mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 05:47:10 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - First-agent setup saves the agent's skill packages to object storage (S3 on hosted installs) > - S3 can answer an upload with `503 SlowDown` when it limits the request rate > - The S3 provider retries a throttled upload, but when the retries run out the error reaches the HTTP error handler unclassified > - The person then sees "Internal server error", and the server reports a handler crash for a transient storage condition > - This pull request answers a storage-unavailable error with 503 and retry guidance, and makes the skill archive upload always use the retryable file-source path > - The benefit is that a throttle is retried, persistent throttling gives a clear retryable answer, and crash reports stay for real faults ## Linked Issues or Issue Description **What happened?** During first-agent setup, a skill package upload hit S3 request-rate throttling (`SlowDown`, HTTP 503). The person saw "Internal server error". The server logged `error.handler_crash` with `error_code=SlowDown`. A retry soon after got "This skill package is being saved. Retry after its upload settles." on a build before #22477. **Expected behavior** A transient throttle is retried. Persistent throttling answers with a retryable status and guidance. The same person can retry at once. **Steps to reproduce** 1. Use S3 storage and make the bucket answer `PUT` with `503 SlowDown` until the provider's retries run out. 2. Start first-agent setup, or call `skillPackageStore().prepare` for a new package. 3. The request fails with 500, and the error handler reports a crash. **Paperclip version or commit** `master` at `5f5ac154368`. **Deployment mode** Hosted (S3 storage). Self-hosted installs with S3-compatible storage behave the same way. Refs #22477 (failed upload claims expire at once, so an immediate retry no longer gets 409). Refs #22404 (throttle backoff for small uploads without a source file). ## What Changed - `error-handler.ts`: a recorded storage-unavailable error (throttling, 5xx, timeouts, network failures, as `isStorageUnavailableError` already defines) answers `503` with `Retry-After: 30` and code `storage_unavailable`. The response text is fixed. The handler logs the fixed-shape storage diagnostics (operation, error code, HTTP status, request id) as a warning, not as a crash. Storage credential rejections still report as server faults. - `error-handler.ts`: the client-abort shortcut (`aborted` with `ECONNRESET`, answered as 499) no longer catches a recorded storage failure. A storage read that the backend reset now answers 503 while the caller is still connected. - `storage-unavailable.ts`: add the response text and `recordedStorageFailureDiagnostics`. - `skill-package-store.ts`: pass the staged archive as `sourceFile`. The S3 provider then re-reads the file on each attempt, so it can resend the archive after a throttle even when the shared upload buffer is full. The upload also gets a Content-MD5 check. - The claim behavior from #22477 does not change: a failed attempt's claim expires at once, its exact keys go to the deletion outbox, and a retry uses fresh keys. - New test `storage-unavailable-error-handler.test.ts`: a storage connection reset answers 503, and a storage credential rejection still reports as a server fault. - New test `skill-package-storage-throttle.test.ts` (real PostgreSQL, the real S3 provider, and a local S3 stand-in): a transient `SlowDown` is resent and the package publishes; persistent throttling answers 503 with no crash report, and an immediate retry by the same caller succeeds. ## Verification - `pnpm exec vitest run server/src/__tests__/skill-package-storage-throttle.test.ts`: 2 passed. Both tests fail on `master` (no Content-MD5 on the archive upload; 500 instead of 503). - Related suites (skill package store and upload, error handler, sandbox outage handler, storage-unavailable, S3 throttle and backoff): 17 files, 175 tests passed. - `pnpm --filter @paperclipai/server typecheck` passes. ## Risks - Other routes that fail on a storage outage now answer 503 instead of 500 and do not send a crash report. This is the intent, but storage outages are now visible only as warning logs, not as crash reports. - The archive upload now hashes the archive for Content-MD5 before it sends it. Skill archives are small, so the cost is low. - This change does not explain why one company's prefix hit the S3 request-rate limit. That needs a separate operations check. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with shell, file edit, and code execution tools. ## 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 - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge
406 lines
15 KiB
TypeScript
406 lines
15 KiB
TypeScript
import { AgentLifecycleConflict } from "../modules/agent-lifecycle/index.js";
|
|
import type { Request, Response, NextFunction } from "express";
|
|
import type { Db } from "@paperclipai/db";
|
|
import { ZodError } from "zod";
|
|
import { HttpError } from "../errors.js";
|
|
import { trackErrorHandlerCrash } from "@paperclipai/shared/telemetry";
|
|
import { getTelemetryClient } from "../telemetry.js";
|
|
import { captureException } from "../sentry.js";
|
|
import { COMPANY_IMPORT_API_PATH } from "../routes/company-import-paths.js";
|
|
import { logger } from "./logger.js";
|
|
import {
|
|
isSecretSensitiveHttpRequest,
|
|
secretSensitiveRouteFamily,
|
|
} from "./http-log-policy.js";
|
|
import { SecretSensitiveRequestError } from "./secret-sensitive-request-error.js";
|
|
import {
|
|
collectSensitiveStringValues,
|
|
redactSensitiveValueOccurrences,
|
|
} from "./redact-sensitive.js";
|
|
import { recordResponsibleUserDenialOnActiveRun } from "../services/responsible-user-denial-run-outcomes.js";
|
|
import { isObjectJournalBusyError } from "../services/object-byte-journal.js";
|
|
import { isExpectedMcpConnectionFailure } from "../services/mcp-connection-failure.js";
|
|
import { isOpenRouterCatalogUnavailable } from "../services/openrouter-models.js";
|
|
import { ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE, readTransientSandboxCreationRefusal } from "../services/environment-provider-unavailable-error.js";
|
|
import { isEndedDbPoolError } from "../database-retry.js";
|
|
import { ToolGatewayHttpError } from "../services/tool-gateway.js";
|
|
import { isStorageCredentialRejection, isStorageUnavailableError, recordedStorageFailureDiagnostics, STORAGE_TEMPORARILY_UNAVAILABLE_MESSAGE, STORAGE_UNAVAILABLE_CODE } from "../storage/storage-unavailable.js";
|
|
|
|
export interface ErrorContext {
|
|
error: {
|
|
message: string;
|
|
stack?: string;
|
|
name?: string;
|
|
details?: unknown;
|
|
raw?: unknown;
|
|
};
|
|
method: string;
|
|
url: string;
|
|
reqBody?: unknown;
|
|
reqParams?: unknown;
|
|
reqQuery?: unknown;
|
|
}
|
|
|
|
function isRedactedSkillPolicyDenial(details: Record<string, unknown> | null) {
|
|
return details?.code === "skill_policy_denied";
|
|
}
|
|
|
|
function readZodIssues(err: unknown): unknown[] | null {
|
|
if (err instanceof ZodError) return err.issues;
|
|
if (
|
|
!err ||
|
|
typeof err !== "object" ||
|
|
(err as { name?: unknown }).name !== "ZodError"
|
|
)
|
|
return null;
|
|
const issues = (err as { issues?: unknown }).issues;
|
|
return Array.isArray(issues) ? issues : null;
|
|
}
|
|
|
|
function attachErrorContext(
|
|
req: Request,
|
|
res: Response,
|
|
payload: ErrorContext["error"],
|
|
rawError?: Error,
|
|
) {
|
|
(res as any).__errorContext = {
|
|
error: payload,
|
|
method: req.method,
|
|
url: req.originalUrl,
|
|
reqBody: req.body,
|
|
reqParams: req.params,
|
|
reqQuery: req.query,
|
|
} satisfies ErrorContext;
|
|
if (rawError) {
|
|
(res as any).err = rawError;
|
|
}
|
|
}
|
|
|
|
function sanitizeSecretSensitiveError(req: Request, error: Error): Error {
|
|
const routeFamily = secretSensitiveRouteFamily(req.method, req.originalUrl);
|
|
if (!routeFamily) return error;
|
|
return new SecretSensitiveRequestError(error, {
|
|
routeFamily,
|
|
method: req.method,
|
|
routePath: (req.route as { path?: unknown } | undefined)?.path,
|
|
});
|
|
}
|
|
|
|
function sanitizeSecretSensitiveResponse(
|
|
req: Request,
|
|
value: unknown,
|
|
): unknown {
|
|
if (!isSecretSensitiveHttpRequest(req.method, req.originalUrl)) return value;
|
|
return redactSensitiveValueOccurrences(
|
|
value,
|
|
collectSensitiveStringValues(req.body),
|
|
);
|
|
}
|
|
|
|
/** Report a server-side crash to every error sink. */
|
|
function reportCrash(error: Error, req: Request, reportToSentry = true): void {
|
|
const tc = getTelemetryClient();
|
|
if (tc) trackErrorHandlerCrash(tc, { errorCode: error.name });
|
|
if (reportToSentry) {
|
|
if (req.actor?.type === "agent" && req.actor.runId && req.actor.companyId && req.actor.agentId) {
|
|
captureException(error, { runId: req.actor.runId, companyId: req.actor.companyId, agentId: req.actor.agentId });
|
|
} else captureException(error);
|
|
}
|
|
}
|
|
|
|
/** Set by the orderly shutdown just before it ends the database pools. */
|
|
function isDatabaseClosing(req: Request): boolean {
|
|
const locals = req.app?.locals as { paperclipDatabaseClosing?: boolean } | undefined;
|
|
return locals?.paperclipDatabaseClosing === true;
|
|
}
|
|
|
|
function getPaperclipDb(req: Request): Db | null {
|
|
const locals = req.app?.locals as { paperclipDb?: Db; db?: Db } | undefined;
|
|
return locals?.paperclipDb ?? locals?.db ?? null;
|
|
}
|
|
|
|
function recordResponsibleUserDenialFromHttpError(
|
|
req: Request,
|
|
details: Record<string, unknown> | null,
|
|
) {
|
|
if (req.actor?.type !== "agent") return;
|
|
const db = getPaperclipDb(req);
|
|
if (!db) return;
|
|
|
|
void recordResponsibleUserDenialOnActiveRun(db, {
|
|
runId: req.actor.runId ?? null,
|
|
agentId: req.actor.agentId ?? null,
|
|
companyId: req.actor.companyId ?? null,
|
|
code: details?.code,
|
|
}).catch((recordErr) => {
|
|
logger.warn(
|
|
{
|
|
err: recordErr,
|
|
runId: req.actor?.runId ?? null,
|
|
agentId:
|
|
req.actor?.type === "agent" ? (req.actor.agentId ?? null) : null,
|
|
},
|
|
"failed to record responsible-user denial on heartbeat run",
|
|
);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* The tool gateway rejects requests with its own error type. A route that lets
|
|
* one reach this handler (such as approving a tool review from a task card)
|
|
* would otherwise turn an expected rejection, for example a 409 asking for a
|
|
* new review, into a 500 crash report. Gateway server failures stay on the
|
|
* crash path so their provider text is not exposed.
|
|
*/
|
|
function clientToolGatewayErrorAsHttpError(err: unknown): unknown {
|
|
if (!(err instanceof ToolGatewayHttpError) || err.status < 400 || err.status >= 500) return err;
|
|
const mapped = new HttpError(err.status, err.message, { ...err.details, code: err.reasonCode });
|
|
mapped.stack = err.stack;
|
|
return mapped;
|
|
}
|
|
|
|
export function errorHandler(
|
|
thrown: unknown,
|
|
req: Request,
|
|
res: Response,
|
|
_next: NextFunction,
|
|
) {
|
|
const err = clientToolGatewayErrorAsHttpError(thrown);
|
|
if (err instanceof AgentLifecycleConflict) { res.status(409).json({ error: err.message }); return; }
|
|
if (err instanceof HttpError) {
|
|
const details =
|
|
err.details &&
|
|
typeof err.details === "object" &&
|
|
!Array.isArray(err.details)
|
|
? (err.details as Record<string, unknown>)
|
|
: null;
|
|
const redactedSkillPolicyDenial = isRedactedSkillPolicyDenial(details);
|
|
const workspaceRepairPreconditionFailure =
|
|
details?.code === "workspace_repair_precondition_failed";
|
|
// Its code and remediation are already top-level; repeating them only lengthens agent context.
|
|
const boardAccessDenial = details?.code === "board_access_required";
|
|
const structuredConnectionError = new Set([
|
|
"user_authorization_required",
|
|
"organization_authorization_required",
|
|
"grant_audience_denied",
|
|
"grant_revoked",
|
|
"needs_reauthorization",
|
|
"installation_required",
|
|
"connection_not_installed",
|
|
"subject_not_permitted",
|
|
"standing_delegation_required",
|
|
"grant_owner_membership_inactive",
|
|
]).has(typeof details?.code === "string" ? details.code : "");
|
|
const responseDetailsValue = sanitizeSecretSensitiveResponse(
|
|
req,
|
|
err.details,
|
|
);
|
|
const responseDetails =
|
|
responseDetailsValue &&
|
|
typeof responseDetailsValue === "object" &&
|
|
!Array.isArray(responseDetailsValue)
|
|
? (responseDetailsValue as Record<string, unknown>)
|
|
: null;
|
|
recordResponsibleUserDenialFromHttpError(req, details);
|
|
if (err.status >= 500) {
|
|
const reportableError = sanitizeSecretSensitiveError(req, err);
|
|
attachErrorContext(
|
|
req,
|
|
res,
|
|
isSecretSensitiveHttpRequest(req.method, req.originalUrl)
|
|
? { message: reportableError.message, name: reportableError.name }
|
|
: {
|
|
message: err.message,
|
|
stack: err.stack,
|
|
name: err.name,
|
|
details: err.details,
|
|
},
|
|
reportableError,
|
|
);
|
|
// An unreachable public provider catalog still answers 503 with its
|
|
// retry guidance, but it is the provider's outage, not a server fault.
|
|
reportCrash(reportableError, req, !isExpectedMcpConnectionFailure(err) && !isOpenRouterCatalogUnavailable(err));
|
|
}
|
|
const secretSensitiveServerError =
|
|
err.status >= 500 &&
|
|
isSecretSensitiveHttpRequest(req.method, req.originalUrl);
|
|
res.status(err.status).json(
|
|
secretSensitiveServerError
|
|
? { error: "Internal server error" }
|
|
: {
|
|
error: sanitizeSecretSensitiveResponse(req, err.message),
|
|
...(typeof responseDetails?.code === "string"
|
|
? { code: responseDetails.code }
|
|
: {}),
|
|
...(redactedSkillPolicyDenial &&
|
|
typeof responseDetails?.reason === "string"
|
|
? { reason: responseDetails.reason }
|
|
: {}),
|
|
...(workspaceRepairPreconditionFailure &&
|
|
typeof responseDetails?.reason === "string"
|
|
? { reason: responseDetails.reason }
|
|
: {}),
|
|
...(workspaceRepairPreconditionFailure &&
|
|
typeof responseDetails?.repairPhase === "string"
|
|
? { repairPhase: responseDetails.repairPhase }
|
|
: {}),
|
|
...(typeof responseDetails?.remediation === "string" ||
|
|
(structuredConnectionError &&
|
|
responseDetails?.remediation &&
|
|
typeof responseDetails.remediation === "object")
|
|
? { remediation: responseDetails.remediation }
|
|
: {}),
|
|
...(structuredConnectionError && responseDetails?.connection
|
|
? { connection: responseDetails.connection }
|
|
: {}),
|
|
...(structuredConnectionError && responseDetails?.subject
|
|
? { subject: responseDetails.subject }
|
|
: {}),
|
|
...(structuredConnectionError &&
|
|
typeof responseDetails?.grantId === "string"
|
|
? { grantId: responseDetails.grantId }
|
|
: {}),
|
|
...(!redactedSkillPolicyDenial &&
|
|
!workspaceRepairPreconditionFailure &&
|
|
!boardAccessDenial &&
|
|
responseDetailsValue
|
|
? { details: responseDetailsValue }
|
|
: {}),
|
|
},
|
|
);
|
|
return;
|
|
}
|
|
|
|
const zodIssues = readZodIssues(err);
|
|
if (zodIssues) {
|
|
res.status(400).json({
|
|
error: "Validation error",
|
|
details: sanitizeSecretSensitiveResponse(req, zodIssues),
|
|
});
|
|
return;
|
|
}
|
|
|
|
// Only body-parser's malformed-JSON errors are client input failures.
|
|
// Parser messages can quote request bytes; return a constant response and
|
|
// keep the raw error out of crash reporting and HTTP error context.
|
|
if (
|
|
err instanceof SyntaxError &&
|
|
"status" in err && err.status === 400 &&
|
|
"type" in err && err.type === "entity.parse.failed"
|
|
) {
|
|
res.status(400).json({ error: "Invalid JSON body" });
|
|
return;
|
|
}
|
|
|
|
const rootError = err instanceof Error ? err : new Error(String(err));
|
|
|
|
// The client tore down the connection mid-request (closed tab, dropped
|
|
// mobile network, cancelled upload): Node surfaces it as `Error: aborted`
|
|
// with ECONNRESET. There is no server fault to report and nobody left to
|
|
// answer, so skip the error sinks and just close out the response.
|
|
if (
|
|
rootError.message === "aborted" &&
|
|
(rootError as NodeJS.ErrnoException).code === "ECONNRESET" &&
|
|
!isStorageUnavailableError(rootError)
|
|
) {
|
|
if (!res.headersSent) res.status(499);
|
|
res.end();
|
|
return;
|
|
}
|
|
|
|
// A route that cancels its work when the response closes (for example a
|
|
// storage read) rejects with AbortError after the client has gone. That
|
|
// rejection is the cancellation, not a server fault. An AbortError while
|
|
// the client is still connected is still reported.
|
|
if (rootError.name === "AbortError" && res.destroyed && !res.writableFinished) {
|
|
if (!res.headersSent) res.status(499);
|
|
res.end();
|
|
return;
|
|
}
|
|
|
|
// Shutdown drains the HTTP listener before it ends the pool, but a handler
|
|
// whose client already disconnected (or whose socket the drain timeout
|
|
// closed) keeps running. Its next query then fails with CONNECTION_ENDED
|
|
// against the pool this process deliberately ended. That is shutdown, not a
|
|
// server fault, so skip the error sinks. Any other error during shutdown is
|
|
// still reported.
|
|
if (isDatabaseClosing(req) && isEndedDbPoolError(rootError)) {
|
|
if (!res.headersSent) {
|
|
res.status(503).json({ error: "Server is shutting down" });
|
|
} else {
|
|
res.end();
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (isObjectJournalBusyError(rootError)) {
|
|
if (!res.headersSent) {
|
|
res.set("Retry-After", "2");
|
|
res.status(503).json({ error: rootError.message, code: rootError.code });
|
|
} else {
|
|
res.end();
|
|
}
|
|
return;
|
|
}
|
|
|
|
// A sandbox provider outage during a sandbox creation that this request
|
|
// started is not a server fault. The answer is fixed text: provider text and
|
|
// provisional sandbox names stay out, and cleanup stays with its own record.
|
|
const providerRefusal = readTransientSandboxCreationRefusal(rootError);
|
|
if (providerRefusal) {
|
|
if (!res.headersSent) {
|
|
res.set("Retry-After", "30");
|
|
res.status(503).json({ error: providerRefusal.message, code: ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE });
|
|
} else {
|
|
res.end();
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (isStorageUnavailableError(rootError) && !isStorageCredentialRejection(rootError)) {
|
|
logger.warn({ method: req.method, route: req.route?.path, storageFailure: recordedStorageFailureDiagnostics(rootError) },
|
|
"File storage was unavailable for a request");
|
|
if (!res.headersSent) {
|
|
res.set("Retry-After", "30");
|
|
res.status(503).json({ error: STORAGE_TEMPORARILY_UNAVAILABLE_MESSAGE, code: STORAGE_UNAVAILABLE_CODE });
|
|
} else {
|
|
res.end();
|
|
}
|
|
return;
|
|
}
|
|
|
|
const reportableError = sanitizeSecretSensitiveError(req, rootError);
|
|
attachErrorContext(
|
|
req,
|
|
res,
|
|
isSecretSensitiveHttpRequest(req.method, req.originalUrl)
|
|
? { message: reportableError.message, name: reportableError.name }
|
|
: err instanceof Error
|
|
? { message: err.message, stack: err.stack, name: err.name }
|
|
: {
|
|
message: String(err),
|
|
raw: err,
|
|
stack: rootError.stack,
|
|
name: rootError.name,
|
|
},
|
|
reportableError,
|
|
);
|
|
|
|
reportCrash(reportableError, req);
|
|
|
|
res.status(500).json({
|
|
error: "Internal server error",
|
|
...(shouldExposeTrustedCloudTenantImportError(req)
|
|
? { message: rootError.message }
|
|
: {}),
|
|
});
|
|
}
|
|
|
|
function shouldExposeTrustedCloudTenantImportError(req: Request) {
|
|
return (
|
|
req.actor?.source === "cloud_tenant" &&
|
|
req.method === "POST" &&
|
|
req.originalUrl.split("?")[0] === COMPANY_IMPORT_API_PATH
|
|
);
|
|
}
|