mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-26 01:39:51 +01:00
fix(github): recover response requests that ran out of retries; restore lost regression tests (#22906)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Review agents answer GitHub pull request threads, and each request's comment must end in a real reply or an honest final notice > - After #22672, #22710, #22798 and #22807, new review-bot comments on staging settle: 0 of 85 comments since the deploy are stuck > - Two older "Working on this…" comments (PRs #22649 and #22676) still did not settle. Before those fixes, their requests spent all acknowledgement retries and were left `failed`, a state no recovery path reads again > - Separately, the chat-channels split (#22838) was built from an older copy of the monolith and dropped the regression tests those fixes added > - This pull request adds a one-time recovery migration for exhausted requests and restores the lost regression tests > - The benefit is that the last stuck comments settle, and the settle rules stay covered by tests that run on every PR ## Linked Issues or Issue Description Refs #22672, #22710, #22798, #22807, #22838 **Describe the bug** Two GitHub request comments from 2026-11-23 still read "Working on this…" on staging after the settle fixes deployed. Before #22798, an unsettled reply made each acknowledgement attempt fail with "GitHub reply is still being resolved", so these requests spent all 8 retries and stayed `failed` with `retryable: false`. Neither the acknowledgement sweep (retryable only) nor the terminal sweep (processed only) reads them again. **Steps to reproduce** 1. A request's acknowledgement fails 8 times and is left `failed`, `retryable: false`, with its comment still "Working on this…". 2. Deploy the settle fixes. Nothing reads the request again. **Expected behavior** Such a request settles with the current decision once. ## What Changed - Migration `0509_recover_exhausted_github_responses.sql`: one UPDATE that returns failed, non-final `github_response_comment` rows that already hold a posted comment to `processed` (code `recovered_after_exhausted_retries`, wait key and retry time cleared), so the terminal sweep settles them. Marked `online_compatible`. - Restored regression tests dropped by the split, in `server/src/__tests__/chat-channels/github-review-workflow.integration.test.ts`: published review kept in the main comment (ended / paused), older status settles against a newer placeholder, back-to-back runs settle, waited thread links a later response (including a different-PR guard), inline-only review link, waited thread settles when the task finishes, refused reply settles. - New tests: a failed run whose automatic retry finished the task (inline and issue threads), and the exhausted-retries recovery. ## Verification - `github-review-workflow.integration.test.ts` restored + new tests: 11 passed locally. The recovery test shows the comment stuck before the migration and settled after it. - Test tree typecheck (`src/__tests__/tsconfig.json`) is clean. - After deploy: the two remaining placeholders on #22649 and #22676 should settle within a sweep pass; I will check them on staging. ## Risks - The migration updates only failed, non-final GitHub request rows that have a posted comment; on staging that is a handful of rows. Each is read once by the terminal sweep and then settles or waits under the current rules. - Restored tests add a few seconds to the GitHub review workflow suite. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## 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 - [ ] 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
4aaa77e6fc
commit
4622965a25
5 files changed
+5919
-5415
No files matched your search
+313
-2
@@ -1,10 +1,17 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import path from "node:path";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { and, asc, eq, inArray, sql } from "drizzle-orm";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
chatActions,
|
||||
chatConversations,
|
||||
chatDeliveries,
|
||||
chatGitHubReviews,
|
||||
chatMessageLinks,
|
||||
heartbeatRuns,
|
||||
issues,
|
||||
} from "@paperclipai/db";
|
||||
// Opt-in private physical candidate; normal CI uses the staged pinned package.
|
||||
vi.mock("@chat-adapter/telegram", async (importOriginal) => {
|
||||
@@ -12,6 +19,7 @@ vi.mock("@chat-adapter/telegram", async (importOriginal) => {
|
||||
return candidate ? import(/* @vite-ignore */ candidate) : importOriginal();
|
||||
});
|
||||
import { githubResponseCommentService } from "../../services/chat-github-response-comments.js";
|
||||
import { githubChatReviewService } from "../../services/chat-github-reviews.js";
|
||||
import { type TestDb, describeEmbeddedPostgres, makeThread, makeMessage } from "./providers.js";
|
||||
import { createChatChannelHarness } from "./harness.js";
|
||||
import { createGitHubHarness } from "./github-harness.js";
|
||||
@@ -24,9 +32,312 @@ describeEmbeddedPostgres("chat channels: github review response maintenance", ()
|
||||
const gh = createGitHubHarness(h);
|
||||
const rev = createGitHubReviewHarness(h, gh);
|
||||
const { readChatActionsById, chatWakeContext, deliverMessage } = h;
|
||||
const { publicationRetryFixture } = rev;
|
||||
const { publicationRetryFixture, toolReplyFixture } = rev;
|
||||
|
||||
describe("GitHub agent review response maintenance", () => {
|
||||
const passiveWait = (key: string) => ({ status: "succeeded" as const, runtimeMode: "native" as const, nativePhase: "committed", resultJson: {
|
||||
finalizationPhase: "committed", finalizationReasonCode: "external_chat_response_waiting",
|
||||
nativeResult: { schema: "paperclip.run_result.v1", reportedWorkDisposition: "yielded",
|
||||
continuation: { kind: "response_wake", idempotencyKey: key } },
|
||||
presentationDecision: { schema: "paperclip.run_presentation_decision.v1", chosenSource: "none",
|
||||
commentAction: "none", reasonCodes: ["yielded_control_plane_wait"] } } });
|
||||
it.each(["ended_without_reply", "paused"] as const)(
|
||||
"keeps the published review in the main GitHub PR comment when a later request has only a status: %s", async statusCase => {
|
||||
const f = await publicationRetryFixture();
|
||||
await f.service.execute(f.session, "submit_review", f.assessment, "first-review");
|
||||
const [mainId] = [...f.responseComments.keys()];
|
||||
expect(f.responseComments.get(mainId)?.body).toContain("Advisory review");
|
||||
const committed = { status: "succeeded" as const, nativePhase: "committed", resultJson: {
|
||||
presentationDecision: { schema: "paperclip.run_presentation_decision.v1", chosenSource: "none", commentAction: "none" } } };
|
||||
await db.update(heartbeatRuns).set(committed).where(eq(heartbeatRuns.id, f.run.id));
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: f.conversation.externalThreadId }).thread;
|
||||
// Production saw several queued re-review requests while one run owned
|
||||
// the task: the run's own request ends without a reply, and the older
|
||||
// queued request is shown as paused while the task is blocked.
|
||||
for (const id of ["41802", "41803"]) await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "mention", message: makeMessage({ id, text: "Review again", userId: "42", userName: "octocat", mentioned: true }) });
|
||||
await githubResponseCommentService(db, f.providerFetch).processPending();
|
||||
const [next] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.assignedAgentId,
|
||||
status: "running", runtimeMode: "native", contextSnapshot: await chatWakeContext({
|
||||
endpointId: f.endpoint.id, issueId: f.conversation.issueId, provider: "github", providerMessageId: "41803",
|
||||
}) }).returning();
|
||||
await db.update(heartbeatRuns).set(committed).where(eq(heartbeatRuns.id, next.id));
|
||||
if (statusCase === "paused") {
|
||||
await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, f.conversation.issueId!));
|
||||
} else {
|
||||
await githubResponseCommentService(db, f.providerFetch).failRun({ companyId: f.companyId, endpointId: f.endpoint.id,
|
||||
issueId: f.conversation.issueId!, runId: next.id,
|
||||
body: "This turn ended without publishing a final response. See the Paperclip task for details." });
|
||||
}
|
||||
for (let pass = 0; pass < 3; pass++) await githubResponseCommentService(db, f.providerFetch).processPending();
|
||||
expect([...f.responseComments.keys()]).toEqual([mainId]);
|
||||
const body = f.responseComments.get(mainId)?.body ?? "";
|
||||
expect(body).toContain("Advisory review");
|
||||
expect(body).not.toContain("Work is paused");
|
||||
expect(body).not.toContain("without publishing a final response");
|
||||
// Requests with a status settle against the kept review instead of
|
||||
// retrying. Unpaused, the older queued request still waits for its run.
|
||||
const open = await db.select({ id: chatActions.id }).from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id),
|
||||
eq(chatActions.kind, "github_response_comment"), sql`coalesce(${chatActions.result}->>'final', 'false') <> 'true'`));
|
||||
expect(open).toHaveLength(statusCase === "paused" ? 0 : 1);
|
||||
});
|
||||
it("settles an older request's status without replacing a newer main GitHub PR placeholder", async () => {
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418");
|
||||
// The first request's run stopped before the next request arrived.
|
||||
await db.update(heartbeatRuns).set({ status: "failed", updatedAt: new Date(Date.now() - 60_000) })
|
||||
.where(eq(heartbeatRuns.id, f.run.id));
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: f.conversation.externalThreadId }).thread;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "mention", message: makeMessage({ id: "41802", text: "Review again", userId: "42", userName: "octocat", mentioned: true }) });
|
||||
const responses = githubResponseCommentService(db, f.providerFetch);
|
||||
await responses.processPending();
|
||||
await responses.processPending();
|
||||
expect(f.responseComments.size).toBe(1);
|
||||
const body = [...f.responseComments.values()][0].body;
|
||||
expect(body).not.toContain("stopped before completing");
|
||||
const [first] = await db.select().from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id),
|
||||
eq(chatActions.kind, "github_response_comment"))).orderBy(asc(chatActions.createdAt)).limit(1);
|
||||
expect(first).toMatchObject({ status: "processed", result: { final: true, code: "status_superseded" } });
|
||||
});
|
||||
it("settles a GitHub working comment whose run finished just before another request's run started", async () => {
|
||||
const f = await toolReplyFixture();
|
||||
const [firstId] = [...f.responseComments.keys()];
|
||||
expect(f.responseComments.get(firstId)?.body).toContain("Working on this");
|
||||
const committed = { status: "succeeded" as const, nativePhase: "committed", resultJson: {
|
||||
presentationDecision: { schema: "paperclip.run_presentation_decision.v1", chosenSource: "none", commentAction: "none" } } };
|
||||
// The first request's run ends without a reply, and the next request's run
|
||||
// starts before any sweep sees the first run as the task's latest.
|
||||
await db.update(heartbeatRuns).set(committed).where(eq(heartbeatRuns.id, f.run.id));
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: f.conversation.externalThreadId }).thread;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "mention", message: makeMessage({ id: "41802", text: "One more thing", userId: "42", userName: "octocat", mentioned: true }) });
|
||||
const [next] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.assignedAgentId,
|
||||
status: "running", runtimeMode: "native", contextSnapshot: await chatWakeContext({
|
||||
endpointId: f.endpoint.id, issueId: f.conversation.issueId, provider: "github", providerMessageId: "41802",
|
||||
}) }).returning();
|
||||
const responses = githubResponseCommentService(db, f.providerFetch);
|
||||
await responses.processPending();
|
||||
// Work is still running on the task, so the first request waits.
|
||||
expect(f.responseComments.get(firstId)?.body).toContain("Working on this");
|
||||
await db.update(heartbeatRuns).set(committed).where(eq(heartbeatRuns.id, next.id));
|
||||
await responses.processPending();
|
||||
expect(f.responseComments.get(firstId)?.body).toContain("ended without publishing a final response");
|
||||
const open = await db.select({ id: chatActions.id }).from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id),
|
||||
eq(chatActions.kind, "github_response_comment"), sql`coalesce(${chatActions.result}->>'final', 'false') <> 'true'`));
|
||||
expect(open).toEqual([]);
|
||||
const writes = f.responseWrites.length;
|
||||
await responses.processPending();
|
||||
expect(f.responseWrites).toHaveLength(writes);
|
||||
});
|
||||
it("links a GitHub thread whose run waited to the response a later run published", async () => {
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100");
|
||||
const [firstId] = [...f.responseComments.keys()];
|
||||
await db.update(heartbeatRuns).set(passiveWait("first-wait")).where(eq(heartbeatRuns.id, f.run.id));
|
||||
const responses = githubResponseCommentService(db, f.providerFetch);
|
||||
await responses.processPending();
|
||||
// The run waits on purpose and the task is still open, so the thread waits too.
|
||||
expect(f.responseComments.get(firstId)?.body).toContain("Working on this");
|
||||
// A response on another pull request bound to the same task is not linked.
|
||||
const [other] = await db.insert(chatConversations).values({ companyId: f.companyId, endpointId: f.endpoint.id,
|
||||
issueId: f.conversation.issueId, externalConversationId: "github:paperclipai/paperclip",
|
||||
externalLabel: "paperclipai/paperclip", externalThreadId: "github:paperclipai/paperclip:4180" }).returning();
|
||||
await db.insert(chatActions).values({ companyId: f.companyId, endpointId: f.endpoint.id, conversationId: other.id,
|
||||
kind: "github_review_publication", providerActionId: `github_publication:${randomUUID()}`, status: "processed",
|
||||
payload: { operation: "comment", session: { companyId: f.companyId, issueId: f.conversation.issueId, runId: f.run.id } },
|
||||
result: { id: "77", url: "https://github.com/paperclipai/paperclip/pull/4180#issuecomment-77" } });
|
||||
await db.update(issues).set({ status: "in_progress" }).where(eq(issues.id, f.conversation.issueId!));
|
||||
await responses.processPending();
|
||||
expect(f.responseComments.get(firstId)?.body).toContain("Working on this");
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: f.conversation.externalThreadId }).thread;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "mention", message: makeMessage({ id: "41802", text: "Fixed this one too", userId: "42", userName: "octocat", mentioned: true }) });
|
||||
const [next] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.assignedAgentId,
|
||||
status: "running", runtimeMode: "native", contextSnapshot: await chatWakeContext({
|
||||
endpointId: f.endpoint.id, issueId: f.conversation.issueId, provider: "github", providerMessageId: "41802",
|
||||
}) }).returning();
|
||||
await githubChatReviewService(db, f.providerFetch).execute({ ...f.session, runId: next.id }, "comment",
|
||||
{ body: "Re-reviewed both threads", idempotencyKey: "later-response" });
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, next.id));
|
||||
await responses.processPending();
|
||||
expect(f.responseComments.get(firstId)?.body).toMatch(/See the \[latest response\]\(https:\/\/github\.com\//);
|
||||
});
|
||||
it("links a waiting GitHub thread to a later review published only as inline findings", async () => {
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100");
|
||||
const [firstId] = [...f.responseComments.keys()];
|
||||
await db.update(heartbeatRuns).set(passiveWait("inline-only-wait")).where(eq(heartbeatRuns.id, f.run.id));
|
||||
const responses = githubResponseCommentService(db, f.providerFetch);
|
||||
await responses.processPending();
|
||||
expect(f.responseComments.get(firstId)?.body).toContain("Working on this");
|
||||
const reviewId = randomUUID();
|
||||
await db.insert(chatGitHubReviews).values({ id: reviewId, companyId: f.companyId, endpointId: f.endpoint.id,
|
||||
issueId: f.conversation.issueId!, repositoryId: "42", repository: "paperclipai/paperclip", pullNumber: 418,
|
||||
headSha: "b".repeat(40), deliveryId: "inline-only", configurationRevision: 1, policySnapshot: {} as never, event: {} as never,
|
||||
state: "completed", publicationReceipts: { "finding:1": { id: "88",
|
||||
url: "https://github.com/paperclipai/paperclip/pull/418#discussion_r88", digest: "d" } } });
|
||||
await db.insert(chatActions).values({ companyId: f.companyId, endpointId: f.endpoint.id, conversationId: f.conversation.id,
|
||||
kind: "github_review_publication", providerActionId: `github_publication:${randomUUID()}`, status: "processed",
|
||||
payload: { operation: "assessment", reviewId, session: { companyId: f.companyId, issueId: f.conversation.issueId, runId: f.run.id } },
|
||||
result: { reviewId, summaryUrl: null } });
|
||||
await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.conversation.issueId!));
|
||||
await responses.processPending();
|
||||
// The outgoing-text projection drops URL fragments, so the link names the pull request.
|
||||
expect(f.responseComments.get(firstId)?.body).toContain("See the [latest response](https://github.com/paperclipai/paperclip/pull/418)");
|
||||
expect(f.responseComments.get(firstId)?.body).not.toContain("ended without publishing");
|
||||
});
|
||||
it("settles a waiting GitHub thread once the task finishes without a later response", async () => {
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100");
|
||||
const [firstId] = [...f.responseComments.keys()];
|
||||
await db.update(heartbeatRuns).set(passiveWait("only-wait")).where(eq(heartbeatRuns.id, f.run.id));
|
||||
const responses = githubResponseCommentService(db, f.providerFetch);
|
||||
await responses.processPending();
|
||||
expect(f.responseComments.get(firstId)?.body).toContain("Working on this");
|
||||
await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.conversation.issueId!));
|
||||
await responses.processPending();
|
||||
expect(f.responseComments.get(firstId)?.body).toContain("ended without publishing a final response");
|
||||
});
|
||||
it("settles a GitHub thread whose run's final reply could not be published", async () => {
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100");
|
||||
const [firstId] = [...f.responseComments.keys()];
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded", runtimeMode: "native", nativePhase: "committed", resultJson: {
|
||||
finalizationPhase: "committed", finalizationReasonCode: "governed_gate_pending",
|
||||
responsePublication: { schema: "paperclip.native_response_publication.v1", state: "failed", attempts: 6,
|
||||
reasonCode: "native_response_publication_failed", lastReason: "publication_refused", nextAttemptAt: null } } })
|
||||
.where(eq(heartbeatRuns.id, f.run.id));
|
||||
await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.conversation.issueId!));
|
||||
const responses = githubResponseCommentService(db, f.providerFetch);
|
||||
for (let pass = 0; pass < 2; pass++) await responses.processPending();
|
||||
expect(f.responseComments.get(firstId)?.body).toContain("reply could not be published");
|
||||
});
|
||||
it.each(["github:paperclipai/paperclip:418:rc:4100", "github:paperclipai/paperclip:issue:418"])(
|
||||
"settles a GitHub request whose run failed and whose automatic retry finished the task: %s", async threadId => {
|
||||
const f = await toolReplyFixture(threadId);
|
||||
const [firstId] = [...f.responseComments.keys()];
|
||||
expect(f.responseComments.get(firstId)?.body).toContain("Working on this");
|
||||
await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, f.run.id));
|
||||
// The retry carries the task, not the request's wake comment.
|
||||
await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.assignedAgentId,
|
||||
status: "succeeded", runtimeMode: "native", nativePhase: "committed", retryOfRunId: f.run.id,
|
||||
contextSnapshot: { issueId: f.conversation.issueId }, resultJson: {
|
||||
presentationDecision: { schema: "paperclip.run_presentation_decision.v1", chosenSource: "none", commentAction: "none" } } });
|
||||
await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.conversation.issueId!));
|
||||
const responses = githubResponseCommentService(db, f.providerFetch);
|
||||
for (let pass = 0; pass < 3; pass++) await responses.processPending();
|
||||
expect(f.responseComments.get(firstId)?.body).not.toContain("Working on this");
|
||||
});
|
||||
it.each([[502, true], [422, false]] as const)(
|
||||
"keeps retrying a GitHub request after 8 attempts only for a temporary error: %s", async (status, retryable) => {
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100");
|
||||
await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, f.run.id));
|
||||
await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.conversation.issueId!));
|
||||
const readResponse = async () => (await db.select().from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id),
|
||||
eq(chatActions.kind, "github_response_comment"))))[0];
|
||||
const before = await readResponse();
|
||||
await db.update(chatActions).set({ status: "failed", result: { ...before.result, attempts: 7, retryable: true,
|
||||
retryAt: new Date(0).toISOString(), code: "acknowledgement_unconfirmed" } }).where(eq(chatActions.id, before.id));
|
||||
f.setSupplementalProviderFetch(async (_input, init) => init?.method === "PATCH"
|
||||
? Response.json({ message: "GitHub error" }, { status }) : undefined);
|
||||
const startedAt = Date.now();
|
||||
await githubResponseCommentService(db, f.providerFetch).processPending();
|
||||
const after = await readResponse();
|
||||
expect(after).toMatchObject({ status: "failed", result: { attempts: 8, retryable } });
|
||||
if (retryable) {
|
||||
const wait = Date.parse(String(after.result?.retryAt)) - startedAt;
|
||||
expect(wait).toBeGreaterThanOrEqual(3_590_000);
|
||||
expect(wait).toBeLessThanOrEqual(3_660_000);
|
||||
}
|
||||
});
|
||||
it("settles a coalesced GitHub request whose comment was deleted without blocking the reply", async () => {
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100");
|
||||
const thread = makeThread({ channelId: "paperclipai/paperclip", id: f.conversation.externalThreadId }).thread;
|
||||
await deliverMessage({ callbacks: f.callbacks, endpointId: f.endpoint.id, provider: "github", thread,
|
||||
trigger: "mention", message: makeMessage({ id: "41802", text: "And this one", userId: "42", userName: "octocat", mentioned: true }) });
|
||||
await githubResponseCommentService(db, f.providerFetch).processPending();
|
||||
const inbound = await db.select({ commentId: chatMessageLinks.commentId, deliveryId: chatMessageLinks.deliveryId })
|
||||
.from(chatMessageLinks).where(and(eq(chatMessageLinks.conversationId, f.conversation.id), eq(chatMessageLinks.direction, "inbound")))
|
||||
.orderBy(asc(chatMessageLinks.createdAt));
|
||||
expect(inbound).toHaveLength(2);
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id));
|
||||
await db.update(heartbeatRuns).set({ contextSnapshot: { ...run.contextSnapshot,
|
||||
wakeCommentIds: inbound.map(link => link.commentId) } }).where(eq(heartbeatRuns.id, f.run.id));
|
||||
const [sibling] = await db.select().from(chatActions).where(and(eq(chatActions.deliveryId, inbound[1]!.deliveryId!),
|
||||
eq(chatActions.kind, "github_response_comment")));
|
||||
expect(sibling.result?.id).toBeTruthy();
|
||||
f.responseComments.delete(Number(sibling.result!.id));
|
||||
await githubChatReviewService(db, f.providerFetch).execute(f.session, "comment",
|
||||
{ body: "Answered both requests", idempotencyKey: "coalesced-reply" });
|
||||
expect([...f.responseComments.values()].some(comment => comment.body.includes("Answered both requests"))).toBe(true);
|
||||
expect((await readChatActionsById(sibling.id))[0]).toMatchObject({ status: "cancelled",
|
||||
result: { final: true, code: "response_deleted" } });
|
||||
});
|
||||
it("settles a GitHub request whose posted comment was deleted instead of retrying it", async () => {
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100");
|
||||
const [firstId] = [...f.responseComments.keys()];
|
||||
await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, f.run.id));
|
||||
await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.conversation.issueId!));
|
||||
const responses = githubResponseCommentService(db, f.providerFetch);
|
||||
const readResponse = async () => (await db.select().from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id),
|
||||
eq(chatActions.kind, "github_response_comment"))))[0];
|
||||
// A 404 that is not about this comment (here the comment write) is not a deletion.
|
||||
f.setSupplementalProviderFetch(async (_input, init) => init?.method === "PATCH"
|
||||
? Response.json({ message: "Not Found" }, { status: 404 }) : undefined);
|
||||
await responses.processPending();
|
||||
expect(await readResponse()).toMatchObject({ status: "failed", result: { retryable: true } });
|
||||
f.setSupplementalProviderFetch(async () => undefined);
|
||||
const due = await readResponse();
|
||||
await db.update(chatActions).set({ result: { ...due.result, retryAt: new Date(0).toISOString() } }).where(eq(chatActions.id, due.id));
|
||||
f.responseComments.delete(firstId);
|
||||
const writes = f.responseWrites.length;
|
||||
await responses.processPending();
|
||||
const response = await readResponse();
|
||||
expect(response).toMatchObject({ status: "cancelled", result: { final: true, code: "response_deleted" } });
|
||||
expect(f.responseComments.size).toBe(0);
|
||||
expect(f.responseWrites).toHaveLength(writes);
|
||||
});
|
||||
it("settles a GitHub thread whose acknowledgement retries ran out, after the recovery migration", async () => {
|
||||
const f = await toolReplyFixture("github:paperclipai/paperclip:418:rc:4100");
|
||||
const [firstId] = [...f.responseComments.keys()];
|
||||
await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, f.run.id));
|
||||
await db.update(issues).set({ status: "done" }).where(eq(issues.id, f.conversation.issueId!));
|
||||
// Before the settle fixes, a request could spend all its acknowledgement
|
||||
// retries and stay failed, which no recovery path reads again.
|
||||
const [response] = await db.select().from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id),
|
||||
eq(chatActions.kind, "github_response_comment")));
|
||||
await db.update(chatActions).set({ status: "failed", result: { ...response.result,
|
||||
attempts: 8, retryable: false, code: "acknowledgement_unconfirmed" } }).where(eq(chatActions.id, response.id));
|
||||
const responses = githubResponseCommentService(db, f.providerFetch);
|
||||
await responses.processPending();
|
||||
expect(f.responseComments.get(firstId)?.body).toContain("Working on this");
|
||||
const migration = await readFile(path.resolve(path.dirname(fileURLToPath(import.meta.url)),
|
||||
"../../../../packages/db/src/migrations/0509_recover_exhausted_github_responses.sql"), "utf8");
|
||||
// Rows the recovery must leave alone: final, still retryable, no posted comment, or no delivery.
|
||||
const untouched = await db.insert(chatActions).values([
|
||||
{ result: { id: "1", final: true }, providerActionId: `untouched:${randomUUID()}`, deliveryId: response.deliveryId },
|
||||
{ result: { id: "2", retryable: true }, providerActionId: `untouched:${randomUUID()}`, deliveryId: response.deliveryId },
|
||||
{ result: { code: "acknowledgement_unconfirmed" }, providerActionId: `untouched:${randomUUID()}`, deliveryId: response.deliveryId },
|
||||
{ result: { id: "4" }, providerActionId: `untouched:${randomUUID()}`, deliveryId: null },
|
||||
].map(row => ({ ...row, companyId: f.companyId, endpointId: f.endpoint.id, conversationId: f.conversation.id,
|
||||
kind: "github_response_comment", status: "failed" as const, payload: {} }))).returning();
|
||||
await db.$client.unsafe(migration);
|
||||
expect((await Promise.all(untouched.map(row => readChatActionsById(row.id)))).map(([row]) => row.status))
|
||||
.toEqual(["failed", "failed", "failed", "failed"]);
|
||||
await db.delete(chatActions).where(inArray(chatActions.id, untouched.map(row => row.id)));
|
||||
// Recovery resets the attempt count so a temporary GitHub error can retry.
|
||||
expect((await readChatActionsById(response.id))[0]).toMatchObject({ status: "processed",
|
||||
result: { attempts: 0, code: "recovered_after_exhausted_retries" } });
|
||||
let failures = 0;
|
||||
f.setSupplementalProviderFetch(async (input, init) => init?.method === "PATCH" && failures++ === 0
|
||||
? Response.json({ message: "Server Error" }, { status: 502 }) : undefined);
|
||||
await responses.processPending();
|
||||
expect(f.responseComments.get(firstId)?.body).toContain("Working on this");
|
||||
const [retrying] = await readChatActionsById(response.id);
|
||||
expect(retrying).toMatchObject({ status: "failed", result: { retryable: true } });
|
||||
await db.update(chatActions).set({ result: { ...retrying.result, retryAt: new Date(0).toISOString() } })
|
||||
.where(eq(chatActions.id, response.id));
|
||||
await responses.processPending();
|
||||
expect(f.responseComments.get(firstId)?.body).toContain("stopped before completing");
|
||||
const [settled] = await db.select().from(chatActions).where(eq(chatActions.id, response.id));
|
||||
expect(settled.result?.final).toBe(true);
|
||||
});
|
||||
it.each((["completed", "failed", "missing_decision", "comment_requested", "missing_semantic", "legacy", "uncommitted_native", "pending_publication", "missing_decision_then_missing", "uncommitted_then_failed", "malformed_null", "malformed_scalar", "malformed_schema", "malformed_action"] as const)
|
||||
.flatMap(scenario => ["external_chat_response_waiting", "preserved_result_status_unproven"].map(reason => ({ scenario, reason }))))(
|
||||
"keeps GitHub response maintenance truthful for a new request: $scenario ($reason)", async ({ scenario, reason }) => {
|
||||
|
||||
@@ -43,6 +43,11 @@ const legacyStatusBodies = new Set(["Work is paused. Your request is saved. See
|
||||
/** A reply or review the agent published, as opposed to a placeholder or a Paperclip status notice. */
|
||||
export const holdsPublishedResponse = (body: string | undefined) => !!body?.includes("<!-- paperclip-response-state:final -->") &&
|
||||
!body.includes(statusMarker) && !legacyStatusBodies.has(body.split("\n\n<!-- paperclip-")[0]!.trim());
|
||||
/** A 404 when reading the request's own posted comment: it was deleted on GitHub. */
|
||||
const responseCommentDeleted = (error: unknown) => {
|
||||
const details = error instanceof HttpError ? error.details as { code?: string; providerStatus?: number } | undefined : undefined;
|
||||
return details?.code === "github_response_deleted";
|
||||
};
|
||||
const responseMarker = (source: Source) => isMainPullResponse(source) ? pullResponseMarker(source) : requestResponseMarker(source);
|
||||
|
||||
async function findResponseComment(source: Source, api: Api, legacyMarkers: string[] = []): Promise<Comment | null> {
|
||||
@@ -143,7 +148,15 @@ export async function writeGitHubResponseComment(
|
||||
if (target.result?.id) {
|
||||
// Never recreate a deleted comment or edit an arbitrary caller-selected ID.
|
||||
if (!/^[1-9][0-9]*$/.test(String(target.result.id))) throw forbidden("Invalid GitHub response receipt");
|
||||
previous = await api.request<Comment>(`${item}/${target.result.id}`);
|
||||
try {
|
||||
previous = await api.request<Comment>(`${item}/${target.result.id}`);
|
||||
} catch (error) {
|
||||
const details = error instanceof HttpError ? error.details as { providerStatus?: number } | undefined : undefined;
|
||||
// Only a 404 for this exact comment proves it was deleted; a token or
|
||||
// repository-access failure is not.
|
||||
if (details?.providerStatus === 404) throw conflict("GitHub response comment was deleted", { code: "github_response_deleted" });
|
||||
throw error;
|
||||
}
|
||||
if (!previous.body?.includes(marker) || previous.user?.login !== source.endpoint.botUsername)
|
||||
throw forbidden("GitHub response is no longer owned by this App");
|
||||
} else {
|
||||
@@ -372,7 +385,8 @@ export function githubResponseCommentService(db: Db, fetchImpl = fetch) {
|
||||
}, async () => { await assertCurrent(); await context(link.deliveryId!); });
|
||||
} catch (error) {
|
||||
const details = error instanceof HttpError ? error.details as { code?: string; providerStatus?: number } | undefined : undefined;
|
||||
if (!response.result?.id || details?.code !== "github_bot_operation_failed" || details.providerStatus !== 404) throw error;
|
||||
const deleted = responseCommentDeleted(error) || (details?.code === "github_bot_operation_failed" && details.providerStatus === 404);
|
||||
if (!response.result?.id || !deleted) throw error;
|
||||
// A human can delete an earlier working comment while the coalesced
|
||||
// review runs. Settle that exact receipt without recreating the comment
|
||||
// or blocking the current response and check publication.
|
||||
@@ -472,11 +486,25 @@ export function githubResponseCommentService(db: Db, fetchImpl = fetch) {
|
||||
if (!row || row.result?.final === true) return;
|
||||
const attempts = Number(row.result?.attempts ?? 0) + 1;
|
||||
const denied = error instanceof Error && "status" in error && error.status === 403;
|
||||
const details = error instanceof HttpError ? error.details as { code?: string; retryable?: boolean } | undefined : undefined;
|
||||
if (row.result?.id && responseCommentDeleted(error)) {
|
||||
// Someone deleted the posted comment. Settle the request without
|
||||
// recreating it, as finishRun does for coalesced requests.
|
||||
await db.transaction(async tx => {
|
||||
await notifyChatResponseAvailability(tx, { companyId: row.companyId, deliveryId });
|
||||
await tx.update(chatActions).set({ status: "cancelled", result: { ...row.result, final: true, code: "response_deleted" },
|
||||
updatedAt: new Date() }).where(and(eq(chatActions.id, row.id), sql`coalesce(${chatActions.result}->>'final', 'false') <> 'true'`));
|
||||
});
|
||||
return;
|
||||
}
|
||||
await db.transaction(async tx => {
|
||||
await notifyChatResponseAvailability(tx, { companyId: row.companyId, deliveryId });
|
||||
await tx.update(chatActions).set({ status: denied ? "cancelled" : "failed", result: {
|
||||
...row.result, attempts, retryable: !denied && attempts < 8,
|
||||
retryAt: new Date(Date.now() + Math.min(300000, 1000 * 2 ** attempts)).toISOString(),
|
||||
// Temporary failures (network, rate limit, 5xx) keep retrying with
|
||||
// backoff up to 5 minutes, then hourly. An error GitHub calls
|
||||
// permanent stops after 8 attempts, since retrying cannot fix it.
|
||||
...row.result, attempts, retryable: !denied && (details?.retryable !== false || attempts < 8),
|
||||
retryAt: new Date(Date.now() + (attempts < 8 ? Math.min(300000, 1000 * 2 ** attempts) : 3_600_000)).toISOString(),
|
||||
code: denied ? "authorization_changed" : "acknowledgement_unconfirmed",
|
||||
}, updatedAt: new Date() }).where(and(eq(chatActions.id, row.id), sql`coalesce(${chatActions.result}->>'final', 'false') <> 'true'`));
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user