mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 14:35:17 +01:00
Merge current master into Photon sleep handoff qualification
* commit '5acf27bc3b11ed1209f1e41a71f167f0c879ca9c': perf(server): read the instance role and membership once per GET request in authorization (#21716) fix(ui): let Request changes on a plan always take a revision note (#21721) feat(native): send launch preparation and run digests to plugin task prepare (#21717) fix(db): recover prepared statements that a pooler or schema change invalidates (#21718) perf(server): list skills without a folder transaction when bundled folders exist (#21715) perf(server): read the issue detail with fewer database statements (#21713) perf(chat): read the run state of a GitHub response sweep page in one batch (#21711) perf(native): accept a plugin's in-preparation project-auth check on warm attach (#21710) feat(server): add an instance-admin server metrics endpoint for the scale ramp (#21708) fix(restart-chaos): credit a follow-up only to a run that started a provider turn, and post a missed follow-up after the run ends (#21692) test(server): stop the accounting identity child from timing out on loaded runners (#21712) test(e2e): use the Coordinator task panel, inbox and plan controls in QA journeys (#21701) perf(db): build the agent request authentication statements once per client (#21707) fix(chat): park GitHub terminal responses that wait for a newer run or task change (#21705) perf(server): bound dedicated database connections with a fair queue (#21693) fix(heartbeat): settle deferred chat wakes that can never resume instead of retrying every pass (#21678) refactor: remove doc/execution-semantics.md and its references (#21699) fix(native): retry a coordinator claim that loses a deadlock instead of failing the run (#21703)
This commit is contained in:
commit
1fe39c2424
133 files changed
+5245
-6833
No files matched your search
@@ -16,7 +16,7 @@ approval before implementation, perform the investigation and safety analysis
|
||||
within that scope. For example, a Terminal-Bench diagnosis child does not override
|
||||
the loop's board approval boundary. Keep the next action and its owner explicit.
|
||||
|
||||
For issue-tree diagnosis, read the current `doc/execution-semantics.md`, inspect the
|
||||
For issue-tree diagnosis, inspect the
|
||||
relevant subtree and recent repairs, and classify non-progressing nodes:
|
||||
|
||||
- **Genuine wait:** a named human or external dependency must act.
|
||||
|
||||
@@ -43,9 +43,9 @@ Use authorized diagnostic access. If company scoping blocks a read, use an
|
||||
already-authorized diagnostic path or label the missing evidence; do not bypass
|
||||
the boundary.
|
||||
|
||||
Read repository instructions and the relevant current execution contract. In this
|
||||
repository, use `doc/execution-semantics.md` for ownership, continuation, waiting,
|
||||
finalization, and recovery. Inspect recent changes and open/merged repairs in the
|
||||
Read repository instructions. In this repository, the code and tests under
|
||||
`server/src/services/heartbeat/` and `server/src/services/recovery/` define
|
||||
ownership, continuation, waiting, finalization, and recovery. Inspect recent changes and open/merged repairs in the
|
||||
affected area. A correct fix that has not reached the target is a deployment gap;
|
||||
do not create a second patch without evidence that the first is insufficient.
|
||||
Choose code repair, configuration repair, or recovery from that evidence. If an
|
||||
|
||||
@@ -12,7 +12,7 @@ A repeatable operating skill for driving one Terminal-Bench problem to a passing
|
||||
|
||||
This skill is **operational + diagnostic**, not engineering. It coordinates issues, artifacts, and approvals around a Terminal-Bench loop. It does not authorize code changes — product fixes require a board confirmation before implementation.
|
||||
|
||||
Canonical execution model: read `doc/execution-semantics.md` before starting a loop or moving any loop issue. Every loop issue must rest in a state the doc allows: terminal (`done`/`cancelled`), explicitly live (active run / queued wake), explicitly waiting (`in_review` with participant/interaction/approval), or explicit recovery/blocker (`blocked` with `blockedByIssueIds` and a named owner).
|
||||
Every loop issue must rest in an allowed state: terminal (`done`/`cancelled`), explicitly live (active run / queued wake), explicitly waiting (`in_review` with participant/interaction/approval), or explicit recovery/blocker (`blocked` with `blockedByIssueIds` and a named owner).
|
||||
|
||||
## When to use
|
||||
|
||||
@@ -77,7 +77,7 @@ Wire dependencies with `blockedByIssueIds`, never with prose like "blocked by X"
|
||||
|
||||
### 0. Read the current execution contract
|
||||
|
||||
Before opening or advancing a loop, read `doc/execution-semantics.md`. Use that document's terms intact when classifying loop-issue state: live path / waiting path / recovery path; post-run disposition; bounded continuation; productivity review; pause-hold; watchdog. Do not invent a new state.
|
||||
Before opening or advancing a loop, use these terms when classifying loop-issue state: live path / waiting path / recovery path; post-run disposition; bounded continuation; productivity review; pause-hold; watchdog. Do not invent a new state.
|
||||
|
||||
### 1. Open or reuse the top-level loop issue
|
||||
|
||||
|
||||
+5
-5
@@ -4,7 +4,7 @@
|
||||
"content": "Audience and outcome: write a guided architecture handbook for contributors and coding agents. Help a reader understand the control plane, trace a task through the code, choose the right place to change behavior, and find the tests that protect it. Explain the problem and mental model before introducing symbols. Prefer a concrete example and a short causal explanation to exhaustive class, endpoint, package, or configuration inventories. Use plain language and define abbreviations on first use."
|
||||
},
|
||||
{
|
||||
"content": "Evidence and document authority: use current implementation, schemas, configuration, public exports, and tests to establish what ships in the indexed revision. Read `doc/GOAL.md` and `doc/PRODUCT.md` for intent; the focused docs under `doc/` (for example `doc/execution-semantics.md`) give background on policy. Contributor instructions such as `AGENTS.md` are not implementation evidence. Explain material disagreements between code and policy instead of silently treating either as proof of the other. Plans, historical snapshots, proposed ADRs, prototypes, fixtures, and roadmap entries do not establish shipping behavior. Verify their claims against production wiring and distinguish implemented, gated/experimental, and proposed behavior."
|
||||
"content": "Evidence and document authority: use current implementation, schemas, configuration, public exports, and tests to establish what ships in the indexed revision. Read `doc/GOAL.md` and `doc/PRODUCT.md` for intent; the focused docs under `doc/` give background on policy. Contributor instructions such as `AGENTS.md` are not implementation evidence. Explain material disagreements between code and policy instead of silently treating either as proof of the other. Plans, historical snapshots, proposed ADRs, prototypes, fixtures, and roadmap entries do not establish shipping behavior. Verify their claims against production wiring and distinguish implemented, gated/experimental, and proposed behavior."
|
||||
},
|
||||
{
|
||||
"content": "Page contract: each subsystem page should explain the problem it solves, what it owns, its inputs and outputs, authoritative persisted state, and its boundaries with neighboring systems. Trace one representative flow through actual entry points. Include a compact 'Where to change it' map linking responsibilities to source, relevant regression tests with the behavior they protect, and practical investigation steps for characteristic failures. Cite the code that performs a decision or effect rather than an import list or unrelated file. A passing unit fixture does not establish live provider support. Parent pages should offer reading routes, boundary maps, or diagnostic routing instead of repeating all their children."
|
||||
@@ -60,7 +60,7 @@
|
||||
"content": "Use a concept-to-schema/service table for company, agent/org tree, goal, project, task/issue, wake, run, session, approval/interaction, and work product. Explain company scope and documented instance-level exceptions without asserting every table has identical tenancy. Distinguish assignment from execution ownership, parent/child structure from blockers, and business goals from provider session goals. Give concrete examples of atomic checkout, company-boundary rejection, and a durable wait. Explain where these invariants are enforced and tested; leave full state transitions, permissions, and database operations to their owning pages."
|
||||
},
|
||||
{
|
||||
"content": "Source anchors: `doc/execution-semantics.md`, `packages/db/src/schema/index.ts`, `packages/db/src/schema/issues.ts`, `packages/db/src/schema/agents.ts`, `packages/db/src/schema/heartbeat_runs.ts`, `packages/db/src/schema/agent_task_sessions.ts`, `packages/shared/src/constants.ts`, `server/src/services/issues.ts`. Regression anchors: `server/src/__tests__/authz-company-access.test.ts`, `server/src/__tests__/issues-service.test.ts`, `server/src/__tests__/heartbeat-auto-checkout.test.ts`."
|
||||
"content": "Source anchors: `packages/db/src/schema/index.ts`, `packages/db/src/schema/issues.ts`, `packages/db/src/schema/agents.ts`, `packages/db/src/schema/heartbeat_runs.ts`, `packages/db/src/schema/agent_task_sessions.ts`, `packages/shared/src/constants.ts`, `server/src/services/issues.ts`. Regression anchors: `server/src/__tests__/authz-company-access.test.ts`, `server/src/__tests__/issues-service.test.ts`, `server/src/__tests__/heartbeat-auto-checkout.test.ts`."
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -162,7 +162,7 @@
|
||||
"content": "Introduce the control loop: accepted work, eligible wake, owned execution, persisted outcome, and either completion, durable waiting, continuation, or visible recovery. Use a responsibility table for issue service, wake queue, dispatch gates, heartbeat orchestration, status arbitration, and recovery. Explain that orchestration policies stay in Paperclip even when execution is remote. Provide a short symptom routing table for never-started work, blocked work, review waits, repeated turns, and interrupted work. Link to the four child pages and Run Agents; keep provider transports and detailed state machines out of this parent."
|
||||
},
|
||||
{
|
||||
"content": "Source anchors: `doc/execution-semantics.md`, `server/src/services/issues.ts`, `server/src/modules/wake-queue/index.ts`, `server/src/modules/run-dispatch/index.ts`, `server/src/services/heartbeat.ts`, `server/src/services/recovery/service.ts`, `server/src/services/native-runtime/status-arbiter.ts`. Policy evidence: `server/src/modules/wake-queue/domain/policy.test.ts`, `server/src/modules/run-dispatch/domain/policy.test.ts`."
|
||||
"content": "Source anchors: `server/src/services/issues.ts`, `server/src/modules/wake-queue/index.ts`, `server/src/modules/run-dispatch/index.ts`, `server/src/services/heartbeat.ts`, `server/src/services/recovery/service.ts`, `server/src/services/native-runtime/status-arbiter.ts`. Policy evidence: `server/src/modules/wake-queue/domain/policy.test.ts`, `server/src/modules/run-dispatch/domain/policy.test.ts`."
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -214,7 +214,7 @@
|
||||
"content": "Separate operator stop/cancel/pause, provider failure, controller restart, network loss, output silence, and stranded-task recovery. Trace direct-adapter controller ownership separately from native runner leases, reconnect, and replacement evidence. Explain when replay/reattachment is safe, why transport redelivery is not permission to replay side-effecting tools, and what prevents two controllers from owning execution. Distinguish source-scoped recovery actions, independent repair tasks, bounded same-owner retries, board escalation, and explicitly configured task watchdogs. Explain stopped-run cleanup and later user messages. Diagnose using durable identity/lease/decision records before suggesting retries; link scheduler and status details elsewhere."
|
||||
},
|
||||
{
|
||||
"content": "Source anchors: `doc/execution-semantics.md`, `server/src/services/recovery/service.ts`, `server/src/services/legacy-execution-recovery.ts`, `server/src/services/native-runtime/native-runner-ownership.ts`, `server/src/services/native-runtime/native-safe-replacement.ts`, `server/src/modules/active-run-watchdog/index.ts`. Regression anchors: `server/src/__tests__/issue-recovery-actions.test.ts`, `server/src/services/legacy-execution-recovery.test.ts`, `server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts`."
|
||||
"content": "Source anchors: `server/src/services/recovery/service.ts`, `server/src/services/legacy-execution-recovery.ts`, `server/src/services/native-runtime/native-runner-ownership.ts`, `server/src/services/native-runtime/native-safe-replacement.ts`, `server/src/modules/active-run-watchdog/index.ts`. Regression anchors: `server/src/__tests__/issue-recovery-actions.test.ts`, `server/src/services/legacy-execution-recovery.test.ts`, `server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts`."
|
||||
}
|
||||
]
|
||||
},
|
||||
@@ -354,7 +354,7 @@
|
||||
"content": "Organize this landing page around six questions: where to add a company-scoped feature, why assigned work did not start, why a successful run left a task open, who owns cancellation/restart recovery, how a tool obtained authority/credentials, and where a deliverable or diagnostic event went. For each, name the first durable record or decision to inspect and link the owning page. Explain company/actor/task/run correlation and distinguish activity history, run events, traces, telemetry, transcripts, and artifacts. Include an example investigation that follows evidence across layers without treating a UI symptom or model claim as the root cause. Avoid prescribing blind retries or copying sensitive payloads into reports."
|
||||
},
|
||||
{
|
||||
"content": "Source anchors: `doc/execution-semantics.md`, `doc/run-log-events.md`, `doc/observability.md`, `doc/AGENT-ARTIFACTS.md`, `server/src/routes/authz.ts`, `server/src/services/budgets.ts`, `server/src/services/work-products.ts`. Regression anchors: `server/src/__tests__/authz-company-access.test.ts`, `server/src/__tests__/budgets-service.test.ts`, `server/src/__tests__/work-product-runtime-reconciliation.test.ts`. Link orchestration and runtime investigations back to those chapters rather than repeating their state machines."
|
||||
"content": "Source anchors: `doc/run-log-events.md`, `doc/observability.md`, `doc/AGENT-ARTIFACTS.md`, `server/src/routes/authz.ts`, `server/src/services/budgets.ts`, `server/src/services/work-products.ts`. Regression anchors: `server/src/__tests__/authz-company-access.test.ts`, `server/src/__tests__/budgets-service.test.ts`, `server/src/__tests__/work-product-runtime-reconciliation.test.ts`. Link orchestration and runtime investigations back to those chapters rather than repeating their state machines."
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
+49
-4
@@ -141,16 +141,41 @@ DATABASE_APPLICATION_NAME=paperclip # application_name in pg_stat_activity; def
|
||||
the main pool (application name `paperclip-workspace-finalization-lock`). Each
|
||||
`createDb` owner keeps at most `DEDICATED_CONNECTION_IDLE_MAX` (4) of these
|
||||
single-connection clients idle for reuse; they follow the same idle timeout and
|
||||
max lifetime as the main pool. This is not an admission limit: callers hold
|
||||
advisory locks and nest dedicated actions, so an action that finds no idle
|
||||
client opens one and closes it on release when four are already retained. A
|
||||
connection whose action throws is closed, never reused. Actions must keep
|
||||
max lifetime as the main pool. At most `DATABASE_DEDICATED_CONNECTION_MAX`
|
||||
(default 24) dedicated clients are in use at once per owner. A caller that
|
||||
finds the limit reached waits in a first-in, first-out queue. A caller that
|
||||
already holds a dedicated client, or runs inside an open transaction of the
|
||||
same process, is admitted at once, because its wait could deadlock with the
|
||||
holder that it blocks. A caller that holds another bounded resource that a
|
||||
holder can need passes `{ admitWithoutWaiting: true }` for the same reason; the
|
||||
skill package store does this while it holds one of its package I/O permits
|
||||
(at most 2 storage and 2 response permits). Such callers can take the in-use
|
||||
count above the limit.
|
||||
A caller that waits longer than `DATABASE_DEDICATED_CONNECTION_WAIT_MS`
|
||||
(default 30000) is admitted over the limit, so a lock cycle that the database
|
||||
cannot see ends in a delay, not a hang. A connection whose action throws is
|
||||
closed, never reused. Actions must keep
|
||||
session state transaction-scoped (`pg_advisory_xact_lock`,
|
||||
`set_config(..., true)`). Like the main pool, a retained session sees an
|
||||
`ALTER DATABASE` or `ALTER ROLE ... SET` change only after it reconnects; a test
|
||||
that changes such a setting calls `closeDedicatedDbConnections` first. Shutdown
|
||||
and ending the owner client close the idle set.
|
||||
|
||||
Connections per server process, at most (`databaseConnectionBudget` in
|
||||
`packages/db/src/client.ts` computes this, and a test keeps it equal to the
|
||||
pool settings):
|
||||
|
||||
| Source | Connections |
|
||||
| --- | --- |
|
||||
| Main pool | `DATABASE_POOL_MAX` (driver default 10) |
|
||||
| Private pools: controller lease 2, legacy controller lease 1, controller-instance lease 1, runner checkpoint 3, file storage 2 | 9 |
|
||||
| Notification listeners: plugin lifecycle 1, deployment notifications 1 | 2 |
|
||||
| Dedicated clients: 2 x `DATABASE_DEDICATED_CONNECTION_MAX` in use (one nested client per holder) + 4 idle | 52 with the default limit |
|
||||
| Total with defaults | 73 |
|
||||
|
||||
A separate `DATABASE_MIGRATION_URL` adds a second owner with its own pools.
|
||||
Admission over the limit after the wait bound can exceed this total.
|
||||
|
||||
An explicit `DATABASE_PREPARED_STATEMENTS=true` enables named prepared statements
|
||||
for parameterized ORM queries, transactions, reserved connections, and dedicated
|
||||
clients. Postgres.js manages the statement cache. This does not cache query
|
||||
@@ -159,6 +184,26 @@ still apply, including `prepare: false` and simple-protocol execution. With the
|
||||
setting unset, ORM queries keep their existing unprepared behavior and tagged
|
||||
SQL uses the driver default. With `false`, preparation stays disabled.
|
||||
|
||||
With `true`, a database client and its private pools prepare at most 1,000
|
||||
distinct SQL texts, and never a text longer than 8 KB; other texts run
|
||||
unprepared. A transaction-mode pooler
|
||||
(PgBouncer 1.22 or later, Neon `-pooler` hosts) shares prepared statements by
|
||||
SQL text across clients, so after a migration changes a column type, the
|
||||
pooler's statement for an affected text keeps failing with `cached plan must
|
||||
not change result type` for every client and every process. When a statement
|
||||
fails with that error, `prepared statement does not exist` (26000), or a
|
||||
duplicate statement name (42P05), the client stops preparing that text for the
|
||||
rest of the process and retries once without preparation. A pooled statement
|
||||
is retried on its own. When the failed statement is the first one that the
|
||||
transaction ran (after `SET TRANSACTION` only), the client rolls back, begins
|
||||
again with the same options, repeats the `SET TRANSACTION` statements, and runs
|
||||
the statement unprepared on the same connection. The transaction callback does
|
||||
not run again and receives the result. A later statement in a transaction, or a
|
||||
statement in a savepoint, is not retried, so that transaction or savepoint fails
|
||||
once for each affected text in each process. `preparedStatementStats(db)`
|
||||
reports the prepared texts and the unprepared, demoted, retried, and restarted
|
||||
counts.
|
||||
|
||||
## Switching between modes
|
||||
|
||||
The database mode is controlled by `DATABASE_URL`:
|
||||
|
||||
@@ -126,8 +126,7 @@ company-boundary checks.
|
||||
|
||||
## Child→Parent Reporting Under Containment
|
||||
|
||||
The direct-parent report comment (`doc/execution-semantics.md` §6, "Child→Parent
|
||||
Reporting") is **off by default** for `low_trust_review`: a contained run reads
|
||||
The direct-parent report comment is **off by default** for `low_trust_review`: a contained run reads
|
||||
untrusted input, so a free-prose comment into the higher-trust parent thread is
|
||||
a prompt-injection promotion path. Contained reviewers report by completing
|
||||
their own review issue (`done` — the verdict is the deliverable; the
|
||||
|
||||
+1
-1
@@ -544,7 +544,7 @@ The agent performs authorized setup, reuses saved accounts and drafts, and hands
|
||||
|
||||
Authorized policy administration includes user-requested changes that loosen the acting agent’s own tool controls. These writes remain bounded by management grants, resource scope and the responsible user’s current authority; they do not need an additional approval solely because the agent is a target. Subsequent tool calls obey the resulting policy. Agents cannot approve their own governed action requests or edit their own principal permission grants.
|
||||
|
||||
Ordinary tool approvals remain reviewable without an implicit one-hour deadline. Authenticated OAuth refresh preserves a pending approval for the same saved action and authorization. Sign-in repair retains an accepted decision and resumes through connection-change events after revalidation; changed consent, permissions, credentials or action targets require a new review. Current access, explicit deadlines, task closure and execution receipts remain enforced. See [Delayed tool approvals](execution-semantics.md#delayed-tool-approvals).
|
||||
Ordinary tool approvals remain reviewable without an implicit one-hour deadline. Authenticated OAuth refresh preserves a pending approval for the same saved action and authorization. Sign-in repair retains an accepted decision and resumes through connection-change events after revalidation; changed consent, permissions, credentials or action targets require a new review. Current access, explicit deadlines, task closure and execution receipts remain enforced.
|
||||
|
||||
The implementation, operation inventory, permission matrix and fixture qualification are recorded in [Agent API parity for connection configuration](plans/2026-10-13-connection-api-parity.md). Provider fixtures establish API behavior; they do not constitute live provider setup or an empirical agent-success claim.
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ Agents can stop work for the wrong reasons: misreading a blocker, accepting a st
|
||||
|
||||
A task watchdog gives you a second pass on stopped work without rerunning the original assignee. It is verification-shaped, not execution-shaped: the watchdog reads what other agents claimed, checks it against the evidence in the thread, and either accepts the stop or restores a live path.
|
||||
|
||||
It is **not** an output-silence monitor for active runs. That is a separate mechanism — the silent active-run watchdog described in [`doc/execution-semantics.md`](execution-semantics.md) §12. Task watchdog only fires when the whole watched subtree has come to rest.
|
||||
It is **not** an output-silence monitor for active runs. That is a separate mechanism — the silent active-run watchdog in `server/src/modules/active-run-watchdog/`. Task watchdog only fires when the whole watched subtree has come to rest.
|
||||
|
||||
---
|
||||
|
||||
@@ -112,7 +112,7 @@ The mandate also enforces safety constraints that custom instructions **cannot o
|
||||
- No creating another watchdog for the watched subtree. No waking itself. Exactly one reusable review task per watched issue.
|
||||
- Custom instructions can narrow focus or veto specific shortcuts. They cannot grant authority the server does not already give the watchdog.
|
||||
|
||||
The formal authority contract (the full list of allowed and disallowed mutations) is in [Authority contract](#authority-contract) below. The ordinary interaction resolver contract is in [execution semantics](execution-semantics.md#issue-thread-interaction-resolution).
|
||||
The formal authority contract (the full list of allowed and disallowed mutations) is in [Authority contract](#authority-contract) below.
|
||||
|
||||
### Writing custom instructions
|
||||
|
||||
@@ -198,10 +198,6 @@ Within the watched subtree, a watchdog run may perform only mutations that resto
|
||||
|
||||
Every watchdog-triggered mutation must write activity with the watchdog id, source issue id, watchdog issue id when present, run id, and stop fingerprint. Mutations still use the normal status-transition, blocker, assignment, budget, and company-boundary guards.
|
||||
|
||||
The atomic recovery batch, restoration verification and escalation, and interaction
|
||||
resolution rules for watchdog runs are in
|
||||
[execution semantics §11](execution-semantics.md#11-task-watchdog-for-issue-trees).
|
||||
|
||||
### Disallowed watchdog mutations
|
||||
|
||||
A task watchdog must not:
|
||||
@@ -229,8 +225,7 @@ Deliberately deferred and disallowed for the first implementation: letting watch
|
||||
| Topic | File |
|
||||
| -------------------------------- | --------------------------------------------------------------------- |
|
||||
| Authority contract (formal) | [Authority contract](#authority-contract) (this doc) |
|
||||
| Execution semantics (formal) | [`doc/execution-semantics.md`](execution-semantics.md) §11 |
|
||||
| Silent active-run watchdog | [`doc/execution-semantics.md`](execution-semantics.md) §12 |
|
||||
| Silent active-run watchdog | `server/src/modules/active-run-watchdog/` |
|
||||
| Database schema | `packages/db/src/schema/issue_watchdogs.ts` |
|
||||
| Server service | `server/src/services/task-watchdogs.ts` |
|
||||
| Scope enforcement | `server/src/services/task-watchdog-scope.ts` |
|
||||
|
||||
@@ -19,7 +19,7 @@ terminal tasks. Resume/restore retain the optional wake-agents checkbox.
|
||||
## Resume and execution recovery
|
||||
|
||||
Resume releases a hold. Work the pause interrupted is re-dispatched once
|
||||
automatically, under current admission gates (see `doc/execution-semantics.md`).
|
||||
automatically, under current admission gates.
|
||||
Waking other agents is optional and only applies to tasks in
|
||||
`todo`, `in_progress`, or `in_review`; parked and terminal tasks stay untouched.
|
||||
The current execution-recovery policy requires verified outcomes before a stopped
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -369,8 +369,7 @@ refuses any archive whose manifest names an absolute or escaping link. Omitting
|
||||
a tracked link shows as a deletion in `git status` after restore.
|
||||
|
||||
Saves that recovery exhausted before this policy (capture policy version 1) are
|
||||
retried once automatically; see the capture-policy re-arm in
|
||||
`doc/execution-semantics.md`.
|
||||
retried once automatically.
|
||||
|
||||
## Automatic unsafe archive recovery
|
||||
|
||||
|
||||
@@ -445,12 +445,44 @@ A missing source is reported as "not measured", never as zero.
|
||||
| Lease renewals that miss their deadline | finish line | 0 | metrics endpoint |
|
||||
| Kill one server process | finish line | runs resume, no Retry | not measured by this harness |
|
||||
|
||||
The server has no metrics endpoint today. `PAPERCLIP_SCALE_METRICS_URL` must
|
||||
answer a JSON object with any of `mainThreadCpu`, `eventLoopUtilization`
|
||||
(0 to 1, highest server process), `eventLoopDelayP99Ms`,
|
||||
`statementsPerSecond`, `poolWaitP99Ms`, `runEventLatenessP99Ms`,
|
||||
`agentApiPreHandlerP99Ms` and `leaseRenewalsMissed` (a counter). Without it,
|
||||
the four server criteria are not measured, and a run can be at best
|
||||
**Server metrics.** Each server process can serve
|
||||
`GET /api/instance/server-metrics`, a JSON snapshot of that process over the
|
||||
last 50 to 60 s (`windowMs`), with its `processId` (random per process
|
||||
start), `uptimeSec` and `buildRevision`. It is off by default: set
|
||||
`PAPERCLIP_SERVER_METRICS=true` on the stack before the run (read once at
|
||||
start; off, the path answers 404 and nothing is collected). Only an instance
|
||||
admin can read it, so the board token must belong to an instance admin.
|
||||
Point the harness at it on the target origin, and the harness sends the board
|
||||
token in its `Authorization: Bearer` header (never in the URL;
|
||||
`PAPERCLIP_SCALE_METRICS_TOKEN` overrides it, and a URL on another origin gets
|
||||
no token unless that variable is set):
|
||||
|
||||
```sh
|
||||
export PAPERCLIP_SCALE_METRICS_URL=https://$H/api/instance/server-metrics
|
||||
```
|
||||
|
||||
| Field | Meaning | Source |
|
||||
| --- | --- | --- |
|
||||
| `mainThreadCpu` | main-thread CPU per wall second, 0 to 1 (Linux only, else null) | `/proc/self/task/<pid>/stat` |
|
||||
| `eventLoopUtilization` | 0 to 1 | `performance.eventLoopUtilization()` |
|
||||
| `eventLoopDelayP99Ms` | highest 10 s p99 in the window | `monitorEventLoopDelay` (20 ms) |
|
||||
| `statementsPerSecond` | Drizzle statements per second (not BEGIN/COMMIT or raw driver calls) | Drizzle logger counter |
|
||||
| `runEventLatenessP99Ms` | runner `emittedAt` to committed row, p99 (null with no events) | runner event append |
|
||||
| `agentApiPreHandlerP99Ms` | agent API request arrival to the API router, p99 (null with no agent requests) | two middlewares |
|
||||
| `leaseRenewalsMissed` | counter since process start: native run leases whose deadline passed unrenewed | lease deadline timer |
|
||||
|
||||
`processCpu`, `runEventLatenessSamples`, `agentApiPreHandlerSamples` and
|
||||
`dedicatedConnections` are extra context. `dedicatedConnections` is the
|
||||
process's dedicated-connection bound at the time of the request: `limit`,
|
||||
`inUse`, `waiting` (gauges), `peakInUse`, `queued`, `overLimit` and
|
||||
`nestedOverLimit` (counts since start); queueing there shows a restart burst. `poolWaitP99Ms` is absent: postgres.js exposes no cheap hook
|
||||
for time spent queued for a connection, so pool wait stays not measured. With
|
||||
several processes, each request reaches one of them; the harness keeps the
|
||||
highest gauge and sums the counter's growth per `processId`; a process
|
||||
whose `uptimeSec` shows it started during the run counts its whole counter.
|
||||
After an event-loop block longer than the window, `windowMs` reports the real,
|
||||
longer span so the block stays visible. Without the
|
||||
endpoint, the four server criteria are not measured, and a run can be at best
|
||||
`incomplete`. The harness does not read the database.
|
||||
|
||||
**Proof order.** A hosted stack that is not `paperclip.staging` first
|
||||
|
||||
@@ -462,7 +462,7 @@ runner lifecycle, `other` for an unknown value, or `unavailable` when the state
|
||||
none. `runnerSettled` is true only when the outbox is empty and no terminal delivery,
|
||||
provider cleanup or warm transition is pending. These fields explain how the runner
|
||||
stopped. The event is not recorded when a scheduled retry resumes a runner that
|
||||
exited after a settled suspension; see `doc/execution-semantics.md`.
|
||||
exited after a settled suspension.
|
||||
|
||||
`native.interrupted_turn_outcome_unknown` (level `warn`) is recorded once on a
|
||||
failed run whose reattachment proved the Runner process gone
|
||||
|
||||
@@ -291,8 +291,7 @@ of the same class, then the stable Runner default. The task shows a warning with
|
||||
the requested model, effective model, and CLI version. Agent and task settings
|
||||
stay unchanged. Update the image CLI to restore the requested model on later
|
||||
runs. Explicit `PAPERCLIP_RUNNER_REMOTE_CODEX_PATH` and
|
||||
`PAPERCLIP_RUNNER_REMOTE_CODEX_NPM_SPEC` settings take precedence. See
|
||||
[execution semantics](execution-semantics.md#remote-codex-model-compatibility).
|
||||
`PAPERCLIP_RUNNER_REMOTE_CODEX_NPM_SPEC` settings take precedence.
|
||||
|
||||
### Sandbox ACP input delivery
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@ Paperclip applies one process-wide scheduler to expensive host-side workspace Gi
|
||||
|
||||
The shared scan subprocess sets `GIT_OPTIONAL_LOCKS=0`, including when a caller supplies an environment. This prevents background `git status` from rewriting the index's stat cache and competing with workspace writers. Git still computes current tracked and untracked changes. Required write locks remain enforced; existing lock files are never removed or treated as stale by a scan. This avoids optional index refresh work but may make later scans repeat stat checks. See Git's [background refresh guidance](https://git-scm.com/docs/git-status#_background_refresh).
|
||||
|
||||
Workspace snapshots list ignored paths with `git ls-files --others --ignored --exclude-standard --directory -z` so ignored directory contents do not require a full status walk. Changed, untracked, deleted, and ignored filename lists stream into private SQLite manifests. There is no total filename-list byte limit. The parser and each sink chunk are limited to 64 KiB, and each SQLite connection uses a 1 MiB page cache with disk-backed temporary storage. Records must be complete NUL-delimited UTF-8 paths. Invalid, oversized, or incomplete records fail the scan. Explicit file selection excludes files created after the scan. Buffered browser/guard and referenced-source scan bounds stay unchanged. Snapshot failures retain their typed cause instead of becoming a non-Git-folder result. During pre-provider setup, scan timeouts and queue saturation use the existing two automatic failure retries with a 30-second delay. Cancellation, output limits, and other Git errors stop with specific recovery guidance. See `doc/execution-semantics.md` for the ownership and retry-budget contract.
|
||||
Workspace snapshots list ignored paths with `git ls-files --others --ignored --exclude-standard --directory -z` so ignored directory contents do not require a full status walk. Changed, untracked, deleted, and ignored filename lists stream into private SQLite manifests. There is no total filename-list byte limit. The parser and each sink chunk are limited to 64 KiB, and each SQLite connection uses a 1 MiB page cache with disk-backed temporary storage. Records must be complete NUL-delimited UTF-8 paths. Invalid, oversized, or incomplete records fail the scan. Explicit file selection excludes files created after the scan. Buffered browser/guard and referenced-source scan bounds stay unchanged. Snapshot failures retain their typed cause instead of becoming a non-Git-folder result. During pre-provider setup, scan timeouts and queue saturation use the existing two automatic failure retries with a 30-second delay. Cancellation, output limits, and other Git errors stop with specific recovery guidance.
|
||||
|
||||
|
||||
Snapshot scans default to a 30-minute execution deadline, including disk backpressure, rather than the short interactive scan deadline. Set `PAPERCLIP_WORKSPACE_GIT_SNAPSHOT_TIMEOUT_MS` to allow slower storage or larger trees (1 second to 24 hours). Disk capacity, filesystem path limits, Git's own resource use, and this execution budget remain practical limits. Each manifest is admitted with a page allowance equal to one quarter of the available bytes above the host reserve at creation. SQLite enforces that allowance before page allocation, so one snapshot cannot consume all available storage. This is a disk-capacity admission policy, not a fixed filename-list byte or record limit. Nested repository and baseline manifests receive separate allowances from the remaining capacity. Manifest writers also check available disk space before creation and at most every 1 MiB of input thereafter. They stop below a 256 MiB free-space reserve. `PAPERCLIP_WORKSPACE_MANIFEST_MIN_FREE_BYTES` can raise or lower the reserve, with a 64 MiB minimum. Concurrent writers can consume space between checks; filesystem quota and write errors still fail the operation. The scheduler keeps the active slot until the child, pipes, and pending sink write finish. Snapshot failures cancel sibling producers and settle all started producers before removing temporary storage.
|
||||
|
||||
@@ -68,6 +68,10 @@ queries inside transactions and reserved or dedicated connections. Check the
|
||||
provider's configuration before you enable it. Preparation caches statement
|
||||
metadata, not query results. Unset preserves the existing ORM behavior and the
|
||||
driver default for tagged SQL. Explicit per-query options still apply.
|
||||
Each database client prepares at most 1,000 distinct statements and skips
|
||||
statements longer than 8 KB. If a prepared statement fails because the pooler's copy is
|
||||
stale after a schema change or was lost, Paperclip stops preparing that
|
||||
statement and retries it once unprepared.
|
||||
|
||||
Related optional client tuning: `DATABASE_POOL_MAX`, `DATABASE_IDLE_TIMEOUT_SECONDS`, `DATABASE_CONNECT_TIMEOUT_SECONDS`, `DATABASE_MAX_LIFETIME_SECONDS`, `DATABASE_APPLICATION_NAME`. Driver defaults apply when unset, except that idle pooled connections close after 60 seconds (`DATABASE_IDLE_TIMEOUT_SECONDS=0` keeps them open) and the pool reports `application_name=paperclip`. See [Connection pool settings](#connection-pool-settings).
|
||||
|
||||
@@ -82,9 +86,11 @@ The server opens one postgres.js pool for its own queries (and a second one when
|
||||
| `DATABASE_CONNECT_TIMEOUT_SECONDS` | `30` (driver) | Give up on a connection attempt after this long. |
|
||||
| `DATABASE_MAX_LIFETIME_SECONDS` | 30–60 min, randomized (driver) | Recycle a pooled connection once it is this old. |
|
||||
| `DATABASE_APPLICATION_NAME` | `paperclip` | Value of `application_name` in `pg_stat_activity`, so you can find Paperclip's backends: `SELECT * FROM pg_stat_activity WHERE application_name = 'paperclip';` |
|
||||
| `DATABASE_DEDICATED_CONNECTION_MAX` | `24` | Dedicated lock connections in use at once per process before new callers wait. Nested callers do not wait. |
|
||||
| `DATABASE_DEDICATED_CONNECTION_WAIT_MS` | `30000` | After this wait, a queued caller gets a dedicated connection over the limit. |
|
||||
| `DATABASE_PREPARED_STATEMENTS` | Unset | `true` opts parameterized ORM queries into preparation. `false` disables preparation. Use `false` when the pooler does not support named statements. Unset preserves existing behavior. |
|
||||
|
||||
The server ends its pools during shutdown (SIGINT/SIGTERM) and when startup fails after the pool was opened, so a restarting server does not leave idle backends behind. Size `max_connections` on the PostgreSQL side for at least `DATABASE_POOL_MAX` per server process plus your other clients. Each server process also opens up to 2 connections (`application_name=paperclip-controller-lease`) for agent-run lease renewals, so they never queue behind slow application queries; count those too.
|
||||
The server ends its pools during shutdown (SIGINT/SIGTERM) and when startup fails after the pool was opened, so a restarting server does not leave idle backends behind. Size `max_connections` on the PostgreSQL side for at least `DATABASE_POOL_MAX` per server process plus your other clients. Each server process also opens private pools and dedicated lock connections. With the defaults, one process can open up to 73 connections: `DATABASE_POOL_MAX` (10), 9 in private pools (lease renewal, checkpoints, file storage), 2 notification listeners, and up to 52 dedicated lock connections (`application_name=paperclip-workspace-finalization-lock`). `DATABASE_DEDICATED_CONNECTION_MAX` (default 24) bounds the dedicated connections in use; the worst case is twice that value plus 4 idle. Count all of these per process when you size `max_connections`, or lower `DATABASE_DEDICATED_CONNECTION_MAX` to fit.
|
||||
|
||||
## Switching Between Modes
|
||||
|
||||
|
||||
@@ -468,8 +468,7 @@ only. Separately inspect the underlying execution if it is still stuck.
|
||||
silently trigger recovery that fights the user's instruction.
|
||||
- Source inspection and mocked component tests do not qualify real server
|
||||
restart continuity. Use the appropriate runtime suite for that claim.
|
||||
- See [execution semantics](../../doc/execution-semantics.md) for the governing
|
||||
recovery contract and [steering](./steering.md) for saved follow-ups.
|
||||
- See [steering](./steering.md) for saved follow-ups.
|
||||
|
||||
### Storybook verification
|
||||
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { cpus, loadavg } from "node:os";
|
||||
import { and, eq, inArray, mapResultRow, sql } from "drizzle-orm";
|
||||
import { tracer } from "drizzle-orm/tracing";
|
||||
import { drizzle } from "drizzle-orm/postgres-js";
|
||||
import postgres from "postgres";
|
||||
import { createDb } from "../src/client.js";
|
||||
import * as schema from "../src/schema/index.js";
|
||||
import { activityLog, agents, companies, companyMemberships, issues } from "../src/schema/index.js";
|
||||
import { startEmbeddedPostgresTestDatabase } from "../src/test-embedded-postgres.js";
|
||||
|
||||
const iterations = Number(process.env.ITERATIONS ?? 2000);
|
||||
const passes = Number(process.env.PASSES ?? 5);
|
||||
const concurrency = Number(process.env.CONCURRENCY ?? 1);
|
||||
const only = process.env.ONLY?.split(",").filter(Boolean);
|
||||
const variants = process.env.VARIANTS?.split("|").filter(Boolean);
|
||||
const median = (values: number[]) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]!;
|
||||
|
||||
async function pass(action: () => Promise<unknown> | unknown) {
|
||||
const cpu = process.cpuUsage(), startedAt = performance.now();
|
||||
let next = 0;
|
||||
await Promise.all(Array.from({ length: concurrency }, async () => {
|
||||
while (next < iterations) { next += 1; await action(); }
|
||||
}));
|
||||
const used = process.cpuUsage(cpu);
|
||||
return { cpu: (used.user + used.system) / iterations, wall: (performance.now() - startedAt) * 1000 / iterations };
|
||||
}
|
||||
|
||||
const results: Record<string, Record<string, { median: number; min: number; max: number }>> = {};
|
||||
async function measure(statement: string, variant: string, action: () => Promise<unknown> | unknown) {
|
||||
if (only && !only.includes(statement)) return;
|
||||
if (variants && !variants.some(name => variant.startsWith(name))) return;
|
||||
for (let index = 0; index < Math.min(500, iterations); index += 1) await action();
|
||||
const samples = [];
|
||||
for (let index = 0; index < passes; index += 1) samples.push(await pass(action));
|
||||
const cpu = samples.map(sample => sample.cpu);
|
||||
(results[statement] ??= {})[variant] = { median: Number(median(cpu).toFixed(1)), min: Number(Math.min(...cpu).toFixed(1)),
|
||||
max: Number(Math.max(...cpu).toFixed(1)) };
|
||||
console.log(JSON.stringify({ statement, variant, cpuMicros: results[statement][variant],
|
||||
wallMicros: Number(median(samples.map(sample => sample.wall)).toFixed(1)) }));
|
||||
}
|
||||
|
||||
type Query = { toSQL(): { sql: string; params: unknown[] }; _: { selectedFields?: unknown } };
|
||||
type Case = {
|
||||
name: string;
|
||||
build: (db: ReturnType<typeof createDb>) => Query & PromiseLike<unknown>;
|
||||
prepare: (db: ReturnType<typeof createDb>) => { execute(values: Record<string, unknown>): Promise<unknown> };
|
||||
values: Record<string, unknown>;
|
||||
fields?: (query: Query) => unknown;
|
||||
};
|
||||
|
||||
const database = await startEmbeddedPostgresTestDatabase("paperclip-statement-cpu-");
|
||||
const db = createDb(database.connectionString, { maxConnections: 4 });
|
||||
const plainSql = postgres(database.connectionString, { max: 4, onnotice: () => {} });
|
||||
const plain = drizzle(plainSql, { schema });
|
||||
try {
|
||||
const [company] = await db.insert(companies).values({ name: "Bench", issuePrefix: "BEN" }).returning({ id: companies.id });
|
||||
const companyId = company!.id;
|
||||
const [agent] = await db.insert(agents).values({ companyId, name: "Agent" }).returning({ id: agents.id });
|
||||
const issueIds: string[] = [];
|
||||
for (let index = 0; index < 20; index += 1) {
|
||||
const [issue] = await db.insert(issues).values({ companyId, title: `Issue ${index}`, assigneeAgentId: agent!.id,
|
||||
description: "x".repeat(400) }).returning({ id: issues.id });
|
||||
issueIds.push(issue!.id);
|
||||
}
|
||||
const userId = "user-1";
|
||||
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId, status: "active",
|
||||
membershipRole: "owner" });
|
||||
const listIds = issueIds.slice(0, 10);
|
||||
|
||||
const cases: Case[] = [
|
||||
{
|
||||
name: "issue parent by id",
|
||||
build: d => d.select({ parentId: issues.parentId }).from(issues).where(eq(issues.id, issueIds[0]!)),
|
||||
prepare: d => d.select({ parentId: issues.parentId }).from(issues).where(eq(issues.id, sql.placeholder("id"))).prepare("p1"),
|
||||
values: { id: issueIds[0] },
|
||||
},
|
||||
{
|
||||
name: "issue row by id",
|
||||
build: d => d.select().from(issues).where(eq(issues.id, issueIds[1]!)),
|
||||
prepare: d => d.select().from(issues).where(eq(issues.id, sql.placeholder("id"))).prepare("p2"),
|
||||
values: { id: issueIds[1] },
|
||||
},
|
||||
{
|
||||
name: "membership by principal",
|
||||
build: d => d.select({ companyId: companyMemberships.companyId, membershipRole: companyMemberships.membershipRole,
|
||||
status: companyMemberships.status }).from(companyMemberships).where(and(eq(companyMemberships.companyId, companyId),
|
||||
eq(companyMemberships.principalType, "user"), eq(companyMemberships.principalId, userId),
|
||||
eq(companyMemberships.status, "active"))),
|
||||
prepare: d => d.select({ companyId: companyMemberships.companyId, membershipRole: companyMemberships.membershipRole,
|
||||
status: companyMemberships.status }).from(companyMemberships).where(and(
|
||||
eq(companyMemberships.companyId, sql.placeholder("companyId")), eq(companyMemberships.principalType, "user"),
|
||||
eq(companyMemberships.principalId, sql.placeholder("userId")), eq(companyMemberships.status, "active"))).prepare("p3"),
|
||||
values: { companyId, userId },
|
||||
},
|
||||
{
|
||||
name: "join with in-list of 10",
|
||||
build: d => d.select({ id: issues.id, title: issues.title, status: issues.status, agentName: agents.name })
|
||||
.from(issues).leftJoin(agents, eq(issues.assigneeAgentId, agents.id))
|
||||
.where(and(eq(issues.companyId, companyId), inArray(issues.id, listIds))),
|
||||
prepare: d => d.select({ id: issues.id, title: issues.title, status: issues.status, agentName: agents.name })
|
||||
.from(issues).leftJoin(agents, eq(issues.assigneeAgentId, agents.id))
|
||||
.where(and(eq(issues.companyId, sql.placeholder("companyId")), sql`${issues.id} = any(${sql.placeholder("ids")}::uuid[])`)).prepare("p4"),
|
||||
values: { companyId, ids: listIds },
|
||||
},
|
||||
{
|
||||
name: "update by id",
|
||||
build: d => d.update(issues).set({ updatedAt: new Date(), checkoutRunId: null }).where(eq(issues.id, issueIds[2]!)) as never,
|
||||
prepare: d => d.update(issues).set({ updatedAt: sql.placeholder("now") as never, checkoutRunId: null })
|
||||
.where(eq(issues.id, sql.placeholder("id"))).prepare("p5"),
|
||||
values: { id: issueIds[2], now: new Date() },
|
||||
},
|
||||
{
|
||||
name: "insert activity",
|
||||
build: d => d.insert(activityLog).values({ companyId, actorType: "agent", actorId: agent!.id, action: "issue.updated",
|
||||
entityType: "issue", entityId: issueIds[3]!, agentId: agent!.id, details: { field: "status", from: "todo", to: "done" } }) as never,
|
||||
prepare: d => d.insert(activityLog).values({ companyId: sql.placeholder("companyId"), actorType: "agent",
|
||||
actorId: sql.placeholder("actorId"), action: "issue.updated", entityType: "issue", entityId: sql.placeholder("entityId"),
|
||||
agentId: sql.placeholder("actorId"), details: sql.placeholder("details") }).prepare("p6"),
|
||||
values: { companyId, actorId: agent!.id, entityId: issueIds[3], details: { field: "status", from: "todo", to: "done" } },
|
||||
},
|
||||
];
|
||||
|
||||
await measure("tracer", "no-op startActiveSpan (async callback)", () => tracer.startActiveSpan("x", async () => 1));
|
||||
for (const item of cases) {
|
||||
const sample = item.build(db);
|
||||
const { sql: text, params } = sample.toSQL();
|
||||
const ordered = (sample as unknown as { _prepare(): { fields?: unknown; joinsNotNullableMap?: unknown } })._prepare();
|
||||
const mapFields = ordered.fields as Parameters<typeof mapResultRow>[0] | undefined;
|
||||
const joins = ordered.joinsNotNullableMap as Parameters<typeof mapResultRow>[2];
|
||||
await measure(item.name, "build only (toSQL)", () => item.build(db).toSQL());
|
||||
await measure(item.name, "drizzle builder, createDb", () => item.build(db));
|
||||
await measure(item.name, "drizzle builder, plain drizzle()", () => item.build(plain as never));
|
||||
const prepared = item.prepare(db);
|
||||
await measure(item.name, "drizzle .prepare() reused", () => prepared.execute(item.values));
|
||||
if (mapFields) {
|
||||
await measure(item.name, "unsafe .values() + mapResultRow", async () => {
|
||||
const rows = await db.$client.unsafe(text, params as never[]).values();
|
||||
return rows.map(row => mapResultRow(mapFields, row as unknown[], joins));
|
||||
});
|
||||
}
|
||||
await measure(item.name, "unsafe(text, params)", () => db.$client.unsafe(text, params as never[]));
|
||||
await measure(item.name, "unsafe(text, params, {prepare:true})", () => db.$client.unsafe(text, params as never[], { prepare: true }));
|
||||
}
|
||||
console.log(JSON.stringify({ kind: "summary", node: process.version, cpus: cpus().length, loadavg: loadavg(), iterations,
|
||||
passes, concurrency, results }));
|
||||
} finally {
|
||||
await plainSql.end({ timeout: 1 });
|
||||
await db.$client.end({ timeout: 1 });
|
||||
await database.cleanup();
|
||||
}
|
||||
+143
-26
@@ -1,10 +1,11 @@
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, readdir } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import postgres from "postgres";
|
||||
import { installDatabaseWorkSignals } from "./work-signals.js";
|
||||
import { installDatabaseResponseCapture } from "./response-capture.js";
|
||||
import { installPreparedQueries } from "./prepared-queries.js";
|
||||
import { createPreparedQueryState, installPreparedQueries, preparedQueryStats, type PreparedQueryState, type PreparedQueryStats } from "./prepared-queries.js";
|
||||
import { drizzleWithLazyTransactionQueries } from "./lazy-transaction-queries.js";
|
||||
import * as schema from "./schema/index.js";
|
||||
|
||||
@@ -168,6 +169,8 @@ export interface DatabaseClientOptions {
|
||||
* parameter (no extra round trip). For dedicated single-purpose pools only.
|
||||
*/
|
||||
statementTimeoutMs?: number;
|
||||
dedicatedConnectionMax?: number;
|
||||
dedicatedConnectionWaitMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -236,6 +239,10 @@ export function databaseClientOptionsFromEnv(env: NodeJS.ProcessEnv = process.en
|
||||
if (maxLifetimeSeconds !== undefined) options.maxLifetimeSeconds = maxLifetimeSeconds;
|
||||
const applicationName = envNonEmptyString(env, "DATABASE_APPLICATION_NAME");
|
||||
if (applicationName !== undefined) options.applicationName = applicationName;
|
||||
const dedicatedConnectionMax = envPositiveInteger(env, "DATABASE_DEDICATED_CONNECTION_MAX");
|
||||
if (dedicatedConnectionMax !== undefined) options.dedicatedConnectionMax = dedicatedConnectionMax;
|
||||
const dedicatedConnectionWaitMs = envPositiveInteger(env, "DATABASE_DEDICATED_CONNECTION_WAIT_MS");
|
||||
if (dedicatedConnectionWaitMs !== undefined) options.dedicatedConnectionWaitMs = dedicatedConnectionWaitMs;
|
||||
return options;
|
||||
}
|
||||
|
||||
@@ -274,14 +281,113 @@ export function postgresJsOptions(options: DatabaseClientOptions): Record<string
|
||||
const ownedDatabaseListenerFactories = new WeakMap<object, () => Db>();
|
||||
|
||||
export const DEDICATED_CONNECTION_IDLE_MAX = 4;
|
||||
export const DEFAULT_DEDICATED_CONNECTION_MAX = 24;
|
||||
export const DEFAULT_DEDICATED_CONNECTION_WAIT_MS = 30_000;
|
||||
|
||||
type DedicatedConnectionWaiter = { grant(): void; timer: ReturnType<typeof setTimeout> };
|
||||
type DedicatedConnectionSet = {
|
||||
create(): Db;
|
||||
idle: Db[];
|
||||
ended: WeakSet<Db>;
|
||||
closed: boolean;
|
||||
limit: number;
|
||||
waitMs: number;
|
||||
inUse: number;
|
||||
waiters: DedicatedConnectionWaiter[];
|
||||
stats: DedicatedDbConnectionStats;
|
||||
};
|
||||
export type DedicatedDbConnectionStats = { limit: number; inUse: number; peakInUse: number; waiting: number;
|
||||
queued: number; overLimit: number; nestedOverLimit: number };
|
||||
const dedicatedConnectionSets = new WeakMap<object, DedicatedConnectionSet>();
|
||||
type DedicatedConnectionHold = { set: DedicatedConnectionSet; active: boolean };
|
||||
const heldDedicatedConnections = new AsyncLocalStorage<readonly DedicatedConnectionHold[]>();
|
||||
const openTransactions = new AsyncLocalStorage<{ active: boolean }>();
|
||||
|
||||
function dedicatedConnectionSet(create: DedicatedConnectionSet["create"], resolved: DatabaseClientOptions): DedicatedConnectionSet {
|
||||
const limit = resolved.dedicatedConnectionMax ?? DEFAULT_DEDICATED_CONNECTION_MAX;
|
||||
return { create, idle: [], ended: new WeakSet(), closed: false, limit, inUse: 0, waiters: [],
|
||||
waitMs: resolved.dedicatedConnectionWaitMs ?? DEFAULT_DEDICATED_CONNECTION_WAIT_MS,
|
||||
stats: { limit, inUse: 0, peakInUse: 0, waiting: 0, queued: 0, overLimit: 0, nestedOverLimit: 0 } };
|
||||
}
|
||||
|
||||
function takeDedicatedSlot(set: DedicatedConnectionSet) {
|
||||
set.inUse++;
|
||||
set.stats.inUse = set.inUse;
|
||||
set.stats.peakInUse = Math.max(set.stats.peakInUse, set.inUse);
|
||||
}
|
||||
|
||||
function releaseDedicatedSlot(set: DedicatedConnectionSet) {
|
||||
set.inUse--;
|
||||
set.stats.inUse = set.inUse;
|
||||
while (set.waiters.length && set.inUse < set.limit) set.waiters.shift()!.grant();
|
||||
set.stats.waiting = set.waiters.length;
|
||||
}
|
||||
|
||||
function holdsLiveDedicatedOrTransaction(set: DedicatedConnectionSet): boolean {
|
||||
return Boolean(heldDedicatedConnections.getStore()?.some(hold => hold.active && hold.set === set)
|
||||
|| openTransactions.getStore()?.active);
|
||||
}
|
||||
|
||||
async function admitDedicatedConnection(set: DedicatedConnectionSet, nested: boolean): Promise<void> {
|
||||
if (nested || (set.inUse < set.limit && set.waiters.length === 0)) {
|
||||
if (nested && set.inUse >= set.limit) set.stats.nestedOverLimit++;
|
||||
takeDedicatedSlot(set);
|
||||
return;
|
||||
}
|
||||
set.stats.queued++;
|
||||
await new Promise<void>(resolve => {
|
||||
const waiter: DedicatedConnectionWaiter = {
|
||||
grant: () => { clearTimeout(waiter.timer); takeDedicatedSlot(set); resolve(); },
|
||||
timer: setTimeout(() => {
|
||||
const index = set.waiters.indexOf(waiter);
|
||||
if (index < 0) return;
|
||||
set.waiters.splice(index, 1);
|
||||
set.stats.waiting = set.waiters.length;
|
||||
set.stats.overLimit++;
|
||||
takeDedicatedSlot(set);
|
||||
resolve();
|
||||
}, set.waitMs),
|
||||
};
|
||||
set.waiters.push(waiter);
|
||||
set.stats.waiting = set.waiters.length;
|
||||
});
|
||||
}
|
||||
|
||||
function markOpenTransactions(db: Db) {
|
||||
const transaction = db.transaction.bind(db) as (...args: unknown[]) => Promise<unknown>;
|
||||
db.transaction = ((fn: (tx: unknown) => Promise<unknown>, ...rest: unknown[]) => transaction(async (tx: unknown) => {
|
||||
const open = { active: true };
|
||||
try { return await openTransactions.run(open, () => fn(tx)); }
|
||||
finally { open.active = false; }
|
||||
}, ...rest)) as Db["transaction"];
|
||||
}
|
||||
|
||||
export const DRIVER_DEFAULT_POOL_MAX_CONNECTIONS = 10;
|
||||
export const PRIVATE_POOL_MAX_CONNECTIONS = {
|
||||
liveness: 2, legacyControllerLease: 1, controllerInstanceLease: 1, checkpoint: 3, fileStorage: 2,
|
||||
} as const;
|
||||
export const DATABASE_LISTENER_CONNECTIONS = 2;
|
||||
|
||||
export function databaseConnectionBudget(options: DatabaseClientOptions = {}) {
|
||||
const main = options.maxConnections ?? DRIVER_DEFAULT_POOL_MAX_CONNECTIONS;
|
||||
const privatePools = Object.values(PRIVATE_POOL_MAX_CONNECTIONS).reduce((sum, value) => sum + value, 0);
|
||||
const dedicatedLimit = options.dedicatedConnectionMax ?? DEFAULT_DEDICATED_CONNECTION_MAX;
|
||||
const dedicated = 2 * dedicatedLimit + DEDICATED_CONNECTION_IDLE_MAX;
|
||||
return { main, privatePools, listeners: DATABASE_LISTENER_CONNECTIONS, dedicatedLimit, dedicated,
|
||||
total: main + privatePools + DATABASE_LISTENER_CONNECTIONS + dedicated };
|
||||
}
|
||||
|
||||
const preparedQueryStates = new WeakMap<object, PreparedQueryState>();
|
||||
|
||||
export function preparedStatementStats(db: Db): PreparedQueryStats | null {
|
||||
const state = preparedQueryStates.get(db);
|
||||
return state ? preparedQueryStats(state) : null;
|
||||
}
|
||||
|
||||
export function dedicatedDbConnectionStats(db: Db): DedicatedDbConnectionStats | null {
|
||||
const set = dedicatedConnectionSets.get(db);
|
||||
return set ? { ...set.stats } : null;
|
||||
}
|
||||
|
||||
function trackClientEnd(client: Db, onEnd: (timeoutSeconds: number | undefined) => Promise<void> | void): void {
|
||||
const sql = client.$client;
|
||||
@@ -317,25 +423,36 @@ export function createOwnedDatabaseListener(db: Db): OwnedDatabaseListener {
|
||||
};
|
||||
}
|
||||
|
||||
export async function withDedicatedDbConnection<T>(db: Db, action: (dedicated: Db) => Promise<T>): Promise<T> {
|
||||
export type DedicatedDbConnectionOptions = { admitWithoutWaiting?: boolean };
|
||||
|
||||
export async function withDedicatedDbConnection<T>(db: Db, action: (dedicated: Db) => Promise<T>,
|
||||
options: DedicatedDbConnectionOptions = {}): Promise<T> {
|
||||
const set = dedicatedConnectionSets.get(db);
|
||||
if (!set) throw new Error("dedicated_connection_requires_create_db");
|
||||
await admitDedicatedConnection(set, options.admitWithoutWaiting === true || holdsLiveDedicatedOrTransaction(set));
|
||||
const hold: DedicatedConnectionHold = { set, active: true };
|
||||
let dedicated: Db | undefined;
|
||||
while (!dedicated && set.idle.length) {
|
||||
const candidate = set.idle.pop()!;
|
||||
if (!set.ended.has(candidate)) dedicated = candidate;
|
||||
}
|
||||
dedicated ??= set.create();
|
||||
let completed = false;
|
||||
try {
|
||||
const result = await action(dedicated);
|
||||
while (!dedicated && set.idle.length) {
|
||||
const candidate = set.idle.pop()!;
|
||||
if (!set.ended.has(candidate)) dedicated = candidate;
|
||||
}
|
||||
dedicated ??= set.create();
|
||||
const connection = dedicated;
|
||||
const result = await heldDedicatedConnections.run([...(heldDedicatedConnections.getStore() ?? []), hold], () => action(connection));
|
||||
completed = true;
|
||||
return result;
|
||||
} finally {
|
||||
if (completed && !set.closed && !set.ended.has(dedicated) && set.idle.length < DEDICATED_CONNECTION_IDLE_MAX) {
|
||||
set.idle.push(dedicated);
|
||||
} else if (!set.ended.has(dedicated)) {
|
||||
await dedicated.$client.end({ timeout: 1 });
|
||||
hold.active = false;
|
||||
try {
|
||||
if (dedicated && completed && !set.closed && !set.ended.has(dedicated) && set.idle.length < DEDICATED_CONNECTION_IDLE_MAX) {
|
||||
set.idle.push(dedicated);
|
||||
} else if (dedicated && !set.ended.has(dedicated)) {
|
||||
await dedicated.$client.end({ timeout: 1 });
|
||||
}
|
||||
} finally {
|
||||
releaseDedicatedSlot(set);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -346,7 +463,6 @@ export async function withDedicatedDbConnection<T>(db: Db, action: (dedicated: D
|
||||
// private pool, created on first use and shared for the owner's lifetime.
|
||||
const livenessDbFactories = new WeakMap<object, () => Db>();
|
||||
const livenessDbs = new WeakMap<object, Db>();
|
||||
const LIVENESS_POOL_MAX_CONNECTIONS = 2;
|
||||
|
||||
/** The private liveness pool for a `createDb` client; other clients (test
|
||||
* doubles, transactions) are returned unchanged. */
|
||||
@@ -415,7 +531,6 @@ export async function closeLivenessDb(db: Db, timeoutSeconds: number): Promise<v
|
||||
// during an aligned burst. Share at most three lazy connections per owner.
|
||||
const checkpointDbFactories = new WeakMap<object, () => Db>();
|
||||
const checkpointDbs = new WeakMap<object, Db>();
|
||||
const CHECKPOINT_POOL_MAX_CONNECTIONS = 3;
|
||||
const closedCheckpointOwners = new WeakSet<object>();
|
||||
|
||||
/** The bounded controller checkpoint pool; transactions and test doubles keep
|
||||
@@ -465,7 +580,10 @@ export function createDb(url: string, options?: DatabaseClientOptions) {
|
||||
|
||||
function createDbClient(url: string, resolved: DatabaseClientOptions, owner?: object, dedicatedSet?: DedicatedConnectionSet) {
|
||||
const sql = postgres(url, postgresJsOptions(resolved));
|
||||
if (resolved.prepare === true) installPreparedQueries(sql);
|
||||
const preparedState = resolved.prepare === true
|
||||
? (owner && preparedQueryStates.get(owner)) || createPreparedQueryState()
|
||||
: undefined;
|
||||
if (preparedState) installPreparedQueries(sql, preparedState);
|
||||
const key = hostPortKeyOrNull(url);
|
||||
if (key) registerClient(key, sql);
|
||||
// A disconnect can lose the response after a statement has committed.
|
||||
@@ -474,6 +592,8 @@ function createDbClient(url: string, resolved: DatabaseClientOptions, owner?: ob
|
||||
// that know the complete operation is idempotent.
|
||||
const db = installDatabaseWorkSignals(drizzleWithLazyTransactionQueries(sql, schema), owner);
|
||||
installDatabaseResponseCapture(db, schema);
|
||||
markOpenTransactions(db);
|
||||
if (preparedState) preparedQueryStates.set(db, preparedState);
|
||||
const ownerSet = owner ? dedicatedConnectionSets.get(owner) : undefined;
|
||||
if (dedicatedSet) {
|
||||
trackClientEnd(db, () => { dedicatedSet.ended.add(db); });
|
||||
@@ -481,12 +601,9 @@ function createDbClient(url: string, resolved: DatabaseClientOptions, owner?: ob
|
||||
} else if (ownerSet) {
|
||||
dedicatedConnectionSets.set(db, ownerSet);
|
||||
} else {
|
||||
const set: DedicatedConnectionSet = {
|
||||
create: () => createDbClient(url, {
|
||||
...resolved, maxConnections: 1, applicationName: "paperclip-workspace-finalization-lock",
|
||||
}, db, set),
|
||||
idle: [], ended: new WeakSet(), closed: false,
|
||||
};
|
||||
const set: DedicatedConnectionSet = dedicatedConnectionSet(() => createDbClient(url, {
|
||||
...resolved, maxConnections: 1, applicationName: "paperclip-workspace-finalization-lock",
|
||||
}, db, set), resolved);
|
||||
dedicatedConnectionSets.set(db, set);
|
||||
trackClientEnd(db, timeoutSeconds => closeDedicatedDbConnections(db, timeoutSeconds ?? 1));
|
||||
}
|
||||
@@ -494,20 +611,20 @@ function createDbClient(url: string, resolved: DatabaseClientOptions, owner?: ob
|
||||
...resolved, maxConnections: 1,
|
||||
}, db));
|
||||
livenessDbFactories.set(db, () => createDbClient(url, {
|
||||
...resolved, maxConnections: LIVENESS_POOL_MAX_CONNECTIONS, applicationName: "paperclip-controller-lease",
|
||||
...resolved, maxConnections: PRIVATE_POOL_MAX_CONNECTIONS.liveness, applicationName: "paperclip-controller-lease",
|
||||
}, db));
|
||||
controllerLeaseDbFactories.set(db, () => createDbClient(url, {
|
||||
...resolved, maxConnections: 1, applicationName: "paperclip-legacy-controller-lease",
|
||||
...resolved, maxConnections: PRIVATE_POOL_MAX_CONNECTIONS.legacyControllerLease, applicationName: "paperclip-legacy-controller-lease",
|
||||
}, db));
|
||||
controllerInstanceLeaseDbFactories.set(db, statementTimeoutMs => createDbClient(url, {
|
||||
...resolved, maxConnections: 1, applicationName: "paperclip-controller-instance-lease",
|
||||
...resolved, maxConnections: PRIVATE_POOL_MAX_CONNECTIONS.controllerInstanceLease, applicationName: "paperclip-controller-instance-lease",
|
||||
...(statementTimeoutMs !== null ? { statementTimeoutMs } : {}),
|
||||
}, db));
|
||||
checkpointDbFactories.set(db, () => createDbClient(url, {
|
||||
...resolved, maxConnections: CHECKPOINT_POOL_MAX_CONNECTIONS, applicationName: "paperclip-runner-checkpoint",
|
||||
...resolved, maxConnections: PRIVATE_POOL_MAX_CONNECTIONS.checkpoint, applicationName: "paperclip-runner-checkpoint",
|
||||
}, db));
|
||||
fileStorageDbFactories.set(db, () => createDbClient(url, {
|
||||
...resolved, maxConnections: 2, applicationName: "paperclip-file-storage",
|
||||
...resolved, maxConnections: PRIVATE_POOL_MAX_CONNECTIONS.fileStorage, applicationName: "paperclip-file-storage",
|
||||
}, db));
|
||||
return db;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
import { sql } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
import {
|
||||
DEDICATED_CONNECTION_IDLE_MAX,
|
||||
DEFAULT_DEDICATED_CONNECTION_MAX,
|
||||
PRIVATE_POOL_MAX_CONNECTIONS,
|
||||
checkpointDb,
|
||||
closeCheckpointDb,
|
||||
closeDedicatedDbConnections,
|
||||
closeFileStorageDb,
|
||||
closeLivenessDb,
|
||||
controllerInstanceLeaseDb,
|
||||
controllerLeaseDb,
|
||||
createDb,
|
||||
databaseConnectionBudget,
|
||||
dedicatedDbConnectionStats,
|
||||
fileStorageDb,
|
||||
livenessDb,
|
||||
withDedicatedDbConnection,
|
||||
type DatabaseClientOptions,
|
||||
type Db,
|
||||
} from "./client.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
const APPLICATION_NAME = "paperclip-workspace-finalization-lock";
|
||||
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
|
||||
|
||||
function percentile(values: number[], p: number): number {
|
||||
const sorted = [...values].sort((a, b) => a - b);
|
||||
return sorted.length ? sorted[Math.min(sorted.length - 1, Math.ceil(p * sorted.length) - 1)]! : 0;
|
||||
}
|
||||
|
||||
describe.skipIf(!support.supported)("withDedicatedDbConnection admission", () => {
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let observer: Db;
|
||||
const owners: Db[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
temporary = await startEmbeddedPostgresTestDatabase("dedicated-admission-");
|
||||
observer = createDb(temporary.connectionString, { maxConnections: 1, applicationName: "dedicated-admission-observer" });
|
||||
await observer.execute(sql`create table admission_rows (id int primary key)`);
|
||||
await observer.execute(sql`insert into admission_rows values (1)`);
|
||||
}, 90_000);
|
||||
afterEach(async () => {
|
||||
for (const db of owners.splice(0)) {
|
||||
await closeDedicatedDbConnections(db, 1);
|
||||
await db.$client.end({ timeout: 1 });
|
||||
}
|
||||
});
|
||||
afterAll(async () => {
|
||||
await observer?.$client.end({ timeout: 1 });
|
||||
await temporary?.cleanup();
|
||||
});
|
||||
|
||||
function owner(options: DatabaseClientOptions = {}) {
|
||||
const db = createDb(temporary.connectionString, { maxConnections: 2, ...options });
|
||||
owners.push(db);
|
||||
return db;
|
||||
}
|
||||
|
||||
async function openDedicatedSessions(): Promise<number> {
|
||||
const [row] = await observer.execute<{ open: number }>(sql`select count(*)::int as open from pg_stat_activity
|
||||
where application_name = ${APPLICATION_NAME} and datname = current_database()`);
|
||||
return Number(row?.open ?? 0);
|
||||
}
|
||||
|
||||
async function restartBurst(db: Db, runs: number, holdMs: number) {
|
||||
const waits: number[] = [];
|
||||
let failures = 0;
|
||||
let peakSessions = 0;
|
||||
let sampling = true;
|
||||
const sampler = (async () => {
|
||||
while (sampling) {
|
||||
peakSessions = Math.max(peakSessions, await openDedicatedSessions());
|
||||
await sleep(20);
|
||||
}
|
||||
})();
|
||||
const startedAt = performance.now();
|
||||
await Promise.all(Array.from({ length: runs }, (_, index) => {
|
||||
const requestedAt = performance.now();
|
||||
return withDedicatedDbConnection(db, source => source.transaction(async tx => {
|
||||
waits.push(performance.now() - requestedAt);
|
||||
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`burst-source:${index}`}, 0))`);
|
||||
await withDedicatedDbConnection(db, lifecycle => lifecycle.transaction(async nested => {
|
||||
await nested.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`burst-lifecycle:${index}`}, 0))`);
|
||||
await sleep(holdMs / 2);
|
||||
}));
|
||||
await sleep(holdMs / 2);
|
||||
})).catch(() => { failures++; });
|
||||
}));
|
||||
const elapsedMs = performance.now() - startedAt;
|
||||
sampling = false;
|
||||
await sampler;
|
||||
return { runs, failures, peakSessions, peakInUse: dedicatedDbConnectionStats(db)!.peakInUse,
|
||||
waitP50Ms: Math.round(percentile(waits, 0.5)), waitP99Ms: Math.round(percentile(waits, 0.99)), elapsedMs: Math.round(elapsedMs) };
|
||||
}
|
||||
|
||||
it("never queues a caller while fewer than the limit are in use", async () => {
|
||||
const db = owner();
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
const waits: number[] = [];
|
||||
const holders = Array.from({ length: 20 }, () => {
|
||||
const requestedAt = performance.now();
|
||||
return withDedicatedDbConnection(db, async dedicated => {
|
||||
waits.push(performance.now() - requestedAt);
|
||||
await dedicated.execute(sql`select 1`);
|
||||
await gate;
|
||||
});
|
||||
});
|
||||
await expect.poll(() => waits.length).toBe(20);
|
||||
release();
|
||||
await Promise.all(holders);
|
||||
expect(dedicatedDbConnectionStats(db)).toMatchObject({ limit: DEFAULT_DEDICATED_CONNECTION_MAX, queued: 0, overLimit: 0, inUse: 0, peakInUse: 20 });
|
||||
});
|
||||
|
||||
it.each([200, 1_000])("bounds the sessions of a %i-run restart burst whose source lock nests a lifecycle lock", async runs => {
|
||||
const limit = DEFAULT_DEDICATED_CONNECTION_MAX;
|
||||
const db = owner();
|
||||
const result = await restartBurst(db, runs, 40);
|
||||
console.info(JSON.stringify({ metric: "dedicated_connection_restart_burst", limit, ...result }));
|
||||
expect(result.failures).toBe(0);
|
||||
expect(result.peakInUse).toBeLessThanOrEqual(2 * limit);
|
||||
expect(result.peakSessions).toBeLessThanOrEqual(2 * limit + DEDICATED_CONNECTION_IDLE_MAX);
|
||||
expect(dedicatedDbConnectionStats(db)).toMatchObject({ inUse: 0, waiting: 0, overLimit: 0 });
|
||||
}, 120_000);
|
||||
|
||||
it("admits queued callers in arrival order as slots free one at a time", async () => {
|
||||
const db = owner({ dedicatedConnectionMax: 1 });
|
||||
const releases: Array<() => void> = [];
|
||||
const admitted: string[] = [];
|
||||
const hold = (label: string) => withDedicatedDbConnection(db, async dedicated => {
|
||||
admitted.push(label);
|
||||
await dedicated.execute(sql`select 1`);
|
||||
await new Promise<void>(resolve => { releases.push(resolve); });
|
||||
});
|
||||
const first = hold("first");
|
||||
await expect.poll(() => releases.length).toBe(1);
|
||||
const queued = ["a", "b", "c", "d"].map(label => hold(label));
|
||||
await expect.poll(() => dedicatedDbConnectionStats(db)!.waiting).toBe(4);
|
||||
for (let expected = 2; expected <= 5; expected++) {
|
||||
releases.shift()!();
|
||||
await expect.poll(() => releases.length).toBe(1);
|
||||
expect(admitted).toHaveLength(expected);
|
||||
expect(dedicatedDbConnectionStats(db)!.inUse).toBe(1);
|
||||
}
|
||||
releases.shift()!();
|
||||
await Promise.all([first, ...queued]);
|
||||
expect(admitted).toEqual(["first", "a", "b", "c", "d"]);
|
||||
expect(dedicatedDbConnectionStats(db)).toMatchObject({ inUse: 0, waiting: 0, queued: 4, overLimit: 0 });
|
||||
});
|
||||
|
||||
it("lets every holder take its nested connection while the limit is full and others queue", async () => {
|
||||
const db = owner({ dedicatedConnectionMax: 2 });
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
let holding = 0;
|
||||
const holders = Array.from({ length: 2 }, (_, index) => withDedicatedDbConnection(db, outer => outer.transaction(async tx => {
|
||||
await tx.execute(sql`select pg_advisory_xact_lock(${1000 + index})`);
|
||||
holding++;
|
||||
await gate;
|
||||
return withDedicatedDbConnection(db, inner => inner.transaction(async nested => {
|
||||
await nested.execute(sql`select pg_advisory_xact_lock(${2000 + index})`);
|
||||
return index;
|
||||
}));
|
||||
})));
|
||||
await expect.poll(() => holding).toBe(2);
|
||||
const queued = withDedicatedDbConnection(db, dedicated => dedicated.execute(sql`select 1`));
|
||||
await expect.poll(() => dedicatedDbConnectionStats(db)!.waiting).toBe(1);
|
||||
release();
|
||||
await expect(Promise.race([Promise.all(holders), sleep(5_000).then(() => "deadlocked")])).resolves.toEqual([0, 1]);
|
||||
await queued;
|
||||
expect(dedicatedDbConnectionStats(db)).toMatchObject({ inUse: 0, waiting: 0, queued: 1, overLimit: 0, nestedOverLimit: 2 });
|
||||
});
|
||||
|
||||
it("admits a caller inside an open transaction without waiting, so a holder blocked on its row lock finishes", async () => {
|
||||
const db = owner({ dedicatedConnectionMax: 1 });
|
||||
let rowLocked!: () => void;
|
||||
const locked = new Promise<void>(resolve => { rowLocked = resolve; });
|
||||
let holderStarted!: () => void;
|
||||
const started = new Promise<void>(resolve => { holderStarted = resolve; });
|
||||
const writer = db.transaction(async tx => {
|
||||
await tx.execute(sql`select id from admission_rows where id = 1 for update`);
|
||||
rowLocked();
|
||||
await started;
|
||||
await sleep(50);
|
||||
return withDedicatedDbConnection(db, dedicated => dedicated.execute(sql`select 'writer' as owner`));
|
||||
});
|
||||
await locked;
|
||||
const holder = withDedicatedDbConnection(db, dedicated => dedicated.transaction(async tx => {
|
||||
holderStarted();
|
||||
await tx.execute(sql`select id from admission_rows where id = 1 for update`);
|
||||
return "holder";
|
||||
}));
|
||||
await expect(Promise.race([Promise.all([writer, holder]), sleep(10_000).then(() => "deadlocked")]))
|
||||
.resolves.toEqual([[{ owner: "writer" }], "holder"]);
|
||||
expect(dedicatedDbConnectionStats(db)).toMatchObject({ inUse: 0, overLimit: 0, nestedOverLimit: 1 });
|
||||
});
|
||||
|
||||
it("admits a caller that holds a resource the slot holder needs without waiting", async () => {
|
||||
const db = owner({ dedicatedConnectionMax: 1, dedicatedConnectionWaitMs: 60_000 });
|
||||
let releasePermit!: () => void;
|
||||
const permit = new Promise<void>(resolve => { releasePermit = resolve; });
|
||||
let holding!: () => void;
|
||||
const slotTaken = new Promise<void>(resolve => { holding = resolve; });
|
||||
const holder = withDedicatedDbConnection(db, async dedicated => {
|
||||
holding();
|
||||
await permit;
|
||||
return dedicated.execute(sql`select 'holder' as owner`);
|
||||
});
|
||||
await slotTaken;
|
||||
const reader = (async () => {
|
||||
try {
|
||||
return await withDedicatedDbConnection(db, dedicated => dedicated.execute(sql`select 'reader' as owner`), { admitWithoutWaiting: true });
|
||||
} finally { releasePermit(); }
|
||||
})();
|
||||
await expect(Promise.race([Promise.all([reader, holder]), sleep(5_000).then(() => "deadlocked")]))
|
||||
.resolves.toEqual([[{ owner: "reader" }], [{ owner: "holder" }]]);
|
||||
expect(dedicatedDbConnectionStats(db)).toMatchObject({ inUse: 0, waiting: 0, overLimit: 0 });
|
||||
});
|
||||
|
||||
it("admits a queued caller over the limit after the wait bound instead of waiting forever", async () => {
|
||||
const db = owner({ dedicatedConnectionMax: 1, dedicatedConnectionWaitMs: 100 });
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
const holder = withDedicatedDbConnection(db, async () => { await gate; });
|
||||
const requestedAt = performance.now();
|
||||
await withDedicatedDbConnection(db, dedicated => dedicated.execute(sql`select 1`));
|
||||
const waitedMs = performance.now() - requestedAt;
|
||||
release();
|
||||
await holder;
|
||||
expect(waitedMs).toBeGreaterThanOrEqual(90);
|
||||
expect(dedicatedDbConnectionStats(db)).toMatchObject({ inUse: 0, waiting: 0, queued: 1, overLimit: 1 });
|
||||
});
|
||||
|
||||
it("states a connection budget equal to the sum of every pool's maximum", async () => {
|
||||
const db = owner({ maxConnections: 7, dedicatedConnectionMax: 5 });
|
||||
const pools = [livenessDb(db), controllerLeaseDb(db), controllerInstanceLeaseDb(db), checkpointDb(db), fileStorageDb(db)];
|
||||
const poolMax = (client: Db) => Number((client.$client as unknown as { options: { max: number } }).options.max);
|
||||
try {
|
||||
const budget = databaseConnectionBudget({ maxConnections: 7, dedicatedConnectionMax: 5 });
|
||||
expect(budget.main).toBe(poolMax(db));
|
||||
expect(budget.privatePools).toBe(pools.reduce((sum, client) => sum + poolMax(client), 0));
|
||||
expect(budget.privatePools).toBe(Object.values(PRIVATE_POOL_MAX_CONNECTIONS).reduce((sum, value) => sum + value, 0));
|
||||
expect(budget.dedicated).toBe(2 * 5 + DEDICATED_CONNECTION_IDLE_MAX);
|
||||
expect(budget.total).toBe(7 + budget.privatePools + budget.listeners + budget.dedicated);
|
||||
expect(databaseConnectionBudget()).toEqual({ main: 10, privatePools: 9, listeners: 2,
|
||||
dedicatedLimit: DEFAULT_DEDICATED_CONNECTION_MAX, dedicated: 2 * DEFAULT_DEDICATED_CONNECTION_MAX + DEDICATED_CONNECTION_IDLE_MAX,
|
||||
total: 10 + 9 + 2 + 2 * DEFAULT_DEDICATED_CONNECTION_MAX + DEDICATED_CONNECTION_IDLE_MAX });
|
||||
} finally {
|
||||
await closeLivenessDb(db, 1);
|
||||
await closeCheckpointDb(db, 1);
|
||||
await closeFileStorageDb(db, 1);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,14 @@ export {
|
||||
withDedicatedDbConnection,
|
||||
closeDedicatedDbConnections,
|
||||
DEDICATED_CONNECTION_IDLE_MAX,
|
||||
DEFAULT_DEDICATED_CONNECTION_MAX,
|
||||
DEFAULT_DEDICATED_CONNECTION_WAIT_MS,
|
||||
dedicatedDbConnectionStats,
|
||||
type DedicatedDbConnectionStats,
|
||||
type DedicatedDbConnectionOptions,
|
||||
preparedStatementStats,
|
||||
databaseConnectionBudget,
|
||||
PRIVATE_POOL_MAX_CONNECTIONS,
|
||||
createOwnedDatabaseListener,
|
||||
type OwnedDatabaseListener,
|
||||
livenessDb,
|
||||
@@ -58,3 +66,4 @@ export * from "./schema/index.js";
|
||||
|
||||
export { databaseWorkScopeKey, primeDatabaseWorkTransactionId, signalDatabaseWork, subscribeDatabaseWork, databaseWorkPending, reconcileDatabaseWork } from "./work-signals.js";
|
||||
export { withDatabaseOperation } from "./response-capture.js";
|
||||
export { databaseStatementCount } from "./statement-count.js";
|
||||
@@ -5,6 +5,7 @@ import postgres from "postgres";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
import { createDb, type Db } from "./client.js";
|
||||
import { createDatabaseResponseCapture, installDatabaseResponseCapture } from "./response-capture.js";
|
||||
import { databaseStatementCount } from "./statement-count.js";
|
||||
import { announcementDismissals, announcementPublications } from "./schema/index.js";
|
||||
import {
|
||||
EMBEDDED_POSTGRES_TEST_TIMEOUT_MS,
|
||||
@@ -48,6 +49,17 @@ describeEmbeddedPostgres("transactions on the Paperclip database client", () =>
|
||||
});
|
||||
afterAll(async () => { await database?.cleanup(); });
|
||||
|
||||
it("counts each statement, inside transactions and savepoints too", async () => {
|
||||
const before = databaseStatementCount();
|
||||
await db.select().from(announcementPublications);
|
||||
await db.transaction(async (tx) => {
|
||||
await publication(tx, "counted");
|
||||
await tx.transaction(async nested => { await nested.select().from(announcementPublications); });
|
||||
await tx.query.announcementPublications.findMany();
|
||||
});
|
||||
expect(databaseStatementCount() - before).toBe(4);
|
||||
});
|
||||
|
||||
describe("relational query builders", () => {
|
||||
it("builds none for a transaction or savepoint that never reads tx.query", async () => {
|
||||
const schemaTables = Object.keys(db.query).length;
|
||||
|
||||
@@ -3,6 +3,7 @@ import { RelationalQueryBuilder } from "drizzle-orm/pg-core/query-builders/query
|
||||
import { drizzle, type PostgresJsDatabase } from "drizzle-orm/postgres-js";
|
||||
import type { TableRelationalConfig } from "drizzle-orm";
|
||||
import type postgres from "postgres";
|
||||
import { statementCountingLogger } from "./statement-count.js";
|
||||
|
||||
type Callback = (tx: Transaction) => unknown;
|
||||
type Transaction = {
|
||||
@@ -27,18 +28,19 @@ type Transaction = {
|
||||
* built, bound to that transaction's session, and `tx._` still describes the
|
||||
* schema.
|
||||
*
|
||||
* Both clients and the builders' dialect take Drizzle's defaults. A Drizzle
|
||||
* option added here (`casing`, `logger`, `cache`) must go to all three.
|
||||
* Both clients count each statement through `statementCountingLogger`, and
|
||||
* otherwise both clients and the builders' dialect take Drizzle's defaults. A
|
||||
* Drizzle option added here (`casing`, `cache`) must go to all three.
|
||||
*/
|
||||
export function drizzleWithLazyTransactionQueries<TSchema extends Record<string, unknown>, TClient extends postgres.Sql<any>>(
|
||||
client: TClient,
|
||||
schema: TSchema,
|
||||
): PostgresJsDatabase<TSchema> & { $client: TClient } {
|
||||
const db = drizzle(client, { schema });
|
||||
const db = drizzle(client, { schema, logger: statementCountingLogger });
|
||||
const tables = db._.schema;
|
||||
if (!tables) return db;
|
||||
const { fullSchema, tableNamesMap } = db._;
|
||||
const transactions = drizzle(client) as unknown as Transaction;
|
||||
const transactions = drizzle(client, { logger: statementCountingLogger }) as unknown as Transaction;
|
||||
const dialect = new PgDialect();
|
||||
const resolved = (value: unknown): PropertyDescriptor => ({ value, writable: true, enumerable: true, configurable: true });
|
||||
const lazyQuery: PropertyDescriptor = {
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import postgres from "postgres";
|
||||
import { integer, jsonb, pgTable, text } from "drizzle-orm/pg-core";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { closeLivenessDb, createDb, databaseClientOptionsFromEnv, livenessDb, withDedicatedDbConnection, type DatabaseClientOptions, type Db } from "./client.js";
|
||||
import { closeLivenessDb, createDb, databaseClientOptionsFromEnv, livenessDb, preparedStatementStats, withDedicatedDbConnection, type DatabaseClientOptions, type Db } from "./client.js";
|
||||
import { createPreparedQueryState, installPreparedQueries, preparedQueryStats } from "./prepared-queries.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js";
|
||||
import { runEventPayload } from "./run-event-payload.js";
|
||||
|
||||
const records = pgTable("prepared_query_fixture", { id: text("id").primaryKey(), companyId: text("company_id").notNull(), value: integer("value").notNull(), payload: jsonb("payload") });
|
||||
const stale = pgTable("prepared_stale_fixture", { id: text("id").primaryKey(), value: integer("value").notNull() });
|
||||
const encoded = pgTable("prepared_encoded_fixture", { id: text("id").primaryKey(), payload: runEventPayload("payload") });
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
|
||||
@@ -19,6 +22,8 @@ describe.skipIf(!support.supported)("explicit ORM prepared statements on Postgre
|
||||
await setup.execute(sql`create table prepared_query_fixture(id text primary key, company_id text not null, value integer not null, payload jsonb)`);
|
||||
await setup.execute(sql`create table prepared_encoded_fixture(id text primary key, payload jsonb)`);
|
||||
await setup.execute(sql`create table prepared_schema_change_fixture(id text primary key)`);
|
||||
await setup.execute(sql`create table prepared_stale_fixture(id text primary key, value integer not null)`);
|
||||
await setup.execute(sql`insert into prepared_stale_fixture(id, value) values ('stale', 5)`);
|
||||
await setup.execute(sql`insert into prepared_schema_change_fixture(id) values ('retained')`);
|
||||
}, 90_000);
|
||||
beforeEach(async () => {
|
||||
@@ -172,4 +177,181 @@ describe.skipIf(!support.supported)("explicit ORM prepared statements on Postgre
|
||||
await setup.execute(sql`alter table prepared_schema_change_fixture drop column if exists extra`);
|
||||
}
|
||||
});
|
||||
|
||||
async function changeStaleValueType(type: "bigint" | "integer") {
|
||||
await setup.execute(sql.raw(`alter table prepared_stale_fixture alter column value type ${type}`));
|
||||
}
|
||||
|
||||
it("restarts a transaction whose first statement meets an invalidated plan without running the callback again", async () => {
|
||||
const db = fixture({ prepare: true });
|
||||
let calls = 0;
|
||||
const read = () => db.transaction(tx => { calls++; return tx.select().from(stale).where(eq(stale.id, "stale")); });
|
||||
expect(await read()).toEqual([{ id: "stale", value: 5 }]);
|
||||
await changeStaleValueType("bigint");
|
||||
try {
|
||||
expect(await read()).toEqual([{ id: "stale", value: 5 }]);
|
||||
expect(calls).toBe(2);
|
||||
expect(preparedStatementStats(db)).toMatchObject({ restartedTransactions: 1, demoted: 1 });
|
||||
} finally {
|
||||
await changeStaleValueType("integer");
|
||||
}
|
||||
});
|
||||
|
||||
it("restarts a transaction whose first statement lost its prepared statement and keeps its later work", async () => {
|
||||
const db = fixture({ prepare: true });
|
||||
const run = (value: number) => db.transaction(async tx => {
|
||||
const [row] = await tx.select({ value: records.value }).from(records).where(eq(records.id, "a"));
|
||||
await tx.execute(sql`update prepared_query_fixture set value = ${value} where id = ${"b"} ${sql.raw(`/* run ${value} */`)}`);
|
||||
return row;
|
||||
});
|
||||
expect(await run(3)).toEqual({ value: 1 });
|
||||
const [{ name }] = await statements(db, 'select "value" from "prepared_query_fixture"%');
|
||||
await db.$client.unsafe(`deallocate "${String(name)}"`);
|
||||
expect(await run(4)).toEqual({ value: 1 });
|
||||
expect(await setup.select({ value: records.value }).from(records).where(eq(records.id, "b"))).toEqual([{ value: 4 }]);
|
||||
expect(preparedStatementStats(db)).toMatchObject({ restartedTransactions: 1, demoted: 1 });
|
||||
});
|
||||
|
||||
it("keeps the isolation level and access mode of a restarted transaction", async () => {
|
||||
const db = fixture({ prepare: true });
|
||||
const settings = "select current_setting('transaction_isolation') as isolation, current_setting('transaction_read_only') as read_only, $1::integer as marker";
|
||||
const snapshot = { isolation: "repeatable read", read_only: "on", marker: 1 };
|
||||
const readDriver = () => db.$client.begin("isolation level repeatable read read only", async tx => {
|
||||
const rows = await tx.unsafe("select id, value from prepared_stale_fixture where id = $1", ["stale"]);
|
||||
return [rows, await tx.unsafe(settings, [1])];
|
||||
});
|
||||
const readOrm = () => db.transaction(async tx => [
|
||||
await tx.select().from(stale).where(eq(stale.id, "stale")),
|
||||
await tx.execute(sql`select current_setting('transaction_isolation') as isolation, current_setting('transaction_read_only') as read_only, ${1}::integer as marker`),
|
||||
], { isolationLevel: "repeatable read", accessMode: "read only" });
|
||||
expect(await readDriver()).toEqual([[{ id: "stale", value: 5 }], [snapshot]]);
|
||||
expect(await readOrm()).toEqual([[{ id: "stale", value: 5 }], [snapshot]]);
|
||||
await changeStaleValueType("bigint");
|
||||
try {
|
||||
expect(await readDriver()).toEqual([[{ id: "stale", value: "5" }], [snapshot]]);
|
||||
expect(await readOrm()).toEqual([[{ id: "stale", value: 5 }], [snapshot]]);
|
||||
expect(preparedStatementStats(db)).toMatchObject({ restartedTransactions: 2, demoted: 2 });
|
||||
} finally {
|
||||
await changeStaleValueType("integer");
|
||||
}
|
||||
});
|
||||
|
||||
it("does not restart a transaction after its first statement and runs the invalidated text unprepared", async () => {
|
||||
const db = fixture({ prepare: true });
|
||||
let calls = 0;
|
||||
const update = () => db.transaction(async tx => {
|
||||
calls++;
|
||||
await tx.update(records).set({ value: 7 }).where(eq(records.id, "b"));
|
||||
return tx.select().from(stale).where(eq(stale.id, "stale"));
|
||||
});
|
||||
expect(await update()).toEqual([{ id: "stale", value: 5 }]);
|
||||
await changeStaleValueType("bigint");
|
||||
try {
|
||||
await expect(update()).rejects.toMatchObject({ cause: { code: "0A000" } });
|
||||
expect(calls).toBe(2);
|
||||
expect(await update()).toEqual([{ id: "stale", value: 5 }]);
|
||||
expect(await statements(db, '%"prepared_stale_fixture"%')).toHaveLength(1);
|
||||
expect(preparedStatementStats(db)).toMatchObject({ restartedTransactions: 0, demoted: 1 });
|
||||
} finally {
|
||||
await changeStaleValueType("integer");
|
||||
}
|
||||
});
|
||||
|
||||
it("counts a tagged statement as the first statement of a transaction", async () => {
|
||||
const db = fixture({ prepare: true });
|
||||
const read = "select id, value from prepared_stale_fixture where id = $1";
|
||||
expect(await db.$client.unsafe(read, ["stale"])).toEqual([{ id: "stale", value: 5 }]);
|
||||
await changeStaleValueType("bigint");
|
||||
try {
|
||||
await expect(db.$client.begin(async tx => {
|
||||
await tx`update prepared_query_fixture set value = value + 1 where id = 'a'`;
|
||||
return tx.unsafe(read, ["stale"]);
|
||||
})).rejects.toMatchObject({ code: "0A000" });
|
||||
expect(await setup.select({ value: records.value }).from(records).where(eq(records.id, "a"))).toEqual([{ value: 1 }]);
|
||||
expect(preparedStatementStats(db)).toMatchObject({ restartedTransactions: 0, demoted: 1 });
|
||||
} finally {
|
||||
await changeStaleValueType("integer");
|
||||
}
|
||||
});
|
||||
|
||||
it("rolls back only the savepoint whose first statement fails and continues the outer transaction once", async () => {
|
||||
const db = fixture({ prepare: true });
|
||||
const nestedRead = (tx: Parameters<Parameters<Db["transaction"]>[0]>[0]) =>
|
||||
tx.transaction(nested => nested.select().from(stale).where(eq(stale.id, "stale")));
|
||||
await db.transaction(async tx => { await nestedRead(tx); });
|
||||
await changeStaleValueType("bigint");
|
||||
let outerCalls = 0;
|
||||
try {
|
||||
const result = await db.transaction(async tx => {
|
||||
outerCalls++;
|
||||
await tx.execute(sql`update prepared_query_fixture set value = value + 10 where id = ${"a"}`);
|
||||
const nested = await nestedRead(tx).catch((error: { cause?: { code?: string } }) => error.cause?.code);
|
||||
await tx.execute(sql`update prepared_query_fixture set value = value + 100 where id = ${"b"}`);
|
||||
return [nested, await tx.select().from(stale).where(eq(stale.id, "stale"))];
|
||||
});
|
||||
expect(result).toEqual(["0A000", [{ id: "stale", value: 5 }]]);
|
||||
expect(outerCalls).toBe(1);
|
||||
expect(await setup.select({ id: records.id, value: records.value }).from(records).orderBy(records.id))
|
||||
.toEqual([{ id: "a", value: 11 }, { id: "b", value: 102 }]);
|
||||
expect(preparedStatementStats(db)).toMatchObject({ restartedTransactions: 0, demoted: 1 });
|
||||
} finally {
|
||||
await changeStaleValueType("integer");
|
||||
}
|
||||
});
|
||||
|
||||
async function occupyNextStatementName(db: Db) {
|
||||
const names = (await statements(db, "%")).map(row => String(row.name));
|
||||
const prefix = names.find(name => /\d$/.test(name) && !name.includes(" "))!.replace(/\d+$/, "");
|
||||
const counters = names.filter(name => name.startsWith(prefix)).map(name => Number(name.slice(prefix.length)));
|
||||
await db.$client.unsafe(`prepare "${prefix}${Math.max(...counters) + 1}" as select 1`, [], { prepare: false });
|
||||
}
|
||||
|
||||
it("retries a pooled statement unprepared when its prepared statement cannot be created", async () => {
|
||||
const db = fixture({ prepare: true });
|
||||
await statements(db, "%");
|
||||
await occupyNextStatementName(db);
|
||||
expect(await db.select({ value: records.value }).from(records).where(eq(records.id, "b"))).toEqual([{ value: 2 }]);
|
||||
await occupyNextStatementName(db);
|
||||
expect(await db.$client.unsafe("select $1::integer as raw_retry_marker", [3]).values()).toEqual([[3]]);
|
||||
expect(await statements(db)).toHaveLength(0);
|
||||
expect(await statements(db, "%raw_retry_marker%")).toHaveLength(0);
|
||||
expect(preparedStatementStats(db)).toMatchObject({ retried: 2, demoted: 2 });
|
||||
});
|
||||
|
||||
it("does not restart a transaction when a query created first executes after another statement", async () => {
|
||||
const db = fixture({ prepare: true });
|
||||
const read = "select id, value from prepared_stale_fixture where id = $1";
|
||||
expect(await db.$client.unsafe(read, ["stale"])).toEqual([{ id: "stale", value: 5 }]);
|
||||
await changeStaleValueType("bigint");
|
||||
let calls = 0;
|
||||
try {
|
||||
await expect(db.$client.begin(async tx => {
|
||||
calls++;
|
||||
const saved = tx.unsafe(read, ["stale"]);
|
||||
await tx.unsafe("select $1::integer as ordering_marker", [1]);
|
||||
return await saved;
|
||||
})).rejects.toMatchObject({ code: "0A000" });
|
||||
expect(calls).toBe(1);
|
||||
expect(preparedStatementStats(db)).toMatchObject({ restartedTransactions: 0, demoted: 1 });
|
||||
} finally {
|
||||
await changeStaleValueType("integer");
|
||||
}
|
||||
});
|
||||
|
||||
it("prepares at most the configured number of distinct texts and skips long texts", async () => {
|
||||
const raw = postgres(temporary.connectionString, { max: 1, prepare: true, onnotice: () => {} });
|
||||
const state = createPreparedQueryState({ limit: 2, maxLength: 80 });
|
||||
installPreparedQueries(raw, state);
|
||||
try {
|
||||
for (const marker of ["cap_a", "cap_b", "cap_c", "cap_d"]) {
|
||||
expect(await raw.unsafe(`select $1::integer as ${marker}`, [1])).toEqual([{ [marker]: 1 }]);
|
||||
}
|
||||
const long = `select $1::integer as cap_long /* ${"x".repeat(80)} */`;
|
||||
expect(await raw.unsafe(long, [2])).toEqual([{ cap_long: 2 }]);
|
||||
expect((await raw.unsafe("select name from pg_prepared_statements where statement like 'select $1::integer as cap_%'", [], { prepare: false })).length).toBe(2);
|
||||
expect(preparedQueryStats(state)).toMatchObject({ texts: 2, unprepared: 3 });
|
||||
} finally {
|
||||
await raw.end();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,108 @@
|
||||
type Method = (this: unknown, ...args: unknown[]) => unknown;
|
||||
|
||||
export function installPreparedQueries(client: unknown): void {
|
||||
export const PREPARED_QUERY_TEXT_LIMIT = 1_000;
|
||||
export const PREPARED_QUERY_TEXT_MAX_LENGTH = 8_192;
|
||||
|
||||
export type PreparedQueryStats = {
|
||||
texts: number;
|
||||
unprepared: number;
|
||||
demoted: number;
|
||||
retried: number;
|
||||
restartedTransactions: number;
|
||||
};
|
||||
|
||||
export type PreparedQueryState = {
|
||||
limit: number;
|
||||
maxLength: number;
|
||||
texts: Set<string>;
|
||||
demoted: Set<string>;
|
||||
stats: Omit<PreparedQueryStats, "texts">;
|
||||
};
|
||||
|
||||
type Counts = { created: number; executed: number; setup: string[] };
|
||||
type Scope = { retry: "statement" | "restart" | "none"; begin?: string; counts: Counts };
|
||||
|
||||
type PendingQuery = {
|
||||
options: Record<string, unknown>;
|
||||
reject(error: unknown): void;
|
||||
resolve(value: unknown): void;
|
||||
isRaw?: unknown;
|
||||
cursorFn?: unknown;
|
||||
forEachFn?: unknown;
|
||||
onlyDescribe?: unknown;
|
||||
then(onFulfilled: (value: unknown) => void, onRejected: (error: unknown) => void): unknown;
|
||||
};
|
||||
|
||||
export function createPreparedQueryState(options: { limit?: number; maxLength?: number } = {}): PreparedQueryState {
|
||||
return {
|
||||
limit: options.limit ?? PREPARED_QUERY_TEXT_LIMIT,
|
||||
maxLength: options.maxLength ?? PREPARED_QUERY_TEXT_MAX_LENGTH,
|
||||
texts: new Set(),
|
||||
demoted: new Set(),
|
||||
stats: { unprepared: 0, demoted: 0, retried: 0, restartedTransactions: 0 },
|
||||
};
|
||||
}
|
||||
|
||||
export function preparedQueryStats(state: PreparedQueryState): PreparedQueryStats {
|
||||
return { texts: state.texts.size, ...state.stats };
|
||||
}
|
||||
|
||||
export function isPreparedStatementFailure(error: unknown): boolean {
|
||||
if (typeof error !== "object" || error === null) return false;
|
||||
const { code, routine, message } = error as { code?: unknown; routine?: unknown; message?: unknown };
|
||||
if (code === "26000" || code === "42P05") return true;
|
||||
return code === "0A000" && (routine === "RevalidateCachedQuery"
|
||||
|| (typeof message === "string" && message.includes("cached plan must not change result type")));
|
||||
}
|
||||
|
||||
function shouldPrepare(state: PreparedQueryState, text: string): boolean {
|
||||
if (state.texts.has(text)) return true;
|
||||
if (state.demoted.has(text) || text.length > state.maxLength || state.texts.size >= state.limit) {
|
||||
state.stats.unprepared++;
|
||||
return false;
|
||||
}
|
||||
state.texts.add(text);
|
||||
return true;
|
||||
}
|
||||
|
||||
function demote(state: PreparedQueryState, text: string): void {
|
||||
if (state.demoted.has(text)) return;
|
||||
state.texts.delete(text);
|
||||
state.demoted.add(text);
|
||||
state.stats.demoted++;
|
||||
}
|
||||
|
||||
const TRANSACTION_SETUP = /^\s*set\s+transaction\b/i;
|
||||
|
||||
function scope(retry: Scope["retry"], begin?: string, counts: Counts = { created: 0, executed: 0, setup: [] }): Scope {
|
||||
return { retry, begin, counts };
|
||||
}
|
||||
|
||||
function track(query: PendingQuery, current: Counts, text: string | undefined, decide: () => unknown) {
|
||||
current.created++;
|
||||
let explicit: unknown = "prepare" in query.options ? query.options.prepare : undefined;
|
||||
const execution = { started: false, first: false };
|
||||
Object.defineProperty(query.options, "prepare", {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
get: () => {
|
||||
if (!execution.started) {
|
||||
execution.started = true;
|
||||
execution.first = current.executed === current.setup.length;
|
||||
current.executed++;
|
||||
if (execution.first && text !== undefined && query.options.simple && TRANSACTION_SETUP.test(text)) current.setup.push(text);
|
||||
}
|
||||
return explicit ?? decide();
|
||||
},
|
||||
set: (value: unknown) => { explicit = value; },
|
||||
});
|
||||
return { execution, explicit: () => explicit };
|
||||
}
|
||||
|
||||
export function installPreparedQueries(client: unknown, state: PreparedQueryState = createPreparedQueryState()): void {
|
||||
const visited = new WeakSet<object>();
|
||||
|
||||
function visit(value: unknown): void {
|
||||
function visit(value: unknown, current: Scope): void {
|
||||
if ((typeof value !== "object" || value === null) && typeof value !== "function") return;
|
||||
if (visited.has(value)) return;
|
||||
visited.add(value);
|
||||
@@ -12,22 +111,52 @@ export function installPreparedQueries(client: unknown): void {
|
||||
if (typeof unsafe === "function") {
|
||||
target.unsafe = function (this: unknown, ...args: unknown[]) {
|
||||
const index = args.length === 2 && !Array.isArray(args[1]) ? 1 : 2;
|
||||
const options = args[index];
|
||||
const options = args[index] as Record<string, unknown> | undefined;
|
||||
if (options !== undefined && (options === null || typeof options !== "object")) {
|
||||
return Reflect.apply(unsafe, this, args);
|
||||
}
|
||||
if (index === 2 && args.length < 2) args[1] = [];
|
||||
const text = args[0];
|
||||
args[index] = { prepare: true, ...options };
|
||||
return Reflect.apply(unsafe, this, args);
|
||||
};
|
||||
if (typeof text !== "string") return Reflect.apply(unsafe, this, args);
|
||||
const query = Reflect.apply(unsafe, this, args) as PendingQuery;
|
||||
const caller = (options !== undefined && "prepare" in options) || query.options.simple;
|
||||
if (!caller) delete query.options.prepare;
|
||||
const tracked = track(query, current.counts, text, () => shouldPrepare(state, text));
|
||||
const reject = query.reject;
|
||||
query.reject = (error: unknown) => {
|
||||
if (tracked.explicit() !== undefined || !isPreparedStatementFailure(error)) return reject(error);
|
||||
demote(state, text);
|
||||
if (query.cursorFn || query.forEachFn || query.onlyDescribe || options?.onexecute) return reject(error);
|
||||
const params = index === 2 ? args[1] : [];
|
||||
const unprepared = { ...options, prepare: false };
|
||||
if (current.retry === "statement") {
|
||||
state.stats.retried++;
|
||||
const retry = Reflect.apply(unsafe, this, [text, params, unprepared]) as PendingQuery;
|
||||
retry.isRaw = query.isRaw;
|
||||
retry.then(query.resolve, reject);
|
||||
return;
|
||||
}
|
||||
if (current.retry !== "restart" || !tracked.execution.first || current.counts.created !== current.counts.executed) return reject(error);
|
||||
state.stats.restartedTransactions++;
|
||||
const run = (sql: string, ...rest: unknown[]) => Reflect.apply(unsafe, this, [sql, ...rest]) as PendingQuery;
|
||||
const steps = [run("rollback"), run(`begin ${current.begin ?? ""}`.trim()), ...current.counts.setup.map(setup => run(setup))];
|
||||
const retry = run(text, params, unprepared);
|
||||
retry.isRaw = query.isRaw;
|
||||
Promise.all([...steps, retry]).then(results => query.resolve(results[results.length - 1]), reject);
|
||||
};
|
||||
return query;
|
||||
} satisfies Method;
|
||||
}
|
||||
for (const method of ["begin", "savepoint"]) {
|
||||
for (const method of ["begin", "savepoint"] as const) {
|
||||
const original = target[method];
|
||||
if (typeof original !== "function") continue;
|
||||
target[method] = function (this: unknown, ...args: unknown[]) {
|
||||
const wrapped = args.map(arg => typeof arg !== "function" ? arg : function (this: unknown, ...inner: unknown[]) {
|
||||
visit(inner[0]);
|
||||
return Reflect.apply(arg, this, inner);
|
||||
const begin = method === "begin" && typeof args[0] === "string" ? args[0].replace(/[^a-z ]/ig, "") : undefined;
|
||||
const inner = method === "begin" ? scope("restart", begin) : scope("none", undefined, current.counts);
|
||||
const wrapped = args.map(arg => typeof arg !== "function" ? arg : function (this: unknown, ...params: unknown[]) {
|
||||
visit(params[0], inner);
|
||||
return Reflect.apply(arg, this, [counted(params[0], inner), ...params.slice(1)]);
|
||||
});
|
||||
return Reflect.apply(original, this, wrapped);
|
||||
} satisfies Method;
|
||||
@@ -36,12 +165,26 @@ export function installPreparedQueries(client: unknown): void {
|
||||
if (typeof reserve === "function") {
|
||||
target.reserve = function (this: unknown, ...args: unknown[]) {
|
||||
return Promise.resolve(Reflect.apply(reserve, this, args)).then(reserved => {
|
||||
visit(reserved);
|
||||
visit(reserved, scope("none"));
|
||||
return reserved;
|
||||
});
|
||||
} satisfies Method;
|
||||
}
|
||||
}
|
||||
|
||||
visit(client);
|
||||
function counted(sql: unknown, current: Scope): unknown {
|
||||
if (typeof sql !== "function") return sql;
|
||||
return new Proxy(sql, {
|
||||
apply(target, self, args) {
|
||||
const result = Reflect.apply(target, self, args) as unknown;
|
||||
const strings = args[0] as { raw?: unknown } | undefined;
|
||||
if (Array.isArray(strings?.raw) && result instanceof Promise && "options" in result) {
|
||||
track(result as unknown as PendingQuery, current.counts, undefined, () => true);
|
||||
}
|
||||
return result;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
visit(client, scope("statement"));
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Logger } from "drizzle-orm";
|
||||
|
||||
let statements = 0;
|
||||
|
||||
export const statementCountingLogger: Logger = {
|
||||
logQuery(): void {
|
||||
statements += 1;
|
||||
},
|
||||
};
|
||||
|
||||
export function databaseStatementCount(): number {
|
||||
return statements;
|
||||
}
|
||||
@@ -137,7 +137,7 @@ export { RunnerdDotDriver, type RunnerdDotDriverOptions } from "./drivers/dot/ru
|
||||
|
||||
export type { RunnerExecutionDriver } from "./control-plane/runner-execution-driver.js";
|
||||
|
||||
export { RUNNER_GITHUB_LAUNCHER_VERSION, bindRunnerLaunchResources, createRunnerProviderLaunch, runnerProviderLaunchRequirements, runnerLaunchRequirementsDigest, validatePreparedRunnerLaunch } from "./live/runner-provider-launch.js";
|
||||
export { RUNNER_GITHUB_LAUNCHER_VERSION, bindRunnerLaunchResources, createRunnerProviderLaunch, runnerProviderLaunchRequirements, runnerLaunchPreparationDigest, runnerLaunchRequirementsDigest, runnerLaunchRunDigest, validatePreparedRunnerLaunch } from "./live/runner-provider-launch.js";
|
||||
export type { RunnerProviderLaunchRequirements, RunnerProviderLaunchEnvironment, PreparedRunnerProviderLaunch, RunnerLaunchPreparer } from "./live/runner-provider-launch.js";
|
||||
|
||||
export { resolveGrokDisableWebSearch } from "./drivers/acpx/grok-web-search.js";
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { canonicalNativeRuntimeContextDigest, composeNativeSystemInstructions, NATIVE_RUNTIME_ASSET_SCHEMA } from "../contracts/runtime-context.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { bindRunnerLaunchResources, createRunnerProviderLaunch, runnerLaunchRequirementsDigest, runnerProviderLaunchRequirements,
|
||||
import { bindRunnerLaunchResources, createRunnerProviderLaunch, runnerLaunchPreparationDigest, runnerLaunchRequirementsDigest, runnerLaunchRunDigest, runnerProviderLaunchRequirements,
|
||||
validatePreparedRunnerLaunch, type RunnerProviderLaunchRequirements } from "./runner-provider-launch.js";
|
||||
|
||||
const identity = { runnerInstanceId: "runner", environmentLeaseId: "lease", runId: "run",
|
||||
@@ -96,3 +96,83 @@ describe("environment-owned launch contract", () => {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("launch preparation and run digests", () => {
|
||||
const nextRun = { ...identity, runId: "next-run", turnId: "next-turn", itemId: "next-item" };
|
||||
const withIdentity = (value: typeof identity) => ({ ...requirements(), identity: value });
|
||||
|
||||
it("keeps the preparation digest across runs of one Runner and changes the run digest", () => {
|
||||
const first = runnerLaunchPreparationDigest(requirements());
|
||||
expect(runnerLaunchPreparationDigest(withIdentity(nextRun))).toBe(first);
|
||||
expect(first).toMatch(/^sha256:[a-f0-9]{64}$/);
|
||||
expect(first).not.toBe(runnerLaunchRequirementsDigest(requirements()));
|
||||
const run = runnerLaunchRunDigest(first, withIdentity(identity));
|
||||
expect(run).toMatch(/^sha256:[a-f0-9]{64}$/);
|
||||
expect(runnerLaunchRunDigest(first, withIdentity(nextRun))).not.toBe(run);
|
||||
expect(runnerLaunchRunDigest(first, withIdentity({ ...identity, itemId: "other-item" }))).not.toBe(run);
|
||||
expect(runnerLaunchRunDigest(first, withIdentity(identity))).toBe(run);
|
||||
});
|
||||
|
||||
const zero = "0".repeat(64);
|
||||
const one = "1".repeat(64);
|
||||
type Context = NonNullable<RunnerProviderLaunchRequirements["runtimeContext"]>;
|
||||
const baseContext = (): Omit<Context, "aggregateDigest"> => ({
|
||||
prompt: { revision: "fixture", text: "Core policy", digest: createHash("sha256").update("Core policy").digest("hex") },
|
||||
instructions: { entryPath: "AGENTS.md", bundle: { schema: NATIVE_RUNTIME_ASSET_SCHEMA,
|
||||
rootPath: "/controller/instructions", digest: zero, manifestDigest: zero, fileCount: 1, totalBytes: 1 } },
|
||||
skills: [{ key: "assigned", runtimeName: "assigned", versionId: "v1", bundle: {
|
||||
schema: NATIVE_RUNTIME_ASSET_SCHEMA, rootPath: "/controller/skill", digest: zero, manifestDigest: zero, fileCount: 1, totalBytes: 1 } }],
|
||||
mcp: { assignmentSetId: "assigned", digest: zero, bindingId: "native-mcp:run" },
|
||||
});
|
||||
const withContext = (value: typeof identity, change: (context: Omit<Context, "aggregateDigest">) => void = () => {}): RunnerProviderLaunchRequirements => {
|
||||
const context = baseContext();
|
||||
change(context);
|
||||
return { ...requirements(), identity: value, runtimeContext: { ...context, aggregateDigest: canonicalNativeRuntimeContextDigest(context) } };
|
||||
};
|
||||
|
||||
// MCP reaches the Runner through Core's tool authority on every run attachment, never through files the environment
|
||||
// publishes, and Core keeps a warm session across an MCP-only change. So MCP belongs to the run digest only.
|
||||
it("keeps the preparation digest across warm runs whose runtime context changes only in MCP", () => {
|
||||
const first = withContext(identity);
|
||||
const digest = runnerLaunchPreparationDigest(first);
|
||||
const mcpChanges: Array<[string, RunnerProviderLaunchRequirements]> = [
|
||||
["the run's binding", withContext(nextRun, context => { context.mcp.bindingId = "native-mcp:next-run"; })],
|
||||
["no binding", withContext(nextRun, context => { context.mcp.bindingId = null; })],
|
||||
["the assigned access set", withContext(nextRun, context => { context.mcp = { assignmentSetId: "other-set", digest: one, bindingId: "native-mcp:next-run" }; })],
|
||||
];
|
||||
for (const [label, next] of mcpChanges) {
|
||||
expect(runnerLaunchPreparationDigest(next), label).toBe(digest);
|
||||
expect(runnerLaunchRunDigest(digest, next), label).not.toBe(runnerLaunchRunDigest(digest, first));
|
||||
}
|
||||
// Within one run, an MCP change still changes the run digest.
|
||||
const sameRun = withContext(identity, context => { context.mcp.assignmentSetId = "other-set"; });
|
||||
expect(runnerLaunchRunDigest(digest, sameRun)).not.toBe(runnerLaunchRunDigest(digest, first));
|
||||
});
|
||||
|
||||
it.each([
|
||||
["instruction bundle", (context: Omit<Context, "aggregateDigest">) => { context.instructions.bundle.digest = one; }],
|
||||
["instruction entry", (context: Omit<Context, "aggregateDigest">) => { context.instructions.entryPath = "CLAUDE.md"; }],
|
||||
["skill bundle", (context: Omit<Context, "aggregateDigest">) => { context.skills[0]!.bundle.digest = one; }],
|
||||
["skill set", (context: Omit<Context, "aggregateDigest">) => { context.skills = []; }],
|
||||
["instruction working copy", (context: Omit<Context, "aggregateDigest">) => {
|
||||
context.instructions.workingCopy = { rootPath: "/workspace/.paperclip-runtime/agent-files/agent/run", entryPath: "AGENTS.md", kind: "agent_files" }; }],
|
||||
["connection instructions", (context: Omit<Context, "aggregateDigest">) => { context.connectionInstructions = { text: "Use the connector.", digest: one }; }],
|
||||
])("changes the preparation digest when the %s changes", (_label, change) => {
|
||||
expect(runnerLaunchPreparationDigest(withContext(identity, change))).not.toBe(runnerLaunchPreparationDigest(withContext(identity)));
|
||||
});
|
||||
|
||||
it.each([
|
||||
["runner instance", withIdentity({ ...identity, runnerInstanceId: "other-runner" })],
|
||||
["environment lease", withIdentity({ ...identity, environmentLeaseId: "other-lease" })],
|
||||
["session", withIdentity({ ...identity, normalizedSessionId: "other-session" })],
|
||||
["instructions", { ...requirements(), instructions: "Changed instructions" }],
|
||||
["model", { ...requirements(), model: "other-model" }],
|
||||
["approval policy", { ...requirements(), approvalPolicy: "never" as const }],
|
||||
["settings", { ...requirements(), settings: { ...requirements().settings, disableCodexWebSearch: true } }],
|
||||
])("changes the preparation digest when the %s changes", (_label, changed) => {
|
||||
const before = runnerLaunchPreparationDigest(requirements());
|
||||
const after = runnerLaunchPreparationDigest(changed as RunnerProviderLaunchRequirements);
|
||||
expect(after).not.toBe(before);
|
||||
expect(runnerLaunchRunDigest(after, withIdentity(identity))).not.toBe(runnerLaunchRunDigest(before, withIdentity(identity)));
|
||||
});
|
||||
});
|
||||
@@ -93,13 +93,51 @@ export function bindRunnerLaunchResources(
|
||||
};
|
||||
}
|
||||
|
||||
export function runnerLaunchRequirementsDigest(requirements: RunnerProviderLaunchRequirements): string {
|
||||
const canonical = JSON.stringify(requirements, (_key, value: unknown) =>
|
||||
value && typeof value === "object" && !Array.isArray(value)
|
||||
? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : value);
|
||||
function canonicalDigest(value: unknown): string {
|
||||
const canonical = JSON.stringify(value, (_key, entry: unknown) =>
|
||||
entry && typeof entry === "object" && !Array.isArray(entry)
|
||||
? Object.fromEntries(Object.entries(entry).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : entry);
|
||||
return `sha256:${createHash("sha256").update(canonical).digest("hex")}`;
|
||||
}
|
||||
|
||||
export function runnerLaunchRequirementsDigest(requirements: RunnerProviderLaunchRequirements): string {
|
||||
return canonicalDigest(requirements);
|
||||
}
|
||||
|
||||
/**
|
||||
* The launch requirements an environment reconciles when it prepares a Runner: the runner, lease and session identity,
|
||||
* provider, model and settings, the prompt and instruction text, and the runtime context's instruction and skill
|
||||
* bundles, working copy and connection instructions. It leaves out what names one run (the run, turn and item ids) and
|
||||
* the runtime context's MCP assignment and binding: MCP reaches the Runner through Core's tool authority on every run
|
||||
* attachment, never through files the environment publishes, and Core already continues a warm session across an
|
||||
* MCP-only change (`nativeRuntimeContextsMatch` with tool refresh). The context's `aggregateDigest` is left out with it,
|
||||
* since it hashes the MCP assignment and every other field it covers is in this digest directly.
|
||||
*/
|
||||
export function runnerLaunchPreparationDigest(requirements: RunnerProviderLaunchRequirements): string {
|
||||
const { runId: _runId, turnId: _turnId, itemId: _itemId, ...identity } = requirements.identity;
|
||||
let runtimeContext: Omit<NativeRuntimeContextSnapshot, "mcp" | "aggregateDigest"> | null = null;
|
||||
if (requirements.runtimeContext) {
|
||||
const { mcp: _mcp, aggregateDigest: _aggregateDigest, ...prepared } = requirements.runtimeContext;
|
||||
runtimeContext = prepared;
|
||||
}
|
||||
return canonicalDigest({ schema: "paperclip.runner.launch-preparation-digest.v1", requirements: { ...requirements, identity, runtimeContext } });
|
||||
}
|
||||
|
||||
/**
|
||||
* The preparation digest plus everything it leaves out: the run, turn and item ids, and the MCP assignment and binding.
|
||||
* It is unique to one run's launch.
|
||||
*/
|
||||
export function runnerLaunchRunDigest(preparationDigest: string, requirements: {
|
||||
identity: Pick<DurableRecoveryIdentity, "runId" | "turnId" | "itemId">;
|
||||
runtimeContext: Pick<NativeRuntimeContextSnapshot, "mcp"> | null;
|
||||
}): string {
|
||||
const { identity } = requirements;
|
||||
const mcp = requirements.runtimeContext?.mcp;
|
||||
return canonicalDigest({ schema: "paperclip.runner.launch-run-digest.v1", preparationDigest,
|
||||
runId: identity.runId, turnId: identity.turnId, itemId: identity.itemId,
|
||||
mcp: mcp ? { assignmentSetId: mcp.assignmentSetId, digest: mcp.digest, bindingId: mcp.bindingId } : null });
|
||||
}
|
||||
|
||||
function runnerLaunchPolicy(requirements: RunnerProviderLaunchRequirements): Record<string, unknown> {
|
||||
return createRunnerProviderLaunch(requirements, {
|
||||
options: { codexArgs: [] }, root: "/", cwd: "/", codexHome: "/",
|
||||
|
||||
@@ -95,6 +95,8 @@ export const environmentTaskOperationSchema = z.discriminatedUnion("kind", [
|
||||
githubBroker: githubBroker.optional(),
|
||||
recovery: preparedLaunch.optional(), resumeFrom: providerId.optional(),
|
||||
priorIdentity: durableIdentity.optional(), accountIdentity: z.string().min(1).max(1024).optional(),
|
||||
preparationDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional(),
|
||||
runDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/).optional(),
|
||||
projectIds: z.array(z.string().uuid()).max(64).refine(ids => new Set(ids).size === ids.length, "Duplicate project IDs"),
|
||||
}).strict(),
|
||||
z.object({
|
||||
@@ -186,7 +188,8 @@ export const environmentTaskResultSchema = z.discriminatedUnion("kind", [
|
||||
sha256: z.string().regex(/^[a-f0-9]{64}$/),
|
||||
}).strict(),
|
||||
z.object({ kind: z.literal("state"), taskId: providerId, state: z.record(z.string(), z.unknown()) }).strict(),
|
||||
z.object({ kind: z.literal("prepared"), taskId: providerId, launch: preparedLaunch, projectAuthCheckAtSubmit: z.literal(true).optional() }).strict(),
|
||||
z.object({ kind: z.literal("prepared"), taskId: providerId, launch: preparedLaunch, projectAuthCheckAtSubmit: z.literal(true).optional(),
|
||||
projectAuthChecked: z.literal(true).optional() }).strict(),
|
||||
z.object({ kind: z.literal("credentials"), taskId: providerId, /** Null proves that cancellation fenced admission before the task could start. It must not mean an unavailable export. */
|
||||
credential: environmentTaskCredentialSchema.nullable() }).strict(),
|
||||
z.object({ kind: z.literal("description"), taskId: providerId,
|
||||
@@ -205,6 +208,7 @@ export const environmentTaskResultSchema = z.discriminatedUnion("kind", [
|
||||
githubCredentialBrokerVersion: z.literal(1).optional(),
|
||||
configuredEnvironmentVersion: z.literal(1).optional(),
|
||||
resumeLaunchInputsVersion: z.literal(1).optional(),
|
||||
launchDigestVersion: z.literal(1).optional(),
|
||||
}).strict(),
|
||||
z.object({
|
||||
kind: z.literal("status"), taskId: providerId,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
description: The known instance-wide data is announcement dismissals, the announcement publication-ID registry, personal workspace presentation preferences, and the per-user sidebar company order; these grant no authority, and a new exception must be added to this list.
|
||||
globs: "packages/db/src/schema/announcement_dismissals.ts,packages/shared/src/announcements.ts,server/src/routes/announcements.ts,server/src/services/announcements.ts,server/src/services/announcement-feed.ts,packages/db/src/schema/user_workspace_preferences.ts,packages/shared/src/workspace-preferences.ts,server/src/routes/workspace-preferences.ts,server/src/services/workspace-preferences.ts,packages/db/src/schema/user_sidebar_preferences.ts,packages/shared/src/types/sidebar-preferences.ts,server/src/routes/sidebar-preferences.ts,server/src/services/sidebar-preferences.ts"
|
||||
description: The known instance-wide data is announcement dismissals, the announcement publication-ID registry, personal workspace presentation preferences, the per-user sidebar company order, and the instance-admin server metrics snapshot; these grant no authority, and a new exception must be added to this list.
|
||||
globs: "packages/db/src/schema/announcement_dismissals.ts,packages/shared/src/announcements.ts,server/src/routes/announcements.ts,server/src/services/announcements.ts,server/src/services/announcement-feed.ts,packages/db/src/schema/user_workspace_preferences.ts,packages/shared/src/workspace-preferences.ts,server/src/routes/workspace-preferences.ts,server/src/services/workspace-preferences.ts,packages/db/src/schema/user_sidebar_preferences.ts,packages/shared/src/types/sidebar-preferences.ts,server/src/routes/sidebar-preferences.ts,server/src/services/sidebar-preferences.ts,server/src/routes/instance-server-metrics.ts,server/src/services/server-metrics.ts"
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
@@ -29,6 +29,13 @@ company scope here.
|
||||
- **The sidebar company order** in `user_sidebar_preferences` is instance-wide by
|
||||
user, because it orders the user's companies. Sidebar preferences inside one
|
||||
company stay company-scoped in `company_user_sidebar_preferences`.
|
||||
- **The server metrics snapshot** (`GET /api/instance/server-metrics`) describes
|
||||
one server process: CPU, event-loop load, statement rate, latency
|
||||
percentiles and missed lease renewals. Company scope does not fit, because the
|
||||
process serves every company and the numbers cannot be split by company. Only
|
||||
an instance admin can read it, it is off unless `PAPERCLIP_SERVER_METRICS` is
|
||||
set, and it returns numbers and a build revision only: no SQL, names, IDs or
|
||||
hostnames. It persists nothing and changes nothing.
|
||||
|
||||
## Requirements
|
||||
|
||||
|
||||
@@ -65,6 +65,3 @@ Persisted run identity includes:
|
||||
where the run can be in flight?
|
||||
- Is the fix class-level, rather than one more per-code exception?
|
||||
- Do remote-sandbox paths have a test that applies the provider's confinement?
|
||||
|
||||
The release-compatibility contract is stated in
|
||||
[`doc/execution-semantics.md`](../doc/execution-semantics.md#94-release-compatibility-of-saved-run-state).
|
||||
@@ -6,7 +6,7 @@ import { createRequire } from "node:module";
|
||||
const { and, eq } = createRequire(new URL("../server/package.json", import.meta.url))("drizzle-orm");
|
||||
import { agents, companies, createDb, heartbeatRuns, startEmbeddedPostgresTestDatabase, type Db } from "../packages/db/src/index.js";
|
||||
import { agentRunWritesRevoked } from "../server/src/agent-run-cancellation.js";
|
||||
import { loadAgentRunAuthentication } from "../server/src/middleware/agent-run-authentication.js";
|
||||
import { agentRunAuthenticationQuery } from "../server/src/middleware/agent-run-authentication.js";
|
||||
|
||||
type Query = { sql: string; params: unknown[] };
|
||||
const baselineRef = process.argv.find(arg => arg.startsWith("--baseline-ref="))?.slice(15);
|
||||
@@ -32,7 +32,7 @@ try {
|
||||
const baseline = new Function("db", "heartbeatRuns", "and", "eq", "claims", `return ${expression}`)(
|
||||
db, heartbeatRuns, and, eq, { sub: agentId, company_id: companyId, run_id: runId },
|
||||
).toSQL() as Query;
|
||||
const treatment = loadAgentRunAuthentication(db, { companyId, agentId, runId }).toSQL();
|
||||
const treatment = agentRunAuthenticationQuery(db, { companyId, agentId, runId }).toSQL();
|
||||
|
||||
function contract(rows: unknown[][]) {
|
||||
return rows.map(([activeIdentityContextId, responsibleUserId, status, resultJson, contextSnapshot]) => ({
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import { randomBytes, randomUUID } from "node:crypto";
|
||||
import { loadavg } from "node:os";
|
||||
process.env.PAPERCLIP_SECRETS_MASTER_KEY ??= randomBytes(32).toString("base64");
|
||||
process.env.PAPERCLIP_AGENT_JWT_SECRET ??= randomBytes(32).toString("base64");
|
||||
const { agents, authUsers, companies, companyMemberships, createDb, heartbeatRuns, startEmbeddedPostgresTestDatabase } =
|
||||
await import("../packages/db/src/index.js");
|
||||
const { createLocalAgentJwt } = await import("../server/src/agent-auth-jwt.js");
|
||||
const { actorMiddleware } = await import("../server/src/middleware/auth.js");
|
||||
|
||||
const N = Number(process.env.N ?? 2000), PASSES = Number(process.env.PASSES ?? 7);
|
||||
const temporary = await startEmbeddedPostgresTestDatabase("auth-request-cpu-");
|
||||
const db = createDb(temporary.connectionString);
|
||||
try {
|
||||
const [company] = await db.insert(companies).values({ name: "Auth", issuePrefix: "AUT" }).returning();
|
||||
const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "A", adapterType: "process" }).returning();
|
||||
const userId = "user-1", runId = randomUUID();
|
||||
await db.insert(authUsers).values({ id: userId, name: "U", email: "u@example.test", createdAt: new Date(), updatedAt: new Date() });
|
||||
await db.insert(companyMemberships).values({ companyId: company!.id, principalType: "user", principalId: userId, status: "active", membershipRole: "owner" });
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: company!.id, agentId: agent!.id, status: "running", responsibleUserId: userId });
|
||||
const token = createLocalAgentJwt(agent!.id, company!.id, "process", runId, userId)!;
|
||||
const middleware = actorMiddleware(db, { deploymentMode: "authenticated", resolveSession: async () => null });
|
||||
const headers: Record<string, string> = { authorization: `Bearer ${token}`, "x-paperclip-run-id": runId };
|
||||
const once = () => new Promise<void>((resolve, reject) => {
|
||||
const req: any = { method: "GET", url: "/api/x", originalUrl: "/api/x", path: "/api/x", headers,
|
||||
header: (name: string) => headers[name.toLowerCase()], get: (name: string) => headers[name.toLowerCase()] };
|
||||
const res: any = { once() {}, on() {}, status() { return res; }, json(body: unknown) { reject(new Error(JSON.stringify(body))); }, statusCode: 200 };
|
||||
middleware(req, res, (error?: unknown) => {
|
||||
if (error) return reject(error);
|
||||
if (req.actor?.type !== "agent" || req.actor.onBehalfOfMemberships?.length !== 1) return reject(new Error(`bad actor ${JSON.stringify(req.actor)}`));
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
for (let i = 0; i < 500; i++) await once();
|
||||
const samples: number[] = [];
|
||||
for (let p = 0; p < PASSES; p++) {
|
||||
const c = process.cpuUsage();
|
||||
for (let i = 0; i < N; i++) await once();
|
||||
const u = process.cpuUsage(c);
|
||||
samples.push((u.user + u.system) / N);
|
||||
}
|
||||
samples.sort((a, b) => a - b);
|
||||
console.log(JSON.stringify({ cpuMicrosPerRequest: { median: +samples[Math.floor(PASSES / 2)]!.toFixed(1), min: +samples[0]!.toFixed(1),
|
||||
max: +samples[PASSES - 1]!.toFixed(1), all: samples.map(s => +s.toFixed(1)) }, loadavg: loadavg().map(v => +v.toFixed(1)) }));
|
||||
} finally {
|
||||
await db.$client.end({ timeout: 1 });
|
||||
await temporary.cleanup();
|
||||
}
|
||||
@@ -104,6 +104,16 @@ export function readSecrets(env: NodeJS.ProcessEnv, credentialKey: string | null
|
||||
};
|
||||
}
|
||||
|
||||
export function metricsCredential(options: Pick<Options, "metricsUrl" | "target">, secrets: Secrets): string | null {
|
||||
if (secrets.metricsToken) return secrets.metricsToken;
|
||||
if (!options.metricsUrl) return null;
|
||||
try {
|
||||
return new URL(options.metricsUrl).origin === options.target.baseUrl ? secrets.token : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function adapterOverrides(raw: string | undefined): Record<string, unknown> {
|
||||
if (!raw) return {};
|
||||
let parsed: unknown;
|
||||
|
||||
@@ -3,7 +3,7 @@ import path from "node:path";
|
||||
import { createInterface } from "node:readline/promises";
|
||||
import { cleanupRun, discoverState, type CleanupReport } from "./cleanup.ts";
|
||||
import { PaperclipClient, Redactor, realClock, type Clock, type Fetcher } from "./client.ts";
|
||||
import { FALLBACK_TOKEN_ENV, parseOptions, readSecrets, TOKEN_ENV, type Options } from "./config.ts";
|
||||
import { FALLBACK_TOKEN_ENV, metricsCredential, parseOptions, readSecrets, TOKEN_ENV, type Options } from "./config.ts";
|
||||
import { criteriaTable } from "./criteria.ts";
|
||||
import { checkSpend, estimateSpend, type SpendEstimate } from "./estimate.ts";
|
||||
import { Ramp, type RampOutcome } from "./ramp.ts";
|
||||
@@ -121,7 +121,7 @@ export async function main(argv: readonly string[], deps: MainDeps): Promise<num
|
||||
await prepareCompany({ api, options, state, store, credential: secrets.credential, log: out });
|
||||
const ramp = new Ramp({
|
||||
api, clock: deps.clock, fetcher: deps.fetcher, options, state, store, maxTasks: estimate.maxTasks,
|
||||
spendCapUsd: options.confirmSpendUsd ?? Math.max(options.spendThresholdUsd, estimate.totalUsd), metricsToken: secrets.metricsToken,
|
||||
spendCapUsd: options.confirmSpendUsd ?? Math.max(options.spendThresholdUsd, estimate.totalUsd), metricsToken: metricsCredential(options, secrets),
|
||||
log: out, shouldStop: () => interrupted,
|
||||
});
|
||||
outcome = await ramp.run();
|
||||
|
||||
@@ -130,12 +130,42 @@ function rows(body: unknown): Json[] {
|
||||
return [];
|
||||
}
|
||||
|
||||
export function serverMetrics(samples: ReadonlyArray<Record<string, unknown>>): ServerMetrics {
|
||||
type Sample = Record<string, unknown>;
|
||||
const processOf = (sample: Sample) => typeof sample.processId === "string" ? sample.processId : "";
|
||||
|
||||
function counterBaseline(first: Sample, earlier: readonly Sample[], runStartedAt: number | null, counter: string): number {
|
||||
const processId = processOf(first);
|
||||
for (let index = earlier.length - 1; index >= 0; index -= 1) {
|
||||
const value = num(earlier[index]![counter]);
|
||||
if (processOf(earlier[index]!) === processId && value !== null) return value;
|
||||
}
|
||||
const uptimeSec = num(first.uptimeSec);
|
||||
const sampledAt = num(first.sampledAt);
|
||||
if (runStartedAt !== null && uptimeSec !== null && sampledAt !== null && sampledAt - uptimeSec * 1_000 > runStartedAt) return 0;
|
||||
return num(first[counter]) ?? 0;
|
||||
}
|
||||
|
||||
function counterGrowth(samples: readonly Sample[], earlier: readonly Sample[], runStartedAt: number | null, counter: string): number | null {
|
||||
const byProcess = new Map<string, Sample[]>();
|
||||
for (const sample of samples) {
|
||||
if (num(sample[counter]) === null) continue;
|
||||
const processId = processOf(sample);
|
||||
byProcess.set(processId, [...byProcess.get(processId) ?? [], sample]);
|
||||
}
|
||||
if (byProcess.size === 0) return null;
|
||||
let growth = 0;
|
||||
for (const processSamples of byProcess.values()) {
|
||||
const last = num(processSamples[processSamples.length - 1]![counter])!;
|
||||
growth += Math.max(0, last - counterBaseline(processSamples[0]!, earlier, runStartedAt, counter));
|
||||
}
|
||||
return growth;
|
||||
}
|
||||
|
||||
export function serverMetrics(samples: ReadonlyArray<Sample>, history: { earlier?: readonly Sample[]; runStartedAt?: number | null } = {}): ServerMetrics {
|
||||
const max = (key: string) => {
|
||||
const values = samples.map(sample => num(sample[key])).filter((value): value is number => value !== null);
|
||||
return values.length ? Math.max(...values) : null;
|
||||
};
|
||||
const missed = samples.map(sample => num(sample.leaseRenewalsMissed)).filter((value): value is number => value !== null);
|
||||
return {
|
||||
mainThreadCpuMax: max("mainThreadCpu"),
|
||||
eventLoopUtilizationMax: max("eventLoopUtilization"),
|
||||
@@ -144,7 +174,7 @@ export function serverMetrics(samples: ReadonlyArray<Record<string, unknown>>):
|
||||
poolWaitP99MsMax: max("poolWaitP99Ms"),
|
||||
runEventLatenessP99MsMax: max("runEventLatenessP99Ms"),
|
||||
agentApiPreHandlerP99MsMax: max("agentApiPreHandlerP99Ms"),
|
||||
leaseRenewalsMissed: missed.length ? missed[missed.length - 1]! - missed[0]! : null,
|
||||
leaseRenewalsMissed: counterGrowth(samples, history.earlier ?? [], history.runStartedAt ?? null, "leaseRenewalsMissed"),
|
||||
samples: samples.length,
|
||||
};
|
||||
}
|
||||
@@ -467,7 +497,10 @@ export class Ramp {
|
||||
firstActivityMs: distribution(accumulator.firstActivityMs),
|
||||
runDurationMs: distribution(runs.flatMap(run => run.startedAt !== null && run.finishedAt !== null ? [run.finishedAt - run.startedAt] : [])),
|
||||
board: { requests: accumulator.boardRequests, failures: accumulator.boardFailures, ms: distribution(accumulator.boardMs) },
|
||||
server: serverMetrics(accumulator.serverSamples),
|
||||
server: serverMetrics(accumulator.serverSamples, {
|
||||
earlier: this.accumulators.slice(0, stepIndex).flatMap(earlier => earlier.serverSamples),
|
||||
runStartedAt: this.accumulators[0]?.startedAt ?? null,
|
||||
}),
|
||||
recordedSpendUsd: Math.round(spend * 100) / 100,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,16 +1,17 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { mkdtemp, readdir, readFile, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { after, describe, it } from "node:test";
|
||||
import { PaperclipClient, Redactor } from "./client.ts";
|
||||
import { parseOptions, QUALIFIED_OPENCODE_MODEL } from "./config.ts";
|
||||
import { metricsCredential, parseOptions, QUALIFIED_OPENCODE_MODEL, readSecrets } from "./config.ts";
|
||||
import { evaluate, type StepMetrics } from "./criteria.ts";
|
||||
import { checkSpend, estimateSpend } from "./estimate.ts";
|
||||
import { FakePaperclip, VirtualClock, type FakeConfig } from "./fake-paperclip.ts";
|
||||
import { classifyHost, resolveTarget, TargetRefused } from "./guard.ts";
|
||||
import { EXIT, main, type MainDeps } from "./main.ts";
|
||||
import { Ramp } from "./ramp.ts";
|
||||
import { Ramp, serverMetrics } from "./ramp.ts";
|
||||
import { verdictOf, type RampResult } from "./report.ts";
|
||||
import { ensureAgents, prepareCompany } from "./setup.ts";
|
||||
import { distribution } from "./stats.ts";
|
||||
@@ -246,6 +247,75 @@ describe("criteria", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("server metrics endpoint contract", () => {
|
||||
const fixture = JSON.parse(readFileSync(new URL("./server-metrics.fixture.json", import.meta.url), "utf8")) as Record<string, unknown>;
|
||||
const SERVER_METRICS_URL = `${ORIGIN}/api/instance/server-metrics`;
|
||||
|
||||
it("parses every finish-line field of the server's own serialized response except pool wait, which the server does not measure", () => {
|
||||
const parsed = serverMetrics([fixture, { ...fixture, leaseRenewalsMissed: 3 }]);
|
||||
assert.deepEqual(parsed, {
|
||||
mainThreadCpuMax: fixture.mainThreadCpu, eventLoopUtilizationMax: fixture.eventLoopUtilization, eventLoopDelayP99MsMax: fixture.eventLoopDelayP99Ms,
|
||||
statementsPerSecondMax: fixture.statementsPerSecond, poolWaitP99MsMax: null, runEventLatenessP99MsMax: fixture.runEventLatenessP99Ms,
|
||||
agentApiPreHandlerP99MsMax: fixture.agentApiPreHandlerP99Ms, leaseRenewalsMissed: 2, samples: 2,
|
||||
});
|
||||
assert.equal("poolWaitP99Ms" in fixture, false);
|
||||
});
|
||||
|
||||
it("counts missed lease renewals per server process, so samples from several processes never cancel out", () => {
|
||||
const parsed = serverMetrics([
|
||||
{ processId: "a", leaseRenewalsMissed: 5 }, { processId: "b", leaseRenewalsMissed: 0 },
|
||||
{ processId: "a", leaseRenewalsMissed: 6 }, { processId: "b", leaseRenewalsMissed: 2 }, { processId: "a", leaseRenewalsMissed: 6 },
|
||||
]);
|
||||
assert.equal(parsed.leaseRenewalsMissed, 3);
|
||||
});
|
||||
|
||||
it("counts the full counter of a process that started during the run, so a restart cannot hide a missed renewal", () => {
|
||||
const runStartedAt = 1_000_000;
|
||||
const earlier = [{ processId: "a", uptimeSec: 3_600, sampledAt: runStartedAt + 10_000, leaseRenewalsMissed: 4 }];
|
||||
const parsed = serverMetrics([
|
||||
{ processId: "a", uptimeSec: 3_630, sampledAt: runStartedAt + 40_000, leaseRenewalsMissed: 4 },
|
||||
{ processId: "b", uptimeSec: 20, sampledAt: runStartedAt + 70_000, leaseRenewalsMissed: 1 },
|
||||
{ processId: "b", uptimeSec: 35, sampledAt: runStartedAt + 85_000, leaseRenewalsMissed: 1 },
|
||||
], { earlier, runStartedAt });
|
||||
assert.equal(parsed.leaseRenewalsMissed, 1);
|
||||
});
|
||||
|
||||
it("keeps a process's counter baseline from earlier steps", () => {
|
||||
const runStartedAt = 1_000_000;
|
||||
const earlier = [
|
||||
{ processId: "a", uptimeSec: 3_600, sampledAt: runStartedAt + 10_000, leaseRenewalsMissed: 4 },
|
||||
{ processId: "a", uptimeSec: 3_650, sampledAt: runStartedAt + 60_000, leaseRenewalsMissed: 6 },
|
||||
];
|
||||
const parsed = serverMetrics([{ processId: "a", uptimeSec: 3_700, sampledAt: runStartedAt + 110_000, leaseRenewalsMissed: 7 }],
|
||||
{ earlier, runStartedAt });
|
||||
assert.equal(parsed.leaseRenewalsMissed, 1);
|
||||
assert.equal(serverMetrics([{ processId: "a", uptimeSec: 3_700, sampledAt: runStartedAt + 110_000, leaseRenewalsMissed: 7 }], { runStartedAt })
|
||||
.leaseRenewalsMissed, 0, "a process that predates the run and is first seen now starts from its first sample");
|
||||
});
|
||||
|
||||
it("sends the board token to a metrics URL on the target origin, and no token to another origin", () => {
|
||||
const options = parseOptions(["--base-url", ORIGIN, "--target-kind", "test-stack"], { PAPERCLIP_SCALE_METRICS_URL: SERVER_METRICS_URL }, 0);
|
||||
assert.equal(metricsCredential(options, readSecrets({ PAPERCLIP_SCALE_TOKEN: TOKEN }, null)), TOKEN);
|
||||
assert.equal(metricsCredential(options, readSecrets({ PAPERCLIP_SCALE_TOKEN: TOKEN, PAPERCLIP_SCALE_METRICS_TOKEN: METRICS_TOKEN }, null)), METRICS_TOKEN);
|
||||
const elsewhere = parseOptions(["--base-url", ORIGIN, "--target-kind", "test-stack"], { PAPERCLIP_SCALE_METRICS_URL: METRICS_URL }, 0);
|
||||
assert.equal(metricsCredential(elsewhere, readSecrets({ PAPERCLIP_SCALE_TOKEN: TOKEN }, null)), null);
|
||||
});
|
||||
|
||||
it("measures the server criteria from the server metrics endpoint with the board token in the authorization header", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness({ metricsUrl: SERVER_METRICS_URL, metrics: () => fixture }, { PAPERCLIP_SCALE_METRICS_URL: SERVER_METRICS_URL });
|
||||
await main(baseArgs(out, ["--steps", "2"]), h.deps);
|
||||
const result = await readResult(out);
|
||||
const metricsRequests = h.fake.requests.filter(request => request.url === SERVER_METRICS_URL);
|
||||
assert.ok(metricsRequests.length > 0);
|
||||
assert.ok(metricsRequests.every(request => request.authorization === `Bearer ${TOKEN}`));
|
||||
assert.equal(result.sources.serverMetrics, "PAPERCLIP_SCALE_METRICS_URL");
|
||||
const statuses = Object.fromEntries(result.steps[0]!.criteriaFinal.map(criterion => [criterion.id, criterion.status]));
|
||||
for (const id of ["main_thread_cpu", "run_event_lateness_p99", "agent_api_pre_handler_p99"]) assert.equal(statuses[id], "pass", id);
|
||||
assert.equal(statuses.lease_renewals_missed_zero, "pass");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ramp against the fake API", () => {
|
||||
it("ramps every step, measures it, passes with a metrics endpoint and cleans up", async () => {
|
||||
const out = await tempDir();
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"schema": "paperclip.server-metrics.v1",
|
||||
"processId": "a1b2c3d4e5f60718",
|
||||
"buildRevision": "0123456789abcdef0123456789abcdef01234567",
|
||||
"uptimeSec": 160,
|
||||
"sampledAt": "2026-11-14T12:01:00.000Z",
|
||||
"windowMs": 50000,
|
||||
"mainThreadCpu": 0.42,
|
||||
"processCpu": 0.55,
|
||||
"eventLoopUtilization": 0.42,
|
||||
"eventLoopDelayP99Ms": 0,
|
||||
"statementsPerSecond": 180,
|
||||
"runEventLatenessP99Ms": 120.063,
|
||||
"runEventLatenessSamples": 50,
|
||||
"agentApiPreHandlerP99Ms": 15.007,
|
||||
"agentApiPreHandlerSamples": 50,
|
||||
"leaseRenewalsMissed": 1,
|
||||
"dedicatedConnections": {
|
||||
"limit": 24,
|
||||
"inUse": 3,
|
||||
"peakInUse": 9,
|
||||
"waiting": 1,
|
||||
"queued": 12,
|
||||
"overLimit": 0,
|
||||
"nestedOverLimit": 0
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,9 @@ function createSelectChain(rowsForTable: (table: unknown) => unknown[]) {
|
||||
from(table: unknown) {
|
||||
return {
|
||||
where() {
|
||||
return Promise.resolve(rowsForTable(table));
|
||||
return Object.assign(Promise.resolve(rowsForTable(table)), {
|
||||
prepare: () => ({ execute: async () => rowsForTable(table) }),
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { fillPlaceholders, sql } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, authUsers, companies, companyMemberships, createDb, heartbeatRuns } from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { createLocalAgentJwt } from "../agent-auth-jwt.js";
|
||||
import { agentAuthenticationQuery, actorMiddleware, responsibleUserMembershipsQuery } from "../middleware/auth.js";
|
||||
import { agentRunAuthenticationQuery } from "../middleware/agent-run-authentication.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
|
||||
(support.supported ? describe : describe.skip)("agent request authentication statements", () => {
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
const companyId = randomUUID(), agentId = randomUUID(), runId = randomUUID(), userId = `user-${randomUUID()}`;
|
||||
|
||||
beforeAll(async () => {
|
||||
vi.stubEnv("PAPERCLIP_AGENT_JWT_SECRET", "agent-auth-prepared-statements-secret");
|
||||
database = await startEmbeddedPostgresTestDatabase("paperclip-agent-auth-prepared-");
|
||||
db = createDb(database.connectionString);
|
||||
await db.insert(companies).values({ id: companyId, name: "Prepared authentication", issuePrefix: "PREP" });
|
||||
await db.insert(authUsers).values({ id: userId, name: "Owner", email: "owner@example.test", emailVerified: true,
|
||||
createdAt: new Date(), updatedAt: new Date() });
|
||||
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId,
|
||||
status: "active", membershipRole: "owner" });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Worker", adapterType: "process", lifecycleHolds: [] });
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", responsibleUserId: userId,
|
||||
resultJson: { executionCancellation: { state: "none" }, freshContinuationSupersededAt: null },
|
||||
contextSnapshot: { conversationMode: true, issueId: randomUUID() } });
|
||||
}, 30_000);
|
||||
|
||||
afterAll(async () => {
|
||||
vi.unstubAllEnvs();
|
||||
await db?.$client.end({ timeout: 5 });
|
||||
await database?.cleanup();
|
||||
}, 60_000);
|
||||
|
||||
const cases = () => [
|
||||
{
|
||||
bound: agentAuthenticationQuery(db, agentId),
|
||||
prepared: agentAuthenticationQuery(db, sql.placeholder("agentId")),
|
||||
values: { agentId },
|
||||
},
|
||||
{
|
||||
bound: agentRunAuthenticationQuery(db, { runId, companyId, agentId }),
|
||||
prepared: agentRunAuthenticationQuery(db, { runId: sql.placeholder("runId"), companyId: sql.placeholder("companyId"),
|
||||
agentId: sql.placeholder("agentId") }),
|
||||
values: { runId, companyId, agentId },
|
||||
},
|
||||
{
|
||||
bound: responsibleUserMembershipsQuery(db, { companyId, userId }),
|
||||
prepared: responsibleUserMembershipsQuery(db, { companyId: sql.placeholder("companyId"), userId: sql.placeholder("userId") }),
|
||||
values: { companyId, userId },
|
||||
},
|
||||
];
|
||||
|
||||
it("sends the same statement and returns the same rows as the query builder", async () => {
|
||||
for (const { bound, prepared, values } of cases()) {
|
||||
const statement = prepared.prepare("fixture");
|
||||
const built = bound.toSQL(), placeholders = prepared.toSQL();
|
||||
expect(placeholders.sql).toBe(built.sql);
|
||||
expect(fillPlaceholders(statement.getQuery().params, values)).toEqual(built.params);
|
||||
const rows = await bound;
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(await statement.execute(values)).toStrictEqual(rows);
|
||||
}
|
||||
});
|
||||
|
||||
it("builds the request authentication statements once per database client", async () => {
|
||||
const app = express();
|
||||
app.use(actorMiddleware(db, { deploymentMode: "authenticated", resolveSession: async () => null }));
|
||||
app.get("/actor", (req, res) => { res.json(req.actor); });
|
||||
const token = createLocalAgentJwt(agentId, companyId, "process", runId, userId)!;
|
||||
const call = () => request(app).get("/actor").set("authorization", `Bearer ${token}`).set("x-paperclip-run-id", runId);
|
||||
|
||||
const select = vi.spyOn(db, "select");
|
||||
const first = await call();
|
||||
expect(first.status).toBe(200);
|
||||
expect(first.body).toMatchObject({ type: "agent", agentId, companyId, runId, onBehalfOfUserId: userId,
|
||||
onBehalfOfMemberships: [{ companyId, membershipRole: "owner", status: "active" }] });
|
||||
select.mockClear();
|
||||
|
||||
for (let index = 0; index < 3; index += 1) {
|
||||
const next = await call();
|
||||
expect(next.status).toBe(200);
|
||||
expect(next.body).toEqual(first.body);
|
||||
}
|
||||
expect(select).not.toHaveBeenCalled();
|
||||
select.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,290 @@
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { and, eq as equals } from "drizzle-orm";
|
||||
import { authUsers, companyMemberships, instanceUserRoles, issues, projects } from "@paperclipai/db";
|
||||
import { actorMiddleware } from "../middleware/auth.js";
|
||||
import { errorHandler } from "../middleware/error-handler.js";
|
||||
import { issueRoutes } from "../routes/issues.js";
|
||||
import { AUTHORIZATION_READ_MAX_AGE_MS, authorizationReadScope, readOncePerRequest } from "../services/authorization-read-scope.js";
|
||||
import { readInstanceAdmin } from "../services/authorization.js";
|
||||
import { meterDatabaseStatements } from "./helpers/database-statement-meter.js";
|
||||
import { describeEmbeddedPostgres, seedCompanyWithBoardAccess, useEmbeddedPostgres } from "./helpers/route-test-harness.js";
|
||||
|
||||
describeEmbeddedPostgres("authorization reads per request", () => {
|
||||
const ctx = useEmbeddedPostgres("authorization-request-reads-");
|
||||
|
||||
function appFor(userId: string) {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use(actorMiddleware(ctx.db, {
|
||||
deploymentMode: "authenticated",
|
||||
resolveSession: async () => ({
|
||||
session: { id: `session-${userId}`, userId },
|
||||
user: { id: userId, name: "Reader", email: `${userId}@example.test` },
|
||||
}),
|
||||
}));
|
||||
app.use(authorizationReadScope);
|
||||
app.use("/api", issueRoutes(ctx.db, {} as never));
|
||||
app.use(errorHandler);
|
||||
return app;
|
||||
}
|
||||
|
||||
async function seed(name: string) {
|
||||
const company = await seedCompanyWithBoardAccess(ctx.db, name);
|
||||
const now = new Date();
|
||||
await ctx.db.insert(authUsers).values({
|
||||
id: company.userId, name, email: `${company.userId}@example.test`, emailVerified: true, createdAt: now, updatedAt: now,
|
||||
});
|
||||
const [project] = await ctx.db.insert(projects).values({ companyId: company.companyId, name: `${name} project` }).returning();
|
||||
const [issue] = await ctx.db.insert(issues).values({
|
||||
companyId: company.companyId, title: `${name} task`, status: "todo", projectId: project!.id, createdByUserId: company.userId,
|
||||
}).returning();
|
||||
return { ...company, issue: issue! };
|
||||
}
|
||||
|
||||
it("reads the instance role once per request and the membership once for the authorization of one issue read", async () => {
|
||||
const { host, port } = (ctx.db.$client as unknown as { options: { host: string[]; port: number[] } }).options;
|
||||
const meter = meterDatabaseStatements(ctx.db, `postgres://${host[0]}:${port[0]}/authorization`);
|
||||
try {
|
||||
const fixture = await seed("Reads");
|
||||
const app = appFor(fixture.userId);
|
||||
await request(app).get(`/api/issues/${fixture.issue.id}`).expect(200);
|
||||
meter.startLog();
|
||||
await request(app).get(`/api/issues/${fixture.issue.id}`).expect(200);
|
||||
const log = meter.stopLog();
|
||||
const roleReads = log.filter((entry) => /from "instance_user_roles"/.test(entry.sql));
|
||||
const membershipReads = log.filter((entry) => /from "company_memberships"/.test(entry.sql));
|
||||
expect(roleReads).toHaveLength(1);
|
||||
expect(membershipReads).toHaveLength(2);
|
||||
|
||||
meter.startLog();
|
||||
await request(app).get(`/api/companies/${fixture.companyId}/issues`).expect(200);
|
||||
await request(app).get(`/api/companies/${fixture.companyId}/issues/summaries?ids=${fixture.issue.id}`).expect(200);
|
||||
const listLog = meter.stopLog();
|
||||
expect(listLog.filter((entry) => /from "instance_user_roles"/.test(entry.sql))).toHaveLength(2);
|
||||
} finally {
|
||||
meter.uninstall();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it("denies the very next request after the membership is removed", async () => {
|
||||
const fixture = await seed("Revoked");
|
||||
const app = appFor(fixture.userId);
|
||||
await request(app).get(`/api/issues/${fixture.issue.id}`).expect(200);
|
||||
await ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId));
|
||||
await request(app).get(`/api/issues/${fixture.issue.id}`).expect(404);
|
||||
}, 60_000);
|
||||
function membershipRead(companyId: string, userId: string) {
|
||||
return readOncePerRequest(`membership:${companyId}:user:${userId}`, () => ctx.db.select({ id: companyMemberships.id })
|
||||
.from(companyMemberships)
|
||||
.where(and(equals(companyMemberships.companyId, companyId), equals(companyMemberships.principalId, userId),
|
||||
equals(companyMemberships.status, "active")))
|
||||
.then((rows) => rows.length > 0));
|
||||
}
|
||||
|
||||
function streamApp(userId: string, companyId: string, events: { afterRevoke: Promise<void>; late: (allowed: boolean) => void }) {
|
||||
const app = express();
|
||||
app.use(actorMiddleware(ctx.db, {
|
||||
deploymentMode: "authenticated",
|
||||
resolveSession: async () => ({
|
||||
session: { id: `session-${userId}`, userId },
|
||||
user: { id: userId, name: "Reader", email: `${userId}@example.test` },
|
||||
}),
|
||||
}));
|
||||
app.use(authorizationReadScope);
|
||||
app.get("/stream", async (_req, res) => {
|
||||
const atConnect = await membershipRead(companyId, userId);
|
||||
res.writeHead(200, { "Content-Type": "text/event-stream" });
|
||||
res.flushHeaders();
|
||||
res.write(`data: ${atConnect}\n\n`);
|
||||
await events.afterRevoke;
|
||||
res.end(`data: ${await membershipRead(companyId, userId)}\n\n`);
|
||||
});
|
||||
app.get("/later", async (_req, res) => {
|
||||
await membershipRead(companyId, userId);
|
||||
setTimeout(() => { void events.afterRevoke.then(() => membershipRead(companyId, userId)).then(events.late); }, 0);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
return app;
|
||||
}
|
||||
|
||||
it("re-reads the membership during a stream after it is removed", async () => {
|
||||
const fixture = await seed("Stream");
|
||||
let revoked!: () => void;
|
||||
const afterRevoke = new Promise<void>((resolve) => { revoked = resolve; });
|
||||
const app = streamApp(fixture.userId, fixture.companyId, { afterRevoke, late: () => {} });
|
||||
const pending = request(app).get("/stream").buffer(true).parse((res, done) => {
|
||||
let text = "";
|
||||
res.on("data", (chunk: Buffer) => {
|
||||
text += chunk.toString();
|
||||
if (text.includes("data: true") && !text.includes("data: false")) {
|
||||
void ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId)).then(revoked);
|
||||
}
|
||||
});
|
||||
res.on("end", () => done(null, text));
|
||||
});
|
||||
const response = await pending;
|
||||
expect(response.body).toBe("data: true\n\ndata: false\n\n");
|
||||
}, 60_000);
|
||||
|
||||
it("re-reads in a callback that runs after the response and after a revoke", async () => {
|
||||
const fixture = await seed("Later");
|
||||
let revoked!: () => void;
|
||||
const afterRevoke = new Promise<void>((resolve) => { revoked = resolve; });
|
||||
let late!: (allowed: boolean) => void;
|
||||
const lateResult = new Promise<boolean>((resolve) => { late = resolve; });
|
||||
const app = streamApp(fixture.userId, fixture.companyId, { afterRevoke, late });
|
||||
await request(app).get("/later").expect(200);
|
||||
await ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId));
|
||||
revoked();
|
||||
expect(await lateResult).toBe(false);
|
||||
}, 60_000);
|
||||
|
||||
it("seeds the instance role from a session read that matches the authorization predicate", async () => {
|
||||
const now = new Date();
|
||||
const cases = [
|
||||
{ userId: `user-admin-${Date.now()}`, roles: ["instance_admin"], expected: true },
|
||||
{ userId: `user-other-${Date.now()}`, roles: ["instance_viewer"], expected: false },
|
||||
{ userId: `user-none-${Date.now()}`, roles: [], expected: false },
|
||||
];
|
||||
for (const entry of cases) {
|
||||
await ctx.db.insert(authUsers).values({ id: entry.userId, name: entry.userId, email: `${entry.userId}@example.test`,
|
||||
emailVerified: true, createdAt: now, updatedAt: now });
|
||||
if (entry.roles.length) await ctx.db.insert(instanceUserRoles).values(entry.roles.map((role) => ({ userId: entry.userId, role })));
|
||||
const app = express();
|
||||
app.use(actorMiddleware(ctx.db, {
|
||||
deploymentMode: "authenticated",
|
||||
resolveSession: async () => ({ session: { id: `session-${entry.userId}`, userId: entry.userId },
|
||||
user: { id: entry.userId, name: "Admin check", email: `${entry.userId}@example.test` } }),
|
||||
}));
|
||||
app.get("/actor", (req, res) => { res.json({ isInstanceAdmin: req.actor.isInstanceAdmin }); });
|
||||
const seeded = (await request(app).get("/actor").expect(200)).body.isInstanceAdmin;
|
||||
expect({ seeded, read: await readInstanceAdmin(ctx.db, entry.userId) }).toEqual({ seeded: entry.expected, read: entry.expected });
|
||||
}
|
||||
await ctx.db.delete(instanceUserRoles);
|
||||
}, 60_000);
|
||||
|
||||
it("treats HEAD like GET for an authorized read and denies it after a revoke", async () => {
|
||||
const fixture = await seed("Head");
|
||||
const app = appFor(fixture.userId);
|
||||
await request(app).head(`/api/issues/${fixture.issue.id}`).expect(200);
|
||||
await ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId));
|
||||
await request(app).head(`/api/issues/${fixture.issue.id}`).expect(404);
|
||||
}, 60_000);
|
||||
});
|
||||
|
||||
describe("authorization read scope boundaries", () => {
|
||||
afterEach(() => { vi.useRealTimers(); });
|
||||
|
||||
function countingApp(actor: Express.Request["actor"] = { type: "board", source: "session", userId: "user-1", isInstanceAdmin: false }) {
|
||||
let reads = 0;
|
||||
const gates: Array<() => void> = [];
|
||||
const app = express();
|
||||
app.use((req, _res, next) => {
|
||||
req.actor = actor;
|
||||
next();
|
||||
});
|
||||
app.use(authorizationReadScope);
|
||||
app.all("/read", async (req, res) => {
|
||||
const read = () => readOncePerRequest("membership:company-1:user:user-1", async () => ++reads);
|
||||
const first = await read();
|
||||
if (req.query.wait) await new Promise<void>((resolve) => gates.push(resolve));
|
||||
res.json({ first, second: await read(), admin: await readOncePerRequest("admin:user-1", async () => "read") });
|
||||
});
|
||||
return { app, gates, reads: () => reads };
|
||||
}
|
||||
|
||||
it("shares a read only inside one GET request", async () => {
|
||||
const { app, reads } = countingApp();
|
||||
expect((await request(app).get("/read")).body).toEqual({ first: 1, second: 1, admin: false });
|
||||
expect((await request(app).get("/read")).body).toEqual({ first: 2, second: 2, admin: false });
|
||||
expect(reads()).toBe(2);
|
||||
});
|
||||
|
||||
it("reads again for every call in a write request", async () => {
|
||||
const { app, reads } = countingApp();
|
||||
expect((await request(app).post("/read")).body).toEqual({ first: 1, second: 2, admin: "read" });
|
||||
expect((await request(app).delete("/read")).body).toEqual({ first: 3, second: 4, admin: "read" });
|
||||
expect(reads()).toBe(4);
|
||||
});
|
||||
|
||||
it("keeps overlapping GET requests apart", async () => {
|
||||
const { app, gates } = countingApp();
|
||||
const slow = request(app).get("/read?wait=1").then((res) => res.body);
|
||||
while (gates.length === 0) await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
const fast = await request(app).get("/read");
|
||||
gates[0]!();
|
||||
expect(await slow).toEqual({ first: 1, second: 1, admin: false });
|
||||
expect(fast.body).toEqual({ first: 2, second: 2, admin: false });
|
||||
});
|
||||
it("ignores an entry older than the age bound", async () => {
|
||||
const { app, gates, reads } = countingApp();
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
const pending = request(app).get("/read?wait=1").then((res) => res.body);
|
||||
while (gates.length === 0) await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
vi.setSystemTime(Date.now() + AUTHORIZATION_READ_MAX_AGE_MS + 1);
|
||||
gates[0]!();
|
||||
expect(await pending).toEqual({ first: 1, second: 2, admin: "read" });
|
||||
expect(reads()).toBe(2);
|
||||
});
|
||||
|
||||
it("does not keep a rejected read", async () => {
|
||||
let attempts = 0;
|
||||
const app = express();
|
||||
app.use((req, _res, next) => {
|
||||
req.actor = { type: "board", source: "session", userId: "user-1", isInstanceAdmin: false };
|
||||
next();
|
||||
});
|
||||
app.use(authorizationReadScope);
|
||||
app.get("/read", async (_req, res) => {
|
||||
const read = () => readOncePerRequest("membership:company-1:user:user-1", async () => {
|
||||
attempts += 1;
|
||||
if (attempts === 1) throw new Error("connection reset");
|
||||
return attempts;
|
||||
});
|
||||
const first = await read().catch((error: Error) => error.message);
|
||||
res.json({ first, second: await read(), third: await read() });
|
||||
});
|
||||
expect((await request(app).get("/read")).body).toEqual({ first: "connection reset", second: 2, third: 2 });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["an agent key", { type: "agent", source: "agent_key", agentId: "agent-1", companyId: "company-1" }],
|
||||
["a board key", { type: "board", source: "board_key", userId: "user-1", isInstanceAdmin: true }],
|
||||
["a cloud tenant", { type: "board", source: "cloud_tenant", userId: "user-1", isInstanceAdmin: true }],
|
||||
] as const)("seeds nothing for %s", async (_label, actor) => {
|
||||
const { app } = countingApp(actor as Express.Request["actor"]);
|
||||
expect((await request(app).get("/read")).body.admin).toBe("read");
|
||||
});
|
||||
it("keeps response hooks that later middleware installs", async () => {
|
||||
const app = express();
|
||||
app.use(authorizationReadScope);
|
||||
app.use((_req, res, next) => {
|
||||
const { writeHead, write } = res;
|
||||
let writes = 0;
|
||||
res.writeHead = function (this: typeof res, ...args: Parameters<typeof res.writeHead>) {
|
||||
this.setHeader("x-late-hook", "kept");
|
||||
return writeHead.apply(this, args);
|
||||
} as typeof res.writeHead;
|
||||
res.write = function (this: typeof res, ...args: Parameters<typeof res.write>) {
|
||||
writes += 1;
|
||||
res.locals.writes = writes;
|
||||
return write.apply(this, args);
|
||||
} as typeof res.write;
|
||||
next();
|
||||
});
|
||||
app.get("/json", (_req, res) => { res.json({ ok: true }); });
|
||||
app.get("/stream", (_req, res) => {
|
||||
res.write("a");
|
||||
res.write("b");
|
||||
res.end(String(res.locals.writes));
|
||||
});
|
||||
const json = await request(app).get("/json").expect(200);
|
||||
expect(json.headers["x-late-hook"]).toBe("kept");
|
||||
const stream = await request(app).get("/stream").expect(200);
|
||||
expect(stream.headers["x-late-hook"]).toBe("kept");
|
||||
expect(stream.text).toBe("ab2");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { writeFileSync } from "node:fs";
|
||||
import request from "supertest";
|
||||
import { expect, it } from "vitest";
|
||||
import { boardCensusRoutes, boardSessionApp, seedBoardRouteFixture } from "./helpers/route-census-fixture.js";
|
||||
import { describeEmbeddedPostgres, useEmbeddedPostgres } from "./helpers/route-test-harness.js";
|
||||
import { createStatementCensus, formatStatementCensus } from "./helpers/statement-census.js";
|
||||
|
||||
describeEmbeddedPostgres("board route statement census", () => {
|
||||
const ctx = useEmbeddedPostgres("board-route-census-");
|
||||
|
||||
it("answers every polled and page-load board route and reports statements per request", async () => {
|
||||
const census = createStatementCensus(ctx.db);
|
||||
try {
|
||||
const fixture = await seedBoardRouteFixture(ctx.db, "Census");
|
||||
const app = boardSessionApp(ctx.db, () => fixture.userId);
|
||||
const report: string[] = [];
|
||||
for (const [label, path] of boardCensusRoutes(fixture)) {
|
||||
const warm = await request(app).get(path);
|
||||
expect(warm.status, `${label}: ${JSON.stringify(warm.body)}`).toBe(200);
|
||||
const measured = await census.measure(() => request(app).get(path).expect(200), { stacks: true });
|
||||
expect(measured.statements, label).toBeGreaterThan(0);
|
||||
report.push(formatStatementCensus(label, measured, Number(process.env.PAPERCLIP_STATEMENT_CENSUS_TOP ?? 5)));
|
||||
}
|
||||
if (process.env.PAPERCLIP_STATEMENT_CENSUS) writeFileSync(process.env.PAPERCLIP_STATEMENT_CENSUS, `${report.join("\n\n")}\n`);
|
||||
} finally {
|
||||
census.uninstall();
|
||||
}
|
||||
}, 120_000);
|
||||
});
|
||||
@@ -2749,10 +2749,13 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
const [settled] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, receipt.id));
|
||||
const successors = (await readHeartbeatRunsByCompanyId(f.companyId)).filter(row => row.wakeupRequestId === receipt.id);
|
||||
const admitted = ["callback", "restart", "race"].includes(safetyScenario);
|
||||
const sourceGone = { deleted_comment: "authority_source_comment", changed_generation: "authority_conversation_binding",
|
||||
changed_source: "authority_source_shape" }[safetyScenario as "deleted_comment" | "changed_generation" | "changed_source"];
|
||||
expect(successors).toHaveLength(admitted ? 1 : 0);
|
||||
expect(settled).toMatchObject({ id: receipt.id, idempotencyKey: receipt.idempotencyKey,
|
||||
requestedByActorId: receipt.requestedByActorId, requestedAt: receipt.requestedAt,
|
||||
status: admitted ? "queued" : "deferred_issue_execution" });
|
||||
status: admitted ? "queued" : sourceGone ? "skipped" : "deferred_issue_execution",
|
||||
...(sourceGone ? { error: sourceGone, runId: null } : {}) });
|
||||
if (admitted) {
|
||||
expect(extractWakeCommentIds(successors[0].contextSnapshot)).toEqual([comment.id]);
|
||||
expect(successors[0].contextSnapshot?.chatConversationId).toBe(f.conversation.id);
|
||||
@@ -4507,9 +4510,10 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
await expect.poll(() => [...f.responseComments.values()][0]?.body, { timeout: 5000 }).toContain("stopped before completing");
|
||||
await expect.poll(() => coordinator.nextWakeAt(), { timeout: 5000 }).toBeNull();
|
||||
expect(f.responseWrites).toHaveLength(baseline + 1);
|
||||
// The retained requests only record that they wait for a newer run.
|
||||
expect(await db.select().from(chatActions).where(inArray(chatActions.id, history.map(row => row.actionId))))
|
||||
.toEqual(expect.arrayContaining(history.map(row => expect.objectContaining({ id: row.actionId,
|
||||
status: "processed", result: { code: "fast_response_superseded" } }))));
|
||||
status: "processed", result: { code: "fast_response_superseded", terminalWaitKey: expect.any(String) } }))));
|
||||
expect(errors).toEqual([]);
|
||||
} finally {
|
||||
await coordinator.stop();
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import request from "supertest";
|
||||
import { and, eq, like } from "drizzle-orm";
|
||||
import { expect, it } from "vitest";
|
||||
import { folders } from "@paperclipai/db";
|
||||
import { companySkillRoutes } from "../routes/company-skills.js";
|
||||
import { folderService } from "../services/folders.js";
|
||||
import { meterDatabaseStatements } from "./helpers/database-statement-meter.js";
|
||||
import { describeEmbeddedPostgres, routeApp, seedCompanyWithBoardAccess, useEmbeddedPostgres } from "./helpers/route-test-harness.js";
|
||||
|
||||
describeEmbeddedPostgres("GET /api/companies/:companyId/skills statements per request", () => {
|
||||
const ctx = useEmbeddedPostgres("company-skills-list-statements-");
|
||||
|
||||
function meter() {
|
||||
const { host, port } = (ctx.db.$client as unknown as { options: { host: string[]; port: number[] } }).options;
|
||||
return meterDatabaseStatements(ctx.db, `postgres://${host[0]}:${port[0]}/skills`);
|
||||
}
|
||||
|
||||
const bundledFolders = (companyId: string) => ctx.db.select().from(folders)
|
||||
.where(and(eq(folders.companyId, companyId), like(folders.systemKey, "bundled%")));
|
||||
|
||||
it("lists skills with plain reads once the bundled folders exist", async () => {
|
||||
const statements = meter();
|
||||
try {
|
||||
const company = await seedCompanyWithBoardAccess(ctx.db, "Skills list");
|
||||
const app = routeApp(ctx.db, company.actor, (db) => companySkillRoutes(db));
|
||||
const first = await request(app).get(`/api/companies/${company.companyId}/skills`).expect(200);
|
||||
expect(first.body.length).toBeGreaterThan(0);
|
||||
const foldersAfterFirst = await bundledFolders(company.companyId);
|
||||
|
||||
const before = statements.read();
|
||||
statements.startLog();
|
||||
const second = await request(app).get(`/api/companies/${company.companyId}/skills`).expect(200);
|
||||
const log = statements.stopLog();
|
||||
const after = statements.read();
|
||||
|
||||
expect(second.body).toEqual(first.body);
|
||||
expect(after.transactions - before.transactions).toBe(0);
|
||||
expect(log.filter((entry) => /pg_advisory/.test(entry.sql))).toEqual([]);
|
||||
expect(after.statements - before.statements).toBeLessThanOrEqual(45);
|
||||
expect(await bundledFolders(company.companyId)).toEqual(foldersAfterFirst);
|
||||
} finally {
|
||||
statements.uninstall();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it("creates exactly one folder when two first requests ensure the same category at once", async () => {
|
||||
const company = await seedCompanyWithBoardAccess(ctx.db, "Skills race");
|
||||
const [left, right] = await Promise.all([
|
||||
folderService(ctx.db).ensureBundledCategory(company.companyId, "Race Category"),
|
||||
folderService(ctx.db).ensureBundledCategory(company.companyId, "Race Category"),
|
||||
]);
|
||||
expect(left.id).toBe(right.id);
|
||||
const rows = await bundledFolders(company.companyId);
|
||||
expect(rows.filter((row) => row.systemKey === "bundled:race-category")).toHaveLength(1);
|
||||
expect(rows.filter((row) => row.systemKey === "bundled")).toHaveLength(1);
|
||||
|
||||
const app = routeApp(ctx.db, company.actor, (db) => companySkillRoutes(db));
|
||||
await Promise.all([
|
||||
request(app).get(`/api/companies/${company.companyId}/skills`).expect(200),
|
||||
request(app).get(`/api/companies/${company.companyId}/skills`).expect(200),
|
||||
]);
|
||||
const systemKeys = (await bundledFolders(company.companyId)).map((row) => row.systemKey);
|
||||
expect(new Set(systemKeys).size).toBe(systemKeys.length);
|
||||
}, 60_000);
|
||||
|
||||
it("still renames a changed category and prunes an empty one under the lock", async () => {
|
||||
const statements = meter();
|
||||
try {
|
||||
const company = await seedCompanyWithBoardAccess(ctx.db, "Skills repair");
|
||||
const svc = folderService(ctx.db);
|
||||
const locked = async (write: () => Promise<unknown>) => {
|
||||
const before = statements.read();
|
||||
statements.startLog();
|
||||
await write();
|
||||
const log = statements.stopLog();
|
||||
const lockIndex = log.findIndex((entry) => /pg_advisory_xact_lock/.test(entry.sql));
|
||||
const writes = log.filter((entry) => /^\s*(insert|update|delete)\b/i.test(entry.sql));
|
||||
return {
|
||||
transactions: statements.read().transactions - before.transactions,
|
||||
lockedBeforeWrite: lockIndex >= 0 && writes.every((entry) => entry.inTransaction && log.indexOf(entry) > lockIndex),
|
||||
writes: writes.length,
|
||||
};
|
||||
};
|
||||
|
||||
const created = await locked(() => svc.ensureBundledCategory(company.companyId, "Repair Category"));
|
||||
expect(created).toMatchObject({ transactions: 1, lockedBeforeWrite: true });
|
||||
expect(created.writes).toBeGreaterThan(0);
|
||||
const [category] = (await bundledFolders(company.companyId)).filter((row) => row.systemKey === "bundled:repair-category");
|
||||
await ctx.db.update(folders).set({ name: "Renamed by hand" }).where(eq(folders.id, category!.id));
|
||||
const renamed = await locked(() => svc.ensureBundledCategory(company.companyId, "Repair Category"));
|
||||
expect(renamed).toMatchObject({ transactions: 1, lockedBeforeWrite: true, writes: 1 });
|
||||
expect((await bundledFolders(company.companyId)).find((row) => row.id === category!.id)?.name).toBe("Repair Category");
|
||||
|
||||
expect(await locked(() => svc.pruneEmptyBundledCategories(company.companyId, ["Repair Category"])))
|
||||
.toEqual({ transactions: 0, lockedBeforeWrite: false, writes: 0 });
|
||||
expect((await bundledFolders(company.companyId)).map((row) => row.id)).toContain(category!.id);
|
||||
expect(await locked(() => svc.pruneEmptyBundledCategories(company.companyId, [])))
|
||||
.toEqual({ transactions: 1, lockedBeforeWrite: true, writes: 1 });
|
||||
expect((await bundledFolders(company.companyId)).map((row) => row.id)).not.toContain(category!.id);
|
||||
} finally {
|
||||
statements.uninstall();
|
||||
}
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -0,0 +1,420 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { setImmediate as immediate } from "node:timers/promises";
|
||||
import { setTimeout as realTimeout } from "node:timers";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { agents, agentWakeupRequests, authUsers, chatActions, chatConversations, chatDeliveries, chatEndpoints,
|
||||
chatExternalPrincipals, companies, companyMemberships, createDb, heartbeatRuns, issueComments, issues,
|
||||
chatMessageLinks, chatPublications, toolApplications, toolConnections, type Db } from "@paperclipai/db";
|
||||
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
||||
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
|
||||
import { notifyDeferredExecutionEligibility, notifyDeferredExecutionWork, notifyDeferredWakesForIssue } from "../services/deferred-execution-notifications.js";
|
||||
import { heartbeatService } from "../services/heartbeat.js";
|
||||
import { createDurableChatWakeupRequest, resumeDeferredChatWake } from "../services/durable-chat-wakeup.js";
|
||||
import { createInboundWakeups } from "../services/chat-channels/inbound/wakeups.js";
|
||||
import { chatWakeAuthorityDenied } from "../services/chat-channels/inbound/wakeup-authorization-error.js";
|
||||
import { createInboundWakeNotices } from "../services/chat-channels/inbound/wakeup-notices.js";
|
||||
import { inboundWakePublicationKey } from "../services/chat-inbound-wakeup-publications.js";
|
||||
import { projectSafeChatPublication } from "../services/chat-publication-projection.js";
|
||||
import { DELIVERY_QUEUES, subscribeDeliveryWork } from "../services/delivery-work-notifications.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
|
||||
vi.setConfig({ testTimeout: 120_000 });
|
||||
const RESUME_FAILED = "saved chat source could not resume after recovery";
|
||||
const HOUR_MS = 60 * 60_000;
|
||||
|
||||
describe("deferred chat wake sweep", () => {
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let heartbeat: ReturnType<typeof heartbeatService>;
|
||||
let coordinator: ReturnType<typeof createDeliveryWorkCoordinator>;
|
||||
let unregisterOwner: (() => void) | undefined;
|
||||
const statements: string[] = [];
|
||||
const errors: unknown[] = [];
|
||||
const passes = new Set<Promise<unknown>>();
|
||||
|
||||
beforeAll(async () => {
|
||||
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_DEFERRED_CHAT_WAKE_TEST_DATABASE_URL");
|
||||
if (!external) temporary = await startEmbeddedPostgresTestDatabase("deferred-chat-wake-");
|
||||
db = createDb(external ?? temporary!.connectionString, { maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
|
||||
db.$client.options.onnotice = () => {};
|
||||
db.$client.options.debug = (_connection, query) => { statements.push(query); };
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await db.execute(sql`truncate companies cascade`);
|
||||
errors.length = 0;
|
||||
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
|
||||
heartbeat = heartbeatService(db);
|
||||
coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true,
|
||||
onError: error => { errors.push(error); } });
|
||||
const register = coordinator.register.bind(coordinator);
|
||||
coordinator.register = (queue, task) => register(queue, { ...task, run: signal => {
|
||||
const pass = Promise.resolve(task.run(signal)); passes.add(pass);
|
||||
void pass.then(() => passes.delete(pass), () => passes.delete(pass)); return pass;
|
||||
} });
|
||||
unregisterOwner = createInboundWakeups(db, {
|
||||
authorizeInboundWakeup: async () => { throw new Error("unused"); },
|
||||
authorizeInboundWorkStart: (tx, action) => authorize(tx as unknown as Db, action) as never,
|
||||
attachmentOmissionDetail: () => null, isExternalActionAuthorizationChange: () => false, redactError: String,
|
||||
fetchImpl: async () => { throw new Error("unused"); }, heartbeat,
|
||||
}).unregisterDeferredWakeOwner;
|
||||
});
|
||||
afterEach(async () => {
|
||||
unregisterOwner?.(); onAuthorize = undefined;
|
||||
await coordinator.stop(); await heartbeat.drainActiveRunExecutions();
|
||||
vi.useRealTimers(); vi.restoreAllMocks();
|
||||
});
|
||||
afterAll(async () => { await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); });
|
||||
|
||||
let onAuthorize: ((action: typeof chatActions.$inferSelect) => Promise<void>) | undefined;
|
||||
async function authorize(tx: Db, action: typeof chatActions.$inferSelect) {
|
||||
await onAuthorize?.(action);
|
||||
const [issue] = await tx.select().from(issues).where(and(eq(issues.companyId, action.companyId),
|
||||
eq(issues.id, String(action.payload.issueId)))).for("update");
|
||||
if (!issue || issue.assigneeAgentId !== action.payload.agentId || ["backlog", "done", "cancelled"].includes(issue.status))
|
||||
throw chatWakeAuthorityDenied("task_assignment");
|
||||
const [comment] = await tx.select().from(issueComments).where(eq(issueComments.id, String(action.payload.commentId)));
|
||||
if (!comment || comment.deletedAt) throw chatWakeAuthorityDenied("source_comment");
|
||||
const [endpoint] = await tx.select().from(chatEndpoints).where(eq(chatEndpoints.id, action.endpointId));
|
||||
if (endpoint.status === "paused") throw chatWakeAuthorityDenied("runtime_fence");
|
||||
const [conversation] = await tx.select().from(chatConversations).where(eq(chatConversations.id, action.conversationId!));
|
||||
const [delivery] = await tx.select().from(chatDeliveries).where(eq(chatDeliveries.id, action.deliveryId!));
|
||||
return { issue, endpoint, conversation, delivery };
|
||||
}
|
||||
|
||||
async function company() {
|
||||
const companyId = randomUUID(), userId = `chat-user-${companyId.slice(0, 8)}`;
|
||||
await db.insert(authUsers).values({ id: userId, name: "Chat sender", email: `${userId}@example.test`,
|
||||
createdAt: new Date(), updatedAt: new Date() });
|
||||
await db.insert(companies).values({ id: companyId, name: "Deferred chat", issuePrefix: `DC${companyId.slice(0, 6)}`,
|
||||
defaultResponsibleUserId: userId, requireBoardApprovalForNewAgents: false });
|
||||
await db.insert(companyMemberships).values({ companyId, principalId: userId, principalType: "user", status: "active", membershipRole: "owner" });
|
||||
const [agent] = await db.insert(agents).values({ companyId, name: "Chat agent", adapterType: "process", status: "idle",
|
||||
adapterConfig: { command: process.execPath, args: ["-e", "console.log('chat-proof')"], cwd: process.cwd() },
|
||||
runtimeConfig: { heartbeat: { enabled: true, intervalSec: 0, wakeOnDemand: true } } }).returning();
|
||||
const [application] = await db.insert(toolApplications).values({ companyId, name: "Chat", type: "mcp_http" }).returning();
|
||||
const [connection] = await db.insert(toolConnections).values({ companyId, applicationId: application.id,
|
||||
uid: randomUUID(), name: "Chat", transport: "rest_api" }).returning();
|
||||
const [endpoint] = await db.insert(chatEndpoints).values({ companyId, connectionId: connection.id, provider: "slack",
|
||||
publicId: randomUUID(), assignedAgentId: agent.id, status: "active" }).returning();
|
||||
const [principal] = await db.insert(chatExternalPrincipals).values({ companyId, provider: "slack",
|
||||
providerAccountId: "TWORKSPACE", externalId: `U${companyId.slice(0, 6)}`, kind: "user", isBot: false }).returning();
|
||||
return { companyId, userId, agent, endpoint, principal };
|
||||
}
|
||||
|
||||
async function wake(c: Awaited<ReturnType<typeof company>>, input: { status: string; ageMs: number; runStatus?: string;
|
||||
on?: { issue: typeof issues.$inferSelect; conversation: typeof chatConversations.$inferSelect } }) {
|
||||
const createdAt = new Date(Date.now() - input.ageMs);
|
||||
const issue = input.on?.issue ?? (await db.insert(issues).values({ companyId: c.companyId, title: "Chat task", status: input.status,
|
||||
assigneeAgentId: c.agent.id }).returning())[0];
|
||||
const conversation = input.on?.conversation ?? (await db.insert(chatConversations).values({ companyId: c.companyId,
|
||||
endpointId: c.endpoint.id, issueId: issue.id, externalConversationId: "CCHANNEL",
|
||||
externalThreadId: `slack:CCHANNEL:${randomUUID()}`, externalLabel: "Thread", state: "active", isDirectMessage: false }).returning())[0];
|
||||
const [comment] = await db.insert(issueComments).values({ companyId: c.companyId, issueId: issue.id,
|
||||
authorUserId: c.userId, body: "A follow-up sent while the task was running" }).returning();
|
||||
const providerEventId = randomUUID();
|
||||
const [delivery] = await db.insert(chatDeliveries).values({ companyId: c.companyId, endpointId: c.endpoint.id,
|
||||
conversationId: conversation.id, principalId: c.principal.id, providerEventId, deduplicationKey: randomUUID(),
|
||||
eventKind: "message", state: "processed", attempts: 1, normalizedEvent: { providerEventId, kind: "message" } }).returning();
|
||||
const actionId = randomUUID();
|
||||
const payload = { version: 1, issueId: issue.id, agentId: c.agent.id, commentId: comment.id, sessionGeneration: 1,
|
||||
requestedByActorType: "user", requestedByActorId: c.userId };
|
||||
await db.insert(chatActions).values({ id: actionId, companyId: c.companyId, endpointId: c.endpoint.id, deliveryId: delivery.id,
|
||||
conversationId: conversation.id, principalId: c.principal.id, kind: "inbound_wakeup",
|
||||
providerActionId: `inbound_wakeup:${delivery.id}`, status: "processed", payload, createdAt });
|
||||
const request = createDurableChatWakeupRequest({ id: actionId, companyId: c.companyId, agentId: c.agent.id, issueId: issue.id,
|
||||
commentId: comment.id, requestedByActorType: "user", requestedByActorId: c.userId, requestedAt: createdAt,
|
||||
authorize: async () => {} });
|
||||
await db.insert(agentWakeupRequests).values({ id: actionId, companyId: c.companyId, agentId: c.agent.id,
|
||||
source: "assignment", triggerDetail: "system", reason: "issue_commented", status: "deferred_issue_execution",
|
||||
requestedByActorType: "user", requestedByActorId: c.userId, idempotencyKey: request.idempotencyKey,
|
||||
requestedAt: createdAt, createdAt, updatedAt: createdAt,
|
||||
payload: { issueId: issue.id, mutation: "comment", _paperclipWakeContext: { issueId: issue.id, wakeReason: "issue_commented",
|
||||
wakeCommentId: comment.id, wakeCommentIds: [comment.id], commentId: comment.id } } });
|
||||
const [run] = await db.insert(heartbeatRuns).values({ companyId: c.companyId, agentId: c.agent.id,
|
||||
status: input.runStatus ?? "succeeded", startedAt: createdAt,
|
||||
finishedAt: input.runStatus === "running" ? null : new Date(createdAt.getTime() + 1000),
|
||||
contextSnapshot: { issueId: issue.id } }).returning();
|
||||
return { issue, requestId: actionId, run, conversation, payloadCommentId: comment.id };
|
||||
}
|
||||
|
||||
async function settle() {
|
||||
for (let index = 0; index < 20; index++) {
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
await Promise.allSettled([...passes]); await immediate();
|
||||
}
|
||||
}
|
||||
function resumeFailures(spy: { mock: { calls: unknown[][] } }): unknown[][] {
|
||||
return spy.mock.calls.filter(call => call[1] === RESUME_FAILED);
|
||||
}
|
||||
async function idle(minutes: number) {
|
||||
const before = statements.length;
|
||||
const updatesBefore = statements.filter(query => /^\s*update\s+"agent_wakeup_requests"/i.test(query)).length;
|
||||
for (let minute = 0; minute < minutes; minute++) {
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
await Promise.allSettled([...passes]); await immediate();
|
||||
}
|
||||
return { statements: statements.length - before,
|
||||
wakeUpdates: statements.filter(query => /^\s*update\s+"agent_wakeup_requests"/i.test(query)).length - updatesBefore };
|
||||
}
|
||||
async function receipt(requestId: string) {
|
||||
return (await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, requestId)))[0];
|
||||
}
|
||||
function waitForReal(assertion: () => Promise<unknown>, timeout = 10_000) {
|
||||
const started = performance.now();
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const attempt = async () => {
|
||||
try { await assertion(); resolve(); }
|
||||
catch (error) { if (performance.now() - started > timeout) reject(error); else realTimeout(attempt, 50); }
|
||||
};
|
||||
void attempt();
|
||||
});
|
||||
}
|
||||
|
||||
it("settles stale wakes of finished tasks once and then stays idle for 30 minutes", async () => {
|
||||
const c = await company();
|
||||
const wakes = [];
|
||||
for (let index = 0; index < 12; index++) {
|
||||
wakes.push(await wake(c, { status: index % 3 === 0 ? "cancelled" : "done", ageMs: 7 * 24 * 60 * 60_000 }));
|
||||
}
|
||||
const warn = vi.spyOn(logger, "warn");
|
||||
await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready;
|
||||
await settle();
|
||||
const settledLogs = resumeFailures(warn).length;
|
||||
const quiet = await idle(30);
|
||||
const logs = resumeFailures(warn).length - settledLogs;
|
||||
console.info(`[deferred-chat-wake] 12 stale wakes, 30 idle minutes: statements=${quiet.statements} `
|
||||
+ `wakeUpdates=${quiet.wakeUpdates} resumeFailureLogs=${logs} firstPassLogs=${settledLogs}`);
|
||||
for (const { requestId } of wakes) {
|
||||
expect(await receipt(requestId)).toMatchObject({ status: "skipped", error: "task_closed", runId: null });
|
||||
}
|
||||
expect(await db.select().from(heartbeatRuns).where(sql`${heartbeatRuns.wakeupRequestId} is not null`)).toHaveLength(0);
|
||||
expect((await db.select().from(issues).where(eq(issues.companyId, c.companyId))).map(row => row.status).sort())
|
||||
.toEqual(wakes.map((_, index) => index % 3 === 0 ? "cancelled" : "done").sort());
|
||||
expect(resumeFailures(warn).every(call => (call[0] as { reason?: string }).reason === "task_closed")).toBe(true);
|
||||
expect(quiet).toEqual({ statements: 0, wakeUpdates: 0 });
|
||||
expect(logs).toBe(0);
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
it("settles a saved chat wake whose task no longer exists", async () => {
|
||||
const c = await company();
|
||||
const orphan = await wake(c, { status: "todo", ageMs: 60_000 });
|
||||
const before = await receipt(orphan.requestId);
|
||||
await db.update(agentWakeupRequests).set({ payload: { ...before.payload, issueId: randomUUID() } })
|
||||
.where(eq(agentWakeupRequests.id, orphan.requestId));
|
||||
await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready;
|
||||
await settle();
|
||||
expect(await receipt(orphan.requestId)).toMatchObject({ status: "skipped", error: "task_missing", runId: null });
|
||||
expect(await idle(30)).toEqual({ statements: 0, wakeUpdates: 0 });
|
||||
expect(errors).toEqual([]);
|
||||
});
|
||||
|
||||
async function visibleQueuedNotice(c: Awaited<ReturnType<typeof company>>, saved: Awaited<ReturnType<typeof wake>>) {
|
||||
const [action] = await db.select().from(chatActions).where(eq(chatActions.id, saved.requestId));
|
||||
const providerMessageId = randomUUID();
|
||||
const [publication] = await db.insert(chatPublications).values({ companyId: c.companyId, endpointId: c.endpoint.id,
|
||||
conversationId: saved.conversation.id, issueId: saved.issue.id, commentId: saved.payloadCommentId,
|
||||
idempotencyKey: inboundWakePublicationKey(saved.requestId, "queued", c.endpoint.id, saved.conversation.id),
|
||||
payload: projectSafeChatPublication({ classification: "external", source: "safe_milestone",
|
||||
text: "Your follow-up is queued.", progressState: "queued" }),
|
||||
state: "published", providerMessageId }).returning();
|
||||
await db.insert(chatMessageLinks).values({ companyId: c.companyId, endpointId: c.endpoint.id,
|
||||
conversationId: saved.conversation.id, publicationId: publication.id, providerMessageId, direction: "outbound" });
|
||||
return action;
|
||||
}
|
||||
function noticeWorker() {
|
||||
return createInboundWakeNotices(db, {
|
||||
authorizeInboundWakeup: (async (tx: Db, action: typeof chatActions.$inferSelect) => {
|
||||
const [issue] = await tx.select().from(issues).where(eq(issues.id, String(action.payload.issueId)));
|
||||
const [endpoint] = await tx.select().from(chatEndpoints).where(eq(chatEndpoints.id, action.endpointId));
|
||||
const [conversation] = await tx.select().from(chatConversations).where(eq(chatConversations.id, action.conversationId!));
|
||||
const [delivery] = await tx.select().from(chatDeliveries).where(eq(chatDeliveries.id, action.deliveryId!));
|
||||
return { issue, endpoint, conversation, delivery, resource: null };
|
||||
}) as never,
|
||||
enqueueFailedChatRetryPublications: async () => 0,
|
||||
authorizeRetainedChatSourcePublication: async () => false,
|
||||
isExternalActionAuthorizationChange: () => false,
|
||||
isShuttingDown: () => false,
|
||||
});
|
||||
}
|
||||
async function notStartedNotices(companyId: string) {
|
||||
return (await db.select().from(chatPublications).where(eq(chatPublications.companyId, companyId)))
|
||||
.filter(row => row.idempotencyKey.includes(":not_started:"));
|
||||
}
|
||||
|
||||
it("closes old saved messages silently and tells a recent watcher once, across passes and restarts", async () => {
|
||||
const c = await company();
|
||||
const old = await wake(c, { status: "done", ageMs: 72 * HOUR_MS });
|
||||
const recent = await wake(c, { status: "done", ageMs: 3 * HOUR_MS });
|
||||
await visibleQueuedNotice(c, old);
|
||||
await visibleQueuedNotice(c, recent);
|
||||
const noticeSignals: string[] = [];
|
||||
const unsubscribe = subscribeDeliveryWork(db, DELIVERY_QUEUES.chatInboundWakeNotices, () => { noticeSignals.push("signal"); });
|
||||
try {
|
||||
await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready;
|
||||
await settle();
|
||||
} finally { unsubscribe(); }
|
||||
expect(await receipt(old.requestId)).toMatchObject({ status: "skipped", error: "task_closed", runId: null,
|
||||
payload: { silentSettlement: true } });
|
||||
expect(await receipt(recent.requestId)).toMatchObject({ status: "skipped", error: "task_closed", runId: null });
|
||||
expect((await receipt(recent.requestId)).payload?.silentSettlement).toBeUndefined();
|
||||
expect(noticeSignals).toHaveLength(1);
|
||||
const deliveries = await db.select().from(chatDeliveries).where(eq(chatDeliveries.companyId, c.companyId));
|
||||
const deliveryOf = async (requestId: string) => {
|
||||
const [action] = await db.select().from(chatActions).where(eq(chatActions.id, requestId));
|
||||
return deliveries.find(row => row.id === action.deliveryId)!;
|
||||
};
|
||||
expect((await deliveryOf(old.requestId)).redactedError).toBeNull();
|
||||
expect((await deliveryOf(recent.requestId)).redactedError).toContain("Input saved.");
|
||||
const first = await noticeWorker().reconcileInboundWakeNotices({ scope: { companyId: c.companyId } });
|
||||
expect(first.inserted).toBe(1);
|
||||
expect((await notStartedNotices(c.companyId)).map(row => row.commentId)).toEqual([recent.payloadCommentId]);
|
||||
expect((await noticeWorker().reconcileInboundWakeNotices({ scope: { companyId: c.companyId } })).inserted).toBe(0);
|
||||
expect(await noticeWorker().loadInboundWakeNoticeScopes()).toEqual([]);
|
||||
expect((await notStartedNotices(c.companyId)).map(row => row.commentId)).toEqual([recent.payloadCommentId]);
|
||||
});
|
||||
|
||||
it("reopens a finished task for a recent saved chat message, as a message on a finished task does", async () => {
|
||||
const c = await company();
|
||||
const recent = await wake(c, { status: "done", ageMs: 5 * 60_000 });
|
||||
await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready;
|
||||
await waitForReal(async () => {
|
||||
const runs = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.wakeupRequestId, recent.requestId));
|
||||
expect(runs).toHaveLength(1);
|
||||
});
|
||||
expect((await db.select().from(issues).where(eq(issues.id, recent.issue.id)))[0].status).not.toBe("done");
|
||||
expect((await receipt(recent.requestId)).status).not.toBe("skipped");
|
||||
});
|
||||
|
||||
it("starts one follow-up run for two recent saved messages on the same finished task", async () => {
|
||||
const c = await company();
|
||||
const first = await wake(c, { status: "done", ageMs: 10 * 60_000 });
|
||||
const second = await wake(c, { status: "done", ageMs: 5 * 60_000, on: first });
|
||||
await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready;
|
||||
await waitForReal(async () => {
|
||||
const runs = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, c.companyId),
|
||||
sql`${heartbeatRuns.wakeupRequestId} is not null`));
|
||||
expect(runs).toHaveLength(1);
|
||||
const receipts = await Promise.all([receipt(first.requestId), receipt(second.requestId)]);
|
||||
expect(receipts.map(row => row.runId)).toEqual([runs[0].id, runs[0].id]);
|
||||
expect(receipts[0]).toMatchObject({ status: "coalesced", payload: { coalescedIntoWakeupRequestId: second.requestId } });
|
||||
expect(runs[0].contextSnapshot?.wakeCommentIds).toEqual([
|
||||
first.payloadCommentId, second.payloadCommentId]);
|
||||
});
|
||||
await settle();
|
||||
expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, c.companyId),
|
||||
sql`${heartbeatRuns.wakeupRequestId} is not null`))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("answers a recent saved message alone when a newer message of the same task lost its source", async () => {
|
||||
const c = await company();
|
||||
const valid = await wake(c, { status: "done", ageMs: 10 * 60_000 });
|
||||
const removed = await wake(c, { status: "done", ageMs: 5 * 60_000, on: valid });
|
||||
await db.update(issueComments).set({ deletedAt: new Date() }).where(eq(issueComments.id, removed.payloadCommentId));
|
||||
await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready;
|
||||
await waitForReal(async () => {
|
||||
const runs = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, c.companyId),
|
||||
sql`${heartbeatRuns.wakeupRequestId} is not null`));
|
||||
expect(runs).toHaveLength(1);
|
||||
expect(runs[0].wakeupRequestId).toBe(valid.requestId);
|
||||
expect(runs[0].contextSnapshot?.wakeCommentIds ?? []).not.toContain(removed.payloadCommentId);
|
||||
const left = await receipt(removed.requestId);
|
||||
expect(left.runId).toBeNull();
|
||||
expect(["skipped", "deferred_issue_execution"]).toContain(left.status);
|
||||
if (left.status === "skipped") expect(left.error).toBe("authority_source_comment");
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses a batch that another run took a message from before admission, then answers the rest alone", async () => {
|
||||
const c = await company();
|
||||
const older = await wake(c, { status: "done", ageMs: 10 * 60_000 });
|
||||
const newer = await wake(c, { status: "done", ageMs: 5 * 60_000, on: older });
|
||||
const [other] = await db.insert(heartbeatRuns).values({ companyId: c.companyId, agentId: c.agent.id, status: "succeeded",
|
||||
startedAt: new Date(Date.now() - 2000), finishedAt: new Date(Date.now() - 1000),
|
||||
contextSnapshot: { issueId: randomUUID(), wakeCommentIds: [older.payloadCommentId] } }).returning();
|
||||
let newerChecks = 0;
|
||||
onAuthorize = async action => {
|
||||
if (action.id !== newer.requestId || ++newerChecks !== 2) return;
|
||||
await db.update(agentWakeupRequests).set({ status: "completed", runId: other.id }).where(eq(agentWakeupRequests.id, older.requestId));
|
||||
};
|
||||
const scope = { companyId: c.companyId, agentId: c.agent.id, issueId: older.issue.id, recoverySweep: true };
|
||||
await expect(resumeDeferredChatWake(db, { ...scope, requestId: older.requestId }))
|
||||
.rejects.toThrow("chat_inbound_wakeup_batch_changed");
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.wakeupRequestId, newer.requestId))).toHaveLength(0);
|
||||
expect(await receipt(newer.requestId)).toMatchObject({ status: "deferred_issue_execution", runId: null });
|
||||
await resumeDeferredChatWake(db, { ...scope, requestId: newer.requestId });
|
||||
const [alone] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.wakeupRequestId, newer.requestId));
|
||||
expect(alone.contextSnapshot?.wakeCommentIds ?? [newer.payloadCommentId]).toEqual([newer.payloadCommentId]);
|
||||
expect(await receipt(older.requestId)).toMatchObject({ status: "completed", runId: other.id });
|
||||
});
|
||||
|
||||
it("keeps a refused follow-up in the saved pause wait without retrying, then starts it when the pause lifts", async () => {
|
||||
const c = await company();
|
||||
await db.update(agents).set({ status: "paused" }).where(eq(agents.id, c.agent.id));
|
||||
const refused = await wake(c, { status: "done", ageMs: 5 * 60_000 });
|
||||
await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready;
|
||||
await settle();
|
||||
const waiting = await receipt(refused.requestId);
|
||||
expect(waiting).toMatchObject({ status: "deferred_issue_execution", runId: null,
|
||||
payload: { executionWait: { reason: "agent.not_invokable" } } });
|
||||
expect(waiting.payload?.chatResume).toBeUndefined();
|
||||
expect(await db.select().from(heartbeatRuns).where(sql`${heartbeatRuns.wakeupRequestId} is not null`)).toHaveLength(0);
|
||||
await idle(1);
|
||||
expect(await idle(30)).toEqual({ statements: 0, wakeUpdates: 0 });
|
||||
expect(await db.select().from(heartbeatRuns).where(sql`${heartbeatRuns.wakeupRequestId} is not null`)).toHaveLength(0);
|
||||
await db.transaction(async tx => {
|
||||
await tx.update(agents).set({ status: "idle" }).where(eq(agents.id, c.agent.id));
|
||||
await notifyDeferredExecutionEligibility(tx, { companyId: c.companyId });
|
||||
});
|
||||
await waitForReal(async () => {
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.wakeupRequestId, refused.requestId))).toHaveLength(1);
|
||||
}, 10_000);
|
||||
});
|
||||
|
||||
it("spaces bounded attempts on a stored time and still resumes promptly on a real event", async () => {
|
||||
const c = await company();
|
||||
await db.update(chatEndpoints).set({ status: "paused" }).where(eq(chatEndpoints.id, c.endpoint.id));
|
||||
const paused = await wake(c, { status: "todo", ageMs: 60_000 });
|
||||
const warn = vi.spyOn(logger, "warn");
|
||||
await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready;
|
||||
await settle();
|
||||
const first = await receipt(paused.requestId);
|
||||
expect(first).toMatchObject({ status: "deferred_issue_execution", error: "authority_runtime_fence" });
|
||||
const nextAttemptAt = Date.parse(String((first.payload?.chatResume as Record<string, unknown>).nextAttemptAt));
|
||||
expect(nextAttemptAt).toBeGreaterThan(Date.now());
|
||||
const window = await idle(30);
|
||||
const attempts = resumeFailures(warn);
|
||||
console.info(`[deferred-chat-wake] paused endpoint, 30 idle minutes: attempts=${attempts.length} statements=${window.statements}`);
|
||||
expect(attempts.length).toBeGreaterThanOrEqual(2);
|
||||
expect(attempts.length).toBeLessThanOrEqual(4);
|
||||
expect(attempts.every(call => (call[0] as { reason?: string }).reason === "authority_runtime_fence")).toBe(true);
|
||||
const later = await receipt(paused.requestId);
|
||||
expect(later.status).toBe("deferred_issue_execution");
|
||||
await db.transaction(async tx => {
|
||||
await tx.update(chatEndpoints).set({ status: "active" }).where(eq(chatEndpoints.id, c.endpoint.id));
|
||||
await notifyDeferredExecutionWork(tx, { companyId: c.companyId, requestId: paused.requestId });
|
||||
});
|
||||
await waitForReal(async () => {
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.wakeupRequestId, paused.requestId))).toHaveLength(1);
|
||||
}, 5_000);
|
||||
});
|
||||
|
||||
it("waits for the run it was deferred behind and resumes as soon as that run finishes", async () => {
|
||||
const c = await company();
|
||||
const waiting = await wake(c, { status: "in_progress", ageMs: 30_000, runStatus: "running" });
|
||||
await heartbeat.registerDeferredReceiptWork(coordinator, () => true).ready;
|
||||
await settle();
|
||||
const window = await idle(10);
|
||||
expect(window).toEqual({ statements: 0, wakeUpdates: 0 });
|
||||
expect(await receipt(waiting.requestId)).toMatchObject({ status: "deferred_issue_execution", error: null });
|
||||
await db.transaction(async tx => {
|
||||
await tx.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, waiting.run.id));
|
||||
await notifyDeferredWakesForIssue(tx, { companyId: c.companyId, issueId: waiting.issue.id });
|
||||
});
|
||||
await waitForReal(async () => {
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.wakeupRequestId, waiting.requestId))).toHaveLength(1);
|
||||
}, 5_000);
|
||||
});
|
||||
});
|
||||
@@ -5,6 +5,7 @@ import { environmentTaskErrorCodeData, environmentTaskOperationSchema, parseEnvi
|
||||
readEnvironmentTaskErrorCode, readEnvironmentTaskErrorDiagnostic } from "@paperclipai/plugin-sdk";
|
||||
import { executeEnvironmentTask, isSettledReadyRunnerState, settleDispatchedEnvironmentTask } from "../services/environment-task-runtime.js";
|
||||
import { NativeExecutionContext } from "../services/native-runtime/native-execution-context.js";
|
||||
import { runnerLaunchPreparationDigest, runnerLaunchRunDigest } from "../vendor/paperclip-runner/index.js";
|
||||
|
||||
const state = vi.hoisted(() => ({ plugin: {} as any, release: vi.fn(), identity: vi.fn(), config: vi.fn() }));
|
||||
vi.mock("../services/provider-fresh-workspace.js", () => ({
|
||||
@@ -344,7 +345,7 @@ describe("plugin-provided Runner execution", () => {
|
||||
await expect(executeEnvironmentTask(database(row(), []).db, denied as never, { companyId: "company", leaseId, operation })).rejects.toThrow("project unavailable");
|
||||
expect(denied.call).not.toHaveBeenCalled();
|
||||
});
|
||||
it.each([false, true])("prepares scoped configuration with submit-time auth %s", async atSubmit => {
|
||||
it("accepts prepare launch digests only when they match the requirements", async () => {
|
||||
const operation = { kind: "prepare" as const, projectIds: [projectId], requirements: {
|
||||
schema: "paperclip.runner.launch-requirements.v1" as const,
|
||||
identity: { runnerInstanceId: "runner", environmentLeaseId: leaseId, runId: "run",
|
||||
@@ -353,7 +354,35 @@ describe("plugin-provided Runner execution", () => {
|
||||
settings: {}, approvalPolicy: "on-request" as const, readOnly: false,
|
||||
preparedConversation: false, includeCollaborationModeInstructions: true,
|
||||
} };
|
||||
const result = { kind: "prepared", taskId: "attempt-1", ...(atSubmit ? {projectAuthCheckAtSubmit: true} : {}), launch: { configurationId: "configuration-1",
|
||||
const preparationDigest = runnerLaunchPreparationDigest(operation.requirements);
|
||||
const runDigest = runnerLaunchRunDigest(preparationDigest, operation.requirements);
|
||||
const result = { kind: "prepared", taskId: "attempt-1", launch: { configurationId: "configuration-1",
|
||||
requirementsDigest: `sha256:${"a".repeat(64)}`, provider: { kind: "codex" } } };
|
||||
const accepted = worker(result);
|
||||
await expect(executeEnvironmentTask(database().db, accepted as never, { companyId: "company", leaseId,
|
||||
operation: { ...operation, preparationDigest, runDigest } })).resolves.toEqual(result);
|
||||
expect(accepted.call).toHaveBeenCalledWith("original", "environmentTask", expect.objectContaining({
|
||||
operation: expect.objectContaining({ preparationDigest, runDigest }) }), 15_000);
|
||||
const forged = `sha256:${"b".repeat(64)}`;
|
||||
for (const digests of [{ preparationDigest: forged, runDigest }, { preparationDigest, runDigest: forged },
|
||||
{ preparationDigest }, { runDigest }]) {
|
||||
const refused = worker(result);
|
||||
await expect(executeEnvironmentTask(database().db, refused as never, { companyId: "company", leaseId,
|
||||
operation: { ...operation, ...digests } })).rejects.toThrow("launch digest mismatch");
|
||||
expect(refused.call).not.toHaveBeenCalled();
|
||||
}
|
||||
});
|
||||
it.each([[false, false], [true, false], [false, true], [true, true]])("prepares scoped configuration with submit-time auth %s and in-prepare auth %s", async (atSubmit, checked) => {
|
||||
const operation = { kind: "prepare" as const, projectIds: [projectId], requirements: {
|
||||
schema: "paperclip.runner.launch-requirements.v1" as const,
|
||||
identity: { runnerInstanceId: "runner", environmentLeaseId: leaseId, runId: "run",
|
||||
normalizedSessionId: "session", turnId: "turn", itemId: "item" },
|
||||
provider: "codex" as const, model: "selected", instructions: "Core instructions", runtimeContext: null,
|
||||
settings: {}, approvalPolicy: "on-request" as const, readOnly: false,
|
||||
preparedConversation: false, includeCollaborationModeInstructions: true,
|
||||
} };
|
||||
const result = { kind: "prepared", taskId: "attempt-1", ...(atSubmit ? {projectAuthCheckAtSubmit: true} : {}),
|
||||
...(checked ? {projectAuthChecked: true} : {}), launch: { configurationId: "configuration-1",
|
||||
requirementsDigest: `sha256:${"a".repeat(64)}`, provider: { kind: "codex" } } };
|
||||
const workers = worker(result), store = database();
|
||||
await expect(executeEnvironmentTask(store.db, workers as never, { companyId: "company", leaseId, operation }))
|
||||
@@ -361,9 +390,10 @@ describe("plugin-provided Runner execution", () => {
|
||||
expect(workers.call).toHaveBeenCalledWith("original", "environmentTask", expect.objectContaining({
|
||||
companyId: "company", runId: "run", agentId: "agent", projectIds: [projectId], operation,
|
||||
}), 15_000);
|
||||
expect(store.sets).toHaveLength(atSubmit ? 2 : 1);
|
||||
if (atSubmit) expect(new PgDialect().sqlToQuery(store.sets[1].metadata as never).params).toContain(JSON.stringify({
|
||||
runnerTaskProjectAuthValidation: { configurationId: "configuration-1", provider: "openai", projectIds: [projectId], atSubmit: true },
|
||||
expect(store.sets).toHaveLength(atSubmit || checked ? 2 : 1);
|
||||
if (atSubmit || checked) expect(new PgDialect().sqlToQuery(store.sets[1].metadata as never).params).toContain(JSON.stringify({
|
||||
runnerTaskProjectAuthValidation: { configurationId: "configuration-1", provider: "openai", projectIds: [projectId],
|
||||
...(checked ? {} : { atSubmit: true }) },
|
||||
}));
|
||||
const denied = worker(result);
|
||||
const inactive = row(); inactive.lease.status = "released";
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
{
|
||||
"id": "<id:0>",
|
||||
"companyId": "<id:1>",
|
||||
"conversationAgentId": null,
|
||||
"conversationUserId": null,
|
||||
"conversationState": null,
|
||||
"conversationSessionGeneration": 0,
|
||||
"conversationBoundaryCommentId": null,
|
||||
"projectId": "<id:2>",
|
||||
"projectWorkspaceId": null,
|
||||
"goalId": null,
|
||||
"parentId": "<id:3>",
|
||||
"visibility": "open",
|
||||
"privacyRootIssueId": null,
|
||||
"privacyParentIssueId": null,
|
||||
"title": "Detail task",
|
||||
"titleNeedsGeneration": false,
|
||||
"description": "Uses [@Detail project](project://<id:2>)",
|
||||
"status": "in_progress",
|
||||
"statusVersion": 0,
|
||||
"lastStatusDecisionId": null,
|
||||
"workMode": "standard",
|
||||
"harnessKind": null,
|
||||
"priority": "high",
|
||||
"reviewPolicy": null,
|
||||
"assigneeAgentId": "<id:4>",
|
||||
"assigneeUserId": null,
|
||||
"checkoutRunId": null,
|
||||
"executionRunId": null,
|
||||
"executionAgentNameKey": null,
|
||||
"executionLockedAt": null,
|
||||
"createdByAgentId": null,
|
||||
"createdByUserId": "<user>",
|
||||
"responsibleUserId": null,
|
||||
"issueNumber": null,
|
||||
"identifier": null,
|
||||
"originKind": "manual",
|
||||
"originId": null,
|
||||
"originRunId": null,
|
||||
"originIssueId": null,
|
||||
"originIdentityContextId": null,
|
||||
"continuationIdentityContextId": null,
|
||||
"originFingerprint": "default",
|
||||
"requestDepth": 0,
|
||||
"billingCode": null,
|
||||
"assigneeAdapterOverrides": null,
|
||||
"executionPolicy": null,
|
||||
"executionState": null,
|
||||
"monitorNextCheckAt": null,
|
||||
"monitorWakeRequestedAt": null,
|
||||
"monitorLastTriggeredAt": null,
|
||||
"monitorAttemptCount": 0,
|
||||
"monitorNotes": null,
|
||||
"monitorScheduledBy": null,
|
||||
"executionWorkspaceId": null,
|
||||
"workspaceBindingRevision": 0,
|
||||
"workspaceSelection": null,
|
||||
"workspacePendingSelection": null,
|
||||
"executionWorkspacePreference": null,
|
||||
"executionWorkspaceSettings": null,
|
||||
"sourceTrust": null,
|
||||
"unblockDescriptor": null,
|
||||
"blockedTransitionAt": null,
|
||||
"blockedOwnerNotifiedAt": null,
|
||||
"startedAt": null,
|
||||
"completedAt": null,
|
||||
"cancelledAt": null,
|
||||
"hiddenAt": null,
|
||||
"createdAt": "<time>",
|
||||
"updatedAt": "<time>",
|
||||
"displayStatus": "todo",
|
||||
"externalConversationState": null,
|
||||
"labels": [],
|
||||
"labelIds": [],
|
||||
"watchdog": null,
|
||||
"ancestors": [
|
||||
{
|
||||
"id": "<id:3>",
|
||||
"identifier": null,
|
||||
"title": "Detail parent",
|
||||
"description": null,
|
||||
"status": "todo",
|
||||
"priority": "medium",
|
||||
"assigneeAgentId": null,
|
||||
"projectId": null,
|
||||
"goalId": null,
|
||||
"project": null,
|
||||
"goal": null
|
||||
},
|
||||
{
|
||||
"id": "<id:6>",
|
||||
"identifier": null,
|
||||
"title": "Detail grandparent",
|
||||
"description": null,
|
||||
"status": "todo",
|
||||
"priority": "medium",
|
||||
"assigneeAgentId": null,
|
||||
"projectId": "<id:2>",
|
||||
"goalId": null,
|
||||
"project": {
|
||||
"id": "<id:2>",
|
||||
"name": "Detail project",
|
||||
"description": null,
|
||||
"status": "backlog",
|
||||
"goalId": null,
|
||||
"workspaces": [],
|
||||
"primaryWorkspace": null
|
||||
},
|
||||
"goal": null
|
||||
}
|
||||
],
|
||||
"blockerAttention": {
|
||||
"state": "none",
|
||||
"reason": null,
|
||||
"unresolvedBlockerCount": 0,
|
||||
"coveredBlockerCount": 0,
|
||||
"stalledBlockerCount": 0,
|
||||
"attentionBlockerCount": 0,
|
||||
"pendingFinalizeBlockerIssueIds": [],
|
||||
"sampleBlockerIdentifier": null,
|
||||
"sampleStalledBlockerIdentifier": null,
|
||||
"blockingTreeLive": false,
|
||||
"directBlockerIssueId": null,
|
||||
"terminalBlockerIssueId": null,
|
||||
"terminalBlocker": null
|
||||
},
|
||||
"reviewAttention": {
|
||||
"state": "none",
|
||||
"paths": [],
|
||||
"reason": null
|
||||
},
|
||||
"successfulRunHandoff": null,
|
||||
"executionBlocker": null,
|
||||
"interruption": null,
|
||||
"scheduledRetry": null,
|
||||
"activeRecoveryAction": null,
|
||||
"stalledDependencies": [],
|
||||
"blockedBy": [
|
||||
{
|
||||
"id": "<id:7>",
|
||||
"identifier": null,
|
||||
"title": "Detail blocker",
|
||||
"status": "todo",
|
||||
"displayStatus": "todo",
|
||||
"priority": "medium",
|
||||
"assigneeAgentId": null,
|
||||
"assigneeUserId": null,
|
||||
"scheduledRetry": null,
|
||||
"activeRecoveryAction": null
|
||||
}
|
||||
],
|
||||
"blocks": [],
|
||||
"relatedWork": {
|
||||
"outbound": [],
|
||||
"inbound": []
|
||||
},
|
||||
"referencedIssueIdentifiers": [],
|
||||
"planDocument": null,
|
||||
"documentSummaries": [],
|
||||
"legacyPlanDocument": null,
|
||||
"project": {
|
||||
"id": "<id:2>",
|
||||
"companyId": "<id:1>",
|
||||
"urlKey": "detail-project",
|
||||
"goalId": null,
|
||||
"goalIds": [],
|
||||
"goals": [],
|
||||
"name": "Detail project",
|
||||
"description": null,
|
||||
"visibility": "open",
|
||||
"personalOwnerUserId": null,
|
||||
"status": "backlog",
|
||||
"leadAgentId": null,
|
||||
"targetDate": null,
|
||||
"color": null,
|
||||
"icon": null,
|
||||
"env": null,
|
||||
"pauseReason": null,
|
||||
"pausedAt": null,
|
||||
"executionWorkspacePolicy": null,
|
||||
"codebase": {
|
||||
"workspaceId": null,
|
||||
"repoUrl": null,
|
||||
"repoRef": null,
|
||||
"defaultRef": null,
|
||||
"repoName": null,
|
||||
"localFolder": null,
|
||||
"managedFolder": "<home>/projects/<id:1>/<id:2>/_default",
|
||||
"effectiveLocalFolder": "<home>/projects/<id:1>/<id:2>/_default",
|
||||
"origin": "managed_checkout"
|
||||
},
|
||||
"workspaces": [],
|
||||
"primaryWorkspace": null,
|
||||
"managedByPlugin": null,
|
||||
"archivedAt": null,
|
||||
"createdAt": "<time>",
|
||||
"updatedAt": "<time>"
|
||||
},
|
||||
"goal": null,
|
||||
"mentionedProjects": [
|
||||
{
|
||||
"id": "<id:2>",
|
||||
"companyId": "<id:1>",
|
||||
"goalId": null,
|
||||
"name": "Detail project",
|
||||
"description": null,
|
||||
"visibility": "open",
|
||||
"privacyOwnerUserId": null,
|
||||
"personalOwnerUserId": null,
|
||||
"status": "backlog",
|
||||
"leadAgentId": null,
|
||||
"decisionOwnerUserId": null,
|
||||
"targetDate": null,
|
||||
"color": null,
|
||||
"icon": null,
|
||||
"env": null,
|
||||
"gitAuthorizationGrantId": null,
|
||||
"gitAuthorizedByUserId": null,
|
||||
"pauseReason": null,
|
||||
"pausedAt": null,
|
||||
"executionWorkspacePolicy": null,
|
||||
"archivedAt": null,
|
||||
"createdAt": "<time>",
|
||||
"updatedAt": "<time>",
|
||||
"urlKey": "detail-project",
|
||||
"goalIds": [],
|
||||
"goals": [],
|
||||
"codebase": {
|
||||
"workspaceId": null,
|
||||
"repoUrl": null,
|
||||
"repoRef": null,
|
||||
"defaultRef": null,
|
||||
"repoName": null,
|
||||
"localFolder": null,
|
||||
"managedFolder": "<home>/projects/<id:1>/<id:2>/_default",
|
||||
"effectiveLocalFolder": "<home>/projects/<id:1>/<id:2>/_default",
|
||||
"origin": "managed_checkout"
|
||||
},
|
||||
"workspaces": [],
|
||||
"primaryWorkspace": null,
|
||||
"managedByPlugin": null,
|
||||
"workspaceProvider": {
|
||||
"source": "core",
|
||||
"pluginId": null,
|
||||
"displayName": "Core / local",
|
||||
"providers": [],
|
||||
"effectivePolicy": null,
|
||||
"error": null
|
||||
}
|
||||
}
|
||||
],
|
||||
"currentExecutionWorkspace": null,
|
||||
"workProducts": [
|
||||
{
|
||||
"id": "<id:8>",
|
||||
"companyId": "<id:1>",
|
||||
"projectId": "<id:2>",
|
||||
"issueId": "<id:0>",
|
||||
"executionWorkspaceId": null,
|
||||
"runtimeServiceId": null,
|
||||
"type": "pull_request",
|
||||
"provider": "github",
|
||||
"externalId": null,
|
||||
"title": "Fixture PR",
|
||||
"url": "https://example.test/pr/1",
|
||||
"status": "open",
|
||||
"reviewState": "none",
|
||||
"isPrimary": false,
|
||||
"healthStatus": "unknown",
|
||||
"summary": null,
|
||||
"metadata": null,
|
||||
"sourceTrust": null,
|
||||
"createdByRunId": null,
|
||||
"createdAt": "<time>",
|
||||
"updatedAt": "<time>"
|
||||
}
|
||||
],
|
||||
"externalChannelBinding": null,
|
||||
"createdFrom": null
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import net from "node:net";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
|
||||
export type MeteredStatement = { sql: string; parameters: number; rows: number; ms: number; inTransaction: boolean };
|
||||
export type MeteredStatement = { sql: string; parameters: number; rows: number; ms: number; inTransaction: boolean; stack?: string };
|
||||
|
||||
type Method = (this: unknown, ...args: unknown[]) => unknown;
|
||||
|
||||
@@ -27,6 +27,7 @@ export function meterDatabaseStatements(db: Db, databaseUrl: string) {
|
||||
const totals = { statements: 0, transactions: 0, waits: 0, rows: 0, sqlBytes: 0 };
|
||||
let inFlight = 0;
|
||||
let log: MeteredStatement[] | null = null;
|
||||
let captureStacks = false;
|
||||
const visited = new WeakSet<object>();
|
||||
const visit = (value: unknown, inTransaction: boolean) => {
|
||||
if ((typeof value !== "object" || value === null) && typeof value !== "function") return;
|
||||
@@ -42,7 +43,13 @@ export function meterDatabaseStatements(db: Db, databaseUrl: string) {
|
||||
if (inFlight === 0) totals.waits += 1;
|
||||
inFlight += 1;
|
||||
const pending = Reflect.apply(unsafe, this, args) as PromiseLike<{ length: number }>;
|
||||
const entry = { sql: query, parameters: Array.isArray(args[1]) ? args[1].length : 0, rows: 0, ms: 0, inTransaction };
|
||||
const entry: MeteredStatement = { sql: query, parameters: Array.isArray(args[1]) ? args[1].length : 0, rows: 0, ms: 0, inTransaction };
|
||||
if (log && captureStacks) {
|
||||
const limit = Error.stackTraceLimit;
|
||||
Error.stackTraceLimit = 60;
|
||||
entry.stack = new Error().stack;
|
||||
Error.stackTraceLimit = limit;
|
||||
}
|
||||
log?.push(entry);
|
||||
// The query starts one microtask after its first `then`, so a caller
|
||||
// can still select the result format on the returned query.
|
||||
@@ -79,7 +86,7 @@ export function meterDatabaseStatements(db: Db, databaseUrl: string) {
|
||||
/** The totals since the client started. Subtract two readings to meter one request. */
|
||||
read: () => ({ ...totals, bytesReceived: bytesReceived() }),
|
||||
/** Records every statement until `stopLog`. */
|
||||
startLog: () => { log = []; },
|
||||
startLog: (options: { stacks?: boolean } = {}) => { log = []; captureStacks = options.stacks === true; },
|
||||
stopLog: () => {
|
||||
const recorded = log ?? [];
|
||||
log = null;
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import express from "express";
|
||||
import { agents, authUsers, issueComments, issueWorkProducts, issues, projects, type Db } from "@paperclipai/db";
|
||||
import { actorMiddleware } from "../../middleware/auth.js";
|
||||
import { errorHandler } from "../../middleware/error-handler.js";
|
||||
import { activityRoutes } from "../../routes/activity.js";
|
||||
import { agentRoutes } from "../../routes/agents.js";
|
||||
import { companySkillRoutes } from "../../routes/company-skills.js";
|
||||
import { dashboardRoutes } from "../../routes/dashboard.js";
|
||||
import { issueRoutes } from "../../routes/issues.js";
|
||||
import { sidebarBadgeRoutes } from "../../routes/sidebar-badges.js";
|
||||
import { seedCompanyWithBoardAccess } from "./route-test-harness.js";
|
||||
|
||||
export function boardSessionApp(db: Db, sessionUserId: () => string | null) {
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use(actorMiddleware(db, {
|
||||
deploymentMode: "authenticated",
|
||||
resolveSession: async () => {
|
||||
const userId = sessionUserId();
|
||||
return userId ? {
|
||||
session: { id: `session-${userId}`, userId },
|
||||
user: { id: userId, name: "Board user", email: `${userId}@example.test` },
|
||||
} : null;
|
||||
},
|
||||
}));
|
||||
app.use("/api", issueRoutes(db, {} as never));
|
||||
app.use("/api", agentRoutes(db));
|
||||
app.use("/api", activityRoutes(db));
|
||||
app.use("/api", companySkillRoutes(db));
|
||||
app.use("/api", sidebarBadgeRoutes(db));
|
||||
app.use("/api", dashboardRoutes(db));
|
||||
app.use(errorHandler);
|
||||
return app;
|
||||
}
|
||||
|
||||
export async function seedBoardRouteFixture(db: Db, name: string, commentCount = 3) {
|
||||
const company = await seedCompanyWithBoardAccess(db, name);
|
||||
const now = new Date("2026-11-01T00:00:00.000Z");
|
||||
await db.insert(authUsers).values({
|
||||
id: company.userId, name, email: `${company.userId}@example.test`, emailVerified: true, createdAt: now, updatedAt: now,
|
||||
});
|
||||
const [agent] = await db.insert(agents).values({
|
||||
companyId: company.companyId, name: `${name} agent`, role: "engineer", adapterType: "process", status: "idle",
|
||||
}).returning();
|
||||
const [project] = await db.insert(projects).values({ companyId: company.companyId, name: `${name} project` }).returning();
|
||||
const [parent] = await db.insert(issues).values({
|
||||
companyId: company.companyId, title: `${name} parent`, status: "todo", createdByUserId: company.userId,
|
||||
createdAt: now, updatedAt: now,
|
||||
}).returning();
|
||||
const [issue] = await db.insert(issues).values({
|
||||
companyId: company.companyId, title: `${name} task`, description: "Fixture task", status: "in_progress",
|
||||
priority: "high", parentId: parent!.id, projectId: project!.id, assigneeAgentId: agent!.id,
|
||||
createdByUserId: company.userId, createdAt: now, updatedAt: now,
|
||||
}).returning();
|
||||
if (commentCount > 0) {
|
||||
await db.insert(issueComments).values(Array.from({ length: commentCount }, (_, index) => ({
|
||||
companyId: company.companyId, issueId: issue!.id, authorUserId: company.userId, authorType: "user" as const,
|
||||
body: `Comment ${index}`, createdAt: new Date(now.getTime() + (index + 1) * 1000), updatedAt: now,
|
||||
})));
|
||||
}
|
||||
await db.insert(issueWorkProducts).values({
|
||||
companyId: company.companyId, projectId: project!.id, issueId: issue!.id, type: "pull_request", provider: "github",
|
||||
title: "Fixture PR", url: "https://example.test/pr/1", status: "open", createdAt: now, updatedAt: now,
|
||||
});
|
||||
return { ...company, agent: agent!, project: project!, parent: parent!, issue: issue! };
|
||||
}
|
||||
|
||||
export type BoardRouteFixture = Awaited<ReturnType<typeof seedBoardRouteFixture>>;
|
||||
|
||||
export function boardCensusRoutes(fixture: BoardRouteFixture) {
|
||||
const { companyId, issue, parent } = fixture;
|
||||
return [
|
||||
["GET /api/issues/:id", `/api/issues/${issue.id}`],
|
||||
["GET /api/issues/:id/comments", `/api/issues/${issue.id}/comments`],
|
||||
["GET /api/issues/:id/activity", `/api/issues/${issue.id}/activity`],
|
||||
["GET /api/issues/:id/interactions", `/api/issues/${issue.id}/interactions`],
|
||||
["GET /api/issues/:id/work-products", `/api/issues/${issue.id}/work-products`],
|
||||
["GET /api/companies/:id/issues", `/api/companies/${companyId}/issues`],
|
||||
["GET /api/companies/:id/issues/summaries?ids", `/api/companies/${companyId}/issues/summaries?ids=${issue.id},${parent.id}`],
|
||||
["GET /api/companies/:id/live-runs", `/api/companies/${companyId}/live-runs`],
|
||||
["GET /api/companies/:id/skills", `/api/companies/${companyId}/skills`],
|
||||
["GET /api/companies/:id/sidebar-badges", `/api/companies/${companyId}/sidebar-badges`],
|
||||
["GET /api/companies/:id/dashboard", `/api/companies/${companyId}/dashboard`],
|
||||
["GET /api/companies/:id/agents", `/api/companies/${companyId}/agents`],
|
||||
["GET /api/companies/:id/chats", `/api/companies/${companyId}/chats`],
|
||||
] as const;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { meterDatabaseStatements, type MeteredStatement } from "./database-statement-meter.js";
|
||||
|
||||
export type StatementShape = { shape: string; count: number; callers: string[] };
|
||||
export type RequestCensus = { statements: number; transactions: number; shapes: StatementShape[]; log: MeteredStatement[] };
|
||||
|
||||
export function normalizeStatementShape(sql: string) {
|
||||
return sql
|
||||
.replace(/\s+/g, " ")
|
||||
.replace(/\$\d+(?:\s*,\s*\$\d+)*/g, "$n")
|
||||
.replace(/\(\s*\$n\s*\)(?:\s*,\s*\(\s*\$n\s*\))+/g, "($n)")
|
||||
.trim();
|
||||
}
|
||||
|
||||
export function statementCaller(stack: string | undefined, depth = 3) {
|
||||
if (!stack) return "unknown";
|
||||
const frames = stack.split("\n").slice(1).map((line) => line.trim())
|
||||
.filter((line) => line.includes("/server/src/") && !line.includes("/__tests__/"))
|
||||
.slice(0, depth)
|
||||
.map((line) => {
|
||||
const match = /at (?:async )?(?:(\S+) )?\(?.*\/server\/src\/([^:)]+):(\d+)/.exec(line);
|
||||
return match ? `${match[2]}:${match[3]}${match[1] ? ` ${match[1]}` : ""}` : line;
|
||||
});
|
||||
return frames.length > 0 ? frames.join(" < ") : "unknown";
|
||||
}
|
||||
|
||||
export function groupStatementShapes(log: MeteredStatement[]): StatementShape[] {
|
||||
const byShape = new Map<string, StatementShape>();
|
||||
for (const entry of log) {
|
||||
const shape = normalizeStatementShape(entry.sql);
|
||||
const group = byShape.get(shape) ?? { shape, count: 0, callers: [] };
|
||||
group.count += 1;
|
||||
const caller = statementCaller(entry.stack);
|
||||
if (!group.callers.includes(caller)) group.callers.push(caller);
|
||||
byShape.set(shape, group);
|
||||
}
|
||||
return [...byShape.values()].sort((left, right) => right.count - left.count);
|
||||
}
|
||||
|
||||
export function createStatementCensus(db: Db) {
|
||||
const { host, port } = (db.$client as unknown as { options: { host: string[]; port: number[] } }).options;
|
||||
const meter = meterDatabaseStatements(db, `postgres://${host[0]}:${port[0]}/census`);
|
||||
return {
|
||||
async measure(run: () => Promise<unknown>, options: { stacks?: boolean } = {}): Promise<RequestCensus> {
|
||||
const before = meter.read();
|
||||
meter.startLog(options);
|
||||
let log: MeteredStatement[];
|
||||
try {
|
||||
await run();
|
||||
} finally {
|
||||
log = meter.stopLog();
|
||||
}
|
||||
const after = meter.read();
|
||||
return {
|
||||
statements: after.statements - before.statements,
|
||||
transactions: after.transactions - before.transactions,
|
||||
shapes: groupStatementShapes(log),
|
||||
log,
|
||||
};
|
||||
},
|
||||
uninstall: () => meter.uninstall(),
|
||||
};
|
||||
}
|
||||
|
||||
export function formatStatementCensus(label: string, census: RequestCensus, top = 5) {
|
||||
const lines = [`${label}: ${census.statements} statements, ${census.transactions} transactions`];
|
||||
for (const shape of census.shapes.slice(0, top)) {
|
||||
lines.push(` ${String(shape.count).padStart(3)}x ${shape.shape.slice(0, 160)}`);
|
||||
for (const caller of shape.callers.slice(0, 3)) lines.push(` ${caller}`);
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { agentApiKeys, agents, authUsers, boardApiKeys, companies, companyMemberships, createDb, databaseStatementCount,
|
||||
instanceUserRoles } from "@paperclipai/db";
|
||||
import { createApp } from "../app.js";
|
||||
import { activeServerMetrics, recordMissedLeaseRenewal, recordRunEventCommitted } from "../services/server-metrics.js";
|
||||
import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js";
|
||||
import { createStorageService } from "../storage/service.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
const describePostgres = support.supported ? describe : describe.skip;
|
||||
const PATH = "/api/instance/server-metrics";
|
||||
const FIELDS = [
|
||||
"schema", "processId", "buildRevision", "uptimeSec", "sampledAt", "windowMs", "mainThreadCpu", "processCpu",
|
||||
"eventLoopUtilization", "eventLoopDelayP99Ms", "statementsPerSecond", "runEventLatenessP99Ms", "runEventLatenessSamples",
|
||||
"agentApiPreHandlerP99Ms", "agentApiPreHandlerSamples", "leaseRenewalsMissed", "dedicatedConnections",
|
||||
].sort();
|
||||
|
||||
type Db = ReturnType<typeof createDb>;
|
||||
type App = Awaited<ReturnType<typeof createApp>>;
|
||||
|
||||
describePostgres("instance server metrics route", () => {
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: Db;
|
||||
let directory: string;
|
||||
const hash = (token: string) => createHash("sha256").update(token).digest("hex");
|
||||
const ids = { companyId: randomUUID(), agentId: randomUUID(), adminId: randomUUID(), memberId: randomUUID() };
|
||||
const keys = { admin: `pcp_board_${randomUUID()}`, member: `pcp_board_${randomUUID()}`, agent: `pcp_agent_${randomUUID()}` };
|
||||
|
||||
beforeAll(async () => {
|
||||
database = await startEmbeddedPostgresTestDatabase("instance-server-metrics-");
|
||||
db = createDb(database.connectionString);
|
||||
directory = await mkdtemp(join(tmpdir(), "instance-server-metrics-storage-"));
|
||||
await db.insert(companies).values({ id: ids.companyId, name: "Metrics company", issuePrefix: "MET" });
|
||||
await db.insert(authUsers).values([ids.adminId, ids.memberId].map(id => ({ id, name: "Person", email: `${id}@example.com`,
|
||||
createdAt: new Date(), updatedAt: new Date() })));
|
||||
await db.insert(instanceUserRoles).values({ userId: ids.adminId, role: "instance_admin" });
|
||||
await db.insert(agents).values({ id: ids.agentId, companyId: ids.companyId, name: "Metrics agent", adapterType: "process",
|
||||
status: "idle", permissions: {}, runtimeConfig: { heartbeat: { wakeOnDemand: false, intervalSec: 0 } } });
|
||||
await db.insert(companyMemberships).values([
|
||||
{ companyId: ids.companyId, principalType: "user", principalId: ids.memberId, membershipRole: "owner", status: "active" },
|
||||
{ companyId: ids.companyId, principalType: "agent", principalId: ids.agentId, membershipRole: "member", status: "active" },
|
||||
]);
|
||||
await db.insert(boardApiKeys).values([
|
||||
{ userId: ids.adminId, name: "Admin", keyHash: hash(keys.admin) },
|
||||
{ userId: ids.memberId, name: "Member", keyHash: hash(keys.member) },
|
||||
]);
|
||||
await db.insert(agentApiKeys).values({ companyId: ids.companyId, agentId: ids.agentId, name: "Agent", keyHash: hash(keys.agent),
|
||||
responsibleUserId: ids.memberId });
|
||||
}, 120_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await db?.$client.end();
|
||||
await database?.cleanup();
|
||||
if (directory) await rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function serve<T>(serverMetricsEnabled: boolean, body: (call: (path: string, token?: string) => Promise<{ status: number; body: any; text: string }>) => Promise<T>) {
|
||||
const app: App = await createApp(db, {
|
||||
uiMode: "none", serverPort: 0, bindHost: "127.0.0.1", allowedHostnames: ["127.0.0.1"],
|
||||
deploymentMode: "authenticated", deploymentExposure: "private", authReady: true, companyDeletionEnabled: false,
|
||||
managedPluginAutoInstall: [], storageService: createStorageService(createLocalDiskStorageProvider(directory)),
|
||||
decisionServiceOptions: { wakeOriginAgent: async () => null }, serverMetricsEnabled,
|
||||
});
|
||||
await app.locals.bundledPluginsStartup;
|
||||
const server = app.listen(0, "127.0.0.1");
|
||||
try {
|
||||
await new Promise<void>(resolve => server.once("listening", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("No HTTP test address");
|
||||
const call = async (path: string, token?: string) => {
|
||||
const response = await fetch(`http://127.0.0.1:${address.port}${path}`, { headers: token ? { authorization: `Bearer ${token}` } : {} });
|
||||
const text = await response.text();
|
||||
let parsed: unknown = null;
|
||||
try { parsed = JSON.parse(text); } catch { parsed = null; }
|
||||
return { status: response.status, body: parsed, text };
|
||||
};
|
||||
return await body(call);
|
||||
} finally {
|
||||
await app.locals.paperclipShutdown?.();
|
||||
await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
||||
}
|
||||
}
|
||||
|
||||
it("serves numbers to an instance admin only, and they move with load", async () => {
|
||||
await serve(true, async (call) => {
|
||||
expect(activeServerMetrics()).not.toBeNull();
|
||||
expect([401, 403]).toContain((await call(PATH)).status);
|
||||
expect((await call(PATH, keys.member)).status).toBe(403);
|
||||
expect((await call(PATH, keys.agent)).status).toBe(403);
|
||||
|
||||
const first = await call(PATH, keys.admin);
|
||||
expect(first.status).toBe(200);
|
||||
expect(Object.keys(first.body).sort()).toEqual(FIELDS);
|
||||
expect(first.body).toMatchObject({ schema: "paperclip.server-metrics.v1", processId: expect.stringMatching(/^[0-9a-f]{16}$/) });
|
||||
expect(first.body.buildRevision === null || /^[0-9a-f]{40}$/.test(first.body.buildRevision)).toBe(true);
|
||||
for (const field of ["uptimeSec", "windowMs", "processCpu", "eventLoopUtilization", "eventLoopDelayP99Ms", "statementsPerSecond",
|
||||
"runEventLatenessSamples", "agentApiPreHandlerSamples", "leaseRenewalsMissed"]) {
|
||||
expect(typeof first.body[field], field).toBe("number");
|
||||
}
|
||||
expect(first.body.eventLoopUtilization).toBeGreaterThanOrEqual(0);
|
||||
expect(first.body.dedicatedConnections).toMatchObject({ limit: expect.any(Number), inUse: expect.any(Number), waiting: expect.any(Number),
|
||||
queued: expect.any(Number) });
|
||||
expect(first.body.eventLoopUtilization).toBeLessThanOrEqual(1);
|
||||
|
||||
const statementsBefore = databaseStatementCount();
|
||||
for (let index = 0; index < 5; index += 1) expect((await call("/api/agents/me", keys.agent)).status).toBe(200);
|
||||
expect(databaseStatementCount()).toBeGreaterThan(statementsBefore);
|
||||
recordRunEventCommitted(new Date(Date.now() - 750).toISOString(), Date.now());
|
||||
recordMissedLeaseRenewal();
|
||||
|
||||
const second = await call(PATH, keys.admin);
|
||||
expect(second.status).toBe(200);
|
||||
expect(second.body.processId).toBe(first.body.processId);
|
||||
expect(second.body.agentApiPreHandlerSamples).toBeGreaterThanOrEqual(first.body.agentApiPreHandlerSamples + 5);
|
||||
expect(second.body.agentApiPreHandlerP99Ms).toBeGreaterThan(0);
|
||||
expect(second.body.statementsPerSecond).toBeGreaterThan(0);
|
||||
expect(second.body.runEventLatenessSamples).toBe(first.body.runEventLatenessSamples + 1);
|
||||
expect(second.body.runEventLatenessP99Ms).toBeGreaterThanOrEqual(700);
|
||||
expect(second.body.leaseRenewalsMissed).toBe(first.body.leaseRenewalsMissed + 1);
|
||||
for (const secret of [...Object.values(ids), ...Object.values(keys)]) expect(second.text).not.toContain(secret);
|
||||
expect(second.text).not.toMatch(/select|insert|update|from\s/i);
|
||||
});
|
||||
expect(activeServerMetrics()).toBeNull();
|
||||
}, 240_000);
|
||||
|
||||
it("is absent and collects nothing when the kill switch is off", async () => {
|
||||
await serve(false, async (call) => {
|
||||
expect(activeServerMetrics()).toBeNull();
|
||||
expect((await call(PATH, keys.admin)).status).toBe(404);
|
||||
expect((await call(PATH, keys.member)).status).toBe(404);
|
||||
expect((await call("/api/agents/me", keys.agent)).status).toBe(200);
|
||||
expect(activeServerMetrics()).toBeNull();
|
||||
});
|
||||
}, 240_000);
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import request from "supertest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { expect, it } from "vitest";
|
||||
import { authUsers, companies, companyMemberships, issueRelations, issues } from "@paperclipai/db";
|
||||
import { boardSessionApp, seedBoardRouteFixture } from "./helpers/route-census-fixture.js";
|
||||
import { describeEmbeddedPostgres, useEmbeddedPostgres } from "./helpers/route-test-harness.js";
|
||||
import { createStatementCensus, formatStatementCensus } from "./helpers/statement-census.js";
|
||||
import { issueService } from "../services/issues.js";
|
||||
import { issueThreadInteractionService } from "../services/issue-thread-interactions.js";
|
||||
|
||||
const GOLDEN = new URL("./fixtures/issue-detail-response.json", import.meta.url);
|
||||
|
||||
function normalizeResponse(body: unknown, issuePrefix: string) {
|
||||
const ids = new Map<string, string>();
|
||||
const text = JSON.stringify(body, null, 2)
|
||||
.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g, (id) => {
|
||||
if (!ids.has(id)) ids.set(id, `<id:${ids.size}>`);
|
||||
return ids.get(id)!;
|
||||
})
|
||||
.replace(/"[^"]*\/instances\/[^/"]+\//g, "\"<home>/")
|
||||
.replace(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z/g, "<time>")
|
||||
.replaceAll(issuePrefix, "<prefix>")
|
||||
.replace(/user-<id:\d+>/g, "<user>");
|
||||
return `${text}\n`;
|
||||
}
|
||||
|
||||
describeEmbeddedPostgres("GET /api/issues/:id statements per request", () => {
|
||||
const ctx = useEmbeddedPostgres("issue-detail-statements-");
|
||||
|
||||
async function seed() {
|
||||
const fixture = await seedBoardRouteFixture(ctx.db, "Detail");
|
||||
const [grandparent] = await ctx.db.insert(issues).values({
|
||||
companyId: fixture.companyId, title: "Detail grandparent", status: "todo", projectId: fixture.project.id,
|
||||
createdByUserId: fixture.userId, createdAt: new Date("2026-10-30T00:00:00.000Z"), updatedAt: new Date("2026-10-30T00:00:00.000Z"),
|
||||
}).returning();
|
||||
await ctx.db.update(issues).set({ parentId: grandparent!.id }).where(eq(issues.id, fixture.parent.id));
|
||||
const [blocker] = await ctx.db.insert(issues).values({
|
||||
companyId: fixture.companyId, title: "Detail blocker", status: "todo", createdByUserId: fixture.userId,
|
||||
createdAt: new Date("2026-10-31T00:00:00.000Z"), updatedAt: new Date("2026-10-31T00:00:00.000Z"),
|
||||
}).returning();
|
||||
await ctx.db.insert(issueRelations).values({
|
||||
companyId: fixture.companyId, issueId: blocker!.id, relatedIssueId: fixture.issue.id, type: "blocks",
|
||||
});
|
||||
await ctx.db.update(issues).set({ description: `Uses [@Detail project](project://${fixture.project.id})` })
|
||||
.where(eq(issues.id, fixture.issue.id));
|
||||
const [company] = await ctx.db.select({ issuePrefix: companies.issuePrefix }).from(companies)
|
||||
.where(eq(companies.id, fixture.companyId));
|
||||
return { ...fixture, grandparent: grandparent!, blocker: blocker!, issuePrefix: company!.issuePrefix };
|
||||
}
|
||||
|
||||
it("answers the issue detail with the same JSON in fewer statements", async () => {
|
||||
const census = createStatementCensus(ctx.db);
|
||||
try {
|
||||
const fixture = await seed();
|
||||
const app = boardSessionApp(ctx.db, () => fixture.userId);
|
||||
const path = `/api/issues/${fixture.issue.id}`;
|
||||
await request(app).get(path).expect(200);
|
||||
let response: request.Response | undefined;
|
||||
const measured = await census.measure(async () => {
|
||||
response = await request(app).get(path).expect(200);
|
||||
}, { stacks: true });
|
||||
|
||||
const normalized = normalizeResponse(response!.body, fixture.issuePrefix);
|
||||
if (process.env.PAPERCLIP_WRITE_ISSUE_DETAIL_GOLDEN) writeFileSync(GOLDEN, normalized);
|
||||
expect(normalized).toBe(readFileSync(GOLDEN, "utf8"));
|
||||
expect(response!.body.ancestors.map((ancestor: { id: string }) => ancestor.id))
|
||||
.toEqual([fixture.parent.id, fixture.grandparent.id]);
|
||||
expect(response!.body.blockedBy.map((relation: { id: string }) => relation.id)).toEqual([fixture.blocker.id]);
|
||||
expect(response!.body.mentionedProjects.map((project: { id: string }) => project.id)).toEqual([fixture.project.id]);
|
||||
expect(measured.statements, formatStatementCensus(path, measured, 80)).toBeLessThanOrEqual(64);
|
||||
} finally {
|
||||
census.uninstall();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it("keeps the access rules: another company's user, a missing issue and a hidden issue", async () => {
|
||||
const fixture = await seed();
|
||||
const outsider = await seedBoardRouteFixture(ctx.db, "Outsider");
|
||||
const [hidden] = await ctx.db.insert(issues).values({
|
||||
companyId: fixture.companyId, title: "Hidden", status: "todo", hiddenAt: new Date(),
|
||||
}).returning();
|
||||
const memberApp = boardSessionApp(ctx.db, () => fixture.userId);
|
||||
const outsiderApp = boardSessionApp(ctx.db, () => outsider.userId);
|
||||
const anonymousApp = boardSessionApp(ctx.db, () => null);
|
||||
|
||||
const statuses = {
|
||||
outsiderReadsMemberIssue: (await request(outsiderApp).get(`/api/issues/${fixture.issue.id}`)).status,
|
||||
memberReadsOtherCompanyIssue: (await request(memberApp).get(`/api/issues/${outsider.issue.id}`)).status,
|
||||
memberReadsMissingIssue: (await request(memberApp).get(`/api/issues/${randomUUID()}`)).status,
|
||||
anonymousReadsMemberIssue: (await request(anonymousApp).get(`/api/issues/${fixture.issue.id}`)).status,
|
||||
};
|
||||
expect(statuses).toEqual({
|
||||
outsiderReadsMemberIssue: 404,
|
||||
memberReadsOtherCompanyIssue: 404,
|
||||
memberReadsMissingIssue: 404,
|
||||
anonymousReadsMemberIssue: 404,
|
||||
});
|
||||
const hiddenResponse = await request(memberApp).get(`/api/issues/${hidden!.id}`);
|
||||
expect(hiddenResponse.status).toBe(200);
|
||||
expect(hiddenResponse.body.hiddenAt).not.toBeNull();
|
||||
}, 60_000);
|
||||
|
||||
it("denies the very next request after the membership is removed", async () => {
|
||||
const fixture = await seed();
|
||||
const app = boardSessionApp(ctx.db, () => fixture.userId);
|
||||
await request(app).get(`/api/issues/${fixture.issue.id}`).expect(200);
|
||||
await ctx.db.delete(companyMemberships).where(eq(companyMemberships.principalId, fixture.userId));
|
||||
await request(app).get(`/api/issues/${fixture.issue.id}`).expect(404);
|
||||
await ctx.db.delete(authUsers).where(eq(authUsers.id, fixture.userId));
|
||||
}, 60_000);
|
||||
it("walks the ancestor chain nearest first, stops at a cycle and ignores a task that is its own parent", async () => {
|
||||
const fixture = await seed();
|
||||
const svc = issueService(ctx.db);
|
||||
await ctx.db.update(issues).set({ parentId: fixture.parent.id }).where(eq(issues.id, fixture.grandparent.id));
|
||||
const expected = [fixture.parent.id, fixture.grandparent.id];
|
||||
expect((await svc.getAncestors(fixture.issue.id)).map((ancestor) => ancestor.id)).toEqual(expected);
|
||||
expect((await svc.getAncestors(fixture.issue.id, { parentId: fixture.parent.id })).map((ancestor) => ancestor.id)).toEqual(expected);
|
||||
await ctx.db.update(issues).set({ parentId: fixture.blocker.id }).where(eq(issues.id, fixture.blocker.id));
|
||||
expect(await svc.getAncestors(fixture.blocker.id)).toEqual([]);
|
||||
}, 60_000);
|
||||
it("answers the interactions poll without reading the issue again", async () => {
|
||||
const census = createStatementCensus(ctx.db);
|
||||
try {
|
||||
const fixture = await seed();
|
||||
const app = boardSessionApp(ctx.db, () => fixture.userId);
|
||||
const path = `/api/issues/${fixture.issue.id}/interactions`;
|
||||
await request(app).get(path).expect(200);
|
||||
let response: request.Response | undefined;
|
||||
const measured = await census.measure(async () => {
|
||||
response = await request(app).get(path).expect(200);
|
||||
});
|
||||
const expected = await issueThreadInteractionService(ctx.db).listForIssue(fixture.issue.id);
|
||||
expect(response!.body).toEqual(JSON.parse(JSON.stringify(expected)));
|
||||
expect(measured.shapes.filter((shape) => shape.shape.startsWith('select "status", "company_id", "execution_workspace_id" from "issues"'))).toEqual([]);
|
||||
expect(measured.statements, formatStatementCensus(path, measured, 20)).toBeLessThanOrEqual(10);
|
||||
} finally {
|
||||
census.uninstall();
|
||||
}
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -872,7 +872,7 @@ describe("issue thread interaction routes", () => {
|
||||
.get("/api/issues/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/interactions")
|
||||
.expect(200, []);
|
||||
|
||||
expect(mockInteractionService.listForIssue).toHaveBeenCalledExactlyOnceWith(ISSUE_ID);
|
||||
expect(mockInteractionService.listForIssue).toHaveBeenCalledExactlyOnceWith(ISSUE_ID, expect.objectContaining({ id: ISSUE_ID, status }));
|
||||
expect(mockInteractionService.expireRequestConfirmationsSupersededByHistoricalComments).not.toHaveBeenCalled();
|
||||
expect(mockInteractionService.expirePendingInteractionsForTerminalIssue).not.toHaveBeenCalled();
|
||||
expect(mockLogActivity).not.toHaveBeenCalled();
|
||||
|
||||
@@ -312,7 +312,7 @@ describe("issue goal context routes", () => {
|
||||
);
|
||||
expect(mockIssueService.findMentionedProjectIds).toHaveBeenCalledWith(
|
||||
"11111111-1111-4111-8111-111111111111",
|
||||
{ includeCommentBodies: false },
|
||||
{ includeCommentBodies: false, issue: expect.objectContaining({ id: "11111111-1111-4111-8111-111111111111" }) },
|
||||
);
|
||||
expect(mockGoalService.getDefaultCompanyGoal).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
@@ -76,6 +76,7 @@ const apiPrefixes: Record<string, string> = {
|
||||
"inbox-agent-policy.ts": "/api",
|
||||
"inbox-dismissals.ts": "/api",
|
||||
"instance-database-backups.ts": "/api",
|
||||
"instance-server-metrics.ts": "/api",
|
||||
"instance-settings.ts": "/api",
|
||||
"issues.ts": "/api",
|
||||
"issue-tree-control.ts": "/api",
|
||||
|
||||
@@ -2,7 +2,7 @@ import { eq, fillPlaceholders, sql } from "drizzle-orm";
|
||||
import { PgDialect, pgTable, timestamp, uuid } from "drizzle-orm/pg-core";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { columnPlaceholder, preparedStatements } from "../services/prepared-statements.js";
|
||||
import { columnPlaceholder, preparedStatement, preparedStatements } from "../services/prepared-statements.js";
|
||||
|
||||
describe("prepared statements", () => {
|
||||
it("prepares a shape one time for a client, and again for another client or shape", () => {
|
||||
@@ -18,6 +18,17 @@ describe("prepared statements", () => {
|
||||
expect(prepare.mock.calls).toEqual([[root, "first"], [root, "after"], [transaction, "first"]]);
|
||||
});
|
||||
|
||||
it("prepares a single statement one time for each client", () => {
|
||||
const prepare = vi.fn((db: Db) => ({ db }));
|
||||
const statement = preparedStatement(prepare);
|
||||
const root = {} as Db, other = {} as Db;
|
||||
const first = statement(root);
|
||||
expect(statement(root)).toBe(first);
|
||||
expect(statement(other)).toEqual({ db: other });
|
||||
expect(statement(other)).not.toBe(first);
|
||||
expect(prepare.mock.calls).toEqual([[root], [other]]);
|
||||
});
|
||||
|
||||
it("encodes a placeholder value with the column, as the query builder encodes a bound value", () => {
|
||||
const table = pgTable("prepared_statement_fixture", { id: uuid("id"), at: timestamp("at", { withTimezone: true }) });
|
||||
const at = new Date("2026-11-12T10:00:00.123Z");
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import type { EventLoopUtilization } from "node:perf_hooks";
|
||||
import {
|
||||
activeServerMetrics,
|
||||
recordMissedLeaseRenewal,
|
||||
recordRunEventCommitted,
|
||||
ServerMetricsCollector,
|
||||
serverMetricsEnabledFromEnv,
|
||||
startServerMetrics,
|
||||
stopServerMetrics,
|
||||
type ServerMetricsProbes,
|
||||
} from "../services/server-metrics.js";
|
||||
|
||||
const FIXTURE = fileURLToPath(new URL("../../../scripts/scale-ramp/server-metrics.fixture.json", import.meta.url));
|
||||
|
||||
function fakeProbes() {
|
||||
const state = { now: 0, wall: Date.parse("2026-11-14T12:00:00.000Z"), idle: 0, active: 0, cpuMicros: 0, mainMs: 0, statements: 0, uptime: 100 };
|
||||
const elu = (): EventLoopUtilization => ({ idle: state.idle, active: state.active, utilization: 0 });
|
||||
const probes: ServerMetricsProbes = {
|
||||
now: () => state.now,
|
||||
wallNow: () => state.wall,
|
||||
eventLoopUtilization: (current?: EventLoopUtilization, previous?: EventLoopUtilization) => {
|
||||
if (!current) return elu();
|
||||
const idle = current.idle - (previous?.idle ?? 0);
|
||||
const active = current.active - (previous?.active ?? 0);
|
||||
return { idle, active, utilization: idle + active > 0 ? active / (idle + active) : 0 };
|
||||
},
|
||||
processCpuMicros: () => state.cpuMicros,
|
||||
mainThreadCpuMs: () => state.mainMs,
|
||||
statementCount: () => state.statements,
|
||||
uptimeSec: () => state.uptime,
|
||||
dedicatedConnections: () => ({ limit: 24, inUse: 3, peakInUse: 9, waiting: 1, queued: 12, overLimit: 0, nestedOverLimit: 0 }),
|
||||
};
|
||||
const advance = (ms: number, load: { busy: number; cpu?: number; statementsPerSecond?: number }) => {
|
||||
state.now += ms;
|
||||
state.wall += ms;
|
||||
state.uptime += ms / 1000;
|
||||
state.active += ms * load.busy;
|
||||
state.idle += ms * (1 - load.busy);
|
||||
state.mainMs += ms * load.busy;
|
||||
state.cpuMicros += ms * (load.cpu ?? load.busy) * 1000;
|
||||
state.statements += (ms / 1000) * (load.statementsPerSecond ?? 0);
|
||||
};
|
||||
return { probes, advance };
|
||||
}
|
||||
|
||||
const collectors: ServerMetricsCollector[] = [];
|
||||
function collector(probes: ServerMetricsProbes) {
|
||||
const created = new ServerMetricsCollector({ probes, bucketMs: 10_000, buckets: 6, buildRevision: "0123456789abcdef0123456789abcdef01234567",
|
||||
monitorEventLoop: false, processId: "a1b2c3d4e5f60718" });
|
||||
collectors.push(created);
|
||||
return created;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const created of collectors.splice(0)) created.stop();
|
||||
const active = activeServerMetrics();
|
||||
if (active) stopServerMetrics(active);
|
||||
});
|
||||
|
||||
describe("server metrics collector", () => {
|
||||
it("reports rates and utilization over the sliding window, dropping buckets older than the window", () => {
|
||||
const { probes, advance } = fakeProbes();
|
||||
const metrics = collector(probes);
|
||||
for (let bucket = 0; bucket < 6; bucket += 1) {
|
||||
advance(10_000, { busy: 0.9, statementsPerSecond: 500 });
|
||||
metrics.rotate();
|
||||
}
|
||||
const busy = metrics.snapshot();
|
||||
expect(busy.windowMs).toBe(50_000);
|
||||
expect(busy.eventLoopUtilization).toBeCloseTo(0.9, 4);
|
||||
expect(busy.mainThreadCpu).toBeCloseTo(0.9, 4);
|
||||
expect(busy.statementsPerSecond).toBeCloseTo(500, 2);
|
||||
|
||||
for (let bucket = 0; bucket < 6; bucket += 1) {
|
||||
advance(10_000, { busy: 0.1, statementsPerSecond: 20 });
|
||||
metrics.rotate();
|
||||
}
|
||||
const quiet = metrics.snapshot();
|
||||
expect(quiet.eventLoopUtilization).toBeCloseTo(0.1, 4);
|
||||
expect(quiet.statementsPerSecond).toBeCloseTo(20, 2);
|
||||
});
|
||||
|
||||
it("expires buckets by elapsed time when the rotation timer fires late", () => {
|
||||
const { probes, advance } = fakeProbes();
|
||||
const metrics = collector(probes);
|
||||
for (let bucket = 0; bucket < 6; bucket += 1) {
|
||||
advance(10_000, { busy: 0.1, statementsPerSecond: 10 });
|
||||
metrics.rotate();
|
||||
}
|
||||
metrics.recordRunEventLatenessMs(5_000);
|
||||
advance(35_000, { busy: 0.5, statementsPerSecond: 100 });
|
||||
metrics.rotate();
|
||||
const late = metrics.snapshot();
|
||||
expect(late.windowMs).toBe(55_000);
|
||||
expect(late.statementsPerSecond).toBeCloseTo((20 * 10 + 35 * 100) / 55, 2);
|
||||
expect(late.runEventLatenessSamples).toBe(1);
|
||||
});
|
||||
|
||||
it("reports the real window after a block longer than the window, and the block shows in it", () => {
|
||||
const { probes, advance } = fakeProbes();
|
||||
const metrics = collector(probes);
|
||||
for (let bucket = 0; bucket < 6; bucket += 1) {
|
||||
advance(10_000, { busy: 0.1 });
|
||||
metrics.rotate();
|
||||
}
|
||||
metrics.recordRunEventLatenessMs(20);
|
||||
advance(300_000, { busy: 1 });
|
||||
metrics.rotate();
|
||||
const blocked = metrics.snapshot();
|
||||
expect(blocked.windowMs).toBe(300_000);
|
||||
expect(blocked.eventLoopUtilization).toBeCloseTo(1, 4);
|
||||
expect(blocked.runEventLatenessSamples).toBe(1);
|
||||
advance(10_000, { busy: 0.2 });
|
||||
metrics.rotate();
|
||||
expect(metrics.snapshot()).toMatchObject({ windowMs: 10_000, runEventLatenessSamples: 0 });
|
||||
for (let bucket = 0; bucket < 5; bucket += 1) {
|
||||
advance(10_000, { busy: 0.2 });
|
||||
metrics.rotate();
|
||||
}
|
||||
const recovered = metrics.snapshot();
|
||||
expect(recovered.windowMs).toBe(50_000);
|
||||
expect(recovered.eventLoopUtilization).toBeCloseTo(0.2, 4);
|
||||
});
|
||||
|
||||
it("reports latency percentiles only for the window and absent when nothing was recorded", () => {
|
||||
const { probes, advance } = fakeProbes();
|
||||
const metrics = collector(probes);
|
||||
expect(metrics.snapshot()).toMatchObject({ runEventLatenessP99Ms: null, runEventLatenessSamples: 0,
|
||||
agentApiPreHandlerP99Ms: null, agentApiPreHandlerSamples: 0 });
|
||||
for (let index = 0; index < 100; index += 1) metrics.recordRunEventLatenessMs(index < 98 ? 20 : 2_000);
|
||||
metrics.recordAgentApiPreHandlerMs(3.5);
|
||||
const recorded = metrics.snapshot();
|
||||
expect(recorded.runEventLatenessSamples).toBe(100);
|
||||
expect(recorded.runEventLatenessP99Ms).toBeGreaterThan(1_900);
|
||||
expect(recorded.agentApiPreHandlerP99Ms).toBeCloseTo(3.5, 1);
|
||||
for (let bucket = 0; bucket < 6; bucket += 1) {
|
||||
advance(10_000, { busy: 0 });
|
||||
metrics.rotate();
|
||||
}
|
||||
expect(metrics.snapshot()).toMatchObject({ runEventLatenessP99Ms: null, runEventLatenessSamples: 0, agentApiPreHandlerSamples: 0 });
|
||||
});
|
||||
|
||||
it("counts missed lease renewals since start and never resets them with the window", () => {
|
||||
const { probes, advance } = fakeProbes();
|
||||
const metrics = collector(probes);
|
||||
metrics.recordMissedLeaseRenewal();
|
||||
metrics.recordMissedLeaseRenewal();
|
||||
for (let bucket = 0; bucket < 8; bucket += 1) {
|
||||
advance(10_000, { busy: 0 });
|
||||
metrics.rotate();
|
||||
}
|
||||
expect(metrics.snapshot().leaseRenewalsMissed).toBe(2);
|
||||
});
|
||||
|
||||
it("records into the process collector only while it runs", () => {
|
||||
recordRunEventCommitted(new Date(Date.now() - 500).toISOString(), Date.now());
|
||||
recordMissedLeaseRenewal();
|
||||
expect(activeServerMetrics()).toBeNull();
|
||||
const started = startServerMetrics();
|
||||
expect(startServerMetrics()).toBe(started);
|
||||
recordRunEventCommitted(new Date(Date.now() - 500).toISOString(), Date.now());
|
||||
recordRunEventCommitted("not a time", Date.now());
|
||||
recordMissedLeaseRenewal();
|
||||
const snapshot = started.snapshot();
|
||||
expect(snapshot.runEventLatenessSamples).toBe(1);
|
||||
expect(snapshot.runEventLatenessP99Ms).toBeGreaterThanOrEqual(450);
|
||||
expect(snapshot.leaseRenewalsMissed).toBe(1);
|
||||
stopServerMetrics(started);
|
||||
expect(activeServerMetrics()).toBeNull();
|
||||
});
|
||||
|
||||
it("reads the kill switch strictly and defaults it off", () => {
|
||||
expect(serverMetricsEnabledFromEnv({})).toBe(false);
|
||||
expect(serverMetricsEnabledFromEnv({ PAPERCLIP_SERVER_METRICS: "true" })).toBe(true);
|
||||
expect(serverMetricsEnabledFromEnv({ PAPERCLIP_SERVER_METRICS: "0" })).toBe(false);
|
||||
expect(() => serverMetricsEnabledFromEnv({ PAPERCLIP_SERVER_METRICS: "yes" })).toThrow(/PAPERCLIP_SERVER_METRICS/);
|
||||
});
|
||||
|
||||
it("serializes exactly the fixture the scale-ramp harness parses", () => {
|
||||
const { probes, advance } = fakeProbes();
|
||||
const metrics = collector(probes);
|
||||
for (let bucket = 0; bucket < 6; bucket += 1) {
|
||||
advance(10_000, { busy: 0.42, cpu: 0.55, statementsPerSecond: 180 });
|
||||
metrics.rotate();
|
||||
}
|
||||
for (let index = 0; index < 50; index += 1) metrics.recordRunEventLatenessMs(120);
|
||||
for (let index = 0; index < 50; index += 1) metrics.recordAgentApiPreHandlerMs(15);
|
||||
metrics.recordMissedLeaseRenewal();
|
||||
const snapshot = JSON.parse(JSON.stringify(metrics.snapshot()));
|
||||
if (process.env.UPDATE_SERVER_METRICS_FIXTURE === "1") writeFileSync(FIXTURE, `${JSON.stringify(snapshot, null, 2)}\n`);
|
||||
expect(snapshot).toEqual(JSON.parse(readFileSync(FIXTURE, "utf8")));
|
||||
});
|
||||
});
|
||||
@@ -17,7 +17,7 @@ import * as storageModule from "../storage/index.js";
|
||||
import { createStorageService } from "../storage/service.js";
|
||||
import { createLocalDiskStorageProvider } from "../storage/local-disk-provider.js";
|
||||
import { companySkillService } from "../services/company-skills.js";
|
||||
import { skillPackageStore, skillPackagePaths, withSkillPackageReadScope } from "../services/skill-package-store.js";
|
||||
import { skillPackageStore, skillPackagePaths, skillPackageStorageIoDepth, withSkillPackageReadScope } from "../services/skill-package-store.js";
|
||||
import { skillPackageMaintenance } from "../services/skill-package-maintenance.js";
|
||||
import { skillPackageManifest, validateSkillPackageManifest, writeSkillPackageArchive, extractSkillPackageArchive,
|
||||
verifySkillPackageDirectory } from "../services/skill-package-files.js";
|
||||
@@ -755,7 +755,6 @@ describe.skipIf(!support.supported)("external skill packages", () => {
|
||||
let ready = 0;
|
||||
vi.spyOn(dbModule, "withDedicatedDbConnection").mockImplementation((owner, action) => dedicated(owner, connection => {
|
||||
connection.$client.options.debug = observe;
|
||||
if (kind === "files") ready++;
|
||||
return action(connection);
|
||||
}));
|
||||
if (kind === "manifest") {
|
||||
@@ -770,7 +769,8 @@ describe.skipIf(!support.supported)("external skill packages", () => {
|
||||
const read = (id: string) => kind === "files" ? store.files(companyId, id, true) : store.manifest(companyId, id);
|
||||
const queued = rows.slice(0, 32).map(row => read(row.id));
|
||||
try {
|
||||
await vi.waitFor(() => expect(ready).toBe(32));
|
||||
await vi.waitFor(() => expect(kind === "files" ? skillPackageStorageIoDepth().waiting : ready).toBe(32));
|
||||
if (kind === "files") expect(dbModule.dedicatedDbConnectionStats(db)?.inUse).toBe(2);
|
||||
// The final reader observes the full queue only after all earlier readers
|
||||
// have reached admission. None may preload repository bodies while waiting.
|
||||
await expect(read(rows[32]!.id)).rejects.toThrow("busy");
|
||||
|
||||
+17
-1
@@ -1,3 +1,4 @@
|
||||
import { authorizationReadScope } from "./services/authorization-read-scope.js";
|
||||
import type { IdleDeadlineOwners } from "./services/idle-deadline-types.js";
|
||||
import { startMcpClientMirrorSync } from "./services/public-mcp/client-mirror-sync.js";
|
||||
import { registerIdleMcpOwners } from "./services/public-mcp/idle-sleep-proof.js";
|
||||
@@ -11,7 +12,7 @@ import { finishServiceShutdown } from "./shutdown.js";
|
||||
import { promptInjectionPreventionRoutes } from "./routes/prompt-injection-prevention.js";
|
||||
import { voiceSessionRoutes, voiceWebhookRoutes } from "./routes/voice-sessions.js";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { chatEndpoints } from "@paperclipai/db";
|
||||
import { chatEndpoints, dedicatedDbConnectionStats } from "@paperclipai/db";
|
||||
import { fastResponseRoutes } from "./routes/fast-responses.js";
|
||||
import { fastResponseService } from "./services/fast-responses.js";
|
||||
import { createDeliveryWorkCoordinator } from "./services/delivery-work-coordinator.js";
|
||||
@@ -253,6 +254,14 @@ import {
|
||||
import { COMPANY_IMPORT_API_PATH } from "./routes/company-import-paths.js";
|
||||
import { apiCompression } from "./middleware/api-compression.js";
|
||||
import { apiServerTiming } from "./middleware/api-server-timing.js";
|
||||
import { instanceServerMetricsRoutes } from "./routes/instance-server-metrics.js";
|
||||
import {
|
||||
serverMetricsAgentPreHandler,
|
||||
serverMetricsArrival,
|
||||
serverMetricsEnabledFromEnv,
|
||||
startServerMetrics,
|
||||
stopServerMetrics,
|
||||
} from "./services/server-metrics.js";
|
||||
import { chatWebhookBodyParser } from "./middleware/chat-webhook-body.js";
|
||||
import { createChatWebhookDiagnostics } from "./services/chat-webhook-diagnostics.js";
|
||||
|
||||
@@ -491,9 +500,12 @@ export async function createApp(
|
||||
managedPluginAutoInstall?: readonly string[] | null;
|
||||
/** Test override for the bundled plugin catalog root. */
|
||||
bundledPluginCatalogRoot?: string;
|
||||
serverMetricsEnabled?: boolean;
|
||||
},
|
||||
) {
|
||||
const app = express();
|
||||
const serverMetrics = (opts.serverMetricsEnabled ?? serverMetricsEnabledFromEnv(process.env)) ? startServerMetrics(() => dedicatedDbConnectionStats(db)) : null;
|
||||
if (serverMetrics) app.use("/api", serverMetricsArrival());
|
||||
// First, so the reported server time includes admission and database waits.
|
||||
app.use("/api", apiServerTiming());
|
||||
app.use(databaseOperationMiddleware);
|
||||
@@ -624,6 +636,7 @@ export async function createApp(
|
||||
// REPLACES whatever actor the request otherwise resolved to, and only on
|
||||
// the one endpoint it authorizes (see the middleware for the contract).
|
||||
app.use(cloudControlMiddleware());
|
||||
app.use(authorizationReadScope);
|
||||
app.use(runnerCallOutcomeMiddleware(db));
|
||||
app.use(connectionEventWakeRoutes(db));
|
||||
app.use(skillAccessRequestContext);
|
||||
@@ -886,6 +899,7 @@ export async function createApp(
|
||||
if (opts.databaseBackupService) {
|
||||
api.use(instanceDatabaseBackupRoutes(opts.databaseBackupService));
|
||||
}
|
||||
if (serverMetrics) api.use(instanceServerMetricsRoutes(serverMetrics));
|
||||
const pluginRegistry = pluginRegistryService(db);
|
||||
const eventBus = createPluginEventBus();
|
||||
setPluginEventBus(eventBus);
|
||||
@@ -1084,6 +1098,7 @@ export async function createApp(
|
||||
|
||||
api.use(museBoardRoutes(db, opts.authPublicBaseUrl));
|
||||
api.use(museQualificationRoutes(db));
|
||||
if (serverMetrics) app.use("/api", serverMetricsAgentPreHandler(serverMetrics));
|
||||
app.use("/api", api);
|
||||
app.use("/api", (_req, res) => {
|
||||
res.status(404).json({ error: "API route not found" });
|
||||
@@ -1448,6 +1463,7 @@ export async function createApp(
|
||||
// caller stops the database and the provider. A lease release that
|
||||
// fails stays a durable record for the startup reaper.
|
||||
await setupTokenLoginService?.shutdown();
|
||||
if (serverMetrics) stopServerMetrics(serverMetrics);
|
||||
});
|
||||
});
|
||||
return appServicesShutdown;
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { and, eq, sql, type Placeholder } from "drizzle-orm";
|
||||
import { heartbeatRuns, type Db } from "@paperclipai/db";
|
||||
import { requestRunIdentityFields } from "../services/run-identity.js";
|
||||
import { preparedStatement } from "../services/prepared-statements.js";
|
||||
|
||||
export function loadAgentRunAuthentication(db: Db, input: {
|
||||
runId: string;
|
||||
companyId: string;
|
||||
agentId: string;
|
||||
}) {
|
||||
type Bound<Value> = Value | Placeholder;
|
||||
export type AgentRunAuthenticationBinding = { runId: Bound<string>; companyId: Bound<string>; agentId: Bound<string> };
|
||||
|
||||
export function agentRunAuthenticationQuery(db: Db, input: AgentRunAuthenticationBinding) {
|
||||
return db.select({
|
||||
activeIdentityContextId: heartbeatRuns.activeIdentityContextId,
|
||||
responsibleUserId: heartbeatRuns.responsibleUserId,
|
||||
@@ -27,3 +27,17 @@ export function loadAgentRunAuthentication(db: Db, input: {
|
||||
eq(heartbeatRuns.agentId, input.agentId),
|
||||
));
|
||||
}
|
||||
|
||||
const agentRunAuthenticationStatement = preparedStatement(db => agentRunAuthenticationQuery(db, {
|
||||
runId: sql.placeholder("runId"),
|
||||
companyId: sql.placeholder("companyId"),
|
||||
agentId: sql.placeholder("agentId"),
|
||||
}).prepare("agent_run_authentication"));
|
||||
|
||||
export function loadAgentRunAuthentication(db: Db, input: {
|
||||
runId: string;
|
||||
companyId: string;
|
||||
agentId: string;
|
||||
}) {
|
||||
return agentRunAuthenticationStatement(db).execute(input);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { notifyMuseContactVerification } from "../modules/external-agents/index.
|
||||
import { idleApiActivity } from "../services/idle-api-activity.js";
|
||||
import { createHash, timingSafeEqual } from "node:crypto";
|
||||
import type { Request, RequestHandler } from "express";
|
||||
import { and, eq, exists, isNull, sql } from "drizzle-orm";
|
||||
import { and, eq, exists, isNull, sql, type Placeholder } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import {
|
||||
activityLog,
|
||||
@@ -31,6 +31,7 @@ import { logger } from "./logger.js";
|
||||
import { localAgentProcessBoundary, type LocalAgentProcessBoundary } from "./local-agent-process-boundary.js";
|
||||
import { resolveRequestRunIdentity } from "../services/run-identity.js";
|
||||
import { boardAuthService } from "../services/board-auth.js";
|
||||
import { preparedStatement } from "../services/prepared-statements.js";
|
||||
import { retryIdempotentDatabaseOperation } from "../database-retry.js";
|
||||
import { beginIdleTrackedWork } from "../services/task-admission.js";
|
||||
import { notifyChatCompanyAuthorityChange } from "../services/chat-run-milestone-notifications.js";
|
||||
@@ -76,11 +77,20 @@ const agentAuthenticationFields = {
|
||||
lifecycleHolds: agents.lifecycleHolds,
|
||||
};
|
||||
|
||||
async function loadResponsibleUserMemberships(
|
||||
db: Db,
|
||||
input: { companyId: string; userId: string | null },
|
||||
) {
|
||||
if (!input.userId) return [];
|
||||
type Bound<Value> = Value | Placeholder;
|
||||
|
||||
export function agentAuthenticationQuery(db: Db, agentId: Bound<string>) {
|
||||
return db.select(agentAuthenticationFields).from(agents).where(eq(agents.id, agentId));
|
||||
}
|
||||
|
||||
const agentAuthenticationStatement = preparedStatement(db =>
|
||||
agentAuthenticationQuery(db, sql.placeholder("agentId")).prepare("agent_authentication"));
|
||||
|
||||
function loadAgentAuthentication(db: Db, agentId: string) {
|
||||
return agentAuthenticationStatement(db).execute({ agentId }).then((rows) => rows[0] ?? null);
|
||||
}
|
||||
|
||||
export function responsibleUserMembershipsQuery(db: Db, input: { companyId: Bound<string>; userId: Bound<string> }) {
|
||||
return db
|
||||
.select({
|
||||
companyId: companyMemberships.companyId,
|
||||
@@ -99,6 +109,19 @@ async function loadResponsibleUserMemberships(
|
||||
);
|
||||
}
|
||||
|
||||
const responsibleUserMembershipsStatement = preparedStatement(db => responsibleUserMembershipsQuery(db, {
|
||||
companyId: sql.placeholder("companyId"),
|
||||
userId: sql.placeholder("userId"),
|
||||
}).prepare("responsible_user_memberships"));
|
||||
|
||||
async function loadResponsibleUserMemberships(
|
||||
db: Db,
|
||||
input: { companyId: string; userId: string | null },
|
||||
) {
|
||||
if (!input.userId) return [];
|
||||
return responsibleUserMembershipsStatement(db).execute({ companyId: input.companyId, userId: input.userId });
|
||||
}
|
||||
|
||||
/**
|
||||
* The user's own active company memberships — the exact company scope a
|
||||
* locally authenticated session actor carries. Shared by the session path
|
||||
@@ -357,11 +380,7 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa
|
||||
return;
|
||||
}
|
||||
|
||||
const agentRecord = await db
|
||||
.select(agentAuthenticationFields)
|
||||
.from(agents)
|
||||
.where(eq(agents.id, claims.sub))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
const agentRecord = await loadAgentAuthentication(db, claims.sub);
|
||||
|
||||
if (!agentRecord || agentRecord.companyId !== claims.company_id) {
|
||||
next(unauthorized("Agent record is missing or belongs to another company; obtain fresh credentials and retry"));
|
||||
@@ -478,11 +497,7 @@ export function actorMiddleware(db: Db, opts: ActorMiddlewareOptions): RequestHa
|
||||
.set({ lastUsedAt: new Date() })
|
||||
.where(eq(agentApiKeys.id, key.id));
|
||||
|
||||
const agentRecord = await db
|
||||
.select(agentAuthenticationFields)
|
||||
.from(agents)
|
||||
.where(eq(agents.id, key.agentId))
|
||||
.then((rows) => rows[0] ?? null);
|
||||
const agentRecord = await loadAgentAuthentication(db, key.agentId);
|
||||
|
||||
if (!agentRecord || agentRecord.companyId !== key.companyId) {
|
||||
next(unauthorized("Agent record is missing or belongs to another company; obtain fresh credentials and retry"));
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Router } from "express";
|
||||
import type { ServerMetricsCollector } from "../services/server-metrics.js";
|
||||
import { assertInstanceAdmin } from "./authz.js";
|
||||
|
||||
export function instanceServerMetricsRoutes(collector: ServerMetricsCollector) {
|
||||
const router = Router();
|
||||
|
||||
router.get("/instance/server-metrics", (req, res) => {
|
||||
assertInstanceAdmin(req);
|
||||
res.set("Cache-Control", "no-store");
|
||||
res.json(collector.snapshot());
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
@@ -8478,9 +8478,9 @@ export function issueRoutes(
|
||||
companyId: string;
|
||||
projectId: string | null;
|
||||
goalId: string | null;
|
||||
}) {
|
||||
}, options: { workspaceProvider?: boolean } = {}) {
|
||||
const projectPromise = issue.projectId
|
||||
? projectsSvc.getById(issue.projectId)
|
||||
? projectsSvc.getById(issue.projectId, options)
|
||||
: Promise.resolve(null);
|
||||
const directGoalPromise = issue.goalId
|
||||
? goalsSvc.getById(issue.goalId)
|
||||
@@ -10157,20 +10157,20 @@ export function issueRoutes(
|
||||
workProducts,
|
||||
createdFrom,
|
||||
] = await Promise.all([
|
||||
timing.time("project_goal", () => resolveIssueProjectAndGoal(issue)),
|
||||
timing.time("ancestors", () => svc.getAncestors(issue.id)),
|
||||
timing.time("mentions", () => svc.findMentionedProjectIds(issue.id, { includeCommentBodies: false })),
|
||||
timing.time("project_goal", () => resolveIssueProjectAndGoal(issue, { workspaceProvider: false })),
|
||||
timing.time("ancestors", () => svc.getAncestors(issue.id, { parentId: issue.parentId })),
|
||||
timing.time("mentions", () => svc.findMentionedProjectIds(issue.id, { includeCommentBodies: false, issue })),
|
||||
timing.time("documents", () => documentsSvc.getIssueDocumentPayload(issue)),
|
||||
timing.time("relations", () => svc.getRelationSummaries(issue.id)),
|
||||
timing.time("relations", () => svc.getRelationSummaries(issue.id, { companyId: issue.companyId })),
|
||||
timing.time("blockers", () => svc
|
||||
.listBlockerAttention(issue.companyId, [issue])
|
||||
.then((map) => map.get(issue.id) ?? null)),
|
||||
timing.time("review", () => svc
|
||||
.listReviewAttention(issue.companyId, [issue])
|
||||
.then((map) => map.get(issue.id) ?? null)),
|
||||
timing.time("references", () => issueReferencesSvc.listIssueReferenceSummary(issue.id)),
|
||||
timing.time("references", () => issueReferencesSvc.listIssueReferenceSummary(issue.id, undefined, { companyId: issue.companyId })),
|
||||
timing.time("handoff", () => listSuccessfulRunHandoffStates(db, issue.companyId, [issue.id])),
|
||||
timing.time("retry", () => svc.getCurrentScheduledRetry(issue.id)),
|
||||
timing.time("retry", () => svc.getCurrentScheduledRetry(issue.id, { companyId: issue.companyId })),
|
||||
timing.time("recovery", () => recoveryActionsSvc.getActiveForIssue(issue.companyId, issue.id)),
|
||||
inboxArchiveFieldsPromise,
|
||||
timing.time("channel", () => getExternalChannelBindingSummary(db, issue.companyId, issue.id)),
|
||||
@@ -18402,7 +18402,7 @@ export function issueRoutes(
|
||||
if (!issue) return;
|
||||
if (!(await assertIssueReadAllowed(req, res, issue))) return;
|
||||
const interactions =
|
||||
await issueThreadInteractionService(db).listForIssue(id);
|
||||
await issueThreadInteractionService(db).listForIssue(issue.id, issue);
|
||||
if (req.actor.type === "agent" && req.actor.agentId && req.actor.runId) {
|
||||
await recordDeclinedInteractionRead(db, { companyId: issue.companyId, agentId: req.actor.agentId, runId: req.actor.runId,
|
||||
issue, interactions: interactions as Parameters<typeof recordDeclinedInteractionRead>[1]["interactions"] })
|
||||
|
||||
@@ -1642,6 +1642,7 @@ const INSTANCE_ADMIN_OPERATIONS = new Set([
|
||||
"POST /api/companies",
|
||||
"POST /api/plugins/install",
|
||||
"POST /api/instance/database-backups",
|
||||
"GET /api/instance/server-metrics",
|
||||
"POST /api/admin/users/{userId}/promote-instance-admin",
|
||||
"POST /api/admin/users/{userId}/demote-instance-admin",
|
||||
"PUT /api/admin/users/{userId}/company-access",
|
||||
@@ -10391,6 +10392,17 @@ registry.registerPath({
|
||||
responses: { 201: r.ok(), 401: r.unauthorized, 403: r.forbidden },
|
||||
});
|
||||
|
||||
// ─── Instance server metrics ──────────────────────────────────────────────────
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/api/instance/server-metrics",
|
||||
tags: ["instance"],
|
||||
summary: "Get this server process's load metrics",
|
||||
description: "Instance admins only: agent credentials and company members receive 403. Returns numbers for the one server process that answers: CPU, event-loop utilization and delay, statements per second, run event lateness and agent API pre-handler p99, missed lease renewals and dedicated database connection use, over about the last minute (windowMs). It returns 404 unless the operator set PAPERCLIP_SERVER_METRICS=true.",
|
||||
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden, 404: r.notFound },
|
||||
});
|
||||
|
||||
// ─── LLM text endpoints ───────────────────────────────────────────────────────
|
||||
|
||||
registry.registerPath({
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
import type { RequestHandler, Response } from "express";
|
||||
|
||||
export const AUTHORIZATION_READ_MAX_AGE_MS = 2_000;
|
||||
|
||||
type ReadScope = { open: boolean; entries: Map<string, { value: Promise<unknown>; readAt: number }> };
|
||||
|
||||
const reads = new AsyncLocalStorage<ReadScope>();
|
||||
|
||||
function closeWhenResponseStarts(res: Response, close: () => void) {
|
||||
const { write, flushHeaders, writeHead } = res;
|
||||
res.write = function (this: Response, ...args: Parameters<Response["write"]>) {
|
||||
close();
|
||||
return write.apply(this, args);
|
||||
} as Response["write"];
|
||||
res.flushHeaders = function (this: Response) {
|
||||
close();
|
||||
return flushHeaders.call(this);
|
||||
};
|
||||
res.writeHead = function (this: Response, ...args: Parameters<Response["writeHead"]>) {
|
||||
close();
|
||||
return writeHead.apply(this, args);
|
||||
} as Response["writeHead"];
|
||||
res.once("finish", close);
|
||||
res.once("close", close);
|
||||
}
|
||||
|
||||
export const authorizationReadScope: RequestHandler = (req, res, next) => {
|
||||
if (req.method !== "GET" && req.method !== "HEAD") {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
const scope: ReadScope = { open: true, entries: new Map() };
|
||||
const actor = req.actor;
|
||||
if (actor?.type === "board" && actor.source === "session" && actor.userId && typeof actor.isInstanceAdmin === "boolean") {
|
||||
scope.entries.set(`admin:${actor.userId}`, { value: Promise.resolve(actor.isInstanceAdmin), readAt: Date.now() });
|
||||
}
|
||||
closeWhenResponseStarts(res, () => {
|
||||
scope.open = false;
|
||||
scope.entries.clear();
|
||||
});
|
||||
reads.run(scope, next);
|
||||
};
|
||||
|
||||
export function readOncePerRequest<T>(key: string, read: () => Promise<T>): Promise<T> {
|
||||
const scope = reads.getStore();
|
||||
if (!scope?.open) return read();
|
||||
const now = Date.now();
|
||||
const cached = scope.entries.get(key);
|
||||
if (cached && now - cached.readAt <= AUTHORIZATION_READ_MAX_AGE_MS) return cached.value as Promise<T>;
|
||||
const entry = { value: read() as Promise<unknown>, readAt: now };
|
||||
scope.entries.set(key, entry);
|
||||
entry.value.catch(() => {
|
||||
if (scope.entries.get(key) === entry) scope.entries.delete(key);
|
||||
});
|
||||
return entry.value as Promise<T>;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { readOncePerRequest } from "./authorization-read-scope.js";
|
||||
import { and, eq, inArray, isNull, or, sql, type SQL } from "drizzle-orm";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { agentInteractionDenial, type AgentInteractionDenial, type AgentInteractionOperation } from "./agent-interaction-policy.js";
|
||||
@@ -725,14 +726,21 @@ export async function canActorReadIssuePrivacy(db: Db | DbTransaction, actor: Au
|
||||
}
|
||||
|
||||
/** Filter every externally reachable task query with the same privacy predicate. */
|
||||
export async function readInstanceAdmin(db: Db | DbTransaction, userId: string): Promise<boolean> {
|
||||
return db
|
||||
.select({ id: instanceUserRoles.id })
|
||||
.from(instanceUserRoles)
|
||||
.where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin")))
|
||||
.limit(1)
|
||||
.then((rows) => rows.length > 0);
|
||||
}
|
||||
|
||||
export async function issueReadSqlCondition(db: Db | DbTransaction, actor: AuthorizationActor): Promise<SQL<boolean>> {
|
||||
if (actor.authorizingUserId) return issuePrivacyCondition(actor);
|
||||
if (issuePrivacyMode() !== "enforce") return sql<boolean>`true`;
|
||||
if (actor.source === "local_implicit" || actor.isInstanceAdmin) return sql<boolean>`true`;
|
||||
if (actor.type === "board" && !actor.ignoreInstanceAdmin && actor.source !== "cloud_tenant"
|
||||
&& await db.select({ id: instanceUserRoles.id }).from(instanceUserRoles)
|
||||
.where(and(eq(instanceUserRoles.userId, actor.userId ?? ""), eq(instanceUserRoles.role, "instance_admin")))
|
||||
.limit(1).then(rows => rows.length > 0)) return sql<boolean>`true`;
|
||||
&& await readOncePerRequest(`admin:${actor.userId ?? ""}`, () => readInstanceAdmin(db, actor.userId ?? ""))) return sql<boolean>`true`;
|
||||
return issuePrivacyCondition(actor);
|
||||
}
|
||||
|
||||
@@ -745,15 +753,7 @@ export async function projectReadSqlCondition(db: Db | DbTransaction, actor: Aut
|
||||
actor.type === "board"
|
||||
&& !actor.ignoreInstanceAdmin
|
||||
&& actor.source !== "cloud_tenant"
|
||||
&& Boolean(await db
|
||||
.select({ id: instanceUserRoles.id })
|
||||
.from(instanceUserRoles)
|
||||
.where(and(
|
||||
eq(instanceUserRoles.userId, actor.userId ?? ""),
|
||||
eq(instanceUserRoles.role, "instance_admin"),
|
||||
))
|
||||
.limit(1)
|
||||
.then((rows) => rows[0] ?? null))
|
||||
&& await readOncePerRequest(`admin:${actor.userId ?? ""}`, () => readInstanceAdmin(db, actor.userId ?? ""))
|
||||
) return sql<boolean>`true`;
|
||||
return projectPrivacyCondition(actor);
|
||||
}
|
||||
@@ -928,18 +928,7 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
|
||||
|
||||
async function isInstanceAdmin(userId: string | null | undefined): Promise<boolean> {
|
||||
if (!userId) return false;
|
||||
return batchRead(`admin:${userId}`, async () => {
|
||||
if (
|
||||
await db
|
||||
.select({ id: instanceUserRoles.id })
|
||||
.from(instanceUserRoles)
|
||||
.where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin")))
|
||||
.then((rows) => rows[0] ?? null)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
return batchRead(`admin:${userId}`, () => readOncePerRequest(`admin:${userId}`, () => readInstanceAdmin(db, userId)));
|
||||
}
|
||||
|
||||
async function getActiveMembership(
|
||||
@@ -947,7 +936,8 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
|
||||
principalType: PrincipalType,
|
||||
principalId: string,
|
||||
) {
|
||||
return batchRead(`membership:${companyId}:${principalType}:${principalId}`, async () => {
|
||||
const key = `membership:${companyId}:${principalType}:${principalId}`;
|
||||
return batchRead(key, () => readOncePerRequest(key, async () => {
|
||||
return db
|
||||
.select()
|
||||
.from(companyMemberships)
|
||||
@@ -960,7 +950,7 @@ function createAuthorizationService(db: Db | DbTransaction, readSnapshot?: ReadA
|
||||
),
|
||||
)
|
||||
.then((rows) => rows[0] ?? null);
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
async function loadResponsibleUserSnapshot(companyId: string, userId: string): Promise<ResponsibleUserSnapshot> {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { readGitHubResponseRun } from "./response-run-state.js";
|
||||
import { readGitHubResponseRuns, type GitHubResponseRunRead } from "./response-run-state.js";
|
||||
import { githubRunReplyState } from "../../chat-run-publications.js";
|
||||
import { and, asc, eq, gt, isNotNull, or, sql } from "drizzle-orm";
|
||||
import { chatActions, chatConversations, chatEndpointLeases, chatEndpointResources,
|
||||
@@ -57,16 +57,34 @@ export function registerGitHubAcknowledgementWork(
|
||||
actionId ? eq(chatActions.id, actionId) : undefined,
|
||||
)).orderBy(asc(chatActions.id)).limit(100);
|
||||
}
|
||||
async function entry(row: Awaited<ReturnType<typeof page>>[number]): Promise<Entry | null> {
|
||||
const { latestRun, ownsLatestRequest } = await readGitHubResponseRun(db, {
|
||||
companyId: row.companyId, endpointId: row.endpointId, agentId: row.agentId,
|
||||
issueId: row.issueId, deliveryId: row.deliveryId!, sourceMessageId: row.sourceMessageId,
|
||||
});
|
||||
// Execution success alone does not decide whether a final response exists.
|
||||
// Presentation/publication commits invalidate this parked request.
|
||||
if (row.issueId && ownsLatestRequest && latestRun?.nativePresentationPending &&
|
||||
await githubRunReplyState(db, { companyId: row.companyId, endpointId: row.endpointId,
|
||||
issueId: row.issueId, runId: latestRun.id }) === "none") return null;
|
||||
type Row = Awaited<ReturnType<typeof page>>[number];
|
||||
async function entry(row: Row, read: GitHubResponseRunRead): Promise<Entry | null> {
|
||||
// A request whose requester provenance changed stays due, so the
|
||||
// acknowledgement owner revokes it. It must not stop the rest of the page.
|
||||
if (!("forbidden" in read)) {
|
||||
const { latestRun, ownsLatestRequest } = read;
|
||||
// Execution success alone does not decide whether a final response exists.
|
||||
// Presentation/publication commits invalidate this parked request.
|
||||
if (row.issueId && ownsLatestRequest && latestRun?.nativePresentationPending &&
|
||||
await githubRunReplyState(db, { companyId: row.companyId, endpointId: row.endpointId,
|
||||
issueId: row.issueId, runId: latestRun.id }) === "none") return null;
|
||||
}
|
||||
return schedule(row);
|
||||
}
|
||||
/** The entries of a page, by position, from one batched run-state read. */
|
||||
async function entries(rows: Row[]) {
|
||||
const reads = await readGitHubResponseRuns(db, rows.map(row => ({ companyId: row.companyId, endpointId: row.endpointId,
|
||||
agentId: row.agentId, issueId: row.issueId, deliveryId: row.deliveryId!, sourceMessageId: row.sourceMessageId })));
|
||||
const values: Array<Entry | null> = [];
|
||||
for (const [index, row] of rows.entries()) values.push(await entry(row, reads[index]!));
|
||||
return values;
|
||||
}
|
||||
async function current(actionId: string) {
|
||||
const [row] = await page(undefined, undefined, actionId);
|
||||
return row ? (await entries([row]))[0] ?? null : null;
|
||||
}
|
||||
/** When the request is due, from its own row. */
|
||||
function schedule(row: Row): Entry | null {
|
||||
let dueAt = row.status === "failed" ? Date.parse(String(row.result?.retryAt)) : 0;
|
||||
if (!Number.isFinite(dueAt)) throw new Error("GitHub acknowledgement has an invalid retry deadline");
|
||||
const fast = row.fast;
|
||||
@@ -89,23 +107,24 @@ export function registerGitHubAcknowledgementWork(
|
||||
(!scope.endpointId || value.endpointId === scope.endpointId) && (!scope.repositoryId || value.repositoryId === scope.repositoryId) &&
|
||||
(!scope.number || value.number === scope.number)),
|
||||
load: async (scope?: Scope, signal?: AbortSignal) => {
|
||||
const entries: Entry[] = [];
|
||||
const loaded: Entry[] = [];
|
||||
let cursor: string | undefined;
|
||||
while (canRun() && !signal?.aborted) {
|
||||
const rows = await page(scope, cursor);
|
||||
for (const row of rows) { const value = await entry(row); if (value) entries.push(value); }
|
||||
if (rows.length < 100) return entries;
|
||||
for (const value of await entries(rows)) if (value) loaded.push(value);
|
||||
if (rows.length < 100) return loaded;
|
||||
cursor = rows[rows.length - 1].id;
|
||||
}
|
||||
throw signal?.reason ?? new Error("GitHub acknowledgement recovery stopped");
|
||||
},
|
||||
check: async (value: Entry, signal?: AbortSignal) => {
|
||||
const [row] = await page(undefined, undefined, value.id);
|
||||
const current = row ? await entry(row) : null;
|
||||
if (!current || current.dueAt > Date.now() || !canRun() || signal?.aborted) return current;
|
||||
await acknowledge(current.deliveryId, () => canRun() && !signal?.aborted);
|
||||
const due = await current(value.id);
|
||||
if (!due || due.dueAt > Date.now() || !canRun() || signal?.aborted) return due;
|
||||
await acknowledge(due.deliveryId, () => canRun() && !signal?.aborted);
|
||||
// A request that is still owed keeps its saved deadline. The next check
|
||||
// reads its run state again before it acknowledges.
|
||||
const [remaining] = await page(undefined, undefined, value.id);
|
||||
return remaining ? await entry(remaining) : null;
|
||||
return remaining ? schedule(remaining) : null;
|
||||
},
|
||||
}, canRun);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { githubRunReplyState } from "../../chat-run-publications.js";
|
||||
import { readGitHubResponseRun } from "./response-run-state.js";
|
||||
import { readGitHubResponseRun, type GitHubResponseRunRead } from "./response-run-state.js";
|
||||
export { responseRunColumns as githubResponseRunColumns } from "./response-run-state.js";
|
||||
|
||||
export type GitHubResponseExecutionInput = {
|
||||
@@ -14,8 +14,11 @@ export type GitHubResponseExecutionInput = {
|
||||
deliveryCreatedAt: Date;
|
||||
};
|
||||
|
||||
export async function githubResponseExecution(db: Db, input: GitHubResponseExecutionInput) {
|
||||
const { latestRun, ownsLatestRequest } = await readGitHubResponseRun(db, input);
|
||||
/** `read` is this request's state from a batched page read, if the caller has it. */
|
||||
export async function githubResponseExecution(db: Db, input: GitHubResponseExecutionInput, read?: GitHubResponseRunRead) {
|
||||
const state = read ?? await readGitHubResponseRun(db, input);
|
||||
if ("forbidden" in state) throw state.forbidden;
|
||||
const { latestRun, ownsLatestRequest } = state;
|
||||
const requestRunning = ownsLatestRequest && latestRun?.status === "running";
|
||||
const terminal = latestRun && ["succeeded", "failed", "interrupted", "timed_out", "cancelled"].includes(latestRun.status);
|
||||
const run = terminal && (ownsLatestRequest || input.issueStatus === "blocked") ? latestRun : null;
|
||||
|
||||
@@ -4,7 +4,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { chatMessageLinks, createDb, heartbeatRuns, type Db } from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
|
||||
import { chatRunSourceMessageId } from "../run-origin.js";
|
||||
import { readGitHubResponseRun, responseRunColumns } from "./response-run-state.js";
|
||||
import { readGitHubResponseRun, readGitHubResponseRuns, responseRunColumns } from "./response-run-state.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
const suite = support.supported ? describe : describe.skip;
|
||||
@@ -195,6 +195,18 @@ suite("GitHub response run state", () => {
|
||||
.toEqual(new Set(["native", "legacy"]));
|
||||
}, 120_000);
|
||||
|
||||
it("reads a page of requests in one latest-run statement with the state each single read returns", async () => {
|
||||
const all = inputs();
|
||||
const single = [];
|
||||
for (const input of all) single.push(await readGitHubResponseRun(db, input));
|
||||
const statements: string[] = [], prior = db.$client.options.debug;
|
||||
db.$client.options.debug = (_connection, query) => { statements.push(query); };
|
||||
let batch;
|
||||
try { batch = await readGitHubResponseRuns(db, all); } finally { db.$client.options.debug = prior; }
|
||||
expect(batch).toEqual(single);
|
||||
expect(statements.filter(query => /from "heartbeat_runs"|join "heartbeat_runs"/.test(query))).toHaveLength(1);
|
||||
}, 120_000);
|
||||
|
||||
it("reads a few runs of the issue, not the agent's whole run history", async () => {
|
||||
const tenant = tenants[0]!;
|
||||
const request = tenant.requests[0]!;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { and, eq, sql, type SQL } from "drizzle-orm";
|
||||
import { chatMessageLinks, heartbeatRuns, type Db } from "@paperclipai/db";
|
||||
import { chatRunSourceMessageId } from "../run-origin.js";
|
||||
import type { HttpError } from "../../../errors.js";
|
||||
import { chatRunSourceMessageId, chatRunSourceMessageIds } from "../run-origin.js";
|
||||
|
||||
export const responseRunColumns = {
|
||||
id: heartbeatRuns.id,
|
||||
@@ -47,35 +48,97 @@ export const responseRunColumns = {
|
||||
'wakeCommentIds', ${heartbeatRuns.contextSnapshot}->'wakeCommentIds'
|
||||
)`,
|
||||
};
|
||||
/** Shared request ownership and presentation state for delivery and recovery. */
|
||||
export async function readGitHubResponseRun(db: Db, input: {
|
||||
|
||||
export type GitHubResponseRunInput = {
|
||||
companyId: string; endpointId: string; agentId: string; issueId: string | null;
|
||||
deliveryId: string; sourceMessageId: string | null;
|
||||
}) {
|
||||
const { issueId } = input;
|
||||
if (!issueId) return { latestRun: undefined, ownsLatestRequest: false };
|
||||
const latestRunId = sql`(select latest.id from (
|
||||
(select r.id, r.created_at from ${heartbeatRuns} r
|
||||
where r.company_id = ${input.companyId} and r.native_issue_id = ${issueId} and r.agent_id = ${input.agentId}
|
||||
order by r.created_at desc, r.id desc limit 1)
|
||||
union all
|
||||
(select r.id, r.created_at from ${heartbeatRuns} r
|
||||
where r.company_id = ${input.companyId} and r.native_issue_id is null
|
||||
and r.context_snapshot->>'issueId' = ${issueId} and r.agent_id = ${input.agentId}
|
||||
order by r.created_at desc, r.id desc limit 1)
|
||||
) latest order by latest.created_at desc, latest.id desc limit 1)`;
|
||||
const wokeForRequest = sql<boolean>`exists (select 1 from ${chatMessageLinks} l
|
||||
where l.company_id = ${input.companyId} and l.endpoint_id = ${input.endpointId}
|
||||
and l.delivery_id = ${input.deliveryId} and l.direction = 'inbound'
|
||||
and (l.comment_id::text = ${heartbeatRuns.contextSnapshot}->>'wakeCommentId'
|
||||
or coalesce(${heartbeatRuns.contextSnapshot}->'wakeCommentIds', '[]'::jsonb) ? l.comment_id::text))`;
|
||||
const [row] = await db.select({ ...responseRunColumns, wokeForRequest }).from(heartbeatRuns)
|
||||
.where(and(eq(heartbeatRuns.companyId, input.companyId), sql`${heartbeatRuns.id} = ${latestRunId}`));
|
||||
};
|
||||
type RunRow = Omit<Awaited<ReturnType<typeof readRunRows>>[number], "ordinal">;
|
||||
export type GitHubResponseRunState = { latestRun: Omit<RunRow, "wokeForRequest"> | undefined; ownsLatestRequest: boolean };
|
||||
/** The state of one request of a batch, or the 403 that its single read throws. */
|
||||
export type GitHubResponseRunRead = GitHubResponseRunState | { forbidden: HttpError };
|
||||
|
||||
/** A value of the run reads: a literal of one request in a single read, or a
|
||||
* column of the request row in a batch read. */
|
||||
type Value = string | SQL;
|
||||
type Of = Record<"companyId" | "endpointId" | "agentId" | "issueId" | "deliveryId", Value>;
|
||||
|
||||
/** The assigned agent's latest run bound to the issue, where a run's issue is
|
||||
* coalesce(native_issue_id, context_snapshot->>'issueId'). The two precedence
|
||||
* branches are disjoint and each uses an issue index. */
|
||||
const latestRunId = (of: Of) => sql`(select latest.id from (
|
||||
(select r.id, r.created_at from ${heartbeatRuns} r
|
||||
where r.company_id = ${of.companyId}::uuid and r.native_issue_id = ${of.issueId}::uuid and r.agent_id = ${of.agentId}::uuid
|
||||
order by r.created_at desc, r.id desc limit 1)
|
||||
union all
|
||||
(select r.id, r.created_at from ${heartbeatRuns} r
|
||||
where r.company_id = ${of.companyId}::uuid and r.native_issue_id is null
|
||||
and r.context_snapshot->>'issueId' = ${of.issueId}::text and r.agent_id = ${of.agentId}::uuid
|
||||
order by r.created_at desc, r.id desc limit 1)
|
||||
) latest order by latest.created_at desc, latest.id desc limit 1)`;
|
||||
/** Whether the run woke for one of the request's inbound comments. */
|
||||
const wokeForRequest = (of: Of) => sql<boolean>`exists (select 1 from ${chatMessageLinks} l
|
||||
where l.company_id = ${of.companyId}::uuid and l.endpoint_id = ${of.endpointId}::uuid
|
||||
and l.delivery_id = ${of.deliveryId}::uuid and l.direction = 'inbound'
|
||||
and (l.comment_id::text = ${heartbeatRuns.contextSnapshot}->>'wakeCommentId'
|
||||
or coalesce(${heartbeatRuns.contextSnapshot}->'wakeCommentIds', '[]'::jsonb) ? l.comment_id::text))`;
|
||||
|
||||
const request = sql.identifier("github_response_request");
|
||||
const column = (name: string) => sql`${request}.${sql.identifier(name)}`;
|
||||
const columns: Array<[keyof Of, string]> = [["companyId", "company_id"], ["endpointId", "endpoint_id"],
|
||||
["agentId", "agent_id"], ["issueId", "issue_id"], ["deliveryId", "delivery_id"]];
|
||||
|
||||
/** The latest run of each request, in one statement. For each request row the
|
||||
* lateral subquery is the single read with the request columns in place of
|
||||
* the literals. */
|
||||
async function readRunRows(db: Db, inputs: Array<GitHubResponseRunInput & { issueId: string }>) {
|
||||
const of = Object.fromEntries(columns.map(([key, name]) => [key, column(name)])) as Of;
|
||||
return db.select({ ordinal: sql<number>`${column("ordinal")}`.mapWith(Number), ...responseRunColumns,
|
||||
wokeForRequest: wokeForRequest(of) })
|
||||
.from(sql`unnest(${sql.join(columns.map(([key]) => sql`${sql.param(inputs.map(input => input[key]))}::uuid[]`), sql`, `)})
|
||||
with ordinality as ${request}(${sql.join([...columns.map(([, name]) => sql.identifier(name)), sql.identifier("ordinal")], sql`, `)})
|
||||
cross join lateral (select ${latestRunId(of)} as id) latest_request_run`)
|
||||
.innerJoin(heartbeatRuns, and(sql`${heartbeatRuns.id} = latest_request_run.id`,
|
||||
sql`${heartbeatRuns.companyId} = ${column("company_id")}`));
|
||||
}
|
||||
|
||||
function ownership(input: GitHubResponseRunInput, row: RunRow | undefined, originMessageId: string | null): GitHubResponseRunState {
|
||||
if (!row) return { latestRun: undefined, ownsLatestRequest: false };
|
||||
const { wokeForRequest: requestRunIsLatest, ...latestRun } = row;
|
||||
const originMessageId = latestRun.activeIdentityContextId ? await chatRunSourceMessageId(db, latestRun,
|
||||
{ allowLegacyWakeComment: true, provider: "github" }) : null;
|
||||
const ownsLatestRequest = requestRunIsLatest ||
|
||||
(!!input.sourceMessageId && originMessageId === input.sourceMessageId);
|
||||
return { latestRun, ownsLatestRequest };
|
||||
}
|
||||
|
||||
/** Shared request ownership and presentation state for delivery and recovery. */
|
||||
export async function readGitHubResponseRun(db: Db, input: GitHubResponseRunInput): Promise<GitHubResponseRunState> {
|
||||
const { issueId } = input;
|
||||
if (!issueId) return { latestRun: undefined, ownsLatestRequest: false };
|
||||
const of = { ...input, issueId };
|
||||
const [row] = await db.select({ ...responseRunColumns, wokeForRequest: wokeForRequest(of) }).from(heartbeatRuns)
|
||||
.where(and(eq(heartbeatRuns.companyId, input.companyId), sql`${heartbeatRuns.id} = ${latestRunId(of)}`));
|
||||
const originMessageId = row?.activeIdentityContextId ? await chatRunSourceMessageId(db, row,
|
||||
{ allowLegacyWakeComment: true, provider: "github" }) : null;
|
||||
return ownership(input, row, originMessageId);
|
||||
}
|
||||
|
||||
/** `readGitHubResponseRun` for a page of requests: one latest-run read for the
|
||||
* whole page, then one batched provenance check of its distinct runs, which
|
||||
* reuses the single check's reads. Each request gets, by position, the state a
|
||||
* separate call returns or the 403 that call throws. */
|
||||
export async function readGitHubResponseRuns(db: Db, inputs: GitHubResponseRunInput[]): Promise<GitHubResponseRunRead[]> {
|
||||
const bound = inputs.flatMap((input, index) => input.issueId ? [{ index, input: { ...input, issueId: input.issueId } }] : []);
|
||||
const found = new Map<number, RunRow>();
|
||||
if (bound.length) {
|
||||
for (const { ordinal, ...row } of await readRunRows(db, bound.map(entry => entry.input))) found.set(bound[ordinal - 1]!.index, row);
|
||||
}
|
||||
const runs = [...new Map([...found.values()].filter(row => row.activeIdentityContextId).map(row => [row.id, row])).values()];
|
||||
const checked = await chatRunSourceMessageIds(db, runs, { allowLegacyWakeComment: true, provider: "github" });
|
||||
const origins = new Map(runs.map((run, index) => [run.id, checked[index]!]));
|
||||
return inputs.map((input, index) => {
|
||||
const row = found.get(index);
|
||||
const origin = row ? origins.get(row.id) : undefined;
|
||||
if (origin && "forbidden" in origin) return { forbidden: origin.forbidden };
|
||||
return ownership(input, row, origin?.messageId ?? null);
|
||||
});
|
||||
}
|
||||
@@ -68,7 +68,12 @@ suite("GitHub response sweep scopes", () => {
|
||||
builder.from = ((...args: Parameters<typeof from>) => {
|
||||
const selection = from(...args), execute = selection.execute.bind(selection);
|
||||
selection.execute = (async () => {
|
||||
if (selection.toSQL().sql.includes(`'wakeCommentIds', '[]'::jsonb) ?`)) reads += 1;
|
||||
// Count requests whose run state is read. A batched read names its
|
||||
// requests in arrays, so count the requests rather than statements.
|
||||
const query = selection.toSQL();
|
||||
if (query.sql.includes(`'wakeCommentIds', '[]'::jsonb) ?`)) {
|
||||
reads += Array.isArray(query.params[0]) ? query.params[0].length : 1;
|
||||
}
|
||||
return execute();
|
||||
}) as typeof selection.execute;
|
||||
return selection;
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, chatActions, companies, createDb, heartbeatRuns, issues, runIdentityContexts, type Db } from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
|
||||
import { createDeliveryWorkCoordinator } from "../../delivery-work-coordinator.js";
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "../../delivery-work-notifications.js";
|
||||
import { idleWorkSnapshot } from "../../task-admission.js";
|
||||
import { registerGitHubAcknowledgementWork } from "./acknowledgement-work.js";
|
||||
import { registerGitHubTerminalResponseWork } from "./terminal-response-work.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
|
||||
// Staging (2026-11-15) held 1,557 processed, non-final response comments whose
|
||||
// result codes were null (89%), acknowledgement_unconfirmed (10%) and
|
||||
// acknowledgement_superseded (1%). Each task's latest run had ended and had
|
||||
// been started by a later GitHub request, so it did not own these requests.
|
||||
const ISSUES = 30;
|
||||
const STALE_PER_ISSUE = 4;
|
||||
const STALE = ISSUES * STALE_PER_ISSUE;
|
||||
const code = (index: number) => index % 50 === 1 ? "acknowledgement_superseded"
|
||||
: index % 10 === 0 ? "acknowledgement_unconfirmed" : null;
|
||||
|
||||
describe.skipIf(!support.supported)("GitHub terminal response sweep backlog", () => {
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: Db;
|
||||
let coordinator: ReturnType<typeof createDeliveryWorkCoordinator> | undefined;
|
||||
const errors: unknown[] = [];
|
||||
const acknowledged: string[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
temporary = await startEmbeddedPostgresTestDatabase("github-terminal-response-work-");
|
||||
db = createDb(temporary.connectionString);
|
||||
}, 60_000);
|
||||
afterEach(async () => {
|
||||
await coordinator?.stop(); coordinator = undefined; acknowledged.length = 0;
|
||||
vi.useRealTimers();
|
||||
expect(errors.splice(0)).toEqual([]);
|
||||
});
|
||||
afterAll(async () => { await db?.$client.end({ timeout: 1 }); await temporary?.cleanup(); });
|
||||
|
||||
type Request = { issueId: string; deliveryId: string; actionId: string; commentId: string };
|
||||
/** `waiting`: processed, non-final responses as on staging. `received`: every
|
||||
* request still owes its first acknowledgement. */
|
||||
async function seed(shape: "waiting" | "received" = "waiting") {
|
||||
const client = db.$client;
|
||||
const companyId = randomUUID(), agentId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "GitHub backlog", issuePrefix: `G${companyId.slice(0, 7)}` });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer" });
|
||||
const [{ application }] = await client.unsafe(`insert into tool_applications (company_id, application_key, name, type)
|
||||
values ($1, 'github', 'GitHub', 'chat') returning id as application`, [companyId]);
|
||||
const [{ connection }] = await client.unsafe(`insert into tool_connections (company_id, application_id, name, uid, transport, connection_purpose)
|
||||
values ($1, $2, 'GitHub', $3, 'chat_sdk', 'channel') returning id as connection`, [companyId, application, `github-${companyId}`]);
|
||||
const [{ endpoint }] = await client.unsafe(`insert into chat_endpoints (company_id, connection_id, provider, public_id, assigned_agent_id, status)
|
||||
values ($1, $2, 'github', $3, $4, 'active') returning id as endpoint`, [companyId, connection, `backlog-${companyId}`, agentId]);
|
||||
const stale: Request[] = [];
|
||||
const runs: Array<{ issueId: string; runId: string }> = [];
|
||||
const base = Date.UTC(2026, 9, 28);
|
||||
for (let issueNumber = 1; issueNumber <= ISSUES; issueNumber++) {
|
||||
const [{ issue }] = await client.unsafe(`insert into issues (company_id, title, status, assignee_agent_id)
|
||||
values ($1, $2, 'in_progress', $3) returning id as issue`, [companyId, `Pull ${issueNumber}`, agentId]);
|
||||
const [{ conversation }] = await client.unsafe(`insert into chat_conversations (company_id, endpoint_id, issue_id,
|
||||
external_conversation_id, external_label, external_thread_id)
|
||||
values ($1, $2, $3, $4, $4, $4) returning id as conversation`, [companyId, endpoint, issue, `github:paperclipai/paperclip:${issueNumber}`]);
|
||||
const requests: Request[] = [];
|
||||
for (let request = 0; request <= STALE_PER_ISSUE; request++) {
|
||||
const [{ delivery }] = await client.unsafe(`insert into chat_deliveries (company_id, endpoint_id, provider_event_id,
|
||||
deduplication_key, event_kind, normalized_event, conversation_id, state)
|
||||
values ($1, $2, $3, $3, 'message', '{}', $4, 'processed') returning id as delivery`,
|
||||
[companyId, endpoint, `event-${companyId}-${issueNumber}-${request}`, conversation]);
|
||||
const [{ comment }] = await client.unsafe(`insert into issue_comments (company_id, issue_id, body)
|
||||
values ($1, $2, 'Please review') returning id as comment`, [companyId, issue]);
|
||||
await client.unsafe(`insert into chat_message_links (company_id, endpoint_id, conversation_id, delivery_id, comment_id,
|
||||
provider_message_id, direction) values ($1, $2, $3, $4, $5, $6, 'inbound')`,
|
||||
[companyId, endpoint, conversation, delivery, comment, `in-${companyId}-${issueNumber}-${request}`]);
|
||||
const index = stale.length;
|
||||
const latest = request === STALE_PER_ISSUE;
|
||||
const [action] = await db.insert(chatActions).values({ companyId, endpointId: endpoint, conversationId: conversation,
|
||||
deliveryId: delivery, kind: "github_response_comment", providerActionId: `github_response:${delivery}`,
|
||||
payload: { agentId }, status: shape === "received" ? "received" : "processed",
|
||||
result: shape === "received" ? null : { id: String(1_000 + index),
|
||||
url: `https://github.com/paperclipai/paperclip/pull/${issueNumber}#c${index}`,
|
||||
final: latest, versionAt: new Date(base).toISOString(), ...(latest ? {} : { code: code(index) }) },
|
||||
updatedAt: new Date(base + index * 60_000) }).returning();
|
||||
requests.push({ issueId: issue, deliveryId: delivery, actionId: action!.id, commentId: comment });
|
||||
}
|
||||
stale.push(...(shape === "received" ? requests : requests.slice(0, STALE_PER_ISSUE)));
|
||||
// The latest run answered the newest request, through its identity context.
|
||||
const runId = randomUUID(), contextId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: issue, issueId: issue,
|
||||
scopeKind: "issue", status: "succeeded", responsibleUserId: "requester", activeIdentityContextId: contextId,
|
||||
contextSnapshot: { issueId: issue }, createdAt: new Date(base + issueNumber * 3_600_000) });
|
||||
await db.insert(runIdentityContexts).values({ id: contextId, companyId, runId, revision: 1, responsibleUserId: "requester",
|
||||
messageId: requests[STALE_PER_ISSUE]!.commentId, cause: "chat_request", correlationId: runId, status: "accepted" });
|
||||
runs.push({ issueId: issue, runId });
|
||||
}
|
||||
await db.execute(sql`analyze`);
|
||||
return { companyId, agentId, endpointId: endpoint as string, stale, runs };
|
||||
}
|
||||
|
||||
async function start(register: typeof registerGitHubTerminalResponseWork = registerGitHubTerminalResponseWork) {
|
||||
coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true,
|
||||
onError: error => errors.push(error) });
|
||||
const worker = register(db, coordinator, async deliveryId => {
|
||||
acknowledged.push(deliveryId);
|
||||
// Stand in for the real acknowledgement, which records a final response.
|
||||
await db.update(chatActions).set({ status: "processed", updatedAt: new Date(),
|
||||
result: sql`coalesce(${chatActions.result}, '{}'::jsonb) || '{"final": true}'::jsonb` })
|
||||
.where(and(eq(chatActions.deliveryId, deliveryId), eq(chatActions.kind, "github_response_comment")));
|
||||
}, () => true);
|
||||
await worker.ready;
|
||||
}
|
||||
async function advance(ms: number) {
|
||||
const until = Date.now() + ms;
|
||||
while (Date.now() < until) {
|
||||
await vi.advanceTimersByTimeAsync(Math.min(1_000, until - Date.now())); await delay(1);
|
||||
while (idleWorkSnapshot().active > 0) await delay(5);
|
||||
}
|
||||
}
|
||||
/** Company-wide hints, as run lifecycle changes elsewhere in the company send them. */
|
||||
async function companyHint(companyId: string) {
|
||||
await db.transaction(async tx => {
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.chatGitHubTerminalResponses, JSON.stringify({ companyId }));
|
||||
});
|
||||
}
|
||||
async function observe(work: () => Promise<unknown>) {
|
||||
const statements: string[] = [], prior = db.$client.options.debug;
|
||||
db.$client.options.debug = (_connection, query) => { statements.push(query); };
|
||||
try { await work(); } finally { db.$client.options.debug = prior; }
|
||||
const sweep = statements.filter(query => /"chat_actions"|heartbeat_runs|run_identity_contexts|chat_message_links/.test(query));
|
||||
return {
|
||||
statements: sweep.length,
|
||||
provenance: sweep.filter(query => /from "run_identity_contexts"/.test(query)).length,
|
||||
};
|
||||
}
|
||||
const finals = async (actionIds: string[]) => (await db.select({ result: chatActions.result }).from(chatActions)
|
||||
.where(inArray(chatActions.id, actionIds))).filter(row => row.result?.final === true).length;
|
||||
|
||||
it("stops re-reading processed, non-final responses that cannot progress on every company rebuild", async () => {
|
||||
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
|
||||
const f = await seed();
|
||||
const first = await observe(async () => { await start(); await advance(5_000); });
|
||||
expect(acknowledged).toEqual([]);
|
||||
const rebuilds = await observe(async () => {
|
||||
for (let pass = 0; pass < 4; pass++) { await companyHint(f.companyId); await advance(31_000); }
|
||||
});
|
||||
console.info(`terminal response sweep: first pass ${first.statements} statements (${first.provenance} run identity reads); `
|
||||
+ `4 company rebuilds ${rebuilds.statements} statements (${rebuilds.provenance} run identity reads) for ${STALE} rows`);
|
||||
// Nothing these rows wait for changed, so a rebuild reads none of them.
|
||||
expect(rebuilds.provenance).toBe(0);
|
||||
expect(rebuilds.statements).toBeLessThanOrEqual(4 * 2);
|
||||
expect(acknowledged).toEqual([]);
|
||||
// No GitHub comment changed and no row was finalized.
|
||||
expect(await finals(f.stale.map(request => request.actionId))).toBe(0);
|
||||
}, 300_000);
|
||||
|
||||
it("reads a page of waiting responses in a constant number of statements", async () => {
|
||||
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
|
||||
await seed();
|
||||
const first = await observe(async () => { await start(); await advance(5_000); });
|
||||
console.info(`terminal response sweep, first pass: ${first.statements} statements `
|
||||
+ `(${first.provenance} run identity reads) for ${STALE} rows in 2 pages`);
|
||||
expect(acknowledged).toEqual([]);
|
||||
// Per page: the page, its latest runs, the batched context and link reads, and the wait keys.
|
||||
expect(first.provenance).toBeLessThanOrEqual(2);
|
||||
expect(first.statements).toBeLessThanOrEqual(2 * 5);
|
||||
}, 300_000);
|
||||
|
||||
it("acknowledges every owed request of a page when one run's requester provenance changed", async () => {
|
||||
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
|
||||
const f = await seed("received");
|
||||
// One task's latest run lost its accepted identity context, so reading its
|
||||
// requester provenance is forbidden. Only that task's requests are affected.
|
||||
await db.update(runIdentityContexts).set({ status: "revoked" }).where(eq(runIdentityContexts.runId, f.runs[3]!.runId));
|
||||
const first = await observe(async () => { await start(registerGitHubAcknowledgementWork); await advance(30_000); });
|
||||
console.info(`acknowledgement sweep: ${first.statements} statements (${first.provenance} run identity reads) `
|
||||
+ `for ${f.stale.length} owed requests`);
|
||||
expect(new Set(acknowledged)).toEqual(new Set(f.stale.map(request => request.deliveryId)));
|
||||
expect(acknowledged).toHaveLength(f.stale.length);
|
||||
}, 300_000);
|
||||
|
||||
it("still settles a waiting response once a run that owns it ends", async () => {
|
||||
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
|
||||
const f = await seed();
|
||||
await start(); await advance(5_000);
|
||||
const target = f.stale[5]!;
|
||||
await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, nativeIssueId: target.issueId,
|
||||
issueId: target.issueId, scopeKind: "issue", status: "failed",
|
||||
contextSnapshot: { issueId: target.issueId, wakeCommentId: target.commentId }, createdAt: new Date() });
|
||||
await companyHint(f.companyId);
|
||||
await advance(31_000);
|
||||
expect(acknowledged).toEqual([target.deliveryId]);
|
||||
const rebuilds = await observe(async () => { await companyHint(f.companyId); await advance(31_000); });
|
||||
expect(rebuilds.provenance).toBe(0);
|
||||
expect(acknowledged).toEqual([target.deliveryId]);
|
||||
}, 300_000);
|
||||
|
||||
it("still settles a response after a restart lost the hint of the reply publication it waited for", async () => {
|
||||
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
|
||||
const f = await seed();
|
||||
const target = f.stale[9]!;
|
||||
const [response] = await db.select().from(chatActions).where(eq(chatActions.id, target.actionId));
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, nativeIssueId: target.issueId,
|
||||
issueId: target.issueId, scopeKind: "issue", status: "failed",
|
||||
contextSnapshot: { issueId: target.issueId, wakeCommentId: target.commentId }, createdAt: new Date() });
|
||||
// The owning run's formal review is still being published.
|
||||
const [publication] = await db.insert(chatActions).values({ companyId: f.companyId, endpointId: f.endpointId,
|
||||
conversationId: response!.conversationId, deliveryId: target.deliveryId, kind: "github_review_publication",
|
||||
providerActionId: `github_review:${runId}`, status: "processing",
|
||||
payload: { operation: "formal_review", session: { companyId: f.companyId, issueId: target.issueId, runId, agentId: f.agentId } } })
|
||||
.returning();
|
||||
await start(); await advance(5_000);
|
||||
expect(acknowledged).toEqual([]);
|
||||
// The publication commits, and the server stops before its lease release
|
||||
// sends the targeted hint. The next start runs only a broad load.
|
||||
await db.update(chatActions).set({ status: "processed", updatedAt: new Date(),
|
||||
result: { id: "77", url: "https://github.com/paperclipai/paperclip/pull/1#pullrequestreview-77" } })
|
||||
.where(eq(chatActions.id, publication!.id));
|
||||
await coordinator!.stop(); coordinator = undefined;
|
||||
await start(); await advance(5_000);
|
||||
expect(acknowledged).toEqual([target.deliveryId]);
|
||||
}, 300_000);
|
||||
|
||||
it("still pauses waiting responses once their task is blocked", async () => {
|
||||
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
|
||||
const f = await seed();
|
||||
await start(); await advance(5_000);
|
||||
const blocked = f.runs[2]!.issueId;
|
||||
await db.update(issues).set({ status: "blocked", updatedAt: new Date() }).where(eq(issues.id, blocked));
|
||||
await companyHint(f.companyId);
|
||||
await advance(31_000);
|
||||
expect(new Set(acknowledged)).toEqual(new Set(f.stale.filter(request => request.issueId === blocked).map(request => request.deliveryId)));
|
||||
}, 300_000);
|
||||
});
|
||||
@@ -5,11 +5,16 @@ import type { createDeliveryWorkCoordinator } from "../../delivery-work-coordina
|
||||
import { DELIVERY_QUEUES } from "../../delivery-work-notifications.js";
|
||||
import { registerScopedDeadlineWork } from "../../scoped-deadline-work.js";
|
||||
import { githubResponseExecution } from "./response-execution.js";
|
||||
import { readGitHubResponseRuns, type GitHubResponseRunRead } from "./response-run-state.js";
|
||||
import { githubResponseReconstructionIntervalMs, type GitHubResponseSweepScope as Scope } from "./response-sweep-scope.js";
|
||||
import { HttpError } from "../../../errors.js";
|
||||
type Entry = { id: string; companyId: string; endpointId: string; deliveryId: string;
|
||||
issueId: string; conversationId: string; repositoryId: string | null; number: number | null; dueAt: number };
|
||||
|
||||
/** A load of a whole company (or every company) rather than a targeted hint. */
|
||||
const broad = (scope?: Scope) => !scope || (!scope.issueId && !scope.deliveryId && !scope.conversationId &&
|
||||
!scope.endpointId && !scope.repositoryId && !scope.number);
|
||||
|
||||
export function registerGitHubTerminalResponseWork(
|
||||
db: Db,
|
||||
coordinator: ReturnType<typeof createDeliveryWorkCoordinator>,
|
||||
@@ -19,28 +24,37 @@ export function registerGitHubTerminalResponseWork(
|
||||
const repositoryId = sql<string | null>`${chatEndpointResources.metadata}->>'providerRepositoryId'`;
|
||||
const number = sql<string | null>`substring(${chatConversations.externalThreadId}
|
||||
from '^github:[^:]+:(?:issue:)?([1-9][0-9]*)(?::rc:[1-9][0-9]*)?$')`;
|
||||
// Status of the assigned agent's latest run bound to the issue, where a run's
|
||||
// issue is coalesce(native_issue_id, context_snapshot->>'issueId'). The two
|
||||
// The assigned agent's latest run bound to the issue, where a run's issue is
|
||||
// coalesce(native_issue_id, context_snapshot->>'issueId'). The two
|
||||
// precedence branches are disjoint and each uses an issue index, so a
|
||||
// candidate does not walk (and detoast) the agent's whole run history.
|
||||
const latestIssueRunStatus = sql<string | null>`select latest.status from (
|
||||
(select r.status, r.created_at, r.id from ${heartbeatRuns} r
|
||||
const latestIssueRun = db.select({
|
||||
status: sql<string>`latest.status`.as("latest_run_status"),
|
||||
version: sql<string>`latest.id::text || ':' || latest.status || ':' || extract(epoch from latest.updated_at)::text`
|
||||
.as("latest_run_version"),
|
||||
}).from(sql`((select r.status, r.created_at, r.id, r.updated_at from ${heartbeatRuns} r
|
||||
where r.company_id = ${chatActions.companyId} and r.native_issue_id = ${chatConversations.issueId}
|
||||
and r.agent_id = ${chatEndpoints.assignedAgentId}
|
||||
order by r.created_at desc, r.id desc limit 1)
|
||||
union all
|
||||
(select r.status, r.created_at, r.id from ${heartbeatRuns} r
|
||||
(select r.status, r.created_at, r.id, r.updated_at from ${heartbeatRuns} r
|
||||
where r.company_id = ${chatActions.companyId} and r.native_issue_id is null
|
||||
and r.context_snapshot->>'issueId' = ${chatConversations.issueId}::text
|
||||
and r.agent_id = ${chatEndpoints.assignedAgentId}
|
||||
order by r.created_at desc, r.id desc limit 1)
|
||||
) latest order by latest.created_at desc, latest.id desc limit 1`;
|
||||
order by r.created_at desc, r.id desc limit 1)) latest`)
|
||||
.orderBy(sql`latest.created_at desc, latest.id desc`).limit(1).as("latest_issue_run");
|
||||
// A request whose latest run does not own it (or whose pause is already
|
||||
// shown) can progress only once the task's latest run, the task's status or
|
||||
// the request's own row changes. Such a request records this key, and a broad
|
||||
// rebuild skips it until one of them changes. A targeted load still reads it.
|
||||
const actionVersion = sql<string>`extract(epoch from ${chatActions.updatedAt})::text`;
|
||||
const waitKey = sql<string>`coalesce(${latestIssueRun.version}, 'none') || '|' || ${issues.status} || '|' || ${actionVersion}`;
|
||||
async function page(scope?: Scope, cursor?: string, actionId?: string) {
|
||||
return db.select({
|
||||
id: chatActions.id, companyId: chatActions.companyId, endpointId: chatActions.endpointId,
|
||||
deliveryId: chatActions.deliveryId, conversationId: chatConversations.id, issueId: issues.id,
|
||||
agentId: chatEndpoints.assignedAgentId, issueStatus: issues.status,
|
||||
deliveryCreatedAt: chatDeliveries.createdAt, repositoryId, number, result: chatActions.result,
|
||||
deliveryCreatedAt: chatDeliveries.createdAt, repositoryId, number, result: chatActions.result, actionVersion, waitKey,
|
||||
sourceMessageId: sql<string | null>`(select l.comment_id from ${chatMessageLinks} l
|
||||
where l.company_id = ${chatActions.companyId} and l.endpoint_id = ${chatActions.endpointId}
|
||||
and l.delivery_id = ${chatActions.deliveryId} and l.direction = 'inbound' limit 1)`,
|
||||
@@ -53,10 +67,12 @@ export function registerGitHubTerminalResponseWork(
|
||||
.innerJoin(chatDeliveries, and(eq(chatDeliveries.id, chatActions.deliveryId), eq(chatDeliveries.companyId, chatActions.companyId)))
|
||||
.innerJoin(issues, and(eq(issues.id, chatConversations.issueId), eq(issues.companyId, chatActions.companyId)))
|
||||
.leftJoin(chatEndpointResources, and(eq(chatEndpointResources.id, chatConversations.resourceId), eq(chatEndpointResources.companyId, chatActions.companyId)))
|
||||
.leftJoinLateral(latestIssueRun, sql`true`)
|
||||
.where(and(eq(chatActions.kind, "github_response_comment"), eq(chatActions.status, "processed"),
|
||||
isNotNull(chatActions.deliveryId), isNotNull(chatEndpoints.assignedAgentId),
|
||||
sql`coalesce(${chatActions.result}->>'final', 'false') <> 'true'`,
|
||||
sql`(${issues.status} = 'blocked' or (${latestIssueRunStatus}) in ('succeeded', 'failed', 'interrupted', 'timed_out', 'cancelled'))`,
|
||||
sql`(${issues.status} = 'blocked' or ${latestIssueRun.status} in ('succeeded', 'failed', 'interrupted', 'timed_out', 'cancelled'))`,
|
||||
broad(scope) && !actionId ? sql`${chatActions.result}->>'terminalWaitKey' is distinct from ${waitKey}` : undefined,
|
||||
scope ? eq(chatActions.companyId, scope.companyId) : undefined,
|
||||
scope?.issueId ? eq(issues.id, scope.issueId) : undefined,
|
||||
scope?.conversationId ? eq(chatActions.conversationId, scope.conversationId) : undefined,
|
||||
@@ -67,20 +83,61 @@ export function registerGitHubTerminalResponseWork(
|
||||
cursor ? gt(chatActions.id, cursor) : undefined, actionId ? eq(chatActions.id, actionId) : undefined,
|
||||
)).orderBy(asc(chatActions.id)).limit(100);
|
||||
}
|
||||
async function entry(row: Awaited<ReturnType<typeof page>>[number]): Promise<Entry | null> {
|
||||
const pending: Entry = { id: row.id, companyId: row.companyId, endpointId: row.endpointId, deliveryId: row.deliveryId!,
|
||||
issueId: row.issueId, conversationId: row.conversationId, repositoryId: row.repositoryId,
|
||||
number: row.number ? Number(row.number) : null, dueAt: row.leaseExpiresAt ? Date.parse(row.leaseExpiresAt) : 0 };
|
||||
type Row = Awaited<ReturnType<typeof page>>[number];
|
||||
/** The request's entry when it is owed now, else whether its wait may be
|
||||
* recorded. A wait on the owning run's reply or presentation is never
|
||||
* recorded: a publication that commits it changes no wait-key input, and a
|
||||
* restart can lose the hint that its lease release sends. */
|
||||
async function entry(row: Row, read: GitHubResponseRunRead): Promise<Entry | { parkable: boolean }> {
|
||||
try {
|
||||
const execution = await githubResponseExecution(db, { ...row, agentId: row.agentId!, deliveryId: row.deliveryId! });
|
||||
const execution = await githubResponseExecution(db, { ...row, agentId: row.agentId!, deliveryId: row.deliveryId! }, read);
|
||||
if (execution.body === undefined || execution.reply === "unsettled" ||
|
||||
(execution.paused && row.result?.pausedVersion === execution.version)) return null;
|
||||
(execution.paused && row.result?.pausedVersion === execution.version))
|
||||
return { parkable: !execution.presentationPending && execution.reply === "none" };
|
||||
} catch (error) {
|
||||
if (!(error instanceof HttpError) || error.status !== 403) throw error;
|
||||
// Keep this request eligible for the acknowledgement owner's authority
|
||||
// check and cancellation; it must not poison discovery for other requests.
|
||||
}
|
||||
return pending;
|
||||
return pending(row);
|
||||
}
|
||||
/** The request's entry, before its run state is read. */
|
||||
function pending(row: Row): Entry {
|
||||
return { id: row.id, companyId: row.companyId, endpointId: row.endpointId, deliveryId: row.deliveryId!,
|
||||
issueId: row.issueId, conversationId: row.conversationId, repositoryId: row.repositoryId,
|
||||
number: row.number ? Number(row.number) : null, dueAt: row.leaseExpiresAt ? Date.parse(row.leaseExpiresAt) : 0 };
|
||||
}
|
||||
/** The entries of a page, by position, from one batched run-state read. */
|
||||
async function entries(rows: Row[], signal?: AbortSignal) {
|
||||
const reads = await readGitHubResponseRuns(db, rows.map(row => ({ companyId: row.companyId, endpointId: row.endpointId,
|
||||
agentId: row.agentId!, issueId: row.issueId, deliveryId: row.deliveryId!, sourceMessageId: row.sourceMessageId })));
|
||||
const values: Array<Awaited<ReturnType<typeof entry>>> = [];
|
||||
for (const [index, row] of rows.entries()) {
|
||||
if (!canRun() || signal?.aborted) throw signal?.reason ?? new Error("GitHub terminal-response recovery stopped");
|
||||
values.push(await entry(row, reads[index]!));
|
||||
}
|
||||
return values;
|
||||
}
|
||||
/** Record the wait of requests that cannot progress yet. A request whose row
|
||||
* changed after the read gets no key and is read again. The write leaves
|
||||
* updated_at alone, because the key includes it. */
|
||||
async function park(rows: Row[]) {
|
||||
const waiting = rows.filter(row => row.result?.terminalWaitKey !== row.waitKey);
|
||||
if (!waiting.length) return;
|
||||
await db.execute(sql`update ${chatActions}
|
||||
set result = coalesce(${chatActions.result}, '{}'::jsonb) || jsonb_build_object('terminalWaitKey', waiting.key)
|
||||
from unnest(${sql.param(waiting.map(row => row.id))}::uuid[], ${sql.param(waiting.map(row => row.actionVersion))}::text[],
|
||||
${sql.param(waiting.map(row => row.waitKey))}::text[]) as waiting(id, version, key)
|
||||
where ${chatActions.id} = waiting.id and ${actionVersion} = waiting.version
|
||||
and ${chatActions.status} = 'processed' and coalesce(${chatActions.result}->>'final', 'false') <> 'true'`);
|
||||
}
|
||||
async function current(actionId: string) {
|
||||
const [row] = await page(undefined, undefined, actionId);
|
||||
if (!row) return null;
|
||||
const [value] = await entries([row]);
|
||||
if (!("parkable" in value!)) return value!;
|
||||
if (value.parkable) await park([row]);
|
||||
return null;
|
||||
}
|
||||
|
||||
return registerScopedDeadlineWork(coordinator, {
|
||||
@@ -93,26 +150,29 @@ export function registerGitHubTerminalResponseWork(
|
||||
(!scope.endpointId || value.endpointId === scope.endpointId) && (!scope.repositoryId || value.repositoryId === scope.repositoryId) &&
|
||||
(!scope.number || value.number === scope.number)),
|
||||
load: async (scope?: Scope, signal?: AbortSignal) => {
|
||||
const entries: Entry[] = [];
|
||||
const loaded: Entry[] = [];
|
||||
let cursor: string | undefined;
|
||||
while (canRun() && !signal?.aborted) {
|
||||
const rows = await page(scope, cursor);
|
||||
for (const row of rows) {
|
||||
if (!canRun() || signal?.aborted) throw signal?.reason ?? new Error("GitHub terminal-response recovery stopped");
|
||||
const value = await entry(row); if (value) entries.push(value);
|
||||
const values = await entries(rows, signal);
|
||||
const waiting: Row[] = [];
|
||||
for (const [index, value] of values.entries()) {
|
||||
if (!("parkable" in value)) loaded.push(value); else if (value.parkable) waiting.push(rows[index]!);
|
||||
}
|
||||
if (rows.length < 100) return entries;
|
||||
await park(waiting);
|
||||
if (rows.length < 100) return loaded;
|
||||
cursor = rows[rows.length - 1].id;
|
||||
}
|
||||
throw signal?.reason ?? new Error("GitHub terminal-response recovery stopped");
|
||||
},
|
||||
check: async (value: Entry, signal?: AbortSignal) => {
|
||||
const [row] = await page(undefined, undefined, value.id);
|
||||
const current = row ? await entry(row) : null;
|
||||
if (!current || current.dueAt > Date.now() || !canRun() || signal?.aborted) return current;
|
||||
await acknowledge(current.deliveryId, () => canRun() && !signal?.aborted);
|
||||
const due = await current(value.id);
|
||||
if (!due || due.dueAt > Date.now() || !canRun() || signal?.aborted) return due;
|
||||
await acknowledge(due.deliveryId, () => canRun() && !signal?.aborted);
|
||||
// Keep a request that still waits for the next check, which reads its
|
||||
// run state again before it acknowledges. One check reads it once.
|
||||
const [remaining] = await page(undefined, undefined, value.id);
|
||||
return remaining ? entry(remaining) : null;
|
||||
return remaining ? pending(remaining) : null;
|
||||
},
|
||||
}, canRun);
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { isExternalChatWaitAuthorizationContention } from "../../native-runtime/
|
||||
import { projectSafeChatPublication } from "../../chat-publication-projection.js";
|
||||
import { inboundWakePublicationKey, inboundWakePublicationText, parseInboundWakePublicationKey, resolveInboundWakeReceipt } from "../../chat-inbound-wakeup-publications.js";
|
||||
import { inboundWakeScope, type createInboundWakeAuthority } from "./wakeup-authorization.js";
|
||||
import { SILENT_CHAT_WAKE_SETTLEMENT_KEY } from "../../durable-chat-wakeup.js";
|
||||
import type { createChatFailedRunRetry } from "../failed-run-retry.js";
|
||||
type NoticeOptions = {
|
||||
authorizeInboundWakeup: ReturnType<typeof createInboundWakeAuthority>["authorizeInboundWakeup"];
|
||||
@@ -182,6 +183,8 @@ export function createInboundWakeNotices(db: Db, options: NoticeOptions) {
|
||||
scope?.issueId ? eq(payloadIssueId, scope.issueId) : undefined,
|
||||
inArray(chatActions.status, ["processed", "failed"]),
|
||||
eq(owner.companyId, chatActions.companyId),
|
||||
sql`${owner.payload}->>${SILENT_CHAT_WAKE_SETTLEMENT_KEY} is distinct from 'true'`,
|
||||
sql`${agentWakeupRequests.payload}->>${SILENT_CHAT_WAKE_SETTLEMENT_KEY} is distinct from 'true'`,
|
||||
or(
|
||||
and(
|
||||
isNull(owner.runId),
|
||||
|
||||
@@ -5,11 +5,12 @@ import type { EndpointRow, DbOrTransaction } from "../runtime-types.js";
|
||||
import { notifyChatRunMilestones } from "../../chat-run-milestone-notifications.js";
|
||||
import { notifyChatDeliveryWork } from "../../chat-work-notifications.js";
|
||||
import { enqueueFastResponse } from "../../fast-responses.js";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { and, asc, eq, gte, inArray, isNull, sql } from "drizzle-orm";
|
||||
import { retryChatControlAdmission } from "../../chat-control-admission-retry.js";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { createDurableChatWakeupRequest, assertDurableChatWakeupReceipt, registerDeferredChatWakeOwner } from "../../durable-chat-wakeup.js";
|
||||
import { agentWakeupRequests, chatActions, chatConversations, chatDeliveries, chatEndpoints } from "@paperclipai/db";
|
||||
import { createDurableChatWakeupRequest, assertDurableChatWakeupReceipt, registerDeferredChatWakeOwner, CLOSED_TASK_CHAT_WAKE_REOPEN_WINDOW_MS, type DeferredChatWakeDecline } from "../../durable-chat-wakeup.js";
|
||||
import { agentWakeupRequests, chatActions, chatConversations, chatDeliveries, chatEndpoints, heartbeatRuns, issues } from "@paperclipai/db";
|
||||
import { issueService } from "../../issues.js";
|
||||
import { forbidden } from "../../../errors.js";
|
||||
import { logger } from "../../../middleware/logger.js";
|
||||
import { queueIssueAssignmentWakeup } from "../../issue-assignment-wakeup.js";
|
||||
@@ -438,44 +439,117 @@ export function createInboundWakeups(db: Db, options: WakeupOptions) {
|
||||
return denied;
|
||||
}
|
||||
}
|
||||
const unregisterDeferredWakeOwner = registerDeferredChatWakeOwner(db, async (scope) => {
|
||||
const action = await db.select().from(chatActions).where(and(
|
||||
async function reopenClosedChatTask(tx: Db, action: typeof chatActions.$inferSelect) {
|
||||
const [issue] = await tx.select().from(issues).where(and(eq(issues.companyId, action.companyId),
|
||||
eq(issues.id, String(action.payload.issueId)))).for("update");
|
||||
if (!issue || issue.assigneeAgentId !== action.payload.agentId || !["done", "cancelled"].includes(issue.status)) return;
|
||||
const [endpoint] = await tx.select({ sponsorUserId: chatEndpoints.sponsorUserId }).from(chatEndpoints)
|
||||
.where(and(eq(chatEndpoints.companyId, action.companyId), eq(chatEndpoints.id, action.endpointId)));
|
||||
await issueService(tx).update(issue.id, { status: "todo",
|
||||
actorUserId: action.payload.requestedByActorType === "user" ? String(action.payload.requestedByActorId) : endpoint?.sponsorUserId ?? null,
|
||||
}, tx);
|
||||
}
|
||||
async function recentClosedTaskChatWakes(scope: { companyId: string; agentId: string; issueId: string },
|
||||
action: typeof chatActions.$inferSelect) {
|
||||
const rows = await db.select({ receipt: agentWakeupRequests, action: chatActions }).from(agentWakeupRequests)
|
||||
.innerJoin(chatActions, and(eq(chatActions.companyId, agentWakeupRequests.companyId), eq(chatActions.id, agentWakeupRequests.id)))
|
||||
.where(and(eq(agentWakeupRequests.companyId, scope.companyId), eq(agentWakeupRequests.agentId, scope.agentId),
|
||||
eq(agentWakeupRequests.status, "deferred_issue_execution"), isNull(agentWakeupRequests.runId),
|
||||
sql`${agentWakeupRequests.idempotencyKey} like 'chat-inbound:%'`,
|
||||
sql`${agentWakeupRequests.payload}->>'issueId' = ${scope.issueId}`,
|
||||
gte(agentWakeupRequests.createdAt, new Date(Date.now() - CLOSED_TASK_CHAT_WAKE_REOPEN_WINDOW_MS)),
|
||||
eq(chatActions.kind, "inbound_wakeup"), eq(chatActions.status, "processed"),
|
||||
action.conversationId ? eq(chatActions.conversationId, action.conversationId) : isNull(chatActions.conversationId),
|
||||
sql`${chatActions.payload}->>'issueId' = ${scope.issueId}`, sql`${chatActions.payload}->>'agentId' = ${scope.agentId}`))
|
||||
.orderBy(asc(agentWakeupRequests.createdAt), asc(agentWakeupRequests.id));
|
||||
return rows;
|
||||
}
|
||||
const unregisterDeferredWakeOwner = registerDeferredChatWakeOwner(db, async (scope): Promise<DeferredChatWakeDecline | void> => {
|
||||
const saved = await db.select().from(chatActions).where(and(
|
||||
eq(chatActions.id, scope.requestId), eq(chatActions.companyId, scope.companyId),
|
||||
eq(chatActions.kind, "inbound_wakeup"), eq(chatActions.status, "processed"),
|
||||
)).then(rows => rows[0] ?? null);
|
||||
if (!action || action.payload.agentId !== scope.agentId || action.payload.issueId !== scope.issueId) return;
|
||||
if (!saved || saved.kind !== "inbound_wakeup") return;
|
||||
const source = saved;
|
||||
const [receipt] = await db.select().from(agentWakeupRequests).where(and(
|
||||
eq(agentWakeupRequests.id, action.id), eq(agentWakeupRequests.companyId, scope.companyId),
|
||||
eq(agentWakeupRequests.id, scope.requestId), eq(agentWakeupRequests.companyId, scope.companyId),
|
||||
eq(agentWakeupRequests.agentId, scope.agentId), eq(agentWakeupRequests.status, "deferred_issue_execution"),
|
||||
));
|
||||
if (!receipt || receipt.runId) return;
|
||||
const authorize = async (tx: Db) => {
|
||||
const [source] = await tx.select().from(chatActions).where(and(
|
||||
eq(chatActions.id, action.id), eq(chatActions.companyId, scope.companyId),
|
||||
const sweep = scope.recoverySweep === true;
|
||||
if (["preparing", "issued", "processing"].includes(source.status)) return sweep ? { retry: "source_pending" } : undefined;
|
||||
if (source.status !== "processed" || source.payload.agentId !== scope.agentId ||
|
||||
source.payload.issueId !== scope.issueId) return sweep ? { settle: "source_missing" } : undefined;
|
||||
let closed = false;
|
||||
if (sweep) {
|
||||
const [task] = await db.select({ status: issues.status, assigneeAgentId: issues.assigneeAgentId }).from(issues)
|
||||
.where(and(eq(issues.companyId, scope.companyId), eq(issues.id, scope.issueId)));
|
||||
if (!task) return { settle: "task_missing" };
|
||||
if (task.assigneeAgentId !== scope.agentId) return { settle: "task_reassigned" };
|
||||
if (task.status === "backlog") return { retry: "task_backlog" };
|
||||
closed = task.status === "done" || task.status === "cancelled";
|
||||
if (closed && receipt.createdAt.getTime() < Date.now() - CLOSED_TASK_CHAT_WAKE_REOPEN_WINDOW_MS) return { settle: "task_closed" };
|
||||
}
|
||||
const candidates = closed
|
||||
? (await recentClosedTaskChatWakes(scope, source)).filter(row => row.receipt.id !== receipt.id) : [];
|
||||
const authorizeAction = async (tx: Db, saved: typeof chatActions.$inferSelect) => {
|
||||
const [current] = await tx.select().from(chatActions).where(and(
|
||||
eq(chatActions.id, saved.id), eq(chatActions.companyId, scope.companyId),
|
||||
eq(chatActions.kind, "inbound_wakeup"), eq(chatActions.status, "processed"),
|
||||
));
|
||||
if (!source || inboundWakeScope(source) !== inboundWakeScope(action))
|
||||
if (!current || inboundWakeScope(current) !== inboundWakeScope(saved))
|
||||
throw forbidden("The saved chat source changed", { code: "chat_action_authorization_changed" });
|
||||
const current = await authorizeInboundWorkStart(tx, source);
|
||||
if (current.delivery.state !== "processed") throw new Error("chat_inbound_wakeup_acceptance_not_committed");
|
||||
return current;
|
||||
const authorized = await authorizeInboundWorkStart(tx, current);
|
||||
if (authorized.delivery.state !== "processed") throw new Error("chat_inbound_wakeup_acceptance_not_committed");
|
||||
return authorized;
|
||||
};
|
||||
const accepted: typeof candidates = [];
|
||||
// The same authority used at ingress checks the live endpoint, principal,
|
||||
// immutable action source, conversation generation and original comment.
|
||||
const context = await db.transaction(tx => authorize(tx as unknown as Db));
|
||||
const context = await db.transaction(async tx => {
|
||||
if (closed) await reopenClosedChatTask(tx as unknown as Db, source);
|
||||
const authorized = await authorizeAction(tx as unknown as Db, source);
|
||||
for (const candidate of candidates) {
|
||||
if (await tx.transaction(inner => authorizeAction(inner as unknown as Db, candidate.action)).then(() => true, () => false))
|
||||
accepted.push(candidate);
|
||||
}
|
||||
return authorized;
|
||||
});
|
||||
const batch = [{ receipt, action: source }, ...accepted].sort((left, right) =>
|
||||
left.receipt.createdAt.getTime() - right.receipt.createdAt.getTime() || left.receipt.id.localeCompare(right.receipt.id));
|
||||
const { receipt: primaryReceipt, action } = batch.at(-1)!;
|
||||
const riders = batch.slice(0, -1);
|
||||
const request = createDurableChatWakeupRequest({
|
||||
id: action.id, companyId: scope.companyId, agentId: scope.agentId, issueId: scope.issueId,
|
||||
commentId: String(action.payload.commentId),
|
||||
requestedByActorType: action.payload.requestedByActorType as "user" | "system",
|
||||
requestedByActorId: String(action.payload.requestedByActorId), requestedAt: action.createdAt,
|
||||
resumeDeferred: true, authorize: async tx => { await authorize(tx); },
|
||||
resumeDeferred: true,
|
||||
authorize: async tx => {
|
||||
await authorizeAction(tx, action);
|
||||
if (!riders.length) return;
|
||||
const current = await tx.select({ status: agentWakeupRequests.status, runId: agentWakeupRequests.runId })
|
||||
.from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, scope.companyId),
|
||||
inArray(agentWakeupRequests.id, riders.map(rider => rider.receipt.id)))).for("update");
|
||||
if (current.length !== riders.length || current.some(row => row.status !== "deferred_issue_execution" || row.runId))
|
||||
throw new Error("chat_inbound_wakeup_batch_changed");
|
||||
},
|
||||
...(riders.length ? { onAdmitted: async (tx: Db, admitted: { runId: string | null }) => {
|
||||
if (!admitted.runId) return;
|
||||
const now = new Date();
|
||||
await tx.update(agentWakeupRequests).set({ status: "coalesced", runId: admitted.runId, finishedAt: now, updatedAt: now,
|
||||
payload: sql`coalesce(${agentWakeupRequests.payload}, '{}'::jsonb) || ${JSON.stringify({ coalescedIntoWakeupRequestId: action.id })}::jsonb`,
|
||||
}).where(and(eq(agentWakeupRequests.companyId, scope.companyId),
|
||||
inArray(agentWakeupRequests.id, riders.map(rider => rider.receipt.id)),
|
||||
eq(agentWakeupRequests.status, "deferred_issue_execution"), isNull(agentWakeupRequests.runId)));
|
||||
} } : {}),
|
||||
});
|
||||
assertDurableChatWakeupReceipt(request, receipt);
|
||||
assertDurableChatWakeupReceipt(request, primaryReceipt);
|
||||
await queueIssueAssignmentWakeup({ heartbeat: options.heartbeat, issue: context.issue,
|
||||
reason: EXTERNAL_CHAT_MESSAGE_WAKE_REASON, mutation: EXTERNAL_CHAT_MESSAGE_WAKE_MUTATION,
|
||||
contextSource: `chat:${context.endpoint.provider}`, taskKey: context.issue.identifier,
|
||||
requestedByActorType: request.requestedByActorType, requestedByActorId: request.requestedByActorId,
|
||||
wakeCommentId: request.commentId, chatConversationId: context.conversation.id,
|
||||
...(riders.length ? { wakeCommentIds: batch.map(entry => String(entry.action.payload.commentId)) } : {}),
|
||||
attachmentOmissionReasons: action.payload.attachmentOmissionReasons as Record<string, number> | undefined,
|
||||
durableChatRequest: request, rethrowOnError: true });
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { agentWakeupRequests, chatActions } from "@paperclipai/db";
|
||||
import {
|
||||
assertDurableChatWakeupReceipt,
|
||||
createDurableChatWakeupRequest,
|
||||
SILENT_CHAT_WAKE_SETTLEMENT_KEY,
|
||||
} from "./durable-chat-wakeup.js";
|
||||
import { QUEUED_MESSAGES_DELIVERED_REASON } from "../modules/wake-queue/index.js";
|
||||
|
||||
@@ -130,6 +131,8 @@ export function resolveInboundWakeReceipt(
|
||||
// "not started" would be wrong; it keeps the same silence as a promotion.
|
||||
if (declined && owner.status === "cancelled" && owner.error === QUEUED_MESSAGES_DELIVERED_REASON)
|
||||
return null;
|
||||
if (declined && [owner, receipt].some(row => row.payload?.[SILENT_CHAT_WAKE_SETTLEMENT_KEY] === true))
|
||||
return null;
|
||||
if (declined)
|
||||
return owner.runId || receipt.runId
|
||||
? null
|
||||
|
||||
@@ -7,6 +7,7 @@ export type DeferredReceiptRecoveryOptions = {
|
||||
companyId?: string;
|
||||
requestId?: string;
|
||||
onError?: (error: unknown) => void;
|
||||
onDeferredDeadline?: (at: number) => void;
|
||||
};
|
||||
|
||||
const ASSIGNMENT_WAKE_REASON = "issue_assigned";
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { slackDeliveryMeetsMentionRequirement } from "./chat-channels/slack/wake-authority.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { agentWakeupRequests, chatActions, chatConversations, chatDeliveries, chatEndpoints, type Db } from "@paperclipai/db";
|
||||
import { and, eq, exists, inArray, or, sql, type SQLWrapper } from "drizzle-orm";
|
||||
import { and, eq, exists, inArray, isNull, or, sql, type SQLWrapper } from "drizzle-orm";
|
||||
import { HttpError } from "../errors.js";
|
||||
import { safeChatWakeAuthorityReason } from "./chat-channels/inbound/wakeup-authorization-error.js";
|
||||
import { notifyChatInboundWakeNotices } from "./chat-inbound-wake-notice-notifications.js";
|
||||
|
||||
export interface CommittedChatResponseAuthorizationInput {
|
||||
companyId: string;
|
||||
@@ -233,6 +235,82 @@ export interface DeferredChatWakeScope {
|
||||
agentId: string;
|
||||
issueId: string;
|
||||
requestId: string;
|
||||
recoverySweep?: boolean;
|
||||
}
|
||||
|
||||
export type DeferredChatWakeDecline = { settle: string } | { retry: string };
|
||||
|
||||
export const CLOSED_TASK_CHAT_WAKE_REOPEN_WINDOW_MS = 60 * 60_000;
|
||||
export const SILENT_CHAT_WAKE_SETTLEMENT_AFTER_MS = 24 * 60 * 60_000;
|
||||
export const DEFERRED_CHAT_WAKE_RETRY_KEY = "chatResume";
|
||||
export const SILENT_CHAT_WAKE_SETTLEMENT_KEY = "silentSettlement";
|
||||
export const DEFERRED_CHAT_WAKE_RETRY_DELAYS_MS = [60_000, 10 * 60_000, 60 * 60_000, 6 * 60 * 60_000, 24 * 60 * 60_000];
|
||||
const SETTLED_AUTHORITY_REASONS = new Set<string>(["source_shape", "delivery_binding", "conversation_binding",
|
||||
"destination_binding", "source_comment"]);
|
||||
const DECLINED_CHAT_INPUT_NOTICE =
|
||||
"Input saved. Its work request was skipped, cancelled, or failed; no automatic replay was performed.";
|
||||
|
||||
export function deferredChatWakeNextAttemptAt(payload: Record<string, unknown> | null | undefined): number | null {
|
||||
const retry = payload?.[DEFERRED_CHAT_WAKE_RETRY_KEY];
|
||||
if (!retry || typeof retry !== "object" || Array.isArray(retry)) return null;
|
||||
const at = Date.parse(String((retry as Record<string, unknown>).nextAttemptAt));
|
||||
return Number.isFinite(at) ? at : null;
|
||||
}
|
||||
|
||||
export function deferredChatWakeDeclineForError(error: unknown): DeferredChatWakeDecline {
|
||||
const authority = safeChatWakeAuthorityReason(error);
|
||||
if (authority) return SETTLED_AUTHORITY_REASONS.has(authority)
|
||||
? { settle: `authority_${authority}` } : { retry: `authority_${authority}` };
|
||||
if (error instanceof HttpError) {
|
||||
const details = error.details && typeof error.details === "object" ? error.details as Record<string, unknown> : {};
|
||||
return { retry: typeof details.code === "string" ? details.code : `http_${error.status}` };
|
||||
}
|
||||
return { retry: error instanceof Error && /^chat_[a-z_]+$/.test(error.message) ? error.message : "resume_failed" };
|
||||
}
|
||||
|
||||
export async function recordDeferredChatWakeDecline(db: Db,
|
||||
scope: { companyId: string; issueId: string; requestId: string }, decline: DeferredChatWakeDecline) {
|
||||
return db.transaction(async tx => {
|
||||
const [receipt] = await tx.select({ payload: agentWakeupRequests.payload, createdAt: agentWakeupRequests.createdAt })
|
||||
.from(agentWakeupRequests).where(and(
|
||||
eq(agentWakeupRequests.companyId, scope.companyId), eq(agentWakeupRequests.id, scope.requestId),
|
||||
eq(agentWakeupRequests.status, "deferred_issue_execution"), isNull(agentWakeupRequests.runId))).for("update");
|
||||
if (!receipt) return null;
|
||||
const previous = receipt.payload?.[DEFERRED_CHAT_WAKE_RETRY_KEY];
|
||||
const attempts = (previous && typeof previous === "object" && !Array.isArray(previous)
|
||||
? Number((previous as Record<string, unknown>).attempts) || 0 : 0) + 1;
|
||||
const now = new Date();
|
||||
if ("retry" in decline && attempts <= DEFERRED_CHAT_WAKE_RETRY_DELAYS_MS.length) {
|
||||
const nextAttemptAt = now.getTime() + DEFERRED_CHAT_WAKE_RETRY_DELAYS_MS[attempts - 1]!;
|
||||
await tx.update(agentWakeupRequests).set({ error: decline.retry, updatedAt: now,
|
||||
payload: sql`coalesce(${agentWakeupRequests.payload}, '{}'::jsonb) || ${JSON.stringify({ [DEFERRED_CHAT_WAKE_RETRY_KEY]: {
|
||||
attempts, reason: decline.retry, nextAttemptAt: new Date(nextAttemptAt).toISOString() } })}::jsonb`,
|
||||
}).where(eq(agentWakeupRequests.id, scope.requestId));
|
||||
return { outcome: "retry" as const, reason: decline.retry, attempts, nextAttemptAt };
|
||||
}
|
||||
const reason = "settle" in decline ? decline.settle : `retry_exhausted:${decline.retry}`;
|
||||
const silent = receipt.createdAt.getTime() < now.getTime() - SILENT_CHAT_WAKE_SETTLEMENT_AFTER_MS;
|
||||
await tx.update(agentWakeupRequests).set({ status: "skipped", error: reason, finishedAt: now, updatedAt: now,
|
||||
payload: silent
|
||||
? sql`(${agentWakeupRequests.payload} - ${DEFERRED_CHAT_WAKE_RETRY_KEY}::text) || ${JSON.stringify({ [SILENT_CHAT_WAKE_SETTLEMENT_KEY]: true })}::jsonb`
|
||||
: sql`${agentWakeupRequests.payload} - ${DEFERRED_CHAT_WAKE_RETRY_KEY}::text`,
|
||||
}).where(eq(agentWakeupRequests.id, scope.requestId));
|
||||
if (silent) return { outcome: "settled" as const, reason, attempts, silent };
|
||||
await notifyChatInboundWakeNotices(tx, { companyId: scope.companyId, issueId: scope.issueId });
|
||||
await tx.update(chatDeliveries).set({ redactedError: DECLINED_CHAT_INPUT_NOTICE, updatedAt: now }).where(and(
|
||||
eq(chatDeliveries.companyId, scope.companyId), eq(chatDeliveries.state, "processed"),
|
||||
sql`${chatDeliveries.id} = (select ${chatActions.deliveryId} from ${chatActions}
|
||||
where ${chatActions.companyId} = ${scope.companyId} and ${chatActions.id} = ${scope.requestId}
|
||||
and ${chatActions.kind} = 'inbound_wakeup')`));
|
||||
return { outcome: "settled" as const, reason, attempts, silent };
|
||||
});
|
||||
}
|
||||
|
||||
export async function clearDeferredChatWakeRetry(db: Db, scope: { companyId: string; requestId: string }) {
|
||||
await db.update(agentWakeupRequests).set({ error: null,
|
||||
payload: sql`${agentWakeupRequests.payload} - ${DEFERRED_CHAT_WAKE_RETRY_KEY}::text`,
|
||||
}).where(and(eq(agentWakeupRequests.companyId, scope.companyId), eq(agentWakeupRequests.id, scope.requestId),
|
||||
sql`${agentWakeupRequests.payload} ? ${DEFERRED_CHAT_WAKE_RETRY_KEY}::text`));
|
||||
}
|
||||
|
||||
/** Identify saved input by its canonical receipt, never by a caller's source
|
||||
@@ -250,15 +328,18 @@ export function deferredChatInputPredicate(db: Db) {
|
||||
sql`${chatActions.payload}->>'issueId' = ${agentWakeupRequests.payload}->>'issueId'`,
|
||||
sql`${chatActions.payload}->>'agentId' = ${agentWakeupRequests.agentId}::text`)));
|
||||
}
|
||||
const deferredChatWakeOwners = new WeakMap<Db, (input: DeferredChatWakeScope) => Promise<void>>();
|
||||
type DeferredChatWakeOwner = (input: DeferredChatWakeScope) => Promise<DeferredChatWakeDecline | void>;
|
||||
const deferredChatWakeOwners = new WeakMap<Db, DeferredChatWakeOwner>();
|
||||
|
||||
/** The live inbound owner reauthorizes the original source. Cleanup owns no chat authority. */
|
||||
export function registerDeferredChatWakeOwner(db: Db, owner: (input: DeferredChatWakeScope) => Promise<void>) {
|
||||
export function registerDeferredChatWakeOwner(db: Db, owner: DeferredChatWakeOwner) {
|
||||
deferredChatWakeOwners.set(db, owner);
|
||||
return () => { if (deferredChatWakeOwners.get(db) === owner) deferredChatWakeOwners.delete(db); };
|
||||
}
|
||||
export async function resumeDeferredChatWake(db: Db, input: DeferredChatWakeScope) {
|
||||
await deferredChatWakeOwners.get(db)?.(input);
|
||||
export async function resumeDeferredChatWake(db: Db, input: DeferredChatWakeScope): Promise<DeferredChatWakeDecline | undefined> {
|
||||
const owner = deferredChatWakeOwners.get(db);
|
||||
if (!owner) return undefined;
|
||||
return (await owner(input)) ?? undefined;
|
||||
}
|
||||
|
||||
/** Internal authority: this object cannot be supplied through a JSON API. */
|
||||
|
||||
@@ -18,6 +18,7 @@ import type { PluginWorkerManager } from "./plugin-worker-manager.js";
|
||||
import { NativeExecutionContext } from "./native-runtime/native-execution-context.js";
|
||||
import { assertPluginTaskSourceAttachment, assertPluginTaskSourceRecovery } from "./native-runtime/plugin-task-source-recovery.js";
|
||||
import { pluginAgentRuntimeIdentity } from "./plugin-agent-runtime-state.js";
|
||||
import { runnerLaunchPreparationDigest, runnerLaunchRunDigest } from "../vendor/paperclip-runner/index.js";
|
||||
import { assertPluginTaskOwnershipDispatch, PluginTaskOwnershipPendingError, readyPortableTaskSource, reconcilePluginTaskAdmission } from "./plugin-task-ownership.js";
|
||||
|
||||
export type PluginTaskDescription = Extract<PluginEnvironmentTaskResult, { kind: "description" }>;
|
||||
@@ -61,6 +62,12 @@ export async function executeEnvironmentTask(db: Db, workers: Pick<PluginWorkerM
|
||||
expectedTaskId?: string;
|
||||
}): Promise<PluginEnvironmentTaskResult> {
|
||||
const operation = environmentTaskOperationSchema.parse(input.operation);
|
||||
if (operation.kind === "prepare" && (operation.preparationDigest !== undefined || operation.runDigest !== undefined)) {
|
||||
const preparationDigest = runnerLaunchPreparationDigest(operation.requirements as Parameters<typeof runnerLaunchPreparationDigest>[0]);
|
||||
if (operation.preparationDigest !== preparationDigest || operation.runDigest !== runnerLaunchRunDigest(preparationDigest, operation.requirements as Parameters<typeof runnerLaunchRunDigest>[1])) {
|
||||
throw new Error("Plugin Runner launch digest mismatch");
|
||||
}
|
||||
}
|
||||
const [row] = await db.select({ lease: environmentLeases, environment: environments, run: heartbeatRuns })
|
||||
.from(environmentLeases)
|
||||
.leftJoin(environments, eq(environments.id, environmentLeases.environmentId))
|
||||
@@ -534,12 +541,13 @@ export async function executeEnvironmentTask(db: Db, workers: Pick<PluginWorkerM
|
||||
}
|
||||
if (freshWorkspace && parsed.kind === "description" && parsed.freshWorkspaceVersion !== 1)
|
||||
throw new Error("Plugin-provided fresh workspace preparation unavailable");
|
||||
if (operation.kind === "prepare" && parsed.kind === "prepared" && parsed.projectAuthCheckAtSubmit) {
|
||||
if (operation.kind === "prepare" && parsed.kind === "prepared" && (parsed.projectAuthChecked || parsed.projectAuthCheckAtSubmit)) {
|
||||
const harness = operation.requirements.provider === "acpx" ? operation.requirements.settings.acpxAgent : operation.requirements.provider;
|
||||
if (!harness) throw new Error("Plugin Runner prepared provider unavailable");
|
||||
const provider = harness === "codex" ? "openai" : harness === "claude" ? "anthropic" : harness;
|
||||
const saved = await db.update(environmentLeases).set({ metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb) || ${JSON.stringify({
|
||||
runnerTaskProjectAuthValidation: { configurationId: parsed.launch.configurationId, provider, projectIds, atSubmit: true },
|
||||
runnerTaskProjectAuthValidation: { configurationId: parsed.launch.configurationId, provider, projectIds,
|
||||
...(parsed.projectAuthChecked ? {} : { atSubmit: true }) },
|
||||
})}::jsonb` }).where(and(eq(environmentLeases.id, lease.id), eq(environmentLeases.companyId, input.companyId),
|
||||
eq(environmentLeases.status, "active"), sql`coalesce(${environmentLeases.metadata}->>'runnerTaskRetiring', 'false') != 'true'`)).returning({ id: environmentLeases.id });
|
||||
if (saved.length !== 1) throw new Error("Plugin Runner project validation lease expired");
|
||||
|
||||
@@ -544,14 +544,23 @@ export function folderService(db: Db, mutationLockHeld = false) {
|
||||
throw conflict("Could not create project skill folder");
|
||||
}
|
||||
|
||||
async function findCurrentBundledCategory(companyId: string, systemKey: string, name: string) {
|
||||
const rows = await getRows(companyId, "skill");
|
||||
const existing = rows.find((row) => row.systemKey === systemKey);
|
||||
if (!existing || existing.name !== name || !rows.some((row) => row.systemKey === "bundled")) return null;
|
||||
return buildFolderViews(rows).get(existing.id) ?? null;
|
||||
}
|
||||
|
||||
async function ensureBundledCategory(companyId: string, category: string): Promise<Folder> {
|
||||
if (!mutationLockHeld) {
|
||||
return withCompanyFolderLock(companyId, (lockedDb) => folderService(lockedDb, true).ensureBundledCategory(companyId, category));
|
||||
}
|
||||
const root = await ensureContainer(companyId, "bundled", "Bundled");
|
||||
const name = normalizeName(category);
|
||||
const slug = normalizeFolderSlug(category);
|
||||
const systemKey = `bundled:${slug}`;
|
||||
if (!mutationLockHeld) {
|
||||
const current = await findCurrentBundledCategory(companyId, systemKey, name);
|
||||
if (current) return current;
|
||||
return withCompanyFolderLock(companyId, (lockedDb) => folderService(lockedDb, true).ensureBundledCategory(companyId, category));
|
||||
}
|
||||
const root = await ensureContainer(companyId, "bundled", "Bundled");
|
||||
for (let attempt = 0; attempt < 3; attempt += 1) {
|
||||
const resolved = await uniqueSystemSlug(companyId, root.id, slug, systemKey, "bundled");
|
||||
if (resolved.id) {
|
||||
@@ -576,16 +585,15 @@ export function folderService(db: Db, mutationLockHeld = false) {
|
||||
throw conflict("Could not create bundled skill folder");
|
||||
}
|
||||
|
||||
async function pruneEmptyBundledCategories(companyId: string, retainedCategories: string[]): Promise<void> {
|
||||
if (!mutationLockHeld) {
|
||||
return withCompanyFolderLock(companyId, (lockedDb) => folderService(lockedDb, true).pruneEmptyBundledCategories(companyId, retainedCategories));
|
||||
}
|
||||
const root = await findSystemFolder(companyId, "bundled");
|
||||
if (!root) return;
|
||||
const rows = await getRows(companyId, "skill");
|
||||
async function emptyBundledCategoryIds(companyId: string, retainedCategories: string[], rows: FolderRow[]) {
|
||||
const root = rows.find((row) => row.kind === "skill" && row.systemKey === "bundled");
|
||||
if (!root) return [];
|
||||
const retainedSystemKeys = new Set(
|
||||
retainedCategories.map((category) => `bundled:${normalizeFolderSlug(category)}`),
|
||||
);
|
||||
const candidates = rows.filter((row) => row.parentId === root.id && row.systemKey?.startsWith("bundled:")
|
||||
&& !retainedSystemKeys.has(row.systemKey));
|
||||
if (candidates.length === 0) return [];
|
||||
const usedFolderIds = new Set(
|
||||
await db
|
||||
.select({ folderId: companySkills.folderId })
|
||||
@@ -594,10 +602,16 @@ export function folderService(db: Db, mutationLockHeld = false) {
|
||||
.then((skills) => skills.flatMap((skill) => skill.folderId ? [skill.folderId] : [])),
|
||||
);
|
||||
const parentIds = new Set(rows.flatMap((row) => row.parentId ? [row.parentId] : []));
|
||||
for (const row of rows) {
|
||||
if (row.parentId !== root.id || !row.systemKey?.startsWith("bundled:")) continue;
|
||||
if (retainedSystemKeys.has(row.systemKey) || usedFolderIds.has(row.id) || parentIds.has(row.id)) continue;
|
||||
await db.delete(folders).where(and(eq(folders.companyId, companyId), eq(folders.id, row.id)));
|
||||
return candidates.filter((row) => !usedFolderIds.has(row.id) && !parentIds.has(row.id)).map((row) => row.id);
|
||||
}
|
||||
|
||||
async function pruneEmptyBundledCategories(companyId: string, retainedCategories: string[]): Promise<void> {
|
||||
if (!mutationLockHeld) {
|
||||
if ((await emptyBundledCategoryIds(companyId, retainedCategories, await getRows(companyId, "skill"))).length === 0) return;
|
||||
return withCompanyFolderLock(companyId, (lockedDb) => folderService(lockedDb, true).pruneEmptyBundledCategories(companyId, retainedCategories));
|
||||
}
|
||||
for (const id of await emptyBundledCategoryIds(companyId, retainedCategories, await getRows(companyId, "skill"))) {
|
||||
await db.delete(folders).where(and(eq(folders.companyId, companyId), eq(folders.id, id)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,8 +6,9 @@ import { DELIVERY_QUEUES } from "../delivery-work-notifications.js";
|
||||
import { assignmentWakePayloadSql, type DeferredExecutionScope, type DeferredReceiptRecoveryOptions } from "../deferred-execution-notifications.js";
|
||||
import { registerScopedDeadlineWork } from "../scoped-deadline-work.js";
|
||||
import { dependencyResolvedWakePayloadSql } from "../issue-dependency-wakeups.js";
|
||||
import { DEFERRED_CHAT_WAKE_RETRY_KEY, deferredChatWakeNextAttemptAt } from "../durable-chat-wakeup.js";
|
||||
|
||||
type Entry = { id: string; companyId: string; dueAt: number; immediate: boolean; operatorRetry?: boolean };
|
||||
type Entry = { id: string; companyId: string; dueAt: number; immediate: boolean; operatorRetry?: boolean; forced?: boolean };
|
||||
type NativeIntentOptions = DeferredExecutionScope & {
|
||||
onDeferredDeadline(at: number): void;
|
||||
onError(error: unknown): void;
|
||||
@@ -63,6 +64,7 @@ export function registerDeferredReceiptWork(
|
||||
status: agentWakeupRequests.status, updatedAt: agentWakeupRequests.updatedAt,
|
||||
claimedAt: agentWakeupRequests.claimedAt, error: agentWakeupRequests.error,
|
||||
operatorRetry: sql<boolean>`${operatorRetry}`,
|
||||
chatRetryAt: sql<string | null>`${agentWakeupRequests.payload} #>> ${`{${DEFERRED_CHAT_WAKE_RETRY_KEY},nextAttemptAt}`}`,
|
||||
delayed: sql<boolean>`${agentWakeupRequests.payload}->'queuedCommentInterrupt' is not null
|
||||
or ${agentWakeupRequests.payload}->'executionWait' is not null`,
|
||||
interruptedLegacy: sql<boolean>`exists (select 1 from heartbeat_runs r
|
||||
@@ -104,13 +106,16 @@ export function registerDeferredReceiptWork(
|
||||
if (complete) cursors.delete(key); else cursors.set(key, rows.at(-1)!.id);
|
||||
const now = Date.now();
|
||||
return { rows: [...prioritized, ...rows].map(row => {
|
||||
const forced = kind === "deferred" && scope?.requestId === row.id;
|
||||
const chatRetryAt = kind === "deferred" && !forced && row.chatRetryAt ? Date.parse(row.chatRetryAt) : NaN;
|
||||
const deadline = kind === "native" && row.status === "claimed" && row.claimedAt ? row.claimedAt.getTime() + 60_000
|
||||
: kind === "native" && row.error ? row.updatedAt.getTime() + 30_000
|
||||
: kind === "deferred" && row.delayed && !row.interruptedLegacy ? row.updatedAt.getTime() + 30_000
|
||||
: kind === "deferred" && row.delayed && !row.interruptedLegacy ? Math.max(row.updatedAt.getTime() + 30_000, chatRetryAt || 0)
|
||||
: Number.isFinite(chatRetryAt) ? chatRetryAt
|
||||
: null;
|
||||
const immediate = deadline === null || deadline <= now;
|
||||
return { id: row.id, companyId: row.companyId, dueAt: immediate ? now : deadline, immediate,
|
||||
operatorRetry: kind === "deferred" && row.operatorRetry };
|
||||
operatorRetry: kind === "deferred" && row.operatorRetry, forced };
|
||||
}), complete };
|
||||
},
|
||||
check: async entry => {
|
||||
@@ -125,12 +130,15 @@ export function registerDeferredReceiptWork(
|
||||
}).from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, entry.companyId),
|
||||
eq(agentWakeupRequests.id, entry.id)));
|
||||
if (!current) return null;
|
||||
const due = kind === "native" && current.status === "claimed" && current.claimedAt
|
||||
const chatRetryAt = kind === "deferred" && !entry.forced && current.status === "deferred_issue_execution"
|
||||
? deferredChatWakeNextAttemptAt(current.payload) : null;
|
||||
const delayedDue = kind === "native" && current.status === "claimed" && current.claimedAt
|
||||
? current.claimedAt.getTime() + 60_000
|
||||
: kind === "native" && current.status === "queued" && current.error ? current.updatedAt.getTime() + 30_000
|
||||
: kind === "deferred" && current.status === "deferred_issue_execution" && !current.interruptedLegacy
|
||||
&& (current.payload?.queuedCommentInterrupt || current.payload?.executionWait)
|
||||
? current.updatedAt.getTime() + 30_000 : null;
|
||||
const due = chatRetryAt === null ? delayedDue : Math.max(delayedDue ?? 0, chatRetryAt);
|
||||
if (due !== null && due > Date.now()) return { ...entry, dueAt: due, immediate: false };
|
||||
}
|
||||
const errors: unknown[] = [];
|
||||
@@ -143,11 +151,12 @@ export function registerDeferredReceiptWork(
|
||||
else if (kind === "task_chat") await owner.settleTaskChat(scope);
|
||||
else {
|
||||
const failed = (error: unknown) => { if (!(error instanceof PersistedExecutionWaitRefusal)) errors.push(error); };
|
||||
try { await owner.resume({ ...scope, onError: failed }); }
|
||||
try { await owner.resume({ ...scope, onError: failed,
|
||||
onDeferredDeadline: at => { next = next === null ? at : Math.min(next, at); } }); }
|
||||
catch (error) { failed(error); }
|
||||
}
|
||||
if (errors.length) throw new AggregateError(errors, `Deferred receipt ${entry.id} could not settle`);
|
||||
return next === null ? null : { ...entry, dueAt: next, immediate: false };
|
||||
return next === null ? null : { ...entry, dueAt: next, immediate: false, forced: false };
|
||||
},
|
||||
}, canRun);
|
||||
}
|
||||
|
||||
@@ -83,6 +83,10 @@ import { executionFailureRetryCount } from "../execution-recovery-attempt.js";
|
||||
import {
|
||||
slackMentionAllowsRunStart,
|
||||
resumeDeferredChatWake,
|
||||
recordDeferredChatWakeDecline,
|
||||
clearDeferredChatWakeRetry,
|
||||
deferredChatWakeDeclineForError,
|
||||
DEFERRED_CHAT_WAKE_RETRY_KEY,
|
||||
assertDurableChatWakeupReceipt,
|
||||
assertDurableChatWakeupRequest,
|
||||
withDurableChatAdmission,
|
||||
@@ -2197,6 +2201,27 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
// A server restart or a message/cleanup race can leave a deferred wake
|
||||
// after its owner has released the issue lock. Revisit it through the same
|
||||
// release admission, so recovery holds and operator Stops still apply.
|
||||
const orphanedChatWakes = await db.select({ id: agentWakeupRequests.id, companyId: agentWakeupRequests.companyId,
|
||||
payload: agentWakeupRequests.payload }).from(agentWakeupRequests)
|
||||
.where(and(scope.companyId ? eq(agentWakeupRequests.companyId, scope.companyId) : undefined,
|
||||
scope.requestId ? eq(agentWakeupRequests.id, scope.requestId) : undefined,
|
||||
eq(agentWakeupRequests.status, "deferred_issue_execution"), isNull(agentWakeupRequests.runId),
|
||||
sql`${agentWakeupRequests.idempotencyKey} like 'chat-inbound:%'`,
|
||||
sql`EXISTS (SELECT 1 FROM chat_actions chat_wake_source WHERE chat_wake_source.company_id = ${agentWakeupRequests.companyId}
|
||||
AND chat_wake_source.id = ${agentWakeupRequests.id} AND chat_wake_source.kind = 'inbound_wakeup')`,
|
||||
sql`NOT EXISTS (SELECT 1 FROM issues chat_wake_issue WHERE chat_wake_issue.company_id = ${agentWakeupRequests.companyId}
|
||||
AND chat_wake_issue.id::text = ${agentWakeupRequests.payload}->>'issueId')`))
|
||||
.limit(50);
|
||||
for (const wake of orphanedChatWakes) {
|
||||
await recordDeferredChatWakeDecline(db, { companyId: wake.companyId, issueId: String(wake.payload?.issueId),
|
||||
requestId: wake.id }, { settle: "task_missing" }).then(recorded => {
|
||||
if (recorded) logger.warn({ requestId: wake.id, reason: recorded.reason, outcome: recorded.outcome, attempts: recorded.attempts },
|
||||
"saved chat source could not resume after recovery");
|
||||
}).catch(err => {
|
||||
scope.onError?.(err);
|
||||
logger.warn({ err, requestId: wake.id }, "saved chat source could not record its resume outcome");
|
||||
});
|
||||
}
|
||||
const strandedQueues = await db.select({ wake: agentWakeupRequests })
|
||||
.from(agentWakeupRequests)
|
||||
.innerJoin(issues, and(eq(issues.companyId, agentWakeupRequests.companyId),
|
||||
@@ -2214,6 +2239,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
), sql`${agentWakeupRequests.payload}->>'mutation' = 'interaction'`,
|
||||
dependencyResolvedWakePayloadSql, assignmentWakePayloadSql),
|
||||
sql`${agentWakeupRequests.payload}->'queuedCommentInterrupt' is null`,
|
||||
scope.requestId ? undefined : sql`coalesce((${agentWakeupRequests.payload} #>> ${`{${DEFERRED_CHAT_WAKE_RETRY_KEY},nextAttemptAt}`})::timestamptz <= now(), true)`,
|
||||
sql`NOT EXISTS (SELECT 1 FROM heartbeat_runs live_issue_run
|
||||
WHERE live_issue_run.company_id = ${issues.companyId}
|
||||
AND (live_issue_run.context_snapshot->>'issueId' = ${issues.id}::text
|
||||
@@ -2240,17 +2266,29 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${String(wake.payload?.issueId)}`,
|
||||
or(isNull(heartbeatRuns.nativeIssueId), sql`${heartbeatRuns.nativeIssueId}::text = ${String(wake.payload?.issueId)}`),
|
||||
)).orderBy(desc(heartbeatRuns.createdAt), desc(heartbeatRuns.id)).limit(1);
|
||||
await db.update(agentWakeupRequests).set({ updatedAt: new Date() }).where(and(
|
||||
if (!wake.idempotencyKey?.startsWith("chat-inbound:")) await db.update(agentWakeupRequests).set({ updatedAt: new Date() }).where(and(
|
||||
eq(agentWakeupRequests.id, wake.id), eq(agentWakeupRequests.status, "deferred_issue_execution"),
|
||||
));
|
||||
if (!latest || !latest.finishedAt || !isHeartbeatRunTerminalStatus(latest.status)) continue;
|
||||
if (latest.runtimeMode !== "legacy" && latest.runtimeMode !== "native") continue;
|
||||
if (wake.idempotencyKey?.startsWith("chat-inbound:")) {
|
||||
await resumeDeferredChatWake(db, { companyId: wake.companyId, agentId: wake.agentId,
|
||||
issueId: String(wake.payload?.issueId), requestId: wake.id }).catch(err => {
|
||||
scope.onError?.(err);
|
||||
logger.warn({ requestId: wake.id }, "saved chat source could not resume after recovery");
|
||||
});
|
||||
const chatScope = { companyId: wake.companyId, issueId: String(wake.payload?.issueId), requestId: wake.id };
|
||||
await resumeDeferredChatWake(db, { ...chatScope, agentId: wake.agentId, recoverySweep: true })
|
||||
.then(decline => decline ?? null, err => err instanceof PersistedExecutionWaitRefusal ? null : deferredChatWakeDeclineForError(err))
|
||||
.then(async decline => {
|
||||
if (!decline) {
|
||||
if (wake.payload?.[DEFERRED_CHAT_WAKE_RETRY_KEY]) await clearDeferredChatWakeRetry(db, chatScope);
|
||||
return;
|
||||
}
|
||||
const recorded = await recordDeferredChatWakeDecline(db, chatScope, decline);
|
||||
if (!recorded) return;
|
||||
logger.warn({ requestId: wake.id, reason: recorded.reason, outcome: recorded.outcome, attempts: recorded.attempts,
|
||||
silent: "silent" in recorded ? recorded.silent : undefined }, "saved chat source could not resume after recovery");
|
||||
if (recorded.outcome === "retry") scope.onDeferredDeadline?.(recorded.nextAttemptAt);
|
||||
}).catch(err => {
|
||||
scope.onError?.(err);
|
||||
logger.warn({ err, requestId: wake.id }, "saved chat source could not record its resume outcome");
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const releaseSource = `${latest.companyId}:${String(wake.payload?.issueId)}:${latest.id}:${latest.sourceVersion}`;
|
||||
|
||||
@@ -2888,8 +2888,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
const shouldRetry =
|
||||
!await pendingCaseHandoffForRun(db, run.id, run.companyId) &&
|
||||
// Process loss spends the durable failure retry budget that
|
||||
// enqueueProcessLossRetry schedules against (execution-semantics
|
||||
// "Shutdown, process loss, and provider failure"). Checking it here
|
||||
// enqueueProcessLossRetry schedules against. Checking it here
|
||||
// keeps "retrying once" honest and lets an exhausted chain fall
|
||||
// through to the interaction continuation path below.
|
||||
// A conversation run that a restart ended draws on the server-restart
|
||||
|
||||
@@ -716,14 +716,14 @@ describe.skipIf(!support.supported)("heartbeat runtime execution boundary", () =
|
||||
expectCleanup(input);
|
||||
});
|
||||
|
||||
it("logs a pointer to the docs when a same-run retry follows a failed attachment", async () => {
|
||||
it("logs an explanation when a same-run retry follows a failed attachment", async () => {
|
||||
const { input, run } = await fixture(true);
|
||||
await db.update(heartbeatRuns).set({ nativeIssueId: input.task.issueId }).where(eq(heartbeatRuns.id, run.id));
|
||||
await db.insert(nativeRunFinalizations).values({ companyId: run.companyId, issueId: input.task.issueId!, runId: run.id, phase: "retryable_failure" });
|
||||
const error = new Error('native_session_recovery_failed: Error: PRP command run.attach failed: {"result":{"message":"run.attach requires a settled Codex provider session: active_turn"}}');
|
||||
vi.mocked(executePaperclipNativeSession).mockRejectedValueOnce(error);
|
||||
await expect(executeHeartbeatRuntime(db, input)).rejects.toMatchObject({ name: "NativeSessionResumeScheduledError", original: error });
|
||||
expect(input.output.onLog).toHaveBeenCalledWith("stderr", expect.stringContaining("doc/execution-semantics.md#session-settlement-after-a-run"));
|
||||
expect(input.output.onLog).toHaveBeenCalledWith("stderr", expect.stringContaining("A later run may start a new provider thread."));
|
||||
expect(input.output.onLog).toHaveBeenCalledWith("stderr", expect.stringContaining("run.attach requires a settled Codex provider session: active_turn"));
|
||||
expectCleanup(input);
|
||||
});
|
||||
|
||||
@@ -36,6 +36,7 @@ export function queueIssueAssignmentWakeup(input: {
|
||||
/** Latest issue comment that caused this wakeup. Included in both payload
|
||||
* and context so the heartbeat can build the exact turn that was requested. */
|
||||
wakeCommentId?: string | null;
|
||||
wakeCommentIds?: string[];
|
||||
/** Closed, server-derived omission counts for provider attachments on the
|
||||
* exact wake comment. These are prompt diagnostics, never authorization. */
|
||||
attachmentOmissionReasons?: Record<string, number> | null;
|
||||
@@ -69,6 +70,7 @@ export function queueIssueAssignmentWakeup(input: {
|
||||
source: input.contextSource,
|
||||
...(input.taskKey ? { taskKey: input.taskKey } : {}),
|
||||
...(input.wakeCommentId ? { wakeCommentId: input.wakeCommentId } : {}),
|
||||
...(input.wakeCommentIds?.length ? { wakeCommentIds: input.wakeCommentIds } : {}),
|
||||
...(input.chatConversationId ? { chatConversationId: input.chatConversationId } : {}),
|
||||
...(input.wakeCommentId && input.attachmentOmissionReasons
|
||||
? {
|
||||
|
||||
@@ -343,8 +343,12 @@ export function issueReferenceService(db: Db) {
|
||||
}
|
||||
}
|
||||
|
||||
async function listIssueReferenceSummary(issueId: string, dbOrTx: any = db): Promise<IssueRelatedWorkSummary> {
|
||||
const issue = await issueById(issueId, dbOrTx);
|
||||
async function listIssueReferenceSummary(
|
||||
issueId: string,
|
||||
dbOrTx: any = db,
|
||||
known?: { companyId: string },
|
||||
): Promise<IssueRelatedWorkSummary> {
|
||||
const issue = known ? { id: issueId, companyId: known.companyId } : await issueById(issueId, dbOrTx);
|
||||
if (!issue) throw notFound("Issue not found");
|
||||
|
||||
const [outboundRows, inboundRows] = await Promise.all([
|
||||
|
||||
@@ -3429,7 +3429,10 @@ export function issueThreadInteractionService(
|
||||
woken,
|
||||
};
|
||||
},
|
||||
listForIssue: async (issueId: string) => {
|
||||
listForIssue: async (
|
||||
issueId: string,
|
||||
known?: { status: string; companyId: string; executionWorkspaceId: string | null },
|
||||
) => {
|
||||
const [rows, issue] = await Promise.all([
|
||||
db
|
||||
.select()
|
||||
@@ -3439,7 +3442,7 @@ export function issueThreadInteractionService(
|
||||
asc(issueThreadInteractions.createdAt),
|
||||
asc(issueThreadInteractions.id),
|
||||
),
|
||||
db
|
||||
known ? { status: known.status, companyId: known.companyId, executionWorkspaceId: known.executionWorkspaceId } : db
|
||||
.select({
|
||||
status: issues.status,
|
||||
companyId: issues.companyId,
|
||||
|
||||
@@ -9124,10 +9124,9 @@ export function issueService(db: Db) {
|
||||
issue: Pick<IssueRow, "id" | "companyId" | "updatedAt">,
|
||||
userId: string,
|
||||
) => {
|
||||
const [[activity], [archive]] = await Promise.all([
|
||||
lastActivityStatsForIssues(db, issue.companyId, [issue.id]),
|
||||
inboxArchiveRowsForIssues(db, issue.companyId, userId, [issue.id]),
|
||||
]);
|
||||
const [archive] = await inboxArchiveRowsForIssues(db, issue.companyId, userId, [issue.id]);
|
||||
if (!archive) return activeInboxArchiveFields(archive, issue.updatedAt);
|
||||
const [activity] = await lastActivityStatsForIssues(db, issue.companyId, [issue.id]);
|
||||
const lastActivityAt =
|
||||
latestIssueActivityAt(
|
||||
issue.updatedAt,
|
||||
@@ -9215,8 +9214,8 @@ export function issueService(db: Db) {
|
||||
return getIssueByIdentifier(identifier);
|
||||
},
|
||||
|
||||
getCurrentScheduledRetry: async (issueId: string) => {
|
||||
const issue = await db
|
||||
getCurrentScheduledRetry: async (issueId: string, known?: { companyId: string }) => {
|
||||
const issue = known ? { id: issueId, companyId: known.companyId } : await db
|
||||
.select({ id: issues.id, companyId: issues.companyId })
|
||||
.from(issues)
|
||||
.where(eq(issues.id, issueId))
|
||||
@@ -9225,8 +9224,8 @@ export function issueService(db: Db) {
|
||||
return getCurrentScheduledRetryForIssue(issue.id, issue.companyId);
|
||||
},
|
||||
|
||||
getRelationSummaries: async (issueId: string) => {
|
||||
const issue = await db
|
||||
getRelationSummaries: async (issueId: string, known?: { companyId: string }) => {
|
||||
const issue = known ? { id: issueId, companyId: known.companyId } : await db
|
||||
.select({ id: issues.id, companyId: issues.companyId })
|
||||
.from(issues)
|
||||
.where(eq(issues.id, issueId))
|
||||
@@ -14633,9 +14632,12 @@ export function issueService(db: Db) {
|
||||
|
||||
findMentionedProjectIds: async (
|
||||
issueId: string,
|
||||
opts?: { includeCommentBodies?: boolean },
|
||||
opts?: {
|
||||
includeCommentBodies?: boolean;
|
||||
issue?: { companyId: string; title: string; description: string | null };
|
||||
},
|
||||
) => {
|
||||
const issue = await db
|
||||
const issue = opts?.issue ?? await db
|
||||
.select({
|
||||
companyId: issues.companyId,
|
||||
title: issues.title,
|
||||
@@ -14686,7 +14688,7 @@ export function issueService(db: Db) {
|
||||
return [...mentionedIds].filter((projectId) => valid.has(projectId));
|
||||
},
|
||||
|
||||
getAncestors: async (issueId: string) => {
|
||||
getAncestors: async (issueId: string, known?: { parentId: string | null }) => {
|
||||
const raw: Array<{
|
||||
id: string;
|
||||
identifier: string | null;
|
||||
@@ -14698,44 +14700,56 @@ export function issueService(db: Db) {
|
||||
projectId: string | null;
|
||||
goalId: string | null;
|
||||
}> = [];
|
||||
const visited = new Set<string>([issueId]);
|
||||
const start = await db
|
||||
.select()
|
||||
.from(issues)
|
||||
.where(eq(issues.id, issueId))
|
||||
.then((r) => r[0] ?? null);
|
||||
let currentId = start?.parentId ?? null;
|
||||
while (currentId && !visited.has(currentId) && raw.length < 50) {
|
||||
visited.add(currentId);
|
||||
const parent = await db
|
||||
.select({
|
||||
id: issues.id,
|
||||
identifier: issues.identifier,
|
||||
title: issues.title,
|
||||
description: issues.description,
|
||||
status: issues.status,
|
||||
priority: issues.priority,
|
||||
assigneeAgentId: issues.assigneeAgentId,
|
||||
projectId: issues.projectId,
|
||||
goalId: issues.goalId,
|
||||
parentId: issues.parentId,
|
||||
})
|
||||
const firstParentId = known
|
||||
? known.parentId
|
||||
: await db
|
||||
.select({ parentId: issues.parentId })
|
||||
.from(issues)
|
||||
.where(eq(issues.id, currentId))
|
||||
.then((r) => r[0] ?? null);
|
||||
if (!parent) break;
|
||||
raw.push({
|
||||
id: parent.id,
|
||||
identifier: parent.identifier ?? null,
|
||||
title: parent.title,
|
||||
description: parent.description ?? null,
|
||||
status: parent.status,
|
||||
priority: parent.priority,
|
||||
assigneeAgentId: parent.assigneeAgentId ?? null,
|
||||
projectId: parent.projectId ?? null,
|
||||
goalId: parent.goalId ?? null,
|
||||
});
|
||||
currentId = parent.parentId ?? null;
|
||||
.where(eq(issues.id, issueId))
|
||||
.then((r) => r[0]?.parentId ?? null);
|
||||
if (firstParentId && firstParentId !== issueId) {
|
||||
const chain = await db.execute<{
|
||||
id: string;
|
||||
identifier: string | null;
|
||||
title: string;
|
||||
description: string | null;
|
||||
status: string;
|
||||
priority: string;
|
||||
assignee_agent_id: string | null;
|
||||
project_id: string | null;
|
||||
goal_id: string | null;
|
||||
}>(sql`
|
||||
with recursive chain as (
|
||||
select i.id, i.identifier, i.title, i.description, i.status, i.priority,
|
||||
i.assignee_agent_id, i.project_id, i.goal_id, i.parent_id,
|
||||
1 as depth, array[${issueId}::uuid, i.id] as path
|
||||
from ${issues} i
|
||||
where i.id = ${firstParentId}::uuid
|
||||
union all
|
||||
select p.id, p.identifier, p.title, p.description, p.status, p.priority,
|
||||
p.assignee_agent_id, p.project_id, p.goal_id, p.parent_id,
|
||||
chain.depth + 1, chain.path || p.id
|
||||
from chain
|
||||
join ${issues} p on p.id = chain.parent_id
|
||||
where chain.depth < 50 and not (p.id = any(chain.path))
|
||||
)
|
||||
select id, identifier, title, description, status, priority, assignee_agent_id, project_id, goal_id
|
||||
from chain
|
||||
order by depth
|
||||
`);
|
||||
for (const parent of chain) {
|
||||
raw.push({
|
||||
id: parent.id,
|
||||
identifier: parent.identifier ?? null,
|
||||
title: parent.title,
|
||||
description: parent.description ?? null,
|
||||
status: parent.status,
|
||||
priority: parent.priority,
|
||||
assigneeAgentId: parent.assignee_agent_id ?? null,
|
||||
projectId: parent.project_id ?? null,
|
||||
goalId: parent.goal_id ?? null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Batch-fetch referenced projects and goals
|
||||
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, companies, companyMemberships, completionContracts, createDb, heartbeatRuns, issues,
|
||||
nativeRunFinalizations } from "@paperclipai/db";
|
||||
import type { NativeExecutionInputV1 } from "@paperclipai/paperclip-runner";
|
||||
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
|
||||
|
||||
const provider = vi.hoisted(() => ({ execute: vi.fn() }));
|
||||
vi.mock("../../vendor/paperclip-runner/index.js", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("../../vendor/paperclip-runner/index.js")>()),
|
||||
executeNativeSession: provider.execute,
|
||||
}));
|
||||
|
||||
import { executePaperclipNativeSession } from "./native-session-executor.js";
|
||||
import { buildNativeCompletionContract } from "./completion-contracts.js";
|
||||
import { prepareNativeHeartbeatRun } from "./prepare-native-run.js";
|
||||
|
||||
// QA Cloud: a fresh assignment run failed before its first provider turn with
|
||||
// "Database query failed (40P01)" and was left as a task that needed
|
||||
// reconciliation. The coordinator claim locks the coordinator row, then the
|
||||
// run row. A writer that holds the run row and then asks for the coordinator
|
||||
// closes a lock cycle; PostgreSQL aborts the claim, the waiter that checks
|
||||
// first. The aborted claim rolled back whole, yet it failed the run.
|
||||
describe("native coordinator claim under a run-then-coordinator lock cycle", () => {
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
const companyId = randomUUID();
|
||||
const agentId = randomUUID();
|
||||
|
||||
beforeAll(async () => {
|
||||
temporary = await startEmbeddedPostgresTestDatabase("native-claim-deadlock-");
|
||||
db = createDb(temporary.connectionString);
|
||||
await db.insert(companies).values({ id: companyId, name: "Claim deadlock", issuePrefix: "NCD" });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "OpenCode agent", status: "active", adapterType: "paperclip_runner",
|
||||
adapterConfig: { provider: "opencode", model: "openrouter/test-model" } });
|
||||
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "board-user", status: "active", membershipRole: "member" });
|
||||
});
|
||||
afterAll(async () => { await temporary?.cleanup(); });
|
||||
|
||||
it("retries a claim that lost a deadlock and reaches the provider", async () => {
|
||||
const issueId = randomUUID();
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Write the brief", status: "todo", workMode: "standard",
|
||||
assigneeAgentId: agentId, createdByUserId: "board-user", responsibleUserId: "board-user" });
|
||||
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
||||
const runId = randomUUID();
|
||||
const [run] = await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", runtimeMode: "native",
|
||||
nativeIssueId: issueId, responsibleUserId: "board-user", invocationSource: "assignment", triggerDetail: "system",
|
||||
contextSnapshot: { issueId } }).returning();
|
||||
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
|
||||
const native = await prepareNativeHeartbeatRun({ db, run, issue, environmentLeaseId: randomUUID() });
|
||||
const [contract] = await db.select().from(completionContracts).where(eq(completionContracts.issueId, issueId));
|
||||
// Runtime selection leaves the coordinator unclaimed: observed, attempt 0.
|
||||
await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed" });
|
||||
const execution: NativeExecutionInputV1 = {
|
||||
schema: "paperclip.native-execution-input.v1",
|
||||
binding: { companyId, runId, issueId, agentId, executionWorkspaceId: runId },
|
||||
provider: { kind: "opencode", model: "openrouter/test-model" },
|
||||
task: { identifier: issueId, title: issue.title, description: null, prompt: "Write the brief.", workMode: "standard" },
|
||||
workspace: { cwd: "/tmp", repoUrl: null, repoRef: null, branchName: null },
|
||||
session: { normalizedSessionId: native.normalizedSessionId, driverKind: "opencode_server", protocolVersion: 1, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } },
|
||||
completionContract: { id: contract.id, sha256: contract.canonicalSha256, schemaVersion: "paperclip.completion-contract.v1",
|
||||
contract: buildNativeCompletionContract(issue, { revision: contract.revision }) },
|
||||
interactionResponses: [], credentialBindings: [],
|
||||
};
|
||||
await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution } }).where(eq(heartbeatRuns.id, runId));
|
||||
|
||||
// Another writer holds the run row (as a run update does) before the claim
|
||||
// starts. Once the claim holds the coordinator and waits for the run row,
|
||||
// the writer asks for the coordinator: a deadlock. The writer's own
|
||||
// detector waits longer, so PostgreSQL always aborts the claim.
|
||||
let writerBlockedClaim = false;
|
||||
let releaseWriter!: () => void;
|
||||
const writerHoldsRun = new Promise<void>(resolve => { releaseWriter = resolve; });
|
||||
const writer = db.transaction(async tx => {
|
||||
await tx.execute(sql`set local deadlock_timeout = '10s'`);
|
||||
await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)).for("no key update");
|
||||
const writerPid = (await tx.execute<{ pid: number }>(sql`select pg_backend_pid() as pid`))[0]!.pid;
|
||||
releaseWriter();
|
||||
for (let poll = 0; poll < 1_000 && !writerBlockedClaim; poll++) {
|
||||
const rows = (await db.execute(
|
||||
sql`select 1 from pg_stat_activity where ${writerPid} = any(pg_blocking_pids(pid))`,
|
||||
)) as unknown as Array<unknown>;
|
||||
if (rows[0]) writerBlockedClaim = true;
|
||||
else await new Promise(resolve => setTimeout(resolve, 10));
|
||||
}
|
||||
await tx.select({ runId: nativeRunFinalizations.runId }).from(nativeRunFinalizations)
|
||||
.where(eq(nativeRunFinalizations.runId, runId)).for("update");
|
||||
});
|
||||
await writerHoldsRun;
|
||||
|
||||
provider.execute.mockReset().mockRejectedValue(new Error("provider_reached_after_claim"));
|
||||
const outcome = await executePaperclipNativeSession({ db, execution, runnerInstanceId: native.runnerInstanceId, backend: {
|
||||
descriptor: async () => { throw new Error("Unexpected provider call"); },
|
||||
openSession: async () => { throw new Error("Unexpected provider call"); },
|
||||
} }).then(() => null, (error: unknown) => error);
|
||||
await writer;
|
||||
|
||||
expect(writerBlockedClaim).toBe(true);
|
||||
expect((outcome as { cause?: { code?: string } } | null)?.cause?.code).not.toBe("40P01");
|
||||
expect(provider.execute).toHaveBeenCalledTimes(1);
|
||||
const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId));
|
||||
expect(coordinator.attempt).toBe(1);
|
||||
}, 120_000);
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import type { SQL } from "drizzle-orm";
|
||||
import { PgDialect } from "drizzle-orm/pg-core";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { startNativeSessionExecutionLeaseRenewal } from "./native-execution-lease.js";
|
||||
import { startServerMetrics, stopServerMetrics } from "../server-metrics.js";
|
||||
|
||||
const dialect = new PgDialect();
|
||||
|
||||
@@ -134,6 +135,24 @@ describe("native execution renewal ownership", () => {
|
||||
expect(returning).toHaveBeenCalledTimes(1);
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
it("counts a renewal deadline that passes as a missed lease renewal for the server metrics", async () => {
|
||||
const metrics = startServerMetrics();
|
||||
try {
|
||||
vi.useFakeTimers();
|
||||
const { input, returning } = fixture();
|
||||
let complete!: (value: { runId: string }[]) => void;
|
||||
returning.mockImplementationOnce(() => new Promise(resolve => { complete = resolve; }));
|
||||
const guard = startNativeSessionExecutionLeaseRenewal(input);
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(metrics.snapshot().leaseRenewalsMissed).toBe(0);
|
||||
await vi.advanceTimersByTimeAsync(30_000);
|
||||
expect(metrics.snapshot().leaseRenewalsMissed).toBe(1);
|
||||
complete([{ runId: "run" }]);
|
||||
await expect(guard.stop()).rejects.toThrow("native_session_lease_renewal_deadline");
|
||||
} finally {
|
||||
stopServerMetrics(metrics);
|
||||
}
|
||||
});
|
||||
it("hands preparation renewal to the same owner's executor at the next attempt", async () => {
|
||||
vi.useFakeTimers();
|
||||
const { input, returning } = fixture();
|
||||
|
||||
@@ -5,6 +5,7 @@ import { currentNativeControllerIdentity, type NativeControllerIdentity } from "
|
||||
import { OPERATOR_ATTESTED_CONTROLLER_HOST } from "./native-controller-host-recovery.js";
|
||||
import { NATIVE_OWNERSHIP_UNVERIFIED_ERROR_CODE } from "./native-runner-ownership.js";
|
||||
import { REMOTE_CONTROLLER_LEASE_MS } from "./native-runner-recovery-contract.js";
|
||||
import { recordMissedLeaseRenewal } from "../server-metrics.js";
|
||||
|
||||
export const NATIVE_SESSION_EXECUTION_LEASE_TTL_MS = 20 * 60_000;
|
||||
const NATIVE_SESSION_EXECUTION_LEASE_RENEW_INTERVAL_MS = 5 * 60_000;
|
||||
@@ -613,7 +614,10 @@ export function startNativeSessionExecutionLeaseRenewal(input: RenewalInput): Na
|
||||
state!.loss = Promise.resolve().then(state!.input.onLost).catch(() => undefined);
|
||||
};
|
||||
const deadline = (delay: number) => {
|
||||
const timer = setTimeout(() => lose(new Error("native_session_lease_renewal_deadline")), Math.max(0, delay));
|
||||
const timer = setTimeout(() => {
|
||||
recordMissedLeaseRenewal();
|
||||
lose(new Error("native_session_lease_renewal_deadline"));
|
||||
}, Math.max(0, delay));
|
||||
timer.unref?.();
|
||||
return timer;
|
||||
};
|
||||
|
||||
@@ -11131,11 +11131,25 @@ async function executePaperclipNativeSessionAttempt(
|
||||
let claimedStartupContext: NativeExecutionContext | undefined;
|
||||
let freshClaimAttempt: number | undefined;
|
||||
let scheduledResumeContinuation = false;
|
||||
const startupContextBeforeClaim = nativeSessionStartups.get(input.execution.binding.runId)?.executionContext;
|
||||
try {
|
||||
attempt = await trace.measure(
|
||||
"native.coordinator.claim",
|
||||
() =>
|
||||
input.db.transaction(async (tx) => {
|
||||
// The claim locks the coordinator, then the run row. A writer holding
|
||||
// those rows in the other order can deadlock it (40P01); a lock wait
|
||||
// can also time out (55P03). Either rolls the claim back whole and it
|
||||
// starts no provider work, so a fresh attempt re-reads and re-proves
|
||||
// everything. Without it the run failed before its first turn and the
|
||||
// task needed reconciliation.
|
||||
retryTransientLockContention(() => input.db.transaction(async (tx) => {
|
||||
// A rolled-back attempt may have opened a startup context; drop it.
|
||||
if (claimedStartupContext) {
|
||||
claimedStartupContext.finish();
|
||||
claimedStartupContext = undefined;
|
||||
const startup = nativeSessionStartups.get(input.execution.binding.runId);
|
||||
if (startup) startup.executionContext = startupContextBeforeClaim;
|
||||
}
|
||||
const coordinator = await tx
|
||||
.select()
|
||||
.from(nativeRunFinalizations)
|
||||
@@ -11369,7 +11383,7 @@ async function executePaperclipNativeSessionAttempt(
|
||||
})
|
||||
.where(eq(heartbeatRuns.id, coordinator.runId));
|
||||
return nextAttempt;
|
||||
}).then(async claimedAttempt => {
|
||||
})).then(async claimedAttempt => {
|
||||
const startup = nativeSessionStartups.get(input.execution.binding.runId);
|
||||
if (!startup) throw new Error("native_session_startup_owner_missing");
|
||||
startup.leaseOwner = leaseOwner;
|
||||
@@ -16643,6 +16657,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
configuredEnvironment: taskConfiguredEnvironment,
|
||||
releaseResumeVersion: description.releaseResumeVersion,
|
||||
resumeLaunchInputsVersion: description.resumeLaunchInputsVersion,
|
||||
launchDigestVersion: description.launchDigestVersion,
|
||||
authorityRunId: description.releaseResumeVersion === 1 ? input.execution.binding.runId : undefined,
|
||||
releasedSource: input.remoteWarmRecovery?.releasedSource,
|
||||
sessionHandoff: !!input.remoteWarmRecovery?.portableSourceTaskId,
|
||||
|
||||
@@ -2,6 +2,7 @@ import { nativeResponsePresentationWork } from "./native-response-presentation-w
|
||||
import { resolveExternalTestDatabaseUrl } from "../../__tests__/helpers/external-test-database.js";
|
||||
import { plugins } from "@paperclipai/db";
|
||||
import { readTaskPanelActivations } from "../plugin-task-panels.js";
|
||||
import { startServerMetrics, stopServerMetrics } from "../server-metrics.js";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { and, asc, eq, sql } from "drizzle-orm";
|
||||
import { createHash, generateKeyPairSync, randomUUID } from "node:crypto";
|
||||
@@ -548,6 +549,21 @@ describe("PaperclipControlPlanePort conformance", () => {
|
||||
payload: { itemId: "ending-item", kind: "commandExecution", text: "***REDACTED***" } }]);
|
||||
});
|
||||
|
||||
it("records the lateness of each committed runner event once for the server metrics", async () => {
|
||||
const metrics = startServerMetrics();
|
||||
try {
|
||||
const f = await terminalObserverFixture();
|
||||
const event = { ...f.event, emittedAt: new Date(Date.now() - 2_000).toISOString() };
|
||||
await f.port.appendEvent(event);
|
||||
await f.port.appendEvent(event);
|
||||
const snapshot = metrics.snapshot();
|
||||
expect(snapshot.runEventLatenessSamples).toBe(1);
|
||||
expect(snapshot.runEventLatenessP99Ms).toBeGreaterThanOrEqual(1_900);
|
||||
} finally {
|
||||
stopServerMetrics(metrics);
|
||||
}
|
||||
});
|
||||
|
||||
it("completes a native run when a bound secret equals a protocol word", async () => {
|
||||
const observed: PrpEvent[] = [];
|
||||
const f = await terminalObserverFixture({ secrets: ["interrupted", "completed", "succeeded", "satisfied"],
|
||||
@@ -1020,6 +1036,27 @@ describe("PaperclipControlPlanePort conformance", () => {
|
||||
return { port, binding, identity, runnerId, event, stored, streamed };
|
||||
};
|
||||
|
||||
it("measures every row of a streaming batch from the batch commit, not after earlier rows' observers", async () => {
|
||||
const metrics = startServerMetrics();
|
||||
const recorded: number[] = [];
|
||||
const record = metrics.recordRunEventLatenessMs.bind(metrics);
|
||||
metrics.recordRunEventLatenessMs = (ms: number) => { recorded.push(ms); record(ms); };
|
||||
try {
|
||||
const f = await streamingFixture({ streamingBatchMs: 600_000, onCommittedEvent: async (event) => {
|
||||
if (event.sourceSeq === 2) await new Promise(resolve => setTimeout(resolve, 1_200));
|
||||
} });
|
||||
await f.port.appendEvent(f.event(1), f.streamed);
|
||||
const deltas = [2, 3, 4].map(sourceSeq => f.port.appendEvent(f.event(sourceSeq), f.streamed));
|
||||
await f.port.appendEvent(f.event(5, "tool.execution.started"));
|
||||
await Promise.all(deltas);
|
||||
const batch = recorded.slice(1, 4);
|
||||
expect(batch).toHaveLength(3);
|
||||
expect(Math.max(...batch) - Math.min(...batch)).toBeLessThan(500);
|
||||
} finally {
|
||||
stopServerMetrics(metrics);
|
||||
}
|
||||
});
|
||||
|
||||
it("commits the first text delta at once and later deltas in one batch before the next other event", async () => {
|
||||
const committed: number[] = [];
|
||||
// A timer this long would time the test out: only the first delta and the
|
||||
|
||||
@@ -39,6 +39,7 @@ import { eligibleNativeTaskSessionPublication, publishNativeTaskSessionInTransac
|
||||
import { lockNativeRunnerCheckpointOwner, nativeRunnerCheckpointOwnerLock, validateNativeRunnerCheckpointOwner, inspectNativeRunnerUpgradeHeader, type NativeRunnerCheckpointOwner } from "./native-runner-checkpoint.js";
|
||||
import { crashPoint } from "@paperclipai/shared/crash-points";
|
||||
import { NATIVE_PROVIDER_DURABLE_EVENT_TYPES } from "./native-retired-backup-source.js";
|
||||
import { recordRunEventCommitted } from "../server-metrics.js";
|
||||
|
||||
export interface PaperclipControlPlaneBinding {
|
||||
companyId: string;
|
||||
@@ -476,10 +477,11 @@ export class PaperclipControlPlanePort implements ControlPlanePort {
|
||||
this.#assertActive(options);
|
||||
const pendingObservation = this.#deferredEventObservers.get(observerKey);
|
||||
const persisted = await appendHeartbeatRunEvent(this.#db, input);
|
||||
const committedAtMs = Date.now();
|
||||
this.#assertActive(options);
|
||||
const persistenceEndedAt = persistenceStartedAt + performance.now() - persistenceClock;
|
||||
let observation = pendingObservation ?? this.#deferredEventObservers.get(observerKey);
|
||||
if (!observation) observation = this.#observePersistedEvent(event, persisted, persistenceStartedAt, persistenceEndedAt);
|
||||
if (!observation) observation = this.#observePersistedEvent(event, persisted, persistenceStartedAt, persistenceEndedAt, committedAtMs);
|
||||
if (options?.deferPostCommitObservers) {
|
||||
this.#deferredEventObservers.set(observerKey, observation);
|
||||
void observation.then(() => {
|
||||
@@ -503,9 +505,11 @@ export class PaperclipControlPlanePort implements ControlPlanePort {
|
||||
persisted: AppendHeartbeatRunEventResult,
|
||||
persistenceStartedAt: number,
|
||||
persistenceEndedAt: number,
|
||||
committedAtMs: number,
|
||||
): Promise<void> {
|
||||
try { await this.#onEventPersistence?.(event, persistenceStartedAt, persistenceEndedAt); } catch {}
|
||||
if (persisted.disposition === "committed") {
|
||||
recordRunEventCommitted(event.emittedAt, committedAtMs);
|
||||
try {
|
||||
publishLiveEvent({
|
||||
companyId: this.#binding.companyId,
|
||||
@@ -590,11 +594,12 @@ export class PaperclipControlPlanePort implements ControlPlanePort {
|
||||
for (const pending of batch) pending.reject(error);
|
||||
return;
|
||||
}
|
||||
const committedAtMs = Date.now();
|
||||
for (const [index, pending] of batch.entries()) {
|
||||
const persisted = receipts[index]!;
|
||||
const endedAt = pending.startedAtMs + performance.now() - pending.startedClock;
|
||||
try {
|
||||
await this.#observePersistedEvent(pending.event, persisted, pending.startedAtMs, endedAt);
|
||||
await this.#observePersistedEvent(pending.event, persisted, pending.startedAtMs, endedAt, committedAtMs);
|
||||
} catch (error) {
|
||||
pending.reject(error);
|
||||
continue;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { RunnerProviderLaunchRequirements } from "@paperclipai/paperclip-runner";
|
||||
import type { RunnerProcessLaunchSpec } from "../../vendor/paperclip-runner/index.js";
|
||||
import { runnerLaunchPreparationDigest, runnerLaunchRunDigest, type RunnerProcessLaunchSpec } from "../../vendor/paperclip-runner/index.js";
|
||||
import { createPluginRunnerTaskOwner } from "./plugin-runner-task.js";
|
||||
import { NativeExecutionContext } from "./native-execution-context.js";
|
||||
|
||||
@@ -831,6 +831,66 @@ it.each(["codex", "claude"])("reuses a warm %s process across run authorities wi
|
||||
expect(nextTask.mock.calls.filter(([op])=>op.kind==="stop")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["advertised", 1 as const],
|
||||
["not advertised", undefined],
|
||||
] as const)("launch digests are sent on prepare only when the plugin has %s them", async (_label, version) => {
|
||||
const {task} = provider();
|
||||
ingress.connect.mockReturnValue({ready:Promise.resolve(),close:async()=>{}});
|
||||
const input = {taskId:"task",task,projectIds:[],harness:"codex",projectAuthCheckVersion:1 as const,warmTaskVersion:1 as const,
|
||||
accountIdentity:"account",credentialIdentity:"revision",pollMs:1,launchDigestVersion:version};
|
||||
const owner = createPluginRunnerTaskOwner(input);
|
||||
await prepare(owner, launchRequirements("codex"));
|
||||
const registration = await owner.registration({} as never,"run");
|
||||
const spec = launchSpec(); spec.nativeRunner!.lifecyclePolicy = {mode:"warm",idleTimeoutMs:300000};
|
||||
const handle = owner.launcher(spec); registration.activate(); await registration.ready();
|
||||
const nextIdentity={...requirements.identity,runId:"next-run",turnId:"next-turn",itemId:"next-item"};
|
||||
const nextRegistration=await owner.registration({} as never,"next-run");
|
||||
await owner.driver.prepareLaunch!({...launchRequirements("codex"),identity:nextIdentity});
|
||||
const prepares=task.mock.calls.map(([op])=>op).filter(op=>op.kind==="prepare");
|
||||
expect(prepares).toHaveLength(2);
|
||||
if (version === 1) {
|
||||
const [first, next] = prepares as Array<{preparationDigest?:string;runDigest?:string}>;
|
||||
expect(first.preparationDigest).toBe(runnerLaunchPreparationDigest(launchRequirements("codex")));
|
||||
expect(next.preparationDigest).toBe(first.preparationDigest);
|
||||
expect(first.runDigest).toBe(runnerLaunchRunDigest(first.preparationDigest!, launchRequirements("codex")));
|
||||
expect(next.runDigest).toBe(runnerLaunchRunDigest(first.preparationDigest!, {...launchRequirements("codex"),identity:nextIdentity}));
|
||||
expect(next.runDigest).not.toBe(first.runDigest);
|
||||
} else {
|
||||
for (const op of prepares) expect(op).not.toHaveProperty("preparationDigest");
|
||||
for (const op of prepares) expect(op).not.toHaveProperty("runDigest");
|
||||
}
|
||||
await registration.release(); nextRegistration.activate(); await nextRegistration.ready();
|
||||
await nextRegistration.release(); await nextRegistration.checkpoint("settled"); await handle.completion;
|
||||
});
|
||||
|
||||
it.each([
|
||||
["checked inside prepare", true, ["prepare"]],
|
||||
["left to Core", false, ["prepare", "check_project_auth"]],
|
||||
] as const)("a warm attach whose project authentication is %s makes only the round trips it needs", async (_label, checked, kinds) => {
|
||||
const {task} = provider();
|
||||
ingress.connect.mockReturnValue({ready:Promise.resolve(),close:async()=>{}});
|
||||
const input = {taskId:"task",task,projectIds:[],harness:"codex",projectAuthCheckVersion:1 as const,warmTaskVersion:1 as const,
|
||||
accountIdentity:"account",credentialIdentity:"revision",pollMs:1};
|
||||
const owner = createPluginRunnerTaskOwner(input);
|
||||
await prepare(owner, launchRequirements("codex"));
|
||||
const registration = await owner.registration({} as never,"run");
|
||||
const spec = launchSpec(); spec.nativeRunner!.lifecyclePolicy = {mode:"warm",idleTimeoutMs:300000};
|
||||
const handle = owner.launcher(spec); registration.activate(); await registration.ready();
|
||||
const originalTask=task.getMockImplementation()!;
|
||||
const nextTask=vi.fn(async op=>{
|
||||
const result=await originalTask(op) as Record<string,unknown>;
|
||||
return op.kind === "prepare" && checked ? {...result,projectAuthChecked:true} : result;
|
||||
});
|
||||
owner.rebind({...input,task:nextTask});
|
||||
const nextRegistration=await owner.registration({} as never,"next-run");
|
||||
const nextIdentity={...requirements.identity,runId:"next-run",turnId:"next-turn",itemId:"next-item"};
|
||||
await owner.driver.prepareLaunch!({...launchRequirements("codex"),identity:nextIdentity});
|
||||
expect(nextTask.mock.calls.map(([op])=>op.kind)).toEqual(kinds);
|
||||
await registration.release(); nextRegistration.activate(); await nextRegistration.ready();
|
||||
await nextRegistration.release(); await nextRegistration.checkpoint("settled"); await handle.completion;
|
||||
});
|
||||
|
||||
it.each(["codex", "claude"])("adopts a verified retained %s task without submitting a replacement", async harness => {
|
||||
const {task}=provider();
|
||||
ingress.connect.mockReturnValue({ready:Promise.resolve(),close:async()=>{}});
|
||||
|
||||
@@ -3,7 +3,7 @@ import { createHash } from "node:crypto";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { environmentTaskOperationSchema, environmentTaskResultSchema, parseEnvironmentTaskResult, type PluginEnvironmentTaskOperation, type PluginEnvironmentTaskResult, type PluginEnvironmentTaskCredential } from "@paperclipai/plugin-sdk";
|
||||
import type { RunnerIngressEndpoint } from "@paperclipai/adapter-utils/runner-connectivity";
|
||||
import { RUNNER_PRP_PROTOCOL_MIN, RUNNER_PRP_PROTOCOL_MAX, type RunnerProcessHandle, type RunnerProcessLaunchSpec,
|
||||
import { RUNNER_PRP_PROTOCOL_MIN, RUNNER_PRP_PROTOCOL_MAX, runnerLaunchPreparationDigest, runnerLaunchRunDigest, type RunnerProcessHandle, type RunnerProcessLaunchSpec,
|
||||
type DurablePrpControlPlane, type RunnerExecutionDriver, type RunnerLaunchPreparer, type DurableRecoveryIdentity, type PrpEvent } from "../../vendor/paperclip-runner/index.js";
|
||||
import { connectRunnerPrpIngress } from "../../realtime/runner-prp-outbound.js";
|
||||
import type { NativeExecutionContext } from "./native-execution-context.js";
|
||||
@@ -50,6 +50,7 @@ export function createPluginRunnerTaskOwner(input: {
|
||||
warmTaskVersion?: 1;
|
||||
releaseResumeVersion?: 1;
|
||||
resumeLaunchInputsVersion?: 1;
|
||||
launchDigestVersion?: 1;
|
||||
releasedSource?: DurableRecoveryIdentity;
|
||||
sessionHandoff?: boolean;
|
||||
onResumed?: (identity: DurableRecoveryIdentity) => Promise<void>;
|
||||
@@ -143,7 +144,9 @@ export function createPluginRunnerTaskOwner(input: {
|
||||
if (input.githubBroker && input.githubCredentialBrokerVersion !== 1) {
|
||||
throw new Error("Update the environment plugin to support the GitHub credential broker v1");
|
||||
}
|
||||
const preparationDigest = input.launchDigestVersion === 1 ? runnerLaunchPreparationDigest(requirements) : undefined;
|
||||
const result = await call(environmentTaskOperationSchema.parse({ kind: "prepare", requirements,
|
||||
...(preparationDigest ? { preparationDigest, runDigest: runnerLaunchRunDigest(preparationDigest, requirements) } : {}),
|
||||
...(input.githubBroker ? { githubBroker: input.githubBroker } : {}),
|
||||
projectIds: [...input.projectIds], ...(recovery ? { recovery } : {}),
|
||||
...(input.resumeFrom && (!authorityRunId || !launchIdentity || launchIdentity.runId === authorityRunId || sourceRecovery)
|
||||
@@ -155,7 +158,7 @@ export function createPluginRunnerTaskOwner(input: {
|
||||
if (released || stopRequested) throw new Error("Plugin Runner preparation cancelled");
|
||||
if (result.kind !== "prepared") throw new Error("Plugin Runner preparation unavailable");
|
||||
if (input.projectAuthCheckVersion !== 1) throw new Error("Plugin Runner managed project authentication validation unavailable");
|
||||
if (launched || !result.projectAuthCheckAtSubmit) await checkProjectAuth(result.launch.configurationId);
|
||||
if (!result.projectAuthChecked && (launched || !result.projectAuthCheckAtSubmit)) await checkProjectAuth(result.launch.configurationId);
|
||||
preparedLaunchId = result.launch.configurationId;
|
||||
preparedIdentity = requirements.identity;
|
||||
return result.launch;
|
||||
|
||||
@@ -78,11 +78,11 @@ describe("settled remote warm control evidence", () => {
|
||||
.toBe("provider.notice.recorded x2, session.goal.snapshot x1");
|
||||
});
|
||||
|
||||
it("points a failed attachment at the reviewed docs with its real cause", () => {
|
||||
it("explains a failed attachment with its real cause", () => {
|
||||
const stored = 'native_session_recovery_failed: Error: PRP command run.attach failed: {"commandType":"run.attach","result":{"code":"command_execution_failed","message":"run.attach requires a settled Codex provider session: active_turn"},"status":"failed"}';
|
||||
const pointer = describeFailedAttachment(stored);
|
||||
expect(pointer).toContain("run.attach requires a settled Codex provider session: active_turn");
|
||||
expect(pointer).toContain("https://github.com/paperclipai/paperclip/blob/master/doc/execution-semantics.md#session-settlement-after-a-run");
|
||||
expect(pointer).toContain("A later run may start a new provider thread.");
|
||||
expect(describeFailedAttachment("run.attach requires the restored Codex provider process")).toContain("restored Codex provider process");
|
||||
const quoted = `PRP command run.attach failed: ${JSON.stringify({ result: { message: 'run.attach provider is invalid: unknown "value" here' } })}`;
|
||||
expect(describeFailedAttachment(quoted)).toContain('run.attach provider is invalid: unknown "value" here. A later run');
|
||||
|
||||
@@ -157,16 +157,14 @@ export function describeOwnFailedAttachment(recoveryHistory: unknown): string {
|
||||
return `runner_state_identity_mismatch: prior_attach_failed: ${typeof cause === "string" && cause ? cause : "unknown"}`;
|
||||
}
|
||||
|
||||
const SETTLEMENT_DOC = "https://github.com/paperclipai/paperclip/blob/master/doc/execution-semantics.md#session-settlement-after-a-run";
|
||||
|
||||
/** Points whoever diagnoses a failed attachment at reviewed docs. The stored
|
||||
* failure is already redacted and bounded; other failures produce no pointer. */
|
||||
/** Explains a failed attachment to whoever diagnoses it. The stored failure is
|
||||
* already redacted and bounded; other failures produce no explanation. */
|
||||
export function describeFailedAttachment(failureMessage: unknown): string | null {
|
||||
if (typeof failureMessage !== "string" || !/\brun\.attach (failed|requires)\b/.test(failureMessage)) return null;
|
||||
const encoded = /"message":("(?:[^"\\]|\\.)*")/.exec(failureMessage)?.[1];
|
||||
let cause = failureMessage;
|
||||
try { if (encoded) cause = JSON.parse(encoded) as string; } catch { /* Keep the whole failure. */ }
|
||||
return `This run could not attach to its provider session: ${cause}. A later run may start a new provider thread. See ${SETTLEMENT_DOC}`;
|
||||
return `This run could not attach to its provider session: ${cause}. A later run may start a new provider thread.`;
|
||||
}
|
||||
|
||||
type WarmRecoveryRefusal = "identity_incomplete" | "target_not_resumed_sandbox" | "owner_unsettled" | "execution_mismatch"
|
||||
|
||||
@@ -12,6 +12,15 @@ export function preparedStatements<Shape extends string, Statement>(prepare: (db
|
||||
};
|
||||
}
|
||||
|
||||
export function preparedStatement<Statement>(prepare: (db: Db) => Statement) {
|
||||
const statements = new WeakMap<Db, Statement>();
|
||||
return (db: Db): Statement => {
|
||||
let statement = statements.get(db);
|
||||
if (!statement) statements.set(db, statement = prepare(db));
|
||||
return statement;
|
||||
};
|
||||
}
|
||||
|
||||
export function columnPlaceholder(name: string, column: DriverValueEncoder<unknown, unknown>): Param {
|
||||
return new Param(sql.placeholder(name), column);
|
||||
}
|
||||
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user