Skip to content

The open-source app everyone uses to manage agents at work

feat(observability): report terminal run failures to Sentry (#13446)

Nicky Leachc276d3fdc3f4
diff --git a/doc/observability.md b/doc/observability.md
index 9d7939a9c6..f604150e95 100644
--- a/doc/observability.md
+++ b/doc/observability.md
@@ -375,11 +375,24 @@ sends, so an operator can read what the feature does before turning it on.
Each Sentry integration name below is verified against the default
integration list of `@sentry/[email protected]` and `@sentry/[email protected]`.
+**Server attribute this feature sets**
+
+- `server_name` — every server event carries the host name of the process.
+ The `@sentry/node` client already sets this value by default when the
+ operator does not pass a `serverName` option; this feature passes the
+ value directly, so the server keeps sending it even if a later SDK
+ version changes its default. To send a different value in place of the
+ host name, set the environment variable `SENTRY_NAME` to that value.
+
**Server events this feature adds**
- An Express `HttpError` with `status >= 500`.
- Any unknown throw that is not a `ZodError`. It always answers 500.
- A server startup failure.
+- A run that ends with the status `failed` or the status `timed_out`. The
+ event carries five context fields: `taskId`, `runId`, `errorMessage`,
+ `errorCode`, and `agentAdapter`. The server redacts the error message and
+ the error code before it sends the event.
**Server events the default integrations add**
diff --git a/server/src/__tests__/heartbeat-process-recovery.test.ts b/server/src/__tests__/heartbeat-process-recovery.test.ts
index 2e98adcf32..cd1cee5419 100644
--- a/server/src/__tests__/heartbeat-process-recovery.test.ts
+++ b/server/src/__tests__/heartbeat-process-recovery.test.ts
@@ -140,6 +140,15 @@ vi.mock("../telemetry.ts", () => ({
getTelemetryClient: () => mockTelemetryClient,
}));
+const mockCaptureRunFailure = vi.hoisted(() => vi.fn());
+vi.mock("../sentry.ts", async () => {
+ const actual = await vi.importActual<typeof import("../sentry.ts")>("../sentry.ts");
+ return {
+ ...actual,
+ captureRunFailure: mockCaptureRunFailure,
+ };
+});
+
vi.mock("../services/native-runtime/native-session-executor.js", async () => {
const actual = await vi.importActual<
typeof import("../services/native-runtime/native-session-executor.js")
@@ -2405,6 +2414,16 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
timeoutConfigured: false,
timeoutFired: false,
});
+ // The legacy engine writes this terminal status through the same
+ // guarded emitter that reports a genuine failed transition to Sentry.
+ expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1);
+ expect(mockCaptureRunFailure).toHaveBeenCalledWith(
+ expect.objectContaining({
+ runId,
+ errorCode: "process_lost",
+ runStatus: "failed",
+ }),
+ );
const [action] = await db
.select()
.from(issueRecoveryActions)
@@ -2418,6 +2437,9 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
.from(heartbeatRuns)
.where(eq(heartbeatRuns.agentId, agentId)),
).toHaveLength(2);
+ // A replay over the same already-failed run must not report a second
+ // Sentry event for one terminal failure.
+ expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1);
const issue = await waitForValue(async () =>
db
diff --git a/server/src/__tests__/heartbeat-status-preserving-telemetry.test.ts b/server/src/__tests__/heartbeat-status-preserving-telemetry.test.ts
index 9872be6d8d..88d17ccd61 100644
--- a/server/src/__tests__/heartbeat-status-preserving-telemetry.test.ts
+++ b/server/src/__tests__/heartbeat-status-preserving-telemetry.test.ts
@@ -22,6 +22,15 @@ vi.mock("../telemetry.js", () => ({
getTelemetryClient: () => mockTelemetryClient,
}));
+const mockCaptureRunFailure = vi.hoisted(() => vi.fn());
+vi.mock("../sentry.js", async () => {
+ const actual = await vi.importActual<typeof import("../sentry.js")>("../sentry.js");
+ return {
+ ...actual,
+ captureRunFailure: mockCaptureRunFailure,
+ };
+});
+
import { heartbeatService } from "../services/heartbeat.ts";
function agentTaskRunCalls(fromIndex: number) {
@@ -128,6 +137,9 @@ describeEmbeddedPostgres(
errorCode: "native_execution_ownership_unverified",
});
expect(agentTaskRunCalls(callsBefore)).toHaveLength(0);
+ // A status-preserving write is not a new transition, so it must not
+ // report a second Sentry event for the same terminal failure.
+ expect(mockCaptureRunFailure).not.toHaveBeenCalled();
});
},
);
diff --git a/server/src/__tests__/native-session-resumption.test.ts b/server/src/__tests__/native-session-resumption.test.ts
index 2abaab12f0..14f340e3d3 100644
--- a/server/src/__tests__/native-session-resumption.test.ts
+++ b/server/src/__tests__/native-session-resumption.test.ts
@@ -67,6 +67,12 @@ vi.mock("../adapters/index.js", async () => {
};
});
+const mockCaptureRunFailure = vi.hoisted(() => vi.fn());
+vi.mock("../sentry.js", async () => {
+ const actual = await vi.importActual<typeof import("../sentry.js")>("../sentry.js");
+ return { ...actual, captureRunFailure: mockCaptureRunFailure };
+});
+
import { heartbeatService } from "../services/heartbeat.js";
import { instanceSettingsService } from "../services/instance-settings.js";
@@ -528,6 +534,77 @@ describe("P6-25 pre-result native session recovery", () => {
expect.objectContaining({ phase: "observed", attempt: 0, failureCode: null }),
]);
});
+
+ it("sends exactly one Sentry event when a sweep resolves a run from running to failed", async () => {
+ const freshRunId = "79000000-0000-4000-8000-000000000101";
+ await db.insert(heartbeatRuns).values({
+ id: freshRunId,
+ companyId,
+ agentId,
+ nativeIssueId: issueId,
+ status: "running",
+ runtimeMode: "native",
+ runtimeModeResolvedAt: new Date(),
+ runnerProfileJson: {
+ nativeExecutionInput: {
+ ...persistedProfile.nativeExecutionInput,
+ binding: { runId: freshRunId },
+ },
+ },
+ contextSnapshot: { issueId },
+ });
+ await db.insert(nativeRunFinalizations).values({
+ runId: freshRunId,
+ companyId,
+ issueId,
+ phase: "retryable_failure",
+ attempt: 1,
+ });
+ const captureCallsBefore = mockCaptureRunFailure.mock.calls.length;
+
+ await claimNativeSessionResumptions({ db, runnerInstanceId: "reaper", runIds: [freshRunId] });
+ // The Sentry report fires without an await inside the reconciler, so a
+ // follow-up round trip to the real database gives that fire-and-forget
+ // call room to complete before this test reads the spy.
+ await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, freshRunId));
+
+ const newCaptures = mockCaptureRunFailure.mock.calls.slice(captureCallsBefore);
+ expect(newCaptures).toHaveLength(1);
+ expect(newCaptures[0]?.[0]).toMatchObject({ runId: freshRunId, runStatus: "failed" });
+ });
+
+ it("sends no Sentry event when a sweep finds a run that is already failed", async () => {
+ const freshRunId = "79000000-0000-4000-8000-000000000102";
+ await db.insert(heartbeatRuns).values({
+ id: freshRunId,
+ companyId,
+ agentId,
+ nativeIssueId: issueId,
+ status: "failed",
+ runtimeMode: "native",
+ runtimeModeResolvedAt: new Date(),
+ runnerProfileJson: {
+ nativeExecutionInput: {
+ ...persistedProfile.nativeExecutionInput,
+ binding: { runId: freshRunId },
+ },
+ },
+ contextSnapshot: { issueId },
+ });
+ await db.insert(nativeRunFinalizations).values({
+ runId: freshRunId,
+ companyId,
+ issueId,
+ phase: "retryable_failure",
+ attempt: 1,
+ });
+ const captureCallsBefore = mockCaptureRunFailure.mock.calls.length;
+
+ await claimNativeSessionResumptions({ db, runnerInstanceId: "reaper", runIds: [freshRunId] });
+ await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, freshRunId));
+
+ expect(mockCaptureRunFailure.mock.calls.slice(captureCallsBefore)).toHaveLength(0);
+ });
});
describe.each(["unchanged", "newer_active", "stale_idle"] as const)(
diff --git a/server/src/__tests__/run-failure-sentry.test.ts b/server/src/__tests__/run-failure-sentry.test.ts
new file mode 100644
index 0000000000..aa6f51ff43
--- /dev/null
+++ b/server/src/__tests__/run-failure-sentry.test.ts
@@ -0,0 +1,188 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { RunFailureEvent } from "../sentry.js";
+
+/**
+ * Tests for `captureRunFailure`, the Sentry report for a terminal run
+ * failure. `@sentry/node` is an optional runtime dependency and is not
+ * installed in this test environment, so each test mocks a fake copy of the
+ * package the same way `sentry.test.ts` does, then imports a fresh copy of
+ * `../sentry.js` with a backend DSN set. That opens the gate and lets the
+ * fake package's `withScope`/`captureException` spies record the real call
+ * shape.
+ */
+
+const DSN_ENV = "SENTRY_DSN";
+const FRONTEND_DSN_ENV = "SENTRY_DSN_FRONTEND";
+const BACKEND_DSN_ENV = "SENTRY_DSN_BACKEND";
+const originalDsn = process.env[DSN_ENV];
+const originalFrontendDsn = process.env[FRONTEND_DSN_ENV];
+const originalBackendDsn = process.env[BACKEND_DSN_ENV];
+
+function baseEvent(overrides: Partial<RunFailureEvent> = {}): RunFailureEvent {
+ return {
+ taskId: "11111111-1111-1111-1111-111111111111",
+ runId: "22222222-2222-2222-2222-222222222222",
+ errorMessage: "the provider process exited with code 1",
+ errorCode: "process_lost",
+ agentAdapter: "claude-code",
+ runStatus: "failed",
+ ...overrides,
+ };
+}
+
+/** Mirrors `sentry.test.ts`'s `mockSentryPackage`, plus a `withScope` spy. */
+function mockSentryPackage() {
+ const scope = {
+ setTag: vi.fn(),
+ setContext: vi.fn(),
+ setFingerprint: vi.fn(),
+ };
+ const init = vi.fn();
+ const captureException = vi.fn(() => "event-id");
+ const withScope = vi.fn((callback: (s: typeof scope) => void) => callback(scope));
+ const close = vi.fn(async () => true);
+ const httpIntegration = vi.fn((options: unknown) => ({ name: "Http", ...(options as object) }));
+ const onUnhandledRejectionIntegration = vi.fn((options: unknown) => ({
+ name: "OnUnhandledRejection",
+ ...(options as object),
+ }));
+
+ vi.doMock("@sentry/node", () => ({
+ init,
+ captureException,
+ withScope,
+ close,
+ httpIntegration,
+ onUnhandledRejectionIntegration,
+ }));
+ vi.doMock("../peer-version-check.js", () => ({
+ checkExactPeerVersions: () => ({ ok: true }),
+ }));
+
+ return { scope, init, captureException, withScope, close };
+}
+
+async function importFreshSentryWithGateOpen() {
+ process.env[BACKEND_DSN_ENV] = "https://[email protected]/1";
+ const mocks = mockSentryPackage();
+ vi.resetModules();
+ const sentryModule = await import("../sentry.js");
+ await sentryModule.sentryReady;
+ return { sentryModule, ...mocks };
+}
+
+beforeEach(() => {
+ delete process.env[DSN_ENV];
+ delete process.env[FRONTEND_DSN_ENV];
+ delete process.env[BACKEND_DSN_ENV];
+});
+
+afterEach(() => {
+ if (originalDsn === undefined) delete process.env[DSN_ENV];
+ else process.env[DSN_ENV] = originalDsn;
+ if (originalFrontendDsn === undefined) delete process.env[FRONTEND_DSN_ENV];
+ else process.env[FRONTEND_DSN_ENV] = originalFrontendDsn;
+ if (originalBackendDsn === undefined) delete process.env[BACKEND_DSN_ENV];
+ else process.env[BACKEND_DSN_ENV] = originalBackendDsn;
+ vi.restoreAllMocks();
+ vi.doUnmock("@sentry/node");
+ vi.doUnmock("../peer-version-check.js");
+});
+
+describe("captureRunFailure", () => {
+ it("sets the fingerprint [errorCode, agentAdapter] in that order", async () => {
+ const { sentryModule, scope } = await importFreshSentryWithGateOpen();
+
+ sentryModule.captureRunFailure(baseEvent({ errorCode: "timeout", agentAdapter: "codex" }));
+
+ expect(scope.setFingerprint).toHaveBeenCalledWith(["timeout", "codex"]);
+ });
+
+ it("keeps the error message out of the fingerprint for two runs with the same code and adapter but different messages", async () => {
+ const { sentryModule, scope } = await importFreshSentryWithGateOpen();
+
+ sentryModule.captureRunFailure(
+ baseEvent({ errorMessage: "message one", errorCode: "timeout", agentAdapter: "codex" }),
+ );
+ sentryModule.captureRunFailure(
+ baseEvent({ errorMessage: "message two", errorCode: "timeout", agentAdapter: "codex" }),
+ );
+
+ expect(scope.setFingerprint).toHaveBeenNthCalledWith(1, ["timeout", "codex"]);
+ expect(scope.setFingerprint).toHaveBeenNthCalledWith(2, ["timeout", "codex"]);
+ });
+
+ it("sets the fingerprint element \"unknown\" when the error code is absent", async () => {
+ const { sentryModule, scope } = await importFreshSentryWithGateOpen();
+
+ sentryModule.captureRunFailure(baseEvent({ errorCode: null }));
+
+ expect(scope.setFingerprint).toHaveBeenCalledWith(["unknown", "claude-code"]);
+ });
+
+ it("sets the five diagnostic values on the run_failure context", async () => {
+ const { sentryModule, scope } = await importFreshSentryWithGateOpen();
+ const event = baseEvent();
+
+ sentryModule.captureRunFailure(event);
+
+ expect(scope.setContext).toHaveBeenCalledWith("run_failure", {
+ taskId: event.taskId,
+ runId: event.runId,
+ errorMessage: event.errorMessage,
+ errorCode: event.errorCode,
+ agentAdapter: event.agentAdapter,
+ });
+ });
+
+ it("does not set an instance key on the run_failure context", async () => {
+ const { sentryModule, scope } = await importFreshSentryWithGateOpen();
+
+ sentryModule.captureRunFailure(baseEvent());
+
+ const [, context] = scope.setContext.mock.calls[0]!;
+ expect(context).not.toHaveProperty("instance");
+ });
+
+ it("sets run_id, task_id, error_code, agent_adapter, and run_status as tags", async () => {
+ const { sentryModule, scope } = await importFreshSentryWithGateOpen();
+ const event = baseEvent();
+
+ sentryModule.captureRunFailure(event);
+
+ expect(scope.setTag).toHaveBeenCalledWith("run_id", event.runId);
+ expect(scope.setTag).toHaveBeenCalledWith("task_id", event.taskId);
+ expect(scope.setTag).toHaveBeenCalledWith("error_code", event.errorCode);
+ expect(scope.setTag).toHaveBeenCalledWith("agent_adapter", event.agentAdapter);
+ expect(scope.setTag).toHaveBeenCalledWith("run_status", event.runStatus);
+ });
+
+ it("captures the redacted error message as the exception message", async () => {
+ const { sentryModule, captureException } = await importFreshSentryWithGateOpen();
+ const event = baseEvent({ errorMessage: "boom" });
+
+ sentryModule.captureRunFailure(event);
+
+ expect(captureException).toHaveBeenCalledTimes(1);
+ const [received] = captureException.mock.calls[0]!;
+ expect(received).toBeInstanceOf(Error);
+ expect((received as Error).message).toBe("boom");
+ });
+
+ it("does not throw and captures nothing when the gate is closed", async () => {
+ vi.resetModules();
+ const sentryModule = await import("../sentry.js");
+ await sentryModule.sentryReady;
+
+ expect(() => sentryModule.captureRunFailure(baseEvent())).not.toThrow();
+ });
+
+ it("does not throw when the client throws", async () => {
+ const { sentryModule, withScope } = await importFreshSentryWithGateOpen();
+ withScope.mockImplementation(() => {
+ throw new Error("sentry client is down");
+ });
+
+ expect(() => sentryModule.captureRunFailure(baseEvent())).not.toThrow();
+ });
+});
diff --git a/server/src/__tests__/sentry.test.ts b/server/src/__tests__/sentry.test.ts
index 60edd8fc41..9067b96f36 100644
--- a/server/src/__tests__/sentry.test.ts
+++ b/server/src/__tests__/sentry.test.ts
@@ -1,5 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { createRequire } from "node:module";
+import os from "node:os";
import http from "node:http";
import express from "express";
import request from "supertest";
@@ -458,6 +459,84 @@ describe("buildSentryInitOptions", () => {
});
});
+describe("buildSentryInitOptions serverName", () => {
+ it("sets serverName to the host name", async () => {
+ const { buildSentryInitOptions } = await importFreshSentry();
+
+ const options = buildSentryInitOptions("https://[email protected]/1", {
+ httpIntegration: () => ({ name: "Http" }),
+ onUnhandledRejectionIntegration: () => ({ name: "OnUnhandledRejection" }),
+ });
+
+ expect(options.serverName).toBe(os.hostname());
+ });
+
+ it("reads the host name from node:os at call time, not at module load time", async () => {
+ vi.doMock("node:os", () => ({
+ default: { hostname: () => "fixed-test-host" },
+ hostname: () => "fixed-test-host",
+ }));
+
+ const { buildSentryInitOptions } = await importFreshSentry();
+ const options = buildSentryInitOptions("https://[email protected]/1", {
+ httpIntegration: () => ({ name: "Http" }),
+ onUnhandledRejectionIntegration: () => ({ name: "OnUnhandledRejection" }),
+ });
+
+ expect(options.serverName).toBe("fixed-test-host");
+
+ vi.doUnmock("node:os");
+ });
+
+ const SENTRY_NAME_ENV = "SENTRY_NAME";
+ let originalSentryName: string | undefined;
+
+ beforeEach(() => {
+ originalSentryName = process.env[SENTRY_NAME_ENV];
+ });
+
+ afterEach(() => {
+ if (originalSentryName === undefined) delete process.env[SENTRY_NAME_ENV];
+ else process.env[SENTRY_NAME_ENV] = originalSentryName;
+ });
+
+ it("uses SENTRY_NAME as serverName when the variable holds a non-empty string", async () => {
+ process.env[SENTRY_NAME_ENV] = "opaque-operator-id";
+ const { buildSentryInitOptions } = await importFreshSentry();
+
+ const options = buildSentryInitOptions("https://[email protected]/1", {
+ httpIntegration: () => ({ name: "Http" }),
+ onUnhandledRejectionIntegration: () => ({ name: "OnUnhandledRejection" }),
+ });
+
+ expect(options.serverName).toBe("opaque-operator-id");
+ });
+
+ it("uses the host name as serverName when SENTRY_NAME is absent", async () => {
+ delete process.env[SENTRY_NAME_ENV];
+ const { buildSentryInitOptions } = await importFreshSentry();
+
+ const options = buildSentryInitOptions("https://[email protected]/1", {
+ httpIntegration: () => ({ name: "Http" }),
+ onUnhandledRejectionIntegration: () => ({ name: "OnUnhandledRejection" }),
+ });
+
+ expect(options.serverName).toBe(os.hostname());
+ });
+
+ it("uses the host name as serverName when SENTRY_NAME is an empty string", async () => {
+ process.env[SENTRY_NAME_ENV] = "";
+ const { buildSentryInitOptions } = await importFreshSentry();
+
+ const options = buildSentryInitOptions("https://[email protected]/1", {
+ httpIntegration: () => ({ name: "Http" }),
+ onUnhandledRejectionIntegration: () => ({ name: "OnUnhandledRejection" }),
+ });
+
+ expect(options.serverName).toBe(os.hostname());
+ });
+});
+
describe("with @sentry/node mocked", () => {
it("initializes the client and shares captureException / shutdownSentry with it", async () => {
process.env[DSN_ENV] = "https://[email protected]/1";
diff --git a/server/src/index.ts b/server/src/index.ts
index 959cf299ef..ba8cde96eb 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -5,6 +5,7 @@
// HTTP server, so trace coverage does not depend on incidental timing.
import { instrumentationReady, shutdownInstrumentation } from "./instrumentation.js";
import { sentryReady, shutdownSentry, captureException } from "./sentry.js";
+import { waitForPendingRunFailureReports } from "./services/run-failure-report.js";
import { verifyStoppedNativeSessionForReplacement } from "./services/native-runtime/native-session-executor.js";
import { embeddedPostgresOwnerPort } from "./embedded-postgres-owner.js";
import { deliverExecutionStatuses } from "./services/execution-status-delivery.js";
@@ -1992,6 +1993,7 @@ async function startServerWithDatabaseTeardown(
shutdownAppServices: appShutdown,
closeHttpListener: () =>
closeHttpListenerForShutdown({ server, signal, log: logger }),
+ drainPendingRunFailureReports: waitForPendingRunFailureReports,
closeDatabase: closeDatabaseClients,
stopEmbeddedPostgres,
shutdownInstrumentation,
diff --git a/server/src/sentry.ts b/server/src/sentry.ts
index 8cac6728c2..cfe7ecb929 100644
--- a/server/src/sentry.ts
+++ b/server/src/sentry.ts
@@ -16,6 +16,17 @@
// adds error monitoring only and starts no span or trace behavior of its
// own.
//
+// `serverName`: the initializer sets this to the host name of the process,
+// with `os.hostname()`. The `@sentry/node` client already falls back to the
+// same host name when the caller omits this option, so this line makes an
+// existing default explicit instead of changing captured event content. An
+// explicit value stays correct if a future SDK version changes its default.
+//
+// An operator can still send a different value in place of the host name.
+// When the environment variable `SENTRY_NAME` holds a non-empty string, the
+// initializer uses that value instead. This keeps the same order the
+// `@sentry/node` client itself uses when the caller omits `serverName`.
+//
// Default-integration privacy note: `sendDefaultPii: false` filters values
// by name, inside the `RequestData` integration only. Three other default
// integrations copy raw values past that filter, so the initializer removes
@@ -44,6 +55,7 @@
// never throws. This gate mirrors the OpenTelemetry gate in
// `instrumentation.ts`.
+import os from "node:os";
import { checkExactPeerVersions } from "./peer-version-check.js";
import { resolveSentryDsns } from "./sentry-dsn.js";
@@ -59,9 +71,17 @@ if (legacyFallbackUsed) {
);
}
+/** The subset of the `@sentry/node` scope surface `captureRunFailure` calls. */
+interface SentryScopeLike {
+ setTag(key: string, value: string): void;
+ setContext(name: string, context: Record<string, unknown> | null): void;
+ setFingerprint(fingerprint: string[]): void;
+}
+
/** The subset of the `@sentry/node` client surface this gate calls. */
interface SentryHandle {
captureException(error: unknown): string;
+ withScope(callback: (scope: SentryScopeLike) => void): void;
close(timeout?: number): Promise<boolean>;
}
@@ -92,6 +112,65 @@ export function captureException(error: unknown): void {
}
}
+/** The run status values that mark a run as a genuine terminal failure. */
+export type RunFailureStatus = "failed" | "timed_out";
+
+/**
+ * The diagnostic values `captureRunFailure` sends with a terminal-failure
+ * event. `errorCode` is `null` when the run holds no error code.
+ */
+export interface RunFailureEvent {
+ /** The task UUID the run belongs to. */
+ taskId: string;
+ /** The `heartbeat_runs` row id. */
+ runId: string;
+ /** The redacted error message. */
+ errorMessage: string;
+ /** The run's error code, or `null` when the run holds none. */
+ errorCode: string | null;
+ /** The agent's adapter type, or `"unknown"` when the agent row is absent. */
+ agentAdapter: string;
+ /** The run status that triggered this report. */
+ runStatus: RunFailureStatus;
+}
+
+/**
+ * Report one terminal run failure to Sentry. A no-op before the gate opens
+ * or when the gate never opens. Never throws — observability must not
+ * change run control flow.
+ *
+ * Sets the fingerprint to `[errorCode, agentAdapter]`, in that order, so
+ * Sentry groups events by error code and adapter. The error message stays
+ * out of the fingerprint — it still travels as the exception message and as
+ * a field of the `run_failure` context.
+ */
+export function captureRunFailure(event: RunFailureEvent): void {
+ if (!sentryHandle) return;
+ const handle = sentryHandle;
+ try {
+ handle.withScope((scope) => {
+ const errorCode = event.errorCode ?? "unknown";
+ scope.setTag("run_id", event.runId);
+ scope.setTag("task_id", event.taskId);
+ scope.setTag("error_code", errorCode);
+ scope.setTag("agent_adapter", event.agentAdapter);
+ scope.setTag("run_status", event.runStatus);
+ scope.setContext("run_failure", {
+ taskId: event.taskId,
+ runId: event.runId,
+ errorMessage: event.errorMessage,
+ errorCode,
+ agentAdapter: event.agentAdapter,
+ });
+ scope.setFingerprint([errorCode, event.agentAdapter]);
+ handle.captureException(new Error(event.errorMessage));
+ });
+ } catch (err) {
+ // eslint-disable-next-line no-console
+ console.error("[paperclip] Sentry captureRunFailure failed", err);
+ }
+}
+
/**
* Flush buffered events and close the Sentry client. Idempotent — concurrent
* callers share one shutdown. A no-op when monitoring is off or bootstrap
@@ -130,6 +209,7 @@ export interface SentryInitOptions {
skipOpenTelemetrySetup: boolean;
tracesSampleRate: number;
sendDefaultPii: boolean;
+ serverName: string;
integrations: (defaults: Array<{ name: string }>) => Array<{ name: string }>;
}
@@ -148,6 +228,7 @@ export function buildSentryInitOptions(
skipOpenTelemetrySetup: true,
tracesSampleRate: 0,
sendDefaultPii: false,
+ serverName: process.env.SENTRY_NAME || os.hostname(),
integrations: (defaults: Array<{ name: string }>) => {
const kept = defaults.filter(
(integration) =>
@@ -198,6 +279,7 @@ async function bootstrapSentry(dsn: string): Promise<void> {
sentryHandle = {
captureException: (error) => Sentry.captureException(error),
+ withScope: (callback) => Sentry.withScope(callback),
close: (timeout) => Sentry.close(timeout),
};
} catch (err) {
diff --git a/server/src/services/__tests__/run-failure-report.test.ts b/server/src/services/__tests__/run-failure-report.test.ts
new file mode 100644
index 0000000000..75ba13de1f
--- /dev/null
+++ b/server/src/services/__tests__/run-failure-report.test.ts
@@ -0,0 +1,405 @@
+import { randomUUID } from "node:crypto";
+import os from "node:os";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { agents, companies, createDb, heartbeatRuns, type Db } from "@paperclipai/db";
+import {
+ getEmbeddedPostgresTestSupport,
+ startEmbeddedPostgresTestDatabase,
+} from "../../__tests__/helpers/embedded-postgres.js";
+
+const mockCaptureRunFailure = vi.hoisted(() => vi.fn());
+const mockRedactCurrentUserText = vi.hoisted(() => vi.fn());
+
+vi.mock("../../sentry.js", () => ({
+ captureRunFailure: mockCaptureRunFailure,
+}));
+// Wrap the real function instead of a fake, so tests can assert the actual
+// redacted output while still spying on the call. A fake output would hide
+// whether the composed redaction in run-failure-report.ts is correct.
+vi.mock("../../log-redaction.js", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../log-redaction.js")>();
+ mockRedactCurrentUserText.mockImplementation(actual.redactCurrentUserText);
+ return { ...actual, redactCurrentUserText: mockRedactCurrentUserText };
+});
+
+import { reportRunFailure, waitForPendingRunFailureReports } from "../run-failure-report.js";
+import { redactSensitiveText, REDACTED_EVENT_VALUE } from "../../redaction.js";
+import { redactCurrentUserText } from "../../log-redaction.js";
+
+const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
+const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
+
+describeEmbeddedPostgres("reportRunFailure", () => {
+ let db!: ReturnType<typeof createDb>;
+ let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
+ let companyId!: string;
+ let agentId!: string;
+
+ beforeAll(async () => {
+ tempDb = await startEmbeddedPostgresTestDatabase("paperclip-run-failure-report-");
+ db = createDb(tempDb.connectionString);
+ }, 20_000);
+
+ afterEach(async () => {
+ vi.clearAllMocks();
+ await db.delete(agents);
+ await db.delete(companies);
+ });
+
+ afterAll(async () => {
+ await tempDb?.cleanup();
+ });
+
+ async function seedCompanyAndAgent(agentOverrides: Partial<typeof agents.$inferInsert> = {}) {
+ companyId = randomUUID();
+ agentId = randomUUID();
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Paperclip",
+ issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
+ requireBoardApprovalForNewAgents: false,
+ defaultResponsibleUserId: "responsible-user",
+ });
+ await db.insert(agents).values({
+ id: agentId,
+ companyId,
+ name: "CodexCoder",
+ role: "engineer",
+ status: "active",
+ adapterType: "codex_local",
+ adapterConfig: {},
+ runtimeConfig: {},
+ permissions: {},
+ ...agentOverrides,
+ });
+ return { companyId, agentId };
+ }
+
+ function buildRun(
+ overrides: Partial<typeof heartbeatRuns.$inferSelect> = {},
+ ): typeof heartbeatRuns.$inferSelect {
+ return {
+ id: randomUUID(),
+ companyId,
+ agentId,
+ status: "failed",
+ error: "the provider process exited with code 1",
+ errorCode: "process_lost",
+ nativeIssueId: randomUUID(),
+ contextSnapshot: null,
+ ...overrides,
+ } as unknown as typeof heartbeatRuns.$inferSelect;
+ }
+
+ it("captures once for the status failed", async () => {
+ await seedCompanyAndAgent();
+ const run = buildRun({ status: "failed" });
+
+ await reportRunFailure(db, run);
+
+ expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1);
+ });
+
+ it("captures once for the status timed_out", async () => {
+ await seedCompanyAndAgent();
+ const run = buildRun({ status: "timed_out" });
+
+ await reportRunFailure(db, run);
+
+ expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1);
+ expect(mockCaptureRunFailure).toHaveBeenCalledWith(
+ expect.objectContaining({ runStatus: "timed_out" }),
+ );
+ });
+
+ it("captures nothing for succeeded, cancelled, and interrupted", async () => {
+ await seedCompanyAndAgent();
+ for (const status of ["succeeded", "cancelled", "interrupted"] as const) {
+ const run = buildRun({ status });
+ await reportRunFailure(db, run);
+ }
+
+ expect(mockCaptureRunFailure).not.toHaveBeenCalled();
+ });
+
+ it("sends agents.adapterType from the loaded agent row", async () => {
+ await seedCompanyAndAgent({ adapterType: "claude_managed" });
+ const run = buildRun({ status: "failed" });
+
+ await reportRunFailure(db, run);
+
+ expect(mockCaptureRunFailure).toHaveBeenCalledWith(
+ expect.objectContaining({ agentAdapter: "claude_managed" }),
+ );
+ });
+
+ it("sends the adapter value unknown when the agent row is absent", async () => {
+ await seedCompanyAndAgent();
+ const run = buildRun({ status: "failed", agentId: randomUUID() });
+
+ await reportRunFailure(db, run);
+
+ expect(mockCaptureRunFailure).toHaveBeenCalledWith(
+ expect.objectContaining({ agentAdapter: "unknown" }),
+ );
+ });
+
+ it("calls redactCurrentUserText on the error message before it composes the credential redactor", async () => {
+ await seedCompanyAndAgent();
+ const run = buildRun({ status: "failed", error: "raw message" });
+
+ await reportRunFailure(db, run);
+
+ expect(mockRedactCurrentUserText).toHaveBeenCalledWith("raw message");
+ });
+
+ it("removes an Authorization: Bearer credential from the error message", async () => {
+ await seedCompanyAndAgent();
+ const run = buildRun({
+ status: "failed",
+ error: "the adapter request failed: Authorization: Bearer live-secret-token-value",
+ });
+
+ await reportRunFailure(db, run);
+
+ const { errorMessage } = mockCaptureRunFailure.mock.calls[0][0];
+ expect(errorMessage).not.toContain("live-secret-token-value");
+ expect(errorMessage).toContain(REDACTED_EVENT_VALUE);
+ });
+
+ it("removes an API-key form from the error message", async () => {
+ await seedCompanyAndAgent();
+ const run = buildRun({
+ status: "failed",
+ error: `adapter payload: {"apiKey":"json-secret-value"}`,
+ });
+
+ await reportRunFailure(db, run);
+
+ const { errorMessage } = mockCaptureRunFailure.mock.calls[0][0];
+ expect(errorMessage).not.toContain("json-secret-value");
+ expect(errorMessage).toContain(REDACTED_EVENT_VALUE);
+ });
+
+ it("removes a JSON Web Token form from the error message", async () => {
+ await seedCompanyAndAgent();
+ const jwt =
+ "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
+ const run = buildRun({ status: "failed", error: `session token: ${jwt}` });
+
+ await reportRunFailure(db, run);
+
+ const { errorMessage } = mockCaptureRunFailure.mock.calls[0][0];
+ expect(errorMessage).not.toContain(jwt);
+ expect(errorMessage).toContain(REDACTED_EVENT_VALUE);
+ });
+
+ it("removes a password value from the error message", async () => {
+ await seedCompanyAndAgent();
+ const run = buildRun({
+ status: "failed",
+ error: `login failed: password="hunter2-super-secret"`,
+ });
+
+ await reportRunFailure(db, run);
+
+ const { errorMessage } = mockCaptureRunFailure.mock.calls[0][0];
+ expect(errorMessage).not.toContain("hunter2-super-secret");
+ expect(errorMessage).toContain(REDACTED_EVENT_VALUE);
+ });
+
+ it("removes a database connection string from the error message", async () => {
+ await seedCompanyAndAgent();
+ const run = buildRun({
+ status: "failed",
+ error: `connect failed: connectionString: "postgres://appuser:[email protected]:5432/paperclip"`,
+ });
+
+ await reportRunFailure(db, run);
+
+ const { errorMessage } = mockCaptureRunFailure.mock.calls[0][0];
+ expect(errorMessage).not.toContain("s3cr3t-pass");
+ expect(errorMessage).toContain(REDACTED_EVENT_VALUE);
+ });
+
+ it("still masks the current user's home path in the error message", async () => {
+ await seedCompanyAndAgent();
+ const homeDir = os.homedir();
+ const rawError = `read failed at ${homeDir}/workspace/report.log`;
+ const run = buildRun({ status: "failed", error: rawError });
+
+ await reportRunFailure(db, run);
+
+ const expectedErrorMessage = redactSensitiveText(redactCurrentUserText(rawError));
+ const { errorMessage } = mockCaptureRunFailure.mock.calls[0][0];
+ expect(errorMessage).toBe(expectedErrorMessage);
+ expect(errorMessage).not.toContain(homeDir);
+ });
+
+ const MAX_ERROR_MESSAGE_LENGTH = 4096;
+
+ it("truncates an error message that is longer than the bound", async () => {
+ await seedCompanyAndAgent();
+ const longError = "x".repeat(MAX_ERROR_MESSAGE_LENGTH + 500);
+ const run = buildRun({ status: "failed", error: longError });
+
+ await reportRunFailure(db, run);
+
+ const { errorMessage } = mockCaptureRunFailure.mock.calls[0][0];
+ expect(errorMessage).toHaveLength(MAX_ERROR_MESSAGE_LENGTH);
+ expect(errorMessage).toBe("x".repeat(MAX_ERROR_MESSAGE_LENGTH));
+ });
+
+ it("does not change a short error message", async () => {
+ await seedCompanyAndAgent();
+ const shortError = "the provider process exited with code 1";
+ const run = buildRun({ status: "failed", error: shortError });
+
+ await reportRunFailure(db, run);
+
+ const { errorMessage } = mockCaptureRunFailure.mock.calls[0][0];
+ expect(errorMessage).toBe(shortError);
+ });
+
+ const MAX_ERROR_CODE_LENGTH = 200;
+
+ it("sends a normal error code such as adapter_failed to Sentry unchanged", async () => {
+ await seedCompanyAndAgent();
+ const run = buildRun({ status: "failed", errorCode: "adapter_failed" });
+
+ await reportRunFailure(db, run);
+
+ expect(mockCaptureRunFailure).toHaveBeenCalledWith(
+ expect.objectContaining({ errorCode: "adapter_failed" }),
+ );
+ });
+
+ it("redacts an error code that holds a credential form", async () => {
+ await seedCompanyAndAgent();
+ const run = buildRun({
+ status: "failed",
+ errorCode: "Authorization: Bearer live-secret-token-value",
+ });
+
+ await reportRunFailure(db, run);
+
+ const { errorCode } = mockCaptureRunFailure.mock.calls[0][0];
+ expect(errorCode).not.toContain("live-secret-token-value");
+ expect(errorCode).toContain(REDACTED_EVENT_VALUE);
+ });
+
+ it("truncates an error code that is longer than 200 characters", async () => {
+ await seedCompanyAndAgent();
+ const longErrorCode = "y".repeat(MAX_ERROR_CODE_LENGTH + 50);
+ const run = buildRun({ status: "failed", errorCode: longErrorCode });
+
+ await reportRunFailure(db, run);
+
+ const { errorCode } = mockCaptureRunFailure.mock.calls[0][0];
+ expect(errorCode).toHaveLength(MAX_ERROR_CODE_LENGTH);
+ expect(errorCode).toBe("y".repeat(MAX_ERROR_CODE_LENGTH));
+ });
+
+ it("sends errorCode null unchanged when the run holds no error code", async () => {
+ await seedCompanyAndAgent();
+ const run = buildRun({ status: "failed", errorCode: null });
+
+ await reportRunFailure(db, run);
+
+ expect(mockCaptureRunFailure).toHaveBeenCalledWith(
+ expect.objectContaining({ errorCode: null }),
+ );
+ });
+
+ it("reads the task id from nativeIssueId, falling back to contextSnapshot.issueId", async () => {
+ await seedCompanyAndAgent();
+ const nativeIssueId = randomUUID();
+ const runWithNativeIssueId = buildRun({
+ status: "failed",
+ nativeIssueId,
+ contextSnapshot: { issueId: randomUUID() },
+ });
+
+ await reportRunFailure(db, runWithNativeIssueId);
+
+ expect(mockCaptureRunFailure).toHaveBeenCalledWith(
+ expect.objectContaining({ taskId: nativeIssueId }),
+ );
+
+ mockCaptureRunFailure.mockClear();
+ const contextIssueId = randomUUID();
+ const runWithContextIssueId = buildRun({
+ status: "failed",
+ nativeIssueId: null,
+ contextSnapshot: { issueId: contextIssueId },
+ });
+
+ await reportRunFailure(db, runWithContextIssueId);
+
+ expect(mockCaptureRunFailure).toHaveBeenCalledWith(
+ expect.objectContaining({ taskId: contextIssueId }),
+ );
+ });
+
+ it("does not throw when the database read fails", async () => {
+ const throwingDb = {
+ select: () => {
+ throw new Error("connection reset");
+ },
+ } as unknown as Db;
+ const run = buildRun({ status: "failed", agentId: randomUUID() });
+
+ await expect(reportRunFailure(throwingDb, run)).resolves.toBeUndefined();
+ expect(mockCaptureRunFailure).not.toHaveBeenCalled();
+ });
+
+ describe("waitForPendingRunFailureReports", () => {
+ function deferredAgentRows() {
+ let resolve!: (rows: Array<{ adapterType: string }>) => void;
+ const promise = new Promise<Array<{ adapterType: string }>>((res) => {
+ resolve = res;
+ });
+ return { promise, resolve };
+ }
+
+ function fakeDb(agentRowsPromise: Promise<Array<{ adapterType: string }>>): Db {
+ return {
+ select: () => ({
+ from: () => ({
+ where: () => agentRowsPromise,
+ }),
+ }),
+ } as unknown as Db;
+ }
+
+ it("resolves at once when no report is in flight", async () => {
+ await expect(waitForPendingRunFailureReports()).resolves.toBeUndefined();
+ });
+
+ it("waits for an unawaited report's database read and Sentry capture before it resolves", async () => {
+ const agentRows = deferredAgentRows();
+ const run = buildRun({ status: "failed", agentId: randomUUID() });
+
+ // Do not await the report — this models the fire-and-forget
+ // `void reportRunFailure(db, run)` call every caller uses.
+ void reportRunFailure(fakeDb(agentRows.promise), run);
+
+ const drain = waitForPendingRunFailureReports(1_000);
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ expect(mockCaptureRunFailure).not.toHaveBeenCalled();
+
+ agentRows.resolve([{ adapterType: "claude_managed" }]);
+ await drain;
+
+ expect(mockCaptureRunFailure).toHaveBeenCalledTimes(1);
+ });
+
+ it("gives up after the bound and does not throw when a report never settles", async () => {
+ const run = buildRun({ status: "failed", agentId: randomUUID() });
+ void reportRunFailure(fakeDb(new Promise(() => undefined)), run);
+
+ await expect(waitForPendingRunFailureReports(20)).resolves.toBeUndefined();
+ expect(mockCaptureRunFailure).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/server/src/services/execution-control-reconciliation.test.ts b/server/src/services/execution-control-reconciliation.test.ts
new file mode 100644
index 0000000000..ca9bf41673
--- /dev/null
+++ b/server/src/services/execution-control-reconciliation.test.ts
@@ -0,0 +1,116 @@
+import { randomUUID } from "node:crypto";
+import { eq } from "drizzle-orm";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+import { agents, companies, createDb, heartbeatRuns, issues } from "@paperclipai/db";
+import {
+ getEmbeddedPostgresTestSupport,
+ startEmbeddedPostgresTestDatabase,
+} from "../__tests__/helpers/embedded-postgres.js";
+
+const mockCaptureRunFailure = vi.hoisted(() => vi.fn());
+vi.mock("../sentry.js", async () => {
+ const actual = await vi.importActual<typeof import("../sentry.js")>("../sentry.js");
+ return {
+ ...actual,
+ captureRunFailure: mockCaptureRunFailure,
+ };
+});
+
+import { reconcileAbandonedExecutionControl } from "./execution-control-reconciliation.js";
+
+const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
+const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
+
+describeEmbeddedPostgres("reconcileAbandonedExecutionControl reports a genuine failed transition", () => {
+ let db!: ReturnType<typeof createDb>;
+ let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
+
+ beforeAll(async () => {
+ tempDb = await startEmbeddedPostgresTestDatabase("execution-control-reconciliation-");
+ db = createDb(tempDb.connectionString);
+ }, 30_000);
+
+ afterAll(async () => {
+ await tempDb?.cleanup();
+ });
+
+ async function seedAbandonedRunFixture() {
+ const companyId = randomUUID();
+ const agentId = randomUUID();
+ const issueId = randomUUID();
+ const runId = randomUUID();
+ const pastDeadline = new Date(Date.now() - 60_000);
+
+ await db.insert(companies).values({
+ id: companyId,
+ name: "Execution Control Reconciliation",
+ issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`,
+ });
+ await db.insert(agents).values({
+ id: agentId,
+ companyId,
+ name: "Stuck worker",
+ adapterType: "codex_local",
+ status: "running",
+ });
+ await db.insert(heartbeatRuns).values({
+ id: runId,
+ companyId,
+ agentId,
+ status: "running",
+ executionControlDeadlineAt: pastDeadline,
+ contextSnapshot: { issueId },
+ });
+ await db.insert(issues).values({
+ id: issueId,
+ companyId,
+ title: "Abandoned execution control fixture",
+ status: "in_progress",
+ assigneeAgentId: agentId,
+ executionRunId: runId,
+ checkoutRunId: runId,
+ });
+
+ return { companyId, agentId, issueId, runId };
+ }
+
+ it("reports exactly one Sentry event for a genuine finalization-deadline failure", async () => {
+ const { runId } = await seedAbandonedRunFixture();
+ const captureCallsBefore = mockCaptureRunFailure.mock.calls.length;
+
+ const result = await reconcileAbandonedExecutionControl(db);
+
+ expect(result.surfaced).toBe(1);
+ const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
+ expect(run?.status).toBe("failed");
+ expect(run?.errorCode).toBe("execution_finalization_deadline_exceeded");
+
+ const newCaptures = mockCaptureRunFailure.mock.calls.slice(captureCallsBefore);
+ expect(newCaptures).toHaveLength(1);
+ expect(newCaptures[0]?.[0]).toMatchObject({
+ runId,
+ runStatus: "failed",
+ errorCode: "execution_finalization_deadline_exceeded",
+ });
+ });
+
+ it("reports zero events for a repeated sweep over the same already-failed run", async () => {
+ const { runId } = await seedAbandonedRunFixture();
+ await reconcileAbandonedExecutionControl(db);
+ // The first sweep already cleared executionControlDeadlineAt and moved the
+ // run to "failed". Restore the deadline to simulate a second sweep still
+ // observing the same run as a candidate.
+ await db
+ .update(heartbeatRuns)
+ .set({ executionControlDeadlineAt: new Date(Date.now() - 1_000) })
+ .where(eq(heartbeatRuns.id, runId));
+
+ const captureCallsBefore = mockCaptureRunFailure.mock.calls.length;
+ const result = await reconcileAbandonedExecutionControl(db);
+
+ // The run is already terminal ("failed"), so the early terminal-status
+ // guard applies and no second "failed" write happens.
+ expect(result.surfaced).toBe(1);
+ expect(mockCaptureRunFailure.mock.calls.slice(captureCallsBefore)).toHaveLength(0);
+ });
+});
diff --git a/server/src/services/execution-control-reconciliation.ts b/server/src/services/execution-control-reconciliation.ts
index 58c8578cce..cba2f2f15b 100644
--- a/server/src/services/execution-control-reconciliation.ts
+++ b/server/src/services/execution-control-reconciliation.ts
@@ -10,6 +10,7 @@ import {
} from "@paperclipai/db";
import { parseIssueExecutionState } from "./issue-execution-policy.js";
import { issueRecoveryActionService } from "./issue-recovery-actions.js";
+import { reportRunFailure } from "./run-failure-report.js";
/** Only newly recorded control deadlines are eligible. Upgrades never replay ambiguous historical runs. */
export async function reconcileAbandonedExecutionControl(
@@ -66,6 +67,10 @@ export async function reconcileAbandonedExecutionControl(
while (nextCandidate < due.length) {
const candidate = due[nextCandidate++]!;
try {
+ // Set inside the transaction only when the write below genuinely
+ // transitions the run into "failed". Read after the transaction
+ // commits, so a rolled-back write never reports a false failure.
+ let terminalRunToReport: typeof heartbeatRuns.$inferSelect | null = null;
const repaired = await db.transaction(async (tx) => {
await tx.execute(
sql`select set_config('statement_timeout', '15000', true), set_config('lock_timeout', '1000', true)`,
@@ -167,7 +172,7 @@ export async function reconcileAbandonedExecutionControl(
updatedAt: now,
})
.where(eq(nativeRunFinalizations.runId, run.id));
- await tx
+ const [updatedRun] = await tx
.update(heartbeatRuns)
.set({
status: "failed",
@@ -181,7 +186,11 @@ export async function reconcileAbandonedExecutionControl(
nextAction,
updatedAt: now,
})
- .where(eq(heartbeatRuns.id, run.id));
+ .where(eq(heartbeatRuns.id, run.id))
+ .returning();
+ if (updatedRun && updatedRun.status !== run.status) {
+ terminalRunToReport = updatedRun;
+ }
await tx
.update(agents)
.set({ status: "idle", updatedAt: now })
@@ -233,6 +242,7 @@ export async function reconcileAbandonedExecutionControl(
return true;
});
if (repaired) surfaced += 1;
+ if (terminalRunToReport) void reportRunFailure(db, terminalRunToReport);
} catch {
logger.warn(
{ runId: candidate.runId },
diff --git a/server/src/services/heartbeat.ts b/server/src/services/heartbeat.ts
index 9c0309254c..b985426deb 100644
--- a/server/src/services/heartbeat.ts
+++ b/server/src/services/heartbeat.ts
@@ -297,6 +297,7 @@ import {
emitAgentTaskRun,
emitAgentTaskRunById,
} from "./agent-task-run-telemetry.js";
+import { reportRunFailure } from "./run-failure-report.js";
import { companySkillService } from "./company-skills.js";
import { budgetService, type BudgetEnforcementScope } from "./budgets.js";
import { secretService, type MissingRuntimeBinding } from "./secrets.js";
@@ -12599,6 +12600,7 @@ export function heartbeatService(
if (previousStatus === updated.status) return;
clearHeartbeatRunRuntimeStatus(updated.id);
void emitAgentTaskRun(db, updated);
+ void reportRunFailure(db, updated);
}
async function setRunStatus(
diff --git a/server/src/services/native-runtime/native-finalization-reconciler.ts b/server/src/services/native-runtime/native-finalization-reconciler.ts
index f63d0e27e5..c88479166b 100644
--- a/server/src/services/native-runtime/native-finalization-reconciler.ts
+++ b/server/src/services/native-runtime/native-finalization-reconciler.ts
@@ -32,6 +32,7 @@ import {
import { issueRecoveryActionService } from "../issue-recovery-actions.js";
import { issueService } from "../issues.js";
import { emitAgentTaskRun } from "../agent-task-run-telemetry.js";
+import { reportRunFailure } from "../run-failure-report.js";
import { resumeNativeWorkspaceFinalization } from "./native-workspace-finalizer.js";
import { dismissObsoleteNativePolicyReviews } from "./obsolete-policy-reviews.js";
import {
@@ -461,7 +462,11 @@ export async function claimNativeSessionResumptions(input: {
: "Persisted native session state is ambiguous and cannot be resumed safely",
updatedAt: now,
}).where(eq(heartbeatRuns.id, row.run.id)).returning();
- terminalRunToEmit = updatedRun ?? null;
+ // Only a genuine transition into "failed" is a new terminal failure.
+ // A candidate that is already "failed" (the filter above admits
+ // both "running" and "failed") must not send a second Sentry event.
+ terminalRunToEmit =
+ updatedRun && updatedRun.status !== row.run.status ? updatedRun : null;
await issueService(tx as unknown as Db).update(
row.coordinator.issueId,
{ status: "blocked" },
@@ -520,6 +525,7 @@ export async function claimNativeSessionResumptions(input: {
// the remaining candidates in this loop, so fire it and do not await it.
if (terminalRunToEmit) {
void emitAgentTaskRun(input.db, terminalRunToEmit);
+ void reportRunFailure(input.db, terminalRunToEmit);
}
if (claimed) claims.push({ runId: candidate.runId, leaseOwner });
}
diff --git a/server/src/services/native-runtime/native-restart-recovery.ts b/server/src/services/native-runtime/native-restart-recovery.ts
index 30ba177efa..5d5743e9b5 100644
--- a/server/src/services/native-runtime/native-restart-recovery.ts
+++ b/server/src/services/native-runtime/native-restart-recovery.ts
@@ -13,6 +13,7 @@ import { readProcessStartedAt } from "../hot-restart.js";
import { getServerInfoSnapshot } from "../../server-info.js";
import { redactSensitiveText } from "../../redaction.js";
import { issueRecoveryActionService } from "../issue-recovery-actions.js";
+import { reportRunFailure } from "../run-failure-report.js";
import { isNativeRunnerOwnershipHeld } from "./native-runner-ownership.js";
export type NativeControllerIdentity = {
@@ -473,6 +474,10 @@ export async function claimNativeRestartRecoveries(input: {
const dispositions: NativeRestartRecoveryDisposition[] = [];
for (const candidate of candidates) {
+ // Set inside the transaction only when the write below genuinely
+ // transitions the run into "failed". Read after the transaction
+ // commits, so a rolled-back write never reports a false failure.
+ let terminalRunToReport: typeof heartbeatRuns.$inferSelect | null = null;
const disposition = await input.db.transaction(async (tx) => {
await tx.execute(
sql`select set_config('statement_timeout', '15000', true), set_config('lock_timeout', '1000', true)`,
@@ -782,7 +787,7 @@ export async function claimNativeRestartRecoveries(input: {
eq(nativeRunFinalizations.phase, row.coordinator.phase),
),
);
- await tx
+ const [updatedRun] = await tx
.update(heartbeatRuns)
.set({
status: "failed",
@@ -794,7 +799,11 @@ export async function claimNativeRestartRecoveries(input: {
error: reason,
updatedAt: now,
})
- .where(eq(heartbeatRuns.id, row.run.id));
+ .where(eq(heartbeatRuns.id, row.run.id))
+ .returning();
+ if (updatedRun && updatedRun.status !== row.run.status) {
+ terminalRunToReport = updatedRun;
+ }
await tx
.update(issues)
.set({ executionRunId: null, updatedAt: now })
@@ -958,6 +967,7 @@ export async function claimNativeRestartRecoveries(input: {
...common,
} satisfies NativeRestartRecoveryClaim;
});
+ if (terminalRunToReport) void reportRunFailure(input.db, terminalRunToReport);
dispositions.push(disposition);
}
return dispositions;
diff --git a/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts b/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts
index 6a8ce58198..5699f58511 100644
--- a/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts
+++ b/server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts
@@ -27,12 +27,25 @@ const mockTelemetryClient = vi.hoisted(() => ({
}));
vi.mock("../../telemetry.ts", () => ({ getTelemetryClient: () => mockTelemetryClient }));
+const mockCaptureRunFailure = vi.hoisted(() => vi.fn());
+vi.mock("../../sentry.ts", async () => {
+ const actual = await vi.importActual<typeof import("../../sentry.ts")>("../../sentry.ts");
+ return {
+ ...actual,
+ captureRunFailure: mockCaptureRunFailure,
+ };
+});
+
function agentTaskRunCalls(fromIndex: number) {
return mockTelemetryClient.track.mock.calls
.slice(fromIndex)
.filter((call) => call[0] === "agent.task_run");
}
+function captureRunFailureCallsFrom(fromIndex: number) {
+ return mockCaptureRunFailure.mock.calls.slice(fromIndex);
+}
+
import { PaperclipControlPlanePort } from "./paperclip-control-plane-port.js";
import { finalizeNativeRun, recordNativeFinalizationFailure } from "./native-run-finalizer.js";
import { commitNativeStatusDecision } from "./status-decision-committer.js";
@@ -166,6 +179,7 @@ describeEmbeddedPostgres("native run finalizer / status decision committer — a
await driveToCompleteResult(fixture);
const callsBefore = mockTelemetryClient.track.mock.calls.length;
+ const captureCallsBefore = mockCaptureRunFailure.mock.calls.length;
await finalizeNativeRun({
db,
runId: fixture.runId,
@@ -183,6 +197,8 @@ describeEmbeddedPostgres("native run finalizer / status decision committer — a
.where(eq(heartbeatRuns.id, fixture.runId))
.then((rows) => rows[0]);
expect(run?.status).toBe("succeeded");
+ // "succeeded" is not a failure status, so it never reports to Sentry.
+ expect(captureRunFailureCallsFrom(captureCallsBefore)).toHaveLength(0);
});
it("emits zero events when a repeat finalize call preserves the succeeded terminal state", async () => {
@@ -410,6 +426,7 @@ describeEmbeddedPostgres("native run finalizer / status decision committer — a
// workspaceFinalizeStatus reports whether the workspace finalization
// step itself succeeded, independent of the run's own terminal state
// (runTerminalState below), which is what actually failed here.
+ const captureCallsBeforeFirstFinalize = mockCaptureRunFailure.mock.calls.length;
await finalizeNativeRun({
db,
runId: fixture.runId,
@@ -422,13 +439,23 @@ describeEmbeddedPostgres("native run finalizer / status decision committer — a
.where(eq(heartbeatRuns.id, fixture.runId))
.then((rows) => rows[0]);
expect(run?.status).toBe("failed");
+ // The first write is a genuine transition into "failed": it reports
+ // exactly one Sentry event.
+ const firstFinalizeCaptures = captureRunFailureCallsFrom(captureCallsBeforeFirstFinalize);
+ expect(firstFinalizeCaptures).toHaveLength(1);
+ expect(firstFinalizeCaptures[0]?.[0]).toMatchObject({
+ runId: fixture.runId,
+ runStatus: "failed",
+ });
const callsBefore = mockTelemetryClient.track.mock.calls.length;
+ const captureCallsBeforeReplay = mockCaptureRunFailure.mock.calls.length;
// The coordinator is already "committed" with a "failed" terminal
// result, and the run row is already "failed". Like "succeeded",
// "failed" sits inside projectCommittedRun's WHERE clause, so its write
// matches the row. The write changes nothing (failed -> failed), so it
- // must not emit a second event for the same committed result.
+ // must not emit a second event for the same committed result, and it
+ // must not report a second Sentry event either.
await finalizeNativeRun({
db,
runId: fixture.runId,
@@ -436,6 +463,7 @@ describeEmbeddedPostgres("native run finalizer / status decision committer — a
projectRunStatus: true,
});
expect(agentTaskRunCalls(callsBefore)).toHaveLength(0);
+ expect(captureRunFailureCallsFrom(captureCallsBeforeReplay)).toHaveLength(0);
});
it("emits zero events when a retryable-failure write's conditional status spread is omitted", async () => {
diff --git a/server/src/services/native-runtime/native-run-finalizer.ts b/server/src/services/native-runtime/native-run-finalizer.ts
index a2a977a769..f2142a719f 100644
--- a/server/src/services/native-runtime/native-run-finalizer.ts
+++ b/server/src/services/native-runtime/native-run-finalizer.ts
@@ -40,6 +40,7 @@ import {
readNativeBoardResponseWaitSource,
} from "./native-board-response-wait.js";
import { emitAgentTaskRun } from "../agent-task-run-telemetry.js";
+import { reportRunFailure } from "../run-failure-report.js";
import { resolveExternalChatResponseWaitAuthorization } from "./chat-attachment-reuse.js";
import {
authorizeNativeChatReviewPresentation,
@@ -486,7 +487,10 @@ async function recordRetryableFailure(input: {
nextAttemptAt: supersededByNewerRun || exhausted ? null : nextAttemptAt,
};
});
- if (terminalRunToEmit) await emitAgentTaskRun(input.db, terminalRunToEmit);
+ if (terminalRunToEmit) {
+ await emitAgentTaskRun(input.db, terminalRunToEmit);
+ void reportRunFailure(input.db, terminalRunToEmit);
+ }
return {
...input.coordinator,
...outcome,
@@ -627,6 +631,7 @@ async function projectCommittedRun(input: {
// committed terminal result.
if (updatedRun && updatedRun.status !== input.run.status) {
await emitAgentTaskRun(input.db, updatedRun);
+ void reportRunFailure(input.db, updatedRun);
}
}
@@ -1331,6 +1336,7 @@ export async function finalizeNativeRun(input: {
updatedRun
) {
await emitAgentTaskRun(input.db, updatedRun);
+ void reportRunFailure(input.db, updatedRun);
}
if (input.projectRunStatus)
await materializeCommittedReviewResponse(input.db, input.runId);
diff --git a/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts b/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts
index cb2d54a132..87f2e0c4f8 100644
--- a/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts
+++ b/server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts
@@ -35,6 +35,16 @@ import {
} from "../../realtime/runner-prp-ws.js";
import { readProcessStartedAt } from "../hot-restart.js";
import { prepareNativeHeartbeatRun } from "./prepare-native-run.js";
+
+const mockCaptureRunFailure = vi.hoisted(() => vi.fn());
+vi.mock("../../sentry.js", async () => {
+ const actual = await vi.importActual<typeof import("../../sentry.js")>("../../sentry.js");
+ return {
+ ...actual,
+ captureRunFailure: mockCaptureRunFailure,
+ };
+});
+
import {
claimNativeRestartRecoveries,
type NativeControllerIdentity,
@@ -985,8 +995,25 @@ describeEmbeddedPostgres("native runner restart recovery with real processes", (
} } }).where(eq(heartbeatRuns.id, fixture.runId));
await fixture.db.update(nativeRunFinalizations).set({ attempt: 3 }).where(eq(nativeRunFinalizations.runId, fixture.runId));
const input = { db: fixture.db, controller: successor, restartKind: "hard" as const, runIds: [fixture.runId] };
+ const captureCallsBeforeFirstClaim = mockCaptureRunFailure.mock.calls.length;
expect(await claimNativeRestartRecoveries(input)).toEqual([{ kind: "blocked", runId: fixture.runId, reason: "provider_checkpoint_permanently_failed" }]);
+ // The report fires without being awaited, so wait for it before asserting.
+ await vi.waitFor(() => {
+ expect(mockCaptureRunFailure.mock.calls.length).toBeGreaterThan(captureCallsBeforeFirstClaim);
+ });
+ const firstClaimCaptures = mockCaptureRunFailure.mock.calls.slice(captureCallsBeforeFirstClaim);
+ expect(firstClaimCaptures).toHaveLength(1);
+ expect(firstClaimCaptures[0]?.[0]).toMatchObject({
+ runId: fixture.runId,
+ runStatus: "failed",
+ errorCode: "native_restart_recovery_blocked",
+ });
+
+ const captureCallsBeforeReplay = mockCaptureRunFailure.mock.calls.length;
expect(await claimNativeRestartRecoveries(input)).toEqual([]);
+ // A replay that finds no eligible candidate must not report a second event.
+ expect(mockCaptureRunFailure.mock.calls.slice(captureCallsBeforeReplay)).toHaveLength(0);
+
const [run] = await fixture.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
const [issue] = await fixture.db.select().from(issues).where(eq(issues.id, fixture.issueId));
expect(run).toMatchObject({ status: "failed", nativePhase: "terminal_failure", errorCode: "native_restart_recovery_blocked" });
diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts
index 80b9b92225..2173f6b6f9 100644
--- a/server/src/services/native-runtime/native-session-executor.ts
+++ b/server/src/services/native-runtime/native-session-executor.ts
@@ -127,6 +127,7 @@ import { verifyRetainedMaintenanceNoLaunch } from "./native-maintenance-no-launc
import { registerRunnerPrpAuthority } from "../../realtime/runner-prp-ws.js";
import { connectRunnerPrpIngress } from "../../realtime/runner-prp-outbound.js";
import { issueRecoveryActionService } from "../issue-recovery-actions.js";
+import { reportRunFailure } from "../run-failure-report.js";
import { persistActivity, publishActivity } from "../activity-log.js";
import { commitNativeStatusDecision } from "./status-decision-committer.js";
import { resolvePaperclipInstanceRoot } from "../../home-paths.js";
@@ -8234,6 +8235,10 @@ async function executePaperclipNativeSessionWithinScope(
? error.message.slice(0, 2_000)
: String(error).slice(0, 2_000);
const sanitizedStderrTail = redactSensitiveText(message).slice(-4_096);
+ // Set inside the transaction only when the write below genuinely
+ // transitions the run into "failed". Read after the transaction
+ // commits, so a rolled-back write never reports a false failure.
+ let terminalRunToReport: typeof heartbeatRuns.$inferSelect | null = null;
await input.db.transaction(async (tx) => {
await tx.execute(
sql`select set_config('statement_timeout', '15000', true), set_config('lock_timeout', '1000', true)`,
@@ -8364,7 +8369,12 @@ async function executePaperclipNativeSessionWithinScope(
.returning({ runId: nativeRunFinalizations.runId })
.then((rows) => rows[0] ?? null);
if (!updated) throw new Error("native_session_lease_lost");
- await tx
+ const [runBeforeWrite] = await tx
+ .select({ status: heartbeatRuns.status })
+ .from(heartbeatRuns)
+ .where(eq(heartbeatRuns.id, input.execution.binding.runId))
+ .for("update");
+ const [updatedRun] = await tx
.update(heartbeatRuns)
.set({
// An authentication timeout does not prove the retained runner or
@@ -8384,7 +8394,15 @@ async function executePaperclipNativeSessionWithinScope(
: sourceFailureCode,
updatedAt: now,
})
- .where(eq(heartbeatRuns.id, input.execution.binding.runId));
+ .where(eq(heartbeatRuns.id, input.execution.binding.runId))
+ .returning();
+ if (
+ updatedRun &&
+ runBeforeWrite &&
+ updatedRun.status !== runBeforeWrite.status
+ ) {
+ terminalRunToReport = updatedRun;
+ }
const stillOwnsTask =
failureTask?.assigneeAgentId === input.execution.binding.agentId &&
["in_progress", "in_review"].includes(failureTask.status) &&
@@ -8470,6 +8488,7 @@ async function executePaperclipNativeSessionWithinScope(
recoveryProjection.supersedeOnIdentityChange,
});
});
+ if (terminalRunToReport) void reportRunFailure(input.db, terminalRunToReport);
await boundedExecutionCleanup(async () => {
await stoppedLeaseRenewal;
await attemptFailureStep(() =>
diff --git a/server/src/services/run-failure-report.ts b/server/src/services/run-failure-report.ts
new file mode 100644
index 0000000000..98aa919311
--- /dev/null
+++ b/server/src/services/run-failure-report.ts
@@ -0,0 +1,118 @@
+import { eq } from "drizzle-orm";
+import { agents, heartbeatRuns, type Db } from "@paperclipai/db";
+import { captureRunFailure, type RunFailureStatus } from "../sentry.js";
+import { redactCurrentUserText } from "../log-redaction.js";
+import { redactSensitiveText } from "../redaction.js";
+import { logger } from "../middleware/logger.js";
+
+type HeartbeatRun = typeof heartbeatRuns.$inferSelect;
+
+const UNKNOWN_ADAPTER = "unknown";
+
+/** Sentry rejects an oversized event with HTTP 413. Bound the error message. */
+const MAX_ERROR_MESSAGE_LENGTH = 4096;
+/** The error code is a short label. Bound it well under the message limit. */
+const MAX_ERROR_CODE_LENGTH = 200;
+
+/**
+ * Every report that `reportRunFailure` started and has not yet settled.
+ * Shutdown must wait for this set to drain — see `waitForPendingRunFailureReports`.
+ */
+const pendingRunFailureReports = new Set<Promise<void>>();
+
+/** Bounds the shutdown wait, so one stuck report cannot hang the process exit. */
+const PENDING_REPORT_DRAIN_TIMEOUT_MS = 5_000;
+
+/**
+ * Remove a credential and the current user's home path from adapter-supplied
+ * text, then cut the result to `maxLength`. Run the length cut after the
+ * redaction, so a credential cannot survive at a cut boundary.
+ */
+function sanitizeAdapterText(input: string, maxLength: number): string {
+ return redactSensitiveText(redactCurrentUserText(input)).slice(0, maxLength);
+}
+
+function isRunFailureStatus(status: string): status is RunFailureStatus {
+ return status === "failed" || status === "timed_out";
+}
+
+function readTaskId(run: HeartbeatRun): string | null {
+ if (run.nativeIssueId) return run.nativeIssueId;
+ const contextIssueId = run.contextSnapshot?.issueId;
+ return typeof contextIssueId === "string" && contextIssueId.length > 0 ? contextIssueId : null;
+}
+
+/**
+ * Report a terminal run failure to Sentry. Returns at once for any status
+ * other than `failed` and `timed_out`. Never throws — a Sentry failure or a
+ * database read failure must not change the caller's control flow.
+ *
+ * Call this beside the caller's own terminal-status write, with
+ * `void reportRunFailure(db, run)`. Do not await it — a Sentry read must
+ * not delay the caller's own required lifecycle work. The function tracks
+ * its own in-flight promise, so a caller that does not await it still lets
+ * shutdown find and wait for the report — see `waitForPendingRunFailureReports`.
+ */
+export function reportRunFailure(db: Db, run: HeartbeatRun): Promise<void> {
+ if (!isRunFailureStatus(run.status)) return Promise.resolve();
+ const runStatus = run.status;
+ const report = captureTerminalRunFailure(db, run, runStatus);
+ pendingRunFailureReports.add(report);
+ void report.finally(() => pendingRunFailureReports.delete(report));
+ return report;
+}
+
+async function captureTerminalRunFailure(
+ db: Db,
+ run: HeartbeatRun,
+ runStatus: RunFailureStatus,
+): Promise<void> {
+ try {
+ const agent = await db
+ .select({ adapterType: agents.adapterType })
+ .from(agents)
+ .where(eq(agents.id, run.agentId))
+ .then((rows) => rows[0] ?? null);
+
+ const taskId = readTaskId(run);
+ if (!taskId) {
+ logger.warn({ runId: run.id }, "run failure report has no task id, skipping Sentry report");
+ return;
+ }
+
+ captureRunFailure({
+ taskId,
+ runId: run.id,
+ errorMessage: sanitizeAdapterText(run.error ?? "", MAX_ERROR_MESSAGE_LENGTH),
+ errorCode:
+ run.errorCode === null
+ ? null
+ : sanitizeAdapterText(run.errorCode, MAX_ERROR_CODE_LENGTH),
+ agentAdapter: agent?.adapterType ?? UNKNOWN_ADAPTER,
+ runStatus,
+ });
+ } catch (err) {
+ logger.warn({ err, runId: run.id }, "failed to report run failure to Sentry");
+ }
+}
+
+/**
+ * Wait for every run-failure report that is still in flight, up to
+ * `timeoutMs`. Call this during server shutdown, before the database pool
+ * ends and before Sentry flushes — `reportRunFailure` reads the database and
+ * then calls Sentry, so a report started just before shutdown can otherwise
+ * lose its database read, its Sentry call, or both. Never throws.
+ */
+export async function waitForPendingRunFailureReports(
+ timeoutMs = PENDING_REPORT_DRAIN_TIMEOUT_MS,
+): Promise<void> {
+ if (pendingRunFailureReports.size === 0) return;
+ const drained = Promise.allSettled(Array.from(pendingRunFailureReports));
+ await Promise.race([
+ drained,
+ new Promise<void>((resolve) => {
+ const timer = setTimeout(resolve, timeoutMs);
+ timer.unref?.();
+ }),
+ ]);
+}
diff --git a/server/src/shutdown.test.ts b/server/src/shutdown.test.ts
index 4a4c13bf12..c9d118a809 100644
--- a/server/src/shutdown.test.ts
+++ b/server/src/shutdown.test.ts
@@ -169,6 +169,73 @@ describe("finalizeServerShutdown", () => {
);
});
+ it("waits for pending run-failure reports before the database stop and the Sentry flush", async () => {
+ const order: string[] = [];
+ const release = deferred();
+ const drainPendingRunFailureReports = vi.fn(async () => {
+ order.push("runFailureReports:start");
+ await release.promise;
+ order.push("runFailureReports:settled");
+ });
+ const closeDatabase = vi.fn(async () => {
+ order.push("database:close");
+ });
+ const shutdownSentry = vi.fn(async () => {
+ order.push("sentry:flush");
+ });
+
+ const finalize = finalizeServerShutdown({
+ signal: "SIGTERM",
+ shutdownAppServices: vi.fn(async () => undefined),
+ drainPendingRunFailureReports,
+ closeDatabase,
+ stopEmbeddedPostgres: null,
+ shutdownInstrumentation: vi.fn(async () => undefined),
+ shutdownSentry,
+ log: stubLogger(),
+ });
+
+ await vi.waitFor(() => expect(drainPendingRunFailureReports).toHaveBeenCalledOnce());
+ expect(closeDatabase).not.toHaveBeenCalled();
+ expect(shutdownSentry).not.toHaveBeenCalled();
+
+ release.resolve();
+ await finalize;
+
+ expect(order).toEqual([
+ "runFailureReports:start",
+ "runFailureReports:settled",
+ "database:close",
+ "sentry:flush",
+ ]);
+ });
+
+ it("logs a failed run-failure report drain and still stops the database and exits", async () => {
+ const drainError = new Error("drain failed");
+ const drainPendingRunFailureReports = vi.fn(async () => {
+ throw drainError;
+ });
+ const closeDatabase = vi.fn(async () => undefined);
+ const log = stubLogger();
+
+ await finalizeServerShutdown({
+ signal: "SIGTERM",
+ shutdownAppServices: vi.fn(async () => undefined),
+ drainPendingRunFailureReports,
+ closeDatabase,
+ stopEmbeddedPostgres: null,
+ shutdownInstrumentation: vi.fn(async () => undefined),
+ shutdownSentry: vi.fn(async () => undefined),
+ log,
+ });
+
+ expect(closeDatabase).toHaveBeenCalledOnce();
+ expect(log.error).toHaveBeenCalledWith(
+ expect.objectContaining({ err: drainError, signal: "SIGTERM" }),
+ "run-failure report drain failed",
+ );
+ });
+
it("skips the database stop when no embedded PostgreSQL runs in this process", async () => {
const shutdownAppServices = vi.fn(async () => undefined);
const shutdownInstrumentation = vi.fn(async () => undefined);
diff --git a/server/src/shutdown.ts b/server/src/shutdown.ts
index a76501b9f3..cda7499392 100644
--- a/server/src/shutdown.ts
+++ b/server/src/shutdown.ts
@@ -111,6 +111,13 @@ export async function finalizeServerShutdown(input: {
* runs against a half-dismantled service or an ended pool.
*/
closeHttpListener?: (() => Promise<unknown>) | null;
+ /**
+ * Waits for every run-failure Sentry report still in flight. Runs after the
+ * application services and before the database pool ends, so a report that
+ * started just before shutdown still gets its database read and reaches
+ * Sentry before `shutdownSentry` flushes and closes the client.
+ */
+ drainPendingRunFailureReports?: (() => Promise<void>) | null;
/**
* Ends the server's PostgreSQL client pools. Runs after the application
* services (which still need the database) and before the embedded
@@ -144,6 +151,18 @@ export async function finalizeServerShutdown(input: {
input.log.error({ err, signal }, "Application service shutdown failed");
}
+ // Wait for every in-flight run-failure Sentry report before the database
+ // pool ends. `reportRunFailure` is fire-and-forget: without this wait, a
+ // report that started just before shutdown can lose its database read to
+ // the pool end below, or lose its Sentry call to the flush further down.
+ if (input.drainPendingRunFailureReports) {
+ try {
+ await input.drainPendingRunFailureReports();
+ } catch (err) {
+ input.log.error({ err, signal }, "run-failure report drain failed");
+ }
+ }
+
// End the client pools once nothing needs them any more. Without this the
// process exit leaves the pooled backends to PostgreSQL's own TCP keepalive
// reaping, and a restart loop can pile up enough of them to hit