mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-30 17:14:54 +01:00
fix(heartbeat): keep a credential denial an owner action when the lease lapses during AI selection (#22379)
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The heartbeat prepares each run before the agent starts. One
preparation step selects the AI account for the run.
> - AI selection can reject an account for a reason that only its owner
can fix. An example is a credential that is not shared with the
responsible user.
> - Run setup gives a lost controller lease priority over every other
failure code. When the lease lapsed during the same setup, the run got
`controller_lease_lost` instead of `configuration_incomplete`.
> - `controller_lease_lost` is retryable. So the run retried and failed
again with the same rejection. The code also bypassed the Sentry filter
for owned AI selection blockers, so the server sent a spurious Sentry
event.
> - This pull request keeps `configuration_incomplete` when AI selection
itself rejected the account, even when the lease is lost at the same
time.
> - The benefit is that the owner gets the correct action at once, with
no wasted retry and no Sentry noise.
## Linked Issues or Issue Description
Refs #15714 (this PR adds the Sentry filter for owned AI selection
blockers, and this change reuses that check).
**What happened?**
A legacy run was in setup. AI selection correctly rejected the account
(`ai_connection_credential_not_shared`). At the same time, a lease
renewal stalled for about 29 seconds and the controller lease lapsed.
Setup recorded the run as `controller_lease_lost` with the configuration
message. The run was retried. The retry failed again as
`configuration_incomplete`. The first failure also went to Sentry,
because the filter only matches `configuration_incomplete`.
**Expected behavior**
When AI selection rejects the account for an owned reason, the run fails
as `configuration_incomplete`. The run is not retried. The board gets
the configuration action. No Sentry event is sent. The run result keeps
the lease-loss evidence.
**Steps to reproduce**
1. Start a legacy run whose AI account selection fails with an owned
rejection (for example, a credential that is not shared with the
responsible user).
2. Make the controller lease lapse while setup selects the AI account.
3. Look at the run `errorCode`, the retry schedule, and the Sentry
report.
**Paperclip version or commit**
`master` at c41145e72a.
**Agent adapter(s) involved**
Not adapter-specific (core bug).
## What Changed
- Added `isOwnedAiConnectionSelectionRejection` in
`server/src/lib/ai-connection-configuration-failure.ts`. It matches a
`configurationIncomplete` result with reason `ai_connection_unavailable`
and a known `selectionFailure`.
- `run-completion.ts` setup failure: a lost lease no longer replaces the
error code when AI selection itself rejected the account. Any other AI
preparation error (the broad wrapper) still records a retryable
`controller_lease_lost`.
- `run-failure-report.ts`: the Sentry filter now uses the same shared
check. Its behavior does not change.
- Added tests:
- A unit test in `run-completion.test.ts` for both cases (owned
rejection keeps its code; unclassified error keeps
`controller_lease_lost`).
- A full heartbeat test in `heartbeat-process-recovery.test.ts`. It
checks the error code, no retry, the board configuration action, and no
Sentry report.
- A test in `run-failure-report.test.ts` for the shared check.
## Verification
- `cd server && npx vitest run
src/services/heartbeat/run-completion.test.ts
src/services/__tests__/run-failure-report.test.ts`
- `cd server && npx vitest run
src/__tests__/heartbeat-process-recovery.test.ts -t "credential sharing
denial"`
- Without the `run-completion.ts` change, both new regression tests fail
with `controller_lease_lost`. With the change, they pass.
- In the author's sandbox, 4 sandbox-provider lease tests in
`run-completion.test.ts` and 4 provider-outage tests in
`heartbeat-process-recovery.test.ts` fail. They fail the same way on
untouched `master` in that sandbox, so the cause is the environment. CI
runs the full suite.
## Risks
- Low risk. The change applies only when AI selection recorded an owned
rejection. A lost lease with any other setup error keeps the same
retryable code as before.
- The run is no longer retried in this case. That is correct, because
every host repeats the same rejection until the owner acts.
## Model Used
- Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution
in an agent harness.
## 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
- [ ] 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: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
7 files changed
+99
-6
No files matched your search
@@ -1787,6 +1787,54 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("routes a credential sharing denial to its owner when the controller lease lapses during AI selection", async () => {
|
||||
const { companyId, agentId, issueId, runId } = await seedQueuedIssueRunFixture();
|
||||
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "responsible-user", status: "active", membershipRole: "member" }).onConflictDoNothing();
|
||||
await db.update(agents).set({ runtimeConfig: {
|
||||
heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 },
|
||||
aiConnection: { provider: "openai", method: "api_key", mode: "responsible_user" },
|
||||
} }).where(eq(agents.id, agentId));
|
||||
let runController: AbortController | undefined;
|
||||
const originalWatch = controllerLeases.watchLegacyControllerLease;
|
||||
const watcher = vi.spyOn(controllerLeases, "watchLegacyControllerLease").mockImplementation((...args) => {
|
||||
if (args[1].id === runId) runController = args[2];
|
||||
return originalWatch(...args);
|
||||
});
|
||||
// The renewal deadline passes while selection reads the grant, then the
|
||||
// selection's own sharing denial reaches the setup failure path.
|
||||
const prepare = vi.spyOn(aiConnectionRuntime, "prepareManagedAiRuntime").mockImplementationOnce(async () => {
|
||||
runController!.abort(new controllerLeases.LegacyControllerLeaseLostError("renewal_deadline",
|
||||
{ sinceRenewalMs: 37_725, renewalPendingMs: 29_418, deadlineLateMs: 52, renewalCount: 2 }));
|
||||
throw aiConnectionCredentialNotSharedFailure();
|
||||
});
|
||||
const heartbeat = heartbeatService(db);
|
||||
try {
|
||||
await heartbeat.resumeQueuedRuns();
|
||||
await waitForRunToSettle(heartbeat, runId, 5_000);
|
||||
await heartbeat.waitForRunExecutionDrain(runId);
|
||||
await waitForPendingRunFailureReports();
|
||||
expect(prepare).toHaveBeenCalledOnce();
|
||||
expect(await heartbeat.getRun(runId)).toMatchObject({ status: "failed", errorCode: "configuration_incomplete",
|
||||
error: "This credential is not shared with the responsible user", resultJson: {
|
||||
configurationIncomplete: { reason: "ai_connection_unavailable", selectionFailure: "ai_connection_credential_not_shared" },
|
||||
controllerLeaseLoss: { cause: "renewal_deadline", renewalPendingMs: 29_418 },
|
||||
executionRecovery: { kind: "bootstrap", providerWorkStarted: false } } });
|
||||
expect(mockCaptureRunFailure).not.toHaveBeenCalled();
|
||||
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
||||
// No retry that would repeat the same denial before the owner acts.
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.retryOfRunId, runId))).toHaveLength(0);
|
||||
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
||||
expect(issue).toMatchObject({ status: "blocked", executionRunId: null });
|
||||
const [action] = await selectRecoveryActionsForIssue(issueId);
|
||||
expect(action).toMatchObject({ status: "active", kind: "configuration_validation", cause: "configuration_incomplete", ownerType: "board" });
|
||||
} finally {
|
||||
await heartbeat.drainActiveRunExecutions().catch(() => undefined);
|
||||
prepare.mockRestore();
|
||||
watcher.mockRestore();
|
||||
await db.delete(companyMemberships).where(eq(companyMemberships.companyId, companyId));
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["timeout", "upstream", "cleanup_pending", "cleanup_pending_edited", "cleanup_pending_exhausted", "edited", "exhausted", "new_message", "no_claim", "reassigned", "superseded", "stopped"])(
|
||||
"settles explicit retry admission through real executor cleanup: %s", async scenario => {
|
||||
const { companyId, agentId, runId, issueId } = await seedQueuedIssueRunFixture();
|
||||
|
||||
Reference in new issue
Block a user