fix(server): group setup conflicts by their detail code in run-failure reports (#23568)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - When an agent run fails, the server sends a run-failure report to
Sentry. The fingerprint of the report sets the Sentry group.
> - Setup failures without a root error code use a fallback fingerprint:
the exception name and the HTTP status.
> - The `conflict()` helper keeps its stable code in `details.code`. The
diagnostics read only `code` and `reasonCode` on the error. They ignore
`details.code`.
> - Thus every coded 409 setup conflict gets the fingerprint
`exception:Error` + `status:409`. Unrelated causes go into one Sentry
group. For example, an unfinished workspace writer and a missing remote
execution environment share one group.
> - This pull request reads a bounded identifier from `details.code`
when the error has no own code.
> - The benefit is one Sentry group for each setup conflict cause. A fix
for one cause no longer shows as a regression of another cause.

## Linked Issues or Issue Description

**What happened**
One Sentry group receives three different setup failures. They are "The
workspace still has an unfinished writer or save operation.", "This
workspace requires a supported remote execution environment." and
"Workspace ownership changed." Each one has a different cause. The first
two have a stable code in `details.code`
(`remote_workspace_writer_pending` and
`remote_workspace_execution_required`). The run-failure diagnostics do
not read that code, so all three get the same fallback fingerprint.

**Expected behavior**
A setup conflict with a stable code gets a fingerprint with that code.
Different causes go into different Sentry groups.

**Steps to reproduce**
1. Make a run fail setup with `conflict(message, { code:
"remote_workspace_writer_pending" })`.
2. Make another run fail setup with `conflict(message, { code:
"remote_workspace_execution_required" })`.
3. Look at the run-failure fingerprints. Both are `[setup_failed,
<adapter>, setup, exception:Error, status:409]`.

**Paperclip version or commit**
master at 53bebb59f.

Refs #23475, #23446, #22103 (fixes for the unfinished-writer cause; this
change lets Sentry show that cause by itself).

## What Changed

- `run-failure-diagnostics.ts`: when an exception has no `code` and no
`reasonCode`, read `details.code`. Accept it only when it is a lowercase
identifier of 2 to 100 characters (`^[a-z][a-z0-9_]{1,99}$`). Do not
read other fields of `details`.
- An own `code` or `reasonCode` on the error still has priority.
- Tests: a diagnostics test for the accepted and rejected detail values,
and a Sentry capture test that sends real `conflict()` errors through
the diagnostics and checks the fingerprints.

## Verification

- `cd server && npx vitest run
src/services/__tests__/run-failure-diagnostics.test.ts
src/__tests__/run-failure-sentry.test.ts`: 184 of 184 pass.
- Without the change to `run-failure-diagnostics.ts`, the two new tests
fail. The other 182 tests pass.
- All 19 server test files that use run-failure diagnostics or reports
pass (921 passed, 35 skipped).

## Risks

- Low risk. The change affects only Sentry run-failure reports. No other
code reads these exception codes.
- Expected behavior change: setup conflicts with a `details.code` move
from the shared fallback group to new Sentry groups, one for each code.
Uncoded conflicts stay in the fallback group.
- The code value also goes into the `root_error_code` tag and the
`run_exception_N` context. The strict pattern keeps free text and
secrets out.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code execution
in a sandbox.

## 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: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-12-02 18:13:08 -08:00
1 parent b0f682b66b
commit c852420baf
3 files changed
+44

No files matched your search

@@ -233,6 +233,31 @@ describe("captureRunFailure", () => {
expect(JSON.stringify(fingerprints)).not.toMatch(/workspace|timed out|plain failure/i);
});
it("separates coded setup conflicts from each other and from uncoded ones", async () => {
const { sentryModule, captureException } = await importFreshSentryWithGateOpen();
const { conflict } = await import("../errors.js");
const { collectRunFailureDiagnostics } = await import("../services/run-failure-diagnostics.js");
const setupFailure = (error: Error) => baseEvent({
errorCode: "setup_failed", agentAdapter: "paperclip_runner", errorMessage: error.message,
diagnostics: collectRunFailureDiagnostics({ resultJson: null } as Parameters<typeof collectRunFailureDiagnostics>[0],
{ error, phase: "setup" }),
});
sentryModule.captureRunFailure(setupFailure(conflict("The workspace still has an unfinished writer or save operation.",
{ code: "remote_workspace_writer_pending" })));
sentryModule.captureRunFailure(setupFailure(conflict("This workspace requires a supported remote execution environment.",
{ code: "remote_workspace_execution_required" })));
sentryModule.captureRunFailure(setupFailure(conflict("Workspace ownership changed.")));
const prefix = ["setup_failed", "paperclip_runner", "setup"];
expect(captureException.mock.calls.map(([, context]) => context?.fingerprint)).toEqual([
[...prefix, "remote_workspace_writer_pending"],
[...prefix, "remote_workspace_execution_required"],
[...prefix, "exception:Error", "status:409"],
]);
expect(captureException.mock.calls[0]![1]?.tags).toMatchObject({ root_error_code: "remote_workspace_writer_pending" });
});
it("separates native turn failures by their runner failure code", async () => {
const { sentryModule, captureException } = await importFreshSentryWithGateOpen();
const turnFailure = (provider: NonNullable<RunFailureEvent["diagnostics"]>["provider"]) => baseEvent({
@@ -1,3 +1,4 @@
import { conflict } from "../../errors.js";
import { captureEnvironmentAcquisitionDiagnostic } from "../environment-acquisition-diagnostics.js";
import { describe, expect, it } from "vitest";
import type { heartbeatRuns } from "@paperclipai/db";
@@ -23,6 +24,20 @@ describe("run failure diagnostics", () => {
expect(diagnostic.exceptions[0]).toMatchObject({ code: "tool_name_collision" });
expect(JSON.stringify(diagnostic)).not.toContain("private-token");
});
it("reads a bounded HTTP error detail code when the error has no own code", () => {
const code = (details?: unknown, extra: Record<string, unknown> = {}) =>
collect(Object.assign(conflict("Setup refused", details), extra)).exceptions[0]?.code;
expect(code({ code: "remote_workspace_writer_pending" })).toBe("remote_workspace_writer_pending");
expect(code({ code: "remote_workspace_execution_required", token: "private-token" })).toBe("remote_workspace_execution_required");
expect(code({ code: "remote_workspace_writer_pending" }, { code: "ECONNRESET" })).toBe("ECONNRESET");
expect(code({ code: "remote_workspace_writer_pending" }, { reasonCode: "tool_name_collision" })).toBe("tool_name_collision");
for (const details of [undefined, null, "remote_workspace_writer_pending", { code: "Bearer private-token" },
{ code: "x".repeat(101) }, { code: 409 }, Object.defineProperty({}, "code", { get() { throw new Error("private"); } })]) {
expect(code(details)).toBeUndefined();
}
expect(JSON.stringify(collect(conflict("Setup refused", { code: "remote_workspace_writer_pending", token: "private-token" }))))
.not.toContain("private-token");
});
it("reports only private acquisition observations for the exact failed setup run", () => {
const scope = { companyId: "company-fixture", environmentId: "environment-fixture", runId: "run-fixture" };
const diagnostic = { phase: "workspace", elapsedMs: 100, budgetMs: 2_000 } as const;
@@ -426,6 +426,10 @@ export function collectRunFailureDiagnostics(run: Run, options: RunFailureReport
const reasonCode = read(error, "reasonCode");
if (typeof reasonCode === "string") entry.code = reasonCode;
}
if (entry.code === undefined) {
const detailCode = read(read(error, "details"), "code");
if (typeof detailCode === "string" && /^[a-z][a-z0-9_]{1,99}$/.test(detailCode)) entry.code = detailCode;
}
const status = read(error, "status") ?? read(error, "statusCode");
if (typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599) entry.status = status;
const requestId = read(error, "requestId") ?? read(error, "request_id");