diff --git a/server/src/__tests__/issue-list-assignee-filter-routes.test.ts b/server/src/__tests__/issue-list-assignee-filter-routes.test.ts index ce3d6cd6e1b..baf3eee3513 100644 --- a/server/src/__tests__/issue-list-assignee-filter-routes.test.ts +++ b/server/src/__tests__/issue-list-assignee-filter-routes.test.ts @@ -19,6 +19,28 @@ import { issueRecoveryActionService } from "../services/issue-recovery-actions.j import { ensureHumanRoleDefaultGrants } from "../services/principal-access-compatibility.js"; import { resolveRequiredSuccessfulRunHandoffOnValidPath } from "../services/successful-run-handoff-state.js"; +const issueListReadHooks = vi.hoisted(() => ({ + afterList: null as null | (() => Promise), +})); + +vi.mock("../services/index.js", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + issueService: (...args: Parameters) => { + const svc = actual.issueService(...args); + return { + ...svc, + list: async (...listArgs: Parameters) => { + const rows = await svc.list(...listArgs); + await issueListReadHooks.afterList?.(); + return rows; + }, + }; + }, + }; +}); + const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; @@ -38,6 +60,7 @@ describeEmbeddedPostgres("issue list routes assigneeAgentId filter", () => { }, 20_000); afterEach(async () => { + issueListReadHooks.afterList = null; __clearIssueListResponseCacheForTests(); await db.delete(issues); await db.delete(activityLog); @@ -697,6 +720,121 @@ describeEmbeddedPostgres("issue list routes assigneeAgentId filter", () => { expect(second.headers["x-paperclip-request-cache"]).toBe("hit"); }); + it("refetches the compact issue list after an issue changes within the cache lifetime", async () => { + const companyId = randomUUID(); + const issueId = randomUUID(); + let computeCount = 0; + + await db.insert(companies).values({ + id: companyId, + name: "Paperclip", + issuePrefix: uniqueIssuePrefix(), + requireBoardApprovalForNewAgents: false, + }); + await seedCloudTenantMember(companyId); + await db.insert(issues).values({ + id: issueId, + companyId, + title: "Before", + status: "todo", + priority: "medium", + }); + + const app = createApp(companyId, { + issueListDiagnostics: { + onComputeStart() { + computeCount += 1; + }, + }, + }); + const first = await request(app) + .get(`/api/companies/${companyId}/issues`) + .query({ view: "compact", limit: "20" }); + expect(first.status, JSON.stringify(first.body)).toBe(200); + expect(first.body[0].title).toBe("Before"); + + const patched = await request(app) + .patch(`/api/issues/${issueId}`) + .send({ title: "After", priority: "high" }); + expect(patched.status, JSON.stringify(patched.body)).toBe(200); + + const second = await request(app) + .get(`/api/companies/${companyId}/issues`) + .query({ view: "compact", limit: "20" }); + expect(second.status, JSON.stringify(second.body)).toBe(200); + expect(second.headers["x-paperclip-request-cache"]).toBe("miss"); + expect(second.body[0]).toMatchObject({ title: "After", priority: "high" }); + expect(computeCount).toBe(2); + }); + + it("does not cache a compact issue list read before an issue changes", async () => { + const companyId = randomUUID(); + const issueId = randomUUID(); + let listCount = 0; + let releaseStaleRead!: () => void; + const staleReadReleased = new Promise((resolve) => { + releaseStaleRead = resolve; + }); + let markStaleReadDone!: () => void; + const staleReadDone = new Promise((resolve) => { + markStaleReadDone = resolve; + }); + + await db.insert(companies).values({ + id: companyId, + name: "Paperclip", + issuePrefix: uniqueIssuePrefix(), + requireBoardApprovalForNewAgents: false, + }); + await seedCloudTenantMember(companyId); + await db.insert(issues).values({ + id: issueId, + companyId, + title: "Before", + status: "todo", + priority: "medium", + }); + + issueListReadHooks.afterList = async () => { + listCount += 1; + if (listCount === 1) { + markStaleReadDone(); + await staleReadReleased; + } + }; + const app = createApp(companyId); + const staleRequest = request(app) + .get(`/api/companies/${companyId}/issues`) + .query({ view: "compact", limit: "20" }) + .then((res) => res); + await staleReadDone; + + const patched = await request(app) + .patch(`/api/issues/${issueId}`) + .send({ title: "After" }); + expect(patched.status, JSON.stringify(patched.body)).toBe(200); + + const fresh = await request(app) + .get(`/api/companies/${companyId}/issues`) + .query({ view: "compact", limit: "20" }); + expect(fresh.status, JSON.stringify(fresh.body)).toBe(200); + expect(fresh.headers["x-paperclip-request-cache"]).toBe("miss"); + expect(fresh.body[0].title).toBe("After"); + + releaseStaleRead(); + const stale = await staleRequest; + expect(stale.status, JSON.stringify(stale.body)).toBe(200); + expect(stale.body[0].title).toBe("Before"); + + const next = await request(app) + .get(`/api/companies/${companyId}/issues`) + .query({ view: "compact", limit: "20" }); + expect(next.status, JSON.stringify(next.body)).toBe(200); + expect(next.headers["x-paperclip-request-cache"]).toBe("hit"); + expect(next.body[0].title).toBe("After"); + expect(listCount).toBe(2); + }); + it("bounds compact issue-list server cache entries", async () => { const companyId = randomUUID(); const issueId = randomUUID(); diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index 2019a29d2e9..9e0b8bc5f17 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -46,6 +46,7 @@ import { } from "../services/issue-creation-source.js"; import { activeIssueInteractionCondition, readTaskQuestionContext } from "../services/issue-question-context.js"; import { setIssueTitle } from "../services/issue-title.js"; +import { subscribeAllCompanyLiveEvents } from "../services/live-events.js"; import { setIssueTitleSchema } from "@paperclipai/shared"; import { resolveConfirmationFromComment } from "../services/confirmation-comment-resolution.js"; import { createIssueReadTiming } from "../services/issue-read-timing.js"; @@ -3255,16 +3256,19 @@ type IssueListDiagnostics = { }; type IssueListCacheEntry = { + companyId: string; response: IssueListPreparedResponse; expiresAt: number; staleUntil: number; }; type IssueListInflightEntry = { + companyId: string; promise: Promise; startedAt: number; waiterCount: number; stormLogged: boolean; + invalidated: boolean; }; const issueListResponseCache = new Map(); @@ -3279,6 +3283,29 @@ export function __clearIssueListResponseCacheForTests() { issueListResponseCache.clear(); } +function invalidateCompanyIssueListResponses(companyId: string) { + for (const [key, entry] of issueListResponseCache) { + if (entry.companyId === companyId) issueListResponseCache.delete(key); + } + for (const [key, entry] of issueListInflight) { + if (entry.companyId !== companyId) continue; + entry.invalidated = true; + issueListInflight.delete(key); + } +} + +let issueListInvalidationSubscribed = false; + +function subscribeIssueListInvalidation() { + if (issueListInvalidationSubscribed) return; + issueListInvalidationSubscribed = true; + subscribeAllCompanyLiveEvents((event) => { + if (event.type === "activity.logged" && event.payload.entityType === "issue") { + invalidateCompanyIssueListResponses(event.companyId); + } + }); +} + function shortHash(value: string): string { return createHash("sha256").update(value).digest("base64url").slice(0, 16); } @@ -3604,10 +3631,12 @@ async function coordinateIssueListGet(input: { return input.compute(); })(); const inflightEntry: IssueListInflightEntry = { + companyId: input.companyId, promise, startedAt: now, waiterCount: 0, stormLogged: false, + invalidated: false, }; issueListInflight.set(input.requestKey.key, inflightEntry); // Mine reads its primary rows before its optional context has necessarily @@ -3624,8 +3653,9 @@ async function coordinateIssueListGet(input: { try { const response = await promise; - if (input.allowTtlCache) { + if (input.allowTtlCache && !inflightEntry.invalidated) { setIssueListResponseCacheEntry(input.requestKey.key, { + companyId: input.companyId, response, expiresAt: Date.now() + ISSUE_LIST_SERVER_CACHE_TTL_MS, staleUntil: Date.now() + ISSUE_LIST_SERVER_CACHE_STALE_MS, @@ -3758,6 +3788,7 @@ export function issueRoutes( }) => Promise; } = {}, ) { + subscribeIssueListInvalidation(); const router = Router(); const svc = issueService(db); const runRedactions = createRunSecretRedactionRegistry(db);