From 163d9f323c2e7e723fa4d594e69d7c234e93bbe3 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:42:06 -0600 Subject: [PATCH 1/2] perf(github): reuse repository installation tokens until shortly before expiry (#21641) 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 GitHub chat channel lets an agent review pull requests and answer comments through a GitHub App > - Each GitHub call gets a repository-scoped installation token from `githubBotRepositoryToken` > - That function minted a new token on every call. To mint, it resolved every App secret through the secret service, and each resolution wrote one audit row > - The review-check head poll calls it about every 5 minutes for each waiting check. On staging this made the secret audit insert one of the busiest statements in the database > - This pull request keeps a minted token in memory until shortly before it expires, and checks the connection's current state on every call > - The benefit is far fewer database writes and reads, fewer GitHub token mints, and an audit log that records real secret use ## Linked Issues or Issue Description **What happened?** On paperclip.staging (commit a18479bbba, measured at 19:05Z on 2026-11-14), `secret_access_events` got about 285 rows in 60 s. These were 44 resolutions each of the GitHub App connection's `credentials.appId`, `privateKey`, `installationId`, `webhookSecret`, `clientId` and `clientSecret` (+21 `slug`), with `consumer_type` `tool_connection` and actor `system`. That is about 4.7 audit inserts/s. The matching `secret_versions` and binding reads ran at about 3.6/s each in Neon. These were among the busiest statements on the database. **Expected behavior** A GitHub installation token is valid for one hour. Paperclip should reuse it and resolve the App secrets only when it mints a new token. **Steps to reproduce** 1. Connect a GitHub App chat endpoint and get pull request reviews into the `received` review-check state (staging had 84 `github_review_check` actions). 2. Let the review-check worker poll the pull request head (23 polls/min measured on staging). 3. Count `secret_access_events` rows per minute. Each poll adds one row per App secret and mints a new token at GitHub. **Paperclip version or commit** master at a18479bbba (the commit serving paperclip.staging at the time of measurement). **Where in the code** `githubBotRepositoryToken` in `server/src/services/chat-github-client.ts`. Callers: `chat-github-checks.ts` (review-check head poll), `chat-github-response-comments.ts` and `chat-github-reviews.ts`. ## What Changed - `githubBotRepositoryToken` keeps a minted token in a per-process, in-memory cache (at most 512 entries, least recently used first out). It never persists or logs tokens. - The cache uses the token until 5 minutes before GitHub's `expires_at` (capped at one hour). If GitHub does not give a usable expiry, the token is not kept. - The cache key holds the company, endpoint, repository id, the exact permission set, and an authority revision. The revision holds the connection id, the endpoint's runtime generation (pause, revoke and availability changes advance it), and for each mint credential its secret ref, version selector, secret status, current version, `updatedAt`, and binding. The installation id is a secret, so its secret ref and version identify it in the key. - Each call reads the current authority from the database in two narrow statements: one row from the endpoint and connection join (status, enabled, refs, runtime generation), and the three mint secrets with their bindings (status and version columns only, no secret values). The endpoint and connection status checks run on every call, as before. - If a status check fails, all cached tokens for that endpoint are dropped. A token cannot survive a revoke, pause, disable or credential change. - Secrets are resolved only when a token is minted, and only the three that minting uses (`appId`, `privateKey`, `installationId`). So the audit log gets three rows per mint instead of one row per App secret per call. - New `githubBotRepositoryClient` sends repository requests. If GitHub returns 401 for a cached token, it drops that token, mints a new one, and sends the request once more. A 401 for a newly minted token is not retried. The review-check, response-comment and review paths use this client. - The token policy stays in the GitHub chat client module (`rules/module-boundaries.mdc`). The callers only change how they get a request function. ## Verification - New test file `server/src/__tests__/github-repository-token-cache.test.ts` (embedded Postgres, real secret service, mocked GitHub fetch): - `mints once and resolves the App's secrets only when it mints`: red on master (second call minted `installation-token-2`), green now. It also checks that only the three mint secrets are audited. - `refreshes a token shortly before GitHub's expiry`: reused at +54 min, minted again at +56 min. - `never keeps a token GitHub issues for less than the safety margin` - `mints again after a credential rotation and uses the new credential`: rotates the installation id secret and checks that the new mint uses it. - `mints again after the connection's credential refs change` - `never serves a cached token across a pause, revoke or disabled connection`: includes a pause and resume with no call in between. - `mints a separate token for each repository` - `replaces a cached token GitHub rejects and retries the request once`: also checks that a 401 for a new token is not retried. - On master, 5 of the 8 tests fail. All 8 pass with this change. - Focused suites pass locally: every server test file that matches `github`, plus `chat-sdk-runtime.adapters`, `chat-provider-inventory`, `idle-completed-history` and `connection-management.integration` (41 of 42 files, 955 of 956 tests). The one failure, `github-connection-enrollment-work.test.ts`, also fails on unchanged master (`expected +0 to be 1`), so this change did not cause it. - `pnpm --filter @paperclipai/server typecheck` passes. - CI supplies the full typecheck, build and test coverage for the final revision. ## Risks - Low risk. A cached token is used only while the endpoint, connection and mint secrets are unchanged, and the status checks still read current database state on every call. - A GitHub-side revoke of a token (for example, an App uninstall) makes GitHub return 401. The client then mints again once. If the installation is gone, the mint fails as before. - The cache is per process. Each server process mints its own token, at most once per hour per repository and permission set. - Two concurrent first calls for the same key can both mint. This is the same as before and is rare. - No schema, migration or API change. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edit, test runs). ## 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 - [x] 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 --- .../github-repository-token-cache.test.ts | 217 ++++++++++++ server/src/services/chat-github-checks.ts | 12 +- server/src/services/chat-github-client.ts | 333 ++++++++++++++++-- .../services/chat-github-response-comments.ts | 6 +- server/src/services/chat-github-reviews.ts | 6 +- 5 files changed, 522 insertions(+), 52 deletions(-) create mode 100644 server/src/__tests__/github-repository-token-cache.test.ts diff --git a/server/src/__tests__/github-repository-token-cache.test.ts b/server/src/__tests__/github-repository-token-cache.test.ts new file mode 100644 index 00000000000..457838bb1d8 --- /dev/null +++ b/server/src/__tests__/github-repository-token-cache.test.ts @@ -0,0 +1,217 @@ +import { generateKeyPairSync, randomUUID } from "node:crypto"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { and, eq, sql } from "drizzle-orm"; +import { + agents, + chatEndpoints, + companies, + companySecretBindings, + createDb, + secretAccessEvents, + toolApplications, + toolConnections, +} from "@paperclipai/db"; +import type { ToolCredentialSecretRef } from "@paperclipai/shared"; +import { + githubBotRepositoryClient, + githubBotRepositoryToken, +} from "../services/chat-github-client.js"; +import { secretService } from "../services/secrets.js"; +import { + getEmbeddedPostgresTestSupport, + startEmbeddedPostgresTestDatabase, +} from "./helpers/embedded-postgres.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const describeDatabase = support.supported ? describe : describe.skip; + +const { privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 }); +const privateKeyPem = privateKey.export({ type: "pkcs8", format: "pem" }).toString(); +const HOUR = 60 * 60_000; + +describeDatabase("GitHub repository token reuse", () => { + let database: Awaited>; + let db: ReturnType; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("paperclip-github-token-cache-"); + db = createDb(database.connectionString); + }, 30_000); + afterEach(() => vi.restoreAllMocks()); + afterAll(async () => { + await db?.$client.end({ timeout: 0 }); + await database?.cleanup(); + }); + + async function fixture() { + const companyId = randomUUID(), applicationId = randomUUID(), connectionId = randomUUID(), endpointId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "GitHub token reuse", issuePrefix: randomUUID().slice(0, 8).toUpperCase() }); + const agentId = randomUUID(); + await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", adapterType: "process" }); + await db.insert(toolApplications).values({ id: applicationId, companyId, name: "GitHub", type: "chat" }); + const secrets = secretService(db); + const values = { appId: "1234", privateKey: privateKeyPem, installationId: "2468", webhookSecret: "webhook-secret" }; + const refs: ToolCredentialSecretRef[] = []; + const secretIds: Record = {}; + for (const [key, value] of Object.entries(values)) { + const secret = await secrets.create(companyId, { + name: `github.${key}.${randomUUID().slice(0, 8)}`, + key: `CHAT_GITHUB_${key}_${randomUUID()}`.replaceAll("-", "_").toUpperCase(), + provider: "local_encrypted", + value, + }); + secretIds[key] = secret.id; + refs.push({ secretId: secret.id, versionSelector: "latest", configPath: `credentials.${key}`, required: true }); + } + await db.insert(toolConnections).values({ id: connectionId, companyId, applicationId, name: "GitHub", uid: connectionId, + transport: "chat_sdk", connectionPurpose: "channel", enabled: true, status: "active", credentialSecretRefs: refs }); + await db.insert(companySecretBindings).values(refs.map(ref => ({ companyId, secretId: ref.secretId, + targetType: "tool_connection", targetId: connectionId, configPath: ref.configPath }))); + await db.insert(chatEndpoints).values({ id: endpointId, companyId, connectionId, provider: "github", + publicId: endpointId, assignedAgentId: agentId, status: "active" }); + + const mints: Array<{ installationId: string; repositoryIds: number[]; permissions: unknown }> = []; + const requests: Array<{ path: string; token: string }> = []; + const rejected = new Set(); + let expiresIn = HOUR; + const fetchImpl = vi.fn(async (input: string | URL | Request, init?: RequestInit) => { + const url = new URL(String(input)); + const token = String(new Headers(init?.headers).get("authorization") ?? "").replace(/^Bearer /, ""); + const mint = url.pathname.match(/^\/app\/installations\/(\d+)\/access_tokens$/); + if (mint) { + const body = JSON.parse(String(init?.body)) as { repository_ids: number[]; permissions: unknown }; + mints.push({ installationId: mint[1]!, repositoryIds: body.repository_ids, permissions: body.permissions }); + return Response.json({ token: `installation-token-${mints.length}`, + expires_at: new Date(Date.now() + expiresIn).toISOString() }, { status: 201 }); + } + requests.push({ path: url.pathname, token }); + if (rejected.has(token)) return Response.json({ message: "Bad credentials" }, { status: 401 }); + return Response.json({ head: { sha: "abc" } }); + }) as unknown as typeof fetch & ReturnType; + const audits = async () => (await db.select({ configPath: secretAccessEvents.configPath }).from(secretAccessEvents) + .where(and(eq(secretAccessEvents.companyId, companyId), eq(secretAccessEvents.consumerId, connectionId)))) + .map(row => row.configPath).sort(); + const token = (repositoryId = "101") => githubBotRepositoryToken(db, companyId, endpointId, repositoryId, fetchImpl); + return { companyId, connectionId, endpointId, secretIds, mints, requests, rejected, fetchImpl, audits, token, + setExpiresIn: (ms: number) => { expiresIn = ms; } }; + } + + it("mints once and resolves the App's secrets only when it mints", async () => { + const f = await fixture(); + const first = await f.token(); + const second = await f.token(); + expect(second).toBe(first); + expect(f.mints).toEqual([{ installationId: "2468", repositoryIds: [101], + permissions: { contents: "read", metadata: "read", issues: "write", pull_requests: "write", checks: "write" } }]); + // One audited read per mint credential; the webhook secret is never read to mint. + expect(await f.audits()).toEqual(["credentials.appId", "credentials.installationId", "credentials.privateKey"]); + }); + + it("refreshes a token shortly before GitHub's expiry", async () => { + const f = await fixture(); + const start = Date.now(); + const now = vi.spyOn(Date, "now").mockReturnValue(start); + const first = await f.token(); + now.mockReturnValue(start + 54 * 60_000); + expect(await f.token()).toBe(first); + now.mockReturnValue(start + 56 * 60_000); + const refreshed = await f.token(); + expect(refreshed).not.toBe(first); + expect(f.mints).toHaveLength(2); + expect(await f.token()).toBe(refreshed); + }); + + it("never keeps a token GitHub issues for less than the safety margin", async () => { + const f = await fixture(); + f.setExpiresIn(2 * 60_000); + await f.token(); + await f.token(); + expect(f.mints).toHaveLength(2); + }); + + it("mints again after a credential rotation and uses the new credential", async () => { + const f = await fixture(); + const first = await f.token(); + await secretService(db).rotate(f.secretIds.installationId!, { value: "1357" }); + const rotated = await f.token(); + expect(rotated).not.toBe(first); + expect(f.mints.map(mint => mint.installationId)).toEqual(["2468", "1357"]); + expect(await f.token()).toBe(rotated); + expect(f.mints).toHaveLength(2); + }); + + it("mints again after the connection's credential refs change", async () => { + const f = await fixture(); + const first = await f.token(); + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, f.connectionId)); + // Same secrets under a pinned version: a different authority, so a different token. + await db.update(toolConnections).set({ credentialSecretRefs: connection!.credentialSecretRefs + .map(ref => ({ ...ref, versionSelector: 1 })) }).where(eq(toolConnections.id, f.connectionId)); + expect(await f.token()).not.toBe(first); + expect(f.mints).toHaveLength(2); + }); + + it("never serves a cached token across a pause, revoke or disabled connection", async () => { + const f = await fixture(); + const endpoint = eq(chatEndpoints.id, f.endpointId); + const first = await f.token(); + + await db.update(chatEndpoints).set({ status: "paused" }).where(endpoint); + await expect(f.token()).rejects.toThrow("GitHub bot connection is unavailable"); + await db.update(chatEndpoints).set({ status: "active" }).where(endpoint); + const afterPause = await f.token(); + expect(afterPause).not.toBe(first); + + // A pause and resume with no call in between still drops the token: pausing + // advances the endpoint's runtime generation. + await db.update(chatEndpoints).set({ status: "paused", + setup: sql`jsonb_set(${chatEndpoints.setup}, '{runtimeGeneration}', to_jsonb(coalesce((${chatEndpoints.setup}->>'runtimeGeneration')::int, 0) + 1))` }) + .where(endpoint); + await db.update(chatEndpoints).set({ status: "active" }).where(endpoint); + const afterResume = await f.token(); + expect(afterResume).not.toBe(afterPause); + + await db.update(toolConnections).set({ enabled: false }).where(eq(toolConnections.id, f.connectionId)); + await expect(f.token()).rejects.toThrow("GitHub bot connection is not active"); + await db.update(toolConnections).set({ enabled: true }).where(eq(toolConnections.id, f.connectionId)); + const afterDisable = await f.token(); + expect(afterDisable).not.toBe(afterResume); + + await db.update(chatEndpoints).set({ status: "revoked" }).where(endpoint); + await expect(f.token()).rejects.toThrow("GitHub bot connection is unavailable"); + expect(f.mints).toHaveLength(4); + }); + + it("mints a separate token for each repository", async () => { + const f = await fixture(); + const first = await f.token("101"); + const second = await f.token("202"); + expect(second).not.toBe(first); + expect(await f.token("101")).toBe(first); + expect(await f.token("202")).toBe(second); + expect(f.mints.map(mint => mint.repositoryIds)).toEqual([[101], [202]]); + }); + + it("replaces a cached token GitHub rejects and retries the request once", async () => { + const f = await fixture(); + const cached = await f.token(); + f.rejected.add(cached); + const request = await githubBotRepositoryClient(db, f.companyId, f.endpointId, "101", f.fetchImpl); + await expect(request<{ head: { sha: string } }>("/repos/o/r/pulls/1")).resolves.toEqual({ head: { sha: "abc" } }); + expect(f.requests).toEqual([ + { path: "/repos/o/r/pulls/1", token: cached }, + { path: "/repos/o/r/pulls/1", token: "installation-token-2" }, + ]); + // The replacement is the cached token from now on. + expect(await f.token()).toBe("installation-token-2"); + expect(f.mints).toHaveLength(2); + + // A freshly minted token that GitHub rejects is not retried. + const other = await fixture(); + other.rejected.add("installation-token-1"); + const fresh = await githubBotRepositoryClient(db, other.companyId, other.endpointId, "101", other.fetchImpl); + await expect(fresh("/repos/o/r/pulls/1")).rejects.toMatchObject({ details: { providerStatus: 401 } }); + expect(other.requests).toHaveLength(1); + expect(other.mints).toHaveLength(1); + }); +}); diff --git a/server/src/services/chat-github-checks.ts b/server/src/services/chat-github-checks.ts index be799375918..5a273636fa6 100644 --- a/server/src/services/chat-github-checks.ts +++ b/server/src/services/chat-github-checks.ts @@ -17,7 +17,7 @@ import { import type { GitHubReviewEventContext } from "@paperclipai/shared"; import { runtimePublicOrigin } from "./cloud-runtime-identity.js"; import { - githubBotRepositoryToken, + githubBotRepositoryClient, githubBotRequest, } from "./chat-github-client.js"; @@ -132,7 +132,7 @@ export function githubReviewCheckService(db: Db, fetchImpl = fetch) { : state === "running" ? "Agent is reviewing this commit" : "Waiting for the assigned agent"; - const token = await githubBotRepositoryToken( + const github = await githubBotRepositoryClient( db, action.companyId, action.endpointId, @@ -143,13 +143,7 @@ export function githubReviewCheckService(db: Db, fetchImpl = fetch) { const request = ( path: string, options?: Parameters[3], - ) => - githubBotRequest( - lease.fetch, - token, - `${prefix}${path}`, - options, - ); + ) => github(`${prefix}${path}`, options); const current = await request<{ head: { sha: string } }>( `/pulls/${event.pullNumber}`, ); diff --git a/server/src/services/chat-github-client.ts b/server/src/services/chat-github-client.ts index 65d93445111..25a1ea893e9 100644 --- a/server/src/services/chat-github-client.ts +++ b/server/src/services/chat-github-client.ts @@ -1,8 +1,14 @@ import { createPrivateKey, createSign } from "node:crypto"; -import { and, eq } from "drizzle-orm"; -import { chatEndpoints, toolConnections, type Db } from "@paperclipai/db"; +import { and, eq, inArray, sql } from "drizzle-orm"; +import { + chatEndpoints, + companySecretBindings, + companySecrets, + toolConnections, + type Db, +} from "@paperclipai/db"; import { secretService } from "./secrets.js"; -import { conflict, forbidden, unprocessable } from "../errors.js"; +import { HttpError, conflict, forbidden, unprocessable } from "../errors.js"; import { githubPublicationRetry, githubProviderRetry, GITHUB_INLINE_RETRY_WINDOW_MS, GITHUB_INLINE_MAX_ATTEMPTS } from "./chat-channels/github/retry.js"; export function githubAppJwt( @@ -200,7 +206,238 @@ export async function githubBotCredentials( }; } -/** Least-privilege short-lived token restricted to the single task repository. */ +const GITHUB_REPOSITORY_TOKEN_PERMISSIONS = { + contents: "read", + metadata: "read", + issues: "write", + pull_requests: "write", + checks: "write", +} as const; +/** Only these secrets are needed to mint; the App's other credentials are not read here. */ +const GITHUB_MINT_CREDENTIALS = ["appId", "privateKey", "installationId"] as const; +const GITHUB_REPOSITORY_TOKEN_REFRESH_MARGIN_MS = 5 * 60_000; +const GITHUB_REPOSITORY_TOKEN_MAX_LIFETIME_MS = 60 * 60_000; +const GITHUB_REPOSITORY_TOKEN_CACHE_LIMIT = 512; + +type CachedRepositoryToken = { token: string; endpointId: string; refreshAt: number }; +type RepositoryToken = { token: string; key: string; cached: boolean }; + +// Per process and in memory only. Tokens are never persisted or logged. +const repositoryTokens = new Map(); + +function forgetEndpointRepositoryTokens(endpointId: string) { + for (const [key, entry] of repositoryTokens) + if (entry.endpointId === endpointId) repositoryTokens.delete(key); +} + +function rememberRepositoryToken(key: string, entry: CachedRepositoryToken) { + repositoryTokens.delete(key); + if (repositoryTokens.size >= GITHUB_REPOSITORY_TOKEN_CACHE_LIMIT) { + const now = Date.now(); + for (const [stale, cached] of repositoryTokens) + if (cached.refreshAt <= now) repositoryTokens.delete(stale); + } + // Map order is least recently used first. + for (const oldest of repositoryTokens.keys()) { + if (repositoryTokens.size < GITHUB_REPOSITORY_TOKEN_CACHE_LIMIT) break; + repositoryTokens.delete(oldest); + } + repositoryTokens.set(key, entry); +} + +/** + * Current minting authority, read from the database on every call. The + * revision covers everything that changes what a token may do: the endpoint's + * runtime generation (bumped on pause, revoke and availability changes), the + * connection, and each mint credential's secret ref, selected version, state + * and binding. Any change makes every token cached under the old revision + * unreachable. Secret values are not read here. + */ +async function githubBotRepositoryAuthority( + db: Db, + companyId: string, + endpointId: string, +) { + const [row] = await db + .select({ + endpointStatus: chatEndpoints.status, + runtimeGeneration: sql`${chatEndpoints.setup}->'runtimeGeneration'`, + connectionId: toolConnections.id, + enabled: toolConnections.enabled, + connectionStatus: toolConnections.status, + refs: toolConnections.credentialSecretRefs, + }) + .from(chatEndpoints) + .innerJoin( + toolConnections, + and( + eq(toolConnections.id, chatEndpoints.connectionId), + eq(toolConnections.companyId, companyId), + ), + ) + .where( + and( + eq(chatEndpoints.companyId, companyId), + eq(chatEndpoints.id, endpointId), + eq(chatEndpoints.provider, "github"), + ), + ); + if (!row || ["archived", "revoked", "paused"].includes(row.endpointStatus)) + throw conflict("GitHub bot connection is unavailable"); + const [appId, privateKey, installationId] = GITHUB_MINT_CREDENTIALS.map( + (key) => row.refs.find((ref) => ref.configPath === `credentials.${key}`), + ); + if (!appId || !privateKey) + throw conflict("Connect the GitHub App before continuing"); + if ( + !row.enabled || + row.connectionStatus !== "active" || + !["active", "verifying"].includes(row.endpointStatus) + ) + throw conflict("GitHub bot connection is not active"); + if (!installationId) throw conflict("Verify the GitHub App installation first"); + const refs = [appId, privateKey, installationId]; + const secrets = await db + .select({ + id: companySecrets.id, + status: companySecrets.status, + latestVersion: companySecrets.latestVersion, + updatedAt: companySecrets.updatedAt, + bindingId: companySecretBindings.id, + bindingPath: companySecretBindings.configPath, + bindingSelector: companySecretBindings.versionSelector, + bindingUpdatedAt: companySecretBindings.updatedAt, + }) + .from(companySecrets) + .leftJoin( + companySecretBindings, + and( + eq(companySecretBindings.secretId, companySecrets.id), + eq(companySecretBindings.companyId, companyId), + eq(companySecretBindings.targetType, "tool_connection"), + eq(companySecretBindings.targetId, row.connectionId), + ), + ) + .where( + and( + eq(companySecrets.companyId, companyId), + inArray(companySecrets.id, [...new Set(refs.map((ref) => ref.secretId))]), + ), + ); + const revision = JSON.stringify([ + row.connectionId, + row.runtimeGeneration ?? 0, + refs.map((ref) => { + const selector = ref.versionSelector ?? "latest"; + const secret = secrets.find((candidate) => candidate.id === ref.secretId); + const binding = secrets.find( + (candidate) => + candidate.id === ref.secretId && candidate.bindingPath === ref.configPath, + ); + return [ + ref.configPath, + ref.secretId, + selector, + secret + ? [ + secret.status, + selector === "latest" ? secret.latestVersion : selector, + secret.updatedAt.getTime(), + ] + : null, + binding + ? [binding.bindingId, binding.bindingSelector, binding.bindingUpdatedAt?.getTime()] + : null, + ]; + }), + ]); + return { connectionId: row.connectionId, refs, revision }; +} + +async function githubBotRepositoryTokenFor( + db: Db, + companyId: string, + endpointId: string, + repositoryId: string, + fetchImpl: typeof fetch, + options: { refresh?: boolean } = {}, +): Promise { + let authority: Awaited>; + try { + authority = await githubBotRepositoryAuthority(db, companyId, endpointId); + } catch (error) { + // A connection that cannot mint must not keep its earlier tokens either. + forgetEndpointRepositoryTokens(endpointId); + throw error; + } + if (!/^[1-9][0-9]*$/.test(repositoryId) || !Number.isSafeInteger(Number(repositoryId))) + throw conflict("Verify the GitHub App installation first"); + const key = JSON.stringify([ + companyId, + endpointId, + repositoryId, + GITHUB_REPOSITORY_TOKEN_PERMISSIONS, + authority.revision, + ]); + const cached = repositoryTokens.get(key); + if (cached && !options.refresh && cached.refreshAt > Date.now()) { + rememberRepositoryToken(key, cached); + return { token: cached.token, key, cached: true }; + } + if (cached) repositoryTokens.delete(key); + // Resolve (and audit) the App's secrets only when a token is actually minted. + const secrets = secretService(db); + const values: string[] = []; + for (const ref of authority.refs) + values.push( + await secrets.resolveSecretValue( + companyId, + ref.secretId, + ref.versionSelector ?? "latest", + { + consumerType: "tool_connection", + consumerId: authority.connectionId, + configPath: ref.configPath, + actorType: "system", + actorId: null, + }, + ), + ); + const [appId, privateKey, installationId] = values; + if (!appId || !privateKey) + throw conflict("Connect the GitHub App before continuing"); + if (!installationId) throw conflict("Verify the GitHub App installation first"); + const issued = await githubBotRequest<{ token?: string; expires_at?: string }>( + fetchImpl, + githubAppJwt(appId, privateKey), + `/app/installations/${encodeURIComponent(installationId)}/access_tokens`, + { + method: "POST", + body: { + repository_ids: [Number(repositoryId)], + permissions: GITHUB_REPOSITORY_TOKEN_PERMISSIONS, + }, + }, + ); + if (!issued.token) + throw unprocessable("GitHub did not issue an installation token"); + const now = Date.now(); + const refreshAt = + Math.min( + Date.parse(issued.expires_at ?? ""), + now + GITHUB_REPOSITORY_TOKEN_MAX_LIFETIME_MS, + ) - GITHUB_REPOSITORY_TOKEN_REFRESH_MARGIN_MS; + // Without a usable expiry the token serves this call only. + if (Number.isFinite(refreshAt) && refreshAt > now) + rememberRepositoryToken(key, { token: issued.token, endpointId, refreshAt }); + return { token: issued.token, key, cached: false }; +} + +/** + * Least-privilege short-lived token restricted to the single task repository. + * Reused until shortly before GitHub's expiry while the connection's current + * authority is unchanged. + */ export async function githubBotRepositoryToken( db: Db, companyId: string, @@ -208,38 +445,60 @@ export async function githubBotRepositoryToken( repositoryId: string, fetchImpl = fetch, ) { - const result = await githubBotCredentials(db, companyId, endpointId); - if ( - !result.connection.enabled || - result.connection.status !== "active" || - !["active", "verifying"].includes(result.endpoint.status) - ) - throw conflict("GitHub bot connection is not active"); - if ( - !result.credentials.installationId || - !/^[1-9][0-9]*$/.test(repositoryId) || - !Number.isSafeInteger(Number(repositoryId)) - ) - throw conflict("Verify the GitHub App installation first"); - const issued = await githubBotRequest<{ token?: string }>( - fetchImpl, - result.appJwt, - `/app/installations/${encodeURIComponent(result.credentials.installationId)}/access_tokens`, - { - method: "POST", - body: { - repository_ids: [Number(repositoryId)], - permissions: { - contents: "read", - metadata: "read", - issues: "write", - pull_requests: "write", - checks: "write", - }, - }, - }, + return ( + await githubBotRepositoryTokenFor(db, companyId, endpointId, repositoryId, fetchImpl) + ).token; +} + +export type GitHubBotRepositoryRequest = ( + path: string, + options?: Parameters[3], +) => Promise; + +function githubUnauthorized(error: unknown) { + return ( + error instanceof HttpError && + !!error.details && + typeof error.details === "object" && + (error.details as { providerStatus?: unknown }).providerStatus === 401 ); - if (!issued.token) - throw unprocessable("GitHub did not issue an installation token"); - return issued.token; +} + +/** + * GitHub requests with a repository token. When GitHub rejects a cached token + * (401), that token is dropped and the request is sent once more with a newly + * minted one. GitHub did not act on the rejected request, so the retry is safe. + */ +export async function githubBotRepositoryClient( + db: Db, + companyId: string, + endpointId: string, + repositoryId: string, + fetchImpl = fetch, +): Promise { + let current = Promise.resolve( + await githubBotRepositoryTokenFor(db, companyId, endpointId, repositoryId, fetchImpl), + ); + return async (path: string, options?: Parameters[3]) => { + const used = current; + const issued = await used; + try { + return await githubBotRequest(fetchImpl, issued.token, path, options); + } catch (error) { + if (!issued.cached || !githubUnauthorized(error)) throw error; + if (current === used) { + if (repositoryTokens.get(issued.key)?.token === issued.token) + repositoryTokens.delete(issued.key); + current = githubBotRepositoryTokenFor( + db, + companyId, + endpointId, + repositoryId, + fetchImpl, + { refresh: true }, + ); + } + return githubBotRequest(fetchImpl, (await current).token, path, options); + } + }; } diff --git a/server/src/services/chat-github-response-comments.ts b/server/src/services/chat-github-response-comments.ts index 2bb0ecbc5c1..a69812614bf 100644 --- a/server/src/services/chat-github-response-comments.ts +++ b/server/src/services/chat-github-response-comments.ts @@ -13,7 +13,7 @@ import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator. import { conflict, forbidden, HttpError } from "../errors.js"; import { githubChatPrincipalAccess } from "./chat-github-access.js"; import { githubAutomaticAdmission } from "./chat-github-events.js"; -import { githubBotRepositoryToken, githubBotRequest } from "./chat-github-client.js"; +import { githubBotRepositoryClient } from "./chat-github-client.js"; import { withGitHubPublicationLease } from "./chat-github-publication-lease.js"; import { projectSafeChatPublicationText } from "./chat-publication-projection.js"; import type { GitHubAutomaticPolicyContext } from "./chat-github-review-policy.js"; @@ -276,9 +276,9 @@ export function githubResponseCommentService(db: Db, fetchImpl = fetch) { ["pending", "retry"].includes(fast.publicationState ?? ""))))) return; } } - const token = await githubBotRepositoryToken(db, source.endpoint.companyId, source.endpoint.id, source.repositoryId, lease.fetch); + const github = await githubBotRepositoryClient(db, source.endpoint.companyId, source.endpoint.id, source.repositoryId, lease.fetch); const prefix = `/repos/${source.repository.split("/").map(encodeURIComponent).join("/")}`; - const api: Api = { request: (path, options) => githubBotRequest(lease.fetch, token, `${prefix}${path}`, options) }; + const api: Api = { request: (path, options) => github(`${prefix}${path}`, options) }; if (onlyExisting && !(await findResponseComment(source, api))) { const existing = await stageResponse(db, source); await lease.commit(async tx => { await tx.update(chatActions).set({ status: "cancelled", result: { final: true, code: "run_already_answered" }, updatedAt: new Date() }).where(eq(chatActions.id, existing.id)); }); diff --git a/server/src/services/chat-github-reviews.ts b/server/src/services/chat-github-reviews.ts index 77d4477fb20..ddd190aba1b 100644 --- a/server/src/services/chat-github-reviews.ts +++ b/server/src/services/chat-github-reviews.ts @@ -43,7 +43,7 @@ import { } from "@paperclipai/shared"; import { HttpError, conflict, forbidden, notFound } from "../errors.js"; import { - githubBotRepositoryToken, + githubBotRepositoryClient, githubBotRequest, } from "./chat-github-client.js"; import { githubChatPrincipalAccess } from "./chat-github-access.js"; @@ -316,7 +316,7 @@ export function githubChatReviewService(db: Db, fetchImpl = fetch) { source: Awaited>, requestFetch = fetchImpl, ) { - const token = await githubBotRepositoryToken( + const github = await githubBotRepositoryClient( db, source.endpoint.companyId, source.endpoint.id, @@ -330,7 +330,7 @@ export function githubChatReviewService(db: Db, fetchImpl = fetch) { path: string, options?: Parameters[3], ) => - githubBotRequest(requestFetch, token, `${prefix}${path}`, options), + github(`${prefix}${path}`, options), }; } async function reviewForHead( From 95a6ab31e606a8ffe7dd59e3ac65666688078806 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:54:00 -0600 Subject: [PATCH 2/2] feat(db): attribute work signals by caller behind a debug flag (#21640) 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 > - Background queues wake from work signals. A transaction calls `signalDatabaseWork(topic, hint)`, and the delivery coordinator wakes the queue for that topic with that hint. > - On a hosted instance with zero runs, the stranded-assignment recovery queue re-checks tasks about 7 times a second. About 2.6 hinting commits per second drive it. HTTP traffic, chat review polls and local fixtures with all heartbeat workers do not explain the writer. > - Statement statistics show what runs, but not who signalled it. Nothing records the caller of a work signal or why a queue woke. > - This pull request adds an opt-in attribution log for work signals and recovery-queue wakes, off by default. > - The benefit is that one short run on an affected instance names the writer of any idle signal loop, without code changes. ## Linked Issues or Issue Description No issue exists. This describes the gap with the fields of `.github/ISSUE_TEMPLATE/enhancement.yml`. **What existing behavior does this improve?** Observability of `signalDatabaseWork` (`packages/db/src/work-signals.ts`) and of the issue recovery queues (`server/src/services/recovery/work.ts`). **Current behavior** A queue that wakes several times a second at idle shows up only as repeated statements. Nothing tells you which caller published the hint, whether the wake came from another process, a reconnect, a direct settled publish or a stored deadline, or which load and check it caused. **Proposed behavior** An environment variable, `PAPERCLIP_DEBUG_WORK_SIGNALS`, read once when the module loads. It holds a comma-separated topic allowlist, and each topic can carry `:N` for its stack sampling rate. When it is unset or empty, the signal path only checks one boolean and does nothing else. **Reason and benefit** Several idle-load loops this week took hours of statement analysis before the writer was found. Attribution by caller turns that into one log query. ## What Changed - `packages/db/src/work-signal-debug.ts` (new): - `parseWorkSignalDebugSpec` reads `topic[:N],…`. An optional numeric suffix is parsed from the right, so topics that contain colons (for example `live:`) work with or without `:N`. N defaults to 20; malformed entries are ignored. - `createWorkSignalDebug` returns `enabled`, `allows(topic)`, `signal(topic, hint, entry)`, `event(topic, name, fields, stack, entry)` and `flush()`. A disabled instance constructs no `Error`, captures no stack, builds no line and starts no timer. - Stack capture (`captureWorkSignalStack(entry)`) raises `Error.stackTraceLimit` to 40 and restores it in a `finally`. It calls `Error.captureStackTrace(holder, entry)`, so V8 cuts every frame above the public entry (`signalDatabaseWork`, `publishDatabaseWorkSettled`, or the recovery `wake()`). - Frames are dropped by file (`node_modules`, `node:internal`, the signal wrapper files) and by function name (`signalDatabaseWork`, `notifyDeliveryWork`, …), so trimming works on the bundled `index.mjs`. Positions are kept raw (`index.mjs:L:C`) for offline source-map lookup. At most 10 frames are kept. - Each (topic, event) pair has its own budget of 10 lines per second, checked BEFORE any stack is captured. A `suppressed` line names the topic, the dropped event and the count. Frequent `check` lines therefore never drop `signal` or `direct_wake` lines. - Stack sampling (1 in N) counts per (topic, event), so `check` and `load` do not shift the phase of `signal` sampling. `direct_wake` always captures its caller's stack. - Lines go to an in-memory buffer that an unref'd 1-second timer flushes to stderr. The signal path does no I/O and no await. - `workSignalDebug` is the process instance, built from `process.env.PAPERCLIP_DEBUG_WORK_SIGNALS` once at module load. - `packages/db/src/work-signals.ts`: when enabled, it records: - `signal` in `signalDatabaseWork`; - `remote_notification` and `notification_reconnect`; - `settled_publish` (with a sampled stack) for `publishDatabaseWorkSettled`; - `uncertain_settled` when an uncertain transaction resolves. - `server/src/services/recovery/work.ts`: under the same flag: - each task-queue `load` logs its scope key; - each `check` logs the issue and company id, `dueAt`, and `wake: "deadline"` or `"load"`. The marker rides on the queued entry itself, and only while the flag is on, so nothing is tracked otherwise and nothing outlives the entry; - `wake()` logs ONE `direct_wake` line listing the queues it actually invalidates (assigned-work only when registered), under the first allowlisted one, with its caller's stack. - **No request route is logged.** The server has no request async context to read one synchronously, and this change does not add one. - `docs/deploy/environment-variables.md`: documents the flag, internal ids only, raw positions, and that enabling or changing it requires a restart. - Tests: - `packages/db/src/work-signal-debug.test.ts`, 12 tests: - strict no-op when unset or empty (no `Error`, no `captureStackTrace`, no stack capture, no sink); - the process instance is disabled without the env; - allowlist filtering, and spec parsing including colon topics; - per-(topic, event) sampling, and always-on direct-wake stacks; - source-tree trimming, and a synthetic single-file bundle stack with raw positions kept and wrappers dropped by name; - real capture below the entry with the limit raised and restored; - checks at about 8/s alongside signals at about 3/s for 5 seconds, with every signal line kept; - suppressed records never capture a stack; - buffered, timer-driven output. - `packages/db/src/work-signals.test.ts`: on real PostgreSQL, the signal and settled-publish paths never call the debug log while the flag is off. - `server/src/__tests__/issue-recovery-work-debug-attribution.test.ts`, on the recovery fixture with real PostgreSQL: - no recovery log calls while the flag is off; - with the flag on, a run graph hint logs its signal, the graph-scoped load and the check; - `wake()` logs exactly one `direct_wake` that lists the queues and carries the caller's stack. ## Verification - `packages/db`: `vitest run src/work-signal-debug.test.ts src/work-signals.test.ts`: 39 passed. `tsc --noEmit` passes. - `server`: `vitest run src/__tests__/issue-recovery-work-debug-attribution.test.ts src/__tests__/issue-recovery-deadlines.test.ts`: 17 passed. `tsc --noEmit` passes. - Staging values: `PAPERCLIP_DEBUG_WORK_SIGNALS=stranded-assignments:10`, then restart. - Sample output from the synthetic single-file bundle test: ``` {"msg":"paperclip work signal debug","at":1000000,"event":"signal","topic":"stranded-assignments","hint":"{\"companyId\":\"c\",\"graphRunId\":\"r\"}","stack":["at notifyIssueGraphRecovery (file:///app/server/dist-runtime/index.mjs:120456:11)","at async notifyRunDispatch (file:///app/server/dist-runtime/index.mjs:120501:3)","at async PostgresJsDatabase.connection.transaction [as transaction] (file:///app/server/dist-runtime/index.mjs:4021:22)","at async Object.settleRunProjection (file:///app/server/dist-runtime/index.mjs:300777:5)","at async file:///app/server/dist-runtime/index.mjs:310002:17"]} {"msg":"paperclip work signal debug","at":1000000,"event":"check","topic":"stranded-assignments","issueId":"i","companyId":"c","wake":"load","dueAt":1} {"msg":"paperclip work signal debug","at":1000000,"event":"direct_wake","topic":"stranded-assignments","queues":"stranded-assignments,orphan-blockers","stack":["at notifyIssueGraphRecovery (file:///app/server/dist-runtime/index.mjs:120456:11)","…"]} {"msg":"paperclip work signal debug","at":1001000,"event":"suppressed","topic":"stranded-assignments","suppressedEvent":"check","count":17} ``` ## Risks - Low risk. It is off by default. While off, each signal costs one property read and one boolean check. - While on, the log can show internal ids from hints (company, issue, run). It holds no secrets and no user identifiers, and the topic allowlist limits what is logged. - Stack capture costs CPU. Sampling (default 1 in 20) and the 10 lines per second cap bound it. - The file owner of `packages/db/src/work-signals.ts` reviews this before merge. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edits, local PostgreSQL test runs). ## 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 - [x] I will address all Greptile and reviewer comments before requesting merge Related: #21621. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- docs/deploy/environment-variables.md | 1 + packages/db/src/work-signal-debug.test.ts | 187 ++++++++++++++++++ packages/db/src/work-signal-debug.ts | 139 +++++++++++++ packages/db/src/work-signals.test.ts | 15 ++ packages/db/src/work-signals.ts | 14 +- ...ue-recovery-work-debug-attribution.test.ts | 65 ++++++ server/src/services/recovery/work.ts | 19 +- 7 files changed, 435 insertions(+), 5 deletions(-) create mode 100644 packages/db/src/work-signal-debug.test.ts create mode 100644 packages/db/src/work-signal-debug.ts create mode 100644 server/src/__tests__/issue-recovery-work-debug-attribution.test.ts diff --git a/docs/deploy/environment-variables.md b/docs/deploy/environment-variables.md index eb60708a670..0460ab91346 100644 --- a/docs/deploy/environment-variables.md +++ b/docs/deploy/environment-variables.md @@ -28,6 +28,7 @@ All environment variables that Paperclip uses for server configuration. | `PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH` | `/opt/paperclip-runner/provider-pack` in Docker; otherwise unset | Host-local path to the immutable provider pack built by `pnpm --filter @paperclipai/paperclip-runner build:provider-pack`. Stamped standard Docker images include the pack; downstream compositions and the `cloud` target inherit it. Unstamped local Docker builds skip pack generation. The pack includes its target-built Node 24.11+ runtime, locked production dependencies, OpenCode proxy/executable, and ACPX sidecar. Remote OpenCode and ACPX fail closed without it. A preinstalled pack is accepted only when its complete digested manifest matches this build-owned pack; otherwise Paperclip stages this pack into the sandbox. | | `PAPERCLIP_HIDDEN_SETTINGS` | (unset) | Comma-separated settings surfaces to hide from the UI and floor at the API, for operators hosting Paperclip for others (managed cloud, internal shared server). See [Hiding settings surfaces](#hiding-settings-surfaces). | | `PAPERCLIP_SETTING_DEFAULTS` | (unset) | JSON object replacing the schema default of selected instance settings, for hosting operators. See [Operator setting defaults](#operator-setting-defaults). | +| `PAPERCLIP_DEBUG_WORK_SIGNALS` | (unset) | Diagnostic only. Comma-separated allowlist of work-signal topics, each optionally followed by `:N` (for example `stranded-assignments:10,run-dispatch`). For each listed topic the server writes JSON lines to stderr: every work signal (topic and hint), with the caller stack on one signal in N (default 20); remote and reconnect notifications; direct settled publishes; and the recovery queues' loads, checks and direct wakes (direct wakes always carry the caller stack). Logged values are internal ids only (company, issue, run), never secrets or user identifiers. Stack frames keep their raw file and line positions, so bundled builds map them offline with that build's source map. Each topic and event pair is capped at 10 lines per second; a `suppressed` line names the dropped event and its count. The value is read once at startup, so enabling or changing it requires a restart. Unset or empty disables it completely. | Daytona connectivity for `paperclip_runner` uses authenticated provider WebSocket ingress and follows the instance experimental setting diff --git a/packages/db/src/work-signal-debug.test.ts b/packages/db/src/work-signal-debug.test.ts new file mode 100644 index 00000000000..aa3038f5e66 --- /dev/null +++ b/packages/db/src/work-signal-debug.test.ts @@ -0,0 +1,187 @@ +import { appendFileSync } from "node:fs"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { captureWorkSignalStack, createWorkSignalDebug, parseWorkSignalDebugSpec, trimWorkSignalStack, workSignalDebug } from "./work-signal-debug.js"; + +const SOURCE_STACK = [ + "Error", + " at notifyDeliveryWork (/app/server/src/services/delivery-work-notifications.ts:169:3)", + " at notifyIssueGraphRecovery (/app/server/src/services/issue-recovery-notifications.ts:44:5)", + " at process.processTicksAndRejections (node:internal/process/task_queues:104:5)", + " at someLibrary (/app/node_modules/postgres/src/index.js:1:1)", + " at writer (/app/server/src/services/writer.ts:12:7)", +].join("\n"); + +const BUNDLE = "file:///app/server/dist-runtime/index.mjs"; +const BUNDLED_STACK = [ + "Error", + ` at notifyDeliveryWork (${BUNDLE}:91234:9)`, + ` at notifyIssueGraphRecovery (${BUNDLE}:120456:11)`, + ` at async notifyRunDispatch (${BUNDLE}:120501:3)`, + ` at async PostgresJsDatabase.connection.transaction [as transaction] (${BUNDLE}:4021:22)`, + ` at async Object.settleRunProjection (${BUNDLE}:300777:5)`, + ` at async ${BUNDLE}:310002:17`, + " at process.processTicksAndRejections (node:internal/process/task_queues:104:5)", +].join("\n"); + +function harness(spec: string | undefined, options: { maxLinesPerSecond?: number; stack?: string } = {}) { + let clock = 1_000_000; + const lines: string[] = []; + const sink = vi.fn((text: string) => { lines.push(...text.trim().split("\n")); }); + const captureStack = vi.fn((_entry: Function) => options.stack ?? SOURCE_STACK); + const debug = createWorkSignalDebug({ spec, sink, captureStack, now: () => clock, flushIntervalMs: 0, ...options }); + return { debug, sink, captureStack, lines, entries: () => lines.map(line => JSON.parse(line)), + advance: (ms: number) => { clock += ms; } }; +} + +afterEach(() => { vi.restoreAllMocks(); }); + +describe("work signal debug attribution", () => { + it("is a strict no-op when the flag is unset or empty", () => { + for (const spec of [undefined, "", " , "]) { + const { debug, sink, captureStack } = harness(spec); + const errors = vi.spyOn(globalThis, "Error"); + const capture = vi.spyOn(Error, "captureStackTrace"); + expect(debug.enabled).toBe(false); + for (let index = 0; index < 50; index++) { + debug.signal("stranded-assignments", "{\"companyId\":\"c\"}"); + debug.event("stranded-assignments", "direct_wake", { queues: "a" }, "always"); + } + debug.flush(); + expect(captureStack).not.toHaveBeenCalled(); + expect(errors).not.toHaveBeenCalled(); + expect(capture).not.toHaveBeenCalled(); + expect(sink).not.toHaveBeenCalled(); + } + }); + + it("leaves the process-wide instance disabled when the environment does not set it", () => { + expect(process.env.PAPERCLIP_DEBUG_WORK_SIGNALS ?? "").toBe(""); + expect(workSignalDebug.enabled).toBe(false); + }); + + it("logs only allowlisted topics", () => { + const { debug, entries } = harness("stranded-assignments,run-dispatch:5"); + debug.signal("stranded-assignments", "{\"companyId\":\"c\",\"graphRunId\":\"r\"}"); + debug.signal("issue-monitors", "{\"companyId\":\"c\"}"); + debug.event("run-dispatch", "load", { scope: "*" }); + debug.event("orphan-blockers", "load", { scope: "*" }); + debug.flush(); + expect(entries().map(entry => [entry.event, entry.topic])).toEqual([ + ["signal", "stranded-assignments"], ["load", "run-dispatch"]]); + expect(entries()[0].hint).toBe("{\"companyId\":\"c\",\"graphRunId\":\"r\"}"); + expect(debug.allows("run-dispatch")).toBe(true); + expect(debug.allows("orphan-blockers")).toBe(false); + }); + + it("parses per-topic sampling and ignores malformed entries", () => { + expect([...parseWorkSignalDebugSpec("stranded-assignments:3, run-dispatch,bad topic!, :4,x:0,live:7f3e-11,live:7f3e-12:4")]) + .toEqual([["stranded-assignments", 3], ["run-dispatch", 20], ["x", 20], ["live:7f3e-11", 20], ["live:7f3e-12", 4]]); + const { debug, entries } = harness("live:7f3e-11"); + debug.event("live:7f3e-11", "remote_notification"); + debug.flush(); + expect(entries()).toEqual([expect.objectContaining({ topic: "live:7f3e-11", event: "remote_notification" })]); + }); + + it("samples stacks one in N per topic and event, independent of other events", () => { + const { debug, entries, captureStack } = harness("stranded-assignments:3"); + for (let index = 0; index < 7; index++) { + debug.signal("stranded-assignments", undefined); + debug.event("stranded-assignments", "check", { issueId: `i${index}` }, "sampled"); + debug.event("stranded-assignments", "load", { scope: "*" }, "sampled"); + } + debug.flush(); + const signals = entries().filter(entry => entry.event === "signal"); + expect(signals.map(entry => Boolean(entry.stack))).toEqual([true, false, false, true, false, false, true]); + expect(captureStack).toHaveBeenCalledTimes(9); + }); + + it("captures an always-on stack for direct wakes on every call", () => { + const { debug, entries, captureStack } = harness("stranded-assignments:20"); + for (let index = 0; index < 3; index++) debug.event("stranded-assignments", "direct_wake", { queues: "a,b" }, "always"); + debug.flush(); + expect(captureStack).toHaveBeenCalledTimes(3); + expect(entries().every(entry => Array.isArray(entry.stack) && entry.queues === "a,b")).toBe(true); + }); + + it("trims a source-tree stack by file and by function name", () => { + expect(trimWorkSignalStack(SOURCE_STACK)).toEqual([ + "at notifyIssueGraphRecovery (/app/server/src/services/issue-recovery-notifications.ts:44:5)", + "at writer (/app/server/src/services/writer.ts:12:7)", + ]); + const deep = ["Error", ...Array.from({ length: 30 }, (_, index) => ` at f${index} (/app/server/src/f.ts:${index}:1)`)].join("\n"); + expect(trimWorkSignalStack(deep)).toHaveLength(10); + }); + + it("keeps raw bundle positions and drops wrappers by function name when every frame is in one bundled file", () => { + const { debug, entries } = harness("stranded-assignments:1", { stack: BUNDLED_STACK }); + debug.signal("stranded-assignments", "{\"companyId\":\"c\",\"graphRunId\":\"r\"}"); + debug.event("stranded-assignments", "check", { issueId: "i", companyId: "c", wake: "load", dueAt: 1 }); + debug.event("stranded-assignments", "direct_wake", { queues: "stranded-assignments,orphan-blockers" }, "always"); + debug.flush(); + expect(entries()[0].stack).toEqual([ + `at notifyIssueGraphRecovery (${BUNDLE}:120456:11)`, + `at async notifyRunDispatch (${BUNDLE}:120501:3)`, + `at async PostgresJsDatabase.connection.transaction [as transaction] (${BUNDLE}:4021:22)`, + `at async Object.settleRunProjection (${BUNDLE}:300777:5)`, + `at async ${BUNDLE}:310002:17`, + ]); + if (process.env.WORK_SIGNAL_DEBUG_SAMPLE_OUT) appendFileSync(process.env.WORK_SIGNAL_DEBUG_SAMPLE_OUT, + entries().map(entry => JSON.stringify(entry)).join("\n") + "\n"); + }); + + it("captures frames below the entry function with a raised and restored stack limit", () => { + const before = Error.stackTraceLimit; + function signalEntry() { return captureWorkSignalStack(signalEntry); } + function nest(depth: number): string | undefined { return depth === 0 ? signalEntry() : nest(depth - 1); } + const stack = nest(25); + expect(Error.stackTraceLimit).toBe(before); + const frames = (stack ?? "").split("\n").slice(1); + expect(frames.some(frame => frame.includes("signalEntry"))).toBe(false); + expect(frames.filter(frame => frame.includes("nest")).length).toBeGreaterThan(before); + }); + + it("budgets each topic and event separately so frequent checks never drop signals", () => { + const { debug, entries, advance } = harness("stranded-assignments:1000", { maxLinesPerSecond: 10 }); + let signals = 0; + for (let second = 0; second < 5; second++) { + for (let tick = 0; tick < 24; tick++) { + debug.event("stranded-assignments", "check", { issueId: `i${tick}` }); + if (tick % 8 === 0) { debug.signal("stranded-assignments", `h${second}-${tick}`); signals++; } + if (tick % 3 === 0) debug.event("stranded-assignments", "check", { issueId: `x${tick}` }); + advance(1000 / 24); + } + } + debug.flush(); + expect(entries().filter(entry => entry.event === "signal")).toHaveLength(signals); + expect(entries().filter(entry => entry.event === "check").length).toBeLessThanOrEqual(5 * 10 + 10); + const suppressed = entries().filter(entry => entry.event === "suppressed"); + expect(suppressed).toEqual([expect.objectContaining({ topic: "stranded-assignments", suppressedEvent: "check" })]); + expect(suppressed[0].count).toBeGreaterThan(0); + }); + + it("captures no stack for a record the cap suppresses", () => { + const { debug, captureStack, entries } = harness("stranded-assignments:1", { maxLinesPerSecond: 3 }); + for (let index = 0; index < 20; index++) { + debug.signal("stranded-assignments", undefined); + debug.event("stranded-assignments", "direct_wake", { queues: "a" }, "always"); + } + debug.flush(); + expect(captureStack).toHaveBeenCalledTimes(6); + expect(entries().filter(entry => entry.event === "suppressed").map(entry => [entry.suppressedEvent, entry.count])) + .toEqual([["signal", 17], ["direct_wake", 17]]); + }); + + it("writes nothing on the signal path and flushes later from a timer", () => { + vi.useFakeTimers(); + try { + const sink = vi.fn(); + const debug = createWorkSignalDebug({ spec: "stranded-assignments", sink, captureStack: () => SOURCE_STACK }); + debug.signal("stranded-assignments", undefined); + expect(sink).not.toHaveBeenCalled(); + vi.advanceTimersByTime(1000); + expect(sink).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(5000); + expect(sink).toHaveBeenCalledTimes(1); + } finally { vi.useRealTimers(); } + }); +}); diff --git a/packages/db/src/work-signal-debug.ts b/packages/db/src/work-signal-debug.ts new file mode 100644 index 00000000000..fc604790dba --- /dev/null +++ b/packages/db/src/work-signal-debug.ts @@ -0,0 +1,139 @@ +export type WorkSignalDebugOptions = { + spec?: string; + defaultSampleEvery?: number; + maxLinesPerSecond?: number; + flushIntervalMs?: number; + sink?: (text: string) => void; + now?: () => number; + captureStack?: (entry: Function) => string | undefined; +}; + +export type WorkSignalDebugFields = Record; +export type WorkSignalDebugStack = "none" | "sampled" | "always"; + +const DROPPED_FILES = /node_modules|node:internal|work-signals\.(ts|js)|work-signal-debug\.(ts|js)|delivery-work-notifications\.(ts|js)/; +const DROPPED_FUNCTIONS = new Set(["signalDatabaseWork", "publishDatabaseWorkSettled", "notifyDeliveryWork", + "captureWorkSignalStack", "processTicksAndRejections"]); +const STACK_LIMIT = 40; + +export function parseWorkSignalDebugSpec(spec: string | undefined, defaultSampleEvery = 20): Map { + const topics = new Map(); + for (const part of (spec ?? "").split(",")) { + const match = /^(.+?)(?::(\d+))?$/.exec(part.trim()); + const topic = match?.[1]?.trim(); + if (!topic || !/^[a-z0-9:_-]{1,200}$/i.test(topic) || topic.startsWith(":") || topic.endsWith(":")) continue; + const every = Number(match?.[2]); + topics.set(topic, Number.isInteger(every) && every >= 1 ? every : defaultSampleEvery); + } + return topics; +} + +function frameFunction(line: string) { + const match = /^at (?:async )?(?:new )?([^\s(]+)(?: \[as [^\]]+\])? \(/.exec(line); + if (!match) return null; + const name = match[1]!; + return name.slice(name.lastIndexOf(".") + 1); +} + +export function trimWorkSignalStack(stack: string | undefined, frames = 10): string[] { + if (!stack) return []; + return stack.split("\n").slice(1).map(line => line.trim()) + .filter(line => line.startsWith("at ") && !DROPPED_FILES.test(line) && !DROPPED_FUNCTIONS.has(frameFunction(line) ?? "")) + .slice(0, frames); +} + +export function captureWorkSignalStack(entry: Function): string | undefined { + const holder: { stack?: string } = {}; + const limit = Error.stackTraceLimit; + try { + Error.stackTraceLimit = STACK_LIMIT; + Error.captureStackTrace(holder, entry); + } finally { + Error.stackTraceLimit = limit; + } + return holder.stack; +} + +export function createWorkSignalDebug(options: WorkSignalDebugOptions = {}) { + const topics = parseWorkSignalDebugSpec(options.spec, options.defaultSampleEvery); + const enabled = topics.size > 0; + const now = options.now ?? Date.now; + const maxLines = options.maxLinesPerSecond ?? 10; + const sink = options.sink ?? ((text: string) => { process.stderr.write(text); }); + const captureStack = options.captureStack ?? captureWorkSignalStack; + const counts = new Map(); + const budgets = new Map(); + const pending: string[] = []; + let timer: ReturnType | null = null; + + function admit(topic: string, event: string) { + const at = now(); + const key = `${topic}\u0000${event}`; + let budget = budgets.get(key); + if (!budget) budgets.set(key, budget = { windowStart: at, lines: 0, suppressed: 0, topic, event }); + if (at - budget.windowStart >= 1000) { budget.windowStart = at; budget.lines = 0; } + schedule(); + if (budget.lines >= maxLines) { budget.suppressed += 1; return false; } + budget.lines += 1; + return true; + } + + function emit(topic: string, event: string, entry: Record) { + pending.push(JSON.stringify({ msg: "paperclip work signal debug", at: now(), event, topic, ...entry })); + } + + function schedule() { + if (timer || options.flushIntervalMs === 0) return; + timer = setInterval(flush, options.flushIntervalMs ?? 1000); + timer.unref?.(); + } + + function sampled(topic: string, event: string) { + const key = `${topic}\u0000${event}`; + const count = counts.get(key) ?? 0; + counts.set(key, count + 1); + return count % (topics.get(topic) ?? 1) === 0; + } + + function stackFor(topic: string, event: string, mode: WorkSignalDebugStack, entry: Function) { + if (mode === "none" || (mode === "sampled" && !sampled(topic, event))) return undefined; + return trimWorkSignalStack(captureStack(entry)); + } + + function flush() { + for (const budget of budgets.values()) { + if (budget.suppressed === 0) continue; + pending.push(JSON.stringify({ msg: "paperclip work signal debug", at: now(), event: "suppressed", + topic: budget.topic, suppressedEvent: budget.event, count: budget.suppressed })); + budget.suppressed = 0; + } + if (pending.length === 0) { + if (timer) { clearInterval(timer); timer = null; } + return; + } + sink(pending.splice(0).join("\n") + "\n"); + } + + function signal(topic: string, hint: string | undefined, entry: Function = signal) { + if (!enabled || !topics.has(topic) || !admit(topic, "signal")) return; + const stack = stackFor(topic, "signal", "sampled", entry); + emit(topic, "signal", { ...(hint === undefined ? {} : { hint }), ...(stack ? { stack } : {}) }); + } + + function event(topic: string, name: string, fields: WorkSignalDebugFields = {}, + stack: WorkSignalDebugStack = "none", entry: Function = event) { + if (!enabled || !topics.has(topic) || !admit(topic, name)) return; + const frames = stackFor(topic, name, stack, entry); + emit(topic, name, { ...fields, ...(frames ? { stack: frames } : {}) }); + } + + return { + get enabled() { return enabled; }, + allows(topic: string) { return enabled && topics.has(topic); }, + signal, + event, + flush, + }; +} + +export const workSignalDebug = createWorkSignalDebug({ spec: process.env.PAPERCLIP_DEBUG_WORK_SIGNALS }); diff --git a/packages/db/src/work-signals.test.ts b/packages/db/src/work-signals.test.ts index b4d652eec08..fdfb9202233 100644 --- a/packages/db/src/work-signals.test.ts +++ b/packages/db/src/work-signals.test.ts @@ -3,6 +3,7 @@ import { drizzle } from "drizzle-orm/postgres-js"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { createDb, withDedicatedDbConnection } from "./client.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; +import { workSignalDebug } from "./work-signal-debug.js"; import { DATABASE_WORK_CHANNEL, databaseWorkScopeKey, databaseWorkPending, enableDatabaseWorkNotifications, installDatabaseWorkSignals, notifyDatabaseWorkOnCommit, primeDatabaseWorkTransactionId, publishDatabaseWorkSettled, reconcileDatabaseWork, signalDatabaseWork, subscribeDatabaseWork } from "./work-signals.js"; const support = await getEmbeddedPostgresTestSupport(); @@ -16,6 +17,20 @@ const support = await getEmbeddedPostgresTestSupport(); }, 90_000); afterAll(async () => { await temporary?.cleanup(); }); + it("does not touch the debug attribution log on the signal path when the flag is off", async () => { + const signal = vi.spyOn(workSignalDebug, "signal"); + const event = vi.spyOn(workSignalDebug, "event"); + try { + await db.transaction(async tx => { + await signalDatabaseWork(tx, "debug-off", "{\"companyId\":\"c\"}"); + await tx.execute(sql`insert into work_signal_test values ('debug-off')`); + }); + publishDatabaseWorkSettled(db, "debug-off"); + expect(signal).not.toHaveBeenCalled(); + expect(event).not.toHaveBeenCalled(); + } finally { signal.mockRestore(); event.mockRestore(); } + }); + it("defers nested savepoint notifications until the outer commit and preserves return values", async () => { const events: string[] = []; const unsubscribe = subscribeDatabaseWork(db, "nested", event => events.push(event)); diff --git a/packages/db/src/work-signals.ts b/packages/db/src/work-signals.ts index 6b4bdbd126a..42be2669622 100644 --- a/packages/db/src/work-signals.ts +++ b/packages/db/src/work-signals.ts @@ -1,5 +1,6 @@ import { sql } from "drizzle-orm"; import { randomUUID } from "node:crypto"; +import { workSignalDebug } from "./work-signal-debug.js"; // Hints about existing durable queues; process-local by default, with optional // commit-bound PostgreSQL notifications during controller replacement. No SQL @@ -72,6 +73,7 @@ export async function signalDatabaseWork(connection: object, topic: string, hint if (!context) return; // Lightweight service test doubles have no DB lifecycle. const state = context.transaction; if (!state) throw new Error("Database work must be registered inside a transaction"); + if (workSignalDebug.enabled) workSignalDebug.signal(topic, hint, signalDatabaseWork); state.topics.add(topic); if (hint !== undefined) { let hints = state.hints.get(topic); @@ -138,6 +140,7 @@ export function databaseWorkCommitNotification(owner: object, topic: string): st export function publishDatabaseWorkSettled(owner: object, topic: string, hint?: string): void { const context = contexts.get(owner); if (!context) return; + if (workSignalDebug.enabled) workSignalDebug.event(topic, "settled_publish", { hint }, "sampled", publishDatabaseWorkSettled); if (!context.transaction) { publish(context.scope, topic, "settled", hint === undefined ? undefined : new Set([hint])); return; @@ -159,12 +162,16 @@ export function receiveDatabaseWorkNotification(owner: object, payload: string): try { value = JSON.parse(payload); } catch { return; } if (!value || value.version !== 1 || typeof value.origin !== "string" || value.origin === scope.notificationOrigin || typeof value.topic !== "string" || !validTopic(value.topic)) return; + if (workSignalDebug.enabled) workSignalDebug.event(value.topic, "remote_notification"); publish(scope, value.topic); } /** Reconnect can lose hints. Reconstruct existing durable queues once; no poll. */ export function reconcileDatabaseWorkNotifications(owner: object): void { const scope = contexts.get(owner)?.scope; - if (scope) for (const topic of scope.listeners.keys()) publish(scope, topic); + if (scope) for (const topic of scope.listeners.keys()) { + if (workSignalDebug.enabled) workSignalDebug.event(topic, "notification_reconnect"); + publish(scope, topic); + } } export function databaseWorkPending(owner: object, topic: string): boolean { @@ -188,7 +195,10 @@ export async function reconcileDatabaseWork(owner: object, topic: string): Promi throw new Error("Unexpected database transaction status"); } scope.transactions.delete(state); - for (const affected of state.topics) publish(scope, affected, "settled", state.hints.get(affected)); + for (const affected of state.topics) { + if (workSignalDebug.enabled) workSignalDebug.event(affected, "uncertain_settled", { status: rows[0]?.status ?? null }); + publish(scope, affected, "settled", state.hints.get(affected)); + } } } diff --git a/server/src/__tests__/issue-recovery-work-debug-attribution.test.ts b/server/src/__tests__/issue-recovery-work-debug-attribution.test.ts new file mode 100644 index 00000000000..8b0282ac0e5 --- /dev/null +++ b/server/src/__tests__/issue-recovery-work-debug-attribution.test.ts @@ -0,0 +1,65 @@ +import { expect, it, vi } from "vitest"; +import { agents, heartbeatRuns, issues } from "@paperclipai/db"; +import { eq } from "drizzle-orm"; +import { workSignalDebug } from "@paperclipai/db/work-signal-debug"; +import { signalDatabaseWork } from "@paperclipai/db/work-signals"; +import { notifyIssueGraphRecovery } from "../services/issue-recovery-notifications.js"; +import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js"; + +describeIssueRecovery("issue recovery work signal attribution", () => { + const state = issueRecoveryFixture(); + + it("logs nothing from recovery loads and checks while the flag is off", async () => { + const f = await state.fixture(); + await state.db.insert(issues).values({ companyId: f.companyId, title: "Waiting", status: "in_review", assigneeAgentId: f.agentId }); + const event = vi.spyOn(workSignalDebug, "event"); + const signal = vi.spyOn(workSignalDebug, "signal"); + await state.start(); await state.settled(); + expect(event).not.toHaveBeenCalled(); + expect(signal).not.toHaveBeenCalled(); + }); + + it("ties each stranded check to the load and hint that caused it when the flag is on", async () => { + const f = await state.fixture(); + await state.db.update(agents).set({ status: "error" }).where(eq(agents.id, f.agentId)); + const [task] = await state.db.insert(issues).values({ companyId: f.companyId, title: "Waiting", status: "in_review", + assigneeAgentId: f.agentId }).returning(); + const [run] = await state.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "succeeded", + runtimeMode: "native", nativeIssueId: task.id, finishedAt: new Date(), contextSnapshot: { issueId: task.id } }).returning(); + await state.start(); await state.settled(); + const enabled = vi.spyOn(workSignalDebug, "enabled", "get").mockReturnValue(true); + const event = vi.spyOn(workSignalDebug, "event").mockImplementation(() => {}); + const signal = vi.spyOn(workSignalDebug, "signal").mockImplementation(() => {}); + try { + await state.db.transaction(tx => notifyIssueGraphRecovery(tx, { companyId: f.companyId, runId: run.id })); + await state.settled({ backstopPending: true }); + expect(signal).toHaveBeenCalledWith("stranded-assignments", + JSON.stringify({ companyId: f.companyId, graphRunId: run.id }), signalDatabaseWork); + const stranded = event.mock.calls.filter(([topic]) => topic === "stranded-assignments"); + expect(stranded).toContainEqual(["stranded-assignments", "load", + { scope: JSON.stringify([f.companyId, null, run.id, null, null]) }]); + expect(stranded).toContainEqual(["stranded-assignments", "check", + expect.objectContaining({ issueId: task.id, companyId: f.companyId, wake: "load" })]); + } finally { enabled.mockRestore(); event.mockRestore(); signal.mockRestore(); } + }); + + it("logs one direct wake listing the woken queues with its caller's stack", async () => { + await state.fixture(); + await state.start(); await state.settled(); + const enabled = vi.spyOn(workSignalDebug, "enabled", "get").mockReturnValue(true); + const allows = vi.spyOn(workSignalDebug, "allows").mockImplementation(topic => topic === "stranded-assignments"); + const event = vi.spyOn(workSignalDebug, "event").mockImplementation(() => {}); + try { + state.worker.wake(); + const wakes = event.mock.calls.filter(([, name]) => name === "direct_wake"); + expect(wakes).toHaveLength(1); + const [topic, , fields, stack, entry] = wakes[0]!; + expect(topic).toBe("stranded-assignments"); + expect(String(fields?.queues).split(",")).toEqual(expect.arrayContaining(["stranded-assignments", + "orphan-blockers", "assigned-work-invariant"])); + expect(stack).toBe("always"); + expect(entry).toBe(state.worker.wake); + await state.settled(); + } finally { enabled.mockRestore(); allows.mockRestore(); event.mockRestore(); } + }); +}); diff --git a/server/src/services/recovery/work.ts b/server/src/services/recovery/work.ts index 06a9baf803a..7c9e02c2271 100644 --- a/server/src/services/recovery/work.ts +++ b/server/src/services/recovery/work.ts @@ -6,9 +6,10 @@ import { DELIVERY_QUEUES, type DeliveryQueue } from "../delivery-work-notificati import { decodeIssueRecoveryHint, ISSUE_RECOVERY_BACKSTOP_MS, issueRecoveryScopeMatches, resolveIssueGraph, type IssueRecoveryScope } from "../issue-recovery-notifications.js"; import { registerScopedDeadlineWork } from "../scoped-deadline-work.js"; +import { workSignalDebug } from "@paperclipai/db/work-signal-debug"; import { recoveryActionSweepCondition } from "./blocker-stall-wakeups.js"; -type Entry = { id: string; companyId: string; dueAt: number }; +type Entry = { id: string; companyId: string; dueAt: number; fromDeadline?: true }; type Scope = { companyId: string; issueId: string; onDeferredDeadline: (at: number) => void }; const PAGE_SIZE = 100; @@ -88,6 +89,7 @@ export function registerIssueRecoveryWork( matches: issueRecoveryScopeMatches, load: async scope => { const key = scopeKey(scope); + if (workSignalDebug.enabled) workSignalDebug.event(queue, "load", { scope: key }); if (!enabled) { cursors.delete(key); return []; } if (await toCompany(scope, worker)) return { rows: null, complete: true }; const cursor = cursors.get(key); @@ -109,10 +111,12 @@ export function registerIssueRecoveryWork( }, check: async entry => { if (!enabled) return null; + if (workSignalDebug.enabled) workSignalDebug.event(queue, "check", { issueId: entry.id, companyId: entry.companyId, + wake: entry.fromDeadline ? "deadline" : "load", dueAt: entry.dueAt }); let next: number | null = null; await check({ companyId: entry.companyId, issueId: entry.id, onDeferredDeadline: at => { next = next === null ? at : Math.min(next, at); } }); - return next === null ? null : { ...entry, dueAt: next }; + return next === null ? null : { ...entry, dueAt: next, ...(workSignalDebug.enabled ? { fromDeadline: true as const } : {}) }; }, }, canRun); return worker; @@ -219,7 +223,16 @@ export function registerIssueRecoveryWork( }, canRun); const workers = [assignments, orphanBlockers, recoveryActions, dependencies, locks, watchdogs, ...(assignedWork ? [assignedWork] : [])]; + const queues: string[] = [DELIVERY_QUEUES.strandedAssignments, DELIVERY_QUEUES.orphanBlockers, DELIVERY_QUEUES.activeRecoveryActions, + DELIVERY_QUEUES.resolvedDependencies, DELIVERY_QUEUES.staleIssueLocks, DELIVERY_QUEUES.taskWatchdogs, + ...(assignedWork ? [DELIVERY_QUEUES.assignedWorkInvariant] : [])]; return { watchdogs, assignments, assignedWork, ready: Promise.all(workers.map(worker => worker.ready)), - wake() { for (const worker of workers) worker.invalidate(); }, + wake: function wake() { + if (workSignalDebug.enabled) { + const topic = queues.find(queue => workSignalDebug.allows(queue)); + if (topic) workSignalDebug.event(topic, "direct_wake", { queues: queues.join(",") }, "always", wake); + } + for (const worker of workers) worker.invalidate(); + }, async stop() { await Promise.all(workers.map(worker => worker.stop())); } }; }