From 0da786fdc359bb73e17f105b8542bbcbd5a7c7f5 Mon Sep 17 00:00:00 2001 From: brianCodes Date: Sat, 5 Dec 2026 03:39:21 -0700 Subject: [PATCH] fix(issues): clear the compact issue-list cache when an issue changes (#17828) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The board reads task lists through `GET /api/companies/:companyId/issues?view=compact` > - The server keeps compact list responses in a short in-memory cache (`ISSUE_LIST_SERVER_CACHE_TTL_MS = 2000`), keyed by actor and query, to absorb request storms (#9190) > - The board refetches its issue lists when it receives an `activity.logged` live event for an issue > - But a create, update or delete does not clear the cache, so the refetch gets the cached list from before the change. The board shows the old value for up to two seconds, and a quick edit seems to snap back > - This pull request clears the cached compact lists of a company when the server publishes an `activity.logged` event for an issue in that company > - The benefit is that a list fetched after a change shows the change, and the cache still absorbs request storms between changes ## Linked Issues or Issue Description **What happened?** I changed the title of a task, and the board refetched the task list immediately. The response had the old title and the header `x-paperclip-request-cache: hit`. The list showed the old title until the board fetched the list again more than two seconds later. The same thing happens for other changes that the compact list shows, for example status, priority and assignee. **Expected behavior** A compact list request that the server receives after a change returns the changed values. The cache can answer repeated requests only while no issue in the company changes. **Steps to reproduce** 1. Start Paperclip with a company and one task. 2. Send `GET /api/companies//issues?view=compact`. 3. Within two seconds, send `PATCH /api/issues/` with `{"title":"After"}`. 4. Within two seconds of step 2, send the request from step 2 again. 5. Before this change, the response has the old title and `x-paperclip-request-cache: hit`. **Paperclip version or commit** `master` at 835966dec8. **Deployment mode** Local development server (`pnpm dev`) with embedded PostgreSQL. The cache is in-process, so the deployment mode does not change the behavior. Refs #9190, which added the cache. I did not find an open issue or pull request for this problem. ## What Changed - `server/src/routes/issues.ts`: each cache entry and each in-flight list computation now records its company. - `server/src/routes/issues.ts`: the issue routes subscribe once, through `subscribeAllCompanyLiveEvents`, to company live events. On an `activity.logged` event with `entityType: "issue"`, the server removes the cached compact lists of that company. It also removes the in-flight computations of that company from the coalescing map, so a new request does not join a computation that started before the change. - `server/src/routes/issues.ts`: a computation that was in flight during the change does not store its result in the cache. - `server/src/__tests__/issue-list-assignee-filter-routes.test.ts`: two embedded PostgreSQL route tests. The first test lists, sends `PATCH /api/issues/:id`, and lists again within the cache lifetime. It expects the new values and a cache `miss`. The second test holds a list computation after it reads the old title. It sends the `PATCH`, and expects that a fresh request does not coalesce with the old computation and caches the new title. Then it releases the old computation, which returns the old title, and expects that the next request is a cache `hit` with the new title. This checks that a stale in-flight result does not replace the fresh cache entry. To hold the computation after its read, the test file wraps `issueService().list` with `vi.mock`. I put the invalidation on the `activity.logged` event because it is the existing signal that an issue changed. Mutations must log activity. Most routes that use a transaction publish the event after the commit. The board already uses this event to refetch its issue lists. One subscription covers every route and service that changes an issue: create, `PATCH`, delete, checkout and release, comments, read marks, and changes that heartbeat runs make. A call in each route would miss some of these paths. The change stays in `routes/issues.ts`, which owns the cache, and it adds no shared contract. The invalidation is event-driven, so it adds no polling. ## Verification - Run `pnpm --filter @paperclipai/server exec vitest run src/__tests__/issue-list-assignee-filter-routes.test.ts`. All 39 tests pass. - Without the change in `issues.ts`, the first new test fails. It gets `hit` instead of `miss`. - With only the `!inflightEntry.invalidated` guard removed, the second new test fails. The old computation writes its stale result over the fresh cache entry, so the next request gets `Before` instead of `After`. The other 38 tests pass. - The existing cache tests still pass: a repeated request without a change still gets `hit`, simultaneous requests still coalesce, cache keys stay separate per user, and the cache stays bounded. - Run `pnpm --filter @paperclipai/server exec tsc --noEmit`. It passes. - The design assumes that each change to an issue publishes `activity.logged` before the next list request. The first new test checks this with a real `PATCH` on embedded PostgreSQL, not a mock. - Locally, I ran only this test file and `tsc --noEmit`, on Windows. I did not run `pnpm -r typecheck`, `pnpm test:run` or `pnpm build`, and I left them to CI. On Windows, the `typecheck` script of the server stops in `prepare:runner-vendor` with `ERR_UNSUPPORTED_ESM_URL_SCHEME`, with or without this change. A wider local run did not finish in 50 minutes. - That wider run showed failures in `server-startup-feedback-export`, `external-chat-wait.integration` and `workspace-recovery`. These files fail in the same way without this change. `muse-control` failed once and then passed except for one test, which also fails without this change. These files do not test the issue-list cache. - No documentation describes this cache, so this change does not update documentation. - To check by hand, follow the steps to reproduce above. After this change, the response in step 4 has the new title and `x-paperclip-request-cache: miss`. ## Risks - Low risk. The change affects only the compact list TTL cache and in-flight coalescing. The `index` and `rows` views do not use the TTL cache, but they get the coalescing change. - The cache absorbs fewer requests while a company has many issue changes, because each change clears the cached lists of that company. Each change already makes the board refetch its lists, so the extra work is one computation per list after each change. Coalescing between changes is the same as before. - If many requests from one client are in flight, the server can answer with a stale cache entry. After a change, that stale entry is gone, so the server answers with its existing retry response instead of old data. - The invalidation is per process. A deployment with more than one server process can still serve a list that is up to two seconds old from another process. This is the same as before this change. - Each issue change scans the cache once to find the entries of the company. The cache holds at most 256 entries (`ISSUE_LIST_SERVER_CACHE_MAX_ENTRIES`), so this cost stays small. - Some services log issue activity inside a transaction and publish the event before the commit. A list request in that short window can cache the old values. The board's own refetch has the same race. - Changes that do not log issue activity, for example a label rename, do not clear the cache. The board does not refetch issue lists for these changes either. > 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 - Anthropic Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. It wrote the change, the tests and this description. A human reviews the change before submission. ## 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 --- .../issue-list-assignee-filter-routes.test.ts | 138 ++++++++++++++++++ server/src/routes/issues.ts | 33 ++++- 2 files changed, 170 insertions(+), 1 deletion(-) 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);