diff --git a/server/src/services/documents.ts b/server/src/services/documents.ts index 1f99f012ef8..4ea296c63f3 100644 --- a/server/src/services/documents.ts +++ b/server/src/services/documents.ts @@ -222,9 +222,9 @@ export function documentService(db: Db) { return revision ? { ...revision, isLatest: revision.latestRevisionId === revision.id } : null; }, - listIssueDocumentRevisions: async (issueId: string, rawKey: string) => { + listIssueDocumentRevisions: async (issueId: string, rawKey: string, options: { limit?: number } = {}) => { const key = normalizeDocumentKey(rawKey); - return db + const query = db .select({ id: documentRevisions.id, companyId: documentRevisions.companyId, @@ -246,6 +246,8 @@ export function documentService(db: Db) { .innerJoin(documentRevisions, eq(documentRevisions.documentId, documents.id)) .where(and(eq(issueDocuments.issueId, issueId), eq(issueDocuments.key, key))) .orderBy(desc(documentRevisions.revisionNumber)); + // Newest first, so a limit keeps the most recent revisions. + return options.limit === undefined ? query : query.limit(options.limit); }, upsertIssueDocument: async (input: { diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts index f8c046e358f..710f4ada239 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts @@ -1358,6 +1358,35 @@ describe("PaperclipRunnerToolAuthority", () => { ).rejects.toThrow("paperclip_runner_tool_idempotency_conflict"); }); + it("honors the revision limit and returns a read too large to journal as a small named tool error", async () => { + // A Sentry case document accumulates many large revisions. Its full + // history once exceeded the PRP command bound, so the run disconnected + // and restart recovery reran the same read and failed the run. + const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId }); + let baseRevisionId: string | null = null; + for (let revision = 1; revision <= 5; revision += 1) { + const written = await authority.execute({ tool: "write_document", callId: `history-${revision}`, arguments: { + idempotencyKey: `history-${revision}`, key: "large-history", title: "Case", baseRevisionId, + body: `Revision ${revision}\n${"evidence ".repeat(18_000)}`, changeSummary: `Revision ${revision}`, + } }) as { document: { latestRevisionId: string } }; + baseRevisionId = written.document.latestRevisionId; + } + + const latest = await authority.execute({ tool: "list_document_revisions", callId: "latest-revision", + arguments: { key: "large-history", limit: 1 } }) as { revisions: Array<{ revisionNumber: number }> }; + expect(latest.revisions.map(revision => revision.revisionNumber)).toEqual([5]); + const recent = await authority.execute({ tool: "list_document_revisions", callId: "recent-revisions", + arguments: { key: "large-history", limit: 2 } }) as { revisions: Array<{ revisionNumber: number }> }; + expect(recent.revisions.map(revision => revision.revisionNumber)).toEqual([5, 4]); + + const oversized = { tool: "list_document_revisions", callId: "whole-history", arguments: { key: "large-history" } }; + await expect(authority.execute(oversized)).rejects.toThrow(/^paperclip_runner_read_result_too_large: The list_document_revisions result is \d+ bytes/); + const recovered = await authority.recover(oversized); + expect(recovered).toMatchObject({ isError: true, result: { success: false, + contentItems: [{ type: "inputText", text: expect.stringContaining("paperclip_runner_read_result_too_large") }] } }); + expect(Buffer.byteLength(JSON.stringify(recovered))).toBeLessThan(1_000); + }); + it("settles a write_document a restart orphaned from its transactional receipt, applying it at most once", async () => { // A restart can cut a write_document callback after the runner journaled // its input but before any result was saved. The revision and its receipt diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts index 2887876fafb..6378e3ca06d 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -204,7 +204,18 @@ function nativeToolAllowedInMode(operationId: string, workMode: string): boolean const RECOVERABLE_READ_ERRORS = new Set([ "paperclip_runner_document_not_found", "paperclip_runner_agent_not_found", "paperclip_runner_approval_not_found", "paperclip_runner_tool_input_invalid", + "paperclip_runner_read_result_too_large", ]); +// A tool result travels as one durable PRP command. A document read larger than +// that bound cannot be journaled: it would disconnect the run, and restart +// recovery would read it again and fail the run. Return a small named error. +function boundedDocumentRead(tool: string, result: T): T { + const bytes = Buffer.byteLength(JSON.stringify(result) ?? ""); + if (bytes <= RUNNER_TOOL_RESULT_MAX_BYTES) return result; + throw new Error(`paperclip_runner_read_result_too_large: The ${tool} result is ${bytes} bytes, above the ` + + `${RUNNER_TOOL_RESULT_MAX_BYTES}-byte limit for one tool result.` + + (tool === "list_document_revisions" ? " Request fewer revisions with a smaller limit, such as limit: 1." : "")); +} const idSimilarity = (left: string, right: string) => { const a = left.toLowerCase(), b = right.toLowerCase(); let prefix = 0; @@ -1125,21 +1136,24 @@ export class PaperclipRunnerToolAuthority { }; } case "list_documents": - return { documents: await this.#visibleMuseDocuments(context.issue, - await documentService(this.db).listIssueDocuments(this.binding.issueId)) }; + return boundedDocumentRead(call.tool, { documents: await this.#visibleMuseDocuments(context.issue, + await documentService(this.db).listIssueDocuments(this.binding.issueId)) }); case "read_document": { const document = await documentService(this.db).getIssueDocumentByKey(this.binding.issueId, requiredString(input.key)); if (!document) throw new Error("paperclip_runner_document_not_found"); const [visible] = await this.#visibleMuseDocuments(context.issue, [document]); - return { document: visible }; + return boundedDocumentRead(call.tool, { document: visible }); } case "list_document_revisions": { const key = requiredString(input.key); const service = documentService(this.db); - const revisions = await service.listIssueDocumentRevisions(this.binding.issueId, key); - if (!this.binding.museRuntime || revisions.length === 0) return { revisions }; + // Honor the advertised limit (default 50, maximum 200), newest first. + const revisions = await service.listIssueDocumentRevisions(this.binding.issueId, key, + { limit: boundedLimit(input.limit, 50, 200) }); + if (!this.binding.museRuntime || revisions.length === 0) return boundedDocumentRead(call.tool, { revisions }); const document = await service.getIssueDocumentByKey(this.binding.issueId, key); - return { revisions: await this.#projectMuseDocumentContent(context.issue, revisions, document ? [document] : []) }; + return boundedDocumentRead(call.tool, + { revisions: await this.#projectMuseDocumentContent(context.issue, revisions, document ? [document] : []) }); } case "write_document": return this.#writeDocument(input); case "list_agents":