From 77295faebc8fa0c3aa455523f2eb084974d8358d Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:10:44 -0500 Subject: [PATCH 1/7] fix(server): recover approved tool actions from committed changes (#17454) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip manages agent work and its governed tool calls. > - A human approval can persist before the approving process dispatches the tool. > - Recovery currently scans approved requests on every maintenance tick. > - Completed and deliberately inert approvals do not owe another execution. > - Test-tab approval also needs a shared execution claim before recovery can safely race the foreground path. > - This PR wakes recovery from committed changes and retries only unresolved approvals. > - Idle history becomes quiet while existing approval and execution checks remain with the gateway. ## Linked Issues or Issue Description Refs #17453. This is the fifth slice of the recurring-server sleep migration, stacked on `codex/sleep-04-tool-review-expiry`. **Problem** Approved tool requests are scanned periodically even when no executable work remains. The Test-tab foreground path lacks the request claim needed to admit concurrent recovery safely. **Proposed Solution** Use the existing transaction-aware review notification boundary and shared deadline worker. Keep signed-payload interpretation, current policy and target checks, and provider dispatch in the gateway. Share a claim between Test-tab foreground and recovery, then persist both authoritative outcome rows atomically. **Alternatives Considered** A longer interval still scans idle history. A new durable queue would duplicate existing request/invocation state. Dispatching Test-tab approvals without a claim risks duplicate external calls. ## What Changed - Recheck both principals for delegated Test-tab approvals. Save their rate receipts in the same claim transaction, share only the same bucket, and roll back new charges on denial. - Preserve delegated gateway authorization and both issuer/target rate receipts inside the existing claimed-invocation transaction; retain the durable actor during approved replay. - Expire stale managed connector payloads before consuming approved-tool admission. - Persist current rate-policy charges and their invocation receipts atomically before dispatch, preserving exact approval claim fencing and read-only preflight. - Recover approved requests at startup and after committed review changes; retry only unresolved approvals. - Leave legacy agent approvals without execute-on-approve intent inert. Repair completed Test-tab history without another provider call. - Fence Test-tab execution and outcome settlement with an atomic claim shared by both callers. Revalidate the approved target and current policy before dispatch. - Keep provider calls outside database transactions. Retain quarantine for interrupted execution and unknown outcomes. - Add a concurrent, idempotent partial index for approved-request pagination. Reuse the parent's company-scoped review signals and shared scoped deadline worker. - Remove approved scanning from the aggregate tick. Preserve the public combined sweep and scheduler-disabled startup behavior. - Document producer ownership, quiet states, lifecycle behavior, and remaining recovery duties. ## Verification Latest published head: `23868c1751c100a27f58087f7ce16b93c52d4eba`, targeting master. The review-found delegated gateway pool deadlock is repaired by passing the admission transaction through token and issuer-authority reads. Foreground and recovery each reproduced the deadlock with a one-connection pool; all three constrained-pool cases, including revoked authority, now pass. All 81 HTTP integration cases pass. The historical foreground rate-slot regression also reproduced before its repair; verified preview hashes are accepted only by read-only preflight, while consuming admission still requires the complete identity under the exact claim. Five full suites passed 329 cases; the gateway service then passed all 141 cases after two additional mixed historical hash controls. Production types/build passed before the final normal integration of master `35820cf398` (including independent Grok/Runner changes); integration validation is running. Initial fixture/assertion errors and the prior E2E restoration/cancellation deadlock remain recorded in [the owning audit](doc/idle-approved-tool-recovery.md#gateway-admission-uses-its-transaction-connection). Fresh-head CI, Greptile 5/5, and passing Ponytail are still required before merge. - Master landing reconciliation at `8dfe3958db6e4e8a0b7499f3f5be0a396ca77361` after #17453 merged: production and server test files are byte-identical to the accepted 320-case repair. The landed migration journal prefix is unchanged, and #17928's independent eval reporting changes are preserved. Fresh CI and reviews on this exact head are required before merge. - Historical-identity repair published at `096b7c7198c3ca864aca9377e261cbaa0a8aad6f` (production/test source identical to integrated acceptance `81231824d773a79fc50c835eccf7d9b3977e79fc`): all 320 accepted gateway, policy, startup, preparation-timing and authenticated HTTP management cases pass. Server types and the production server build pass. Four real historical sensitive-argument regressions failed before repair; invalid-signature, foreign-hash and stale-claim controls remain denied without dispatch or identity changes. Both agent and Test-tab calls deliver the original signed arguments once, and new rate policies still apply. - The first integrated combined run passed 319 cases and hit a Slack bot ownership collision left in a reused HTTP test database. The guard correctly returned 409. The full 78-case HTTP suite passed on a fresh dedicated fixture without product or assertion changes. Earlier fixture-construction errors are distinguished from the four real regressions in the audit document. Fresh remote CI and reviews remain required. - Parent reconciliation at `736e7f56097055e21ce13b4e45d9033391483af8`: 299 cases pass (221 full gateway/policy/startup cases and 78 assembled-server connection management cases), with no skipped cases. Server types pass. This includes real delegated Test-tab approval admission for newly added shared and caller rate rules. Fresh remote CI and Greptile review remain required. Approved delegated Test-tab calls now evaluate caller and target policies in the existing claim transaction. Real HTTP regressions first showed a missing caller charge and shared-limit self-rejection. All 78 connection-management cases and 92 gateway cases now pass on the owning branch, along with server production typechecking. All 78 connection-management cases also pass at combined tip `d25f830db89c1623bff3547bfc68015c1c66e0cf`. The three new cases cover shared charges, separate charges, rollback on denial, duplicate approval, and rejection of a later authorized call. Intermediate counter/identity fixture failures and a reused-database Slack collision are recorded in [the owning audit](https://github.com/paperclipai/paperclip/blob/bcca5b006976a471f4afd1f70c4031aa40a2b3f7/doc/idle-approved-tool-recovery.md#delegated-test-tab-admission-after-policy-changes). The earlier combined checks below remain evidence for their stated revisions. Current-head CI and review remain required. Current head: `bcca5b006976a471f4afd1f70c4031aa40a2b3f7`. This remains a single-duty PR stacked on #17453. - 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-24-recurring-server-sleep-stack.md](https://github.com/paperclipai/paperclip/blob/a021467f04d22be42ee5b0c87b6583b2300a62a9/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 the existing database-owner, single-active-writer contract. Independent SQL writers and other replicas need an explicit wake path. - Unknown provider outcomes cannot be replayed safely. Failed result persistence retains an executing claim and the existing stale-execution quarantine. - Interrupted execution and terminal interaction projection repair remain periodic until their separate slices. This PR changes only approved recovery. - A pending-only review write can trigger one empty approved-recovery pass. Settled idle work schedules no further scan. - The partial index uses the existing top-level concurrent migration executor. Snapshot pruning follows repository policy. - Cloud sleep eligibility and external alarm coverage remain unchanged. Worker quiet is not proof of deployed instance suspension. ## 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-approved-tool-recovery.md | 381 ++++++++ ...2026-10-24-recurring-server-sleep-stack.md | 115 ++- packages/db/src/client.ts | 1 + .../migrations/0384_funny_adam_warlock.sql | 1 + ...{0379_snapshot.json => 0384_snapshot.json} | 85 +- packages/db/src/migrations/meta/_journal.json | 7 + packages/db/src/schema/tool_access.ts | 1 + .../connection-management.integration.test.ts | 91 +- .../__tests__/helpers/runner-api-server.ts | 1 + .../server-startup-feedback-export.test.ts | 2 + .../tool-access-policy-service.test.ts | 120 ++- .../src/__tests__/tool-access-service.test.ts | 8 +- .../__tests__/tool-gateway-service.test.ts | 733 ++++++++++++++- server/src/index.ts | 11 +- server/src/services/approvals.ts | 17 +- .../services/delivery-work-notifications.ts | 1 + server/src/services/tool-access-policy.ts | 115 ++- .../src/services/tool-approval-execution.ts | 119 +++ server/src/services/tool-gateway.ts | 849 +++++++++--------- .../src/services/tool-review-recovery-work.ts | 33 + server/src/services/tool-review-recovery.ts | 119 +++ .../tool-review-work-notifications.ts | 5 +- server/src/services/tool-runtime-metrics.ts | 4 +- 23 files changed, 2313 insertions(+), 506 deletions(-) create mode 100644 doc/idle-approved-tool-recovery.md create mode 100644 packages/db/src/migrations/0384_funny_adam_warlock.sql rename packages/db/src/migrations/meta/{0379_snapshot.json => 0384_snapshot.json} (99%) create mode 100644 server/src/services/tool-approval-execution.ts create mode 100644 server/src/services/tool-review-recovery-work.ts create mode 100644 server/src/services/tool-review-recovery.ts diff --git a/doc/idle-approved-tool-recovery.md b/doc/idle-approved-tool-recovery.md new file mode 100644 index 00000000000..dbb7a8682c7 --- /dev/null +++ b/doc/idle-approved-tool-recovery.md @@ -0,0 +1,381 @@ +# Approved tool-action recovery + +Approved tool actions recover at startup and after committed review changes. +The aggregate maintenance tick no longer scans approved requests. The existing +request and invocation rows remain authoritative; this change adds no queue table. + +## Work and quiet states + +The gateway owns the approved-work predicate. A signed agent action with +`executionOnApprove: true` owes execution through the normal approval path. +A legacy signed action without that flag remains deliberately inert. A Test-tab +approval can owe execution even when no agent run exists. Recovery uses the saved +origin and current authorization/target checks; the scheduler sees only whether +another attempt is needed. + +Startup discovers companies with saved approved requests. Committed review +signals carry the affected company ID; subsequent discovery and recovery reads +filter by that company. The shared scoped worker coalesces changes and dispatches +one company per pass with a one-second minimum spacing. A company writing reviews +does not scan or lock another company's approved backlog. + +Recovery pages that company's approved requests in ID order using a partial index. It does not +let a full batch of unavailable approvals starve later work. A failed read or +unresolved executable approval retains a 30-second retry. New writes preserve +that company's retry deadline, while other companies can run independently. +A company pass still drains all its pages; this change does not cap provider +calls within that pass or alter the provider's existing execution timeout. Once a pass leaves no +such obligation, there is no recurring approved-recovery query. An empty system, +configured idle tools, completed history, and deliberately inert approvals are +quiet after reconciliation. + +## Producer and transaction ownership + +The existing tool-review notification boundary now signals both pending expiry +and approved recovery. This covers human review transactions, gateway approval +and accepted-interaction inference, administrative interaction resolution, review +queue invalidation, and the gateway's approval claims and managed-argument +invalidation. The notification is awaited before SQL in the existing transaction; +caller-owned outer transactions retain commit/rollback ownership. + +A pending-only change can cause one empty company-scoped discovery read. It does not +create a periodic scan. No per-route recovery bookkeeping or database listener +is added. Signals use the existing database owner's single-active-writer model. +Independent SQL writers or another process need a separate notification contract. + +## Single execution and outcome ownership + +Agent actions retain their existing approved-to-executing claim. Test-tab +foreground approval and recovery now share an equivalent claim before provider +dispatch. The invocation then starts only if the request still holds that claim. +Provider calls and target discovery remain outside SQL transactions. Current rate-policy admission and its receipt commit together in a short database transaction. + +The Test-tab invocation outcome and terminal request status commit together. +Claim timestamps fence late settlement. A later audit failure cannot overwrite +an already committed outcome. Recovery repairs legacy approved Test-tab requests +from a saved terminal invocation without decoding old arguments or calling the +provider. A legacy executing invocation moves to the existing interrupted-work +path; it is not dispatched again. + +If the provider may have run but its result cannot be persisted, the executing +claim remains authoritative. The existing stale-execution recovery quarantines +unknown outcomes. This slice does not promise exactly-once external effects or +replay an uncertain provider call. + +## Lifecycle and remaining duties + +The shared deadline worker coalesces notifications, preserves changes during a +pass, and retains skipped work across idle drain/resume. Startup reconstructs +saved approvals. Company deletion invalidates cached recovery and retries through +the same transactional notification boundary. Shutdown stops its coordinator registration. With heartbeat +scheduling disabled, startup keeps the existing one-off recovery behavior. + +Pending expiry is owned by the preceding slice. Interrupted execution and +interaction projection repair remain in the old sweep until their own migrations. +The public combined sweep retains all duties for manual/recovery callers. +No Cloud eligibility or external-wake proof changes here; worker quiet does not +establish deployed database or host suspension. + +## Verification + +Real PostgreSQL service/startup tests cover producer commit and rollback, +startup reconstruction, empty/configured/history quiet states, concrete retries, +first-write drain/resume, legacy inert approvals, and multi-page recovery. +Controlled Test-tab provider tests cover both foreground/recovery race winners, +completed legacy outcomes, interrupted legacy calls, target changes, and a failed +atomic outcome write followed by quarantine without another provider call. + +The service/startup selection passes 123 tests. The existing gateway acceptance +suite passes 92 tests. The strengthened paging and outcome-failure cases pass +again after their final edits. Workspace typecheck and build pass. Full CI and +review remain separate PR gates; no real external provider was invoked by these +fixtures. + +Review found that a one-shot success-write failure could fall into the provider +error handler and save a false failure on its second attempt. The added sequence- +based PostgreSQL fault reproduces that bug before the fix. Provider execution, +pre-dispatch validation, and outcome persistence now have separate error +boundaries. Both persistent and one-shot result-write failures retain the claim +for quarantine without repeating the call. The complete 123-test selection and +92 gateway acceptance cases pass after the repair, as do typecheck and build. + +The existing tool-access service regression now expects a completed Test-tab +request to be executed and verifies exactly one provider call before asking for +a new approval. Its full 469-test suite passes. The initial local command skipped +its database cases; the suite now honors its supplied disposable database through +the standard test-database guard independently of embedded Postgres support. + +Company-scoping regression: a real signed/reviewed action in company A previously +caused an unfiltered approved-request SELECT over company B's inert legacy action. +The captured-SQL test fails before this repair and passes with scoped reads. Added +lifecycle cases check retry preservation across committed writes, independent +company progress, and disarming after the real company-deletion producer. These +checks supplement the earlier execution, transaction, and paging evidence above. + +After company scoping, the complete gateway-service and startup selection passes +149 tests against a disposable PostgreSQL database, and server typecheck passes. +Stack integration, workspace checks, and fresh remote CI remain separate gates. + +## Preparation failures retain an approved Test-tab action + +A real PostgreSQL policy-read timeout reproduced a permanent-failure bug after +claiming a Test-tab action: the provider had never been called, but both request +and invocation were saved as failed, so approved recovery could not retry them. + +The preparation boundary now distinguishes explicit validation/access rejections +from unexpected dependency errors and transient HTTP errors. The existing +`tool-approval-execution` owner releases only its exact claim: invocation and request +are locked in the established order, their link/company/claim timestamp must +match, and the invocation must still await approval with no recorded start. +The request returns to `approved` with a transaction-aware notification. Signed +arguments and the human approval remain unchanged; the error propagates so the +existing recovery worker retains its retry obligation. + +This boundary ends before `runTestToolInvocation`. Provider dispatch and outcome +persistence keep their existing conservative no-replay behavior. A changed claim, +started invocation or prior-dispatch evidence cannot be released by this path. +If the requeue transaction itself fails, the error propagates and no terminal +failure is fabricated; existing interrupted-execution reconciliation remains the +fallback. This change does not infer replay safety from a failed requeue. + +Before the fix, both foreground and recovery timeout regressions failed. They +now observe the committed claim under a real PostgreSQL table lock, wait for +`55P03`, verify unchanged approval and no provider call, then prove automatic +recovery invokes the provider once and becomes quiet. Additional real-row cases +cover changed ownership, mismatched invocation, a started call, prior-dispatch +history, and outer-transaction rollback. A released claim cannot start execution. +All 117 gateway-service cases pass on the owning slice, including existing target +invalidation, provider-outcome persistence failures and unknown-outcome no-replay +cases. Integrated consumer checks, workspace verification and remote PR gates +must still be recorded after propagation. + + +## Agent-origin preparation and dispatch ownership + +Agent-origin approvals use the same pre-dispatch retry contract as Test-tab +approvals. Previously, a policy or identity dependency failure after claiming an +approved action permanently failed it; earlier issue/signing failures could +leave the claim executing. Preparation now has one owning error boundary around +issue, signature, identity, target, policy, managed-argument, and content checks. +Validation and nontransient access rejections retain their terminal handling. +Unexpected dependency failures and transient HTTP errors release only the exact, +still-undispatched claim to the existing approved queue and publish its existing +transactional work signal. No table, maintenance scan, or retry wrapper per +producer is added. + +`tool-approval-execution.ts` owns the shared claim token, release, and dispatch +transition. Its Test-tab claim/outcome functions remain specific to that consumer. +Both origins use the same invocation-then-request locks and verify invocation, +company, request linkage, claim timestamp, awaiting-approval state, and absence +of an earlier start before dispatch. An agent that loses its claim during +preparation cannot call the provider or overwrite its successor. The Test-tab +unapproved direct-call path retains its original behavior. + +Only preparation is retryable here. Recording the invocation start, provider +execution, and outcome persistence remain outside that catch. A provider error, +unknown outcome, or failed durable release does not establish replay safety. +Existing interruption handling remains the conservative fallback. Closed-issue +expiry, signature/target invalidation, identity authority, and policy rejection +remain enforced, including the final issue check before recording dispatch. + +Real PostgreSQL lock-timeout cases cover foreground approval and recovery: +observe the committed executing claim, block the policy read, then require the +same signed request to remain approved with no invocation start and zero provider +calls. Recovery after releasing the table lock executes once and becomes quiet. +A separate contention case replaces the claim while preparation is blocked and +proves the old owner cannot dispatch; the surviving approval later executes once. +A provider-error case proves that an already-started call is not requeued as a +preparation failure. The existing Test-tab timeout and ownership cases exercise +the other consumer of the shared boundary. + + +## New or edited rate rules during approval + +A reviewed invocation already has durable `consumedRateAdmissions` in its policy +explanation. The original read-only recheck retained unchanged rules correctly, +but new or edited rules only inspected their counters. Two approved actions could +therefore both execute against one available slot. The real recovery regression +failed for both a newly added limit and an increased limit before this repair. + +The policy service now owns `admitInvocation`: lock the company-scoped invocation, +validate its exact actor/task/tool/argument binding, recheck current policy, spend +only admissions not already recorded for that policy generation, and save the +receipt atomically. The gateway supplies its execution claim; that claim is locked +and checked by ID, invocation, company, executing status and timestamp. This also +supports historical approved requests whose invocation still says pending, without +accepting a stale claimant. Existing claim/start/settlement owners still control +provider execution. No queue table, periodic query, or per-route wrapper is added. + +Counter updates preserve the number of already spent slots when the limit changes. +A rejection by a later policy or failure to save the receipt rolls back new charges. +A retry of a committed admission retains the saved receipt, including concurrent +rechecks. Read-only approval preflight and browser authority probes stay read-only; +trust-rule usage is not counted again during execution revalidation. The policy +service and its metric helper accept only the database capabilities they use, so +transaction clients do not require a cast to a root connection. + +The owning gateway and policy suites pass all 181 cases against disposable real +PostgreSQL databases. Coverage includes two competing invocations, concurrent +retries of one invocation, changed limits, failed receipt writes, rejection after +an earlier rate charge, unchanged admissions, historical approvals, scope mismatch, +claim loss, quiet recovery and unknown provider outcomes. Server typechecking +passes after preparing current runner dependencies. + +Earlier verification failures remain part of this evidence: the first full run +was stopped because an old claim-loss fixture held the policy table while trying +to revoke the newly locked invocation. It now pauses discovery before admission +and retains the no-provider-dispatch assertion. A new receipt assertion was fixed +to permit the intended additional receipt while preserving original fields. The +next full run exposed an overly strict historical-approval check; exact execution- +claim validation fixed it. Typechecking then exposed root-client-only signatures, +which were narrowed to their actual database capabilities. The final complete +suites and TypeScript check pass; stack integration and current-head CI remain +separate gates. This proves worker and admission behavior, not deployed host sleep. + + +## Managed-argument expiry ordering + +Latest-head CI exposed a preparation-order regression in +`tool-gateway.test.ts`: a valid historical Shopify approval whose managed UCP +arguments were obsolete became `failed` instead of `expired`. The new consuming +admission compared the current invocation identity before the existing managed +argument expiry owner ran. It prevented dispatch, but bypassed the correct saved +expiry outcome. + +Approved execution now verifies target/signed/managed arguments and content +before consuming admission. Exact claim fencing, fresh policy checks, atomic +rate receipts, and the final issue-open check remain before dispatch. No check +was removed and stale payloads are not permitted to execute. + +The existing regression reproduced the CI failure on this owner in +`/tmp/sleep-approved-managed-expiry-red.log`. All 92 gateway acceptance cases +pass after the ordering change (`/tmp/sleep-approved-managed-expiry-full.log`), +including the historical approval's expired request, failed invocation with +`approvalState: expired`, and zero provider requests. Server typecheck passes +in `/tmp/sleep-approved-managed-expiry-types.log`. Latest-head remote CI and +combined-stack acceptance still need their own results. + +## Delegated Test-tab admission after policy changes + +A delegated Test-tab call has an originating agent but no gateway token. The +named-gateway admission path therefore did not evaluate its caller policy. If a +rate rule was added while approval was pending, approval charged only the target. +A shared company/tool bucket then rejected the caller against that same charge; +a caller-specific rule instead allowed execution without recording its charge. + +The Test-tab owner now supplies its caller/target policy evaluation to the existing +claim-transaction admission API. Both decisions use the claimed invocation's +receipts. The target can share the caller's charge only when the rule and bucket +match. Both receipts commit together. A denial rolls back new charges and receipts. +Management reauthorization and credential identity checks remain with their owners, +and provider execution stays outside the transaction. This adds no queue or timer. + +Three actual HTTP/PostgreSQL cases cover a newly added shared rate rule, separate +caller and target rules, and a target denial after caller admission. The unchanged +implementation failed the first two cases: the shared rule rejected execution, +and separate rules left only one charge. The denial case already passed. After +the repair, all three pass, including duplicate approval, both saved receipts, +one provider execution, and rejection of a subsequent authorized call. + +The full connection-management suite passes all 78 cases against a fresh database. +All 92 existing gateway tests and the server production typecheck also pass. +Intermediate fixture failures remain accounted for: the new assertion initially +used a nonexistent counter count field instead of remaining; the subsequent-call +fixture first reused an ended run and then lacked responsible-user authority. +The final fixture uses a new live run with the original responsible user. A reused +full-suite database also retained a conflicting Slack bot identity; final acceptance +uses a fresh isolated database. These are local checks, not current-head CI or a +host-suspension qualification. + + +## Historical argument identity compatibility repair + +Earlier invocations stored the hash of their redacted argument preview. Modern +admission correctly requires the complete request identity, including a keyed hash +for sensitive arguments. The gateway already verified signed historical arguments, +but admission rejected their saved preview hash even with no rate policy. That +permanently failed an otherwise valid approval before the provider call. + +Both agent-origin and Test-tab preparation now bind the verified complete identity +for a historical invocation before current policy admission. Signature, reviewed +target and managed-argument checks still run first. The approval execution owner +performs the identity transition in an invocation-then-request lock transaction. +It requires the exact current claim, company and invocation relationship, an +undispatched awaiting-approval invocation, and the expected reviewed/preview hash. +Unrelated saved hashes are not accepted. Modern matching identities do not add +this transaction. Current policies and rate charges still apply afterward. + +Four real-PostgreSQL regressions reproduced the defect: valid sensitive historical +arguments, with and without a newly configured rate rule, through each of the two +origins. Four controls keep invalid signatures and unrelated invocation hashes +rejected without dispatch or identity changes. The provider receives the original +verified arguments exactly once, rather than their redacted preview. A separate +real-transaction case proves a replaced claim cannot change the saved identity. + +The first draft fixtures used a nonexistent request-level tool name and then +non-sensitive arguments whose preview and complete hashes were equal. Those +fixture failures are not credited as product regressions. The corrected four +positive cases fail before the repair and all eight parameter cases pass after. +The complete gateway, policy and startup selection passes 230 cases with no skips; +server types pass. The complete assembled-server connection-management suite also +passes all 78 cases, including delegated approval and rate-policy behavior. Fresh +remote CI and reviews remain required after publication. + + +The repair was then integrated with the master-based parent, including #17918's +tracing changes, at `81231824d773a79fc50c835eccf7d9b3977e79fc`. Server types and the +production server build pass. The gateway, policy, startup and preparation-timing +suites pass all 242 cases. The complete HTTP management suite passes all 78 cases +on a fresh dedicated database, for 320 passing cases across the accepted runs. + +The first combined integrated run passed 319 cases and failed the Slack setup +case because its reused HTTP database still held the previous run's bot identity. +The existing ownership guard correctly rejected the duplicate connection. A fresh +dedicated fixture resolved that environment collision; no product behavior or +assertion changed for the rerun. That failed run remains part of the evidence. + + +## Gateway admission uses its transaction connection + +Review of the master-targeted branch exposed a delegated gateway deadlock: the +admission transaction held the sole pool connection while issuer/token authority +reads used the root client. Foreground approval and approved recovery each failed +the real one-connection regression; a revoked-issuer control already passed. +The admission callback now receives its transaction and passes it through the +existing issuer authority checks. Both connection authorization checks and the +token read use that connection. Ordinary checks retain their root client, and +current authority, claim, company and rate enforcement remain in place. +The three constrained-pool cases pass, as do all 81 HTTP integration cases and +190 gateway, policy, startup and deadline consumer cases. The initial consumer +command selected an incorrect policy filename and omitted the gateway database +override; it was interrupted and is not counted as passing evidence. + +## Pending historical approvals retain their original admission + +A second review finding concerned the normal foreground approval gate, before +execution has claimed and rebound historical arguments. A real PostgreSQL +regression with signed sensitive arguments and an already-consumed limit of one +failed with `rate_limited`; the Test-tab and invalid-signature controls passed. +The gateway now supplies the preview digest only after verifying the signed +payload and matching either supported form of the review's canonical digest. Policy may match that digest +only in a read-only preflight, with every other invocation-context field and +stored rate-rule receipt still checked. The consuming admission continues to +require the complete keyed identity, rebound under the exact execution claim. +New or changed rate rules still apply. Historical recovery, invalid signatures, +foreign invocation hashes, stale claims, and provider argument preservation stay +covered. This adds no schema, recurring query or additional connection. + +The preceding CI head also failed E2E shard 3/8. Its failure is retained in the +validation record; local gateway checks do not erase it. Fresh-head CI and both +required automated reviews remain merge gates. + +The five full gateway/policy/startup/deadline suites passed 329 cases before the +additional mixed historical identity control. The first combined attempt is +retained: a Test-tab failure-result assertion incorrectly expected a thrown +error, and reusing the earlier HTTP database left formal-approval foreign keys +that prevented gateway acceptance setup. The assertion now checks the existing +failed-result contract, with unchanged no-provider, hash and counter checks; +the complete acceptance rerun used an independently migrated gateway database. +Server production typechecking and build passed. The earlier E2E failure was a +500 during the agent-chat project-plan fixture restoration, with a PostgreSQL +deadlock in cancellation; it remains a fresh-head CI gate. 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 5bdacbcd130..b699f1b242d 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 proposals: [#17446](https://github.com/paperclipai/paperclip/pull/17446), merged; gateway credentials: [#17450](https://github.com/paperclipai/paperclip/pull/17450), merged; pending tool-review expiry implemented on slice 04; other review duties pending | +| 07 | Secret proposals, tool reviews, gateway tokens | Separate expiry/scrub/recovery owners | Secret proposals: [#17446](https://github.com/paperclipai/paperclip/pull/17446), merged; gateway credentials: [#17450](https://github.com/paperclipai/paperclip/pull/17450), merged; pending tool-review expiry: [#17453](https://github.com/paperclipai/paperclip/pull/17453), merged; approved recovery: [#17454](https://github.com/paperclipai/paperclip/pull/17454), historical argument identity repair verified and awaiting fresh CI/review; other review duties 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 | @@ -117,3 +117,116 @@ index, applies/replays its migration, and preserves approval-time rejection and separate approved/executing/projection recovery. Workspace typecheck/build and all 92 existing gateway acceptance tests also passed. The first acceptance command matched no files; the corrected `tool-gateway.test.ts` selection passed. Fresh PR CI/review remains required. + + +## Approved-review follow-up repairs (2026-10-26) + +Slice 05 preserves the rate slot admitted before a human review. Agent and +Test-tab foreground/recovery paths reuse only the exact invocation/context and +unchanged rate-policy admission while rechecking current policy. A one-call +limit must not reject the same approved operation against its own occupied slot. + +Recovery now locks and rereads invocation/request history before dispatch. +Finished records repair the request without provider replay; executing records +retain unknown-outcome recovery. Invalid signatures, unusable formal approvals, +and inconsistent invocation states settle once. Missing signing-key configuration +and temporary dependencies retain retries. Company mismatches never mutate the +foreign invocation. No new table or generic HTTP-error discard rule is introduced. + +Formal approvals awaiting human input have no recovery cadence. The existing +approval service publishes commit-aware review notifications for approve/reject +and cancellation. Its shared record owner retains the decision validation/CAS +contract; hire decisions remain with their lifecycle owner. Revision/resubmission +keeps the review parked, and startup rediscovers saved work. Budget approval writes +belong to budget incidents, not tool-gateway formal reviews. Company deletion +removes the dependent work. These exclusions come from the producer audit. + +Local evidence: the four rate-admission regressions, seven permanent-record +regressions, and four formal-approval commit/rollback regressions failed before +their respective repairs. The complete gateway, policy, approval-service and +signature suites pass (208 tests), and server typechecking passes. Configuration +failure, company boundaries, concurrent claims, provider-outcome persistence +failure, restart and paging remain covered. The paging fixture now has independent +invocations instead of 101 approvals sharing an already-expired invocation. +Full remote checks and downstream integration verification remain required; +this is not an all-stack acceptance or deployed-sleep claim. + +## Next owner audit: approved tool-action recovery + +The next branch is `codex/sleep-05-approved-tool-recovery`, based on pending +expiry PR #17453 at `ce6a260a83`. Keep this separate from interrupted execution +and terminal projection repair. The public combined sweep remains compatible. + +- `commitToolActionReview` and accepted-interaction inference in the gateway are + approved-state producers. Existing notification ownership from slice 04 can + carry the new duty without adding another wrapper around callers. +- Agent execute-on-approve uses an atomic approved-to-executing claim before + provider execution. Keep that claim and all current authorization, signed + argument, current-target, identity, and issue-state checks in the gateway. +- Approved history is not uniformly executable. Legacy signed arguments without + `executionOnApprove` are deliberately inert. The payload can be encrypted; + shared scheduling must not decode it or inspect private provider fields. +- Board Test-tab invocations are a separate execution origin. The normal fresh + approval calls `runApprovedTestInvocation`, but the already-approved branch + currently skips test-origin execution. Test execution can leave the request + approved while the invocation holds the completed result. Do not treat those + completed rows as perpetual unfinished work. +- Before driving test-origin recovery, establish the same single-execution + claim on both foreground and recovery paths. The existing test helper does + not claim the request before provider dispatch. Simply invoking it from a + new worker would risk duplicate effects during foreground/recovery races. +- Distinguish saved completed outcomes, never-dispatched approved work, and + interrupted execution with unknown outcomes. Known completed provider results + must not be converted to unknown-outcome failures because another projection + write was interrupted. Retain quarantine for actually uncertain calls. +- Concrete unresolved approval work may retain a retry; configured idle, + terminal invocation history, and deliberately inert legacy approvals must + not cause empty recurring scans. Preserve restart reconstruction and all + supported producer paths, including transitions that finish an approved row. + +This is an audit, not an implementation or readiness claim. Tests must exercise +real approval producers, foreground/recovery contention, provider failure, +commit/rollback, legacy inert approvals, completed Test-tab history, and actual +unfinished Test-tab recovery before the next PR is ready. + +Current parent CI note: #17450 at `c5c53fc43f` has Greptile 5/5. Its server shard +10/12 failed the unchanged login-cleanup consume test waiting for an idle hold. +All 16 login-cleanup tests passed locally on recheck. The run remains active; +an attempted single-job rerun was rejected as not rerunnable. Recheck after the +run finishes before requesting its one justified retry. Do not report it green. + + +Slice 05 implementation now separates approved recovery from the aggregate tick. +The existing review notification boundary wakes it after outer commit. Legacy +inert approvals and completed Test-tab history become quiet; unresolved work +retains a retry. Test-tab foreground and recovery share a claim and atomic outcome +settlement. No provider call occurs inside that transaction. See +[approved recovery](../idle-approved-tool-recovery.md). Local service/startup +verification passes 122 tests, gateway acceptance passes 92, and workspace +typecheck/build pass. Paging and outcome-failure tests passed again after their +final strengthening. Full CI/review is not yet complete. + +Parent CI follow-up: #17450's completed run was retried once for its unchanged +login-cleanup timeout after all 16 local tests passed. #17453 has a Runner +prepared-launch close failure. Seven focused local Runner cases also fail, so +this is under investigation rather than assumed flaky. No retry of that run has +been requested. Neither parent is reported green without fresh evidence. + + +Slice 05 is [#17454](https://github.com/paperclipai/paperclip/pull/17454). +Review identified a real one-shot outcome-write error path. A new regression +failed before the repair; result persistence now runs outside provider-error +handling. The repaired head passes 123 service/startup tests, 92 acceptance +tests, workspace typecheck and build. Fresh CI/review remains required. +#17450 now has passing checks after its single retry. The local Runner +reproduction for #17453 was missing the fake-provider binary: its durable state +showed ENOENT hidden by close failure. After building the fixture all seven +cases pass; one CI retry is running. + +#17453 now has passing checks after its single Runner retry. #17454's initial +server shard found an old expected approved state for a completed Test-tab call; +the updated regression requires executed and one provider call. All 469 +tool-access service tests pass after enabling the existing external database +path independently of embedded support. Its initial browser shard failed during +unrelated plan-task fixture company deletion with a concurrent activity-log FK +violation. Inspect fresh-head CI before deciding whether that needs a repair. diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index df20aa973ab..b3d66e14855 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -503,6 +503,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([ "0369_late_logan.sql", "0381_mean_scream.sql", "0382_narrow_the_executioner.sql", + "0384_funny_adam_warlock.sql", "0383_tool_review_company_expiry.sql", ]); diff --git a/packages/db/src/migrations/0384_funny_adam_warlock.sql b/packages/db/src/migrations/0384_funny_adam_warlock.sql new file mode 100644 index 00000000000..c4f62d14e82 --- /dev/null +++ b/packages/db/src/migrations/0384_funny_adam_warlock.sql @@ -0,0 +1 @@ +CREATE INDEX CONCURRENTLY IF NOT EXISTS "tool_action_requests_approved_idx" ON "tool_action_requests" USING btree ("id") WHERE "tool_action_requests"."status" = 'approved'; diff --git a/packages/db/src/migrations/meta/0379_snapshot.json b/packages/db/src/migrations/meta/0384_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0379_snapshot.json rename to packages/db/src/migrations/meta/0384_snapshot.json index 98067609cb0..bb2ed3c9595 100644 --- a/packages/db/src/migrations/meta/0379_snapshot.json +++ b/packages/db/src/migrations/meta/0384_snapshot.json @@ -1,6 +1,6 @@ { - "id": "2a9439e3-4a2b-4a20-ab2b-2aee3db8cb03", - "prevId": "a0fcd9b8-f125-4985-8795-f567466b9aef", + "id": "4f96f70a-fd19-4d35-ad8a-8d5559b83cbd", + "prevId": "410457fc-266b-4bd0-8bc0-2b14b0634d07", "version": "7", "dialect": "postgresql", "tables": { @@ -52812,6 +52812,66 @@ "method": "btree", "with": {} }, + "tool_action_requests_pending_expiry_idx": { + "name": "tool_action_requests_pending_expiry_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_action_requests\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_action_requests_company_pending_expiry_idx": { + "name": "tool_action_requests_company_pending_expiry_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_action_requests\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_action_requests_approved_idx": { + "name": "tool_action_requests_approved_idx", + "columns": [ + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_action_requests\".\"status\" = 'approved'", + "concurrently": false, + "method": "btree", + "with": {} + }, "tool_action_requests_invocation_idx": { "name": "tool_action_requests_invocation_idx", "columns": [ @@ -55222,6 +55282,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": [ @@ -55967,6 +56042,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 02023247485..6b79f74c167 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -2675,6 +2675,13 @@ "when": 1793060791727, "tag": "0383_tool_review_company_expiry", "breakpoints": true + }, + { + "idx": 384, + "version": "7", + "when": 1793060791728, + "tag": "0384_funny_adam_warlock", + "breakpoints": true } ] } diff --git a/packages/db/src/schema/tool_access.ts b/packages/db/src/schema/tool_access.ts index e970c445b6c..f1e788626e3 100644 --- a/packages/db/src/schema/tool_access.ts +++ b/packages/db/src/schema/tool_access.ts @@ -836,6 +836,7 @@ export const toolActionRequests = pgTable( .where(sql`${table.status} = 'pending'`), index("tool_action_requests_company_pending_expiry_idx").on(table.companyId, table.expiresAt) .where(sql`${table.status} = 'pending'`), + index("tool_action_requests_approved_idx").on(table.id).where(sql`${table.status} = 'approved'`), index("tool_action_requests_invocation_idx").on(table.invocationId), index("tool_action_requests_issue_idx").on(table.companyId, table.issueId), ], diff --git a/server/src/__tests__/connection-management.integration.test.ts b/server/src/__tests__/connection-management.integration.test.ts index 8f091fa49d6..2a91b321306 100644 --- a/server/src/__tests__/connection-management.integration.test.ts +++ b/server/src/__tests__/connection-management.integration.test.ts @@ -1,10 +1,12 @@ +import { createToolGatewayService } from "../services/tool-gateway.js"; +import { commitToolActionReview } from "../services/tool-action-review.js"; import { googleWorkspaceSelectedScopes, defaultGitHubReviewPolicy, SLACK_CHAT_BOT_SCOPES, SLACK_BOT_TOOL_SCOPES } from "@paperclipai/shared"; import { randomUUID, generateKeyPairSync } from "node:crypto"; import { join } from "node:path"; import { createServer } from "node:http"; -import { and, eq } from "drizzle-orm"; +import { and, eq, sql } from "drizzle-orm"; import { beforeAll, afterAll, describe, expect, it, vi } from "vitest"; -import { activityLog, agentApiKeys, companies, companySecrets, companySecretVersions, chatConversations, chatDeliveries, chatEndpoints, chatExternalPrincipals, chatIdentityLinks, toolPolicies, connectionGrants, connectionGrantDelegations, toolAccessAuditEvents, toolOauthStates, issueThreadInteractions, connectionIntentDeliveries, agents, companyMemberships, heartbeatRuns, issues, principalPermissionGrants, projects, toolConnections, toolMcpGateways, toolMcpGatewayTokens, toolActionRequests, toolCatalogEntries, toolInvocations, toolCallEvents, toolProfileBindings, plugins, adapterAuthSessions, environments, routines, chatGitHubReviews } from "@paperclipai/db"; +import { createDb, activityLog, agentApiKeys, companies, companySecrets, companySecretVersions, chatConversations, chatDeliveries, chatEndpoints, chatExternalPrincipals, chatIdentityLinks, toolPolicies, toolRateLimitCounters, connectionGrants, connectionGrantDelegations, toolAccessAuditEvents, toolOauthStates, issueThreadInteractions, connectionIntentDeliveries, agents, companyMemberships, heartbeatRuns, issues, principalPermissionGrants, projects, toolConnections, toolMcpGateways, toolMcpGatewayTokens, toolActionRequests, toolCatalogEntries, toolInvocations, toolCallEvents, toolProfileBindings, plugins, adapterAuthSessions, environments, routines, chatGitHubReviews } from "@paperclipai/db"; import { findSatisfiedToolConnection, satisfiedConnectionIntentService } from "../services/satisfied-connection-intents.js"; import { connectionManagementService, continuingConnectionManagement } from "../services/connection-management.js"; import { redactRunnerApiPayloads } from "../services/native-runtime/runner-api-log-redaction.js"; @@ -234,7 +236,7 @@ describe("connection management with production default agents", () => { expect(bindings.map(binding => binding.targetId)).toEqual([f.agentId]); }); - it.each(["none", "other-agent", "other-agent-no-access", "other-agent-allow-policy", "other-agent-explicit-grant", "other-agent-caller-ask", "other-agent-caller-rate", "other-agent-shared-rate", "other-agent-credential", "other-agent-credential-none", "other-agent-caller-revoked", "private-status", "agent", "user", "cancelled", "project-block", "rate-limit", "agent-rate-approval", "authorized-policy-edit"] as const)("keeps delegated test policy and approval continuation bounded (%s)", async revocation => { + it.each(["none", "other-agent", "other-agent-no-access", "other-agent-allow-policy", "other-agent-explicit-grant", "other-agent-caller-ask", "other-agent-new-rate", "other-agent-new-shared-rate", "other-agent-new-rate-target-block", "other-agent-caller-rate", "other-agent-shared-rate", "other-agent-credential", "other-agent-credential-none", "other-agent-caller-revoked", "private-status", "agent", "user", "cancelled", "project-block", "rate-limit", "agent-rate-approval", "authorized-policy-edit"] as const)("keeps delegated test policy and approval continuation bounded (%s)", async revocation => { const f = await fixture(); let targetAgentId = f.agentId; if (revocation.startsWith("other-agent")) { @@ -247,7 +249,7 @@ describe("connection management with production default agents", () => { await lifecycle.process(targetAgentId); await vi.waitFor(async () => expect((await agentService(server.db).getById(targetAgentId))?.status).toBe("idle")); } - const allowed = revocation === "none" || revocation === "other-agent" || revocation === "other-agent-caller-ask"; + const allowed = revocation === "none" || revocation === "other-agent" || revocation === "other-agent-caller-ask" || ["other-agent-new-rate", "other-agent-new-shared-rate"].includes(revocation); let calls = 0; const remote = createServer(async (req, res) => { const chunks: Buffer[] = []; @@ -264,7 +266,7 @@ describe("connection management with production default agents", () => { const address = remote.address(); if (!address || typeof address === "string") throw new Error("Fixture did not listen"); const mcpUrl = `http://127.0.0.1:${address.port}/mcp`; - const freezeRateClock = ["other-agent-caller-rate", "other-agent-shared-rate", "rate-limit", "agent-rate-approval"].includes(revocation); + const freezeRateClock = revocation.startsWith("other-agent-new-") || ["other-agent-caller-rate", "other-agent-shared-rate", "rate-limit", "agent-rate-approval"].includes(revocation); if (freezeRateClock) vi.useFakeTimers({ toFake: ["Date"] }); try { const created = await f.request("POST", `/companies/${f.companyId}/tools/connections`, { name: "Governed test", transport: "mcp_remote", authKind: "none", transportConfig: { url: mcpUrl } }); @@ -381,6 +383,16 @@ describe("connection management with production default agents", () => { if (revocation === "cancelled") await server.db.update(issues).set({ status: "cancelled" }).where(eq(issues.id, f.issueId)); if (revocation === "other-agent-caller-revoked") await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "Caller access revoked", policyType: "block", selectors: { connectionId: created.body.id, agentId: f.agentId }, priority: 0 }); if (revocation === "project-block") await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "New project block", policyType: "block", selectors: { connectionId: created.body.id, projectId: f.projectId }, priority: 0 }); + if (revocation.startsWith("other-agent-new-")) { + await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "New delegated test admission", policyType: "rate_limit", + selectors: { connectionId: created.body.id, ...(revocation === "other-agent-new-shared-rate" ? {} : { agentId: f.agentId }) }, + priority: -2, config: { limit: 1, windowSeconds: 60, keyBy: revocation === "other-agent-new-shared-rate" ? ["company", "tool"] : ["agent", "tool"] } }); + if (revocation === "other-agent-new-rate") await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "New test target admission", policyType: "rate_limit", + selectors: { connectionId: created.body.id, agentId: targetAgentId }, priority: -2, + config: { limit: 1, windowSeconds: 60, keyBy: ["agent", "tool"] } }); + if (revocation === "other-agent-new-rate-target-block") await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "New test target block", policyType: "block", + selectors: { connectionId: created.body.id, agentId: targetAgentId }, priority: -1 }); + } const cookie = await server.humanSession(f.userId); const approve = () => fetch(server.apiUrl + "/api" + approvalPath, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify({ companyId: f.companyId }) }); const response = await approve(); @@ -390,6 +402,20 @@ describe("connection management with production default agents", () => { else expect(settled, JSON.stringify(settled)).toMatchObject({ status: allowed ? "succeeded" : "failed" }); expect(calls).toBe(allowed ? 1 : 0); if (allowed) { expect((await approve()).status).toBe(200); expect(calls).toBe(1); } + if (revocation.startsWith("other-agent-new-")) { + const counters = await server.db.select().from(toolRateLimitCounters).where(eq(toolRateLimitCounters.companyId, f.companyId)); + expect(counters).toHaveLength(allowed ? revocation === "other-agent-new-shared-rate" ? 1 : 2 : 0); + expect(counters.every(counter => counter.remaining === 0)).toBe(true); + if (allowed) { + expect(settled.policyExplanation?.consumedRateAdmissions).toHaveLength(1); + expect(settled.policyExplanation?.delegatedCallerConsumedRateAdmissions).toHaveLength(1); + const [nextRun] = await server.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, + status: "running", responsibleUserId: f.userId, contextSnapshot: { issueId: f.issueId } }).returning(); + const nextJwt = createLocalAgentJwt(f.agentId, f.companyId, "paperclip_runner", nextRun.id, f.userId); + expect(await f.request("POST", path, body, nextJwt)).toMatchObject({ status: 200, body: { decision: "off", error: { reasonCode: "rate_limited" } } }); + expect(calls).toBe(1); + } + } } finally { if (freezeRateClock) vi.useRealTimers(); remote.closeAllConnections(); await new Promise((resolve, reject) => remote.close(error => error ? reject(error) : resolve())); } }); @@ -1229,7 +1255,7 @@ describe("connection management with production default agents", () => { expect((await use()).status).toBeGreaterThanOrEqual(400); }); - it.each(["block", "ask", "ask-board", "ask-revoked", "ask-rate", "ask-token-revoked", "ask-token-deleted", "ask-token-scope", "ask-grant-revoked", "rate", "shared-rate", "target-block", "credential"] as const)("intersects gateway issuer and target rules (%s)", async mode => { + it.each(["block", "ask", "ask-board", "ask-revoked", "ask-rate", "ask-new-rate", "ask-new-shared-rate", "ask-new-rate-target-block", "ask-token-revoked", "ask-token-deleted", "ask-token-scope", "ask-grant-revoked", "ask-one-connection", "ask-one-connection-recovery", "ask-one-connection-revoked", "rate", "shared-rate", "target-block", "credential"] as const)("intersects gateway issuer and target rules (%s)", async mode => { const f = await fixture(); const cookie = await server.humanSession(f.userId); const createdTarget = await fetch(`${server.apiUrl}/api/companies/${f.companyId}/agents`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, @@ -1302,16 +1328,59 @@ describe("connection management with production default agents", () => { if (!mode.startsWith("ask")) return; const [action] = await server.db.select().from(toolActionRequests).where(eq(toolActionRequests.invocationId, invocation.id)); expect(action.requestedByAgentId).toBe(mode === "ask-board" ? null : f.agentId); + if (mode.startsWith("ask-new-")) { + await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "New admission after review", policyType: "rate_limit", + selectors: { connectionId: connection.body.id, ...(mode === "ask-new-shared-rate" ? {} : { agentId: f.agentId }) }, + priority: -2, config: { limit: 1, windowSeconds: 60, keyBy: mode === "ask-new-shared-rate" ? ["company", "tool"] : ["agent", "tool"] } }); + if (mode === "ask-new-rate") await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "New target admission", policyType: "rate_limit", + selectors: { connectionId: connection.body.id, agentId: target.id }, priority: -1, + config: { limit: 1, windowSeconds: 60, keyBy: ["agent", "tool"] } }); + if (mode === "ask-new-rate-target-block") await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "New target block", policyType: "block", + selectors: { connectionId: connection.body.id, agentId: target.id }, priority: -1 }); + } if (mode === "ask-revoked") await server.db.insert(toolPolicies).values({ companyId: f.companyId, name: "Issuer blocked after review", policyType: "block", selectors: { connectionId: connection.body.id, agentId: f.agentId }, priority: -1 }); if (mode === "ask-token-revoked") await server.db.update(toolMcpGatewayTokens).set({ revokedAt: new Date() }).where(eq(toolMcpGatewayTokens.id, token.body.id)); if (mode === "ask-token-deleted") await server.db.delete(toolMcpGatewayTokens).where(eq(toolMcpGatewayTokens.id, token.body.id)); if (mode === "ask-token-scope") await server.db.update(toolMcpGatewayTokens).set({ allowedActions: ["tools/list"] }).where(eq(toolMcpGatewayTokens.id, token.body.id)); - if (mode === "ask-grant-revoked") await server.db.delete(principalPermissionGrants).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_connections"))); - const approvalDenied = ["ask-revoked", "ask-token-revoked", "ask-token-deleted", "ask-token-scope", "ask-grant-revoked"].includes(mode); - const response = await fetch(`${server.apiUrl}/api/tool-gateway/action-requests/${action.id}/approve`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify({ companyId: f.companyId }) }); - expect(response.status, JSON.stringify(await response.json())).toBe(approvalDenied ? 403 : 200); + if (mode === "ask-grant-revoked" || mode === "ask-one-connection-revoked") await server.db.delete(principalPermissionGrants).where(and(eq(principalPermissionGrants.principalId, f.agentId), eq(principalPermissionGrants.permissionKey, "tools:manage_connections"))); + const approvalDenied = ["ask-revoked", "ask-new-rate-target-block", "ask-token-revoked", "ask-token-deleted", "ask-token-scope", "ask-grant-revoked", "ask-one-connection-revoked"].includes(mode); + if (mode.startsWith("ask-one-connection")) { + const limited = createDb(server.databaseUrl, { maxConnections: 1, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 }); + const service = createToolGatewayService(limited); + let timer: ReturnType | undefined; + let attempt: Promise | undefined; + try { + if (mode === "ask-one-connection-recovery") await commitToolActionReview(server.db, { + companyId: f.companyId, actionRequestId: action.id, decision: "approved", actor: { userId: f.userId }, + }); + attempt = mode === "ask-one-connection-recovery" ? service.recoverApprovedActionReviews(f.companyId) + : service.approveActionRequest({ companyId: f.companyId, actionRequestId: action.id, actor: { userId: f.userId } }); + void attempt.catch(() => undefined); + const completed = Promise.race([attempt, new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error("Single-connection gateway approval did not settle")), 5000); + })]); + if (approvalDenied) await expect(completed).rejects.toMatchObject({ status: 403 }); + else await completed; + expect((await limited.execute(sql`select 1 as available`))[0].available).toBe(1); + } finally { + clearTimeout(timer); await limited.$client.end({ timeout: 1 }); await attempt?.catch(() => undefined); + } + } else { + const response = await fetch(`${server.apiUrl}/api/tool-gateway/action-requests/${action.id}/approve`, { method: "POST", headers: { cookie, origin: server.apiUrl, "Content-Type": "application/json" }, body: JSON.stringify({ companyId: f.companyId }) }); + expect(response.status, JSON.stringify(await response.json())).toBe(approvalDenied ? 403 : 200); + } expect(calls).toBe(approvalDenied ? 0 : 1); - if (mode === "ask-rate") { + if (mode.startsWith("ask-new-")) { + const counters = await server.db.select().from(toolRateLimitCounters).where(eq(toolRateLimitCounters.companyId, f.companyId)); + expect(counters).toHaveLength(approvalDenied ? 0 : mode === "ask-new-shared-rate" ? 1 : 2); + expect(counters.every(counter => counter.remaining === 0)).toBe(true); + if (!approvalDenied) { + const [settled] = await server.db.select().from(toolInvocations).where(eq(toolInvocations.id, invocation.id)); + expect(settled.policyExplanation?.consumedRateAdmissions).toHaveLength(1); + expect(settled.policyExplanation?.delegatedCallerConsumedRateAdmissions).toHaveLength(1); + } + } + if (["ask-rate", "ask-new-rate", "ask-new-shared-rate"].includes(mode)) { await rpc("tools/call", { name: tool.name, arguments: { another: true } }); expect(calls).toBe(1); } diff --git a/server/src/__tests__/helpers/runner-api-server.ts b/server/src/__tests__/helpers/runner-api-server.ts index e59e1bb61fe..40cbabf896e 100644 --- a/server/src/__tests__/helpers/runner-api-server.ts +++ b/server/src/__tests__/helpers/runner-api-server.ts @@ -60,6 +60,7 @@ export async function startRunnerApiTestServer(options: { const apiUrl = `http://127.0.0.1:${address.port}`; setupRunnerPrpWebSocketServer(http, { apiUrl }); return { + databaseUrl: temporary.connectionString, db, root, apiUrl, storage, async humanSession(userId: string) { if (!auth) throw new Error("Enable humanSessions for this fixture"); diff --git a/server/src/__tests__/server-startup-feedback-export.test.ts b/server/src/__tests__/server-startup-feedback-export.test.ts index 2ede1c6c85f..658f5c418ff 100644 --- a/server/src/__tests__/server-startup-feedback-export.test.ts +++ b/server/src/__tests__/server-startup-feedback-export.test.ts @@ -69,6 +69,8 @@ const { stop: vi.fn(async () => {}), }, toolGateway: { + recoverApprovedActionReviews: vi.fn(async () => ({ scanned: 0, retry: false })), + approvedActionReviewCompanies: vi.fn(async () => []), sweepActionReviews: vi.fn(async () => ({ scanned: 0 })), sweepExpiredActionReviews: vi.fn(async () => ({ scanned: 0 })), nextActionReviewExpiryAt: vi.fn(async () => null), diff --git a/server/src/__tests__/tool-access-policy-service.test.ts b/server/src/__tests__/tool-access-policy-service.test.ts index e74fa60b9c9..adf2fd5a374 100644 --- a/server/src/__tests__/tool-access-policy-service.test.ts +++ b/server/src/__tests__/tool-access-policy-service.test.ts @@ -1,5 +1,5 @@ import { createHash, randomUUID } from "node:crypto"; -import { eq } from "drizzle-orm"; +import { eq, sql } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; import { activityLog, @@ -34,8 +34,9 @@ import { toolAccessService } from "../services/tool-access.js"; import { createToolGatewayService, ToolGatewayHttpError } from "../services/tool-gateway.js"; import { canonicalToolArguments, signToolArguments } from "../services/tool-content-guards.js"; -const externalTestDatabaseUrl = process.env.PAPERCLIP_TOOL_POLICY_TEST_DATABASE_URL; -const embeddedPostgresSupport = externalTestDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; +const externalDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_TOOL_POLICY_TEST_DATABASE_URL"); +const embeddedPostgresSupport = externalDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; function legacySideEffectKey(invocation: typeof toolInvocations.$inferSelect, argumentsHash: string) { @@ -216,8 +217,11 @@ describeEmbeddedPostgres("tool access policy service", () => { let tempDb: Awaited> | null = null; beforeAll(async () => { - if (!externalTestDatabaseUrl) tempDb = await startEmbeddedPostgresTestDatabase("paperclip-tool-access-policy-"); - db = createDb(externalTestDatabaseUrl ?? tempDb!.connectionString); + if (externalDatabaseUrl) db = createDb(externalDatabaseUrl); + else { + tempDb = await startEmbeddedPostgresTestDatabase("paperclip-tool-access-policy-"); + db = createDb(tempDb.connectionString); + } }, 20_000); afterEach(async () => { @@ -1115,11 +1119,103 @@ describeEmbeddedPostgres("tool access policy service", () => { expect(await svc.decide(input, { admittedInvocationId: invocation.id })).toMatchObject({ allowed: true }); expect(await db.select().from(toolRateLimitCounters)).toEqual(counters); expect((await db.select().from(toolRateLimitCounters))[0].remaining).toBe(0); - // Neither a new invocation nor an accidental consuming recheck can borrow - // another invocation's already-spent slot. + // A fresh invocation cannot borrow another invocation's already-spent slot. + // Execution revalidation retains its own durable admission. expect(await svc.decide(input, { admittedInvocationId: randomUUID() })).toMatchObject({ decision: "rate_limited" }); - expect(await svc.decide({ ...input, consumeRateLimit: true }, { admittedInvocationId: invocation.id })) - .toMatchObject({ decision: "rate_limited" }); + expect(await svc.admitInvocation(input, invocation.id)).toMatchObject({ allowed: true }); + expect(await db.select().from(toolRateLimitCounters)).toEqual(counters); + }); + + it("atomically charges a new rule once across concurrent retries of the same invocation", async () => { + const { company, input, invocation, svc } = await admittedRateLimitedInvocation(); + const added = await svc.createPolicy(company.id, { name: "New admission", policyType: "rate_limit", priority: 0, + selectors: { toolName: "send_email" }, config: { limit: 1, windowSeconds: 3600, keyBy: ["agent", "tool"] } }); + const oldCounters = await db.select().from(toolRateLimitCounters); + expect(await svc.decide(input, { admittedInvocationId: invocation.id })).toMatchObject({ allowed: true }); + expect(await db.select().from(toolRateLimitCounters)).toEqual(oldCounters); + const results = await Promise.all(Array.from({ length: 4 }, () => svc.admitInvocation(input, invocation.id))); + expect(results.every(result => result.allowed)).toBe(true); + expect(await db.select().from(toolRateLimitCounters).where(eq(toolRateLimitCounters.policyId, added.id))) + .toMatchObject([{ limit: 1, remaining: 0 }]); + const [saved] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, invocation.id)); + expect(saved.policyExplanation?.consumedRateAdmissions).toHaveLength(2); + const { consumedRateAdmissions: oldAdmissions, ...oldExplanation } = invocation.policyExplanation!; + expect(saved.policyExplanation).toMatchObject(oldExplanation); + expect(saved.policyExplanation?.consumedRateAdmissions).toEqual(expect.arrayContaining(oldAdmissions as unknown[])); + }); + + it("allows only one of two admitted invocations to spend a newly added final slot", async () => { + const { company, input, invocation, svc } = await admittedRateLimitedInvocation(2); + const initial = await svc.decide({ ...input, consumeRateLimit: true }); + expect(initial.allowed).toBe(true); + const { invocation: second } = await svc.recordInvocation(input, initial); + await db.update(toolInvocations).set({ status: "executing" }).where(eq(toolInvocations.id, second.id)); + const added = await svc.createPolicy(company.id, { name: "One competing slot", policyType: "rate_limit", priority: 0, + selectors: { toolName: "send_email" }, config: { limit: 1, windowSeconds: 3600, keyBy: ["agent", "tool"] } }); + const results = await Promise.all([invocation.id, second.id].map(id => svc.admitInvocation(input, id))); + expect(results.filter(result => result.allowed)).toHaveLength(1); + expect(results.filter(result => result.decision === "rate_limited")).toHaveLength(1); + expect(await db.select().from(toolRateLimitCounters).where(eq(toolRateLimitCounters.policyId, added.id))) + .toMatchObject([{ limit: 1, remaining: 0 }]); + }); + + it("rolls back new rate charges when a later policy rejects the invocation", async () => { + const { company, input, invocation, svc } = await admittedRateLimitedInvocation(); + await svc.createPolicy(company.id, { name: "Before rejection", policyType: "rate_limit", priority: 0, + selectors: { toolName: "send_email" }, config: { limit: 1, windowSeconds: 3600, keyBy: ["agent", "tool"] } }); + await svc.createPolicy(company.id, { name: "Later rejection", policyType: "block", priority: 10, + selectors: { toolName: "send_email" } }); + const counters = await db.select().from(toolRateLimitCounters); + expect(await svc.admitInvocation(input, invocation.id)).toMatchObject({ decision: "deny" }); + expect(await db.select().from(toolRateLimitCounters)).toEqual(counters); + expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, invocation.id)))[0].policyExplanation) + .toEqual(invocation.policyExplanation); + }); + + it("rolls back rate charges when saving the admission receipt fails and admits a retry once", async () => { + const { company, input, invocation, svc } = await admittedRateLimitedInvocation(); + const added = await svc.createPolicy(company.id, { name: "Receipt failure", policyType: "rate_limit", priority: 0, + selectors: { toolName: "send_email" }, config: { limit: 1, windowSeconds: 3600, keyBy: ["agent", "tool"] } }); + await db.execute(sql`create function sleep_admission_fail() returns trigger language plpgsql as $$ begin + raise exception 'receipt write unavailable'; end $$`); + await db.execute(sql`create trigger sleep_admission_fail before update of policy_explanation on tool_invocations + for each row execute function sleep_admission_fail()`); + try { + await expect(svc.admitInvocation(input, invocation.id)).rejects.toThrow(); + expect(await db.select().from(toolRateLimitCounters).where(eq(toolRateLimitCounters.policyId, added.id))).toEqual([]); + expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, invocation.id)))[0].policyExplanation) + .toEqual(invocation.policyExplanation); + } finally { + await db.execute(sql`drop trigger sleep_admission_fail on tool_invocations`); + await db.execute(sql`drop function sleep_admission_fail()`); + } + expect(await svc.admitInvocation(input, invocation.id)).toMatchObject({ allowed: true }); + expect(await svc.admitInvocation(input, invocation.id)).toMatchObject({ allowed: true }); + expect(await db.select().from(toolRateLimitCounters).where(eq(toolRateLimitCounters.policyId, added.id))) + .toMatchObject([{ limit: 1, remaining: 0 }]); + }); + + it.each([2, 4])("preserves spent slots when a rate limit changes from three to %s", async limit => { + const { company, input, ratePolicy, svc } = await admittedRateLimitedInvocation(3); + await svc.updatePolicy({ companyId: company.id, policyId: ratePolicy.id, + body: { config: { limit, windowSeconds: 3600, keyBy: ["agent", "tool"] } } }); + const results = await Promise.all(Array.from({ length: limit }, () => svc.decide({ ...input, consumeRateLimit: true }))); + expect(results.filter(result => result.allowed)).toHaveLength(limit - 1); + expect(results.filter(result => result.decision === "rate_limited")).toHaveLength(1); + expect(await db.select().from(toolRateLimitCounters)).toMatchObject([{ limit, remaining: 0 }]); + }); + + it.each(["pending", "approved"] as const)("retains a waiting invocation's consumed slot without bypassing %s approval policy", async approvalState => { + const { company, input, invocation, svc } = await admittedRateLimitedInvocation(); + await db.update(toolInvocations).set({ status: "awaiting_approval", policyDecision: "require_approval", approvalState }) + .where(eq(toolInvocations.id, invocation.id)); + await db.insert(toolPolicies).values({ companyId: company.id, name: "Review admitted sends", + policyType: "require_approval", priority: 2, selectors: { toolName: "send_email" } }); + const counters = await db.select().from(toolRateLimitCounters); + expect(await svc.decide(input, { admittedInvocationId: invocation.id })) + .toMatchObject({ allowed: false, decision: "require_approval" }); + expect(await db.select().from(toolRateLimitCounters)).toEqual(counters); + expect(await svc.decide(input)).toMatchObject({ decision: "rate_limited" }); }); it("rechecks a newly added rate policy rather than borrowing an older policy's consumed slot", async () => { @@ -1172,15 +1268,19 @@ describeEmbeddedPostgres("tool access policy service", () => { { actorType: "system" }, { actorId: randomUUID() }, { agentId: null }, { runId: null }, { issueId: null }, { gatewayId: null }, { applicationId: null }, { connectionId: null }, { catalogEntryId: null }, { toolName: "different_tool" }, { providerType: null }, { applicationKey: null }, { upstreamToolName: null }, { argumentsHash: "different" }, - { status: "authorized" }, { policyDecision: "deny" }, { policyDecision: "require_approval", approvalState: "pending" }, + { status: "authorized" }, { status: "succeeded" }, { status: "awaiting_approval" }, + { status: "awaiting_approval", policyDecision: "require_approval", approvalState: "rejected" }, { policyDecision: "deny" }, { policyDecision: "require_approval", approvalState: "pending" }, ]; for (const mutation of mutations) { await db.update(toolInvocations).set(mutation).where(eq(toolInvocations.id, invocation.id)); expect(await svc.decide(input, options), JSON.stringify(mutation)).toMatchObject({ decision: "rate_limited" }); + expect(await svc.admitInvocation(input, invocation.id), JSON.stringify(mutation)).toMatchObject({ decision: "deny" }); await db.update(toolInvocations).set({ ...invocation, status: "executing" }).where(eq(toolInvocations.id, invocation.id)); } expect(await svc.decide({ ...input, request: { ...input.request, arguments: { to: "another@example.test" } } }, options)) .toMatchObject({ decision: "rate_limited" }); + expect(await svc.admitInvocation({ ...input, request: { ...input.request, arguments: { to: "another@example.test" } } }, invocation.id)) + .toMatchObject({ decision: "deny" }); }); it("rejects unsupported policy semantics at create and update time", async () => { diff --git a/server/src/__tests__/tool-access-service.test.ts b/server/src/__tests__/tool-access-service.test.ts index 6caafb2cb03..e5629ead55f 100644 --- a/server/src/__tests__/tool-access-service.test.ts +++ b/server/src/__tests__/tool-access-service.test.ts @@ -1,3 +1,4 @@ +import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; import * as fs from "node:fs/promises"; import { createHash, generateKeyPairSync, randomUUID } from "node:crypto"; import { createServer } from "node:http"; @@ -97,8 +98,8 @@ import { HttpError } from "../errors.js"; import type { VercelConnectClient } from "../services/vercel-connect.js"; import { invalidatePaperclipCloudConnectorCapabilities, PaperclipCloudConnectorError, type PaperclipCloudConnector } from "../services/paperclip-cloud-connector.js"; -const externalDatabaseUrl = process.env.PAPERCLIP_TOOL_ACCESS_TEST_DATABASE_URL?.trim(); -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); +const externalDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_TOOL_ACCESS_TEST_DATABASE_URL"); +const embeddedPostgresSupport = externalDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; @@ -4119,8 +4120,9 @@ describeEmbeddedPostgres("tool access service", () => { .from(toolActionRequests) .where(eq(toolActionRequests.companyId, company.id)); expect(requests).toHaveLength(2); + expect(globalThis.fetch).toHaveBeenCalledTimes(1); expect(requests.map((row) => row.status).sort()).toEqual([ - "approved", + "executed", "pending", ]); }); diff --git a/server/src/__tests__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index 3e9829670c6..4a014b22ab0 100644 --- a/server/src/__tests__/tool-gateway-service.test.ts +++ b/server/src/__tests__/tool-gateway-service.test.ts @@ -35,12 +35,15 @@ import { toolGatewaySessions, toolInvocations, toolPolicies, + toolRateLimitCounters, } from "@paperclipai/db"; import type { PluginToolDispatcher } from "../services/plugin-tool-dispatcher.js"; import type { VercelConnectClient } from "../services/vercel-connect.js"; import { initializeRunIdentity, reserveSteeredIdentity, reconcileSteeredIdentity } from "../services/run-identity.js"; import { issueService } from "../services/issues.js"; +import { approvalService } from "../services/approvals.js"; import { commitToolActionReview } from "../services/tool-action-review.js"; +import { bindVerifiedToolApprovalArguments, claimToolTestApproval, releaseToolApproval, startToolInvocation } from "../services/tool-approval-execution.js"; import { materializeNativeInteractionResponses } from "../services/native-runtime/native-interaction-bridge.js"; import { toolActionDeliveryService } from "../services/tool-action-delivery.js"; import { secretService } from "../services/secrets.js"; @@ -49,7 +52,7 @@ import { createToolGatewayService, ToolGatewayHttpError, } from "../services/tool-gateway.js"; -import { canonicalToolArguments, signToolArguments } from "../services/tool-content-guards.js"; +import { canonicalToolArguments, readSignedToolArgumentsPayload, signToolArguments, summarizeToolValue, toolRequestIdentityHash } from "../services/tool-content-guards.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, @@ -57,6 +60,7 @@ import { import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js"; import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; +import { registerToolReviewRecoveryWork } from "../services/tool-review-recovery-work.js"; import { registerToolReviewExpiryWork } from "../services/tool-review-expiry-work.js"; import { idleWorkSnapshot } from "../services/task-admission.js"; @@ -210,7 +214,7 @@ function runSessionInput(company: IdRef, agent: IdRef, run: IdRef): Parameters { let db!: ReturnType; let tempDb: Awaited> | null = null; - let stopExpiryWorker: (() => Promise) | undefined; + let stopReviewWorker: (() => Promise) | undefined; beforeAll(async () => { if (!externalDatabaseUrl) tempDb = await startEmbeddedPostgresTestDatabase("paperclip-tool-gateway-"); @@ -221,7 +225,7 @@ describeEmbeddedPostgres("tool gateway service", () => { }, 20_000); afterEach(async () => { - await stopExpiryWorker?.(); stopExpiryWorker = undefined; + await stopReviewWorker?.(); stopReviewWorker = undefined; await clearFixtures(); }); @@ -268,7 +272,7 @@ describeEmbeddedPostgres("tool gateway service", () => { await db.insert(toolPolicies).values(reviewNotePolicyRow(fixture.company)); gateway = createTestToolGatewayService(db); draining = false; errors.length = 0; - stopExpiryWorker = stopWorker; + stopReviewWorker = stopWorker; vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: true }); }); async function stopWorker() { @@ -276,6 +280,7 @@ describeEmbeddedPostgres("tool gateway service", () => { vi.useRealTimers(); vi.restoreAllMocks(); await db.execute(sql`drop trigger if exists sleep_review_fail on tool_invocations`); await db.execute(sql`drop function if exists sleep_review_fail()`); + await db.execute(sql`drop sequence if exists sleep_review_failure_attempt`); expect(errors).toEqual([]); } async function start() { @@ -313,6 +318,710 @@ describeEmbeddedPostgres("tool gateway service", () => { expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toEqual([]); } + describe("approved review recovery worker", () => { + async function startRecovery() { + coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => !draining, + canReconcile: () => true, onError: error => errors.push(error) }); + await registerToolReviewRecoveryWork(coordinator, gateway, () => !draining).ready; + } + const approve = (pending: Awaited>, source = db) => commitToolActionReview(source, { + companyId: fixture.company.id, actionRequestId: pending.id, decision: "approved", actor: { userId: "board" }, + }); + async function executed(pending: Awaited>) { + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0].status).toBe("executed"); + expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0].status).toBe("succeeded"); + } + + it("is quiet while configured idle and executes a committed approval once", async () => { + await startRecovery(); await quiet(); + const pending = await request(); await approve(pending); await settle(); + await executed(pending); await quiet(); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(1); + }); + + it("does not scan another company's approved backlog after review writes", async () => { + const other = await createRunFixture(db); + await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company)); + const foreign = await request(gateway, db, other); + await db.update(toolActionRequests).set({ signedArguments: signToolArguments({ + invocationId: foreign.invocationId, toolName: "mcp-remote-fixture:update_note", + canonicalArguments: canonicalToolArguments({ noteId: "legacy", body: "inert" }), + signingSecret: testToolActionSigningSecret, + }) }).where(eq(toolActionRequests.id, foreign.id)); + await commitToolActionReview(db, { companyId: other.company.id, actionRequestId: foreign.id, + decision: "approved", actor: { userId: "board" } }); + await startRecovery(); await quiet(); + 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('"tool_action_requests"') && + query.includes('"tool_action_requests"."status" =') && params.includes("approved")) + reads.push({ query, params: [...params] }); + }; + try { + for (let index = 0; index < 3; index++) { + const pending = await request(); await settle(1500); + await approve(pending); await settle(1500); await executed(pending); + } + } finally { db.$client.options.debug = debug; } + expect(reads.length).toBeGreaterThan(0); + for (const read of reads) { + expect(read.query).toContain('"tool_action_requests"."company_id" ='); + expect(read.params).toContain(fixture.company.id); + expect(read.params).not.toContain(other.company.id); + } + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, foreign.id)))[0].status).toBe("approved"); + expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, foreign.invocationId)))[0].status).toBe("awaiting_approval"); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(3); + await quiet(); + }); + + it.each(["foreground", "recovery"] as const)("preserves the admitted rate slot for an agent action through %s approval", async mode => { + await db.insert(toolPolicies).values({ companyId: fixture.company.id, name: "One reviewed note", + policyType: "rate_limit", priority: 1, selectors: { toolName: "mcp-remote-fixture:update_note" }, + config: { limit: 1, windowSeconds: 3600, keyBy: ["agent", "tool"] } }); + const pending = await request(); + const counters = await db.select().from(toolRateLimitCounters); + expect(counters).toHaveLength(1); expect(counters[0].remaining).toBe(0); + if (mode === "foreground") { + await gateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }); + await startRecovery(); + } else { await approve(pending); await startRecovery(); } + await settle(); await executed(pending); await quiet(); + expect(await db.select().from(toolRateLimitCounters)).toEqual(counters); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(1); + }); + + it.each(["new", "increased"] as const)("spends the newly available slot of a %s rate rule during approved recovery", async change => { + const rate = { companyId: fixture.company.id, name: "Changed reviewed-note limit", + policyType: "rate_limit" as const, priority: 1, selectors: { toolName: "mcp-remote-fixture:update_note" }, + config: { limit: 2, windowSeconds: 3600, keyBy: ["agent", "tool"] } }; + const original = change === "increased" ? (await db.insert(toolPolicies).values(rate).returning())[0] : null; + const first = await request(), second = await request(); + if (original) { + await db.update(toolPolicies).set({ config: { ...rate.config, limit: 3 }, updatedAt: new Date() }) + .where(eq(toolPolicies.id, original.id)); + } else { + await db.insert(toolPolicies).values({ ...rate, config: { ...rate.config, limit: 1 } }); + } + await approve(first); await approve(second); + await startRecovery(); await settle(); await quiet(); + const requests = await db.select().from(toolActionRequests); + expect(requests.filter(row => row.status === "executed")).toHaveLength(1); + expect(requests.filter(row => row.status === "failed")).toHaveLength(1); + const invocations = await db.select().from(toolInvocations); + expect(invocations.filter(row => row.errorCode === "rate_limited")).toHaveLength(1); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(1); + const counters = await db.select().from(toolRateLimitCounters); + expect(counters).toHaveLength(1); + expect(counters[0]).toMatchObject({ limit: change === "increased" ? 3 : 1, remaining: 0 }); + }); + + it.each([ + ...["agent", "test-tab"].flatMap(origin => ["valid", "new-rate", "invalid-signature", "foreign-hash", "foreground-rate", "foreground-invalid-signature", "foreground-foreign-hash", "foreground-modern-review-hash"] + .map(state => ({ origin, state }))), + ])("recovers historical preview-hash approval ($origin, $state)", async ({ origin, state }) => { + const remoteCall = providerFixture(); remoteCall.release(); + const parameters = { value: "reviewed", apiKey: "synthetic-historical-approval-key" }; + const foreground = state.startsWith("foreground-"); + if (foreground) await db.insert(toolPolicies).values({ companyId: fixture.company.id, + name: "Already admitted historical action", policyType: "rate_limit", priority: 1, + selectors: {}, config: { limit: 1, windowSeconds: 3600, keyBy: ["company", "tool"] } }); + const pending = origin === "agent" ? await agentRequest(remoteCall.provider, parameters) + : (await testRequest(remoteCall.provider, false, parameters)).pending; + const [originalInvocation] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)); + const payload = readSignedToolArgumentsPayload({ signedArguments: pending.signedArguments, + invocationId: pending.invocationId, toolName: originalInvocation.toolName, signingSecret: testToolActionSigningSecret })!; + expect(payload).not.toBeNull(); + const legacyHash = summarizeToolValue(payload.arguments).sha256!; + const completeHash = toolRequestIdentityHash(payload.arguments, testToolActionSigningSecret); + expect(legacyHash).not.toBe(completeHash); + const storedHash = state.endsWith("foreign-hash") ? "e".repeat(64) : legacyHash; + await db.update(toolInvocations).set({ argumentsHash: storedHash }).where(eq(toolInvocations.id, pending.invocationId)); + await db.update(toolActionRequests).set({ canonicalArgumentsHash: state === "foreground-modern-review-hash" ? completeHash : legacyHash, + ...(["invalid-signature", "foreground-invalid-signature"].includes(state) ? { signedArguments: "unreadable-old-signature" } : {}), + }).where(eq(toolActionRequests.id, pending.id)); + if (state === "new-rate") await db.insert(toolPolicies).values({ companyId: fixture.company.id, + name: "New admission for historical approval", policyType: "rate_limit", priority: 1, + selectors: {}, config: { limit: 1, windowSeconds: 3600, keyBy: ["company", "tool"] } }); + const counters = foreground ? await db.select().from(toolRateLimitCounters) : []; + if (foreground) { + expect(counters).toEqual([expect.objectContaining({ remaining: 0 })]); + const approval = gateway.approveActionRequest({ companyId: fixture.company.id, + actionRequestId: pending.id, actor: { userId: "board" } }); + if (state === "foreground-invalid-signature") await expect(approval).rejects.toMatchObject({ reasonCode: "action_request_invalidated" }); + else if (state === "foreground-foreign-hash" && origin === "agent") await expect(approval).rejects.toMatchObject({ reasonCode: "rate_limited" }); + else await approval; + } else await approve(pending); + await startRecovery(); await settle(); + if (state === "valid" || state === "new-rate" || state === "foreground-rate" || state === "foreground-modern-review-hash") { + await executed(pending); + expect((await db.select().from(toolInvocations))[0].argumentsHash).toBe(completeHash); + expect(remoteCall.provider).toHaveBeenCalledOnce(); + expect(JSON.parse(String(remoteCall.provider.mock.calls[0][1].body)).params.arguments).toEqual(parameters); + if (state === "new-rate") expect(await db.select().from(toolRateLimitCounters)) + .toEqual([expect.objectContaining({ limit: 1, remaining: 0 })]); + } else { + expect((await db.select().from(toolActionRequests))[0].status) + .toBe(["invalid-signature", "foreground-invalid-signature"].includes(state) ? "cancelled" + : state === "foreground-foreign-hash" && origin === "agent" ? "pending" : "failed"); + expect((await db.select().from(toolInvocations))[0].argumentsHash).toBe(storedHash); + expect(remoteCall.provider).not.toHaveBeenCalled(); + } + if (foreground) expect(await db.select().from(toolRateLimitCounters)).toEqual(counters); + await quiet(); + }); + + it("does not rebind historical arguments after the execution claim is replaced", async () => { + const remoteCall = providerFixture(); remoteCall.release(); + const pending = await agentRequest(remoteCall.provider, { value: "reviewed", apiKey: "synthetic-stale-claim-key" }); + const [invocation] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)); + const payload = readSignedToolArgumentsPayload({ signedArguments: pending.signedArguments, + invocationId: invocation.id, toolName: invocation.toolName, signingSecret: testToolActionSigningSecret })!; + const preview = summarizeToolValue(payload.arguments).sha256; + const verified = toolRequestIdentityHash(payload.arguments, testToolActionSigningSecret); + await db.update(toolInvocations).set({ argumentsHash: preview }).where(eq(toolInvocations.id, invocation.id)); + await db.update(toolActionRequests).set({ canonicalArgumentsHash: preview }).where(eq(toolActionRequests.id, pending.id)); + await approve(pending); + const claim = (await claimToolTestApproval(db, pending.id, invocation.id))!; + expect(claim).not.toBeNull(); + await db.update(toolActionRequests).set({ updatedAt: new Date(claim.claimedAt.getTime() + 1) }) + .where(eq(toolActionRequests.id, pending.id)); + expect(await bindVerifiedToolApprovalArguments(db, claim, { preview, verified })).toBe(false); + expect((await db.select().from(toolInvocations))[0].argumentsHash).toBe(preview); + expect(remoteCall.provider).not.toHaveBeenCalled(); + }); + + it("reconstructs a saved approved action after restart", async () => { + const pending = await request(); await approve(pending); + await startRecovery(); await settle(); await executed(pending); await quiet(); + }); + + it("retries a failed approval dispatch only while the approved action remains unresolved", async () => { + const pending = await request(); await approve(pending); + const recover = vi.spyOn(gateway, "approveActionRequest").mockRejectedValue(new Error("Recovery dependency unavailable")); + await startRecovery(); + expect(recover).toHaveBeenCalledTimes(1); expect(coordinator!.nextWakeAt()).not.toBeNull(); + await settle(10_000); expect(recover).toHaveBeenCalledTimes(1); + recover.mockRestore(); await settle(); await executed(pending); await quiet(); + }); + + it("preserves a failed company's retry across writes while another company executes", async () => { + const pending = await request(); await approve(pending); + const original = gateway.approveActionRequest.bind(gateway); + const dispatch = vi.spyOn(gateway, "approveActionRequest").mockImplementation(async input => { + if (input.companyId === fixture.company.id) throw new Error("Company dependency unavailable"); + return original(input); + }); + await startRecovery(); + expect(dispatch).toHaveBeenCalledTimes(1); + const retryAt = coordinator!.nextWakeAt(); + expect(retryAt).not.toBeNull(); + const later = await request(); await approve(later); + const other = await createRunFixture(db); + await db.insert(toolPolicies).values(reviewNotePolicyRow(other.company)); + const foreign = await request(gateway, db, other); + await commitToolActionReview(db, { companyId: other.company.id, actionRequestId: foreign.id, + decision: "approved", actor: { userId: "board" } }); + await settle(5000); await executed(foreign); + expect(dispatch.mock.calls.filter(([input]) => input.companyId === fixture.company.id)).toHaveLength(1); + expect(coordinator!.nextWakeAt()).toBe(retryAt); + dispatch.mockRestore(); + await settle(); await executed(pending); await executed(later); await quiet(); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(3); + }); + + it("disarms a failed company's recovery after company deletion commits", async () => { + const pending = await request(); await approve(pending); + const dispatch = vi.spyOn(gateway, "approveActionRequest").mockRejectedValue(new Error("Company dependency unavailable")); + await startRecovery(); expect(coordinator!.nextWakeAt()).not.toBeNull(); + await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }) + .where(eq(heartbeatRuns.id, fixture.run.id)); + await db.update(agents).set({ status: "terminated", lifecycleState: "terminated" }) + .where(eq(agents.id, fixture.agent.id)); + await deleteCompany(db, fixture.company.id); + await settle(1500); + expect(coordinator!.nextWakeAt()).toBeNull(); + expect(dispatch).toHaveBeenCalledTimes(1); await quiet(); + }); + + it.each([null, "unreadable-old-signature"])("settles an approved invalid signature (%s) without recurring recovery", async signedArguments => { + const pending = await request(); await approve(pending); + await db.update(toolActionRequests).set({ signedArguments }).where(eq(toolActionRequests.id, pending.id)); + const dispatch = vi.spyOn(gateway, "approveActionRequest"); + await startRecovery(); await settle(); + expect((await db.select().from(toolActionRequests))[0].status).toBe("cancelled"); + expect((await db.select().from(toolInvocations))[0]).toMatchObject({ + status: "failed", errorCode: "action_request_invalidated", + }); + expect(dispatch).not.toHaveBeenCalled(); await quiet(); + }); + + it.each(["rejected", "cancelled"])("settles a %s formal approval without recurring recovery", async status => { + const pending = await request(); await approve(pending); + const [formal] = await db.insert(approvals).values({ companyId: fixture.company.id, + type: "request_board_approval", status, payload: {} }).returning(); + await db.update(toolActionRequests).set({ approvalId: formal.id }).where(eq(toolActionRequests.id, pending.id)); + const dispatch = vi.spyOn(gateway, "approveActionRequest"); + await startRecovery(); await settle(); + expect((await db.select().from(toolActionRequests))[0].status).toBe("cancelled"); + expect((await db.select().from(toolInvocations))[0]).toMatchObject({ + status: "denied", errorCode: "formal_approval_unavailable", + }); + expect(dispatch).not.toHaveBeenCalled(); await quiet(); + }); + + it.each([false, true])("parks a formal approval until its decision commits (rollback %s)", async rollback => { + const pending = await request(); await approve(pending); + const [formal] = await db.insert(approvals).values({ companyId: fixture.company.id, + type: "request_board_approval", status: "pending", payload: {} }).returning(); + await db.update(toolActionRequests).set({ approvalId: formal.id }).where(eq(toolActionRequests.id, pending.id)); + await startRecovery(); await quiet(); + let release!: () => void, staged!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const ready = new Promise(resolve => { staged = resolve; }); + const aborted = new Error("formal approval rollback fixture"); + const writing = db.transaction(async tx => { + await approvalService(tx as unknown as typeof db).approve(formal.id, "board"); + staged(); await gate; if (rollback) throw aborted; + }).catch(error => { if (error !== aborted) throw error; }); + await Promise.race([ready, writing]); + try { + await vi.advanceTimersByTimeAsync(60_000); + expect((await db.select().from(toolActionRequests))[0].status).toBe("approved"); + expect((await db.select().from(toolInvocations))[0].status).toBe("awaiting_approval"); + } finally { release(); } + await writing; await settle(); + if (rollback) { + expect((await db.select().from(toolActionRequests))[0].status).toBe("approved"); await quiet(); + await approvalService(db).approve(formal.id, "board"); await settle(); + } + await executed(pending); await quiet(); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(1); + }); + + it.each(["reject", "cancel"] as const)("wakes a parked revision-requested formal approval on %s", async decision => { + const pending = await request(); await approve(pending); + const [formal] = await db.insert(approvals).values({ companyId: fixture.company.id, + type: "request_board_approval", status: "revision_requested", payload: {} }).returning(); + await db.update(toolActionRequests).set({ approvalId: formal.id }).where(eq(toolActionRequests.id, pending.id)); + await startRecovery(); await quiet(); + const service = approvalService(db); + if (decision === "cancel") await service.cancel(formal.id, "Cancelled by user"); + else await service.reject(formal.id, "board"); + await settle(); + expect((await db.select().from(toolActionRequests))[0].status).toBe("cancelled"); + expect((await db.select().from(toolInvocations))[0]).toMatchObject({ status: "denied", errorCode: "formal_approval_unavailable" }); + await quiet(); + }); + + it("retains approved work when the signing key is temporarily unavailable", async () => { + const pending = await request(); await approve(pending); + vi.stubEnv("PAPERCLIP_TOOL_ACTION_SIGNING_SECRET", ""); + vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "invalid-master-key"); + gateway = createToolGatewayService(db); + await startRecovery(); + expect(coordinator!.nextWakeAt()).not.toBeNull(); + expect((await db.select().from(toolActionRequests))[0].status).toBe("approved"); + expect((await db.select().from(toolInvocations))[0].status).toBe("awaiting_approval"); + vi.stubEnv("PAPERCLIP_TOOL_ACTION_SIGNING_SECRET", testToolActionSigningSecret); + await settle(); await executed(pending); await quiet(); + }); + + it("does not accept another company's formal approval", async () => { + const pending = await request(); await approve(pending); + const other = await createRunFixture(db); + const [formal] = await db.insert(approvals).values({ companyId: other.company.id, + type: "request_board_approval", status: "approved", payload: {} }).returning(); + await db.update(toolActionRequests).set({ approvalId: formal.id }).where(eq(toolActionRequests.id, pending.id)); + await startRecovery(); await settle(); + expect((await db.select().from(toolActionRequests))[0].status).toBe("cancelled"); + expect((await db.select().from(toolInvocations))[0]).toMatchObject({ status: "denied", errorCode: "formal_approval_unavailable" }); + expect((await db.select().from(approvals))[0]).toEqual(formal); + await quiet(); + }); + + it("quarantines a mismatched request without modifying another company's invocation", async () => { + const pending = await request(); await approve(pending); + const [invocation] = await db.select().from(toolInvocations); + const other = await createRunFixture(db); + await db.update(toolActionRequests).set({ companyId: other.company.id }).where(eq(toolActionRequests.id, pending.id)); + await startRecovery(); await settle(); + expect((await db.select().from(toolActionRequests))[0].status).toBe("failed"); + expect((await db.select().from(toolInvocations))[0]).toEqual(invocation); + await quiet(); + }); + + it("repairs completed agent history without executing the action again", async () => { + const pending = await request(); + await gateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }); + await executed(pending); + const [invocation] = await db.select().from(toolInvocations); + await db.update(toolActionRequests).set({ status: "approved", signedArguments: "unreadable-old-signature" }) + .where(eq(toolActionRequests.id, pending.id)); + await startRecovery(); await settle(); await executed(pending); await quiet(); + expect((await db.select().from(toolInvocations))[0]).toEqual(invocation); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toHaveLength(1); + }); + + it("keeps deliberately inert legacy approvals quiet", async () => { + const pending = await request(); + await db.update(toolActionRequests).set({ signedArguments: signToolArguments({ + invocationId: pending.invocationId, toolName: "mcp-remote-fixture:update_note", + canonicalArguments: canonicalToolArguments({ noteId: "legacy", body: "inert" }), + signingSecret: testToolActionSigningSecret, + }) }).where(eq(toolActionRequests.id, pending.id)); + await approve(pending); await startRecovery(); await quiet(); + expect((await db.select().from(toolActionRequests))[0].status).toBe("approved"); + expect((await db.select().from(toolInvocations))[0].status).toBe("awaiting_approval"); + }); + + it.each([false, true])("waits for the outer approval transaction (rollback %s)", async rollback => { + await startRecovery(); const pending = await request(); + let release!: () => void, staged!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const ready = new Promise(resolve => { staged = resolve; }); + const aborted = new Error("approval rollback fixture"); + const writing = db.transaction(async tx => { + await approve(pending, tx as unknown as typeof db); staged(); await gate; + if (rollback) throw aborted; + }).catch(error => { if (error !== aborted) throw error; }); + await Promise.race([ready, writing]); + try { + await vi.advanceTimersByTimeAsync(60_000); + expect((await db.select().from(toolActionRequests))[0].status).toBe("pending"); + } finally { release(); } + await writing; await settle(); + if (rollback) expect((await db.select().from(toolActionRequests))[0].status).toBe("pending"); + else await executed(pending); + await quiet(); + }); + + it("retains the first approval during drain without passive queries", async () => { + await startRecovery(); await quiet(); draining = true; + const pending = await request(); await approve(pending); await settle(); + const reads = vi.spyOn(db, "select"); + await settle(60 * 60_000); expect(reads).not.toHaveBeenCalled(); reads.mockRestore(); + draining = false; await settle(); await executed(pending); await quiet(); + }); + + async function testRequest(provider: NonNullable, rateLimited = false, parameters: Record = { value: "reviewed" }) { + await db.insert(companyMemberships).values({ companyId: fixture.company.id, principalType: "user", + principalId: "board", status: "active", membershipRole: "owner" }); + const remote = await createRemoteMcpToolFixture(db, fixture.company.id); + await db.update(toolCatalogEntries).set({ isReadOnly: false, riskLevel: "write" }) + .where(eq(toolCatalogEntries.id, remote.catalogEntry.id)); + await db.insert(toolPolicies).values({ companyId: fixture.company.id, name: "Review connected writes", + policyType: "require_approval", priority: 10, selectors: { connectionId: remote.connection.id } }); + if (rateLimited) await db.insert(toolPolicies).values({ companyId: fixture.company.id, name: "One reviewed test call", + policyType: "rate_limit", priority: 1, selectors: { connectionId: remote.connection.id }, + config: { limit: 1, windowSeconds: 3600, keyBy: ["agent", "tool"] } }); + gateway = createTestToolGatewayService(db, { remoteHttpRequest: provider }); + const result = await gateway.executeTestCall({ companyId: fixture.company.id, connectionId: remote.connection.id, + agentId: fixture.agent.id, userId: "board", toolName: "needs_input", parameters }); + expect(result.decision).toBe("ask_first"); + const [pending] = await db.select().from(toolActionRequests); + return { pending, remote }; + } + function providerFixture() { + let release!: () => void, entered!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const started = new Promise(resolve => { entered = resolve; }); + const provider = vi.fn(async (_url, init) => { + const payload = JSON.parse(String(init.body)); + expect(payload.method).toBe("tools/call"); + entered(); await gate; + return Response.json({ jsonrpc: "2.0", id: payload.id, + result: { content: [{ type: "text", text: "Saved once" }] } }); + }); + return { provider, release, started }; + } + + it.each(["foreground", "recovery"] as const)("retries a Test-tab %s approval after a real pre-dispatch database timeout", async mode => { + const remoteCall = providerFixture(); remoteCall.release(); + const { pending } = await testRequest(remoteCall.provider); await approve(pending); + const preparationDb = createDb(externalDatabaseUrl ?? tempDb!.connectionString, { + maxConnections: 1, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0, + }); + const preparingGateway = createTestToolGatewayService(preparationDb, { remoteHttpRequest: remoteCall.provider }); + let unlock!: () => void, locked!: () => void; + const gate = new Promise(resolve => { unlock = resolve; }); + const acquired = new Promise(resolve => { locked = resolve; }); + const lock = db.transaction(async tx => { + await tx.execute(sql`lock table tool_policies in access exclusive mode`); + locked(); await gate; + }); + await acquired; + try { + await preparationDb.execute(sql`set lock_timeout = '2s'`); + const attempting = mode === "foreground" + ? preparingGateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }) + : preparingGateway.recoverApprovedActionReviews(fixture.company.id); + // Observe the real committed claim while its subsequent policy read + // is blocked. Provider execution has not started. + void attempting.catch(() => undefined); + await vi.waitFor(async () => { + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0].status).toBe("executing"); + }); + if (mode === "foreground") await expect(attempting).rejects.toMatchObject({ cause: { code: "55P03" } }); + else expect(await attempting).toEqual({ scanned: 1, retry: true }); + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0]) + .toMatchObject({ status: "approved", signedArguments: pending.signedArguments }); + expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0]) + .toMatchObject({ status: "awaiting_approval", startedAt: null }); + expect(remoteCall.provider).not.toHaveBeenCalled(); + } finally { unlock(); await lock; await preparationDb.$client.end({ timeout: 1 }); } + await startRecovery(); await settle(); await executed(pending); await quiet(); + expect(remoteCall.provider).toHaveBeenCalledOnce(); + }, 15_000); + + async function agentRequest(provider: NonNullable, parameters: Record = { value: "reviewed" }) { + const remote = await createRemoteMcpToolFixture(db, fixture.company.id); + await db.update(toolCatalogEntries).set({ isReadOnly: false, riskLevel: "write" }) + .where(eq(toolCatalogEntries.id, remote.catalogEntry.id)); + await db.insert(toolPolicies).values({ companyId: fixture.company.id, name: "Review agent writes", + policyType: "require_approval", selectors: { connectionId: remote.connection.id } }); + gateway = createTestToolGatewayService(db, { remoteHttpRequest: provider }); + const session = await gateway.createSession(runSessionInput(fixture.company, fixture.agent, fixture.run)); + const tool = (await gateway.listToolsForSession(session.token)).find(t => t.connectionId === remote.connection.id)!; + await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters })) + .rejects.toMatchObject({ reasonCode: "approval_required" }); + const [pending] = await db.select().from(toolActionRequests); + return pending; + } + + it.each(["foreground", "recovery"] as const)("retries an agent-origin %s approval after a real pre-dispatch database timeout", async mode => { + const remoteCall = providerFixture(); remoteCall.release(); + const pending = await agentRequest(remoteCall.provider); await approve(pending); + const preparationDb = createDb(externalDatabaseUrl ?? tempDb!.connectionString, { + maxConnections: 1, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0, + }); + const preparingGateway = createTestToolGatewayService(preparationDb, { remoteHttpRequest: remoteCall.provider }); + let unlock!: () => void, locked!: () => void; + const gate = new Promise(resolve => { unlock = resolve; }); + const acquired = new Promise(resolve => { locked = resolve; }); + const lock = db.transaction(async tx => { + await tx.execute(sql`lock table tool_policies in access exclusive mode`); + locked(); await gate; + }); + await acquired; + try { + await preparationDb.execute(sql`set lock_timeout = '2s'`); + const attempting = mode === "foreground" + ? preparingGateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }) + : preparingGateway.recoverApprovedActionReviews(fixture.company.id); + // Observe the real committed claim while its subsequent policy read + // is blocked. Provider execution has not started. + void attempting.catch(() => undefined); + await vi.waitFor(async () => { + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0].status).toBe("executing"); + }); + if (mode === "foreground") expect(await attempting).toMatchObject({ status: "approved" }); + else expect(await attempting).toEqual({ scanned: 1, retry: true }); + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0]) + .toMatchObject({ status: "approved", signedArguments: pending.signedArguments }); + expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0]) + .toMatchObject({ status: "awaiting_approval", startedAt: null }); + expect(remoteCall.provider).not.toHaveBeenCalled(); + } finally { unlock(); await lock; await preparationDb.$client.end({ timeout: 1 }); } + await startRecovery(); await settle(); await executed(pending); await quiet(); + expect(remoteCall.provider).toHaveBeenCalledOnce(); + }, 15_000); + + it("refuses agent dispatch after preparation loses its claim", async () => { + const remoteCall = providerFixture(); remoteCall.release(); + const pending = await agentRequest(remoteCall.provider); await approve(pending); + let unlock!: () => void, locked!: () => void; + const gate = new Promise(resolve => { unlock = resolve; }); + const acquired = new Promise(resolve => { locked = resolve; }); + const lock = db.transaction(async tx => { + // Pause tool discovery before admission locks the invocation. Revocation + // cannot legitimately take that lock from an in-flight admission. + await tx.execute(sql`lock table tool_catalog_entries in access exclusive mode`); + locked(); await gate; + }); + await acquired; + const attempting = gateway.approveActionRequest({ companyId: fixture.company.id, + actionRequestId: pending.id, actor: { userId: "board" } }); + void attempting.catch(() => undefined); + let successor!: NonNullable>>; + try { + await vi.waitFor(async () => { + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0].status).toBe("executing"); + }); + const [claimed] = await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)); + expect(await releaseToolApproval(db, { actionRequestId: pending.id, + invocationId: pending.invocationId, claimedAt: claimed.updatedAt })).toBe(true); + await vi.advanceTimersByTimeAsync(10); + successor = (await claimToolTestApproval(db, pending.id, pending.invocationId))!; + expect(successor).not.toBeNull(); + expect(successor.claimedAt.getTime()).toBeGreaterThan(claimed.updatedAt.getTime()); + } finally { unlock(); await lock; } + expect(await attempting).toMatchObject({ status: "executing" }); + expect(remoteCall.provider).not.toHaveBeenCalled(); + expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0]) + .toMatchObject({ status: "awaiting_approval", startedAt: null }); + expect(await releaseToolApproval(db, successor)).toBe(true); + await startRecovery(); await settle(); await executed(pending); await quiet(); + expect(remoteCall.provider).toHaveBeenCalledOnce(); + }); + + it("does not retry an agent provider error as a preparation failure", async () => { + const provider = vi.fn(async () => { throw new Error("Provider outcome is unknown"); }); + const pending = await agentRequest(provider); await approve(pending); + await gateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }); + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0].status).toBe("failed"); + expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0].startedAt).not.toBeNull(); + await startRecovery(); await quiet(); + expect(provider).toHaveBeenCalledOnce(); + }); + + it.each(["started", "reclaimed", "mismatched", "prior_dispatch"] as const)("refuses to release a Test-tab preparation claim with %s ownership evidence", async state => { + const remoteCall = providerFixture(); remoteCall.release(); + const { pending } = await testRequest(remoteCall.provider); await approve(pending); + const claim = await claimToolTestApproval(db, pending.id, pending.invocationId); + expect(claim).not.toBeNull(); + if (state === "started") expect(await startToolInvocation(db, pending.invocationId, claim!)).toBe(true); + if (state === "reclaimed") await db.update(toolActionRequests) + .set({ updatedAt: new Date(claim!.claimedAt.getTime() + 1000) }).where(eq(toolActionRequests.id, pending.id)); + if (state === "prior_dispatch") await db.update(toolInvocations) + .set({ startedAt: new Date() }).where(eq(toolInvocations.id, pending.invocationId)); + const beforeRequest = (await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0]; + const beforeInvocation = (await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0]; + expect(await releaseToolApproval(db, state === "mismatched" ? { ...claim!, invocationId: randomUUID() } : claim!)).toBe(false); + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0]).toEqual(beforeRequest); + expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0]).toEqual(beforeInvocation); + expect(remoteCall.provider).not.toHaveBeenCalled(); + }); + + it("rolls a Test-tab preparation release back with its transaction and invalidates the released claim", async () => { + const remoteCall = providerFixture(); remoteCall.release(); + const { pending } = await testRequest(remoteCall.provider); await approve(pending); + const claim = await claimToolTestApproval(db, pending.id, pending.invocationId); + expect(claim).not.toBeNull(); + await expect(db.transaction(async tx => { + expect(await releaseToolApproval(tx as unknown as typeof db, claim!)).toBe(true); + throw new Error("release rollback"); + })).rejects.toThrow("release rollback"); + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0].status).toBe("executing"); + expect(await releaseToolApproval(db, claim!)).toBe(true); + expect(await startToolInvocation(db, pending.invocationId, claim!)).toBe(false); + await startRecovery(); await settle(); await executed(pending); await quiet(); + expect(remoteCall.provider).toHaveBeenCalledOnce(); + }); + + it.each(["foreground", "recovery"] as const)("claims a Test-tab action once when %s wins", async winner => { + const remoteCall = providerFixture(); + const { pending } = await testRequest(remoteCall.provider); + let running: Promise; + if (winner === "foreground") { + await startRecovery(); + running = gateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }); + } else { + await approve(pending); + running = startRecovery(); + } + await Promise.race([remoteCall.started, running]); + try { + await vi.advanceTimersByTimeAsync(60_000); + await gateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }); + expect(remoteCall.provider).toHaveBeenCalledTimes(1); + } finally { remoteCall.release(); } + await running; await settle(); await executed(pending); await quiet(); + expect(remoteCall.provider).toHaveBeenCalledTimes(1); + }); + + it.each(["foreground", "recovery"] as const)("preserves the admitted rate slot for a Test-tab action through %s approval", async mode => { + const remoteCall = providerFixture(); remoteCall.release(); + const { pending } = await testRequest(remoteCall.provider, true); + const counters = await db.select().from(toolRateLimitCounters); + expect(counters).toHaveLength(1); expect(counters[0].remaining).toBe(0); + if (mode === "foreground") { + await gateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }); + await startRecovery(); + } else { await approve(pending); await startRecovery(); } + await settle(); await executed(pending); await quiet(); + expect(await db.select().from(toolRateLimitCounters)).toEqual(counters); + expect(remoteCall.provider).toHaveBeenCalledOnce(); + }); + + it("repairs completed Test-tab history without sending the request again", async () => { + const remoteCall = providerFixture(); remoteCall.release(); + const { pending } = await testRequest(remoteCall.provider); + await gateway.approveActionRequest({ companyId: fixture.company.id, actionRequestId: pending.id, actor: { userId: "board" } }); + await executed(pending); + await db.update(toolActionRequests).set({ status: "approved", signedArguments: "unreadable-old-signature" }) + .where(eq(toolActionRequests.id, pending.id)); + remoteCall.provider.mockClear(); + await startRecovery(); await settle(); await executed(pending); await quiet(); + expect(remoteCall.provider).not.toHaveBeenCalled(); + }); + + it.each(["pending", "authorized", "cancelled"])("settles inconsistent Test-tab %s history without replay", async status => { + const remoteCall = providerFixture(); remoteCall.release(); + const { pending } = await testRequest(remoteCall.provider); await approve(pending); + await db.update(toolInvocations).set({ status }).where(eq(toolInvocations.id, pending.invocationId)); + await startRecovery(); await settle(); + expect((await db.select().from(toolActionRequests))[0].status).toBe(status === "cancelled" ? "cancelled" : "failed"); + expect((await db.select().from(toolInvocations))[0]).toMatchObject(status === "cancelled" + ? { status: "cancelled" } + : { status: "failed", errorCode: "tool_recovery_state_invalid" }); + await quiet(); expect(remoteCall.provider).not.toHaveBeenCalled(); + }); + + it("does not replay an interrupted legacy Test-tab invocation", async () => { + const remoteCall = providerFixture(); remoteCall.release(); + const { pending } = await testRequest(remoteCall.provider); + await approve(pending); + await db.update(toolInvocations).set({ status: "executing", startedAt: new Date(Date.now() - 11 * 60_000) }) + .where(eq(toolInvocations.id, pending.invocationId)); + await startRecovery(); await settle(); + expect((await db.select().from(toolActionRequests))[0].status).toBe("executing"); + await gateway.sweepActionReviews({ includeApproved: false, includeExpiry: false }); + expect((await db.select().from(toolInvocations))[0]).toMatchObject({ status: "failed", errorCode: "tool_execution_outcome_unknown" }); + await quiet(); expect(remoteCall.provider).not.toHaveBeenCalled(); + }); + + it.each(["always", "once"])("does not replay a Test-tab call when persisting its external result fails %s", async mode => { + const remoteCall = providerFixture(); remoteCall.release(); + const { pending } = await testRequest(remoteCall.provider); + await approve(pending); + await db.execute(sql`create sequence sleep_review_failure_attempt`); + await db.execute(sql.raw(`create function sleep_review_fail() returns trigger language plpgsql as $$ + begin + if ${mode === "always" ? "true" : "nextval('sleep_review_failure_attempt') = 1"} then + raise exception 'approval result fixture failure'; + end if; + return new; + end $$`)); + await db.execute(sql`create trigger sleep_review_fail before update on tool_action_requests + for each row when (new.status in ('executed', 'failed')) execute function sleep_review_fail()`); + try { + await startRecovery(); + expect((await db.select().from(toolActionRequests))[0].status).toBe("executing"); + expect((await db.select().from(toolInvocations))[0].status).toBe("executing"); + expect(remoteCall.provider).toHaveBeenCalledTimes(1); + } finally { + await db.execute(sql`drop trigger sleep_review_fail on tool_action_requests`); + } + await settle(); + await vi.advanceTimersByTimeAsync(11 * 60_000); + await gateway.sweepActionReviews({ includeApproved: false, includeExpiry: false }); + expect((await db.select().from(toolInvocations))[0]).toMatchObject({ status: "failed", errorCode: "tool_execution_outcome_unknown" }); + await quiet(); expect(remoteCall.provider).toHaveBeenCalledTimes(1); + }); + + it("revalidates the reviewed Test-tab target before recovery dispatch", async () => { + const remoteCall = providerFixture(); remoteCall.release(); + const { pending, remote } = await testRequest(remoteCall.provider); + await approve(pending); + await db.update(toolCatalogEntries).set({ versionHash: "changed-after-review" }).where(eq(toolCatalogEntries.id, remote.catalogEntry.id)); + await startRecovery(); await settle(); + expect((await db.select().from(toolInvocations))[0]).toMatchObject({ status: "failed", errorCode: "approved_tool_target_changed" }); + await quiet(); expect(remoteCall.provider).not.toHaveBeenCalled(); + }); + }); + async function requestWithExpiry(expiresAt: Date, context = fixture) { return db.transaction(async tx => { const source = tx as unknown as typeof db; @@ -876,13 +1585,21 @@ describeEmbeddedPostgres("tool gateway service", () => { await expect(gateway.executeTool({ sessionToken: session.token, tool: "mcp-remote-fixture:update_note", parameters: { noteId: "expire" } })).rejects.toMatchObject({ reasonCode: "approval_required" }); const [request] = await db.select().from(toolActionRequests); await db.update(toolActionRequests).set({ expiresAt: new Date(Date.now() - 1000) }).where(eq(toolActionRequests.id, request.id)); - await db.insert(toolActionRequests).values(Array.from({ length: 100 }, (_, i) => ({ + const [originalInvocation] = await db.select().from(toolInvocations).where(eq(toolInvocations.id, request.invocationId)); + const blockedInvocations = Array.from({ length: 101 }, (_, i) => ({ ...originalInvocation, + id: `10000000-0000-4000-8000-${String(i).padStart(12, "0")}`, approvalState: "approved", idempotencyKey: null, + })); + await db.insert(toolInvocations).values(blockedInvocations); + await db.insert(toolActionRequests).values(blockedInvocations.map((invocation, i) => ({ ...request, id: `00000000-0000-4000-8000-${String(i).padStart(12, "0")}`, - interactionId: null, status: "approved" as const, + invocationId: invocation.id, interactionId: null, status: "approved" as const, + signedArguments: signToolArguments({ invocationId: invocation.id, toolName: invocation.toolName, + canonicalArguments: canonicalToolArguments({ noteId: "blocked" }), executionOnApprove: true, + signingSecret: testToolActionSigningSecret }), }))); const recover = vi.spyOn(gateway, "approveActionRequest").mockRejectedValue(new Error("Unavailable approval dependency")); - expect(await gateway.sweepActionReviews()).toEqual({ scanned: 101 }); - expect(recover).toHaveBeenCalledTimes(100); + expect(await gateway.sweepActionReviews()).toEqual({ scanned: 102 }); + expect(recover).toHaveBeenCalledTimes(101); const [settled] = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, request.interactionId!)); expect(settled.status).toBe("expired"); }); diff --git a/server/src/index.ts b/server/src/index.ts index ea24010565f..e9fc24fcf0b 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -1,3 +1,4 @@ +import { registerToolReviewRecoveryWork } from "./services/tool-review-recovery-work.js"; import { registerToolReviewExpiryWork } from "./services/tool-review-expiry-work.js"; import { registerGatewayCredentialExpiryWork } from "./services/gateway-credential-expiry-work.js"; import { registerSecretProposalExpiryWork } from "./services/secret-proposal-expiry-work.js"; @@ -1472,7 +1473,13 @@ async function startServerWithDatabaseTeardown( } else { await app.locals.toolGateway.sweepExpiredActionReviews(); } - return app.locals.toolGateway.sweepActionReviews({ includeExpiry: false }); + if (config.heartbeatSchedulerEnabled) { + await registerToolReviewRecoveryWork(deliveryWork, app.locals.toolGateway, + () => !isIdleTaskDrainActive() && !heartbeatSchedulerStopped && !isWarmStandby()).ready; + } else { + await app.locals.toolGateway.recoverApprovedActionReviews(); + } + return app.locals.toolGateway.sweepActionReviews({ includeExpiry: false, includeApproved: false }); }).catch((err: unknown) => logger.error({ err }, "startup tool review recovery failed")); await timeStartupRecovery("gateway_sessions", () => config.heartbeatSchedulerEnabled ? registerGatewayCredentialExpiryWork(deliveryWork, app.locals.toolGateway, @@ -1903,7 +1910,7 @@ async function startServerWithDatabaseTeardown( logger.error({ err }, "periodic tool connection health sweep failed"); })); - trackHeartbeatSchedulerWork(app.locals.toolGateway.sweepActionReviews({ includeExpiry: false }).catch((err: unknown) => logger.error({ err }, "tool review recovery failed"))); + trackHeartbeatSchedulerWork(app.locals.toolGateway.sweepActionReviews({ includeExpiry: false, includeApproved: false }).catch((err: unknown) => logger.error({ err }, "tool review recovery failed"))); if (isIdleTaskDrainActive() || heartbeatSchedulerStopped) return; if (!(await heartbeat.resolveSchedulingSuppression()).suppressed) { diff --git a/server/src/services/approvals.ts b/server/src/services/approvals.ts index 290a59fdf4b..4f4149f773d 100644 --- a/server/src/services/approvals.ts +++ b/server/src/services/approvals.ts @@ -1,3 +1,4 @@ +import { writeToolReviewChange } from "./tool-review-work-notifications.js"; import { approvalResolutionRecords, resolvableApprovalStatuses as resolvableStatuses } from "../lib/approval-records.js"; import { notifyHireApproved } from "./hire-hook.js"; @@ -12,7 +13,15 @@ import { instanceSettingsService } from "./instance-settings.js"; export function approvalRecords(db: Db) { const instanceSettings = instanceSettingsService(db); - const { getExistingApproval, resolveApproval } = approvalResolutionRecords(db); + const { getExistingApproval, resolveApproval: resolveApprovalRecord } = approvalResolutionRecords(db); + + // Tool reviews waiting for a formal decision stay parked until this producer + // commits. The shared record owner retains approval validation and CAS rules. + async function resolveApproval(id: string, status: "approved" | "rejected", userId: string, + note: string | null | undefined, database: Db = db) { + const existing = await getExistingApproval(id, database); + return writeToolReviewChange(database, existing.companyId, tx => resolveApprovalRecord(id, status, userId, note, tx)); + } function redactApprovalComment(comment: T, censorUsernameInLogs: boolean): T { return { @@ -64,7 +73,9 @@ export function approvalRecords(db: Db) { // cleanup. Idempotent: a no-op on already-resolved approvals. cancel: async (id: string, reason?: string | null) => { const now = new Date(); - const updated = await db + const [existing] = await db.select({ companyId: approvals.companyId }).from(approvals).where(eq(approvals.id, id)); + if (!existing) return null; + const updated = await writeToolReviewChange(db, existing.companyId, tx => tx .update(approvals) .set({ status: "cancelled", @@ -74,7 +85,7 @@ export function approvalRecords(db: Db) { }) .where(and(eq(approvals.id, id), inArray(approvals.status, resolvableStatuses))) .returning() - .then((rows) => rows[0] ?? null); + .then((rows) => rows[0] ?? null)); return updated; }, diff --git a/server/src/services/delivery-work-notifications.ts b/server/src/services/delivery-work-notifications.ts index 210c830f91a..923ae4b7979 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", + toolReviewRecovery: "tool-review-recovery", toolReviewExpiry: "tool-review-expiry", gatewayCredentialExpiry: "gateway-credential-expiry", secretProposalExpiry: "secret-proposal-expiry", diff --git a/server/src/services/tool-access-policy.ts b/server/src/services/tool-access-policy.ts index 16ac7f6fdce..cfd2f4478a6 100644 --- a/server/src/services/tool-access-policy.ts +++ b/server/src/services/tool-access-policy.ts @@ -1,7 +1,8 @@ import type { ConnectionManagementContext } from "./connection-management.js"; import { createHash } from "node:crypto"; import { boundRunIssueIdSql } from "./run-task-binding.js"; -import { and, asc, desc, eq, gt, inArray, isNull, ne, sql } from "drizzle-orm"; +import type { ToolApprovalClaim } from "./tool-approval-execution.js"; +import { and, asc, desc, eq, inArray, isNull, ne, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { agents, @@ -53,6 +54,12 @@ import { import { recordToolRuntimeAuditWriteFailure } from "./tool-runtime-metrics.js"; import { canonicalToolArguments, readSignedToolArgumentsPayload, toolRequestIdentityHash } from "./tool-content-guards.js"; +class RejectedInvocationAdmission extends Error { + constructor(readonly decision: ToolAccessDecision) { + super(decision.explanation); + } +} + type ToolAccessContext = { companyId: string; actorType: "agent" | "user" | "system" | "plugin"; @@ -717,7 +724,7 @@ function assertSupportedGenericPolicyShape( } } -async function getGenericPolicyRow(db: Db, companyId: string, policyId: string) { +async function getGenericPolicyRow(db: Pick, companyId: string, policyId: string) { const [policy] = await db .select() .from(toolPolicies) @@ -785,7 +792,7 @@ function scopeAllowsTool(scope: Record | null, ctx: ToolAccessC return selectorMatches(selectors, ctx); } -export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecret?: string } = {}) { +export function toolAccessPolicyService(db: Pick, options: { toolActionSigningSecret?: string } = {}) { // Policy administration includes authorized self-targeted changes. It cannot // resolve governed action requests or modify principal permission grants. async function listPolicies(companyId: string) { @@ -1301,11 +1308,12 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr ], set: { limit: rule.limit, - remaining: sql`greatest(0, least(${toolRateLimitCounters.remaining}, ${rule.limit}) - 1)`, + // Preserve the number already spent when an operator changes the limit. + remaining: sql`greatest(0, ${rule.limit} - (${toolRateLimitCounters.limit} - ${toolRateLimitCounters.remaining}) - 1)`, resetAt, updatedAt: now, }, - setWhere: gt(toolRateLimitCounters.remaining, 0), + setWhere: sql`${toolRateLimitCounters.limit} - ${toolRateLimitCounters.remaining} < ${rule.limit}`, }) .returning({ remaining: toolRateLimitCounters.remaining }); if (!counter) { @@ -1376,7 +1384,7 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr }); } - async function admittedRateLimitAdmissions(ctx: ToolAccessContext, invocationId: string): Promise { + async function admittedRateLimitAdmissions(ctx: ToolAccessContext, invocationId: string, previewHash?: string): Promise { const [invocation] = await db.select({ actorType: toolInvocations.actorType, actorId: toolInvocations.actorId, agentId: toolInvocations.agentId, runId: toolInvocations.runId, issueId: toolInvocations.issueId, gatewayId: toolInvocations.gatewayId, @@ -1387,6 +1395,9 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr status: toolInvocations.status, policyDecision: toolInvocations.policyDecision, approvalState: toolInvocations.approvalState, policyExplanation: toolInvocations.policyExplanation, }).from(toolInvocations).where(and(eq(toolInvocations.companyId, ctx.companyId), eq(toolInvocations.id, invocationId))); + // A parked request already spent its slot before asking for review. Reusing + // that admission only skips the same rate rule; current policy and the + // gateway's approval/claim owners still decide whether it may execute. const delegated = invocation?.policyExplanation?.delegatedConnectionTest as { agentId?: string } | undefined; const gatewayIssuer = invocation?.gatewayId ? invocation.policyExplanation?.delegatedGatewayIssuer : undefined; const isDelegatedCaller = invocation?.actorType === "agent" && invocation.actorId === ctx.agentId @@ -1401,13 +1412,81 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr && invocation.catalogEntryId === ctx.catalogEntryId && invocation.toolName === ctx.toolName && invocation.providerType === ctx.providerType && invocation.applicationKey === ctx.applicationKey && invocation.upstreamToolName === ctx.upstreamToolName - && invocation.argumentsHash === ctx.argumentsHash; - const stored = authorized ? invocation.policyExplanation?.[isDelegatedCaller ? "delegatedCallerConsumedRateAdmissions" : "consumedRateAdmissions"] : null; + && (invocation.argumentsHash === ctx.argumentsHash || invocation.argumentsHash === previewHash); + if (!authorized) return null; + const stored = invocation.policyExplanation?.[isDelegatedCaller ? "delegatedCallerConsumedRateAdmissions" : "consumedRateAdmissions"]; return Array.isArray(stored) ? stored.filter((item): item is ConsumedRateAdmission => isRecord(item) && typeof item.policyId === "string" && CANONICAL_UUID_RE.test(item.policyId) && typeof item.versionHash === "string" && /^[a-f0-9]{64}$/.test(item.versionHash)) : []; } + /** Revalidate claimed work and persist new rate charges before provider dispatch. */ + async function admitInvocation( + input: ToolAccessDecisionInput, + invocationId: string, + claim?: ToolApprovalClaim, + evaluate?: ( + policy: Pick, "decide" | "writeAudit">, + input: ToolAccessDecisionInput, + transaction: Db, + ) => Promise, + ): Promise { + try { + return await db.transaction(async tx => { + const [invocation] = await tx.select().from(toolInvocations) + .where(and(eq(toolInvocations.companyId, input.companyId), eq(toolInvocations.id, invocationId))) + .for("update"); + // Historical reviewed requests can still have a pending invocation. + // Accept that state only with the exact executing claim owned by the + // gateway, locked in the same invocation-then-request order as dispatch. + let ownsClaim = false; + if (claim && claim.invocationId === invocationId) { + const [request] = await tx.select().from(toolActionRequests).where(and( + eq(toolActionRequests.id, claim.actionRequestId), + eq(toolActionRequests.invocationId, invocationId), + eq(toolActionRequests.companyId, input.companyId), + )).for("update"); + ownsClaim = request?.status === "executing" && request.updatedAt.getTime() === claim.claimedAt.getTime(); + } + if (!invocation || (claim && !ownsClaim) + || !(invocation.status === "executing" && invocation.policyDecision === "allow" + || ["awaiting_approval", "executing"].includes(invocation.status) + && invocation.policyDecision === "require_approval" && invocation.approvalState === "approved" + || invocation.status === "awaiting_approval" && invocation.policyDecision === "require_approval" + && invocation.approvalState === "pending" && ownsClaim)) { + return decision("deny", "deny_policy_block", "Tool invocation admission is unavailable.", [], []); + } + const admissionPolicy = toolAccessPolicyService(tx, options); + const admissionInput = { ...input, consumeRateLimit: true }; + // Composed caller/target policy must share this claim transaction so + // either all new charges and receipts commit or all roll back. + const result = evaluate + ? await evaluate(admissionPolicy, admissionInput, tx as unknown as Db) + : await admissionPolicy.decide(admissionInput, { admittedInvocationId: invocationId }); + if (!result.allowed && result.decision !== "require_approval") { + // A later policy can reject after an earlier rate rule spent a slot. + // Roll back both the new charges and their receipt on any rejection. + throw new RejectedInvocationAdmission(result); + } + const admissions = result.policyExplanation?.consumedRateAdmissions; + const delegatedAdmissions = result.policyExplanation?.delegatedCallerConsumedRateAdmissions; + if (Array.isArray(admissions) || Array.isArray(delegatedAdmissions)) { + await tx.update(toolInvocations).set({ + policyExplanation: { + ...invocation.policyExplanation, + ...(Array.isArray(admissions) ? { consumedRateAdmissions: admissions } : {}), + ...(Array.isArray(delegatedAdmissions) ? { delegatedCallerConsumedRateAdmissions: delegatedAdmissions } : {}), + }, + }).where(and(eq(toolInvocations.companyId, input.companyId), eq(toolInvocations.id, invocationId))); + } + return result; + }); + } catch (error) { + if (error instanceof RejectedInvocationAdmission) return error.decision; + throw error; + } + } + /** * Decides one tool access request. Pass the same `cache` to every call of a * batch that shares one actor and run context (for example, one tools/list @@ -1415,7 +1494,7 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr */ async function decide( input: ToolAccessDecisionInput, - options: { cache?: ToolAccessDecisionCache; admittedInvocationId?: string; sharedRateDecision?: ToolAccessDecision } = {}, + options: { cache?: ToolAccessDecisionCache; admittedInvocationId?: string; admittedPreviewHash?: string; sharedRateDecision?: ToolAccessDecision } = {}, ): Promise { const consumedRateAdmissions: ConsumedRateAdmission[] = []; const result = await decideInternal(input, options, consumedRateAdmissions); @@ -1426,7 +1505,7 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr async function decideInternal( input: ToolAccessDecisionInput, - options: { cache?: ToolAccessDecisionCache; admittedInvocationId?: string; sharedRateDecision?: ToolAccessDecision }, + options: { cache?: ToolAccessDecisionCache; admittedInvocationId?: string; admittedPreviewHash?: string; sharedRateDecision?: ToolAccessDecision }, consumedRateAdmissions: ConsumedRateAdmission[], ): Promise { // A decision that consumes a rate limit can also record a trust-rule hit @@ -1438,9 +1517,14 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr // A final handoff rechecks current permissions for work already admitted by // the gateway. Its own last consumed slot cannot reject that same work. // Only durable consumption of an unchanged rule retains that slot; new or - // edited rules still apply. This option never approves or consumes a call. - const admittedRates = input.consumeRateLimit === false && options.admittedInvocationId - ? await admittedRateLimitAdmissions(ctx, options.admittedInvocationId) : []; + // edited rules still apply. admitInvocation owns atomic consuming rechecks; + // ordinary preflight and browser handoff callers remain read-only. + const admittedRates = options.admittedInvocationId + ? await admittedRateLimitAdmissions(ctx, options.admittedInvocationId, input.consumeRateLimit === true ? undefined : options.admittedPreviewHash) : []; + if (options.admittedInvocationId && input.consumeRateLimit === true && admittedRates === null) { + return decision("deny", "deny_policy_block", "Tool invocation no longer matches this admission.", [], []); + } + if (input.consumeRateLimit === true) consumedRateAdmissions.push(...(admittedRates ?? [])); const profileState = await effectiveProfiles(ctx, cache); const effectiveProfileIds = profileState.profiles.map((profile) => profile.id); const permittedByProfile = profileState.profiles.some((profile) => { @@ -1513,7 +1597,7 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr ); } const versionHash = ratePolicyVersionHash(policy); - if (admittedRates.some(admission => admission.policyId === policy.id && admission.versionHash === versionHash)) continue; + if (admittedRates?.some(admission => admission.policyId === policy.id && admission.versionHash === versionHash)) continue; // Paired caller/target checks for one delegated test share a slot only // when the exact policy version and counter bucket are identical. const shared = options.sharedRateDecision?.policyExplanation?.consumedRateAdmissions; @@ -1548,7 +1632,7 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr { redactionPlan: redaction.redactionPlan, policyExplanation }, ); } - if (input.consumeRateLimit === true) { + if (input.consumeRateLimit === true && !options.admittedInvocationId) { await recordTrustRuleHit(policy, ctx, redaction); } return decision("allow", "allow_trust_rule", policy.description ?? "Tool access allowed by trust rule.", effectiveProfileIds, [policy.id], { redactionPlan: redaction.redactionPlan, policyExplanation }); @@ -2178,6 +2262,7 @@ export function toolAccessPolicyService(db: Db, options: { toolActionSigningSecr return { decide, + admitInvocation, writeAudit, recordInvocation, summarizeAndRedact, diff --git a/server/src/services/tool-approval-execution.ts b/server/src/services/tool-approval-execution.ts new file mode 100644 index 00000000000..f5f4fb78abf --- /dev/null +++ b/server/src/services/tool-approval-execution.ts @@ -0,0 +1,119 @@ +import { and, eq } from "drizzle-orm"; +import { toolActionRequests, toolInvocations, type Db } from "@paperclipai/db"; +import type { ToolRedactedValueSummary } from "@paperclipai/shared"; +import { notifyToolReviewChange } from "./tool-review-work-notifications.js"; + +export type ToolApprovalClaim = { actionRequestId: string; invocationId: string; claimedAt: Date }; +export type ToolTestOutcome = { + status: "succeeded" | "failed" | "timed_out" | "rate_limited"; + result?: ToolRedactedValueSummary; + errorCode?: string; + errorMessage?: string; +}; + +export async function claimToolTestApproval(db: Db, actionRequestId: string, invocationId: string): Promise { + return db.transaction(async tx => { + const [invocation] = await tx.select().from(toolInvocations) + .where(eq(toolInvocations.id, invocationId)).for("update"); + const [request] = await tx.select().from(toolActionRequests) + .where(and(eq(toolActionRequests.id, actionRequestId), eq(toolActionRequests.invocationId, invocationId))).for("update"); + if (!invocation || request?.status !== "approved") return null; + await notifyToolReviewChange(tx, request.companyId); + const now = new Date(); + if (invocation.status !== "awaiting_approval") { + if (["succeeded", "failed", "denied", "timed_out", "rate_limited"].includes(invocation.status)) { + await tx.update(toolActionRequests).set({ status: invocation.status === "succeeded" ? "executed" : "failed", + resolvedAt: invocation.completedAt ?? now, updatedAt: now }).where(eq(toolActionRequests.id, actionRequestId)); + } else if (invocation.status === "executing") { + await tx.update(toolActionRequests).set({ status: "executing", updatedAt: invocation.startedAt ?? invocation.updatedAt }) + .where(eq(toolActionRequests.id, actionRequestId)); + } + return null; + } + await tx.update(toolActionRequests).set({ status: "executing", updatedAt: now }) + .where(eq(toolActionRequests.id, actionRequestId)); + return { actionRequestId, invocationId, claimedAt: now }; + }); +} + +/** Return only this still-undispatched claim to its existing approval queue. */ +export async function releaseToolApproval(db: Db, claim: ToolApprovalClaim) { + return db.transaction(async tx => { + const [invocation] = await tx.select().from(toolInvocations) + .where(eq(toolInvocations.id, claim.invocationId)).for("update"); + const [request] = await tx.select().from(toolActionRequests) + .where(and(eq(toolActionRequests.id, claim.actionRequestId), + eq(toolActionRequests.invocationId, claim.invocationId))).for("update"); + if (invocation?.status !== "awaiting_approval" || invocation.startedAt !== null || + request?.status !== "executing" || request.companyId !== invocation.companyId || + request.updatedAt.getTime() !== claim.claimedAt.getTime()) return false; + await notifyToolReviewChange(tx, request.companyId); + await tx.update(toolActionRequests).set({ status: "approved", updatedAt: new Date() }) + .where(eq(toolActionRequests.id, request.id)); + return true; + }); +} + +export async function bindVerifiedToolApprovalArguments(db: Db, claim: ToolApprovalClaim, hashes: { preview: string; verified: string }) { + return db.transaction(async tx => { + const [invocation] = await tx.select().from(toolInvocations) + .where(eq(toolInvocations.id, claim.invocationId)).for("update"); + const [request] = await tx.select().from(toolActionRequests) + .where(and(eq(toolActionRequests.id, claim.actionRequestId), + eq(toolActionRequests.invocationId, claim.invocationId))).for("update"); + if (invocation?.status !== "awaiting_approval" || invocation.startedAt !== null || + request?.status !== "executing" || request.companyId !== invocation.companyId || + request.updatedAt.getTime() !== claim.claimedAt.getTime() || + ![hashes.preview, hashes.verified].includes(request.canonicalArgumentsHash) || + ![hashes.preview, hashes.verified].includes(invocation.argumentsHash ?? "")) return false; + if (invocation.argumentsHash !== hashes.verified) await tx.update(toolInvocations) + .set({ argumentsHash: hashes.verified, updatedAt: new Date() }).where(eq(toolInvocations.id, claim.invocationId)); + return true; + }); +} + +export async function startToolInvocation(db: Db, invocationId: string, claim?: ToolApprovalClaim) { + const now = new Date(); + if (!claim) { + await db.update(toolInvocations).set({ status: "executing", startedAt: now, updatedAt: now }) + .where(eq(toolInvocations.id, invocationId)); + return true; + } + return db.transaction(async tx => { + const [invocation] = await tx.select().from(toolInvocations) + .where(eq(toolInvocations.id, invocationId)).for("update"); + const [request] = await tx.select().from(toolActionRequests) + .where(eq(toolActionRequests.id, claim.actionRequestId)).for("update"); + if (invocationId !== claim.invocationId || invocation?.status !== "awaiting_approval" || invocation.startedAt !== null || + request?.status !== "executing" || request.invocationId !== invocationId || request.companyId !== invocation.companyId || + request.updatedAt.getTime() !== claim.claimedAt.getTime()) return false; + await tx.update(toolInvocations).set({ status: "executing", approvalState: "approved", startedAt: now, updatedAt: now }) + .where(eq(toolInvocations.id, invocationId)); + return true; + }); +} + +export async function persistToolTestOutcome(db: Db, invocationId: string, outcome: ToolTestOutcome, claim?: ToolApprovalClaim) { + const now = new Date(); + const values = { status: outcome.status, ...(outcome.result ? { + resultHash: outcome.result.sha256 ?? null, resultSummary: outcome.result, + resultSizeBytes: outcome.result.sizeBytes ?? null, + } : {}), errorCode: outcome.errorCode, errorMessage: outcome.errorMessage, completedAt: now, updatedAt: now }; + if (!claim) { + await db.update(toolInvocations).set(values).where(eq(toolInvocations.id, invocationId)); + return true; + } + return db.transaction(async tx => { + const [invocation] = await tx.select({ status: toolInvocations.status }).from(toolInvocations) + .where(eq(toolInvocations.id, invocationId)).for("update"); + const [request] = await tx.select().from(toolActionRequests) + .where(eq(toolActionRequests.id, claim.actionRequestId)).for("update"); + if (!invocation || !["awaiting_approval", "executing"].includes(invocation.status) || + request?.status !== "executing" || request.updatedAt.getTime() !== claim.claimedAt.getTime()) return false; + await notifyToolReviewChange(tx, request.companyId); + await tx.update(toolInvocations).set(values).where(eq(toolInvocations.id, invocationId)); + await tx.update(toolActionRequests).set({ status: outcome.status === "succeeded" ? "executed" : "failed", + resolvedAt: now, updatedAt: now }).where(eq(toolActionRequests.id, claim.actionRequestId)); + return true; + }); +} diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 2ff322ad308..ff5e1028ffc 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -1,3 +1,5 @@ +import { bindVerifiedToolApprovalArguments, claimToolTestApproval, releaseToolApproval, persistToolTestOutcome, startToolInvocation, type ToolApprovalClaim } from "./tool-approval-execution.js"; +import { approvedToolReviewCompanies, prepareApprovedToolReview, recoverApprovedToolReviews } from "./tool-review-recovery.js"; import { toolReviewExpiryService } from "./tool-review-expiry.js"; import { writeToolReviewChange } from "./tool-review-work-notifications.js"; import { restConnectorFor } from "./connectors/rest-registry.js"; @@ -1245,46 +1247,56 @@ export function createToolGatewayService( const interactions = issueThreadInteractionService(db); const basePolicyService = toolAccessPolicyService(db, { toolActionSigningSecret: options.toolActionSigningSecret }); const issuerDecisionCaches = new WeakMap(); + async function decideGatewayPolicy( + input: ToolAccessDecisionInput, + decisionOptions: NonNullable[1]> & { requiredGatewayAction?: ToolMcpGatewayTokenAction } = {}, + policy: Pick = basePolicyService, + database: Db = db, + ): Promise { + const issuerId = input.runContext?.originatingAgentId; + if (!issuerId || !input.runContext?.gatewayId || input.actor.actorType !== "agent") return policy.decide(input, decisionOptions); + if (!input.runContext.gatewayTokenId) throw new ToolGatewayHttpError(403, "Delegated gateway token is no longer available", "gateway_token_run_context_invalid"); + let issuerCache: ToolAccessDecisionCache | undefined; + if (decisionOptions.cache) { + issuerCache = issuerDecisionCaches.get(decisionOptions.cache); + if (!issuerCache) { issuerCache = createToolAccessDecisionCache(); issuerDecisionCaches.set(decisionOptions.cache, issuerCache); } + } + const requiredAction = decisionOptions.requiredGatewayAction ?? (input.consumeRateLimit ? "tools/call" : undefined); + const authorityKey = `gateway-issuer:${input.companyId}:${input.runContext.gatewayTokenId}:${issuerId}:${requiredAction ?? "inspect"}`; + let authority = issuerCache?.get(authorityKey); + if (!authority) { + authority = assertGatewayIssuerAuthority(input, requiredAction, database); + issuerCache?.set(authorityKey, authority); + } + await authority; + if (issuerId === input.actor.agentId) { + const decision = await policy.decide(input, decisionOptions); + return { ...decision, policyExplanation: { ...decision.policyExplanation, delegatedGatewayIssuer: issuerId } }; + } + const issuerInput = { ...input, actor: { ...input.actor, agentId: issuerId } }; + const issuer = await policy.decide(issuerInput, { ...decisionOptions, cache: issuerCache }); + const target = await policy.decide(input, { ...decisionOptions, sharedRateDecision: issuer }); + const chosen = !issuer.allowed && issuer.decision !== "require_approval" ? issuer + : !target.allowed ? target : issuer.decision === "require_approval" ? issuer : target; + if (input.consumeRateLimit) await policy.writeAudit(issuerInput, issuer); + return { ...chosen, matchedPolicyIds: [...new Set([...issuer.matchedPolicyIds, ...target.matchedPolicyIds])], policyExplanation: { + ...chosen.policyExplanation, + consumedRateAdmissions: target.policyExplanation?.consumedRateAdmissions, + delegatedCallerConsumedRateAdmissions: issuer.policyExplanation?.consumedRateAdmissions, + delegatedGatewayIssuer: issuerId, + } }; + } const policyService = { ...basePolicyService, - async decide(input: ToolAccessDecisionInput, decisionOptions: NonNullable[1]> & { requiredGatewayAction?: ToolMcpGatewayTokenAction } = {}): Promise { - const issuerId = input.runContext?.originatingAgentId; - if (!issuerId || !input.runContext?.gatewayId || input.actor.actorType !== "agent") return basePolicyService.decide(input, decisionOptions); - if (!input.runContext.gatewayTokenId) throw new ToolGatewayHttpError(403, "Delegated gateway token is no longer available", "gateway_token_run_context_invalid"); - let issuerCache: ToolAccessDecisionCache | undefined; - if (decisionOptions.cache) { - issuerCache = issuerDecisionCaches.get(decisionOptions.cache); - if (!issuerCache) { issuerCache = createToolAccessDecisionCache(); issuerDecisionCaches.set(decisionOptions.cache, issuerCache); } - } - const requiredAction = decisionOptions.requiredGatewayAction ?? (input.consumeRateLimit ? "tools/call" : undefined); - const authorityKey = `gateway-issuer:${input.companyId}:${input.runContext.gatewayTokenId}:${issuerId}:${requiredAction ?? "inspect"}`; - let authority = issuerCache?.get(authorityKey); - if (!authority) { - authority = assertGatewayIssuerAuthority(input, requiredAction); - issuerCache?.set(authorityKey, authority); - } - await authority; - if (issuerId === input.actor.agentId) { - const decision = await basePolicyService.decide(input, decisionOptions); - return { ...decision, policyExplanation: { ...decision.policyExplanation, delegatedGatewayIssuer: issuerId } }; - } - const issuerInput = { ...input, actor: { ...input.actor, agentId: issuerId } }; - const issuer = await basePolicyService.decide(issuerInput, { ...decisionOptions, cache: issuerCache }); - const target = await basePolicyService.decide(input, { ...decisionOptions, sharedRateDecision: issuer }); - const chosen = !issuer.allowed && issuer.decision !== "require_approval" ? issuer - : !target.allowed ? target : issuer.decision === "require_approval" ? issuer : target; - if (input.consumeRateLimit) await basePolicyService.writeAudit(issuerInput, issuer); - return { ...chosen, matchedPolicyIds: [...new Set([...issuer.matchedPolicyIds, ...target.matchedPolicyIds])], policyExplanation: { - ...chosen.policyExplanation, - consumedRateAdmissions: target.policyExplanation?.consumedRateAdmissions, - delegatedCallerConsumedRateAdmissions: issuer.policyExplanation?.consumedRateAdmissions, - delegatedGatewayIssuer: issuerId, - } }; + decide: decideGatewayPolicy, + admitInvocation(input: ToolAccessDecisionInput, invocationId: string, claim?: ToolApprovalClaim) { + return basePolicyService.admitInvocation(input, invocationId, claim, (policy, admissionInput, transaction) => + decideGatewayPolicy(admissionInput, { admittedInvocationId: invocationId, requiredGatewayAction: "tools/call" }, policy, transaction)); }, }; - async function assertGatewayIssuerAuthority(input: ToolAccessDecisionInput, requiredAction?: ToolMcpGatewayTokenAction) { - const [row] = await db.select({ token: toolMcpGatewayTokens, gateway: toolMcpGateways }).from(toolMcpGatewayTokens) + async function assertGatewayIssuerAuthority(input: ToolAccessDecisionInput, requiredAction?: ToolMcpGatewayTokenAction, database: Db = db) { + const [row] = await database.select({ token: toolMcpGatewayTokens, gateway: toolMcpGateways }).from(toolMcpGatewayTokens) .innerJoin(toolMcpGateways, eq(toolMcpGateways.id, toolMcpGatewayTokens.gatewayId)) .where(and(eq(toolMcpGatewayTokens.id, input.runContext!.gatewayTokenId!), eq(toolMcpGatewayTokens.companyId, input.companyId))); const issuerId = input.runContext!.originatingAgentId!; @@ -1299,8 +1311,8 @@ export function createToolGatewayService( const resource = { type: "connection_management" as const, companyId: input.companyId, gatewayId: row.gateway.id, profileId: row.gateway.profileId, purpose: "tool" as const, operation: "gateway_token.use", targetAgentId: row.gateway.agentId, projectId: row.gateway.projectId, issueId: row.gateway.issueId }; - await connectionManagementService(db).authorize(actor, "connections:gateway", resource, { mutation: false }); - await connectionManagementService(db).authorize(actor, "connections:test", resource, { mutation: false }); + await connectionManagementService(database).authorize(actor, "connections:gateway", resource, { mutation: false }); + await connectionManagementService(database).authorize(actor, "connections:test", resource, { mutation: false }); } async function recordToolInvocation(input: ToolAccessDecisionInput, decision: ToolAccessDecision) { try { @@ -7548,6 +7560,7 @@ export function createToolGatewayService( matchedPolicyIds: string[]; timeoutMs?: number; signal?: AbortSignal; + approvedClaim?: ToolApprovalClaim; managementContext?: ConnectionManagementContext; }): Promise< | { decision: "allowed"; invocationId: string; result: unknown } @@ -7557,14 +7570,9 @@ export function createToolGatewayService( error: { message: string; reasonCode: string }; } > { - await db - .update(toolInvocations) - .set({ - status: "executing", - startedAt: new Date(), - updatedAt: new Date(), - }) - .where(eq(toolInvocations.id, args.invocationId)); + if (!(await startToolInvocation(db, args.invocationId, args.approvedClaim))) { + throw new ToolGatewayHttpError(409, "Tool action execution claim is no longer current", "action_already_consumed"); + } await writeAudit({ session: args.session, companyId: args.companyId, @@ -7587,6 +7595,8 @@ export function createToolGatewayService( }); const startedAt = Date.now(); + let connectedMcpExecution: Awaited> | Awaited> | null; + let resultValidation: Awaited>; try { await args.managementContext?.reauthorize(); if (args.managementContext?.actor.type === "agent") { @@ -7598,7 +7608,7 @@ export function createToolGatewayService( } } const executionTimeoutMs = timeoutMs(args.timeoutMs, args.tool); - const connectedMcpExecution = + connectedMcpExecution = (args.tool.providerType === "mcp_remote_http" || args.tool.providerType === "provider_rest") ? await executeRemoteHttpTool( args.session, @@ -7629,7 +7639,7 @@ export function createToolGatewayService( ); } const result = connectedMcpExecution.result; - const resultValidation = await validateToolContent({ + resultValidation = await validateToolContent({ value: result, direction: "result", sensitiveMode: "redact", @@ -7640,69 +7650,6 @@ export function createToolGatewayService( throw new ToolGatewayHttpError(502, String(providerResult.content || providerResult.error), "tool_error", { execution: connectedMcpExecution.execution }); } - await db - .update(toolInvocations) - .set({ - status: "succeeded", - resultHash: resultValidation.summary.sha256 ?? null, - resultSummary: resultValidation.summary, - resultSizeBytes: resultValidation.summary.sizeBytes ?? null, - completedAt: new Date(), - updatedAt: new Date(), - }) - .where(eq(toolInvocations.id, args.invocationId)); - await writeToolCallEvent({ - invocationId: args.invocationId, - session: args.session, - eventType: "call_completed", - outcome: "success", - toolName: args.tool.name, - policyDecision: "allow", - reasonCode: "tool_completed", - argumentsSummary: args.argumentsSummary, - resultSummary: resultValidation.summary, - detectorMetadata: resultValidation.detectorMetadata, - metadata: { - source: "test", - headerSummary: connectedMcpExecution.headerSummary ?? undefined, - execution: connectedMcpExecution.execution, - }, - tool: args.tool, - }); - await writeAudit({ - session: args.session, - companyId: args.companyId, - agentId: args.agentId, - runId: args.session.runId, - issueId: args.session.issueId, - actorType: args.session.actorType, - actorId: args.session.actorId ?? args.userId, - action: "tool_gateway.call_completed", - details: { - source: "test", - invocationId: args.invocationId, - decision: "allow", - reasonCode: "tool_completed", - tool: args.tool.name, - ...toolAuditMetadata(args.tool), - durationMs: Date.now() - startedAt, - argumentsSummary: args.argumentsSummary, - result: summarizeResult(resultValidation.value), - resultSummary: resultValidation.summary, - promptInjection: resultValidation.detectorMetadata, - headerSummary: connectedMcpExecution.headerSummary ?? undefined, - execution: connectedMcpExecution.execution, - }, - }); - // After the bookkeeping above: a throw there is caught below, overwrites - // the row to failed, and emits — an earlier success emit would make one - // execution report both outcomes. - void emitConnectionInvoked(db, args.invocationId); - return { - decision: "allowed" as const, - invocationId: args.invocationId, - result: resultValidation.value, - }; } catch (err) { const status = err instanceof ToolGatewayHttpError ? err.status : 502; const reasonCode = @@ -7712,21 +7659,10 @@ export function createToolGatewayService( ? err.reasonCode : "tool_execution_failed"; const message = err instanceof Error ? err.message : String(err); - await db - .update(toolInvocations) - .set({ - status: - status === 504 - ? "timed_out" - : status === 429 - ? "rate_limited" - : "failed", - errorCode: reasonCode, - errorMessage: message, - completedAt: new Date(), - updatedAt: new Date(), - }) - .where(eq(toolInvocations.id, args.invocationId)); + await persistToolTestOutcome(db, args.invocationId, { + status: status === 504 ? "timed_out" : status === 429 ? "rate_limited" : "failed", + errorCode: reasonCode, errorMessage: message, + }, args.approvedClaim); void emitConnectionInvoked(db, args.invocationId); await writeToolCallEvent({ invocationId: args.invocationId, @@ -7785,132 +7721,161 @@ export function createToolGatewayService( : {}), }; } + await persistToolTestOutcome(db, args.invocationId, { + status: "succeeded", result: resultValidation.summary, + }, args.approvedClaim); + await writeToolCallEvent({ + invocationId: args.invocationId, + session: args.session, + eventType: "call_completed", + outcome: "success", + toolName: args.tool.name, + policyDecision: "allow", + reasonCode: "tool_completed", + argumentsSummary: args.argumentsSummary, + resultSummary: resultValidation.summary, + detectorMetadata: resultValidation.detectorMetadata, + metadata: { + source: "test", + headerSummary: connectedMcpExecution.headerSummary ?? undefined, + execution: connectedMcpExecution.execution, + }, + tool: args.tool, + }); + await writeAudit({ + session: args.session, + companyId: args.companyId, + agentId: args.agentId, + runId: args.session.runId, + issueId: args.session.issueId, + actorType: args.session.actorType, + actorId: args.session.actorId ?? args.userId, + action: "tool_gateway.call_completed", + details: { + source: "test", + invocationId: args.invocationId, + decision: "allow", + reasonCode: "tool_completed", + tool: args.tool.name, + ...toolAuditMetadata(args.tool), + durationMs: Date.now() - startedAt, + argumentsSummary: args.argumentsSummary, + result: summarizeResult(resultValidation.value), + resultSummary: resultValidation.summary, + promptInjection: resultValidation.detectorMetadata, + headerSummary: connectedMcpExecution.headerSummary ?? undefined, + execution: connectedMcpExecution.execution, + }, + }); + void emitConnectionInvoked(db, args.invocationId); + return { + decision: "allowed" as const, + invocationId: args.invocationId, + result: resultValidation.value, + }; + + } + + function isApprovalPreparationRejection(error: unknown) { + return error instanceof ToolContentValidationError || + (error instanceof ToolGatewayHttpError || error instanceof HttpError) && error.status >= 400 && error.status < 500 && + ![408, 425, 429].includes(error.status); + } + + async function bindVerifiedApprovalArguments(invocation: typeof toolInvocations.$inferSelect, claim: ToolApprovalClaim, parameters: unknown) { + const preview = summarizeToolValue(parameters).sha256; + const verified = toolRequestIdentityHash(parameters, options.toolActionSigningSecret); + if (invocation.argumentsHash === preview && invocation.argumentsHash !== verified && + !await bindVerifiedToolApprovalArguments(db, claim, { preview, verified })) { + throw new ToolGatewayHttpError(409, "Tool action execution claim is no longer current", "action_already_consumed"); + } } - /** - * Drive a freshly-approved test-origin ask-first request to completion. The - * Test tab has no agent run to re-invoke the parked call, so approving it in - * the Review tab is what executes it — the live status panel then surfaces the - * real result. Reconstructs the impersonated test session and the signed - * arguments, and never throws: any failure is recorded on the invocation so it - * shows up as an error in the panel rather than rolling back the approval. - */ async function runApprovedTestInvocation( invocation: typeof toolInvocations.$inferSelect, - parameters: unknown, + signedPayload: NonNullable>, actionRequestId: string, ): Promise { - const agentId = invocation.agentId; - if (!invocation.connectionId || !agentId) return; - const delegated = invocation.policyExplanation?.delegatedConnectionTest as { - agentId: string; responsibleUserId: string; runId: string | null; keyId: string | null; - resource: ConnectionManagementContext["resource"]; - } | undefined; - const userId = delegated?.responsibleUserId ?? invocation.actorId ?? "board"; - const session: ToolGatewaySession = { - id: "test-call", - token: "test-call", - companyId: invocation.companyId, - agentId, - runId: null, - issueId: null, - projectId: null, - actorType: delegated ? "agent" : "user", - actorId: delegated?.agentId ?? userId, - responsibleUserId: userId, - createdAt: new Date(), - expiresAt: new Date(Date.now() + DEFAULT_SESSION_TTL_MS), - }; - let managementContext: ConnectionManagementContext | undefined; - let tool: ToolGatewayDescriptor | undefined; - try { - tool = ( - await connectedMcpToolsForConnection( - invocation.companyId, - invocation.connectionId, - ) - ).find( - (candidate) => - candidate.name === invocation.toolName || - candidate.upstreamToolName === invocation.toolName, - ); - } catch { - tool = undefined; - } - if (!tool) { - await db - .update(toolInvocations) - .set({ - status: "failed", - errorCode: "tool_not_found", - errorMessage: `Tool "${invocation.toolName}" is no longer connected`, - completedAt: new Date(), - updatedAt: new Date(), - }) - .where(eq(toolInvocations.id, invocation.id)); - void emitConnectionInvoked(db, invocation.id); - await reflectToolActionInteractionLifecycle({ - actionRequestId, - status: "failed", - errorCode: "tool_not_found", - errorMessage: `Tool "${invocation.toolName}" is no longer connected`, - }); - return; - } - const argumentsSummary = (await validateToolContent({ - value: parameters, - direction: "arguments", - sensitiveMode: "redact", - promptInjectionMode: "ignore", - })).summary; + const claim = await claimToolTestApproval(db, actionRequestId, invocation.id); + if (!claim) return; + let execution: Parameters[0]; try { + const agentId = invocation.agentId; + if (!invocation.connectionId || !agentId) { + throw new ToolGatewayHttpError(409, "Test action context is no longer available", "action_origin_invalid"); + } + const delegated = invocation.policyExplanation?.delegatedConnectionTest as { + agentId: string; responsibleUserId: string; runId: string | null; keyId: string | null; + resource: ConnectionManagementContext["resource"]; + } | undefined; + const userId = delegated?.responsibleUserId ?? invocation.actorId ?? "board"; + const session: ToolGatewaySession = { + id: "test-call", token: "test-call", companyId: invocation.companyId, agentId, + runId: null, issueId: null, projectId: null, actorType: delegated ? "agent" : "user", actorId: delegated?.agentId ?? userId, + responsibleUserId: userId, createdAt: new Date(), expiresAt: new Date(Date.now() + DEFAULT_SESSION_TTL_MS), + }; + let managementContext: ConnectionManagementContext | undefined; if (delegated) { managementContext = await connectionManagementService(db).authorize({ type: "agent", companyId: invocation.companyId, agentId: delegated.agentId, onBehalfOfUserId: delegated.responsibleUserId, runId: delegated.runId, keyId: delegated.keyId, }, "connections:test", delegated.resource, { targetAgentIds: [agentId], afterHumanAction: true }); Object.assign(session, managementContext.workContext, { originatingAgentId: delegated.agentId, approvedInvocationId: invocation.id }); - const current = await policyService.decide(policyInputForTool({ session, tool, parameters }), { admittedInvocationId: invocation.id }); - if (!current.allowed && current.decision !== "require_approval") throw new ToolGatewayHttpError(403, current.explanation, current.reasonCode); } - const outcome = await runTestToolInvocation({ - session, - managementContext, - tool, - parameters, - invocationId: invocation.id, - companyId: invocation.companyId, - agentId, - userId, - argumentsSummary, - reasonCode: "approval_granted", - matchedPolicyIds: invocation.matchedPolicyIds ?? [], - }); - await reflectToolActionInteractionLifecycle({ - actionRequestId, - status: "error" in outcome ? "failed" : "executed", - ...("error" in outcome ? { errorCode: outcome.error.reasonCode, errorMessage: outcome.error.message } : {}), - }); + const tool = (await connectedMcpToolsForConnection(invocation.companyId, invocation.connectionId)) + .find(candidate => candidate.name === invocation.toolName || candidate.upstreamToolName === invocation.toolName); + if (!tool) throw new ToolGatewayHttpError(404, `Tool "${invocation.toolName}" is no longer connected`, "tool_not_found"); + if (!approvalSnapshotsMatch(signedPayload.approvalSnapshot, await connectedRemoteApprovalSnapshot(session, tool))) { + throw new ToolGatewayHttpError(409, "Tool definition or connection changed; request a new review", "approved_tool_target_changed"); + } + if (!(await approvedManagedArgumentsRemainCurrent(session, tool, signedPayload.arguments))) { + throw new ToolGatewayHttpError(409, "Approved tool action managed arguments changed after review", "approved_tool_managed_arguments_changed"); + } + await bindVerifiedApprovalArguments(invocation, claim, signedPayload.arguments); + const access = await basePolicyService.admitInvocation( + policyInputForTool({ session, tool, parameters: signedPayload.arguments, consumeRateLimit: false }), + invocation.id, + claim, + async (policy, admissionInput) => { + const callerSession = delegatedTestCallerSession(session); + const callerInput = callerSession ? policyInputForTool({ session: callerSession, tool, + parameters: signedPayload.arguments, consumeRateLimit: true }) : null; + const options = { admittedInvocationId: invocation.id }; + const caller = callerInput ? await policy.decide(callerInput, options) : null; + const target = await policy.decide(admissionInput, { ...options, sharedRateDecision: caller ?? undefined }); + const chosen = caller && !caller.allowed && caller.decision !== "require_approval" ? caller + : !target.allowed ? target : caller?.decision === "require_approval" ? caller : target; + if (callerInput && caller) await policy.writeAudit(callerInput, caller); + return { ...chosen, policyExplanation: { + ...chosen.policyExplanation, + consumedRateAdmissions: target.policyExplanation?.consumedRateAdmissions, + delegatedCallerConsumedRateAdmissions: caller?.policyExplanation?.consumedRateAdmissions, + } }; + }, + ); + if (!access.allowed && access.decision !== "require_approval") { + throw new ToolGatewayHttpError(403, access.explanation, access.reasonCode); + } + const argumentsSummary = (await validateToolContent({ value: signedPayload.arguments, + direction: "arguments", sensitiveMode: "redact", promptInjectionMode: "ignore" })).summary; + execution = { session, managementContext, tool, parameters: signedPayload.arguments, invocationId: invocation.id, + companyId: invocation.companyId, agentId, userId, argumentsSummary, reasonCode: "approval_granted", + approvedClaim: claim, matchedPolicyIds: invocation.matchedPolicyIds ?? [] }; } catch (err) { + if (!isApprovalPreparationRejection(err)) { + // Preparation has not entered runTestToolInvocation. Preserve approval + // through dependency failures; the claim owner still verifies no dispatch. + await releaseToolApproval(db, claim); + throw err; + } const message = err instanceof Error ? err.message : String(err); - await db - .update(toolInvocations) - .set({ - status: "failed", - errorCode: "tool_execution_failed", - errorMessage: message, - completedAt: new Date(), - updatedAt: new Date(), - }) - .where(eq(toolInvocations.id, invocation.id)); - void emitConnectionInvoked(db, invocation.id); - await reflectToolActionInteractionLifecycle({ - actionRequestId, - status: "failed", - errorCode: "tool_execution_failed", - errorMessage: message, - }); + const errorCode = err instanceof ToolGatewayHttpError || err instanceof ToolContentValidationError + ? err.reasonCode : "tool_execution_failed"; + const settled = await persistToolTestOutcome(db, invocation.id, { status: "failed", errorCode, errorMessage: message }, claim); + if (settled) void emitConnectionInvoked(db, invocation.id); + return; } + await runTestToolInvocation(execution); } async function waitForActionRequestExecution(actionRequestId: string) { @@ -8080,6 +8045,7 @@ export function createToolGatewayService( } async function expireApprovedActionForManagedArgumentDrift(input: { + companyId: string; actionRequestId: string; invocationId: string; toolName: string; @@ -8097,7 +8063,7 @@ export function createToolGatewayService( ); const now = new Date(); await options.beforeManagedArgumentDriftExpiry?.(); - const [expired] = await db + const [expired] = await writeToolReviewChange(db, input.companyId, tx => tx .update(toolActionRequests) .set({ status: "expired", resolvedAt: now, updatedAt: now }) .where( @@ -8108,7 +8074,7 @@ export function createToolGatewayService( : eq(toolActionRequests.status, "approved"), ), ) - .returning({ id: toolActionRequests.id }); + .returning({ id: toolActionRequests.id })); if (!expired) return error; await db .update(toolInvocations) @@ -8227,7 +8193,7 @@ export function createToolGatewayService( ); } - const [claimed] = await db + const [claimed] = await writeToolReviewChange(db, actionRequest.companyId, tx => tx .update(toolActionRequests) .set({ status: "executing", updatedAt: new Date() }) .where( @@ -8236,7 +8202,7 @@ export function createToolGatewayService( eq(toolActionRequests.status, "approved"), ), ) - .returning(); + .returning()); if (!claimed) { const settled = await waitForActionRequestExecution(actionRequest.id); const [settledInvocation] = await db @@ -8262,92 +8228,141 @@ export function createToolGatewayService( ); } - // Terminal-issue expiry revokes pending/approved requests, but a claim that - // committed just before the issue closed slips past that revocation. Recheck - // the issue after winning the claim so a governed action never runs external - // side effects for an issue that is already done or cancelled. - const issue = await assertIssueOpenForApprovedAction({ - claimed, - invocation, - }); - - const signedPayload = readSignedToolArgumentsPayload({ - signedArguments: claimed.signedArguments, - invocationId: invocation.id, - toolName: invocation.toolName, - signingSecret: options.toolActionSigningSecret, - }); - if (!signedPayload) { - const error = new ToolGatewayHttpError( - 409, - "Approved tool action arguments signature is invalid", - "signed_arguments_invalid", - ); - await markApprovedActionFailed({ - actionRequestId: claimed.id, - invocationId: invocation.id, - claimUpdatedAt: claimed.updatedAt, - expectedInvocationStatus: "awaiting_approval", - error, - }); - throw error; - } - if (signedPayload.executionOnApprove !== true) { - const error = new ToolGatewayHttpError( - 409, - "This approval predates execute-on-approve and must remain inert", - "legacy_approved_action_inert", - ); - await markApprovedActionFailed({ - actionRequestId: claimed.id, - invocationId: invocation.id, - claimUpdatedAt: claimed.updatedAt, - expectedInvocationStatus: "awaiting_approval", - error, - }); - throw error; - } - - const session: ToolGatewaySession = { - id: `approved-action:${claimed.id}`, - token: "", - companyId: invocation.companyId, - agentId: invocation.agentId, - runId: invocation.runId, - issueId: invocation.issueId, - projectId: issue?.projectId ?? null, - gatewayId: invocation.gatewayId, - gatewayPublicId: invocation.gatewayPublicId, - gatewayTokenId: invocation.gatewayTokenId, - actorType: "agent", - actorId: invocation.actorType === "agent" ? invocation.actorId ?? invocation.agentId : invocation.agentId, - originatingAgentId: typeof invocation.policyExplanation?.delegatedGatewayIssuer === "string" ? invocation.policyExplanation.delegatedGatewayIssuer : invocation.actorType === "agent" && invocation.gatewayId && !invocation.runId && !invocation.gatewayTokenId ? invocation.actorId : null, - createdAt: new Date(), - expiresAt: new Date(Date.now() + DEFAULT_SESSION_TTL_MS), + const claim: ToolApprovalClaim = { + actionRequestId: claimed.id, invocationId: invocation.id, claimedAt: claimed.updatedAt, }; - let tool: ToolGatewayDescriptor; - let liveApprovalSnapshot: Awaited< - ReturnType - >; - try { + const agentId = invocation.agentId; + async function prepareExecution() { + // Terminal-issue expiry revokes pending/approved requests, but a claim that + // committed just before the issue closed slips past that revocation. Recheck + // the issue after winning the claim so a governed action never runs external + // side effects for an issue that is already done or cancelled. + const issue = await assertIssueOpenForApprovedAction({ + claimed, + invocation, + }); + + const signedPayload = readSignedToolArgumentsPayload({ + signedArguments: claimed.signedArguments, + invocationId: invocation.id, + toolName: invocation.toolName, + signingSecret: options.toolActionSigningSecret, + }); + if (!signedPayload) { + const error = new ToolGatewayHttpError( + 409, + "Approved tool action arguments signature is invalid", + "signed_arguments_invalid", + ); + throw error; + } + if (signedPayload.executionOnApprove !== true) { + const error = new ToolGatewayHttpError( + 409, + "This approval predates execute-on-approve and must remain inert", + "legacy_approved_action_inert", + ); + throw error; + } + + const session: ToolGatewaySession = { + id: `approved-action:${claimed.id}`, + token: "", + companyId: invocation.companyId, + agentId, + runId: invocation.runId, + issueId: invocation.issueId, + projectId: issue?.projectId ?? null, + gatewayId: invocation.gatewayId, + gatewayPublicId: invocation.gatewayPublicId, + gatewayTokenId: invocation.gatewayTokenId, + actorType: invocation.actorType as ToolGatewaySession["actorType"], + actorId: invocation.actorId, + originatingAgentId: typeof invocation.policyExplanation?.delegatedGatewayIssuer === "string" ? invocation.policyExplanation.delegatedGatewayIssuer : invocation.actorType === "agent" && invocation.gatewayId && !invocation.runId && !invocation.gatewayTokenId ? invocation.actorId : null, + createdAt: new Date(), + expiresAt: new Date(Date.now() + DEFAULT_SESSION_TTL_MS), + }; await restoreApprovedActionIdentity( session, signedPayload.identityContextId, ); session.approvedInvocationId = invocation.id; session.approvedSlackInvocationId = invocation.id; - tool = await findToolForSession(session, invocation.toolName); - liveApprovalSnapshot = await connectedRemoteApprovalSnapshot( + const tool = await findToolForSession(session, invocation.toolName); + const liveApprovalSnapshot = await connectedRemoteApprovalSnapshot( session, tool, ); - const currentAccess = await policyService.decide( + if ( + !approvalSnapshotsMatch( + signedPayload.approvalSnapshot, + liveApprovalSnapshot, + ) + ) { + const error = new ToolGatewayHttpError( + 409, + "Approved tool action target changed after review", + "approved_tool_target_changed", + ); + throw error; + } + const parameters = signedPayload.arguments; + const canonicalArguments = canonicalToolArguments(parameters); + if ( + ![ + toolRequestIdentityHash(parameters, options.toolActionSigningSecret), + // Historical approvals used the redacted preview hash. Their signature + // still binds the complete canonical arguments checked below. + summarizeToolValue(parameters).sha256, + ].includes(claimed.canonicalArgumentsHash) || + !verifyToolArgumentsSignature({ + signedArguments: claimed.signedArguments, + invocationId: invocation.id, + toolName: invocation.toolName, + canonicalArguments, + approvalSnapshot: signedPayload.approvalSnapshot, + executionOnApprove: true, + identityContextId: signedPayload.identityContextId, + signingSecret: options.toolActionSigningSecret, + }) + ) { + const error = new ToolGatewayHttpError( + 409, + "Approved tool action arguments do not match reviewed hash", + "signed_arguments_mismatch", + ); + throw error; + } + const managedArgumentsRemainCurrent = + await approvedManagedArgumentsRemainCurrent(session, tool, parameters); + if (!managedArgumentsRemainCurrent) { + throw await expireApprovedActionForManagedArgumentDrift({ + companyId: claimed.companyId, + actionRequestId: claimed.id, + invocationId: invocation.id, + toolName: invocation.toolName, + ownsExecutingClaim: true, + }); + } + + const argumentsSummary = (await validateToolContent({ + value: parameters, + direction: "arguments", + sensitiveMode: "redact", + promptInjectionMode: "ignore", + })).summary; + // Validate the signed and managed payload before consuming admission. + // Historical payload drift belongs to the expiry owner above. + await bindVerifiedApprovalArguments(invocation, claim, signedPayload.arguments); + const currentAccess = await policyService.admitInvocation( policyInputForTool({ session, tool, parameters: signedPayload.arguments, + consumeRateLimit: false, }), - { admittedInvocationId: invocation.id, requiredGatewayAction: "tools/call" }, + invocation.id, + claim, ); if ( !currentAccess.allowed && @@ -8358,120 +8373,43 @@ export function createToolGatewayService( currentAccess.explanation, currentAccess.reasonCode, ); - } catch (error) { - await markApprovedActionFailed({ - actionRequestId: claimed.id, - invocationId: invocation.id, - claimUpdatedAt: claimed.updatedAt, - expectedInvocationStatus: "awaiting_approval", - error, - }); - throw error; + // Final recheck at the last DB write before dispatch: tool and snapshot + // resolution above involve network calls, so re-verify the issue is still + // open now that only the provider call remains. A close that commits after + // this read has raced an execution that was approved, claimed, and verified + // while the issue was open; that instant is irreducible for an external + // side effect gated by DB state (holding a DB lock across a remote provider + // call is not an option), and the accepted linearization is that the + // execution wins — its result still lands on the expired card via + // reflectToolActionInteractionLifecycle. + await assertIssueOpenForApprovedAction({ claimed, invocation }); + return { session, tool, parameters, argumentsSummary }; } - if ( - !approvalSnapshotsMatch( - signedPayload.approvalSnapshot, - liveApprovalSnapshot, - ) - ) { - const error = new ToolGatewayHttpError( - 409, - "Approved tool action target changed after review", - "approved_tool_target_changed", - ); - await markApprovedActionFailed({ - actionRequestId: claimed.id, - invocationId: invocation.id, - claimUpdatedAt: claimed.updatedAt, - expectedInvocationStatus: "awaiting_approval", - error, - }); - throw error; - } - const parameters = signedPayload.arguments; - const canonicalArguments = canonicalToolArguments(parameters); - if ( - ![ - toolRequestIdentityHash(parameters, options.toolActionSigningSecret), - // Historical approvals used the redacted preview hash. Their signature - // still binds the complete canonical arguments checked below. - summarizeToolValue(parameters).sha256, - ].includes(claimed.canonicalArgumentsHash) || - !verifyToolArgumentsSignature({ - signedArguments: claimed.signedArguments, - invocationId: invocation.id, - toolName: invocation.toolName, - canonicalArguments, - approvalSnapshot: signedPayload.approvalSnapshot, - executionOnApprove: true, - identityContextId: signedPayload.identityContextId, - signingSecret: options.toolActionSigningSecret, - }) - ) { - const error = new ToolGatewayHttpError( - 409, - "Approved tool action arguments do not match reviewed hash", - "signed_arguments_mismatch", - ); - await markApprovedActionFailed({ - actionRequestId: claimed.id, - invocationId: invocation.id, - claimUpdatedAt: claimed.updatedAt, - expectedInvocationStatus: "awaiting_approval", - error, - }); - throw error; - } - let managedArgumentsRemainCurrent: boolean; + let prepared: Awaited>; try { - managedArgumentsRemainCurrent = - await approvedManagedArgumentsRemainCurrent(session, tool, parameters); + prepared = await prepareExecution(); } catch (error) { - await markApprovedActionFailed({ - actionRequestId: claimed.id, - invocationId: invocation.id, - claimUpdatedAt: claimed.updatedAt, - expectedInvocationStatus: "awaiting_approval", - error, - }); + if (isApprovalPreparationRejection(error)) { + await markApprovedActionFailed({ + actionRequestId: claimed.id, + invocationId: invocation.id, + claimUpdatedAt: claimed.updatedAt, + expectedInvocationStatus: "awaiting_approval", + error, + }); + } else { + await releaseToolApproval(db, claim); + } throw error; } - if (!managedArgumentsRemainCurrent) { - throw await expireApprovedActionForManagedArgumentDrift({ - actionRequestId: claimed.id, - invocationId: invocation.id, - toolName: invocation.toolName, - ownsExecutingClaim: true, - }); - } - - const argumentsSummary = (await validateToolContent({ - value: parameters, - direction: "arguments", - sensitiveMode: "redact", - promptInjectionMode: "ignore", - })).summary; - // Final recheck at the last DB write before dispatch: tool and snapshot - // resolution above involve network calls, so re-verify the issue is still - // open now that only the provider call remains. A close that commits after - // this read has raced an execution that was approved, claimed, and verified - // while the issue was open; that instant is irreducible for an external - // side effect gated by DB state (holding a DB lock across a remote provider - // call is not an option), and the accepted linearization is that the - // execution wins — its result still lands on the expired card via - // reflectToolActionInteractionLifecycle. - await assertIssueOpenForApprovedAction({ claimed, invocation }); + const { session, tool, parameters, argumentsSummary } = prepared; const startedAt = Date.now(); - await db - .update(toolInvocations) - .set({ - status: "executing", - approvalState: "approved", - startedAt: new Date(), - updatedAt: new Date(), - }) - .where(eq(toolInvocations.id, invocation.id)); + // Keep dispatch and outcome persistence outside the preparation retry + // boundary. Only the still-current claim may record the provider start. + if (!(await startToolInvocation(db, invocation.id, claim))) { + throw new ToolGatewayHttpError(409, "Tool action execution claim is no longer current", "action_already_consumed"); + } await reflectToolActionInteractionLifecycle({ actionRequestId: claimed.id, status: "executing", @@ -9977,7 +9915,33 @@ export function createToolGatewayService( actionReviewExpiryDeadlines: reviewExpiry.deadlines, sweepExpiredActionReviewsForCompany: reviewExpiry.sweepForCompany, - async sweepActionReviews(input: { includeExpiry?: boolean } = {}) { + approvedActionReviewCompanies: (companyId?: string) => approvedToolReviewCompanies(db, companyId), + + async recoverApprovedActionReviews(companyId?: string) { + return recoverApprovedToolReviews(db, async row => { + try { + const prepared = await prepareApprovedToolReview(db, { actionRequestId: row.request.id, + invocationId: row.invocation.id, signingSecret: options.toolActionSigningSecret }); + if (prepared.kind === "skip") return false; + if (prepared.kind === "settled") { + await reflectToolActionInteractionLifecycle(prepared.projection); + return false; + } + const { request, invocation, payload } = prepared; + if (!isTestOriginInvocation(invocation) && payload.executionOnApprove !== true) return false; + await this.approveActionRequest({ companyId: request.companyId, actionRequestId: request.id, + actor: { userId: request.decidedByUserId ?? request.resolvedByUserId } }); + const [remaining] = await db.select({ status: toolActionRequests.status }).from(toolActionRequests) + .where(eq(toolActionRequests.id, request.id)); + return remaining?.status === "approved"; + } catch (err) { + logger.warn({ err, actionRequestId: row.request.id }, "Could not recover approved tool action"); + return true; + } + }, companyId); + }, + + async sweepActionReviews(input: { includeExpiry?: boolean; includeApproved?: boolean } = {}) { // A process may stop between persisting a provider outcome and updating the // feed projection. Reconcile from authoritative rows before delivering it. const unreflected = await db @@ -10016,38 +9980,21 @@ export function createToolGatewayService( const staleAt = new Date(now.getTime() - 10 * 60_000); let cursor: string | undefined; let scanned = input.includeExpiry === false ? 0 : (await reviewExpiry.sweep(now)).scanned; + if (input.includeApproved !== false) scanned += (await this.recoverApprovedActionReviews()).scanned; for (;;) { const rows = await db .select() .from(toolActionRequests) .where( and( - or( - eq(toolActionRequests.status, "approved"), - and( - eq(toolActionRequests.status, "executing"), - lte(toolActionRequests.updatedAt, staleAt), - ), - ), + eq(toolActionRequests.status, "executing"), + lte(toolActionRequests.updatedAt, staleAt), cursor ? gt(toolActionRequests.id, cursor) : undefined, ), ) .orderBy(asc(toolActionRequests.id)) .limit(100); for (const row of rows) { - if (row.status === "approved") { - await this.approveActionRequest({ - companyId: row.companyId, - actionRequestId: row.id, - actor: { userId: row.decidedByUserId ?? row.resolvedByUserId }, - }).catch((error) => - logger.warn( - { err: error, actionRequestId: row.id }, - "Could not recover approved tool action", - ), - ); - continue; - } const status = "failed"; const errorCode = "tool_execution_outcome_unknown"; const errorMessage = "Execution was interrupted; the external outcome is unknown. Inspect the provider before retrying."; @@ -10239,10 +10186,12 @@ export function createToolGatewayService( actionRequestId: actionRequest.id, status: "approved", }); - if ( - !isTestOriginInvocation(invocation) && - signedPayload.executionOnApprove === true - ) { + if (isTestOriginInvocation(invocation)) { + await runApprovedTestInvocation(invocation, signedPayload, actionRequest.id); + const [settled] = await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, actionRequest.id)); + return actionRequestResolution(settled ?? actionRequest); + } + if (signedPayload.executionOnApprove === true) { try { await executeApprovedAgentInvocation({ actionRequest, invocation }); } catch { @@ -10318,13 +10267,18 @@ export function createToolGatewayService( "Tool definition or connection changed; request a new review", "approved_tool_target_changed", ); + const previewHash = summarizeToolValue(signedPayload.arguments).sha256; const access = await policyService.decide( policyInputForTool({ session, tool, parameters: signedPayload.arguments, + consumeRateLimit: false, }), - { admittedInvocationId: invocation.id, requiredGatewayAction: "tools/call" }, + { admittedInvocationId: invocation.id, requiredGatewayAction: "tools/call", + admittedPreviewHash: [previewHash, toolRequestIdentityHash(signedPayload.arguments, options.toolActionSigningSecret)] + .includes(actionRequest.canonicalArgumentsHash) ? previewHash : undefined, + }, ); if (!access.allowed && access.decision !== "require_approval") throw new ToolGatewayHttpError( @@ -10347,7 +10301,7 @@ export function createToolGatewayService( if (isTestOriginInvocation(invocation)) { await runApprovedTestInvocation( { ...invocation, approvalState: "approved" }, - signedPayload.arguments, + signedPayload, updated.id, ); } else if (signedPayload.executionOnApprove === true) { @@ -10911,7 +10865,7 @@ export function createToolGatewayService( ); await options.beforeLegacyApprovedActionClaim?.(); const claimedAt = new Date(); - const [claimed] = await db + const [claimed] = await writeToolReviewChange(db, actionRequest.companyId, tx => tx .update(toolActionRequests) .set({ status: "executing", @@ -10924,7 +10878,7 @@ export function createToolGatewayService( eq(toolActionRequests.status, "approved"), ), ) - .returning(); + .returning()); if (!claimed) { throw new ToolGatewayHttpError( 409, @@ -11004,13 +10958,14 @@ export function createToolGatewayService( )) ) { throw await expireApprovedActionForManagedArgumentDrift({ + companyId: actionRequest.companyId, actionRequestId: actionRequest.id, invocationId: storedInvocation.id, toolName: storedInvocation.toolName, }); } const claimedAt = new Date(); - const [claimed] = await db + const [claimed] = await writeToolReviewChange(db, actionRequest.companyId, tx => tx .update(toolActionRequests) .set({ status: "executing", @@ -11023,7 +10978,7 @@ export function createToolGatewayService( eq(toolActionRequests.status, "approved"), ), ) - .returning(); + .returning()); if (!claimed) { throw new ToolGatewayHttpError( 409, diff --git a/server/src/services/tool-review-recovery-work.ts b/server/src/services/tool-review-recovery-work.ts new file mode 100644 index 00000000000..5611f5cf155 --- /dev/null +++ b/server/src/services/tool-review-recovery-work.ts @@ -0,0 +1,33 @@ +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 { createToolGatewayService } from "./tool-gateway.js"; + +export function registerToolReviewRecoveryWork( + coordinator: ReturnType, + gateway: Pick, "recoverApprovedActionReviews" | "approvedActionReviewCompanies">, + canRun: () => boolean, +) { + // Dispatch failures are reported by the domain owner, not thrown. Preserve + // their retry deadline when another write reloads the same company's work. + const retries = new Map(); + return registerScopedDeadlineWork(coordinator, { + queue: DELIVERY_QUEUES.toolReviewRecovery, + batchSize: 1, + decodeScope: hint => hint === "*" ? undefined : hint, + matches: (entry, companyId?: string) => companyId === undefined || entry.companyId === companyId, + load: async (companyId?: string) => { + const rows = await gateway.approvedActionReviewCompanies(companyId); + const retained = new Set(rows.map(row => row.companyId)); + for (const id of retries.keys()) if ((companyId === undefined || id === companyId) && !retained.has(id)) retries.delete(id); + return rows.map(row => ({ ...row, id: row.companyId, dueAt: retries.get(row.companyId) ?? Date.now() })); + }, + check: async entry => { + const result = await gateway.recoverApprovedActionReviews(entry.companyId); + if (!result.retry) { retries.delete(entry.companyId); return null; } + const dueAt = Date.now() + 30_000; + retries.set(entry.companyId, dueAt); + return { ...entry, dueAt }; + }, + }, canRun); +} diff --git a/server/src/services/tool-review-recovery.ts b/server/src/services/tool-review-recovery.ts new file mode 100644 index 00000000000..69aa98c76f0 --- /dev/null +++ b/server/src/services/tool-review-recovery.ts @@ -0,0 +1,119 @@ +import { and, asc, eq, gt } from "drizzle-orm"; +import { approvals, toolActionRequests, toolInvocations, type Db } from "@paperclipai/db"; + +import { readSignedToolArgumentsPayload } from "./tool-content-guards.js"; +import { notifyToolReviewChange } from "./tool-review-work-notifications.js"; + +type ReviewProjection = { + actionRequestId: string; + status: "executed" | "executing" | "failed" | "cancelled"; + errorCode?: string | null; + errorMessage?: string | null; + resultSummary?: string | null; +}; + +/** Reconcile saved history before dispatch; never infer a safe provider replay. */ +export async function prepareApprovedToolReview(db: Db, input: { + actionRequestId: string; + invocationId: string; + signingSecret?: string; +}) { + return db.transaction(async tx => { + // Match Test-tab claims/outcome persistence. Recheck after the locks because + // a foreground approval may have claimed the row since the recovery scan. + const [invocation] = await tx.select().from(toolInvocations) + .where(eq(toolInvocations.id, input.invocationId)).for("update"); + const [request] = await tx.select().from(toolActionRequests) + .where(and(eq(toolActionRequests.id, input.actionRequestId), + eq(toolActionRequests.invocationId, input.invocationId))).for("update"); + if (!invocation || request?.status !== "approved") return { kind: "skip" } as const; + const now = new Date(); + + async function settle(projection: ReviewProjection, failure?: { + status: "failed" | "denied"; + errorCode: string; + errorMessage: string; + }) { + await notifyToolReviewChange(tx, request.companyId); + if (failure) await tx.update(toolInvocations).set({ ...failure, completedAt: now, updatedAt: now }) + .where(eq(toolInvocations.id, invocation.id)); + await tx.update(toolActionRequests).set({ status: projection.status, + ...(projection.status === "executing" + ? { updatedAt: invocation.startedAt ?? invocation.updatedAt } + : { resolvedAt: invocation.completedAt ?? now, updatedAt: now }), + }).where(eq(toolActionRequests.id, request.id)); + return { kind: "settled", projection } as const; + } + function fail(status: "failed" | "cancelled", invocationStatus: "failed" | "denied", errorCode: string, errorMessage: string) { + return settle({ actionRequestId: request.id, status, errorCode, errorMessage }, + { status: invocationStatus, errorCode, errorMessage }); + } + if (invocation.companyId !== request.companyId) { + // Quarantine the request without modifying another company's invocation. + return settle({ actionRequestId: request.id, status: "failed", + errorCode: "action_context_mismatch", errorMessage: "Tool action and invocation companies do not match." }); + } + if (["succeeded", "failed", "denied", "cancelled", "timed_out", "rate_limited", "executing"].includes(invocation.status)) { + return settle({ actionRequestId: request.id, + status: invocation.status === "succeeded" ? "executed" + : invocation.status === "executing" ? "executing" + : invocation.status === "cancelled" ? "cancelled" : "failed", + errorCode: invocation.errorCode, errorMessage: invocation.errorMessage, + resultSummary: invocation.resultSummary?.summary }); + } + if (invocation.status !== "awaiting_approval") { + return fail("failed", "failed", "tool_recovery_state_invalid", + "Approved action has inconsistent invocation history. Inspect the provider before retrying; recovery did not replay it."); + } + + // Missing-key/configuration errors deliberately propagate as retryable; + // only a decoded invalid signature is a permanent request failure. + const payload = readSignedToolArgumentsPayload({ signedArguments: request.signedArguments, + invocationId: invocation.id, toolName: invocation.toolName, signingSecret: input.signingSecret }); + if (!payload) return fail("cancelled", "failed", "action_request_invalidated", + "Stored tool arguments are no longer verifiable; submit a new action for review."); + if (request.approvalId) { + const [formal] = await tx.select({ status: approvals.status }).from(approvals) + .where(and(eq(approvals.id, request.approvalId), eq(approvals.companyId, request.companyId))); + if (!formal || formal.status === "rejected" || formal.status === "cancelled") { + return fail("cancelled", "denied", "formal_approval_unavailable", + "Required formal board approval is unavailable or was declined; submit a new action for review."); + } + // Human input has no deadline. The approval owner publishes a committed + // resolution/cancellation to this queue; startup also rediscovers the row. + if (formal.status === "pending" || formal.status === "revision_requested") { + return { kind: "skip" } as const; + } + } + return { kind: "ready", request, invocation, payload } as const; + }); +} + +export function approvedToolReviewCompanies(db: Db, companyId?: string) { + return db.select({ companyId: toolActionRequests.companyId }).from(toolActionRequests) + .innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId)) + .where(and(eq(toolActionRequests.status, "approved"), + companyId ? eq(toolActionRequests.companyId, companyId) : undefined)) + .groupBy(toolActionRequests.companyId); +} + +export async function recoverApprovedToolReviews(db: Db, recover: (input: { + request: typeof toolActionRequests.$inferSelect; + invocation: typeof toolInvocations.$inferSelect; +}) => Promise, companyId?: string) { + let cursor: string | undefined; + let scanned = 0, retry = false; + for (;;) { + const rows = await db.select({ request: toolActionRequests, invocation: toolInvocations }) + .from(toolActionRequests).innerJoin(toolInvocations, eq(toolInvocations.id, toolActionRequests.invocationId)) + .where(and(eq(toolActionRequests.status, "approved"), + companyId ? eq(toolActionRequests.companyId, companyId) : undefined, + cursor ? gt(toolActionRequests.id, cursor) : undefined)) + .orderBy(asc(toolActionRequests.id)).limit(100); + for (const row of rows) retry = await recover(row) || retry; + scanned += rows.length; + if (rows.length < 100) break; + cursor = rows[rows.length - 1].request.id; + } + return { scanned, retry }; +} diff --git a/server/src/services/tool-review-work-notifications.ts b/server/src/services/tool-review-work-notifications.ts index 19c8e433d75..1fc52d02b56 100644 --- a/server/src/services/tool-review-work-notifications.ts +++ b/server/src/services/tool-review-work-notifications.ts @@ -1,8 +1,9 @@ import type { Db } from "@paperclipai/db"; import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; -export function notifyToolReviewChange(transaction: object, companyId: string) { - return notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewExpiry, companyId); +export async function notifyToolReviewChange(transaction: object, companyId: string) { + await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewExpiry, companyId); + await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewRecovery, companyId); } export function writeToolReviewChange(db: Db, companyId: string, write: (transaction: Db) => Promise): Promise { diff --git a/server/src/services/tool-runtime-metrics.ts b/server/src/services/tool-runtime-metrics.ts index 3d877f0dee9..c984ba24915 100644 --- a/server/src/services/tool-runtime-metrics.ts +++ b/server/src/services/tool-runtime-metrics.ts @@ -11,7 +11,7 @@ function minuteBucket(date: Date): Date { } export async function incrementToolRuntimeMetricCounter( - db: Db, + db: Pick, input: { companyId: string; metric: string; @@ -42,7 +42,7 @@ export async function incrementToolRuntimeMetricCounter( }); } -export async function recordToolRuntimeAuditWriteFailure(db: Db, companyId: string) { +export async function recordToolRuntimeAuditWriteFailure(db: Pick, companyId: string) { try { await incrementToolRuntimeMetricCounter(db, { companyId, From 56bc470ab25efa265ed7248bb9a9bc73f7a031c4 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:30:37 -0500 Subject: [PATCH 2/7] perf(server): project continuation history result fields (#17930) 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. > - A continuation carries completed tool receipts so the agent can avoid repeat actions. > - It also checks saved conversation and workspace recovery fields before choosing a prior terminal run. > - The history query transfers every result field for every matching run. > - Native output and unused receipt request fields can make this read large. > - This pull request selects the fields those consumers use and keeps each completed receipt result in full. > - The benefit is less database transfer with the same history, recovery decisions, and completed-action evidence. ## Linked Issues or Issue Description **What existing behavior does this improve?** The history read in `buildExecutionContinuation`. **Current behavior** The query returns complete `result_json` values for all matching runs. Consumers read completed receipt state, operation ID and result, plus conversation and workspace recovery controls. Large native output and receipt request fields cross the connection without being used. **Proposed behavior** Select only those result fields in PostgreSQL. Keep typed policy and recovery values. Keep all eligible completed receipts and their complete result values. Retain missing versus null receipt results, run and receipt order, company/task/agent scope, and the source-run exception. Keep the full retained history without a new limit. **Reason and benefit** The synthetic wide-output fixture removes 99.879% of this query's DataRow bytes. A required 2 MiB receipt-result control saves only 0.0074%, because that complete result is needed. Actual savings depend on result contents; the wide-output result is not a forecast for all deployments. **Breaking changes** None intended. No schema, API, migration, workflow, history limit, or receipt truncation changes. **Additional context** Related: #17481 projects a separate recovery read, and #17896 narrows explicit continuation admission. This PR covers the continuation history query and has no dependency on the other byte reduction PRs. ## What Changed - Project completed tool receipts to their state, operation ID and complete result. Omit fields that the continuation does not read. - Project typed conversation/workspace controls and the recovery schema. Keep the shared policy helper unchanged. - Add real PostgreSQL comparisons for complete continuation envelopes, ordering, scope, legacy JSON, recovery flags, and receipt result preservation. - Add external isolated database support to the existing continuation tests and document a reproducible query benchmark. ## Verification - Pinned baseline: `3cd3af5d75f200185ed4d9703a3145594a489b13`. - PostgreSQL 17.11 with synthetic local data. The harness captures SQL from the real baseline and treatment services. Imported helpers remain unchanged. - Command: `pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-continuation-history.ts --baseline-ref=3cd3af5d75f200185ed4d9703a3145594a489b13`. Set `PAPERCLIP_CONTINUATION_HISTORY_BENCHMARK_DATABASE_URL` to a disposable database ending in `_test` to use an external server. The default uses disposable embedded PostgreSQL. - The baseline was measured before the production edit with `--baseline-only`. The treatment compares complete envelopes, every retained scalar column, completed receipts, and shared policy decisions. The wide unused-output fixture must remove more than 90% of DataRow bytes or the benchmark fails. - Wide unused-output fixture: 25 runs with independent incompressible 192 KiB native output and 32 KiB unused receipt request fields. DataRow bytes: 5,744,950 to 6,925 (99.879% less). - Required-result control: one complete 2 MiB receipt result. DataRow bytes: 2,097,556 to 2,097,401 (0.0074% less). The whole result is checked for equality. - Exact byte boundary: PostgreSQL text-format DataRow frames, including field length prefixes. Excludes RowDescription, command metadata, TLS, TCP, and other service queries. - Seven measured query round trips per variant follow two warmups and alternate order. Final-head wide-output median: 32.86 to 4.41 ms (ranges 26.24–35.54 and 3.62–5.21 ms). Required-result median: 17.01 to 20.60 ms (ranges 16.30–32.89 and 18.85–22.48 ms). The required-result control shows projection overhead and overlapping timing ranges; it has no latency improvement claim. These are local measurements, not deployed latency results. - `PAPERCLIP_EXECUTION_CONTINUATION_TEST_DATABASE_URL= pnpm exec vitest run server/src/services/execution-continuation.test.ts server/src/services/execution-continuation-history-read.test.ts --maxWorkers=1`: 55 tests pass in PostgreSQL 17. - Cases cover numeric receipt key order, empty operation IDs, malformed receipt entries, missing versus null results, complete large results, malformed root JSON, all closed workspace restore failure codes, invalid recovery schemas, cancelled admission rows, and company/task/agent/source-run boundaries. - `pnpm -r typecheck` and `pnpm build` pass on final head `d665d9f5c47b237c81b9cc80fdec1d39ad90754f`. The final-head focused PostgreSQL run passes all 55 tests. The final benchmark records that SHA, an empty source diff, and passing equivalence/byte assertions. The first typecheck found optional array accesses in new test assertions; explicit required-array assertions fixed them. Local full `pnpm test:run` is not claimed because the host embedded PostgreSQL runtime is unavailable; the full test matrix runs in CI. Exact-head Greptile review completed success at 5/5 with no actionable findings or unresolved threads. The full final-head CI matrix passes. All 58 current-head checks are terminal: 54 success, two neutral, and two optional Storybook skips. One original server shard ended with a canceled test step and no assertion failure; its single targeted retry passed. No product change was needed for that interruption. ## Risks - Future continuation consumers must add any newly required result field to this projection. Existing shared policy semantics stay in the helper. - Completed receipt results can still be large and can dominate transfer. This PR preserves them without a cap. The receipt-heavy control adds JSON projection work for only 155 bytes of savings, so it can be slower despite equal output. - JSON malformed-value and property-presence rules affect action evidence and recovery. Real PostgreSQL comparisons check those decisions and complete output. - Production transfer and latency improvements need a fresh deployed capture. Nothing was merged or deployed by this work. ## Model Used OpenAI GPT-6 through Codex. The exact runtime model ID and context window are not exposed by this session. The work used repository tools, code execution, and real PostgreSQL validation. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: Paperclip --- doc/DEVELOPING.md | 11 ++ scripts/benchmark-continuation-history.ts | 120 ++++++++++++++++ ...xecution-continuation-history-read.test.ts | 128 ++++++++++++++++++ .../services/execution-continuation.test.ts | 12 +- server/src/services/execution-continuation.ts | 24 +++- 5 files changed, 291 insertions(+), 4 deletions(-) create mode 100644 scripts/benchmark-continuation-history.ts create mode 100644 server/src/services/execution-continuation-history-read.test.ts diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 4853284df55..6f7b2b181cc 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -1888,6 +1888,17 @@ TLS and protocol metadata. To use an isolated external database, set `PAPERCLIP_CONTINUATION_BENCHMARK_DATABASE_URL` to a disposable database ending in `_test`. The harness applies migrations there and adds synthetic fixtures. +Continuation history reads select completed tool receipts and the typed +conversation/workspace recovery fields used to choose the prior terminal run. +Every completed receipt keeps its full result. Receipt order, company/agent/task +scope, and the complete retained history stay unchanged. Saved results remain +available to detail, recovery, and execution paths. +Use `pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-continuation-history.ts --baseline-ref=` +to compare generated SQL, complete continuation envelopes, and DataRow bytes. +The benchmark includes a large required-receipt control. Its external database +option is `PAPERCLIP_CONTINUATION_HISTORY_BENCHMARK_DATABASE_URL`, with the same +disposable `_test` database restriction. + Retry scheduling is in `server/src/services/heartbeat/retries.ts`. It owns bounded retry schedules, connection and workspace contention deferrals, shared-workspace holder checks, due retry promotion, and retry-now requests. `createHeartbeatRetries` diff --git a/scripts/benchmark-continuation-history.ts b/scripts/benchmark-continuation-history.ts new file mode 100644 index 00000000000..c26a118c589 --- /dev/null +++ b/scripts/benchmark-continuation-history.ts @@ -0,0 +1,120 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { randomBytes, randomUUID } from "node:crypto"; +import { promises as fs } from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { agents, applyPendingMigrations, companies, createDb, heartbeatRuns, issues, startEmbeddedPostgresTestDatabase, type Db } from "../packages/db/src/index.js"; +import { buildExecutionContinuation } from "../server/src/services/execution-continuation.js"; +import { hasConversationContinuationPolicy } from "../server/src/services/conversation-continuation.js"; +import { resolveExternalTestDatabaseUrl } from "../server/src/__tests__/helpers/external-test-database.js"; + +const repoRoot = fileURLToPath(new URL("../", import.meta.url)); +const git = (...args: string[]) => execFileSync("git", args, { cwd: repoRoot, encoding: "utf8" }); +const baselineRef = process.argv.find(arg => arg.startsWith("--baseline-ref="))?.slice(15); +assert.ok(baselineRef, "Pass a pinned pre-fix --baseline-ref"); +const baselineRevision = git("rev-parse", "--verify", `${baselineRef}^{commit}`).trim(); +const baselineOnly = process.argv.includes("--baseline-only"); +const keepAlive = setInterval(() => {}, 1000); +let database: Awaited> | undefined; +let db: Db | undefined; +let baselineDir: string | undefined; +try { + const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_CONTINUATION_HISTORY_BENCHMARK_DATABASE_URL"); + if (externalUrl) { + await applyPendingMigrations(externalUrl); + database = { connectionString: externalUrl, cleanup: async () => {} }; + } else database = await startEmbeddedPostgresTestDatabase("continuation-history-benchmark-"); + db = createDb(database.connectionString); + const original = new URL("../server/src/services/execution-continuation.ts", import.meta.url); + baselineDir = await fs.mkdtemp(path.join(repoRoot, "server/scripts/.history-baseline-")); + const source = git("show", `${baselineRevision}:server/src/services/execution-continuation.ts`); + const baselinePath = path.join(baselineDir, "continuation.ts"); + await fs.writeFile(baselinePath, source.replace(/(from |import\()"(\.{1,2}\/[^\"]+)"/g, + (_match, prefix: string, specifier: string) => `${prefix}${JSON.stringify(fileURLToPath(new URL(specifier, original)))}`)); + const baseline = await import(pathToFileURL(baselinePath).href) as { buildExecutionContinuation: typeof buildExecutionContinuation }; + const object = (value: unknown): Record => value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; + const receipts = (value: unknown) => Object.entries(object(object(value).apiToolReceipts)).flatMap(([id, entry]) => { + const receipt = object(entry); + return receipt.state === "completed" && typeof receipt.operationId === "string" ? [{ id, operationId: receipt.operationId, result: receipt.result }] : []; + }); + const results = []; + for (const receiptHeavy of [false, true]) { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Synthetic history", issuePrefix: `B${companyId.replaceAll("-", "")}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Fixture", adapterType: "paperclip_runner" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Continue", status: "in_progress", assigneeAgentId: agentId }); + const runCount = receiptHeavy ? 1 : 25; + const requiredResult = receiptHeavy ? randomBytes(1536 * 1024).toString("base64") : { receipt: "required output" }; + for (let index = 0; index < runCount; index++) await db.insert(heartbeatRuns).values({ companyId, agentId, + contextSnapshot: { issueId }, status: "failed", errorCode: "adapter_failed", runtimeMode: "legacy", + createdAt: new Date(Date.UTC(2020, 0, 1, 0, 0, index)), + resultJson: { nativeResult: { output: receiptHeavy ? "small" : randomBytes(144 * 1024).toString("base64") }, + conversationContinuation: "continue_conversation_v1", + apiToolReceipts: { saved: { state: "completed", operationId: "save_document", result: requiredResult, + request: receiptHeavy ? "small" : randomBytes(24 * 1024).toString("base64") }, pending: { state: "started", operationId: "unfinished", result: "not a completed action" } } }, + }); + await db.$client.unsafe("ANALYZE"); + async function capture(invoke: typeof buildExecutionContinuation) { + let query: { sql: string; params: unknown[] } | undefined; + let history: Array> | undefined; + const recorded = new Proxy(db!, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const selection = from(...args), execute = selection.execute.bind(selection); + if (args[0] === heartbeatRuns) selection.execute = async (...executeArgs: Parameters) => { + const statement = selection.toSQL(), rows = await execute(...executeArgs); + if (statement.sql.includes('order by "heartbeat_runs"."created_at" asc')) { query = statement; history = rows; } + return rows; + }; + return selection; + }) as typeof builder.from; + return builder; + }; + }}); + const envelope = await invoke({ db: recorded, companyId, issueId, agentId, context: {}, summary: null, exposeLowTrustRaw: false }); + assert.ok(query); assert.ok(history); + return { query, history, envelope }; + } + const before = await capture(baseline.buildExecutionContinuation); + const after = await capture(baselineOnly ? baseline.buildExecutionContinuation : buildExecutionContinuation); + assert.deepEqual(after.envelope, before.envelope); + assert.equal(after.history.length, before.history.length); + for (let index = 0; index < before.history.length; index++) { + const oldRow = before.history[index], newRow = after.history[index]; + for (const [key, value] of Object.entries(oldRow)) if (key !== "result") assert.deepEqual(newRow[key], value); + assert.deepEqual(receipts(newRow.result), receipts(oldRow.result)); + assert.equal(hasConversationContinuationPolicy(newRow.result as Record), hasConversationContinuationPolicy(oldRow.result as Record)); + } + const queries = [before.query, after.query], bytes: number[] = [], samples: number[][] = [[], []]; + for (let iteration = 0; iteration < 9; iteration++) for (const variant of iteration % 2 ? [1, 0] : [0, 1]) { + const query = queries[variant], start = performance.now(); + const rows = await db.$client.unsafe(query.sql, query.params as never[]).raw(); + if (iteration >= 2) samples[variant].push(performance.now() - start); + bytes[variant] = rows.reduce((sum, row) => sum + 7 + row.reduce((n: number, value: Buffer | null) => n + 4 + (value?.length ?? 0), 0), 0); + } + if (!baselineOnly && !receiptHeavy) assert.ok(bytes[1] < bytes[0] / 10, "Wide unused-result fixture must remove more than 90% of DataRow bytes"); + if (receiptHeavy) { + assert.ok(after.envelope.completedActions); + assert.deepEqual(after.envelope.completedActions[0].result, requiredResult); + } + const plans = []; + for (const query of queries) { + const [plan] = await db.$client.unsafe(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query.sql}`, query.params as never[]); + plans.push(plan["QUERY PLAN"]); + } + const median = (values: number[]) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]; + results.push({ fixture: receiptHeavy ? "required-receipt-result" : "wide-unused-output", runCount, rows: after.history.length, + equalEnvelope: true, equalRetainedColumnsAndReceipts: true, baselineDataRowBytes: bytes[0], treatmentDataRowBytes: bytes[1], + reduction: 1 - bytes[1] / bytes[0], baselineMedianMs: median(samples[0]), treatmentMedianMs: median(samples[1]), samples, queries, plans }); + } + console.log(JSON.stringify({ baselineRevision, treatmentRevision: git("rev-parse", "HEAD").trim(), + treatmentDiff: git("diff", "HEAD", "--", "server/src/services/execution-continuation.ts"), baselineOnly, + byteBoundary: "Exact text-format PostgreSQL DataRow frames, excluding metadata, TLS and TCP", postgres: await db.$client.unsafe("select version()"), results }, null, 2)); +} finally { + try { await db?.$client.end({ timeout: 0 }); await database?.cleanup(); + if (baselineDir) await fs.rm(baselineDir, { recursive: true, force: true }); + } finally { clearInterval(keepAlive); } +} diff --git a/server/src/services/execution-continuation-history-read.test.ts b/server/src/services/execution-continuation-history-read.test.ts new file mode 100644 index 00000000000..78b288849dc --- /dev/null +++ b/server/src/services/execution-continuation-history-read.test.ts @@ -0,0 +1,128 @@ +import assert from "node:assert/strict"; +import { randomBytes, randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { agents, applyPendingMigrations, companies, createDb, heartbeatRuns, issues, type Db } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; +import { resolveExternalTestDatabaseUrl } from "../__tests__/helpers/external-test-database.js"; +import { buildExecutionContinuation } from "./execution-continuation.js"; + +const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_EXECUTION_CONTINUATION_TEST_DATABASE_URL"); +const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("continuation history PostgreSQL projection", () => { + let database: Awaited>; + let db: Db; + beforeAll(async () => { + if (externalUrl) { + await applyPendingMigrations(externalUrl); + database = { connectionString: externalUrl, cleanup: async () => {} }; + } else database = await startEmbeddedPostgresTestDatabase("continuation-history-read-"); + db = createDb(database.connectionString); + }, 60_000); + afterAll(async () => { await db?.$client.end(); await database?.cleanup(); }); + + async function fixture(result: unknown) { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "History", issuePrefix: `H${companyId.replaceAll("-", "")}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Executor", adapterType: "paperclip_runner" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Continue", status: "in_progress", assigneeAgentId: agentId }); + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "failed", errorCode: "adapter_failed", + contextSnapshot: { issueId }, createdAt: new Date("2020-01-01T00:00:00Z"), resultJson: result as Record | null }).returning(); + return { companyId, agentId, issueId, run }; + } + + async function invoke(f: Awaited>, fullResult: boolean, context: Record = {}) { + const reads: Array>> = []; + const recorded = new Proxy(db, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const historyRead = Object.hasOwn(fields[0] ?? {}, "retryOfRunId"); + const builder = historyRead && fullResult + ? target.select({ ...fields[0], result: heartbeatRuns.resultJson }) : target.select(...fields); + const from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const query = from(...args), execute = query.execute.bind(query); + if (historyRead) query.execute = async (...executeArgs: Parameters) => { + const rows = await execute(...executeArgs); reads.push(rows); return rows; + }; + return query; + }) as typeof builder.from; + return builder; + }; + }}); + const result = await buildExecutionContinuation({ db: recorded, companyId: f.companyId, agentId: f.agentId, + issueId: f.issueId, context, summary: null, exposeLowTrustRaw: false }); + return { result, reads }; + } + + async function compare(f: Awaited>, context: Record = {}) { + const before = await invoke(f, true, context), after = await invoke(f, false, context); + expect(after.result).toEqual(before.result); + expect(after.reads).toHaveLength(1); + expect(after.reads[0].map(({ result: _result, ...fields }) => fields)).toEqual(before.reads[0].map(({ result: _result, ...fields }) => fields)); + return { before, after }; + } + + it("keeps every completed receipt, its full result, missing values and receipt order", async () => { + const payload = randomBytes(128 * 1024).toString("base64"); + const result = { nativeResult: { output: payload }, conversationContinuation: "continue_conversation_v1", apiToolReceipts: { + "10": { state: "completed", operationId: "ten", result: null, unusedRequest: payload }, + "2": { state: "completed", operationId: "two", result: { nested: [payload, false, null] } }, + missing: { state: "completed", operationId: "" }, + pending: { state: "started", operationId: "pending", result: payload }, + invalid: { state: "completed", operationId: 42, result: payload }, + array: ["completed", "operation"], + scalar: "completed", number: 42, null: null, + } }; + const f = await fixture(result), { before, after } = await compare(f); + assert.ok(after.result.completedActions); + expect(after.result.completedActions.map(receipt => receipt.receiptId)).toEqual(["2", "10", "missing"]); + expect(after.result.completedActions[0].result).toEqual(result.apiToolReceipts["2"].result); + expect(after.result.completedActions[1].result).toBeNull(); + expect(after.result.completedActions[2].result).toBeUndefined(); + expect(Buffer.byteLength(JSON.stringify(after.reads))).toBeLessThan(Buffer.byteLength(JSON.stringify(before.reads)) / 2); + expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.run.id)))[0].resultJson).toEqual(result); + }); + + const recovery = { schema: "paperclip.workspace-restore-recovery.v1" }; + it.each([ + { value: null, interrupted: false }, { value: [], interrupted: false }, { value: "scalar", interrupted: false }, { value: 42, interrupted: false }, + { value: {}, interrupted: false }, { value: { conversationContinuation: "continue_conversation_v1", apiToolReceipts: [1, 2] }, interrupted: true }, + { value: { conversationContinuation: 42, apiToolReceipts: "malformed" }, interrupted: false }, + ...["restore_permission_denied", "restore_lock_timeout", "restore_unsafe_archive", "restore_failed"].map(workspaceRestoreFailure => ({ + value: { conversationContinuation: "continue_conversation_v1", workspaceRestoreFailure, workspaceRestoreRecovery: recovery }, interrupted: false, + })), + { value: { conversationContinuation: "continue_conversation_v1", workspaceRestoreFailure: "restore_unsafe_archive" }, interrupted: false }, + { value: { conversationContinuation: "continue_conversation_v1", workspaceRestoreFailure: "custom", workspaceRestoreRecovery: recovery }, interrupted: true }, + ...[null, [], "schema", { schema: 42 }, { schema: "other" }].map(workspaceRestoreRecovery => ({ + value: { conversationContinuation: "continue_conversation_v1", workspaceRestoreFailure: "restore_failed", workspaceRestoreRecovery }, interrupted: true, + })), + ])("keeps continuation/recovery decisions for typed legacy JSON $value", async ({ value, interrupted }) => { + const f = await fixture(value), { after } = await compare(f); + expect(after.result.interruptedRunId).toBe(interrupted ? f.run.id : undefined); + expect(after.result.completedActions).toEqual([]); + }); + + it("keeps full ordered history and source-agent scope without cross-company or cross-task receipts", async () => { + const completed = (operationId: string) => ({ apiToolReceipts: { saved: { state: "completed", operationId, result: { operationId } } } }); + const f = await fixture({ ...completed("first"), conversationContinuation: "continue_conversation_v1" }); + const otherAgentId = randomUUID(); + await db.insert(agents).values({ id: otherAgentId, companyId: f.companyId, name: "Previous owner", adapterType: "paperclip_runner" }); + const [source] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: otherAgentId, status: "succeeded", + contextSnapshot: { issueId: f.issueId }, resultJson: completed("other-agent"), createdAt: new Date("2020-01-01T00:01:00Z") }).returning(); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "cancelled", errorCode: "execution_reconciliation_required", + contextSnapshot: { issueId: f.issueId }, resultJson: completed("cancelled"), createdAt: new Date("2020-01-01T00:02:00Z") }); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "failed", + contextSnapshot: { issueId: randomUUID() }, resultJson: completed("foreign-task") }); + const foreign = await fixture(completed("foreign-company")); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId } }).where(eq(heartbeatRuns.id, foreign.run.id)); + const ordinary = await compare(f); + assert.ok(ordinary.after.result.completedActions); + expect(ordinary.after.result.completedActions.map(receipt => receipt.operationId)).toEqual(["first", "cancelled"]); + expect(ordinary.after.result.interruptedRunId).toBe(f.run.id); + const resumed = await compare(f, { previousRunId: source.id }); + assert.ok(resumed.after.result.completedActions); + expect(resumed.after.result.completedActions.map(receipt => receipt.operationId)).toEqual(["first", "other-agent", "cancelled"]); + expect(resumed.after.result.interruptedRunId).toBeUndefined(); + }); +}); diff --git a/server/src/services/execution-continuation.test.ts b/server/src/services/execution-continuation.test.ts index 834bf515ee7..fc9e88795ad 100644 --- a/server/src/services/execution-continuation.test.ts +++ b/server/src/services/execution-continuation.test.ts @@ -3,6 +3,7 @@ import { eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { agents, + applyPendingMigrations, companies, createDb, heartbeatRuns, @@ -15,6 +16,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, } from "../__tests__/helpers/embedded-postgres.js"; +import { resolveExternalTestDatabaseUrl } from "../__tests__/helpers/external-test-database.js"; import { StaleExecutionContinuationError, buildExecutionContinuation, currentContinuationOrigins, projectHumanInteractionResponse } from "./execution-continuation.js"; const expectStaleContinuation = async ( @@ -29,7 +31,8 @@ const expectMissingContinuationContext = async (run: () => Promise) => await expect(result).rejects.toThrow("continuation_source_context_missing"); await expect(result).rejects.not.toBeInstanceOf(StaleExecutionContinuationError); }; -const support = await getEmbeddedPostgresTestSupport(); +const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_EXECUTION_CONTINUATION_TEST_DATABASE_URL"); +const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); (support.supported ? describe : describe.skip)( "authorized continuation context", () => { @@ -44,13 +47,16 @@ const support = await getEmbeddedPostgresTestSupport(); laterId = randomUUID(), interactionId = randomUUID(); beforeAll(async () => { - database = await startEmbeddedPostgresTestDatabase( + if (externalUrl) { + await applyPendingMigrations(externalUrl); + database = { connectionString: externalUrl, cleanup: async () => {} }; + } else database = await startEmbeddedPostgresTestDatabase( "paperclip-continuation-context-", ); db = createDb(database.connectionString); await db .insert(companies) - .values({ id: companyId, name: "Continuation", issuePrefix: "CTX" }); + .values({ id: companyId, name: "Continuation", issuePrefix: `CTX${companyId.replaceAll("-", "")}` }); await db .insert(agents) .values({ diff --git a/server/src/services/execution-continuation.ts b/server/src/services/execution-continuation.ts index c44ce6ee325..378e7f1382c 100644 --- a/server/src/services/execution-continuation.ts +++ b/server/src/services/execution-continuation.ts @@ -31,6 +31,28 @@ const object = (v: unknown): Record => : {}; const string = (v: unknown) => typeof v === "string" && v.length > 0 ? v : null; +const historyResult = sql | null>`case + when jsonb_typeof(${heartbeatRuns.resultJson}) = 'object' then ( + select coalesce(jsonb_object_agg(field.key, case + when field.key = 'apiToolReceipts' and jsonb_typeof(field.value) = 'object' then ( + select coalesce(jsonb_object_agg(receipt.key, ( + select jsonb_object_agg(detail.key, detail.value) + from jsonb_each(receipt.value) as detail(key, value) + where detail.key in ('state', 'operationId', 'result') + )), '{}'::jsonb) + from jsonb_each(field.value) as receipt(key, value) + where receipt.value->'state' = '"completed"'::jsonb + and jsonb_typeof(receipt.value->'operationId') = 'string' + ) + when field.key = 'workspaceRestoreRecovery' and jsonb_typeof(field.value) = 'object' then ( + select coalesce(jsonb_object_agg(detail.key, detail.value), '{}'::jsonb) + from jsonb_each(field.value) as detail(key, value) + where detail.key = 'schema' + ) + else field.value end), '{}'::jsonb) + from jsonb_each(${heartbeatRuns.resultJson}) as field(key, value) + where field.key in ('apiToolReceipts', 'conversationContinuation', 'workspaceRestoreFailure', 'workspaceRestoreRecovery') + ) else ${heartbeatRuns.resultJson} end`; export function continuationOriginCommentIds(context: unknown): string[] { const c = object(context); const prior = object(c.executionContinuation); @@ -335,7 +357,7 @@ export async function buildExecutionContinuation(input: { ? { kind: "description" as const, id: issue.id, revision: hashObjectiveSource(issue.description) } : { kind: "title" as const, id: issue.id, revision: hashObjectiveSource(issue.title) }; const priorRuns = await db - .select({ id: heartbeatRuns.id, result: heartbeatRuns.resultJson, status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode, runtimeMode: heartbeatRuns.runtimeMode, retryOfRunId: heartbeatRuns.retryOfRunId }) + .select({ id: heartbeatRuns.id, result: historyResult, status: heartbeatRuns.status, errorCode: heartbeatRuns.errorCode, runtimeMode: heartbeatRuns.runtimeMode, retryOfRunId: heartbeatRuns.retryOfRunId }) .from(heartbeatRuns) .where( and( From c3a9a8e92af0ad4008481f8eed57df434acccdaa Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:31:21 -0500 Subject: [PATCH 3/7] perf(server): scope run identity reads to operation needs (#17931) 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. > - Tool and connection operations capture the current accepted requester. > - Capture locks the task and run, then reconciles pending steering. > - Most callers use identity or task fields from the returned run. > - The default query also transfers saved prompts, runner configuration, results, and logs. > - This pull request gives each production caller an explicit read scope. > - Narrow scopes keep their authority checks and return only selected columns. > - The Muse project path still reads its complete saved execution input. ## Linked Issues or Issue Description **What existing behavior does this improve?** Operation-time run identity capture for native tools, gateway sessions, project and workspace access, Slack, voice, connection management, and connection token admission. **Current behavior** These callers use the default full run read. Large saved execution documents cross the database connection even when the caller only needs the current accepted requester or task binding. **Proposed behavior** Use typed identity, task, broker, and project-execution scopes. Keep task-before-run locks, company and agent predicates, active status validation, and pending-steering reconciliation. Return the complete saved native input only where project admission uses it. **Reason and benefit** A synthetic PostgreSQL 17.11 fixture matches a wide run with a 142 KB context and a 77 KB runner profile. Its locked run DataRow falls from 225,101 bytes to 190–605 bytes for authority reads. The project scope returns 66,004 bytes because it must retain a complete 64 KB execution input. These are local DataRow measurements, not a forecast of production billing or latency. **Breaking changes** None to public APIs, saved data, or authority policy. Internal narrow return types omit columns that were not selected. The default full compatibility read and the existing GitHub-credential and authentication scopes keep their current contracts. **Additional context** The public issue and PR duplicate searches found no matching open change. This is one independent query optimization. It does not require other performance PRs. ## What Changed - Add typed scopes for accepted identity metadata, task authorization, token attribution, and saved project execution input. - Assign explicit scopes at all production `captureRunIdentity` call sites. - Keep the full native execution input for Muse project admission while omitting unrelated profile, context, result, and log data. - Narrow the broker's initial read and the existing Slack and connection-management historical reads to the same required fields. - Extend steering and acknowledgement regressions to all new scopes. Add real PostgreSQL projection, malformed JSON, tenant and agent, session-generation, and saved-input coverage. - Add a service-generated SQL benchmark with exact raw DataRow accounting, retained-field equality, plans, and alternating transaction timings. - Document the scope contracts and reproducible benchmark. ## Verification - Baseline: `623f1dc289a14a699ebbe3f09b94179d38fc2ae2`. - `vitest run server/src/__tests__/run-identity-projections.test.ts server/src/__tests__/run-identity.test.ts`: 54 tests passed on an owned disposable PostgreSQL 17.11 database. - The tests retain task-before-run and audit foreign-key lock behavior. Every scope rejects uncertain steering, accepts its durable acknowledgement, and preserves requester replay ordering. - A full-row mutation makes the narrow identity regression fail. The restored treatment passes. - `pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-run-identity-projections.ts --baseline-ref=623f1dc289a14a699ebbe3f09b94179d38fc2ae2` captures the real locked SQL for both versions. - Every retained column and selected JSON field matches the baseline. Identity contexts match. The complete stored run remains unchanged. Capture keeps the same five queries. | Scope | Before DataRow bytes | After DataRow bytes | Reduction | | --- | ---: | ---: | ---: | | Identity | 225,101 | 190 | 99.92% | | Task authorization | 225,101 | 410 | 99.82% | | Token broker | 225,101 | 605 | 99.73% | | Project execution input | 225,101 | 66,004 | 70.68% | - DataRow bytes include row framing and raw text-format column values. They exclude response metadata, TLS, and TCP. - Two warmups and seven alternating samples measure the complete capture transaction. Several timing ranges overlap. The primary claim is byte reduction; production latency is not verified. - Initial fixture runs exposed an empty external schema and an incomplete synthetic conversation binding. The test setup now applies migrations and supplies the required user/state fields. The final 54 tests passed. - `pnpm -r typecheck` and `pnpm build` passed locally. - Four existing skill-setup tests passed. Four assembled connection-management/native-tool consumer cases passed with real JWT/API-key authentication. These include per-request identity freshness and task-scoped activity authority. - A CI-only stale mock assertion expected two capture arguments; it now verifies the explicit identity scope. A repository-wide capture mock audit found no other stale argument assertions. - Review follow-up: the projection suite uses the existing embedded-support guard while always enabling an explicitly supplied external database. The audit-lock regression merges URL query parameters and retains existing PostgreSQL options. - `vitest run server/src/__tests__/run-identity-projections.test.ts server/src/__tests__/run-identity.test.ts server/src/__tests__/company-skills-routes.test.ts server/src/__tests__/project-skill-setup-identity.test.ts`: 123 tests passed. The external PostgreSQL URL included both `application_name` and `options`; lock tests verified `lock_timeout=1s` and retained `statement_timeout=5s`. - Full local tests are not run because the host's embedded PostgreSQL setup is unavailable. Greptile reviewed `06e1dd53a3fb24df74d5fbfb2ad397f291f1e30f` at 5/5 with zero unresolved threads. The full final-head CI matrix passes. All 58 checks are terminal: 55 success, one neutral, and two optional Storybook skips. - No migration, lockfile, workflow, new polling, or cache change. ## Risks A narrow read must retain each caller's actual fields. The caller audit includes Slack's wake-request fallback, conversation generation, legacy broker attribution, and the Muse parser's complete native input. JSON selection retains value types, including malformed legacy values. The saved-input scope preserves missing-key behavior. The default full read still returns the complete stored row for compatibility. Locks and live authority checks are unchanged. ## Model Used OpenAI GPT-6, accessed through Codex. The exact runtime model ID and context-window size were not exposed in this session. Used repository inspection, code execution, and PostgreSQL validation. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/run-identity-reads.md | 35 +++++ scripts/benchmark-run-identity-projections.ts | 120 ++++++++++++++++++ .../__tests__/company-skills-routes.test.ts | 2 +- .../run-identity-projection-fixture.ts | 41 ++++++ .../project-skill-setup-identity.test.ts | 2 +- .../run-identity-projections.test.ts | 116 +++++++++++++++++ server/src/__tests__/run-identity.test.ts | 37 ++++-- server/src/routes/projects.ts | 2 +- server/src/services/connection-intents.ts | 2 +- server/src/services/connection-management.ts | 8 +- .../services/connectors/slack-authority.ts | 6 +- .../execution-workspace-repositories.ts | 2 +- .../paperclip-runner-tool-authority.ts | 6 +- .../services/project-skill-source-bindings.ts | 2 +- server/src/services/project-tool-context.ts | 11 +- server/src/services/run-identity.ts | 65 +++++++++- .../tool-access/token-broker/admission.ts | 6 +- server/src/services/tool-gateway.ts | 2 +- .../src/services/voice/speko-agent-tools.ts | 2 +- 19 files changed, 427 insertions(+), 40 deletions(-) create mode 100644 doc/run-identity-reads.md create mode 100644 scripts/benchmark-run-identity-projections.ts create mode 100644 server/src/__tests__/helpers/run-identity-projection-fixture.ts create mode 100644 server/src/__tests__/run-identity-projections.test.ts diff --git a/doc/run-identity-reads.md b/doc/run-identity-reads.md new file mode 100644 index 00000000000..a41b252b411 --- /dev/null +++ b/doc/run-identity-reads.md @@ -0,0 +1,35 @@ +# Run identity reads + +`captureRunIdentity` locks the task before the run. It validates company, agent, +and active status. Pending steering still requires its durable acknowledgement. +The accepted requester is read for each operation. No scope adds a cache or skips +these checks. + +Callers choose a typed read scope: + +| Scope | Retained run data | Consumers | +| --- | --- | --- | +| `identity` | Run and accepted requester identifiers, status | Gateway, native connection tools, connection intents, project skill setup | +| `task_authorization` | Identity, task bindings, wake request, conversation generation, skill-test marker | Projects, workspace repositories, Slack, voice, connection management | +| `token_broker` | Identity, invocation source, task/project/routine and requester attribution | Connection token broker | +| `project_execution` | Task authorization plus runtime mode and the complete saved native execution input | Muse project admission | + +Narrow return types omit unselected columns. JSON projections preserve the types +of retained values. The default full read remains available for compatibility and +explicit inspection. Existing GitHub-credential and request-authentication scopes +keep their current contracts. Execution preparation and recovery retain their +separate complete-input reads. + +The synthetic real-PostgreSQL benchmark captures the actual locked query and +compares every retained column, context and identity result. It keeps the same +five-query reconciliation transaction, checks the unchanged stored run, records +plans and alternating timings, and measures raw PostgreSQL DataRow bytes: + +```sh +pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-run-identity-projections.ts --baseline-ref=623f1dc289a14a699ebbe3f09b94179d38fc2ae2 +``` + +The default uses disposable embedded PostgreSQL. `PAPERCLIP_TEST_DATABASE_URL` +can select a disposable local database whose name ends in `_test`. DataRow bytes +exclude response metadata, TLS and TCP. Byte reduction does not establish a +production latency or billing change. diff --git a/scripts/benchmark-run-identity-projections.ts b/scripts/benchmark-run-identity-projections.ts new file mode 100644 index 00000000000..4ddc589ef3b --- /dev/null +++ b/scripts/benchmark-run-identity-projections.ts @@ -0,0 +1,120 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { promises as fs } from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { applyPendingMigrations, createDb, startEmbeddedPostgresTestDatabase } from "../packages/db/src/index.js"; +import { captureRunIdentity } from "../server/src/services/run-identity.js"; +import { captureIdentityQueries, seedIdentityProjection, type IdentityQuery } from "../server/src/__tests__/helpers/run-identity-projection-fixture.js"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const git = (args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8" }); +const baselineRef = process.argv.find(arg => arg.startsWith("--baseline-ref="))?.slice(15); +assert.ok(baselineRef, "Pass an explicit pre-fix --baseline-ref="); +const baselineRevision = git(["rev-parse", "--verify", `${baselineRef}^{commit}`]).trim(); +const modulePath = "server/src/services/run-identity.ts"; +const unchangedHelpers = ["run-task-binding.ts", "task-retry.ts", "issue-queued-comment-queue.ts"]; +for (const name of unchangedHelpers) { + const helper = `server/src/services/${name}`; + assert.equal(git(["show", `${baselineRevision}:${helper}`]), await fs.readFile(path.join(root, helper), "utf8"), + `Baseline helper ${name} changed; isolate it before benchmarking`); +} +const keepAlive = setInterval(() => {}, 1_000); +let temporary: Awaited> | undefined; +let db: ReturnType | undefined; +let baselineDir: string | undefined; +try { + const oldSource = git(["show", `${baselineRevision}:${modulePath}`]); + const moduleUrl = new URL(`../${modulePath}`, import.meta.url); + baselineDir = await fs.mkdtemp(path.join(root, "server/scripts/.identity-projection-baseline-")); + const baselineFile = path.join(baselineDir, "run-identity.ts"); + await fs.writeFile(baselineFile, oldSource.replace(/from "(\.{1,2}\/[^\"]+)"/g, + (_match, specifier: string) => `from ${JSON.stringify(fileURLToPath(new URL(specifier, moduleUrl)))}`)); + const baseline = await import(pathToFileURL(baselineFile).href) as typeof import("../server/src/services/run-identity.js"); + const externalUrl = process.env.PAPERCLIP_TEST_DATABASE_URL; + if (externalUrl) { + const parsed = new URL(externalUrl); + assert.ok(["127.0.0.1", "localhost"].includes(parsed.hostname) && /_test$/.test(parsed.pathname), + "External benchmark database must be a disposable local *_test database"); + await applyPendingMigrations(externalUrl); + db = createDb(externalUrl); + } else { + temporary = await startEmbeddedPostgresTestDatabase("identity-projection-benchmark-"); + db = createDb(temporary.connectionString); + } + const f = await seedIdentityProjection(db); + await db.$client.unsafe("ANALYZE"); + const beforeQueries: IdentityQuery[] = []; + const before = await baseline.captureRunIdentity(captureIdentityQueries(db, beforeQueries), f); + const findRunQuery = (queries: IdentityQuery[]) => { + const query = queries.find(query => query.sql.includes('from "heartbeat_runs"') && query.sql.includes("for no key update")); + assert.ok(query, "Capture the actual locked identity query"); + return query; + }; + const beforeQuery = findRunQuery(beforeQueries); + const dataRowBytes = async (query: IdentityQuery) => { + const rows = await db!.$client.unsafe(query.sql, query.params as never[]).raw(); + return rows.reduce((total, row) => total + 7 + 4 * row.length + row.reduce((bytes, value) => bytes + (value?.byteLength ?? 0), 0), 0); + }; + const baselineBytes = await dataRowBytes(beforeQuery); + async function plan(query: IdentityQuery) { + const [result] = await db!.$client.unsafe(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query.sql}`, query.params as never[]); + return result!["QUERY PLAN"]; + } + const results = []; + for (const readScope of ["identity", "task_authorization", "token_broker", "project_execution"] as const) { + const afterQueries: IdentityQuery[] = []; + const after = await captureRunIdentity(captureIdentityQueries(db, afterQueries), f, { readScope }); + assert.deepEqual(after.context, before.context); + for (const [key, value] of Object.entries(after.run)) { + if (key === "runnerProfileJson") assert.deepEqual(value, { nativeExecutionInput: before.run.runnerProfileJson?.nativeExecutionInput }); + else if (key !== "contextSnapshot") assert.deepEqual(value, before.run[key as keyof typeof before.run], `Retained ${key}`); + else { + const snapshot = value as Record; + for (const [name, selected] of Object.entries(snapshot)) { + if (name !== "paperclipIssue") assert.deepEqual(selected, before.run.contextSnapshot?.[name] ?? null, `Retained context ${name}`); + else for (const [nested, item] of Object.entries(selected as Record)) + assert.deepEqual(item, (before.run.contextSnapshot?.paperclipIssue as Record)?.[nested] ?? null, `Retained nested ${nested}`); + } + } + } + const afterQuery = findRunQuery(afterQueries), afterBytes = await dataRowBytes(afterQuery); + assert.ok(afterBytes < baselineBytes * (readScope === "project_execution" ? 0.5 : 0.05), + "Fixture acceptance: remove at least 95% of authority bytes or 50% while preserving complete execution input"); + assert.equal(afterQueries.length, beforeQueries.length, "No queries added or removed from identity reconciliation"); + const samples = { baseline: [] as number[], treatment: [] as number[] }; + for (let n = 0; n < 9; n++) { + for (const version of n % 2 ? ["treatment", "baseline"] as const : ["baseline", "treatment"] as const) { + const start = performance.now(); + if (version === "baseline") await baseline.captureRunIdentity(db, f); + else await captureRunIdentity(db, f, { readScope }); + if (n >= 2) samples[version].push(performance.now() - start); + } + } + const stats = (values: number[]) => { + const sorted = [...values].sort((a, b) => a - b); + return { samplesMs: values, medianMs: sorted[Math.floor(sorted.length / 2)], minMs: sorted[0], maxMs: sorted.at(-1) }; + }; + results.push({ readScope, baselineBytes, treatmentBytes: afterBytes, reductionPercent: 100 * (1 - afterBytes / baselineBytes), + retainedColumnsAndContextEqual: true, identityContextEqual: true, queryCount: afterQueries.length, + generatedSql: { baseline: beforeQuery, treatment: afterQuery }, + timings: { scope: "complete captureRunIdentity service transaction", warmups: 2, samples: 7, order: "alternating", + baseline: stats(samples.baseline), treatment: stats(samples.treatment) }, + plans: { baseline: await plan(beforeQuery), treatment: await plan(afterQuery) } }); + } + assert.deepEqual((await captureRunIdentity(db, f)).run, before.run, "Complete stored run unchanged"); + console.log(JSON.stringify({ baselineRevision, treatmentRevision: git(["rev-parse", "HEAD"]).trim(), + treatmentDiff: git(["diff", "HEAD", "--", "server/src"]), unchangedHelpers, + postgresVersion: (await db.$client.unsafe("SELECT version()"))[0]!.version, + settings: await db.$client.unsafe("SELECT name, setting FROM pg_settings WHERE name IN ('block_size','shared_buffers','work_mem','jit') ORDER BY name"), + fixture: { runs: 1, synthetic: true, contextBytes: Buffer.byteLength(JSON.stringify(f.payloads.contextSnapshot)), + profileBytes: Buffer.byteLength(JSON.stringify(f.payloads.runnerProfileJson)) }, + measurement: "PostgreSQL DataRow messages from raw text-format buffers; excludes metadata, TLS and TCP", results, + }, null, 2)); +} finally { + try { + await db?.$client.end({ timeout: 0 }); + await temporary?.cleanup(); + if (baselineDir) await fs.rm(baselineDir, { recursive: true, force: true }); + } finally { clearInterval(keepAlive); } +} diff --git a/server/src/__tests__/company-skills-routes.test.ts b/server/src/__tests__/company-skills-routes.test.ts index f40bfa0f8ce..11fe51213a7 100644 --- a/server/src/__tests__/company-skills-routes.test.ts +++ b/server/src/__tests__/company-skills-routes.test.ts @@ -1264,7 +1264,7 @@ describe("company skill mutation permissions", () => { const response = await request(createApp(agent)).post("/api/companies/company-1/skills/import") .send({ source: "https://github.com/acme/public-skills" }); expect(response.status, JSON.stringify(response.body)).toBe(201); - expect(mockCaptureRunIdentity).toHaveBeenCalledWith(expect.anything(), { companyId: "company-1", agentId: agent.agentId, runId: "run-1" }); + expect(mockCaptureRunIdentity).toHaveBeenCalledWith(expect.anything(), { companyId: "company-1", agentId: agent.agentId, runId: "run-1" }, { readScope: "identity" }); expect(mockSkillSourceService.importFromUrl).toHaveBeenCalledWith("company-1", expect.anything(), expect.objectContaining({ setup: { userId: "validated-owner", agentId: agent.agentId, localTrusted: false } })); }); diff --git a/server/src/__tests__/helpers/run-identity-projection-fixture.ts b/server/src/__tests__/helpers/run-identity-projection-fixture.ts new file mode 100644 index 00000000000..5072e37060f --- /dev/null +++ b/server/src/__tests__/helpers/run-identity-projection-fixture.ts @@ -0,0 +1,41 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { agents, companies, heartbeatRuns, issueComments, issues, type Db } from "@paperclipai/db"; +import { initializeRunIdentity } from "../../services/run-identity.js"; + +export async function seedIdentityProjection(db: Db) { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(), messageId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Synthetic identity", issuePrefix: companyId }); + await db.insert(agents).values({ id: agentId, companyId, name: "Identity reader", adapterType: "process" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Identity task", assigneeAgentId: agentId, + conversationAgentId: agentId, conversationUserId: "operator", conversationState: "active", conversationSessionGeneration: 3, workMode: "standard" }); + const payloads = { contextSnapshot: { issueId, conversationSessionGeneration: 3, paperclipSkillTest: false, + projectId: randomUUID(), routineId: randomUUID(), paperclipIssue: { id: issueId, projectId: randomUUID(), + responsibleUserId: "nested-user", document: randomBytes(8_192).toString("base64") }, + savedInput: randomBytes(96 * 1_024).toString("base64") }, + runnerProfileJson: { nativeExecutionInput: { savedInput: randomBytes(48 * 1_024).toString("base64") }, + unrelatedProfileDocument: randomBytes(8_192).toString("base64") }, + resultJson: { retained: randomBytes(4_096).toString("base64") }, stdoutExcerpt: "retained stdout", stderrExcerpt: "retained stderr" }; + await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", nativeIssueId: issueId, + runtimeMode: "native", invocationSource: "automation", ...payloads }); + await db.insert(issueComments).values({ id: messageId, companyId, issueId, authorUserId: "next-user", body: "New request" }); + const context = await initializeRunIdentity(db, { companyId, runId, issueId, responsibleUserId: "operator", cause: "instruction" }); + return { companyId, agentId, issueId, runId, messageId, context, payloads }; +} + +export type IdentityQuery = { sql: string; params: unknown[] }; +export function captureIdentityQueries(db: Db, queries: IdentityQuery[]): Db { + return new Proxy(db, { get(target, key) { + if (key === "transaction") return (action: (tx: Db) => Promise) => + target.transaction(tx => action(captureIdentityQueries(tx as unknown as Db, queries))); + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const selection = from(...args), execute = selection.execute.bind(selection); + selection.execute = async () => { queries.push(selection.toSQL()); return execute(); }; + return selection; + }) as typeof builder.from; + return builder; + }; + }}); +} diff --git a/server/src/__tests__/project-skill-setup-identity.test.ts b/server/src/__tests__/project-skill-setup-identity.test.ts index 844c4f7df71..d08cd9ec867 100644 --- a/server/src/__tests__/project-skill-setup-identity.test.ts +++ b/server/src/__tests__/project-skill-setup-identity.test.ts @@ -13,7 +13,7 @@ it('keeps responsibility without searching personal GitHub grants when the run h it('pins only the connection and grant already authorized for the active run', async () => { capture.mockResolvedValue({ run: { responsibleUserId: 'person' }, context: { github: { status: 'available', connectionId: 'selected', grantId: 'grant' } } }); expect(await projectSkillSetupIdentity(db, 'company', actor)).toMatchObject({ refreshUserId: 'person', connectionId: 'selected', refreshGrantId: 'grant' }); - expect(capture).toHaveBeenCalledWith(db, { companyId: 'company', agentId: 'agent', runId: 'run' }); + expect(capture).toHaveBeenCalledWith(db, { companyId: 'company', agentId: 'agent', runId: 'run' }, { readScope: 'identity' }); }); it('does not reuse an unavailable run credential', async () => { capture.mockResolvedValue({ run: { responsibleUserId: 'person' }, context: { github: { status: 'unavailable', connectionId: 'old', grantId: 'old' } } }); diff --git a/server/src/__tests__/run-identity-projections.test.ts b/server/src/__tests__/run-identity-projections.test.ts new file mode 100644 index 00000000000..1e7132029a2 --- /dev/null +++ b/server/src/__tests__/run-identity-projections.test.ts @@ -0,0 +1,116 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { applyPendingMigrations, createDb, heartbeatRuns, issues, type Db } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { captureIdentityQueries, seedIdentityProjection, type IdentityQuery } from "./helpers/run-identity-projection-fixture.js"; +import { captureRunIdentity } from "../services/run-identity.js"; +import { projectToolContext } from "../services/project-tool-context.js"; +import { boundRunIssueId } from "../services/run-task-binding.js"; + +const externalDatabaseUrl = process.env.PAPERCLIP_TEST_DATABASE_URL; +const support = externalDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); +const scopes = ["identity", "task_authorization", "token_broker"] as const; +(support.supported ? describe : describe.skip)("operation identity read projections", () => { + let temporary: Awaited> | undefined; + let db: Db; + beforeAll(async () => { + if (externalDatabaseUrl) { + await applyPendingMigrations(externalDatabaseUrl); + db = createDb(externalDatabaseUrl); + } else { + temporary = await startEmbeddedPostgresTestDatabase("identity-projection-"); + db = createDb(temporary.connectionString); + } + }, 90_000); + afterAll(async () => { await db?.$client.end({ timeout: 0 }); await temporary?.cleanup(); }); + + it.each(scopes)("bounds %s SQL results and preserves the stored execution", async readScope => { + const f = await seedIdentityProjection(db), queries: IdentityQuery[] = []; + const full = await captureRunIdentity(db, f); + const narrow = await captureRunIdentity(captureIdentityQueries(db, queries), f, { readScope }); + expect(narrow.context).toEqual(full.context); + expect(narrow.run).toMatchObject({ id: f.runId, companyId: f.companyId, agentId: f.agentId, + status: "running", responsibleUserId: "operator", activeIdentityContextId: full.run.activeIdentityContextId }); + expect(narrow.run).not.toHaveProperty("runnerProfileJson"); + expect(narrow.run).not.toHaveProperty("resultJson"); + const query = queries.find(query => query.sql.includes('from "heartbeat_runs"') && query.sql.includes("for no key update"))!; + const rows = await db.$client.unsafe(query.sql, query.params as never[]).raw(); + expect(rows).toHaveLength(1); + expect(rows[0]!.reduce((bytes, value) => bytes + (value?.byteLength ?? 0), 0)).toBeLessThan(2_048); + expect((await captureRunIdentity(db, f)).run).toEqual(full.run); + }); + + it("preserves task binding types and legacy non-object contexts", async () => { + const f = await seedIdentityProjection(db); + for (const snapshot of [null, false, 42, "text", [], ["value"], {}, ...[null, false, 42, " 3 ", [], {}, { nested: true }] + .map(value => ({ issueId: f.issueId, conversationSessionGeneration: value, paperclipSkillTest: value }))]) { + await db.$client.unsafe("UPDATE heartbeat_runs SET context_snapshot = $1::jsonb WHERE id = $2", [JSON.stringify(snapshot), f.runId]); + const full = await captureRunIdentity(db, f), narrow = await captureRunIdentity(db, f, { readScope: "task_authorization" }); + expect(boundRunIssueId(narrow.run)).toBe(boundRunIssueId(full.run)); + expect(Number(narrow.run.contextSnapshot?.conversationSessionGeneration ?? 0)).toBe(Number(full.run.contextSnapshot?.conversationSessionGeneration ?? 0)); + expect(Boolean(narrow.run.contextSnapshot?.paperclipSkillTest)).toBe(Boolean(full.run.contextSnapshot?.paperclipSkillTest)); + } + for (const issueId of [true, 123, [], {}, "malformed"]) { + await db.$client.unsafe("UPDATE heartbeat_runs SET context_snapshot = $1::jsonb WHERE id = $2", [JSON.stringify({ issueId }), f.runId]); + await expect(captureRunIdentity(db, f)).rejects.toThrow("task identity is invalid"); + await expect(captureRunIdentity(db, f, { readScope: "task_authorization" })).rejects.toThrow("task identity is invalid"); + } + }); + + it("retains broker fields and nested attribution without document payloads", async () => { + const f = await seedIdentityProjection(db); + for (const value of [null, true, 42, " padded ", [], {}, { retained: true }]) { + const snapshot = { issueId: f.issueId, projectId: value, routineId: value, responsibleUserId: value, + responsible_user_id: value, paperclipIssue: { id: value, projectId: value, responsibleUserId: value, + responsible_user_id: value, savedDocument: f.payloads.contextSnapshot.savedInput } }; + await db.update(heartbeatRuns).set({ contextSnapshot: snapshot }).where(eq(heartbeatRuns.id, f.runId)); + const narrow = await captureRunIdentity(db, f, { readScope: "token_broker" }); + expect(narrow.run.invocationSource).toBe("automation"); + expect(narrow.run.contextSnapshot).toEqual({ ...snapshot, paperclipIssue: { id: value, + projectId: value, responsibleUserId: value, responsible_user_id: value } }); + } + for (const paperclipIssue of [null, true, 42, "legacy", []]) { + await db.update(heartbeatRuns).set({ contextSnapshot: { paperclipIssue } }).where(eq(heartbeatRuns.id, f.runId)); + expect((await captureRunIdentity(db, f, { readScope: "token_broker" })).run.contextSnapshot?.paperclipIssue).toBeNull(); + } + }); + + it.each(scopes.flatMap(readScope => (["company", "agent", "run", "finished"] as const).map(fault => ({ readScope, fault }))))( + "denies $fault mismatches for $readScope", async ({ readScope, fault }) => { + const f = await seedIdentityProjection(db); + if (fault === "finished") await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, f.runId)); + await expect(captureRunIdentity(db, { ...f, ...(fault === "company" ? { companyId: randomUUID() } : + fault === "agent" ? { agentId: randomUUID() } : fault === "run" ? { runId: randomUUID() } : {}) }, { readScope })).rejects.toThrow("active run"); + }, + ); + + it("preserves every saved native input shape without unrelated profile fields", async () => { + const f = await seedIdentityProjection(db); + for (const nativeExecutionInput of [null, true, 42, "legacy", [], {}, { opaque: { retained: true } }]) { + await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput, unrelated: "drop" } }).where(eq(heartbeatRuns.id, f.runId)); + expect((await captureRunIdentity(db, f, { readScope: "project_execution" })).run.runnerProfileJson).toEqual({ nativeExecutionInput }); + } + await db.update(heartbeatRuns).set({ runnerProfileJson: { unrelated: "drop" } }).where(eq(heartbeatRuns.id, f.runId)); + expect((await captureRunIdentity(db, f, { readScope: "project_execution" })).run.runnerProfileJson).toEqual({}); + for (const profile of [null, true, 42, "legacy", []]) { + await db.$client.unsafe("UPDATE heartbeat_runs SET runner_profile_json = $1::jsonb WHERE id = $2", [JSON.stringify(profile), f.runId]); + expect((await captureRunIdentity(db, f, { readScope: "project_execution" })).run.runnerProfileJson).toBeNull(); + } + }); + + it("keeps the complete execution input for the project admission consumer", async () => { + const f = await seedIdentityProjection(db); + const actor = { type: "agent" as const, source: "agent_jwt" as const, companyId: f.companyId, agentId: f.agentId, runId: f.runId }; + const narrow = await projectToolContext(db, actor); + expect(narrow.run).not.toHaveProperty("runnerProfileJson"); + const full = await projectToolContext(db, actor, true, "Project", { includeExecutionInput: true }); + expect(full.run.runnerProfileJson).toEqual({ nativeExecutionInput: f.payloads.runnerProfileJson.nativeExecutionInput }); + expect(full.run.contextSnapshot).toEqual(narrow.run.contextSnapshot); + expect(full.run).not.toHaveProperty("resultJson"); + expect(full.run.contextSnapshot).not.toHaveProperty("savedInput"); + await db.update(issues).set({ conversationSessionGeneration: 4 }).where(eq(issues.id, f.issueId)); + await expect(projectToolContext(db, actor)).rejects.toThrow("session has changed"); + await expect(projectToolContext(db, actor, true, "Project", { includeExecutionInput: true })).rejects.toThrow("session has changed"); + }); +}); diff --git a/server/src/__tests__/run-identity.test.ts b/server/src/__tests__/run-identity.test.ts index 069139a8123..1cc8ed20f7a 100644 --- a/server/src/__tests__/run-identity.test.ts +++ b/server/src/__tests__/run-identity.test.ts @@ -1,19 +1,23 @@ import { randomUUID } from "node:crypto"; import { eq, sql } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { agentWakeupRequests, agents, companies, createDb, heartbeatRuns, heartbeatRunEvents, issueComments, issueThreadInteractions, issues, secretAccessEvents } from "@paperclipai/db"; +import { agentWakeupRequests, agents, companies, applyPendingMigrations, createDb, closeRegisteredClients, heartbeatRuns, heartbeatRunEvents, issueComments, issueThreadInteractions, issues, secretAccessEvents } from "@paperclipai/db"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; import { acceptSteeredIdentity, captureRunIdentity, initializeRunIdentity, listRunIdentityContexts, rejectSteeredIdentity, reserveSteeredIdentity } from "../services/run-identity.js"; -const support = await getEmbeddedPostgresTestSupport(); +const externalDatabaseUrl = process.env.PAPERCLIP_TEST_DATABASE_URL; +const support = externalDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); (support.supported ? describe : describe.skip)("durable execution identity", () => { let database: Awaited>; let db: ReturnType; beforeAll(async () => { - database = await startEmbeddedPostgresTestDatabase("paperclip-run-identity-"); - db = createDb(database.connectionString); + if (externalDatabaseUrl) { await applyPendingMigrations(externalDatabaseUrl); db = createDb(externalDatabaseUrl); } + else { + database = await startEmbeddedPostgresTestDatabase("paperclip-run-identity-"); + db = createDb(database.connectionString); + } }, 30_000); - afterAll(async () => { await database?.cleanup(); }, 60_000); + afterAll(async () => { if (externalDatabaseUrl) await closeRegisteredClients(externalDatabaseUrl); await database?.cleanup(); }, 60_000); async function seed() { const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(); @@ -123,7 +127,7 @@ const support = await getEmbeddedPostgresTestSupport(); }, ); - it.each([undefined, "github_credentials", "request_authentication"] as const)("holds acquisition during uncertain steering and never rewinds on replay with %s", async (readScope) => { + it.each([undefined, "github_credentials", "request_authentication", "identity", "task_authorization", "token_broker", "project_execution"] as const)("holds acquisition during uncertain steering and never rewinds on replay with %s", async (readScope) => { const options = readScope ? { readScope } : undefined; const input = await seed(); await initializeRunIdentity(db, { ...input, messageIds: [input.messageIds[0]], responsibleUserId: "A", cause: "instruction" }); @@ -176,7 +180,7 @@ const support = await getEmbeddedPostgresTestSupport(); expect(captured.run.responsibleUserId).toBeNull(); expect(captured.context?.parentContextId).toBe(origin.id); }); - it.each([undefined, "github_credentials", "request_authentication"] as const)("recovers an uncertain native acknowledgement with %s", async (readScope) => { + it.each([undefined, "github_credentials", "request_authentication", "identity", "task_authorization", "token_broker", "project_execution"] as const)("recovers an uncertain native acknowledgement with %s", async (readScope) => { const options = readScope ? { readScope } : undefined; const input = await seed(); await initializeRunIdentity(db, { ...input, messageIds: [], responsibleUserId: "A", cause: "instruction" }); @@ -260,9 +264,9 @@ const support = await getEmbeddedPostgresTestSupport(); await expect(initialization).resolves.toMatchObject({ responsibleUserId: "A" }); }); - it.each(["initialize", "capture"] as const)( - "can %s identity while an audit append holds foreign-key locks", - async (operation) => { + it.each((["initialize", "capture"] as const).flatMap(operation => [false, true].map(withQuery => ({ operation, withQuery }))))( + "can $operation identity while an audit append holds foreign-key locks (query: $withQuery)", + async ({ operation, withQuery }) => { const input = await seed(); if (operation === "capture") { await initializeRunIdentity(db, { ...input, messageIds: [], responsibleUserId: "A", cause: "instruction" }); @@ -270,11 +274,22 @@ const support = await getEmbeddedPostgresTestSupport(); // A real append holds KEY SHARE on both parent rows until it commits. // Bound the other connection's wait so a conflicting lock fails this // regression instead of leaving both transactions waiting for each other. - const identityDb = createDb(`${database.connectionString}?options=-c%20lock_timeout%3D1000`, { + const identityUrl = new URL(externalDatabaseUrl ?? database.connectionString); + if (withQuery) { + identityUrl.searchParams.set("application_name", "identity-query-test"); + identityUrl.searchParams.set("options", [identityUrl.searchParams.get("options"), "-c statement_timeout=5000"].filter(Boolean).join(" ")); + } + identityUrl.searchParams.set("options", [identityUrl.searchParams.get("options"), "-c lock_timeout=1000"].filter(Boolean).join(" ")); + const identityDb = createDb(identityUrl.toString(), { maxConnections: 1, }); const [settings] = await identityDb.execute(sql`show lock_timeout`); expect(settings?.lock_timeout).toBe("1s"); + if (withQuery) { + expect(identityUrl.searchParams.get("application_name")).toBe("identity-query-test"); + const [timeouts] = await identityDb.execute(sql`show statement_timeout`); + expect(timeouts?.statement_timeout).toBe("5s"); + } await db.transaction(async (audit) => { await audit.insert(secretAccessEvents).values({ companyId: input.companyId, diff --git a/server/src/routes/projects.ts b/server/src/routes/projects.ts index c6479982335..272051bf521 100644 --- a/server/src/routes/projects.ts +++ b/server/src/routes/projects.ts @@ -423,7 +423,7 @@ export function projectRoutes(db: Db) { // The receipt lock can wait too. Keep current authority behind every // admission wait and ahead of both receipt replay and project creation. await withExternalExecutionAdmission(tx, actorCompanyId, agentId, runId, async () => { - const current = await projectToolContext(tx as unknown as Db, museActor, true); + const current = await projectToolContext(tx as unknown as Db, museActor, true, "Project", { includeExecutionInput: true }); try { const execution = parseNativeExecutionInput(current.run.runnerProfileJson?.nativeExecutionInput); const broker = museExternalAgents(db); diff --git a/server/src/services/connection-intents.ts b/server/src/services/connection-intents.ts index 1788c0ebd60..f0d143861e5 100644 --- a/server/src/services/connection-intents.ts +++ b/server/src/services/connection-intents.ts @@ -214,7 +214,7 @@ export function connectionIntentService(db: Db) { throw forbidden("Runtime tool token is no longer active"); } if (run.activeIdentityContextId && !failedAuthRun) { - const current = await captureRunIdentity(db, { companyId: run.companyId, agentId: run.agentId, runId: run.id }); + const current = await captureRunIdentity(db, { companyId: run.companyId, agentId: run.agentId, runId: run.id }, { readScope: "identity" }); run = { ...run, responsibleUserId: current.run.responsibleUserId }; } if (!run.responsibleUserId) throw forbidden("This task needs a responsible user to connect a service"); diff --git a/server/src/services/connection-management.ts b/server/src/services/connection-management.ts index fcc532476be..0c1740f04ba 100644 --- a/server/src/services/connection-management.ts +++ b/server/src/services/connection-management.ts @@ -3,7 +3,7 @@ import { isUuidLike } from "@paperclipai/shared"; import { agents, agentApiKeys, heartbeatRuns, runIdentityContexts, issues, projects, toolApplications, toolCatalogEntries, toolConnections, toolConnectionInstalls, toolProfiles, toolProfileEntries, toolProfileBindings, toolMcpGateways, aiConnectionPools, connectionGrants, routines, type Db } from "@paperclipai/db"; import { forbidden } from "../errors.js"; import { authorizationService, canActorReadIssuePrivacy, canActorReadProjectPrivacy, type AuthorizationActor, type AuthorizationDecision } from "./authorization.js"; -import { captureRunIdentity } from "./run-identity.js"; +import { captureRunIdentity, runIdentityTaskFields, type RunIdentityCapture } from "./run-identity.js"; import type { LogActivityInput } from "./activity-log.js"; import type { ConnectionManagementAction, ConnectionManagementResource } from "./connection-management-policy.js"; @@ -17,7 +17,7 @@ export type ConnectionManagementContext = { reauthorize: (continuation?: { afterHumanAction: true }) => Promise; }; -type CapturedConnectionRun = Omit>, "context"> & { context: Awaited>["context"] | null }; +type CapturedConnectionRun = RunIdentityCapture<"task_authorization">; const connectionReadRuns = new WeakMap(); export function responsibleConnectionUser(actor: AuthorizationActor): string | null { @@ -51,12 +51,12 @@ export function connectionManagementService(db: Db) { const reusable = options.capabilityProbe && !options.afterHumanAction && options.readContext?.actor === actor && options.readContext.resource.companyId === resource.companyId ? connectionReadRuns.get(options.readContext) : undefined; const captured = reusable ?? (options.afterHumanAction ? await (async () => { - const [run] = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, actor.runId!), eq(heartbeatRuns.agentId, actor.agentId!), eq(heartbeatRuns.companyId, resource.companyId))); + const [run] = await db.select(runIdentityTaskFields).from(heartbeatRuns).where(and(eq(heartbeatRuns.id, actor.runId!), eq(heartbeatRuns.agentId, actor.agentId!), eq(heartbeatRuns.companyId, resource.companyId))); if (!run || !["running", "succeeded"].includes(run.status)) throw forbidden("The originating run cannot continue this authentication"); const [pending] = await db.select().from(runIdentityContexts).where(and(eq(runIdentityContexts.runId, run.id), eq(runIdentityContexts.status, "pending"))); if (pending) throw forbidden("Run identity is being reconciled"); return { run, context: null }; - })() : await captureRunIdentity(db, { companyId: resource.companyId, agentId: actor.agentId, runId: actor.runId })); + })() : await captureRunIdentity(db, { companyId: resource.companyId, agentId: actor.agentId, runId: actor.runId }, { readScope: "task_authorization" })); capturedRun = captured; const { run, context } = captured; if ((context?.responsibleUserId ?? run.responsibleUserId) !== responsibleUserId) throw forbidden("Run responsible-user authority has changed"); diff --git a/server/src/services/connectors/slack-authority.ts b/server/src/services/connectors/slack-authority.ts index 06da6455d35..ee19440f45e 100644 --- a/server/src/services/connectors/slack-authority.ts +++ b/server/src/services/connectors/slack-authority.ts @@ -8,7 +8,7 @@ import { type chatConversations, } from "@paperclipai/db"; import { and, eq, inArray } from "drizzle-orm"; -import { captureRunIdentity } from "../run-identity.js"; +import { captureRunIdentity, runIdentityTaskFields } from "../run-identity.js"; import { forbidden } from "../../errors.js"; import { boundRunIssueId } from "../run-task-binding.js"; import { chatRunSourceMessageId } from "../chat-channels/run-origin.js"; @@ -110,7 +110,7 @@ export async function slackRunOrigin(db: Db, binding: SlackTaskBinding) { if (!approved || !binding.identityContextId) throw forbidden("Slack approval is not executing for this task"); const [run] = await db - .select() + .select(runIdentityTaskFields) .from(heartbeatRuns) .where( and( @@ -141,7 +141,7 @@ export async function slackRunOrigin(db: Db, binding: SlackTaskBinding) { ); captured = { run, context }; } else { - captured = await captureRunIdentity(db, binding); + captured = await captureRunIdentity(db, binding, { readScope: "task_authorization" }); if ( binding.identityContextId && binding.identityContextId !== captured.context?.id diff --git a/server/src/services/execution-workspace-repositories.ts b/server/src/services/execution-workspace-repositories.ts index fae172296ff..4d4cfe16b86 100644 --- a/server/src/services/execution-workspace-repositories.ts +++ b/server/src/services/execution-workspace-repositories.ts @@ -134,7 +134,7 @@ export function executionWorkspaceRepositoryService(db: Db) { let localTrusted = input.actor.source === "local_implicit"; if (input.actor.type === "agent") { if (input.actor.source !== "agent_jwt" || !input.actor.agentId || !input.actor.runId || input.actor.companyId !== input.companyId) throw forbidden("Repository preparation requires an authenticated task run"); - const identity = await captureRunIdentity(db, { companyId: input.companyId, agentId: input.actor.agentId, runId: input.actor.runId }); + const identity = await captureRunIdentity(db, { companyId: input.companyId, agentId: input.actor.agentId, runId: input.actor.runId }, { readScope: "task_authorization" }); const runIssueId = identity.run.nativeIssueId ?? identity.run.contextSnapshot?.issueId; if (runIssueId !== input.issueId) throw forbidden("Repository preparation is scoped to the current task"); userId = identity.run.responsibleUserId; diff --git a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts index aa6863205fb..71f9e3ea02b 100644 --- a/server/src/services/native-runtime/paperclip-runner-tool-authority.ts +++ b/server/src/services/native-runtime/paperclip-runner-tool-authority.ts @@ -458,7 +458,7 @@ export class PaperclipRunnerToolAuthority { } if (RUNTIME_CONNECTION_TOOL_DEFINITIONS.some((tool) => tool.name === call.tool)) { await this.#boundContext(); - const { run } = await captureRunIdentity(this.db, this.binding); + const { run } = await captureRunIdentity(this.db, this.binding, { readScope: "identity" }); if (!run.responsibleUserId) throw forbidden("This task needs a responsible user before requesting a connection"); const claims = { sub: this.binding.agentId, company_id: this.binding.companyId, @@ -794,9 +794,9 @@ export class PaperclipRunnerToolAuthority { } case "report_progress": return this.#reportProgress(input); case "request_human_input": return this.#requestHumanInput(input, - (await captureRunIdentity(this.db, this.binding)).context?.id ?? null); + (await captureRunIdentity(this.db, this.binding, { readScope: "identity" })).context?.id ?? null); case "create_task": return this.#createTask(input, - (await captureRunIdentity(this.db, this.binding)).context?.id ?? null); + (await captureRunIdentity(this.db, this.binding, { readScope: "identity" })).context?.id ?? null); case "reassign_task": return this.#reassignTask(input); case "set_task_title": return this.#setTaskTitle(input); case "set_task_monitor": return this.#setTaskMonitor(input); diff --git a/server/src/services/project-skill-source-bindings.ts b/server/src/services/project-skill-source-bindings.ts index 29ff8bb1875..259e0dda705 100644 --- a/server/src/services/project-skill-source-bindings.ts +++ b/server/src/services/project-skill-source-bindings.ts @@ -12,7 +12,7 @@ export async function projectSkillSetupIdentity(db: Db, companyId: string, actor let connectionId: string | null = null, refreshGrantId: string | null = null; if (actor?.type === 'agent' && actor.source === 'agent_jwt') { if (!actor.runId || !actor.agentId || actor.companyId !== companyId) throw forbidden('Project skill setup requires an authenticated agent run.'); - const identity = await captureRunIdentity(db, { companyId, agentId: actor.agentId, runId: actor.runId }); + const identity = await captureRunIdentity(db, { companyId, agentId: actor.agentId, runId: actor.runId }, { readScope: 'identity' }); userId = identity.run.responsibleUserId; // Only reuse the connection already authorized by managed GitHub delivery // for this active run. Responsibility alone cannot discover another grant. diff --git a/server/src/services/project-tool-context.ts b/server/src/services/project-tool-context.ts index a0cc9468351..89be328b052 100644 --- a/server/src/services/project-tool-context.ts +++ b/server/src/services/project-tool-context.ts @@ -2,16 +2,21 @@ import type { Request } from "express"; import { and, eq } from "drizzle-orm"; import { issues, type Db } from "@paperclipai/db"; import { forbidden } from "../errors.js"; -import { captureRunIdentity } from "./run-identity.js"; +import { captureRunIdentity, type RunIdentityCapture } from "./run-identity.js"; +type ProjectToolResult = { run: Run; issue: typeof issues.$inferSelect; userId: string | null; localTrusted: boolean }; /** Resolve authority from the authenticated run, never caller-supplied user/task IDs. */ -export async function projectToolContext(db: Db, actor: Request["actor"], write = false, resource = "Project") { +export function projectToolContext(db: Db, actor: Request["actor"], write?: boolean, resource?: string): Promise["run"]>>; +export function projectToolContext(db: Db, actor: Request["actor"], write: boolean, resource: string, options: { includeExecutionInput: true }): Promise["run"]>>; +export async function projectToolContext(db: Db, actor: Request["actor"], write = false, resource = "Project", options?: { includeExecutionInput: true }) { if (actor.type !== "agent" || actor.source !== "agent_jwt" || !actor.runId || !actor.agentId || !actor.companyId) { throw forbidden(`${resource} tools require an authenticated agent run`); } // Acquire task/run locks before checking mode and session generation. A reset, // cancellation, or steering update cannot race a committing project mutation. - const identity = await captureRunIdentity(db, { companyId: actor.companyId, agentId: actor.agentId, runId: actor.runId }); + const binding = { companyId: actor.companyId, agentId: actor.agentId, runId: actor.runId }; + const identity = options?.includeExecutionInput ? await captureRunIdentity(db, binding, { readScope: "project_execution" }) : + await captureRunIdentity(db, binding, { readScope: "task_authorization" }); const run = identity.run; const snapshot = run.contextSnapshot ?? {}; const issueId = run.nativeIssueId ?? (typeof snapshot.issueId === "string" ? snapshot.issueId : null); diff --git a/server/src/services/run-identity.ts b/server/src/services/run-identity.ts index 166b1ae8cac..f72cc974ca7 100644 --- a/server/src/services/run-identity.ts +++ b/server/src/services/run-identity.ts @@ -465,16 +465,71 @@ export async function acceptSteeredIdentity( if (accepted) await activate(executor, accepted); } -export async function captureRunIdentity( +const runIdentityFields = { + id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId, + status: heartbeatRuns.status, responsibleUserId: heartbeatRuns.responsibleUserId, + activeIdentityContextId: heartbeatRuns.activeIdentityContextId, +}; + +export const runIdentityTaskFields = { + ...runIdentityFields, nativeIssueId: heartbeatRuns.nativeIssueId, issueId: heartbeatRuns.issueId, + wakeupRequestId: heartbeatRuns.wakeupRequestId, + contextSnapshot: sql | null>`case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' + then jsonb_build_object('issueId', ${heartbeatRuns.contextSnapshot}->'issueId', + 'taskId', ${heartbeatRuns.contextSnapshot}->'taskId', + 'conversationSessionGeneration', ${heartbeatRuns.contextSnapshot}->'conversationSessionGeneration', + 'paperclipSkillTest', ${heartbeatRuns.contextSnapshot}->'paperclipSkillTest') else null end`, +}; + +export const runIdentityBrokerFields = { + ...runIdentityFields, invocationSource: heartbeatRuns.invocationSource, + contextSnapshot: sql | null>`case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' + then jsonb_build_object('issueId', ${heartbeatRuns.contextSnapshot}->'issueId', + 'projectId', ${heartbeatRuns.contextSnapshot}->'projectId', 'routineId', ${heartbeatRuns.contextSnapshot}->'routineId', + 'responsibleUserId', ${heartbeatRuns.contextSnapshot}->'responsibleUserId', + 'responsible_user_id', ${heartbeatRuns.contextSnapshot}->'responsible_user_id', + 'paperclipIssue', case when jsonb_typeof(${heartbeatRuns.contextSnapshot}->'paperclipIssue') = 'object' + then jsonb_build_object('id', ${heartbeatRuns.contextSnapshot}->'paperclipIssue'->'id', + 'projectId', ${heartbeatRuns.contextSnapshot}->'paperclipIssue'->'projectId', + 'responsibleUserId', ${heartbeatRuns.contextSnapshot}->'paperclipIssue'->'responsibleUserId', + 'responsible_user_id', ${heartbeatRuns.contextSnapshot}->'paperclipIssue'->'responsible_user_id') else null end) + else null end`, +}; + +const runIdentityProjectFields = { + ...runIdentityTaskFields, runtimeMode: heartbeatRuns.runtimeMode, + runnerProfileJson: sql | null>`case when jsonb_typeof(${heartbeatRuns.runnerProfileJson}) = 'object' + then case when ${heartbeatRuns.runnerProfileJson} ? 'nativeExecutionInput' + then jsonb_build_object('nativeExecutionInput', ${heartbeatRuns.runnerProfileJson}->'nativeExecutionInput') + else '{}'::jsonb end else null end`, +}; + +type FullIdentityRun = typeof heartbeatRuns.$inferSelect; +type IdentityRun = Pick; +type TaskIdentityRun = Pick; +type BrokerIdentityRun = Pick; +type ProjectIdentityRun = Pick; +export type RunIdentityReadScope = "github_credentials" | "request_authentication" | "identity" | "task_authorization" | "token_broker" | "project_execution"; +export type RunIdentityCapture = { + run: Scope extends "identity" ? IdentityRun : Scope extends "task_authorization" ? TaskIdentityRun : + Scope extends "token_broker" ? BrokerIdentityRun : Scope extends "project_execution" ? ProjectIdentityRun : FullIdentityRun; + context: RunIdentityContext | null; +}; + +export async function captureRunIdentity( db: Db, input: { companyId: string; runId: string; agentId: string }, - options?: { readScope: "github_credentials" | "request_authentication" }, -) { + options?: { readScope: Scope }, +): Promise> { // Lock acquisition serializes with steering delivery and its durable acknowledgement. return db.transaction(async (tx) => { await lockIdentityTask(tx, input.companyId, input.runId); const [run] = await tx - .select(options?.readScope === "github_credentials" || options?.readScope === "request_authentication" ? { + .select(options?.readScope === "identity" ? runIdentityFields : + options?.readScope === "task_authorization" ? runIdentityTaskFields : + options?.readScope === "token_broker" ? runIdentityBrokerFields : + options?.readScope === "project_execution" ? runIdentityProjectFields : + options?.readScope === "github_credentials" || options?.readScope === "request_authentication" ? { ...getTableColumns(heartbeatRuns), contextSnapshot: sql | null>`case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' then jsonb_build_object('issueId', ${heartbeatRuns.contextSnapshot}->'issueId', @@ -528,7 +583,7 @@ export async function captureRunIdentity( ), ) : []; - return { run, context: context ?? null }; + return { run, context: context ?? null } as RunIdentityCapture; }); } diff --git a/server/src/services/tool-access/token-broker/admission.ts b/server/src/services/tool-access/token-broker/admission.ts index 5b30a3fd915..b4a98042001 100644 --- a/server/src/services/tool-access/token-broker/admission.ts +++ b/server/src/services/tool-access/token-broker/admission.ts @@ -1,5 +1,5 @@ import type { DbTransaction } from "../types.js"; -import { captureRunIdentity } from "../../run-identity.js"; +import { captureRunIdentity, runIdentityBrokerFields } from "../../run-identity.js"; import { and, eq, gte, inArray, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { connectionTokenIssuances, companyMemberships, heartbeatRuns, toolConnections, toolProfileBindings, toolProfileEntries, toolProfiles } from "@paperclipai/db"; @@ -75,11 +75,11 @@ export function createTokenBrokerAdmission(db: Db, now: () => Date) { runId: string; }) { const [initialRun] = await db - .select() + .select(runIdentityBrokerFields) .from(heartbeatRuns) .where(eq(heartbeatRuns.id, input.runId)); const run = initialRun?.activeIdentityContextId - ? (await captureRunIdentity(db, input)).run + ? (await captureRunIdentity(db, input, { readScope: "token_broker" })).run : initialRun; if ( !run || diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index ff5e1028ffc..57763f8b8d5 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -2199,7 +2199,7 @@ export function createToolGatewayService( companyId: session.companyId, agentId: session.agentId, runId: session.runId, - }); + }, { readScope: "identity" }); return { ...session, identityContextId: captured.context?.id, diff --git a/server/src/services/voice/speko-agent-tools.ts b/server/src/services/voice/speko-agent-tools.ts index 6332329fe35..7f0ce74b78f 100644 --- a/server/src/services/voice/speko-agent-tools.ts +++ b/server/src/services/voice/speko-agent-tools.ts @@ -19,7 +19,7 @@ export function registerSpekoVoiceRuntime(db: Db, start: (binding: Binding, invo async function resolveAuthority(db: Db, session: SpekoTaskSession, endpointId: string) { if (!(await instanceSettingsService(db).getExperimental()).enableChatConnectors) throw forbidden("Voice connections are disabled"); if (!runtimes.has(db) || !session.agentId || !session.runId || !session.issueId) throw forbidden("Speko tools require an active task run"); - const { run, context } = await captureRunIdentity(db, { companyId: session.companyId, agentId: session.agentId, runId: session.runId }); + const { run, context } = await captureRunIdentity(db, { companyId: session.companyId, agentId: session.agentId, runId: session.runId }, { readScope: "task_authorization" }); if (boundRunIssueId(run) !== session.issueId || !run.responsibleUserId || session.identityContextId && session.identityContextId !== context?.id) throw forbidden("The accepted requester or task changed"); const [endpoint] = await db.select().from(chatEndpoints).where(and(eq(chatEndpoints.companyId, session.companyId), eq(chatEndpoints.id, endpointId), eq(chatEndpoints.provider, "speko"), eq(chatEndpoints.assignedAgentId, session.agentId), eq(chatEndpoints.status, "active"))); if (!endpoint) throw forbidden("This agent has no active Speko connection"); From 3d07e06be7ff24c04e8143eda1e893cf54349652 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:31:40 -0500 Subject: [PATCH 4/7] perf(chat): project reply lineage run context (#17932) 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. > - A run can continue a task that began in an external chat. > - The reply router follows durable lineage to find the authorized conversation. > - Each lineage hop reads the full run context, although it uses only nine keys. > - Wide prompts and workspace data make that read transfer far more data than the router needs. > - This pull request selects those keys inside PostgreSQL and preserves their exact JSON values. > - The benefit is less database transfer with the same reply destination and authorization checks. ## Linked Issues or Issue Description Refs: #17255, #17894. The first owns related chat review delivery. The second is an independent result-projection optimization. This PR has no dependency on another open PR. A public issue and PR search found no duplicate change. The roadmap does not list this query optimization as planned core work. **What existing behavior does this improve?** The server resolves the conversation that may receive a reply after one or more task continuations. **Current behavior** Each hop reads agent identity, responsible user identity, and the complete context snapshot. The snapshot can contain large prompts and workspace data that the router never reads. **Proposed behavior** Select only the nine context keys that this function consumes. Preserve missing keys, explicit JSON nulls, arrays, objects, and scalar values. Keep non-object contexts unchanged. Keep all durable authorization queries and the cycle-safe traversal. **Reason and benefit** A synthetic wide context needs 262,402 DataRow bytes before the change and 244 after it. A valid 24-continuation lineage needs 6,560,338 bytes before and 6,388 after it. The reduction occurs before PostgreSQL sends the result. **Breaking changes** None. The public API, stored context, reply bindings, tenant checks, and admission proofs retain their existing behavior. ## What Changed - Project an object context through `jsonb_each` and `jsonb_object_agg`. Retain only the nine consumed keys. Preserve all selected JSON values and key presence. - Keep the agent and responsible-user columns. Keep the company and run predicates. - Add 22 real PostgreSQL tests for routing, malformed JSON, strict tool-action receipt comparisons, tenant boundaries, 24 valid continuation hops, and an authorized cycle. - Add a synthetic benchmark that loads the pinned baseline service, captures its generated SQL, compares complete bindings and selected columns, and measures text-format PostgreSQL DataRow frames. - Run owned resource cleanup in nested `finally` blocks so fixture deletion or client close failures cannot skip cluster and scratch cleanup. Preserve the original benchmark failure alongside a cleanup failure. The complete consumer-key audit is: | Context keys | Consumer | | --- | --- | | `issueId`, `taskId` | Task identity fence, with the existing fallback order | | `wakeCommentIds`, `wakeCommentId`, `commentId` | Board reply and root comment provenance | | `source`, `sourceRunId`, `interactionId` | Durable continuation branches and tool-action receipt checks | | `endpointId` | Root destination fence | Missing `interactionId` stays absent. It does not become JSON null. This matters because the tool-action branch compares it strictly with the durable wake payload. The tests cover absent, null, string, number, and object values. They also remove the delivery receipt to prove that context alone cannot authorize a reply. ## Verification Baseline: `3cd3af5d75f200185ed4d9703a3145594a489b13`. Treatment: `3439ba7b714090d9f251816efec26622b3df223b`. PostgreSQL 17.11, Node 26.4.0. All data is synthetic. The benchmark holds imported helpers and fixtures identical and loads only the baseline `issues.ts` from history. It records generated SQL, parameters, plans, source SHA-256, and the initial worktree state before scratch creation. The committed final measurement reports a clean worktree and source SHA-256 `cd7e955179118fda12f6b2e981a17efff54137cbf241019785a3f8d16a7dcbb8`. Reproduce the benchmark: ```sh node --import ./server/node_modules/tsx/dist/loader.mjs scripts/benchmark-chat-reply-lineage.ts --baseline-ref=3cd3af5d75f200185ed4d9703a3145594a489b13 ``` The default creates disposable embedded PostgreSQL. `PAPERCLIP_CHAT_LINEAGE_BENCHMARK_DATABASE_URL` can name a dedicated external database that ends in `_test`. The harness applies migrations and removes its own fixture rows. It never uses an application database by default. Each wide run has 192 KiB of random bytes encoded as base64. This produces a 262,144-byte incompressible body. Two warmups precede seven timed samples. Baseline and treatment alternate order. Every scenario returns the same complete bindings. Every retained SQL column matches its baseline value, and the context matches the exact key projection. The acceptance check requires removal of every unrelated synthetic body byte. | Scenario | Baseline DataRow bytes | Changed DataRow bytes | Baseline SQL median ms (range) | Changed SQL median ms (range) | | --- | ---: | ---: | ---: | ---: | | small | 282 | 244 | 0.927 (0.900–1.455) | 1.027 (0.801–1.063) | | wide | 262,402 | 244 | 2.618 (2.440–4.831) | 1.490 (1.400–1.815) | | wide-24-continuations | 6,560,338 | 6,388 | 87.450 (80.103–130.197) | 43.103 (38.549–52.864) | These bytes are exact text-format DataRow frame sizes. They exclude row descriptions, command metadata, TLS, and TCP. Timings cover the captured lineage SQL, including all hops. They exclude the other authorization queries. The small control is neutral and timing ranges overlap on wider cases. An earlier loaded run had a small-control median of 1.15 ms before and 1.33 ms after. No deployed latency or billing improvement is claimed. The byte reduction is the primary result. Local checks: - `pnpm run preflight:workspace-links`: passed. - `pnpm exec vitest run server/src/services/chat-reply-lineage-context.test.ts`: 22 passed on the committed rebased head. - The existing `chat-interaction-continuation.test.ts` file: all 28 tests passed. These cover confirmation, verdict, connection, and invalid-authority paths. - Five selected cases in `chat-channels.integration.test.ts`: passed in a fresh dedicated database. They cover closed-choice question delivery and steering, Telegram confirmation, ambiguous close control, and both fresh-after-close authorization paths. - `pnpm -r typecheck` and `pnpm build`: passed again after the master rebase. - `node scripts/check-module-boundaries.mjs` and `git diff --check`: passed. - Cleanup repair at `3439ba7b714090d9f251816efec26622b3df223b`: all 22 focused PostgreSQL tests, the benchmark above, and server `tsc --noEmit` passed. Six controlled cleanup-failure cases confirmed later finalizers run; benchmark and cleanup errors remain visible together. The unchanged baseline failed the wide-result regression: 262,383 value bytes exceeded its 1 KiB bound. The treatment passes. Initial fixture setup needed a required conversation label and explicit foreign-key cleanup. The first full typecheck found a row-type mismatch in the new capture helper; that helper was corrected. The complete typecheck then passed. No production logic changed for those setup repairs. A prior assembled run reused the interaction test database. Its retained running fixtures caused a global milestone-count assertion to fail. Later reuse exposed retained bot registration and identity state. An attempted manual reset named a nonexistent table and did not complete. These failed attempts are not acceptance evidence. The final five-case assembled proof used a newly created and migrated database and passed every assertion. No existing assertion was changed. The full local `pnpm test:run` was not run. Focused tests used the coordinated disposable PostgreSQL server to avoid uncontrolled embedded-cluster concurrency on this host. The full final-head CI matrix passes on `3439ba7b714090d9f251816efec26622b3df223b`: 55 successful checks, one neutral check, and two optional Storybook skips. Greptile completed at 5/5 on that exact head, with zero unresolved findings. The existing interaction and assembled cases ran before the unrelated master rebase; the measured service source is unchanged. Focused tests, benchmark, full typecheck, and build passed on the rebased production-change head. The current cleanup-only head reran focused tests, benchmark, and server TypeScript validation; production service source is unchanged. ## Risks - Future lineage consumers must add any new context key to the SQL projection and the correctness oracle. - Selected values retain their complete JSON content. Non-object contexts pass through unchanged. Savings depend on unrelated object data being present. - PostgreSQL must still read the stored object to make the projection. The change reduces returned data, rather than removing all server-side JSON work. - Question delivery, tool action, connection, monitor, publication, company, and agent proofs retain their existing owners. No hop limit, cache, schema change, startup task, or deployment is added. - Benchmark usage and the result contract are documented here. No public command or API contract changes. ## Model Used OpenAI GPT-6 through Codex. The exact runtime model ID and context window are not exposed by this environment. Capabilities used: source analysis, code editing, shell tools, real PostgreSQL experiments, and automated tests. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- scripts/benchmark-chat-reply-lineage.ts | 110 +++++++++++++++++ .../__tests__/helpers/chat-reply-lineage.ts | 67 +++++++++++ .../chat-reply-lineage-context.test.ts | 111 ++++++++++++++++++ server/src/services/issues.ts | 8 +- 4 files changed, 295 insertions(+), 1 deletion(-) create mode 100644 scripts/benchmark-chat-reply-lineage.ts create mode 100644 server/src/__tests__/helpers/chat-reply-lineage.ts create mode 100644 server/src/services/chat-reply-lineage-context.test.ts diff --git a/scripts/benchmark-chat-reply-lineage.ts b/scripts/benchmark-chat-reply-lineage.ts new file mode 100644 index 00000000000..353b92de5be --- /dev/null +++ b/scripts/benchmark-chat-reply-lineage.ts @@ -0,0 +1,110 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import { promises as fs, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { applyPendingMigrations, createDb, startEmbeddedPostgresTestDatabase, type Db } from "../packages/db/src/index.js"; +import { resolveChatOriginPublicationBindings } from "../server/src/services/issues.js"; +import { captureLineageReads, chatReplyLineageFixture, cleanupChatReplyLineageFixture, expectedLineageContext, type LineageQuery, type LineageResolver } from "../server/src/__tests__/helpers/chat-reply-lineage.js"; +import { resolveExternalTestDatabaseUrl } from "../server/src/__tests__/helpers/external-test-database.js"; + +const repoRoot = fileURLToPath(new URL("../", import.meta.url)); +const ref = process.argv.find(arg => arg.startsWith("--baseline-ref="))?.slice(15); +assert.ok(ref, "Pass a pinned pre-fix --baseline-ref"); +const git = (args: string[]) => execFileSync("git", args, { cwd: repoRoot, encoding: "utf8" }).trim(); +const sourcePath = "server/src/services/issues.ts"; +const baselineRevision = git(["rev-parse", `${ref}^{commit}`]), treatmentRevision = git(["rev-parse", "HEAD"]); +const uncommittedChanges = git(["status", "--porcelain"]), treatmentDiff = git(["diff", "HEAD", "--", sourcePath]); +const sourceHash = () => createHash("sha256").update(readFileSync(path.join(repoRoot, sourcePath))).digest("hex"); +const treatmentSourceSha256 = sourceHash(); +const keepAlive = setInterval(() => {}, 1000); +let db: Db | undefined, temporary: Awaited> | undefined, baselineDirectory: string | undefined; +const companyIds: string[] = []; +let benchmarkFailure: { error: unknown } | undefined; +try { + const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_CHAT_LINEAGE_BENCHMARK_DATABASE_URL"); + if (externalUrl) await applyPendingMigrations(externalUrl); + else temporary = await startEmbeddedPostgresTestDatabase("chat-lineage-benchmark-"); + db = createDb(externalUrl ?? temporary!.connectionString); + baselineDirectory = await fs.mkdtemp(path.join(repoRoot, "server/scripts/.chat-lineage-baseline-")); + const original = pathToFileURL(path.join(repoRoot, sourcePath)); + const baselineSource = execFileSync("git", ["show", `${baselineRevision}:${sourcePath}`], { cwd: repoRoot, encoding: "utf8" }); + await fs.writeFile(path.join(baselineDirectory, "issues.ts"), baselineSource.replace(/(from\s+|import\()(["'])(\.{1,2}\/[^"']+)\2/g, + (_match, prefix: string, quote: string, specifier: string) => `${prefix}${quote}${fileURLToPath(new URL(specifier, original))}${quote}`)); + const baseline = (await import(pathToFileURL(path.join(baselineDirectory, "issues.ts")).href)).resolveChatOriginPublicationBindings as LineageResolver; + const measurements = []; + for (const scenario of [{ name: "small", bytes: 16, hops: 0 }, { name: "wide", bytes: 192 * 1024, hops: 0 }, { name: "wide-24-continuations", bytes: 192 * 1024, hops: 24 }]) { + const f = await chatReplyLineageFixture(db, scenario.bytes); companyIds.push(f.companyId); + let runId = f.root.id; + for (let hop = 0; hop < scenario.hops; hop++) runId = (await f.continueFrom(runId)).run.id; + await db.$client.unsafe("ANALYZE"); + async function capture(resolver: LineageResolver) { + const reads: LineageQuery[] = []; + const result = await resolver(captureLineageReads(db!, reads), f.companyId, f.issueId, runId); + assert.deepEqual(result, f.expected); + assert.equal(reads.length, scenario.hops + 1); + return { result, reads }; + } + const before = await capture(baseline), after = await capture(resolveChatOriginPublicationBindings); + assert.deepEqual(after.result, before.result); + for (let index = 0; index < before.reads.length; index++) { + const row = before.reads[index].rows[0]; + assert.deepEqual(after.reads[index].rows, [{ ...row, contextSnapshot: expectedLineageContext(row.contextSnapshot) }]); + } + const variants = [before, after], samples: number[][] = [[], []], bytes: number[] = [0, 0]; + for (let iteration = 0; iteration < 9; iteration++) { + for (const variant of iteration % 2 ? [1, 0] : [0, 1]) { + const started = performance.now(); let returned = 0; + for (const query of variants[variant].reads) { + const rows = await db.$client.unsafe(query.sql, query.params as never[]).raw(); + returned += rows.reduce((sum, row) => sum + 7 + row.reduce((n: number, value: Buffer | null) => n + 4 + (value?.length ?? 0), 0), 0); + } + if (iteration >= 2) samples[variant].push(performance.now() - started); + bytes[variant] = returned; + } + } + const minimumSaving = Buffer.byteLength(f.context.prompt) * (scenario.hops + 1); + assert.ok(bytes[0] - bytes[1] >= minimumSaving, "All unrelated synthetic body bytes must be removed before transfer"); + const plans = []; + for (const variant of variants) { + const query = variant.reads[0]; + const [plan] = await db.$client.unsafe(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query.sql}`, query.params as never[]); + plans.push(plan["QUERY PLAN"]); + } + const timing = (values: number[]) => { const sorted = [...values].sort((a, b) => a - b); return { medianMs: sorted[3], minMs: sorted[0], maxMs: sorted[6], samplesMs: values }; }; + measurements.push({ scenario, bodyBytesPerRun: Buffer.byteLength(f.context.prompt), completeBindingsEqual: true, selectedColumnsEqual: true, + baselineDataRowBytes: bytes[0], treatmentDataRowBytes: bytes[1], minimumSaving, baselineTiming: timing(samples[0]), treatmentTiming: timing(samples[1]), + baselineQueries: before.reads.map(({ rows: _rows, ...query }) => query), treatmentQueries: after.reads.map(({ rows: _rows, ...query }) => query), plans }); + } + assert.equal(sourceHash(), treatmentSourceSha256, "Measured service source changed during the benchmark"); + console.log(JSON.stringify({ baselineRevision, treatmentRevision, sourcePath, treatmentSourceSha256, uncommittedChanges, treatmentDiff, + byteBoundary: "Exact text-format PostgreSQL DataRow frames; excludes row descriptions, command metadata, TLS and TCP. Timings cover captured lineage SQL only, not the complete authorization service.", + dependencyScope: "Only the pinned baseline issues.ts is loaded from history; imported helpers and synthetic fixtures are held identical.", + postgres: await db.$client.unsafe("select version()"), settings: await db.$client.unsafe("select name,setting,unit from pg_settings where name in ('shared_buffers','work_mem','jit') order by name"), + node: process.version, measurements }, null, 2)); +} catch (error) { + benchmarkFailure = { error }; + throw error; +} finally { + try { + try { + if (db) for (const companyId of companyIds) await cleanupChatReplyLineageFixture(db, companyId); + } finally { + try { + await db?.$client.end({ timeout: 0 }); + } finally { + try { + await temporary?.cleanup(); + } finally { + try { + if (baselineDirectory) await fs.rm(baselineDirectory, { recursive: true, force: true }); + } finally { clearInterval(keepAlive); } + } + } + } + } catch (error) { + if (benchmarkFailure) throw new AggregateError([benchmarkFailure.error, error], "Benchmark and cleanup failed"); + throw error; + } +} diff --git a/server/src/__tests__/helpers/chat-reply-lineage.ts b/server/src/__tests__/helpers/chat-reply-lineage.ts new file mode 100644 index 00000000000..5a5b65baedc --- /dev/null +++ b/server/src/__tests__/helpers/chat-reply-lineage.ts @@ -0,0 +1,67 @@ +import { randomBytes, randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { agents, agentWakeupRequests, chatConversations, chatEndpoints, chatMessageLinks, companies, heartbeatRuns, issueComments, issues, issueThreadInteractions, toolApplications, toolConnections, toolActionRequests, toolActionDeliveries, toolInvocations, type Db } from "@paperclipai/db"; +import { resolveChatOriginPublicationBindings } from "../../services/issues.js"; + +export const lineageContextKeys = ["issueId", "taskId", "wakeCommentIds", "wakeCommentId", "commentId", "source", "sourceRunId", "interactionId", "endpointId"] as const; +export type LineageResolver = typeof resolveChatOriginPublicationBindings; +export type LineageQuery = { sql: string; params: unknown[]; rows: Array> }; + +export function captureLineageReads(db: Db, queries: LineageQuery[]): Db { + return new Proxy(db, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const query = from(...args), execute = query.execute.bind(query); + if (args[0] === heartbeatRuns) query.execute = async (...executeArgs: Parameters) => { + const statement = query.toSQL(); + const rows = await execute(...executeArgs); + if (fields[0] && Object.keys(fields[0]).join(",") === "agentId,responsibleUserId,contextSnapshot") queries.push({ ...statement, rows }); + return rows; + }; + return query; + }) as typeof builder.from; + return builder; + }; + } }); +} + +export function expectedLineageContext(value: unknown): unknown { + if (value === null || typeof value !== "object" || Array.isArray(value)) return value; + return Object.fromEntries(lineageContextKeys.filter(key => Object.hasOwn(value, key)).map(key => [key, (value as Record)[key]])); +} + +export async function chatReplyLineageFixture(db: Db, bytes = 192 * 1024) { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(); + await db.insert(companies).values({ id: companyId, name: "Synthetic reply lineage", issuePrefix: `L${companyId.replaceAll("-", "").slice(0, 7)}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Synthetic worker", adapterType: "paperclip_runner" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Synthetic external reply", status: "in_progress", assigneeAgentId: agentId }); + const [application] = await db.insert(toolApplications).values({ companyId, name: "Synthetic chat", applicationKey: randomUUID(), type: "chat" }).returning(); + const [connection] = await db.insert(toolConnections).values({ companyId, applicationId: application.id, name: "Synthetic chat", uid: randomUUID(), transport: "chat_sdk", connectionPurpose: "channel" }).returning(); + const [endpoint] = await db.insert(chatEndpoints).values({ companyId, connectionId: connection.id, assignedAgentId: agentId, provider: "slack", publicId: randomUUID(), status: "active" }).returning(); + const [conversation] = await db.insert(chatConversations).values({ companyId, endpointId: endpoint.id, issueId, externalConversationId: randomUUID(), externalThreadId: randomUUID(), externalLabel: "Synthetic conversation" }).returning(); + const [comment] = await db.insert(issueComments).values({ companyId, issueId, authorType: "user", authorUserId: "synthetic-requester", body: "Please continue" }).returning(); + await db.insert(chatMessageLinks).values({ companyId, endpointId: endpoint.id, conversationId: conversation.id, commentId: comment.id, providerMessageId: randomUUID(), direction: "inbound" }); + const context = { source: "chat:slack", issueId, endpointId: endpoint.id, wakeCommentIds: [comment.id], prompt: randomBytes(bytes).toString("base64") }; + const insertRun = async (snapshot: unknown = context, overrides: Partial = {}) => { + const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "succeeded", contextSnapshot: snapshot as never, ...overrides }).returning(); + return run; + }; + const root = await insertRun(); + async function continueFrom(sourceRunId: string) { + const [interaction] = await db.insert(issueThreadInteractions).values({ companyId, issueId, sourceRunId, kind: "request_confirmation", status: "accepted", payload: { version: 1 } as never }).returning(); + const run = await insertRun({ issueId, source: "issue.interaction.accept", sourceRunId, interactionId: interaction.id, prompt: context.prompt }); + const [wake] = await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "automation", reason: "issue_commented", status: "claimed", runId: run.id, idempotencyKey: `interaction:${interaction.id}:accepted` }).returning(); + return { run, interaction, wake }; + } + return { companyId, agentId, issueId, endpoint, conversation, comment, context, root, insertRun, continueFrom, + expected: [{ companyId, endpointId: endpoint.id, conversationId: conversation.id }] }; +} + +export async function cleanupChatReplyLineageFixture(db: Db, companyId: string) { + for (const table of [agentWakeupRequests, toolActionDeliveries, toolActionRequests, toolInvocations, issueThreadInteractions, chatMessageLinks, chatConversations, chatEndpoints, heartbeatRuns, issueComments, issues, toolConnections, toolApplications, agents]) { + await db.delete(table).where(eq(table.companyId, companyId)); + } + await db.delete(companies).where(eq(companies.id, companyId)); +} diff --git a/server/src/services/chat-reply-lineage-context.test.ts b/server/src/services/chat-reply-lineage-context.test.ts new file mode 100644 index 00000000000..41ad66d3f3e --- /dev/null +++ b/server/src/services/chat-reply-lineage-context.test.ts @@ -0,0 +1,111 @@ +import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { applyPendingMigrations, createDb, heartbeatRuns, agentWakeupRequests, toolInvocations, toolActionRequests, toolActionDeliveries } from "@paperclipai/db"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../__tests__/helpers/embedded-postgres.js"; +import { resolveExternalTestDatabaseUrl } from "../__tests__/helpers/external-test-database.js"; +import { captureLineageReads, chatReplyLineageFixture, cleanupChatReplyLineageFixture, expectedLineageContext, type LineageQuery } from "../__tests__/helpers/chat-reply-lineage.js"; +import { resolveChatOriginPublicationBindings } from "./issues.js"; + +const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_TEST_DATABASE_URL"); +const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); +describe.skipIf(!support.supported)("chat reply lineage context projection", () => { + let db: ReturnType; + let temporary: Awaited> | undefined; + const companyIds: string[] = []; + async function fixture(bytes?: number) { const f = await chatReplyLineageFixture(db, bytes); companyIds.push(f.companyId); return f; } + beforeAll(async () => { + if (externalUrl) await applyPendingMigrations(externalUrl); + else temporary = await startEmbeddedPostgresTestDatabase("chat-lineage-projection-"); + db = createDb(externalUrl ?? temporary!.connectionString); + }, 90_000); + afterAll(async () => { + try { + if (db) for (const companyId of companyIds) await cleanupChatReplyLineageFixture(db, companyId); + } finally { + try { await db?.$client.end({ timeout: 0 }); } + finally { await temporary?.cleanup(); } + } + }); + + it("projects the complete routing context before a wide body crosses PostgreSQL", async () => { + const f = await fixture(), reads: LineageQuery[] = []; + expect(await resolveChatOriginPublicationBindings(captureLineageReads(db, reads), f.companyId, f.issueId, f.root.id)).toEqual(f.expected); + expect(reads).toHaveLength(1); + const rows = await db.$client.unsafe(reads[0].sql, reads[0].params as never[]).raw(); + expect(rows.reduce((total, row) => total + row.reduce((n: number, value: Buffer | null) => n + (value?.length ?? 0), 0), 0)).toBeLessThan(1024); + expect(reads[0].rows).toEqual([{ agentId: f.agentId, responsibleUserId: null, contextSnapshot: expectedLineageContext(f.context) }]); + }); + + it.each([null, false, true, 0, 12, "", "malformed", [], ["source", { source: "chat:slack" }], {}, + { issueId: null, taskId: false, source: 3, interactionId: null, wakeCommentIds: { id: "not-array" } }, + ])("preserves malformed JSON and key absence for %j", async snapshot => { + const f = await fixture(1), run = await f.insertRun(snapshot), reads: LineageQuery[] = []; + expect(await resolveChatOriginPublicationBindings(captureLineageReads(db, reads), f.companyId, f.issueId, run.id)).toEqual([]); + expect(reads[0].rows[0].contextSnapshot).toEqual(expectedLineageContext(snapshot)); + }); + + it("keeps all nine keys and their JSON values, including explicit nulls and arrays", async () => { + const f = await fixture(1); + const snapshot = { issueId: null, taskId: f.issueId, wakeCommentIds: [f.comment.id, 1, null, f.comment.id], wakeCommentId: f.comment.id, commentId: f.comment.id, + source: "chat:slack", sourceRunId: { invalid: true }, interactionId: null, endpointId: f.endpoint.id, omitted: "wide unrelated value" }; + const run = await f.insertRun(snapshot), reads: LineageQuery[] = []; + expect(await resolveChatOriginPublicationBindings(captureLineageReads(db, reads), f.companyId, f.issueId, run.id)).toEqual(f.expected); + expect(reads[0].rows[0].contextSnapshot).toEqual(expectedLineageContext(snapshot)); + expect(Object.hasOwn(reads[0].rows[0].contextSnapshot as object, "interactionId")).toBe(true); + expect(Object.hasOwn(reads[0].rows[0].contextSnapshot as object, "omitted")).toBe(false); + }); + + it("preserves explicit JSON null as well as SQL null", async () => { + const f = await fixture(1), run = await f.insertRun(null), reads: LineageQuery[] = []; + await db.$client.unsafe("update heartbeat_runs set context_snapshot = 'null'::jsonb where id = $1::uuid", [run.id]); + expect(await resolveChatOriginPublicationBindings(captureLineageReads(db, reads), f.companyId, f.issueId, run.id)).toEqual([]); + expect(reads[0].rows[0].contextSnapshot).toBeNull(); + }); + + it.each([ + { name: "missing", snapshot: {}, wake: {}, allowed: true }, + { name: "explicit null", snapshot: { interactionId: null }, wake: { interactionId: null }, allowed: true }, + { name: "missing versus null", snapshot: { interactionId: null }, wake: {}, allowed: false }, + { name: "equal strings", snapshot: { interactionId: "synthetic-interaction" }, wake: { interactionId: "synthetic-interaction" }, allowed: true }, + { name: "number versus text", snapshot: { interactionId: 12 }, wake: { interactionId: "12" }, allowed: false }, + { name: "separate objects", snapshot: { interactionId: { id: "same" } }, wake: { interactionId: { id: "same" } }, allowed: false }, + ])("retains strict tool-action interaction semantics for $name and requires the durable receipt", async ({ snapshot, wake, allowed }) => { + const f = await fixture(1), continued = await f.continueFrom(f.root.id); + const [invocation] = await db.insert(toolInvocations).values({ companyId: f.companyId, issueId: f.issueId, agentId: f.agentId, runId: f.root.id, toolName: "synthetic-operation" }).returning(); + const [request] = await db.insert(toolActionRequests).values({ companyId: f.companyId, issueId: f.issueId, invocationId: invocation.id, + interactionId: continued.interaction.id, requestedByAgentId: f.agentId, status: "executed", canonicalArgumentsHash: "synthetic", canonicalArgumentsSummary: { summary: "Synthetic operation" } }).returning(); + await db.insert(toolActionDeliveries).values({ companyId: f.companyId, issueId: f.issueId, actionRequestId: request.id, interactionId: continued.interaction.id }); + await db.update(heartbeatRuns).set({ contextSnapshot: { issueId: f.issueId, source: "tool_action_review", sourceRunId: f.root.id, ...snapshot } }).where(eq(heartbeatRuns.id, continued.run.id)); + await db.insert(agentWakeupRequests).values({ companyId: f.companyId, agentId: f.agentId, source: "automation", reason: "issue_commented", status: "claimed", runId: continued.run.id, + idempotencyKey: `tool-action-response:${request.id}`, payload: { sourceRunId: f.root.id, toolActionRequestIds: [request.id], ...wake } }); + expect(await resolveChatOriginPublicationBindings(db, f.companyId, f.issueId, continued.run.id)).toEqual(allowed ? f.expected : []); + await db.delete(toolActionDeliveries).where(eq(toolActionDeliveries.actionRequestId, request.id)); + expect(await resolveChatOriginPublicationBindings(db, f.companyId, f.issueId, continued.run.id)).toEqual([]); + }); + + it("retains valid lineage beyond sixteen hops and rejects a durable cycle", async () => { + const f = await fixture(1); + let previous = f.root.id; + for (let index = 0; index < 24; index++) previous = (await f.continueFrom(previous)).run.id; + expect(await resolveChatOriginPublicationBindings(db, f.companyId, f.issueId, previous)).toEqual(f.expected); + const cycle = await f.continueFrom(previous); + await db.update(heartbeatRuns).set({ contextSnapshot: { source: "issue.interaction.accept", issueId: f.issueId, interactionId: cycle.interaction.id, sourceRunId: previous } }).where(eq(heartbeatRuns.id, f.root.id)); + await db.update(agentWakeupRequests).set({ runId: f.root.id }).where(eq(agentWakeupRequests.id, cycle.wake.id)); + const reads: LineageQuery[] = []; + expect(await resolveChatOriginPublicationBindings(captureLineageReads(db, reads), f.companyId, f.issueId, previous)).toEqual([]); + expect(reads).toHaveLength(25); + }); + + it("rejects mismatched company, task, agent, and endpoint bindings", async () => { + const f = await fixture(1), other = await fixture(1); + expect(await resolveChatOriginPublicationBindings(db, other.companyId, f.issueId, f.root.id)).toEqual([]); + for (const change of [{ issueId: other.issueId }, { endpointId: other.endpoint.id }, { source: false }, { wakeCommentIds: [randomUUID()], wakeCommentId: 12 }]) { + const run = await f.insertRun({ ...f.context, ...change }); + expect(await resolveChatOriginPublicationBindings(db, f.companyId, f.issueId, run.id)).toEqual([]); + } + const continued = await f.continueFrom(f.root.id); + await db.update(heartbeatRuns).set({ agentId: other.agentId }).where(eq(heartbeatRuns.id, continued.run.id)); + expect(await resolveChatOriginPublicationBindings(db, f.companyId, f.issueId, continued.run.id)).toEqual([]); + }); +}); diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index c6e54798555..391d08c660f 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -1170,7 +1170,13 @@ export async function resolveChatOriginPublicationBindings( .select({ agentId: heartbeatRuns.agentId, responsibleUserId: heartbeatRuns.responsibleUserId, - contextSnapshot: heartbeatRuns.contextSnapshot, + contextSnapshot: sql | null>` + case when jsonb_typeof(${heartbeatRuns.contextSnapshot}) = 'object' then + (select coalesce(jsonb_object_agg(entry.key, entry.value), '{}'::jsonb) + from jsonb_each(${heartbeatRuns.contextSnapshot}) as entry + where entry.key in ('issueId', 'taskId', 'wakeCommentIds', 'wakeCommentId', + 'commentId', 'source', 'sourceRunId', 'interactionId', 'endpointId')) + else ${heartbeatRuns.contextSnapshot} end`, }) .from(heartbeatRuns) .where( From dc8cbdb81953bd295ca2ab635414412af729e458 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:31:55 -0500 Subject: [PATCH 5/7] perf(server): narrow native session resume database reads (#17934) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://entire.com/gh/paperclipai/-/trails/94/changes/paperclip/94 ## Thinking Path > - Paperclip manages AI agents and their work. > - Native agents resume prior provider sessions from saved run checkpoints. > - Resume selection must respect every newer progress barrier. > - The prior query returned large context and profile JSON for up to 32 candidates. > - Most candidates need only process, status, binding, and checkpoint-presence checks. > - This PR selects the same source in one SQL snapshot and returns only its required payloads. > - This reduces database response bytes while preserving session authority and saved task context. ## Linked Issues or Issue Description **What existing behavior does this improve?** Native task/session resume selection in `findNativeSessionResumeRun`. **Current behavior** At baseline `bf3ef12f3a78d0b15a32ad57f7e16520fbf6cd5e`, a resume lookup reads complete context and profile JSON for up to 32 runs, then reads provider-event evidence. A synthetic 15-run history returns about 4.44 MB even though one checkpoint is selected. **Proposed behavior** A bounded CTE finds the first checkpoint or progress barrier. The same SQL statement returns the selected source's native input, checkpoint, tool fingerprint, wake envelope, canonical task brief, and process identity. All fallback barriers and the 32-run limit stay in place. **Reason and benefit** Rejected candidates no longer transfer saved prompts and execution inputs to Node. A single snapshot also prevents a gap between candidate selection and payload hydration. **Breaking changes** None to public APIs or stored history. This private service returns the fields consumed by runtime selection and checkpoint rebinding. It keeps complete required nested values and distinguishes missing brief fields from explicit JSON nulls. **Additional context** Checked `ROADMAP.md`. This is a targeted improvement to existing resume behavior. Public searches for native session resume projections found no duplicate. Related work includes #6573 (durable agent sessions) and #17011 (managed Claude resume opt-in); neither changes this database read. Provider-refusal recovery in #17676 is a separate concern and is unchanged. ## What Changed - Select the newest progress barrier within the existing exact company/agent/task/session and 32-run window in one SQL snapshot. - Return three required profile fields, the full wake envelope, and the saved task's ID, title, and description only for the selected source. - Preserve invalid non-null checkpoint barriers, provider evidence, process authority, terminal-status rules, timestamp precision, and exact string binding checks. - Add real PostgreSQL regression coverage and a reproducible baseline/treatment benchmark. Document the read and benchmark command. ## Verification - `pnpm -r typecheck` passed. `pnpm build` passed. The final server `tsc --noEmit` also passed. The later benchmark-only relocation passed `pnpm check:module-boundaries` and the real PostgreSQL proof; runtime and regression-test source are unchanged. - Related suites: `native-session-resume-projection.test.ts`, `native-session-resume.test.ts`, `heartbeat/retries.test.ts`, and `heartbeat-retry-scheduling.test.ts`: 78 passed and 54 skipped across 3 passed files and 1 skipped file. Embedded PostgreSQL/platform gates caused the skips. Resume orchestration and the 10 new SQL tests ran against isolated PostgreSQL 17.11. The final 10-test projection rerun passed. - New SQL cases cover all seven provider evidence kinds, each process authority field, all terminal statuses, wrong bindings and runtime, invalid checkpoints, null/scalar/array/object JSON, missing versus null brief fields, the 32-row bound, ordering ties, future barriers, submillisecond timestamps, and a change committed before the one selection statement. - `pnpm test:run` was attempted. The host's embedded PostgreSQL startup failed after five attempts. The broad run recorded failures/skips in embedded-database suites and was stopped after that concrete host limitation (exit 143). It is not a local full-suite pass. The full final-head CI matrix passes on `dcde4e3dac2173321d7be2406e7775af8411826a`: 55 successful checks, one neutral check, and two optional Storybook skips. Greptile completed at 5/5 on that exact head, with zero unresolved findings. The initial benchmark-location policy failure was fixed before this final run. - Reproduce the benchmark with `pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-native-session-resume-reads.ts --baseline-ref=bf3ef12f3a78d0b15a32ad57f7e16520fbf6cd5e`. The optional `PAPERCLIP_SESSION_RESUME_BENCHMARK_DATABASE_URL` must name an isolated database ending in `_test`. - The harness imports the pinned baseline module, invokes both actual services, captures complete generated SQL and parameters, compares every retained consumer field, and captures `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)`. Its incompressible wide fixture keeps a complete 96 KiB native input in the selected result. Raw PostgreSQL text DataRow frames are measured exactly; RowDescription, protocol command metadata, TLS, and TCP are excluded. | Synthetic local case | Baseline DataRow bytes | Treatment DataRow bytes | Reduction | | --- | ---: | ---: | ---: | | 15 runs, one selected checkpoint | 4,441,143 | 104,599 | 97.64% | | 15 unused bootstraps | 4,435,590 | 0 | 100% | | One small selected source | 6,395 | 6,319 | 1.19% | The committed-head benchmark uses two warmups and seven alternating samples per variant. Local round-trip medians and ranges were: | Synthetic local case | Baseline median (range), ms | Treatment median (range), ms | | --- | ---: | ---: | | Wide history | 20.32 (18.63–24.37) | 1.63 (1.40–2.21) | | Unused history | 18.52 (17.63–20.35) | 1.20 (1.13–1.56) | | Small selected source | 1.05 (0.95–1.70) | 0.78 (0.73–1.30) | The small case has overlapping ranges and a 1.19% byte change, so it is neutral. `EXPLAIN` server execution time was higher for the treatment (wide: 0.402 ms versus 0.028 ms across the two baseline statements). `EXPLAIN` does not serialize result rows; the new JSON presence checks do extra server work while avoiding large result transfer. These are local synthetic round-trip measurements, not production latency claims. The final proof ran on `dcde4e3dac2173321d7be2406e7775af8411826a` with no runtime source diff. ## Risks - Selection policy now has a SQL form. Regression tests preserve the pure selector's barrier semantics, including invalid non-null checkpoints and JavaScript Date precision. - Checkpoint-presence checks can still detoast candidate profiles inside PostgreSQL. The change reduces returned bytes; it does not eliminate all database JSON work. - The selected checkpoint, native input, and wake envelope can still be large because consumers require them in full. No new payload cap is introduced. - There is no migration, cache, background polling, ownership lock change, deployment, or merge in this PR. ## Model Used OpenAI GPT-6 through Codex. The host did not expose an exact runtime model ID or context-window size. The agent used reasoning, code execution, real PostgreSQL, and GitHub tools. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/DATABASE.md | 12 ++ .../benchmark-native-session-resume-reads.ts | 127 +++++++++++ .../native-session-resume-projection.test.ts | 203 ++++++++++++++++++ .../native-runtime/native-session-resume.ts | 119 +++++++--- 4 files changed, 429 insertions(+), 32 deletions(-) create mode 100644 scripts/benchmark-native-session-resume-reads.ts create mode 100644 server/src/services/native-runtime/native-session-resume-projection.test.ts diff --git a/doc/DATABASE.md b/doc/DATABASE.md index 24e06d59830..bf9f4a03333 100644 --- a/doc/DATABASE.md +++ b/doc/DATABASE.md @@ -49,6 +49,18 @@ and leaves all existing cases passive. Source identities are not grants. ### Task query performance +Native session resume selects its newest progress barrier within the existing +32-run task/session window in one SQL snapshot. Only the chosen checkpoint source +returns its saved native input, checkpoint, tool fingerprint, wake envelope, and +canonical task brief. Unused bootstrap candidates do not return full context or +profiles. Wrong runtime, nonterminal status, process identity, provider events, +invalid but non-null checkpoints, and future checkpoint barriers retain their +existing selection rules. Stored run payloads and history reads stay complete. +Run the synthetic PostgreSQL comparison with a pinned pre-change revision: +`pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-native-session-resume-reads.ts --baseline-ref=`. +An optional `PAPERCLIP_SESSION_RESUME_BENCHMARK_DATABASE_URL` must name a dedicated +test database ending in `_test`; otherwise the harness starts disposable PostgreSQL. + Agent request authentication uses a compact run-identity read. It omits saved execution payloads, results, and log excerpts from the query response. The read still locks the task before the run and reconciles pending steering from durable diff --git a/scripts/benchmark-native-session-resume-reads.ts b/scripts/benchmark-native-session-resume-reads.ts new file mode 100644 index 00000000000..df302f1ba71 --- /dev/null +++ b/scripts/benchmark-native-session-resume-reads.ts @@ -0,0 +1,127 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { randomBytes, randomUUID } from "node:crypto"; +import { promises as fs } from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { agents, applyPendingMigrations, companies, createDb, heartbeatRuns, issues, startEmbeddedPostgresTestDatabase, type Db } from "../packages/db/src/index.js"; +import { findNativeSessionResumeRun } from "../server/src/services/native-runtime/native-session-resume.js"; +import { resolveExternalTestDatabaseUrl } from "../server/src/__tests__/helpers/external-test-database.js"; + +type Query = { sql: string; params: unknown[] }; +const root = fileURLToPath(new URL("../", import.meta.url)); +const baselineRef = process.argv.find(arg => arg.startsWith("--baseline-ref="))?.slice(15); +assert.ok(baselineRef, "Pass a pinned pre-fix --baseline-ref"); +const baselineRevision = execFileSync("git", ["rev-parse", "--verify", `${baselineRef}^{commit}`], { cwd: root, encoding: "utf8" }).trim(); +const sourcePath = "server/src/services/native-runtime/native-session-resume.ts"; +const treatmentRevision = execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8" }).trim(); +const treatmentDiff = execFileSync("git", ["diff", "HEAD", "--", sourcePath], { cwd: root, encoding: "utf8" }); +const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_SESSION_RESUME_BENCHMARK_DATABASE_URL"); +const database = externalUrl ? { connectionString: externalUrl, cleanup: async () => {} } : await startEmbeddedPostgresTestDatabase("native-session-resume-benchmark-"); +const db = createDb(database.connectionString); +const baselineDir = await fs.mkdtemp(path.join(root, "server/scripts/.session-resume-baseline-")); +const companyIds: string[] = []; +try { + if (externalUrl) await applyPendingMigrations(externalUrl); + const moduleUrl = new URL(`../${sourcePath}`, import.meta.url); + const source = execFileSync("git", ["show", `${baselineRevision}:${sourcePath}`], { cwd: root, encoding: "utf8" }); + await fs.writeFile(path.join(baselineDir, "resume.ts"), source.replace(/from "(\.{1,2}\/[^\"]+)"/g, + (_match, specifier: string) => `from ${JSON.stringify(fileURLToPath(new URL(specifier, moduleUrl)))}`)); + const baseline = await import(pathToFileURL(path.join(baselineDir, "resume.ts")).href) as { findNativeSessionResumeRun: typeof findNativeSessionResumeRun }; + async function capture(invoke: typeof findNativeSessionResumeRun, input: Parameters[1]) { + const queries: Query[] = []; + const wrap = (target: Db): Db => new Proxy(target, { get(target, key) { + if (key === "with") return (...args: Parameters) => wrap(target.with(...args) as Db); + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const query = from(...args), execute = query.execute.bind(query); + query.execute = async (...executeArgs: Parameters) => { + queries.push(query.toSQL()); + return execute(...executeArgs); + }; + return query; + }) as typeof builder.from; + return builder; + }; + }}); + return { result: await invoke(wrap(db), input), queries }; + } + const median = (values: number[]) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]; + const measurements = []; + for (const scenario of ["wide_history", "unused_history", "small_selected"] as const) { + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), normalizedSessionId = randomUUID(); + companyIds.push(companyId); + await db.insert(companies).values({ id: companyId, name: "Synthetic resume benchmark", issuePrefix: `B${companyId.replaceAll("-", "")}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Synthetic runner", adapterType: "paperclip_runner" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Retain canonical task" }); + const runCount = scenario === "small_selected" ? 1 : 15; + const prompt = randomBytes(scenario === "small_selected" ? 16 : 144 * 1024).toString("base64"); + const profilePadding = randomBytes(scenario === "small_selected" ? 16 : 72 * 1024).toString("base64"); + const neededInput = { task: { title: "Prior task", description: "Canonical description", prompt: profilePadding }, runtimeContext: { instructions: "Keep complete input" } }; + const checkpoint = { sessionId: normalizedSessionId, state: randomBytes(4096).toString("base64") }; + await db.insert(heartbeatRuns).values(Array.from({ length: runCount }, (_, n) => ({ + id: randomUUID(), companyId, agentId, nativeIssueId: issueId, nativeSessionId: normalizedSessionId, + runtimeMode: "native", status: "failed", createdAt: new Date(Date.UTC(2026, 8, 8, 0, 0, n)), + runnerProfileJson: { padding: "Unused profile metadata", nativeExecutionInput: neededInput, nativeToolContractFingerprint: "fixture", + ...(scenario !== "unused_history" && n === 0 ? { sessionCheckpoint: checkpoint } : {}) }, + contextSnapshot: { prompt, paperclipWake: { externalChatProvider: "slack", githubReviewConfigurations: [{ key: "review" }] }, + paperclipIssue: { id: issueId, title: "Prior canonical title", description: "Prior canonical description" } }, + }))); + await db.$client.unsafe("ANALYZE heartbeat_runs"); + const input = { companyId, agentId, issueId, normalizedSessionId, currentRunId: randomUUID(), beforeCreatedAt: new Date("2026-09-09T00:00:00Z") }; + const before = await capture(baseline.findNativeSessionResumeRun, input), after = await capture(findNativeSessionResumeRun, input); + const contract = (run: typeof after.result) => run && ({ ...run, + runnerProfileJson: { nativeExecutionInput: run.runnerProfileJson?.nativeExecutionInput ?? null, + nativeToolContractFingerprint: run.runnerProfileJson?.nativeToolContractFingerprint ?? null, + sessionCheckpoint: run.runnerProfileJson?.sessionCheckpoint ?? null }, + contextSnapshot: { paperclipWake: run.contextSnapshot?.paperclipWake ?? null, paperclipIssue: run.contextSnapshot?.paperclipIssue ?? null } }); + assert.deepEqual(contract(after.result), contract(before.result)); + const variants = [before.queries, after.queries], samples: number[][] = [[], []], dataRowBytes = [0, 0], resultRows = [0, 0]; + for (let iteration = 0; iteration < 9; iteration++) { + for (const variant of iteration % 2 ? [1, 0] : [0, 1]) { + const start = performance.now(); + let bytes = 0, count = 0; + for (const query of variants[variant]) { + const rows = await db.$client.unsafe(query.sql, query.params as never[]).raw(); + count += rows.length; + bytes += rows.reduce((total, row) => total + 7 + row.reduce((size: number, value: Buffer | null) => size + 4 + (value?.length ?? 0), 0), 0); + } + if (iteration >= 2) samples[variant].push(performance.now() - start); + dataRowBytes[variant] = bytes; resultRows[variant] = count; + } + } + const plans = []; + for (const queries of variants) { + const variantPlans = []; + for (const query of queries) { + const [plan] = await db.$client.unsafe(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query.sql}`, query.params as never[]); + variantPlans.push(plan["QUERY PLAN"]); + } + plans.push(variantPlans); + } + if (!process.argv.includes("--baseline-only") && scenario !== "small_selected") assert.ok(dataRowBytes[1] < dataRowBytes[0] / 10); + measurements.push({ scenario, runCount, equalConsumerFields: true, baselineQueryCount: before.queries.length, treatmentQueryCount: after.queries.length, + dataRowBytes, resultRows, baselineMedianMs: median(samples[0]), treatmentMedianMs: median(samples[1]), samples, queries: variants, plans }); + } + console.log(JSON.stringify({ baselineRevision, treatmentRevision, treatmentDiff, + acceptance: "Equal selected consumer fields; wide and unused histories remove at least 90% of DataRow bytes; no timing threshold", + byteBoundary: "Exact text-format PostgreSQL DataRow frames (7 bytes framing + 4 bytes length per column + raw field bytes); excludes RowDescription, command metadata, TLS and TCP", + postgres: await db.$client.unsafe("select version()"), measurements }, null, 2)); +} finally { + try { + for (const companyId of companyIds) { + await db.$client.unsafe("DELETE FROM heartbeat_runs WHERE company_id = $1::uuid", [companyId]); + await db.$client.unsafe("DELETE FROM issues WHERE company_id = $1::uuid", [companyId]); + await db.$client.unsafe("DELETE FROM agents WHERE company_id = $1::uuid", [companyId]); + await db.$client.unsafe("DELETE FROM companies WHERE id = $1::uuid", [companyId]); + } + } finally { + try { await db.$client.end({ timeout: 0 }); } + finally { + try { await database.cleanup(); } + finally { await fs.rm(baselineDir, { recursive: true, force: true }); } + } + } +} diff --git a/server/src/services/native-runtime/native-session-resume-projection.test.ts b/server/src/services/native-runtime/native-session-resume-projection.test.ts new file mode 100644 index 00000000000..08242f2a690 --- /dev/null +++ b/server/src/services/native-runtime/native-session-resume-projection.test.ts @@ -0,0 +1,203 @@ +import { randomUUID } from "node:crypto"; +import { and, eq, sql } from "drizzle-orm"; +import { agents, companies, createDb, heartbeatRunEvents, heartbeatRuns, issues, type Db } from "@paperclipai/db"; +import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; +import { resolveExternalTestDatabaseUrl } from "../../__tests__/helpers/external-test-database.js"; +import { findNativeSessionResumeRun } from "./native-session-resume.js"; + +const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_TEST_DATABASE_URL"); +const supported = Boolean(externalUrl) || (await getEmbeddedPostgresTestSupport()).supported; + +(supported ? describe : describe.skip)("native session resume SQL projection", () => { + let database: Awaited>; + let db: Db; + const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), normalizedSessionId = randomUUID(); + const currentRunId = randomUUID(); + const at = (second: number) => new Date(Date.UTC(2026, 8, 8, 0, 0, second)); + const input = { companyId, agentId, issueId, normalizedSessionId, currentRunId, beforeCreatedAt: at(30) }; + const checkpoint = { sessionId: "provider-session", identity: { runId: "prior" }, complete: [false, 0, "", null] }; + const nativeExecutionInput = { binding: { issueId }, task: { prompt: "Complete native input", description: "Description" }, runtimeContext: { nested: [1, 2] } }; + const paperclipWake = { externalChatProvider: "slack", githubReviewConfigurations: [{ key: "configuration", nested: { retained: true } }], other: ["preserved"] }; + const paperclipIssue = { id: issueId, title: "Saved canonical title", description: "Saved canonical description" }; + const profile = { nativeExecutionInput, sessionCheckpoint: checkpoint, nativeToolContractFingerprint: "fingerprint", unrelated: "Omit" }; + const run = (second: number, overrides: Partial = {}) => ({ + id: randomUUID(), companyId, agentId, nativeIssueId: issueId, nativeSessionId: normalizedSessionId, + runtimeMode: "native", status: "failed", createdAt: at(second), runnerProfileJson: {}, ...overrides, + }); + const select = () => findNativeSessionResumeRun(db, input); + const source = () => run(0, { runnerInstanceId: randomUUID(), processPid: 17, processGroupId: 19, processStartedAt: at(0), + runnerProfileJson: profile, contextSnapshot: { paperclipWake, paperclipIssue: { ...paperclipIssue, unrelated: "Omit" }, prompt: "Omit" } }); + const writeProfile = (id: string, value: unknown) => db.execute(sql`update ${heartbeatRuns} + set runner_profile_json = ${JSON.stringify(value)}::jsonb where ${heartbeatRuns.id} = ${id}`); + + beforeAll(async () => { + database = externalUrl ? { connectionString: externalUrl, cleanup: async () => {} } : await startEmbeddedPostgresTestDatabase("native-resume-projection-"); + db = createDb(database.connectionString); + await db.insert(companies).values({ id: companyId, name: "Resume projection", issuePrefix: `N${companyId.replaceAll("-", "")}` }); + await db.insert(agents).values({ id: agentId, companyId, name: "Runner" }); + await db.insert(issues).values({ id: issueId, companyId, title: "Resume task" }); + }); + afterEach(async () => { + await db.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.companyId, companyId)); + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId)); + }); + afterAll(async () => { + if (!db) return; + try { + await db.delete(issues).where(eq(issues.companyId, companyId)); + await db.delete(agents).where(eq(agents.companyId, companyId)); + await db.delete(companies).where(eq(companies.id, companyId)); + } finally { + try { await db.$client.end({ timeout: 0 }); } + finally { await database.cleanup(); } + } + }); + + it("retains full required input, checkpoint, wake, canonical brief and process identity only for the selected source", async () => { + const saved = source(); + await db.insert(heartbeatRuns).values([saved, run(1), run(2)]); + const result = await select(); + expect(result).toEqual({ ...saved, runnerProfileJson: { nativeExecutionInput, sessionCheckpoint: checkpoint, nativeToolContractFingerprint: "fingerprint" }, + contextSnapshot: { paperclipWake, paperclipIssue } }); + const stored = await db.select({ profile: heartbeatRuns.runnerProfileJson, context: heartbeatRuns.contextSnapshot }).from(heartbeatRuns).where(eq(heartbeatRuns.id, saved.id)); + expect(stored[0].profile).toEqual(profile); + expect(stored[0].context).toEqual(saved.contextSnapshot); + for (const status of ["succeeded", "interrupted", "cancelled", "timed_out"]) { + await db.update(heartbeatRuns).set({ status }).where(eq(heartbeatRuns.id, saved.id)); + expect((await select())?.id).toBe(saved.id); + } + }); + + it("treats every non-null checkpoint as a barrier, including invalid false, zero, empty string, array and object values", async () => { + const saved = source(), newer = run(1); + await db.insert(heartbeatRuns).values([saved, newer]); + for (const value of [false, 0, "", "invalid", [], {}]) { + await writeProfile(newer.id, { sessionCheckpoint: value }); + const selected = await select(); + expect(selected?.id).toBe(newer.id); + expect(selected?.runnerProfileJson.sessionCheckpoint).toEqual(value); + } + }); + + it("skips only unused SQL-null, JSON-null, scalar, array and checkpoint-null profiles", async () => { + const saved = source(), newer = run(1, { runnerProfileJson: null }); + await db.insert(heartbeatRuns).values([saved, newer]); + expect((await select())?.id).toBe(saved.id); + for (const value of [null, false, 0, "sessionCheckpoint", [], ["sessionCheckpoint"], {}, { sessionCheckpoint: null }]) { + await writeProfile(newer.id, value); + expect((await select())?.id).toBe(saved.id); + } + }); + + it("preserves malformed selected context values and missing brief fields", async () => { + const saved = source(); + await db.insert(heartbeatRuns).values(saved); + for (const value of [null, false, 0, "invalid", [], {}, { paperclipWake: [], paperclipIssue: { id: issueId, title: false } }, + { paperclipIssue: { id: issueId, title: "Valid title without description" } }, + { paperclipIssue: { id: issueId, title: "Valid title", description: null } }]) { + await db.execute(sql`update ${heartbeatRuns} set context_snapshot = ${JSON.stringify(value)}::jsonb where ${heartbeatRuns.id} = ${saved.id}`); + const result = await select(); + const object = typeof value === "object" && value !== null && !Array.isArray(value) ? value : {}; + expect(result?.contextSnapshot.paperclipWake).toEqual("paperclipWake" in object ? object.paperclipWake : null); + expect(result?.contextSnapshot.paperclipIssue).toEqual("paperclipIssue" in object ? object.paperclipIssue : null); + } + }); + + it("stops at wrong runtime, nonterminal status and each process authority field", async () => { + await db.insert(heartbeatRuns).values(source()); + for (const override of [{ runtimeMode: "legacy" }, { status: "running" }, { processPid: 0 }, { processGroupId: 0 }, { processStartedAt: at(0) }]) { + const newer = run(1, override); + await db.insert(heartbeatRuns).values(newer); + expect(await select()).toBeNull(); + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, newer.id)); + } + }); + + it("checks every provider evidence event and ignores unrelated event kinds", async () => { + const saved = source(), newer = run(1); + await db.insert(heartbeatRuns).values([saved, newer]); + for (const eventType of ["harness.ready", "session.started", "session.resumed", "session.updated", "turn.started", "provider.event", "provider.rpc_result", "log"]) { + await db.insert(heartbeatRunEvents).values({ companyId, agentId, runId: newer.id, seq: 1, eventType }); + if (eventType === "log") expect((await select())?.id).toBe(saved.id); + else expect(await select()).toBeNull(); + await db.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, newer.id)); + } + }); + + it("excludes current and mismatched agent, company, task and session rows before applying barriers", async () => { + const saved = source(), otherCompany = randomUUID(), otherAgent = randomUUID(), otherIssue = randomUUID(); + await db.insert(companies).values({ id: otherCompany, name: "Other", issuePrefix: `D${otherCompany.replaceAll("-", "")}` }); + await db.insert(agents).values({ id: otherAgent, companyId: otherCompany, name: "Other" }); + await db.insert(issues).values({ id: otherIssue, companyId, title: "Other" }); + try { + await db.insert(heartbeatRuns).values([saved, run(1, { id: currentRunId, status: "running" }), + run(2, { companyId: otherCompany, status: "running" }), run(3, { agentId: otherAgent, status: "running" }), + run(4, { nativeIssueId: otherIssue, status: "running" }), run(5, { nativeSessionId: randomUUID(), status: "running" })]); + expect((await select())?.id).toBe(saved.id); + } finally { + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.companyId, otherCompany)); + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.agentId, otherAgent)); + await db.delete(issues).where(eq(issues.id, otherIssue)); + await db.delete(agents).where(eq(agents.id, otherAgent)); + await db.delete(companies).where(eq(companies.id, otherCompany)); + } + expect(await findNativeSessionResumeRun(db, { ...input, normalizedSessionId: "invalid" })).toBeNull(); + for (const key of ["companyId", "agentId", "issueId", "normalizedSessionId"] as const) { + expect(await findNativeSessionResumeRun(db, { ...input, [key]: input[key].toUpperCase() })).toBeNull(); + } + }); + + it("retains the 32-row bound and deterministic created-at/id ordering", async () => { + const saved = source(), unused = Array.from({ length: 32 }, () => run(1)); + await db.insert(heartbeatRuns).values([saved, ...unused]); + expect(await select()).toBeNull(); + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, unused[0].id)); + expect((await select())?.id).toBe(saved.id); + const tied = [run(2, { runnerProfileJson: { sessionCheckpoint: false } }), run(2, { status: "running" })].sort((a, b) => b.id.localeCompare(a.id)); + await db.insert(heartbeatRuns).values(tied); + if (tied[0].status === "running") expect(await select()).toBeNull(); + else expect((await select())?.id).toBe(tied[0].id); + }); + + it("does not skip future checkpoint barriers and preserves Date millisecond comparison", async () => { + const saved = source(), future = run(31); + await db.insert(heartbeatRuns).values([saved, future]); + expect((await select())?.id).toBe(saved.id); + await writeProfile(future.id, { sessionCheckpoint: false }); + expect(await select()).toBeNull(); + await db.execute(sql`update ${heartbeatRuns} set created_at = '2026-09-08T00:00:30.000999Z'::timestamptz where ${heartbeatRuns.id} = ${future.id}`); + expect((await select())?.id).toBe(future.id); + }); + + it("sees a newly committed barrier and changed source binding in its single selection snapshot", async () => { + const saved = source(); + await db.insert(heartbeatRuns).values(saved); + let reads = 0; + const changing = new Proxy(db, { get(target, key) { + if (key !== "with") return Reflect.get(target, key); + return (...ctes: Parameters) => { + const builder = target.with(...ctes), original = builder.select.bind(builder); + builder.select = ((...fields: Parameters) => { + const selection = original(...fields), from = selection.from.bind(selection); + selection.from = ((...args: Parameters) => { + const query = from(...args), execute = query.execute.bind(query); + query.execute = async (...executeArgs: Parameters) => { + reads++; + await db.insert(heartbeatRuns).values(run(1, { runnerProfileJson: { sessionCheckpoint: 0 } })); + await db.update(heartbeatRuns).set({ nativeSessionId: randomUUID() }).where(and(eq(heartbeatRuns.id, saved.id), eq(heartbeatRuns.companyId, companyId))); + return execute(...executeArgs); + }; + return query; + }) as typeof selection.from; + return selection; + }) as typeof builder.select; + return builder; + }; + }}); + const selected = await findNativeSessionResumeRun(changing, input); + expect(reads).toBe(1); + expect(selected?.id).not.toBe(saved.id); + expect(selected?.runnerProfileJson.sessionCheckpoint).toBe(0); + }); +}); diff --git a/server/src/services/native-runtime/native-session-resume.ts b/server/src/services/native-runtime/native-session-resume.ts index a271601ce0b..25463b68c78 100644 --- a/server/src/services/native-runtime/native-session-resume.ts +++ b/server/src/services/native-runtime/native-session-resume.ts @@ -1,6 +1,6 @@ import { createHash, randomUUID } from "node:crypto"; import { isDeepStrictEqual } from "node:util"; -import { and, desc, eq, inArray, ne } from "drizzle-orm"; +import { and, desc, eq, exists, inArray, isNotNull, ne, not, or, sql } from "drizzle-orm"; import { heartbeatRunEvents, heartbeatRuns, type Db } from "@paperclipai/db"; import type { NativeExecutionInput, @@ -186,6 +186,16 @@ export function selectNativeSessionResumeRun< return null; } +const NATIVE_SESSION_PROVIDER_EVENT_TYPES = [ + "harness.ready", + "session.started", + "session.resumed", + "session.updated", + "turn.started", + "provider.event", + "provider.rpc_result", +]; + export async function nativeSessionProviderEvidence( db: Pick, runIds: string[], @@ -197,15 +207,7 @@ export async function nativeSessionProviderEvidence( .where( and( inArray(heartbeatRunEvents.runId, runIds), - inArray(heartbeatRunEvents.eventType, [ - "harness.ready", - "session.started", - "session.resumed", - "session.updated", - "turn.started", - "provider.event", - "provider.rpc_result", - ]), + inArray(heartbeatRunEvents.eventType, NATIVE_SESSION_PROVIDER_EVENT_TYPES), ), ) .groupBy(heartbeatRunEvents.runId); @@ -224,7 +226,50 @@ export async function findNativeSessionResumeRun( }, ) { if (!isNativeSessionId(input.normalizedSessionId)) return null; - const runs = await db + const candidates = db.$with("native_resume_candidates").as(db + .select({ + id: heartbeatRuns.id, + runtimeMode: heartbeatRuns.runtimeMode, + status: heartbeatRuns.status, + createdAt: heartbeatRuns.createdAt, + processPid: heartbeatRuns.processPid, + processGroupId: heartbeatRuns.processGroupId, + processStartedAt: heartbeatRuns.processStartedAt, + hasCheckpoint: sql`coalesce(${heartbeatRuns.runnerProfileJson}->'sessionCheckpoint' <> 'null'::jsonb, false)`.as("has_checkpoint"), + }) + .from(heartbeatRuns) + .where( + and( + ne(heartbeatRuns.id, input.currentRunId), + eq(heartbeatRuns.companyId, input.companyId), + eq(heartbeatRuns.agentId, input.agentId), + eq(heartbeatRuns.nativeIssueId, input.issueId), + eq(heartbeatRuns.nativeSessionId, input.normalizedSessionId), + ), + ) + .orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)) + .limit(32)); + const terminalStatuses = [...LEGACY_RETRY_SOURCE_TERMINAL_STATUSES]; + const barrier = db.$with("native_resume_barrier").as(db + .select() + .from(candidates) + .where(or( + ne(candidates.runtimeMode, "native"), + not(inArray(candidates.status, terminalStatuses)), + candidates.hasCheckpoint, + isNotNull(candidates.processPid), + isNotNull(candidates.processGroupId), + isNotNull(candidates.processStartedAt), + exists(db.select({ runId: heartbeatRunEvents.runId }) + .from(heartbeatRunEvents) + .where(and( + eq(heartbeatRunEvents.runId, candidates.id), + inArray(heartbeatRunEvents.eventType, NATIVE_SESSION_PROVIDER_EVENT_TYPES), + ))), + )) + .orderBy(desc(candidates.createdAt), desc(candidates.id)) + .limit(1)); + const [run] = await db.with(candidates, barrier) .select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, @@ -238,29 +283,39 @@ export async function findNativeSessionResumeRun( processPid: heartbeatRuns.processPid, processGroupId: heartbeatRuns.processGroupId, processStartedAt: heartbeatRuns.processStartedAt, - runnerProfileJson: heartbeatRuns.runnerProfileJson, - contextSnapshot: heartbeatRuns.contextSnapshot, + runnerProfileJson: sql<{ + nativeToolContractFingerprint: unknown; + nativeExecutionInput: unknown; + sessionCheckpoint: unknown; + }>`jsonb_build_object( + 'nativeToolContractFingerprint', ${heartbeatRuns.runnerProfileJson}->'nativeToolContractFingerprint', + 'nativeExecutionInput', ${heartbeatRuns.runnerProfileJson}->'nativeExecutionInput', + 'sessionCheckpoint', ${heartbeatRuns.runnerProfileJson}->'sessionCheckpoint' + )`, + contextSnapshot: sql<{ + paperclipWake: unknown; + paperclipIssue: unknown; + }>`jsonb_build_object( + 'paperclipWake', ${heartbeatRuns.contextSnapshot}->'paperclipWake', + 'paperclipIssue', case when jsonb_typeof(${heartbeatRuns.contextSnapshot}->'paperclipIssue') = 'object' + then (select coalesce(jsonb_object_agg(brief.key, brief.value), '{}'::jsonb) + from jsonb_each(${heartbeatRuns.contextSnapshot}->'paperclipIssue') as brief + where brief.key in ('id', 'title', 'description')) else ${heartbeatRuns.contextSnapshot}->'paperclipIssue' end + )`, }) .from(heartbeatRuns) - .where( - and( - ne(heartbeatRuns.id, input.currentRunId), - eq(heartbeatRuns.companyId, input.companyId), - eq(heartbeatRuns.agentId, input.agentId), - eq(heartbeatRuns.nativeIssueId, input.issueId), - eq(heartbeatRuns.nativeSessionId, input.normalizedSessionId), - ), - ) - .orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)) - .limit(32); - return selectNativeSessionResumeRun({ - ...input, - runs, - providerEvidenceRunIds: await nativeSessionProviderEvidence( - db, - runs.map((run) => run.id), - ), - }); + .innerJoin(barrier, eq(heartbeatRuns.id, barrier.id)) + .where(and( + eq(barrier.runtimeMode, "native"), + inArray(barrier.status, terminalStatuses), + eq(barrier.hasCheckpoint, true), + sql`${heartbeatRuns.companyId}::text = ${input.companyId}`, + sql`${heartbeatRuns.agentId}::text = ${input.agentId}`, + sql`${heartbeatRuns.nativeIssueId}::text = ${input.issueId}`, + sql`${heartbeatRuns.nativeSessionId}::text = ${input.normalizedSessionId}`, + sql`date_trunc('milliseconds', ${barrier.createdAt}) <= ${input.beforeCreatedAt.toISOString()}::timestamptz`, + )); + return run ?? null; } /** A preassigned session id may rotate only before immutable native admission. */ From 09d4ca533e5f84ddc7abb93660a72d1c0264d51e Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:32:09 -0500 Subject: [PATCH 6/7] perf(server): return only sidebar failure badge candidates (#17935) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://entire.com/gh/paperclipai/-/trails/95/changes/paperclip/95 ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - The sidebar badge shows failures that need attention. > - The service reads the newest 200 runs before it selects one run per agent. > - Most of those rows cannot contribute to the failure count. > - This pull request selects failure candidates in SQL and returns four required fields. > - The benefit is less database response data with the same badge and access rules. ## Linked Issues or Issue Description Refs: #12770. Refs: #17756. Refs: #17683. These are related load, inbox, and badge reports. This implementation was written independently from the current service. It does not change which issue states count as failures. **What existing behavior does this improve?** The run read used by the company sidebar badge. **Current behavior** Every call transfers up to 200 rows with eight scalar fields. The application then selects the latest run per agent and applies status, Mine, dismissal, and access rules. **Proposed behavior** SQL selects the same latest run per agent from the same 200-row window. It then applies status and Mine rules. It returns only the run ID, scope, issue ID, and creation time. The service still checks dismissals and current issue access. **Reason and benefit** A mixed synthetic fixture reduces the response from 30,689 to 1,297 value bytes. The complete badge response stays equal. **Breaking changes** None. The endpoint response and the 200-run window stay the same. ## What Changed - Keep company and active-agent filters before the existing 200-row limit. - Rank each agent by the full creation timestamp in descending order, then by the observation ordinal. The timestamp order explicitly selects the newest run. Exact ties retain the first observed row. No ID tie-break is added. - Apply failure and Mine filters after ranking. A shared agent's success cannot expose an older failure. - Return four fields for dismissal and fresh issue authorization. Supply the already constrained company ID in the service. - Add real PostgreSQL regression fixtures and a service-generated SQL comparison harness. Document the command in `doc/DEVELOPING.md`. ## Verification - `pnpm -r typecheck` passed. `pnpm build` then passed in a separate sequential step. The normal Runner verifier checked 1,509 inputs and 1,555 outputs before reuse. - `PAPERCLIP_SIDEBAR_TEST_DATABASE_URL= pnpm --filter @paperclipai/server exec vitest run src/__tests__/sidebar-badges.test.ts` passed all 14 tests on PostgreSQL 17.11. - The 10 unchanged `inbox-dismissals.test.ts` route tests passed against the same real PostgreSQL server through a temporary local adapter for database startup and cleanup. The adapter was removed. The standard host run passed the 13 new tests and skipped those 10 embedded-PostgreSQL tests. - The first focused attempt could not import the unbuilt plugin SDK. The normal build supplied that package before the passing reruns. - `pnpm test:run` was attempted. It recorded 16 embedded-PostgreSQL startup failures in the unrelated native-session executor suite. Other database suites also reported startup failures and skipped. The owned command was then stopped with exit 143. This is incomplete local full-suite evidence, not a pass. Full remote CI passed on final head `df5b2c81af43c282d031cc37e6bc867054217df5`: 54 successful checks, 2 neutral checks, and 2 optional Storybook skips; no pending or failed checks. Fresh exact-head Greptile review is 5/5 with zero unresolved threads. - A fixture rollback test reproduced the review finding before the fix: a failed final approval insert left 2 companies, 44 agents, 2 issues, and 657 runs. After the fix, the same PostgreSQL constraint error leaves zero owned rows in all five tables. The test also confirms that more than 600 runs were written before the deliberate failure. - Fixture seeding now uses one transaction, including the submillisecond SQL insert. The 14 focused tests and all 10 benchmark cases pass after this repair. The server typecheck also passes. Production SQL is unchanged. - The final ordering repair passed all 14 real-PostgreSQL tests, all 10 pinned-baseline benchmark cases, and affected server typecheck and build, run sequentially. The plans now explicitly sort by agent ID, full creation time descending, then observation ordinal. Complete badge responses and candidate bindings remain equal. - One server-test shard was interrupted by its CI runner receiving a shutdown signal. Its test step was canceled without an assertion failure. A single targeted retry passed; the aggregate `ci / verify` gate also passed. No source change was needed for that interruption. - `git diff --check` passed. No schema, workflow, or lockfile changed. Reproduce the benchmark with current schema migrations and a dedicated synthetic database whose name ends in `_test`: ```sh PAPERCLIP_SIDEBAR_TEST_DATABASE_URL= PAPERCLIP_LOG_LEVEL=error SIDEBAR_REQUIRE_BYTE_REDUCTION=1 pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-sidebar-badges.ts --baseline-ref=bf3ef12f3a78d0b15a32ad57f7e16520fbf6cd5e ``` The harness loads the baseline service from that commit. Its authorization, privacy, and shared helper dependencies are unchanged. It captures the SQL each service executes. It compares complete badge responses and every returned candidate field. Fixtures cover more than 200 runs, shared agents, superseding successes, exact and submillisecond ties, Mine user variants, dismissal equality, private and deleted issues, missing issue bindings, terminated agents, and cross-company rows. Tests also cover absent actors, grants, revocation, deletion after a prior read, and index versus sort plans. Synthetic local SQL results from PostgreSQL 17.11 on Docker, Node 24.22.1, and postgres.js 3.4.9 follow. Each timing is the median of seven alternating warm samples after two warmups. The report includes all samples, ranges, settings, SQL, parameters, and `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` plans. | Fixture | Rows before → after | Value bytes before → after | Reduction | Median ms before → after | | --- | --- | --- | --- | --- | | Mixed, company-wide | 200 → 18 | 30,689 → 1,297 | 95.8% | 1.361 → 1.305 | | Mixed, user-1 | 200 → 9 | 30,689 → 676 | 97.8% | 1.785 → 1.391 | | Mixed, local-board | 200 → 6 | 30,689 → 414 | 98.7% | 1.463 → 1.232 | | All failed, 200 distinct latest agents | 200 → 200 | 30,298 → 13,778 | 54.5% | 1.277 → 1.237 | | All succeeded | 200 → 0 | 30,898 → 0 | 100% | 1.095 → 0.898 | | Empty | 0 → 0 | 0 → 0 | Neutral | 0.703 → 1.002 | Value bytes mean UTF-8 non-null cell values before Drizzle decoding. They exclude PostgreSQL protocol framing and are not wire bytes. The primary claim is less response data. Warm timing ranges overlap. Earlier all-failed samples were slower, and the empty control remains slower. SQL adds ranking work. No production latency improvement is claimed. The plans keep the limit below both window operations. ## Risks - SQL adds two bounded window operations. The all-failed control transfers fewer bytes but can take more SQL time. - Per-agent ranking explicitly orders by full creation time descending. Exact timestamp ties retain the observation ordinal. Real PostgreSQL tests compare complete candidates with the original helper under index and sort plans. - Mine rules now also have a SQL form. Tests cover undefined, null, empty, named, and local-board users, including empty responsible-user IDs. - Issue access stays fresh and fail closed. No authorization result is cached. No migration or stored run change is required. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used OpenAI GPT-6 through Codex. The exact serving model ID and context window are not exposed in this session. The model used reasoning, code execution, SQL inspection, and GitHub tools. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip --- doc/DEVELOPING.md | 29 ++++ scripts/benchmark-sidebar-badges.ts | 104 +++++++++++++ .../helpers/sidebar-badges-fixture.ts | 127 ++++++++++++++++ server/src/__tests__/sidebar-badges.test.ts | 139 ++++++++++++++++++ server/src/services/sidebar-badges.ts | 53 +++++-- 5 files changed, 443 insertions(+), 9 deletions(-) create mode 100644 scripts/benchmark-sidebar-badges.ts create mode 100644 server/src/__tests__/helpers/sidebar-badges-fixture.ts create mode 100644 server/src/__tests__/sidebar-badges.test.ts diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 6f7b2b181cc..20f874a17ae 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -3382,6 +3382,35 @@ pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-workspace-prepar It compares actual preparation guards with synthetic history. Local timings are separate from Git materialization, environment acquisition, and provider startup. +### Sidebar badge run-query benchmark + +The badge query keeps the newest 200 runs of nonterminated same-company agents. +It selects each agent's first observed run before status or Mine filters. An +observation ordinal preserves equal-time input order. Per-agent ranking orders +by full creation time first, then that ordinal for exact ties. SQL returns only failure +IDs, issue bindings, and creation times. Dismissals and fresh issue authorization +still run in the service. + +Run the synthetic PostgreSQL comparison with a pinned pre-change revision: + +```sh +PAPERCLIP_LOG_LEVEL=error SIDEBAR_REQUIRE_BYTE_REDUCTION=1 pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-sidebar-badges.ts --baseline-ref=bf3ef12f3a78d0b15a32ad57f7e16520fbf6cd5e +``` + +The harness starts disposable embedded PostgreSQL by default. To use an existing +isolated test database with current migrations, set +`PAPERCLIP_SIDEBAR_TEST_DATABASE_URL` to a dedicated database whose name ends in +`_test`. The harness removes only its own synthetic company fixtures. Do not use +a development or hosted company database. + +The report includes service-generated SQL, complete badge equality, candidate +bindings, alternating warm samples, plans, and UTF-8 response-value bytes before +Drizzle decoding. This byte count excludes protocol framing. The mixed fixture +covers shared agents, superseding successes, timestamp ties, Mine users, +dismissal equality, private and deleted issues, and more than 200 runs. The +all-failed, all-succeeded, and empty controls expose neutral or slower paths. +Timings describe local SQL work and do not establish hosted request latency. + ### Budget accounting performance Budget admission and settlement share the company accounting lock. They evaluate diff --git a/scripts/benchmark-sidebar-badges.ts b/scripts/benchmark-sidebar-badges.ts new file mode 100644 index 00000000000..6e45bb45a65 --- /dev/null +++ b/scripts/benchmark-sidebar-badges.ts @@ -0,0 +1,104 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { promises as fs } from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { createDb, startEmbeddedPostgresTestDatabase, type Db } from "../packages/db/src/index.js"; +import { sidebarBadgeService } from "../server/src/services/sidebar-badges.js"; +import { captureSidebarQueries, cleanupSidebarFixture, observedSidebarFailures, seedSidebarFixture, type CapturedQuery } from "../server/src/__tests__/helpers/sidebar-badges-fixture.js"; + +const baselineRef = process.argv.find(arg => arg.startsWith("--baseline-ref="))?.slice(15); +assert.ok(baselineRef, "Pass --baseline-ref="); +const baselineRevision = execFileSync("git", ["rev-parse", "--verify", `${baselineRef}^{commit}`], { encoding: "utf8" }).trim(); +const treatmentRevision = execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim(); +const externalUrl = process.env.PAPERCLIP_SIDEBAR_TEST_DATABASE_URL; +assert.ok(!externalUrl || new URL(externalUrl).pathname.endsWith("_test"), "Use a dedicated synthetic *_test database"); +const keepAlive = setInterval(() => {}, 1000); +let database: Awaited> | undefined; +let baselineDir: string | undefined; +let db: Db | undefined; +const fixtures: Awaited>[] = []; +let failure: unknown; +try { + if (!externalUrl) database = await startEmbeddedPostgresTestDatabase("sidebar-benchmark-"); + db = createDb(externalUrl ?? database!.connectionString); + const modulePath = "server/src/services/sidebar-badges.ts"; + const moduleUrl = new URL(`../${modulePath}`, import.meta.url); + const source = execFileSync("git", ["show", `${baselineRevision}:${modulePath}`], { encoding: "utf8" }); + const rewritten = source.replace(/from "(\.{1,2}\/[^\"]+)"/g, + (_match, specifier: string) => `from ${JSON.stringify(fileURLToPath(new URL(specifier, moduleUrl)))}`); + baselineDir = await fs.mkdtemp(path.join(fileURLToPath(new URL("../server/scripts/", import.meta.url)), ".sidebar-baseline-")); + const baselineFile = path.join(baselineDir, "sidebar-badges.ts"); + await fs.writeFile(baselineFile, rewritten); + const baseline = await import(pathToFileURL(baselineFile).href) as typeof import("../server/src/services/sidebar-badges.js"); + const [{ version }] = await db.$client.unsafe("select version()"); + const settings = await db.$client.unsafe("select name, setting from pg_settings where name in ('work_mem', 'shared_buffers', 'jit', 'max_parallel_workers_per_gather')"); + const results = []; + for (const mode of ["mixed", "all-failed", "all-succeeded", "empty"] as const) { + const fixture = await seedSidebarFixture(db, mode); + fixtures.push(fixture); + await db.$client.unsafe("ANALYZE heartbeat_runs"); + await db.$client.unsafe("ANALYZE agents"); + const users = mode === "mixed" ? [undefined, null, "", "user-1", "user-2", "local-board", "nobody"] : [undefined]; + for (const currentUserId of users) { + const queries = { baseline: [] as CapturedQuery[], treatment: [] as CapturedQuery[] }; + const before = baseline.sidebarBadgeService(captureSidebarQueries(db, queries.baseline)); + const after = sidebarBadgeService(captureSidebarQueries(db, queries.treatment)); + const options = { ...fixture.options, currentUserId }; + const baselineResponse = await before.get(fixture.companyId, options); + const treatmentResponse = await after.get(fixture.companyId, options); + assert.deepEqual(treatmentResponse, baselineResponse); + assert.equal(queries.baseline.length, 1); + assert.equal(queries.treatment.length, 1); + const expected = await observedSidebarFailures(db, fixture.companyId, currentUserId); + const normalize = (rows: unknown[][]) => rows.map(row => JSON.stringify(row)).sort(); + const baselineQuery = queries.baseline[0]!, treatmentQuery = queries.treatment[0]!; + const treatmentRows = await db.$client.unsafe(treatmentQuery.sql, treatmentQuery.params as never[]).values(); + if (treatmentQuery.sql !== baselineQuery.sql) { + assert.deepEqual(normalize(treatmentRows.map(row => [...row.slice(0, 3), new Date(String(row[3])).toISOString()])), normalize(expected.map(row => [row.id, row.scopeKind, row.issueId, row.createdAt.toISOString()]))); + } + const samples = { baseline: [] as number[], treatment: [] as number[] }; + const rowsByVersion: Record = {}; + for (let iteration = 0; iteration < 9; iteration++) { + for (const label of iteration % 2 ? ["treatment", "baseline"] as const : ["baseline", "treatment"] as const) { + const query = label === "baseline" ? baselineQuery : treatmentQuery; + const start = performance.now(); + rowsByVersion[label] = await db.$client.unsafe(query.sql, query.params as never[]).values(); + if (iteration >= 2) samples[label].push(performance.now() - start); + } + } + const measurements = []; + for (const label of ["baseline", "treatment"] as const) { + const query = label === "baseline" ? baselineQuery : treatmentQuery; + const rows = rowsByVersion[label]!; + const responseValueBytes = rows.flat().reduce((sum, value) => sum + (value == null ? 0 : Buffer.byteLength(typeof value === "string" ? value : String(value))), 0); + const [plan] = await db.$client.unsafe(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${query.sql}`, query.params as never[]); + const sorted = [...samples[label]].sort((a, b) => a - b); + measurements.push({ label, query, rows: rows.length, responseValueBytes, samplesMs: samples[label], medianMs: sorted[3], minMs: sorted[0], maxMs: sorted[6], plan: plan!["QUERY PLAN"] }); + } + if (process.env.SIDEBAR_REQUIRE_BYTE_REDUCTION === "1" && mode !== "empty") { + assert.ok(measurements[1]!.responseValueBytes < measurements[0]!.responseValueBytes); + } + results.push({ mode, currentUserId: currentUserId === undefined ? "" : currentUserId, equalBadgeResponse: treatmentResponse, equalCandidateRows: expected.length, measurements }); + } + } + console.log(JSON.stringify({ baselineRevision, treatmentRevision, + treatmentDiff: execFileSync("git", ["diff", "--", modulePath], { encoding: "utf8" }), + dependencyPolicy: "Baseline imports unchanged current authorization, privacy, and shared helpers", version, settings, + acceptance: "Identical complete badges and candidate bindings; fewer response-value bytes for nonempty fixtures. Timings are descriptive with no latency threshold.", + byteBoundary: "UTF-8 non-null cell values before Drizzle decoding, excluding PostgreSQL protocol framing; not wire bytes", + results }, null, 2)); +} catch (error) { + failure = error; +} finally { + const errors: unknown[] = failure === undefined ? [] : [failure]; + async function cleanup(action: () => Promise | undefined) { + try { await action(); } catch (error) { errors.push(error); } + } + if (db) for (const fixture of fixtures) await cleanup(() => cleanupSidebarFixture(db!, fixture)); + await cleanup(() => db?.$client.end({ timeout: 0 })); + await cleanup(() => database?.cleanup()); + await cleanup(() => baselineDir ? fs.rm(baselineDir, { recursive: true, force: true }) : undefined); + clearInterval(keepAlive); + if (errors.length) throw new AggregateError(errors, "Sidebar benchmark or cleanup failed"); +} diff --git a/server/src/__tests__/helpers/sidebar-badges-fixture.ts b/server/src/__tests__/helpers/sidebar-badges-fixture.ts new file mode 100644 index 00000000000..7effeb74757 --- /dev/null +++ b/server/src/__tests__/helpers/sidebar-badges-fixture.ts @@ -0,0 +1,127 @@ +import { randomUUID } from "node:crypto"; +import { and, desc, eq, inArray, not, sql } from "drizzle-orm"; +import { agents, approvals, companies, heartbeatRuns, issues, type Db } from "@paperclipai/db"; +import { isHeartbeatRunVisibleInMine, latestFailedRunsByAgent } from "@paperclipai/shared"; +import type { sidebarBadgeService } from "../../services/sidebar-badges.js"; + +export type BadgeOptions = Parameters["get"]>[1]; +export type CapturedQuery = { sql: string; params: unknown[] }; + +export function captureSidebarQueries(db: Db, queries: CapturedQuery[]): Db { + return new Proxy(db, { get(target, key) { + if (key !== "select") return Reflect.get(target, key); + return (...fields: Parameters) => { + const builder = target.select(...fields), from = builder.from.bind(builder); + builder.from = ((...args: Parameters) => { + const selection = from(...args), execute = selection.execute.bind(selection); + selection.execute = async () => { + const query = selection.toSQL(); + if (query.sql.includes('"heartbeat_runs"')) queries.push(query); + return execute(); + }; + return selection; + }) as typeof builder.from; + return builder; + }; + }}); +} + +export async function observedSidebarFailures(db: Db, companyId: string, currentUserId?: string | null) { + const rows = await db.select({ + id: heartbeatRuns.id, agentId: heartbeatRuns.agentId, companyId: heartbeatRuns.companyId, + scopeKind: heartbeatRuns.scopeKind, issueId: heartbeatRuns.issueId, status: heartbeatRuns.status, + responsibleUserId: heartbeatRuns.responsibleUserId, createdAt: heartbeatRuns.createdAt, + }).from(heartbeatRuns).innerJoin(agents, eq(heartbeatRuns.agentId, agents.id)).where(and( + eq(heartbeatRuns.companyId, companyId), eq(agents.companyId, companyId), not(eq(agents.status, "terminated")), + )).orderBy(desc(heartbeatRuns.createdAt)).limit(200); + return latestFailedRunsByAgent(rows).filter(row => currentUserId === undefined || isHeartbeatRunVisibleInMine(row, currentUserId)); +} + +export async function seedSidebarFixture(db: Db, mode: "mixed" | "all-failed" | "all-succeeded" | "empty" = "mixed") { + return db.transaction(async tx => { + const companyId = randomUUID(), foreignCompanyId = randomUUID(); + await tx.insert(companies).values([ + { id: companyId, name: "Synthetic sidebar", issuePrefix: `B${companyId.slice(0, 7)}` }, + { id: foreignCompanyId, name: "Foreign sidebar", issuePrefix: `F${foreignCompanyId.slice(0, 7)}` }, + ]); + const actorId = randomUUID(); + await tx.insert(agents).values({ id: actorId, companyId, name: "Reader", role: "engineer" }); + const actor = { type: "agent" as const, agentId: actorId, companyId }; + const privateIssueId = randomUUID(), publicIssueId = randomUUID(), deletedIssueId = randomUUID(); + await tx.insert(issues).values([ + { id: privateIssueId, companyId, title: "Private", visibility: "private", privacyRootIssueId: privateIssueId, responsibleUserId: "other-user" }, + { id: publicIssueId, companyId, title: "Public" }, + { id: deletedIssueId, companyId, title: "Deleted" }, + ]); + const origin = Date.parse("2026-10-01T00:00:00.000Z"); + const agentIds = Array.from({ length: mode === "all-failed" ? 240 : 30 }, () => randomUUID()); + await tx.insert(agents).values(agentIds.map((id, index) => ({ id, companyId, name: `Agent ${index}`, role: "engineer" }))); + const runs: (typeof heartbeatRuns.$inferInsert)[] = []; + if (mode !== "empty") { + for (let index = 0; index < 420; index++) { + const agentIndex = index % agentIds.length; + runs.push({ id: randomUUID(), companyId, agentId: agentIds[agentIndex]!, + status: mode === "all-failed" ? "failed" : mode === "all-succeeded" ? "succeeded" : ["failed", "timed_out", "succeeded", "running", "queued", "cancelled"][agentIndex % 6], + responsibleUserId: ["user-1", "user-2", null, "", "local-board"][agentIndex % 5], + createdAt: new Date(origin + index), invocationSource: "manual" }); + } + } + const special: Record = {}; + if (mode === "mixed") { + async function add(name: string, values: Partial = {}) { + const agentId = randomUUID(), id = randomUUID(); + await tx.insert(agents).values({ id: agentId, companyId, name, role: "engineer" }); + runs.push({ id, companyId, agentId, status: "failed", responsibleUserId: "user-1", createdAt: new Date(origin + 1000 + runs.length), ...values }); + special[name] = id; + return agentId; + } + await add("outside-window", { createdAt: new Date(origin - 1000) }); + const shared = await add("superseded"); + runs.push({ companyId, agentId: shared, status: "succeeded", responsibleUserId: "user-2", createdAt: new Date(origin + 2000) }); + const foreignOwner = await add("other-user-latest"); + runs.push({ companyId, agentId: foreignOwner, status: "failed", responsibleUserId: "user-2", createdAt: new Date(origin + 2001) }); + await add("private", { scopeKind: "issue", issueId: privateIssueId }); + await add("public", { scopeKind: "issue", issueId: publicIssueId }); + await add("deleted", { scopeKind: "issue", issueId: deletedIssueId }); + await add("missing", { scopeKind: "issue", issueId: null }); + await add("dismissed"); + for (const [name, status] of [["tied-failure-first", "failed"], ["tied-success-first", "succeeded"]] as const) { + const agentId = await add(name, { status, createdAt: new Date(origin + 3000) }); + runs.push({ companyId, agentId, status: status === "failed" ? "succeeded" : "failed", responsibleUserId: "user-1", createdAt: new Date(origin + 3000) }); + } + const terminated = randomUUID(), crossCompanyAgent = randomUUID(); + await tx.insert(agents).values([ + { id: terminated, companyId, name: "Terminated", status: "terminated" }, + { id: crossCompanyAgent, companyId: foreignCompanyId, name: "Foreign" }, + ]); + for (let index = 0; index < 220; index++) runs.push({ companyId, agentId: index % 2 ? terminated : crossCompanyAgent, + status: "failed", responsibleUserId: "user-1", createdAt: new Date(origin + 10000 + index) }); + runs.push({ companyId: foreignCompanyId, agentId: crossCompanyAgent, status: "failed", createdAt: new Date(origin + 20000) }); + } + if (runs.length) await tx.insert(heartbeatRuns).values(runs); + if (mode === "mixed") { + await tx.delete(issues).where(eq(issues.id, deletedIssueId)); + const microAgent = randomUUID(); + await tx.insert(agents).values({ id: microAgent, companyId, name: "Submillisecond" }); + await tx.execute(sql`insert into heartbeat_runs (company_id, agent_id, status, responsible_user_id, created_at) values + (${companyId}, ${microAgent}, 'failed', 'user-1', '2026-10-01 00:00:04.000100+00'), + (${companyId}, ${microAgent}, 'succeeded', 'user-2', '2026-10-01 00:00:04.000900+00')`); + } + const approvalId = randomUUID(); + await tx.insert(approvals).values({ id: approvalId, companyId, type: "hire_agent", status: "pending", payload: {}, updatedAt: new Date(origin) }); + const dismissals = new Map([[`approval:${approvalId}`, origin]]); + const dismissed = runs.find(row => row.id === special.dismissed); + if (dismissed) dismissals.set(`run:${dismissed.id}`, (dismissed.createdAt as Date).getTime()); + return { companyId, foreignCompanyId, actor, actorId, privateIssueId, publicIssueId, special, dismissals, + options: { dismissals, joinRequests: [{ id: "join", createdAt: new Date(origin), updatedAt: null }], unreadTouchedIssues: 2, actor } satisfies BadgeOptions }; + }); +} + +export async function cleanupSidebarFixture(db: Db, fixture: Awaited>) { + const companyIds = [fixture.companyId, fixture.foreignCompanyId]; + await db.delete(heartbeatRuns).where(inArray(heartbeatRuns.companyId, companyIds)); + await db.delete(approvals).where(inArray(approvals.companyId, companyIds)); + await db.delete(issues).where(inArray(issues.companyId, companyIds)); + await db.delete(agents).where(inArray(agents.companyId, companyIds)); + await db.delete(companies).where(inArray(companies.id, companyIds)); +} diff --git a/server/src/__tests__/sidebar-badges.test.ts b/server/src/__tests__/sidebar-badges.test.ts new file mode 100644 index 00000000000..9830424dde9 --- /dev/null +++ b/server/src/__tests__/sidebar-badges.test.ts @@ -0,0 +1,139 @@ +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { count, eq, inArray } from "drizzle-orm"; +import { agents, approvals, companies, createDb, getEmbeddedPostgresTestSupport, heartbeatRuns, issueAccessGrants, issues, startEmbeddedPostgresTestDatabase, type Db } from "@paperclipai/db"; +import { sidebarBadgeService } from "../services/sidebar-badges.js"; +import { authorizationService } from "../services/authorization.js"; +import { getHeartbeatRunReadDecisions } from "../services/heartbeat-run-privacy.js"; +import { captureSidebarQueries, cleanupSidebarFixture, observedSidebarFailures, seedSidebarFixture, type BadgeOptions, type CapturedQuery } from "./helpers/sidebar-badges-fixture.js"; + +const externalUrl = process.env.PAPERCLIP_SIDEBAR_TEST_DATABASE_URL; +const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); +const describePostgres = support.supported ? describe : describe.skip; +if (!support.supported) console.warn(`Skipping sidebar badge SQL tests: ${support.reason}`); + +describePostgres("sidebar badge failure candidates", () => { + let db: ReturnType; + let database: Awaited> | undefined; + const fixtures: Awaited>[] = []; + let fixture: Awaited>; + + beforeAll(async () => { + if (externalUrl && !new URL(externalUrl).pathname.endsWith("_test")) throw new Error("Use a dedicated synthetic *_test database"); + if (!externalUrl) database = await startEmbeddedPostgresTestDatabase("sidebar-badges-"); + db = createDb(externalUrl ?? database!.connectionString, { maxConnections: 1 }); + fixture = await seedSidebarFixture(db); + fixtures.push(fixture); + }, 90_000); + + afterAll(async () => { + const errors: unknown[] = []; + async function cleanup(action: () => Promise | undefined) { + try { await action(); } catch (error) { errors.push(error); } + } + for (const entry of fixtures) await cleanup(() => cleanupSidebarFixture(db, entry)); + await cleanup(() => db?.$client.end({ timeout: 0 })); + await cleanup(() => database?.cleanup()); + if (errors.length) throw new AggregateError(errors, "Sidebar test cleanup failed"); + }); + + async function verify(options?: BadgeOptions) { + const queries: CapturedQuery[] = []; + const actual = await sidebarBadgeService(captureSidebarQueries(db, queries)).get(fixture.companyId, options); + const expectedCandidates = await observedSidebarFailures(db, fixture.companyId, options?.currentUserId); + const candidates = await db.$client.unsafe(queries[0]!.sql, queries[0]!.params as never[]).values(); + const normalize = (rows: unknown[][]) => rows.map(row => JSON.stringify(row)).sort(); + expect(normalize(candidates.map(row => [...row.slice(0, 3), new Date(String(row[3])).toISOString()]))).toEqual(normalize( + expectedCandidates.map(row => [row.id, row.scopeKind, row.issueId, row.createdAt.toISOString()]), + )); + expect(expectedCandidates.map(row => row.id)).not.toContain(fixture.special.superseded); + expect(expectedCandidates.map(row => row.id)).not.toContain(fixture.special["outside-window"]); + const undismissed = expectedCandidates.filter(row => (options?.dismissals?.get(`run:${row.id}`) ?? -Infinity) < row.createdAt.getTime()); + const failedRuns = options?.actor + ? (await getHeartbeatRunReadDecisions(db, authorizationService(db), options.actor, undismissed)).filter(Boolean).length + : undismissed.length; + const approvals = options?.dismissals ? 0 : 1; + const joinRequests = options?.joinRequests?.length ?? 0; + expect(actual).toEqual({ inbox: approvals + failedRuns + joinRequests + (options?.unreadTouchedIssues ?? 0), approvals, failedRuns, joinRequests }); + return actual; + } + + it("rolls back all fixture rows when the final approval insert fails", async () => { + let companyIds: string[] = []; + let writtenRuns = 0; + function failLastInsert>(connection: T): T { + return new Proxy(connection, { get(target, key) { + if (key !== "insert") return Reflect.get(target, key); + return (table: Parameters[0]) => { + if (table === companies) return { values: (values: (typeof companies.$inferInsert)[]) => { + companyIds = values.map(row => row.id!); + fixtures.push({ ...fixture, companyId: companyIds[0]!, foreignCompanyId: companyIds[1]! }); + return target.insert(companies).values(values); + }}; + if (table === approvals) return { values: async (values: typeof approvals.$inferInsert) => { + const [row] = await target.select({ value: count() }).from(heartbeatRuns).where(inArray(heartbeatRuns.companyId, companyIds)); + writtenRuns = row!.value; + return target.insert(approvals).values({ ...values, payload: null as never }); + }}; + return target.insert(table); + }; + }}); + } + const failingDb = new Proxy(failLastInsert(db), { get(target, key) { + if (key !== "transaction") return Reflect.get(target, key); + return (callback: Parameters[0]) => db.transaction(tx => callback(failLastInsert(tx))); + }}); + await expect(seedSidebarFixture(failingDb)).rejects.toMatchObject({ cause: { code: "23502" } }); + expect(companyIds).toHaveLength(2); + expect(writtenRuns).toBeGreaterThan(600); + const rows = await Promise.all([ + db.select({ value: count() }).from(companies).where(inArray(companies.id, companyIds)), + db.select({ value: count() }).from(agents).where(inArray(agents.companyId, companyIds)), + db.select({ value: count() }).from(issues).where(inArray(issues.companyId, companyIds)), + db.select({ value: count() }).from(heartbeatRuns).where(inArray(heartbeatRuns.companyId, companyIds)), + db.select({ value: count() }).from(approvals).where(inArray(approvals.companyId, companyIds)), + ]); + expect(rows.map(([row]) => row!.value)).toEqual([0, 0, 0, 0, 0]); + }); + + it.each([undefined, null, "", "user-1", "user-2", "local-board", "nobody"])("keeps the bounded latest run before Mine filtering for %s", async currentUserId => { + await verify({ ...fixture.options, currentUserId }); + }); + + it("retains company-wide behavior without an actor or options", async () => { + await verify(); + await verify({ ...fixture.options, actor: undefined }); + await verify({ ...fixture.options, actor: { type: "none" } }); + }); + + it("rechecks private issue grants and deletion on every request", async () => { + const service = sidebarBadgeService(db); + const options = { ...fixture.options, currentUserId: "user-1" }; + const denied = await service.get(fixture.companyId, options); + const [grant] = await db.insert(issueAccessGrants).values({ issueId: fixture.privateIssueId, subjectType: "agent", subjectId: fixture.actorId, source: "explicit" }).returning(); + const allowed = await service.get(fixture.companyId, options); + expect(allowed.failedRuns).toBe(denied.failedRuns + 1); + await db.update(issueAccessGrants).set({ revokedAt: new Date() }).where(eq(issueAccessGrants.id, grant!.id)); + expect(await service.get(fixture.companyId, options)).toEqual(denied); + await db.delete(issues).where(eq(issues.id, fixture.publicIssueId)); + expect((await service.get(fixture.companyId, options)).failedRuns).toBe(denied.failedRuns - 1); + await verify(options); + }); + + it("preserves equal-time input order with index and sort plans", async () => { + await db.$client.unsafe("SET enable_indexscan = off"); + await db.$client.unsafe("SET enable_bitmapscan = off"); + try { await verify(fixture.options); } + finally { + await db.$client.unsafe("RESET enable_indexscan"); + await db.$client.unsafe("RESET enable_bitmapscan"); + } + }); + + it.each(["all-failed", "all-succeeded", "empty"] as const)("handles the %s control", async mode => { + const control = await seedSidebarFixture(db, mode); + fixtures.push(control); + const response = await sidebarBadgeService(db).get(control.companyId); + const failedRuns = mode === "all-failed" ? 200 : 0; + expect(response).toEqual({ inbox: failedRuns + 1, approvals: 1, failedRuns, joinRequests: 0 }); + }); +}); diff --git a/server/src/services/sidebar-badges.ts b/server/src/services/sidebar-badges.ts index 4f0249043c2..80348af686a 100644 --- a/server/src/services/sidebar-badges.ts +++ b/server/src/services/sidebar-badges.ts @@ -1,7 +1,7 @@ -import { and, desc, eq, inArray, not, type SQL } from "drizzle-orm"; +import { and, desc, eq, inArray, isNull, not, or, sql, type SQL } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { agents, approvals, heartbeatRuns } from "@paperclipai/db"; -import { isHeartbeatRunVisibleInMine, latestFailedRunsByAgent, type SidebarBadges } from "@paperclipai/shared"; +import type { SidebarBadges } from "@paperclipai/shared"; import { authorizationService, type AuthorizationActor } from "./authorization.js"; import { getHeartbeatRunReadDecisions } from "./heartbeat-run-privacy.js"; @@ -51,11 +51,10 @@ export function sidebarBadgeService(db: Db) { rows.filter((row) => !isDismissed(extra?.dismissals ?? new Map(), `approval:${row.id}`, row.updatedAt)).length ); - const recentRuns = await db + const recentRuns = db .select({ id: heartbeatRuns.id, agentId: heartbeatRuns.agentId, - companyId: heartbeatRuns.companyId, scopeKind: heartbeatRuns.scopeKind, issueId: heartbeatRuns.issueId, status: heartbeatRuns.status, @@ -72,14 +71,50 @@ export function sidebarBadgeService(db: Db) { ), ) .orderBy(desc(heartbeatRuns.createdAt)) - .limit(200); + .limit(200) + .as("recent_runs"); - const failures = latestFailedRunsByAgent(recentRuns).filter((row) => - (extra?.currentUserId === undefined || isHeartbeatRunVisibleInMine(row, extra.currentUserId)) - && !isDismissed(extra?.dismissals ?? new Map(), `run:${row.id}`, row.createdAt), + const observedRuns = db.select({ + id: recentRuns.id, + agentId: recentRuns.agentId, + scopeKind: recentRuns.scopeKind, + issueId: recentRuns.issueId, + status: recentRuns.status, + responsibleUserId: recentRuns.responsibleUserId, + createdAt: recentRuns.createdAt, + observedOrder: sql`row_number() over ()`.as("observed_order"), + }).from(recentRuns).as("observed_runs"); + const rankedRuns = db.select({ + id: observedRuns.id, + scopeKind: observedRuns.scopeKind, + issueId: observedRuns.issueId, + status: observedRuns.status, + responsibleUserId: observedRuns.responsibleUserId, + createdAt: observedRuns.createdAt, + agentRunRank: sql`row_number() over (partition by ${observedRuns.agentId} order by ${observedRuns.createdAt} desc, ${observedRuns.observedOrder})`.as("agent_run_rank"), + }).from(observedRuns).as("ranked_runs"); + const mineCondition = extra?.currentUserId === undefined + ? undefined + : !extra.currentUserId + ? sql`false` + : extra.currentUserId === "local-board" + ? or(eq(rankedRuns.responsibleUserId, "local-board"), isNull(rankedRuns.responsibleUserId), eq(rankedRuns.responsibleUserId, "")) + : eq(rankedRuns.responsibleUserId, extra.currentUserId); + const candidates = await db.select({ + id: rankedRuns.id, + scopeKind: rankedRuns.scopeKind, + issueId: rankedRuns.issueId, + createdAt: rankedRuns.createdAt, + }).from(rankedRuns).where(and( + eq(rankedRuns.agentRunRank, 1), + inArray(rankedRuns.status, ["failed", "timed_out"]), + mineCondition, + )); + const failures = candidates.filter((row) => + !isDismissed(extra?.dismissals ?? new Map(), `run:${row.id}`, row.createdAt), ); const failedRuns = extra?.actor - ? (await getHeartbeatRunReadDecisions(db, authorization, extra.actor, failures)).filter(Boolean).length + ? (await getHeartbeatRunReadDecisions(db, authorization, extra.actor, failures.map((row) => ({ ...row, companyId })))).filter(Boolean).length : failures.length; const joinRequests = (extra?.joinRequests ?? []).filter((row) => From f6bc653f7f745adaafa26393852fb2f5a99256a4 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:33:30 -0500 Subject: [PATCH 7/7] fix(server): schedule interrupted tool claims by their deadlines (#17458) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip governs tool execution and keeps durable approval records. > - An interrupted execution may have produced an external effect without a saved final request state. > - The maintenance tick currently scans executing requests even when none exist. > - Every executing claim already has a ten-minute stale deadline. > - This PR schedules that deadline from committed claim changes and clears it after settlement. > - Recovery preserves saved provider outcomes and quarantines unknown outcomes without another provider call. ## Linked Issues or Issue Description Refs #17454. This is the sixth recurring-server sleep slice, stacked on `codex/sleep-05-approved-tool-recovery`. **Problem** The aggregate maintenance tick repeatedly searches for stale executing tool requests. Its settlement can overwrite a saved successful invocation with an unknown-outcome failure after a crash between invocation and request writes. **Proposed Solution** Use the existing review notification boundary and shared scheduler. Read the earliest executing claim deadline through a partial index. At that deadline, lock invocation then request, recheck claim identity, and atomically settle from the saved outcome or quarantine the unknown outcome. **Alternatives Considered** A longer polling interval still queries empty work. A new queue would duplicate existing records. Replaying an interrupted call can duplicate an external effect. Treating every stale request as unknown discards already saved outcomes. ## What Changed - Coalesce sequential review notifications for up to 30 seconds while preserving already loaded recovery deadlines. Do not schedule scans when no notification or execution deadline remains. - Extract interrupted-execution deadline lookup and settlement into the owning tool-review service. - Register its worker at startup. Use committed claim/result changes to update the existing ten-minute deadline; retry failed settlement after 30 seconds. - Preserve terminal invocation results, reasons, and completion times when repairing request state. - Settle uncertain request/invocation state atomically with the existing unknown-outcome reason, without dispatching a provider call. - Notify all gateway claim and settlement paths through the existing review transaction helper. Keep framework wiring and the shared scheduler free of provider-specific behavior. - Add an idempotent concurrent partial index for executing deadlines. Preserve the combined manual sweep and scheduler-disabled startup pass. - Remove interrupted scanning from the aggregate tick. Interaction projection repair remains the next separate duty. ## Verification Current head: `648d8a9a64ded15deeeb331545b92a12d69e277d`. The final commit changes no files and requests CI after the master retarget. A preceding run appeared while that trigger was being published; it was observational delay, not an established CI outage. No test rerun or bypass was used to turn a failure green. Source remains identical to the 198-test passing integration, apart from the already recorded ledger update. Fresh checks and both automated reviews must qualify this current head before merge. Current master-targeted head: `d55e44b376555e4926bb2c2a0e4dcfb431324162`. Parent #17454 landed as `77295faebc8`; a normal merge reconciles that squash. Every conflicted master file was checked against the already-integrated parent, and all matched byte-for-byte. Each interruption-only hunk was retained; the complete integrated source tree matched the 198-test passing `848f1b87b3` exactly before the sole final documentation update. All master migration journal entries are unchanged, with only this PR's executing-deadline index appended. Server types pass. Fresh CI and current-head Greptile/Ponytail are required before the next authorized merge. Latest published integration: `848f1b87b3a6646ae4e56e8ab142f64889d7a69c`, normally merging approved-recovery parent `23868c1751`. All 198 gateway/interruption/startup/deadline cases and server production typechecking pass. Both parent approval fixes and all interruption tests are retained. The two merge conflicts preserved the interruption import alongside the parent's claim-bound hash helper and preserved the parameterized historical test helpers. This remains stacked on #17454; fresh CI and both automated review gates are required after integration. - Review documentation correction at `c985eb9d1b48a481909de6a1c2d89d7af11bfc03`: the focused real-PostgreSQL interruption-worker selection passes all 16 cases; 124 unrelated cases were filtered out. The docs now correctly name 16 cases and six saved terminal statuses. No production behavior changed in the correction. Fresh remote CI/review is pending after integrating the verified parent. Approved delegated Test-tab calls now evaluate caller and target policies in the existing claim transaction. Real HTTP regressions first showed a missing caller charge and shared-limit self-rejection. All 78 connection-management cases and 92 gateway cases now pass on the owning branch, along with server production typechecking. All 78 connection-management cases also pass at combined tip `d25f830db89c1623bff3547bfc68015c1c66e0cf`. The three new cases cover shared charges, separate charges, rollback on denial, duplicate approval, and rejection of a later authorized call. Intermediate counter/identity fixture failures and a reused-database Slack collision are recorded in [the owning audit](https://github.com/paperclipai/paperclip/blob/f6a5949fb726f71c247950714adecb275655284f/doc/idle-approved-tool-recovery.md#delegated-test-tab-admission-after-policy-changes). The earlier combined checks below remain evidence for their stated revisions. Current-head CI and review remain required. Current head: `f6a5949fb726f71c247950714adecb275655284f`. This remains a single-duty PR stacked on #17454. - 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-24-recurring-server-sleep-stack.md](https://github.com/paperclipai/paperclip/blob/eaac8d343e5ef4d2c13cdf7cb7607cb5a498e9a2/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 - Signals cover the existing single-active-writer database owner. Independent writers and replicas need an explicit wake contract. - The ten-minute policy is unchanged. A provider call that outlives its claim remains an uncertain outcome; this worker never retries the external call. - Interaction projection follows authoritative settlement outside its transaction. Its separate existing repair duty still handles an interrupted projection. - Non-executing review writes can cause one empty reconciliation. Without an executing claim or failed attempt, no recurring deadline remains. - Cloud eligibility and external-alarm coverage remain conservative. Worker quiet does not prove actual host or database suspension. ## 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-interrupted-tool-recovery.md | 116 ++++++++ ...2026-10-24-recurring-server-sleep-stack.md | 52 +++- packages/db/src/client.ts | 1 + .../src/migrations/0385_open_madame_web.sql | 1 + ...{0380_snapshot.json => 0385_snapshot.json} | 101 ++++++- packages/db/src/migrations/meta/_journal.json | 7 + packages/db/src/schema/tool_access.ts | 1 + .../server-startup-feedback-export.test.ts | 2 + .../__tests__/tool-gateway-service.test.ts | 253 ++++++++++++++++++ server/src/index.ts | 11 +- .../services/delivery-work-notifications.ts | 1 + server/src/services/tool-gateway.ts | 90 ++----- .../services/tool-review-interruption-work.ts | 16 ++ .../src/services/tool-review-interruption.ts | 61 +++++ .../tool-review-work-notifications.ts | 1 + 15 files changed, 643 insertions(+), 71 deletions(-) create mode 100644 doc/idle-interrupted-tool-recovery.md create mode 100644 packages/db/src/migrations/0385_open_madame_web.sql rename packages/db/src/migrations/meta/{0380_snapshot.json => 0385_snapshot.json} (99%) create mode 100644 server/src/services/tool-review-interruption-work.ts create mode 100644 server/src/services/tool-review-interruption.ts diff --git a/doc/idle-interrupted-tool-recovery.md b/doc/idle-interrupted-tool-recovery.md new file mode 100644 index 00000000000..c02ecdd97ec --- /dev/null +++ b/doc/idle-interrupted-tool-recovery.md @@ -0,0 +1,116 @@ +# Interrupted tool-action recovery + +An executing tool-action request has an existing ten-minute stale deadline from +its `updatedAt` claim timestamp. Recovery now registers the earliest actual +claim deadline with the shared scheduler. It no longer scans executing requests +on every aggregate maintenance tick. + +## Ownership and producers + +The gateway owns execution claims, provider calls, and result settlement. The +new interruption service owns only the deadline query and stale-row settlement. +The worker uses the existing deadline registration and exposes no provider +protocol or signed argument representation to the scheduler. + +The review write helper signals interruption alongside approved recovery and +pending expiry. All three agent claim paths and the Test-tab claim use that +helper. Test-tab outcomes already commit both rows inside it. Agent pre-dispatch +and execution failure settlement uses the same notification transaction, and +successful or failed direct execution request updates now notify before writing. +Administrative review transitions continue to use the same existing boundary. + +Unrelated pending review changes can cause a bounded empty reconciliation. They +do not create a periodic deadline. Process-local signals cover the existing +single-active-writer database owner; independent writers require a wake contract. + +## Settlement and quiet states + +The query uses a partial executing-request index and reads one earliest row. +There is no deadline after all executing claims settle. Retained terminal +requests and configured-but-idle tools produce no recurring worker queries. + +At the deadline, settlement locks invocation then request, matching the existing +execution-failure lock order. It rechecks the claim status and timestamp after +locking. A changed or completed claim cannot be settled from an earlier scan. +Unknown outcomes atomically mark both rows failed with +`tool_execution_outcome_unknown`. Recovery never calls the external provider. + +A saved terminal invocation is authoritative. Recovery repairs its request to +executed or failed without replacing the saved result, failure reason, or +completion time with an unknown-outcome failure. This covers a crash between +legacy invocation completion and request settlement. Interaction projection +runs after the transaction through the existing gateway owner. A failed +projection still relies on the separate projection-repair duty. + +A database failure rolls back both outcome rows and retains a 30-second retry. +Startup reconstructs saved deadlines. Drain pauses dispatch without forgetting +the first claim or failed retry; resume processes overdue claims. Completion +notifications cancel unnecessary future scans. The scheduler-disabled path keeps +one startup pass. The public combined review sweep retains its existing duties. + +## Verification and limits + +Sixteen new real-PostgreSQL cases cover real foreground execution activation +and completion, configured idle and terminal history, restart/deadline timing, +six saved terminal invocation states, first-write drain/resume, outer commit and +rollback, transactional failure/retry, concurrent claim change, and multi-page +settlement. The service/startup selection passes 136 tests on the combined parent-review +head. Workspace typecheck/build and migration safety checks pass on that head. +Migration application and reapplication passed. The combined run also exercised +469 tool-access tests: 468 passed and an unchanged connection-archive case timed +out under concurrent build load. That case passes in isolation. The separate full tool-access suite passes all +469 tests and gateway acceptance passes all 92 (697 across the final selections). +Fresh full CI/review remains required. + +The first typecheck caught optional approval IDs losing narrowing in transaction +callbacks; capturing them before the callback fixes it. Two new fault/transaction +cases initially waited for idle before advancing their next fake-clock retry. +They now advance time while waiting for the authoritative outcome, and the full +selection passes. These are fixture corrections, not permission to clear an +unresolved work hold. + +The ten-minute policy is unchanged. Active provider execution, unknown external +outcomes, and other worker obligations still prevent unsafe sleep. No Cloud +eligibility or external-alarm coverage changes here. Worker quiet is not evidence +of whole-instance or database suspension. + +## Sequential-write cost correction (October 27) + +Review found that sequential tenant writes could each request a global +interruption pass, even when no execution was stale. A real-SQL regression +created ten tool review requests through the gateway and allowed each preceding +pass to finish. It measured 11 stale-claim scans including startup. Concurrent +notification coalescing alone did not cover this sequence. + +The worker now uses the existing deadline helper's 30-second notification +coalescing window, matching the former default maintenance cadence. The same +regression measures one startup scan and one follow-up scan for those ten +requests, then no worker SQL through an additional idle hour. A loaded stale +claim deadline only 500 milliseconds away still preempts the window and +quarantines the unknown outcome without invoking the provider. Foreground +execution and result settlement remain immediate. Newly discovered work can +wait up to this window; the ten-minute stale-claim policy is unchanged. + +This is the bounded-frequency alternative raised in review. Discovery is still +instance-wide, and real stale backlogs still drain through the existing pages. +It does not claim company-isolated scans or constant cost for a real backlog. +No notification and no saved execution deadline means no periodic scan. No new +table, index, or scheduler is added. Startup, drain, retry and shutdown retain +the existing owners. + +The first full verification passed 175 cases and failed three fake-clock waits: +settlement writes leave a notification pending for its coalesced follow-up, so +waiting for the idle hold without advancing that armed deadline cannot finish. +An initial shared clock adjustment then advanced an unrelated five-second +expiry test too far (177 passed, one failed). The adjustment is now confined to +the interruption tests. It lets real SQL finish and advances only to an actually +armed short follow-up. The imminent-deadline test checks quarantine before that +30-second window and separately waits for eventual quiet. Product assertions +were retained. + +The final complete gateway-service and startup-wiring suites pass all 178 cases +without skips, and server typechecking passes, on owner source based on +`e255d8eff3363cf0bb63541bdc7ef055d4321f83`. The attempted third test selector +`deadline-work.test.ts` did not exist at this owner; no separate helper-suite +pass is claimed. The shared helper is exercised by the full gateway suites. +Fresh combined-source checks and remote review remain required. 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 b699f1b242d..b8976fb34fb 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 proposals: [#17446](https://github.com/paperclipai/paperclip/pull/17446), merged; gateway credentials: [#17450](https://github.com/paperclipai/paperclip/pull/17450), merged; pending tool-review expiry: [#17453](https://github.com/paperclipai/paperclip/pull/17453), merged; approved recovery: [#17454](https://github.com/paperclipai/paperclip/pull/17454), historical argument identity repair verified and awaiting fresh CI/review; other review duties pending | +| 07 | Secret proposals, tool reviews, gateway tokens | Separate expiry/scrub/recovery owners | Secret proposals: [#17446](https://github.com/paperclipai/paperclip/pull/17446), merged; gateway credentials: [#17450](https://github.com/paperclipai/paperclip/pull/17450), merged; pending tool-review expiry: [#17453](https://github.com/paperclipai/paperclip/pull/17453), merged; approved recovery: [#17454](https://github.com/paperclipai/paperclip/pull/17454), merged after current-head CI and both 5/5 reviews; interrupted claims: [#17458](https://github.com/paperclipai/paperclip/pull/17458), integration verified and awaiting fresh CI/review; projection: [#17468](https://github.com/paperclipai/paperclip/pull/17468), interaction-link index verified and awaiting fresh CI/review | | 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 | @@ -230,3 +230,53 @@ tool-access service tests pass after enabling the existing external database path independently of embedded support. Its initial browser shard failed during unrelated plan-task fixture company deletion with a concurrent activity-log FK violation. Inspect fresh-head CI before deciding whether that needs a repair. + + +## Slice 06: interrupted tool executions + +Branch `codex/sleep-06-interrupted-tool-recovery` is based on #17454 and includes +its one-shot outcome-write repair. The next deadline is the minimum executing +claim timestamp plus the existing ten minutes. The new service locks invocation +then request, rechecks claim identity, preserves saved terminal outcomes, and +atomically quarantines unknown outcomes without calling a provider. All claim +producers and request settlements use the existing review notification boundary. +A partial index supports the first deadline. The aggregate tick now excludes +interrupted claims; projection repair remains its own pending slice. + +Sixteen new worker cases and the existing service/startup selection pass +(136 total on the combined head). Workspace typecheck/build and migration checks +pass. Two fake-clock fixture ordering failures were corrected to wait for real +settlement while advancing retry time. The combined tool-access run had one +unchanged connection-archive timeout; it passed in isolation. The full suite +and gateway acceptance are running separately before readiness is claimed. +No PR is claimed ready until fresh CI and review pass. + +## Next owner audit: tool-review interaction projection + +The remaining aggregate tool-review duty selects terminal requests whose +interaction result does not match the authoritative request state. Recovery +currently reads up to 100 joined rows. Move this duty to its own transaction- +notified worker, with retries only while projection debt remains. Do not add +an outbox table merely to migrate the scan. + +Audit the final two direct request writers in the gateway as well as existing +review helpers, expiry, interruption, and Test-tab outcome settlement. Preserve +the existing reflection owner: it locks issue/interaction/request, checks the +current request state before writing the card, then publishes activity and +requests continuation. A no-op reflection can mean an ownership or lifecycle +condition, not successful reconciliation. Retained terminal requests with +already matching cards must be quiet. Unprojectable/mismatched durable state +must not be silently dropped. Paginate without starving later candidates. + +Continuation delivery already has its own coordinator. A projection write is +not proof that downstream delivery or activity publication completed. Identify +the exact existing recovery owner before removing any backstop, and keep +provider/private payload interpretation out of the scheduler. + +Final slice-06 local verification: the isolated tool-access rerun passes all +469 tests, gateway acceptance passes 92, and the combined service/startup +selection passed 136. All 697 selected tests pass on the combined head. The +initial concurrent-run timeout is retained above as evidence, not hidden. +Workspace typecheck/build and migration safety/numbering pass. The first four +PRs are mergeable and have all checks passed at their recorded heads. #17454 +is mergeable with fresh checks and review in progress at `7a1cf03e62`. diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index b3d66e14855..3e4cce15e2e 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -503,6 +503,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([ "0369_late_logan.sql", "0381_mean_scream.sql", "0382_narrow_the_executioner.sql", + "0385_open_madame_web.sql", "0384_funny_adam_warlock.sql", "0383_tool_review_company_expiry.sql", ]); diff --git a/packages/db/src/migrations/0385_open_madame_web.sql b/packages/db/src/migrations/0385_open_madame_web.sql new file mode 100644 index 00000000000..19ce52b5cdb --- /dev/null +++ b/packages/db/src/migrations/0385_open_madame_web.sql @@ -0,0 +1 @@ +CREATE INDEX CONCURRENTLY IF NOT EXISTS "tool_action_requests_executing_deadline_idx" ON "tool_action_requests" USING btree ("updated_at","id") WHERE "tool_action_requests"."status" = 'executing'; \ No newline at end of file diff --git a/packages/db/src/migrations/meta/0380_snapshot.json b/packages/db/src/migrations/meta/0385_snapshot.json similarity index 99% rename from packages/db/src/migrations/meta/0380_snapshot.json rename to packages/db/src/migrations/meta/0385_snapshot.json index 5e635e8be52..5564d696be5 100644 --- a/packages/db/src/migrations/meta/0380_snapshot.json +++ b/packages/db/src/migrations/meta/0385_snapshot.json @@ -1,6 +1,6 @@ { - "id": "bfda87fa-662b-47bb-87c0-dabc814aebd7", - "prevId": "2a9439e3-4a2b-4a20-ab2b-2aee3db8cb03", + "id": "9965d300-e355-4f47-ba0a-951ed3b4b8a2", + "prevId": "4f96f70a-fd19-4d35-ad8a-8d5559b83cbd", "version": "7", "dialect": "postgresql", "tables": { @@ -52812,6 +52812,88 @@ "method": "btree", "with": {} }, + "tool_action_requests_pending_expiry_idx": { + "name": "tool_action_requests_pending_expiry_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_action_requests\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_action_requests_company_pending_expiry_idx": { + "name": "tool_action_requests_company_pending_expiry_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_action_requests\".\"status\" = 'pending'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_action_requests_executing_deadline_idx": { + "name": "tool_action_requests_executing_deadline_idx", + "columns": [ + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_action_requests\".\"status\" = 'executing'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "tool_action_requests_approved_idx": { + "name": "tool_action_requests_approved_idx", + "columns": [ + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"tool_action_requests\".\"status\" = 'approved'", + "concurrently": false, + "method": "btree", + "with": {} + }, "tool_action_requests_invocation_idx": { "name": "tool_action_requests_invocation_idx", "columns": [ @@ -55222,6 +55304,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": [ diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 6b79f74c167..f4cfed69f11 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -2682,6 +2682,13 @@ "when": 1793060791728, "tag": "0384_funny_adam_warlock", "breakpoints": true + }, + { + "idx": 385, + "version": "7", + "when": 1793060791729, + "tag": "0385_open_madame_web", + "breakpoints": true } ] } diff --git a/packages/db/src/schema/tool_access.ts b/packages/db/src/schema/tool_access.ts index f1e788626e3..9f79743d6c3 100644 --- a/packages/db/src/schema/tool_access.ts +++ b/packages/db/src/schema/tool_access.ts @@ -836,6 +836,7 @@ export const toolActionRequests = pgTable( .where(sql`${table.status} = 'pending'`), index("tool_action_requests_company_pending_expiry_idx").on(table.companyId, table.expiresAt) .where(sql`${table.status} = 'pending'`), + index("tool_action_requests_executing_deadline_idx").on(table.updatedAt, table.id).where(sql`${table.status} = 'executing'`), index("tool_action_requests_approved_idx").on(table.id).where(sql`${table.status} = 'approved'`), index("tool_action_requests_invocation_idx").on(table.invocationId), index("tool_action_requests_issue_idx").on(table.companyId, table.issueId), diff --git a/server/src/__tests__/server-startup-feedback-export.test.ts b/server/src/__tests__/server-startup-feedback-export.test.ts index 658f5c418ff..1a9fcf51576 100644 --- a/server/src/__tests__/server-startup-feedback-export.test.ts +++ b/server/src/__tests__/server-startup-feedback-export.test.ts @@ -69,6 +69,8 @@ const { stop: vi.fn(async () => {}), }, toolGateway: { + settleInterruptedActionReviews: vi.fn(async () => ({ scanned: 0 })), + nextActionReviewInterruptionAt: vi.fn(async () => null), recoverApprovedActionReviews: vi.fn(async () => ({ scanned: 0, retry: false })), approvedActionReviewCompanies: vi.fn(async () => []), sweepActionReviews: vi.fn(async () => ({ scanned: 0 })), diff --git a/server/src/__tests__/tool-gateway-service.test.ts b/server/src/__tests__/tool-gateway-service.test.ts index 4a014b22ab0..35dabccbe22 100644 --- a/server/src/__tests__/tool-gateway-service.test.ts +++ b/server/src/__tests__/tool-gateway-service.test.ts @@ -1,3 +1,5 @@ +import { registerToolReviewInterruptionWork } from "../services/tool-review-interruption-work.js"; +import { writeToolReviewChange } from "../services/tool-review-work-notifications.js"; import { deleteCompany } from "../services/company-deletion.js"; import { subscribeDeliveryWork } from "../services/delivery-work-notifications.js"; import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js"; @@ -318,6 +320,257 @@ describeEmbeddedPostgres("tool gateway service", () => { expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toEqual([]); } + async function testRequest(provider: NonNullable, rateLimited = false) { + await db.insert(companyMemberships).values({ companyId: fixture.company.id, principalType: "user", + principalId: "board", status: "active", membershipRole: "owner" }); + const remote = await createRemoteMcpToolFixture(db, fixture.company.id); + await db.update(toolCatalogEntries).set({ isReadOnly: false, riskLevel: "write" }) + .where(eq(toolCatalogEntries.id, remote.catalogEntry.id)); + await db.insert(toolPolicies).values({ companyId: fixture.company.id, name: "Review connected writes", + policyType: "require_approval", priority: 10, selectors: { connectionId: remote.connection.id } }); + if (rateLimited) await db.insert(toolPolicies).values({ companyId: fixture.company.id, name: "One reviewed test call", + policyType: "rate_limit", priority: 1, selectors: { connectionId: remote.connection.id }, + config: { limit: 1, windowSeconds: 3600, keyBy: ["agent", "tool"] } }); + gateway = createTestToolGatewayService(db, { remoteHttpRequest: provider }); + const result = await gateway.executeTestCall({ companyId: fixture.company.id, connectionId: remote.connection.id, + agentId: fixture.agent.id, userId: "board", toolName: "needs_input", parameters: { value: "reviewed" } }); + expect(result.decision).toBe("ask_first"); + const [pending] = await db.select().from(toolActionRequests); + return { pending, remote }; + } + function providerFixture() { + let release!: () => void, entered!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + const started = new Promise(resolve => { entered = resolve; }); + const provider = vi.fn(async (_url, init) => { + const payload = JSON.parse(String(init.body)); + expect(payload.method).toBe("tools/call"); + entered(); await gate; + return Response.json({ jsonrpc: "2.0", id: payload.id, + result: { content: [{ type: "text", text: "Saved once" }] } }); + }); + return { provider, release, started }; + } + + describe("interrupted review recovery worker", () => { + async function startInterruption() { + coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => !draining, + canReconcile: () => true, onError: error => errors.push(error) }); + await registerToolReviewInterruptionWork(coordinator, gateway, () => !draining).ready; + } + async function settle(ms = 60_000) { + await vi.advanceTimersByTimeAsync(ms); + if (!draining) await vi.waitFor(async () => { + // Finish real SQL before following an armed coalescing/retry deadline. + // Do not jump across a future business deadline while waiting for I/O. + 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 selects = vi.spyOn(db, "select"), executes = vi.spyOn(db, "execute"); + await settle(60 * 60_000); + expect(selects).not.toHaveBeenCalled(); expect(executes).not.toHaveBeenCalled(); + selects.mockRestore(); executes.mockRestore(); + } + async function savedClaim(source = db, age = 0) { + const pending = await request(); + const claimedAt = new Date(Date.now() - age); + await writeToolReviewChange(source, fixture.company.id, async tx => { + await tx.update(toolInvocations).set({ status: "executing", startedAt: claimedAt, updatedAt: claimedAt }) + .where(eq(toolInvocations.id, pending.invocationId)); + await tx.update(toolActionRequests).set({ status: "executing", updatedAt: claimedAt }) + .where(eq(toolActionRequests.id, pending.id)); + }); + return { ...pending, updatedAt: claimedAt }; + } + async function unknown(pending: Awaited>) { + expect((await db.select().from(toolActionRequests).where(eq(toolActionRequests.id, pending.id)))[0].status).toBe("failed"); + expect((await db.select().from(toolInvocations).where(eq(toolInvocations.id, pending.invocationId)))[0]) + .toMatchObject({ status: "failed", errorCode: "tool_execution_outcome_unknown" }); + } + + it("coalesces sequential review writes into one interruption scan per window", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: false }); + const previous = db.$client.options.debug; + const scans: string[] = []; + db.$client.options.debug = (_connection, query) => { + if (query.includes('from "tool_action_requests"') && query.includes('"updated_at" <=')) scans.push(query); + }; + try { + await startInterruption(); + const firstPassAt = Date.now(); + expect(scans).toHaveLength(1); + for (let i = 0; i < 10; i++) { + await request(); + await vi.advanceTimersByTimeAsync(1); + // Let each previous pass finish; overlapping calls already coalesce. + await db.execute(sql`select pg_sleep(0.01)`); + } + expect(scans).toHaveLength(1); + expect(coordinator!.nextWakeAt()).toBe(firstPassAt + 30_000); + await vi.advanceTimersByTimeAsync(30_000); + await vi.waitFor(() => { + expect(scans).toHaveLength(2); + expect(idleWorkSnapshot().active).toBe(0); + expect(coordinator!.nextWakeAt()).toBeNull(); + }); + await quiet(); + expect(scans).toHaveLength(2); + } finally { db.$client.options.debug = previous; } + }); + + it("keeps a loaded stale-claim deadline ahead of review notification coalescing", async () => { + vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout", "setInterval", "clearInterval"], shouldAdvanceTime: false }); + const pending = await savedClaim(db, 10 * 60_000 - 500); + const deadline = pending.updatedAt.getTime() + 10 * 60_000; + await startInterruption(); + expect(coordinator!.nextWakeAt()).toBe(deadline); + await request(); + 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 () => { await unknown(pending); }); + expect(Date.now()).toBeLessThan(deadline + 1000); + await quiet(); + }); + + it("arms from a real execution claim and disarms after the provider result", async () => { + await startInterruption(); await quiet(); + const remote = providerFixture(); + const { pending } = await testRequest(remote.provider); + const running = gateway.approveActionRequest({ companyId: fixture.company.id, + actionRequestId: pending.id, actor: { userId: "board" } }); + await Promise.race([remote.started, running]); + try { + await settle(); + const [claim] = await db.select().from(toolActionRequests); + expect(claim.status).toBe("executing"); + expect(coordinator!.nextWakeAt()).toBe(claim.updatedAt.getTime() + 10 * 60_000); + const reads = vi.spyOn(db, "select"); + await settle(60_000); expect(reads).not.toHaveBeenCalled(); reads.mockRestore(); + } finally { remote.release(); } + await running; await quiet(); + expect((await db.select().from(toolActionRequests))[0].status).toBe("executed"); + expect(remote.provider).toHaveBeenCalledTimes(1); + }); + + it("reconstructs the saved deadline and quarantines only when due", async () => { + const pending = await savedClaim(); await startInterruption(); + expect(coordinator!.nextWakeAt()).toBe(pending.updatedAt.getTime() + 10 * 60_000); + await settle(9 * 60_000); + expect((await db.select().from(toolActionRequests))[0].status).toBe("executing"); + await settle(2 * 60_000); await unknown(pending); await quiet(); + expect(await db.select().from(toolCallEvents).where(eq(toolCallEvents.reasonCode, "approved_action_executed"))).toEqual([]); + }); + + it.each(["succeeded", "failed", "denied", "timed_out", "rate_limited", "cancelled"] as const)("preserves a saved %s invocation while repairing the request", async status => { + const pending = await savedClaim(db, 11 * 60_000); + const completedAt = new Date(Date.now() - 5 * 60_000); + await db.update(toolInvocations).set({ status, completedAt, resultSummary: { summary: "Saved provider result" }, + errorCode: status === "succeeded" ? null : "saved_provider_failure" }).where(eq(toolInvocations.id, pending.invocationId)); + await startInterruption(); await quiet(); + expect((await db.select().from(toolActionRequests))[0]).toMatchObject({ + status: status === "succeeded" ? "executed" : "failed", resolvedAt: completedAt }); + expect((await db.select().from(toolInvocations))[0]).toMatchObject({ status, completedAt, + errorCode: status === "succeeded" ? null : "saved_provider_failure", resultSummary: { summary: "Saved provider result" } }); + }); + + it("retains a first claim committed during drain without passive database scans", async () => { + await startInterruption(); await quiet(); draining = true; + const pending = await savedClaim(); await settle(); + const reads = vi.spyOn(db, "select"); + await settle(60 * 60_000); expect(reads).not.toHaveBeenCalled(); reads.mockRestore(); + draining = false; await settle(); await unknown(pending); await quiet(); + }); + + it.each([false, true])("waits for outer execution commit (rollback %s)", async rollback => { + const pending = await request(); await startInterruption(); await quiet(); + let entered!: () => void, release!: () => void; + const ready = new Promise(resolve => { entered = resolve; }); + const gate = new Promise(resolve => { release = resolve; }); + const aborted = new Error("fixture rollback"); + const running = db.transaction(async tx => { + await writeToolReviewChange(tx as unknown as typeof db, fixture.company.id, async nested => { + await nested.update(toolActionRequests).set({ status: "executing", updatedAt: new Date() }) + .where(eq(toolActionRequests.id, pending.id)); + }); + entered(); await gate; if (rollback) throw aborted; + }).catch(error => { if (error !== aborted) throw error; }); + await ready; + try { + await vi.advanceTimersByTimeAsync(11 * 60_000); + expect((await db.select().from(toolActionRequests))[0].status).toBe("pending"); + } finally { release(); await running; } + await vi.waitFor(async () => { + await vi.advanceTimersByTimeAsync(30_000); + if (rollback) expect((await db.select().from(toolActionRequests))[0].status).toBe("pending"); + else await unknown(pending); + expect(idleWorkSnapshot().active).toBe(0); + }, { timeout: 5000 }); + await quiet(); + }); + + it("rolls back both outcome rows on failure and retries after drain", async () => { + const pending = await savedClaim(db, 11 * 60_000); + await db.execute(sql`create function sleep_review_fail() returns trigger language plpgsql as $$ + begin raise exception 'interruption fixture failure'; end $$`); + await db.execute(sql`create trigger sleep_review_fail before update on tool_invocations + for each row when (new.error_code = 'tool_execution_outcome_unknown') execute function sleep_review_fail()`); + await startInterruption(); expect(errors.length).toBeGreaterThan(0); errors.length = 0; + expect((await db.select().from(toolActionRequests))[0].status).toBe("executing"); + expect((await db.select().from(toolInvocations))[0].status).toBe("executing"); + draining = true; + await db.execute(sql`drop trigger sleep_review_fail on tool_invocations`); + await settle(60 * 60_000); + draining = false; + await vi.waitFor(async () => { + await vi.advanceTimersByTimeAsync(30_000); + await unknown(pending); + }, { timeout: 5000 }); + await quiet(); + }); + + it("rechecks a changed claim after selecting a stale candidate", async () => { + const pending = await savedClaim(db, 11 * 60_000); + const transaction = db.transaction.bind(db); + let entered!: () => void, release!: () => void; + const ready = new Promise(resolve => { entered = resolve; }); + const gate = new Promise(resolve => { release = resolve; }); + const intercepted = vi.spyOn(db, "transaction").mockImplementationOnce(async callback => { + entered(); await gate; return transaction(callback); + }); + const sweep = gateway.settleInterruptedActionReviews(); + await ready; + const updatedAt = new Date(); + try { + await writeToolReviewChange(db, fixture.company.id, tx => tx.update(toolActionRequests).set({ updatedAt }) + .where(eq(toolActionRequests.id, pending.id))); + } finally { release(); } + await sweep; intercepted.mockRestore(); + expect((await db.select().from(toolActionRequests))[0].status).toBe("executing"); + await startInterruption(); + expect(coordinator!.nextWakeAt()).toBe(updatedAt.getTime() + 10 * 60_000); + }); + + it("settles more than one page of interrupted claims", async () => { + const pending = await savedClaim(db, 11 * 60_000); + await db.insert(toolActionRequests).values(Array.from({ length: 101 }, () => ({ ...pending, + id: randomUUID(), interactionId: null, status: "executing" as const }))); + await startInterruption(); await quiet(); + const rows = await db.select().from(toolActionRequests); + expect(rows).toHaveLength(102); expect(rows.every(row => row.status === "failed")).toBe(true); + }); + }); + describe("approved review recovery worker", () => { async function startRecovery() { coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => !draining, diff --git a/server/src/index.ts b/server/src/index.ts index e9fc24fcf0b..50627307a54 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -1,3 +1,4 @@ +import { registerToolReviewInterruptionWork } from "./services/tool-review-interruption-work.js"; import { registerToolReviewRecoveryWork } from "./services/tool-review-recovery-work.js"; import { registerToolReviewExpiryWork } from "./services/tool-review-expiry-work.js"; import { registerGatewayCredentialExpiryWork } from "./services/gateway-credential-expiry-work.js"; @@ -1479,7 +1480,13 @@ async function startServerWithDatabaseTeardown( } else { await app.locals.toolGateway.recoverApprovedActionReviews(); } - return app.locals.toolGateway.sweepActionReviews({ includeExpiry: false, includeApproved: false }); + if (config.heartbeatSchedulerEnabled) { + await registerToolReviewInterruptionWork(deliveryWork, app.locals.toolGateway, + () => !isIdleTaskDrainActive() && !heartbeatSchedulerStopped && !isWarmStandby()).ready; + } else { + await app.locals.toolGateway.settleInterruptedActionReviews(); + } + return app.locals.toolGateway.sweepActionReviews({ includeExpiry: false, includeApproved: false, includeInterrupted: false }); }).catch((err: unknown) => logger.error({ err }, "startup tool review recovery failed")); await timeStartupRecovery("gateway_sessions", () => config.heartbeatSchedulerEnabled ? registerGatewayCredentialExpiryWork(deliveryWork, app.locals.toolGateway, @@ -1910,7 +1917,7 @@ async function startServerWithDatabaseTeardown( logger.error({ err }, "periodic tool connection health sweep failed"); })); - trackHeartbeatSchedulerWork(app.locals.toolGateway.sweepActionReviews({ includeExpiry: false, includeApproved: false }).catch((err: unknown) => logger.error({ err }, "tool review recovery failed"))); + trackHeartbeatSchedulerWork(app.locals.toolGateway.sweepActionReviews({ includeExpiry: false, includeApproved: false, includeInterrupted: false }).catch((err: unknown) => logger.error({ err }, "tool review recovery failed"))); if (isIdleTaskDrainActive() || heartbeatSchedulerStopped) return; if (!(await heartbeat.resolveSchedulingSuppression()).suppressed) { diff --git a/server/src/services/delivery-work-notifications.ts b/server/src/services/delivery-work-notifications.ts index 923ae4b7979..9c943677dac 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", + toolReviewInterruption: "tool-review-interruption", toolReviewRecovery: "tool-review-recovery", toolReviewExpiry: "tool-review-expiry", gatewayCredentialExpiry: "gateway-credential-expiry", diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 57763f8b8d5..2d94a361de2 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -1,7 +1,8 @@ +import { toolReviewInterruptionService } from "./tool-review-interruption.js"; import { bindVerifiedToolApprovalArguments, claimToolTestApproval, releaseToolApproval, persistToolTestOutcome, startToolInvocation, type ToolApprovalClaim } from "./tool-approval-execution.js"; import { approvedToolReviewCompanies, prepareApprovedToolReview, recoverApprovedToolReviews } from "./tool-review-recovery.js"; import { toolReviewExpiryService } from "./tool-review-expiry.js"; -import { writeToolReviewChange } from "./tool-review-work-notifications.js"; +import { notifyToolReviewChange, writeToolReviewChange } from "./tool-review-work-notifications.js"; import { restConnectorFor } from "./connectors/rest-registry.js"; import type { runPromptInjectionProvider } from "./prompt-injection-provider.js"; import { promptInjectionPreventionService } from "./prompt-injection-prevention.js"; @@ -46,7 +47,6 @@ import { asc, desc, eq, - gt, inArray, isNull, lte, @@ -7987,6 +7987,7 @@ export function createToolGatewayService( const [actionRequest] = await tx .select({ + companyId: toolActionRequests.companyId, status: toolActionRequests.status, updatedAt: toolActionRequests.updatedAt, }) @@ -8001,6 +8002,7 @@ export function createToolGatewayService( return false; } + await notifyToolReviewChange(tx, actionRequest.companyId); await tx .update(toolInvocations) .set({ @@ -8476,10 +8478,10 @@ export function createToolGatewayService( }) .where(eq(toolInvocations.id, invocation.id)); void emitConnectionInvoked(db, invocation.id); - await db + await writeToolReviewChange(db, claimed.companyId, tx => tx .update(toolActionRequests) .set({ status: "executed", resolvedAt: now, updatedAt: now }) - .where(eq(toolActionRequests.id, claimed.id)); + .where(eq(toolActionRequests.id, claimed.id))); await reflectToolActionInteractionLifecycle({ actionRequestId: claimed.id, status: "executed", @@ -8818,6 +8820,11 @@ export function createToolGatewayService( }; } + const reviewInterruption = toolReviewInterruptionService(db, async settled => { + void emitConnectionInvoked(db, settled.invocationId); + await reflectToolActionInteractionLifecycle(settled); + }); + const reviewExpiry = toolReviewExpiryService(db, async expired => { void emitConnectionInvoked(db, expired.invocationId); await reflectToolActionInteractionLifecycle(expired); @@ -9910,6 +9917,8 @@ export function createToolGatewayService( return buildTestCallStatus(actionRequest, invocation); }, + settleInterruptedActionReviews: reviewInterruption.sweep, + nextActionReviewInterruptionAt: reviewInterruption.next, sweepExpiredActionReviews: reviewExpiry.sweep, nextActionReviewExpiryAt: reviewExpiry.next, actionReviewExpiryDeadlines: reviewExpiry.deadlines, @@ -9941,7 +9950,7 @@ export function createToolGatewayService( }, companyId); }, - async sweepActionReviews(input: { includeExpiry?: boolean; includeApproved?: boolean } = {}) { + async sweepActionReviews(input: { includeExpiry?: boolean; includeApproved?: boolean; includeInterrupted?: boolean } = {}) { // A process may stop between persisting a provider outcome and updating the // feed projection. Reconcile from authoritative rows before delivering it. const unreflected = await db @@ -9976,62 +9985,9 @@ export function createToolGatewayService( errorMessage: invocation.errorMessage, resultSummary: invocation.resultSummary?.summary, }); - const now = new Date(); - const staleAt = new Date(now.getTime() - 10 * 60_000); - let cursor: string | undefined; - let scanned = input.includeExpiry === false ? 0 : (await reviewExpiry.sweep(now)).scanned; + let scanned = input.includeExpiry === false ? 0 : (await reviewExpiry.sweep()).scanned; if (input.includeApproved !== false) scanned += (await this.recoverApprovedActionReviews()).scanned; - for (;;) { - const rows = await db - .select() - .from(toolActionRequests) - .where( - and( - eq(toolActionRequests.status, "executing"), - lte(toolActionRequests.updatedAt, staleAt), - cursor ? gt(toolActionRequests.id, cursor) : undefined, - ), - ) - .orderBy(asc(toolActionRequests.id)) - .limit(100); - for (const row of rows) { - const status = "failed"; - const errorCode = "tool_execution_outcome_unknown"; - const errorMessage = "Execution was interrupted; the external outcome is unknown. Inspect the provider before retrying."; - const [changed] = await db - .update(toolActionRequests) - .set({ status, resolvedAt: now, updatedAt: now }) - .where( - and( - eq(toolActionRequests.id, row.id), - eq(toolActionRequests.status, row.status), - eq(toolActionRequests.updatedAt, row.updatedAt), - ), - ) - .returning(); - if (!changed) continue; - await db - .update(toolInvocations) - .set({ - status: "failed", - errorCode, - errorMessage, - completedAt: now, - updatedAt: now, - }) - .where(eq(toolInvocations.id, row.invocationId)); - void emitConnectionInvoked(db, row.invocationId); - await reflectToolActionInteractionLifecycle({ - actionRequestId: row.id, - status, - errorCode, - errorMessage, - }); - } - scanned += rows.length; - if (rows.length < 100) break; - cursor = rows[rows.length - 1].id; - } + if (input.includeInterrupted !== false) scanned += (await reviewInterruption.sweep()).scanned; return { scanned }; }, @@ -11251,7 +11207,8 @@ export function createToolGatewayService( }) .where(eq(toolInvocations.id, invocationId)); if (input.approvedActionRequestId) { - const [executedRequest] = await db + const actionRequestId = input.approvedActionRequestId; + const [executedRequest] = await writeToolReviewChange(db, session.companyId, tx => tx .update(toolActionRequests) .set({ status: "executed", @@ -11260,11 +11217,11 @@ export function createToolGatewayService( }) .where( and( - eq(toolActionRequests.id, input.approvedActionRequestId), + eq(toolActionRequests.id, actionRequestId), eq(toolActionRequests.status, "executing"), ), ) - .returning({ id: toolActionRequests.id }); + .returning({ id: toolActionRequests.id })); if (executedRequest) { await reflectToolActionInteractionLifecycle({ actionRequestId: executedRequest.id, @@ -11384,7 +11341,8 @@ export function createToolGatewayService( .where(eq(toolInvocations.id, invocationId)); void emitConnectionInvoked(db, invocationId); if (input.approvedActionRequestId) { - const [failedRequest] = await db + const actionRequestId = input.approvedActionRequestId; + const [failedRequest] = await writeToolReviewChange(db, session.companyId, tx => tx .update(toolActionRequests) .set({ status: "failed", @@ -11393,11 +11351,11 @@ export function createToolGatewayService( }) .where( and( - eq(toolActionRequests.id, input.approvedActionRequestId), + eq(toolActionRequests.id, actionRequestId), eq(toolActionRequests.status, "executing"), ), ) - .returning({ id: toolActionRequests.id }); + .returning({ id: toolActionRequests.id })); if (failedRequest) { await reflectToolActionInteractionLifecycle({ actionRequestId: failedRequest.id, diff --git a/server/src/services/tool-review-interruption-work.ts b/server/src/services/tool-review-interruption-work.ts new file mode 100644 index 00000000000..9053cb1c4dd --- /dev/null +++ b/server/src/services/tool-review-interruption-work.ts @@ -0,0 +1,16 @@ +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 registerToolReviewInterruptionWork( + coordinator: ReturnType, + gateway: Pick, "settleInterruptedActionReviews" | "nextActionReviewInterruptionAt">, + canRun: () => boolean, +) { + return registerDeadlineWork(coordinator, DELIVERY_QUEUES.toolReviewInterruption, { + retryMs: 30_000, notificationCoalesceMs: 30_000, canRun, + run: () => gateway.settleInterruptedActionReviews(), + next: () => gateway.nextActionReviewInterruptionAt(), + }); +} diff --git a/server/src/services/tool-review-interruption.ts b/server/src/services/tool-review-interruption.ts new file mode 100644 index 00000000000..de8769f3da1 --- /dev/null +++ b/server/src/services/tool-review-interruption.ts @@ -0,0 +1,61 @@ +import { and, asc, eq, gt, lte } from "drizzle-orm"; +import { toolActionRequests, toolInvocations, type Db } from "@paperclipai/db"; +import { writeToolReviewChange } from "./tool-review-work-notifications.js"; + +const STALE_EXECUTION_MS = 10 * 60_000; + +export function toolReviewInterruptionService(db: Db, onSettled: (input: { + actionRequestId: string; + invocationId: string; + status: "executed" | "failed"; + errorCode: string | null; + errorMessage: string | null; + resultSummary?: string; +}) => Promise) { + return { + async next(): Promise { + const [row] = await db.select({ at: toolActionRequests.updatedAt }).from(toolActionRequests) + .where(eq(toolActionRequests.status, "executing")).orderBy(asc(toolActionRequests.updatedAt)).limit(1); + return row ? row.at.getTime() + STALE_EXECUTION_MS : null; + }, + async sweep(now = new Date()) { + const staleAt = new Date(now.getTime() - STALE_EXECUTION_MS); + let cursor: string | undefined; + let scanned = 0; + for (;;) { + const rows = await db.select().from(toolActionRequests).where(and( + eq(toolActionRequests.status, "executing"), lte(toolActionRequests.updatedAt, staleAt), + cursor ? gt(toolActionRequests.id, cursor) : undefined, + )).orderBy(asc(toolActionRequests.id)).limit(100); + for (const row of rows) { + const settled = await writeToolReviewChange(db, row.companyId, async tx => { + const [invocation] = await tx.select().from(toolInvocations) + .where(eq(toolInvocations.id, row.invocationId)).for("update"); + const [request] = await tx.select().from(toolActionRequests) + .where(eq(toolActionRequests.id, row.id)).for("update"); + if (!invocation || request?.status !== "executing" || + request.updatedAt.getTime() !== row.updatedAt.getTime()) return null; + const completed = ["succeeded", "failed", "denied", "timed_out", "rate_limited", "cancelled"].includes(invocation.status); + const status = invocation.status === "succeeded" ? "executed" as const : "failed" as const; + const errorCode = completed ? invocation.errorCode : "tool_execution_outcome_unknown"; + const errorMessage = completed ? invocation.errorMessage + : "Execution was interrupted; the external outcome is unknown. Inspect the provider before retrying."; + if (!completed) { + await tx.update(toolInvocations).set({ status: "failed", errorCode, errorMessage, + completedAt: now, updatedAt: now }).where(eq(toolInvocations.id, row.invocationId)); + } + await tx.update(toolActionRequests).set({ status, resolvedAt: invocation.completedAt ?? now, updatedAt: now }) + .where(eq(toolActionRequests.id, row.id)); + return { actionRequestId: row.id, invocationId: row.invocationId, status, + errorCode, errorMessage, resultSummary: invocation.resultSummary?.summary }; + }); + if (settled) await onSettled(settled); + } + scanned += rows.length; + if (rows.length < 100) break; + cursor = rows[rows.length - 1].id; + } + return { scanned }; + }, + }; +} diff --git a/server/src/services/tool-review-work-notifications.ts b/server/src/services/tool-review-work-notifications.ts index 1fc52d02b56..44957fefc1b 100644 --- a/server/src/services/tool-review-work-notifications.ts +++ b/server/src/services/tool-review-work-notifications.ts @@ -4,6 +4,7 @@ import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notificatio export async function notifyToolReviewChange(transaction: object, companyId: string) { await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewExpiry, companyId); await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewRecovery, companyId); + await notifyDeliveryWork(transaction, DELIVERY_QUEUES.toolReviewInterruption, companyId); } export function writeToolReviewChange(db: Db, companyId: string, write: (transaction: Db) => Promise): Promise {