fix(sentry): preserve run failure stacks and diagnostic context (#14585)

Builds on merged #14575 and targets `master`.

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Operators use optional Sentry reports to diagnose failed agent runs.
> - The shared reporter currently converts each saved error message into
a new exception.
> - This loses the original stack and cause chain, and omits available
adapter and provider diagnostics.
> - This pull request selects, redacts, and bounds useful diagnostics
before it sends them to Sentry.
> - Operators can locate the failing operation and correlate upstream
failures without copying arbitrary run data.

## Linked Issues or Issue Description

Refs #14573. That change preserves ACP provider failure details in the
run record.
Refs #14575. That merged PR adds recorded exit codes and signals. This
PR covers stacks, causes, and structured diagnostics without duplicating
those fields.

A thrown setup or adapter error currently appears in Sentry with the
reporter's stack. A saved provider failure can contain useful details
that never reach the Sentry event. Both cases use the same shared
reporting path.

## What Changed

- Pass caught setup and execution exceptions, and structured adapter
error metadata, through successful terminal status transitions.
- Snapshot a fixed set of execution, adapter, provider, and exception
fields. Preserve up to four exceptions in the cause chain.
- Remove registered secret values, declared runtime environment
credentials, unknown inherited environment values and encoded credential
forms, and credential patterns before truncation. Mark truncated fields
and bound provider details and stacks.
- Rebuild sanitized Sentry exceptions with the original stacks and
causes. Use an adapter stack preview when available. Omit a fabricated
reporting stack when the source has no stack.
- Keep contexts local to each event. Preserve the optional DSN gate and
existing error-code/adapter fingerprint.
- Document the fields, limits, and omitted data.
- Settle leftover chat fixture outbox rows only after assertions and
worker shutdown, so subsequent tests cannot claim earlier cases’ pending
actions or provider I/O. This fixes the CI shard contamination exposed
during verification; production chat behavior and test timeouts are
unchanged.

## Verification

- `pnpm -r typecheck` passed.
- `pnpm build` passed.
- 86 focused diagnostic, Sentry, and startup tests passed after the
rebase, including the real `@sentry/node@10.71.0` SDK with an in-memory
transport.
- Tests cover cause chains, HTTP status and request IDs, long provider
details, secret redaction, failed secret resolution, cyclic causes, size
limits, and context isolation.
- Five targeted heartbeat integration cases passed, including thrown and
returned errors containing an opaque environment-bound credential. The
earlier full heartbeat integration run also passed its integration
cases.
- The focused suite also passed with an unknown inherited environment
value set to `1`; reporting tests use a controlled environment and
separately verify short-secret redaction.
- Before the fixture cleanup, the full chat shard reproduced the CI
Telegram timeout at `pending recovery before restart` (354 passed, 1
failed). After the cleanup, the same shard passed all 355 tests. No
timeout or production behavior changed.
- Latest-head CI (`0ae9e70df321d66dda025c3a7ba4787e169e0a4f`) passed
typecheck, build, all 12 server shards, all 3 chat shards, workspace and
serialized suites, browser shards, Runner checks, canary validation, the
real Sentry SDK contract, and security checks. Required `ci / verify`
and `ci / e2e` passed.
- The branch has been rebased onto `master` after #14575 merged. All 55
applicable checks passed on this head (2 unrelated Storybook checks
skipped). Greptile re-reviewed the current 11-file diff at 5/5 with no
findings or unresolved review threads.
- Local monolithic full-suite attempts were interrupted to apply fixes;
full-suite success is not claimed from those runs.

## Risks

- Error messages and stacks can contain credentials. The reporter uses
existing redactors and the run's encrypted secret registry, reads only
known fields, and skips capture if registered-secret resolution fails.
- Unknown environment values remain private by default. Unrecognized
short values can mask benign matches; known public settings are
explicitly allowed.
- Diagnostic text is bounded and can be truncated. Truncation is
explicit. Data discarded upstream cannot be recovered.
- These additional fields go to the operator's configured Sentry
endpoint. Arbitrary request/response objects, headers, configuration,
prompts, and stdout/stderr are not copied.

## Model Used

OpenAI GPT-6 through Codex, with tool use and code execution. The exact
serving model ID, context window, and configured reasoning level are not
exposed in this session.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip authored and GitHub committed 2026-09-29 12:54:12 -05:00
1 parent 2de43fc909
commit b3eb03fcba
11 files changed
+667 -36

No files matched your search

@@ -0,0 +1,95 @@
import { describe, expect, it } from "vitest";
import type { heartbeatRuns } from "@paperclipai/db";
import { collectRunFailureDiagnostics, collectRunFailureSecretValues, redactRunFailureSecretValues, sanitizeRunFailureDiagnostics, sanitizeRunFailureText } from "../run-failure-diagnostics.js";
type Run = typeof heartbeatRuns.$inferSelect;
const run = (overrides: Partial<Run> = {}) => ({ resultJson: null, ...overrides }) as Run;
const collect = (error: unknown) => collectRunFailureDiagnostics(run(), { error });
describe("run failure diagnostics", () => {
it("selects declared environment secrets under opaque names and common credential keys", () => {
expect(collectRunFailureSecretValues({
CUSTOM_BINDING: "bound-opaque-value", ACCESS_TOKEN: "plain-opaque-value", REGION: "us-east-1", EMPTY_KEY: "",
}, ["CUSTOM_BINDING"])).toEqual(["bound-opaque-value", "plain-opaque-value", "us-east-1"]);
expect(collectRunFailureSecretValues({ PATH: "/usr/bin", CUSTOM_BINDING: "opaque" }, [], true)).toEqual(["opaque"]);
expect(collectRunFailureSecretValues({ PATH: "secret-override" }, ["PATH"], true)).toEqual(["secret-override"]);
});
it("redacts encoded credentials and URL passwords without expanding replacement markers", () => {
const secret = 'opaque/"credential';
const values = collectRunFailureSecretValues({ DATABASE_URL: `postgres://user:${encodeURIComponent(secret)}@example/db` });
const result = redactRunFailureSecretValues({ text: `${secret} ${encodeURIComponent(secret)} ${JSON.stringify(secret)}`, status: 503 }, [...values, "REDACTED"]);
expect(result.text).not.toContain("opaque");
expect(result.status).toBe(503);
expect(result.text).not.toContain("***[REDACTED]");
});
it("preserves known boolean and numeric settings without exempting unknown or declared secrets", () => {
const env = { PAPERCLIP_DB_BACKUP_ENABLED: "false", PAPERCLIP_DB_BACKUP_RETENTION_DAYS: "1" };
expect(collectRunFailureSecretValues(env, [], true)).toEqual([]);
expect(collectRunFailureSecretValues(env, ["PAPERCLIP_DB_BACKUP_ENABLED"], true)).toEqual(["false"]);
expect(collectRunFailureSecretValues({ CUSTOM_BINDING: "1" }, [], true)).toEqual(["1"]);
expect(collectRunFailureSecretValues({ PAPERCLIP_DB_BACKUP_ENABLED: "opaque" }, [], true)).toEqual(["opaque"]);
});
it("preserves generic exceptions, numeric codes and nested network causes", () => {
const root = Object.assign(new Error("network failed"), { code: "ECONNRESET", statusCode: 502, request_id: "req-123" });
const outer = Object.assign(new TypeError("adapter failed", { cause: root }), { code: -32000 });
const result = sanitizeRunFailureDiagnostics(collect(outer));
expect(result.exceptions).toMatchObject([
{ name: "TypeError", message: "adapter failed", code: "-32000" },
{ name: "Error", message: "network failed", code: "ECONNRESET", status: 502, requestId: "req-123" },
]);
expect(result.exceptions[0].stack).toContain("run-failure-diagnostics.test.ts");
});
it("bounds cyclic, deep, and string causes without inspecting arbitrary error objects", () => {
const cyclic = new Error("cycle"); cyclic.cause = cyclic;
expect(collect(cyclic)).toMatchObject({ exceptions: [{ message: "cycle" }], truncatedFields: ["exceptions.cycle"] });
let error = new Error("leaf");
for (let i = 0; i < 10; i++) error = new Error(`level-${i}`, { cause: error });
expect(collect(error).exceptions).toHaveLength(4);
expect(collect(error).truncatedFields).toContain("exceptions.depth");
expect(collect(new Error("outer", { cause: "string cause" })).exceptions).toHaveLength(2);
const getter = Object.defineProperty({ message: "valid message" }, "response", { get: () => { throw new Error("must not read"); } });
expect(collect(getter).exceptions).toEqual([{ message: "valid message" }]);
expect(collect({ arbitrary: "private payload" }).exceptions).toEqual([]);
expect(collect(Object.defineProperty({}, "message", { get: () => { throw new Error("bad getter"); } })).exceptions).toEqual([]);
});
it("redacts credential forms before truncation in all diagnostic text", () => {
const failure = collectRunFailureDiagnostics(run({ resultJson: {
terminalSessionFailure: { category: "service", title: 'password="secret-password"', details: 'Authorization: Bearer secret-bearer' },
} }), { error: Object.assign(new Error('apiKey="secret-api-key"'), { cause: new Error('token="secret-token"') }), adapterErrorMeta: { causeMessage: 'password="secret-password"' } });
const result = sanitizeRunFailureDiagnostics(failure);
expect(JSON.stringify(result)).not.toContain("secret-");
expect(sanitizeRunFailureText('x'.repeat(90) + ' password="secret-at-cut-boundary"', 110)).not.toContain("secret-at");
expect(sanitizeRunFailureText('pass\x1b[31mword="secret-colored"', 200)).not.toContain("secret-colored");
});
it("reports truncation, preserves UTF-16 pairs, and keeps the total payload bounded", () => {
const huge = "😀".repeat(100_000);
let error = Object.assign(new Error(huge), { stack: huge });
for (let i = 0; i < 5; i++) error = Object.assign(new Error(huge, { cause: error }), { stack: huge });
const result = sanitizeRunFailureDiagnostics(collectRunFailureDiagnostics(run({ resultJson: {
terminalSessionFailure: { category: "service", title: huge, details: huge, truncatedFields: ["details", "private-field"] },
} }), { error }));
expect(String(result.provider.title).length).toBeLessThanOrEqual(4096);
expect(String(result.provider.details).length).toBeLessThanOrEqual(12288);
expect(JSON.stringify(result)).not.toMatch(/[\ud800-\udfff]/u);
expect(result.truncatedFields).toContain("provider.details");
expect(result.truncatedFields).toContain("exceptions.0.stack");
expect(result.truncatedFields).not.toContain("provider.private-field");
expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThan(150_000);
});
it("keeps scalar native and legacy execution evidence and rejects non-finite durations", () => {
const result = collectRunFailureDiagnostics(run({
runtimeMode: "native", nativePhase: "turn", driverKind: "codex", driverVersion: "1.2.3",
startedAt: new Date(1000), finishedAt: new Date(8500),
resultJson: { stopReason: "failed", timeoutFired: true, effectiveTimeoutSec: 60, errorFamily: "transient_upstream", summary: "private prose" },
}), { phase: "execute" });
expect(result.execution).toMatchObject({ runtimeMode: "native", nativePhase: "turn", driverKind: "codex", driverVersion: "1.2.3", durationMs: 7500, timeoutFired: true, effectiveTimeoutSec: 60, errorFamily: "transient_upstream" });
expect(JSON.stringify(result)).not.toContain("private prose");
expect(collectRunFailureDiagnostics(run({ startedAt: new Date(NaN), finishedAt: new Date() }), {}).execution).not.toHaveProperty("durationMs");
});
});
@@ -1,6 +1,6 @@
import { randomUUID } from "node:crypto";
import os from "node:os";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { agents, companies, createDb, heartbeatRuns, type Db } from "@paperclipai/db";
import {
getEmbeddedPostgresTestSupport,
@@ -9,6 +9,11 @@ import {
const mockCaptureRunFailure = vi.hoisted(() => vi.fn());
const mockRedactCurrentUserText = vi.hoisted(() => vi.fn());
const mockResolveSecret = vi.hoisted(() => vi.fn());
vi.mock("../../secrets/provider-registry.js", () => ({
getSecretProvider: () => ({ resolveVersion: mockResolveSecret }),
}));
vi.mock("../../sentry.js", () => ({
captureRunFailure: mockCaptureRunFailure,
@@ -23,8 +28,7 @@ vi.mock("../../log-redaction.js", async (importOriginal) => {
});
import { reportRunFailure, waitForPendingRunFailureReports } from "../run-failure-report.js";
import { redactSensitiveText, REDACTED_EVENT_VALUE } from "../../redaction.js";
import { redactCurrentUserText } from "../../log-redaction.js";
import { REDACTED_EVENT_VALUE } from "../../redaction.js";
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
@@ -34,14 +38,29 @@ describeEmbeddedPostgres("reportRunFailure", () => {
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
let companyId!: string;
let agentId!: string;
let inheritedEnv: NodeJS.ProcessEnv;
beforeAll(async () => {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-run-failure-report-");
db = createDb(tempDb.connectionString);
}, 20_000);
beforeEach(() => {
// Unknown host values intentionally count as secrets, including short values
// such as "1". Keep these fixtures independent of the developer/CI environment
// and add secret values explicitly in the tests that exercise redaction.
inheritedEnv = process.env;
process.env = Object.fromEntries(
["PATH", "HOME", "USER", "USERNAME", "LOGNAME", "USERPROFILE", "TMPDIR", "TEMP", "TMP"]
.flatMap((key) => inheritedEnv[key] === undefined ? [] : [[key, inheritedEnv[key]]]),
);
});
afterEach(async () => {
vi.clearAllMocks();
vi.unstubAllEnvs();
process.env = inheritedEnv;
await db.delete(heartbeatRuns);
await db.delete(agents);
await db.delete(companies);
});
@@ -141,6 +160,98 @@ describeEmbeddedPostgres("reportRunFailure", () => {
}
});
it("reports selected provider diagnostics and the original cause without copying arbitrary payloads", async () => {
await seedCompanyAndAgent();
const cause = Object.assign(new Error("provider unreachable"), {
code: "ECONNRESET", requestId: "request-123", status: 503,
response: { body: "private-response" },
});
const error = new Error("adapter threw", { cause });
const run = buildRun({
runtimeMode: "legacy",
executionStage: "execute",
error: "adapter threw",
stderrExcerpt: "private-stderr",
stdoutExcerpt: "private-stdout",
contextSnapshot: { prompt: "private-prompt" },
resultJson: {
terminalSessionFailure: { category: "service", title: "Provider unavailable", details: "request-123 failed", raw: "private-provider-raw" },
timeoutFired: false, summary: "private-summary", env: { SECRET: "private-env" },
},
});
await reportRunFailure(db, run, { error, phase: "execute", adapterErrorMeta: { phase: "turn", retryable: true, response: "private-adapter-response" } });
const captured = mockCaptureRunFailure.mock.calls[0][0];
expect(captured.diagnostics).toMatchObject({
execution: { runtimeMode: "legacy", executionStage: "execute", failurePhase: "execute", timeoutFired: false },
adapter: { phase: "turn", retryable: true },
provider: { category: "service", title: "Provider unavailable", details: "request-123 failed" },
exceptions: [{ message: "adapter threw" }, { message: "provider unreachable", code: "ECONNRESET", status: 503, requestId: "request-123" }],
});
expect(captured.diagnostics.exceptions[0].stack).toContain("run-failure-report.test.ts");
expect(JSON.stringify(captured)).not.toContain("private-");
expect(error.cause).toBe(cause);
});
it.each([false, true])("redacts registered run secrets and fails closed when resolution fails: %s", async (fails) => {
await seedCompanyAndAgent();
const secret = "opaque-registered-value";
const run = buildRun({
error: `connection failed: ${secret}`,
contextSnapshot: { paperclipSecretRedactions: [{ fingerprintSha256: "fixture", material: { encrypted: "fixture" } }] },
resultJson: { terminalSessionFailure: { category: "service", details: `upstream rejected ${secret}` } },
});
await db.insert(heartbeatRuns).values(run);
if (fails) mockResolveSecret.mockRejectedValueOnce(new Error("fixture resolution failed"));
else mockResolveSecret.mockResolvedValueOnce(secret);
await expect(reportRunFailure(db, run, {
error: new Error(`failed ${secret}`, { cause: new Error(`cause ${secret}`) }),
adapterErrorMeta: { causeMessage: `adapter ${secret}` },
})).resolves.toBeUndefined();
expect(mockResolveSecret).toHaveBeenCalledTimes(1);
if (fails) {
expect(mockCaptureRunFailure).not.toHaveBeenCalled();
} else {
expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1);
const captured = mockCaptureRunFailure.mock.calls[0][0];
expect(JSON.stringify(captured)).not.toContain(secret);
expect(captured.diagnostics.provider.details).toContain(REDACTED_EVENT_VALUE);
expect(captured.diagnostics.exceptions[1].message).toContain(REDACTED_EVENT_VALUE);
}
});
it("redacts runtime and host environment secret values even without a persisted registry", async () => {
await seedCompanyAndAgent();
const runtimeSecret = "opaque-runtime-value";
const hostSecret = "opaque-host-value";
vi.stubEnv("FIXTURE_CUSTOM_VALUE", hostSecret);
const text = `connection failed: ${runtimeSecret} ${hostSecret}`;
const run = buildRun({ error: text, contextSnapshot: null,
resultJson: { terminalSessionFailure: { details: text } },
});
await reportRunFailure(db, run, {
error: new Error(text, { cause: new Error(text) }),
adapterErrorMeta: { causeMessage: text, stackPreview: text },
secretValues: [runtimeSecret],
});
expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1);
const captured = mockCaptureRunFailure.mock.calls[0][0];
expect(JSON.stringify(captured)).not.toContain(runtimeSecret);
expect(JSON.stringify(captured)).not.toContain(hostSecret);
expect(captured.diagnostics.exceptions).toHaveLength(2);
expect(captured).not.toHaveProperty("secretValues");
});
it("still redacts short values from unknown host settings", async () => {
await seedCompanyAndAgent();
vi.stubEnv("FIXTURE_CUSTOM_VALUE", "1");
await reportRunFailure(db, buildRun());
expect(mockCaptureRunFailure.mock.calls[0][0].errorMessage)
.toBe(`the provider process exited with code ${REDACTED_EVENT_VALUE}`);
});
it("captures nothing for succeeded, cancelled, and interrupted", async () => {
await seedCompanyAndAgent();
for (const status of ["succeeded", "cancelled", "interrupted"] as const) {
@@ -259,9 +370,10 @@ describeEmbeddedPostgres("reportRunFailure", () => {
await reportRunFailure(db, run);
const expectedErrorMessage = redactSensitiveText(redactCurrentUserText(rawError));
const { errorMessage } = mockCaptureRunFailure.mock.calls[0][0];
expect(errorMessage).toBe(expectedErrorMessage);
// Environment-value redaction can fully mask the username before the
// current-user redactor applies its partial mask. Both remove the home path.
expect(errorMessage).toContain("workspace/report.log");
expect(errorMessage).not.toContain(homeDir);
});
@@ -276,10 +388,13 @@ describeEmbeddedPostgres("reportRunFailure", () => {
const { errorMessage } = mockCaptureRunFailure.mock.calls[0][0];
expect(errorMessage).toHaveLength(MAX_ERROR_MESSAGE_LENGTH);
expect(errorMessage).toBe("x".repeat(MAX_ERROR_MESSAGE_LENGTH));
expect(errorMessage).toBe("x".repeat(MAX_ERROR_MESSAGE_LENGTH - 12) + "\n[truncated]");
});
it("does not change a short error message", async () => {
it("preserves a short error message with known public host settings", async () => {
vi.stubEnv("PAPERCLIP_DB_BACKUP_ENABLED", "false");
vi.stubEnv("PAPERCLIP_DB_BACKUP_RETENTION_DAYS", "1");
vi.stubEnv("GITHUB_RUN_ATTEMPT", "1");
await seedCompanyAndAgent();
const shortError = "the provider process exited with code 1";
const run = buildRun({ status: "failed", error: shortError });
@@ -326,7 +441,7 @@ describeEmbeddedPostgres("reportRunFailure", () => {
const { errorCode } = mockCaptureRunFailure.mock.calls[0][0];
expect(errorCode).toHaveLength(MAX_ERROR_CODE_LENGTH);
expect(errorCode).toBe("y".repeat(MAX_ERROR_CODE_LENGTH));
expect(errorCode).toBe("y".repeat(MAX_ERROR_CODE_LENGTH - 12) + "\n[truncated]");
});
it("sends errorCode null unchanged when the run holds no error code", async () => {