From 92308f839d75c6ff50f6668a8e9c28595bccf633 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:08:23 -0600 Subject: [PATCH 01/12] test(e2e): use the Coordinator task panel, inbox and plan controls in QA journeys (#21701) 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 QA Cloud product journeys check real user paths on a hosted test stack > - #19360 (2026-11-05) made the Coordinator workspace standard; its task side panel starts with no tabs, and the header control opens a tab chooser > - The journeys were written for the classic panel, which opened straight on Properties, and for older inbox and plan controls > - On QA the smoke suite passed 8 of 24 journeys; 13 failures trace to these out-of-date journey steps > - This pull request updates the journeys to use the shipped Coordinator controls the way a person does > - The benefit is that the QA journeys test the product again instead of failing on removed controls ## Linked Issues or Issue Description **What happened?** The QA staging smoke suite passed 8 of 24 journeys. 13 failures come from journey steps that target the classic UI: - Task side panel: the journeys click "Show properties" and expect property rows. In Coordinator the click opens a tab chooser ("Open a side panel tab"), and the user picks Properties or Artifacts. The product's own e2e tests (`tests/e2e/artifact-tab-arrival.spec.ts`, `artifact-uploads.spec.ts`, `disconnect-resilience.spec.ts`) and the chat-catalog runtime cases already use the chooser. - Inbox: desktop Coordinator inbox rows show unread state as a bold title and have no per-row "Mark as read" button (`doc/plans/2026-11-06-chat-contacts-pins.md`). The `r` shortcut marks the hovered row read on the Mine view. - Plan: the Coordinator Plan chip is named "Open Plan revision N in task sidebar", not "Open Plan revision N". **Steps to reproduce** 1. Run `pnpm test:e2e:runner -- --target-config ` with task-properties, task-edit-lifecycle, task-document-persistence and project-task-context. 2. See 0/4 pass on master; each stops at the tab chooser. **Expected behavior** The journeys reach the same saved-state checks as before through the shipped controls. ## What Changed - New `product-journeys/task-panel.ts` helper: opens the side panel and selects a tab (Properties or Artifacts) from the chooser, an open tab, or the "Open a new tab" button. It waits for the page instead of a single non-waiting visibility check, and does not close an already open panel. - task-properties, task-edit-lifecycle, task-dependency-resume, project-task-context and task-document-persistence (and routine/agent journeys that reuse `openDocumentAuthoring`) use the helper. task-properties reopens the panel after reload before it checks "You". - inbox-triage: when the row has no visible "Mark as read" button, open the Mine view, blur search, hover the row and press `r` (as `tests/e2e/coordinator-inbox-views.spec.ts` does). - Plan journey: `planPreviewLabel()` accepts the optional " in task sidebar" suffix and still requires the exact revision. - No product code changes. An earlier revision of this PR changed "Show properties" to select Properties; it is reverted because the product e2e suite asserts the chooser is the intended design. All saved-state assertions are unchanged: assignment, labels, status, documents, read state and plan revision are still read back through the API, so a broken feature still fails. ## Verification - Real browser journeys on a managed local instance against unmodified master UI: 4/4 pass (task-edit-lifecycle, task-properties, task-document-persistence, project-task-context); 0/4 before. - Inbox fallback checked by hand on a local instance: an unread task on the Mine view became `isUnreadForMe=false` after blur + hover + `r`. - `tests/runner-e2e` unit tests for product-journeys and plan-revision: 47 files, 1240 tests pass. The task-properties contract test now models the chooser and asserts the opener and the Properties option are used before assignment and after reload. New `planPreviewLabel` test covers revision 12 vs 1 and a missing revision. - QA Cloud rerun follows once the QA harness pin moves to a master commit that contains this change. ## Risks - Low risk: test code only. If the chooser changes again, the helper fails visibly at the panel step. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [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 --- tests/runner-e2e/plan-revision-flow.test.ts | 10 ++++- tests/runner-e2e/plan-revision-flow.ts | 6 ++- .../product-journeys/contracts.test.ts | 27 ++++++++++++-- .../product-journeys/inbox-triage-flow.ts | 10 ++++- .../project-context-readback.ts | 5 +-- .../task-dependency-resume.test.ts | 1 + .../task-dependency-resume.ts | 16 +------- .../task-document-flow.test.ts | 2 +- .../product-journeys/task-document-flow.ts | 20 +--------- .../product-journeys/task-lifecycle.ts | 18 +-------- .../runner-e2e/product-journeys/task-panel.ts | 37 +++++++++++++++++++ .../product-journeys/task-properties.ts | 8 ++-- 12 files changed, 98 insertions(+), 62 deletions(-) create mode 100644 tests/runner-e2e/product-journeys/task-panel.ts diff --git a/tests/runner-e2e/plan-revision-flow.test.ts b/tests/runner-e2e/plan-revision-flow.test.ts index 57d55a59897..39322920453 100644 --- a/tests/runner-e2e/plan-revision-flow.test.ts +++ b/tests/runner-e2e/plan-revision-flow.test.ts @@ -1,6 +1,6 @@ import { expect, it, vi } from "vitest"; import type { Page } from "@playwright/test"; -import { runPlanRevisionAcceptance } from "./plan-revision-flow.js"; +import { planPreviewLabel, runPlanRevisionAcceptance } from "./plan-revision-flow.js"; const state = { currentIssue: { status: "in_progress" }, @@ -36,3 +36,11 @@ it("lets deployment callers reject a binding failure without another observation expect(load).toHaveBeenCalledOnce(); expect(get).not.toHaveBeenCalled(); }); + +it("accepts the classic and Coordinator Plan preview names for the exact revision only", () => { + expect(planPreviewLabel(1).test("Open Plan revision 1")).toBe(true); + expect(planPreviewLabel(1).test("Open Plan revision 1 in task sidebar")).toBe(true); + expect(planPreviewLabel(1).test("Open Plan revision 12 in task sidebar")).toBe(false); + expect(planPreviewLabel(2).test("Open Plan revision 1 in task sidebar")).toBe(false); + expect(planPreviewLabel(1).test("Open Plan in task sidebar")).toBe(false); +}); diff --git a/tests/runner-e2e/plan-revision-flow.ts b/tests/runner-e2e/plan-revision-flow.ts index e8d7bd84a7b..553926580bb 100644 --- a/tests/runner-e2e/plan-revision-flow.ts +++ b/tests/runner-e2e/plan-revision-flow.ts @@ -19,11 +19,15 @@ export function isPendingPlanConfirmation(interaction: PlanInteraction) { && typeof interaction.payload.target.revisionId === "string"; } export function normalizePlanMarkdown(body: string | null | undefined) { return (body ?? "").replaceAll("\\_", "_"); } +export function planPreviewLabel(revision: number): RegExp { + return new RegExp(`^Open Plan revision ${revision}(?: in task sidebar)?$`); +} + export async function expectPlanStageVisible(page: Page, options: { native: boolean; revision: number | null }) { const root = options.native ? page.locator('[data-testid="task-chat-turn"][data-settled="true"]') : page.locator("body"); const preview = root.getByTestId("task-chat-plan-preview").last(); await expect(preview).toBeVisible({ timeout: 30_000 }); - if (options.revision !== null) await expect(preview).toHaveAttribute("aria-label", `Open Plan revision ${options.revision}`); + if (options.revision !== null) await expect(preview).toHaveAttribute("aria-label", planPreviewLabel(options.revision)); } /** The classic matrix and deployment-targeted journeys share this exact user story. */ diff --git a/tests/runner-e2e/product-journeys/contracts.test.ts b/tests/runner-e2e/product-journeys/contracts.test.ts index a702406ee61..219fff80f32 100644 --- a/tests/runner-e2e/product-journeys/contracts.test.ts +++ b/tests/runner-e2e/product-journeys/contracts.test.ts @@ -17,7 +17,11 @@ import { journeyRequiredChecks } from "./success-contract.js"; import type { OnboardingConnectEvidence } from "./onboarding-connect.js"; vi.mock("@playwright/test", () => ({ expect: Object.assign( - (locator: { textContent(): Promise }) => ({ async toContainText(value: string) { expect(await locator.textContent()).toContain(value); } }), + (locator: { textContent(): Promise; isVisible?(): Promise }) => ({ + async toContainText(value: string) { expect(await locator.textContent()).toContain(value); }, + async toBeVisible() { expect(await locator.isVisible?.()).toBe(true); }, + async toBeInViewport() {}, + }), { poll: (read: () => Promise) => ({ async toBe(value: unknown) { expect(await read()).toBe(value); } }) }, ), })); @@ -189,10 +193,23 @@ describe("deployment journey contracts", () => { await fixtures.resolve(["backlog-task"]); api.post.mockImplementation(async () => { throw Error("task creation inside measured story"); }); let assigned = false; - const locator = { filter: vi.fn(), first: vi.fn(), locator: vi.fn(), getByRole: vi.fn(), click: vi.fn(), isVisible: vi.fn(async () => false), textContent: vi.fn(async () => assigned ? "You" : "Unassigned") }; - for (const method of [locator.filter, locator.first, locator.locator, locator.getByRole]) method.mockReturnValue(locator); + let panelOpen = false; + let propertiesSelected = false; + const chain = (target: T) => Object.assign(target, { filter: vi.fn(() => target), first: vi.fn(() => target) }); + const hidden = chain({ isVisible: vi.fn(async () => false), click: vi.fn() }); + const link = chain({ click: vi.fn() }); + const opener = chain({ isVisible: vi.fn(async () => !panelOpen), click: vi.fn(async () => { panelOpen = true; }) }); + const propertiesOption = chain({ isVisible: vi.fn(async () => panelOpen && !propertiesSelected), click: vi.fn(async () => { propertiesSelected = true; }) }); + const valueButton = chain({ click: vi.fn() }); + const value = chain({ getByRole: vi.fn(() => valueButton), textContent: vi.fn(async () => assigned ? "You" : "Unassigned") }); + const assignee = chain({ isVisible: vi.fn(async () => propertiesSelected), locator: vi.fn(() => value), + scrollIntoViewIfNeeded: vi.fn() }); + const locator = link; const assign = { click: vi.fn(async () => { assigned = true; }) }; - const page = { goto: vi.fn(), reload: vi.fn(), locator: vi.fn(() => locator), getByRole: vi.fn((_role: string, options?: { name?: unknown }) => options?.name === "Assign to me" ? assign : locator) }; + const page = { goto: vi.fn(), reload: vi.fn(async () => { panelOpen = false; propertiesSelected = false; }), locator: vi.fn(() => assignee), + getByRole: vi.fn((role: string, options?: { name?: unknown }) => options?.name === "Assign to me" ? assign + : role === "link" ? link : role === "option" ? propertiesOption : role === "tab" ? hidden + : options?.name === "Open a new tab" || options?.name === "Toggle side panel" ? hidden : opener) }; const get = vi.fn(async (route: string) => route.endsWith("/runs") ? [] : { assigneeUserId: assigned ? context.user.id : null, assigneeAgentId: null, status: "backlog" }); Object.assign(context.api, { get }); context.page = page as unknown as JourneyContext["page"]; @@ -202,6 +219,8 @@ describe("deployment journey contracts", () => { expect(session.own).toHaveBeenCalledTimes(2); expect(page.goto).toHaveBeenCalledExactlyOnceWith("https://qa.example.test/QA/issues"); expect(locator.filter).toHaveBeenCalledWith({ hasText: "Journey QA campaign-1" }); + expect(opener.click).toHaveBeenCalledTimes(2); + expect(propertiesOption.click).toHaveBeenCalledTimes(2); expect(assign.click).toHaveBeenCalledOnce(); expect(page.reload).toHaveBeenCalledOnce(); expect(get.mock.calls.map(([route]) => route)).toEqual(["/api/issues/task-1", "/api/issues/task-1", "/api/issues/task-1/runs"]); diff --git a/tests/runner-e2e/product-journeys/inbox-triage-flow.ts b/tests/runner-e2e/product-journeys/inbox-triage-flow.ts index baca8ab7ef8..c93acb94219 100644 --- a/tests/runner-e2e/product-journeys/inbox-triage-flow.ts +++ b/tests/runner-e2e/product-journeys/inbox-triage-flow.ts @@ -68,7 +68,15 @@ export async function inboxTriage(context: JourneyContext, session: TargetSessio await inboxStep("inbox_unread_projection_failed", () => expect.poll(async () => (await read()).isUnreadForMe).toBe(true)); await openPersonalInbox(context, "unread"); await inboxStep("inbox_unread_row_missing", () => expect(row).toBeVisible()); - await inboxStep("inbox_mark_read_failed", () => row.getByRole("button", { name: "Mark as read", exact: true }).click()); + await inboxStep("inbox_mark_read_failed", async () => { + const markRead = row.getByRole("button", { name: "Mark as read", exact: true }); + if (await markRead.isVisible()) return await markRead.click(); + await openPersonalInbox(context, "mine"); + await expect(row).toBeVisible(); + await page.getByPlaceholder(/^Search (?:inbox|tasks)(?:…|\.\.\.)$/i).blur(); + await row.hover(); + await page.keyboard.press("r"); + }); await inboxStep("inbox_read_projection_failed", () => expect.poll(async () => (await read()).isUnreadForMe).toBe(false)); await inboxStep("inbox_unread_reload_failed", () => page.reload()); await openPersonalInbox(context, "unread"); diff --git a/tests/runner-e2e/product-journeys/project-context-readback.ts b/tests/runner-e2e/product-journeys/project-context-readback.ts index 498e9c7a5f3..854dea3bdd8 100644 --- a/tests/runner-e2e/product-journeys/project-context-readback.ts +++ b/tests/runner-e2e/product-journeys/project-context-readback.ts @@ -1,4 +1,5 @@ import { expect, type Page } from "@playwright/test"; +import { showPropertyRow } from "./task-panel.js"; import { JourneyError } from "./types.js"; type BrowserStage = "project_list" | "project_open" | "project_task_open" | "project_property"; @@ -39,9 +40,7 @@ export async function openProjectTaskThroughList(input: { page: Page; origin: st await expect(main.getByText(prompt, { exact: true }).filter({ visible: true }).first()).toBeVisible(); }); await browserStep("project_property", async () => { - const properties = page.getByRole("button", { name: /^(Show properties|Properties)$/ }).filter({ visible: true }).first(); - if (await properties.isVisible()) await properties.click(); - const projectProperty = page.locator("[data-property-row]").filter({ has: page.locator('[data-property-label="Project"]') }).filter({ visible: true }); + const projectProperty = await showPropertyRow(page, "Project"); await expect(projectProperty).toHaveCount(1); await expect(projectProperty.locator("[data-property-value]")).toContainText(projectName); }); diff --git a/tests/runner-e2e/product-journeys/task-dependency-resume.test.ts b/tests/runner-e2e/product-journeys/task-dependency-resume.test.ts index fa694af7d1d..b6a4397a988 100644 --- a/tests/runner-e2e/product-journeys/task-dependency-resume.test.ts +++ b/tests/runner-e2e/product-journeys/task-dependency-resume.test.ts @@ -59,6 +59,7 @@ async function fixture(premature = false, options: FixtureOptions = {}) { if (key.includes("data-property-row")) return panelOpen && !options.missingProperty; if (key === "Toggle side panel") return !panelOpen && options.closedPanel === "toggle"; if (key.includes("Show properties")) return !panelOpen && options.closedPanel === "properties"; + if (key === "Open a new tab" || key === "/^Properties/") return false; return true; }, async scrollIntoViewIfNeeded() { actions.push(`scroll:${key}`); }, diff --git a/tests/runner-e2e/product-journeys/task-dependency-resume.ts b/tests/runner-e2e/product-journeys/task-dependency-resume.ts index ed13e309878..98bc71e6a88 100644 --- a/tests/runner-e2e/product-journeys/task-dependency-resume.ts +++ b/tests/runner-e2e/product-journeys/task-dependency-resume.ts @@ -1,4 +1,5 @@ import { randomBytes } from "node:crypto"; +import { showPropertyRow } from "./task-panel.js"; import { mkdir, writeFile } from "node:fs/promises"; import path from "node:path"; import { expect } from "@playwright/test"; @@ -29,20 +30,7 @@ const documentSnapshot = (row: Row) => Object.fromEntries(["id", "companyId", "i "documentId", "createdByAgentId", "createdByUserId", "createdByRunId"].map(key => [key, row[key]])); async function properties(context: JourneyContext, label: string) { - const { page } = context; - const row = page.locator('[data-property-row]:not([inert] *):not([aria-hidden="true"] *)') - .filter({ has: page.locator(`[data-property-label="${label}"]`) }).filter({ visible: true }); - const toggle = page.getByRole("button", { name: "Toggle side panel", exact: true, pressed: false }).filter({ visible: true }); - const propertiesButton = page.getByRole("button", { name: /^(Show properties|Properties)$/ }).filter({ visible: true }); - await expect.poll(async () => await row.isVisible() || await toggle.isVisible() || await propertiesButton.isVisible()).toBe(true); - if (!await row.isVisible()) { - if (await toggle.isVisible()) await toggle.click(); - else await propertiesButton.click(); - } - await expect(row).toBeVisible(); - await row.scrollIntoViewIfNeeded(); - await expect(row).toBeInViewport(); - return row; + return await showPropertyRow(context.page, label); } async function setStatus(context: JourneyContext, label: string) { const { page } = context; diff --git a/tests/runner-e2e/product-journeys/task-document-flow.test.ts b/tests/runner-e2e/product-journeys/task-document-flow.test.ts index 21b546778ee..cd353db0565 100644 --- a/tests/runner-e2e/product-journeys/task-document-flow.test.ts +++ b/tests/runner-e2e/product-journeys/task-document-flow.test.ts @@ -25,7 +25,7 @@ describe("task document reopen navigation", () => { expect(hasText).toBe(issue.title); return { first: () => ({ click }) }; } } - : { isVisible: async () => true, first: () => ({ isVisible: async () => true }) }, + : (() => { const visible = { isVisible: async () => true, filter: () => visible, first: () => visible }; return visible; })(), }, } as unknown as JourneyContext; await reopenTaskDocument(context, issue); diff --git a/tests/runner-e2e/product-journeys/task-document-flow.ts b/tests/runner-e2e/product-journeys/task-document-flow.ts index 32dd89d69c5..b48c98d30a1 100644 --- a/tests/runner-e2e/product-journeys/task-document-flow.ts +++ b/tests/runner-e2e/product-journeys/task-document-flow.ts @@ -1,26 +1,10 @@ import { expect } from "@playwright/test"; +import { openTaskPanelTab } from "./task-panel.js"; import { taskDocumentHistoryPasses, taskDocumentMatches, type TaskDocumentExpectation, type TaskDocumentRevision, type TaskDocumentSnapshot } from "./task-document-evidence.js"; import { JourneyError, type JourneyContext, type JourneyEvidence, type TargetSession } from "./types.js"; export async function openDocumentAuthoring({ page }: JourneyContext) { - const create = page.getByRole("button", { name: "New document", exact: true }); - const properties = page.getByRole("button", { name: /^(Show properties|Properties)$/ }).first(); - const artifacts = page.getByRole("tab", { name: /^Artifacts/ }).first(); - const addTab = page.getByRole("button", { name: "Open a new tab", exact: true }); - const panelReady = async () => await create.isVisible() || await artifacts.isVisible() || await addTab.isVisible(); - await expect.poll(async () => await properties.isVisible() || await panelReady()).toBe(true); - if (await create.isVisible()) return; - if (await properties.isVisible()) { - await properties.click(); - await expect.poll(panelReady).toBe(true); - if (await create.isVisible()) return; - } - if (await artifacts.isVisible()) await artifacts.click(); - else { - await addTab.click(); - await page.getByRole("option", { name: /^Artifacts/ }).click(); - } - await expect(create).toBeVisible(); + await openTaskPanelTab(page, "Artifacts", page.getByRole("button", { name: "New document", exact: true })); } export async function reopenTaskDocument(context: JourneyContext, issue: { title: string }) { diff --git a/tests/runner-e2e/product-journeys/task-lifecycle.ts b/tests/runner-e2e/product-journeys/task-lifecycle.ts index b2086f890cb..c25068b1555 100644 --- a/tests/runner-e2e/product-journeys/task-lifecycle.ts +++ b/tests/runner-e2e/product-journeys/task-lifecycle.ts @@ -3,6 +3,7 @@ import path from "node:path"; import { expect } from "@playwright/test"; import { createTaskThroughUi, withBrowserEvent } from "../user-actions.js"; import { createObservedReader } from "./observation-read.js"; +import { showPropertyRow } from "./task-panel.js"; import { taskLifecycleEvidence, taskLifecycleLabelName, type LifecycleExpectation, type LifecycleLabel, type LifecycleObservation, type LifecycleTask } from "./task-lifecycle-evidence.js"; import { JourneyError, type JourneyContext, type JourneyEvidence, type TargetSession } from "./types.js"; @@ -17,22 +18,7 @@ const emptyObservation = (): LifecycleObservation => ({ task: null, runCount: nu titleVisible: false, descriptionVisible: false, statusVisible: false, labelVisible: false }); async function properties(context: JourneyContext) { - const { page } = context; - // Closed panes keep their rows mounted. Their geometry alone does not make - // an inert or accessibility-hidden panel available for interaction. - const row = page.locator('[data-property-row]:not([inert] *):not([aria-hidden="true"] *)') - .filter({ has: page.locator('[data-property-label="Labels"]') }).filter({ visible: true }); - const toggle = page.getByRole("button", { name: "Toggle side panel", exact: true, pressed: false }).filter({ visible: true }); - const propertiesButton = page.getByRole("button", { name: /^(Show properties|Properties)$/ }).filter({ visible: true }); - await expect.poll(async () => await row.isVisible() || await toggle.isVisible() || await propertiesButton.isVisible()).toBe(true); - if (!await row.isVisible()) { - if (await toggle.isVisible()) await toggle.click(); - else await propertiesButton.click(); - } - await expect(row).toBeVisible(); - await row.scrollIntoViewIfNeeded(); - await expect(row).toBeInViewport(); - return row; + return await showPropertyRow(context.page, "Labels"); } async function setStatus(context: JourneyContext, label: string) { diff --git a/tests/runner-e2e/product-journeys/task-panel.ts b/tests/runner-e2e/product-journeys/task-panel.ts new file mode 100644 index 00000000000..7285dc2d47a --- /dev/null +++ b/tests/runner-e2e/product-journeys/task-panel.ts @@ -0,0 +1,37 @@ +import { expect, type Locator, type Page } from "@playwright/test"; + +export function visiblePropertyRow(page: Page, label: string): Locator { + return page.locator('[data-property-row]:not([inert] *):not([aria-hidden="true"] *)') + .filter({ has: page.locator(`[data-property-label="${label}"]`) }).filter({ visible: true }); +} + +export async function openTaskPanelTab(page: Page, tabName: "Properties" | "Artifacts", ready: Locator): Promise { + const name = new RegExp(`^${tabName}`); + const tab = page.getByRole("tab", { name }).filter({ visible: true }).first(); + const option = page.getByRole("option", { name }).filter({ visible: true }).first(); + const newTab = page.getByRole("button", { name: "Open a new tab", exact: true }).filter({ visible: true }).first(); + const opener = page.getByRole("button", { name: /^(Show properties|Properties)$/ }).filter({ visible: true }).first(); + const toggle = page.getByRole("button", { name: "Toggle side panel", exact: true, pressed: false }).filter({ visible: true }).first(); + const anyVisible = async (...locators: Locator[]) => { + for (const locator of locators) if (await locator.isVisible()) return true; + return false; + }; + for (let step = 0; step < 4; step++) { + await expect.poll(() => anyVisible(ready, tab, option, newTab, toggle, opener)).toBe(true); + if (await ready.isVisible()) return; + if (await option.isVisible()) await option.click(); + else if (await tab.isVisible()) await tab.click(); + else if (await newTab.isVisible()) await newTab.click(); + else if (await toggle.isVisible()) await toggle.click(); + else await opener.click(); + } + await expect(ready).toBeVisible(); +} + +export async function showPropertyRow(page: Page, label: string): Promise { + const row = visiblePropertyRow(page, label); + await openTaskPanelTab(page, "Properties", row); + await row.scrollIntoViewIfNeeded(); + await expect(row).toBeInViewport(); + return row; +} diff --git a/tests/runner-e2e/product-journeys/task-properties.ts b/tests/runner-e2e/product-journeys/task-properties.ts index ca836af1c8b..be0d0a513c6 100644 --- a/tests/runner-e2e/product-journeys/task-properties.ts +++ b/tests/runner-e2e/product-journeys/task-properties.ts @@ -1,4 +1,5 @@ import { expect } from "@playwright/test"; +import { showPropertyRow, visiblePropertyRow } from "./task-panel.js"; import { JourneyError, type JourneyContext, type JourneyEvidence, type TargetSession } from "./types.js"; export async function taskProperties(context: JourneyContext, _session: TargetSession, _campaignId: string, evidence: JourneyEvidence) { @@ -11,13 +12,14 @@ export async function taskProperties(context: JourneyContext, _session: TargetSe // The declared starting point is the task list. Navigation to the task is a user action. await page.goto(`${api.origin}/${company.issuePrefix}/issues`); await page.getByRole("link").filter({ hasText: issue.title }).first().click(); - const properties = page.getByRole("button", { name: /^(Show properties|Properties)$/ }).first(); - if (await properties.isVisible()) await properties.click(); - const assignee = page.locator("[data-property-row]").filter({ has: page.locator('[data-property-label="Assignee"]') }); + const assignee = visiblePropertyRow(page, "Assignee"); + const showAssignee = () => showPropertyRow(page, "Assignee"); + await showAssignee(); await assignee.locator("[data-property-value]").getByRole("button").first().click(); await page.getByRole("button", { name: "Assign to me", exact: true }).click(); await expect.poll(async () => (await api.get<{ assigneeUserId: string }>(`/api/issues/${issue.id}`)).assigneeUserId).toBe(user.id); await page.reload(); + await showAssignee(); await expect(assignee.locator("[data-property-value]")).toContainText("You"); const persisted = await api.get<{ assigneeUserId: string; assigneeAgentId: string | null; status: string }>(`/api/issues/${issue.id}`); if (persisted.assigneeUserId !== user.id || persisted.assigneeAgentId !== null || persisted.status !== "backlog") throw new JourneyError("failed", "assignment_persistence_mismatch"); From 45125f77485ef8b8987f43325eaf37a91748fa83 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:10:11 -0600 Subject: [PATCH 02/12] test(server): stop the accounting identity child from timing out on loaded runners (#21712) 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 server CI runs the general test suite in 12 shards on shared runners > - One accounting test fails at random on unrelated pull requests and passes on re-run > - Each failure costs a full re-run of the shard and the `verify` job, and it teaches people to re-run instead of read > - The test spawns two helper processes that load about 1,400 TypeScript modules under a 5 second kill timer > - This pull request makes the helper processes plain `node` processes, so they do not load the server module graph > - The benefit is that the test no longer depends on runner load, and it still uses real exited processes ## Linked Issues or Issue Description **What happened?** `server/src/services/run-cost-accounting.test.ts > run cost accounting work > normal accounting Retry reconstructs an uncommitted legacy receipt after its real controller and child exited` failed in "General tests (server (5/12))" three times on 2026-11-15 (UTC), each with the retry also failing: - PR #21687, head `2172a5b26a`, job 132643921517 - PR #21687, head `6a1d2fb0ef`, job 132650244103 - PR #21678, head `fc0e96f23c`, job 132663296537 Every failure has the same assertion: `AssertionError: {"exitCode":null,"signal":"SIGTERM","timedOut":true,...,"stderrTail":"accounting-identity:program-entered\naccounting-identity:module-imported\n"}: expected null to be +0` In five of the six failed attempts, the child stopped after `module-imported` and before `birth-read`. In one attempt, the child printed its result but the 5 second timer fired before it exited. **Expected behavior** The test passes on a loaded runner. The helper processes are not under test. Only the accounting Retry decision is under test. **Steps to reproduce** 1. Slow each module load in the child by 8 ms with an `--import` hook in `NODE_OPTIONS`. The test passes `NODE_OPTIONS` to the child. This simulates a loaded runner. 2. Run `npx vitest run src/services/run-cost-accounting.test.ts -t "normal accounting Retry"` in `server/`. 3. On `master` the test fails with the same `timedOut: true` assertion as CI. **Root cause** The child ran `node --import tsx/esm -e "await import('controller-process-identity.ts'); await currentProcessStartedAtMs(); ..."`. That import pulls in `@paperclipai/shared` and `@paperclipai/db` source through tsx, which is 737 modules. On Linux, `readProcessStartedAt` also dynamically imports the full runner package shim (`server/src/vendor/paperclip-runner/index.ts`) to call the 30-line `/proc` reader. That adds 652 more modules. tsx transpiles all of them in a cold process under a 5 second `timeoutSec`. On a shared CI runner this crosses 5 seconds. **Production impact** None. In the built server, the runner package is already loaded at boot, and `currentProcessStartedAtMs()` on Linux reads `/proc` once per process and caches the result. The cost exists only in a fresh tsx process that imports source. ## What Changed - The accounting identity helper child is now `node -e` with no tsx loader and no module imports. It installs a `SIGUSR2` handler, prints `ready`, and waits. - When the test sees `ready`, it reads the child start time with the product function `observedProcessStartedAt(pid)` and then sends `SIGUSR2`. The child exits with code 0. - The test builds the recorded `ControllerProcess` (random boot id, child pid, `currentProcessSpaceHash()`, observed start time). These are the same values the child computed for itself before. The child process is still real, has its own process group, and has exited before the Retry checks run. - No retries, skips or timeout changes. The 5 second guard now covers a plain `node` start, which takes about 40 ms. ## Verification - Red on `master` with the slow-load hook: `Tests 1 failed`, `timedOut: true`, the same assertion as CI. - Green with this change and the same hook: `Tests 1 passed`. - Full file without the hook: `npx vitest run src/services/run-cost-accounting.test.ts` passes 34/34. - Helper loop, 30 runs per variant, macOS, 18 cores with 36 busy-loop processes (load average about 56): - old child (macOS path): 29/30 exited in 5 s, p50 2,020 ms, p90 2,234 ms, max 5,172 ms - old child plus the runner import (as on Linux CI): 29/30, p50 3,663 ms, p90 4,411 ms, max 5,023 ms - new child: 30/30, p50 38 ms, p90 43 ms, max 46 ms - The full test under the same stress: 6/6 before and 6/6 after on macOS. macOS uses the `ps` path and does not load the runner package, so this loop does not show the Linux failure. The helper loop and the slow-load repro do show it. - `npx tsc --noEmit -p server/tsconfig.json` passes. - Other tests with the same pattern: `native-controller-source-digest.test.ts` also spawns a tsx child, but with a 60 second timeout. It is not the same cause, so this pull request does not change it. ## Risks - Low risk. Only one test changes. No product code changes. - The test no longer checks that a separate process computes its own identity stamp. That was not the purpose of this test. Other tests cover `currentControllerProcessStamp()`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edit, GitHub CLI). ## 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 --- .../src/services/run-cost-accounting.test.ts | 40 +++++++++---------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/server/src/services/run-cost-accounting.test.ts b/server/src/services/run-cost-accounting.test.ts index f6b19147456..6c158459e38 100644 --- a/server/src/services/run-cost-accounting.test.ts +++ b/server/src/services/run-cost-accounting.test.ts @@ -3,9 +3,8 @@ import { databaseWorkPending, reconcileDatabaseWork } from "@paperclipai/db/work import { promises as fs } from "node:fs"; import os from "node:os"; import path from "node:path"; -import { fileURLToPath } from "node:url"; import { runChildProcess } from "../adapters/utils.js"; -import { currentControllerProcessStamp, currentProcessStartedAtMs, type ControllerProcess } from "./controller-process-identity.js"; +import { currentControllerProcessStamp, currentProcessSpaceHash, currentProcessStartedAtMs, observedProcessStartedAt, type ControllerProcess } from "./controller-process-identity.js"; import { currentProcessProbe } from "./owner-proof.js"; import { proveRunProcessGone } from "./run-process-owner.js"; import { and, eq, sql } from "drizzle-orm"; @@ -148,28 +147,25 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu }); it.skipIf(process.platform === "win32")("normal accounting Retry reconstructs an uncommitted legacy receipt after its real controller and child exited", async () => { - const identityModule = new URL('./controller-process-identity.ts', import.meta.url).href; - const loader = fileURLToPath(import.meta.resolve('tsx/esm')); async function joinedIdentity() { - const command = `console.error("accounting-identity:program-entered"); const identity = await import(${JSON.stringify(identityModule)}); console.error("accounting-identity:module-imported"); await identity.currentProcessStartedAtMs(); console.error("accounting-identity:birth-read"); console.log(JSON.stringify(identity.currentControllerProcessStamp()));`; - let groupId: number | null = null; - let observedStderrChars = 0; - const result = await runChildProcess(randomUUID(), process.execPath, - ['--import', loader, '--input-type=module', '-e', command], { - cwd: process.cwd(), env: { NODE_OPTIONS: process.env.NODE_OPTIONS ?? '', PATH: process.env.PATH ?? '' }, - timeoutSec: 5, graceSec: 1, onLog: async (stream, chunk) => { - if (stream === "stderr" && observedStderrChars < 8192) { - const observed = chunk.slice(0, 8192 - observedStderrChars); - observedStderrChars += observed.length; - process.stderr.write(observed); - } - }, - onSpawn: async meta => { groupId = meta.processGroupId ?? null; }, - }); - expect(result.exitCode, JSON.stringify({ exitCode: result.exitCode, signal: result.signal, timedOut: result.timedOut, pid: result.pid, startedAt: result.startedAt, stdoutTail: result.stdout.slice(-8192), stderrTail: result.stderr.slice(-8192) })).toBe(0); - const identity = JSON.parse(result.stdout.trim()) as ControllerProcess; - expect(identity.processStartedAt).not.toBeNull(); + const command = `process.on("SIGUSR2", () => process.exit(0)); setInterval(() => {}, 60_000); process.stdout.write("ready\\n");`; + let pid: number | null = null, groupId: number | null = null, startedAt: number | null = null, released = false; + const result = await runChildProcess(randomUUID(), process.execPath, ['-e', command], { + cwd: process.cwd(), env: { PATH: process.env.PATH ?? '' }, + timeoutSec: 5, graceSec: 1, + onSpawn: async meta => { pid = meta.pid; groupId = meta.processGroupId ?? null; }, + onLog: async (stream, chunk) => { + if (stream !== "stdout" || released || pid === null || !chunk.includes("ready")) return; + released = true; + startedAt = await observedProcessStartedAt(pid); + process.kill(pid, "SIGUSR2"); + }, + }); + expect(result.exitCode, JSON.stringify({ exitCode: result.exitCode, signal: result.signal, timedOut: result.timedOut, pid: result.pid, stdoutTail: result.stdout.slice(-8192), stderrTail: result.stderr.slice(-8192) })).toBe(0); + expect(startedAt).not.toBeNull(); expect(Number.isSafeInteger(groupId) && groupId! > 1).toBe(true); + const identity: ControllerProcess = { bootId: randomUUID(), pid: pid!, hostHash: currentProcessSpaceHash(), + processStartedAt: new Date(startedAt!).toISOString() }; return { ...identity, groupId }; } const controller = await joinedIdentity(), child = await joinedIdentity(); From 554e6d415c34d5208aedf1de653318c61ddd5c4f Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:12:52 -0600 Subject: [PATCH 03/12] fix(restart-chaos): credit a follow-up only to a run that started a provider turn, and post a missed follow-up after the run ends (#21692) 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 restart-chaos harness runs staging-mix waves across server swaps and grades each task for duplicate side effects, extra turns and follow-up delivery > - In one wave, the grader reported two false failures > - Task t005: the grader credited a follow-up to a run that failed before its provider turn. It then counted the run that really served the follow-up as a duplicate completion and an extra turn > - Task t009: the agent finished before the follow-up window opened. The harness never posted the follow-up, but the grader still required the post > - False failures hide real regressions, so the grader must match what the product did > - This pull request credits a follow-up only to a run that started a provider turn, and posts a missed follow-up after the run ends > - The benefit is that both false failures go away, and the t009 case still tests the product: the product must answer the late follow-up ## Linked Issues or Issue Description Refs #21598 **What happened?** In wave `w-20261114T231451-s7110`, two tasks failed on harness defects, not product defects. - t005 (`T:completion_once`, a duplicate side effect and an extra turn): run 76f30f70 was woken for follow-up comment 3f6a9eb9. It failed before any provider turn, so the agent never received the comment. Recovery run fdf1f793 served the comment. It added the FOLLOWUP line and did not post DONE again (DONE comments = 1). The grader credited 76f30f70 with the answer and flagged fdf1f793 as a second completion and an extra turn. - t009 (`T:follow_up_posted`): the follow-up was due at 23:25:19. The harness posts only during a swap overlap (opened 23:28:02.7) or at the 85% point (about 23:29:15). The agent finished at 23:27:56.0, so the harness never posted. The grader still required the post. **Expected behavior** - t005 grades one completer (60bdd4dc) and no extra turn. fdf1f793 is the run that answered the follow-up. - t009 gets its follow-up after the run ends. The grade then requires the product to answer it. **Steps to reproduce** 1. Build wake evidence with three runs: a done run, a run woken by a follow-up comment that has no provider turn, and a recovery run that re-completes. 2. Grade with `gradeStagingMix`, `completedAtAnchor` and `runsAfterDone`. 3. Drive `stagingMixStep` with the t009 timings: the run ends before the overlap and before the 85% point. ## What Changed - `tests/restart-chaos/wake-evidence.ts`: record `providerTurnStarted` for each run. It is true when the run has a `turn.submitted`, `turn.accepted` or `turn.started` run event. - `tests/restart-chaos/follow-up-delivery.ts`: a run with `providerTurnStarted: false` does not receive its comments. The comments carry to the next run that starts a provider turn. That run is the answering run. Add `undeliveredFollowUpRuns`. Evidence without the field keeps the old behavior. - `tests/restart-chaos/staging-mix-retry.ts`: `runsAfterDone` does not list a run that failed before it could deliver a follow-up as an extra turn. - `tests/restart-chaos/staging-mix.ts`: when no run is active after the hold or the 85% point, `stagingMixStep` posts the follow-up after the run ended. It records the post as an after-end follow-up, so `after_end_follow_ups_served` requires an agent reply and the ledger line. The `follow_up_posted` detail says "after the run ended". - `tests/restart-chaos/observer.ts`: a staging-mix task with an unposted follow-up does not finish yet. - Tests and `tests/restart-chaos/README.md`. ## Verification - Red on master, green with the fix: - `a follow-up whose run failed before any provider turn (w-20261114T231451-s7110 t005) > credits the follow-up to the run that served it, with one completer and no extra turn` - `... > lets only the serving run re-complete, and still fails a later recovery run that answers nothing` - `staging-mix board step > posts a follow-up the run finished before as an after-end follow-up the product must answer (w-20261114T231451-s7110 t009)` - `staging-mix board step > does not post an after-end follow-up between runs before the during-run window closes, or while a run is queued` - `TaskObserver > does not finish a staging-mix task whose run ended before its planned follow-up was posted` - Guards that still grade as failures on master and with the fix: - `... t005 > still fails a recovery re-completion when the run that received the follow-up started its provider turn` - `a done the server rejected as incomplete > keeps a run woken by recovery after a real completion as an extra turn and a duplicate completion (G5c t004)` (#21598) - `completion_once truth table: a later completion that answers nothing` - `wake evidence against real PostgreSQL` now checks `providerTurnStarted` false, then true after a `turn.started` event. - `npx vitest run --config tests/restart-chaos/vitest.config.ts --maxWorkers=3`: 71 files, 823 tests pass. - `tsc -p tests/restart-chaos/tsconfig.json --noEmit`: clean. - Not run: a new wave. The wave's database is gone, so the real t005 evidence cannot get `providerTurnStarted` from the new query. The tests use the real t005 and t009 values. ## Risks - Low risk. The change affects only the restart-chaos harness. - A run that failed after `turn.submitted` but before the provider read the input counts as a delivery. This keeps the grader strict: it can report a false duplicate, but it cannot hide a real one. - A staging-mix task with a planned follow-up that cannot be posted now waits until its deadline instead of resting. The grade still reports the post errors. ## Model Used - Anthropic Claude Opus 5.5 (`claude-opus-5-5`), via Claude Code with tool use and code execution. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [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 --- tests/restart-chaos/README.md | 11 ++- tests/restart-chaos/follow-up-delivery.ts | 34 +++++++-- tests/restart-chaos/observer.test.ts | 25 +++++++ tests/restart-chaos/observer.ts | 1 + tests/restart-chaos/staging-mix-retry.test.ts | 71 +++++++++++++++++++ tests/restart-chaos/staging-mix-retry.ts | 8 ++- tests/restart-chaos/staging-mix.test.ts | 40 +++++++++++ tests/restart-chaos/staging-mix.ts | 19 +++-- tests/restart-chaos/wake-evidence.test.ts | 7 +- tests/restart-chaos/wake-evidence.ts | 7 +- 10 files changed, 201 insertions(+), 22 deletions(-) diff --git a/tests/restart-chaos/README.md b/tests/restart-chaos/README.md index 46b5d94723f..99faafee805 100644 --- a/tests/restart-chaos/README.md +++ b/tests/restart-chaos/README.md @@ -1584,6 +1584,11 @@ tried again on the next poll with the same `clientRequestId`. The overlap window `staging-mix.ts`, which a swap driver registers. Without a probe, the window is any time a fault is in progress and the server still answers (a K15 overlap). The timeline records `staging_mix_follow_up`. +When no run is active once the hold or the 85% point has passed (the agent finished early), the harness posts the +follow-up after the run ended instead. The task then waits for that post before it counts as finished, and the post is +graded like an after-end follow-up: `after_end_follow_ups_served` needs an agent comment after it and the +`FOLLOWUP-` ledger line. The `follow_up_posted` detail says "after the run ended". + To aim a follow-up at the warm session's idle close instead, set `RESTART_CHAOS_MIX_FOLLOW_UP_AFTER_END_MS=-` (for example `298000-306000` for the 300 s idle timeout). The harness then posts the follow-up that long after the task's last run ended, `RESTART_CHAOS_MIX_FOLLOW_UP_COUNT` times (default 2), and waits for every post before the task @@ -1643,7 +1648,11 @@ started from a wake that carries a person's comment posted after the task's firs wake payload's `commentId`) is a required run. This includes the retry of a failed attempt for the same comment. OpenCode, for example, takes no input mid-turn, so a comment posted during its turn is answered by the next run. Such runs are listed under "Follow-ups the running turn did not receive, answered in a later run" (`followUpsAnsweredLater`, -`followUpWaits`). An extra turn is a run that started after completion from a wake that carries no comment. The +`followUpWaits`). An extra turn is a run that started after completion from a wake that carries no comment. A run +counts as having received its comments only when it started a provider turn (a `turn.submitted`, `turn.accepted` or +`turn.started` run event, `providerTurnStarted` in the wake evidence). When a run fails before any provider turn, its +comments carry to the next run that starts one: that run is the required run and may re-complete the task, and the +failed run is not an extra turn. Wake evidence without `providerTurnStarted` counts every started run as a delivery. The server's delivery rule (`task_history.read`, cited evidence, child-result reads) is covered by the server's own tests. `completion_once` stays the independent side-effect check. The first run that reported completion is always the diff --git a/tests/restart-chaos/follow-up-delivery.ts b/tests/restart-chaos/follow-up-delivery.ts index 88b78754a0a..cc4c40e6c30 100644 --- a/tests/restart-chaos/follow-up-delivery.ts +++ b/tests/restart-chaos/follow-up-delivery.ts @@ -6,6 +6,7 @@ export interface DeliveryRun { startedAt?: number | null; wakeupRequestId: string | null; contextSnapshot?: unknown; + providerTurnStarted?: boolean | null; } export interface DeliveryWake { id: string | null; createdAt?: number | null; payload?: unknown } @@ -30,23 +31,44 @@ export function wakeInputCommentIds(run: Pick, w ...strings(payload.commentId), ...strings(wakeContext.wakeCommentIds), ...strings(wakeContext.wakeCommentId)])]; } -export function laterAnswers(evidence: { runs?: readonly DeliveryRun[]; wakes?: readonly DeliveryWake[] } | null): Map { +const earliest = (a: number | null, b: number | null) => a === null ? b : b === null ? a : Math.min(a, b); + +type DeliveryEvidence = { runs?: readonly DeliveryRun[]; wakes?: readonly DeliveryWake[] } | null; + +function followUpDeliveries(evidence: DeliveryEvidence): { answers: Map; undelivered: Set } { const answers = new Map(); - if (!evidence) return answers; + const undelivered = new Set(); + if (!evidence) return { answers, undelivered }; const wakes = new Map((evidence.wakes ?? []).map(wake => [wake.id, wake])); const started = (evidence.runs ?? []).filter((run): run is DeliveryRun & { runId: string; startedAt: number } => Boolean(run.runId) && typeof run.startedAt === "number") .sort((a, b) => a.startedAt - b.startedAt); const firstStart = started[0]?.startedAt ?? null; + let carried: { commentIds: string[]; postedAt: number | null } | null = null; started.forEach((run, index) => { const wake = run.wakeupRequestId ? wakes.get(run.wakeupRequestId) : undefined; - const owed = wakeInputCommentIds(run, wake); const postedAt = typeof wake?.createdAt === "number" ? wake.createdAt : null; const postedDuringWork = postedAt !== null && firstStart !== null ? postedAt >= firstStart : index > 0; - if (index > 0 && postedDuringWork && owed.length) { - answers.set(run.runId, { runId: run.runId, commentIds: owed, postedAt, queuedAt: run.createdAt, startedAt: run.startedAt }); + const owed = index > 0 && postedDuringWork ? wakeInputCommentIds(run, wake) : []; + const commentIds = [...new Set([...(carried?.commentIds ?? []), ...owed])]; + if (!commentIds.length) return; + const firstPostedAt = owed.length ? earliest(carried?.postedAt ?? null, postedAt) : carried?.postedAt ?? null; + if (run.providerTurnStarted === false) { + carried = { commentIds, postedAt: firstPostedAt }; + undelivered.add(run.runId); + return; } + carried = null; + answers.set(run.runId, { runId: run.runId, commentIds, postedAt: firstPostedAt, queuedAt: run.createdAt, startedAt: run.startedAt }); }); - return answers; + return { answers, undelivered }; +} + +export function laterAnswers(evidence: DeliveryEvidence): Map { + return followUpDeliveries(evidence).answers; +} + +export function undeliveredFollowUpRuns(evidence: DeliveryEvidence): Set { + return followUpDeliveries(evidence).undelivered; } export const COMPLETION_INCOMPLETE_KEY = "native-completion-incomplete"; diff --git a/tests/restart-chaos/observer.test.ts b/tests/restart-chaos/observer.test.ts index 999dda01c42..c1316211f36 100644 --- a/tests/restart-chaos/observer.test.ts +++ b/tests/restart-chaos/observer.test.ts @@ -84,6 +84,31 @@ describe("TaskObserver", () => { } }); + it("does not finish a staging-mix task whose run ended before its planned follow-up was posted", async () => { + let endedAt = 0; + const { api, posted } = fakeApi({ "/runs": () => [{ runId: "r1", status: "succeeded", createdAt: new Date(endedAt - 1_000).toISOString(), + finishedAt: new Date(endedAt).toISOString() }] }); + const followUpAfterMs = REST_CONFIRM_MS + 500; + const mixPlan: TaskPlan = { ...plan, workload: "SM", fault: "K0", followUpAfterMs: null, + stagingMix: { turnMinutes: 2, rounds: 2, subtasks: 0, followUpAfterMs, arriveAtMs: 0, holdMs: 0 } }; + const observer = new TaskObserver(mixPlan, api, lab, new Timeline(null), ready); + await observer.launch(); + const start = observer.record.createdAt!; + endedAt = start; + const comments = () => posted.filter(route => route.endsWith("/comments")).length; + await observer.poll(start + 100); + await observer.poll(start + 100 + REST_CONFIRM_MS + 1); + expect(comments()).toBe(0); + expect(observer.done).toBe(false); + await observer.poll(start + followUpAfterMs + 200); + expect(comments()).toBe(1); + expect(observer.record.stagingMix?.followUp).toMatchObject({ duringRun: false }); + expect(observer.done).toBe(false); + await observer.poll(start + followUpAfterMs + 300); + await observer.poll(start + followUpAfterMs + 400 + REST_CONFIRM_MS); + expect(observer.done).toBe(true); + }); + it("keeps watching unexplained idle work until the stall limit, then records the stall", async () => { const { api } = fakeApi({}, "in_progress"); const observer = new TaskObserver({ ...plan, workload: "A1", followUpAfterMs: null }, api, lab, new Timeline(null), ready); diff --git a/tests/restart-chaos/observer.ts b/tests/restart-chaos/observer.ts index ec339633307..0d10c55eb35 100644 --- a/tests/restart-chaos/observer.ts +++ b/tests/restart-chaos/observer.ts @@ -881,6 +881,7 @@ export class TaskObserver { if (isRewakeWorkload(this.plan.workload)) return awaitingRewake(this.record); const afterEnd = followUpAfterEndRange(); if (afterEnd && this.plan.stagingMix?.followUpAfterMs != null) return (this.record.stagingMix?.afterEndFollowUps?.length ?? 0) < afterEnd.count; + if (this.plan.stagingMix?.followUpAfterMs != null && !this.record.stagingMix?.followUp) return true; return false; } diff --git a/tests/restart-chaos/staging-mix-retry.test.ts b/tests/restart-chaos/staging-mix-retry.test.ts index 8e2dd18b5a3..8d99ee8a8c4 100644 --- a/tests/restart-chaos/staging-mix-retry.test.ts +++ b/tests/restart-chaos/staging-mix-retry.test.ts @@ -483,3 +483,74 @@ describe("staging-mix completion from accepted results", () => { expect(stagingMixDescription(nonce, { turnMinutes: 5, rounds: 4, subtasks: 0, followUpAfterMs: null, arriveAtMs: 0, holdMs: 0 })).toContain("Post exactly one comment"); }); }); + +describe("a follow-up whose run failed before any provider turn (w-20261114T231451-s7110 t005)", () => { + const nonce = "0c544491"; + const comment = "3f6a9eb9-29d9-47d6-a434-a222769dbc54"; + const first = "60bdd4dc-0dde-4052-9a4d-b81924aa70c1", undelivered = "76f30f70-f42f-4e8f-bef8-71e0ae1b33a3", served = "fdf1f793-95a3-4b90-a196-389ef4416c3d"; + const t005 = (undeliveredTurn: boolean): WakeEvidenceFile => ({ + completedAt: 1_794_699_341_813, + runs: [{ runId: first, createdAt: 1_794_698_171_163, startedAt: 1_794_698_171_226, invocationSource: "assignment", triggerDetail: "system", + wakeupRequestId: "035375c8", acceptedDisposition: "done", acceptedAt: 1_794_699_137_418, finishedAt: 1_794_699_138_705, status: "succeeded", providerTurnStarted: true }, + { runId: undelivered, createdAt: 1_794_699_138_879, startedAt: 1_794_699_139_744, invocationSource: "automation", triggerDetail: "system", + wakeupRequestId: "7aa52728", acceptedDisposition: null, acceptedAt: null, finishedAt: 1_794_699_184_470, status: "failed", + contextSnapshot: { wakeCommentIds: [comment], wakeCommentId: comment }, providerTurnStarted: undeliveredTurn }, + { runId: served, createdAt: 1_794_699_254_459, startedAt: 1_794_699_303_349, invocationSource: "automation", triggerDetail: "system", + wakeupRequestId: "fb81665c", acceptedDisposition: "done", acceptedAt: 1_794_699_340_097, finishedAt: 1_794_699_341_889, status: "succeeded", providerTurnStarted: true }], + wakes: [{ id: "035375c8", reason: "issue_assigned", source: "assignment", triggerDetail: "system", requestedByActorType: "user", requestedByActorId: "local-board", + createdAt: 1_794_698_171_163 }, + { id: "7aa52728", reason: "issue_execution_promoted", source: "automation", triggerDetail: "system", requestedByActorType: "user", requestedByActorId: "local-board", + createdAt: 1_794_698_885_238, payload: { commentId: comment, _paperclipWakeContext: { wakeCommentIds: [comment] } } }, + { id: "fb81665c", reason: "issue_recovery_action_restored", source: "automation", triggerDetail: "system", requestedByActorType: "system", + requestedByActorId: "execution-recovery", createdAt: 1_794_699_254_459 }], + }); + const posted = commentEvidence([ + { body: "Ledger document now includes the FOLLOWUP line.", authorAgentId: "a", createdByRunId: served, createdAt: "2026-11-14T23:35:42.025Z" }, + { body: "Done. All 10 rounds completed.", authorAgentId: "a", createdByRunId: first, createdAt: "2026-11-14T23:32:18.864Z" }, + { body: doneMarker(nonce), authorAgentId: "a", createdByRunId: first, createdAt: "2026-11-14T23:32:05.368Z" }]); + const completionOnce = (comments: typeof posted, completion: CompletionEvidence) => gradeStagingMix(nonce, + { turnMinutes: 14, rounds: 4, subtasks: 0, followUpAfterMs: 497_251, arriveAtMs: 20_000, holdMs: 600_000 }, + { issueStatus: "done", documents: { ledger: `${ledger(nonce, 4)}\nFOLLOWUP-${nonce}` }, agentComments: [], files: {}, commands: {}, workspacePath: null, + stagingMix: { followUp: { at: 1_794_698_884_902, commentId: comment, duringRun: true, inOverlap: true, error: null }, followUpErrors: [], retries: [], comments, + completion } }).checks.find(check => check.name === "completion_once")!; + const both = (evidence: WakeEvidenceFile) => [evidenceCompletion(evidence)!, completionEvidence({ completedAt: evidence.completedAt!, wakes: evidence.wakes, + runs: evidence.runs!.map(run => ({ ...run, acceptedDisposition: run.acceptedDisposition ?? null, acceptedAt: run.acceptedAt ?? null })) })]; + + it("credits the follow-up to the run that served it, with one completer and no extra turn", () => { + const evidence = t005(false); + expect(followUpsAnsweredLater("t005", evidence)).toEqual([{ taskId: "t005", runId: served, commentIds: [comment], postedAt: 1_794_698_885_238, + queuedAt: 1_794_699_254_459, startedAt: 1_794_699_303_349 }]); + for (const completion of both(evidence)) { + const anchor = completedAtAnchor(completion, posted, nonce); + expect(anchor).toEqual({ at: 1_794_699_137_418, source: "accepted_result" }); + expect(completionRunIds(posted, nonce, completion)).toEqual([first]); + const after = runsAfterDone("t005", evidence, anchor); + expect(after.started).toEqual([]); + expect(after.answeredFollowUp.map(turn => turn.runId)).toEqual([served]); + expect(completionOnce(posted, completion)).toMatchObject({ ok: true, detail: "runs=1" }); + } + }); + + it("still fails a recovery re-completion when the run that received the follow-up started its provider turn", () => { + const evidence = t005(true); + for (const completion of both(evidence)) { + const anchor = completedAtAnchor(completion, posted, nonce); + expect(runsAfterDone("t005", evidence, anchor).started.map(turn => [turn.runId, turn.wakeReason])).toEqual([[served, "issue_recovery_action_restored"]]); + expect(completionOnce(posted, completion)).toMatchObject({ ok: false, detail: "duplicate completion: runs 60bdd4dc, fdf1f793 each reported completion" }); + } + }); + + it("lets only the serving run re-complete, and still fails a later recovery run that answers nothing", () => { + const extra = "8e8e8e8e-extra"; + const evidence = t005(false); + evidence.runs!.push({ runId: extra, createdAt: 1_794_699_400_000, startedAt: 1_794_699_400_100, invocationSource: "automation", triggerDetail: "system", + wakeupRequestId: "w-extra", acceptedDisposition: "done", acceptedAt: 1_794_699_410_000, status: "succeeded", providerTurnStarted: true }); + evidence.wakes!.push({ id: "w-extra", reason: "issue_recovery_action_restored", source: "automation", triggerDetail: "system", requestedByActorType: "system", + requestedByActorId: "execution-recovery", createdAt: 1_794_699_400_000 }); + for (const completion of both(evidence)) { + const anchor = completedAtAnchor(completion, posted, nonce); + expect(runsAfterDone("t005", evidence, anchor).started.map(turn => turn.runId)).toEqual([extra]); + expect(completionOnce(posted, completion)).toMatchObject({ ok: false, detail: "duplicate completion: runs 60bdd4dc, 8e8e8e8e each reported completion" }); + } + }); +}); diff --git a/tests/restart-chaos/staging-mix-retry.ts b/tests/restart-chaos/staging-mix-retry.ts index 8d286197c19..89c4b329a6f 100644 --- a/tests/restart-chaos/staging-mix-retry.ts +++ b/tests/restart-chaos/staging-mix-retry.ts @@ -6,7 +6,7 @@ import { bannerShownMs, completedAtAnchor, doneCommentsBeforeCompletion, DUPLICATE_CHECKS, firstDoneCommentAt, noteRetryBanner, type CompletionEvidence, } from "./staging-mix.js"; import type { InterruptionSample, OracleResult, TaskPlan, TaskRecord, TaskSample } from "./types.js"; -import { laterAnswers, laterAnswerWaits, rejectedDoneRuns, type LaterAnswer } from "./follow-up-delivery.js"; +import { laterAnswers, laterAnswerWaits, rejectedDoneRuns, undeliveredFollowUpRuns, type LaterAnswer } from "./follow-up-delivery.js"; type Json = Record; @@ -192,7 +192,8 @@ export interface ExtraTurn { export interface WakeEvidenceFile { completedAt?: number | null; runs?: Array<{ runId: string | null; createdAt: number | null; startedAt?: number | null; invocationSource: string | null; triggerDetail: string | null; - wakeupRequestId: string | null; acceptedDisposition?: string | null; acceptedAt?: number | null; finishedAt?: number | null; contextSnapshot?: unknown; status?: string | null }>; + wakeupRequestId: string | null; acceptedDisposition?: string | null; acceptedAt?: number | null; finishedAt?: number | null; contextSnapshot?: unknown; status?: string | null; + providerTurnStarted?: boolean | null }>; wakes?: Array<{ id: string | null; reason: string | null; source: string | null; triggerDetail: string | null; requestedByActorType: string | null; requestedByActorId: string | null; createdAt?: number | null; payload?: unknown }>; } @@ -232,9 +233,10 @@ export function runsAfterDone(taskId: string, evidence: WakeEvidenceFile | null, }; const runs = evidence.runs ?? []; const afterDone = runs.filter(run => run.startedAt != null && run.startedAt > doneAt); + const undelivered = undeliveredFollowUpRuns(evidence); const answered = (run: (typeof runs)[number]) => Boolean(run.runId && answers.has(run.runId)); return { - started: afterDone.filter(run => !answered(run)).map(turn), + started: afterDone.filter(run => !answered(run) && !(run.runId && undelivered.has(run.runId))).map(turn), neverStarted: runs.filter(run => run.startedAt == null && run.createdAt !== null && run.createdAt > doneAt).map(turn), answeredFollowUp: afterDone.filter(answered).map(turn), }; diff --git a/tests/restart-chaos/staging-mix.test.ts b/tests/restart-chaos/staging-mix.test.ts index c6c82ef5cbc..81f7d9cba1f 100644 --- a/tests/restart-chaos/staging-mix.test.ts +++ b/tests/restart-chaos/staging-mix.test.ts @@ -296,6 +296,46 @@ describe("staging-mix board step", () => { expect(late.stagingMix!.followUp!.inOverlap).toBe(false); }); + it("posts a follow-up the run finished before as an after-end follow-up the product must answer (w-20261114T231451-s7110 t009)", async () => { + const createdAt = 1_794_698_190_262, finishedAt = 1_794_698_875_995, latestAt = createdAt + Math.round(10 * ROUND_SECONDS * 1_000 * 0.85); + const plan = task({ turnMinutes: 15, rounds: 10, followUpAfterMs: 529_234, arriveAtMs: 40_000, holdMs: 600_000 }); + const live: TaskSample = { ...running, runs: [{ ...running.runs![0]!, id: "6dfb753b", createdAt: new Date(createdAt + 26).toISOString() }] }; + const ended: TaskSample = { ...live, issueStatus: "done", runs: [{ ...live.runs![0]!, status: "succeeded", finishedAt: new Date(finishedAt).toISOString() }] }; + const rec = record({ createdAt }); + expect((await stepIn(rec, live, createdAt + 529_234 + 10_000, false, plan)).posted).toEqual([]); + expect((await stepIn(rec, live, finishedAt - 1_000, false, plan)).posted).toEqual([]); + expect((await stepIn(rec, ended, 1_794_698_882_700, true, plan)).posted).toEqual([]); + const after = await stepIn(rec, ended, latestAt + 1_000, false, plan); + expect(after.posted.length).toBe(1); + expect(after.posted[0]).toContain(followUpMarker("n1")); + expect(rec.stagingMix!.followUp).toMatchObject({ commentId: "c1", duringRun: false, at: latestAt + 1_000 }); + expect(rec.stagingMix!.afterEndFollowUps).toEqual([{ afterRunEndAt: finishedAt, at: latestAt + 1_000, delayMs: latestAt + 1_000 - finishedAt, commentId: "c1" }]); + expect((await stepIn(rec, ended, latestAt + 5_000, false, plan)).posted).toEqual([]); + + const nonce = "15b397b0"; + const grade = (comments: Array<{ body: string; runId: string | null; createdAt: number }>, extra: string[]) => gradeStagingMix(nonce, plan, artifacts({ + documents: { ledger: ledgerFor(nonce, 10, extra) }, agentComments: comments.map(comment => comment.body), + stagingMix: { followUp: rec.stagingMix!.followUp!, followUpErrors: [], retries: [], comments, afterEndFollowUps: rec.stagingMix!.afterEndFollowUps } })).checks; + const done = { body: doneMarker(nonce), runId: "6dfb753b", createdAt: finishedAt - 1_000 }; + const unanswered = grade([done], []); + expect(unanswered.find(check => check.name === "follow_up_posted")).toMatchObject({ ok: true, detail: "comment c1 after the run ended" }); + expect(unanswered.find(check => check.name === "after_end_follow_ups_served")!.ok).toBe(false); + expect(unanswered.some(check => check.name === "follow_up_served")).toBe(false); + const answered = grade([done, { body: "Added the FOLLOWUP line.", runId: "r2", createdAt: latestAt + 60_000 }], [followUpMarker(nonce)]); + expect(answered.filter(check => !check.ok)).toEqual([]); + }); + + it("does not post an after-end follow-up between runs before the during-run window closes, or while a run is queued", async () => { + const plan = task({ followUpAfterMs: 60_000 }); + const gap: TaskSample = { ...running, issueStatus: "in_progress", runs: [{ ...running.runs![0]!, status: "failed", finishedAt: new Date(50_000).toISOString() }] }; + const queued: TaskSample = { ...gap, runs: [...gap.runs!, { ...running.runs![0]!, id: "r2", status: "queued" }] }; + const rec = record(); + expect((await stepIn(rec, gap, 61_000, true, plan)).posted).toEqual([]); + expect((await stepIn(rec, queued, 60_000 + 600_000, false, plan)).posted).toEqual([]); + expect((await stepIn(rec, gap, 60_000 + 600_000, false, plan)).posted.length).toBe(1); + expect(rec.stagingMix!.followUp).toMatchObject({ duringRun: false }); + }); + it("tries a failed follow-up again on the next poll and keeps every error for the grade", async () => { const rec = record(); const failing = await step(rec, running, 80_000, true, undefined, () => { throw new Error("HTTP 502"); }); diff --git a/tests/restart-chaos/staging-mix.ts b/tests/restart-chaos/staging-mix.ts index fbadcbc9c46..287309d54a5 100644 --- a/tests/restart-chaos/staging-mix.ts +++ b/tests/restart-chaos/staging-mix.ts @@ -495,7 +495,7 @@ export function gradeStagingMix(nonce: string, task: StagingMixTask, artifacts: if (task.followUpAfterMs !== null) { const errors = artifacts.stagingMix?.followUpErrors ?? []; checks.push({ name: "follow_up_posted", ok: Boolean(followUp?.commentId), - detail: followUp?.commentId ? `comment ${followUp.commentId}` : `never posted${errors.length ? `; errors: ${errors.slice(-3).join(" | ")}` : ""}` }); + detail: followUp?.commentId ? `comment ${followUp.commentId}${followUp.duringRun ? "" : " after the run ended"}` : `never posted${errors.length ? `; errors: ${errors.slice(-3).join(" | ")}` : ""}` }); } const afterEnd = artifacts.stagingMix?.afterEndFollowUps ?? []; const range = task.followUpAfterMs !== null ? followUpAfterEndRange() : null; @@ -627,11 +627,14 @@ export async function stagingMixStep(input: StagingMixStepInput): Promise if (commentId && !state.followUp) state.followUp = { at: now, commentId, duringRun: false, inOverlap: overlap, error: null }; } } - } else if (task.followUpAfterMs !== null && !state.followUp && running) { + } else if (task.followUpAfterMs !== null && !state.followUp) { const plannedAt = record.createdAt + task.followUpAfterMs; const latestAt = Math.min(plannedAt + task.holdMs, record.createdAt + Math.round(task.rounds * ROUND_SECONDS * 1_000 * 0.85)); - if (now >= plannedAt && (overlap || now >= latestAt)) { - const followUp: NonNullable = { at: now, commentId: null, duringRun: true, inOverlap: overlap, error: null }; + const runs = sample.runs ?? []; + const lastEnd = Math.max(0, ...runs.map(run => Date.parse(run.finishedAt ?? "") || 0)); + const afterRunEnd = !running && !runs.some(run => ACTIVE.has(run.status)) && lastEnd > 0 && now >= Math.max(plannedAt, latestAt); + if (running ? now >= plannedAt && (overlap || now >= latestAt) : afterRunEnd) { + const followUp: NonNullable = { at: now, commentId: null, duringRun: running, inOverlap: overlap, error: null }; try { const comment = await input.api.post<{ id?: string }>(`/api/issues/${record.issueId}/comments`, { body: followUpComment(input.nonce), clientRequestId: followUpRequestId(record.issueId, input.nonce) }); @@ -640,9 +643,11 @@ export async function stagingMixStep(input: StagingMixStepInput): Promise } catch (error) { followUp.error = error instanceof Error ? error.message : String(error); } - if (followUp.commentId) state.followUp = followUp; - else (state.followUpErrors ??= []).push(followUp.error!); - input.note("staging_mix_follow_up", { ...followUp }); + if (followUp.commentId) { + state.followUp = followUp; + if (afterRunEnd) (state.afterEndFollowUps ??= []).push({ afterRunEndAt: lastEnd, at: now, delayMs: now - lastEnd, commentId: followUp.commentId }); + } else (state.followUpErrors ??= []).push(followUp.error!); + input.note("staging_mix_follow_up", { ...followUp, ...(afterRunEnd ? { afterRunEndAt: lastEnd } : {}) }); } } noteRetryBanner(state, retryShown(sample), now, latestFailureCode(sample)); diff --git a/tests/restart-chaos/wake-evidence.test.ts b/tests/restart-chaos/wake-evidence.test.ts index 438a0836b55..686c7d2e799 100644 --- a/tests/restart-chaos/wake-evidence.test.ts +++ b/tests/restart-chaos/wake-evidence.test.ts @@ -3,7 +3,7 @@ import { mkdtemp, readFile, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { activityLog, agentWakeupRequests, agents, companies, controllerInstances, createDb, heartbeatRuns, issues, type Db } from "../../packages/db/src/index.js"; +import { activityLog, agentWakeupRequests, agents, companies, controllerInstances, createDb, heartbeatRunEvents, heartbeatRuns, issues, type Db } from "../../packages/db/src/index.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../server/src/__tests__/helpers/embedded-postgres.js"; import { boundByProcessExit, captureWakeEvidence, servingAt, unshiftRows, wakeEvidenceForIssue, wakeEvidenceOnce, type ControllerRow } from "./wake-evidence.js"; import { runEvents } from "./evidence.js"; @@ -149,7 +149,7 @@ describe.skipIf(!support.supported)("wake evidence against real PostgreSQL", () expect(written).toBe(1); const evidence = JSON.parse(await readFile(path.join(waveDir, "wake-evidence", "t01.json"), "utf8")); expect(evidence.runs[0]).toMatchObject({ runId, invocationSource: "on_demand", wakeupRequestId: wakeId, contextSnapshot: { wakeReason: "retry" }, - owner: { pid: 4242, processSpace: "space-wake" } }); + owner: { pid: 4242, processSpace: "space-wake" }, providerTurnStarted: false }); const slots = JSON.parse(await readFile(path.join(waveDir, "wake-evidence", "agent-slots.json"), "utf8")); expect(slots.agents).toEqual(expect.arrayContaining([{ agentId, maxConcurrentRuns: 3 }, { agentId: wideAgentId, maxConcurrentRuns: 50 }])); expect(slots.runs).toEqual([{ runId, agentId, startedAt: 1_800_000_000_000, finishedAt: 1_800_000_060_000 }]); @@ -158,8 +158,9 @@ describe.skipIf(!support.supported)("wake evidence against real PostgreSQL", () expect(evidence.wakes[0].servingAtCreate.map((server: { pid: number }) => server.pid)).toEqual([4242]); expect(evidence.statusChanges).toMatchObject([{ action: "issue.updated", from: "in_progress", to: "done" }]); expect(JSON.parse(await readFile(path.join(waveDir, "wake-evidence", "servers.json"), "utf8")).controllers[0]).toMatchObject({ pid: 4242 }); + await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId, seq: 1, eventType: "turn.started" }); expect(await captureWakeEvidence({ db, companyId, waveDir, observers: null, windows: [], redact: text => text })).toBe(1); - expect(JSON.parse(await readFile(path.join(waveDir, "wake-evidence", `issue-${issueId}.json`), "utf8")).runs[0]).toMatchObject({ runId }); + expect(JSON.parse(await readFile(path.join(waveDir, "wake-evidence", `issue-${issueId}.json`), "utf8")).runs[0]).toMatchObject({ runId, providerTurnStarted: true }); } finally { await rm(waveDir, { recursive: true, force: true }); } diff --git a/tests/restart-chaos/wake-evidence.ts b/tests/restart-chaos/wake-evidence.ts index 0d8793c36e6..e1634941ec3 100644 --- a/tests/restart-chaos/wake-evidence.ts +++ b/tests/restart-chaos/wake-evidence.ts @@ -79,7 +79,8 @@ export function wakeEvidenceForIssue(issueId: string, input: WakeEvidenceInput) const owner = controllerByBoot.get(String(run.controllerBootId ?? "")); return { runId: text(run.id), status: text(run.status), invocationSource: text(run.invocationSource), triggerDetail: text(run.triggerDetail), wakeupRequestId: text(run.wakeupRequestId), createdAt: ms(run.createdAt), startedAt: ms(run.startedAt), finishedAt: ms(run.finishedAt), - acceptedDisposition: text(run.acceptedDisposition), acceptedAt: ms(run.acceptedAt), contextSnapshot: run.contextSnapshot ?? null, owner: owner ? { pid: owner.pid, bootId: owner.bootId, epoch: owner.epoch, processSpace: owner.processSpace } : null, + acceptedDisposition: text(run.acceptedDisposition), acceptedAt: ms(run.acceptedAt), contextSnapshot: run.contextSnapshot ?? null, + providerTurnStarted: run.providerTurnStarted == null ? null : Boolean(run.providerTurnStarted), owner: owner ? { pid: owner.pid, bootId: owner.bootId, epoch: owner.epoch, processSpace: owner.processSpace } : null, servingAtCreate: servingAt(ms(run.createdAt), controllers, input.windows) }; }), wakes: wakes.map(wake => ({ id: text(wake.id), reason: text(wake.reason), source: text(wake.source), triggerDetail: text(wake.triggerDetail), @@ -99,7 +100,9 @@ async function readRows(db: Pick, companyId: string, s r.wakeup_request_id::text as "wakeupRequestId", r.context_snapshot as "contextSnapshot", r.controller_boot_id::text as "controllerBootId", floor(extract(epoch from r.created_at) * 1000) as "createdAt", floor(extract(epoch from r.started_at) * 1000) as "startedAt", floor(extract(epoch from r.finished_at) * 1000) as "finishedAt", accepted.disposition as "acceptedDisposition", - floor(extract(epoch from accepted.accepted_at) * 1000) as "acceptedAt" + floor(extract(epoch from accepted.accepted_at) * 1000) as "acceptedAt", + exists (select 1 from heartbeat_run_events t where t.company_id = r.company_id and t.run_id = r.id + and t.event_type in ('turn.submitted', 'turn.accepted', 'turn.started')) as "providerTurnStarted" from heartbeat_runs r left join lateral (select coalesce(e.payload->'prpEvent'->'payload'->'result'->>'reportedWorkDisposition', e.payload->'result'->>'reportedWorkDisposition') as disposition, e.created_at as accepted_at from heartbeat_run_events e where e.run_id = r.id and e.event_type = 'run.result.accepted' From b5ba5481129c29aea095b7aa7553cd9b469b5650 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:13:45 -0600 Subject: [PATCH 04/12] feat(server): add an instance-admin server metrics endpoint for the scale ramp (#21708) 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 scaling plan (`doc/plans/2026-11-13-thousand-concurrent-agents.md`) has a finish line that a real-agent ramp harness checks (#21695) > - Four finish-line criteria need numbers from inside each server process: main-thread CPU, run event lateness, agent API time before the handler, and missed lease renewals > - The server had no way to give them, so every harness run was at best "incomplete" > - This pull request adds one instance-admin endpoint that returns those numbers per process over a short sliding window, off by default, and connects the harness to it > - The benefit is that a ramp run can measure every server criterion it can see, with near-zero cost when on and no cost when off ## Linked Issues or Issue Description Refs #21695 **Subsystem affected** Server (instance routes, run event append, native lease renewal), database client (statement counter), and the scale-ramp harness in `scripts/scale-ramp/`. **Problem or motivation** The scale-ramp harness reads `PAPERCLIP_SCALE_METRICS_URL`, but the server has no endpoint for it. The criteria `main_thread_cpu`, `run_event_lateness_p99`, `agent_api_pre_handler_p99` and `lease_renewals_missed_zero` are therefore always "not measured", and no run can pass. **Proposed solution** Add `GET /api/instance/server-metrics`. It returns a JSON snapshot of one server process over the last 50 to 60 s. Only an instance admin can read it. The env flag `PAPERCLIP_SERVER_METRICS` (read once at start, default off) turns on collection and the route. Off, the path answers 404 and no collector starts. **Alternatives considered** - The postgres.js `debug` option for the statement counter: rejected, because it captures a stack (`new Error()`) for every query. - Process CPU from `process.cpuUsage()` as `mainThreadCpu`: rejected, because it includes GC and libuv threads. It is returned as `processCpu` instead, and `mainThreadCpu` reads the main thread from `/proc` (Linux only, null elsewhere). - Default on: the measured cost is negligible (numbers below), but the event-loop monitor wakes the process every 20 ms when idle, and this is a new instance-wide surface. It stays off; the runbook says how to turn it on for a ramp run. ## What Changed - `server/src/services/server-metrics.ts`: a per-process collector. It uses `performance.eventLoopUtilization()`, `monitorEventLoopDelay` (20 ms), `process.cpuUsage()`, the main thread's `/proc/self/task//stat` on Linux, and six 10 s buckets of native `perf_hooks` histograms. One unref'd timer rotates the buckets. Nothing on the hot path awaits, allocates per call or does I/O. - `server/src/routes/instance-server-metrics.ts`: `GET /api/instance/server-metrics`, guarded by the existing `assertInstanceAdmin` (the check that `/instance/database-backups` and other instance routes use). It returns numbers, a random per-process `processId`, `uptimeSec`, `buildRevision` and `windowMs`. It returns no SQL, names, IDs or hostnames. - `server/src/app.ts`: when the flag is on, two middlewares time agent API requests from arrival to the API router, the route is mounted, and shutdown stops the collector. When the flag is off, nothing is mounted. - The snapshot also carries `dedicatedConnections` from `dedicatedDbConnectionStats()` (#21693): `limit`, `inUse`, `waiting` at request time and `peakInUse`, `queued`, `overLimit`, `nestedOverLimit` since start. The harness ignores it today; it shows dedicated-connection queueing in a restart burst. - `packages/db/src/statement-count.ts` and `lazy-transaction-queries.ts`: a Drizzle logger that increments one counter per statement replaces Drizzle's no-op logger. No edit to `client.ts`. - `paperclip-control-plane-port.ts`: one call records runner `emittedAt` to committed row for each committed (not duplicate) runner event. - `native-execution-lease.ts`: one call counts a lease whose renewal deadline passed. - Harness: missed lease renewals are summed per `processId` (several processes, or a restart, no longer cancel out). A metrics URL on the target origin gets the board token in the `Authorization` header; `PAPERCLIP_SCALE_METRICS_TOKEN` still overrides it, and another origin gets no token. - Contract: `scripts/scale-ramp/server-metrics.fixture.json` is the serializer's own output. A server test asserts the serializer produces exactly this file, and a harness test parses it and checks every field. - `rules/company-scope-exceptions.mdc`: adds the snapshot as an instance-wide exception with its reason. The runbook in the plan doc documents the path, the flag, the credential and each field. | Field | Provided | Source | | --- | --- | --- | | `mainThreadCpu` | yes (Linux; null elsewhere) | `/proc/self/task//stat` utime+stime | | `eventLoopUtilization` | yes | `performance.eventLoopUtilization()` | | `eventLoopDelayP99Ms` | yes | `monitorEventLoopDelay`, highest 10 s p99 in the window | | `statementsPerSecond` | yes | Drizzle logger counter (not BEGIN/COMMIT or raw driver calls) | | `poolWaitP99Ms` | absent | postgres.js has no cheap hook for queue time | | `runEventLatenessP99Ms` | yes (null with no events) | runner event append | | `agentApiPreHandlerP99Ms` | yes (null with no agent requests) | arrival and router-entry middlewares | | `leaseRenewalsMissed` | yes, counter since process start | native lease deadline timer | ## Verification - `cd server && npx vitest run src/__tests__/instance-server-metrics-routes.test.ts src/__tests__/server-metrics.test.ts`: through `createApp` on the embedded test database. 200 with the exact field set for an instance admin; 403 for a company owner who is not an instance admin, for an agent key, and unauthenticated; 404 and no collector when the flag is off; values move after agent requests, statements, a late run event and a missed renewal; the body has no IDs, keys or SQL. - `cd server && npx vitest run src/services/native-runtime/native-execution-lease.test.ts src/services/native-runtime/paperclip-control-plane-port.test.ts src/__tests__/api-server-timing.test.ts`: the lease and run-event hooks (red/green checked for the lease hook by removing the call). - `cd packages/db && npx vitest run src/lazy-transaction-queries.test.ts src/client-options.test.ts`: the counter counts statements inside transactions and savepoints. - `node --test scripts/scale-ramp/scale-ramp.test.ts` and `tsc -p scripts/scale-ramp/tsconfig.json`: 38 pass, including the fixture contract and the board-token header. - `node server/scripts/typecheck-layers.mjs` and `tsc --noEmit` in `packages/db`: pass. Overhead, measured on a shared, loaded laptop (load average 8 to 20), median with min and max: | Measure | Off | On | | --- | --- | --- | | Logger call per statement (5M calls x 7) | 0.28 ns (0.24 to 0.97) | 3.36 ns (3.32 to 6.16) | | CPU per `select 1` statement, embedded Postgres (3,000 x 10) | 28.7 us (20.3 to 42.4) | 32.3 us (20.7 to 45.5) | | CPU per HTTP request, client and server in one process (2,000 x 6) | 67.0 us (40.4 to 107.4) | 64.2 us (40.9 to 83.3) | | Idle process CPU, 5 s x 3 | 0.01% of a core (0.00 to 2.21) | 0.08% (0.05 to 0.09) | | Record one run event (Date.parse + histogram) | - | 148 ns (135 to 188) | | One snapshot | - | 55 us | The statement and request differences are inside the run-to-run spread. The direct cost is about 3 ns per statement, against about 30 us of CPU per statement. ## Risks - Low risk. Off by default; off, only the statement counter runs, and it costs one increment more than Drizzle's no-op logger. - `mainThreadCpu` assumes Linux USER_HZ of 100 and is null on other platforms. The harness then uses `eventLoopUtilization`. - Run event lateness compares the runner's clock with the server's clock, so clock skew adds to it. Negative values count as zero. - With several processes, each request reaches one process. The harness keeps the highest gauge and sums counter growth per process, but a process it never samples is not seen. - The statement counter does not count BEGIN/COMMIT or raw postgres.js calls. > 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 - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with tool use (shell, file edits, local 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 - [ ] 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 --- .../2026-11-13-thousand-concurrent-agents.md | 44 ++- packages/db/src/index.ts | 1 + .../db/src/lazy-transaction-queries.test.ts | 12 + packages/db/src/lazy-transaction-queries.ts | 10 +- packages/db/src/statement-count.ts | 13 + rules/company-scope-exceptions.mdc | 11 +- scripts/scale-ramp/config.ts | 10 + scripts/scale-ramp/main.ts | 4 +- scripts/scale-ramp/ramp.ts | 41 ++- scripts/scale-ramp/scale-ramp.test.ts | 74 ++++- .../scale-ramp/server-metrics.fixture.json | 27 ++ .../instance-server-metrics-routes.test.ts | 140 +++++++++ server/src/__tests__/openapi-routes.test.ts | 1 + server/src/__tests__/server-metrics.test.ts | 196 +++++++++++++ server/src/app.ts | 16 +- server/src/routes/instance-server-metrics.ts | 15 + server/src/routes/openapi.ts | 12 + .../native-execution-lease.test.ts | 19 ++ .../native-runtime/native-execution-lease.ts | 6 +- .../paperclip-control-plane-port.test.ts | 37 +++ .../paperclip-control-plane-port.ts | 9 +- server/src/services/server-metrics.ts | 274 ++++++++++++++++++ 22 files changed, 948 insertions(+), 24 deletions(-) create mode 100644 packages/db/src/statement-count.ts create mode 100644 scripts/scale-ramp/server-metrics.fixture.json create mode 100644 server/src/__tests__/instance-server-metrics-routes.test.ts create mode 100644 server/src/__tests__/server-metrics.test.ts create mode 100644 server/src/routes/instance-server-metrics.ts create mode 100644 server/src/services/server-metrics.ts diff --git a/doc/plans/2026-11-13-thousand-concurrent-agents.md b/doc/plans/2026-11-13-thousand-concurrent-agents.md index 852a9fdf72a..825f67dcdfa 100644 --- a/doc/plans/2026-11-13-thousand-concurrent-agents.md +++ b/doc/plans/2026-11-13-thousand-concurrent-agents.md @@ -445,12 +445,44 @@ A missing source is reported as "not measured", never as zero. | Lease renewals that miss their deadline | finish line | 0 | metrics endpoint | | Kill one server process | finish line | runs resume, no Retry | not measured by this harness | -The server has no metrics endpoint today. `PAPERCLIP_SCALE_METRICS_URL` must -answer a JSON object with any of `mainThreadCpu`, `eventLoopUtilization` -(0 to 1, highest server process), `eventLoopDelayP99Ms`, -`statementsPerSecond`, `poolWaitP99Ms`, `runEventLatenessP99Ms`, -`agentApiPreHandlerP99Ms` and `leaseRenewalsMissed` (a counter). Without it, -the four server criteria are not measured, and a run can be at best +**Server metrics.** Each server process can serve +`GET /api/instance/server-metrics`, a JSON snapshot of that process over the +last 50 to 60 s (`windowMs`), with its `processId` (random per process +start), `uptimeSec` and `buildRevision`. It is off by default: set +`PAPERCLIP_SERVER_METRICS=true` on the stack before the run (read once at +start; off, the path answers 404 and nothing is collected). Only an instance +admin can read it, so the board token must belong to an instance admin. +Point the harness at it on the target origin, and the harness sends the board +token in its `Authorization: Bearer` header (never in the URL; +`PAPERCLIP_SCALE_METRICS_TOKEN` overrides it, and a URL on another origin gets +no token unless that variable is set): + +```sh +export PAPERCLIP_SCALE_METRICS_URL=https://$H/api/instance/server-metrics +``` + +| Field | Meaning | Source | +| --- | --- | --- | +| `mainThreadCpu` | main-thread CPU per wall second, 0 to 1 (Linux only, else null) | `/proc/self/task//stat` | +| `eventLoopUtilization` | 0 to 1 | `performance.eventLoopUtilization()` | +| `eventLoopDelayP99Ms` | highest 10 s p99 in the window | `monitorEventLoopDelay` (20 ms) | +| `statementsPerSecond` | Drizzle statements per second (not BEGIN/COMMIT or raw driver calls) | Drizzle logger counter | +| `runEventLatenessP99Ms` | runner `emittedAt` to committed row, p99 (null with no events) | runner event append | +| `agentApiPreHandlerP99Ms` | agent API request arrival to the API router, p99 (null with no agent requests) | two middlewares | +| `leaseRenewalsMissed` | counter since process start: native run leases whose deadline passed unrenewed | lease deadline timer | + +`processCpu`, `runEventLatenessSamples`, `agentApiPreHandlerSamples` and +`dedicatedConnections` are extra context. `dedicatedConnections` is the +process's dedicated-connection bound at the time of the request: `limit`, +`inUse`, `waiting` (gauges), `peakInUse`, `queued`, `overLimit` and +`nestedOverLimit` (counts since start); queueing there shows a restart burst. `poolWaitP99Ms` is absent: postgres.js exposes no cheap hook +for time spent queued for a connection, so pool wait stays not measured. With +several processes, each request reaches one of them; the harness keeps the +highest gauge and sums the counter's growth per `processId`; a process +whose `uptimeSec` shows it started during the run counts its whole counter. +After an event-loop block longer than the window, `windowMs` reports the real, +longer span so the block stays visible. Without the +endpoint, the four server criteria are not measured, and a run can be at best `incomplete`. The harness does not read the database. **Proof order.** A hosted stack that is not `paperclip.staging` first diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts index 9b84a1ce668..b8f1421ed29 100644 --- a/packages/db/src/index.ts +++ b/packages/db/src/index.ts @@ -65,3 +65,4 @@ export * from "./schema/index.js"; export { databaseWorkScopeKey, primeDatabaseWorkTransactionId, signalDatabaseWork, subscribeDatabaseWork, databaseWorkPending, reconcileDatabaseWork } from "./work-signals.js"; export { withDatabaseOperation } from "./response-capture.js"; +export { databaseStatementCount } from "./statement-count.js"; diff --git a/packages/db/src/lazy-transaction-queries.test.ts b/packages/db/src/lazy-transaction-queries.test.ts index 2cefdf6c8a6..4c7828fc796 100644 --- a/packages/db/src/lazy-transaction-queries.test.ts +++ b/packages/db/src/lazy-transaction-queries.test.ts @@ -5,6 +5,7 @@ import postgres from "postgres"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { createDb, type Db } from "./client.js"; import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "./response-capture.js"; +import { databaseStatementCount } from "./statement-count.js"; import { announcementDismissals, announcementPublications } from "./schema/index.js"; import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, @@ -48,6 +49,17 @@ describeEmbeddedPostgres("transactions on the Paperclip database client", () => }); afterAll(async () => { await database?.cleanup(); }); + it("counts each statement, inside transactions and savepoints too", async () => { + const before = databaseStatementCount(); + await db.select().from(announcementPublications); + await db.transaction(async (tx) => { + await publication(tx, "counted"); + await tx.transaction(async nested => { await nested.select().from(announcementPublications); }); + await tx.query.announcementPublications.findMany(); + }); + expect(databaseStatementCount() - before).toBe(4); + }); + describe("relational query builders", () => { it("builds none for a transaction or savepoint that never reads tx.query", async () => { const schemaTables = Object.keys(db.query).length; diff --git a/packages/db/src/lazy-transaction-queries.ts b/packages/db/src/lazy-transaction-queries.ts index e153ca6452b..c99a2deb19b 100644 --- a/packages/db/src/lazy-transaction-queries.ts +++ b/packages/db/src/lazy-transaction-queries.ts @@ -3,6 +3,7 @@ import { RelationalQueryBuilder } from "drizzle-orm/pg-core/query-builders/query import { drizzle, type PostgresJsDatabase } from "drizzle-orm/postgres-js"; import type { TableRelationalConfig } from "drizzle-orm"; import type postgres from "postgres"; +import { statementCountingLogger } from "./statement-count.js"; type Callback = (tx: Transaction) => unknown; type Transaction = { @@ -27,18 +28,19 @@ type Transaction = { * built, bound to that transaction's session, and `tx._` still describes the * schema. * - * Both clients and the builders' dialect take Drizzle's defaults. A Drizzle - * option added here (`casing`, `logger`, `cache`) must go to all three. + * Both clients count each statement through `statementCountingLogger`, and + * otherwise both clients and the builders' dialect take Drizzle's defaults. A + * Drizzle option added here (`casing`, `cache`) must go to all three. */ export function drizzleWithLazyTransactionQueries, TClient extends postgres.Sql>( client: TClient, schema: TSchema, ): PostgresJsDatabase & { $client: TClient } { - const db = drizzle(client, { schema }); + const db = drizzle(client, { schema, logger: statementCountingLogger }); const tables = db._.schema; if (!tables) return db; const { fullSchema, tableNamesMap } = db._; - const transactions = drizzle(client) as unknown as Transaction; + const transactions = drizzle(client, { logger: statementCountingLogger }) as unknown as Transaction; const dialect = new PgDialect(); const resolved = (value: unknown): PropertyDescriptor => ({ value, writable: true, enumerable: true, configurable: true }); const lazyQuery: PropertyDescriptor = { diff --git a/packages/db/src/statement-count.ts b/packages/db/src/statement-count.ts new file mode 100644 index 00000000000..da0f00f1478 --- /dev/null +++ b/packages/db/src/statement-count.ts @@ -0,0 +1,13 @@ +import type { Logger } from "drizzle-orm"; + +let statements = 0; + +export const statementCountingLogger: Logger = { + logQuery(): void { + statements += 1; + }, +}; + +export function databaseStatementCount(): number { + return statements; +} diff --git a/rules/company-scope-exceptions.mdc b/rules/company-scope-exceptions.mdc index a68dbb9d2e6..7d907af4a09 100644 --- a/rules/company-scope-exceptions.mdc +++ b/rules/company-scope-exceptions.mdc @@ -1,6 +1,6 @@ --- -description: The known instance-wide data is announcement dismissals, the announcement publication-ID registry, personal workspace presentation preferences, and the per-user sidebar company order; these grant no authority, and a new exception must be added to this list. -globs: "packages/db/src/schema/announcement_dismissals.ts,packages/shared/src/announcements.ts,server/src/routes/announcements.ts,server/src/services/announcements.ts,server/src/services/announcement-feed.ts,packages/db/src/schema/user_workspace_preferences.ts,packages/shared/src/workspace-preferences.ts,server/src/routes/workspace-preferences.ts,server/src/services/workspace-preferences.ts,packages/db/src/schema/user_sidebar_preferences.ts,packages/shared/src/types/sidebar-preferences.ts,server/src/routes/sidebar-preferences.ts,server/src/services/sidebar-preferences.ts" +description: The known instance-wide data is announcement dismissals, the announcement publication-ID registry, personal workspace presentation preferences, the per-user sidebar company order, and the instance-admin server metrics snapshot; these grant no authority, and a new exception must be added to this list. +globs: "packages/db/src/schema/announcement_dismissals.ts,packages/shared/src/announcements.ts,server/src/routes/announcements.ts,server/src/services/announcements.ts,server/src/services/announcement-feed.ts,packages/db/src/schema/user_workspace_preferences.ts,packages/shared/src/workspace-preferences.ts,server/src/routes/workspace-preferences.ts,server/src/services/workspace-preferences.ts,packages/db/src/schema/user_sidebar_preferences.ts,packages/shared/src/types/sidebar-preferences.ts,server/src/routes/sidebar-preferences.ts,server/src/services/sidebar-preferences.ts,server/src/routes/instance-server-metrics.ts,server/src/services/server-metrics.ts" alwaysApply: false --- @@ -29,6 +29,13 @@ company scope here. - **The sidebar company order** in `user_sidebar_preferences` is instance-wide by user, because it orders the user's companies. Sidebar preferences inside one company stay company-scoped in `company_user_sidebar_preferences`. +- **The server metrics snapshot** (`GET /api/instance/server-metrics`) describes + one server process: CPU, event-loop load, statement rate, latency + percentiles and missed lease renewals. Company scope does not fit, because the + process serves every company and the numbers cannot be split by company. Only + an instance admin can read it, it is off unless `PAPERCLIP_SERVER_METRICS` is + set, and it returns numbers and a build revision only: no SQL, names, IDs or + hostnames. It persists nothing and changes nothing. ## Requirements diff --git a/scripts/scale-ramp/config.ts b/scripts/scale-ramp/config.ts index 769331262d2..2165cbbe75d 100644 --- a/scripts/scale-ramp/config.ts +++ b/scripts/scale-ramp/config.ts @@ -104,6 +104,16 @@ export function readSecrets(env: NodeJS.ProcessEnv, credentialKey: string | null }; } +export function metricsCredential(options: Pick, secrets: Secrets): string | null { + if (secrets.metricsToken) return secrets.metricsToken; + if (!options.metricsUrl) return null; + try { + return new URL(options.metricsUrl).origin === options.target.baseUrl ? secrets.token : null; + } catch { + return null; + } +} + function adapterOverrides(raw: string | undefined): Record { if (!raw) return {}; let parsed: unknown; diff --git a/scripts/scale-ramp/main.ts b/scripts/scale-ramp/main.ts index 4099781ce2f..db4cab28fe0 100644 --- a/scripts/scale-ramp/main.ts +++ b/scripts/scale-ramp/main.ts @@ -3,7 +3,7 @@ import path from "node:path"; import { createInterface } from "node:readline/promises"; import { cleanupRun, discoverState, type CleanupReport } from "./cleanup.ts"; import { PaperclipClient, Redactor, realClock, type Clock, type Fetcher } from "./client.ts"; -import { FALLBACK_TOKEN_ENV, parseOptions, readSecrets, TOKEN_ENV, type Options } from "./config.ts"; +import { FALLBACK_TOKEN_ENV, metricsCredential, parseOptions, readSecrets, TOKEN_ENV, type Options } from "./config.ts"; import { criteriaTable } from "./criteria.ts"; import { checkSpend, estimateSpend, type SpendEstimate } from "./estimate.ts"; import { Ramp, type RampOutcome } from "./ramp.ts"; @@ -121,7 +121,7 @@ export async function main(argv: readonly string[], deps: MainDeps): Promise interrupted, }); outcome = await ramp.run(); diff --git a/scripts/scale-ramp/ramp.ts b/scripts/scale-ramp/ramp.ts index 2a329474559..9dc68a00faa 100644 --- a/scripts/scale-ramp/ramp.ts +++ b/scripts/scale-ramp/ramp.ts @@ -130,12 +130,42 @@ function rows(body: unknown): Json[] { return []; } -export function serverMetrics(samples: ReadonlyArray>): ServerMetrics { +type Sample = Record; +const processOf = (sample: Sample) => typeof sample.processId === "string" ? sample.processId : ""; + +function counterBaseline(first: Sample, earlier: readonly Sample[], runStartedAt: number | null, counter: string): number { + const processId = processOf(first); + for (let index = earlier.length - 1; index >= 0; index -= 1) { + const value = num(earlier[index]![counter]); + if (processOf(earlier[index]!) === processId && value !== null) return value; + } + const uptimeSec = num(first.uptimeSec); + const sampledAt = num(first.sampledAt); + if (runStartedAt !== null && uptimeSec !== null && sampledAt !== null && sampledAt - uptimeSec * 1_000 > runStartedAt) return 0; + return num(first[counter]) ?? 0; +} + +function counterGrowth(samples: readonly Sample[], earlier: readonly Sample[], runStartedAt: number | null, counter: string): number | null { + const byProcess = new Map(); + for (const sample of samples) { + if (num(sample[counter]) === null) continue; + const processId = processOf(sample); + byProcess.set(processId, [...byProcess.get(processId) ?? [], sample]); + } + if (byProcess.size === 0) return null; + let growth = 0; + for (const processSamples of byProcess.values()) { + const last = num(processSamples[processSamples.length - 1]![counter])!; + growth += Math.max(0, last - counterBaseline(processSamples[0]!, earlier, runStartedAt, counter)); + } + return growth; +} + +export function serverMetrics(samples: ReadonlyArray, history: { earlier?: readonly Sample[]; runStartedAt?: number | null } = {}): ServerMetrics { const max = (key: string) => { const values = samples.map(sample => num(sample[key])).filter((value): value is number => value !== null); return values.length ? Math.max(...values) : null; }; - const missed = samples.map(sample => num(sample.leaseRenewalsMissed)).filter((value): value is number => value !== null); return { mainThreadCpuMax: max("mainThreadCpu"), eventLoopUtilizationMax: max("eventLoopUtilization"), @@ -144,7 +174,7 @@ export function serverMetrics(samples: ReadonlyArray>): poolWaitP99MsMax: max("poolWaitP99Ms"), runEventLatenessP99MsMax: max("runEventLatenessP99Ms"), agentApiPreHandlerP99MsMax: max("agentApiPreHandlerP99Ms"), - leaseRenewalsMissed: missed.length ? missed[missed.length - 1]! - missed[0]! : null, + leaseRenewalsMissed: counterGrowth(samples, history.earlier ?? [], history.runStartedAt ?? null, "leaseRenewalsMissed"), samples: samples.length, }; } @@ -467,7 +497,10 @@ export class Ramp { firstActivityMs: distribution(accumulator.firstActivityMs), runDurationMs: distribution(runs.flatMap(run => run.startedAt !== null && run.finishedAt !== null ? [run.finishedAt - run.startedAt] : [])), board: { requests: accumulator.boardRequests, failures: accumulator.boardFailures, ms: distribution(accumulator.boardMs) }, - server: serverMetrics(accumulator.serverSamples), + server: serverMetrics(accumulator.serverSamples, { + earlier: this.accumulators.slice(0, stepIndex).flatMap(earlier => earlier.serverSamples), + runStartedAt: this.accumulators[0]?.startedAt ?? null, + }), recordedSpendUsd: Math.round(spend * 100) / 100, }; } diff --git a/scripts/scale-ramp/scale-ramp.test.ts b/scripts/scale-ramp/scale-ramp.test.ts index 8751bde83ad..6a34655e617 100644 --- a/scripts/scale-ramp/scale-ramp.test.ts +++ b/scripts/scale-ramp/scale-ramp.test.ts @@ -1,16 +1,17 @@ import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; import { mkdtemp, readdir, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { after, describe, it } from "node:test"; import { PaperclipClient, Redactor } from "./client.ts"; -import { parseOptions, QUALIFIED_OPENCODE_MODEL } from "./config.ts"; +import { metricsCredential, parseOptions, QUALIFIED_OPENCODE_MODEL, readSecrets } from "./config.ts"; import { evaluate, type StepMetrics } from "./criteria.ts"; import { checkSpend, estimateSpend } from "./estimate.ts"; import { FakePaperclip, VirtualClock, type FakeConfig } from "./fake-paperclip.ts"; import { classifyHost, resolveTarget, TargetRefused } from "./guard.ts"; import { EXIT, main, type MainDeps } from "./main.ts"; -import { Ramp } from "./ramp.ts"; +import { Ramp, serverMetrics } from "./ramp.ts"; import { verdictOf, type RampResult } from "./report.ts"; import { ensureAgents, prepareCompany } from "./setup.ts"; import { distribution } from "./stats.ts"; @@ -246,6 +247,75 @@ describe("criteria", () => { }); }); +describe("server metrics endpoint contract", () => { + const fixture = JSON.parse(readFileSync(new URL("./server-metrics.fixture.json", import.meta.url), "utf8")) as Record; + const SERVER_METRICS_URL = `${ORIGIN}/api/instance/server-metrics`; + + it("parses every finish-line field of the server's own serialized response except pool wait, which the server does not measure", () => { + const parsed = serverMetrics([fixture, { ...fixture, leaseRenewalsMissed: 3 }]); + assert.deepEqual(parsed, { + mainThreadCpuMax: fixture.mainThreadCpu, eventLoopUtilizationMax: fixture.eventLoopUtilization, eventLoopDelayP99MsMax: fixture.eventLoopDelayP99Ms, + statementsPerSecondMax: fixture.statementsPerSecond, poolWaitP99MsMax: null, runEventLatenessP99MsMax: fixture.runEventLatenessP99Ms, + agentApiPreHandlerP99MsMax: fixture.agentApiPreHandlerP99Ms, leaseRenewalsMissed: 2, samples: 2, + }); + assert.equal("poolWaitP99Ms" in fixture, false); + }); + + it("counts missed lease renewals per server process, so samples from several processes never cancel out", () => { + const parsed = serverMetrics([ + { processId: "a", leaseRenewalsMissed: 5 }, { processId: "b", leaseRenewalsMissed: 0 }, + { processId: "a", leaseRenewalsMissed: 6 }, { processId: "b", leaseRenewalsMissed: 2 }, { processId: "a", leaseRenewalsMissed: 6 }, + ]); + assert.equal(parsed.leaseRenewalsMissed, 3); + }); + + it("counts the full counter of a process that started during the run, so a restart cannot hide a missed renewal", () => { + const runStartedAt = 1_000_000; + const earlier = [{ processId: "a", uptimeSec: 3_600, sampledAt: runStartedAt + 10_000, leaseRenewalsMissed: 4 }]; + const parsed = serverMetrics([ + { processId: "a", uptimeSec: 3_630, sampledAt: runStartedAt + 40_000, leaseRenewalsMissed: 4 }, + { processId: "b", uptimeSec: 20, sampledAt: runStartedAt + 70_000, leaseRenewalsMissed: 1 }, + { processId: "b", uptimeSec: 35, sampledAt: runStartedAt + 85_000, leaseRenewalsMissed: 1 }, + ], { earlier, runStartedAt }); + assert.equal(parsed.leaseRenewalsMissed, 1); + }); + + it("keeps a process's counter baseline from earlier steps", () => { + const runStartedAt = 1_000_000; + const earlier = [ + { processId: "a", uptimeSec: 3_600, sampledAt: runStartedAt + 10_000, leaseRenewalsMissed: 4 }, + { processId: "a", uptimeSec: 3_650, sampledAt: runStartedAt + 60_000, leaseRenewalsMissed: 6 }, + ]; + const parsed = serverMetrics([{ processId: "a", uptimeSec: 3_700, sampledAt: runStartedAt + 110_000, leaseRenewalsMissed: 7 }], + { earlier, runStartedAt }); + assert.equal(parsed.leaseRenewalsMissed, 1); + assert.equal(serverMetrics([{ processId: "a", uptimeSec: 3_700, sampledAt: runStartedAt + 110_000, leaseRenewalsMissed: 7 }], { runStartedAt }) + .leaseRenewalsMissed, 0, "a process that predates the run and is first seen now starts from its first sample"); + }); + + it("sends the board token to a metrics URL on the target origin, and no token to another origin", () => { + const options = parseOptions(["--base-url", ORIGIN, "--target-kind", "test-stack"], { PAPERCLIP_SCALE_METRICS_URL: SERVER_METRICS_URL }, 0); + assert.equal(metricsCredential(options, readSecrets({ PAPERCLIP_SCALE_TOKEN: TOKEN }, null)), TOKEN); + assert.equal(metricsCredential(options, readSecrets({ PAPERCLIP_SCALE_TOKEN: TOKEN, PAPERCLIP_SCALE_METRICS_TOKEN: METRICS_TOKEN }, null)), METRICS_TOKEN); + const elsewhere = parseOptions(["--base-url", ORIGIN, "--target-kind", "test-stack"], { PAPERCLIP_SCALE_METRICS_URL: METRICS_URL }, 0); + assert.equal(metricsCredential(elsewhere, readSecrets({ PAPERCLIP_SCALE_TOKEN: TOKEN }, null)), null); + }); + + it("measures the server criteria from the server metrics endpoint with the board token in the authorization header", async () => { + const out = await tempDir(); + const h = harness({ metricsUrl: SERVER_METRICS_URL, metrics: () => fixture }, { PAPERCLIP_SCALE_METRICS_URL: SERVER_METRICS_URL }); + await main(baseArgs(out, ["--steps", "2"]), h.deps); + const result = await readResult(out); + const metricsRequests = h.fake.requests.filter(request => request.url === SERVER_METRICS_URL); + assert.ok(metricsRequests.length > 0); + assert.ok(metricsRequests.every(request => request.authorization === `Bearer ${TOKEN}`)); + assert.equal(result.sources.serverMetrics, "PAPERCLIP_SCALE_METRICS_URL"); + const statuses = Object.fromEntries(result.steps[0]!.criteriaFinal.map(criterion => [criterion.id, criterion.status])); + for (const id of ["main_thread_cpu", "run_event_lateness_p99", "agent_api_pre_handler_p99"]) assert.equal(statuses[id], "pass", id); + assert.equal(statuses.lease_renewals_missed_zero, "pass"); + }); +}); + describe("ramp against the fake API", () => { it("ramps every step, measures it, passes with a metrics endpoint and cleans up", async () => { const out = await tempDir(); diff --git a/scripts/scale-ramp/server-metrics.fixture.json b/scripts/scale-ramp/server-metrics.fixture.json new file mode 100644 index 00000000000..6897aaedfc5 --- /dev/null +++ b/scripts/scale-ramp/server-metrics.fixture.json @@ -0,0 +1,27 @@ +{ + "schema": "paperclip.server-metrics.v1", + "processId": "a1b2c3d4e5f60718", + "buildRevision": "0123456789abcdef0123456789abcdef01234567", + "uptimeSec": 160, + "sampledAt": "2026-11-14T12:01:00.000Z", + "windowMs": 50000, + "mainThreadCpu": 0.42, + "processCpu": 0.55, + "eventLoopUtilization": 0.42, + "eventLoopDelayP99Ms": 0, + "statementsPerSecond": 180, + "runEventLatenessP99Ms": 120.063, + "runEventLatenessSamples": 50, + "agentApiPreHandlerP99Ms": 15.007, + "agentApiPreHandlerSamples": 50, + "leaseRenewalsMissed": 1, + "dedicatedConnections": { + "limit": 24, + "inUse": 3, + "peakInUse": 9, + "waiting": 1, + "queued": 12, + "overLimit": 0, + "nestedOverLimit": 0 + } +} diff --git a/server/src/__tests__/instance-server-metrics-routes.test.ts b/server/src/__tests__/instance-server-metrics-routes.test.ts new file mode 100644 index 00000000000..71cd3aaf24f --- /dev/null +++ b/server/src/__tests__/instance-server-metrics-routes.test.ts @@ -0,0 +1,140 @@ +import { createHash, randomUUID } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { agentApiKeys, agents, authUsers, boardApiKeys, companies, companyMemberships, createDb, databaseStatementCount, + instanceUserRoles } from "@paperclipai/db"; +import { createApp } from "../app.js"; +import { activeServerMetrics, recordMissedLeaseRenewal, recordRunEventCommitted } from "../services/server-metrics.js"; +import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js"; +import { createStorageService } from "../storage/service.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const support = await getEmbeddedPostgresTestSupport(); +const describePostgres = support.supported ? describe : describe.skip; +const PATH = "/api/instance/server-metrics"; +const FIELDS = [ + "schema", "processId", "buildRevision", "uptimeSec", "sampledAt", "windowMs", "mainThreadCpu", "processCpu", + "eventLoopUtilization", "eventLoopDelayP99Ms", "statementsPerSecond", "runEventLatenessP99Ms", "runEventLatenessSamples", + "agentApiPreHandlerP99Ms", "agentApiPreHandlerSamples", "leaseRenewalsMissed", "dedicatedConnections", +].sort(); + +type Db = ReturnType; +type App = Awaited>; + +describePostgres("instance server metrics route", () => { + let database: Awaited>; + let db: Db; + let directory: string; + const hash = (token: string) => createHash("sha256").update(token).digest("hex"); + const ids = { companyId: randomUUID(), agentId: randomUUID(), adminId: randomUUID(), memberId: randomUUID() }; + const keys = { admin: `pcp_board_${randomUUID()}`, member: `pcp_board_${randomUUID()}`, agent: `pcp_agent_${randomUUID()}` }; + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("instance-server-metrics-"); + db = createDb(database.connectionString); + directory = await mkdtemp(join(tmpdir(), "instance-server-metrics-storage-")); + await db.insert(companies).values({ id: ids.companyId, name: "Metrics company", issuePrefix: "MET" }); + await db.insert(authUsers).values([ids.adminId, ids.memberId].map(id => ({ id, name: "Person", email: `${id}@example.com`, + createdAt: new Date(), updatedAt: new Date() }))); + await db.insert(instanceUserRoles).values({ userId: ids.adminId, role: "instance_admin" }); + await db.insert(agents).values({ id: ids.agentId, companyId: ids.companyId, name: "Metrics agent", adapterType: "process", + status: "idle", permissions: {}, runtimeConfig: { heartbeat: { wakeOnDemand: false, intervalSec: 0 } } }); + await db.insert(companyMemberships).values([ + { companyId: ids.companyId, principalType: "user", principalId: ids.memberId, membershipRole: "owner", status: "active" }, + { companyId: ids.companyId, principalType: "agent", principalId: ids.agentId, membershipRole: "member", status: "active" }, + ]); + await db.insert(boardApiKeys).values([ + { userId: ids.adminId, name: "Admin", keyHash: hash(keys.admin) }, + { userId: ids.memberId, name: "Member", keyHash: hash(keys.member) }, + ]); + await db.insert(agentApiKeys).values({ companyId: ids.companyId, agentId: ids.agentId, name: "Agent", keyHash: hash(keys.agent), + responsibleUserId: ids.memberId }); + }, 120_000); + + afterAll(async () => { + await db?.$client.end(); + await database?.cleanup(); + if (directory) await rm(directory, { recursive: true, force: true }); + }); + + async function serve(serverMetricsEnabled: boolean, body: (call: (path: string, token?: string) => Promise<{ status: number; body: any; text: string }>) => Promise) { + const app: App = await createApp(db, { + uiMode: "none", serverPort: 0, bindHost: "127.0.0.1", allowedHostnames: ["127.0.0.1"], + deploymentMode: "authenticated", deploymentExposure: "private", authReady: true, companyDeletionEnabled: false, + managedPluginAutoInstall: [], storageService: createStorageService(createLocalDiskStorageProvider(directory)), + decisionServiceOptions: { wakeOriginAgent: async () => null }, serverMetricsEnabled, + }); + await app.locals.bundledPluginsStartup; + const server = app.listen(0, "127.0.0.1"); + try { + await new Promise(resolve => server.once("listening", resolve)); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("No HTTP test address"); + const call = async (path: string, token?: string) => { + const response = await fetch(`http://127.0.0.1:${address.port}${path}`, { headers: token ? { authorization: `Bearer ${token}` } : {} }); + const text = await response.text(); + let parsed: unknown = null; + try { parsed = JSON.parse(text); } catch { parsed = null; } + return { status: response.status, body: parsed, text }; + }; + return await body(call); + } finally { + await app.locals.paperclipShutdown?.(); + await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); + } + } + + it("serves numbers to an instance admin only, and they move with load", async () => { + await serve(true, async (call) => { + expect(activeServerMetrics()).not.toBeNull(); + expect([401, 403]).toContain((await call(PATH)).status); + expect((await call(PATH, keys.member)).status).toBe(403); + expect((await call(PATH, keys.agent)).status).toBe(403); + + const first = await call(PATH, keys.admin); + expect(first.status).toBe(200); + expect(Object.keys(first.body).sort()).toEqual(FIELDS); + expect(first.body).toMatchObject({ schema: "paperclip.server-metrics.v1", processId: expect.stringMatching(/^[0-9a-f]{16}$/) }); + expect(first.body.buildRevision === null || /^[0-9a-f]{40}$/.test(first.body.buildRevision)).toBe(true); + for (const field of ["uptimeSec", "windowMs", "processCpu", "eventLoopUtilization", "eventLoopDelayP99Ms", "statementsPerSecond", + "runEventLatenessSamples", "agentApiPreHandlerSamples", "leaseRenewalsMissed"]) { + expect(typeof first.body[field], field).toBe("number"); + } + expect(first.body.eventLoopUtilization).toBeGreaterThanOrEqual(0); + expect(first.body.dedicatedConnections).toMatchObject({ limit: expect.any(Number), inUse: expect.any(Number), waiting: expect.any(Number), + queued: expect.any(Number) }); + expect(first.body.eventLoopUtilization).toBeLessThanOrEqual(1); + + const statementsBefore = databaseStatementCount(); + for (let index = 0; index < 5; index += 1) expect((await call("/api/agents/me", keys.agent)).status).toBe(200); + expect(databaseStatementCount()).toBeGreaterThan(statementsBefore); + recordRunEventCommitted(new Date(Date.now() - 750).toISOString(), Date.now()); + recordMissedLeaseRenewal(); + + const second = await call(PATH, keys.admin); + expect(second.status).toBe(200); + expect(second.body.processId).toBe(first.body.processId); + expect(second.body.agentApiPreHandlerSamples).toBeGreaterThanOrEqual(first.body.agentApiPreHandlerSamples + 5); + expect(second.body.agentApiPreHandlerP99Ms).toBeGreaterThan(0); + expect(second.body.statementsPerSecond).toBeGreaterThan(0); + expect(second.body.runEventLatenessSamples).toBe(first.body.runEventLatenessSamples + 1); + expect(second.body.runEventLatenessP99Ms).toBeGreaterThanOrEqual(700); + expect(second.body.leaseRenewalsMissed).toBe(first.body.leaseRenewalsMissed + 1); + for (const secret of [...Object.values(ids), ...Object.values(keys)]) expect(second.text).not.toContain(secret); + expect(second.text).not.toMatch(/select|insert|update|from\s/i); + }); + expect(activeServerMetrics()).toBeNull(); + }, 240_000); + + it("is absent and collects nothing when the kill switch is off", async () => { + await serve(false, async (call) => { + expect(activeServerMetrics()).toBeNull(); + expect((await call(PATH, keys.admin)).status).toBe(404); + expect((await call(PATH, keys.member)).status).toBe(404); + expect((await call("/api/agents/me", keys.agent)).status).toBe(200); + expect(activeServerMetrics()).toBeNull(); + }); + }, 240_000); +}); diff --git a/server/src/__tests__/openapi-routes.test.ts b/server/src/__tests__/openapi-routes.test.ts index d4b6e5b8e77..399b53fc554 100644 --- a/server/src/__tests__/openapi-routes.test.ts +++ b/server/src/__tests__/openapi-routes.test.ts @@ -76,6 +76,7 @@ const apiPrefixes: Record = { "inbox-agent-policy.ts": "/api", "inbox-dismissals.ts": "/api", "instance-database-backups.ts": "/api", + "instance-server-metrics.ts": "/api", "instance-settings.ts": "/api", "issues.ts": "/api", "issue-tree-control.ts": "/api", diff --git a/server/src/__tests__/server-metrics.test.ts b/server/src/__tests__/server-metrics.test.ts new file mode 100644 index 00000000000..e0c20ce0b62 --- /dev/null +++ b/server/src/__tests__/server-metrics.test.ts @@ -0,0 +1,196 @@ +import { readFileSync, writeFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { afterEach, describe, expect, it } from "vitest"; +import type { EventLoopUtilization } from "node:perf_hooks"; +import { + activeServerMetrics, + recordMissedLeaseRenewal, + recordRunEventCommitted, + ServerMetricsCollector, + serverMetricsEnabledFromEnv, + startServerMetrics, + stopServerMetrics, + type ServerMetricsProbes, +} from "../services/server-metrics.js"; + +const FIXTURE = fileURLToPath(new URL("../../../scripts/scale-ramp/server-metrics.fixture.json", import.meta.url)); + +function fakeProbes() { + const state = { now: 0, wall: Date.parse("2026-11-14T12:00:00.000Z"), idle: 0, active: 0, cpuMicros: 0, mainMs: 0, statements: 0, uptime: 100 }; + const elu = (): EventLoopUtilization => ({ idle: state.idle, active: state.active, utilization: 0 }); + const probes: ServerMetricsProbes = { + now: () => state.now, + wallNow: () => state.wall, + eventLoopUtilization: (current?: EventLoopUtilization, previous?: EventLoopUtilization) => { + if (!current) return elu(); + const idle = current.idle - (previous?.idle ?? 0); + const active = current.active - (previous?.active ?? 0); + return { idle, active, utilization: idle + active > 0 ? active / (idle + active) : 0 }; + }, + processCpuMicros: () => state.cpuMicros, + mainThreadCpuMs: () => state.mainMs, + statementCount: () => state.statements, + uptimeSec: () => state.uptime, + dedicatedConnections: () => ({ limit: 24, inUse: 3, peakInUse: 9, waiting: 1, queued: 12, overLimit: 0, nestedOverLimit: 0 }), + }; + const advance = (ms: number, load: { busy: number; cpu?: number; statementsPerSecond?: number }) => { + state.now += ms; + state.wall += ms; + state.uptime += ms / 1000; + state.active += ms * load.busy; + state.idle += ms * (1 - load.busy); + state.mainMs += ms * load.busy; + state.cpuMicros += ms * (load.cpu ?? load.busy) * 1000; + state.statements += (ms / 1000) * (load.statementsPerSecond ?? 0); + }; + return { probes, advance }; +} + +const collectors: ServerMetricsCollector[] = []; +function collector(probes: ServerMetricsProbes) { + const created = new ServerMetricsCollector({ probes, bucketMs: 10_000, buckets: 6, buildRevision: "0123456789abcdef0123456789abcdef01234567", + monitorEventLoop: false, processId: "a1b2c3d4e5f60718" }); + collectors.push(created); + return created; +} + +afterEach(() => { + for (const created of collectors.splice(0)) created.stop(); + const active = activeServerMetrics(); + if (active) stopServerMetrics(active); +}); + +describe("server metrics collector", () => { + it("reports rates and utilization over the sliding window, dropping buckets older than the window", () => { + const { probes, advance } = fakeProbes(); + const metrics = collector(probes); + for (let bucket = 0; bucket < 6; bucket += 1) { + advance(10_000, { busy: 0.9, statementsPerSecond: 500 }); + metrics.rotate(); + } + const busy = metrics.snapshot(); + expect(busy.windowMs).toBe(50_000); + expect(busy.eventLoopUtilization).toBeCloseTo(0.9, 4); + expect(busy.mainThreadCpu).toBeCloseTo(0.9, 4); + expect(busy.statementsPerSecond).toBeCloseTo(500, 2); + + for (let bucket = 0; bucket < 6; bucket += 1) { + advance(10_000, { busy: 0.1, statementsPerSecond: 20 }); + metrics.rotate(); + } + const quiet = metrics.snapshot(); + expect(quiet.eventLoopUtilization).toBeCloseTo(0.1, 4); + expect(quiet.statementsPerSecond).toBeCloseTo(20, 2); + }); + + it("expires buckets by elapsed time when the rotation timer fires late", () => { + const { probes, advance } = fakeProbes(); + const metrics = collector(probes); + for (let bucket = 0; bucket < 6; bucket += 1) { + advance(10_000, { busy: 0.1, statementsPerSecond: 10 }); + metrics.rotate(); + } + metrics.recordRunEventLatenessMs(5_000); + advance(35_000, { busy: 0.5, statementsPerSecond: 100 }); + metrics.rotate(); + const late = metrics.snapshot(); + expect(late.windowMs).toBe(55_000); + expect(late.statementsPerSecond).toBeCloseTo((20 * 10 + 35 * 100) / 55, 2); + expect(late.runEventLatenessSamples).toBe(1); + }); + + it("reports the real window after a block longer than the window, and the block shows in it", () => { + const { probes, advance } = fakeProbes(); + const metrics = collector(probes); + for (let bucket = 0; bucket < 6; bucket += 1) { + advance(10_000, { busy: 0.1 }); + metrics.rotate(); + } + metrics.recordRunEventLatenessMs(20); + advance(300_000, { busy: 1 }); + metrics.rotate(); + const blocked = metrics.snapshot(); + expect(blocked.windowMs).toBe(300_000); + expect(blocked.eventLoopUtilization).toBeCloseTo(1, 4); + expect(blocked.runEventLatenessSamples).toBe(1); + advance(10_000, { busy: 0.2 }); + metrics.rotate(); + expect(metrics.snapshot()).toMatchObject({ windowMs: 10_000, runEventLatenessSamples: 0 }); + for (let bucket = 0; bucket < 5; bucket += 1) { + advance(10_000, { busy: 0.2 }); + metrics.rotate(); + } + const recovered = metrics.snapshot(); + expect(recovered.windowMs).toBe(50_000); + expect(recovered.eventLoopUtilization).toBeCloseTo(0.2, 4); + }); + + it("reports latency percentiles only for the window and absent when nothing was recorded", () => { + const { probes, advance } = fakeProbes(); + const metrics = collector(probes); + expect(metrics.snapshot()).toMatchObject({ runEventLatenessP99Ms: null, runEventLatenessSamples: 0, + agentApiPreHandlerP99Ms: null, agentApiPreHandlerSamples: 0 }); + for (let index = 0; index < 100; index += 1) metrics.recordRunEventLatenessMs(index < 98 ? 20 : 2_000); + metrics.recordAgentApiPreHandlerMs(3.5); + const recorded = metrics.snapshot(); + expect(recorded.runEventLatenessSamples).toBe(100); + expect(recorded.runEventLatenessP99Ms).toBeGreaterThan(1_900); + expect(recorded.agentApiPreHandlerP99Ms).toBeCloseTo(3.5, 1); + for (let bucket = 0; bucket < 6; bucket += 1) { + advance(10_000, { busy: 0 }); + metrics.rotate(); + } + expect(metrics.snapshot()).toMatchObject({ runEventLatenessP99Ms: null, runEventLatenessSamples: 0, agentApiPreHandlerSamples: 0 }); + }); + + it("counts missed lease renewals since start and never resets them with the window", () => { + const { probes, advance } = fakeProbes(); + const metrics = collector(probes); + metrics.recordMissedLeaseRenewal(); + metrics.recordMissedLeaseRenewal(); + for (let bucket = 0; bucket < 8; bucket += 1) { + advance(10_000, { busy: 0 }); + metrics.rotate(); + } + expect(metrics.snapshot().leaseRenewalsMissed).toBe(2); + }); + + it("records into the process collector only while it runs", () => { + recordRunEventCommitted(new Date(Date.now() - 500).toISOString(), Date.now()); + recordMissedLeaseRenewal(); + expect(activeServerMetrics()).toBeNull(); + const started = startServerMetrics(); + expect(startServerMetrics()).toBe(started); + recordRunEventCommitted(new Date(Date.now() - 500).toISOString(), Date.now()); + recordRunEventCommitted("not a time", Date.now()); + recordMissedLeaseRenewal(); + const snapshot = started.snapshot(); + expect(snapshot.runEventLatenessSamples).toBe(1); + expect(snapshot.runEventLatenessP99Ms).toBeGreaterThanOrEqual(450); + expect(snapshot.leaseRenewalsMissed).toBe(1); + stopServerMetrics(started); + expect(activeServerMetrics()).toBeNull(); + }); + + it("reads the kill switch strictly and defaults it off", () => { + expect(serverMetricsEnabledFromEnv({})).toBe(false); + expect(serverMetricsEnabledFromEnv({ PAPERCLIP_SERVER_METRICS: "true" })).toBe(true); + expect(serverMetricsEnabledFromEnv({ PAPERCLIP_SERVER_METRICS: "0" })).toBe(false); + expect(() => serverMetricsEnabledFromEnv({ PAPERCLIP_SERVER_METRICS: "yes" })).toThrow(/PAPERCLIP_SERVER_METRICS/); + }); + + it("serializes exactly the fixture the scale-ramp harness parses", () => { + const { probes, advance } = fakeProbes(); + const metrics = collector(probes); + for (let bucket = 0; bucket < 6; bucket += 1) { + advance(10_000, { busy: 0.42, cpu: 0.55, statementsPerSecond: 180 }); + metrics.rotate(); + } + for (let index = 0; index < 50; index += 1) metrics.recordRunEventLatenessMs(120); + for (let index = 0; index < 50; index += 1) metrics.recordAgentApiPreHandlerMs(15); + metrics.recordMissedLeaseRenewal(); + const snapshot = JSON.parse(JSON.stringify(metrics.snapshot())); + if (process.env.UPDATE_SERVER_METRICS_FIXTURE === "1") writeFileSync(FIXTURE, `${JSON.stringify(snapshot, null, 2)}\n`); + expect(snapshot).toEqual(JSON.parse(readFileSync(FIXTURE, "utf8"))); + }); +}); diff --git a/server/src/app.ts b/server/src/app.ts index a3682ea2a26..ff1b4d6a6df 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -11,7 +11,7 @@ import { finishServiceShutdown } from "./shutdown.js"; import { promptInjectionPreventionRoutes } from "./routes/prompt-injection-prevention.js"; import { voiceSessionRoutes, voiceWebhookRoutes } from "./routes/voice-sessions.js"; import { eq } from "drizzle-orm"; -import { chatEndpoints } from "@paperclipai/db"; +import { chatEndpoints, dedicatedDbConnectionStats } from "@paperclipai/db"; import { fastResponseRoutes } from "./routes/fast-responses.js"; import { fastResponseService } from "./services/fast-responses.js"; import { createDeliveryWorkCoordinator } from "./services/delivery-work-coordinator.js"; @@ -253,6 +253,14 @@ import { import { COMPANY_IMPORT_API_PATH } from "./routes/company-import-paths.js"; import { apiCompression } from "./middleware/api-compression.js"; import { apiServerTiming } from "./middleware/api-server-timing.js"; +import { instanceServerMetricsRoutes } from "./routes/instance-server-metrics.js"; +import { + serverMetricsAgentPreHandler, + serverMetricsArrival, + serverMetricsEnabledFromEnv, + startServerMetrics, + stopServerMetrics, +} from "./services/server-metrics.js"; import { chatWebhookBodyParser } from "./middleware/chat-webhook-body.js"; import { createChatWebhookDiagnostics } from "./services/chat-webhook-diagnostics.js"; @@ -491,9 +499,12 @@ export async function createApp( managedPluginAutoInstall?: readonly string[] | null; /** Test override for the bundled plugin catalog root. */ bundledPluginCatalogRoot?: string; + serverMetricsEnabled?: boolean; }, ) { const app = express(); + const serverMetrics = (opts.serverMetricsEnabled ?? serverMetricsEnabledFromEnv(process.env)) ? startServerMetrics(() => dedicatedDbConnectionStats(db)) : null; + if (serverMetrics) app.use("/api", serverMetricsArrival()); // First, so the reported server time includes admission and database waits. app.use("/api", apiServerTiming()); app.use(databaseOperationMiddleware); @@ -886,6 +897,7 @@ export async function createApp( if (opts.databaseBackupService) { api.use(instanceDatabaseBackupRoutes(opts.databaseBackupService)); } + if (serverMetrics) api.use(instanceServerMetricsRoutes(serverMetrics)); const pluginRegistry = pluginRegistryService(db); const eventBus = createPluginEventBus(); setPluginEventBus(eventBus); @@ -1084,6 +1096,7 @@ export async function createApp( api.use(museBoardRoutes(db, opts.authPublicBaseUrl)); api.use(museQualificationRoutes(db)); + if (serverMetrics) app.use("/api", serverMetricsAgentPreHandler(serverMetrics)); app.use("/api", api); app.use("/api", (_req, res) => { res.status(404).json({ error: "API route not found" }); @@ -1448,6 +1461,7 @@ export async function createApp( // caller stops the database and the provider. A lease release that // fails stays a durable record for the startup reaper. await setupTokenLoginService?.shutdown(); + if (serverMetrics) stopServerMetrics(serverMetrics); }); }); return appServicesShutdown; diff --git a/server/src/routes/instance-server-metrics.ts b/server/src/routes/instance-server-metrics.ts new file mode 100644 index 00000000000..247fe952e5f --- /dev/null +++ b/server/src/routes/instance-server-metrics.ts @@ -0,0 +1,15 @@ +import { Router } from "express"; +import type { ServerMetricsCollector } from "../services/server-metrics.js"; +import { assertInstanceAdmin } from "./authz.js"; + +export function instanceServerMetricsRoutes(collector: ServerMetricsCollector) { + const router = Router(); + + router.get("/instance/server-metrics", (req, res) => { + assertInstanceAdmin(req); + res.set("Cache-Control", "no-store"); + res.json(collector.snapshot()); + }); + + return router; +} diff --git a/server/src/routes/openapi.ts b/server/src/routes/openapi.ts index 3803834b536..8762d89f512 100644 --- a/server/src/routes/openapi.ts +++ b/server/src/routes/openapi.ts @@ -1642,6 +1642,7 @@ const INSTANCE_ADMIN_OPERATIONS = new Set([ "POST /api/companies", "POST /api/plugins/install", "POST /api/instance/database-backups", + "GET /api/instance/server-metrics", "POST /api/admin/users/{userId}/promote-instance-admin", "POST /api/admin/users/{userId}/demote-instance-admin", "PUT /api/admin/users/{userId}/company-access", @@ -10391,6 +10392,17 @@ registry.registerPath({ responses: { 201: r.ok(), 401: r.unauthorized, 403: r.forbidden }, }); +// ─── Instance server metrics ────────────────────────────────────────────────── + +registry.registerPath({ + method: "get", + path: "/api/instance/server-metrics", + tags: ["instance"], + summary: "Get this server process's load metrics", + description: "Instance admins only: agent credentials and company members receive 403. Returns numbers for the one server process that answers: CPU, event-loop utilization and delay, statements per second, run event lateness and agent API pre-handler p99, missed lease renewals and dedicated database connection use, over about the last minute (windowMs). It returns 404 unless the operator set PAPERCLIP_SERVER_METRICS=true.", + responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound }, +}); + // ─── LLM text endpoints ─────────────────────────────────────────────────────── registry.registerPath({ diff --git a/server/src/services/native-runtime/native-execution-lease.test.ts b/server/src/services/native-runtime/native-execution-lease.test.ts index 26145d855f5..046d0a3a5bc 100644 --- a/server/src/services/native-runtime/native-execution-lease.test.ts +++ b/server/src/services/native-runtime/native-execution-lease.test.ts @@ -3,6 +3,7 @@ import type { SQL } from "drizzle-orm"; import { PgDialect } from "drizzle-orm/pg-core"; import type { Db } from "@paperclipai/db"; import { startNativeSessionExecutionLeaseRenewal } from "./native-execution-lease.js"; +import { startServerMetrics, stopServerMetrics } from "../server-metrics.js"; const dialect = new PgDialect(); @@ -134,6 +135,24 @@ describe("native execution renewal ownership", () => { expect(returning).toHaveBeenCalledTimes(1); expect(vi.getTimerCount()).toBe(0); }); + it("counts a renewal deadline that passes as a missed lease renewal for the server metrics", async () => { + const metrics = startServerMetrics(); + try { + vi.useFakeTimers(); + const { input, returning } = fixture(); + let complete!: (value: { runId: string }[]) => void; + returning.mockImplementationOnce(() => new Promise(resolve => { complete = resolve; })); + const guard = startNativeSessionExecutionLeaseRenewal(input); + await vi.advanceTimersByTimeAsync(30_000); + expect(metrics.snapshot().leaseRenewalsMissed).toBe(0); + await vi.advanceTimersByTimeAsync(30_000); + expect(metrics.snapshot().leaseRenewalsMissed).toBe(1); + complete([{ runId: "run" }]); + await expect(guard.stop()).rejects.toThrow("native_session_lease_renewal_deadline"); + } finally { + stopServerMetrics(metrics); + } + }); it("hands preparation renewal to the same owner's executor at the next attempt", async () => { vi.useFakeTimers(); const { input, returning } = fixture(); diff --git a/server/src/services/native-runtime/native-execution-lease.ts b/server/src/services/native-runtime/native-execution-lease.ts index a46820364c3..9ee78b6e4b9 100644 --- a/server/src/services/native-runtime/native-execution-lease.ts +++ b/server/src/services/native-runtime/native-execution-lease.ts @@ -5,6 +5,7 @@ import { currentNativeControllerIdentity, type NativeControllerIdentity } from " import { OPERATOR_ATTESTED_CONTROLLER_HOST } from "./native-controller-host-recovery.js"; import { NATIVE_OWNERSHIP_UNVERIFIED_ERROR_CODE } from "./native-runner-ownership.js"; import { REMOTE_CONTROLLER_LEASE_MS } from "./native-runner-recovery-contract.js"; +import { recordMissedLeaseRenewal } from "../server-metrics.js"; export const NATIVE_SESSION_EXECUTION_LEASE_TTL_MS = 20 * 60_000; const NATIVE_SESSION_EXECUTION_LEASE_RENEW_INTERVAL_MS = 5 * 60_000; @@ -613,7 +614,10 @@ export function startNativeSessionExecutionLeaseRenewal(input: RenewalInput): Na state!.loss = Promise.resolve().then(state!.input.onLost).catch(() => undefined); }; const deadline = (delay: number) => { - const timer = setTimeout(() => lose(new Error("native_session_lease_renewal_deadline")), Math.max(0, delay)); + const timer = setTimeout(() => { + recordMissedLeaseRenewal(); + lose(new Error("native_session_lease_renewal_deadline")); + }, Math.max(0, delay)); timer.unref?.(); return timer; }; diff --git a/server/src/services/native-runtime/paperclip-control-plane-port.test.ts b/server/src/services/native-runtime/paperclip-control-plane-port.test.ts index bbda1e48c8b..2975c229823 100644 --- a/server/src/services/native-runtime/paperclip-control-plane-port.test.ts +++ b/server/src/services/native-runtime/paperclip-control-plane-port.test.ts @@ -2,6 +2,7 @@ import { nativeResponsePresentationWork } from "./native-response-presentation-w import { resolveExternalTestDatabaseUrl } from "../../__tests__/helpers/external-test-database.js"; import { plugins } from "@paperclipai/db"; import { readTaskPanelActivations } from "../plugin-task-panels.js"; +import { startServerMetrics, stopServerMetrics } from "../server-metrics.js"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { and, asc, eq, sql } from "drizzle-orm"; import { createHash, generateKeyPairSync, randomUUID } from "node:crypto"; @@ -548,6 +549,21 @@ describe("PaperclipControlPlanePort conformance", () => { payload: { itemId: "ending-item", kind: "commandExecution", text: "***REDACTED***" } }]); }); + it("records the lateness of each committed runner event once for the server metrics", async () => { + const metrics = startServerMetrics(); + try { + const f = await terminalObserverFixture(); + const event = { ...f.event, emittedAt: new Date(Date.now() - 2_000).toISOString() }; + await f.port.appendEvent(event); + await f.port.appendEvent(event); + const snapshot = metrics.snapshot(); + expect(snapshot.runEventLatenessSamples).toBe(1); + expect(snapshot.runEventLatenessP99Ms).toBeGreaterThanOrEqual(1_900); + } finally { + stopServerMetrics(metrics); + } + }); + it("completes a native run when a bound secret equals a protocol word", async () => { const observed: PrpEvent[] = []; const f = await terminalObserverFixture({ secrets: ["interrupted", "completed", "succeeded", "satisfied"], @@ -1020,6 +1036,27 @@ describe("PaperclipControlPlanePort conformance", () => { return { port, binding, identity, runnerId, event, stored, streamed }; }; + it("measures every row of a streaming batch from the batch commit, not after earlier rows' observers", async () => { + const metrics = startServerMetrics(); + const recorded: number[] = []; + const record = metrics.recordRunEventLatenessMs.bind(metrics); + metrics.recordRunEventLatenessMs = (ms: number) => { recorded.push(ms); record(ms); }; + try { + const f = await streamingFixture({ streamingBatchMs: 600_000, onCommittedEvent: async (event) => { + if (event.sourceSeq === 2) await new Promise(resolve => setTimeout(resolve, 1_200)); + } }); + await f.port.appendEvent(f.event(1), f.streamed); + const deltas = [2, 3, 4].map(sourceSeq => f.port.appendEvent(f.event(sourceSeq), f.streamed)); + await f.port.appendEvent(f.event(5, "tool.execution.started")); + await Promise.all(deltas); + const batch = recorded.slice(1, 4); + expect(batch).toHaveLength(3); + expect(Math.max(...batch) - Math.min(...batch)).toBeLessThan(500); + } finally { + stopServerMetrics(metrics); + } + }); + it("commits the first text delta at once and later deltas in one batch before the next other event", async () => { const committed: number[] = []; // A timer this long would time the test out: only the first delta and the diff --git a/server/src/services/native-runtime/paperclip-control-plane-port.ts b/server/src/services/native-runtime/paperclip-control-plane-port.ts index 7601de7f3e6..7afee85af21 100644 --- a/server/src/services/native-runtime/paperclip-control-plane-port.ts +++ b/server/src/services/native-runtime/paperclip-control-plane-port.ts @@ -39,6 +39,7 @@ import { eligibleNativeTaskSessionPublication, publishNativeTaskSessionInTransac import { lockNativeRunnerCheckpointOwner, nativeRunnerCheckpointOwnerLock, validateNativeRunnerCheckpointOwner, inspectNativeRunnerUpgradeHeader, type NativeRunnerCheckpointOwner } from "./native-runner-checkpoint.js"; import { crashPoint } from "@paperclipai/shared/crash-points"; import { NATIVE_PROVIDER_DURABLE_EVENT_TYPES } from "./native-retired-backup-source.js"; +import { recordRunEventCommitted } from "../server-metrics.js"; export interface PaperclipControlPlaneBinding { companyId: string; @@ -476,10 +477,11 @@ export class PaperclipControlPlanePort implements ControlPlanePort { this.#assertActive(options); const pendingObservation = this.#deferredEventObservers.get(observerKey); const persisted = await appendHeartbeatRunEvent(this.#db, input); + const committedAtMs = Date.now(); this.#assertActive(options); const persistenceEndedAt = persistenceStartedAt + performance.now() - persistenceClock; let observation = pendingObservation ?? this.#deferredEventObservers.get(observerKey); - if (!observation) observation = this.#observePersistedEvent(event, persisted, persistenceStartedAt, persistenceEndedAt); + if (!observation) observation = this.#observePersistedEvent(event, persisted, persistenceStartedAt, persistenceEndedAt, committedAtMs); if (options?.deferPostCommitObservers) { this.#deferredEventObservers.set(observerKey, observation); void observation.then(() => { @@ -503,9 +505,11 @@ export class PaperclipControlPlanePort implements ControlPlanePort { persisted: AppendHeartbeatRunEventResult, persistenceStartedAt: number, persistenceEndedAt: number, + committedAtMs: number, ): Promise { try { await this.#onEventPersistence?.(event, persistenceStartedAt, persistenceEndedAt); } catch {} if (persisted.disposition === "committed") { + recordRunEventCommitted(event.emittedAt, committedAtMs); try { publishLiveEvent({ companyId: this.#binding.companyId, @@ -590,11 +594,12 @@ export class PaperclipControlPlanePort implements ControlPlanePort { for (const pending of batch) pending.reject(error); return; } + const committedAtMs = Date.now(); for (const [index, pending] of batch.entries()) { const persisted = receipts[index]!; const endedAt = pending.startedAtMs + performance.now() - pending.startedClock; try { - await this.#observePersistedEvent(pending.event, persisted, pending.startedAtMs, endedAt); + await this.#observePersistedEvent(pending.event, persisted, pending.startedAtMs, endedAt, committedAtMs); } catch (error) { pending.reject(error); continue; diff --git a/server/src/services/server-metrics.ts b/server/src/services/server-metrics.ts new file mode 100644 index 00000000000..a4ee23616d3 --- /dev/null +++ b/server/src/services/server-metrics.ts @@ -0,0 +1,274 @@ +import { randomBytes } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { + createHistogram, + monitorEventLoopDelay, + performance, + type EventLoopUtilization, + type IntervalHistogram, + type RecordableHistogram, +} from "node:perf_hooks"; +import type { RequestHandler } from "express"; +import { databaseStatementCount, type DedicatedDbConnectionStats } from "@paperclipai/db"; +import { readBuildCommit } from "../build-commit.js"; + +export const SERVER_METRICS_ENV = "PAPERCLIP_SERVER_METRICS"; +export const SERVER_METRICS_SCHEMA = "paperclip.server-metrics.v1"; +export const SERVER_METRICS_BUCKET_MS = 10_000; +export const SERVER_METRICS_BUCKETS = 6; +const EVENT_LOOP_DELAY_RESOLUTION_MS = 20; +const LINUX_CLOCK_TICK_MS = 10; + +export type ServerMetricsSnapshot = { + schema: typeof SERVER_METRICS_SCHEMA; + processId: string; + buildRevision: string | null; + uptimeSec: number; + sampledAt: string; + windowMs: number; + mainThreadCpu: number | null; + processCpu: number; + eventLoopUtilization: number; + eventLoopDelayP99Ms: number; + statementsPerSecond: number; + runEventLatenessP99Ms: number | null; + runEventLatenessSamples: number; + agentApiPreHandlerP99Ms: number | null; + agentApiPreHandlerSamples: number; + leaseRenewalsMissed: number; + dedicatedConnections: DedicatedDbConnectionStats | null; +}; + +export type ServerMetricsProbes = { + now: () => number; + wallNow: () => number; + eventLoopUtilization: (current?: EventLoopUtilization, previous?: EventLoopUtilization) => EventLoopUtilization; + processCpuMicros: () => number; + mainThreadCpuMs: () => number | null; + statementCount: () => number; + uptimeSec: () => number; + dedicatedConnections: () => DedicatedDbConnectionStats | null; +}; + +type Checkpoint = { + at: number; + elu: EventLoopUtilization; + processCpuMicros: number; + mainThreadCpuMs: number | null; + statements: number; +}; + +function readLinuxMainThreadCpuMs(): number | null { + if (process.platform !== "linux") return null; + try { + const stat = readFileSync(`/proc/self/task/${process.pid}/stat`, "utf8"); + const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" "); + const ticks = Number(fields[11]) + Number(fields[12]); + return Number.isFinite(ticks) ? ticks * LINUX_CLOCK_TICK_MS : null; + } catch { + return null; + } +} + +const defaultProbes: ServerMetricsProbes = { + now: () => performance.now(), + wallNow: () => Date.now(), + eventLoopUtilization: (current, previous) => performance.eventLoopUtilization(current, previous), + processCpuMicros: () => { + const usage = process.cpuUsage(); + return usage.user + usage.system; + }, + mainThreadCpuMs: readLinuxMainThreadCpuMs, + statementCount: databaseStatementCount, + uptimeSec: () => process.uptime(), + dedicatedConnections: () => null, +}; + +const round = (value: number, digits: number) => Number(value.toFixed(digits)); + +export class ServerMetricsCollector { + readonly processId: string; + readonly buildRevision: string | null; + private readonly probes: ServerMetricsProbes; + private readonly bucketMs: number; + private readonly starts: Array; + private readonly lateness: RecordableHistogram[]; + private readonly preHandler: RecordableHistogram[]; + private readonly delayP99Ns: number[]; + private readonly merged = createHistogram(); + private readonly eventLoopDelay: IntervalHistogram | null; + private current = 0; + private missedLeaseRenewals = 0; + private timer: NodeJS.Timeout | null = null; + private stopped = false; + + constructor(options: { probes?: Partial; bucketMs?: number; buckets?: number; + buildRevision?: string | null; monitorEventLoop?: boolean; processId?: string } = {}) { + this.processId = options.processId ?? randomBytes(8).toString("hex"); + this.probes = { ...defaultProbes, ...options.probes }; + this.bucketMs = options.bucketMs ?? SERVER_METRICS_BUCKET_MS; + const buckets = options.buckets ?? SERVER_METRICS_BUCKETS; + this.buildRevision = options.buildRevision === undefined ? readBuildCommit() : options.buildRevision; + this.starts = Array.from({ length: buckets }, () => null); + this.lateness = Array.from({ length: buckets }, () => createHistogram()); + this.preHandler = Array.from({ length: buckets }, () => createHistogram()); + this.delayP99Ns = Array.from({ length: buckets }, () => 0); + this.eventLoopDelay = options.monitorEventLoop === false ? null + : monitorEventLoopDelay({ resolution: EVENT_LOOP_DELAY_RESOLUTION_MS }); + this.eventLoopDelay?.enable(); + this.starts[0] = this.checkpoint(); + this.arm(); + } + + private checkpoint(): Checkpoint { + return { + at: this.probes.now(), + elu: this.probes.eventLoopUtilization(), + processCpuMicros: this.probes.processCpuMicros(), + mainThreadCpuMs: this.probes.mainThreadCpuMs(), + statements: this.probes.statementCount(), + }; + } + + private arm(): void { + if (this.stopped) return; + this.timer = setTimeout(() => { + this.timer = null; + this.rotate(); + this.arm(); + }, this.bucketMs); + this.timer.unref(); + } + + rotate(): void { + const now = this.checkpoint(); + const started = this.starts[this.current]!; + const steps = Math.min(this.starts.length - 1, Math.max(1, Math.floor((now.at - started.at) / this.bucketMs))); + if (this.eventLoopDelay) { + this.delayP99Ns[this.current] = this.eventLoopDelay.percentile(99); + this.eventLoopDelay.reset(); + } + for (let step = 0; step < steps; step += 1) { + this.current = (this.current + 1) % this.starts.length; + this.lateness[this.current]!.reset(); + this.preHandler[this.current]!.reset(); + this.delayP99Ns[this.current] = 0; + this.starts[this.current] = null; + } + this.starts[this.current] = now; + } + + recordRunEventLatenessMs(ms: number): void { + this.lateness[this.current]!.record(Math.max(1, Math.round(ms * 1000))); + } + + recordAgentApiPreHandlerMs(ms: number): void { + this.preHandler[this.current]!.record(Math.max(1, Math.round(ms * 1000))); + } + + recordMissedLeaseRenewal(): void { + this.missedLeaseRenewals += 1; + } + + private windowP99Ms(histograms: RecordableHistogram[]): { p99Ms: number | null; samples: number } { + this.merged.reset(); + for (const histogram of histograms) if (histogram.count > 0) this.merged.add(histogram); + const samples = this.merged.count; + return { p99Ms: samples > 0 ? round(this.merged.percentile(99) / 1000, 3) : null, samples }; + } + + snapshot(): ServerMetricsSnapshot { + const now = this.checkpoint(); + let oldest = this.starts[this.current]!; + for (let offset = 1; offset < this.starts.length; offset += 1) { + const start = this.starts[(this.current + offset) % this.starts.length]; + if (start) { oldest = start; break; } + } + const windowMs = Math.max(1, now.at - oldest.at); + let delayP99Ns = this.eventLoopDelay?.percentile(99) ?? 0; + for (let index = 0; index < this.starts.length; index += 1) { + if (index !== this.current && this.starts[index]) delayP99Ns = Math.max(delayP99Ns, this.delayP99Ns[index]!); + } + const lateness = this.windowP99Ms(this.lateness); + const preHandler = this.windowP99Ms(this.preHandler); + return { + schema: SERVER_METRICS_SCHEMA, + processId: this.processId, + buildRevision: this.buildRevision, + uptimeSec: Math.round(this.probes.uptimeSec()), + sampledAt: new Date(this.probes.wallNow()).toISOString(), + windowMs: Math.round(windowMs), + mainThreadCpu: now.mainThreadCpuMs !== null && oldest.mainThreadCpuMs !== null + ? round((now.mainThreadCpuMs - oldest.mainThreadCpuMs) / windowMs, 4) : null, + processCpu: round((now.processCpuMicros - oldest.processCpuMicros) / 1000 / windowMs, 4), + eventLoopUtilization: round(this.probes.eventLoopUtilization(now.elu, oldest.elu).utilization, 4), + eventLoopDelayP99Ms: round(delayP99Ns / 1e6, 3), + statementsPerSecond: round((now.statements - oldest.statements) / (windowMs / 1000), 2), + runEventLatenessP99Ms: lateness.p99Ms, + runEventLatenessSamples: lateness.samples, + agentApiPreHandlerP99Ms: preHandler.p99Ms, + agentApiPreHandlerSamples: preHandler.samples, + leaseRenewalsMissed: this.missedLeaseRenewals, + dedicatedConnections: this.probes.dedicatedConnections(), + }; + } + + stop(): void { + this.stopped = true; + if (this.timer) clearTimeout(this.timer); + this.timer = null; + this.eventLoopDelay?.disable(); + } +} + +let active: ServerMetricsCollector | null = null; + +export function serverMetricsEnabledFromEnv(env: NodeJS.ProcessEnv): boolean { + const value = env[SERVER_METRICS_ENV]?.trim().toLowerCase(); + if (value === undefined || value === "") return false; + if (value === "true" || value === "1") return true; + if (value === "false" || value === "0") return false; + throw new Error(`${SERVER_METRICS_ENV} must be "true" or "false", got: ${env[SERVER_METRICS_ENV]}`); +} + +export function startServerMetrics(dedicatedConnections?: () => DedicatedDbConnectionStats | null): ServerMetricsCollector { + active ??= new ServerMetricsCollector(dedicatedConnections ? { probes: { dedicatedConnections } } : {}); + return active; +} + +export function stopServerMetrics(collector: ServerMetricsCollector): void { + collector.stop(); + if (active === collector) active = null; +} + +export function activeServerMetrics(): ServerMetricsCollector | null { + return active; +} + +export function recordRunEventCommitted(emittedAt: string | null | undefined, committedAtMs: number): void { + if (!active || !emittedAt) return; + const emitted = Date.parse(emittedAt); + if (Number.isFinite(emitted)) active.recordRunEventLatenessMs(committedAtMs - emitted); +} + +export function recordMissedLeaseRenewal(): void { + active?.recordMissedLeaseRenewal(); +} + +const arrivedAt = Symbol("serverMetricsArrivedAt"); +type TimedRequest = { [arrivedAt]?: number }; + +export function serverMetricsArrival(): RequestHandler { + return (req, _res, next) => { + (req as TimedRequest)[arrivedAt] = performance.now(); + next(); + }; +} + +export function serverMetricsAgentPreHandler(collector: ServerMetricsCollector): RequestHandler { + return (req, _res, next) => { + const started = (req as TimedRequest)[arrivedAt]; + if (started !== undefined && req.actor?.type === "agent") collector.recordAgentApiPreHandlerMs(performance.now() - started); + next(); + }; +} From 8cc26221af2b87eef80a10462088cf0bade4d6fd Mon Sep 17 00:00:00 2001 From: Nicky Leach Date: Sat, 14 Nov 2026 19:13:48 -0800 Subject: [PATCH 05/12] perf(native): accept a plugin's in-preparation project-auth check on warm attach (#21710) 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 > - Environment plugins can run a native Runner as a plugin task, and a warm session keeps that Runner between turns > - On a warm turn Core attaches the kept Runner to the new run: the plugin prepares the new run, then Core checks managed project authentication > - A warm attach has no submit step, so Core sends a separate `check_project_auth` operation after `prepare` > - That separate operation is one more plugin dispatch and Launcher round trip on every warm turn, about 0.12–0.18 s, and it is serial > - This pull request lets the plugin do the check inside `prepare` and say so, so Core does not send the second operation > - The benefit is a faster warm turn with the same proof and the same failure behavior ## Linked Issues or Issue Description **What existing behavior does this improve?** The warm attach of a plugin Runner task (`plugin-runner-task.ts` `prepareLaunch`). When `launched` is true, Core always calls `checkProjectAuth` after `prepare`. **Subsystem affected** Native runtime, plugin Runner tasks, and the plugin SDK environment task contract. **Current behavior** Cold starts fold the check into submit (`projectAuthCheckAtSubmit`). Warm attaches send `prepare`, then a separate `check_project_auth`. Measured on a plugin sandbox, the separate operation costs 0.12–0.18 s on each warm turn. **Proposed behavior** The `prepared` result has a new optional flag, `projectAuthChecked`. A plugin sets it only when it ran the managed project-authentication check inside this preparation, for this launch's configuration, provider and projects, and the check allowed them. Core then records the same lease proof that an allowed `check_project_auth` records, and skips the separate check. **Reason and benefit** One fewer serial round trip on every warm turn. The plugin already runs the check for this task; this removes a dispatch, not a check. **Breaking changes** None. The flag is optional. A plugin that does not set it, or that saw a refusal, gets the current behavior. Plugins detect the flag with the SDK schema before they send it. ## What Changed - `packages/plugins/sdk/src/environment-tasks.ts`: add optional `projectAuthChecked: true` to the `prepared` result, with a doc comment that defines it. - `server/src/services/environment-task-runtime.ts`: when a `prepared` result has `projectAuthChecked`, record `runnerTaskProjectAuthValidation` for the launch's configuration, provider and projects, without `atSubmit`. This is the proof that `submit` and `read_file` require. - `server/src/services/native-runtime/plugin-runner-task.ts`: do not send `check_project_auth` when the prepared result has `projectAuthChecked`. - Tests: a warm attach with the flag makes only `prepare`; without it, `prepare` then `check_project_auth`. The runtime test covers all four combinations of `projectAuthCheckAtSubmit` and `projectAuthChecked`. ## Verification - `npx vitest run src/services/native-runtime/plugin-runner-task.test.ts src/__tests__/environment-task-runtime.test.ts` in `server/`: 157 passed. - Not run locally: full typecheck and full suite. CI covers them. ## Risks Low risk. Core trusts the flag the same way it trusts a plugin's `check_project_auth` answer and `projectAuthCheckAtSubmit` today. A refusal still goes through Core's own check, so the conflict error is unchanged. The plugin side ships separately and sends the flag only when its SDK accepts it. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use (shell, code search, tracing queries). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- packages/plugins/sdk/src/environment-tasks.ts | 3 ++- .../environment-task-runtime.test.ts | 12 +++++---- .../src/services/environment-task-runtime.ts | 5 ++-- .../native-runtime/plugin-runner-task.test.ts | 27 +++++++++++++++++++ .../native-runtime/plugin-runner-task.ts | 2 +- .../runner-e2e/source-sdk-public-inputs.json | 2 +- 6 files changed, 41 insertions(+), 10 deletions(-) diff --git a/packages/plugins/sdk/src/environment-tasks.ts b/packages/plugins/sdk/src/environment-tasks.ts index 0e99adb1512..e1f22476d4d 100644 --- a/packages/plugins/sdk/src/environment-tasks.ts +++ b/packages/plugins/sdk/src/environment-tasks.ts @@ -186,7 +186,8 @@ export const environmentTaskResultSchema = z.discriminatedUnion("kind", [ sha256: z.string().regex(/^[a-f0-9]{64}$/), }).strict(), z.object({ kind: z.literal("state"), taskId: providerId, state: z.record(z.string(), z.unknown()) }).strict(), - z.object({ kind: z.literal("prepared"), taskId: providerId, launch: preparedLaunch, projectAuthCheckAtSubmit: z.literal(true).optional() }).strict(), + z.object({ kind: z.literal("prepared"), taskId: providerId, launch: preparedLaunch, projectAuthCheckAtSubmit: z.literal(true).optional(), + projectAuthChecked: z.literal(true).optional() }).strict(), z.object({ kind: z.literal("credentials"), taskId: providerId, /** Null proves that cancellation fenced admission before the task could start. It must not mean an unavailable export. */ credential: environmentTaskCredentialSchema.nullable() }).strict(), z.object({ kind: z.literal("description"), taskId: providerId, diff --git a/server/src/__tests__/environment-task-runtime.test.ts b/server/src/__tests__/environment-task-runtime.test.ts index 35df7431481..968b51c38ac 100644 --- a/server/src/__tests__/environment-task-runtime.test.ts +++ b/server/src/__tests__/environment-task-runtime.test.ts @@ -344,7 +344,7 @@ describe("plugin-provided Runner execution", () => { await expect(executeEnvironmentTask(database(row(), []).db, denied as never, { companyId: "company", leaseId, operation })).rejects.toThrow("project unavailable"); expect(denied.call).not.toHaveBeenCalled(); }); - it.each([false, true])("prepares scoped configuration with submit-time auth %s", async atSubmit => { + it.each([[false, false], [true, false], [false, true], [true, true]])("prepares scoped configuration with submit-time auth %s and in-prepare auth %s", async (atSubmit, checked) => { const operation = { kind: "prepare" as const, projectIds: [projectId], requirements: { schema: "paperclip.runner.launch-requirements.v1" as const, identity: { runnerInstanceId: "runner", environmentLeaseId: leaseId, runId: "run", @@ -353,7 +353,8 @@ describe("plugin-provided Runner execution", () => { settings: {}, approvalPolicy: "on-request" as const, readOnly: false, preparedConversation: false, includeCollaborationModeInstructions: true, } }; - const result = { kind: "prepared", taskId: "attempt-1", ...(atSubmit ? {projectAuthCheckAtSubmit: true} : {}), launch: { configurationId: "configuration-1", + const result = { kind: "prepared", taskId: "attempt-1", ...(atSubmit ? {projectAuthCheckAtSubmit: true} : {}), + ...(checked ? {projectAuthChecked: true} : {}), launch: { configurationId: "configuration-1", requirementsDigest: `sha256:${"a".repeat(64)}`, provider: { kind: "codex" } } }; const workers = worker(result), store = database(); await expect(executeEnvironmentTask(store.db, workers as never, { companyId: "company", leaseId, operation })) @@ -361,9 +362,10 @@ describe("plugin-provided Runner execution", () => { expect(workers.call).toHaveBeenCalledWith("original", "environmentTask", expect.objectContaining({ companyId: "company", runId: "run", agentId: "agent", projectIds: [projectId], operation, }), 15_000); - expect(store.sets).toHaveLength(atSubmit ? 2 : 1); - if (atSubmit) expect(new PgDialect().sqlToQuery(store.sets[1].metadata as never).params).toContain(JSON.stringify({ - runnerTaskProjectAuthValidation: { configurationId: "configuration-1", provider: "openai", projectIds: [projectId], atSubmit: true }, + expect(store.sets).toHaveLength(atSubmit || checked ? 2 : 1); + if (atSubmit || checked) expect(new PgDialect().sqlToQuery(store.sets[1].metadata as never).params).toContain(JSON.stringify({ + runnerTaskProjectAuthValidation: { configurationId: "configuration-1", provider: "openai", projectIds: [projectId], + ...(checked ? {} : { atSubmit: true }) }, })); const denied = worker(result); const inactive = row(); inactive.lease.status = "released"; diff --git a/server/src/services/environment-task-runtime.ts b/server/src/services/environment-task-runtime.ts index f3582b55424..5e3b9abeb4a 100644 --- a/server/src/services/environment-task-runtime.ts +++ b/server/src/services/environment-task-runtime.ts @@ -534,12 +534,13 @@ export async function executeEnvironmentTask(db: Db, workers: Pick>'runnerTaskRetiring', 'false') != 'true'`)).returning({ id: environmentLeases.id }); if (saved.length !== 1) throw new Error("Plugin Runner project validation lease expired"); diff --git a/server/src/services/native-runtime/plugin-runner-task.test.ts b/server/src/services/native-runtime/plugin-runner-task.test.ts index ac0032bc46a..873c958eb32 100644 --- a/server/src/services/native-runtime/plugin-runner-task.test.ts +++ b/server/src/services/native-runtime/plugin-runner-task.test.ts @@ -831,6 +831,33 @@ it.each(["codex", "claude"])("reuses a warm %s process across run authorities wi expect(nextTask.mock.calls.filter(([op])=>op.kind==="stop")).toHaveLength(1); }); +it.each([ + ["checked inside prepare", true, ["prepare"]], + ["left to Core", false, ["prepare", "check_project_auth"]], +] as const)("a warm attach whose project authentication is %s makes only the round trips it needs", async (_label, checked, kinds) => { + const {task} = provider(); + ingress.connect.mockReturnValue({ready:Promise.resolve(),close:async()=>{}}); + const input = {taskId:"task",task,projectIds:[],harness:"codex",projectAuthCheckVersion:1 as const,warmTaskVersion:1 as const, + accountIdentity:"account",credentialIdentity:"revision",pollMs:1}; + const owner = createPluginRunnerTaskOwner(input); + await prepare(owner, launchRequirements("codex")); + const registration = await owner.registration({} as never,"run"); + const spec = launchSpec(); spec.nativeRunner!.lifecyclePolicy = {mode:"warm",idleTimeoutMs:300000}; + const handle = owner.launcher(spec); registration.activate(); await registration.ready(); + const originalTask=task.getMockImplementation()!; + const nextTask=vi.fn(async op=>{ + const result=await originalTask(op) as Record; + return op.kind === "prepare" && checked ? {...result,projectAuthChecked:true} : result; + }); + owner.rebind({...input,task:nextTask}); + const nextRegistration=await owner.registration({} as never,"next-run"); + const nextIdentity={...requirements.identity,runId:"next-run",turnId:"next-turn",itemId:"next-item"}; + await owner.driver.prepareLaunch!({...launchRequirements("codex"),identity:nextIdentity}); + expect(nextTask.mock.calls.map(([op])=>op.kind)).toEqual(kinds); + await registration.release(); nextRegistration.activate(); await nextRegistration.ready(); + await nextRegistration.release(); await nextRegistration.checkpoint("settled"); await handle.completion; +}); + it.each(["codex", "claude"])("adopts a verified retained %s task without submitting a replacement", async harness => { const {task}=provider(); ingress.connect.mockReturnValue({ready:Promise.resolve(),close:async()=>{}}); diff --git a/server/src/services/native-runtime/plugin-runner-task.ts b/server/src/services/native-runtime/plugin-runner-task.ts index c63dddf2d36..ba566839390 100644 --- a/server/src/services/native-runtime/plugin-runner-task.ts +++ b/server/src/services/native-runtime/plugin-runner-task.ts @@ -155,7 +155,7 @@ export function createPluginRunnerTaskOwner(input: { if (released || stopRequested) throw new Error("Plugin Runner preparation cancelled"); if (result.kind !== "prepared") throw new Error("Plugin Runner preparation unavailable"); if (input.projectAuthCheckVersion !== 1) throw new Error("Plugin Runner managed project authentication validation unavailable"); - if (launched || !result.projectAuthCheckAtSubmit) await checkProjectAuth(result.launch.configurationId); + if (!result.projectAuthChecked && (launched || !result.projectAuthCheckAtSubmit)) await checkProjectAuth(result.launch.configurationId); preparedLaunchId = result.launch.configurationId; preparedIdentity = requirements.identity; return result.launch; diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index cc252e3f1b7..26c3e22d86e 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -13,7 +13,7 @@ "packages/plugins/sdk/src/environment-stop-error.ts": "b0e03f8aa2b2170ba095da5c7138050fced3f3cb", "packages/plugins/sdk/src/environment-sync-error.ts": "7d6a51a95da49a7da4525aebbab6382dc5c44ae8", "packages/plugins/sdk/src/environment-task-error.ts": "98aae8a06743b38884b68cb9a3ec44c57b34c0e4", - "packages/plugins/sdk/src/environment-tasks.ts": "0e99adb15123cee99c979642a5d93efa48c46d09", + "packages/plugins/sdk/src/environment-tasks.ts": "e1f22476d4d73502bd4dc56afa3f863f3d1a275a", "packages/plugins/sdk/src/host-client-factory.ts": "e0301c390ea13f2340b669383f07af2455e48c8a", "packages/plugins/sdk/src/idle-drain.test.ts": "cc59f7881e7d46c89395a1d93d74f6c6b9b0a64a", "packages/plugins/sdk/src/idle-drain.ts": "ae6e4c6be4657a3d541396922b3bc551b8db557f", From f4f490270712c6f53e717d4059ccd67d4ad68398 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:15:08 -0600 Subject: [PATCH 06/12] perf(chat): read the run state of a GitHub response sweep page in one batch (#21711) 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 has two sweeps for request response comments: the acknowledgement sweep (`acknowledgement-work.ts`) and the terminal-response sweep (`terminal-response-work.ts`). Each reads pages of up to 100 requests. > - For each loaded request, both sweeps call `readGitHubResponseRun` one row at a time. That is one latest-run statement, plus the run identity context read and the message link read of `chatRunSourceMessageId`. A page of 100 requests costs about 300 statements. > - On paperclip.staging, those two provenance reads ran at about 13/s each. #21705 stops the idle backlog from being reloaded. This PR makes the reads that remain cost a constant number of statements per page. > - The per-row read also had a failure mode. A 403 from one run's provenance check aborted the acknowledgement sweep's whole page, so no request of that company was acknowledged until the 403 went away. > - This pull request adds a batched `readGitHubResponseRuns` and uses it once per page in both sweeps. > - The benefit is a constant number of statements per page, and a provenance failure that affects only its own request. ## Linked Issues or Issue Description Refs #21705 (the same sweeps; that PR stops reloading requests that cannot progress). No issue exists. This describes the problem with the fields of `.github/ISSUE_TEMPLATE/bug_report.yml`. **What happened?** On paperclip.staging (2026-11-15, about 01:45–02:25Z), `provenanceReads.context` (`select … from run_identity_contexts where id = $1 and run_id = $2 and company_id = $3 and status = $4 limit $5`) ran at 13.37/s, and `provenanceReads.link` (`select chat_conversations.issue_id, chat_endpoints.provider from chat_message_links join … where chat_message_links.company_id = $3 and comment_id = $4 …`) ran at 13.20/s. Both GitHub response sweeps reach them through `readGitHubResponseRun` → `chatRunSourceMessageId(db, run, { provider: "github" })`, once for each loaded row. `load()` costs one page read plus three statements per row. `check()` read the run state twice for each due request (before and after the acknowledgement). In the acknowledgement sweep, a 403 from `chatRunSourceMessageId` (for example, a run whose identity context is no longer accepted) threw out of `entry()` and aborted the whole page. The terminal sweep already kept such a row due, so the acknowledgement owner could revoke it. **Expected behavior** A page of requests costs a constant number of statements. A failure for one run affects only the requests of that run. **Steps to reproduce** 1. Create 120 GitHub response requests on 30 tasks. Give each task an ended run with an accepted identity context. 2. Register the terminal-response sweep. On master, the first pass costs one page read plus three statements per row. 3. Mark the requests `received`, revoke one run's identity context, and register the acknowledgement sweep. On master, the load fails with a 403, and none of the 150 requests is acknowledged. **Paperclip version or commit** master at ea8c734cb9 (includes #21705). ## What Changed - `server/src/services/chat-channels/github/response-run-state.ts`: - The latest-run subquery and the "woke for this request" check are built once, from literals (single read) or from the columns of a request row (batch read). The single read keeps the same query shape. - New `readGitHubResponseRuns(db, inputs)`. It reads the latest run of every request of a page in one statement: `unnest(…) with ordinality` and a lateral latest-run subquery, then a join to `heartbeat_runs` by id and company. It then calls the existing `chatRunSourceMessageIds(db, runs, { allowLegacyWakeComment: true, provider: "github" })` once for the page's distinct runs. That helper reuses `provenanceReads`, so the scope, status filters and joins are the same as the single check. Results map back by position. A run whose provenance check is forbidden gives `{ forbidden }` for its requests only. - `server/src/services/chat-channels/github/response-execution.ts`: `githubResponseExecution` takes an optional pre-read state. It throws a `{ forbidden }` state as the same 403 that the single read throws. - `server/src/services/chat-channels/github/terminal-response-work.ts`: `load()` reads each page's run state with one `readGitHubResponseRuns` call. `check()` reads the run state once: after the acknowledgement it reads the row only, and keeps a request that is still owed for the next check, which reads its run state again first. - `server/src/services/chat-channels/github/acknowledgement-work.ts`: the same batching. A forbidden provenance check keeps that request due, so the acknowledgement owner revokes it (`authorization_changed`), and the rest of the page continues. After an acknowledgement, a still-owed request keeps the deadline from its own row (retry time, fast-response expiry or lease). - Tests: - `terminal-response-work.test.ts`: `reads a page of waiting responses in a constant number of statements` and `acknowledges every owed request of a page when one run's requester provenance changed`. - `response-run-state.test.ts`: `reads a page of requests in one latest-run statement with the state each single read returns` compares the batch with the single read for every seeded binding and wake link. - `response-sweep-scope.test.ts`: `rebuilds parked requests once per interval for company-wide hints` counted run-state *statements* as a proxy for requests reloaded. With batching, one statement reads a whole page, so the count dropped from 6 to 2 and the test failed in CI. The behavior it guards must stay: a company-wide rebuild reloads every eligible request once per interval, and repeated hints inside the interval reload none. The test now counts the requests that each run-state read names (the length of a batched read's request arrays, or 1 for a single read). The expectations stay 6 / `[6, 0, 0, 0, 0]` / 6, so the test still proves the same rebuild behavior. No GitHub comment behavior changes. ## Verification - `pnpm vitest run src/services/chat-channels/github/terminal-response-work.test.ts` (server), staging-shaped fixtures (120 waiting requests on 30 tasks; codes null / `acknowledgement_unconfirmed` / `acknowledgement_superseded`): - before (#21705 only): the first pass costs 364 statements, with 120 run identity reads. With one revoked context, the acknowledgement sweep acknowledges 0 of 150 owed requests. The 2 new tests fail (red). - after: the first pass costs 10 statements, with 2 run identity reads (per page: page, latest runs, context, link, wait keys). All 150 owed requests are acknowledged, including the 5 whose provenance is forbidden. 8 of 8 tests pass (green). All 7 files under `chat-channels/github/`: 60 passed. `idle-completed-history.test.ts`: 75 passed. - On master before #21705, the first pass was 362 statements, and every company rebuild repeated it. - `pnpm vitest run src/services/chat-channels/github/response-run-state.test.ts`: 3 passed. - `pnpm vitest run src/__tests__/chat-channels.integration.test.ts -t "terminal|acknowledg|GitHub response|response comment|GitHub review"`: 192 passed. - `pnpm typecheck` (server): passed. - `pnpm verify` on #21705 selected 2,738 of 3,565 files (close to the full suite). I relied on the focused runs and required CI, per AGENTS.md. ## Risks - The batched latest-run statement must return the same run as the single read. The equivalence test covers native and legacy bindings, ties, other agents and other companies. - `check()` no longer reads the run state again right after an acknowledgement. A request that is still owed keeps the deadline from its own row and is read in full at its next check. The acknowledgement still revalidates everything before it writes. - A database error still rejects the whole page, as before. Only the 403 provenance decision is isolated per request. > 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 - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, local PostgreSQL tests) and extended reasoning. ## 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 --- .../github/acknowledgement-work.ts | 57 ++++++--- .../github/response-execution.ts | 9 +- .../github/response-run-state.test.ts | 14 ++- .../github/response-run-state.ts | 115 ++++++++++++++---- .../github/response-sweep-scope.test.ts | 7 +- .../github/terminal-response-work.test.ts | 44 +++++-- .../github/terminal-response-work.ts | 47 ++++--- 7 files changed, 221 insertions(+), 72 deletions(-) diff --git a/server/src/services/chat-channels/github/acknowledgement-work.ts b/server/src/services/chat-channels/github/acknowledgement-work.ts index 60e0db1cb7a..fca3560053b 100644 --- a/server/src/services/chat-channels/github/acknowledgement-work.ts +++ b/server/src/services/chat-channels/github/acknowledgement-work.ts @@ -1,4 +1,4 @@ -import { readGitHubResponseRun } from "./response-run-state.js"; +import { readGitHubResponseRuns, type GitHubResponseRunRead } from "./response-run-state.js"; import { githubRunReplyState } from "../../chat-run-publications.js"; import { and, asc, eq, gt, isNotNull, or, sql } from "drizzle-orm"; import { chatActions, chatConversations, chatEndpointLeases, chatEndpointResources, @@ -57,16 +57,34 @@ export function registerGitHubAcknowledgementWork( actionId ? eq(chatActions.id, actionId) : undefined, )).orderBy(asc(chatActions.id)).limit(100); } - async function entry(row: Awaited>[number]): Promise { - const { latestRun, ownsLatestRequest } = await readGitHubResponseRun(db, { - companyId: row.companyId, endpointId: row.endpointId, agentId: row.agentId, - issueId: row.issueId, deliveryId: row.deliveryId!, sourceMessageId: row.sourceMessageId, - }); - // Execution success alone does not decide whether a final response exists. - // Presentation/publication commits invalidate this parked request. - if (row.issueId && ownsLatestRequest && latestRun?.nativePresentationPending && - await githubRunReplyState(db, { companyId: row.companyId, endpointId: row.endpointId, - issueId: row.issueId, runId: latestRun.id }) === "none") return null; + type Row = Awaited>[number]; + async function entry(row: Row, read: GitHubResponseRunRead): Promise { + // A request whose requester provenance changed stays due, so the + // acknowledgement owner revokes it. It must not stop the rest of the page. + if (!("forbidden" in read)) { + const { latestRun, ownsLatestRequest } = read; + // Execution success alone does not decide whether a final response exists. + // Presentation/publication commits invalidate this parked request. + if (row.issueId && ownsLatestRequest && latestRun?.nativePresentationPending && + await githubRunReplyState(db, { companyId: row.companyId, endpointId: row.endpointId, + issueId: row.issueId, runId: latestRun.id }) === "none") return null; + } + return schedule(row); + } + /** The entries of a page, by position, from one batched run-state read. */ + async function entries(rows: Row[]) { + const reads = await readGitHubResponseRuns(db, rows.map(row => ({ companyId: row.companyId, endpointId: row.endpointId, + agentId: row.agentId, issueId: row.issueId, deliveryId: row.deliveryId!, sourceMessageId: row.sourceMessageId }))); + const values: Array = []; + for (const [index, row] of rows.entries()) values.push(await entry(row, reads[index]!)); + return values; + } + async function current(actionId: string) { + const [row] = await page(undefined, undefined, actionId); + return row ? (await entries([row]))[0] ?? null : null; + } + /** When the request is due, from its own row. */ + function schedule(row: Row): Entry | null { let dueAt = row.status === "failed" ? Date.parse(String(row.result?.retryAt)) : 0; if (!Number.isFinite(dueAt)) throw new Error("GitHub acknowledgement has an invalid retry deadline"); const fast = row.fast; @@ -89,23 +107,24 @@ export function registerGitHubAcknowledgementWork( (!scope.endpointId || value.endpointId === scope.endpointId) && (!scope.repositoryId || value.repositoryId === scope.repositoryId) && (!scope.number || value.number === scope.number)), load: async (scope?: Scope, signal?: AbortSignal) => { - const entries: Entry[] = []; + const loaded: Entry[] = []; let cursor: string | undefined; while (canRun() && !signal?.aborted) { const rows = await page(scope, cursor); - for (const row of rows) { const value = await entry(row); if (value) entries.push(value); } - if (rows.length < 100) return entries; + for (const value of await entries(rows)) if (value) loaded.push(value); + if (rows.length < 100) return loaded; cursor = rows[rows.length - 1].id; } throw signal?.reason ?? new Error("GitHub acknowledgement recovery stopped"); }, check: async (value: Entry, signal?: AbortSignal) => { - const [row] = await page(undefined, undefined, value.id); - const current = row ? await entry(row) : null; - if (!current || current.dueAt > Date.now() || !canRun() || signal?.aborted) return current; - await acknowledge(current.deliveryId, () => canRun() && !signal?.aborted); + const due = await current(value.id); + if (!due || due.dueAt > Date.now() || !canRun() || signal?.aborted) return due; + await acknowledge(due.deliveryId, () => canRun() && !signal?.aborted); + // A request that is still owed keeps its saved deadline. The next check + // reads its run state again before it acknowledges. const [remaining] = await page(undefined, undefined, value.id); - return remaining ? await entry(remaining) : null; + return remaining ? schedule(remaining) : null; }, }, canRun); } diff --git a/server/src/services/chat-channels/github/response-execution.ts b/server/src/services/chat-channels/github/response-execution.ts index cb9ca365a2e..2812d3311d2 100644 --- a/server/src/services/chat-channels/github/response-execution.ts +++ b/server/src/services/chat-channels/github/response-execution.ts @@ -1,6 +1,6 @@ import type { Db } from "@paperclipai/db"; import { githubRunReplyState } from "../../chat-run-publications.js"; -import { readGitHubResponseRun } from "./response-run-state.js"; +import { readGitHubResponseRun, type GitHubResponseRunRead } from "./response-run-state.js"; export { responseRunColumns as githubResponseRunColumns } from "./response-run-state.js"; export type GitHubResponseExecutionInput = { @@ -14,8 +14,11 @@ export type GitHubResponseExecutionInput = { deliveryCreatedAt: Date; }; -export async function githubResponseExecution(db: Db, input: GitHubResponseExecutionInput) { - const { latestRun, ownsLatestRequest } = await readGitHubResponseRun(db, input); +/** `read` is this request's state from a batched page read, if the caller has it. */ +export async function githubResponseExecution(db: Db, input: GitHubResponseExecutionInput, read?: GitHubResponseRunRead) { + const state = read ?? await readGitHubResponseRun(db, input); + if ("forbidden" in state) throw state.forbidden; + const { latestRun, ownsLatestRequest } = state; const requestRunning = ownsLatestRequest && latestRun?.status === "running"; const terminal = latestRun && ["succeeded", "failed", "interrupted", "timed_out", "cancelled"].includes(latestRun.status); const run = terminal && (ownsLatestRequest || input.issueStatus === "blocked") ? latestRun : null; diff --git a/server/src/services/chat-channels/github/response-run-state.test.ts b/server/src/services/chat-channels/github/response-run-state.test.ts index c59865a1466..ea409c26661 100644 --- a/server/src/services/chat-channels/github/response-run-state.test.ts +++ b/server/src/services/chat-channels/github/response-run-state.test.ts @@ -4,7 +4,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { chatMessageLinks, createDb, heartbeatRuns, type Db } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js"; import { chatRunSourceMessageId } from "../run-origin.js"; -import { readGitHubResponseRun, responseRunColumns } from "./response-run-state.js"; +import { readGitHubResponseRun, readGitHubResponseRuns, responseRunColumns } from "./response-run-state.js"; const support = await getEmbeddedPostgresTestSupport(); const suite = support.supported ? describe : describe.skip; @@ -195,6 +195,18 @@ suite("GitHub response run state", () => { .toEqual(new Set(["native", "legacy"])); }, 120_000); + it("reads a page of requests in one latest-run statement with the state each single read returns", async () => { + const all = inputs(); + const single = []; + for (const input of all) single.push(await readGitHubResponseRun(db, input)); + const statements: string[] = [], prior = db.$client.options.debug; + db.$client.options.debug = (_connection, query) => { statements.push(query); }; + let batch; + try { batch = await readGitHubResponseRuns(db, all); } finally { db.$client.options.debug = prior; } + expect(batch).toEqual(single); + expect(statements.filter(query => /from "heartbeat_runs"|join "heartbeat_runs"/.test(query))).toHaveLength(1); + }, 120_000); + it("reads a few runs of the issue, not the agent's whole run history", async () => { const tenant = tenants[0]!; const request = tenant.requests[0]!; diff --git a/server/src/services/chat-channels/github/response-run-state.ts b/server/src/services/chat-channels/github/response-run-state.ts index 8060536ddf4..0e169a4edc7 100644 --- a/server/src/services/chat-channels/github/response-run-state.ts +++ b/server/src/services/chat-channels/github/response-run-state.ts @@ -1,6 +1,7 @@ -import { and, eq, sql } from "drizzle-orm"; +import { and, eq, sql, type SQL } from "drizzle-orm"; import { chatMessageLinks, heartbeatRuns, type Db } from "@paperclipai/db"; -import { chatRunSourceMessageId } from "../run-origin.js"; +import type { HttpError } from "../../../errors.js"; +import { chatRunSourceMessageId, chatRunSourceMessageIds } from "../run-origin.js"; export const responseRunColumns = { id: heartbeatRuns.id, @@ -47,35 +48,97 @@ export const responseRunColumns = { 'wakeCommentIds', ${heartbeatRuns.contextSnapshot}->'wakeCommentIds' )`, }; -/** Shared request ownership and presentation state for delivery and recovery. */ -export async function readGitHubResponseRun(db: Db, input: { + +export type GitHubResponseRunInput = { companyId: string; endpointId: string; agentId: string; issueId: string | null; deliveryId: string; sourceMessageId: string | null; -}) { - const { issueId } = input; - if (!issueId) return { latestRun: undefined, ownsLatestRequest: false }; - const latestRunId = sql`(select latest.id from ( - (select r.id, r.created_at from ${heartbeatRuns} r - where r.company_id = ${input.companyId} and r.native_issue_id = ${issueId} and r.agent_id = ${input.agentId} - order by r.created_at desc, r.id desc limit 1) - union all - (select r.id, r.created_at from ${heartbeatRuns} r - where r.company_id = ${input.companyId} and r.native_issue_id is null - and r.context_snapshot->>'issueId' = ${issueId} and r.agent_id = ${input.agentId} - order by r.created_at desc, r.id desc limit 1) - ) latest order by latest.created_at desc, latest.id desc limit 1)`; - const wokeForRequest = sql`exists (select 1 from ${chatMessageLinks} l - where l.company_id = ${input.companyId} and l.endpoint_id = ${input.endpointId} - and l.delivery_id = ${input.deliveryId} and l.direction = 'inbound' - and (l.comment_id::text = ${heartbeatRuns.contextSnapshot}->>'wakeCommentId' - or coalesce(${heartbeatRuns.contextSnapshot}->'wakeCommentIds', '[]'::jsonb) ? l.comment_id::text))`; - const [row] = await db.select({ ...responseRunColumns, wokeForRequest }).from(heartbeatRuns) - .where(and(eq(heartbeatRuns.companyId, input.companyId), sql`${heartbeatRuns.id} = ${latestRunId}`)); +}; +type RunRow = Omit>[number], "ordinal">; +export type GitHubResponseRunState = { latestRun: Omit | undefined; ownsLatestRequest: boolean }; +/** The state of one request of a batch, or the 403 that its single read throws. */ +export type GitHubResponseRunRead = GitHubResponseRunState | { forbidden: HttpError }; + +/** A value of the run reads: a literal of one request in a single read, or a + * column of the request row in a batch read. */ +type Value = string | SQL; +type Of = Record<"companyId" | "endpointId" | "agentId" | "issueId" | "deliveryId", Value>; + +/** The assigned agent's latest run bound to the issue, where a run's issue is + * coalesce(native_issue_id, context_snapshot->>'issueId'). The two precedence + * branches are disjoint and each uses an issue index. */ +const latestRunId = (of: Of) => sql`(select latest.id from ( + (select r.id, r.created_at from ${heartbeatRuns} r + where r.company_id = ${of.companyId}::uuid and r.native_issue_id = ${of.issueId}::uuid and r.agent_id = ${of.agentId}::uuid + order by r.created_at desc, r.id desc limit 1) + union all + (select r.id, r.created_at from ${heartbeatRuns} r + where r.company_id = ${of.companyId}::uuid and r.native_issue_id is null + and r.context_snapshot->>'issueId' = ${of.issueId}::text and r.agent_id = ${of.agentId}::uuid + order by r.created_at desc, r.id desc limit 1) + ) latest order by latest.created_at desc, latest.id desc limit 1)`; +/** Whether the run woke for one of the request's inbound comments. */ +const wokeForRequest = (of: Of) => sql`exists (select 1 from ${chatMessageLinks} l + where l.company_id = ${of.companyId}::uuid and l.endpoint_id = ${of.endpointId}::uuid + and l.delivery_id = ${of.deliveryId}::uuid and l.direction = 'inbound' + and (l.comment_id::text = ${heartbeatRuns.contextSnapshot}->>'wakeCommentId' + or coalesce(${heartbeatRuns.contextSnapshot}->'wakeCommentIds', '[]'::jsonb) ? l.comment_id::text))`; + +const request = sql.identifier("github_response_request"); +const column = (name: string) => sql`${request}.${sql.identifier(name)}`; +const columns: Array<[keyof Of, string]> = [["companyId", "company_id"], ["endpointId", "endpoint_id"], + ["agentId", "agent_id"], ["issueId", "issue_id"], ["deliveryId", "delivery_id"]]; + +/** The latest run of each request, in one statement. For each request row the + * lateral subquery is the single read with the request columns in place of + * the literals. */ +async function readRunRows(db: Db, inputs: Array) { + const of = Object.fromEntries(columns.map(([key, name]) => [key, column(name)])) as Of; + return db.select({ ordinal: sql`${column("ordinal")}`.mapWith(Number), ...responseRunColumns, + wokeForRequest: wokeForRequest(of) }) + .from(sql`unnest(${sql.join(columns.map(([key]) => sql`${sql.param(inputs.map(input => input[key]))}::uuid[]`), sql`, `)}) + with ordinality as ${request}(${sql.join([...columns.map(([, name]) => sql.identifier(name)), sql.identifier("ordinal")], sql`, `)}) + cross join lateral (select ${latestRunId(of)} as id) latest_request_run`) + .innerJoin(heartbeatRuns, and(sql`${heartbeatRuns.id} = latest_request_run.id`, + sql`${heartbeatRuns.companyId} = ${column("company_id")}`)); +} + +function ownership(input: GitHubResponseRunInput, row: RunRow | undefined, originMessageId: string | null): GitHubResponseRunState { if (!row) return { latestRun: undefined, ownsLatestRequest: false }; const { wokeForRequest: requestRunIsLatest, ...latestRun } = row; - const originMessageId = latestRun.activeIdentityContextId ? await chatRunSourceMessageId(db, latestRun, - { allowLegacyWakeComment: true, provider: "github" }) : null; const ownsLatestRequest = requestRunIsLatest || (!!input.sourceMessageId && originMessageId === input.sourceMessageId); return { latestRun, ownsLatestRequest }; } + +/** Shared request ownership and presentation state for delivery and recovery. */ +export async function readGitHubResponseRun(db: Db, input: GitHubResponseRunInput): Promise { + const { issueId } = input; + if (!issueId) return { latestRun: undefined, ownsLatestRequest: false }; + const of = { ...input, issueId }; + const [row] = await db.select({ ...responseRunColumns, wokeForRequest: wokeForRequest(of) }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, input.companyId), sql`${heartbeatRuns.id} = ${latestRunId(of)}`)); + const originMessageId = row?.activeIdentityContextId ? await chatRunSourceMessageId(db, row, + { allowLegacyWakeComment: true, provider: "github" }) : null; + return ownership(input, row, originMessageId); +} + +/** `readGitHubResponseRun` for a page of requests: one latest-run read for the + * whole page, then one batched provenance check of its distinct runs, which + * reuses the single check's reads. Each request gets, by position, the state a + * separate call returns or the 403 that call throws. */ +export async function readGitHubResponseRuns(db: Db, inputs: GitHubResponseRunInput[]): Promise { + const bound = inputs.flatMap((input, index) => input.issueId ? [{ index, input: { ...input, issueId: input.issueId } }] : []); + const found = new Map(); + if (bound.length) { + for (const { ordinal, ...row } of await readRunRows(db, bound.map(entry => entry.input))) found.set(bound[ordinal - 1]!.index, row); + } + const runs = [...new Map([...found.values()].filter(row => row.activeIdentityContextId).map(row => [row.id, row])).values()]; + const checked = await chatRunSourceMessageIds(db, runs, { allowLegacyWakeComment: true, provider: "github" }); + const origins = new Map(runs.map((run, index) => [run.id, checked[index]!])); + return inputs.map((input, index) => { + const row = found.get(index); + const origin = row ? origins.get(row.id) : undefined; + if (origin && "forbidden" in origin) return { forbidden: origin.forbidden }; + return ownership(input, row, origin?.messageId ?? null); + }); +} diff --git a/server/src/services/chat-channels/github/response-sweep-scope.test.ts b/server/src/services/chat-channels/github/response-sweep-scope.test.ts index f162a1689ec..cdbd263c5fe 100644 --- a/server/src/services/chat-channels/github/response-sweep-scope.test.ts +++ b/server/src/services/chat-channels/github/response-sweep-scope.test.ts @@ -68,7 +68,12 @@ suite("GitHub response sweep scopes", () => { builder.from = ((...args: Parameters) => { const selection = from(...args), execute = selection.execute.bind(selection); selection.execute = (async () => { - if (selection.toSQL().sql.includes(`'wakeCommentIds', '[]'::jsonb) ?`)) reads += 1; + // Count requests whose run state is read. A batched read names its + // requests in arrays, so count the requests rather than statements. + const query = selection.toSQL(); + if (query.sql.includes(`'wakeCommentIds', '[]'::jsonb) ?`)) { + reads += Array.isArray(query.params[0]) ? query.params[0].length : 1; + } return execute(); }) as typeof selection.execute; return selection; diff --git a/server/src/services/chat-channels/github/terminal-response-work.test.ts b/server/src/services/chat-channels/github/terminal-response-work.test.ts index cd28076b6f2..d4b6362dcef 100644 --- a/server/src/services/chat-channels/github/terminal-response-work.test.ts +++ b/server/src/services/chat-channels/github/terminal-response-work.test.ts @@ -7,6 +7,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } fro import { createDeliveryWorkCoordinator } from "../../delivery-work-coordinator.js"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../delivery-work-notifications.js"; import { idleWorkSnapshot } from "../../task-admission.js"; +import { registerGitHubAcknowledgementWork } from "./acknowledgement-work.js"; import { registerGitHubTerminalResponseWork } from "./terminal-response-work.js"; const support = await getEmbeddedPostgresTestSupport(); @@ -40,7 +41,9 @@ describe.skipIf(!support.supported)("GitHub terminal response sweep backlog", () afterAll(async () => { await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); }); type Request = { issueId: string; deliveryId: string; actionId: string; commentId: string }; - async function seed() { + /** `waiting`: processed, non-final responses as on staging. `received`: every + * request still owes its first acknowledgement. */ + async function seed(shape: "waiting" | "received" = "waiting") { const client = db.$client; const companyId = randomUUID(), agentId = randomUUID(); await db.insert(companies).values({ id: companyId, name: "GitHub backlog", issuePrefix: `G${companyId.slice(0, 7)}` }); @@ -75,13 +78,14 @@ describe.skipIf(!support.supported)("GitHub terminal response sweep backlog", () const latest = request === STALE_PER_ISSUE; const [action] = await db.insert(chatActions).values({ companyId, endpointId: endpoint, conversationId: conversation, deliveryId: delivery, kind: "github_response_comment", providerActionId: `github_response:${delivery}`, - payload: { agentId }, status: "processed", - result: { id: String(1_000 + index), url: `https://github.com/paperclipai/paperclip/pull/${issueNumber}#c${index}`, + payload: { agentId }, status: shape === "received" ? "received" : "processed", + result: shape === "received" ? null : { id: String(1_000 + index), + url: `https://github.com/paperclipai/paperclip/pull/${issueNumber}#c${index}`, final: latest, versionAt: new Date(base).toISOString(), ...(latest ? {} : { code: code(index) }) }, updatedAt: new Date(base + index * 60_000) }).returning(); requests.push({ issueId: issue, deliveryId: delivery, actionId: action!.id, commentId: comment }); } - stale.push(...requests.slice(0, STALE_PER_ISSUE)); + stale.push(...(shape === "received" ? requests : requests.slice(0, STALE_PER_ISSUE))); // The latest run answered the newest request, through its identity context. const runId = randomUUID(), contextId = randomUUID(); await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issue, issueId: issue, @@ -95,13 +99,14 @@ describe.skipIf(!support.supported)("GitHub terminal response sweep backlog", () return { companyId, agentId, endpointId: endpoint as string, stale, runs }; } - async function start() { + async function start(register: typeof registerGitHubTerminalResponseWork = registerGitHubTerminalResponseWork) { coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true, onError: error => errors.push(error) }); - const worker = registerGitHubTerminalResponseWork(db, coordinator, async deliveryId => { + const worker = register(db, coordinator, async deliveryId => { acknowledged.push(deliveryId); // Stand in for the real acknowledgement, which records a final response. - await db.update(chatActions).set({ result: sql`${chatActions.result} || '{"final": true}'::jsonb`, updatedAt: new Date() }) + await db.update(chatActions).set({ status: "processed", updatedAt: new Date(), + result: sql`coalesce(${chatActions.result}, '{}'::jsonb) || '{"final": true}'::jsonb` }) .where(and(eq(chatActions.deliveryId, deliveryId), eq(chatActions.kind, "github_response_comment"))); }, () => true); await worker.ready; @@ -150,6 +155,31 @@ describe.skipIf(!support.supported)("GitHub terminal response sweep backlog", () expect(await finals(f.stale.map(request => request.actionId))).toBe(0); }, 300_000); + it("reads a page of waiting responses in a constant number of statements", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + await seed(); + const first = await observe(async () => { await start(); await advance(5_000); }); + console.info(`terminal response sweep, first pass: ${first.statements} statements ` + + `(${first.provenance} run identity reads) for ${STALE} rows in 2 pages`); + expect(acknowledged).toEqual([]); + // Per page: the page, its latest runs, the batched context and link reads, and the wait keys. + expect(first.provenance).toBeLessThanOrEqual(2); + expect(first.statements).toBeLessThanOrEqual(2 * 5); + }, 300_000); + + it("acknowledges every owed request of a page when one run's requester provenance changed", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); + const f = await seed("received"); + // One task's latest run lost its accepted identity context, so reading its + // requester provenance is forbidden. Only that task's requests are affected. + await db.update(runIdentityContexts).set({ status: "revoked" }).where(eq(runIdentityContexts.runId, f.runs[3]!.runId)); + const first = await observe(async () => { await start(registerGitHubAcknowledgementWork); await advance(30_000); }); + console.info(`acknowledgement sweep: ${first.statements} statements (${first.provenance} run identity reads) ` + + `for ${f.stale.length} owed requests`); + expect(new Set(acknowledged)).toEqual(new Set(f.stale.map(request => request.deliveryId))); + expect(acknowledged).toHaveLength(f.stale.length); + }, 300_000); + it("still settles a waiting response once a run that owns it ends", async () => { vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true }); const f = await seed(); diff --git a/server/src/services/chat-channels/github/terminal-response-work.ts b/server/src/services/chat-channels/github/terminal-response-work.ts index 49c8447c25a..fdbb18d8ef5 100644 --- a/server/src/services/chat-channels/github/terminal-response-work.ts +++ b/server/src/services/chat-channels/github/terminal-response-work.ts @@ -5,6 +5,7 @@ import type { createDeliveryWorkCoordinator } from "../../delivery-work-coordina import { DELIVERY_QUEUES } from "../../delivery-work-notifications.js"; import { registerScopedDeadlineWork } from "../../scoped-deadline-work.js"; import { githubResponseExecution } from "./response-execution.js"; +import { readGitHubResponseRuns, type GitHubResponseRunRead } from "./response-run-state.js"; import { githubResponseReconstructionIntervalMs, type GitHubResponseSweepScope as Scope } from "./response-sweep-scope.js"; import { HttpError } from "../../../errors.js"; type Entry = { id: string; companyId: string; endpointId: string; deliveryId: string; @@ -87,12 +88,9 @@ export function registerGitHubTerminalResponseWork( * recorded. A wait on the owning run's reply or presentation is never * recorded: a publication that commits it changes no wait-key input, and a * restart can lose the hint that its lease release sends. */ - async function entry(row: Row): Promise { - const pending: Entry = { id: row.id, companyId: row.companyId, endpointId: row.endpointId, deliveryId: row.deliveryId!, - issueId: row.issueId, conversationId: row.conversationId, repositoryId: row.repositoryId, - number: row.number ? Number(row.number) : null, dueAt: row.leaseExpiresAt ? Date.parse(row.leaseExpiresAt) : 0 }; + async function entry(row: Row, read: GitHubResponseRunRead): Promise { try { - const execution = await githubResponseExecution(db, { ...row, agentId: row.agentId!, deliveryId: row.deliveryId! }); + const execution = await githubResponseExecution(db, { ...row, agentId: row.agentId!, deliveryId: row.deliveryId! }, read); if (execution.body === undefined || execution.reply === "unsettled" || (execution.paused && row.result?.pausedVersion === execution.version)) return { parkable: !execution.presentationPending && execution.reply === "none" }; @@ -101,7 +99,24 @@ export function registerGitHubTerminalResponseWork( // Keep this request eligible for the acknowledgement owner's authority // check and cancellation; it must not poison discovery for other requests. } - return pending; + return pending(row); + } + /** The request's entry, before its run state is read. */ + function pending(row: Row): Entry { + return { id: row.id, companyId: row.companyId, endpointId: row.endpointId, deliveryId: row.deliveryId!, + issueId: row.issueId, conversationId: row.conversationId, repositoryId: row.repositoryId, + number: row.number ? Number(row.number) : null, dueAt: row.leaseExpiresAt ? Date.parse(row.leaseExpiresAt) : 0 }; + } + /** The entries of a page, by position, from one batched run-state read. */ + async function entries(rows: Row[], signal?: AbortSignal) { + const reads = await readGitHubResponseRuns(db, rows.map(row => ({ companyId: row.companyId, endpointId: row.endpointId, + agentId: row.agentId!, issueId: row.issueId, deliveryId: row.deliveryId!, sourceMessageId: row.sourceMessageId }))); + const values: Array>> = []; + for (const [index, row] of rows.entries()) { + if (!canRun() || signal?.aborted) throw signal?.reason ?? new Error("GitHub terminal-response recovery stopped"); + values.push(await entry(row, reads[index]!)); + } + return values; } /** Record the wait of requests that cannot progress yet. A request whose row * changed after the read gets no key and is read again. The write leaves @@ -119,8 +134,8 @@ export function registerGitHubTerminalResponseWork( async function current(actionId: string) { const [row] = await page(undefined, undefined, actionId); if (!row) return null; - const value = await entry(row); - if (!("parkable" in value)) return value; + const [value] = await entries([row]); + if (!("parkable" in value!)) return value!; if (value.parkable) await park([row]); return null; } @@ -135,18 +150,17 @@ export function registerGitHubTerminalResponseWork( (!scope.endpointId || value.endpointId === scope.endpointId) && (!scope.repositoryId || value.repositoryId === scope.repositoryId) && (!scope.number || value.number === scope.number)), load: async (scope?: Scope, signal?: AbortSignal) => { - const entries: Entry[] = []; + const loaded: Entry[] = []; let cursor: string | undefined; while (canRun() && !signal?.aborted) { const rows = await page(scope, cursor); + const values = await entries(rows, signal); const waiting: Row[] = []; - for (const row of rows) { - if (!canRun() || signal?.aborted) throw signal?.reason ?? new Error("GitHub terminal-response recovery stopped"); - const value = await entry(row); - if (!("parkable" in value)) entries.push(value); else if (value.parkable) waiting.push(row); + for (const [index, value] of values.entries()) { + if (!("parkable" in value)) loaded.push(value); else if (value.parkable) waiting.push(rows[index]!); } await park(waiting); - if (rows.length < 100) return entries; + if (rows.length < 100) return loaded; cursor = rows[rows.length - 1].id; } throw signal?.reason ?? new Error("GitHub terminal-response recovery stopped"); @@ -155,7 +169,10 @@ export function registerGitHubTerminalResponseWork( const due = await current(value.id); if (!due || due.dueAt > Date.now() || !canRun() || signal?.aborted) return due; await acknowledge(due.deliveryId, () => canRun() && !signal?.aborted); - return current(value.id); + // Keep a request that still waits for the next check, which reads its + // run state again before it acknowledges. One check reads it once. + const [remaining] = await page(undefined, undefined, value.id); + return remaining ? pending(remaining) : null; }, }, canRun); } From 30c4d2f4a130a457186b38fd414c0e6b2e9f11ce Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Sat, 14 Nov 2026 21:42:06 -0600 Subject: [PATCH 07/12] perf(server): read the issue detail with fewer database statements (#21713) 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 UI loads the task page through `GET /api/issues/:id`, and the server runs all requests on one Node main thread > - A CPU profile of the server shows that the cost is per database statement: SQL building, parameter encoding, result parsing and one socket write each > - The issue detail read sent 73 statements for a task with two ancestors, one blocker and a project mention > - Several of those statements read the issue row again, only to get values that the route already loaded > - This pull request passes the loaded issue to those reads, walks the ancestor chain in one query, and skips reads whose result the response does not use > - The benefit is 9 fewer statements on each task page load (73 to 64), plus one fewer statement for each extra ancestor level, with a byte-identical response ## Linked Issues or Issue Description **What existing behavior does this improve?** `GET /api/issues/:id` reads the same issue row several times in one request, and walks the ancestor chain with one statement for each level. **Subsystem affected** Server: issue routes and the issue, issue reference and project services. **Current behavior** The route loads the issue, then `getRelationSummaries`, `getCurrentScheduledRetry`, `findMentionedProjectIds`, `listIssueReferenceSummary` and `getAncestors` each read the issue row again. `getAncestors` sends one statement for each ancestor. The inbox archive fields read two activity aggregates even when the issue has no archive row. The project embed reads the workspace provider catalog, but the compact embed does not return it. The test fixture request sends 73 statements. **Proposed behavior** The route passes the values it already has. The ancestor walk is one recursive query. The activity aggregates run only when an archive row exists. The project embed skips the provider catalog. The same fixture request sends 64 statements, and the JSON response is the same. **Reason and benefit** Fewer statements per request means less CPU on the main thread for every open task page. **Breaking changes** None. Other callers of the changed service functions keep the old behavior, because the new arguments are optional. ## What Changed - `issueService.getRelationSummaries` and `getCurrentScheduledRetry` accept an optional known `companyId` and then skip the issue read. - `issueService.findMentionedProjectIds` accepts the loaded issue (`companyId`, `title`, `description`). - `issueService.getAncestors` accepts the known `parentId` and walks the chain in one recursive query. It keeps the order (nearest first), the limit of 50, and the stop at a cycle or at a task that is its own parent. - `issueService.getActiveInboxArchiveFields` reads the archive row first and reads the activity aggregates only when an archive row exists. - `issueReferenceService.listIssueReferenceSummary` accepts an optional known `companyId`. - `issueThreadInteractionService.listForIssue` accepts the loaded issue (`status`, `companyId`, `executionWorkspaceId`). `GET /api/issues/:id/interactions`, which the board polls, passes it (11 to 10 statements). - `projectService.getById` accepts `{ workspaceProvider: false }`. The issue detail route uses it, because `compactIssueProject` never returns `workspaceProvider`. - Test helpers: `createStatementCensus` (statements per request, grouped by statement shape with the server callers), and a board route fixture with the real session actor middleware. `meterDatabaseStatements` can record a call stack for each statement. - New tests: `issue-detail-statements.test.ts` (statement budget, byte-identical normalized JSON against a fixture file, access rules, membership removal on the next request, ancestor walk with a cycle) plus an interactions poll test, and `board-route-statement-census.test.ts` (census of the polled and page-load board routes). ## Verification - Red: before the change, the fixture request sent 73 statements, and the budget test failed (`expected 73 to be less than or equal to 64`). - Green: after the change, the request sends 64 statements. The normalized JSON is byte-identical to the fixture file that I wrote before the change. - Access: another company's user gets 404, a missing issue gets 404, an anonymous request gets 404, a hidden issue stays readable for a member, and a removed membership gets 404 on the very next request. - `pnpm exec vitest run` on `issue-detail-statements`, `board-route-statement-census`, `issues-goal-context-routes`, `issues-service`, `issue-references-service`, `inbox-archive-routes`, `heartbeat-task-context`, `project-workspace-provider.integration`, `workspace-provider-failure`, `issue-telemetry-routes`, `issue-thread-interaction-routes`, `issue-document-restore-routes`, `heartbeat-referenced-projects`, `project-environments`: 14 files, 414 tests pass. - `pnpm --filter @paperclipai/server typecheck` passes. - Interactions: the polled route sends 10 statements instead of 11, with a response equal to the service result without the known issue. - Census: `PAPERCLIP_STATEMENT_CENSUS=/tmp/census.txt pnpm exec vitest run src/__tests__/board-route-statement-census.test.ts` writes statements per request and the top statement shapes for each board route. ## Risks - Low risk. The new arguments are optional, so other callers keep the old reads. - When the route passes a known `companyId`, a concurrent delete of the issue no longer gives a 404 from these sub-reads. The route already loaded and authorized the issue in the same request, so the response is the same in practice. - The JSON fixture file fails when someone changes the issue detail response. Regenerate it with `PAPERCLIP_WRITE_ISSUE_DETAIL_GOLDEN=1` and review the diff. > 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 - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file edits, 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 --- .../board-route-statement-census.test.ts | 29 ++ .../fixtures/issue-detail-response.json | 280 ++++++++++++++++++ .../helpers/database-statement-meter.ts | 13 +- .../__tests__/helpers/route-census-fixture.ts | 87 ++++++ .../src/__tests__/helpers/statement-census.ts | 72 +++++ .../__tests__/issue-detail-statements.test.ts | 142 +++++++++ .../issue-thread-interaction-routes.test.ts | 2 +- .../issues-goal-context-routes.test.ts | 2 +- server/src/routes/issues.ts | 18 +- server/src/services/issue-references.ts | 8 +- .../src/services/issue-thread-interactions.ts | 7 +- server/src/services/issues.ts | 110 ++++--- server/src/services/projects.ts | 23 +- 13 files changed, 721 insertions(+), 72 deletions(-) create mode 100644 server/src/__tests__/board-route-statement-census.test.ts create mode 100644 server/src/__tests__/fixtures/issue-detail-response.json create mode 100644 server/src/__tests__/helpers/route-census-fixture.ts create mode 100644 server/src/__tests__/helpers/statement-census.ts create mode 100644 server/src/__tests__/issue-detail-statements.test.ts diff --git a/server/src/__tests__/board-route-statement-census.test.ts b/server/src/__tests__/board-route-statement-census.test.ts new file mode 100644 index 00000000000..e2c8d58bf28 --- /dev/null +++ b/server/src/__tests__/board-route-statement-census.test.ts @@ -0,0 +1,29 @@ +import { writeFileSync } from "node:fs"; +import request from "supertest"; +import { expect, it } from "vitest"; +import { boardCensusRoutes, boardSessionApp, seedBoardRouteFixture } from "./helpers/route-census-fixture.js"; +import { describeEmbeddedPostgres, useEmbeddedPostgres } from "./helpers/route-test-harness.js"; +import { createStatementCensus, formatStatementCensus } from "./helpers/statement-census.js"; + +describeEmbeddedPostgres("board route statement census", () => { + const ctx = useEmbeddedPostgres("board-route-census-"); + + it("answers every polled and page-load board route and reports statements per request", async () => { + const census = createStatementCensus(ctx.db); + try { + const fixture = await seedBoardRouteFixture(ctx.db, "Census"); + const app = boardSessionApp(ctx.db, () => fixture.userId); + const report: string[] = []; + for (const [label, path] of boardCensusRoutes(fixture)) { + const warm = await request(app).get(path); + expect(warm.status, `${label}: ${JSON.stringify(warm.body)}`).toBe(200); + const measured = await census.measure(() => request(app).get(path).expect(200), { stacks: true }); + expect(measured.statements, label).toBeGreaterThan(0); + report.push(formatStatementCensus(label, measured, Number(process.env.PAPERCLIP_STATEMENT_CENSUS_TOP ?? 5))); + } + if (process.env.PAPERCLIP_STATEMENT_CENSUS) writeFileSync(process.env.PAPERCLIP_STATEMENT_CENSUS, `${report.join("\n\n")}\n`); + } finally { + census.uninstall(); + } + }, 120_000); +}); diff --git a/server/src/__tests__/fixtures/issue-detail-response.json b/server/src/__tests__/fixtures/issue-detail-response.json new file mode 100644 index 00000000000..e1d98dc1f95 --- /dev/null +++ b/server/src/__tests__/fixtures/issue-detail-response.json @@ -0,0 +1,280 @@ +{ + "id": "", + "companyId": "", + "conversationAgentId": null, + "conversationUserId": null, + "conversationState": null, + "conversationSessionGeneration": 0, + "conversationBoundaryCommentId": null, + "projectId": "", + "projectWorkspaceId": null, + "goalId": null, + "parentId": "", + "visibility": "open", + "privacyRootIssueId": null, + "privacyParentIssueId": null, + "title": "Detail task", + "titleNeedsGeneration": false, + "description": "Uses [@Detail project](project://)", + "status": "in_progress", + "statusVersion": 0, + "lastStatusDecisionId": null, + "workMode": "standard", + "harnessKind": null, + "priority": "high", + "reviewPolicy": null, + "assigneeAgentId": "", + "assigneeUserId": null, + "checkoutRunId": null, + "executionRunId": null, + "executionAgentNameKey": null, + "executionLockedAt": null, + "createdByAgentId": null, + "createdByUserId": "", + "responsibleUserId": null, + "issueNumber": null, + "identifier": null, + "originKind": "manual", + "originId": null, + "originRunId": null, + "originIssueId": null, + "originIdentityContextId": null, + "continuationIdentityContextId": null, + "originFingerprint": "default", + "requestDepth": 0, + "billingCode": null, + "assigneeAdapterOverrides": null, + "executionPolicy": null, + "executionState": null, + "monitorNextCheckAt": null, + "monitorWakeRequestedAt": null, + "monitorLastTriggeredAt": null, + "monitorAttemptCount": 0, + "monitorNotes": null, + "monitorScheduledBy": null, + "executionWorkspaceId": null, + "workspaceBindingRevision": 0, + "workspaceSelection": null, + "workspacePendingSelection": null, + "executionWorkspacePreference": null, + "executionWorkspaceSettings": null, + "sourceTrust": null, + "unblockDescriptor": null, + "blockedTransitionAt": null, + "blockedOwnerNotifiedAt": null, + "startedAt": null, + "completedAt": null, + "cancelledAt": null, + "hiddenAt": null, + "createdAt": "