mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 09:39:53 +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
155 lines
6.3 KiB
TypeScript
155 lines
6.3 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { promises as fs } from "node:fs";
|
|
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
|
import type { AddressInfo } from "node:net";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import express from "express";
|
|
import request from "supertest";
|
|
import { eq } from "drizzle-orm";
|
|
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { companies, companySkillRepositorySnapshots as snapshots, createDb } from "@paperclipai/db";
|
|
import type { CompanySkillVersionFileInventoryEntry } from "@paperclipai/shared";
|
|
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
|
import { errorHandler } from "../middleware/error-handler.js";
|
|
import { skillPackageStore } from "../services/skill-package-store.js";
|
|
import { createS3StorageProvider } from "../storage/s3-provider.js";
|
|
import { createStorageService } from "../storage/service.js";
|
|
|
|
const captureExceptionMock = vi.hoisted(() => vi.fn());
|
|
vi.mock("../sentry.js", () => ({ captureException: captureExceptionMock }));
|
|
vi.mock("../telemetry.js", () => ({ getTelemetryClient: () => null }));
|
|
|
|
const SLOW_DOWN = `<?xml version="1.0" encoding="UTF-8"?>
|
|
<Error><Code>SlowDown</Code><Message>Please reduce your request rate.</Message><RequestId>req-503</RequestId></Error>`;
|
|
|
|
const objects = new Map<string, Buffer>();
|
|
const puts: Array<{ key: string; contentMd5: string | undefined }> = [];
|
|
let throttledPuts = 0;
|
|
|
|
function respond(req: IncomingMessage, res: ServerResponse, body: Buffer) {
|
|
const key = decodeURIComponent((req.url ?? "").split("?")[0]!.replace(/^\/bucket\//, ""));
|
|
if (req.method === "PUT") {
|
|
puts.push({ key, contentMd5: req.headers["content-md5"] as string | undefined });
|
|
if (throttledPuts > 0) {
|
|
throttledPuts--;
|
|
res.writeHead(503, { "content-type": "application/xml" });
|
|
res.end(SLOW_DOWN);
|
|
return;
|
|
}
|
|
objects.set(key, body);
|
|
res.writeHead(200, { etag: '"saved"' });
|
|
res.end();
|
|
return;
|
|
}
|
|
if (req.method === "GET" || req.method === "HEAD") {
|
|
const object = objects.get(key);
|
|
if (!object) {
|
|
res.writeHead(404, { "content-type": "application/xml" });
|
|
res.end("<Error><Code>NoSuchKey</Code></Error>");
|
|
return;
|
|
}
|
|
res.writeHead(200, { "content-length": object.length, etag: '"saved"' });
|
|
res.end(req.method === "GET" ? object : undefined);
|
|
return;
|
|
}
|
|
res.writeHead(204);
|
|
res.end();
|
|
}
|
|
|
|
const server = createServer((req, res) => {
|
|
const chunks: Buffer[] = [];
|
|
req.on("data", chunk => chunks.push(chunk as Buffer));
|
|
req.on("end", () => respond(req, res, Buffer.concat(chunks)));
|
|
});
|
|
|
|
const files: CompanySkillVersionFileInventoryEntry[] = [
|
|
{ path: "skills/one/SKILL.md", kind: "skill", content: "---\nname: one\ndescription: Test one\n---\nUse it.\n" },
|
|
];
|
|
|
|
const support = await getEmbeddedPostgresTestSupport();
|
|
describe.skipIf(!support.supported)("skill package uploads under storage request-rate limits", () => {
|
|
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
|
let db: ReturnType<typeof createDb>;
|
|
let home: string;
|
|
let storage: ReturnType<typeof createStorageService>;
|
|
const savedEnv = { ...process.env };
|
|
|
|
beforeAll(async () => {
|
|
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
|
|
const endpoint = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
|
process.env.AWS_ACCESS_KEY_ID = "fixture-access-key";
|
|
process.env.AWS_SECRET_ACCESS_KEY = "fixture-secret-key";
|
|
delete process.env.AWS_SESSION_TOKEN;
|
|
delete process.env.AWS_PROFILE;
|
|
home = await fs.mkdtemp(path.join(os.tmpdir(), "skill-package-throttle-"));
|
|
process.env.PAPERCLIP_HOME = home;
|
|
database = await startEmbeddedPostgresTestDatabase("skill-package-throttle-");
|
|
db = createDb(database.connectionString, { maxConnections: 2 });
|
|
storage = createStorageService(createS3StorageProvider({ bucket: "bucket", region: "us-east-1", endpoint, forcePathStyle: true }));
|
|
});
|
|
|
|
beforeEach(() => {
|
|
objects.clear();
|
|
puts.length = 0;
|
|
throttledPuts = 0;
|
|
captureExceptionMock.mockReset();
|
|
vi.spyOn(Math, "random").mockReturnValue(0);
|
|
});
|
|
afterEach(() => vi.restoreAllMocks());
|
|
|
|
afterAll(async () => {
|
|
process.env = savedEnv;
|
|
server.closeAllConnections();
|
|
await new Promise<void>(resolve => server.close(() => resolve()));
|
|
await db?.$client.end({ timeout: 1 });
|
|
await database?.cleanup();
|
|
if (home) await fs.rm(home, { recursive: true, force: true });
|
|
});
|
|
|
|
async function company() {
|
|
const id = randomUUID();
|
|
await db.insert(companies).values({ id, name: "Throttle test", issuePrefix: `T${id.slice(0, 6)}` });
|
|
return id;
|
|
}
|
|
|
|
it("resends the archive after a transient SlowDown and publishes the package", async () => {
|
|
const companyId = await company();
|
|
throttledPuts = 1;
|
|
|
|
const id = await skillPackageStore(db, storage).prepare(companyId, files);
|
|
|
|
const [row] = await db.select().from(snapshots).where(eq(snapshots.id, id));
|
|
expect(row!.storage?.archiveKey).toBeTruthy();
|
|
const archivePuts = puts.filter(put => put.key.endsWith("files.tar.gz"));
|
|
expect(archivePuts).toHaveLength(2);
|
|
expect(archivePuts.every(put => put.contentMd5)).toBe(true);
|
|
});
|
|
|
|
it("answers persistent throttling with 503 and lets the same caller retry at once", async () => {
|
|
const companyId = await company();
|
|
throttledPuts = Number.POSITIVE_INFINITY;
|
|
const store = skillPackageStore(db, storage);
|
|
const app = express();
|
|
app.post("/prepare", async (_req, res) => { res.json({ id: await store.prepare(companyId, files) }); });
|
|
app.use(errorHandler);
|
|
|
|
const throttled = await request(app).post("/prepare");
|
|
|
|
expect(throttled.status).toBe(503);
|
|
expect(throttled.headers["retry-after"]).toBe("30");
|
|
expect(throttled.body).toEqual({
|
|
error: "File storage is temporarily unavailable or is limiting requests. Try again in a moment.",
|
|
code: "storage_unavailable",
|
|
});
|
|
expect(captureExceptionMock).not.toHaveBeenCalled();
|
|
|
|
throttledPuts = 0;
|
|
const retried = await request(app).post("/prepare");
|
|
|
|
expect(retried.status).toBe(200);
|
|
const [row] = await db.select().from(snapshots).where(eq(snapshots.id, retried.body.id));
|
|
expect(row!.storage).not.toBeNull();
|
|
});
|
|
});
|