From 623f1dc289a14a699ebbe3f09b94179d38fc2ae2 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:36:28 -0500 Subject: [PATCH 1/3] fix(server): schedule secret-proposal expiry from committed changes (#17446) 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. > - Agents can propose secrets and bindings for approval. > - Pending proposals already contain their expiry and encrypted value. > - The server scans for expired proposals on every maintenance tick, even when none exist. > - Committed proposal changes and saved expiry times provide the required triggers. > - This PR uses those triggers and preserves scrubbing, approval checks, and recovery. > - Empty and completed proposal history no longer causes recurring expiry queries. ## Linked Issues or Issue Description Refs #17443. This is the second PR in the sleep migration stack and targets its branch. **What problem does this solve?** The periodic proposal scan contacts PostgreSQL when no proposal needs maintenance. That obstructs idle database behavior across tenant instances. **What is the proposed solution?** Use transaction-aware notifications for creation and resolution. Reconstruct the earliest pending expiry at startup. Run cleanup at that deadline, or retry while reconciliation remains unfinished. **Why is this useful?** It removes an idle scan while retaining security checks and physical ciphertext cleanup. No queue table or migration is required. ## What Changed - Added intent notifications before secret/binding creation, approval, terminal transitions, and linked interaction resolution. The existing outer transaction owns settlement. - Kept expiry selection, ciphertext scrubbing, dependent rejection, and authorization in the secret-proposal service. - Registered a startup and deadline worker in place of the aggregate maintenance sweep. Empty/terminal states disarm; overdue batches and failures retain retries. - Reused shared scoped deadline dispatch for secret expiry. The service owns company-filtered SQL and expiry policy. Custom-image expiry continues to use `registerDeadlineWork`. - Added real PostgreSQL producer, outer-transaction, concurrent-write, expiry, restart, interaction resolution, and drain/resume tests. Updated startup wiring fixtures and documented the supported writer/lifecycle contract. ## Verification - Landing reconciliation at `c10eb1bcf752b058713e05d3345e5cf38dd3fa72`: 160 tests pass across the complete secret-proposal, scoped deadline, company batch, coordinator, startup, custom-image service and custom-image worker suites; no cases skipped in the accepted runs. Server typecheck passes. This integrates master after #17443 landed; fresh remote CI and Ponytail review are required before merge. Current head: `5bbe17ad9ebc4573b08ed1a9323644ef9608ca09`. This remains a single-duty PR stacked on #17443. - Integrated pinned master `8548173fc9efdc0fa07644fb92dcc0b6851a95e5` with normal merges. Every branch passed generated-schema checks and its target-branch migration-order gate. Existing SQL is unchanged; the 25 stack migrations follow master’s new migration. - Duty-specific producer coverage, lifecycle tests, and earlier failure records: [2026-10-08-instance-sleep-and-scheduler-inventory.md](https://github.com/paperclipai/paperclip/blob/5bbe17ad9ebc4573b08ed1a9323644ef9608ca09/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md), [2026-10-24-recurring-server-sleep-stack.md](https://github.com/paperclipai/paperclip/blob/5bbe17ad9ebc4573b08ed1a9323644ef9608ca09/doc/plans/2026-10-24-recurring-server-sleep-stack.md). - Combined tip `51e6cbe67979b55b340ea9f0f434c5b5c682ccd6`: **355 startup/cancellation/recovery/dispatch/preservation tests**, **75 connection-management tests**, and production server typechecking pass. These combined checks do not mean every intermediate PR independently ran the full repository suite. - Real master-to-stack database upgrade passes: **379 unchanged prior migration receipts plus 25 new migrations**, with the gateway responsibility fixture preserved. - Owning-branch checks: 84 runner installation/settlement cases plus runner typechecking and generated TypeScript/Rust profile agreement; 253 GitHub review workflow cases. Stop-attribution and held-worker readiness regressions failed before their fixes. - Failure accounting: the initial combined run passed 349 cases and failed six idle assertions in a reused preservation database containing old cancelled runs. Repeating the combined command with a fresh preservation database passed. Earlier invalid project selection, merge import/type errors, and the interrupted full local suite are not counted as passing checks. - **Latest-head CI and review remain required.** Prior CI findings include GitHub idle observation, route teardown, attention cleanup, touch-picker E2E, workspace health, and voice-cleanup timing; local passes do not erase those failures. No full local repository-suite, deployed sleep, fleet cost, or live Copilot qualification claim is made. ## Risks - Notifications cover supported writers sharing the database signal owner. Independent SQL writers and other process roots require a separate ingress contract; startup recovery alone is not live replica support. - The shared coordinator and scoped worker also serve later stack duties. Their defaults remain intact; existing voice, chat, native, and startup consumers are included in integrated verification. - Startup now checks overdue proposals immediately. During drain, physical cleanup waits; approval still rejects expired proposals synchronously. - Each due company pass remains bounded to 100 rows. Failed scopes back off from 30 seconds to five minutes; healthy overdue work keeps draining. Self-generated write hints coalesce and do not erase a failed sweep's backoff. - Heartbeat-disabled behavior and Cloud sleep-safety gates remain unchanged. This does not establish deployed suspension or external wake coverage. Tool review and gateway token cleanup remain separate slices. ## Model Used OpenAI Codex, GPT-6 family, with reasoning and code execution. The exact serving model identifier and context window were not exposed. ## 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 --------- Co-authored-by: Paperclip --- doc/idle-secret-proposal-expiry.md | 90 +++++ ...-instance-sleep-and-scheduler-inventory.md | 6 +- ...2026-10-24-recurring-server-sleep-stack.md | 4 +- .../src/__tests__/company-work-batch.test.ts | 29 ++ .../delivery-work-coordinator.test.ts | 52 +++ .../__tests__/scoped-deadline-work.test.ts | 39 +++ .../__tests__/secret-proposals-routes.test.ts | 314 +++++++++++++++++- .../server-startup-feedback-export.test.ts | 25 +- server/src/index.ts | 11 +- server/src/services/company-deletion.ts | 1 + server/src/services/company-work-batch.ts | 28 ++ .../src/services/custom-image-cleanup-work.ts | 21 +- server/src/services/deadline-work.ts | 36 ++ .../src/services/delivery-work-coordinator.ts | 16 +- .../services/delivery-work-notifications.ts | 1 + .../src/services/issue-thread-interactions.ts | 2 + server/src/services/scoped-deadline-work.ts | 99 ++++++ .../services/secret-proposal-expiry-work.ts | 29 ++ server/src/services/secret-proposals.ts | 30 +- 19 files changed, 792 insertions(+), 41 deletions(-) create mode 100644 doc/idle-secret-proposal-expiry.md create mode 100644 server/src/__tests__/company-work-batch.test.ts create mode 100644 server/src/__tests__/scoped-deadline-work.test.ts create mode 100644 server/src/services/company-work-batch.ts create mode 100644 server/src/services/deadline-work.ts create mode 100644 server/src/services/scoped-deadline-work.ts create mode 100644 server/src/services/secret-proposal-expiry-work.ts diff --git a/doc/idle-secret-proposal-expiry.md b/doc/idle-secret-proposal-expiry.md new file mode 100644 index 00000000000..a66747421fb --- /dev/null +++ b/doc/idle-secret-proposal-expiry.md @@ -0,0 +1,90 @@ +# Secret-proposal expiry and idle behavior + +Secret proposals already store `status`, `expiresAt`, and encrypted pending +values. This worker uses those records; it adds no queue table or migration. + +## Ownership and activation + +`secret-proposals.ts` still owns quotas, authority checks, approval, expiry, +ciphertext scrubbing, dependent binding rejection, audit records, and interaction +reflection. `expiryDeadlines(companyId?)` returns one saved deadline per pending +company. Normal write notifications reload only the affected company. Startup +reconstruction loads all companies once. The manual `nextExpiryAt()` query remains +available to existing callers. +Terminal history does not create a deadline. Approval still rejects an expired +proposal synchronously, even when maintenance is paused. + +The supported producers register `secretProposalExpiry` intent before their +writes in the owning transaction: + +- `createWithinQuota`: both secret and binding creation, after quota admission. +- `markApproved`: ordinary approval and prerequisite approval during a cascade. +- `transition`: rejection, withdrawal, expiry, and dependent binding rejection. +- Interaction resolution: rejection, withdrawal/cancellation, expiry, and failed + acceptance execution that resolves a linked pending binding. +- Company deletion: a company hint removes its cached deadline after deletion commits. + +Each producer includes its company ID. The remaining proposal write only attaches +an interaction ID and does not change expiry eligibility. Independent SQL writers +or another DB root are not supported live producers of these process-local signals; +startup reconstructs their persisted rows, but it is not a live replica contract. + +The shared database signal boundary defers notification until the outer transaction +settles. Nested savepoints, rollback, and uncertain commit outcomes retain the +existing protocol. Callers do not pass recovery counters or reconnect the database. + +## Scheduling and lifecycle + +`registerSecretProposalExpiryWork` runs once at startup while heartbeat scheduling +is enabled. It replaces the secret-proposal sweep in the aggregate maintenance +tick. Disabled heartbeat scheduling keeps its existing behavior. + +The worker reloads the affected company's saved minimum expiry after a committed +change. It does not sweep future work. At a due deadline it sweeps at most 100 +expired proposals for that company, then reads that company's next deadline. +Companies rotate fairly between bounded passes. Retained history creates no work. +No pending proposal, unresolved write, or failed reconciliation means no recurring +query. Unscoped legacy hints still reconstruct all companies. + +`scoped-deadline-work.ts` owns scope invalidation, cached deadlines, fair dispatch, +and failure backoff. It owns no SQL or proposal policy. Failed loads and failed +company sweeps back off independently from 30 seconds to five minutes. A new +write reloads that company without erasing its failed sweep's backoff. Other +companies keep their own deadlines, including already-due work. The coordinator's +optional `nextRunAtOnError` contract permits immediate eligible work only after +the worker has recorded per-item backoffs. Failed transaction reconciliation and +failed pending-state inspection retain the coordinator's normal retry. + +Secret expiry opts out of the shared helper's default one-second pass spacing so +newly learned short deadlines are not clamped. Other scoped consumers retain that +default. Custom-image expiry continues to use `deadline-work.ts` unchanged. No +shared scheduler or startup wiring interprets secret-proposal policy. + +A request stays pending until reconciliation succeeds. Changes arriving during a +pass, first writes during drain, and failures followed by drain retain a request. +Passive drain performs no proposal SQL. Resume reconciles retained requests; +restart reconstructs deadlines. Coordinator shutdown unsubscribes and waits for +active work. Deferred physical cleanup does not extend approval authorization. + +## Verification and limits + +The PostgreSQL route suite exercises actual service producers, nested outer commit +and rollback, quiet empty and terminal states, quiet future deadlines, automatic +ciphertext scrubbing and dependent-card resolution, startup reconstruction, +withdrawal, interaction rejection/failed execution, failure retry, and drain/resume. +It also verifies that expired approval fails while cleanup is paused. The existing +coordinator suite verifies fallback retry and uncertainty boundaries. New cases +record actual SQL to prove normal writes and due expiry stay company-scoped; they +also cover five-second deadlines, earlier replacement deadlines, company deletion, +and another company making progress while one sweep fails. A deterministic +shared-worker test covers a 250ms replacement deadline. + +The worker tests use a controlled clock and a real PostgreSQL database. Existing +route tests cover quotas, isolation, authorization, concurrency, and lifecycle +semantics. The test-only database URL must refer to a disposable migrated database: +the suite deletes its fixture tables. Ordinary CI uses its isolated embedded DB. + +This is worker quiet, not proof of host or database suspension. No Cloud alarm or +sleep-eligibility exemption is added. Existing sleep-safety checks remain in force; +a local expiry timer cannot wake a stopped host. Tool review expiry and gateway +session cleanup are separate migrations. diff --git a/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md b/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md index b92d7520ec0..9141878caa8 100644 --- a/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md +++ b/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md @@ -647,8 +647,10 @@ Longer polling intervals alone do not complete an item. visible within the agreed freshness contract. Source: [index.ts](../../server/src/index.ts), `tools.sweepConnectionHealth`. -- [ ] **JOB-21 — Secret proposals and expired action tokens.** Current: **30s** - expiry/cleanup queries. Change: enforce expiry synchronously on use and +- [ ] **JOB-21 — Secret proposals and expired action tokens (partially migrated).** + Secret-proposal expiry now uses transaction signals and saved expiry deadlines; + see [the lifecycle contract](../idle-secret-proposal-expiry.md). Tool review + recovery and gateway token cleanup still use **30s** queries. Change: enforce expiry synchronously on use and register required scrub/cleanup deadlines. **Complete when:** idle cleanup does not extend authorization or secret-retention periods. Sources: [secret-proposals.ts](../../server/src/services/secret-proposals.ts), diff --git a/doc/plans/2026-10-24-recurring-server-sleep-stack.md b/doc/plans/2026-10-24-recurring-server-sleep-stack.md index 50f73222265..20221274e70 100644 --- a/doc/plans/2026-10-24-recurring-server-sleep-stack.md +++ b/doc/plans/2026-10-24-recurring-server-sleep-stack.md @@ -12,13 +12,13 @@ Do not mark an item done from a timer removal or a green check alone. | ID | Original checklist duty | Required slices / disposition | PR / evidence | | --- | --- | --- | --- | -| 01 | Custom-image setup expiry | Session writes, existing expiry, startup/retry/drain | In progress | +| 01 | Custom-image setup expiry | Session writes, existing expiry, startup/retry/drain | [#17443](https://github.com/paperclipai/paperclip/pull/17443), merged after CI and passing reviews | | 02 | Remaining chat maintenance | Provider runtime discovery; voice reconciliation; milestones; wake notices; interaction continuations; terminal confirmations; GitHub recovery; Teams maintenance, separately by owner | Pending | | 03 | Run and task recovery | Orphan runs and active leases; shutdown workspace settlement; scheduled retries; queued runs; stranded assignments; resolved dependencies; task watchdogs; silent-run monitoring; stale locks | Pending | | 04 | Decision retention and notifications | Retention deadlines and notification delivery are separate reasons | Pending | | 05 | Decision expiry and interrupted effects | Expiry, effect recovery, continuation recovery | Pending | | 06 | Tool connection health | Configuration/use activation and defined proactive health deadlines | Pending | -| 07 | Secret proposals, tool reviews, gateway tokens | Separate expiry/scrub/recovery owners | Pending | +| 07 | Secret proposals, tool reviews, gateway tokens | Separate expiry/scrub/recovery owners | Secret-proposal expiry in progress; tool reviews and gateway tokens pending | | 08 | GitHub connection events and continuity | Event discovery/replay and credential continuity separately | Pending | | 09 | Merged-PR confirmations | Candidate writes, webhook activation where supported, outstanding-candidate fallback | Pending | | 10 | External-object refresh | Configuration changes, refresh deadlines, source events | Pending | diff --git a/server/src/__tests__/company-work-batch.test.ts b/server/src/__tests__/company-work-batch.test.ts new file mode 100644 index 00000000000..9fe1abc5a1d --- /dev/null +++ b/server/src/__tests__/company-work-batch.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest"; +import { takeCompanyWorkBatch } from "../services/company-work-batch.js"; + +describe("company work batch", () => { + it("shares capacity while preserving the owner's order within each company", () => { + const entries = [ + { companyId: "a", id: "a-oldest" }, { companyId: "a", id: "a-next" }, + { companyId: "a", id: "a-later" }, { companyId: "b", id: "b-due" }, + ]; + expect(takeCompanyWorkBatch(entries, 3)).toEqual({ + entries: [entries[0], entries[3], entries[1]], lastCompany: "a", + }); + }); + it("rotates between batches when more companies are due than fit in one batch", () => { + const entries = ["a", "b", "c", "d"].flatMap(companyId => [ + { companyId, id: `${companyId}-first` }, { companyId, id: `${companyId}-second` }, + ]); + const first = takeCompanyWorkBatch(entries, 2); + const remaining = entries.filter(entry => !first.entries.includes(entry)); + const second = takeCompanyWorkBatch(remaining, 2, first.lastCompany); + expect([...first.entries, ...second.entries].map(entry => entry.companyId)).toEqual(["a", "b", "c", "d"]); + expect(takeCompanyWorkBatch(remaining, 1, "z").entries[0].companyId).toBe("a"); + }); + it("finishes an empty or exhausted batch without inventing work", () => { + expect(takeCompanyWorkBatch([], 25, "gone")).toEqual({ entries: [], lastCompany: "gone" }); + const entry = { companyId: "only" }; + expect(takeCompanyWorkBatch([entry], 25).entries).toEqual([entry]); + }); +}); diff --git a/server/src/__tests__/delivery-work-coordinator.test.ts b/server/src/__tests__/delivery-work-coordinator.test.ts index 805aa3db4c4..2ec8054336f 100644 --- a/server/src/__tests__/delivery-work-coordinator.test.ts +++ b/server/src/__tests__/delivery-work-coordinator.test.ts @@ -59,6 +59,58 @@ describe("delivery work coordinator", () => { expect(s.onError).not.toHaveBeenCalled(); } finally { clock.mockRestore(); } }); + it("honors a future backlog deadline after failure while preserving the fallback retry", async () => { + const s = setup(), t = task(); + let next: number | null = Date.now() + 1000; + t.run.mockRejectedValueOnce(new Error("One item failed")); + await s.coordinator.register(DELIVERY_QUEUES.feedback, { ...t, nextRunAt: () => next }).ready; + expect(s.coordinator.nextWakeAt()).toBe(next); + expect(s.onError).toHaveBeenCalledOnce(); + next = null; + await vi.advanceTimersByTimeAsync(1000); + expect(t.run).toHaveBeenCalledTimes(2); + expect(s.coordinator.nextWakeAt()).toBeNull(); + }); + it("dispatches another due item after a worker records scoped failure backoffs", async () => { + const s = setup(), t = task(), now = Date.now(); + t.run.mockRejectedValueOnce(new Error("One scoped item failed")); + const nextRunAtOnError = vi.fn(() => now); + await s.coordinator.register(DELIVERY_QUEUES.feedback, { ...t, nextRunAtOnError }).ready; + expect(nextRunAtOnError).toHaveBeenCalledOnce(); + expect(s.coordinator.nextWakeAt()).toBe(now); + await vi.advanceTimersByTimeAsync(1); + expect(t.run).toHaveBeenCalledTimes(2); + expect(s.coordinator.nextWakeAt()).toBeNull(); + }); + it.each(["reconcile", "pending"])("does not consume scoped retry deadlines for a %s failure", async mode => { + const s = setup(), t = task(), now = Date.now(); + if (mode === "reconcile") { + s.failCommit(); + await expect(s.enqueue()).rejects.toThrow("lost commit reply"); + s.execute.mockRejectedValueOnce(new Error("Database unavailable")); + } else t.hasPending.mockRejectedValueOnce(new Error("Pending state unavailable")); + const nextRunAtOnError = vi.fn(() => now); + await s.coordinator.register(DELIVERY_QUEUES.feedback, { ...t, nextRunAtOnError }).ready; + expect(nextRunAtOnError).not.toHaveBeenCalled(); + expect(s.coordinator.nextWakeAt()).toBe(now + 5000); + expect(s.onError).toHaveBeenCalledOnce(); + await vi.advanceTimersByTimeAsync(4999); + expect(s.onError).toHaveBeenCalledOnce(); + }); + it.each(["overdue", "later", "unreadable", "draining"])("keeps failure backoff for a %s deadline", async mode => { + const s = setup(), t = task(), now = Date.now(); + t.run.mockImplementation(async () => { + if (mode === "draining") { s.canRun.mockReturnValue(false); s.canReconcile.mockReturnValue(true); } + throw new Error("Unavailable"); + }); + await s.coordinator.register(DELIVERY_QUEUES.feedback, { ...t, nextRunAt: () => { + if (mode === "unreadable") throw new Error("Deadline unavailable"); + return mode === "overdue" ? now : now + (mode === "later" ? 60_000 : 1000); + } }).ready; + expect(s.coordinator.nextWakeAt()).toBe(now + 5000); + await vi.advanceTimersByTimeAsync(4999); + expect(t.run).toHaveBeenCalledOnce(); + }); it("schedules maintenance without holding idle intent, and lets new work preempt it", async () => { const s = setup(), t = task(); let next: number | null = Date.now() + 60_000; diff --git a/server/src/__tests__/scoped-deadline-work.test.ts b/server/src/__tests__/scoped-deadline-work.test.ts new file mode 100644 index 00000000000..fda914dd13e --- /dev/null +++ b/server/src/__tests__/scoped-deadline-work.test.ts @@ -0,0 +1,39 @@ +import { installDatabaseWorkSignals } from "../../../packages/db/src/work-signals.js"; +import { afterEach, expect, it, vi } from "vitest"; +import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js"; +import { registerScopedDeadlineWork } from "../services/scoped-deadline-work.js"; + +let coordinator: ReturnType | undefined; +afterEach(async () => { await coordinator?.stop(); vi.useRealTimers(); }); + +it("preserves a subsecond replacement deadline when the owner does not require pass spacing", async () => { + vi.useFakeTimers(); + const onError = vi.fn(); + const owner = installDatabaseWorkSignals({ execute: vi.fn(async () => []) }); + coordinator = createDeliveryWorkCoordinator({ owner, canRun: () => true, onError }); + const now = Date.now(); + let dueAt = now + 60_000; + const check = vi.fn(async () => null); + const worker = registerScopedDeadlineWork(coordinator, { + queue: DELIVERY_QUEUES.secretProposalExpiry, + minimumPassIntervalMs: 0, + decodeScope: hint => hint === "*" ? undefined : hint, + matches: (entry, companyId?: string) => companyId === undefined || entry.companyId === companyId, + load: async () => [{ id: "company", companyId: "company", dueAt }], + check, + }, () => true); + await worker.ready; + dueAt = now + 250; + worker.invalidate("company"); + await vi.advanceTimersByTimeAsync(1); + expect(coordinator.nextWakeAt()).toBe(dueAt); + await vi.advanceTimersByTimeAsync(248); + expect(check).not.toHaveBeenCalled(); + await vi.advanceTimersByTimeAsync(1); + expect(check).toHaveBeenCalledOnce(); + expect(coordinator.nextWakeAt()).toBeNull(); + await vi.advanceTimersByTimeAsync(60_000); + expect(check).toHaveBeenCalledOnce(); + expect(onError).not.toHaveBeenCalled(); +}); diff --git a/server/src/__tests__/secret-proposals-routes.test.ts b/server/src/__tests__/secret-proposals-routes.test.ts index 3354345e4f4..935fdb84f89 100644 --- a/server/src/__tests__/secret-proposals-routes.test.ts +++ b/server/src/__tests__/secret-proposals-routes.test.ts @@ -1,3 +1,8 @@ +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; +import { registerSecretProposalExpiryWork } from "../services/secret-proposal-expiry-work.js"; +import { deleteCompany } from "../services/company-deletion.js"; +import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { idleWorkSnapshot } from "../services/task-admission.js"; import { randomUUID } from "node:crypto"; import { mkdirSync, rmSync } from "node:fs"; import os from "node:os"; @@ -5,7 +10,7 @@ import path from "node:path"; import express from "express"; import request from "supertest"; import { and, eq, sql } from "drizzle-orm"; -import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { activityLog, agents, @@ -38,7 +43,8 @@ import { startEmbeddedPostgresTestDatabase, } from "./helpers/embedded-postgres.js"; -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); +const externalTestDatabase = resolveExternalTestDatabaseUrl("PAPERCLIP_SECRET_PROPOSAL_TEST_DATABASE_URL"); +const embeddedPostgresSupport = externalTestDatabase ? { supported: true } : await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; describeEmbeddedPostgres("secret proposal routes", () => { @@ -50,9 +56,10 @@ describeEmbeddedPostgres("secret proposal routes", () => { beforeAll(async () => { mkdirSync(secretsTmpDir, { recursive: true }); process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE = path.join(secretsTmpDir, "master.key"); + if (externalTestDatabase) { db = createDb(externalTestDatabase, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 }); return; } const started = await startEmbeddedPostgresTestDatabase("secret-proposal-routes"); stopDb = started.cleanup; - db = createDb(started.connectionString); + db = createDb(started.connectionString, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 }); }); afterEach(async () => { @@ -74,14 +81,14 @@ describeEmbeddedPostgres("secret proposal routes", () => { }); afterAll(async () => { + await db?.$client.end({ timeout: 1 }); await stopDb?.(); if (previousKeyFile === undefined) delete process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE; else process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE = previousKeyFile; rmSync(secretsTmpDir, { recursive: true, force: true }); }); - async function seedRun() { - const companyId = randomUUID(); + async function seedRun(identifier = "SEC-1", companyId = randomUUID()) { const agentId = randomUUID(); const heartbeatRunId = randomUUID(); const issueId = randomUUID(); @@ -113,7 +120,7 @@ describeEmbeddedPostgres("secret proposal routes", () => { id: issueId, companyId, title: "Needs credential", - identifier: "SEC-1", + identifier, status: "in_progress", responsibleUserId: "user-1", executionRunId: heartbeatRunId, @@ -221,6 +228,301 @@ describeEmbeddedPostgres("secret proposal routes", () => { return app; } + describe("expiry scheduling", () => { + let coordinator: ReturnType | undefined; + let proposals: ReturnType; + let fixture: Awaited>; + let draining: boolean; + const errors: unknown[] = []; + const expiryMs = 14 * 24 * 60 * 60_000; + + beforeEach(async () => { + await Promise.all(Array.from({ length: 6 }, () => db.execute(sql`select pg_sleep(0.01)`))); + fixture = await seedRun(); + proposals = createSecretProposalsService(db); + draining = false; + errors.length = 0; + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: true }); + }); + afterEach(async () => { + await coordinator?.stop(); + coordinator = undefined; + vi.useRealTimers(); + expect(errors).toEqual([]); + }); + async function start() { + coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => !draining, + canReconcile: () => true, onError: error => errors.push(error) }); + await registerSecretProposalExpiryWork(coordinator, proposals, () => !draining).ready; + } + async function settle(ms = 60_000) { + await vi.advanceTimersByTimeAsync(ms); + if (!draining) await vi.waitFor(() => expect(idleWorkSnapshot().active === 0).toBe(true), { timeout: 5000 }); + } + async function quiet() { + await settle(); + expect(coordinator!.nextWakeAt()).toBeNull(); + const reads = vi.spyOn(db, "select"); + await settle(60 * 60_000); + expect(reads).not.toHaveBeenCalled(); + reads.mockRestore(); + } + const create = (service = proposals) => service.createSecret({ ...fixture, registerForRedaction: () => {} }, { + name: "dev/scheduled/secret", value: "expiry-test-only", justification: "Test durable expiry", + }); + const bind = (secretProposalId: string) => proposals.createBinding(fixture, { + secretProposalId, configPath: "access.SCHEDULED", justification: "Test dependent expiry", + bindingTargetPolicy: "self_and_reports", + }); + + async function createWithExpiry(expiresAt: Date) { + return db.transaction(async tx => { + const proposal = await create(createSecretProposalsService(tx as unknown as typeof db)); + const [updated] = await tx.update(companySecretProposals).set({ expiresAt }) + .where(eq(companySecretProposals.id, proposal.id)).returning(); + return updated; + }); + } + + it("honors a saved five-second expiry without clamping it to recovery spacing", async () => { + const delay = 5000; + await start(); await quiet(); + const expiresAt = new Date(Date.now() + delay); + const proposal = await createWithExpiry(expiresAt); await settle(1); + expect(coordinator!.nextWakeAt()).toBe(expiresAt.getTime()); + await settle(delay / 2); + expect(await proposals.getById(fixture.companyId, proposal.id)).toMatchObject({ status: "pending" }); + await settle(delay); + expect(await proposals.getById(fixture.companyId, proposal.id)).toMatchObject({ status: "expired", valueCiphertext: null }); + await quiet(); + }); + + it("moves to an earlier committed proposal deadline without losing the later one", async () => { + await start(); await quiet(); + const later = await createWithExpiry(new Date(Date.now() + 120_000)); await settle(1); + expect(coordinator!.nextWakeAt()).toBe(later.expiresAt.getTime()); + const earlier = await createWithExpiry(new Date(Date.now() + 5000)); await settle(1); + expect(coordinator!.nextWakeAt()).toBe(earlier.expiresAt.getTime()); + await settle(6000); + expect(await proposals.getById(fixture.companyId, earlier.id)).toMatchObject({ status: "expired", valueCiphertext: null }); + expect(await proposals.getById(fixture.companyId, later.id)).toMatchObject({ status: "pending" }); + expect(coordinator!.nextWakeAt()).toBe(later.expiresAt.getTime()); + await settle(120_000); await quiet(); + }); + + it("keeps sequential tenant writes from scanning another company's proposals", async () => { + const other = await seedRun("OTHER-1"); + const foreign = await proposals.createSecret({ ...other, registerForRedaction: () => {} }, { + name: "dev/other/secret", value: "other-expiry-only", justification: "Another company's deadline", + }); + await start(); await settle(1); + const reads: Array<{ query: string; params: unknown[] }> = []; + const debug = db.$client.options.debug; + db.$client.options.debug = (_id, query, params) => { + if (/^select/i.test(query) && query.includes('"company_secret_proposals"') && + (query.includes('min(') || query.includes('"expires_at" <='))) reads.push({ query, params: [...params] }); + }; + try { + for (let i = 0; i < 3; i++) { await create(); await settle(1000); } + } finally { db.$client.options.debug = debug; } + expect(reads.length).toBeGreaterThan(0); + for (const read of reads) { + expect(read.query).toContain('"company_secret_proposals"."company_id" ='); + expect(read.params).toContain(fixture.companyId); + expect(read.params).not.toContain(other.companyId); + } + expect(await proposals.getById(other.companyId, foreign.id)).toMatchObject({ status: "pending", valueCiphertext: foreign.valueCiphertext }); + }); + + it("expires only the company whose saved deadline is due", async () => { + const other = await seedRun("OTHER-1"); + const foreign = await proposals.createSecret({ ...other, registerForRedaction: () => {} }, { + name: "dev/other/secret", value: "other-expiry-only", justification: "Another company's deadline", + }); + const due = await createWithExpiry(new Date(Date.now() + 5000)); + await start(); await settle(1); + const reads: Array<{ query: string; params: unknown[] }> = []; + const debug = db.$client.options.debug; + db.$client.options.debug = (_id, query, params) => { + if (/^select/i.test(query) && query.includes('"company_secret_proposals"') && + (query.includes('min(') || query.includes('"expires_at" <='))) reads.push({ query, params: [...params] }); + }; + try { await settle(6000); } finally { db.$client.options.debug = debug; } + expect(reads.some(read => read.query.includes('"expires_at" <='))).toBe(true); + for (const read of reads) { + expect(read.query).toContain('"company_secret_proposals"."company_id" ='); + expect(read.params).toContain(fixture.companyId); + expect(read.params).not.toContain(other.companyId); + } + expect(await proposals.getById(fixture.companyId, due.id)).toMatchObject({ status: "expired", valueCiphertext: null }); + expect(await proposals.getById(other.companyId, foreign.id)).toMatchObject({ status: "pending", valueCiphertext: foreign.valueCiphertext }); + expect(coordinator!.nextWakeAt()).toBe(foreign.expiresAt.getTime()); + }); + + it.each([0, 3000])("keeps a failed company on backoff while another company expires on time (offset %s)", async offset => { + // Make the failing company first in the fair dispatch order. + const other = await seedRun("OTHER-1", "ffffffff-ffff-ffff-ffff-ffffffffffff"); + const failing = await createWithExpiry(new Date(Date.now() + 5000)); + const healthy = await db.transaction(async tx => { + const proposal = await createSecretProposalsService(tx as unknown as typeof db).createSecret( + { ...other, registerForRedaction: () => {} }, + { name: "dev/other/secret", value: "other-expiry-only", justification: "Independent expiry" }); + const [saved] = await tx.update(companySecretProposals).set({ expiresAt: new Date(failing.expiresAt.getTime() + offset) }) + .where(eq(companySecretProposals.id, proposal.id)).returning(); + return saved; + }); + const sweep = proposals.sweepExpiredForCompany; + let unavailable = true; + const attempts = vi.spyOn(proposals, "sweepExpiredForCompany").mockImplementation(async companyId => { + if (unavailable && companyId === fixture.companyId) throw new Error("company expiry unavailable"); + return sweep(companyId); + }); + await start(); await settle(10_000); + expect(errors).toHaveLength(1); errors.length = 0; + expect(await proposals.getById(other.companyId, healthy.id)).toMatchObject({ status: "expired", valueCiphertext: null }); + expect(await proposals.getById(fixture.companyId, failing.id)).toMatchObject({ status: "pending" }); + // A new write must refresh this company without erasing its failed sweep's backoff. + await create(); await settle(1000); + expect(attempts.mock.calls.filter(([id]) => id === fixture.companyId)).toHaveLength(1); + unavailable = false; await settle(30_000); + expect(await proposals.getById(fixture.companyId, failing.id)).toMatchObject({ status: "expired", valueCiphertext: null }); + await settle(expiryMs); await quiet(); + }); + + it("removes the cached expiry when the company deletion owner commits", async () => { + await create(); await start(); await settle(1); + expect(coordinator!.nextWakeAt()).not.toBeNull(); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }) + .where(eq(heartbeatRuns.id, fixture.heartbeatRunId)); + await db.update(issues).set({ executionRunId: null }).where(eq(issues.id, fixture.issueId)); + // The deletion fixture has no live resources; its agent has already + // finished termination before entering the company deletion transaction. + await db.update(agents).set({ status: "terminated", lifecycleState: "terminated" }) + .where(eq(agents.id, fixture.agentId)); + expect(await deleteCompany(db, fixture.companyId)).toMatchObject({ id: fixture.companyId }); + await quiet(); + expect(await proposals.expiryDeadlines()).toEqual([]); + }); + + it("stays quiet until the real proposal deadline, scrubs ciphertext, and leaves terminal history quiet", async () => { + await start(); await quiet(); + const secret = await create(); + const binding = await bind(secret.id); + expect(secret.valueCiphertext).not.toBeNull(); + await settle(); + expect(coordinator!.nextWakeAt()).toBe(secret.expiresAt.getTime()); + const reads = vi.spyOn(db, "select"); + await settle(24 * 60 * 60_000); + expect(reads).not.toHaveBeenCalled(); reads.mockRestore(); + await settle(expiryMs); + expect(await proposals.getById(fixture.companyId, secret.id)).toMatchObject({ + status: "expired", valueCiphertext: null, ciphertextScrubbedAt: expect.any(Date), + }); + expect(await proposals.getById(fixture.companyId, binding.id)).toMatchObject({ status: "rejected" }); + expect(await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, binding.interactionId!))) + .toEqual([expect.objectContaining({ status: "rejected" })]); + await quiet(); + }); + + it.each([false, true])("only observes the producer after outer settlement (rollback %s)", async rollback => { + await start(); await quiet(); + let release!: () => void, written!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const staged = new Promise(resolve => { written = resolve; }); + const rollbackError = new Error("rollback fixture"); + const writing = db.transaction(async tx => { + await create(createSecretProposalsService(tx as unknown as typeof db)); + written(); await gate; + if (rollback) throw rollbackError; + }).catch(error => { if (error !== rollbackError) throw error; }); + await staged; + try { + await vi.advanceTimersByTimeAsync(60_000); + expect(await proposals.nextExpiryAt()).toBeNull(); + } finally { release(); } + await writing; await settle(); + expect(await proposals.nextExpiryAt()).toEqual(rollback ? null : expect.any(Number)); + if (rollback) await quiet(); + else expect(coordinator!.nextWakeAt()).toBe(await proposals.nextExpiryAt()); + }); + + it("retains a proposal committed while an empty deadline read is finishing", async () => { + let release!: () => void, reading!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const entered = new Promise(resolve => { reading = resolve; }); + const readDeadline = proposals.expiryDeadlines; + vi.spyOn(proposals, "expiryDeadlines").mockImplementationOnce(async () => { + const stale = await readDeadline(); + reading(); await gate; + return stale; + }); + const starting = start(); + await entered; + let secret!: Awaited>; + try { secret = await create(); } finally { release(); } + await starting; await settle(); + expect(coordinator!.nextWakeAt()).toBe(secret.expiresAt.getTime()); + await proposals.transition(fixture.companyId, secret.id, "withdrawn", { proposerAgentId: fixture.agentId }); + await quiet(); + }); + + it("reconstructs a deadline after restart and disarms when the proposer withdraws", async () => { + const secret = await create(); + await start(); await settle(); + expect(coordinator!.nextWakeAt()).toBe(secret.expiresAt.getTime()); + await proposals.transition(fixture.companyId, secret.id, "withdrawn", { proposerAgentId: fixture.agentId }); + await quiet(); + expect(await proposals.getById(fixture.companyId, secret.id)).toMatchObject({ valueCiphertext: null }); + }); + + it.each(["startup", "first_write", "failed_pass"])("retains %s work through drain and still rejects expired approval on use", async mode => { + if (mode === "startup") draining = true; + await start(); + if (mode === "first_write") { await quiet(); draining = true; } + const secret = await create(); + if (mode === "failed_pass") { + vi.spyOn(proposals, "expiryDeadlines").mockRejectedValueOnce(new Error("database unavailable")); + await vi.advanceTimersByTimeAsync(30_000); + await vi.waitFor(() => expect(errors).toHaveLength(1)); errors.length = 0; + draining = true; + } + await settle(); + vi.setSystemTime(Date.now() + expiryMs); + const reads = vi.spyOn(db, "select"); + await settle(2 * 60 * 60_000); + expect(reads).not.toHaveBeenCalled(); reads.mockRestore(); + expect(await proposals.getById(fixture.companyId, secret.id)).toMatchObject({ status: "pending" }); + await expect(proposals.approve(fixture.companyId, secret.id, { resolvedByUserId: "board-user" })) + .rejects.toThrow("Expired proposals cannot be approved"); + draining = false; await settle(); + expect(await proposals.getById(fixture.companyId, secret.id)).toMatchObject({ status: "expired", valueCiphertext: null }); + await quiet(); + }); + + it.each(["rejected", "execution_failed"])("reschedules when the interaction owner resolves a binding: %s", async mode => { + const secret = await create(); + await start(); + const approved = await proposals.approve(fixture.companyId, secret.id, { resolvedByUserId: "board-user" }); + await quiet(); + const remaining = await proposals.createBinding(fixture, { secretId: approved.createdSecretId, + configPath: "access.SECOND", justification: "Independent binding", bindingTargetPolicy: "self_and_reports" }); + await settle(); + expect(coordinator!.nextWakeAt()).toBe(remaining.expiresAt.getTime()); + const interactions = issueThreadInteractionService(db); + if (mode === "rejected") { + await interactions.rejectInteraction({ id: fixture.issueId, companyId: fixture.companyId, status: "in_progress" }, + remaining.interactionId!, { reason: "No longer required" }, { userId: "board-user" }); + } else { + await db.update(issueThreadInteractions).set({ status: "accepted", result: { version: 1, outcome: "accepted" }, + resolvedByUserId: "board-user", resolvedAt: new Date() }).where(eq(issueThreadInteractions.id, remaining.interactionId!)); + await interactions.recordSecretProposalExecutionResult({ id: fixture.issueId, companyId: fixture.companyId }, + remaining.interactionId!, remaining.id, { status: "failed", errorCode: "permission_denied" }); + } + expect(await proposals.getById(fixture.companyId, remaining.id)).toMatchObject({ status: "rejected" }); + await quiet(); + }); + }); + it("requires company admin access to reject secret proposals", async () => { const fixture = await seedRun(); const proposed = await request(createAgentApp(fixture)) diff --git a/server/src/__tests__/server-startup-feedback-export.test.ts b/server/src/__tests__/server-startup-feedback-export.test.ts index 81c689366c3..f3d7171c03a 100644 --- a/server/src/__tests__/server-startup-feedback-export.test.ts +++ b/server/src/__tests__/server-startup-feedback-export.test.ts @@ -1,3 +1,4 @@ +import { createSecretProposalsService } from "../services/secret-proposals.js"; import { logger } from "../middleware/logger.js"; import { getStartupRecoveryState } from "../startup-recovery-state.js"; import { idleWorkSnapshot } from "../services/task-admission.js"; @@ -29,6 +30,7 @@ const { detectPortMock, deriveAuthTrustedOriginsMock, deliveryWorkRegisterMock, + deliveryWorkErrors, environmentCustomImagesServiceMock, environmentCustomImagesServiceFactoryMock, executionWorkspaceServiceFactoryMock, @@ -53,11 +55,12 @@ const { }; const caseHandoffDeliveryServiceFactoryMock = vi.fn(() => caseHandoffDeliveryServiceMock); const completionSweepMock = vi.fn(async () => undefined); - const deliveryWorkRegisterMock = vi.fn((_queue: string, task: { + const deliveryWorkErrors: Array<{ queue: string; error: unknown }> = []; + const deliveryWorkRegisterMock = vi.fn((queue: string, task: { retryMs?: number; run: (signal?: AbortSignal) => Promise; hasPending?: () => Promise; - }) => ({ ready: task.run(new AbortController().signal).catch(() => undefined), wake: vi.fn() })); + }) => ({ ready: task.run(new AbortController().signal).catch(error => { deliveryWorkErrors.push({ queue, error }); }), wake: vi.fn() })); const createAppMock = vi.fn(async () => Object.assign((_: unknown, __: unknown) => {}, { locals: { fastResponses: { hasPending: vi.fn(async () => false), sweepPending: vi.fn(async () => undefined) }, @@ -181,6 +184,7 @@ const { detectPortMock, deriveAuthTrustedOriginsMock, deliveryWorkRegisterMock, + deliveryWorkErrors, environmentCustomImagesServiceMock, environmentCustomImagesServiceFactoryMock, executionWorkspaceServiceFactoryMock, @@ -442,6 +446,9 @@ vi.mock("../services/native-runtime/native-question-bridge.js", () => ({ vi.mock("../services/secret-proposals.js", () => ({ createSecretProposalsService: vi.fn(() => ({ + expiryDeadlines: vi.fn(async () => []), + sweepExpiredForCompany: vi.fn(async () => 0), + nextExpiryAt: vi.fn(async () => null), sweepExpired: vi.fn(async () => 0), })), })); @@ -490,6 +497,7 @@ async function settleStartupHousekeeping() { describe("startServer feedback export wiring", () => { beforeEach(() => { vi.clearAllMocks(); + deliveryWorkErrors.length = 0; process.env.PAPERCLIP_DECISION_SIGNING_SECRET = "fedcba9876543210fedcba9876543210"; process.env.PAPERCLIP_AGENT_JWT_SECRET = "0123456789abcdef0123456789abcdef"; loadConfigMock.mockReturnValue(buildTestConfig()); @@ -791,6 +799,19 @@ describe("startServer feedback export wiring", () => { } }); + it("loads secret expiry deadlines successfully during enabled startup", async () => { + loadConfigMock.mockReturnValue(buildTestConfig({ heartbeatSchedulerEnabled: true })); + await startServer(); + await settleStartupHousekeeping(); + const index = deliveryWorkRegisterMock.mock.calls.findIndex(([queue]) => queue === DELIVERY_QUEUES.secretProposalExpiry); + expect(index).toBeGreaterThanOrEqual(0); + await deliveryWorkRegisterMock.mock.results[index].value.ready; + expect(deliveryWorkErrors.filter(({ queue }) => queue === DELIVERY_QUEUES.secretProposalExpiry)).toEqual([]); + const service = vi.mocked(createSecretProposalsService).mock.results[0].value; + expect(service.expiryDeadlines).toHaveBeenCalledExactlyOnceWith(undefined); + expect(service.sweepExpiredForCompany).not.toHaveBeenCalled(); + }); + it("registers native replacement recovery without an execution-control interval", async () => { loadConfigMock.mockReturnValue(buildTestConfig({ heartbeatSchedulerEnabled: true })); const setIntervalSpy = vi.spyOn(globalThis, "setInterval"); diff --git a/server/src/index.ts b/server/src/index.ts index 411dda3f87f..ca51efe4345 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -1,3 +1,4 @@ +import { registerSecretProposalExpiryWork } from "./services/secret-proposal-expiry-work.js"; import { registerCustomImageCleanupWork } from "./services/custom-image-cleanup-work.js"; import { registerWorkspaceRecoveryWork } from "./services/workspace-recovery-work.js"; import { registerEnvironmentCleanupWork } from "./services/environment-cleanup-work.js"; @@ -1791,6 +1792,8 @@ async function startServerWithDatabaseTeardown( work().catch((err: unknown) => { logger.error({ err, startupStep: name }, "startup housekeeping step failed"); }); + await step("secret_proposal_expiry", () => registerSecretProposalExpiryWork(deliveryWork, secretProposals, + () => !isIdleTaskDrainActive() && !heartbeatSchedulerStopped && !isWarmStandby()).ready); await step("custom_image_setup_cleanup", () => registerCustomImageCleanupWork(deliveryWork, environmentCustomImages, () => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped, config.heartbeatSchedulerIntervalMs).ready); @@ -1887,14 +1890,6 @@ async function startServerWithDatabaseTeardown( logger.error({ err }, "periodic tool connection health sweep failed"); })); - trackHeartbeatSchedulerWork(secretProposals.sweepExpired() - .then((expired) => { - if (expired > 0) logger.warn({ expired }, "periodic secret proposal expiry scrubbed proposals"); - }) - .catch((err) => { - logger.error({ err }, "periodic secret proposal expiry sweep failed"); - })); - trackHeartbeatSchedulerWork(app.locals.toolGateway.sweepActionReviews().catch((err: unknown) => logger.error({ err }, "tool review recovery failed"))); trackHeartbeatSchedulerWork(app.locals.toolGateway.cleanupExpiredSessions().catch((err: unknown) => logger.error({ err }, "gateway token cleanup failed"))); diff --git a/server/src/services/company-deletion.ts b/server/src/services/company-deletion.ts index 432cad76e7a..7e4a41a95d7 100644 --- a/server/src/services/company-deletion.ts +++ b/server/src/services/company-deletion.ts @@ -61,6 +61,7 @@ export async function deleteCompany(db: Db, id: string) { .where(eq(companies.id, id)).for("no key update"); if (!existing) return null; await notifyDeliveryWork(tx, DELIVERY_QUEUES.skillSourceSync); + await notifyDeliveryWork(tx, DELIVERY_QUEUES.secretProposalExpiry, id); await agentObservabilityService(tx as unknown as Db).removeForCompanyDeletion(id); // Finance can reference costs and both can reference runs. Incidents // reference policies and approvals; delete these dependents first. diff --git a/server/src/services/company-work-batch.ts b/server/src/services/company-work-batch.ts new file mode 100644 index 00000000000..f83d2dcd5a5 --- /dev/null +++ b/server/src/services/company-work-batch.ts @@ -0,0 +1,28 @@ +export function takeCompanyWorkBatch( + ordered: readonly T[], + limit: number, + afterCompany: string | null = null, +): { entries: T[]; lastCompany: string | null } { + const grouped = new Map(); + for (const entry of ordered) { + const group = grouped.get(entry.companyId); + if (group) group.push(entry); else grouped.set(entry.companyId, [entry]); + } + const companies = [...grouped.keys()].sort(); + const next = afterCompany === null ? 0 : companies.findIndex(id => id > afterCompany); + const start = next < 0 ? 0 : next; + const rotation = [...companies.slice(start), ...companies.slice(0, start)]; + const entries: T[] = []; + let lastCompany = afterCompany; + for (let round = 0; entries.length < limit; round++) { + let added = false; + for (const companyId of rotation) { + const entry = grouped.get(companyId)![round]; + if (!entry) continue; + entries.push(entry); lastCompany = companyId; added = true; + if (entries.length === limit) break; + } + if (!added) break; + } + return { entries, lastCompany }; +} diff --git a/server/src/services/custom-image-cleanup-work.ts b/server/src/services/custom-image-cleanup-work.ts index 9ecd4e73612..feee4ebefa7 100644 --- a/server/src/services/custom-image-cleanup-work.ts +++ b/server/src/services/custom-image-cleanup-work.ts @@ -1,5 +1,6 @@ import { logger } from "../middleware/logger.js"; import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; +import { registerDeadlineWork } from "./deadline-work.js"; import { DELIVERY_QUEUES } from "./delivery-work-notifications.js"; import type { environmentCustomImageService } from "./environment-custom-images.js"; @@ -9,27 +10,13 @@ export function registerCustomImageCleanupWork( canRun: () => boolean, retryMs = 30_000, ) { - let requested = 1, reconciled = 0; - let next: number | null = null; - let earliest = 0; - return coordinator.register(DELIVERY_QUEUES.customImageExpiry, { + return registerDeadlineWork(coordinator, DELIVERY_QUEUES.customImageExpiry, { retryMs, - pausePassiveMaintenance: true, - onSettled: () => { requested++; }, + canRun, run: async () => { - if (!canRun()) { requested++; return; } - if (Date.now() < earliest) { next = earliest; return; } - const generation = ++requested; - earliest = Date.now() + retryMs; const result = await service.cleanupExpiredSetupSessions(); if (result.timedOut > 0 || result.failed > 0) logger.warn(result, "environment customImage setup cleanup changed sessions"); - const deadline = await service.nextSetupCleanupAt(); - // Back off failed or still-overdue work, not a successfully read future deadline. - if (deadline === null || deadline > Date.now()) earliest = 0; - next = deadline === null ? null : Math.max(earliest, deadline); - reconciled = generation; }, - hasPending: async () => requested !== reconciled, - nextRunAt: () => next, + next: () => service.nextSetupCleanupAt(), }); } diff --git a/server/src/services/deadline-work.ts b/server/src/services/deadline-work.ts new file mode 100644 index 00000000000..9f1de1b2a24 --- /dev/null +++ b/server/src/services/deadline-work.ts @@ -0,0 +1,36 @@ +import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; +import type { DeliveryQueue } from "./delivery-work-notifications.js"; + +export function registerDeadlineWork( + coordinator: ReturnType, + queue: DeliveryQueue, + task: { + run: () => Promise; + next: () => Promise; + canRun: () => boolean; + retryMs: number; + }, +) { + let requested = 1, reconciled = 0; + let next: number | null = null; + let earliest = 0; + return coordinator.register(queue, { + retryMs: task.retryMs, + pausePassiveMaintenance: true, + onSettled: () => { requested++; }, + run: async () => { + if (!task.canRun()) { requested++; return; } + if (Date.now() < earliest) { next = earliest; return; } + const generation = ++requested; + earliest = Date.now() + task.retryMs; + await task.run(); + const deadline = await task.next(); + // Back off failed or still-overdue work, not a successfully read future deadline. + if (deadline === null || deadline > Date.now()) earliest = 0; + next = deadline === null ? null : Math.max(earliest, deadline); + reconciled = generation; + }, + hasPending: async () => requested !== reconciled, + nextRunAt: () => next, + }); +} diff --git a/server/src/services/delivery-work-coordinator.ts b/server/src/services/delivery-work-coordinator.ts index 0284e06aba2..0d1a88c9f59 100644 --- a/server/src/services/delivery-work-coordinator.ts +++ b/server/src/services/delivery-work-coordinator.ts @@ -26,6 +26,9 @@ export function createDeliveryWorkCoordinator(input: { onSettled?: (hints?: ReadonlySet) => void; // Optional maintenance/retry deadline restored from durable state. nextRunAt?: () => number | null; + // Opt in only when run has recorded per-item failure backoffs. Other + // eligible items may already be due, unlike an unchanged failed deadline. + nextRunAtOnError?: () => number | null; // An empty queue's maintenance may wait until dispatch admission reopens. // Notifications and unresolved producer writes still reconcile in drain. pausePassiveMaintenance?: boolean; @@ -65,9 +68,10 @@ export function createDeliveryWorkCoordinator(input: { dirty = false; const finish = beginIdleTrackedWork(); const attempt = new AbortController(); + let runFailed = false; controller = attempt; running = Promise.resolve().then(() => reconcileDatabaseWork(input.owner, queue)) - .then(() => workerStopped || !(input.canRun() || (task.runDuringDrain && input.canReconcile?.())) ? undefined : task.run(attempt.signal)).then(() => workerStopped ? false : task.hasPending()).then(pending => { + .then(() => workerStopped || !(input.canRun() || (task.runDuringDrain && input.canReconcile?.())) ? undefined : task.run(attempt.signal).catch(error => { runFailed = true; throw error; })).then(() => workerStopped ? false : task.hasPending()).then(pending => { pendingWork = pending || databaseWorkPending(input.owner, queue); if (pendingWork) schedule(task.retryMs); else { finishIntent?.(); finishIntent = undefined; } @@ -78,9 +82,17 @@ export function createDeliveryWorkCoordinator(input: { } }).catch(error => { schedule(task.retryMs); + let failure = error; + try { + const scopedRetry = runFailed && task.nextRunAtOnError; + const next = input.canRun() ? (scopedRetry ? scopedRetry() : task.nextRunAt?.()) : null; + if (next != null && (scopedRetry || next > Date.now())) schedule(0, Math.max(Date.now(), next)); + } catch (deadlineError) { + failure = new AggregateError([error, deadlineError], "Delivery failure deadline could not be read"); + } // Logging must never turn a recoverable sweep failure into an // unhandled rejection or prevent other queues from running. - try { if (!workerStopped) input.onError(error, queue); } catch { /* Recovery remains scheduled. */ } + try { if (!workerStopped) input.onError(failure, queue); } catch { /* Recovery remains scheduled. */ } }).finally(() => { running = null; controller = null; diff --git a/server/src/services/delivery-work-notifications.ts b/server/src/services/delivery-work-notifications.ts index f6d50c71930..b6bed1d0f25 100644 --- a/server/src/services/delivery-work-notifications.ts +++ b/server/src/services/delivery-work-notifications.ts @@ -9,6 +9,7 @@ export const DELIVERY_QUEUES = { executionStatus: "execution-status", executionDisposition: "execution-disposition", environmentCleanup: "environment-cleanup", + secretProposalExpiry: "secret-proposal-expiry", customImageExpiry: "custom-image-expiry", historicalCleanup: "historical-cleanup", adapterLoginCleanup: "adapter-login-cleanup", diff --git a/server/src/services/issue-thread-interactions.ts b/server/src/services/issue-thread-interactions.ts index bcfbe2882a9..74e8d8216db 100644 --- a/server/src/services/issue-thread-interactions.ts +++ b/server/src/services/issue-thread-interactions.ts @@ -1159,6 +1159,7 @@ async function resolveLinkedSecretProposal( ) { const proposalId = linkedSecretProposalId(interaction); if (!proposalId) return; + await notifyDeliveryWork(db, DELIVERY_QUEUES.secretProposalExpiry, interaction.companyId); const [proposal] = await db .update(companySecretProposals) .set({ @@ -3181,6 +3182,7 @@ export function issueThreadInteractionService( : execution.status; if (executionStatus === "failed" && proposal.status === "pending") { const resolutionReason = `Interaction acceptance failed: ${execution.errorCode ?? "secret_proposal_execution_failed"}`; + await notifyDeliveryWork(tx, DELIVERY_QUEUES.secretProposalExpiry, proposal.companyId); await tx .update(companySecretProposals) .set({ diff --git a/server/src/services/scoped-deadline-work.ts b/server/src/services/scoped-deadline-work.ts new file mode 100644 index 00000000000..6de9d3895da --- /dev/null +++ b/server/src/services/scoped-deadline-work.ts @@ -0,0 +1,99 @@ +import { takeCompanyWorkBatch } from "./company-work-batch.js"; +import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; +import type { DeliveryQueue } from "./delivery-work-notifications.js"; + +type ScheduledEntry = { id: string; companyId: string; dueAt: number }; + +/** Coalesced scope reconstruction and fair deadline dispatch. Domain owners + * supply persistence, eligibility, and execution; this helper owns no SQL. */ +export function registerScopedDeadlineWork( + coordinator: ReturnType, + options: { + queue: DeliveryQueue; + batchSize?: number; + minimumPassIntervalMs?: number; + decodeScope(hint: string): Scope | undefined; + matches(entry: Entry, scope?: Scope): boolean; + load(scope?: Scope, signal?: AbortSignal): Promise; + check(entry: Entry, signal?: AbortSignal): Promise; + }, + canRun: () => boolean, +) { + const dirty = new Set(["*"]); + const entries = new Map(); + const failures = new Map(); + const scopeFailures = new Map(); + let earliest = 0; + let lastCompany: string | null = null; + function failed(map: typeof failures, id: string) { + const count = Math.min((map.get(id)?.count ?? 0) + 1, 5); + map.set(id, { count, retryAt: Date.now() + Math.min(300_000, 30_000 * 2 ** (count - 1)) }); + } + function dirtyScopes() { + return [...dirty].map(hint => { try { return options.decodeScope(hint); } catch { return undefined; } }); + } + function next() { + if (!canRun()) return dirty.size > 0 || entries.size > 0 ? Date.now() + 30_000 : null; + let nextAt: number | null = null; + const take = (at: number) => { nextAt = nextAt === null ? at : Math.min(nextAt, at); }; + for (const hint of dirty.has("*") ? ["*"] : dirty) take(Math.max(earliest, scopeFailures.get(hint)?.retryAt ?? 0)); + const unavailable = dirtyScopes(); + for (const entry of entries.values()) if (!unavailable.some(scope => options.matches(entry, scope))) + take(Math.max(earliest, entry.dueAt, failures.get(entry.id)?.retryAt ?? 0)); + return nextAt; + } + const worker = coordinator.register(options.queue, { + retryMs: 30_000, + pausePassiveMaintenance: true, + onSettled: hints => { for (const hint of hints ?? ["*"]) dirty.add(hint); }, + run: async signal => { + if (!canRun() || Date.now() < earliest) return; + earliest = Date.now() + (options.minimumPassIntervalMs ?? 1000); + const errors: unknown[] = []; + const requested = (dirty.has("*") ? ["*"] : [...dirty]).filter(hint => (scopeFailures.get(hint)?.retryAt ?? 0) <= Date.now()); + const covered = requested.includes("*") ? [...dirty] : requested; + for (const hint of covered) dirty.delete(hint); + for (let index = 0; index < requested.length; index++) { + if (signal.aborted || !canRun()) { for (const hint of requested.includes("*") ? covered : requested.slice(index)) dirty.add(hint); return; } + const hint = requested[index]; + let scope: Scope | undefined; + let decoded = false; + try { + scope = options.decodeScope(hint); decoded = true; + const rows = await options.load(scope, signal), retained = new Set(rows.map(row => row.id)); + for (const entry of entries.values()) if (options.matches(entry, scope) && !retained.has(entry.id)) { + entries.delete(entry.id); failures.delete(entry.id); + } + for (const entry of rows) entries.set(entry.id, entry); + if (!scope) scopeFailures.clear(); else scopeFailures.delete(hint); + } catch (error) { + const retryHint = decoded ? hint : "*"; + dirty.add(retryHint); failed(scopeFailures, retryHint); errors.push(error); + } + } + const unavailable = dirtyScopes(); + const due = [...entries.values()].filter(entry => !unavailable.some(scope => options.matches(entry, scope)) + && Math.max(entry.dueAt, failures.get(entry.id)?.retryAt ?? 0) <= Date.now()) + .sort((a, b) => a.dueAt - b.dueAt || a.id.localeCompare(b.id)); + const batch = takeCompanyWorkBatch(due, options.batchSize ?? 25, lastCompany); lastCompany = batch.lastCompany; + for (const entry of batch.entries) { + if (signal.aborted || !canRun()) break; + try { + const current = await options.check(entry, signal); + if (current) entries.set(entry.id, current); else entries.delete(entry.id); + failures.delete(entry.id); + } catch (error) { failed(failures, entry.id); errors.push(error); } + } + if (errors.length) throw new AggregateError(errors, `${options.queue} could not settle`); + }, + // Retain scopes/deadlines for resume without retaining a settled write's + // idle hold during drain. The coordinator still fences unresolved XIDs. + hasPending: async () => canRun() && dirty.size > 0, + nextRunAt: next, + nextRunAtOnError: next, + }); + return { ...worker, invalidate(hint = "*") { + dirty.add(hint); + worker.wake(); + } }; +} diff --git a/server/src/services/secret-proposal-expiry-work.ts b/server/src/services/secret-proposal-expiry-work.ts new file mode 100644 index 00000000000..1a019047c92 --- /dev/null +++ b/server/src/services/secret-proposal-expiry-work.ts @@ -0,0 +1,29 @@ +import { logger } from "../middleware/logger.js"; +import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; +import { DELIVERY_QUEUES } from "./delivery-work-notifications.js"; +import { registerScopedDeadlineWork } from "./scoped-deadline-work.js"; +import type { createSecretProposalsService } from "./secret-proposals.js"; + +export function registerSecretProposalExpiryWork( + coordinator: ReturnType, + service: Pick, "sweepExpiredForCompany" | "expiryDeadlines">, + canRun: () => boolean, +) { + return registerScopedDeadlineWork(coordinator, { + queue: DELIVERY_QUEUES.secretProposalExpiry, + batchSize: 1, + // Saved expiry deadlines are authoritative, including deadlines less than + // a second away. Only actual failures require a recovery backoff. + minimumPassIntervalMs: 0, + decodeScope: hint => hint === "*" ? undefined : hint, + matches: (entry, companyId?: string) => companyId === undefined || entry.companyId === companyId, + load: async (companyId?: string) => (await service.expiryDeadlines(companyId)) + .map(row => ({ ...row, id: row.companyId })), + check: async entry => { + const expired = await service.sweepExpiredForCompany(entry.companyId); + if (expired > 0) logger.warn({ companyId: entry.companyId, expired }, "secret proposal expiry scrubbed proposals"); + const [next] = await service.expiryDeadlines(entry.companyId); + return next ? { ...next, id: next.companyId } : null; + }, + }, canRun); +} diff --git a/server/src/services/secret-proposals.ts b/server/src/services/secret-proposals.ts index fbefd53d5fd..05f5af71d91 100644 --- a/server/src/services/secret-proposals.ts +++ b/server/src/services/secret-proposals.ts @@ -1,3 +1,4 @@ +import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; import { updateAgentConfigurationInTransaction } from "./agent-configuration-transaction.js"; import { withAgentAppearance } from "@paperclipai/shared"; import { and, count, desc, eq, gte, inArray, lte, or, sql } from "drizzle-orm"; @@ -144,6 +145,7 @@ export function createSecretProposalsService(db: Db) { }); return { denial, value: null }; } + await notifyDeliveryWork(txDb, DELIVERY_QUEUES.secretProposalExpiry, input.companyId); return { denial: null, value: await create(txDb) }; }); if (result.denial) throw unprocessable(result.denial.message); @@ -619,6 +621,7 @@ export function createSecretProposalsService(db: Db) { appliedBindingConfigPath?: string | null; }) { const now = new Date(); + await notifyDeliveryWork(txDb, DELIVERY_QUEUES.secretProposalExpiry, proposal.companyId); const updated = await txDb.update(companySecretProposals).set({ status: "approved", resolvedByUserId: input.resolvedByUserId, @@ -794,6 +797,7 @@ export function createSecretProposalsService(db: Db) { const now = new Date(); return db.transaction(async (tx) => { const txDb = tx as unknown as Db; + await notifyDeliveryWork(tx, DELIVERY_QUEUES.secretProposalExpiry, companyId); const updated = await tx.update(companySecretProposals).set({ status, resolvedByUserId: input.resolvedByUserId ?? null, @@ -868,10 +872,12 @@ export function createSecretProposalsService(db: Db) { limit = DEFAULT_EXPIRY_SWEEP_LIMIT, expireProposal: (companyId: string, proposalId: string) => Promise = (companyId, proposalId) => transition(companyId, proposalId, "expired", { reason: "Pending proposal expired" }), + companyId?: string, ) { const expired = await db.select({ id: companySecretProposals.id, companyId: companySecretProposals.companyId }) .from(companySecretProposals) - .where(and(eq(companySecretProposals.status, "pending"), lte(companySecretProposals.expiresAt, now))) + .where(and(eq(companySecretProposals.status, "pending"), lte(companySecretProposals.expiresAt, now), + companyId === undefined ? undefined : eq(companySecretProposals.companyId, companyId))) .orderBy(companySecretProposals.expiresAt) .limit(limit); let expiredCount = 0; @@ -887,5 +893,25 @@ export function createSecretProposalsService(db: Db) { return expiredCount; } - return { getById, view: enrich, createSecret, createBinding, listForAgent, listForBoard, assertBindingSnapshotCurrent, approve, transition, sweepExpired }; + async function sweepExpiredForCompany(companyId: string) { + return sweepExpired(new Date(), DEFAULT_EXPIRY_SWEEP_LIMIT, undefined, companyId); + } + + async function expiryDeadlines(companyId?: string) { + const rows = await db.select({ companyId: companySecretProposals.companyId, + at: sql`min(${companySecretProposals.expiresAt})` }) + .from(companySecretProposals) + .where(and(eq(companySecretProposals.status, "pending"), + companyId === undefined ? undefined : eq(companySecretProposals.companyId, companyId))) + .groupBy(companySecretProposals.companyId); + return rows.map(row => ({ companyId: row.companyId, dueAt: new Date(row.at).getTime() })); + } + + async function nextExpiryAt(): Promise { + const [row] = await db.select({ at: sql`min(${companySecretProposals.expiresAt})` }) + .from(companySecretProposals).where(eq(companySecretProposals.status, "pending")); + return row?.at == null ? null : new Date(row.at).getTime(); + } + + return { getById, view: enrich, createSecret, createBinding, listForAgent, listForBoard, assertBindingSnapshotCurrent, approve, transition, sweepExpired, sweepExpiredForCompany, expiryDeadlines, nextExpiryAt }; } From 3cd3af5d75f200185ed4d9703a3145594a489b13 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:53:32 -0500 Subject: [PATCH 2/3] Trace native preparation and OpenCode execution phases (#17918) ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Each native run prepares its workspace and skills, then starts its provider. > - A long preparation span does not show whether inventory refresh, a cache lock, repository reads, or file checks caused the delay. > - One hosted run spent 81 seconds in this phase. The same deployed service and pinned files took 2.55 seconds in a separate diagnostic process. > - Another hosted turn spent 69 seconds before its first output. A matched public-workspace local model replay took 7.64 seconds. > - We need skill preparation and provider-internal measurements before choosing another fix. > - This pull request adds skill spans, a real-service benchmark, and opt-in filtered provider timing. > - The benefit is a faster and more precise diagnosis loop. ## Linked Issues or Issue Description Refs #17620. That PR owns the batched read optimization. This PR adds diagnostics and does not change its read policy. Refs #17907. That PR protects long cache lock transactions from the database idle timeout. **What happened?** Native skill configuration can take much longer than matched standalone resolution. Provider execution also has long gaps with no internal timings. Existing spans cannot separate inventory refresh, cache acquisition, repository reads, context loading, Git snapshots, or model streaming. **Expected behavior** An operator-configured trace shows these phases under the existing run context. Without an OTLP endpoint, the new spans stay off. A local benchmark can reproduce the service path with real PostgreSQL, files, an agent actor, and a responsible user. **Steps to reproduce** 1. Run `pnpm --filter @paperclipai/server exec tsx scripts/benchmark-native-skill-preparation.ts --actor=agent --staging-shape=true`. 2. Inspect cold and warm phase timings, SQL counts, and file verification results. 3. Set the existing operator OTLP configuration and add `--export-otlp=true` to inspect the same hierarchy in the collector. ## What Changed - Add bounded skill inventory, refresh wait, cache acquisition, row, version, repository, file check, and consumer spans. - Keep the existing endpoint gate, attribute allowlist, cache locks, authorization, file validation, and durable pin boundary. - Add a standalone benchmark with a full repository fixture, immutable snapshot input, calibrated local transport delay, and optional OTLP export. - Verify every delivered file and executable bit outside the timed section. Create its fixture agent through the lifecycle API. - Add an opt-in authenticated loopback sink for OpenCode. Discard raw attributes, logs and content. Retain only closed phase names and timestamps. - Carry one bounded diagnostic batch through the real proxy, Rust normalization, durable journal and server trace projection. Group provider phases under their execution parent. - Freeze the Date clock in an existing delegated Slack rate-limit test. This fixes a CI failure when consecutive requests cross a rate-window boundary. It does not change rate-limit behavior. - Document phase boundaries and the difference between SDK startup and confirmed ingestion. ## Verification - Skill service, runtime selection, concurrency, cache and timing suites: 122 tests passed with real PostgreSQL and migrations. Enabled-span integration tests also passed. They verify parent relationships and a real advisory-lock timeout. - A captured 208-file repository produced 209 verified runtime files. The benchmark uses real agent and responsible-user authorization. The lifecycle fixture correction passed with the staging-shaped inventory. - Affected OpenCode driver, collector and transport tests: 72 passed. The tests cover authentication, content removal, size/count bounds, disabled behavior and the rebuilt native Runner boundary. One Rust projection test and 18 server trace tests also passed. A held run-log sink proves that a full 128-span diagnostic batch adds no duplicate database writes before terminal consumption. - The two CI-failing delegated Slack rate-limit cases passed against real PostgreSQL with only the Date clock frozen. - Runner TypeScript and server TypeScript checks passed. Rust formatting and module-boundary checks passed. - Real Honeycomb readback confirmed the 14-span skill waterfall and a 40-span provider waterfall. Provider phases have the correct execution parent. The provider export uses synthetic model replies and is instrumentation proof only. - Earlier full local checks failed on missing package-local executables, then on the default Node heap and a missing generated service worker. The dependency links were repaired. The server check passed with a larger heap. The full local test attempt could not start embedded PostgreSQL on this host and was stopped after retaining its failures; real database coverage uses an isolated database on an existing local server. These attempts do not count as a full local pass. - CI on the prior revision passed typecheck, build, Runner and all E2E shards. It failed the benchmark lifecycle boundary and one existing rate-window test. Those fixes passed CI. A later Runner assertion exposed the Copilot source identity pin on the shared transport file. The diagnostic flag now uses the existing configured-environment projection, preserving that file byte-for-byte. All 66 selected installation and native transport tests passed. New-head CI and review remain required. - The under-15-second hosted response target remains unmet. This PR adds diagnostics and does not claim a hosted latency fix. ## Risks - Skill spans and Honeycomb export retain the operator endpoint gate. OpenCode phase collection requires a separate explicit diagnostic flag. Without an endpoint, its closed measurements stay in the instance run log. - Raw OpenCode OTLP can contain prompts and authorization attributes. The new sink rejects unauthenticated requests and discards all attributes before any measurement reaches PRP or the operator collector. Request, event and per-phase limits bound memory and journal growth. - Collection does not wait for a provider flush. Late or oversized exports can be absent; these measurements are not a complete profiling guarantee. - The benchmark's inventory contents and transport delay are explicit fixtures. They do not reproduce server contention or prove hosted response time. - The one durable diagnostic batch remains the local evidence. Its child span export does not add per-phase run-log rows. - No database migration, authorization policy, model selection or inference transport changes. The Rust Runner and OpenCode proxy must be shipped together for the new opt-in diagnostic. ## Model Used OpenAI GPT-6 through Codex, with repository inspection, shell execution, browser tools, and Honeycomb queries. The session does not expose a verifiable backend deployment ID or context-window size. ## 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 --------- Co-authored-by: Paperclip Co-authored-by: Paperclip --- doc/DEVELOPING.md | 35 +++ doc/observability.md | 43 +++ .../crates/runner-core/src/codex_provider.rs | 1 + .../crates/runner-core/src/provider_events.rs | 63 +++++ .../src/cli/opencode-app-server-proxy.ts | 8 + .../src/contracts/provider-performance.ts | 43 +++ .../durable-prp-control-plane.ts | 1 + .../opencode/opencode-server-driver.ts | 23 ++ .../opencode/performance-diagnostics.test.ts | 65 +++++ .../opencode/performance-diagnostics.ts | 103 +++++++ packages/paperclip-runner/src/index.ts | 1 + .../src/live/runnerd-codex-transport.test.ts | 19 +- .../test/fixtures/fake-opencode-server.mjs | 18 ++ .../benchmark-native-skill-preparation.ts | 260 ++++++++++++++++++ .../company-skills-observability.test.ts | 151 ++++++++++ .../connection-management.integration.test.ts | 4 +- server/src/services/company-skills.ts | 31 ++- .../execution-preparation-timing.test.ts | 3 +- .../services/execution-preparation-timing.ts | 4 + .../native-runtime/native-run-trace.test.ts | 34 +++ .../native-runtime/native-run-trace.ts | 25 +- .../native-runtime/native-session-executor.ts | 5 + server/src/services/skill-version-cache.ts | 8 +- server/src/vendor/paperclip-runner/index.ts | 1 + 24 files changed, 930 insertions(+), 19 deletions(-) create mode 100644 packages/paperclip-runner/src/contracts/provider-performance.ts create mode 100644 packages/paperclip-runner/src/drivers/opencode/performance-diagnostics.test.ts create mode 100644 packages/paperclip-runner/src/drivers/opencode/performance-diagnostics.ts create mode 100644 server/scripts/benchmark-native-skill-preparation.ts create mode 100644 server/src/__tests__/company-skills-observability.test.ts diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 0afd307559a..05071cb68ff 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -838,6 +838,41 @@ Set `SEARCH_EVAL_SCALE=1` to additionally measure a disposable 10,000-task, 30,000-comment dataset. `SEARCH_EVAL_REPORT=/tmp/search-quality.json` saves per-query results and latency measurements; scale measurements are opt-in. +### Native skill preparation benchmark + +Measure native skill preparation through the production service, real PostgreSQL, +and an in-memory OpenTelemetry exporter: + +```sh +pnpm --filter @paperclipai/server exec tsx scripts/benchmark-native-skill-preparation.ts +``` + +The default fixture has a 208-file repository of about 10.8 MB. The report includes +cold and warm resolution, a fresh service instance, detailed phase timings, and +regular-pool SQL statement counts (excluding the separate cache-lock connection). +Every delivered file is checked outside the timed section. No provider is started. +`--snapshot-file=/absolute/path/snapshot.json --entrypoint=skills/example/SKILL.md` +uses a captured repository file inventory instead. `--network-delay-ms=25` adds +25 ms in each direction through a local TCP relay; this is simulated transport +latency, not a measurement of a hosted database. + +`--actor=agent` adds a real agent, run, and responsible user, then records version +pins through the same callback boundary as execution. `--staging-shape=true` +seeds 14 projects, 10 sources, 8 bindings, and 156 other skills. These match one +observed staging inventory's counts; their content is synthetic. Combine these +options to include authorization and unselected library rows in the measurement. + +By default, spans stay in memory. `--export-otlp=true` also exports them using +the operator's `OTEL_EXPORTER_OTLP_ENDPOINT`, protocol, and headers. Keep header +values out of command arguments and reports. The report records source hashes, +the export mode, and trace IDs. Exported traces identify this local diagnostic +in their service version; they are not evidence of staging performance. + +If creating another embedded cluster is impractical, `--postgres-port=55448 +--postgres-user=paperclip` uses an existing **local** server. It creates and migrates +a uniquely named disposable database and drops that database afterward; it does +not reuse an application database. + ### Repository workspace admission benchmark Measure a fresh checkout with and without the repository object cache: diff --git a/doc/observability.md b/doc/observability.md index 55328507d0c..324273807ec 100644 --- a/doc/observability.md +++ b/doc/observability.md @@ -35,6 +35,13 @@ maintains as a dependency; once you install the packages below, they become normal dependencies of **your own** project, and your own Dependabot updates them. +An initialized SDK does not confirm ingestion. Verify a fresh trace from the +deployed revision at the configured destination. A rejected export can leave +the application healthy. For Honeycomb, configure the ingest key in the +`x-honeycomb-team` entry of `OTEL_EXPORTER_OTLP_HEADERS`; see +[Honeycomb authentication](https://docs.honeycomb.io/api/query-annotations/authorization). +Keep credential values out of logs and diagnostic reports. + ## Budget admission, accounting, and enforcement The operator-gated `paperclip.budgets` tracer records @@ -313,6 +320,9 @@ attempt or owning phase: | `runtime_selection.*` | Completion contracts, session/recovery reads, profiles, interaction materialization, backend discovery, bootstrap, run/coordinator writes, transaction entry/settlement, and workspace synchronization. | | `runtime_context.instructions`, `.skills`, `.mcp` | The three concurrent runtime-context branches. Their durations overlap. | | `runtime_context.asset_*` | Source reads, manifest hashing, cache lookup, cold materialization, and exact file verification on cold and warm paths. | +| `skills.inventory`, `.wait`, `.bundled`, `.releases`, `.folders`, `.local_sources` | Company skill reconciliation, waiting for an existing company refresh, and its bundled imports, release verification, folder, and local-source work beneath runtime skill preparation. Inventory children overlap their parent. | +| `skills.cache.acquire`, `skills.rows`, `skills.version.read`, `skills.repository.read`, `skills.version.materialize`, `skills.version.verify` | Dedicated connection/transaction startup plus advisory-lock acquisition, authorized skill rows, frozen version and repository reads, and exact runtime materialization/validation. Lock acquisition ends before the protected work; version verification is inside materialization. Only bounded file counts are added. | +| `skills.consume` | The caller's delivery and durable version-pinning callback while the cache lock remains held. | | `workspace_sync.prepare_host_current`, `.prepare_durable_seed`, `.prepare_adopt_remote` | Runtime preparation under the selected inbound mode, including snapshot and staging work. A warm mismatch may produce a second preparation; it is real repeated work. | | `workspace_sync.source_root`, `.repositories`, `.ignore_rules`, `.snapshot_git`, `.snapshot_baseline` | Physical source capture, managed repositories, ignore rules, Git metadata and baseline content snapshot. | | `workspace_sync.pack`, `.git_clone`, `.git_archive`, `.overlay_copy`, `.overlay_archive`, `.deleted_manifest` | Temporary shallow Git clone, its archive callback, selected working-tree overlay copy/archive, and the deleted-file manifest. The archive is inside the clone's lifetime; do not sum parent and child. | @@ -334,6 +344,33 @@ attempt or owning phase: | `response.resolve`, `.authorize`, `.add_comment`, `.transaction*`, `.row_lock`, `.write`, `.publish` | Response selection, existing authorization, comment transaction including commit or rollback, row wait, insert, and external publication enqueue. | | `execution.realtime` | Synchronous live-event and plugin publication dispatch. It does not measure browser receipt or paint. | +For bounded native OpenCode diagnosis, set +`PAPERCLIP_OPENCODE_PERFORMANCE_DIAGNOSTICS=1` as an agent/environment variable. +The existing configured-environment projection carries it into the native Runner. +It defaults off. The Runner creates an authenticated loopback OTLP sink and enables +the pinned OpenCode runtime's internal tracing. The sink discards logs, resource +attributes, span attributes, events, and unknown span names. It retains only closed +phase names, wall timestamps, and success/failure, with a 1 MiB request limit, +128 retained measurements, and 16 measurements per phase. No operator OTLP endpoint +or ingestion credential is passed to OpenCode. + +Available phases cover context/instruction loading, skill discovery, tool and model +resolution, model streaming (`ai.streamText`, including stream consumption), Git +discovery/default branch, snapshots, dependency installation, and plugin startup. +These intervals overlap; do not sum them as elapsed time. At each terminal turn, +already-received measurements travel in one `harness.diagnostic` event through the +existing durable PRP channel. Late exports may be absent; collection never waits +for a provider flush or delays terminal publication to complete the diagnostic. +Late spans from a prior completed turn are discarded at the next boundary. + +The server validates the closed fields again and records them under a foldable +`provider.runtime` group inside `native.session.execute`. The normal operator +endpoint gate controls Honeycomb export. The single diagnostic batch stays in the instance run log. Its OTel projection +does not write duplicate phase rows or await additional database work before +terminal consumption. Without an endpoint, no provider child spans are exported. Raw OpenCode OTLP must +never be sent directly to the operator endpoint: it can contain prompts and +authorization attributes before the loopback sink removes them. + Detail phases emit at most 16 spans of each name per attempt. Larger receipt and asset inventories continue under the containing group without unbounded per-row or per-file spans. Adding detail spans does not itself change work, query order, @@ -1954,6 +1991,12 @@ It carries no skill contents, identifiers, locations, or credentials. It uses th existing run performance events and operator-configured OpenTelemetry endpoint; no first-party Telemetry event is added. +The `skills.*` detail spans above distinguish inventory reconciliation and lock +acquisition from repository transfer and file validation. A repository-backed +skill's authored `SKILL.md` is not its complete runtime payload: the generated +discovery entrypoint includes the pinned repository under `.paperclip-repository`. +Measure the delivered bundle's file count and bytes when reproducing its cost. + Runtime preparation refreshes the company inventory once per listing. Local and catalog directories remain direct sources, so edits are visible on the next preparation. Explicit version selections still use their stored snapshots. diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/codex_provider.rs b/packages/paperclip-runner/runner/crates/runner-core/src/codex_provider.rs index 70aa6735095..3ec890aa246 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/codex_provider.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/codex_provider.rs @@ -43,6 +43,7 @@ const OPENCODE_PROVIDER_ENVIRONMENT_KEYS: &[&str] = &[ "PAPERCLIP_NATIVE_MCP_TOKEN", "PAPERCLIP_OPENCODE_PERMISSION_MODE", "PAPERCLIP_OPENCODE_RUNTIME_DIR", + "PAPERCLIP_OPENCODE_PERFORMANCE_DIAGNOSTICS", "PAPERCLIP_RUNNER_INSTANCE_ID", "PAPERCLIP_RUN_ID", "PAPERCLIP_NORMALIZED_SESSION_ID", diff --git a/packages/paperclip-runner/runner/crates/runner-core/src/provider_events.rs b/packages/paperclip-runner/runner/crates/runner-core/src/provider_events.rs index 5e1bc498751..755ad5402d5 100644 --- a/packages/paperclip-runner/runner/crates/runner-core/src/provider_events.rs +++ b/packages/paperclip-runner/runner/crates/runner-core/src/provider_events.rs @@ -671,6 +671,27 @@ fn measurement(value: &Value) -> Value { /// Converts Codex app-server notifications into provider-neutral PRP events. /// Provider-native envelopes are consumed here and never cross the PRP boundary. +fn provider_performance_spans(params: &Value) -> Vec { + let mut counts = std::collections::BTreeMap::<&str, usize>::new(); + params.get("spans").and_then(Value::as_array).into_iter().flatten().take(128).filter_map(|span| { + let name = span.get("name")?.as_str()?; + if !matches!(name, + "provider.context.environment" | "provider.context.instructions" | "provider.skills.discovery" + | "provider.tools.resolve" | "provider.model.resolve" | "provider.model.stream" + | "provider.workspace.snapshot.track" | "provider.workspace.snapshot.patch" | "provider.workspace.snapshot.diff" + | "provider.workspace.git.discover" | "provider.workspace.git.default_branch" + | "provider.dependencies.install" | "provider.plugins.initialize") { return None; } + let start = span.get("startedAtMs")?.as_f64()?; + let end = span.get("endedAtMs")?.as_f64()?; + if !start.is_finite() || !end.is_finite() || start < 0.0 || end < start || end - start > 86_400_000.0 { return None; } + let count = counts.entry(name).or_default(); + if *count >= 16 { return None; } + *count += 1; + Some(json!({"name":name,"startedAtMs":start,"endedAtMs":end, + "outcome":if span.get("outcome").and_then(Value::as_str)==Some("failed") {"failed"} else {"ok"}})) + }).collect() +} + pub fn normalize_codex_notification(method: &str, params: &Value) -> Vec { let mut events = Vec::new(); let push = |events: &mut Vec, @@ -685,6 +706,17 @@ pub fn normalize_codex_notification(method: &str, params: &Value) -> Vec { + let spans = provider_performance_spans(params); + if !spans.is_empty() { + push( + &mut events, + "harness.diagnostic", + EventPriority::P1, + json!({"code":"provider_performance_spans","spans":spans}), + ); + } + } "thread/compacted" => push( &mut events, "context.compacted", @@ -1464,6 +1496,37 @@ fn has_rfc_uri_scheme_prefix(value: &str) -> bool { mod tests { use super::*; + #[test] + fn performance_diagnostics_keep_only_bounded_content_free_measurements() { + let mut spans = vec![json!({"name":"private prompt","startedAtMs":1,"endedAtMs":2})]; + for _ in 0..200 { + spans.push( + json!({"name":"provider.model.stream","startedAtMs":1000,"endedAtMs":1010, + "outcome":"failed","authorization":"private","attributes":{"prompt":"private"}}), + ); + } + let events = + normalize_codex_notification("paperclip/providerPerformance", &json!({"spans":spans})); + assert_eq!(events.len(), 1); + assert_eq!(events[0].event_type, "harness.diagnostic"); + assert_eq!(events[0].priority, EventPriority::P1); + let rows = events[0].payload["spans"].as_array().unwrap(); + assert_eq!(rows.len(), 16); + assert_eq!( + rows[0], + json!({"name":"provider.model.stream","startedAtMs":1000.0,"endedAtMs":1010.0,"outcome":"failed"}) + ); + assert!(!events[0].payload.to_string().contains("private")); + assert!(normalize_codex_notification( + "paperclip/providerPerformance", + &json!({"spans":[ + {"name":"provider.model.stream","startedAtMs":10,"endedAtMs":1}, + {"name":"provider.model.stream","startedAtMs":0,"endedAtMs":86400001} + ]}) + ) + .is_empty()); + } + #[test] fn unrelated_information_retains_only_bounded_run_log_diagnostics() { let events = normalize_codex_notification( diff --git a/packages/paperclip-runner/src/cli/opencode-app-server-proxy.ts b/packages/paperclip-runner/src/cli/opencode-app-server-proxy.ts index 971c15f0e59..7737ef2ee20 100644 --- a/packages/paperclip-runner/src/cli/opencode-app-server-proxy.ts +++ b/packages/paperclip-runner/src/cli/opencode-app-server-proxy.ts @@ -30,6 +30,7 @@ import { withoutAmbientOpenCodeCommand, } from "./opencode-proxy-command.js"; import { OpenCodeProxyUsageLedger } from "./opencode-proxy-usage.js"; +import { parseProviderPerformanceSpans, PROVIDER_PERFORMANCE_DIAGNOSTIC } from "../contracts/provider-performance.js"; type RpcMessage = { id?: string | number; @@ -307,6 +308,13 @@ async function pumpEvents(opened: HarnessSession): Promise { ); activeTurnId = null; } else if (event.eventType === "harness.diagnostic") { + if (payload.code === PROVIDER_PERFORMANCE_DIAGNOSTIC) { + send({method: "paperclip/providerPerformance", params: { + threadId: opened.ids().driverSessionId, turnId: event.turnId, + spans: parseProviderPerformanceSpans(payload, Date.now()), + }}); + continue; + } send({ method: "warning", params: { diff --git a/packages/paperclip-runner/src/contracts/provider-performance.ts b/packages/paperclip-runner/src/contracts/provider-performance.ts new file mode 100644 index 00000000000..bc5c6ef279b --- /dev/null +++ b/packages/paperclip-runner/src/contracts/provider-performance.ts @@ -0,0 +1,43 @@ +/** Content-free provider diagnostics carried by the existing PRP diagnostic event. */ +export const PROVIDER_PERFORMANCE_DIAGNOSTIC = "provider_performance_spans"; +export const PROVIDER_PERFORMANCE_ENV = "PAPERCLIP_OPENCODE_PERFORMANCE_DIAGNOSTICS"; +export const MAX_PROVIDER_PERFORMANCE_SPANS = 128; +export const PROVIDER_PERFORMANCE_PHASES = [ + "provider.context.environment", "provider.context.instructions", "provider.skills.discovery", + "provider.tools.resolve", "provider.model.resolve", "provider.model.stream", + "provider.workspace.snapshot.track", "provider.workspace.snapshot.patch", "provider.workspace.snapshot.diff", + "provider.workspace.git.discover", "provider.workspace.git.default_branch", + "provider.dependencies.install", "provider.plugins.initialize", +] as const; +export type ProviderPerformancePhase = typeof PROVIDER_PERFORMANCE_PHASES[number]; +export interface ProviderPerformanceSpan { + name: ProviderPerformancePhase; + startedAtMs: number; + endedAtMs: number; + outcome: "ok" | "failed"; +} + +const names = new Set(PROVIDER_PERFORMANCE_PHASES); +const maxDurationMs = 24 * 60 * 60 * 1000; + +/** Project fields rather than forwarding provider attributes or untrusted diagnostic data. */ +export function parseProviderPerformanceSpans(payload: unknown, observedAtMs: number): ProviderPerformanceSpan[] { + if (!payload || typeof payload !== "object" || Array.isArray(payload)) return []; + const diagnostic = payload as Record; + if (diagnostic.code !== PROVIDER_PERFORMANCE_DIAGNOSTIC || !Array.isArray(diagnostic.spans)) return []; + const counts = new Map(); + return diagnostic.spans.slice(0, MAX_PROVIDER_PERFORMANCE_SPANS).flatMap((value): ProviderPerformanceSpan[] => { + if (!value || typeof value !== "object" || Array.isArray(value)) return []; + const row = value as Record; + const { name, startedAtMs, endedAtMs } = row; + if (typeof name !== "string" || !names.has(name) || typeof startedAtMs !== "number" || typeof endedAtMs !== "number" + || !Number.isFinite(startedAtMs) || !Number.isFinite(endedAtMs) + || startedAtMs < observedAtMs - maxDurationMs || endedAtMs > observedAtMs + 1000 + || endedAtMs < startedAtMs || endedAtMs - startedAtMs > maxDurationMs) return []; + const count = counts.get(name) ?? 0; + if (count >= 16) return []; + counts.set(name, count + 1); + return [{ name: name as ProviderPerformancePhase, startedAtMs, endedAtMs, + outcome: row.outcome === "failed" ? "failed" : "ok" }]; + }); +} diff --git a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts index c209a37bf95..4f09db52dd9 100644 --- a/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts +++ b/packages/paperclip-runner/src/control-plane/durable-prp-control-plane.ts @@ -3503,6 +3503,7 @@ const runnerExplicitProviderEnvironmentKeys = [ "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE", "PAPERCLIP_OPENCODE_PERMISSION_MODE", "PAPERCLIP_OPENCODE_RUNTIME_DIR", + "PAPERCLIP_OPENCODE_PERFORMANCE_DIAGNOSTICS", "PAPERCLIP_RUNNER_INSTANCE_ID", "PAPERCLIP_RUN_ID", "PAPERCLIP_NORMALIZED_SESSION_ID", diff --git a/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts b/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts index bf2a8bed9d5..4505b29d687 100644 --- a/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts +++ b/packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts @@ -24,6 +24,8 @@ import { pipeline } from "node:stream/promises"; import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path"; import { parseOpenCodeReasoningMode, type OpenCodeReasoningMode } from "./reasoning-mode.js"; +import { startOpenCodePerformanceDiagnostics } from "./performance-diagnostics.js"; +import { PROVIDER_PERFORMANCE_ENV } from "../../contracts/provider-performance.js"; import { annotateOmittedProviderText, parseOpenCodeSseFrames } from "./sse-frames.js"; import { githubCredentialEnvironment } from "../../github-credential-environment.js"; @@ -217,6 +219,7 @@ interface OpenCodeRuntime { bridge: OpenCodeMcpBridge; trace: ProviderTraceFileSink | null; sensitiveValues: readonly string[]; + performanceDiagnostics: Awaited> | null; close(input?: { finalizeTrace?: boolean; reason?: string | null; @@ -520,6 +523,7 @@ class OpenCodeHarnessSession implements HarnessSession { #activeTraceEmittedEventIds: string[] = []; #sourceSequence: number; #activeTurnId: string | null; + #performanceBoundaryMs = 0; #result: PrpStructuredRunResult | null; #resultFingerprint: string | null; #resultCallId: string | null; @@ -2133,6 +2137,11 @@ class OpenCodeHarnessSession implements HarnessSession { }); return; } + if (["turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"].includes(eventType)) { + const performance = this.#runtime.performanceDiagnostics?.take(this.#performanceBoundaryMs); + this.#performanceBoundaryMs = this.#now().getTime(); + if (performance) this.#emit("harness.diagnostic", performance, refs); + } const sourceSeq = ++this.#sourceSequence; const event: PrpEvent = { schema: "paperclip.prp.event.v1", @@ -2349,6 +2358,15 @@ async function startRuntime(input: { input.trace?.addSensitiveValues([providerProxy.token]); } let child: ChildProcess | undefined; + // Failure to collect diagnostics must not prevent the requested work. + const performanceDiagnostics = input.options.environment?.[PROVIDER_PERFORMANCE_ENV] === "1" + ? await startOpenCodePerformanceDiagnostics().catch(() => null) : null; + if (performanceDiagnostics) { + const values = [performanceDiagnostics.environment.OTEL_EXPORTER_OTLP_HEADERS, + performanceDiagnostics.environment.OTEL_EXPORTER_OTLP_HEADERS.replace("Authorization=Bearer ", "")]; + sensitiveValues.push(...values); + input.trace?.addSensitiveValues(values); + } let launchPrepared = false; const releaseExecutable = () => { if (!launchPrepared) return; @@ -2366,6 +2384,7 @@ async function startRuntime(input: { small_model: input.options.model, share: "disabled", autoupdate: false, + ...(performanceDiagnostics ? { experimental: { openTelemetry: true } } : {}), // The configured entry is already composed exactly once into the session // system prompt; siblings remain available through the read-only root. instructions: [], @@ -2450,6 +2469,7 @@ async function startRuntime(input: { OPENCODE_DISABLE_DEFAULT_PLUGINS: "true", OPENCODE_SERVER_USERNAME: username, OPENCODE_SERVER_PASSWORD: password, + ...performanceDiagnostics?.environment, ...(providerProxy ? { NO_PROXY: [input.options.environment?.no_proxy ?? input.options.environment?.NO_PROXY, "127.0.0.1", "localhost"].filter(Boolean).join(",") } : {}), }, ); @@ -2547,6 +2567,7 @@ async function startRuntime(input: { bridge, trace: input.trace, sensitiveValues, + performanceDiagnostics, close: async (closeInput = {}) => { await providerProxy?.close(); await bridge.close().catch(() => {}); @@ -2570,6 +2591,7 @@ async function startRuntime(input: { } await waitForExit(providerChild, 2_000); } + await performanceDiagnostics?.close().catch(() => {}); await rm(join(configHome, "opencode", "opencode.json"), { force: true, }).catch(() => undefined); @@ -2580,6 +2602,7 @@ async function startRuntime(input: { }, }; } catch (error) { + await performanceDiagnostics?.close().catch(() => {}); await providerProxy?.close(); await bridge.close().catch(() => {}); child?.kill("SIGKILL"); diff --git a/packages/paperclip-runner/src/drivers/opencode/performance-diagnostics.test.ts b/packages/paperclip-runner/src/drivers/opencode/performance-diagnostics.test.ts new file mode 100644 index 00000000000..46da01dc64d --- /dev/null +++ b/packages/paperclip-runner/src/drivers/opencode/performance-diagnostics.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it } from "vitest"; +import { parseProviderPerformanceSpans, PROVIDER_PERFORMANCE_DIAGNOSTIC } from "../../contracts/provider-performance.js"; +import { startOpenCodePerformanceDiagnostics } from "./performance-diagnostics.js"; + +function batch(spans: unknown[]) { return { resourceSpans: [{resource:{attributes:[{key:"secret",value:"credential"}]},scopeSpans:[{spans}]}]}; } +function span(name = "ai.streamText", extra = {}) { + const now=Date.now(); + return {name,startTimeUnixNano:String(BigInt(now-10)*1000000n),endTimeUnixNano:String(BigInt(now)*1000000n), + attributes:[{key:"Authorization",value:{stringValue:"Bearer private"}},{key:"prompt",value:{stringValue:"private task"}}], + events:[{name:"private content"}],...extra}; +} + +describe("OpenCode content-free performance sink",()=>{ + it("accepts authenticated loopback OTLP and projects only closed phase names and timings",async()=>{ + const sink=await startOpenCodePerformanceDiagnostics(); + const url=sink.environment.OTEL_EXPORTER_OTLP_ENDPOINT; + const headers={Authorization:sink.environment.OTEL_EXPORTER_OTLP_HEADERS.slice("Authorization=".length)}; + try { + expect((await fetch(url+"/v1/traces",{method:"POST",body:JSON.stringify(batch([span()]))})).status).toBe(401); + expect(sink.take()).toBeNull(); + expect((await fetch(url+"/v1/traces",{method:"POST",headers,body:JSON.stringify(batch([ + span(),span("Snapshot.track",{status:{code:2}}),span("private-provider-name"),span("__proto__"),span("toString"), + ]))})).status).toBe(200); + const diagnostic=sink.take()!; + expect(diagnostic.code).toBe(PROVIDER_PERFORMANCE_DIAGNOSTIC); + expect(diagnostic.spans.map(s=>[s.name,s.outcome])).toEqual([["provider.model.stream","ok"],["provider.workspace.snapshot.track","failed"]]); + expect(diagnostic.spans[0].endedAtMs-diagnostic.spans[0].startedAtMs).toBeCloseTo(10, 2); + expect(JSON.stringify(diagnostic)).not.toMatch(/private|Authorization|prompt|credential/); + expect(Object.keys(diagnostic.spans[0]).sort()).toEqual(["endedAtMs","name","outcome","startedAtMs"]); + expect(sink.take()).toBeNull(); + expect((await fetch(url+"/v1/logs",{method:"POST",headers,body:'{"private":"discard"}'})).status).toBe(200); + expect(sink.take()).toBeNull(); + } finally {await sink.close();} + await expect(fetch(url+"/v1/traces")).rejects.toThrow(); + }); + + it("bounds bodies, malformed timestamps and repeated spans and drops prior-turn exports",async()=>{ + const sink=await startOpenCodePerformanceDiagnostics(); + const url=sink.environment.OTEL_EXPORTER_OTLP_ENDPOINT; + const headers={Authorization:sink.environment.OTEL_EXPORTER_OTLP_HEADERS.slice("Authorization=".length)}; + const post=(body:string)=>fetch(url+"/v1/traces",{method:"POST",headers,body}); + try { + expect((await post("x".repeat(1024*1024+1))).status).toBe(413); + expect((await post("invalid json")).status).toBe(400); + expect((await post(JSON.stringify(batch([ + span("ai.streamText",{endTimeUnixNano:"NaN"}),span("ai.streamText",{endTimeUnixNano:"1"}), + ...Array.from({length:200},()=>span()), + ])))).status).toBe(200); + expect(sink.take()!.spans).toHaveLength(16); + await post(JSON.stringify(batch([span()]))); + expect(sink.take(Date.now()+100)).toBeNull(); + }finally{await sink.close();} + }); + + it("validates the shared diagnostic again before server export",()=>{ + const now=Date.now(); + const safe={name:"provider.model.stream",startedAtMs:now-20,endedAtMs:now,outcome:"ok",prompt:"private"}; + const parsed=parseProviderPerformanceSpans({code:PROVIDER_PERFORMANCE_DIAGNOSTIC,spans:[ + safe,{...safe,name:"private"},{...safe,startedAtMs:Infinity},{...safe,endedAtMs:now+2000}, + {...safe,startedAtMs:now-86400001},{...safe,endedAtMs:now-30}, + ]},now); + expect(parsed).toEqual([{name:safe.name,startedAtMs:now-20,endedAtMs:now,outcome:"ok"}]); + expect(parseProviderPerformanceSpans({code:"other",spans:[safe]},now)).toEqual([]); + }); +}); diff --git a/packages/paperclip-runner/src/drivers/opencode/performance-diagnostics.ts b/packages/paperclip-runner/src/drivers/opencode/performance-diagnostics.ts new file mode 100644 index 00000000000..5727e8a3f48 --- /dev/null +++ b/packages/paperclip-runner/src/drivers/opencode/performance-diagnostics.ts @@ -0,0 +1,103 @@ +import { randomBytes, timingSafeEqual } from "node:crypto"; +import { createServer } from "node:http"; +import { + MAX_PROVIDER_PERFORMANCE_SPANS, PROVIDER_PERFORMANCE_DIAGNOSTIC, + type ProviderPerformancePhase, type ProviderPerformanceSpan, +} from "../../contracts/provider-performance.js"; + +const phases: Readonly> = { + "SystemPrompt.environment": "provider.context.environment", + "Instruction.system": "provider.context.instructions", + "Skill.discovery": "provider.skills.discovery", + "SessionTools.resolve": "provider.tools.resolve", + "Provider.getModel": "provider.model.resolve", + "ai.streamText": "provider.model.stream", + "Snapshot.track": "provider.workspace.snapshot.track", + "Snapshot.patch": "provider.workspace.snapshot.patch", + "Snapshot.diffFull": "provider.workspace.snapshot.diff", + "Git.repo.discover": "provider.workspace.git.discover", + "Git.defaultBranch": "provider.workspace.git.default_branch", + "Npm.install": "provider.dependencies.install", + "PluginInternal.boot": "provider.plugins.initialize", +}; +const maxBodyBytes = 1024 * 1024; + +function object(value: unknown): Record { + return value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; +} + +/** OpenCode's raw OTLP can contain authorization and prompt attributes. None leave this sink. */ +export async function startOpenCodePerformanceDiagnostics() { + const token = randomBytes(32).toString("hex"); + const authorization = Buffer.from(`Bearer ${token}`); + const spans: ProviderPerformanceSpan[] = []; + const counts = new Map(); + const server = createServer((request, response) => { + const provided = Buffer.from(request.headers.authorization ?? ""); + if (provided.length !== authorization.length || !timingSafeEqual(provided, authorization)) { + request.resume(); response.writeHead(401).end(); return; + } + if (request.method !== "POST" || !["/v1/traces", "/v1/logs"].includes(request.url ?? "")) { + request.resume(); response.writeHead(404).end(); return; + } + let bytes = 0; + const chunks: Buffer[] = []; + request.on("data", (chunk: Buffer) => { + bytes += chunk.length; + if (bytes <= maxBodyBytes && request.url === "/v1/traces") chunks.push(chunk); + else chunks.length = 0; + }); + request.on("error", () => response.destroy()); + request.on("end", () => { + if (bytes > maxBodyBytes) { response.writeHead(413).end(); return; } + if (request.url === "/v1/logs") { response.writeHead(200).end("{}"); return; } + try { + const batch = object(JSON.parse(Buffer.concat(chunks).toString("utf8"))); + for (const resource of Array.isArray(batch.resourceSpans) ? batch.resourceSpans : []) { + for (const scope of Array.isArray(object(resource).scopeSpans) ? object(resource).scopeSpans as unknown[] : []) { + for (const value of Array.isArray(object(scope).spans) ? object(scope).spans as unknown[] : []) { + const row = object(value); + const name = typeof row.name === "string" && Object.hasOwn(phases, row.name) ? phases[row.name] : undefined; + if (!name || spans.length >= MAX_PROVIDER_PERFORMANCE_SPANS || (counts.get(name) ?? 0) >= 16) continue; + const startedAtMs = Number(row.startTimeUnixNano) / 1e6; + const endedAtMs = Number(row.endTimeUnixNano) / 1e6; + const now = Date.now(); + if (!Number.isFinite(startedAtMs) || !Number.isFinite(endedAtMs) || startedAtMs < now - 86400000 + || endedAtMs < startedAtMs || endedAtMs > now + 1000) continue; + spans.push({name, startedAtMs, endedAtMs, outcome: object(row.status).code === 2 ? "failed" : "ok"}); + counts.set(name, (counts.get(name) ?? 0) + 1); + } + } + } + response.writeHead(200, {"Content-Type":"application/json"}).end("{}"); + } catch { response.writeHead(400).end(); } + }); + }); + server.requestTimeout = 2000; + server.headersTimeout = 2000; + server.maxConnections = 2; + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", () => { server.off("error", reject); resolve(); }); + }); + const address = server.address(); + if (!address || typeof address === "string") { server.close(); throw new Error("OpenCode diagnostics did not bind loopback"); } + return { + environment: { + OTEL_EXPORTER_OTLP_ENDPOINT: `http://127.0.0.1:${address.port}`, + OTEL_EXPORTER_OTLP_PROTOCOL: "http/json", + // OpenCode's Effect logger reads literal values; its trace exporter receives the same map. + OTEL_EXPORTER_OTLP_HEADERS: `Authorization=Bearer ${token}`, + OTEL_BSP_SCHEDULE_DELAY: "100", + }, + take(sinceMs = 0): {code: string; spans: ProviderPerformanceSpan[]} | null { + const collected = spans.splice(0).filter(span => span.startedAtMs >= sinceMs); + counts.clear(); + return collected.length ? {code: PROVIDER_PERFORMANCE_DIAGNOSTIC, spans: collected} : null; + }, + async close() { + spans.length = 0; + await new Promise(resolve => { server.close(() => resolve()); server.closeAllConnections(); }); + }, + }; +} diff --git a/packages/paperclip-runner/src/index.ts b/packages/paperclip-runner/src/index.ts index 8a35f307a32..38c34e26872 100644 --- a/packages/paperclip-runner/src/index.ts +++ b/packages/paperclip-runner/src/index.ts @@ -4,6 +4,7 @@ export { CURSOR_DISTRIBUTION_PINS } from "./drivers/acpx/generated-profiles.js"; export * from "./contracts/control-plane-port.js"; export * from "./contracts/completion-result.js"; export * from "./contracts/codex.js"; +export * from "./contracts/provider-performance.js"; export * from "./contracts/durable-recovery.js"; export * from "./contracts/harness-driver.js"; export * from "./contracts/local-runner.js"; diff --git a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts index d2b054ef787..26a3e0b20b4 100644 --- a/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts +++ b/packages/paperclip-runner/src/live/runnerd-codex-transport.test.ts @@ -1,5 +1,6 @@ import { bindRunnerLaunchResources, createRunnerProviderLaunch, runnerLaunchRequirementsDigest, type PreparedRunnerProviderLaunch, type RunnerProviderLaunchRequirements } from "./runner-provider-launch.js"; import { coldAdmissionTimeoutMs, waitForRunnerCommand } from "./runnerd-codex-transport.js"; +import { configuredEnvironmentProjection } from "../configured-environment.js"; import { chmod, cp, @@ -2086,6 +2087,9 @@ it("preserves OpenCode runtime bindings when a durable runner is respawned", () environment: { PATH: "/bin", OPENROUTER_API_KEY: "test-provider-key", + ...configuredEnvironmentProjection({ PAPERCLIP_OPENCODE_PERFORMANCE_DIAGNOSTICS: "1" }), + OTEL_EXPORTER_OTLP_ENDPOINT: "https://must-not-reach-opencode.invalid", + OTEL_EXPORTER_OTLP_HEADERS: "Authorization=private", HOME: "/host/home", CODEX_HOME: "/host/codex-home", DATABASE_URL: "must-not-reach-runnerd", @@ -2115,7 +2119,10 @@ it("preserves OpenCode runtime bindings when a durable runner is respawned", () PAPERCLIP_NORMALIZED_SESSION_ID: "session-1", PAPERCLIP_NATIVE_RUNTIME_CONTEXT_PATH: "/isolated/runtime-context.json", OPENROUTER_API_KEY: "test-provider-key", + PAPERCLIP_OPENCODE_PERFORMANCE_DIAGNOSTICS: "1", }); + expect(environment.OTEL_EXPORTER_OTLP_ENDPOINT).toBeUndefined(); + expect(environment.OTEL_EXPORTER_OTLP_HEADERS).toBeUndefined(); expect(environment.HOME).toBeUndefined(); expect(environment.CODEX_HOME).toBeUndefined(); expect(environment.DATABASE_URL).toBeUndefined(); @@ -9066,7 +9073,9 @@ it.each([ opencodeProxySha256: digest(proxy), providerNodeCommand: providerNode, providerNodeCommandSha256: digest(providerNode), - environment: { PATH: process.env.PATH, OPENROUTER_API_KEY: "fixture-key" }, + environment: { PATH: process.env.PATH, OPENROUTER_API_KEY: "fixture-key", + ...(supportsReasoning ? configuredEnvironmentProjection({ PAPERCLIP_OPENCODE_PERFORMANCE_DIAGNOSTICS: "1" }) : {}), + }, }); const task = createCodexTaskEnvelope({ objective: "Preserve the prepared task.", contractRevision: "prepared-v1", @@ -9113,6 +9122,14 @@ it.each([ expect(events.find(event => event.eventType === "session.started")?.payload.context).toMatchObject({ model }); expect(completionCalls).toBe(2); expect(events.filter(event => event.eventType === "run.result.proposed")).toHaveLength(1); + const performance = events.filter(event => event.eventType === "harness.diagnostic" && event.payload.code === "provider_performance_spans"); + expect(performance).toHaveLength(supportsReasoning ? 1 : 0); + if (supportsReasoning) { + expect(performance[0].payload.spans).toEqual([{ + name: "provider.model.stream", startedAtMs: expect.any(Number), endedAtMs: expect.any(Number), outcome: "ok", + }]); + expect(JSON.stringify(performance)).not.toContain("private-performance-sentinel"); + } const sessionRoots = (await readdir(runtime, { withFileTypes: true })).filter((entry) => entry.isDirectory()); expect(sessionRoots).toHaveLength(1); const requests = (await readFile(join(runtime, sessionRoots[0]!.name, "data/fake-prompt-requests.ndjson"), "utf8")).trim().split("\n").map((line) => JSON.parse(line)); diff --git a/packages/paperclip-runner/test/fixtures/fake-opencode-server.mjs b/packages/paperclip-runner/test/fixtures/fake-opencode-server.mjs index dee873d0da3..412d602171a 100644 --- a/packages/paperclip-runner/test/fixtures/fake-opencode-server.mjs +++ b/packages/paperclip-runner/test/fixtures/fake-opencode-server.mjs @@ -128,6 +128,24 @@ let promptTurnSeq = 0; // sealed. let lateStragglerRemaining = 0; function emit(value) { + if (value.type === "session.idle" && runtimeConfig.experimental?.openTelemetry) { + const now=Date.now(); + const headers=Object.fromEntries((process.env.OTEL_EXPORTER_OTLP_HEADERS??"").split(",").map(entry=>{ + const i=entry.indexOf("=");return [entry.slice(0,i),entry.slice(i+1)]; + })); + void fetch(`${process.env.OTEL_EXPORTER_OTLP_ENDPOINT}/v1/traces`,{method:"POST",headers, + body:JSON.stringify({resourceSpans:[{scopeSpans:[{spans:[{name:"ai.streamText", + startTimeUnixNano:String(BigInt(now-22)*1000000n),endTimeUnixNano:String(BigInt(now)*1000000n), + attributes:[{key:"prompt",value:{stringValue:"private-performance-sentinel"}}], + }]}]}]})}).then(response=>{ + if(!response.ok)throw new Error(`Performance fixture rejected: ${response.status}`); + emitFrame(value); + }).catch(error=>{process.stderr.write(String(error));process.exit(1)}); + return; + } + emitFrame(value); +} +function emitFrame(value) { const scoped = promptTurnSeq > 0 && typeof value.id === "string" ? { ...value, id: `${value.id}#${promptTurnSeq}` } diff --git a/server/scripts/benchmark-native-skill-preparation.ts b/server/scripts/benchmark-native-skill-preparation.ts new file mode 100644 index 00000000000..da1310afdb0 --- /dev/null +++ b/server/scripts/benchmark-native-skill-preparation.ts @@ -0,0 +1,260 @@ +/** Real skill resolution, PostgreSQL, and filesystem work; no provider is started. */ +import assert from "node:assert/strict"; +import { createHash, randomUUID } from "node:crypto"; +import { execFileSync } from "node:child_process"; +import { promises as fs } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { connect, createServer, type Socket } from "node:net"; +import { context, trace } from "@opentelemetry/api"; +import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks"; +import { InMemorySpanExporter, SimpleSpanProcessor, TracerProvider } from "@opentelemetry/sdk-trace"; +import { resourceFromAttributes } from "@opentelemetry/resources"; +import { eq, sql } from "drizzle-orm"; +import { authUsers, companyMemberships, companySkillSources, heartbeatRuns, projects, projectSkillSources, + companies, companySkills, companySkillVersions, companySkillRepositorySnapshots, + applyPendingMigrations, closeRegisteredClients, createDb, startEmbeddedPostgresTestDatabase } from "../../packages/db/src/index.js"; +import type { CompanySkillVersionFileInventoryEntry } from "@paperclipai/shared"; +import { createRunPreparationTiming, withRunExecutionTiming } from "../src/services/execution-preparation-timing.js"; +import { repositorySkillProjection } from "../src/services/skill-repository-package.js"; +import { skillFileBytes, skillSnapshotHash } from "../src/services/skill-snapshot.js"; + +const argument = (name: string) => process.argv.find(value => value.startsWith(`${name}=`))?.slice(name.length + 1); +const exportOtlp = argument("--export-otlp") === "true"; +const authenticated = argument("--actor") === "agent"; +const stagingShape = argument("--staging-shape") === "true"; +// This standalone benchmark owns its tracer. Load the service graph with the +// app-wide SDK disabled, then restore the operator's export configuration. +const operatorEndpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT; +delete process.env.OTEL_EXPORTER_OTLP_ENDPOINT; +let companySkillService: typeof import("../src/services/company-skills.js").companySkillService; +let withSkillActor: typeof import("../src/services/skill-access.js").withSkillActor; +let createAgentLifecycle: typeof import("../src/services/agent-lifecycle.js").createAgentLifecycle; +try { + ({ companySkillService } = await import("../src/services/company-skills.js")); + ({ withSkillActor } = await import("../src/services/skill-access.js")); + ({ createAgentLifecycle } = await import("../src/services/agent-lifecycle.js")); +} +finally { + if (operatorEndpoint !== undefined) process.env.OTEL_EXPORTER_OTLP_ENDPOINT = operatorEndpoint; +} +const sourceRevision = execFileSync("git", ["rev-parse", "HEAD"], { + cwd: fileURLToPath(new URL("../../", import.meta.url)), encoding: "utf8", +}).trim(); +const sourceHash = createHash("sha256"); +for (const file of [import.meta.url, new URL("../src/services/company-skills.ts", import.meta.url), + new URL("../src/services/skill-version-cache.ts", import.meta.url), new URL("../src/services/execution-preparation-timing.ts", import.meta.url)]) { + sourceHash.update(await fs.readFile(new URL(file))); +} +const sourceChangesHash = sourceHash.digest("hex"); +if (exportOtlp) assert.ok(process.env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim(), "OTLP export requires an operator-configured endpoint"); +const snapshotFile = argument("--snapshot-file"); +const entrypoint = argument("--entrypoint") ?? "skills/diagnostic/SKILL.md"; +const files: CompanySkillVersionFileInventoryEntry[] = snapshotFile + ? JSON.parse(await fs.readFile(snapshotFile, "utf8")) + : [{ path: entrypoint, kind: "skill", content: "---\nname: diagnostic\ndescription: Native preparation benchmark\n---\nReport the model ID.\n" }, + ...Array.from({ length: 207 }, (_, index) => ({ path: `assets/${index}.txt`, kind: "reference" as const, content: "x".repeat(52_000) }))]; +const projected = repositorySkillProjection(files, entrypoint); +const previous = { home: process.env.PAPERCLIP_HOME, instance: process.env.PAPERCLIP_INSTANCE_ID, endpoint: process.env.OTEL_EXPORTER_OTLP_ENDPOINT }; +const home = await fs.mkdtemp(path.join(os.tmpdir(), "native-skill-benchmark-")); +let provider: TracerProvider | undefined; +let manager: AsyncLocalStorageContextManager | undefined; +let database: Awaited> | undefined; +let db: ReturnType | undefined; +let proxy: ReturnType | null = null; +const connections = new Set(); +try { + process.env.PAPERCLIP_HOME = home; + process.env.PAPERCLIP_INSTANCE_ID = "default"; + process.env.OTEL_EXPORTER_OTLP_ENDPOINT = exportOtlp ? previous.endpoint : "http://127.0.0.1:4318"; + const exporter = new InMemorySpanExporter(); + const processors = [new SimpleSpanProcessor({ exporter })]; + const exportResults: number[] = []; + if (exportOtlp) { + const packages: Record = { grpc: "@opentelemetry/exporter-trace-otlp-grpc", + "http/protobuf": "@opentelemetry/exporter-trace-otlp-proto", "http/json": "@opentelemetry/exporter-trace-otlp-http" }; + const packageName = packages[process.env.OTEL_EXPORTER_OTLP_PROTOCOL ?? "grpc"]; + assert.ok(packageName, "Unsupported OTLP protocol"); + const { OTLPTraceExporter } = await import(packageName); + const live = new OTLPTraceExporter(); + processors.push(new SimpleSpanProcessor({ exporter: { + export: (spans, callback) => live.export(spans, (result: { code: number }) => { exportResults.push(result.code); callback(result); }), + shutdown: () => live.shutdown(), + } })); + } + provider = new TracerProvider({ spanProcessors: processors, resource: resourceFromAttributes({ + "service.name": process.env.OTEL_SERVICE_NAME || "paperclip", + "service.version": `local-skill-bench-${sourceChangesHash.slice(0, 12)}`, + "deployment.environment.name": "local-diagnostic", + }) }); + manager = new AsyncLocalStorageContextManager().enable(); + assert.ok(context.setGlobalContextManager(manager)); + assert.ok(trace.setGlobalTracerProvider(provider)); + async function startDatabase() { + const port = argument("--postgres-port"); + if (!port) return startEmbeddedPostgresTestDatabase("native-skill-benchmark-"); + assert.match(port, /^\d{1,5}$/); + assert.ok(Number(port) > 0 && Number(port) <= 65535); + const username = argument("--postgres-user") ?? os.userInfo().username; + const adminUrl = `postgres://${encodeURIComponent(username)}@127.0.0.1:${port}/postgres`; + const name = `native_skill_bench_${randomUUID().replaceAll("-", "")}`; + const connectionString = `postgres://${encodeURIComponent(username)}@127.0.0.1:${port}/${name}`; + const admin = createDb(adminUrl, { maxConnections: 1 }).$client; + try { await admin.unsafe(`CREATE DATABASE "${name}"`); } + finally { await admin.end({ timeout: 1 }); } + const cleanup = async () => { + await closeRegisteredClients(connectionString); + const cleanupAdmin = createDb(adminUrl, { maxConnections: 1 }).$client; + try { await cleanupAdmin.unsafe(`DROP DATABASE "${name}"`); } + finally { await cleanupAdmin.end({ timeout: 1 }); } + }; + try { await applyPendingMigrations(connectionString); } + catch (error) { await cleanup(); throw error; } + return { connectionString, cleanup }; + } + database = await startDatabase(); + const networkDelayMs = Number(argument("--network-delay-ms") ?? 0); + assert.ok(Number.isFinite(networkDelayMs) && networkDelayMs >= 0 && networkDelayMs <= 100); + const target = new URL(database.connectionString); + const upstreamPort = Number(target.port); + proxy = networkDelayMs ? createServer(client => { + const upstream = connect({ host: "127.0.0.1", port: upstreamPort }); + for (const socket of [client, upstream]) { + socket.setNoDelay(true); + connections.add(socket); + socket.on("error", () => { client.destroy(); upstream.destroy(); }); + socket.on("close", () => { connections.delete(socket); }); + } + const relay = (source: Socket, destination: Socket) => { + let pendingBytes = 0; + source.on("data", chunk => { + pendingBytes += chunk.length; + if (pendingBytes >= 2 * 1024 * 1024) source.pause(); + setTimeout(() => { + pendingBytes -= chunk.length; + if (destination.destroyed) return; + const writable = destination.write(chunk); + if (writable && pendingBytes < 2 * 1024 * 1024) source.resume(); + }, networkDelayMs); + }); + destination.on("drain", () => { if (pendingBytes < 2 * 1024 * 1024) source.resume(); }); + source.on("end", () => setTimeout(() => destination.end(), networkDelayMs)); + }; + relay(client, upstream); relay(upstream, client); + }) : null; + if (proxy) { + const server = proxy; + await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); }); + const address = server.address(); + assert.ok(address && typeof address !== "string"); + target.port = String(address.port); + } + db = createDb(target.href); + const companyId = randomUUID(); + const agentId = randomUUID(); + const userId = randomUUID(); + const skillId = randomUUID(); + const key = `company/${companyId}/diagnostic`; + const samples: unknown[] = []; + let rootPoolQueries = 0; + db.$client.options.debug = () => { rootPoolQueries++; }; + await db.insert(companies).values({ id: companyId, name: "Native preparation benchmark", issuePrefix: "BENCH" }); + if (authenticated) { + await createAgentLifecycle(db).requestHire(companyId, { + id: agentId, name: "Diagnostic reader", adapterType: "paperclip_runner", status: "paused", + }, { runnerResolved: true }); + await db.insert(authUsers).values({ id: userId, name: "Diagnostic owner", email: `${userId}@example.invalid`, createdAt: new Date(), updatedAt: new Date() }); + await db.insert(companyMemberships).values([ + { companyId, principalType: "agent", principalId: agentId, membershipRole: "member" }, + { companyId, principalType: "user", principalId: userId, membershipRole: "owner" }, + ]); + } + if (stagingShape) { + // Match observed staging cardinalities without copying unrelated company content. + const projectRows = await db.insert(projects).values(Array.from({ length: 14 }, (_, i) => ({ companyId, name: `Fixture ${i}` }))).returning(); + const sourceRows = await db.insert(companySkillSources).values(Array.from({ length: 10 }, (_, i) => ({ + companyId, repositoryUrl: `https://example.invalid/fixture-${i}`, fullName: `fixture/${i}`, trackingRef: "main", + accessScope: i < 4 ? "projects" as const : "company" as const, + }))).returning(); + await db.insert(projectSkillSources).values(Array.from({ length: 8 }, (_, i) => ({ companyId, + projectId: projectRows[i % 5]!.id, sourceId: sourceRows[i]!.id, + repositoryUrl: sourceRows[i]!.repositoryUrl, trackingRef: "main", status: "ready" as const, + }))); + await db.insert(companySkills).values(Array.from({ length: 155 }, (_, i) => ({ companyId, + key: `fixture/unselected-${i}`, slug: `unselected-${i}`, name: `Unselected ${i}`, sourceType: "github", + sourceLocator: "https://example.invalid/immutable-fixture", markdown: "x".repeat(7_330), + accessSourceId: sourceRows[i % sourceRows.length]!.id, + }))); + await db.insert(companySkills).values({ companyId, key: "fixture/catalog", slug: "catalog", name: "Unselected catalog", sourceType: "catalog", markdown: "x".repeat(1_578) }); + } + await db.insert(companySkills).values({ id: skillId, companyId, key, slug: "diagnostic", name: "Diagnostic", + markdown: files.find(file => file.path === entrypoint)!.content, sourceType: "github", + sourceLocator: "https://example.invalid/immutable-fixture", metadata: { packageMode: "repository", snapshotHash: "fixture" } }); + const [snapshot] = await db.insert(companySkillRepositorySnapshots).values({ companyId, contentHash: skillSnapshotHash(files), fileInventory: files }).returning(); + const [version] = await db.insert(companySkillVersions).values({ companyId, companySkillId: skillId, revisionNumber: 1, + repositorySnapshotId: snapshot!.id, repositorySkillPath: entrypoint }).returning(); + await db.update(companySkills).set({ currentVersionId: version!.id }).where(eq(companySkills.id, skillId)); + const benchmarkDb = db; + const service = companySkillService(db); + for (const label of ["cold", "warm-1", "warm-2", "warm-new-service"]) { + exporter.reset(); + rootPoolQueries = 0; + const selected: ReturnType = label === "warm-new-service" ? companySkillService(db) : service; + const runId = randomUUID(); + if (authenticated) await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", responsibleUserId: userId, contextSnapshot: { executionPolicy: {} } }); + rootPoolQueries = 0; + const measuredStarted = performance.now(); + const resolve = () => selected.withRuntimeSkillEntries(companyId, { + onlyKeys: new Set([key]), versionSelections: new Map([[key, version!.id]]), snapshotLatest: true, + }, async entries => { + if (authenticated) await benchmarkDb.update(heartbeatRuns).set({ contextSnapshot: sql`coalesce(${heartbeatRuns.contextSnapshot}, '{}'::jsonb) || ${JSON.stringify({ skillVersions: { [key]: version!.id }, skillSelectionSnapshot: true })}::jsonb` }).where(eq(heartbeatRuns.id, runId)); + return entries; + }); + const entries: Awaited> = await withRunExecutionTiming(runId, () => createRunPreparationTiming(runId)("configuration_skills", () => authenticated + ? withSkillActor({ type: "agent", agentId, companyId, runId, source: "agent_jwt", onBehalfOfUserId: userId }, resolve) + : resolve())); + const elapsedMs = performance.now() - measuredStarted; + const queryCount = rootPoolQueries; + assert.equal(entries.length, 1); + assert.equal(entries[0]!.sourceStatus, "available", entries[0]!.missingDetail ?? "Skill unavailable"); + // Verify the whole delivered repository, not just its authored SKILL.md. + for (const file of projected) { + const location = path.join(entries[0]!.source, file.path); + assert.deepEqual(await fs.readFile(location), skillFileBytes(file)); + if (process.platform !== "win32") assert.equal(Boolean((await fs.stat(location)).mode & 0o111), Boolean(file.executable)); + } + await provider.forceFlush(); + if (exportOtlp) assert.ok(exportResults.length > 0 && exportResults.every(code => code === 0), "OTLP export failed"); + const spans = exporter.getFinishedSpans(); + assert.ok(spans.some(span => span.name === "skills.version.verify" && span.attributes["paperclip.execution.fileCount"] === projected.length)); + assert.equal(new Set(spans.map(span => span.spanContext().traceId)).size, 1); + assert.ok(spans.every(span => Object.keys(span.attributes).every(key => ["paperclip.task.run.run_id", "paperclip.execution.fileCount", "paperclip.execution.bytes"].includes(key)))); + samples.push({ label, elapsedMs, rootPoolQueries: queryCount, traceId: spans[0]!.spanContext().traceId, + phases: spans.filter(span => span.name.startsWith("skills.")).map(span => ({ name: span.name, + durationMs: span.duration[0] * 1000 + span.duration[1] / 1e6, + spanId: span.spanContext().spanId, parentSpanId: span.parentSpanContext?.spanId, + attributes: span.attributes })) }); + console.error(JSON.stringify({ label, elapsedMs, rootPoolQueries: queryCount })); + } + console.log(JSON.stringify({ schema: "paperclip.native-skill-preparation-benchmark.v1", + sourceRevision, sourceChangesHash, exportedOtlp: exportOtlp, + source: snapshotFile ? "supplied immutable snapshot" : "synthetic repository", + networkDelayMsPerDirection: networkDelayMs, authenticated, stagingShape, + repositoryHash: skillSnapshotHash(files), repositoryFiles: files.length, runtimeFiles: projected.length, + runtimeBytes: projected.reduce((sum, file) => sum + skillFileBytes(file).length, 0), samples }, null, 2)); +} finally { + await db?.$client.end({ timeout: 1 }); + if (proxy) { + for (const socket of connections) socket.destroy(); + const server = proxy; + await new Promise(resolve => server.close(() => resolve())); + } + await database?.cleanup(); + await provider?.shutdown(); + trace.disable(); context.disable(); manager?.disable(); + for (const [name, value] of Object.entries({ PAPERCLIP_HOME: previous.home, PAPERCLIP_INSTANCE_ID: previous.instance, OTEL_EXPORTER_OTLP_ENDPOINT: previous.endpoint })) { + if (value === undefined) delete process.env[name]; else process.env[name] = value; + } + await fs.rm(home, { recursive: true, force: true }); +} diff --git a/server/src/__tests__/company-skills-observability.test.ts b/server/src/__tests__/company-skills-observability.test.ts new file mode 100644 index 00000000000..45d50c2da59 --- /dev/null +++ b/server/src/__tests__/company-skills-observability.test.ts @@ -0,0 +1,151 @@ +import assert from "node:assert/strict"; +import { randomUUID } from "node:crypto"; +import { promises as fs } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { context, SpanStatusCode, trace } from "@opentelemetry/api"; +import { AsyncLocalStorageContextManager } from "@opentelemetry/context-async-hooks"; +import { InMemorySpanExporter, SimpleSpanProcessor, TracerProvider } from "@opentelemetry/sdk-trace"; +import { companies, companySkills, companySkillVersions, companySkillRepositorySnapshots, createDb, + EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db"; +import { eq } from "drizzle-orm"; +import { createRunPreparationTiming, withRunExecutionTiming } from "../services/execution-preparation-timing.js"; +import { skillSnapshotHash } from "../services/skill-snapshot.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +// This test owns its in-memory tracer; do not start the application exporter. +vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", ""); +const { companySkillService } = await import("../services/company-skills.js"); +const { withSkillVersionCacheLock } = await import("../services/skill-version-cache.js"); +const support = await getEmbeddedPostgresTestSupport(); +const describeDatabase = support.supported ? describe : describe.skip; + +describeDatabase("runtime skill observability", () => { + let database: Awaited>; + let db: ReturnType; + let home: string; + const exporter = new InMemorySpanExporter(); + const lifecycle: string[] = []; + const provider = new TracerProvider({ spanProcessors: [new SimpleSpanProcessor({ exporter }), { + onStart: span => { lifecycle.push(`start:${span.name}`); }, + onEnd: span => { lifecycle.push(`end:${span.name}`); }, + forceFlush: async () => {}, shutdown: async () => {}, + }] }); + const manager = new AsyncLocalStorageContextManager(); + + beforeAll(async () => { + database = await startEmbeddedPostgresTestDatabase("skill-observability-"); + db = createDb(database.connectionString); + home = await fs.mkdtemp(path.join(os.tmpdir(), "skill-observability-")); + vi.stubEnv("PAPERCLIP_HOME", home); + vi.stubEnv("OTEL_EXPORTER_OTLP_ENDPOINT", "http://collector.test"); + expect(context.setGlobalContextManager(manager.enable())).toBe(true); + expect(trace.setGlobalTracerProvider(provider)).toBe(true); + }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); + + afterAll(async () => { + await provider.shutdown(); + trace.disable(); context.disable(); manager.disable(); + vi.unstubAllEnvs(); + await db?.$client.end({ timeout: 1 }); + await database?.cleanup(); + if (home) await fs.rm(home, { recursive: true, force: true }); + }); + + function deferred() { + let resolve!: () => void; + const promise = new Promise(done => { resolve = done; }); + return { promise, resolve }; + } + + async function fixture() { + const companyId = randomUUID(); + const skillId = randomUUID(); + const key = `company/${companyId}/traced`; + const files = [{ path: "skills/traced/SKILL.md", kind: "skill" as const, + content: "---\nname: traced\ndescription: Trace fixture\n---\nReport the model ID.\n" }]; + await db.insert(companies).values({ id: companyId, name: "Trace fixture", issuePrefix: `TR${companyId.slice(0, 6)}` }); + await db.insert(companySkills).values({ id: skillId, companyId, key, slug: "traced", name: "Traced", + sourceType: "github", sourceLocator: "https://example.invalid/immutable-fixture", markdown: files[0]!.content }); + const [snapshot] = await db.insert(companySkillRepositorySnapshots).values({ companyId, + contentHash: skillSnapshotHash(files), fileInventory: files }).returning(); + const [version] = await db.insert(companySkillVersions).values({ companyId, companySkillId: skillId, + revisionNumber: 1, repositorySnapshotId: snapshot!.id, repositorySkillPath: files[0]!.path }).returning(); + await db.update(companySkills).set({ currentVersionId: version!.id }).where(eq(companySkills.id, skillId)); + const service = companySkillService(db); + const options = { onlyKeys: new Set([key]), versionSelections: new Map([[key, version!.id]]), snapshotLatest: true }; + return { companyId, service, options }; + } + + it("parents real preparation work and ends acquisition before the consumer settles", async () => { + const f = await fixture(); + exporter.reset(); + lifecycle.length = 0; + const entered = deferred(), release = deferred(); + const runId = randomUUID(); + const preparation = withRunExecutionTiming(runId, () => createRunPreparationTiming(runId)("configuration_skills", + () => f.service.withRuntimeSkillEntries(f.companyId, f.options, async entries => { + entered.resolve(); await release.promise; return entries; + }))); + try { + await Promise.race([entered.promise, preparation]); + expect(exporter.getFinishedSpans().filter(span => span.name === "skills.cache.acquire")).toHaveLength(1); + expect(exporter.getFinishedSpans().some(span => span.name === "skills.consume")).toBe(false); + } finally { release.resolve(); await preparation; } + expect(await preparation).toMatchObject([{ sourceStatus: "available" }]); + await provider.forceFlush(); + const spans = exporter.getFinishedSpans(); + const span = (name: string) => { const found = spans.find(candidate => candidate.name === name); assert.ok(found, name); return found; }; + for (const [child, parent] of [ + ["heartbeat.prepare.configuration_skills", "task.execution_attempt"], + ["skills.inventory", "heartbeat.prepare.configuration_skills"], + ["skills.inventory.bundled", "skills.inventory"], + ["skills.inventory.releases", "skills.inventory"], + ["skills.inventory.folders", "skills.inventory"], + ["skills.inventory.local_sources", "skills.inventory"], + ["skills.cache.acquire", "heartbeat.prepare.configuration_skills"], + ["skills.rows", "heartbeat.prepare.configuration_skills"], + ["skills.version.read", "heartbeat.prepare.configuration_skills"], + ["skills.version.materialize", "heartbeat.prepare.configuration_skills"], + ["skills.repository.read", "skills.version.materialize"], + ["skills.version.verify", "skills.version.materialize"], + ["skills.consume", "heartbeat.prepare.configuration_skills"], + ]) expect(span(child!).parentSpanContext?.spanId, child).toBe(span(parent!).spanContext().spanId); + const acquisition = span("skills.cache.acquire"); + expect(acquisition.status.code).not.toBe(SpanStatusCode.ERROR); + // SDK timestamps can differ by less than a millisecond at this boundary. + // Observe actual lifecycle order instead of comparing rounded wall clocks. + expect(lifecycle.indexOf("end:skills.cache.acquire")).toBeLessThan(lifecycle.indexOf("start:skills.rows")); + expect(new Set(spans.map(value => value.spanContext().traceId)).size).toBe(1); + expect(spans.every(value => Object.keys(value.attributes).every(key => [ + "paperclip.task.run.run_id", "paperclip.execution.fileCount", "paperclip.execution.bytes", + ].includes(key)))).toBe(true); + }, 30_000); + + it("ends a failed real lock acquisition and preserves the database error", async () => { + const f = await fixture(); + await f.service.listRuntimeSkillEntries(f.companyId, f.options); + const name = new URL(database.connectionString).pathname.slice(1); + assert.match(name, /^[a-zA-Z0-9_-]+$/); + await db.$client.unsafe(`ALTER DATABASE "${name}" SET lock_timeout TO '100ms'`); + const entered = deferred(), release = deferred(); + const holder = withSkillVersionCacheLock(db, f.companyId, async () => { entered.resolve(); await release.promise; }); + try { + await Promise.race([entered.promise, holder]); + exporter.reset(); + const runId = randomUUID(); + await expect(withRunExecutionTiming(runId, () => createRunPreparationTiming(runId)("configuration_skills", + () => f.service.listRuntimeSkillEntries(f.companyId, f.options)))).rejects.toMatchObject({ cause: { code: "55P03" } }); + await provider.forceFlush(); + const spans = exporter.getFinishedSpans(); + const acquisitions = spans.filter(span => span.name === "skills.cache.acquire"); + expect(acquisitions).toHaveLength(1); + expect(acquisitions[0]!.status.code).toBe(SpanStatusCode.ERROR); + const configuration = spans.find(span => span.name === "heartbeat.prepare.configuration_skills"); + expect(acquisitions[0]!.parentSpanContext?.spanId).toBe(configuration?.spanContext().spanId); + expect(spans.some(span => span.name === "skills.rows")).toBe(false); + } finally { release.resolve(); await holder; } + expect(await f.service.listRuntimeSkillEntries(f.companyId, f.options)).toMatchObject([{ sourceStatus: "available" }]); + }, 30_000); +}); diff --git a/server/src/__tests__/connection-management.integration.test.ts b/server/src/__tests__/connection-management.integration.test.ts index 4aec44db9c1..8f091fa49d6 100644 --- a/server/src/__tests__/connection-management.integration.test.ts +++ b/server/src/__tests__/connection-management.integration.test.ts @@ -842,6 +842,8 @@ describe("connection management with production default agents", () => { }); const path = `/chat-endpoints/${created.body.id}/slack/test-message`; if (rate) { + // Keep both calls in one rate window even when CI crosses a minute boundary. + vi.useFakeTimers({ toFake: ["Date"] }); // Shared buckets admit one actual send, while each principal's own // limit also prevents the next send. Neither may consume twice. expect(await f.request("POST", path, { requestId: randomUUID(), slackUserId: "UHUMAN" }, f.jwt), mode) @@ -856,7 +858,7 @@ describe("connection management with production default agents", () => { expect(sends, mode).toBe(rate ? 1 : 0); const audit = await server.db.select().from(toolAccessAuditEvents).where(eq(toolAccessAuditEvents.companyId, f.companyId)); expect(audit.some(event => event.details.agentId === f.agentId && event.actorId === f.agentId), mode).toBe(true); - } finally { provider = null; } + } finally { vi.useRealTimers(); provider = null; } } }, 90_000); diff --git a/server/src/services/company-skills.ts b/server/src/services/company-skills.ts index af1b4e063af..d2819de5714 100644 --- a/server/src/services/company-skills.ts +++ b/server/src/services/company-skills.ts @@ -1,4 +1,5 @@ import { ensureSkillCacheDirectory, touchSkillVersionCache, withSkillVersionCacheLock } from "./skill-version-cache.js"; +import { measureRunPhase } from "./execution-preparation-timing.js"; import { verifyExistingBundledSkillRelease } from "./bundled-skill-release-validation.js"; import { retainProjectSkillAccess, skillAccessService } from "./skill-access.js"; import type { AuthorizationActor } from "./authorization.js"; @@ -3237,7 +3238,7 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo if (!visibility().canReadCompany(companyId)) return; const existingRefresh = skillInventoryRefreshPromises.get(companyId); if (existingRefresh) { - await existingRefresh; + await measureRunPhase("skills.inventory.wait", () => existingRefresh); return; } @@ -3250,10 +3251,10 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo if (!companyExists) { throw notFound("Company not found"); } - const bundledSkills = await ensureBundledSkills(companyId); - await ensureBundledSkillReleases(companyId, bundledSkills); - await reconcilePaperclipSkillFolders(companyId); - await reconcileLocalPathSkillSources(companyId); + const bundledSkills = await measureRunPhase("skills.inventory.bundled", () => ensureBundledSkills(companyId)); + await measureRunPhase("skills.inventory.releases", () => ensureBundledSkillReleases(companyId, bundledSkills)); + await measureRunPhase("skills.inventory.folders", () => reconcilePaperclipSkillFolders(companyId)); + await measureRunPhase("skills.inventory.local_sources", () => reconcileLocalPathSkillSources(companyId)); })(); skillInventoryRefreshPromises.set(companyId, refreshPromise); @@ -6009,8 +6010,9 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo async function runtimeVersionInventory(companyId: string, version: CompanySkillVersion) { if (!version.repositorySnapshotId) return version.fileInventory; - const [snapshot] = await db.select().from(companySkillRepositorySnapshots).where(and( - eq(companySkillRepositorySnapshots.companyId, companyId), eq(companySkillRepositorySnapshots.id, version.repositorySnapshotId))); + const snapshotId = version.repositorySnapshotId; + const [snapshot] = await measureRunPhase("skills.repository.read", () => db.select().from(companySkillRepositorySnapshots).where(and( + eq(companySkillRepositorySnapshots.companyId, companyId), eq(companySkillRepositorySnapshots.id, snapshotId)))); if (!snapshot || !version.repositorySkillPath) throw unprocessable("Installed repository snapshot is unavailable."); return repositorySkillProjection(snapshot.fileInventory, version.repositorySkillPath); } @@ -6029,7 +6031,7 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo const skillDir = path.join(runtimeRoot, version.id); return runVersionSnapshotFlight(skillDir, async () => { await ensureSkillCacheDirectory(runtimeRoot, true); - if (await materializedVersionSnapshotMatches(skillDir, version)) return skillDir; + if (await measureRunPhase("skills.version.verify", () => materializedVersionSnapshotMatches(skillDir, version), { fileCount: version.fileInventory.length })) return skillDir; const staging = await fs.mkdtemp(path.join(runtimeRoot, `.${version.id}-`)); try { let wroteSkillFile = false; @@ -6070,7 +6072,7 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo ?? (options.snapshotLatest || (skill.metadata?.skillSourceId && skill.metadata?.snapshotHash) || skill.accessSourceId ? skill.currentVersionId : null); if (selectedVersionId) { const versionPath = path.resolve(resolveManagedSkillsRoot(companyId), "__versions__", skill.id, selectedVersionId); - const version = await getVersion(companyId, skill.id, selectedVersionId); + const version = await measureRunPhase("skills.version.read", () => getVersion(companyId, skill.id, selectedVersionId)); if (!version) { return { status: "missing", @@ -6096,7 +6098,7 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo detail: "The selected skill version will be materialized on the next run." }; } } - const versionSource = await materializeVersionSnapshot(companyId, skill, version); + const versionSource = await measureRunPhase("skills.version.materialize", () => materializeVersionSnapshot(companyId, skill, version)); if (versionSource) return { status: "available", source: versionSource }; return { status: "missing", source: versionPath, detail: "The selected skill version produced no files." }; } catch (error) { @@ -6174,15 +6176,18 @@ export function companySkillService(db: Db, options: { actor?: AuthorizationActo ): Promise { if (options.onlyKeys?.size === 0 || (!options.onlyKeys && options.selectionConfig && !options.includeLegacy && readPaperclipSkillSyncPreference(options.selectionConfig).desiredSkills.length === 0)) return consume([]); - await ensureSkillInventoryCurrent(companyId); - return withSkillVersionCacheLock(db, companyId, async () => consume(await listRuntimeSkillEntriesLocked(companyId, options))); + await measureRunPhase("skills.inventory", () => ensureSkillInventoryCurrent(companyId)); + return withSkillVersionCacheLock(db, companyId, async () => { + const entries = await listRuntimeSkillEntriesLocked(companyId, options); + return measureRunPhase("skills.consume", () => consume(entries)); + }); } async function listRuntimeSkillEntriesLocked( companyId: string, options: RuntimeSkillEntryOptions, ): Promise { - const skills = await readFullSkillRows(companyId); + const skills = await measureRunPhase("skills.rows", () => readFullSkillRows(companyId)); const selectedKeys = options.onlyKeys ?? (options.selectionConfig ? new Set( (options.includeLegacy ? resolveLegacyPaperclipDesiredSkillNames : resolvePaperclipDesiredSkillNames)( options.selectionConfig, skills.map(skill => ({ key: skill.key, runtimeName: buildSkillRuntimeName(skill.key, skill.slug) }))), diff --git a/server/src/services/execution-preparation-timing.test.ts b/server/src/services/execution-preparation-timing.test.ts index 05798901709..21eac0a05f4 100644 --- a/server/src/services/execution-preparation-timing.test.ts +++ b/server/src/services/execution-preparation-timing.test.ts @@ -41,7 +41,8 @@ it.each([undefined, "", " "])("does not consult tracing for endpoint %s", async const error = vi.spyOn(console, "error"); try { await expect(createRunPreparationTiming("run", "native.controller")("backend_setup", () => 42)).resolves.toBe(42); - for (const phase of ["execution.usage_startup", "execution.mcp_handoff", "execution.dispatch_admission", "execution.budget_reservation"] as const) { + for (const phase of ["execution.usage_startup", "execution.mcp_handoff", "execution.dispatch_admission", "execution.budget_reservation", + "skills.inventory", "skills.inventory.wait", "skills.cache.acquire", "skills.version.materialize", "skills.consume"] as const) { const result = {}; const work = vi.fn(() => { recordRepositoryObjectCacheDetail({ outcome: "hit", referenceSupplied: true }); diff --git a/server/src/services/execution-preparation-timing.ts b/server/src/services/execution-preparation-timing.ts index 863ae7b6e5b..a4ff6e82103 100644 --- a/server/src/services/execution-preparation-timing.ts +++ b/server/src/services/execution-preparation-timing.ts @@ -34,6 +34,10 @@ type PreparationPhase = "environment_selection" | "execution_configuration" | "s | "instruction_changes" | "warm_release" | "instruction_collection"; export type ExecutionPhase = + | "skills.inventory" | "skills.inventory.wait" | "skills.inventory.bundled" | "skills.inventory.releases" + | "skills.inventory.folders" | "skills.inventory.local_sources" | "skills.rows" + | "skills.cache.acquire" | "skills.version.read" | "skills.repository.read" + | "skills.version.verify" | "skills.version.materialize" | "skills.consume" | "workspace.transaction" | "workspace.transaction.entry" | "workspace.transaction.commit" | "workspace.transaction.rollback" | "workspace.identity_read" | "workspace.row_lock" | "workspace.provenance" | "workspace.notification" | "workspace.write" | "workspace.sources" | "workspace.sources.canonicalize" | "workspace.sources.inventory" | "workspace.sources.alias_scan" diff --git a/server/src/services/native-runtime/native-run-trace.test.ts b/server/src/services/native-runtime/native-run-trace.test.ts index 2077e64a2ce..8b3a076850c 100644 --- a/server/src/services/native-runtime/native-run-trace.test.ts +++ b/server/src/services/native-runtime/native-run-trace.test.ts @@ -9,6 +9,7 @@ import { createNativeRunTrace, nativeRunPreparationStarts, recordFailedSkillPreparation, + recordNativeProviderPerformanceSpans, NATIVE_RUN_SPAN_EVENT_TYPE, NATIVE_RUN_TRACE_SCHEMA_VERSION, } from "./native-run-trace.js"; @@ -66,6 +67,39 @@ function createRecordingTraceContext(): { } describe("native runner performance trace", () => { + it("projects a full durable diagnostic batch without waiting on duplicate run-log writes", async () => { + const {traceContext, spans}=createRecordingTraceContext(); + let release!: () => void; + const barrier = new Promise(resolve => { release=resolve; }); + const write=vi.fn(async()=>barrier); + const trace=createNativeRunTrace({runId:"provider-perf-blocked-log",startedAtMs:1000,traceContext,onEvent:write}); + const names=["provider.model.stream","provider.context.environment","provider.tools.resolve","provider.model.resolve", + "provider.workspace.snapshot.track","provider.workspace.snapshot.patch","provider.workspace.snapshot.diff","provider.skills.discovery"]; + let completed=false; + const work=recordNativeProviderPerformanceSpans(trace,Array.from({length:128},(_,index)=>({ + name:names[index%names.length],startedAtMs:1100+index,endedAtMs:1200+index, + }))).then(()=>{completed=true;}); + try { + await new Promise(resolve=>setImmediate(resolve)); + expect(completed).toBe(true); + expect(write).not.toHaveBeenCalled(); + expect(spans.filter(span=>span.parentName==="provider.runtime")).toHaveLength(128); + } finally {release();await work;await trace.finish("ok");} + }); + it("groups normalized provider phases under their real native execution parent", async () => { + const {traceContext, spans}=createRecordingTraceContext(); + const trace=createNativeRunTrace({runId:"provider-perf",startedAtMs:1000,traceContext}); + const execute=trace.start("native.session.execute",{startedAtMs:1000}); + await recordNativeProviderPerformanceSpans(trace,[ + {name:"provider.context.environment",startedAtMs:1100,endedAtMs:1200}, + {name:"provider.model.stream",startedAtMs:1200,endedAtMs:1700}, + ]); + await trace.end(execute,{endedAtMs:1800}); + await trace.finish("ok"); + expect(spans.find(s=>s.name==="provider.runtime")).toMatchObject({parentName:"native.session.execute",endedAtMs:1700}); + expect(spans.filter(s=>s.name==="provider.model.stream"||s.name==="provider.context.environment").map(s=>s.parentName)) + .toEqual(["provider.runtime","provider.runtime"]); + }); it.each([7_200_000, 10_800_000])( "times the current answer after %i ms without charging prior questions or human wait", async (answeredAtMs) => { diff --git a/server/src/services/native-runtime/native-run-trace.ts b/server/src/services/native-runtime/native-run-trace.ts index 8594de2d31b..7c38e99cda4 100644 --- a/server/src/services/native-runtime/native-run-trace.ts +++ b/server/src/services/native-runtime/native-run-trace.ts @@ -138,6 +138,7 @@ interface NativeRunSpanScopeState extends NativeRunSpanScope { context: unknown; attributes: Record; ended: boolean; + persistRunLog: boolean; } const NOOP_SPAN: SpanHandle = { @@ -323,6 +324,8 @@ export function createNativeRunTrace(input: { parentName?: string; startedAtMs?: number; attributes?: Record; + /** False only when an existing durable diagnostic batch already contains the measurements. */ + persistRunLog?: boolean; } = {}, ): NativeRunSpanScope => { const startedAtMs = finiteMs(options.startedAtMs ?? Date.now()); @@ -364,6 +367,7 @@ export function createNativeRunTrace(input: { context, attributes, ended: false, + persistRunLog: options.persistRunLog !== false, }; scopes.add(state); openScopes.add(state); @@ -413,7 +417,7 @@ export function createNativeRunTrace(input: { }); if (outcome === "failed") { try { state.span.setStatus({ code: 2 }); } catch {} } try { state.span.end(endedAtMs); } catch {} - await emitCompletedSpanEvent({ + if (state.persistRunLog) await emitCompletedSpanEvent({ name: state.name, parentName: state.parentName, startedAtMs: state.startedAtMs, @@ -458,11 +462,12 @@ export function createNativeRunTrace(input: { ); }; - const record = async (span: NativeRunHistoricalSpan): Promise => { + const record = async (span: NativeRunHistoricalSpan, options: { persistRunLog?: boolean } = {}): Promise => { const scope = start(span.name, { parentName: span.parentName, startedAtMs: span.startedAtMs, attributes: span.attributes, + persistRunLog: options.persistRunLog, }); await end(scope, { endedAtMs: span.endedAtMs, @@ -528,6 +533,22 @@ export function createNativeRunTrace(input: { export type NativeRunTrace = ReturnType; +/** Group already-normalized provider measurements without exporting provider attributes. */ +export async function recordNativeProviderPerformanceSpans(trace: NativeRunTrace, spans: NativeRunHistoricalSpan[]): Promise { + if (!spans.length) return; + try { + const scope = trace.start("provider.runtime", { parentName: "native.session.execute", + startedAtMs: Math.min(...spans.map(span => span.startedAtMs)), persistRunLog: false }); + try { + for (const span of spans) await trace.record({ name: span.name, parentName: "provider.runtime", + startedAtMs: span.startedAtMs, endedAtMs: span.endedAtMs, outcome: span.outcome }, { persistRunLog: false }); + } finally { + await trace.end(scope, { endedAtMs: Math.max(...spans.map(span => span.endedAtMs)), + outcome: spans.some(span => span.outcome === "failed") ? "failed" : "ok" }); + } + } catch { /* Diagnostics cannot replace the work's result. */ } +} + /** Emit preparation failure even when execution aborts before a native session exists. */ export async function recordFailedSkillPreparation(input: { runId: string; diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index 8466a74eef6..cea0ac147cb 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -17,6 +17,7 @@ import { assertExternalNativeRunAuthority } from "./external-native-authority.js import { stageRemoteLaunchAssets } from "./remote-launch-assets.js"; import { createRunPreparationTiming } from "../execution-preparation-timing.js"; import { configuredEnvironment } from "../../vendor/paperclip-runner/index.js"; +import { parseProviderPerformanceSpans } from "../../vendor/paperclip-runner/index.js"; import { apiKeyBillingType } from "@paperclipai/adapter-utils/api-billing-type"; import { agents } from "@paperclipai/db"; import { isCloudManagedInstance } from "../cloud-instance.js"; @@ -204,6 +205,7 @@ import { createNativeRunTrace, isNativeRunRootHistoricalSpan, nativeRunPreparationStarts, + recordNativeProviderPerformanceSpans, type NativeRunHistoricalSpan, type NativeRunSpanScope, type NativeRunTrace, @@ -8527,6 +8529,9 @@ async function executePaperclipNativeSessionWithinScope( assertControllerActive, assertRunAdmissionActive, onCommittedEvent: async (event) => { + if (event.eventType === "harness.diagnostic") { + await recordNativeProviderPerformanceSpans(trace, parseProviderPerformanceSpans(event.payload, Date.now())); + } const textKind = !firstTokenRecorded ? observeDeliverableText(event) : null; if (textKind) { firstTokenRecorded = true; diff --git a/server/src/services/skill-version-cache.ts b/server/src/services/skill-version-cache.ts index 2f3ec15c5ad..57787129e80 100644 --- a/server/src/services/skill-version-cache.ts +++ b/server/src/services/skill-version-cache.ts @@ -10,6 +10,7 @@ import { assertSkillSnapshotPath } from "./skill-snapshot.js"; import { repositorySkillFrontmatter } from "./skill-repository-package.js"; import type { CompanySkillVersionFileInventoryEntry } from "@paperclipai/shared"; import { parseNativeExecutionInput } from "../vendor/paperclip-runner/index.js"; +import { beginRunPhase } from "./execution-preparation-timing.js"; export const SKILL_VERSION_CACHE_IDLE_MS = 60 * 60 * 1000; const locks = new AsyncLocalStorage>(); @@ -26,14 +27,19 @@ export async function withSkillVersionCacheLock(db: Db, companyId: string, ac if (held.some(lock => lock.db === db && lock.companyId === companyId)) return action(); // Preparation uses the ordinary pool for version/pin writes. Borrowing a pool // connection for this lock would deadlock installations with a one-slot pool. + const acquired = beginRunPhase("skills.cache.acquire"); return withDedicatedDbConnection(db, connection => connection.transaction(async tx => { const key = `skill_version_cache:${companyId}`; if (tryOnly) { const rows = await tx.execute<{ acquired: boolean }>(sql`select pg_try_advisory_xact_lock(hashtextextended(${key}, 0)) as acquired`); if (!rows[0]?.acquired) throw new SkillCacheBusy(); } else await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${key}, 0))`); + acquired(); return locks.run([...held, { db, companyId }], action); - })); + })).catch(error => { + acquired(true); + throw error; + }); } export function skillVersionCachePaths(companyId: string, skillId: string, versionId: string) { diff --git a/server/src/vendor/paperclip-runner/index.ts b/server/src/vendor/paperclip-runner/index.ts index 6790b801b36..9e6f34b2f1e 100644 --- a/server/src/vendor/paperclip-runner/index.ts +++ b/server/src/vendor/paperclip-runner/index.ts @@ -154,6 +154,7 @@ export const resolveSourceCodexHome = runner.resolveSourceCodexHome; export const resolveCodexCommand = runner.resolveCodexCommand; export const resolvePinnedCodexCommand = runner.resolvePinnedCodexCommand; export const validatePrpEvent = runner.validatePrpEvent; +export const parseProviderPerformanceSpans = runner.parseProviderPerformanceSpans; export const validatePrpStructuredRunResult = runner.validatePrpStructuredRunResult; From 5398275d2ae7ce11136f09a3f10529328d01dc37 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:58:11 -0500 Subject: [PATCH 3/3] fix(server): schedule gateway credential expiry from committed changes (#17450) 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 tool gateway stores credentials for sessions and named gateways. > - Those credentials already contain expiry dates. > - The server repeatedly scans their tables even when no expiry work exists. > - Creation signals and saved deadlines can drive cleanup without idle scans. > - This PR registers that work with the existing coordinator. > - Authentication continues to reject expired credentials independently of physical cleanup. ## Linked Issues or Issue Description Refs #17446, #17221, #17274. This is the third sleep-migration slice, stacked on #17446. **What problem does this solve?** Gateway credential cleanup queries PostgreSQL on every maintenance tick, including empty tables and retained non-expiring tokens. **What is the proposed solution?** Signal expiring token/session creation from its transaction. Restore the earliest saved expiry at startup. Retry only while cleanup or reconciliation remains outstanding. **Why is this useful?** Configured idle gateways no longer create recurring expiry traffic. Existing credential data remains the durable source of truth. Related work: #17221 and #17274 change run-token lifetime and cleanup eligibility. They remain separate. This PR preserves current master authorization and deletion rules. When those PRs are combined, update the deadline query and signals to match their new operator-token expiry predicate; run-token idle markers must not keep this worker scanning. Retain the separate run-liveness reaper and run both regression suites. Text mergeability is insufficient evidence for that integration. ## What Changed - Make the credential test clock follow real scheduled work without overshooting future-expiry assertions; production behavior is unchanged by this fixture follow-up. - Coalesce sequential credential notifications within the former cleanup cadence, preserve loaded expiry deadlines and immediate authentication rejection, and bound scheduled deletion to 500 rows per pass. - Added transaction-aware intent before the two existing credential inserts. Non-expiring named tokens do not signal expiry work. - Added earliest-expiry selection in the gateway service and a narrow registration wrapper for the shared deadline helper. - Removed gateway credential cleanup from the aggregate maintenance tick. Startup reconstructs saved deadlines. Heartbeat-disabled instances retain their startup-only cleanup behavior. - Preserved expiry/revocation checks, run authorization, audit behavior, and the existing 500-token cleanup batch limit. - Added real PostgreSQL tests and a lifecycle/producer document. Tool-action review recovery remains a separate slice. - Drain all expired session/token pages in explicit and scheduler-disabled startup cleanup, while retaining one-page scheduled passes and authentication enforcement. ## Verification - At `907098cd3656bac59c60220c73b085d0349d4b5f`, all 290 Runner transport tests pass locally (including all seven prepared-environment variants). CI run `40570815360` attempt 1 had one provider-drain settlement failure in the `close-attachment` case; the identical source passed the preceding CI lane. A single failed-job rerun is in progress. The failure remains recorded; no shutdown assertion or production behavior was changed to suppress it. - Master landing reconciliation at `907098cd3656bac59c60220c73b085d0349d4b5f` after #17446 merged: all production and test files are byte-identical to `24318d9b99ee7f044a864ff3981fc1929bf3e509`, where the 150-case acceptance and server types passed. Only commit ancestry and the plan's merged status changed. Fresh CI/review is pending on this head. - Parent reconciliation at `24318d9b99ee7f044a864ff3981fc1929bf3e509`: 150 affected tests pass across gateway credential expiry, the complete tool gateway suite, custom-image worker and startup. The accepted PostgreSQL runs skip no cases. Server types pass. Existing direct tests cover sequential-write coalescing and saved-deadline precedence; the older Ponytail finding needs a fresh review. Remote CI is pending. Current head: `10c85a5eaa288867aa2997a27aee5f675c2a713d`. This remains a single-duty PR stacked on #17446. - Integrated pinned master `8548173fc9efdc0fa07644fb92dcc0b6851a95e5` with normal merges. Every branch passed generated-schema checks and its target-branch migration-order gate. Existing SQL is unchanged; the 25 stack migrations follow master’s new migration. - Duty-specific producer coverage, lifecycle tests, and earlier failure records: [2026-10-08-instance-sleep-and-scheduler-inventory.md](https://github.com/paperclipai/paperclip/blob/10c85a5eaa288867aa2997a27aee5f675c2a713d/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md), [2026-10-24-recurring-server-sleep-stack.md](https://github.com/paperclipai/paperclip/blob/10c85a5eaa288867aa2997a27aee5f675c2a713d/doc/plans/2026-10-24-recurring-server-sleep-stack.md). - Combined tip `51e6cbe67979b55b340ea9f0f434c5b5c682ccd6`: **355 startup/cancellation/recovery/dispatch/preservation tests**, **75 connection-management tests**, and production server typechecking pass. These combined checks do not mean every intermediate PR independently ran the full repository suite. - Real master-to-stack database upgrade passes: **379 unchanged prior migration receipts plus 25 new migrations**, with the gateway responsibility fixture preserved. - Owning-branch checks: 84 runner installation/settlement cases plus runner typechecking and generated TypeScript/Rust profile agreement; 253 GitHub review workflow cases. Stop-attribution and held-worker readiness regressions failed before their fixes. - Failure accounting: the initial combined run passed 349 cases and failed six idle assertions in a reused preservation database containing old cancelled runs. Repeating the combined command with a fresh preservation database passed. Earlier invalid project selection, merge import/type errors, and the interrupted full local suite are not counted as passing checks. - **Latest-head CI and review remain required.** Prior CI findings include GitHub idle observation, route teardown, attention cleanup, touch-picker E2E, workspace health, and voice-cleanup timing; local passes do not erase those failures. No full local repository-suite, deployed sleep, fleet cost, or live Copilot qualification claim is made. ## Risks - Shared-owner signals cover supported local producers. Independent SQL writers or another replica need a separate ingress contract; startup recovery is not live discovery. - This is scheduling only. The open run-token lifetime PRs need semantic integration as described above before combining their behavior. - Expiry cleanup can wait during drain; authentication still enforces expiry on use. Existing Cloud safety gates are preserved. Local deadlines do not prove external wake coverage or deployed suspension. - Revocation does not move expiry. Non-expiring tokens remain retained by design; this PR does not invent a retention deadline. ## Model Used OpenAI Codex, GPT-6 family, with reasoning and code execution. The exact serving model identifier and context window were not exposed. ## 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 Latest-head CI is now green after one evidence-backed retry. Greptile is 5/5 and all review threads are resolved. --------- Co-authored-by: Paperclip --- doc/idle-gateway-credential-expiry.md | 141 +++++++++ ...-instance-sleep-and-scheduler-inventory.md | 6 +- ...2026-10-24-recurring-server-sleep-stack.md | 2 +- packages/db/src/client.ts | 1 + .../db/src/migrations/0381_mean_scream.sql | 1 + ...{0375_snapshot.json => 0381_snapshot.json} | 50 +++- packages/db/src/migrations/meta/_journal.json | 7 + packages/db/src/schema/tool_access.ts | 1 + .../gateway-credential-expiry.test.ts | 269 ++++++++++++++++++ .../server-startup-feedback-export.test.ts | 1 + server/src/__tests__/tool-gateway.test.ts | 10 +- server/src/index.ts | 7 +- server/src/services/deadline-work.ts | 8 + .../services/delivery-work-notifications.ts | 1 + .../gateway-credential-expiry-work.ts | 18 ++ server/src/services/tool-gateway.ts | 161 ++++++----- 16 files changed, 609 insertions(+), 75 deletions(-) create mode 100644 doc/idle-gateway-credential-expiry.md create mode 100644 packages/db/src/migrations/0381_mean_scream.sql rename packages/db/src/migrations/meta/{0375_snapshot.json => 0381_snapshot.json} (99%) create mode 100644 server/src/__tests__/gateway-credential-expiry.test.ts create mode 100644 server/src/services/gateway-credential-expiry-work.ts diff --git a/doc/idle-gateway-credential-expiry.md b/doc/idle-gateway-credential-expiry.md new file mode 100644 index 00000000000..e0486d39886 --- /dev/null +++ b/doc/idle-gateway-credential-expiry.md @@ -0,0 +1,141 @@ +# Gateway credential expiry and idle behavior + +Gateway sessions and named gateway tokens already persist their expiry times. +`cleanupExpiredSessions` remains the owner of physical deletion. Authentication +continues to check expiry, revocation, company scope, run ownership, and active +run state on use. No table, authorization rule, or external alarm is added. + +## Producer inventory + +- `createSession` registers intent before inserting a run-bound session in a + transaction. Its existing audit and returned credential remain unchanged. +- `createNamedGatewayToken` registers intent before inserting an expiring token + in a transaction. A token without an expiry owes no expiry cleanup and does + not notify this worker. +- Last-use updates do not change expiry. Token/session revocation, including + heartbeat completion and connection removal, also leaves the saved expiry + intact. Revoked rows retain the same physical deletion deadline. +- Gateway/company deletion removes dependent rows and can leave one harmless + stale deadline. It cannot create overdue work. No supported service changes + a saved credential expiry after creation. + +The database signal layer owns outer commit, rollback, savepoints, and uncertain +outcomes. The worker supports producers sharing that signal owner. Independent +SQL writers and another process need a separate live ingress contract. Startup +reconstructs existing rows but does not provide continuous replica discovery. + +## Worker contract + +`nextCredentialExpiryAt` reads one earliest non-null expiry from each table using +expiry-first indexes, then compares those at most two values. The migration adds +the session expiry index; the token expiry index already exists. +An empty credential store or retained non-expiring tokens returns no deadline. +`registerGatewayCredentialExpiryWork` supplies cleanup and deadline selection to +the shared `registerDeadlineWork` helper. Provider and authentication behavior +stay in the gateway service; startup only registers the worker. + +The worker starts where the old startup cleanup ran. With heartbeat scheduling +enabled, committed changes and actual expiry times replace the recurring cleanup +call. With heartbeat scheduling disabled, the existing startup-only cleanup is +preserved. Tool action-review recovery is a separate obligation and is unchanged. + +Token and session deletion are each bounded to 500 rows per pass. Session +selection orders by expiry and rechecks expiry when deleting the selected IDs. +A remaining overdue expiry schedules another pass after 30 seconds. Failed reconciliation also +retries at that bound. No unfinished reconciliation or future expiry means no +recurring SQL. A generation retains writes arriving during reconciliation. +Startup restores deadlines; drain retains first writes without passive SQL; +resume completes overdue cleanup. The coordinator owns shutdown and waits for +in-flight work. + +Sequential committed writes are coalesced for up to 30 seconds after a +successful cleanup pass, matching the former heartbeat cleanup cadence. A +previously loaded expiry can preempt that window. A newly reported credential +may physically remain until that bounded follow-up; authentication still rejects +it immediately at expiry. A successful pass with no future expiry and no new +notifications creates no timer. This uses the shared optional notification +coalescing capability, promoted from the later plugin/decision recovery slices; +workers that omit it retain their existing behavior. + +## Evidence and limits + +The concurrent session index runs through the migration executor's existing +per-file top-level path. Initial application and repeat application were tested. +A PostgreSQL plan with 20,000 sessions and 20,000 tokens, including 19,000 +non-expiring tokens, used both expiry indexes and read one row from each. +This establishes bounded lookup on that fixture, not production latency. + +The new PostgreSQL suite exercises real session/token creation, configured idle +state, non-expiring history, expiry ordering, revoked-token cleanup, outer commit +and rollback, startup reconstruction, a backlog larger than one cleanup batch, +and drain/resume. It tests expired authentication before deferred physical +cleanup, through both session and named-gateway entry points. Existing gateway +acceptance and server-startup tests cover the changed integration boundaries. + +Use only disposable migrated databases for the test URL overrides. Their names +must end in `_test`; the suites delete their fixtures. Ordinary CI uses embedded +PostgreSQL. Test credentials are synthetic and no external provider is contacted +by the expiry suite. + +The migration proves worker behavior, not host suspension. Existing Cloud idle +proof remains conservative. An in-process deadline cannot wake stopped compute; +external wake coverage must be verified before changing sleep eligibility. + +## Related unmerged token-lifetime work + +At implementation time, PRs #17221 and #17274 change run-scoped token lifetime +and cleanup eligibility. This slice preserves the current master policy and +changes scheduling only. When combining those changes, the deadline query and +producer signals must use the same token eligibility as cleanup: run-token idle +markers must not schedule the operator-token expiry worker. Keep the run-liveness +reaper with its own owner and retain both regression suites. A conflict-free +text merge alone does not prove this integration. + +## Notification amplification review repair (2026-10-27) + +Ten sequential real session/token creation transactions reproduced ten extra +instance-wide cleanup passes. With coalescing they cause one follow-up pass. +A separate 501-session fixture reproduced the unbounded delete, then passed +with 500 removed initially and the remaining overdue row removed at the saved +30-second retry. A still-valid session survives both passes. The tests also +preserve an already loaded expiry only 500 milliseconds away and verify that a +new one-second session is rejected while physical cleanup waits for coalescing. + +The initial full run exposed four outer-transaction tests whose fake-clock wait +expected the intent hold to release before the new coalescing follow-up. Their +settlement helper now advances the clock through that window while preserving +the original commit/rollback assertions. The complete gateway expiry, gateway +acceptance, custom-image deadline, and startup suites pass: 147 tests in four +files. Server typechecking also passes on the owning branch. This is local +behavioral evidence; combined-stack and fresh remote checks remain required. +The full local test:run remains unverified because of embedded PostgreSQL +startup/capacity limits; the two real gateway suites used separate migrated, +task-owned disposable PostgreSQL databases. + +A later combined run exposed a test-clock overshoot: repeated blind 30-second +advances could expire the future session before its intermediate assertion. +The settlement helper now lets real SQL settle and advances only to an actually +armed follow-up within the coalescing window. All 12 credential expiry tests pass +on the owning gateway branch with the existing exact-deadline and transaction +assertions intact. This follow-up changes the test fixture only. + + +## One-shot cleanup preserves complete backlog removal + +Review found that bounding worker passes also truncated startup cleanup when the +heartbeat scheduler was disabled. That path calls cleanup only once, so it could +leave every expired token or session after the first 500 rows indefinitely. + +`cleanupExpiredSessions` now drains the existing backlog in 500-row SQL batches +by default, using one fixed expiry cutoff for the invocation. The deadline worker +opts into `singleBatch: true` and retains its existing coalescing and next-page +deadline. Future and nonexpiring credentials survive both paths. The return value +still counts deleted sessions, as before. No periodic fallback was added. + +Three real-PostgreSQL regressions reproduced the truncation with 1,001 expired +sessions, tokens, or both, without registering a worker. They pass after the fix. +All 55 expiry/startup cases pass, including the existing worker's 501-row bounded +pass and commit/rollback tests. The original explicit-cleanup compatibility case +and server typecheck also pass. Evidence is in `/tmp/sleep-master-gateway-manual-` +logs: `red`, `green`, `compatibility`, and `types`. This fixes one-shot behavior; +it does not establish provider suspension or complete the stack's CI acceptance. diff --git a/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md b/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md index 9141878caa8..38dec000a0e 100644 --- a/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md +++ b/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md @@ -649,8 +649,10 @@ Longer polling intervals alone do not complete an item. - [ ] **JOB-21 — Secret proposals and expired action tokens (partially migrated).** Secret-proposal expiry now uses transaction signals and saved expiry deadlines; - see [the lifecycle contract](../idle-secret-proposal-expiry.md). Tool review - recovery and gateway token cleanup still use **30s** queries. Change: enforce expiry synchronously on use and + see [the lifecycle contract](../idle-secret-proposal-expiry.md). Gateway token + and session expiry now also uses saved deadlines and producer signals; see + [its lifecycle contract](../idle-gateway-credential-expiry.md). Tool review + recovery still uses **30s** queries. Change: enforce expiry synchronously on use and register required scrub/cleanup deadlines. **Complete when:** idle cleanup does not extend authorization or secret-retention periods. Sources: [secret-proposals.ts](../../server/src/services/secret-proposals.ts), diff --git a/doc/plans/2026-10-24-recurring-server-sleep-stack.md b/doc/plans/2026-10-24-recurring-server-sleep-stack.md index 20221274e70..009401a1d93 100644 --- a/doc/plans/2026-10-24-recurring-server-sleep-stack.md +++ b/doc/plans/2026-10-24-recurring-server-sleep-stack.md @@ -18,7 +18,7 @@ Do not mark an item done from a timer removal or a green check alone. | 04 | Decision retention and notifications | Retention deadlines and notification delivery are separate reasons | Pending | | 05 | Decision expiry and interrupted effects | Expiry, effect recovery, continuation recovery | Pending | | 06 | Tool connection health | Configuration/use activation and defined proactive health deadlines | Pending | -| 07 | Secret proposals, tool reviews, gateway tokens | Separate expiry/scrub/recovery owners | Secret-proposal expiry in progress; tool reviews and gateway tokens pending | +| 07 | Secret proposals, tool reviews, gateway tokens | Separate expiry/scrub/recovery owners | Secret proposals: [#17446](https://github.com/paperclipai/paperclip/pull/17446), merged after CI and passing reviews; gateway credential expiry in progress; tool reviews pending | | 08 | GitHub connection events and continuity | Event discovery/replay and credential continuity separately | Pending | | 09 | Merged-PR confirmations | Candidate writes, webhook activation where supported, outstanding-candidate fallback | Pending | | 10 | External-object refresh | Configuration changes, refresh deadlines, source events | Pending | diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 7f067cbfc1c..77fb0c62fa1 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -501,6 +501,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([ "0332_little_night_nurse.sql", "0345_luxuriant_carmella_unuscione.sql", "0369_late_logan.sql", + "0381_mean_scream.sql", ]); async function applyPendingMigrationsManually( diff --git a/packages/db/src/migrations/0381_mean_scream.sql b/packages/db/src/migrations/0381_mean_scream.sql new file mode 100644 index 00000000000..8827365ffdd --- /dev/null +++ b/packages/db/src/migrations/0381_mean_scream.sql @@ -0,0 +1 @@ +CREATE INDEX CONCURRENTLY IF NOT EXISTS "tool_gateway_sessions_expiry_idx" ON "tool_gateway_sessions" USING btree ("expires_at"); diff --git a/packages/db/src/migrations/meta/0375_snapshot.json b/packages/db/src/migrations/meta/0381_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0375_snapshot.json rename to packages/db/src/migrations/meta/0381_snapshot.json index 7bd1861bd2c..23802aaeece 100644 --- a/packages/db/src/migrations/meta/0375_snapshot.json +++ b/packages/db/src/migrations/meta/0381_snapshot.json @@ -1,6 +1,6 @@ { - "id": "3e17203b-ec95-41e9-8363-685982450199", - "prevId": "945c31ed-f39f-4272-a91d-85de925f5361", + "id": "2e93deb7-f24c-42d1-8c8e-30b21cff90bc", + "prevId": "bfda87fa-662b-47bb-87c0-dabc814aebd7", "version": "7", "dialect": "postgresql", "tables": { @@ -47782,6 +47782,18 @@ "primaryKey": false, "notNull": false }, + "git_authorization_grant_id": { + "name": "git_authorization_grant_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "git_authorized_by_user_id": { + "name": "git_authorized_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, "pause_reason": { "name": "pause_reason", "type": "text", @@ -47920,6 +47932,19 @@ ], "onDelete": "no action", "onUpdate": "no action" + }, + "projects_git_authorization_grant_id_connection_grants_id_fk": { + "name": "projects_git_authorization_grant_id_connection_grants_id_fk", + "tableFrom": "projects", + "tableTo": "connection_grants", + "columnsFrom": [ + "git_authorization_grant_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" } }, "compositePrimaryKeys": {}, @@ -55197,6 +55222,21 @@ "method": "btree", "with": {} }, + "tool_gateway_sessions_expiry_idx": { + "name": "tool_gateway_sessions_expiry_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, "tool_gateway_sessions_run_idx": { "name": "tool_gateway_sessions_run_idx", "columns": [ @@ -55942,6 +55982,12 @@ "notNull": true, "default": "''" }, + "responsible_user_id": { + "name": "responsible_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, "owner_note": { "name": "owner_note", "type": "text", diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 96c505941fd..176a963f7a4 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -2654,6 +2654,13 @@ "when": 1793060791724, "tag": "0380_broken_aqueduct", "breakpoints": true + }, + { + "idx": 381, + "version": "7", + "when": 1793060791725, + "tag": "0381_mean_scream", + "breakpoints": true } ] } diff --git a/packages/db/src/schema/tool_access.ts b/packages/db/src/schema/tool_access.ts index f4aede1b4cd..825eb91589f 100644 --- a/packages/db/src/schema/tool_access.ts +++ b/packages/db/src/schema/tool_access.ts @@ -714,6 +714,7 @@ export const toolGatewaySessions = pgTable( uniqueIndex("tool_gateway_sessions_token_hash_uq").on(table.tokenHash), index("tool_gateway_sessions_company_agent_idx").on(table.companyId, table.agentId), index("tool_gateway_sessions_company_expires_idx").on(table.companyId, table.expiresAt), + index("tool_gateway_sessions_expiry_idx").on(table.expiresAt), index("tool_gateway_sessions_run_idx").on(table.companyId, table.runId), index("tool_gateway_sessions_issue_idx").on(table.companyId, table.issueId), index("tool_gateway_sessions_gateway_idx").on(table.companyId, table.gatewayId), diff --git a/server/src/__tests__/gateway-credential-expiry.test.ts b/server/src/__tests__/gateway-credential-expiry.test.ts new file mode 100644 index 00000000000..caa76674104 --- /dev/null +++ b/server/src/__tests__/gateway-credential-expiry.test.ts @@ -0,0 +1,269 @@ +import { randomUUID } from "node:crypto"; +import { sql } from "drizzle-orm"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { activityLog, agents, companies, createDb, heartbeatRuns, toolAccessAuditEvents, toolGatewaySessions, + toolMcpGateways, toolMcpGatewayTokens, toolProfiles } from "@paperclipai/db"; +import { createToolGatewayService } from "../services/tool-gateway.js"; +import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { registerGatewayCredentialExpiryWork } from "../services/gateway-credential-expiry-work.js"; +import { idleWorkSnapshot } from "../services/task-admission.js"; +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const external = resolveExternalTestDatabaseUrl("PAPERCLIP_GATEWAY_EXPIRY_TEST_DATABASE_URL"); +const supported = external ? true : (await getEmbeddedPostgresTestSupport()).supported; + +describe.skipIf(!supported)("gateway credential expiry", () => { + let db: ReturnType; + let temporary: Awaited> | undefined; + let gateway: ReturnType; + let coordinator: ReturnType | undefined; + let companyId: string, agentId: string, runId: string, namedId: string; + let draining: boolean; + const errors: unknown[] = []; + + beforeAll(async () => { + if (!external) temporary = await startEmbeddedPostgresTestDatabase("gateway-expiry-"); + db = createDb(external ?? temporary!.connectionString, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 }); + }, 90_000); + afterAll(async () => { await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); }); + beforeEach(async () => { + await Promise.all(Array.from({ length: 6 }, () => db.execute(sql`select pg_sleep(0.01)`))); + companyId = randomUUID(); agentId = randomUUID(); runId = randomUUID(); draining = false; errors.length = 0; + await db.insert(companies).values({ id: companyId, name: "Credential expiry", issuePrefix: "EXP" }); + await db.insert(agents).values({ id: agentId, companyId, name: "Agent", role: "engineer", adapterType: "process" }); + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "assignment", status: "running" }); + const [profile] = await db.insert(toolProfiles).values({ companyId, profileKey: "expiry", name: "Expiry", defaultAction: "deny" }).returning(); + gateway = createToolGatewayService(db, { toolActionSigningSecret: "expiry-test-only" }); + namedId = (await gateway.createNamedGateway({ companyId, body: { name: "Expiry", profileId: profile.id } })).id; + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: true }); + }); + afterEach(async () => { + await coordinator?.stop(); coordinator = undefined; + vi.useRealTimers(); vi.restoreAllMocks(); + await db.delete(activityLog); + await db.delete(toolAccessAuditEvents); + await db.delete(toolGatewaySessions); + await db.delete(toolMcpGatewayTokens); + await db.delete(toolMcpGateways); + await db.delete(toolProfiles); + await db.delete(heartbeatRuns); + await db.delete(agents); + await db.delete(companies); + expect(errors).toEqual([]); + }); + async function start() { + coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => !draining, + canReconcile: () => true, onError: error => errors.push(error) }); + await registerGatewayCredentialExpiryWork(coordinator, gateway, () => !draining).ready; + } + async function settle(ms = 60_000) { + await vi.advanceTimersByTimeAsync(ms); + if (!draining) await vi.waitFor(async () => { + // Let real SQL settle before advancing only to an actually armed follow-up. + // Repeated blind clock jumps can expire the future credential under test. + if (idleWorkSnapshot().active > 0) { + await db.execute(sql`select pg_sleep(0.01)`); + const next = coordinator!.nextWakeAt(); + if (next !== null && next <= Date.now() + 30_000) { + await vi.advanceTimersByTimeAsync(Math.max(0, next - Date.now())); + } + } + expect(idleWorkSnapshot().active).toBe(0); + }, { timeout: 5000 }); + } + async function quiet() { + await settle(); expect(coordinator!.nextWakeAt()).toBeNull(); + const reads = vi.spyOn(db, "execute"), selects = vi.spyOn(db, "select"), deletes = vi.spyOn(db, "delete"); + await settle(60 * 60_000); + expect(reads).not.toHaveBeenCalled(); expect(selects).not.toHaveBeenCalled(); expect(deletes).not.toHaveBeenCalled(); + reads.mockRestore(); selects.mockRestore(); deletes.mockRestore(); + } + const token = (expiresAt?: Date) => gateway.createNamedGatewayToken({ companyId, gatewayId: namedId, body: { name: "Expiry", expiresAt } }); + const session = (service = gateway) => service.createSession({ companyId, agentId, runId, ttlMs: 5 * 60_000 }); + + it("stays quiet with configuration and a nonexpiring token, then expires real tokens and sessions by deadline", async () => { + await start(); await quiet(); + const retained = await token(); await quiet(); + const active = await session(); + const due = new Date(Date.now() + 3 * 60_000); + const expiring = await token(due); + await settle(); + expect(coordinator!.nextWakeAt()).toBe(due.getTime()); + const reads = vi.spyOn(db, "execute"), selects = vi.spyOn(db, "select"); + await settle(30_000); + expect(reads).not.toHaveBeenCalled(); expect(selects).not.toHaveBeenCalled(); + reads.mockRestore(); selects.mockRestore(); + await gateway.revokeNamedGatewayToken({ companyId, tokenId: expiring.id }); + await settle(2 * 60_000); + expect((await db.select().from(toolMcpGatewayTokens)).map(row => row.id)).toEqual([retained.id]); + expect(coordinator!.nextWakeAt()).toBe(active.expiresAt.getTime()); + await settle(2 * 60_000); + expect(await db.select().from(toolGatewaySessions)).toEqual([]); + await quiet(); + }); + + it.each([ + { kind: "session", rollback: false }, { kind: "session", rollback: true }, + { kind: "token", rollback: false }, { kind: "token", rollback: true }, + ])("respects $kind outer transaction settlement (rollback $rollback)", async ({ kind, rollback }) => { + await start(); await quiet(); + let release!: () => void, written!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const staged = new Promise(resolve => { written = resolve; }); + const rollbackError = new Error("rollback fixture"); + const writing = db.transaction(async tx => { + const scoped = createToolGatewayService(tx as unknown as typeof db, { toolActionSigningSecret: "expiry-test-only" }); + if (kind === "session") await session(scoped); + else await scoped.createNamedGatewayToken({ companyId, gatewayId: namedId, + body: { name: "Outer transaction", expiresAt: new Date(Date.now() + 5 * 60_000) } }); + written(); await gate; if (rollback) throw rollbackError; + }).catch(error => { if (error !== rollbackError) throw error; }); + await Promise.race([staged, writing]); + try { + await vi.advanceTimersByTimeAsync(60_000); + expect(await db.select().from(toolGatewaySessions)).toEqual([]); + expect(await db.select().from(toolMcpGatewayTokens)).toEqual([]); + } finally { release(); } + await writing; await settle(); + if (rollback) await quiet(); + else { + expect(coordinator!.nextWakeAt()).toBe(await gateway.nextCredentialExpiryAt()); + await settle(5 * 60_000); await quiet(); + } + }); + + it("coalesces sequential credential writes within the former cleanup cadence", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: false }); + const cleanup = vi.spyOn(gateway, "cleanupExpiredSessions"); + const next = vi.spyOn(gateway, "nextCredentialExpiryAt"); + await start(); + const firstPassAt = Date.now(); + for (let i = 0; i < 10; i++) { + if (i % 2 === 0) await session(); + else await token(new Date(Date.now() + 5 * 60_000)); + await vi.advanceTimersByTimeAsync(1); + // Let each old scan finish so this measures sequential writes, not overlapping calls. + await db.execute(sql`select pg_sleep(0.01)`); + } + expect(cleanup).toHaveBeenCalledTimes(1); + expect(next).toHaveBeenCalledTimes(1); + expect(coordinator!.nextWakeAt()).toBe(firstPassAt + 30_000); + await vi.advanceTimersByTimeAsync(30_000); + await vi.waitFor(() => expect(next).toHaveBeenCalledTimes(2)); + await db.execute(sql`select pg_sleep(0.01)`); + expect(cleanup).toHaveBeenCalledTimes(2); + expect(coordinator!.nextWakeAt()).toBeGreaterThan(Date.now()); + await settle(5 * 60_000); await quiet(); + }); + + it("keeps a loaded expiry deadline ahead of credential notification coalescing", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: false }); + const deadline = Date.now() + 500; + await token(new Date(deadline)); + await start(); + expect(coordinator!.nextWakeAt()).toBe(deadline); + await session(); + await vi.advanceTimersByTimeAsync(1); + await db.execute(sql`select pg_sleep(0.01)`); + expect(coordinator!.nextWakeAt()).toBe(deadline); + await vi.advanceTimersByTimeAsync(499); + await vi.waitFor(async () => expect(await db.select().from(toolMcpGatewayTokens)).toEqual([])); + expect(await db.select().from(toolGatewaySessions)).toHaveLength(1); + await settle(5 * 60_000); await quiet(); + }); + + it("rejects a newly expired credential while physical cleanup is coalesced", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: false }); + const cleanup = vi.spyOn(gateway, "cleanupExpiredSessions"); + await start(); + const at = Date.now(); + const active = await gateway.createSession({ companyId, agentId, runId, ttlMs: 1000 }); + await vi.advanceTimersByTimeAsync(1000); + await db.execute(sql`select pg_sleep(0.01)`); + expect(cleanup).toHaveBeenCalledTimes(1); + expect(await db.select().from(toolGatewaySessions)).toHaveLength(1); + await expect(gateway.listToolsForSession(active.token)).rejects.toMatchObject({ status: 401, reasonCode: "session_expired" }); + expect(coordinator!.nextWakeAt()).toBe(at + 30_000); + await vi.advanceTimersByTimeAsync(29_000); + await vi.waitFor(async () => expect(await db.select().from(toolGatewaySessions)).toEqual([])); + await quiet(); + }); + + it.each(["sessions", "tokens", "both"] as const)("drains the full %s backlog without a registered scheduler", async kind => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: false }); + const now = new Date(); + const futureSession = await session(); + const futureToken = await token(new Date(now.getTime() + 60_000)); + const nonexpiringToken = await token(); + if (kind !== "tokens") await db.insert(toolGatewaySessions).values(Array.from({ length: 1001 }, () => ({ + companyId, agentId, runId, tokenHash: randomUUID(), expiresAt: new Date(now.getTime() - 1), + }))); + if (kind !== "sessions") await db.insert(toolMcpGatewayTokens).values(Array.from({ length: 1001 }, () => ({ + companyId, gatewayId: namedId, name: "Expired", tokenHash: randomUUID(), expiresAt: new Date(now.getTime() - 1), + }))); + await expect(gateway.cleanupExpiredSessions({ now })).resolves.toEqual({ deletedCount: kind === "tokens" ? 0 : 1001 }); + expect((await db.select().from(toolGatewaySessions)).map(row => row.id)).toEqual([futureSession.id]); + expect((await db.select().from(toolMcpGatewayTokens)).map(row => row.id).sort()).toEqual([futureToken.id, nonexpiringToken.id].sort()); + expect(coordinator).toBeUndefined(); + expect(idleWorkSnapshot().active).toBe(0); + }); + + it("bounds session cleanup and schedules the remaining overdue batch", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: false }); + await db.insert(toolGatewaySessions).values(Array.from({ length: 501 }, () => ({ + companyId, agentId, runId, tokenHash: randomUUID(), expiresAt: new Date(Date.now() - 1), + }))); + const future = await session(); + const cleanup = vi.spyOn(gateway, "cleanupExpiredSessions"); + await start(); + expect(cleanup).toHaveResolvedWith({ deletedCount: 500 }); + expect(await db.select().from(toolGatewaySessions)).toHaveLength(2); + expect(coordinator!.nextWakeAt()).toBe(Date.now() + 30_000); + await vi.advanceTimersByTimeAsync(29_999); + expect(cleanup).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(1); + await vi.waitFor(async () => expect((await db.select().from(toolGatewaySessions)).map(row => row.id)).toEqual([future.id])); + await settle(5 * 60_000); await quiet(); + }); + + it("reconstructs saved token expiry on startup", async () => { + const due = new Date(Date.now() + 5 * 60_000); + await token(due); + await start(); await settle(); + expect(coordinator!.nextWakeAt()).toBe(due.getTime()); + await settle(5 * 60_000); + expect(await db.select().from(toolMcpGatewayTokens)).toEqual([]); + await quiet(); + }); + + it("drains an overdue persisted backlog across bounded batches", async () => { + await db.insert(toolMcpGatewayTokens).values(Array.from({ length: 501 }, (_, index) => ({ + companyId, gatewayId: namedId, name: `Expired ${index}`, tokenHash: randomUUID(), + tokenPrefix: "expired", expiresAt: new Date(Date.now() - 1), + }))); + await start(); + expect(coordinator!.nextWakeAt()).not.toBeNull(); + await quiet(); + expect(await db.select().from(toolMcpGatewayTokens)).toEqual([]); + }); + + it("retains cleanup through drain without permitting expired authentication", async () => { + await start(); await quiet(); draining = true; + const active = await session(); + const expiredToken = await token(new Date(Date.now() + 3 * 60_000)); + await settle(); + const reads = vi.spyOn(db, "execute"), selects = vi.spyOn(db, "select"); + await settle(10 * 60_000); + expect(reads).not.toHaveBeenCalled(); expect(selects).not.toHaveBeenCalled(); + reads.mockRestore(); selects.mockRestore(); + expect(await db.select().from(toolGatewaySessions)).toHaveLength(1); + await expect(gateway.listToolsForSession(active.token)).rejects.toMatchObject({ status: 401, reasonCode: "session_expired" }); + await expect(gateway.initializeNamedGatewayProtocol({ gatewayId: namedId, bearerToken: expiredToken.token })) + .rejects.toMatchObject({ status: 401 }); + draining = false; await settle(); + expect(await db.select().from(toolGatewaySessions)).toEqual([]); + expect(await db.select().from(toolMcpGatewayTokens)).toEqual([]); + await quiet(); + }); +}); diff --git a/server/src/__tests__/server-startup-feedback-export.test.ts b/server/src/__tests__/server-startup-feedback-export.test.ts index f3d7171c03a..9788b8599ff 100644 --- a/server/src/__tests__/server-startup-feedback-export.test.ts +++ b/server/src/__tests__/server-startup-feedback-export.test.ts @@ -71,6 +71,7 @@ const { toolGateway: { sweepActionReviews: vi.fn(async () => ({ scanned: 0 })), cleanupExpiredSessions: vi.fn(async () => ({ deletedCount: 0 })), + nextCredentialExpiryAt: vi.fn(async () => null), }, toolActionDeliveries: { hasPending: vi.fn(async () => false), sweepPending: vi.fn(async () => ({ scanned: 0, delivered: 0 })) }, }, diff --git a/server/src/__tests__/tool-gateway.test.ts b/server/src/__tests__/tool-gateway.test.ts index a1f0b553d17..4e9ba662bdf 100644 --- a/server/src/__tests__/tool-gateway.test.ts +++ b/server/src/__tests__/tool-gateway.test.ts @@ -1,3 +1,4 @@ +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; import { createHash, randomUUID } from "node:crypto"; import { createServer, type IncomingMessage } from "node:http"; import express from "express"; @@ -65,8 +66,8 @@ import { startEmbeddedPostgresTestDatabase, } from "./helpers/embedded-postgres.js"; -const externalTestDatabaseUrl = process.env.PAPERCLIP_TOOL_GATEWAY_TEST_DATABASE_URL; -const embeddedPostgresSupport = externalTestDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); +const externalTestDatabase = resolveExternalTestDatabaseUrl("PAPERCLIP_TOOL_GATEWAY_TEST_DATABASE_URL"); +const embeddedPostgresSupport = externalTestDatabase ? { supported: true } : await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; const testToolActionSigningSecret = "test-tool-action-signing-secret"; @@ -554,8 +555,9 @@ describeEmbeddedPostgres("tool gateway acceptance", () => { let tempDb: Awaited> | null = null; beforeAll(async () => { - if (!externalTestDatabaseUrl) tempDb = await startEmbeddedPostgresTestDatabase("paperclip-tool-gateway-"); - db = createDb(externalTestDatabaseUrl ?? tempDb!.connectionString); + if (externalTestDatabase) { db = createDb(externalTestDatabase); return; } + tempDb = await startEmbeddedPostgresTestDatabase("paperclip-tool-gateway-"); + db = createDb(tempDb.connectionString); }, 90_000); afterEach(async () => { diff --git a/server/src/index.ts b/server/src/index.ts index ca51efe4345..4116e46bd93 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -1,3 +1,4 @@ +import { registerGatewayCredentialExpiryWork } from "./services/gateway-credential-expiry-work.js"; import { registerSecretProposalExpiryWork } from "./services/secret-proposal-expiry-work.js"; import { registerCustomImageCleanupWork } from "./services/custom-image-cleanup-work.js"; import { registerWorkspaceRecoveryWork } from "./services/workspace-recovery-work.js"; @@ -1464,7 +1465,10 @@ async function startServerWithDatabaseTeardown( }; await timeStartupRecovery("tool_reviews", () => app.locals.toolGateway.sweepActionReviews()).catch((err: unknown) => logger.error({ err }, "startup tool review recovery failed")); - await timeStartupRecovery("gateway_sessions", () => app.locals.toolGateway.cleanupExpiredSessions()).catch((err: unknown) => logger.error({ err }, "startup gateway token cleanup failed")); + await timeStartupRecovery("gateway_sessions", () => config.heartbeatSchedulerEnabled + ? registerGatewayCredentialExpiryWork(deliveryWork, app.locals.toolGateway, + () => !isIdleTaskDrainActive() && !heartbeatSchedulerStopped && !isWarmStandby()).ready + : app.locals.toolGateway.cleanupExpiredSessions()).catch((err: unknown) => logger.error({ err }, "startup gateway token cleanup failed")); await timeStartupRecovery("delivery_workers", () => Promise.all([budgetEnforcementWorker, accountingWorker, fastResponseWorker, ...deliveryWorkers].map(worker => worker.ready))); scheduleGitHubConnectionEventPoll(); scheduleGitHubConnectionContinuitySweep(); @@ -1891,7 +1895,6 @@ async function startServerWithDatabaseTeardown( })); trackHeartbeatSchedulerWork(app.locals.toolGateway.sweepActionReviews().catch((err: unknown) => logger.error({ err }, "tool review recovery failed"))); - trackHeartbeatSchedulerWork(app.locals.toolGateway.cleanupExpiredSessions().catch((err: unknown) => logger.error({ err }, "gateway token cleanup failed"))); if (isIdleTaskDrainActive() || heartbeatSchedulerStopped) return; if (!(await heartbeat.resolveSchedulingSuppression()).suppressed) { diff --git a/server/src/services/deadline-work.ts b/server/src/services/deadline-work.ts index 9f1de1b2a24..044c3cbfce4 100644 --- a/server/src/services/deadline-work.ts +++ b/server/src/services/deadline-work.ts @@ -9,11 +9,14 @@ export function registerDeadlineWork( next: () => Promise; canRun: () => boolean; retryMs: number; + // Optional batching latency for notifications; already-known deadlines still preempt it. + notificationCoalesceMs?: number; }, ) { let requested = 1, reconciled = 0; let next: number | null = null; let earliest = 0; + let coalesceUntil = 0; return coordinator.register(queue, { retryMs: task.retryMs, pausePassiveMaintenance: true, @@ -21,6 +24,10 @@ export function registerDeadlineWork( run: async () => { if (!task.canRun()) { requested++; return; } if (Date.now() < earliest) { next = earliest; return; } + if (Date.now() < coalesceUntil && (next === null || next > Date.now())) { + next = next === null ? coalesceUntil : Math.min(next, coalesceUntil); + return; + } const generation = ++requested; earliest = Date.now() + task.retryMs; await task.run(); @@ -28,6 +35,7 @@ export function registerDeadlineWork( // Back off failed or still-overdue work, not a successfully read future deadline. if (deadline === null || deadline > Date.now()) earliest = 0; next = deadline === null ? null : Math.max(earliest, deadline); + coalesceUntil = Date.now() + (task.notificationCoalesceMs ?? 0); reconciled = generation; }, hasPending: async () => requested !== reconciled, diff --git a/server/src/services/delivery-work-notifications.ts b/server/src/services/delivery-work-notifications.ts index b6bed1d0f25..191b8aef36b 100644 --- a/server/src/services/delivery-work-notifications.ts +++ b/server/src/services/delivery-work-notifications.ts @@ -9,6 +9,7 @@ export const DELIVERY_QUEUES = { executionStatus: "execution-status", executionDisposition: "execution-disposition", environmentCleanup: "environment-cleanup", + gatewayCredentialExpiry: "gateway-credential-expiry", secretProposalExpiry: "secret-proposal-expiry", customImageExpiry: "custom-image-expiry", historicalCleanup: "historical-cleanup", diff --git a/server/src/services/gateway-credential-expiry-work.ts b/server/src/services/gateway-credential-expiry-work.ts new file mode 100644 index 00000000000..2cf6097b6d8 --- /dev/null +++ b/server/src/services/gateway-credential-expiry-work.ts @@ -0,0 +1,18 @@ +import type { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; +import { DELIVERY_QUEUES } from "./delivery-work-notifications.js"; +import { registerDeadlineWork } from "./deadline-work.js"; +import type { createToolGatewayService } from "./tool-gateway.js"; + +export function registerGatewayCredentialExpiryWork( + coordinator: ReturnType, + gateway: Pick, "cleanupExpiredSessions" | "nextCredentialExpiryAt">, + canRun: () => boolean, +) { + return registerDeadlineWork(coordinator, DELIVERY_QUEUES.gatewayCredentialExpiry, { + retryMs: 30_000, + notificationCoalesceMs: 30_000, + canRun, + run: () => gateway.cleanupExpiredSessions({ singleBatch: true }), + next: () => gateway.nextCredentialExpiryAt(), + }); +} diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index d2d703dfcd6..c75413e8529 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -9210,45 +9210,48 @@ export function createToolGatewayService( const token = generateNamedGatewayToken(tokenId); const tokenPrefix = `pcgw_${tokenId.slice(0, 8)}`; const now = new Date(); - const [row] = await db - .insert(toolMcpGatewayTokens) - .values({ - id: tokenId, - companyId: input.companyId, - gatewayId: input.gatewayId, - name: input.body.name, - tokenHash: hashGatewayToken(token), - tokenPrefix, - subjectType: input.body.subjectType ?? "gateway_client", - subjectId: input.body.subjectId ?? null, - clientLabel: input.body.clientLabel, - ownerNote: input.body.ownerNote, - allowedActions: input.body.allowedActions ?? [ - "tools/list", - "tools/call", - "resources/list", - "resources/read", - "prompts/list", - "prompts/get", - ], - expiresAt: input.body.expiresAt ?? null, - expiryOverrideReason: input.body.expiryOverrideReason ?? null, - expiryOverrideByAgentId: - input.actor?.agentId && input.body.expiryOverrideReason - ? input.actor.agentId - : null, - expiryOverrideByUserId: - input.actor?.userId && input.body.expiryOverrideReason - ? input.actor.userId - : null, - expiryOverrideAt: input.body.expiryOverrideReason ? now : null, - responsibleUserId: input.managementContext?.actor.type === "agent" ? input.managementContext.responsibleUserId : null, - createdByAgentId: input.actor?.agentId ?? null, - createdByUserId: input.actor?.userId ?? null, - createdAt: now, - updatedAt: now, - }) - .returning(); + const [row] = await db.transaction(async tx => { + if (input.body.expiresAt) await notifyDeliveryWork(tx, DELIVERY_QUEUES.gatewayCredentialExpiry); + return tx + .insert(toolMcpGatewayTokens) + .values({ + id: tokenId, + companyId: input.companyId, + gatewayId: input.gatewayId, + name: input.body.name, + tokenHash: hashGatewayToken(token), + tokenPrefix, + subjectType: input.body.subjectType ?? "gateway_client", + subjectId: input.body.subjectId ?? null, + clientLabel: input.body.clientLabel, + ownerNote: input.body.ownerNote, + allowedActions: input.body.allowedActions ?? [ + "tools/list", + "tools/call", + "resources/list", + "resources/read", + "prompts/list", + "prompts/get", + ], + expiresAt: input.body.expiresAt ?? null, + expiryOverrideReason: input.body.expiryOverrideReason ?? null, + expiryOverrideByAgentId: + input.actor?.agentId && input.body.expiryOverrideReason + ? input.actor.agentId + : null, + expiryOverrideByUserId: + input.actor?.userId && input.body.expiryOverrideReason + ? input.actor.userId + : null, + expiryOverrideAt: input.body.expiryOverrideReason ? now : null, + responsibleUserId: input.managementContext?.actor.type === "agent" ? input.managementContext.responsibleUserId : null, + createdByAgentId: input.actor?.agentId ?? null, + createdByUserId: input.actor?.userId ?? null, + createdAt: now, + updatedAt: now, + }) + .returning(); + }); if (input.managementContext) await logActivity(db, { companyId: input.companyId, ...input.managementContext.audit, action: "tool_gateway.token_created", entityType: "tool_mcp_gateway", entityId: input.gatewayId, details: { tokenId: row.id, subjectType: row.subjectType, allowedActions: row.allowedActions } }); @@ -9373,18 +9376,21 @@ export function createToolGatewayService( expiresAt: new Date(now.getTime() + sessionTtlMs(input.ttlMs)), }; - await db.insert(toolGatewaySessions).values({ - id: session.id, - companyId: session.companyId, - agentId: input.agentId, - runId: input.runId, - issueId: session.issueId, - projectId: session.projectId, - tokenHash: hashGatewayToken(token), - expiresAt: session.expiresAt, - createdAt: session.createdAt, - updatedAt: session.createdAt, - } as any); + await db.transaction(async tx => { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.gatewayCredentialExpiry); + await tx.insert(toolGatewaySessions).values({ + id: session.id, + companyId: session.companyId, + agentId: input.agentId, + runId: input.runId, + issueId: session.issueId, + projectId: session.projectId, + tokenHash: hashGatewayToken(token), + expiresAt: session.expiresAt, + createdAt: session.createdAt, + updatedAt: session.createdAt, + } as any); + }); await writeAudit({ session, @@ -11860,23 +11866,50 @@ export function createToolGatewayService( return { ...sessionView, revokedAt: session!.revokedAt ?? now }; }, - async cleanupExpiredSessions(input: { now?: Date } = {}) { + async nextCredentialExpiryAt(): Promise { + const [row] = await db.execute<{ at: string | Date | null }>(sql` + select min(expires_at) as at from ( + (select ${toolMcpGatewayTokens.expiresAt} as expires_at from ${toolMcpGatewayTokens} + where ${toolMcpGatewayTokens.expiresAt} is not null + order by ${toolMcpGatewayTokens.expiresAt} limit 1) + union all + (select ${toolGatewaySessions.expiresAt} as expires_at from ${toolGatewaySessions} + order by ${toolGatewaySessions.expiresAt} limit 1) + ) expiries + `); + return row?.at == null ? null : new Date(row.at).getTime(); + }, + + async cleanupExpiredSessions(input: { now?: Date; singleBatch?: boolean } = {}) { const now = input.now ?? new Date(); - const expiredTokens = await db.select({ id: toolMcpGatewayTokens.id }) - .from(toolMcpGatewayTokens) - .where(lte(toolMcpGatewayTokens.expiresAt, now)) - .orderBy(asc(toolMcpGatewayTokens.expiresAt), asc(toolMcpGatewayTokens.id)) - .limit(500); - if (expiredTokens.length > 0) { - await db.delete(toolMcpGatewayTokens) + let deletedCount = 0; + while (true) { + const expiredTokens = await db.select({ id: toolMcpGatewayTokens.id }) + .from(toolMcpGatewayTokens) + .where(lte(toolMcpGatewayTokens.expiresAt, now)) + .orderBy(asc(toolMcpGatewayTokens.expiresAt), asc(toolMcpGatewayTokens.id)) + .limit(500); + if (expiredTokens.length > 0) { + await db.delete(toolMcpGatewayTokens) .where(and(inArray(toolMcpGatewayTokens.id, expiredTokens.map((token) => token.id)), lte(toolMcpGatewayTokens.expiresAt, now))) .returning({ id: toolMcpGatewayTokens.id }); + } + const expiredSessions = await db.select({ id: toolGatewaySessions.id }) + .from(toolGatewaySessions) + .where(lte(toolGatewaySessions.expiresAt, now)) + .orderBy(asc(toolGatewaySessions.expiresAt), asc(toolGatewaySessions.id)) + .limit(500); + if (expiredSessions.length > 0) { + const rows = await db.delete(toolGatewaySessions) + .where(and(inArray(toolGatewaySessions.id, expiredSessions.map((session) => session.id)), lte(toolGatewaySessions.expiresAt, now))) + .returning({ id: toolGatewaySessions.id }); + deletedCount += rows.length; + } + // The worker schedules the next page; one-shot startup/manual callers + // must finish the backlog without relying on another scheduled pass. + if (input.singleBatch || (expiredTokens.length < 500 && expiredSessions.length < 500)) break; } - const rows = await db - .delete(toolGatewaySessions) - .where(lte(toolGatewaySessions.expiresAt, now)) - .returning({ id: toolGatewaySessions.id }); - return { deletedCount: rows.length }; + return { deletedCount }; }, async listRuntimeSlots(companyId?: string) {