mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-25 02:26:12 +02:00
## Thinking Path > - Paperclip is the open source control plane people use to coordinate AI-agent companies > - Agents, routines, productivity review, and recovery services can all create or re-trigger work > - Repeated heartbeats or catch-up cycles can produce duplicate tasks or repeat recovery actions before prior work is visible > - The base duplicate-create and routine catch-up coalescing work has now landed on `master` via related PRs while this PR was being prepared > - This pull request carries the remaining hardening: bounded idempotency retention, recovery cooldown/throttle fixes, productivity-review query batching and ordering fixes, and regression coverage > - The benefit is fewer duplicate tasks, safer retries, and enough provenance to diagnose any future recurrence ## Linked Issues or Issue Description Agents can retry issue creation after ambiguous responses or independently recreate the same child title, while recovery and short-interval routine catch-up paths can repeat before prior work settles. This can produce visible duplicate tasks and makes the originating heartbeat difficult to identify. Related work: Refs #8356 for caller-supplied issue-create idempotency and Refs #9224 for plugin-scoped issue-create idempotency. Prior related PR: #6936. The base issue-create deduplication and routine catch-up coalescing pieces have since landed on `master` via #9650 and #9649; this PR remains as the follow-up hardening stack on top of those changes. ## What Changed - Add 7-day retention for issue-create idempotency claims with indexed, batch-limited cleanup so the claim table does not grow forever. - Preserve recovery cooldown intent after terminal recovery actions are closed, and throttle repeated source-scoped recovery work. - Batch productivity-review source-activity checks to avoid repeated per-source queries while keeping the no-action suppression behavior. - Order productivity-review no-action streak windows by review creation time, matching the window semantics even when completion timestamps are out of order. - Preserve generated issue IDs in route mocks used by backlog/assignment contract tests. - Document PR-gardening task deduplication expectations in the company skill. - Add focused regression tests for idempotency retention, liveness recovery cooldowns, and productivity-review batching/suppression/ordering behavior. ## Verification - `pnpm --filter @paperclipai/server typecheck` — passed on latest head. - `pnpm exec vitest run --project @paperclipai/server server/src/__tests__/productivity-review-service.test.ts server/src/__tests__/issue-create-deduplication-routes.test.ts --reporter verbose` — 2 files, 23 tests passed on latest head. - `pnpm --filter @paperclipai/adapter-utils build && pnpm exec vitest run --project @paperclipai/adapter-utils --reporter dot` — 30 files passed, 476 tests passed, 8 skipped. - `pnpm build` — passed on latest head. - `pnpm -r typecheck` — passed on the rebased head before the final productivity-review ordering commit; the latest touched server code is covered by the server typecheck above. - `pnpm check:token-gates` — passed. - `pnpm test:run` — progressed through server, UI, CLI, shared, skills-catalog, and DB sections, then exposed an adapter-utils compiled-test fingerprint mismatch before rebuilding adapter-utils; the adapter-utils project passed after rebuild, and the GitHub split PR checks passed on the pushed head. ## Risks - Caller-supplied idempotency replay is now bounded to 7 days; reusing an old key after retention can create new work, which matches retry-oriented idempotency semantics. - Recovery and productivity-review timing changes may suppress redundant follow-up work; focused tests cover the intended boundaries. - Advisory locking and idempotency cleanup rely on PostgreSQL-compatible transaction semantics already used by the production data layer. - The migration extends the private claim table indexes without rewriting existing issue rows. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - OpenAI Codex based on GPT-5, with reasoning, repository editing, shell/tool execution, and test execution. Exact model ID and context-window size are not exposed by the runtime. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
326 lines
10 KiB
TypeScript
326 lines
10 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import express from "express";
|
|
import request from "supertest";
|
|
import { eq } from "drizzle-orm";
|
|
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
|
import {
|
|
activityLog,
|
|
agents,
|
|
companies,
|
|
createDb,
|
|
heartbeatRuns,
|
|
issueCreateIdempotencyKeys,
|
|
issues,
|
|
} from "@paperclipai/db";
|
|
import {
|
|
getEmbeddedPostgresTestSupport,
|
|
startEmbeddedPostgresTestDatabase,
|
|
} from "./helpers/embedded-postgres.js";
|
|
import { actorMiddleware } from "../middleware/auth.js";
|
|
import { errorHandler } from "../middleware/index.js";
|
|
import { issueRoutes } from "../routes/issues.js";
|
|
import {
|
|
ISSUE_CREATE_IDEMPOTENCY_KEY_RETENTION_DAYS,
|
|
issueService,
|
|
} from "../services/issues.js";
|
|
|
|
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
|
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
|
|
|
if (!embeddedPostgresSupport.supported) {
|
|
console.warn(
|
|
`Skipping embedded Postgres issue create deduplication route tests on this host: ${
|
|
embeddedPostgresSupport.reason ?? "unsupported environment"
|
|
}`,
|
|
);
|
|
}
|
|
|
|
describeEmbeddedPostgres("issue create deduplication routes", () => {
|
|
let db!: ReturnType<typeof createDb>;
|
|
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
|
|
|
beforeAll(async () => {
|
|
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-issue-create-deduplication-routes-");
|
|
db = createDb(tempDb.connectionString);
|
|
}, 20_000);
|
|
|
|
afterEach(async () => {
|
|
await db.delete(activityLog);
|
|
await db.delete(issueCreateIdempotencyKeys);
|
|
await db.delete(issues);
|
|
await db.delete(heartbeatRuns);
|
|
await db.delete(agents);
|
|
await db.delete(companies);
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await tempDb?.cleanup();
|
|
});
|
|
|
|
function createApp() {
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use(actorMiddleware(db, { deploymentMode: "local_trusted" }));
|
|
app.use("/api", issueRoutes(db, {} as any));
|
|
app.use(errorHandler);
|
|
return app;
|
|
}
|
|
|
|
async function seedCompany() {
|
|
const companyId = randomUUID();
|
|
await db.insert(companies).values({
|
|
id: companyId,
|
|
name: "Paperclip",
|
|
issuePrefix: `D${companyId.replace(/-/g, "").slice(0, 5).toUpperCase()}`,
|
|
requireBoardApprovalForNewAgents: false,
|
|
});
|
|
return companyId;
|
|
}
|
|
|
|
async function seedParent(companyId: string) {
|
|
const [parent] = await db.insert(issues).values({
|
|
companyId,
|
|
title: "Parent issue",
|
|
status: "todo",
|
|
priority: "medium",
|
|
}).returning();
|
|
return parent;
|
|
}
|
|
|
|
it("replays the existing issue for the same company idempotency key", async () => {
|
|
const companyId = await seedCompany();
|
|
const parent = await seedParent(companyId);
|
|
const app = createApp();
|
|
|
|
const first = await request(app)
|
|
.post(`/api/companies/${companyId}/issues`)
|
|
.send({ parentId: parent.id, title: "Prepare release", idempotencyKey: "run-1:prepare-release" })
|
|
.expect(201);
|
|
const replay = await request(app)
|
|
.post(`/api/companies/${companyId}/issues`)
|
|
.send({
|
|
parentId: parent.id,
|
|
title: "Different retry payload",
|
|
idempotencyKey: "run-1:prepare-release",
|
|
allowDuplicate: true,
|
|
})
|
|
.expect(200);
|
|
|
|
expect(replay.body).toMatchObject({
|
|
id: first.body.id,
|
|
title: "Prepare release",
|
|
deduplicated: true,
|
|
deduplicationReason: "idempotency_key",
|
|
});
|
|
expect(await db.select().from(issueCreateIdempotencyKeys)).toHaveLength(1);
|
|
});
|
|
|
|
it("expires old idempotency keys before replay lookup", async () => {
|
|
const companyId = await seedCompany();
|
|
const parent = await seedParent(companyId);
|
|
const app = createApp();
|
|
const oldIssueId = randomUUID();
|
|
const idempotencyKey = "run-1:expired-retry";
|
|
const expiredCreatedAt = new Date(
|
|
Date.now() - (ISSUE_CREATE_IDEMPOTENCY_KEY_RETENTION_DAYS + 1) * 24 * 60 * 60 * 1000,
|
|
);
|
|
await db.insert(issues).values({
|
|
id: oldIssueId,
|
|
companyId,
|
|
parentId: parent.id,
|
|
title: "Expired retry target",
|
|
status: "todo",
|
|
priority: "medium",
|
|
});
|
|
await db.insert(issueCreateIdempotencyKeys).values({
|
|
companyId,
|
|
idempotencyKey,
|
|
issueId: oldIssueId,
|
|
createdAt: expiredCreatedAt,
|
|
});
|
|
|
|
const recreated = await request(app)
|
|
.post(`/api/companies/${companyId}/issues`)
|
|
.send({ parentId: parent.id, title: "Expired retry creates new work", idempotencyKey })
|
|
.expect(201);
|
|
|
|
const rows = await db.select().from(issueCreateIdempotencyKeys);
|
|
expect(recreated.body.id).not.toBe(oldIssueId);
|
|
expect(rows).toHaveLength(1);
|
|
expect(rows[0]).toMatchObject({
|
|
companyId,
|
|
idempotencyKey,
|
|
issueId: recreated.body.id,
|
|
});
|
|
});
|
|
|
|
it("returns a recent open sibling whose normalized title matches", async () => {
|
|
const companyId = await seedCompany();
|
|
const parent = await seedParent(companyId);
|
|
const app = createApp();
|
|
|
|
const first = await request(app)
|
|
.post(`/api/companies/${companyId}/issues`)
|
|
.send({ parentId: parent.id, title: "Create a single PR" })
|
|
.expect(201);
|
|
const duplicate = await request(app)
|
|
.post(`/api/companies/${companyId}/issues`)
|
|
.send({ parentId: parent.id, title: " create a SINGLE pr " })
|
|
.expect(200);
|
|
|
|
expect(duplicate.body).toMatchObject({
|
|
id: first.body.id,
|
|
deduplicated: true,
|
|
deduplicationReason: "recent_open_title",
|
|
});
|
|
});
|
|
|
|
it("serializes keyed and title-only creates for the same issue", async () => {
|
|
const companyId = await seedCompany();
|
|
const parent = await seedParent(companyId);
|
|
const app = createApp();
|
|
|
|
const [keyed, titleOnly] = await Promise.all([
|
|
request(app)
|
|
.post(`/api/companies/${companyId}/issues`)
|
|
.send({ parentId: parent.id, title: "Coordinate launch", idempotencyKey: "run-2:coordinate-launch" }),
|
|
request(app)
|
|
.post(`/api/companies/${companyId}/issues`)
|
|
.send({ parentId: parent.id, title: "Coordinate launch" }),
|
|
]);
|
|
|
|
expect([keyed.status, titleOnly.status].sort()).toEqual([200, 201]);
|
|
expect(keyed.body.id).toBe(titleOnly.body.id);
|
|
expect([keyed, titleOnly].find((response) => response.status === 200)?.body).toMatchObject({
|
|
deduplicated: true,
|
|
deduplicationReason: "recent_open_title",
|
|
});
|
|
expect(await db.select().from(issues).where(eq(issues.parentId, parent.id))).toHaveLength(1);
|
|
expect(await db.select().from(issueCreateIdempotencyKeys)).toEqual([
|
|
expect.objectContaining({ issueId: keyed.body.id, idempotencyKey: "run-2:coordinate-launch" }),
|
|
]);
|
|
|
|
const replay = await request(app)
|
|
.post(`/api/companies/${companyId}/issues`)
|
|
.send({ parentId: parent.id, title: "Different title", idempotencyKey: "run-2:coordinate-launch" })
|
|
.expect(200);
|
|
expect(replay.body).toMatchObject({
|
|
id: keyed.body.id,
|
|
deduplicated: true,
|
|
deduplicationReason: "idempotency_key",
|
|
});
|
|
});
|
|
|
|
it("allows an explicit duplicate create", async () => {
|
|
const companyId = await seedCompany();
|
|
const parent = await seedParent(companyId);
|
|
const app = createApp();
|
|
|
|
const first = await request(app)
|
|
.post(`/api/companies/${companyId}/issues`)
|
|
.send({ parentId: parent.id, title: "Investigate incident" })
|
|
.expect(201);
|
|
const duplicate = await request(app)
|
|
.post(`/api/companies/${companyId}/issues`)
|
|
.send({ parentId: parent.id, title: "Investigate incident", allowDuplicate: true })
|
|
.expect(201);
|
|
|
|
expect(duplicate.body.id).not.toBe(first.body.id);
|
|
});
|
|
|
|
it("does not apply the route soft guard to internal service creates", async () => {
|
|
const companyId = await seedCompany();
|
|
const parent = await seedParent(companyId);
|
|
const svc = issueService(db);
|
|
|
|
const first = await svc.create(companyId, {
|
|
parentId: parent.id,
|
|
title: "System-generated follow-up",
|
|
status: "todo",
|
|
priority: "medium",
|
|
});
|
|
const second = await svc.create(companyId, {
|
|
parentId: parent.id,
|
|
title: "System-generated follow-up",
|
|
status: "todo",
|
|
priority: "medium",
|
|
});
|
|
|
|
expect(second.id).not.toBe(first.id);
|
|
});
|
|
|
|
it("does not let closed or older issues block a recreate", async () => {
|
|
const companyId = await seedCompany();
|
|
const parent = await seedParent(companyId);
|
|
const app = createApp();
|
|
const oldIssueId = randomUUID();
|
|
const closedIssueId = randomUUID();
|
|
await db.insert(issues).values([
|
|
{
|
|
id: oldIssueId,
|
|
companyId,
|
|
parentId: parent.id,
|
|
title: "Retry old work",
|
|
status: "todo",
|
|
priority: "medium",
|
|
createdAt: new Date(Date.now() - 49 * 60 * 60 * 1000),
|
|
},
|
|
{
|
|
id: closedIssueId,
|
|
companyId,
|
|
parentId: parent.id,
|
|
title: "Retry closed work",
|
|
status: "done",
|
|
priority: "medium",
|
|
},
|
|
]);
|
|
|
|
const recreatedOld = await request(app)
|
|
.post(`/api/companies/${companyId}/issues`)
|
|
.send({ parentId: parent.id, title: "Retry old work" })
|
|
.expect(201);
|
|
const recreatedClosed = await request(app)
|
|
.post(`/api/companies/${companyId}/issues`)
|
|
.send({ parentId: parent.id, title: "Retry closed work" })
|
|
.expect(201);
|
|
|
|
expect(recreatedOld.body.id).not.toBe(oldIssueId);
|
|
expect(recreatedClosed.body.id).not.toBe(closedIssueId);
|
|
});
|
|
|
|
it("stores the request run header on manual creates", async () => {
|
|
const companyId = await seedCompany();
|
|
const parent = await seedParent(companyId);
|
|
const app = createApp();
|
|
const runId = randomUUID();
|
|
const agentId = randomUUID();
|
|
await db.insert(agents).values({
|
|
id: agentId,
|
|
companyId,
|
|
name: "Creating agent",
|
|
role: "engineer",
|
|
status: "active",
|
|
adapterType: "codex_local",
|
|
adapterConfig: {},
|
|
runtimeConfig: {},
|
|
permissions: {},
|
|
});
|
|
await db.insert(heartbeatRuns).values({
|
|
id: runId,
|
|
companyId,
|
|
agentId,
|
|
status: "running",
|
|
});
|
|
|
|
const response = await request(app)
|
|
.post(`/api/companies/${companyId}/issues`)
|
|
.set("X-Paperclip-Run-Id", runId)
|
|
.send({ parentId: parent.id, title: "Attributed create" })
|
|
.expect(201);
|
|
const [created] = await db.select().from(issues).where(eq(issues.id, response.body.id));
|
|
|
|
expect(created.originKind).toBe("manual");
|
|
expect(created.originRunId).toBe(runId);
|
|
});
|
|
});
|