mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 05:47:10 +01:00
fix(customer-success): fit oversized inspection list pages instead of failing (#22625)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Paperclip Cloud can do audited, read-only customer-success inspection of a stack through `/api/customer-success/v1/read` > - The tenant rejects any inspection response over 2 MB with 422 > - Run rows are large, so a 25-row `runs` page is often over 2 MB on a busy stack > - Cloud reports the 422 to the agent as a refused read, so the agent cannot tell that a smaller page works > - This pull request makes an oversized list page return the largest prefix of rows that fits, with `nextOffset` at the first omitted row > - The benefit is that list reads succeed at any page size, and normal pagination gets the rest ## Linked Issues or Issue Description **What happened?** A customer-success agent listed `runs` with `limit` 25 on 9 stacks. Each read failed as refused. The same reads with `limit` 3 and `limit` 1 succeeded. A `tasks` list with `limit` 25 on the same stack succeeded. **Expected behavior** A list read returns rows and a `nextOffset`. The size limit must not fail the whole page when fewer rows fit. **Steps to reproduce** 1. Seed a company with 25 tasks that each have a 200 KB description. 2. Send a valid inspection permit for `list tasks` with `limit` 25. 3. The response is 422 "Inspection response is too large". ## What Changed - `server/src/routes/customer-success.ts`: add `fitInspectionResponse`. When a list response is over 2 MB, it does a binary search for the largest row prefix that fits. It sets `nextOffset` to `offset + count`. A single row that cannot fit still gives 422. - `server/src/__tests__/customer-success.test.ts`: add a route test with 25 large tasks and a unit test for the helper. ## Verification - `npx vitest run src/__tests__/customer-success.test.ts src/__tests__/customer-success-cloud.test.ts`: 12 passed, 1 skipped. - Red/green: with the old size check, the new route test fails with `expected 422 to deeply equal 200`. With the fix it passes. - On a staging stack, `runs` with `limit` 25 failed and `limit` 3 succeeded, which matches the cause. ## Risks - Low. Only responses that already failed with 422 change. A page can now hold fewer rows than `limit`. Callers already follow `nextOffset`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code, with tool use. ## 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
30881e6aa9
commit
78b10a43ce
2 files changed
+138
-3
No files matched your search
@@ -22,7 +22,11 @@ import {
|
||||
readCustomerSuccessResource,
|
||||
inspectionReaders,
|
||||
} from "../services/customer-success-inspection.js";
|
||||
import { customerSuccessRoutes, verifyInspectionPermit } from "../routes/customer-success.js";
|
||||
import {
|
||||
customerSuccessRoutes,
|
||||
fitInspectionResponse,
|
||||
verifyInspectionPermit,
|
||||
} from "../routes/customer-success.js";
|
||||
import { agentIdentityService } from "../services/agent-identity.js";
|
||||
import { createLocalAgentJwt, verifyLocalAgentJwt } from "../agent-auth-jwt.js";
|
||||
import { errorHandler } from "../middleware/error-handler.js";
|
||||
@@ -460,6 +464,106 @@ describe("customer-success read authority", () => {
|
||||
),
|
||||
).toThrow();
|
||||
});
|
||||
it("fits an oversized list page to the response limit and points nextOffset at the first omitted row", async () => {
|
||||
vi.stubEnv("PAPERCLIP_CUSTOMER_SUCCESS_INSPECTION_ENABLED", "true");
|
||||
vi.stubEnv("PAPERCLIP_CLOUD_STACK_ID", "fixture-stack");
|
||||
vi.stubEnv("PAPERCLIP_CUSTOMER_SUCCESS_CLOUD_ORIGIN", "https://cloud.example.test");
|
||||
const keys = generateKeyPairSync("ed25519");
|
||||
vi.stubEnv(
|
||||
"PAPERCLIP_CUSTOMER_SUCCESS_INSPECTION_JWKS",
|
||||
JSON.stringify({ keys: [{ ...keys.publicKey.export({ format: "jwk" }), kid: "cloud" }] }),
|
||||
);
|
||||
const [bulky] = await db
|
||||
.insert(schema.companies)
|
||||
.values({ name: "Bulky", issuePrefix: "BLK" })
|
||||
.returning();
|
||||
await db.insert(schema.issues).values(
|
||||
Array.from({ length: 40 }, (_, index) => ({
|
||||
companyId: bulky.id,
|
||||
title: `Large task ${index}`,
|
||||
description: "x".repeat(200 * 1024),
|
||||
})),
|
||||
);
|
||||
function permitFor(query: InspectionQuery) {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const claims: InspectionPermit = {
|
||||
v: 1,
|
||||
iss: "paperclip-cloud",
|
||||
aud: INSPECTION_AUDIENCE,
|
||||
sub: "fixture-stack",
|
||||
iat: now,
|
||||
exp: now + 60,
|
||||
jti: randomUUID(),
|
||||
bindingVersion: 1,
|
||||
grantId: randomUUID(),
|
||||
requestId: randomUUID(),
|
||||
agentId,
|
||||
keyId: "sha256:fixture",
|
||||
runId,
|
||||
query,
|
||||
};
|
||||
const header = Buffer.from(
|
||||
JSON.stringify({ alg: "EdDSA", typ: INSPECTION_PERMIT_TYPE, kid: "cloud" }),
|
||||
).toString("base64url");
|
||||
const input = `${header}.${Buffer.from(JSON.stringify(claims)).toString("base64url")}`;
|
||||
return `${input}.${sign(null, Buffer.from(input), keys.privateKey).toString("base64url")}`;
|
||||
}
|
||||
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({ consumed: true })));
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use("/api/customer-success/v1", customerSuccessRoutes(db, storage));
|
||||
app.use(errorHandler);
|
||||
async function page(offset: number) {
|
||||
const query: InspectionQuery = {
|
||||
operation: "list",
|
||||
resource: "tasks",
|
||||
companyId: bulky.id,
|
||||
limit: 25,
|
||||
offset,
|
||||
};
|
||||
return request(app)
|
||||
.post("/api/customer-success/v1/read")
|
||||
.set(INSPECTION_HEADER, permitFor(query))
|
||||
.send(query);
|
||||
}
|
||||
const ordered = (
|
||||
await db
|
||||
.select({ id: schema.issues.id })
|
||||
.from(schema.issues)
|
||||
.where(eq(schema.issues.companyId, bulky.id))
|
||||
.orderBy(schema.issues.id)
|
||||
).map((row) => row.id);
|
||||
|
||||
const first = await page(5);
|
||||
expect(first.status).toEqual(200);
|
||||
expect(Buffer.byteLength(first.text)).toBeLessThanOrEqual(2 * 1024 * 1024);
|
||||
const count = first.body.items.length;
|
||||
expect(count).toBeGreaterThan(0);
|
||||
expect(count).toBeLessThan(20);
|
||||
expect(first.body.nextOffset).toEqual(5 + count);
|
||||
expect(first.body.items.map((item: { id: string }) => item.id)).toEqual(ordered.slice(5, 5 + count));
|
||||
|
||||
const second = await page(first.body.nextOffset);
|
||||
expect(second.status).toEqual(200);
|
||||
const next = second.body.items.map((item: { id: string }) => item.id);
|
||||
expect(next).toEqual(ordered.slice(5 + count, 5 + count + next.length));
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("returns null only when a single item cannot fit, and fits only list pages", () => {
|
||||
const files = { kind: "files", truncated: true, items: ["a".repeat(40), "b".repeat(40), "c".repeat(40)] };
|
||||
expect(fitInspectionResponse(files, "files.list", 0, 120)).toBeNull();
|
||||
const small = { items: [1, 2, 3], nextOffset: null };
|
||||
expect(fitInspectionResponse(small, "list", 0, 1024)).toEqual(JSON.stringify(small));
|
||||
const big = { items: ["a".repeat(40), "b".repeat(40), "c".repeat(40)], nextOffset: 3 };
|
||||
expect(JSON.parse(fitInspectionResponse(big, "list", 10, 120)!)).toEqual({
|
||||
items: ["a".repeat(40), "b".repeat(40)],
|
||||
nextOffset: 12,
|
||||
});
|
||||
expect(fitInspectionResponse({ items: ["a".repeat(200), "b"], nextOffset: null }, "list", 0, 100)).toBeNull();
|
||||
expect(fitInspectionResponse({ content: "a".repeat(200) }, "get", 0, 100)).toBeNull();
|
||||
});
|
||||
|
||||
it("reads assigned repository URLs, snapshotted skill files, and workspace downloads with existing file restrictions", async () => {
|
||||
const root = await mkdtemp(join(directory, "workspace-"));
|
||||
await writeFile(join(root, "result.bin"), Buffer.alloc(2 * 1024 * 1024, 7));
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
INSPECTION_PERMIT_TYPE,
|
||||
INSPECTION_HEADER,
|
||||
type InspectionPermit,
|
||||
type InspectionQuery,
|
||||
} from "@paperclipai/shared";
|
||||
import type { StorageService } from "../storage/types.js";
|
||||
import { getCloudRuntimeIdentity } from "../services/cloud-runtime-identity.js";
|
||||
@@ -134,6 +135,36 @@ export function verifyRunLivenessQuestion(
|
||||
}
|
||||
}
|
||||
|
||||
export const MAX_INSPECTION_RESPONSE_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
export function fitInspectionResponse(
|
||||
result: unknown,
|
||||
operation: InspectionQuery["operation"],
|
||||
offset: number,
|
||||
maxBytes = MAX_INSPECTION_RESPONSE_BYTES,
|
||||
): string | null {
|
||||
const body = JSON.stringify(result);
|
||||
if (Buffer.byteLength(body) <= maxBytes) return body;
|
||||
if (operation !== "list") return null;
|
||||
const page = result as { items?: unknown; nextOffset?: unknown } | null;
|
||||
if (!page || !Array.isArray(page.items) || page.items.length < 2) return null;
|
||||
const items = page.items;
|
||||
let low = 0;
|
||||
let high = items.length - 1;
|
||||
let fitted: string | null = null;
|
||||
while (low < high) {
|
||||
const count = Math.ceil((low + high) / 2);
|
||||
const candidate = JSON.stringify({ ...page, items: items.slice(0, count), nextOffset: offset + count });
|
||||
if (Buffer.byteLength(candidate) <= maxBytes) {
|
||||
low = count;
|
||||
fitted = candidate;
|
||||
} else {
|
||||
high = count - 1;
|
||||
}
|
||||
}
|
||||
return fitted;
|
||||
}
|
||||
|
||||
/** Mounted before actor middleware: none of these reads creates tenant state. */
|
||||
export function customerSuccessRoutes(db: Db, storage: StorageService, options: CustomerSuccessInspectionOptions = {}) {
|
||||
const router = Router();
|
||||
@@ -188,8 +219,8 @@ export function customerSuccessRoutes(db: Db, storage: StorageService, options:
|
||||
});
|
||||
if (!consumed.ok) throw forbidden("Inspection permit could not be consumed");
|
||||
const result = await readCustomerSuccessResource(db, storage, query, options);
|
||||
const body = JSON.stringify(result);
|
||||
if (Buffer.byteLength(body) > 2 * 1024 * 1024)
|
||||
const body = fitInspectionResponse(result, query.operation, query.offset ?? 0);
|
||||
if (body === null)
|
||||
throw unprocessable("Inspection response is too large; use pagination or a byte range");
|
||||
res.type("application/json").send(body);
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user