mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 20:09:33 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The server records the state of each agent run. > - Terminal run failures need clear error tracking for operators. > - The server did not report terminal `failed` or `timed_out` transitions to Sentry. > - This pull request reports each genuine terminal failure transition with safe diagnostic data. > - The benefit is faster diagnosis without changing run control flow or exposing credentials. ## Linked Issues or Issue Description **What happened?** The server wrote terminal run failures but did not report them to Sentry. Operators could not see these failures in error tracking. **Expected behavior** The server should report each genuine transition to `failed` or `timed_out` to Sentry. **Steps to reproduce** 1. Run an agent task that reaches a terminal failure state. 2. Inspect the Sentry events for the server. 3. Observe that the terminal run failure has no matching Sentry event. **Paperclip version or commit** The change targets the current `master` branch. No public GitHub issue or pull request covers this change. ## What Changed - Add `captureRunFailure()` as a fail-open Sentry entry point. - Add `reportRunFailure()` to filter status, resolve the adapter, redact text, and report the failure. - Call `reportRunFailure()` beside each of the eight terminal status writers. - Report six diagnostic values: the instance host, task identifier, run identifier, error message, error code, and agent adapter. - Group events by error code and agent adapter while keeping the redacted message in the event. - Report only genuine transitions and avoid duplicate finalization events. - Keep Sentry failures outside run control flow. ## Verification - `pnpm vitest run server/src/services/__tests__/run-failure-report.test.ts server/src/__tests__/run-failure-sentry.test.ts server/src/__tests__/native-session-resumption.test.ts` - `pnpm vitest run server/src/services/execution-control-reconciliation.test.ts` - `pnpm --filter @paperclipai/server typecheck` - The full continuous-integration suite must run on this pull request. ## Risks - The report path can add diagnostic events when Sentry is configured. - The report path returns without action when Sentry is not configured. - Redaction runs before length limits and before the event leaves the process. - The change has no migration and no schema change. ## Model Used OpenAI Codex, GPT-5, tool use and code review support. The exact context window and reasoning configuration are not exposed by the runtime. ## 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>
119 lines
4.4 KiB
TypeScript
119 lines
4.4 KiB
TypeScript
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?.();
|
|
}),
|
|
]);
|
|
}
|