mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-06 15:52:22 +01:00
Merge master into fix/mcp-live-claimed-origin
Master now fixes the two ubuntu-26.04 test fixtures (#21787, #21792), so this merge keeps master's versions of those test files. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
4e44f10bd0
125 files changed
+4246
-3488
No files matched your search
@@ -22,11 +22,12 @@ replaying tasks, changing credentials, or deploying instrumentation.
|
||||
| What is a page's real-user load time or SLO on a hosted instance? | Browser `page.load` spans in [browser performance tracing](../../../doc/browser-performance-tracing.md) |
|
||||
| Which CI jobs or test files delay the whole suite? | [CI profiling](references/ci.md) |
|
||||
| How should a trace be organized so a person can understand it? | Human-readable waterfall guidance below and [trace design](references/trace-design.md) |
|
||||
| Where should a new span go? | Instrumentation guidance below and [Observability contract](../../../doc/observability.md) |
|
||||
| Where should a new span go? | Instrumentation guidance below and the code that opens the nearest existing span |
|
||||
|
||||
Repository-relative paths and commands assume the checkout root. The maintained
|
||||
contracts are `doc/observability.md` and `doc/ci-profiling.md`; recheck them and
|
||||
the owning code when a deployed version differs.
|
||||
Repository-relative paths and commands assume the checkout root. Span names and
|
||||
attributes are defined in the code that opens each span; `doc/observability.md`
|
||||
covers only operator setup and Sentry. `doc/ci-profiling.md` covers CI traces.
|
||||
Recheck the owning code when a deployed version differs.
|
||||
|
||||
Keep the repository's three paths distinct:
|
||||
|
||||
@@ -178,7 +179,7 @@ explain one slow scan.
|
||||
Observability must not retry the operation, replace its return/error, change
|
||||
authorization/locks, or break execution when the tracer fails. Preserve root
|
||||
sampling and the explicit endpoint gate even if another library registers an
|
||||
OTel provider. Update `doc/observability.md` when the trace contract changes.
|
||||
OTel provider. Update `doc/observability.md` only when operator setup changes.
|
||||
Run focused tests for endpoint-off behavior, parentage/concurrent-run isolation,
|
||||
failure handling, and the changed seam. Use real exported evidence to claim that
|
||||
new spans appear in Honeycomb; a unit-test tracer alone does not prove ingestion.
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
Read this when adding, reorganizing, or reviewing a waterfall's hierarchy.
|
||||
The goal is to understand the work at a glance, then expand the slow phase to
|
||||
find its cause. Follow the current
|
||||
[Observability contract](../../../../doc/observability.md) for exact names,
|
||||
roots, lifecycle boundaries, sampling, and allowed attributes.
|
||||
find its cause. Follow the code that
|
||||
opens the nearest existing span for exact names, roots, lifecycle boundaries,
|
||||
sampling, and allowed attributes.
|
||||
|
||||
## Organize by the work being done
|
||||
|
||||
|
||||
+1
-1
@@ -122,7 +122,7 @@ and coverage requirements.
|
||||
|
||||
This repo has three separate data paths: Telemetry, Observability, and the run log. See [`rules/data-paths.mdc`](rules/data-paths.mdc) for the full definitions and the review level each path needs.
|
||||
|
||||
If your change adds, removes, or modifies emitted telemetry events, update the [Telemetry Data Contract](packages/shared/src/telemetry/README.md) in the same PR. Keep clients emitting raw dimension values and avoid documenting or relying on private delivery details. If your change adds, removes, or modifies an OpenTelemetry span or span attribute, keep the change inside the closed span-attribute allowlist in `packages/adapter-utils/src/acpx-engine/startup-timing.ts`. If your change adds or modifies a run-log event, update `doc/run-log-events.md` in the same PR.
|
||||
If your change adds, removes, or modifies emitted telemetry events, update the [Telemetry Data Contract](packages/shared/src/telemetry/README.md) in the same PR. Keep clients emitting raw dimension values and avoid documenting or relying on private delivery details. If your change adds, removes, or modifies an OpenTelemetry span or span attribute, keep the change inside the closed span-attribute allowlist in `packages/adapter-utils/src/acpx-engine/startup-timing.ts`. Define a new or changed run-log event where it is written; do not list it in a doc.
|
||||
|
||||
### Paperclip Gates Must Pass
|
||||
|
||||
|
||||
+6
-3
@@ -139,9 +139,12 @@ DATABASE_APPLICATION_NAME=paperclip # application_name in pg_stat_activity; def
|
||||
|
||||
`withDedicatedDbConnection` gives an action exclusive use of one session outside
|
||||
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. At most `DATABASE_DEDICATED_CONNECTION_MAX`
|
||||
`createDb` owner keeps released single-connection clients idle for reuse: always
|
||||
up to `DEDICATED_CONNECTION_IDLE_MAX` (4), and more while idle plus in-use
|
||||
clients stay within `DATABASE_DEDICATED_CONNECTION_MAX`, so a recurring burst
|
||||
reuses the sessions the previous burst opened instead of reconnecting. They
|
||||
follow the same idle timeout and max lifetime as the main pool, so a retained
|
||||
client closes its session after `DATABASE_IDLE_TIMEOUT_SECONDS` without use. 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
|
||||
|
||||
+36
-1716
File diff suppressed because it is too large.
Load diff
@@ -432,7 +432,12 @@ the one origin.
|
||||
above `--spend-threshold-usd` (default $5) unless `--confirm-spend <max USD>`
|
||||
is at least the estimate. It never creates more tasks than the printed cap,
|
||||
and it stops when the model spend the runs record passes the confirmed
|
||||
amount. The defaults are assumptions: $0.02 model spend per task and $0.10
|
||||
amount. It reads recorded spend from Paperclip's cost records for the run's
|
||||
agents (`/api/companies/<id>/costs/by-agent?period=all`); run rows carry no
|
||||
cost. When some cost events have no known price, it prints a warning, grades
|
||||
the run incomplete, and checks the cap against tasks created times the
|
||||
per-task assumption as well. The
|
||||
defaults are assumptions: $0.02 model spend per task and $0.10
|
||||
per sandbox-hour (`PAPERCLIP_SCALE_MODEL_USD_PER_TASK`,
|
||||
`PAPERCLIP_SCALE_SANDBOX_USD_PER_HOUR`). Correct them from the recorded spend
|
||||
of the first run.
|
||||
@@ -451,7 +456,8 @@ A missing source is reported as "not measured", never as zero.
|
||||
| Criterion | Source | Target | Measured from |
|
||||
| --- | --- | --- | --- |
|
||||
| Runs that need Retry | finish line | 0, stops at once | task view offers Retry |
|
||||
| Failed or timed-out runs | harness | 0, stops at once | run list |
|
||||
| Failed runs whose task did not finish by itself | harness | 0 within `--recovery-grace-minutes` (default 15), stops then | run list and task status |
|
||||
| Failed runs, recovered ones included, as a share of ended runs | harness | at most `--max-failed-run-percent` (default 2) | run list |
|
||||
| Tasks at rest but not done | harness | 0 | task status |
|
||||
| Peak running agents | harness | at least 90% of the step | run list |
|
||||
| Board page API requests, p90 | finish line | below 500 ms | a GET mix every 10 s: dashboard, issues, agents, live runs, sidebar badges |
|
||||
@@ -464,6 +470,23 @@ 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 |
|
||||
|
||||
**Failed runs.** Paperclip retries many failed runs by itself (a same-run
|
||||
bootstrap retry, a continuation run). A failed run does not stop the ramp
|
||||
while its task can still finish: the harness keeps going and counts the run as
|
||||
recovered when its task reaches `done`, and as unrecovered when the task comes
|
||||
to rest without being done, offers Retry with no automatic retry scheduled, or
|
||||
has no live run for the recovery grace after the failure. An unrecovered run
|
||||
stops the ramp at once. The share of failed runs, recovered ones included, is
|
||||
graded at the end of each step.
|
||||
|
||||
**Cleanup.** The harness reads each agent by id (a terminated agent leaves the
|
||||
company's agent list) and deletes it only after Paperclip reports its
|
||||
termination complete (`lifecycleState` `terminated`). An agent Paperclip keeps
|
||||
for its cost history stays terminated. The result names the agents still
|
||||
terminating and the sandbox leases still active after the waits, and counts the
|
||||
leases that released while it waited; `--cleanup-only <run id>` finishes them
|
||||
later from the state file.
|
||||
|
||||
**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
|
||||
|
||||
+17
-1256
File diff suppressed because it is too large.
Load diff
@@ -343,7 +343,7 @@ idempotent redaction projection. Repeated projection preserves the original
|
||||
payload digest. Provider recovery uses the same projection to compare saved
|
||||
completion results with provider history. Changed private bodies still conflict.
|
||||
Restart preparation preserves the run's admitted REST credential scope, even
|
||||
when the task mode changes. See [the run-log guide](run-log-events.md) for stored fields.
|
||||
when the task mode changes. The stored fields are defined where the run-log event is written.
|
||||
|
||||
The server-issued REST credential for the bound run is never returned to the model.
|
||||
Streaming, WebSocket, MCP and authentication
|
||||
|
||||
@@ -74,6 +74,9 @@ tools or enter MCP discovery. Management requires an instance administrator with
|
||||
access to the company. Only the person who started a pending sign-in can retrieve
|
||||
its sign-in link. Existing SSH environment access governs which agents execute
|
||||
there. Cloud and self-hosted instances use the same Tailscale device sign-in.
|
||||
For Cloud owners, the board access summary reports the effective instance-admin
|
||||
rights computed by Cloud authentication while `enableOwnerInstanceAdmin` is
|
||||
enabled. Disabling that setting removes those rights on the next request.
|
||||
|
||||
The instance starts a private userspace Tailscale device and returns its generated
|
||||
`https://login.tailscale.com/a/...` sign-in address. Pending device state is stored
|
||||
|
||||
@@ -79,7 +79,7 @@ receipt and inline response policy as newly created webhook secrets.
|
||||
Task image access requires the company boundary and the task permission;
|
||||
skill-test and low-trust agents do not need company-wide browsing authority.
|
||||
Completion replay applies the same idempotent projection to stored and expected
|
||||
payloads; [the run-log guide](../../doc/run-log-events.md) describes its fields.
|
||||
payloads; its fields are defined where the [run-log event](../../doc/run-log-events.md) is written.
|
||||
|
||||
Sources: [API client](../../server/src/services/native-runtime/runner-api-client.ts),
|
||||
[catalog](../../server/src/services/native-runtime/runner-api-catalog.ts),
|
||||
|
||||
@@ -287,7 +287,8 @@ The native first-text span ends after text is committed for the existing run-eve
|
||||
reader, including reasoning and completed responses. It exports only the bounded
|
||||
text kind and timing, with no text content or new agent access.
|
||||
This adds no agent API, credential access, run-log write, or recovery authority.
|
||||
See [the tracing contract](../../doc/observability.md#controller-preparation-phases).
|
||||
See the spans in
|
||||
[`execution-preparation-timing.ts`](../../server/src/services/execution-preparation-timing.ts).
|
||||
Live latency verification remains separate from the existing access baseline.
|
||||
|
||||
API: `present` — representative operation IDs:
|
||||
|
||||
@@ -110,7 +110,8 @@ Eyes should appear after authorized task/comment persistence, independently of
|
||||
file preparation, subscription and agent startup. Duplicate delivery must keep
|
||||
one receipt; the final reply must remove only its source message's eyes. Record
|
||||
live mention-to-reaction timing separately from the PostgreSQL fixture tests and
|
||||
the `chat.slack.receipt` transport span described in [Observability](../../doc/observability.md).
|
||||
the `chat.slack.receipt` transport span in
|
||||
[`receipt-timing.ts`](../../server/src/services/chat-channels/slack/receipt-timing.ts).
|
||||
|
||||
During a top-level DM run, verify that the bot adds eyes to the source message
|
||||
and removes them when the final reply arrives. The pinned Slack SDK encodes a
|
||||
|
||||
@@ -44,7 +44,8 @@ For latency diagnosis with an operator OTLP endpoint, search the hashed run ID
|
||||
without restricting the root span name. Compare workspace preparation with its
|
||||
`workspace_<step>` intervals. Measure controller readiness separately through
|
||||
`controller.startup.<phase>`. A recovery pause or deployment drain is not model
|
||||
execution time. See the [tracing contract](../../doc/observability.md#controller-preparation-phases).
|
||||
execution time. See the spans in
|
||||
[`execution-preparation-timing.ts`](../../server/src/services/execution-preparation-timing.ts).
|
||||
These source-level diagnostics do not establish a live response-time budget.
|
||||
`task.time_to_first_token` measures accepted ingress through the first committed
|
||||
text that the task transcript can show, including thinking and completed
|
||||
|
||||
+1
-1
@@ -61,7 +61,7 @@
|
||||
"smoke:notion-generic-live": "node scripts/smoke/notion-generic-live.mjs",
|
||||
"smoke:posthog-live": "node scripts/smoke/posthog-live.mjs",
|
||||
"smoke:terminal-bench-loop-skill": "node scripts/smoke/terminal-bench-loop-skill-smoke.mjs",
|
||||
"test:release-registry": "node scripts/ci-profile/node-test.mjs scripts/ci-profile/reporters.test.mjs scripts/ci/retry-reporter.test.mjs scripts/__tests__/runner-vitest-package-lanes.test.mjs scripts/__tests__/canary-startup-playwright.test.mjs scripts/__tests__/cursor-public-install-sandbox.test.mjs scripts/__tests__/grok-public-install-sandbox.test.mjs scripts/__tests__/public-install-closure.test.mjs scripts/__tests__/public-install-registry.test.mjs scripts/__tests__/prefetch-child.test.mjs scripts/__tests__/stage-bundled-packages.test.mjs scripts/__tests__/pack-staged-packages.test.mjs scripts/__tests__/retain-runner-qualification-packages.test.mjs scripts/__tests__/runner-release-crate-cache.test.mjs scripts/__tests__/runner-debug-crate-cache.test.mjs scripts/__tests__/agent-build-cache.test.mjs scripts/__tests__/agent-preflight.test.mjs scripts/__tests__/vitest-worker-isolation.test.mjs scripts/verify-release-registry-state.test.mjs scripts/release-package-map.test.mjs scripts/check-release-package-bootstrap.test.mjs scripts/check-no-git-push.test.mjs scripts/release-lib.test.mjs scripts/draft-stable-notes.test.mjs scripts/release-registry-versions.test.mjs scripts/link-plugin-dev-sdk.test.js scripts/acpx-patch-packaging.test.mjs scripts/service-onboard-smoke.test.mjs scripts/docker-onboard-smoke.test.mjs scripts/preview-artifacts.test.mjs scripts/cloud-migrator-artifacts.test.mjs scripts/typecheck-test-programs.test.mjs scripts/__tests__/local-verify.test.mjs scripts/test-sandbox-providers.test.mjs scripts/__tests__/ci-typecheck-lane.test.mjs scripts/scale-ramp/scale-ramp.test.ts",
|
||||
"test:release-registry": "node scripts/ci-profile/node-test.mjs scripts/ci-profile/reporters.test.mjs scripts/ci/retry-reporter.test.mjs scripts/__tests__/runner-vitest-package-lanes.test.mjs scripts/__tests__/canary-startup-playwright.test.mjs scripts/__tests__/cursor-public-install-sandbox.test.mjs scripts/__tests__/grok-public-install-sandbox.test.mjs scripts/__tests__/public-install-closure.test.mjs scripts/__tests__/public-install-registry.test.mjs scripts/__tests__/prefetch-child.test.mjs scripts/__tests__/stage-bundled-packages.test.mjs scripts/__tests__/pack-staged-packages.test.mjs scripts/__tests__/retain-runner-qualification-packages.test.mjs scripts/__tests__/runner-release-crate-cache.test.mjs scripts/__tests__/runner-debug-crate-cache.test.mjs scripts/__tests__/agent-build-cache.test.mjs scripts/__tests__/agent-preflight.test.mjs scripts/__tests__/vitest-worker-isolation.test.mjs scripts/verify-release-registry-state.test.mjs scripts/release-package-map.test.mjs scripts/check-release-package-bootstrap.test.mjs scripts/check-no-git-push.test.mjs scripts/release-lib.test.mjs scripts/draft-stable-notes.test.mjs scripts/release-registry-versions.test.mjs scripts/link-plugin-dev-sdk.test.js scripts/acpx-patch-packaging.test.mjs scripts/service-onboard-smoke.test.mjs scripts/docker-onboard-smoke.test.mjs scripts/preview-artifacts.test.mjs scripts/cloud-migrator-artifacts.test.mjs scripts/typecheck-test-programs.test.mjs scripts/__tests__/local-verify.test.mjs scripts/test-sandbox-providers.test.mjs scripts/__tests__/ci-typecheck-lane.test.mjs scripts/scale-ramp/scale-ramp.test.ts scripts/scale-ramp/scale-ramp-spend.test.ts",
|
||||
"storybook-visual:baseline": "node scripts/storybook-visual-baseline.mjs",
|
||||
"test:storybook-visual": "node scripts/storybook-visual-baseline.mjs download && node scripts/storybook-visual-baseline.mjs verify && pnpm build-storybook && npx playwright test --config tests/storybook-visual/playwright.config.ts",
|
||||
"test:storybook-visual:update": "node scripts/storybook-visual-baseline.mjs download && pnpm build-storybook && npx playwright test --config tests/storybook-visual/playwright.config.ts --update-snapshots && node scripts/storybook-visual-baseline.mjs pack",
|
||||
|
||||
@@ -132,9 +132,8 @@ export const HTTP2_BRIDGE_SERVER_OPTIONS: http2.ServerOptions = {
|
||||
* total, so no combination of concurrent streams, across every route, can
|
||||
* retain more than this many bytes at once. This value keeps the accepted
|
||||
* process ceiling at 1,073,741,824 bytes (1 GiB) — the same ceiling
|
||||
* `doc/observability.md` already accepted before the per-body limit rose to
|
||||
* 10 MiB — now enforced by this reservation instead of left as an unenforced
|
||||
* document note. See the per-route budget comment above for the full
|
||||
* the project already accepted before the per-body limit rose to 10 MiB —
|
||||
* now enforced by this reservation instead of left as an unenforced note. See the per-route budget comment above for the full
|
||||
* accounting.
|
||||
*/
|
||||
export const HTTP2_BRIDGE_MAX_PROCESS_BODY_BYTES = 1024 * 1024 * 1024;
|
||||
|
||||
@@ -446,7 +446,8 @@ export async function withDedicatedDbConnection<T>(db: Db, action: (dedicated: D
|
||||
} finally {
|
||||
hold.active = false;
|
||||
try {
|
||||
if (dedicated && completed && !set.closed && !set.ended.has(dedicated) && set.idle.length < DEDICATED_CONNECTION_IDLE_MAX) {
|
||||
if (dedicated && completed && !set.closed && !set.ended.has(dedicated)
|
||||
&& (set.idle.length < DEDICATED_CONNECTION_IDLE_MAX || set.idle.length + set.inUse <= set.limit)) {
|
||||
set.idle.push(dedicated);
|
||||
} else if (dedicated && !set.ended.has(dedicated)) {
|
||||
await dedicated.$client.end({ timeout: 1 });
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { sql } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { checkpointDb, closeCheckpointDb, closeDedicatedDbConnections, createDb, withDedicatedDbConnection, type Db } from "./client.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
|
||||
async function sessionsOpened(observer: Db) {
|
||||
const [row] = await observer.execute<{ sessions: string }>(sql`select sessions::text as sessions from pg_stat_database where datname = current_database()`);
|
||||
return Number(row!.sessions);
|
||||
}
|
||||
|
||||
async function runConcurrently(total: number, concurrency: number, work: () => Promise<unknown>) {
|
||||
let next = 0;
|
||||
await Promise.all(Array.from({ length: concurrency }, async () => {
|
||||
while (next < total) { next++; await work(); }
|
||||
}));
|
||||
}
|
||||
|
||||
describe.skipIf(!support.supported)("connections opened per 1,000 operations", () => {
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let observer: Db;
|
||||
|
||||
beforeAll(async () => {
|
||||
temporary = await startEmbeddedPostgresTestDatabase("connection-reuse-");
|
||||
observer = createDb(temporary.connectionString, { maxConnections: 1, applicationName: "connection-reuse-observer" });
|
||||
await sessionsOpened(observer);
|
||||
}, 90_000);
|
||||
afterAll(async () => {
|
||||
await observer?.$client.end({ timeout: 1 });
|
||||
await temporary?.cleanup();
|
||||
});
|
||||
|
||||
async function measure(open: (db: Db) => Promise<void>) {
|
||||
const db = createDb(temporary.connectionString, { maxConnections: 10 });
|
||||
await db.execute(sql`select 1`);
|
||||
const before = await sessionsOpened(observer);
|
||||
try {
|
||||
await open(db);
|
||||
return await sessionsOpened(observer) - before;
|
||||
} finally {
|
||||
await closeCheckpointDb(db, 1);
|
||||
await closeDedicatedDbConnections(db, 1);
|
||||
await db.$client.end({ timeout: 1 });
|
||||
}
|
||||
}
|
||||
|
||||
it.each([1, 7, 24])("checkpoint saves at concurrency %i reuse the checkpoint pool", async concurrency => {
|
||||
const opened = await measure(db => runConcurrently(1_000, concurrency, () =>
|
||||
checkpointDb(db).transaction(async tx => { await tx.execute(sql`select 1`); })));
|
||||
expect(opened).toBeLessThanOrEqual(3);
|
||||
});
|
||||
|
||||
it.each([1, 4, 8, 16])("dedicated connection uses at concurrency %i", async concurrency => {
|
||||
const opened = await measure(db => runConcurrently(1_000, concurrency, () =>
|
||||
withDedicatedDbConnection(db, connection => connection.transaction(async tx => { await tx.execute(sql`select 1`); }))));
|
||||
expect(opened).toBeLessThanOrEqual(concurrency);
|
||||
});
|
||||
|
||||
it.each([8, 16])("bursts of %i dedicated connection uses reuse the connections the last burst opened", async width => {
|
||||
const opened = await measure(async db => {
|
||||
for (let burst = 0; burst < 1_000 / width; burst++) {
|
||||
await Promise.all(Array.from({ length: width }, () =>
|
||||
withDedicatedDbConnection(db, connection => connection.transaction(async tx => { await tx.execute(sql`select 1`); }))));
|
||||
}
|
||||
});
|
||||
expect(opened).toBeLessThanOrEqual(width);
|
||||
});
|
||||
});
|
||||
@@ -73,8 +73,9 @@ describe.skipIf(!support.supported)("withDedicatedDbConnection connection reuse"
|
||||
expect(seen.size).toBeLessThanOrEqual(DEDICATED_CONNECTION_IDLE_MAX);
|
||||
});
|
||||
|
||||
it("gives concurrent callers exclusive sessions and keeps at most the cap open afterwards", async () => {
|
||||
const db = owner();
|
||||
it("gives concurrent callers exclusive sessions, reuses them for the next burst and closes them once idle", async () => {
|
||||
const db = createDb(temporary.connectionString, { maxConnections: 2, idleTimeoutSeconds: 1 });
|
||||
owners.push(db);
|
||||
const concurrency = DEDICATED_CONNECTION_IDLE_MAX + 3;
|
||||
let release!: () => void;
|
||||
const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
@@ -94,12 +95,16 @@ describe.skipIf(!support.supported)("withDedicatedDbConnection connection reuse"
|
||||
release();
|
||||
const sessions = await Promise.all(held);
|
||||
expect(new Set(sessions.map(key)).size).toBe(concurrency);
|
||||
expect((await eventually(openDedicatedSessions, open => open.length <= DEDICATED_CONNECTION_IDLE_MAX)).length)
|
||||
.toBeLessThanOrEqual(DEDICATED_CONNECTION_IDLE_MAX);
|
||||
const retained = new Set(sessions.map(key));
|
||||
for (let i = 0; i < 20; i++) {
|
||||
expect(retained.has(key(await withDedicatedDbConnection(db, session)))).toBe(true);
|
||||
}
|
||||
const nextBurst = await Promise.all(Array.from({ length: concurrency }, () =>
|
||||
withDedicatedDbConnection(db, dedicated => dedicated.transaction(async tx => {
|
||||
const mine = await session(tx);
|
||||
await tx.execute(sql`select pg_sleep(0.05)`);
|
||||
return mine;
|
||||
}))));
|
||||
expect(nextBurst.every(value => retained.has(key(value)))).toBe(true);
|
||||
expect(await eventually(openDedicatedSessions, open => open.length === 0)).toEqual([]);
|
||||
expect(retained.has(key(await withDedicatedDbConnection(db, session)))).toBe(false);
|
||||
});
|
||||
|
||||
it("discards a connection whose action failed mid-transaction", async () => {
|
||||
|
||||
@@ -8,6 +8,12 @@ agent or recovery of its persisted run. On a fresh launch or restart,
|
||||
- With `--listen-address 0.0.0.0 --listen-path /api/runner/v1/connect/<run-id>`,
|
||||
the Runner listens for Core. `--listen-port` defaults to `43127`.
|
||||
|
||||
A dialing Runner waits `--reconnect-delay-ms` (default 250) between
|
||||
connection attempts and backs off after a failed one. A listening Runner
|
||||
checks for an incoming connection every 10 ms (or sooner, when that delay is
|
||||
smaller). It never redials, so a connection does not wait out the reconnect
|
||||
delay after a disconnect or an authority rotation.
|
||||
|
||||
Choose one form. Both require `PAPERCLIP_RUNNER_BOOTSTRAP_TICKET`.
|
||||
Recovery uses the same entry point. The Runner rejects `--source-reconcile`.
|
||||
|
||||
|
||||
@@ -730,7 +730,8 @@ pub fn run_durable_runner_with_host_control<E: CommandExecutor>(
|
||||
let (mut transport, welcome) = match connection {
|
||||
Ok(Some(connection)) => connection,
|
||||
Ok(None) => {
|
||||
next_connection_attempt = Instant::now() + config.reconnect_delay;
|
||||
next_connection_attempt =
|
||||
Instant::now() + endpoint.retry_delay(config.reconnect_delay);
|
||||
continue;
|
||||
}
|
||||
Err(error) => {
|
||||
@@ -749,7 +750,7 @@ pub fn run_durable_runner_with_host_control<E: CommandExecutor>(
|
||||
}
|
||||
next_connection_attempt = Instant::now()
|
||||
+ reconnect_delay(
|
||||
config.reconnect_delay,
|
||||
endpoint.retry_delay(config.reconnect_delay),
|
||||
connect_deadline.saturating_duration_since(Instant::now()),
|
||||
&mut reconnect_attempt,
|
||||
);
|
||||
@@ -1055,8 +1056,8 @@ pub fn run_durable_runner_with_host_control<E: CommandExecutor>(
|
||||
.map(|credential| credential.expires_at_unix_ms),
|
||||
);
|
||||
next_connection_attempt = Instant::now()
|
||||
+ config
|
||||
.reconnect_delay
|
||||
+ endpoint
|
||||
.retry_delay(config.reconnect_delay)
|
||||
.min(reconnect_deadline.saturating_duration_since(Instant::now()));
|
||||
continue;
|
||||
}
|
||||
@@ -1419,8 +1420,8 @@ pub fn run_durable_runner_with_host_control<E: CommandExecutor>(
|
||||
.map(|credential| credential.expires_at_unix_ms),
|
||||
);
|
||||
next_connection_attempt = Instant::now()
|
||||
+ config
|
||||
.reconnect_delay
|
||||
+ endpoint
|
||||
.retry_delay(config.reconnect_delay)
|
||||
.min(reconnect_deadline.saturating_duration_since(Instant::now()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ const QUEUED_CONTROL_READ_TIMEOUT: Duration = Duration::from_millis(1);
|
||||
const CONNECT_ATTEMPT_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
const CONNECT_TOTAL_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
const MAX_CA_BUNDLE_BYTES: u64 = 4 * 1024 * 1024;
|
||||
const LISTENER_ACCEPT_INTERVAL: Duration = Duration::from_millis(10);
|
||||
|
||||
type HmacSha256 = Hmac<Sha256>;
|
||||
|
||||
@@ -252,6 +253,13 @@ impl RunnerTransportEndpoint {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn retry_delay(&self, configured: Duration) -> Duration {
|
||||
match self {
|
||||
Self::Dial(_) => configured,
|
||||
Self::Listen { .. } => configured.min(LISTENER_ACCEPT_INTERVAL),
|
||||
}
|
||||
}
|
||||
|
||||
fn open(
|
||||
&self,
|
||||
max_frame_bytes: usize,
|
||||
@@ -2172,6 +2180,27 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listener_checks_its_backlog_sooner_than_a_dial_reconnects() {
|
||||
let configured = Duration::from_millis(250);
|
||||
let listener = RunnerTransportEndpoint::Listen {
|
||||
listener: TcpListener::bind("0.0.0.0:0").unwrap(),
|
||||
path: "/api/runner/v1/connect/run_1".to_owned(),
|
||||
};
|
||||
assert_eq!(listener.retry_delay(configured), LISTENER_ACCEPT_INTERVAL);
|
||||
assert!(LISTENER_ACCEPT_INTERVAL <= Duration::from_millis(25));
|
||||
assert_eq!(
|
||||
listener.retry_delay(Duration::from_millis(1)),
|
||||
Duration::from_millis(1)
|
||||
);
|
||||
let dial = RunnerTransportEndpoint::new(
|
||||
"ws://127.0.0.1:43127/api/runner/v1/connect/run_1",
|
||||
"run_1",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(dial.retry_delay(configured), configured);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listener_path_is_exact_and_unambiguous() {
|
||||
validate_listener_path("/api/runner/v1/connect/run_1").unwrap();
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
#![cfg(unix)]
|
||||
|
||||
use std::fs;
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
struct Runner {
|
||||
process: Child,
|
||||
directory: PathBuf,
|
||||
}
|
||||
|
||||
impl Drop for Runner {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.process.kill();
|
||||
let _ = self.process.wait();
|
||||
let _ = fs::remove_dir_all(&self.directory);
|
||||
}
|
||||
}
|
||||
|
||||
const RUN_ID: &str = "run_accept";
|
||||
|
||||
fn upgrade(stream: &mut TcpStream) -> Duration {
|
||||
let started = Instant::now();
|
||||
stream
|
||||
.write_all(
|
||||
format!(
|
||||
"GET /api/runner/v1/connect/{RUN_ID} HTTP/1.1\r\nHost: 127.0.0.1\r\n\
|
||||
Upgrade: websocket\r\nConnection: Upgrade\r\n\
|
||||
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n"
|
||||
)
|
||||
.as_bytes(),
|
||||
)
|
||||
.unwrap();
|
||||
stream
|
||||
.set_read_timeout(Some(Duration::from_secs(5)))
|
||||
.unwrap();
|
||||
let mut response = Vec::new();
|
||||
let mut byte = [0_u8; 1];
|
||||
while !response.ends_with(b"\r\n\r\n") {
|
||||
assert_eq!(
|
||||
stream.read(&mut byte).unwrap(),
|
||||
1,
|
||||
"Runner closed the upgrade"
|
||||
);
|
||||
response.push(byte[0]);
|
||||
}
|
||||
assert!(
|
||||
response.starts_with(b"HTTP/1.1 101"),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&response)
|
||||
);
|
||||
started.elapsed()
|
||||
}
|
||||
|
||||
fn spawn_listening_runner() -> (Runner, u16, TcpStream) {
|
||||
for _ in 0..10 {
|
||||
let reservation = TcpListener::bind("0.0.0.0:0").unwrap();
|
||||
let port = reservation.local_addr().unwrap().port();
|
||||
drop(reservation);
|
||||
let directory =
|
||||
std::env::temp_dir().join(format!("runner-accept-{}", uuid::Uuid::new_v4()));
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::set_permissions(&directory, fs::Permissions::from_mode(0o700)).unwrap();
|
||||
let process = Command::new(env!("CARGO_BIN_EXE_paperclip-runnerd"))
|
||||
.env(
|
||||
"PAPERCLIP_RUNNER_BOOTSTRAP_TICKET",
|
||||
"fixture-bootstrap-ticket",
|
||||
)
|
||||
.args([
|
||||
"--listen-address",
|
||||
"0.0.0.0",
|
||||
"--listen-port",
|
||||
&port.to_string(),
|
||||
"--listen-path",
|
||||
&format!("/api/runner/v1/connect/{RUN_ID}"),
|
||||
"--state-dir",
|
||||
directory.to_str().unwrap(),
|
||||
"--runner-id",
|
||||
"runner",
|
||||
"--environment-lease-id",
|
||||
"lease",
|
||||
"--run-id",
|
||||
RUN_ID,
|
||||
"--session-id",
|
||||
"session",
|
||||
"--turn-id",
|
||||
"turn",
|
||||
"--item-id",
|
||||
"item",
|
||||
"--runner-version",
|
||||
"0.0.0",
|
||||
"--runner-digest",
|
||||
&format!("sha256:{}", "a".repeat(64)),
|
||||
"--max-runtime-ms",
|
||||
"20000",
|
||||
])
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut runner = Runner { process, directory };
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
if let Some(status) = runner.process.try_wait().unwrap() {
|
||||
match TcpListener::bind(("0.0.0.0", port)) {
|
||||
Err(error) if error.kind() == std::io::ErrorKind::AddrInUse => break,
|
||||
_ => panic!("Runner exited before listening: {status}"),
|
||||
}
|
||||
}
|
||||
if let Ok(stream) = TcpStream::connect(("127.0.0.1", port)) {
|
||||
return (runner, port, stream);
|
||||
}
|
||||
assert!(Instant::now() < deadline, "Runner did not bind its port");
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
}
|
||||
panic!("could not acquire an available Runner port");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listener_answers_the_next_connection_without_waiting_out_the_reconnect_delay() {
|
||||
let (_runner, port, mut stale) = spawn_listening_runner();
|
||||
upgrade(&mut stale);
|
||||
drop(stale);
|
||||
thread::sleep(Duration::from_millis(30));
|
||||
|
||||
let mut current = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
let waited = upgrade(&mut current);
|
||||
assert!(
|
||||
waited < Duration::from_millis(120),
|
||||
"listener answered after {waited:?}"
|
||||
);
|
||||
}
|
||||
@@ -39,12 +39,14 @@ test("distribution build admits network settings without provider keys or Node i
|
||||
test("setup cancellation physically stops an in-flight owned child", { timeout: 5_000 }, async t => {
|
||||
const { root } = await fixture(t), pidFile = join(root, "pid");
|
||||
const controller = new AbortController();
|
||||
const result = runKimiBuildCommand(process.execPath, ["-e", "require('node:fs').writeFileSync(process.argv[1],String(process.pid));setInterval(()=>{},1000)", pidFile], { env: {}, timeout: 3_000 }, undefined, controller.signal).then(() => null, error => error);
|
||||
let pid;
|
||||
const result = runKimiBuildCommand(process.execPath, ["-e", "const f=require('node:fs');f.writeFileSync(process.argv[1]+'.tmp',String(process.pid));f.renameSync(process.argv[1]+'.tmp',process.argv[1]);setInterval(()=>{},1000)", pidFile], { env: {}, timeout: 3_000 }, undefined, controller.signal).then(() => null, error => error);
|
||||
let pid, settled = false;
|
||||
void result.then(() => { settled = true; });
|
||||
try {
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
try { pid = Number(await readFile(pidFile, "utf8")); break; }
|
||||
catch (error) { if (error.code !== "ENOENT") throw error; await delay(10); }
|
||||
while (!settled && !(Number.isSafeInteger(pid) && pid > 0)) {
|
||||
try { pid = Number(await readFile(pidFile, "utf8")); }
|
||||
catch (error) { if (error.code !== "ENOENT") throw error; }
|
||||
await delay(10);
|
||||
}
|
||||
assert.ok(Number.isSafeInteger(pid) && pid > 0, "The real child did not start");
|
||||
controller.abort();
|
||||
|
||||
@@ -54,7 +54,7 @@ test("installed Kimi setup is self-contained, rejects corrupt assets and cancels
|
||||
let stderr = ""; cancelled.stderr.on("data", chunk => { stderr = (stderr + chunk).slice(-4096); });
|
||||
const kill = setTimeout(() => cancelled.kill("SIGKILL"), 5_000);
|
||||
try {
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
while (cancelled.exitCode === null && cancelled.signalCode === null) {
|
||||
try { if (await readFile(ready, "utf8") === "ready") break; }
|
||||
catch (error) { if (error.code !== "ENOENT") throw error; }
|
||||
await delay(10);
|
||||
|
||||
@@ -84,16 +84,10 @@ test("release metadata rejects incompatible native, harness and protocol contrac
|
||||
}
|
||||
});
|
||||
|
||||
async function standaloneSleep() {
|
||||
if (process.platform !== "linux") return "/bin/sleep";
|
||||
const multicall = (await readFile("/bin/sleep")).equals(await readFile("/bin/echo"));
|
||||
return multicall ? "/usr/bin/gnusleep" : "/bin/sleep";
|
||||
}
|
||||
|
||||
async function withOwnedChildren(root, action) {
|
||||
const owned = [];
|
||||
const start = (command, args) => {
|
||||
const child = spawn(command, args, { env: { PATH: "/usr/bin:/bin" }, stdio: "ignore" });
|
||||
const start = (command, args, argv0) => {
|
||||
const child = spawn(command, args, { argv0, env: { PATH: "/usr/bin:/bin" }, stdio: "ignore" });
|
||||
// close follows both exit and spawn error. A failed second spawn must not
|
||||
// interrupt retirement of the first still-running executable.
|
||||
const closed = new Promise(resolve => child.once("close", resolve));
|
||||
@@ -118,20 +112,19 @@ async function withOwnedChildren(root, action) {
|
||||
test("atomically publishes while the previous executable is running", { skip: process.platform === "win32", timeout: 15_000 }, async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "runnerd-stage-test-"));
|
||||
const destination = path.join(root, "paperclip-runnerd");
|
||||
const sleep = await standaloneSleep();
|
||||
await withOwnedChildren(root, async start => {
|
||||
await stageRunnerBinary(sleep, destination);
|
||||
await stageRunnerBinary("/bin/sleep", destination);
|
||||
const previous = await stat(destination);
|
||||
const old = start(destination, ["30"]);
|
||||
const old = start(destination, ["30"], "sleep");
|
||||
await old.spawned;
|
||||
await stageRunnerBinary(sleep, destination);
|
||||
await stageRunnerBinary("/bin/sleep", destination);
|
||||
const published = await stat(destination);
|
||||
assert.notEqual(published.ino, previous.ino);
|
||||
assert.equal(published.mode & 0o777, 0o755);
|
||||
assert.equal(old.child.exitCode, null);
|
||||
assert.equal(old.child.signalCode, null);
|
||||
assert.deepEqual(await readdir(root), ["paperclip-runnerd"]);
|
||||
const next = start(destination, ["0"]);
|
||||
const next = start(destination, ["0"], "sleep");
|
||||
await next.spawned; await next.closed;
|
||||
assert.equal(next.child.exitCode, 0);
|
||||
});
|
||||
@@ -157,9 +150,9 @@ test("a source rebuild selects fresh dev bytes while preserving release binaries
|
||||
await mkdir(path.dirname(source), { recursive: true });
|
||||
await writeFile(source, "fn main() {}\n");
|
||||
await mkdir(path.dirname(built), { recursive: true });
|
||||
await copyHostFixture("/bin/echo", built);
|
||||
await copyHostFixture("/bin/sh", built);
|
||||
const previousBuild = path.join(root, "previous-build");
|
||||
await copyHostFixture(await standaloneSleep(), previousBuild);
|
||||
await copyHostFixture("/bin/sleep", previousBuild);
|
||||
await stageRunnerBinary(previousBuild, hostTarget);
|
||||
await stageRunnerBinary(built, path.join(binaryRoot, "paperclip-runnerd"));
|
||||
const platforms = {}, releaseBytes = new Map();
|
||||
@@ -185,7 +178,7 @@ test("a source rebuild selects fresh dev bytes while preserving release binaries
|
||||
const manifestPath = path.join(binaryRoot, "release-manifest.json");
|
||||
const manifest = JSON.stringify({ schema: "paperclip.runner.release-binaries.v1", sourceRevision: "a".repeat(40), platforms });
|
||||
await writeFile(manifestPath, manifest);
|
||||
const old = start(hostTarget, ["30"]);
|
||||
const old = start(hostTarget, ["30"], "sleep");
|
||||
await old.spawned;
|
||||
const requirement = { repoRoot: root, nativeRunnerRequired: true };
|
||||
assert.equal(paperclipRunnerBinaryNeedsBuild(requirement), true);
|
||||
@@ -205,7 +198,7 @@ test("a source rebuild selects fresh dev bytes while preserving release binaries
|
||||
assert.equal(paperclipRunnerBinaryNeedsBuild(requirement), false);
|
||||
assert.equal(old.child.exitCode, null);
|
||||
assert.equal(old.child.signalCode, null);
|
||||
const next = start(selected.binary, ["rebuilt"]);
|
||||
const next = start(selected.binary, ["-c", "exit 0"]);
|
||||
await next.spawned; await next.closed;
|
||||
assert.equal(next.child.exitCode, 0);
|
||||
});
|
||||
|
||||
@@ -293,6 +293,12 @@ export class SemanticToolNotDispatchedError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export class SemanticToolHandedOffError extends Error {
|
||||
constructor() {
|
||||
super("semantic_tool_handed_off");
|
||||
}
|
||||
}
|
||||
|
||||
export interface DurablePrpControlPlaneOptions {
|
||||
stateDirectory: string;
|
||||
identity: DurableRecoveryIdentity;
|
||||
@@ -4798,6 +4804,7 @@ export class DurablePrpControlPlane {
|
||||
queueResult(outcome.result, outcome.isError === true),
|
||||
)
|
||||
.catch((error: unknown) => {
|
||||
if (error instanceof SemanticToolHandedOffError) return;
|
||||
if (error instanceof SemanticToolNotDispatchedError) {
|
||||
queueResult({ error: {
|
||||
code: "semantic_tool_not_dispatched",
|
||||
|
||||
+82
-7
@@ -3,7 +3,8 @@ import { createServer } from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { DurablePrpControlPlane } from "../control-plane/durable-prp-control-plane.js";
|
||||
import * as durableControlPlane from "../control-plane/durable-prp-control-plane.js";
|
||||
import type { DurablePrpControlPlane } from "../control-plane/durable-prp-control-plane.js";
|
||||
import { recoverToolCallback, TOOL_CALLBACK_INTERRUPTED_CODE } from "../control-plane/orphaned-tool-callback.js";
|
||||
import { createCapabilityRunnerdCodexTransport } from "./runnerd-codex-transport.js";
|
||||
import { defaultCapabilityRunnerdBinary, fakeCodex, fakeCodexArgs } from "../../test/support/runnerd-transport.js";
|
||||
@@ -12,7 +13,7 @@ const taskTool = { name: "get_task_context", description: "Read current task", i
|
||||
|
||||
type SavedCommand = { commandId: string; type: string; status: string; payload: Record<string, unknown> };
|
||||
|
||||
it("settles an earlier generation's in-flight tool call at attach even when that attach never finishes startup", async () => {
|
||||
it.each(["dispatched to its handler", "still before dispatch"] as const)("settles an earlier generation's in-flight tool call at attach even when that attach never finishes startup (%s at detach)", async stage => {
|
||||
const stateDirectory = await mkdtemp(join(tmpdir(), "runnerd-orphaned-tool-at-attach-"));
|
||||
const controlPlaneStatePath = join(stateDirectory, "control-plane", "control-plane-state.json");
|
||||
const server = createServer();
|
||||
@@ -55,8 +56,28 @@ it("settles an earlier generation's in-flight tool call at attach even when that
|
||||
const recovered = vi.fn(async (call: { operationId: string; callId: string; input: unknown; admission?: "this_controller" | "earlier_controller" }) =>
|
||||
recoverToolCallback({ runId: identity.runId, call: { tool: call.operationId, callId: call.callId, arguments: call.input },
|
||||
admission: call.admission, recover: async () => null }));
|
||||
let reached!: () => void;
|
||||
const callReached = new Promise<void>(resolveReached => { reached = resolveReached; });
|
||||
let releaseDispatch!: () => void;
|
||||
const dispatchGate = new Promise<void>(resolveGate => { releaseDispatch = resolveGate; });
|
||||
let gatedOutcome: Promise<unknown> | null = null;
|
||||
const OriginalCore = durableControlPlane.DurablePrpControlPlane;
|
||||
const coreSpy = vi.spyOn(durableControlPlane, "DurablePrpControlPlane").mockImplementation(function (coreOptions) {
|
||||
const dispatch = coreOptions.onSemanticToolInput;
|
||||
if (stage === "still before dispatch" && dispatch && !gatedOutcome) {
|
||||
coreOptions = { ...coreOptions, onSemanticToolInput: call => {
|
||||
reached();
|
||||
gatedOutcome = dispatchGate.then(() => dispatch(call));
|
||||
return gatedOutcome as ReturnType<typeof dispatch>;
|
||||
} };
|
||||
}
|
||||
return new OriginalCore(coreOptions);
|
||||
});
|
||||
const first = createCapabilityRunnerdCodexTransport(options);
|
||||
first.transport.setServerRequestHandler(() => new Promise<Record<string, unknown>>(() => undefined));
|
||||
first.transport.setServerRequestHandler(() => {
|
||||
reached();
|
||||
return new Promise<Record<string, unknown>>(() => undefined);
|
||||
});
|
||||
const generations: Array<ReturnType<typeof createCapabilityRunnerdCodexTransport>> = [];
|
||||
let runnerPid: number | null = null;
|
||||
const savedToolResults = async () => (JSON.parse(await readFile(controlPlaneStatePath, "utf8")) as { commands: SavedCommand[] })
|
||||
@@ -66,11 +87,11 @@ it("settles an earlier generation's in-flight tool call at attach even when that
|
||||
runnerPid = first.evidence().runnerPid;
|
||||
const runnerStartedAt = first.transport.processInfo!().startedAt;
|
||||
await first.transport.request("turn/start", { input: [{ type: "text", text: "Read current task" }] });
|
||||
await vi.waitFor(async () => {
|
||||
const saved = JSON.parse(await readFile(controlPlaneStatePath, "utf8")) as { committedEvents: Array<{ eventType: string }> };
|
||||
expect(saved.committedEvents.some(event => event.eventType === "semantic_tool.input")).toBe(true);
|
||||
}, { timeout: 10_000 });
|
||||
await callReached;
|
||||
await first.detachControllerForRestart();
|
||||
releaseDispatch();
|
||||
await (gatedOutcome as Promise<unknown> | null)?.catch(() => undefined);
|
||||
await new Promise<void>(resolveTurn => setImmediate(resolveTurn));
|
||||
expect(await savedToolResults()).toEqual([]);
|
||||
|
||||
const adopt = (graceMs?: number) => {
|
||||
@@ -110,6 +131,8 @@ it("settles an earlier generation's in-flight tool call at attach even when that
|
||||
}, { timeout: 10_000 });
|
||||
expect(recovered).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
releaseDispatch();
|
||||
coreSpy.mockRestore();
|
||||
for (const generation of generations.reverse()) await generation.transport.close().catch(() => undefined);
|
||||
await first.transport.close().catch(() => undefined);
|
||||
if (runnerPid) {
|
||||
@@ -120,3 +143,55 @@ it("settles an earlier generation's in-flight tool call at attach even when that
|
||||
await rm(stateDirectory, { recursive: true, force: true });
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
it("still settles a call stopped before dispatch as not dispatched when the controller closes without a restart", async () => {
|
||||
const stateDirectory = await mkdtemp(join(tmpdir(), "runnerd-not-dispatched-at-close-"));
|
||||
const controlPlaneStatePath = join(stateDirectory, "control-plane", "control-plane-state.json");
|
||||
let reached!: () => void;
|
||||
const callReached = new Promise<void>(resolveReached => { reached = resolveReached; });
|
||||
let releaseDispatch!: () => void;
|
||||
const dispatchGate = new Promise<void>(resolveGate => { releaseDispatch = resolveGate; });
|
||||
let gatedOutcome: Promise<unknown> | null = null;
|
||||
const OriginalCore = durableControlPlane.DurablePrpControlPlane;
|
||||
const coreSpy = vi.spyOn(durableControlPlane, "DurablePrpControlPlane").mockImplementation(function (coreOptions) {
|
||||
const dispatch = coreOptions.onSemanticToolInput;
|
||||
if (dispatch && !gatedOutcome) {
|
||||
coreOptions = { ...coreOptions, onSemanticToolInput: call => {
|
||||
reached();
|
||||
gatedOutcome = dispatchGate.then(() => dispatch(call));
|
||||
return gatedOutcome as ReturnType<typeof dispatch>;
|
||||
} };
|
||||
}
|
||||
return new OriginalCore(coreOptions);
|
||||
});
|
||||
const bundle = createCapabilityRunnerdCodexTransport({
|
||||
runnerBinary: defaultCapabilityRunnerdBinary(),
|
||||
codexCommand: fakeCodex,
|
||||
codexArgs: fakeCodexArgs(stateDirectory, "--emit-tool-call"),
|
||||
stateDirectory,
|
||||
});
|
||||
bundle.transport.setServerRequestHandler(() => new Promise<Record<string, unknown>>(() => undefined));
|
||||
let runnerPid: number | null = null;
|
||||
try {
|
||||
await bundle.transport.request("thread/start", { cwd: tmpdir(), dynamicTools: [taskTool] });
|
||||
runnerPid = bundle.evidence().runnerPid;
|
||||
await bundle.transport.request("turn/start", { input: [{ type: "text", text: "Read current task" }] });
|
||||
await callReached;
|
||||
const closing = bundle.transport.close().catch(() => undefined);
|
||||
releaseDispatch();
|
||||
await (gatedOutcome as Promise<unknown> | null)?.catch(() => undefined);
|
||||
await closing;
|
||||
const results = (JSON.parse(await readFile(controlPlaneStatePath, "utf8")) as { commands: SavedCommand[] })
|
||||
.commands.filter(command => command.type === "semantic_tool.result");
|
||||
expect(results).toHaveLength(1);
|
||||
expect(JSON.stringify(results[0]!.payload)).toContain("semantic_tool_not_dispatched");
|
||||
} finally {
|
||||
releaseDispatch();
|
||||
coreSpy.mockRestore();
|
||||
await bundle.transport.close().catch(() => undefined);
|
||||
if (runnerPid) {
|
||||
try { process.kill(-runnerPid, "SIGKILL"); } catch { runnerPid = null; }
|
||||
}
|
||||
await rm(stateDirectory, { recursive: true, force: true });
|
||||
}
|
||||
}, 120_000);
|
||||
@@ -76,6 +76,7 @@ import { NativeRunnerResumeStateUnavailableError, NativeRunnerSourceReconciliati
|
||||
import {
|
||||
DurablePrpControlPlane,
|
||||
inspectStagedRunAttachment,
|
||||
SemanticToolHandedOffError,
|
||||
SemanticToolNotDispatchedError,
|
||||
durableRecoveryInternals,
|
||||
inspectWarmRunTransition,
|
||||
@@ -6518,7 +6519,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
onAuthenticatedConnection: () => this.#startupSteps?.advance("runner.process.launch", "provider.session.load"),
|
||||
get authorityRunId() { return authorityRunId(); },
|
||||
semanticInputMode: this.#retainsSourceInputs() || this.options.recoveryPurpose === "stop_cleanup" ? "retain_only" : "dispatch",
|
||||
onSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : (call) => this.#handleSemanticToolInput(call),
|
||||
onSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : (call) => this.#dispatchSemanticToolInput(call),
|
||||
recoverSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : call => this.#recoverSemanticToolInput(call),
|
||||
onCommittedEvent: async (event) => {
|
||||
const source = this.#sourceAccountingIdentity();
|
||||
@@ -7079,7 +7080,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
onAuthenticatedConnection: () => this.#startupSteps?.advance("runner.process.launch", "provider.session.load"),
|
||||
get authorityRunId() { return authorityRunId(); },
|
||||
semanticInputMode: this.#retainsSourceInputs() || this.options.recoveryPurpose === "stop_cleanup" ? "retain_only" : "dispatch",
|
||||
onSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : (call) => this.#handleSemanticToolInput(call),
|
||||
onSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : (call) => this.#dispatchSemanticToolInput(call),
|
||||
recoverSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : call => this.#recoverSemanticToolInput(call),
|
||||
onCommittedEvent: async (event) => {
|
||||
const source = this.#sourceAccountingIdentity();
|
||||
@@ -7680,6 +7681,15 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
return outcome ? this.#bindSemanticToolOutcome(call, outcome) : null;
|
||||
}
|
||||
|
||||
async #dispatchSemanticToolInput(call: Parameters<NonNullable<DurablePrpControlPlaneOptions["onSemanticToolInput"]>>[0]) {
|
||||
try {
|
||||
return await this.#handleSemanticToolInput(call);
|
||||
} catch (error) {
|
||||
if (error instanceof SemanticToolNotDispatchedError && this.#controllerDetachedForRestart) throw new SemanticToolHandedOffError();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async #handleSemanticToolInput(
|
||||
call: Parameters<
|
||||
NonNullable<DurablePrpControlPlaneOptions["onSemanticToolInput"]>
|
||||
|
||||
@@ -126,9 +126,8 @@ This document covers Paperclip Telemetry only. The generated Telemetry
|
||||
contract covers neither the Observability path nor the run-log path. Two other
|
||||
data paths document their own contract in their own file:
|
||||
|
||||
- [Observability](../../../../doc/observability.md) — the OpenTelemetry trace
|
||||
path, the sandbox startup trace spans, and the sandbox duplex transport
|
||||
instrumentation.
|
||||
- [Observability](../../../../doc/observability.md) — the operator-enabled
|
||||
OpenTelemetry trace path and Sentry error monitoring.
|
||||
- [Run-Log Events](../../../../doc/run-log-events.md) — events written to the
|
||||
local `heartbeat_run_events` table.
|
||||
|
||||
|
||||
@@ -49,10 +49,10 @@ Apply a review level that matches the path:
|
||||
- **Observability change (lighter review).** The operator endpoint gate stays in
|
||||
place. The no-operation behaviour stays when no endpoint is set. A privacy
|
||||
review is not necessary while the change stays inside the closed
|
||||
span-attribute allowlist.
|
||||
span-attribute allowlist defined in the code that opens the span.
|
||||
- **Run-log change (no extra review).** A run-log change needs neither review
|
||||
level above, because the data stays in the instance database. Update
|
||||
`doc/run-log-events.md` when an event is added or changed.
|
||||
level above, because the data stays in the instance database. Define the
|
||||
event and its payload where it is written; do not list it in a doc.
|
||||
|
||||
## Exclusion
|
||||
|
||||
|
||||
@@ -10,16 +10,23 @@ export interface CleanupReport {
|
||||
agentsTerminated: number;
|
||||
agentsDeleted: number;
|
||||
agentsKeptForCostHistory: number;
|
||||
agentsStillTerminating: string[];
|
||||
secretDeleted: boolean;
|
||||
projectArchived: boolean;
|
||||
companyArchived: boolean;
|
||||
activeSandboxLeases: number | null;
|
||||
activeSandboxLeaseIds: string[];
|
||||
sandboxLeasesReleasedDuringWait: number;
|
||||
durationMs: number;
|
||||
errors: string[];
|
||||
}
|
||||
|
||||
export const LIVE_RUN_STATUSES = new Set(["queued", "running", "scheduled_retry"]);
|
||||
const PARALLELISM = 8;
|
||||
const TERMINATED = new Set(["terminated", "rejected"]);
|
||||
const TERMINATION_READS_PER_POLL = 200;
|
||||
const TERMINATION_POLL_MS_PER_AGENT = 30;
|
||||
const TERMINATION_POLL_MAX_MS = 30_000;
|
||||
|
||||
export interface CleanupInput {
|
||||
api: PaperclipClient;
|
||||
@@ -53,8 +60,9 @@ export async function cleanupRun(input: CleanupInput): Promise<CleanupReport> {
|
||||
const started = clock.now();
|
||||
const pollMs = input.pollMs ?? 3_000;
|
||||
const report: CleanupReport = {
|
||||
agentsPaused: 0, runsCancelled: 0, tasksArchived: 0, agentsTerminated: 0, agentsDeleted: 0, agentsKeptForCostHistory: 0,
|
||||
secretDeleted: false, projectArchived: false, companyArchived: false, activeSandboxLeases: null, durationMs: 0, errors: [],
|
||||
agentsPaused: 0, runsCancelled: 0, tasksArchived: 0, agentsTerminated: 0, agentsDeleted: 0, agentsKeptForCostHistory: 0, agentsStillTerminating: [],
|
||||
secretDeleted: false, projectArchived: false, companyArchived: false, activeSandboxLeases: null, activeSandboxLeaseIds: [],
|
||||
sandboxLeasesReleasedDuringWait: 0, durationMs: 0, errors: [],
|
||||
};
|
||||
const attempt = async (what: string, action: () => Promise<unknown>): Promise<boolean> => {
|
||||
try {
|
||||
@@ -79,8 +87,22 @@ export async function cleanupRun(input: CleanupInput): Promise<CleanupReport> {
|
||||
return report;
|
||||
}
|
||||
const prefix = agentPrefix(label);
|
||||
const readAgent = async (id: string): Promise<Json | null> => {
|
||||
try {
|
||||
return await api.get<Json>(`/api/agents/${id}`);
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError && error.status === 404) return null;
|
||||
report.errors.push(`read agent ${id}: ${error instanceof Error ? error.message : String(error)}`.slice(0, 300));
|
||||
return { id, status: "unknown", lifecycleState: "unknown" };
|
||||
}
|
||||
};
|
||||
const listed = await read<Json[]>("list agents", `/api/companies/${companyId}/agents`, []);
|
||||
const agents = listed.filter(agent => String(agent.name ?? "").startsWith(prefix));
|
||||
const unlisted = state.agentIds.filter(id => !agents.some(agent => String(agent.id) === id));
|
||||
await mapLimit(unlisted, PARALLELISM, async id => {
|
||||
const agent = await readAgent(id);
|
||||
if (agent && String(agent.name ?? prefix).startsWith(prefix)) agents.push(agent);
|
||||
});
|
||||
const agentIds = new Set(agents.map(agent => String(agent.id)));
|
||||
input.log?.(`Cleanup ${label}: ${agents.length} agents, ${state.taskIds.length} recorded tasks`);
|
||||
|
||||
@@ -121,16 +143,27 @@ export async function cleanupRun(input: CleanupInput): Promise<CleanupReport> {
|
||||
if (await attempt(`terminate agent ${agent.id}`, () => api.post(`/api/agents/${agent.id}/terminate`))) report.agentsTerminated += 1;
|
||||
});
|
||||
const pending = new Set(agentIds);
|
||||
for (const until = clock.now() + (input.terminateWaitMs ?? 300_000); pending.size && clock.now() < until;) {
|
||||
const current = await read<Json[]>("list agents", `/api/companies/${companyId}/agents`, []);
|
||||
for (const agent of current) {
|
||||
if (!pending.has(String(agent.id))) continue;
|
||||
if (agent.status === "terminated" && (agent.lifecycleState == null || agent.lifecycleState === "terminated")) pending.delete(String(agent.id));
|
||||
}
|
||||
for (const id of [...pending]) if (!current.some(agent => String(agent.id) === id)) pending.delete(id);
|
||||
if (pending.size) await clock.sleep(pollMs);
|
||||
const waitMs = input.terminateWaitMs ?? 300_000;
|
||||
const readPending = async (ids: string[]) => mapLimit(ids, PARALLELISM, async id => {
|
||||
const agent = await readAgent(id);
|
||||
if (!agent || TERMINATED.has(String(agent.lifecycleState))) pending.delete(id);
|
||||
});
|
||||
let cursor = 0;
|
||||
for (const until = clock.now() + waitMs; pending.size && clock.now() < until;) {
|
||||
const ids = [...pending];
|
||||
const start = cursor % ids.length;
|
||||
const batch = [...ids.slice(start), ...ids.slice(0, start)].slice(0, TERMINATION_READS_PER_POLL);
|
||||
cursor = start + batch.length;
|
||||
await readPending(batch);
|
||||
if (!pending.size) break;
|
||||
await clock.sleep(Math.min(TERMINATION_POLL_MAX_MS, Math.max(pollMs, pending.size * TERMINATION_POLL_MS_PER_AGENT)));
|
||||
}
|
||||
if (pending.size) await readPending([...pending]);
|
||||
report.agentsStillTerminating = [...pending];
|
||||
if (pending.size) {
|
||||
report.errors.push(`${pending.size} agents had not completed termination after ${Math.round(waitMs / 60_000)} min, so they were not deleted: `
|
||||
+ `${[...pending].join(", ")}; run --cleanup-only ${label} again later`);
|
||||
}
|
||||
if (pending.size) report.errors.push(`${pending.size} agents were not terminated in time; run --cleanup-only ${label} again`);
|
||||
await mapLimit([...agentIds].filter(id => !pending.has(id)), PARALLELISM, async agentId => {
|
||||
try {
|
||||
await api.delete(`/api/agents/${agentId}`);
|
||||
@@ -154,7 +187,10 @@ export async function cleanupRun(input: CleanupInput): Promise<CleanupReport> {
|
||||
}
|
||||
|
||||
if (state.environmentId && taskIds.size) {
|
||||
for (const until = clock.now() + (input.leaseWaitMs ?? 300_000); ;) {
|
||||
const leaseWaitMs = input.leaseWaitMs ?? 300_000;
|
||||
const seen = new Set<string>();
|
||||
let active: Json[] = [];
|
||||
for (const until = clock.now() + leaseWaitMs; ;) {
|
||||
let leases: Json[] | null = null;
|
||||
try {
|
||||
leases = await api.get<Json[]>(`/api/environments/${state.environmentId}/leases?status=active`);
|
||||
@@ -162,11 +198,18 @@ export async function cleanupRun(input: CleanupInput): Promise<CleanupReport> {
|
||||
leases = null;
|
||||
}
|
||||
if (leases === null) break;
|
||||
report.activeSandboxLeases = leases.filter(lease => taskIds.has(String(lease.issueId))).length;
|
||||
if (report.activeSandboxLeases === 0 || clock.now() >= until) break;
|
||||
active = leases.filter(lease => taskIds.has(String(lease.issueId)) || agentIds.has(String(lease.metadata?.agentId ?? "")));
|
||||
for (const lease of active) seen.add(String(lease.id));
|
||||
report.activeSandboxLeases = active.length;
|
||||
if (active.length === 0 || clock.now() >= until) break;
|
||||
await clock.sleep(pollMs);
|
||||
}
|
||||
if (report.activeSandboxLeases) report.errors.push(`${report.activeSandboxLeases} sandbox leases of this run are still active`);
|
||||
report.activeSandboxLeaseIds = active.map(lease => String(lease.id));
|
||||
report.sandboxLeasesReleasedDuringWait = [...seen].filter(id => !report.activeSandboxLeaseIds.includes(id)).length;
|
||||
if (active.length) {
|
||||
const detail = active.map(lease => `${lease.id} (run ${lease.heartbeatRunId ?? "unknown"}, acquired ${lease.acquiredAt ?? "unknown"})`).join(", ");
|
||||
report.errors.push(`${active.length} sandbox leases of this run were still active after ${Math.round(leaseWaitMs / 60_000)} min: ${detail}`.slice(0, 600));
|
||||
}
|
||||
}
|
||||
|
||||
if (state.companyCreated) {
|
||||
|
||||
@@ -21,6 +21,8 @@ export interface Thresholds {
|
||||
queueWaitP95Ms: number;
|
||||
firstActivityP95Ms: number;
|
||||
minConcurrencyRatio: number;
|
||||
maxFailedRunRatio: number;
|
||||
recoveryGraceMs: number;
|
||||
maxEventLoopUtilization: number;
|
||||
runEventLatenessP99Ms: number;
|
||||
agentApiPreHandlerP99Ms: number;
|
||||
@@ -159,6 +161,8 @@ export function parseOptions(argv: readonly string[], env: NodeJS.ProcessEnv, no
|
||||
"max-queue-wait-p95-seconds": { type: "string" },
|
||||
"max-first-activity-p95-seconds": { type: "string" },
|
||||
"min-concurrency-ratio": { type: "string" },
|
||||
"max-failed-run-percent": { type: "string" },
|
||||
"recovery-grace-minutes": { type: "string" },
|
||||
},
|
||||
});
|
||||
if (values["dry-run"] && values["cleanup-only"]) throw new Error("--dry-run and --cleanup-only exclude each other");
|
||||
@@ -198,6 +202,8 @@ export function parseOptions(argv: readonly string[], env: NodeJS.ProcessEnv, no
|
||||
queueWaitP95Ms: number(values["max-queue-wait-p95-seconds"], "--max-queue-wait-p95-seconds", 60, 1, 3_600) * 1_000,
|
||||
firstActivityP95Ms: number(values["max-first-activity-p95-seconds"], "--max-first-activity-p95-seconds", 60, 1, 3_600) * 1_000,
|
||||
minConcurrencyRatio: number(values["min-concurrency-ratio"], "--min-concurrency-ratio", 0.9, 0.1, 1),
|
||||
maxFailedRunRatio: number(values["max-failed-run-percent"], "--max-failed-run-percent", 2, 0, 100) / 100,
|
||||
recoveryGraceMs: number(values["recovery-grace-minutes"], "--recovery-grace-minutes", 15, 1, 120) * 60_000,
|
||||
maxEventLoopUtilization: 0.6,
|
||||
runEventLatenessP99Ms: 1_000,
|
||||
agentApiPreHandlerP99Ms: 100,
|
||||
|
||||
@@ -22,7 +22,11 @@ export interface StepMetrics {
|
||||
tasksFinished: number;
|
||||
tasksFailed: number;
|
||||
tasksNeedingRetry: number;
|
||||
runsEnded: number;
|
||||
runsFailed: number;
|
||||
runsFailedRecovered: number;
|
||||
runsFailedUnrecovered: number;
|
||||
runsFailedPending: number;
|
||||
runsInterrupted: number;
|
||||
runsCancelled: number;
|
||||
peakRunning: number;
|
||||
@@ -32,7 +36,7 @@ export interface StepMetrics {
|
||||
ttftMs: Distribution;
|
||||
firstActivityMs: Distribution;
|
||||
runDurationMs: Distribution;
|
||||
board: { requests: number; failures: number; ms: Distribution };
|
||||
board: { requests: number; failures: number; ms: Distribution; byRoute: Record<string, Distribution> };
|
||||
server: ServerMetrics;
|
||||
recordedSpendUsd: number;
|
||||
}
|
||||
@@ -69,10 +73,17 @@ export const CRITERIA: readonly Criterion[] = [
|
||||
evaluate: m => ({ status: m.tasksNeedingRetry === 0 ? "pass" : "fail", observed: m.tasksNeedingRetry }),
|
||||
},
|
||||
{
|
||||
id: "failed_runs_zero", source: "harness", immediate: true,
|
||||
description: "Runs that ended failed or timed out",
|
||||
threshold: () => "= 0",
|
||||
evaluate: m => ({ status: m.runsFailed === 0 ? "pass" : "fail", observed: m.runsFailed }),
|
||||
id: "failed_runs_unrecovered_zero", source: "harness", immediate: true,
|
||||
description: "Failed or timed-out runs whose task did not finish by itself within the recovery grace",
|
||||
threshold: t => `= 0 (grace ${Math.round(t.recoveryGraceMs / 60_000)} min)`,
|
||||
evaluate: m => ({ status: m.runsFailedUnrecovered === 0 ? "pass" : "fail", observed: m.runsFailedUnrecovered }),
|
||||
},
|
||||
{
|
||||
id: "failed_run_rate", source: "harness", immediate: false,
|
||||
description: "Failed or timed-out runs as a share of ended runs, recovered ones included (%)",
|
||||
threshold: t => `<= ${Math.round(t.maxFailedRunRatio * 1_000) / 10}%`,
|
||||
evaluate: (m, t) => m.runsEnded === 0 ? { status: "not_measured", observed: null }
|
||||
: { status: m.runsFailed / m.runsEnded <= t.maxFailedRunRatio ? "pass" : "fail", observed: Math.round((m.runsFailed / m.runsEnded) * 1_000) / 10 },
|
||||
},
|
||||
{
|
||||
id: "tasks_rested_not_done_zero", source: "harness", immediate: false,
|
||||
|
||||
@@ -25,7 +25,14 @@ export interface FakeConfig {
|
||||
runDurationMs: number;
|
||||
capacity: number;
|
||||
failWhenRunningAbove: number;
|
||||
failRun: (startIndex: number) => boolean;
|
||||
retryOnFailure: boolean;
|
||||
recoverFailedRunAfterMs: number | null;
|
||||
retrySameRunAfterMs: number | null;
|
||||
sameRunRetryDurationMs: number | null;
|
||||
unpricedEventsPerAgent: number;
|
||||
terminationDelayMs: number;
|
||||
leaseLingerMs: number;
|
||||
costPerRunUsd: number;
|
||||
boardLatencyMs: (running: number) => number;
|
||||
failRequest: (method: string, path: string, count: number) => { status: number; body: string } | null;
|
||||
@@ -42,6 +49,8 @@ interface FakeRun {
|
||||
startedAt: number | null;
|
||||
finishedAt: number | null;
|
||||
willFail: boolean;
|
||||
recovery: boolean;
|
||||
retryAt?: number | null;
|
||||
}
|
||||
|
||||
export interface RequestLog {
|
||||
@@ -66,6 +75,7 @@ export class FakePaperclip {
|
||||
readonly environmentId = "00000000-0000-4000-8000-0000000000e1";
|
||||
private seq = 0;
|
||||
private agentsCreated = 0;
|
||||
private runsStarted = 0;
|
||||
private counts = new Map<string, number>();
|
||||
|
||||
readonly clock: VirtualClock;
|
||||
@@ -82,7 +92,14 @@ export class FakePaperclip {
|
||||
runDurationMs: 60_000,
|
||||
capacity: Number.POSITIVE_INFINITY,
|
||||
failWhenRunningAbove: Number.POSITIVE_INFINITY,
|
||||
failRun: () => false,
|
||||
retryOnFailure: false,
|
||||
recoverFailedRunAfterMs: null,
|
||||
retrySameRunAfterMs: null,
|
||||
sameRunRetryDurationMs: null,
|
||||
unpricedEventsPerAgent: 0,
|
||||
terminationDelayMs: 0,
|
||||
leaseLingerMs: 0,
|
||||
costPerRunUsd: 0.01,
|
||||
boardLatencyMs: () => 40,
|
||||
failRequest: () => null,
|
||||
@@ -108,7 +125,7 @@ export class FakePaperclip {
|
||||
for (let index = 0; index < count; index += 1) {
|
||||
const id = this.id();
|
||||
this.runs.set(id, { id, agentId: "noise-agent", issueId: "noise-issue", status: "succeeded", createdAt: this.clock.now() + 1e10 + index,
|
||||
startedAt: null, finishedAt: null, willFail: false });
|
||||
startedAt: null, finishedAt: null, willFail: false, recovery: false });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -128,6 +145,7 @@ export class FakePaperclip {
|
||||
advance(): void {
|
||||
const now = this.clock.now();
|
||||
for (const agent of this.agents.values()) {
|
||||
if (agent.lifecycleState === "terminating" && now >= agent.terminatingSince + this.config.terminationDelayMs) agent.lifecycleState = "terminated";
|
||||
const delay = typeof this.config.agentReadyDelayMs === "function" ? this.config.agentReadyDelayMs(agent.index) : this.config.agentReadyDelayMs;
|
||||
if (!["preparing", "verifying"].includes(agent.lifecycleState) || now < agent.createdAt + delay) continue;
|
||||
if (this.config.agentSetupError) {
|
||||
@@ -138,16 +156,38 @@ export class FakePaperclip {
|
||||
agent.status = "idle";
|
||||
}
|
||||
}
|
||||
for (const run of this.runs.values()) {
|
||||
if (run.status !== "failed" || !run.retryAt || now < run.retryAt) continue;
|
||||
run.status = "running";
|
||||
run.startedAt = run.retryAt;
|
||||
run.finishedAt = null;
|
||||
run.retryAt = null;
|
||||
run.willFail = false;
|
||||
run.recovery = true;
|
||||
}
|
||||
for (const run of [...this.runs.values()].sort((a, b) => a.createdAt - b.createdAt)) {
|
||||
if (run.status === "running" && run.startedAt !== null && now >= run.startedAt + this.config.runDurationMs) {
|
||||
run.finishedAt = run.startedAt + this.config.runDurationMs;
|
||||
const duration = run.recovery && this.config.sameRunRetryDurationMs !== null ? this.config.sameRunRetryDurationMs : this.config.runDurationMs;
|
||||
if (run.status === "running" && run.startedAt !== null && now >= run.startedAt + duration) {
|
||||
run.finishedAt = run.startedAt + duration;
|
||||
const issue = this.issues.get(run.issueId)!;
|
||||
if (run.willFail) {
|
||||
run.status = "failed";
|
||||
issue.interruption = this.config.retryOnFailure ? { state: "failed", canRetry: true, retryWait: false } : null;
|
||||
if (this.config.retrySameRunAfterMs !== null) {
|
||||
run.retryAt = run.finishedAt + this.config.retrySameRunAfterMs;
|
||||
issue.interruption = { state: "retry_scheduled", canRetry: true, nextRetryAt: new Date(run.retryAt).toISOString() };
|
||||
}
|
||||
if (this.config.recoverFailedRunAfterMs !== null) {
|
||||
const retryAt = run.finishedAt + this.config.recoverFailedRunAfterMs;
|
||||
issue.interruption = { state: "retry_scheduled", canRetry: true, nextRetryAt: new Date(retryAt).toISOString() };
|
||||
const id = this.id();
|
||||
this.runs.set(id, { id, agentId: run.agentId, issueId: run.issueId, status: "queued", createdAt: retryAt, startedAt: null, finishedAt: null,
|
||||
willFail: false, recovery: true });
|
||||
}
|
||||
} else {
|
||||
run.status = "succeeded";
|
||||
issue.status = "done";
|
||||
issue.interruption = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -156,7 +196,8 @@ export class FakePaperclip {
|
||||
if (this.running() >= this.config.capacity) break;
|
||||
run.status = "running";
|
||||
run.startedAt = Math.max(run.createdAt + this.config.startDelayMs, now - 1_000);
|
||||
run.willFail = this.running() > this.config.failWhenRunningAbove;
|
||||
this.runsStarted += 1;
|
||||
run.willFail = !run.recovery && (this.running() > this.config.failWhenRunningAbove || this.config.failRun(this.runsStarted));
|
||||
this.issues.get(run.issueId)!.status = "in_progress";
|
||||
}
|
||||
}
|
||||
@@ -165,8 +206,7 @@ export class FakePaperclip {
|
||||
const iso = (value: number | null) => value === null ? null : new Date(value).toISOString();
|
||||
return {
|
||||
id: run.id, agentId: run.agentId, issueId: run.issueId, status: run.status, createdAt: iso(run.createdAt), startedAt: iso(run.startedAt),
|
||||
finishedAt: iso(run.finishedAt), costUsd: run.status === "succeeded" || run.status === "failed" ? this.config.costPerRunUsd : null,
|
||||
error: null, errorCode: null,
|
||||
finishedAt: iso(run.finishedAt), costUsd: null, error: null, errorCode: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -227,8 +267,18 @@ export class FakePaperclip {
|
||||
this.projects.set(id, { id, companyId, name: body.name, archivedAt: null });
|
||||
return json(201, this.projects.get(id));
|
||||
}
|
||||
if (c === "costs" && parts[3] === "by-agent" && method === "GET") {
|
||||
const cents = new Map<string, number>();
|
||||
const month = new Date(now).toISOString().slice(0, 7);
|
||||
for (const run of this.runs.values()) {
|
||||
if (run.status !== "succeeded" && run.status !== "failed") continue;
|
||||
if (query.get("period") !== "all" && new Date(run.finishedAt!).toISOString().slice(0, 7) !== month) continue;
|
||||
cents.set(run.agentId, (cents.get(run.agentId) ?? 0) + this.config.costPerRunUsd * 100);
|
||||
}
|
||||
return json(200, [...cents].map(([agentId, costCents]) => ({ agentId, costCents, unpricedEventCount: this.config.unpricedEventsPerAgent })));
|
||||
}
|
||||
if (c === "agents") {
|
||||
if (method === "GET") return json(200, [...this.agents.values()].filter(agent => agent.companyId === companyId));
|
||||
if (method === "GET") return json(200, [...this.agents.values()].filter(agent => agent.companyId === companyId && agent.status !== "terminated"));
|
||||
const id = this.id();
|
||||
this.agents.set(id, { id, companyId, name: body.name, status: "paused", lifecycleState: "preparing", lifecycleHolds: [], lifecycleError: null,
|
||||
pauseReason: null, createdAt: now, index: this.agentsCreated++, payload: body });
|
||||
@@ -242,7 +292,8 @@ export class FakePaperclip {
|
||||
const agent = this.agents.get(body.assigneeAgentId);
|
||||
if (agent && agent.status !== "terminated") {
|
||||
const runId = this.id();
|
||||
this.runs.set(runId, { id: runId, agentId: body.assigneeAgentId, issueId: id, status: "queued", createdAt: now, startedAt: null, finishedAt: null, willFail: false });
|
||||
this.runs.set(runId, { id: runId, agentId: body.assigneeAgentId, issueId: id, status: "queued", createdAt: now, startedAt: null, finishedAt: null,
|
||||
willFail: false, recovery: false });
|
||||
}
|
||||
return json(201, this.issues.get(id));
|
||||
}
|
||||
@@ -267,16 +318,19 @@ export class FakePaperclip {
|
||||
if (a === "agents" && b) {
|
||||
const agent = this.agents.get(b);
|
||||
if (!agent) return json(404, { error: "Agent not found" });
|
||||
if (method === "GET" && !c) return json(200, agent);
|
||||
if (method === "PATCH") {
|
||||
Object.assign(agent, body);
|
||||
return json(200, agent);
|
||||
}
|
||||
if (method === "POST" && c === "terminate") {
|
||||
agent.status = "terminated";
|
||||
agent.lifecycleState = "terminated";
|
||||
agent.lifecycleState = this.config.terminationDelayMs > 0 ? "terminating" : "terminated";
|
||||
agent.terminatingSince = now;
|
||||
return json(200, agent);
|
||||
}
|
||||
if (method === "DELETE") {
|
||||
if (agent.lifecycleState !== "terminated") return json(409, { error: "Complete termination before deleting the agent" });
|
||||
this.agents.delete(b);
|
||||
return json(200, { ok: true });
|
||||
}
|
||||
@@ -324,7 +378,10 @@ export class FakePaperclip {
|
||||
return json(200, project);
|
||||
}
|
||||
if (a === "environments" && b === this.environmentId && c === "leases") {
|
||||
return json(200, this.liveRuns().map(run => ({ id: run.id, issueId: run.issueId, status: "active" })));
|
||||
const held = [...this.runs.values()].filter(run => ["queued", "running"].includes(run.status)
|
||||
|| (run.finishedAt !== null && now < run.finishedAt + this.config.leaseLingerMs));
|
||||
return json(200, held.map(run => ({ id: `lease-${run.id}`, issueId: run.issueId, heartbeatRunId: run.id, status: "active",
|
||||
acquiredAt: new Date(run.createdAt).toISOString(), metadata: { agentId: run.agentId } })));
|
||||
}
|
||||
return json(404, { error: `fake: no route for ${method} ${route}` });
|
||||
}
|
||||
|
||||
+106
-24
@@ -1,9 +1,9 @@
|
||||
import { readMetrics, type Clock, type Fetcher, type PaperclipClient } from "./client.ts";
|
||||
import { pathClass, readMetrics, type Clock, type Fetcher, type PaperclipClient } from "./client.ts";
|
||||
import type { Options, Step } from "./config.ts";
|
||||
import { evaluate, firstFailure, type CriterionResult, type ServerMetrics, type StepMetrics } from "./criteria.ts";
|
||||
import { LIVE_RUN_STATUSES } from "./cleanup.ts";
|
||||
import { AgentsNotReady, describeAgent, ensureAgents, waitForAgentsReady } from "./setup.ts";
|
||||
import { distribution } from "./stats.ts";
|
||||
import { distribution, type Distribution } from "./stats.ts";
|
||||
import { mapLimit, taskTag, type RunState, type StateStore } from "./state.ts";
|
||||
import { runTiming, taskBrief, taskNonce, taskTitle, type RunEvent } from "./workload.ts";
|
||||
|
||||
@@ -27,6 +27,7 @@ const RETRY_RECHECK_MS = 30_000;
|
||||
const EVENT_FETCHES_PER_TICK = 10;
|
||||
const EVENT_PAGES = 4;
|
||||
const SINGLE_READS_PER_TICK = 50;
|
||||
const SPEND_READ_FAILURES_TO_STOP = 3;
|
||||
const AGENT_RUN_PAGE = 20;
|
||||
const AGENT_RUN_READ_PARALLELISM = 8;
|
||||
|
||||
@@ -50,7 +51,8 @@ interface RunRecord {
|
||||
createdAt: number | null;
|
||||
startedAt: number | null;
|
||||
finishedAt: number | null;
|
||||
costUsd: number;
|
||||
everFailed: boolean;
|
||||
everEnded: boolean;
|
||||
sampled: boolean;
|
||||
error: string | null;
|
||||
errorCode: string | null;
|
||||
@@ -63,12 +65,14 @@ interface StepAccumulator {
|
||||
endedAt: number | null;
|
||||
runningSamples: number[];
|
||||
boardMs: number[];
|
||||
boardByRoute: Record<string, number[]>;
|
||||
boardRequests: number;
|
||||
boardFailures: number;
|
||||
serverSamples: Array<Record<string, unknown>>;
|
||||
ttftMs: number[];
|
||||
firstActivityMs: number[];
|
||||
sampled: number;
|
||||
spendAtStartUsd: number;
|
||||
}
|
||||
|
||||
export interface StepResult {
|
||||
@@ -93,7 +97,9 @@ export interface RampOutcome {
|
||||
openTasksAtEnd: number;
|
||||
tasksCreated: number;
|
||||
taskCapReached: boolean;
|
||||
recordedSpendUsd: number;
|
||||
recordedSpendUsd: number | null;
|
||||
spendReadError: string | null;
|
||||
unpricedCostEvents: number;
|
||||
runsListTruncated: boolean;
|
||||
metricsSource: "endpoint" | "not provided" | "unavailable";
|
||||
}
|
||||
@@ -192,6 +198,10 @@ export class Ramp {
|
||||
private nextBoardAt = 0;
|
||||
private nextPollAt = 0;
|
||||
private taskCapReached = false;
|
||||
private spendUsd: number | null = null;
|
||||
private spendReadFailures = 0;
|
||||
private spendReadError: string | null = null;
|
||||
private unpricedCostEvents = 0;
|
||||
private fallbackCursor = 0;
|
||||
private runsListTruncated = false;
|
||||
private metricsSource: RampOutcome["metricsSource"];
|
||||
@@ -220,8 +230,8 @@ export class Ramp {
|
||||
break;
|
||||
}
|
||||
log(`Step ${step.index + 1}/${options.steps.length}: ${step.concurrency} agents for ${Math.round(step.holdMs / 60_000)} min`);
|
||||
const accumulator: StepAccumulator = { step, startedAt: clock.now(), endedAt: null, runningSamples: [], boardMs: [], boardRequests: 0,
|
||||
boardFailures: 0, serverSamples: [], ttftMs: [], firstActivityMs: [], sampled: 0 };
|
||||
const accumulator: StepAccumulator = { step, startedAt: clock.now(), endedAt: null, runningSamples: [], boardMs: [], boardByRoute: {}, boardRequests: 0,
|
||||
boardFailures: 0, serverSamples: [], ttftMs: [], firstActivityMs: [], sampled: 0, spendAtStartUsd: this.spendUsd ?? 0 };
|
||||
this.accumulators.push(accumulator);
|
||||
stop = await this.prepareStep(step);
|
||||
if (!stop) {
|
||||
@@ -249,13 +259,15 @@ export class Ramp {
|
||||
const last = this.current();
|
||||
last.endedAt = clock.now();
|
||||
}
|
||||
const finalSpendRead = await this.readSpend();
|
||||
for (const result of results) {
|
||||
result.metrics = this.metrics(result.index);
|
||||
result.criteriaFinal = evaluate(result.metrics, options.thresholds);
|
||||
}
|
||||
return {
|
||||
steps: results, stop, drained, openTasksAtEnd: this.openTasks().length, tasksCreated: this.tasks.size, taskCapReached: this.taskCapReached,
|
||||
recordedSpendUsd: this.recordedSpend(), runsListTruncated: this.runsListTruncated, metricsSource: this.metricsSource,
|
||||
recordedSpendUsd: finalSpendRead ? this.spendUsd : null, spendReadError: finalSpendRead ? null : this.spendReadError,
|
||||
unpricedCostEvents: this.unpricedCostEvents, runsListTruncated: this.runsListTruncated, metricsSource: this.metricsSource,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -374,8 +386,17 @@ export class Ramp {
|
||||
}
|
||||
|
||||
private immediateStop(stepIndex: number): StopReason | null {
|
||||
if (this.recordedSpend() > this.deps.spendCapUsd) {
|
||||
return { stepIndex, reason: `recorded model spend $${this.recordedSpend().toFixed(2)} passed the cap of $${this.deps.spendCapUsd}`, criterion: "spend_cap" };
|
||||
if ((this.spendUsd ?? 0) > this.deps.spendCapUsd) {
|
||||
return { stepIndex, reason: `recorded model spend $${this.spendUsd!.toFixed(2)} passed the cap of $${this.deps.spendCapUsd}`, criterion: "spend_cap" };
|
||||
}
|
||||
const bound = this.unpricedSpendBoundUsd();
|
||||
if (bound !== null && bound > this.deps.spendCapUsd) {
|
||||
return { stepIndex, reason: `${this.unpricedCostEvents} cost events have no known price, so the spend cap uses tasks created x $${this.deps.options.pricing.modelUsdPerTask}`
|
||||
+ ` per task: $${bound.toFixed(2)} passed the cap of $${this.deps.spendCapUsd}`, criterion: "spend_cap" };
|
||||
}
|
||||
if (this.spendReadFailures >= SPEND_READ_FAILURES_TO_STOP) {
|
||||
return { stepIndex, reason: `recorded model spend could not be read ${this.spendReadFailures} times in a row, so the spend cap cannot be enforced: ${this.spendReadError}`,
|
||||
criterion: "spend_unreadable" };
|
||||
}
|
||||
for (const accumulator of this.accumulators) {
|
||||
const failed = firstFailure(evaluate(this.metrics(accumulator.step.index), this.deps.options.thresholds, true));
|
||||
@@ -388,10 +409,39 @@ export class Ramp {
|
||||
return [...this.tasks.values()].filter(task => task.outcome === "open");
|
||||
}
|
||||
|
||||
private recordedSpend(): number {
|
||||
let total = 0;
|
||||
for (const run of this.runs.values()) total += run.costUsd;
|
||||
return Math.round(total * 100) / 100;
|
||||
private unpricedSpendBoundUsd(): number | null {
|
||||
if (this.unpricedCostEvents === 0) return null;
|
||||
return Math.round(this.tasks.size * this.deps.options.pricing.modelUsdPerTask * 100) / 100;
|
||||
}
|
||||
|
||||
private async readSpend(): Promise<boolean> {
|
||||
const agentIds = new Set(this.deps.state.agentIds);
|
||||
if (!agentIds.size) return this.spendReadFailures === 0;
|
||||
let rows: unknown;
|
||||
try {
|
||||
rows = await this.deps.api.get<unknown>(`/api/companies/${this.companyId}/costs/by-agent?period=all`);
|
||||
if (!Array.isArray(rows)) throw new Error("costs by agent did not return a list");
|
||||
} catch (error) {
|
||||
this.spendReadFailures += 1;
|
||||
this.spendReadError = error instanceof Error ? error.message : String(error);
|
||||
return false;
|
||||
}
|
||||
this.spendReadFailures = 0;
|
||||
this.spendReadError = null;
|
||||
let cents = 0;
|
||||
let unpriced = 0;
|
||||
for (const row of rows as Json[]) {
|
||||
if (!agentIds.has(String(row.agentId))) continue;
|
||||
cents += num(row.costCents) ?? 0;
|
||||
unpriced += num(row.unpricedEventCount) ?? 0;
|
||||
}
|
||||
if (unpriced > 0 && this.unpricedCostEvents === 0) {
|
||||
this.deps.log(`Warning: ${unpriced} cost events of this run have no known price. Recorded spend is a lower bound, so the spend cap now uses`
|
||||
+ ` tasks created x $${this.deps.options.pricing.modelUsdPerTask} per task (PAPERCLIP_SCALE_MODEL_USD_PER_TASK)`);
|
||||
}
|
||||
this.unpricedCostEvents = unpriced;
|
||||
this.spendUsd = Math.round(cents) / 100;
|
||||
return true;
|
||||
}
|
||||
|
||||
private async topUp(concurrency: number, stepIndex: number, until: number): Promise<void> {
|
||||
@@ -425,12 +475,18 @@ export class Ramp {
|
||||
const accumulator = this.current();
|
||||
for (const route of BOARD_MIX) {
|
||||
const before = this.deps.api.records.length;
|
||||
await this.deps.api.get(route(this.companyId), "board").catch(() => null);
|
||||
const path = route(this.companyId);
|
||||
await this.deps.api.get(path, "board").catch(() => null);
|
||||
const record = this.deps.api.records[before];
|
||||
if (!record) continue;
|
||||
accumulator.boardRequests += 1;
|
||||
if (record.ok) accumulator.boardMs.push(record.ms);
|
||||
else accumulator.boardFailures += 1;
|
||||
if (!record.ok) {
|
||||
accumulator.boardFailures += 1;
|
||||
continue;
|
||||
}
|
||||
accumulator.boardMs.push(record.ms);
|
||||
const name = pathClass(path).split("/").at(-1)!;
|
||||
(accumulator.boardByRoute[name] ??= []).push(record.ms);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -439,6 +495,7 @@ export class Ramp {
|
||||
await this.readTasks();
|
||||
await this.checkRetry();
|
||||
await this.sampleEvents();
|
||||
await this.readSpend();
|
||||
let running = 0;
|
||||
for (const run of this.runs.values()) if (run.status === "running") running += 1;
|
||||
if (!recordSample) return;
|
||||
@@ -457,9 +514,11 @@ export class Ramp {
|
||||
if (!this.tasks.has(taskId)) return;
|
||||
const id = String(row.id ?? row.runId);
|
||||
const previous = this.runs.get(id);
|
||||
const status = String(row.status);
|
||||
this.runs.set(id, {
|
||||
id, taskId, agentId: String(row.agentId), status: String(row.status), createdAt: ms(row.createdAt), startedAt: ms(row.startedAt),
|
||||
finishedAt: ms(row.finishedAt), costUsd: num(row.costUsd) ?? previous?.costUsd ?? 0, sampled: previous?.sampled ?? false,
|
||||
id, taskId, agentId: String(row.agentId), status, createdAt: ms(row.createdAt), startedAt: ms(row.startedAt),
|
||||
finishedAt: ms(row.finishedAt), everFailed: (previous?.everFailed ?? false) || FAILED_RUN.has(status),
|
||||
everEnded: (previous?.everEnded ?? false) || ENDED_RUN.has(status), sampled: previous?.sampled ?? false,
|
||||
error: typeof row.error === "string" && row.error ? row.error : null,
|
||||
errorCode: typeof row.errorCode === "string" && row.errorCode ? row.errorCode : null,
|
||||
liveness: typeof row.livenessReason === "string" && row.livenessReason ? row.livenessReason : null,
|
||||
@@ -532,7 +591,9 @@ export class Ramp {
|
||||
if (task.outcome === "failed" && task.lastRetryCheckAt !== null) continue;
|
||||
task.lastRetryCheckAt = now;
|
||||
const view = await this.deps.api.get<Json>(`/api/issues/${task.id}`).catch(() => null);
|
||||
if (view && view.status !== "done" && view.interruption?.canRetry === true && !view.interruption?.retryWait) {
|
||||
const interruption = view?.interruption;
|
||||
const systemRetrying = interruption?.state === "retry_scheduled" || Boolean(interruption?.nextRetryAt) || Boolean(interruption?.retryWait);
|
||||
if (view && view.status !== "done" && interruption?.canRetry === true && !systemRetrying) {
|
||||
task.neededRetry = true;
|
||||
this.deps.log(`Task ${task.nonce} offers Retry`);
|
||||
}
|
||||
@@ -576,8 +637,10 @@ export class Ramp {
|
||||
if (known === undefined || run.startedAt < known) firstStart.set(run.taskId, run.startedAt);
|
||||
}
|
||||
const samples = accumulator.runningSamples;
|
||||
let spend = 0;
|
||||
for (const run of runs) spend += run.costUsd;
|
||||
const failed = this.classifyFailedRuns(runs);
|
||||
const spendAtEnd = this.accumulators[stepIndex + 1]?.spendAtStartUsd ?? this.spendUsd ?? 0;
|
||||
const byRoute: Record<string, Distribution> = {};
|
||||
for (const [name, values] of Object.entries(accumulator.boardByRoute)) byRoute[name] = distribution(values);
|
||||
return {
|
||||
step: accumulator.step,
|
||||
startedAt: accumulator.startedAt,
|
||||
@@ -587,7 +650,11 @@ export class Ramp {
|
||||
tasksFinished: tasks.filter(task => task.outcome === "done").length,
|
||||
tasksFailed: tasks.filter(task => task.outcome === "failed").length,
|
||||
tasksNeedingRetry: tasks.filter(task => task.neededRetry).length,
|
||||
runsFailed: runs.filter(run => FAILED_RUN.has(run.status)).length,
|
||||
runsEnded: runs.filter(run => run.everEnded).length,
|
||||
runsFailed: failed.recovered + failed.unrecovered + failed.pending,
|
||||
runsFailedRecovered: failed.recovered,
|
||||
runsFailedUnrecovered: failed.unrecovered,
|
||||
runsFailedPending: failed.pending,
|
||||
runsInterrupted: runs.filter(run => run.status === "interrupted").length,
|
||||
runsCancelled: runs.filter(run => run.status === "cancelled").length,
|
||||
peakRunning: samples.length ? Math.max(...samples) : 0,
|
||||
@@ -597,12 +664,27 @@ export class Ramp {
|
||||
ttftMs: distribution(accumulator.ttftMs),
|
||||
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) },
|
||||
board: { requests: accumulator.boardRequests, failures: accumulator.boardFailures, ms: distribution(accumulator.boardMs), byRoute },
|
||||
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,
|
||||
recordedSpendUsd: Math.round(Math.max(0, spendAtEnd - accumulator.spendAtStartUsd) * 100) / 100,
|
||||
};
|
||||
}
|
||||
|
||||
private classifyFailedRuns(runs: readonly RunRecord[]): { recovered: number; unrecovered: number; pending: number } {
|
||||
const now = this.deps.clock.now();
|
||||
const out = { recovered: 0, unrecovered: 0, pending: 0 };
|
||||
for (const run of runs) {
|
||||
if (!run.everFailed) continue;
|
||||
const task = this.tasks.get(run.taskId)!;
|
||||
const live = this.runsOf(task.id).some(candidate => LIVE_RUN_STATUSES.has(candidate.status));
|
||||
if (task.outcome === "done") out.recovered += 1;
|
||||
else if (task.outcome === "failed" || task.neededRetry) out.unrecovered += 1;
|
||||
else if (!live && run.finishedAt !== null && now - run.finishedAt >= this.deps.options.thresholds.recoveryGraceMs) out.unrecovered += 1;
|
||||
else out.pending += 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ export interface RampResult {
|
||||
tasksCreated: number;
|
||||
taskCapReached: boolean;
|
||||
recordedSpendUsd: number | null;
|
||||
unpricedCostEvents: number;
|
||||
sources: Record<string, string>;
|
||||
cleanup: CleanupReport | null;
|
||||
requests: { total: number; failed: number };
|
||||
@@ -53,6 +54,10 @@ export function incompleteReasons(outcome: RampOutcome | null): string[] {
|
||||
const missing = notMeasured(outcome);
|
||||
if (missing.length) reasons.push(`criteria not measured: ${missing.join(", ")}`);
|
||||
if (outcome.taskCapReached) reasons.push("the task cap was reached, so a step may have run below its concurrency");
|
||||
if (outcome.recordedSpendUsd === null) reasons.push("recorded model spend could not be read at the end of the run");
|
||||
if (outcome.unpricedCostEvents > 0) {
|
||||
reasons.push(`${outcome.unpricedCostEvents} cost events have no known price, so recorded spend is a lower bound and the spend cap does not cover them`);
|
||||
}
|
||||
if (outcome.openTasksAtEnd > 0) reasons.push(`${outcome.openTasksAtEnd} tasks were still open when the drain ended`);
|
||||
return reasons;
|
||||
}
|
||||
@@ -100,9 +105,13 @@ export function buildResult(input: {
|
||||
tasksCreated: outcome?.tasksCreated ?? 0,
|
||||
taskCapReached: outcome?.taskCapReached ?? false,
|
||||
recordedSpendUsd: outcome ? outcome.recordedSpendUsd : null,
|
||||
unpricedCostEvents: outcome?.unpricedCostEvents ?? 0,
|
||||
sources: {
|
||||
runsAndTasks: outcome?.runsListTruncated ? "API (company run list was full; open tasks without a listed run were read one by one)" : "API",
|
||||
boardLatency: "harness GET mix (dashboard, issues, agents, live runs, sidebar badges)",
|
||||
boardLatency: "harness GET mix (dashboard, issues, agents, live runs, sidebar badges), with a distribution per route",
|
||||
modelSpend: outcome?.spendReadError ? `not measured: the last read of costs by agent failed (${outcome.spendReadError})`
|
||||
: `costs by agent for the run's agents over all time (Paperclip's recorded cost events)${outcome?.unpricedCostEvents
|
||||
? `; ${outcome.unpricedCostEvents} events have no known price and are not included` : ""}`,
|
||||
firstTokenAndActivity: `run events of up to ${options.eventSamplePerStep} succeeded runs per step`,
|
||||
serverMetrics: outcome?.metricsSource === "endpoint" ? "PAPERCLIP_SCALE_METRICS_URL"
|
||||
: outcome?.metricsSource === "unavailable" ? "PAPERCLIP_SCALE_METRICS_URL gave no readable sample: not measured" : "not provided: not measured",
|
||||
@@ -129,7 +138,8 @@ export function summaryLines(result: RampResult): string[] {
|
||||
"",
|
||||
`Verdict: **${result.verdict}**. Target ${result.target.baseUrl} (${result.target.kind}).`,
|
||||
result.stop ? `Stopped at step ${result.stop.stepIndex + 1}: ${result.stop.reason}.` : "No stop.",
|
||||
`Tasks created: ${result.tasksCreated}${result.taskCapReached ? " (task cap reached)" : ""}. Recorded model spend: ${result.recordedSpendUsd === null ? "not measured" : `$${result.recordedSpendUsd}`}; estimate was $${result.plan.estimate.totalUsd}.`,
|
||||
`Tasks created: ${result.tasksCreated}${result.taskCapReached ? " (task cap reached)" : ""}. Recorded model spend: ${result.recordedSpendUsd === null ? "not measured" : `$${result.recordedSpendUsd}`}`
|
||||
+ `${result.unpricedCostEvents ? ` (incomplete: ${result.unpricedCostEvents} cost events have no known price)` : ""}; estimate was $${result.plan.estimate.totalUsd}.`,
|
||||
"",
|
||||
];
|
||||
for (const step of result.steps) {
|
||||
@@ -138,13 +148,15 @@ export function summaryLines(result: RampResult): string[] {
|
||||
`## Step ${step.index + 1}: ${step.concurrency} agents, ${step.holdMs / 60_000} min`,
|
||||
"",
|
||||
`- Tasks created / started / finished / failed / needed Retry: ${m.tasksCreated} / ${m.tasksStarted} / ${m.tasksFinished} / ${m.tasksFailed} / ${m.tasksNeedingRetry}`,
|
||||
`- Runs failed / interrupted / cancelled: ${m.runsFailed} / ${m.runsInterrupted} / ${m.runsCancelled}`,
|
||||
`- Runs ended / failed / interrupted / cancelled: ${m.runsEnded} / ${m.runsFailed} / ${m.runsInterrupted} / ${m.runsCancelled}`,
|
||||
`- Failed runs whose task finished by itself / did not / still pending: ${m.runsFailedRecovered} / ${m.runsFailedUnrecovered} / ${m.runsFailedPending}`,
|
||||
`- Running agents peak / mean: ${m.peakRunning} / ${m.meanRunning ?? "not measured"}`,
|
||||
`- Queue wait p50 / p95 / p99: ${dist(m.queueWaitMs, seconds)}`,
|
||||
`- Time to first token p50 / p95 / p99: ${dist(m.ttftMs, seconds)}`,
|
||||
`- First activity p50 / p95 / p99: ${dist(m.firstActivityMs, seconds)}`,
|
||||
`- Run duration p50 / p95 / p99: ${dist(m.runDurationMs, seconds)}`,
|
||||
`- Board API p50 / p95 / p99: ${dist(m.board.ms, millis)}; failed ${m.board.failures} of ${m.board.requests}`,
|
||||
...Object.entries(m.board.byRoute).map(([route, d]) => ` - ${route} p50 / p90 / p99: ${millis(d.p50)} / ${millis(d.p90)} / ${millis(d.p99)} (n=${d.n})`),
|
||||
`- Event-loop utilization max: ${m.server.eventLoopUtilizationMax ?? "not measured"}; delay p99 max: ${millis(m.server.eventLoopDelayP99MsMax)}; statements/s max: ${m.server.statementsPerSecondMax ?? "not measured"}; pool wait p99 max: ${millis(m.server.poolWaitP99MsMax)}`,
|
||||
"- Criteria (final):",
|
||||
...step.criteriaFinal.map(criterionLine),
|
||||
@@ -157,7 +169,9 @@ export function summaryLines(result: RampResult): string[] {
|
||||
if (result.cleanup) {
|
||||
const c = result.cleanup;
|
||||
lines.push(`Cleanup in ${seconds(c.durationMs)}: ${c.runsCancelled} runs cancelled, ${c.tasksArchived} tasks archived, ${c.agentsDeleted} agents deleted`
|
||||
+ ` (${c.agentsKeptForCostHistory} kept terminated for cost history), sandbox leases still active: ${c.activeSandboxLeases ?? "not readable"}, errors: ${c.errors.length}.`);
|
||||
+ ` (${c.agentsKeptForCostHistory} kept terminated for cost history, ${c.agentsStillTerminating.length} still terminating),`
|
||||
+ ` sandbox leases still active: ${c.activeSandboxLeases ?? "not readable"} (${c.sandboxLeasesReleasedDuringWait} released while the cleanup waited), errors: ${c.errors.length}.`);
|
||||
for (const error of c.errors) lines.push(`- ${error}`);
|
||||
}
|
||||
if (result.error) lines.push(`Error: ${result.error}`);
|
||||
return lines;
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readdir, readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { describe, it } from "node:test";
|
||||
import { PaperclipClient, Redactor } from "./client.ts";
|
||||
import { parseOptions, QUALIFIED_OPENCODE_MODEL } from "./config.ts";
|
||||
import { checkSpend, estimateSpend } from "./estimate.ts";
|
||||
import { EXIT, main } from "./main.ts";
|
||||
import { Ramp } from "./ramp.ts";
|
||||
import { prepareCompany } from "./setup.ts";
|
||||
import { emptyState, fileStateStore, type RunState } from "./state.ts";
|
||||
import { baseArgs, goodMetrics, harness, METRICS_URL, ORIGIN, PROVIDER_KEY, readResult, tempDir, TOKEN } from "./test-harness.ts";
|
||||
|
||||
describe("dry run and spend", () => {
|
||||
it("prints the plan and estimate and touches nothing", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness();
|
||||
const code = await main(["--base-url", ORIGIN, "--target-kind", "test-stack", "--out", out, "--dry-run"], h.deps);
|
||||
assert.equal(code, EXIT.pass);
|
||||
assert.equal(h.fetchCalls(), 0);
|
||||
assert.deepEqual(await readdir(out), []);
|
||||
const text = h.out.join("\n");
|
||||
assert.match(text, /Ramp: 10 -> 50 -> 100 -> 200 -> 500 -> 1000 agents/);
|
||||
assert.match(text, /Estimated spend: \$\d/);
|
||||
assert.match(text, /retry_needed_zero \[finish-line\]/);
|
||||
assert.match(text, /Dry run: nothing was created or contacted/);
|
||||
});
|
||||
|
||||
it("estimates tasks, sandbox-hours and cost from the steps", () => {
|
||||
const options = parseOptions(["--base-url", ORIGIN, "--target-kind", "test-stack", "--steps", "10,50", "--hold-minutes", "10", "--task-minutes", "5",
|
||||
"--drain-minutes", "10"], {}, 0);
|
||||
const estimate = estimateSpend(options);
|
||||
assert.equal(estimate.agents, 50);
|
||||
assert.equal(estimate.tasks, 10 * 2 + 50 * 2);
|
||||
assert.equal(estimate.maxTasks, 150);
|
||||
assert.equal(estimate.sandboxHours, 18.3);
|
||||
assert.equal(estimate.modelUsd, 3);
|
||||
assert.equal(estimate.totalUsd, 4.83);
|
||||
});
|
||||
|
||||
it("requires --confirm-spend of at least the estimate above the threshold", async () => {
|
||||
const estimate = { totalUsd: 120 } as ReturnType<typeof estimateSpend>;
|
||||
assert.equal(checkSpend(estimate, 5, null).ok, false);
|
||||
assert.equal(checkSpend(estimate, 5, 100).ok, false);
|
||||
assert.equal(checkSpend(estimate, 5, 130).ok, true);
|
||||
assert.equal(checkSpend(estimate, 200, null).ok, true);
|
||||
const out = await tempDir();
|
||||
const h = harness();
|
||||
const code = await main(["--base-url", ORIGIN, "--target-kind", "test-stack", "--out", out, "--yes"], h.deps);
|
||||
assert.equal(code, EXIT.usage);
|
||||
assert.equal(h.fetchCalls(), 0);
|
||||
assert.match(h.err.join("\n"), /--confirm-spend/);
|
||||
});
|
||||
|
||||
it("defaults to the qualified OpenCode model of the runner", async () => {
|
||||
const source = await readFile(path.join(import.meta.dirname, "../../packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts"), "utf8");
|
||||
const match = /QUALIFIED_OPENCODE_MODEL\s*=\s*"([^"]+)"/.exec(source);
|
||||
assert.equal(match?.[1], QUALIFIED_OPENCODE_MODEL);
|
||||
});
|
||||
});
|
||||
|
||||
describe("recorded model spend", () => {
|
||||
it("records model spend from Paperclip's cost records, which the run list does not carry", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness({ costPerRunUsd: 0.25 });
|
||||
await main(baseArgs(out, ["--steps", "2", "--drain-minutes", "0"]), h.deps);
|
||||
const result = await readResult(out);
|
||||
const finished = [...h.fake.runs.values()].filter(run => run.status === "succeeded").length;
|
||||
assert.ok(finished > 0);
|
||||
assert.equal(result.recordedSpendUsd, Math.round(finished * 25) / 100);
|
||||
assert.equal(result.steps[0]!.metrics.recordedSpendUsd, result.recordedSpendUsd);
|
||||
const capped = await tempDir();
|
||||
const h2 = harness({ costPerRunUsd: 3 });
|
||||
await main(baseArgs(capped, ["--steps", "2", "--hold-minutes", "20"]), h2.deps);
|
||||
assert.equal((await readResult(capped)).stop!.criterion, "spend_cap");
|
||||
});
|
||||
|
||||
it("keeps the spend of a ramp that crosses a month boundary", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness({ costPerRunUsd: 0.25 });
|
||||
h.clock.t = Date.parse("2026-11-30T23:58:00.000Z");
|
||||
await main(baseArgs(out, ["--steps", "2"]), h.deps);
|
||||
const result = await readResult(out);
|
||||
const finished = [...h.fake.runs.values()].filter(run => run.status === "succeeded");
|
||||
assert.ok(finished.some(run => new Date(run.finishedAt!).getUTCMonth() === 10), "some spend is in the earlier month");
|
||||
assert.ok(finished.some(run => new Date(run.finishedAt!).getUTCMonth() === 11), "some spend is in the later month");
|
||||
assert.equal(result.recordedSpendUsd, Math.round(finished.length * 25) / 100);
|
||||
});
|
||||
|
||||
it("grades a run incomplete when some cost events have no known price", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness({ metricsUrl: METRICS_URL, metrics: goodMetrics, unpricedEventsPerAgent: 1 }, { PAPERCLIP_SCALE_METRICS_URL: METRICS_URL });
|
||||
await main(baseArgs(out, ["--steps", "2"]), h.deps);
|
||||
const result = await readResult(out);
|
||||
assert.equal(result.verdict, "incomplete");
|
||||
assert.ok(result.incompleteReasons.some(reason => /2 cost events have no known price/.test(reason)), result.incompleteReasons.join("; "));
|
||||
assert.match(result.sources.modelSpend!, /no known price/);
|
||||
assert.equal(result.unpricedCostEvents, 2);
|
||||
assert.match(await readFile(path.join(out, "scale-test-run", "SUMMARY.md"), "utf8"), /incomplete: 2 cost events have no known price/);
|
||||
assert.ok(h.out.some(line => /^Warning: \d+ cost events of this run have no known price/.test(line)));
|
||||
});
|
||||
|
||||
it("stops on a conservative spend bound when cost events have no known price", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness({ costPerRunUsd: 0, unpricedEventsPerAgent: 1 }, { PAPERCLIP_SCALE_MODEL_USD_PER_TASK: "0.5" });
|
||||
const options = parseOptions(baseArgs(out, ["--steps", "2", "--hold-minutes", "20"]), h.deps.env, h.clock.now());
|
||||
const api = new PaperclipClient(options.target, TOKEN, h.deps.fetcher, h.clock, new Redactor([TOKEN]));
|
||||
const state: RunState = emptyState(options.label, options.target.baseUrl, h.clock.now());
|
||||
const store = fileStateStore(options.outDir);
|
||||
await prepareCompany({ api, options, state, store, credential: PROVIDER_KEY, log: () => {} });
|
||||
const outcome = await new Ramp({ api, clock: h.clock, fetcher: h.deps.fetcher, options, state, store, maxTasks: 100, spendCapUsd: 2, metricsToken: null,
|
||||
log: () => {}, shouldStop: () => false }).run();
|
||||
assert.equal(outcome.recordedSpendUsd, 0);
|
||||
assert.equal(outcome.stop!.criterion, "spend_cap");
|
||||
assert.match(outcome.stop!.reason, /no known price.*passed the cap of \$2/);
|
||||
assert.ok(outcome.tasksCreated >= 5 && outcome.tasksCreated <= 6, `tasks: ${outcome.tasksCreated}`);
|
||||
});
|
||||
|
||||
it("stops when recorded spend cannot be read, and reports spend as not measured", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness({ failRequest: (method, route, count) => method === "GET" && route.endsWith("/costs/by-agent") && count > 2
|
||||
? { status: 503, body: "{\"error\":\"unavailable\"}" } : null });
|
||||
const code = await main(baseArgs(out, ["--steps", "2", "--hold-minutes", "20"]), h.deps);
|
||||
const result = await readResult(out);
|
||||
assert.equal(code, EXIT.fail);
|
||||
assert.equal(result.stop!.criterion, "spend_unreadable");
|
||||
assert.match(result.stop!.reason, /could not be read 3 times in a row/);
|
||||
assert.equal(result.recordedSpendUsd, null);
|
||||
assert.match(result.sources.modelSpend!, /not measured/);
|
||||
});
|
||||
|
||||
});
|
||||
@@ -1,100 +1,21 @@
|
||||
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 { readdir, readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { after, describe, it } from "node:test";
|
||||
import { describe, it } from "node:test";
|
||||
import { cleanupRun } from "./cleanup.ts";
|
||||
import { PaperclipClient, Redactor } from "./client.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 { EXIT, main } from "./main.ts";
|
||||
import { Ramp, serverMetrics } from "./ramp.ts";
|
||||
import { verdictOf, type RampResult } from "./report.ts";
|
||||
import { verdictOf } from "./report.ts";
|
||||
import { ensureAgents, prepareCompany } from "./setup.ts";
|
||||
import { distribution } from "./stats.ts";
|
||||
import { emptyState, fileStateStore, mapLimit, type RunState } from "./state.ts";
|
||||
import { agentName, emptyState, fileStateStore, mapLimit, type RunState } from "./state.ts";
|
||||
import { runTiming } from "./workload.ts";
|
||||
|
||||
const TOKEN = "board-token-SECRET-4f2a9c";
|
||||
const PROVIDER_KEY = "sk-or-v1-SECRET-provider-key-77";
|
||||
const METRICS_TOKEN = "metrics-token-SECRET-91";
|
||||
const HOST = "scale1.test.paperclip.app";
|
||||
const ORIGIN = `https://${HOST}`;
|
||||
const METRICS_URL = "https://metrics.scale1.test/metrics";
|
||||
|
||||
const dirs: string[] = [];
|
||||
after(async () => {
|
||||
for (const dir of dirs) await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function tempDir(): Promise<string> {
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "scale-ramp-test-"));
|
||||
dirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
interface Harness {
|
||||
clock: VirtualClock;
|
||||
fake: FakePaperclip;
|
||||
out: string[];
|
||||
err: string[];
|
||||
deps: MainDeps;
|
||||
fetchCalls: () => number;
|
||||
interrupt: () => void;
|
||||
}
|
||||
|
||||
function harness(config: Partial<FakeConfig> = {}, env: Record<string, string> = {}, answer = HOST): Harness {
|
||||
const clock = new VirtualClock();
|
||||
const fake = new FakePaperclip(clock, { token: TOKEN, origin: ORIGIN, ...config });
|
||||
const out: string[] = [];
|
||||
const err: string[] = [];
|
||||
let calls = 0;
|
||||
let handler: (() => void) | null = null;
|
||||
const deps: MainDeps = {
|
||||
env: { PAPERCLIP_SCALE_TOKEN: TOKEN, OPENROUTER_API_KEY: PROVIDER_KEY, ...env },
|
||||
fetcher: async (url, init) => {
|
||||
calls += 1;
|
||||
return fake.fetch(url, init);
|
||||
},
|
||||
clock,
|
||||
out: line => out.push(line),
|
||||
err: line => err.push(line),
|
||||
confirm: async () => answer,
|
||||
onInterrupt: fn => {
|
||||
handler = fn;
|
||||
return () => {
|
||||
handler = null;
|
||||
};
|
||||
},
|
||||
random: () => 0.5,
|
||||
};
|
||||
return { clock, fake, out, err, deps, fetchCalls: () => calls, interrupt: () => handler?.() };
|
||||
}
|
||||
|
||||
const baseArgs = (out: string, extra: string[] = []) => [
|
||||
"--base-url", ORIGIN, "--target-kind", "test-stack", "--out", out, "--label", "scale-test-run", "--yes",
|
||||
"--hold-minutes", "2", "--drain-minutes", "3", "--poll-seconds", "15", "--board-probe-seconds", "10", "--task-minutes", "1", ...extra,
|
||||
];
|
||||
|
||||
async function readResult(out: string): Promise<RampResult> {
|
||||
return JSON.parse(await readFile(path.join(out, "scale-test-run", "result.json"), "utf8")) as RampResult;
|
||||
}
|
||||
|
||||
function assertCleanedUp(fake: FakePaperclip): void {
|
||||
assert.equal(fake.liveRuns().length, 0, "no queued or running run is left");
|
||||
assert.equal(fake.agents.size, 0, "every harness agent is deleted");
|
||||
assert.ok([...fake.issues.values()].every(issue => issue.hiddenAt), "every task is archived");
|
||||
assert.equal(fake.secrets.size, 0, "the stored provider secret is deleted");
|
||||
assert.ok([...fake.projects.values()].every(project => project.archivedAt), "the project is archived");
|
||||
}
|
||||
|
||||
const goodMetrics = (running: number) => ({
|
||||
eventLoopUtilization: 0.2 + running / 1_000, mainThreadCpu: 0.25, eventLoopDelayP99Ms: 20, statementsPerSecond: 40 * running,
|
||||
poolWaitP99Ms: 2, runEventLatenessP99Ms: 120, agentApiPreHandlerP99Ms: 15, leaseRenewalsMissed: 0,
|
||||
});
|
||||
import { assertCleanedUp, baseArgs, goodMetrics, harness, HOST, METRICS_TOKEN, METRICS_URL, ORIGIN, PROVIDER_KEY, readResult, tempDir, TOKEN } from "./test-harness.ts";
|
||||
|
||||
describe("target guard", () => {
|
||||
it("classifies hosts", () => {
|
||||
@@ -147,61 +68,14 @@ describe("target guard", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("dry run and spend", () => {
|
||||
it("prints the plan and estimate and touches nothing", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness();
|
||||
const code = await main(["--base-url", ORIGIN, "--target-kind", "test-stack", "--out", out, "--dry-run"], h.deps);
|
||||
assert.equal(code, EXIT.pass);
|
||||
assert.equal(h.fetchCalls(), 0);
|
||||
assert.deepEqual(await readdir(out), []);
|
||||
const text = h.out.join("\n");
|
||||
assert.match(text, /Ramp: 10 -> 50 -> 100 -> 200 -> 500 -> 1000 agents/);
|
||||
assert.match(text, /Estimated spend: \$\d/);
|
||||
assert.match(text, /retry_needed_zero \[finish-line\]/);
|
||||
assert.match(text, /Dry run: nothing was created or contacted/);
|
||||
});
|
||||
|
||||
it("estimates tasks, sandbox-hours and cost from the steps", () => {
|
||||
const options = parseOptions(["--base-url", ORIGIN, "--target-kind", "test-stack", "--steps", "10,50", "--hold-minutes", "10", "--task-minutes", "5",
|
||||
"--drain-minutes", "10"], {}, 0);
|
||||
const estimate = estimateSpend(options);
|
||||
assert.equal(estimate.agents, 50);
|
||||
assert.equal(estimate.tasks, 10 * 2 + 50 * 2);
|
||||
assert.equal(estimate.maxTasks, 150);
|
||||
assert.equal(estimate.sandboxHours, 18.3);
|
||||
assert.equal(estimate.modelUsd, 3);
|
||||
assert.equal(estimate.totalUsd, 4.83);
|
||||
});
|
||||
|
||||
it("requires --confirm-spend of at least the estimate above the threshold", async () => {
|
||||
const estimate = { totalUsd: 120 } as ReturnType<typeof estimateSpend>;
|
||||
assert.equal(checkSpend(estimate, 5, null).ok, false);
|
||||
assert.equal(checkSpend(estimate, 5, 100).ok, false);
|
||||
assert.equal(checkSpend(estimate, 5, 130).ok, true);
|
||||
assert.equal(checkSpend(estimate, 200, null).ok, true);
|
||||
const out = await tempDir();
|
||||
const h = harness();
|
||||
const code = await main(["--base-url", ORIGIN, "--target-kind", "test-stack", "--out", out, "--yes"], h.deps);
|
||||
assert.equal(code, EXIT.usage);
|
||||
assert.equal(h.fetchCalls(), 0);
|
||||
assert.match(h.err.join("\n"), /--confirm-spend/);
|
||||
});
|
||||
|
||||
it("defaults to the qualified OpenCode model of the runner", async () => {
|
||||
const source = await readFile(path.join(import.meta.dirname, "../../packages/paperclip-runner/src/drivers/opencode/opencode-server-driver.ts"), "utf8");
|
||||
const match = /QUALIFIED_OPENCODE_MODEL\s*=\s*"([^"]+)"/.exec(source);
|
||||
assert.equal(match?.[1], QUALIFIED_OPENCODE_MODEL);
|
||||
});
|
||||
});
|
||||
|
||||
describe("criteria", () => {
|
||||
const empty = distribution([]);
|
||||
const metrics = (patch: Partial<StepMetrics> = {}): StepMetrics => ({
|
||||
step: { index: 0, concurrency: 10, holdMs: 60_000 }, startedAt: 0, endedAt: 1, tasksCreated: 10, tasksStarted: 10, tasksFinished: 10,
|
||||
tasksFailed: 0, tasksNeedingRetry: 0, runsFailed: 0, runsInterrupted: 0, runsCancelled: 0, peakRunning: 10, meanRunning: 9,
|
||||
tasksFailed: 0, tasksNeedingRetry: 0, runsEnded: 10, runsFailed: 0, runsFailedRecovered: 0, runsFailedUnrecovered: 0, runsFailedPending: 0,
|
||||
runsInterrupted: 0, runsCancelled: 0, peakRunning: 10, meanRunning: 9,
|
||||
queueWaitMs: distribution([1_000, 2_000]), taskToStartMs: empty, ttftMs: empty, firstActivityMs: distribution([4_000]), runDurationMs: empty,
|
||||
board: { requests: 10, failures: 0, ms: distribution([100, 120, 130, 140]) },
|
||||
board: { requests: 10, failures: 0, ms: distribution([100, 120, 130, 140]), byRoute: {} },
|
||||
server: { mainThreadCpuMax: null, eventLoopUtilizationMax: null, eventLoopDelayP99MsMax: null, statementsPerSecondMax: null, poolWaitP99MsMax: null,
|
||||
runEventLatenessP99MsMax: null, agentApiPreHandlerP99MsMax: null, leaseRenewalsMissed: null, samples: 0 },
|
||||
recordedSpendUsd: 0, ...patch,
|
||||
@@ -217,22 +91,41 @@ describe("criteria", () => {
|
||||
assert.equal(results.lease_renewals_missed_zero, "not_measured");
|
||||
assert.equal(results.run_event_lateness_p99, "not_measured");
|
||||
assert.equal(results.kill_one_process_resumes, "not_measured");
|
||||
assert.equal(byId(evaluate(metrics({ board: { requests: 0, failures: 0, ms: empty } }), thresholds)).board_api_p90, "not_measured");
|
||||
assert.equal(byId(evaluate(metrics({ board: { requests: 0, failures: 0, ms: empty, byRoute: {} } }), thresholds)).board_api_p90, "not_measured");
|
||||
});
|
||||
|
||||
it("fails each finish-line threshold it can measure", () => {
|
||||
const server = { mainThreadCpuMax: 0.7, eventLoopUtilizationMax: 0.5, eventLoopDelayP99MsMax: 10, statementsPerSecondMax: 1, poolWaitP99MsMax: 1,
|
||||
runEventLatenessP99MsMax: 1_500, agentApiPreHandlerP99MsMax: 100, leaseRenewalsMissed: 2, samples: 3 };
|
||||
const results = byId(evaluate(metrics({ tasksNeedingRetry: 1, peakRunning: 8, board: { requests: 4, failures: 1, ms: distribution([100, 600, 700]) }, server }), thresholds));
|
||||
const results = byId(evaluate(metrics({ tasksNeedingRetry: 1, peakRunning: 8, runsFailed: 1, runsFailedUnrecovered: 1,
|
||||
board: { requests: 4, failures: 1, ms: distribution([100, 600, 700]), byRoute: {} }, server }), thresholds));
|
||||
assert.deepEqual(results, {
|
||||
retry_needed_zero: "fail", failed_runs_zero: "pass", tasks_rested_not_done_zero: "pass", concurrency_reached: "fail", board_api_p90: "fail", board_api_errors_zero: "fail",
|
||||
retry_needed_zero: "fail", failed_runs_unrecovered_zero: "fail", failed_run_rate: "fail", tasks_rested_not_done_zero: "pass", concurrency_reached: "fail",
|
||||
board_api_p90: "fail", board_api_errors_zero: "fail",
|
||||
queue_wait_p95: "pass", first_activity_p95: "pass", main_thread_cpu: "fail", run_event_lateness_p99: "fail", agent_api_pre_handler_p99: "fail",
|
||||
lease_renewals_missed_zero: "fail", kill_one_process_resumes: "not_measured",
|
||||
});
|
||||
});
|
||||
|
||||
it("only evaluates retry and failed runs as immediate stops", () => {
|
||||
assert.deepEqual(evaluate(metrics(), thresholds, true).map(result => result.id), ["retry_needed_zero", "failed_runs_zero"]);
|
||||
it("only evaluates retry and unrecovered failed runs as immediate stops", () => {
|
||||
assert.deepEqual(evaluate(metrics(), thresholds, true).map(result => result.id), ["retry_needed_zero", "failed_runs_unrecovered_zero"]);
|
||||
});
|
||||
|
||||
it("passes a step whose failed runs all recovered while their share of ended runs stays under the limit", () => {
|
||||
const recovered = byId(evaluate(metrics({ runsEnded: 106, runsFailed: 1, runsFailedRecovered: 1 }), thresholds));
|
||||
assert.equal(recovered.failed_runs_unrecovered_zero, "pass");
|
||||
assert.equal(recovered.failed_run_rate, "pass");
|
||||
assert.equal(byId(evaluate(metrics({ runsEnded: 20, runsFailed: 1, runsFailedRecovered: 1 }), thresholds)).failed_run_rate, "fail");
|
||||
assert.equal(byId(evaluate(metrics({ runsEnded: 0 }), thresholds)).failed_run_rate, "not_measured");
|
||||
});
|
||||
|
||||
it("compares the unrounded failed-run share with the limit", () => {
|
||||
const justOver = evaluate(metrics({ runsEnded: 49, runsFailed: 1, runsFailedRecovered: 1 }), thresholds).find(result => result.id === "failed_run_rate")!;
|
||||
assert.equal(justOver.status, "fail");
|
||||
assert.equal(justOver.observed, 2);
|
||||
const zero = parseOptions(["--base-url", ORIGIN, "--target-kind", "test-stack", "--max-failed-run-percent", "0"], {}, 0).thresholds;
|
||||
assert.equal(byId(evaluate(metrics({ runsEnded: 2_500, runsFailed: 1, runsFailedRecovered: 1 }), zero)).failed_run_rate, "fail");
|
||||
assert.equal(byId(evaluate(metrics({ runsEnded: 50, runsFailed: 1, runsFailedRecovered: 1 }), thresholds)).failed_run_rate, "pass");
|
||||
});
|
||||
|
||||
it("reads first token and first activity from run spans, with an event fallback", () => {
|
||||
@@ -404,7 +297,7 @@ describe("ramp against the fake API", () => {
|
||||
mutate: (issue, run, now) => { issue.status = "cancelled"; run.status = "cancelled"; run.finishedAt = now; } },
|
||||
{ name: "blocked", criterion: "run_started", reason: /ended before any run started.*is blocked.*is queued/,
|
||||
mutate: issue => { issue.status = "blocked"; } },
|
||||
{ name: "failed before it started", criterion: "failed_runs_zero", reason: /failed_runs_zero failed/,
|
||||
{ name: "failed before it started", criterion: "run_started", reason: /ended before any run started.*is failed/,
|
||||
mutate: (_issue, run, now) => { run.status = "failed"; run.finishedAt = now; } },
|
||||
];
|
||||
for (const preflight of preflightCases) {
|
||||
@@ -450,11 +343,11 @@ describe("ramp against the fake API", () => {
|
||||
const out = await tempDir();
|
||||
const h = harness({ failWhenRunningAbove: 0, runDurationMs: 3 * 60_000, agentReadyDelayMs: index => index === 0 ? 3_000 : 10 * 60_000 });
|
||||
const started = h.clock.now();
|
||||
const code = await main(baseArgs(out, ["--steps", "1,3", "--min-concurrency-ratio", "0.5"]), h.deps);
|
||||
const code = await main(baseArgs(out, ["--steps", "1,3", "--min-concurrency-ratio", "0.5", "--recovery-grace-minutes", "1"]), h.deps);
|
||||
const result = await readResult(out);
|
||||
assert.equal(code, EXIT.fail);
|
||||
assert.equal(result.stop!.stepIndex, 1);
|
||||
assert.equal(result.stop!.criterion, "failed_runs_zero");
|
||||
assert.equal(result.stop!.criterion, "failed_runs_unrecovered_zero");
|
||||
assert.equal(result.steps[0]!.metrics.runsFailed, 1);
|
||||
assert.ok(h.clock.now() - started < 6 * 60_000, "the failure is seen during the agent wait, not after it");
|
||||
assertCleanedUp(h.fake);
|
||||
@@ -540,7 +433,7 @@ describe("ramp against the fake API", () => {
|
||||
assert.equal(code, EXIT.fail);
|
||||
assert.equal(result.verdict, "fail");
|
||||
assert.equal(result.stop!.stepIndex, 1);
|
||||
assert.equal(result.stop!.criterion, "failed_runs_zero");
|
||||
assert.equal(result.stop!.criterion, "failed_run_rate");
|
||||
assert.equal(result.steps.length, 2);
|
||||
const agents = h.fake.requests.filter(request => request.method === "POST" && new URL(request.url).pathname.endsWith("/agents"));
|
||||
assert.equal(agents.length, 4, "the 8-agent step never created agents");
|
||||
@@ -554,7 +447,7 @@ describe("ramp against the fake API", () => {
|
||||
const result = await readResult(out);
|
||||
assert.equal(result.verdict, "fail");
|
||||
assert.equal(result.stop!.stepIndex, 0);
|
||||
assert.ok(["retry_needed_zero", "failed_runs_zero"].includes(result.stop!.criterion!));
|
||||
assert.ok(["retry_needed_zero", "failed_runs_unrecovered_zero"].includes(result.stop!.criterion!));
|
||||
assert.ok(result.steps[0]!.metrics.tasksNeedingRetry + result.steps[0]!.metrics.runsFailed > 0);
|
||||
});
|
||||
|
||||
@@ -625,6 +518,138 @@ describe("ramp against the fake API", () => {
|
||||
assert.ok(result.drained, "finished runs are not left counted as running");
|
||||
});
|
||||
|
||||
it("keeps ramping when Paperclip recovers a failed run by itself, counts it, and grades the failed-run rate at the step end", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness({ failRun: index => index === 2, recoverFailedRunAfterMs: 30_000, runDurationMs: 20_000 });
|
||||
await main(baseArgs(out, ["--steps", "2", "--hold-minutes", "4"]), h.deps);
|
||||
const result = await readResult(out);
|
||||
const metrics = result.steps[0]!.metrics;
|
||||
assert.equal(metrics.runsFailed, 1);
|
||||
assert.equal(metrics.runsFailedRecovered, 1);
|
||||
assert.equal(metrics.runsFailedUnrecovered, 0);
|
||||
assert.equal(metrics.tasksNeedingRetry, 0, "a scheduled automatic retry is not a task that needs Retry");
|
||||
assert.equal(result.stop!.criterion, "failed_run_rate");
|
||||
assert.match(result.stop!.reason, /at the end of the step/);
|
||||
assert.ok(metrics.tasksFinished >= 3, "the step kept creating work after the failure");
|
||||
const tolerant = await tempDir();
|
||||
const h2 = harness({ failRun: index => index === 2, recoverFailedRunAfterMs: 30_000, runDurationMs: 20_000 });
|
||||
await main(baseArgs(tolerant, ["--steps", "2", "--hold-minutes", "4", "--max-failed-run-percent", "50", "--min-concurrency-ratio", "0.5"]), h2.deps);
|
||||
const passed = await readResult(tolerant);
|
||||
assert.equal(passed.stop, null);
|
||||
assert.ok(passed.steps[0]!.criteriaFinal.filter(c => c.id.startsWith("failed_run")).every(c => c.status === "pass"));
|
||||
});
|
||||
|
||||
it("stops when a failed run's task has not finished within the recovery grace", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness({ failRun: index => index === 2 });
|
||||
const started = h.clock.now();
|
||||
const code = await main(baseArgs(out, ["--steps", "2", "--hold-minutes", "20", "--recovery-grace-minutes", "2"]), h.deps);
|
||||
const result = await readResult(out);
|
||||
assert.equal(code, EXIT.fail);
|
||||
assert.equal(result.stop!.criterion, "failed_runs_unrecovered_zero");
|
||||
assert.equal(result.steps[0]!.metrics.runsFailedUnrecovered, 1);
|
||||
assert.ok(h.clock.now() - started < 10 * 60_000, "it stops once the grace runs out, not at the end of the hold");
|
||||
});
|
||||
|
||||
it("counts a run that Paperclip retries on the same run id once, as recovered, with a share of at most 100%", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness({ failRun: index => index === 2, retrySameRunAfterMs: 30_000, runDurationMs: 20_000 });
|
||||
await main(baseArgs(out, ["--steps", "2", "--hold-minutes", "4", "--max-failed-run-percent", "50", "--min-concurrency-ratio", "0.5"]), h.deps);
|
||||
const result = await readResult(out);
|
||||
const metrics = result.steps[0]!.metrics;
|
||||
const retried = [...h.fake.runs.values()].find(run => run.recovery)!;
|
||||
assert.equal(retried.status, "succeeded", "the failed run itself finished on its retry");
|
||||
assert.equal(metrics.runsFailed, 1);
|
||||
assert.equal(metrics.runsFailedRecovered, 1);
|
||||
assert.equal(metrics.tasksNeedingRetry, 0);
|
||||
assert.ok(metrics.runsEnded >= metrics.runsFailed);
|
||||
const rate = result.steps[0]!.criteriaFinal.find(criterion => criterion.id === "failed_run_rate")!;
|
||||
assert.equal(rate.observed, Math.round(1_000 / metrics.runsEnded) / 10);
|
||||
assert.equal(rate.status, "pass");
|
||||
});
|
||||
|
||||
it("keeps a failed run in the ended runs while Paperclip retries it on the same run id", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness({ failRun: index => index === 2, retrySameRunAfterMs: 30_000, sameRunRetryDurationMs: 60 * 60_000, runDurationMs: 20_000 });
|
||||
await main(baseArgs(out, ["--steps", "2", "--hold-minutes", "4", "--drain-minutes", "0", "--max-failed-run-percent", "50",
|
||||
"--min-concurrency-ratio", "0.5"]), h.deps);
|
||||
const metrics = (await readResult(out)).steps[0]!.metrics;
|
||||
const succeeded = [...h.fake.runs.values()].filter(run => run.status === "succeeded").length;
|
||||
assert.equal(metrics.runsFailed, 1);
|
||||
assert.equal(metrics.runsFailedPending, 1, "the retry is still running");
|
||||
assert.equal(metrics.runsEnded, succeeded + 1, "the retrying run still counts as ended once");
|
||||
});
|
||||
|
||||
it("keeps the termination wait to a bounded number of reads for a large run", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness({ terminationDelayMs: 60 * 60_000 });
|
||||
const options = parseOptions(baseArgs(out, ["--steps", "2"]), h.deps.env, h.clock.now());
|
||||
const api = new PaperclipClient(options.target, TOKEN, h.deps.fetcher, h.clock, new Redactor([TOKEN]));
|
||||
const state: RunState = emptyState(options.label, options.target.baseUrl, h.clock.now());
|
||||
await prepareCompany({ api, options, state, store: fileStateStore(options.outDir), credential: PROVIDER_KEY, log: () => {} });
|
||||
for (let index = 0; index < 1_000; index += 1) {
|
||||
const agent = await api.post<{ id: string }>(`/api/companies/${state.companyId}/agents`, { name: agentName(options.label, index) });
|
||||
state.agentIds.push(agent.id);
|
||||
}
|
||||
const before = h.fake.requests.length;
|
||||
const report = await cleanupRun({ api, clock: h.clock, label: options.label, state });
|
||||
const reads = h.fake.requests.slice(before).filter(request => request.method === "GET" && /\/api\/agents\/[0-9a-f-]+$/.test(new URL(request.url).pathname)).length;
|
||||
assert.equal(report.agentsStillTerminating.length, 1_000);
|
||||
assert.ok(reads <= 5_000, `termination reads: ${reads}`);
|
||||
});
|
||||
|
||||
it("reports board latency per route", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness({ boardLatencyMs: () => 300 });
|
||||
await main(baseArgs(out, ["--steps", "2"]), h.deps);
|
||||
const byRoute = (await readResult(out)).steps[0]!.metrics.board.byRoute;
|
||||
assert.deepEqual(Object.keys(byRoute).sort(), ["agents", "dashboard", "issues", "live-runs", "sidebar-badges"]);
|
||||
assert.equal(byRoute.dashboard!.p50, 300);
|
||||
assert.ok(byRoute.issues!.n > 0);
|
||||
const summary = await readFile(path.join(out, "scale-test-run", "SUMMARY.md"), "utf8");
|
||||
assert.match(summary, / - dashboard p50 \/ p90 \/ p99: 300 ms/);
|
||||
});
|
||||
|
||||
it("deletes an agent only after Paperclip completes its termination", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness({ terminationDelayMs: 2 * 60_000 });
|
||||
await main(baseArgs(out, ["--steps", "2"]), h.deps);
|
||||
const result = await readResult(out);
|
||||
assert.deepEqual(result.cleanup!.errors, []);
|
||||
assert.deepEqual(result.cleanup!.agentsStillTerminating, []);
|
||||
assert.equal(result.cleanup!.agentsDeleted, 2);
|
||||
assertCleanedUp(h.fake);
|
||||
});
|
||||
|
||||
it("names the agents still terminating and the sandbox leases still active, and finishes them with --cleanup-only later", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness({ terminationDelayMs: 20 * 60_000, leaseLingerMs: 20 * 60_000 });
|
||||
const code = await main(baseArgs(out, ["--steps", "2"]), h.deps);
|
||||
const result = await readResult(out);
|
||||
assert.equal(code, EXIT.incomplete);
|
||||
assert.equal(result.cleanup!.agentsStillTerminating.length, 2);
|
||||
assert.equal(result.cleanup!.agentsDeleted, 0);
|
||||
assert.ok(result.cleanup!.activeSandboxLeases! > 0);
|
||||
assert.equal(result.cleanup!.activeSandboxLeaseIds.length, result.cleanup!.activeSandboxLeases);
|
||||
assert.ok(result.cleanup!.errors.some(error => /had not completed termination/.test(error)));
|
||||
assert.ok(result.cleanup!.errors.some(error => /still active after 5 min: lease-/.test(error)));
|
||||
assert.ok(!result.cleanup!.errors.some(error => /409/.test(error)), "no delete is sent before termination completes");
|
||||
await h.clock.sleep(20 * 60_000);
|
||||
const later = await main(["--base-url", ORIGIN, "--target-kind", "test-stack", "--out", out, "--cleanup-only", "scale-test-run", "--yes"], h.deps);
|
||||
assert.equal(later, EXIT.pass);
|
||||
assertCleanedUp(h.fake);
|
||||
});
|
||||
|
||||
it("counts sandbox leases that release while the cleanup waits", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness({ leaseLingerMs: 2 * 60_000 });
|
||||
await main(baseArgs(out, ["--steps", "2"]), h.deps);
|
||||
const cleanup = (await readResult(out)).cleanup!;
|
||||
assert.equal(cleanup.activeSandboxLeases, 0);
|
||||
assert.ok(cleanup.sandboxLeasesReleasedDuringWait > 0);
|
||||
assert.deepEqual(cleanup.errors, []);
|
||||
});
|
||||
|
||||
it("cleans up after a crash in the middle of the ramp", async () => {
|
||||
const out = await tempDir();
|
||||
const h = harness({ failRequest: (method, route, count) => method === "POST" && route.endsWith("/issues") && count === 5 ? { status: 500, body: "boom" } : null });
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { after } from "node:test";
|
||||
import { FakePaperclip, VirtualClock, type FakeConfig } from "./fake-paperclip.ts";
|
||||
import type { MainDeps } from "./main.ts";
|
||||
import type { RampResult } from "./report.ts";
|
||||
|
||||
export const TOKEN = "board-token-SECRET-4f2a9c";
|
||||
export const PROVIDER_KEY = "sk-or-v1-SECRET-provider-key-77";
|
||||
export const METRICS_TOKEN = "metrics-token-SECRET-91";
|
||||
export const HOST = "scale1.test.paperclip.app";
|
||||
export const ORIGIN = `https://${HOST}`;
|
||||
export const METRICS_URL = "https://metrics.scale1.test/metrics";
|
||||
|
||||
const dirs: string[] = [];
|
||||
after(async () => {
|
||||
for (const dir of dirs) await rm(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
export async function tempDir(): Promise<string> {
|
||||
const dir = await mkdtemp(path.join(tmpdir(), "scale-ramp-test-"));
|
||||
dirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
export interface Harness {
|
||||
clock: VirtualClock;
|
||||
fake: FakePaperclip;
|
||||
out: string[];
|
||||
err: string[];
|
||||
deps: MainDeps;
|
||||
fetchCalls: () => number;
|
||||
interrupt: () => void;
|
||||
}
|
||||
|
||||
export function harness(config: Partial<FakeConfig> = {}, env: Record<string, string> = {}, answer = HOST): Harness {
|
||||
const clock = new VirtualClock();
|
||||
const fake = new FakePaperclip(clock, { token: TOKEN, origin: ORIGIN, ...config });
|
||||
const out: string[] = [];
|
||||
const err: string[] = [];
|
||||
let calls = 0;
|
||||
let handler: (() => void) | null = null;
|
||||
const deps: MainDeps = {
|
||||
env: { PAPERCLIP_SCALE_TOKEN: TOKEN, OPENROUTER_API_KEY: PROVIDER_KEY, ...env },
|
||||
fetcher: async (url, init) => {
|
||||
calls += 1;
|
||||
return fake.fetch(url, init);
|
||||
},
|
||||
clock,
|
||||
out: line => out.push(line),
|
||||
err: line => err.push(line),
|
||||
confirm: async () => answer,
|
||||
onInterrupt: fn => {
|
||||
handler = fn;
|
||||
return () => {
|
||||
handler = null;
|
||||
};
|
||||
},
|
||||
random: () => 0.5,
|
||||
};
|
||||
return { clock, fake, out, err, deps, fetchCalls: () => calls, interrupt: () => handler?.() };
|
||||
}
|
||||
|
||||
export const baseArgs = (out: string, extra: string[] = []) => [
|
||||
"--base-url", ORIGIN, "--target-kind", "test-stack", "--out", out, "--label", "scale-test-run", "--yes",
|
||||
"--hold-minutes", "2", "--drain-minutes", "3", "--poll-seconds", "15", "--board-probe-seconds", "10", "--task-minutes", "1", ...extra,
|
||||
];
|
||||
|
||||
export async function readResult(out: string): Promise<RampResult> {
|
||||
return JSON.parse(await readFile(path.join(out, "scale-test-run", "result.json"), "utf8")) as RampResult;
|
||||
}
|
||||
|
||||
export function assertCleanedUp(fake: FakePaperclip): void {
|
||||
assert.equal(fake.liveRuns().length, 0, "no queued or running run is left");
|
||||
assert.equal(fake.agents.size, 0, "every harness agent is deleted");
|
||||
assert.ok([...fake.issues.values()].every(issue => issue.hiddenAt), "every task is archived");
|
||||
assert.equal(fake.secrets.size, 0, "the stored provider secret is deleted");
|
||||
assert.ok([...fake.projects.values()].every(project => project.archivedAt), "the project is archived");
|
||||
}
|
||||
|
||||
export const goodMetrics = (running: number) => ({
|
||||
eventLoopUtilization: 0.2 + running / 1_000, mainThreadCpu: 0.25, eventLoopDelayP99Ms: 20, statementsPerSecond: 40 * running,
|
||||
poolWaitP99Ms: 2, runEventLatenessP99Ms: 120, agentApiPreHandlerP99Ms: 15, leaseRenewalsMissed: 0,
|
||||
});
|
||||
@@ -47,9 +47,10 @@ describe("agent file restore locking", () => {
|
||||
const board = () => ({ type: "board" as const, userId, source: "session" as const });
|
||||
const target = () => ({ companyId, agentId });
|
||||
|
||||
const lockCheckQuery = () => sql`select id from agents where id = ${agentId} for share nowait`;
|
||||
async function agentRowLocked(): Promise<boolean> {
|
||||
try {
|
||||
await observer.transaction(async tx => { await tx.execute(sql`select id from agents where id = ${agentId} for update nowait`); });
|
||||
await observer.transaction(async tx => { await tx.execute(lockCheckQuery()); });
|
||||
return false;
|
||||
} catch (error) {
|
||||
const code = (error as { code?: string; cause?: { code?: string } }).code ?? (error as { cause?: { code?: string } }).cause?.code;
|
||||
@@ -106,6 +107,30 @@ describe("agent file restore locking", () => {
|
||||
await fs.rm(home, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
async function whileHolding(lock: (tx: Parameters<Parameters<typeof db.transaction>[0]>[0]) => Promise<unknown>, check: () => Promise<void>) {
|
||||
let release!: () => void;
|
||||
const released = new Promise<void>(resolve => { release = resolve; });
|
||||
let holding!: () => void;
|
||||
const held = new Promise<void>(resolve => { holding = resolve; });
|
||||
const holder = db.transaction(async tx => { await lock(tx); holding(); await released; });
|
||||
await Promise.race([held, holder]);
|
||||
try { await check(); } finally { release(); }
|
||||
await holder;
|
||||
}
|
||||
|
||||
it("a lock check does not block another lock check", async () => {
|
||||
await whileHolding(tx => tx.execute(lockCheckQuery()), async () => {
|
||||
expect(await agentRowLocked()).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
it("a lock check detects the product's agent row lock", async () => {
|
||||
await whileHolding(tx => tx.select().from(agents).where(eq(agents.id, agentId)).for("update"), async () => {
|
||||
expect(await agentRowLocked()).toBe(true);
|
||||
});
|
||||
expect(await agentRowLocked()).toBe(false);
|
||||
});
|
||||
|
||||
it("downloads a stale projection without holding the agent row lock", async () => {
|
||||
await loseLocalProjection();
|
||||
objects.probe = agentRowLocked;
|
||||
|
||||
@@ -15,6 +15,7 @@ import { toolAccessService } from "../services/tool-access.js";
|
||||
import { createToolGatewayService } from "../services/tool-gateway.js";
|
||||
import { connectionIntentService } from "../services/connection-intents.js";
|
||||
import { aiConnectionService } from "../services/ai-connections.js";
|
||||
import { invalidateInstanceSettingsCache } from "../services/instance-settings-cache.js";
|
||||
|
||||
vi.mock("../services/subscription-refresh.js", () => ({ refreshSubscriptionConnection: vi.fn().mockResolvedValue(undefined) }));
|
||||
|
||||
@@ -170,6 +171,7 @@ describeDatabase("connection assignment synchronization", () => {
|
||||
await pluginAgentRuntimeState(db, pluginId, companyId, agentId);
|
||||
const before = (await events()).length;
|
||||
await db.update(instanceSettings).set({ experimental: { enableChatConnectors: true } });
|
||||
invalidateInstanceSettingsCache();
|
||||
expect(await events()).toHaveLength(before + 2);
|
||||
expect((await pluginAgentRuntimeState(db, pluginId, companyId, agentId))!.connectionAssignments.features).toEqual({ publicMcp: false, chatConnectors: true });
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { pluginAgentRuntimeState } from "../services/plugin-agent-runtime-state.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
import { invalidateInstanceSettingsCache } from "../services/instance-settings-cache.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
const describeDatabase = support.supported ? describe : describe.skip;
|
||||
@@ -143,6 +144,7 @@ describeDatabase("skill runtime invalidation", () => {
|
||||
it("resolves immutable pinned and latest skill sources and removes unassigned skills", async () => {
|
||||
await instanceSettingsService(db).getExperimental();
|
||||
await db.update(instanceSettings).set({ experimental: { enableBetaSkills: true } });
|
||||
invalidateInstanceSettingsCache();
|
||||
const first = await publish("first version", 1);
|
||||
const pinned = await agent([{ key, versionId: first.id }]);
|
||||
const latest = await agent();
|
||||
|
||||
@@ -49,6 +49,7 @@ import * as copilotProbe from "../services/copilot-connection-probe.js";
|
||||
import * as settingsModule from "../services/instance-settings.js";
|
||||
import { agentRoutes } from "../routes/agents.js";
|
||||
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
|
||||
import { invalidateInstanceSettingsCache } from "../services/instance-settings-cache.js";
|
||||
vi.mock("../services/local-ai-browser-login.js", () => ({
|
||||
startLocalBrowserLogin: () => ({ authorizationUrl: "https://auth.openai.com/codex/device", code: "ABCD-EFGHJ", abort: () => {} }),
|
||||
}));
|
||||
@@ -2519,6 +2520,7 @@ console.log(JSON.stringify({ type: "result", subtype: "success", result: "hello"
|
||||
await db.insert(toolConnections).values(ids.map(id => ({ ...connection, id, uid: id, name: `Cost ${id}` })));
|
||||
await db.insert(connectionGrants).values(ids.map(connectionId => ({ ...grant, id: randomUUID(), connectionId })));
|
||||
selects.mockClear();
|
||||
invalidateInstanceSettingsCache();
|
||||
const large = await request(app).get(url);
|
||||
largeQueries = selects.mock.calls.length;
|
||||
expect(large.status).toBe(200);
|
||||
|
||||
@@ -106,6 +106,38 @@ describe("cli auth routes", () => {
|
||||
await Promise.all([import("../routes/access.js"), import("../middleware/index.js")]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[true, false],
|
||||
[false, true],
|
||||
])("reports effective Cloud owner access when actor admin=%s and stored admin=%s", async (effectiveAdmin, storedAdmin) => {
|
||||
mockBoardAuthService.resolveBoardAccess.mockResolvedValue({
|
||||
user: { id: "user-1", name: "User One", email: "user@example.com" },
|
||||
companyIds: ["company-1"],
|
||||
memberships: [{ companyId: "company-1", membershipRole: "owner", status: "active" }],
|
||||
isInstanceAdmin: storedAdmin,
|
||||
});
|
||||
const app = await createApp({ type: "board", source: "cloud_tenant", userId: "user-1", isInstanceAdmin: effectiveAdmin });
|
||||
const res = await request(app).get("/api/cli-auth/me");
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toMatchObject({ source: "cloud_tenant", isInstanceAdmin: effectiveAdmin, companyIds: ["company-1"] });
|
||||
});
|
||||
|
||||
it.each(["session", "board_key"])("keeps the fresh stored access snapshot for %s authentication", async source => {
|
||||
mockBoardAuthService.resolveBoardAccess.mockResolvedValue({ user: null, companyIds: [], isInstanceAdmin: false });
|
||||
const app = await createApp({ type: "board", source, userId: "user-1", isInstanceAdmin: true });
|
||||
const res = await request(app).get("/api/cli-auth/me");
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.isInstanceAdmin).toBe(false);
|
||||
});
|
||||
|
||||
it.each([{ type: "none", source: "none" }, { type: "agent", source: "agent_key", agentId: "agent-1" }])(
|
||||
"denies the board access summary to $type callers", async actor => {
|
||||
const app = await createApp(actor);
|
||||
expect((await request(app).get("/api/cli-auth/me")).status).toBe(401);
|
||||
expect(mockBoardAuthService.resolveBoardAccess).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it("creates a CLI auth challenge with approval metadata", async () => {
|
||||
mockBoardAuthService.createCliAuthChallenge.mockResolvedValue({
|
||||
challenge: {
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
agents,
|
||||
companies,
|
||||
createDb,
|
||||
environmentLeases,
|
||||
environments,
|
||||
heartbeatRunEvents,
|
||||
heartbeatRuns,
|
||||
issues,
|
||||
nativeRunFinalizations,
|
||||
plugins,
|
||||
} from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
|
||||
const mockTelemetryClient = vi.hoisted(() => ({ track: vi.fn() }));
|
||||
vi.mock("../telemetry.ts", () => ({ getTelemetryClient: () => mockTelemetryClient }));
|
||||
|
||||
import { heartbeatService } from "../services/heartbeat.ts";
|
||||
import { createLifecycleDriver } from "../services/agent-lifecycle-driver.js";
|
||||
import { configureAgentLifecycle, createAgentLifecycle } from "../services/agent-lifecycle.js";
|
||||
import { PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED } from "../services/native-local-process-stop.js";
|
||||
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = support.supported ? describe : describe.skip;
|
||||
|
||||
type Window = "artifact_discovery" | "provider_pack_select" | "provider_pack_upload" | "runner_launch" | "transport_connect" | "session_open";
|
||||
const PRE_LAUNCH: Window[] = ["artifact_discovery", "provider_pack_select", "provider_pack_upload"];
|
||||
const ALL_WINDOWS: Window[] = [...PRE_LAUNCH, "runner_launch", "transport_connect", "session_open"];
|
||||
const PROVIDER_METHODS = ["environmentAcquireLease", "environmentExecute", "environmentReleaseLease",
|
||||
"environmentDestroyLease", "environmentStopLease"];
|
||||
|
||||
describeEmbeddedPostgres("environment lease release between sandbox acquire and runner attach", () => {
|
||||
let db!: ReturnType<typeof createDb>;
|
||||
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
||||
const workers: Array<{ stop(): Promise<void> }> = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-lease-release-before-attach-");
|
||||
db = createDb(tempDb.connectionString);
|
||||
}, 30_000);
|
||||
|
||||
afterEach(async () => {
|
||||
for (const worker of workers.splice(0)) await worker.stop();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await tempDb?.cleanup();
|
||||
});
|
||||
|
||||
function providerWorker(pluginId: string) {
|
||||
const call = vi.fn(async (_pluginId: string, method: string, params: { providerLeaseId?: string }) => {
|
||||
if (method === "environmentDestroyLease") return { providerLeaseId: params.providerLeaseId, state: "destroyed" };
|
||||
if (method === "environmentStopLease") return { providerLeaseId: params.providerLeaseId, state: "stopped" };
|
||||
if (method === "environmentReleaseLease") return { providerLeaseId: params.providerLeaseId, state: "destroyed" };
|
||||
throw new Error(`Unexpected provider method ${method}`);
|
||||
});
|
||||
const manager = {
|
||||
isRunning: vi.fn((id: string) => id === pluginId),
|
||||
getWorker: vi.fn(() => ({ supportedMethods: PROVIDER_METHODS })),
|
||||
call,
|
||||
} as unknown as PluginWorkerManager;
|
||||
const teardownCalls = () => call.mock.calls.filter(([, method]) =>
|
||||
method === "environmentDestroyLease" || method === "environmentStopLease" || method === "environmentReleaseLease");
|
||||
return { manager, teardownCalls };
|
||||
}
|
||||
|
||||
async function seed(window: Window) {
|
||||
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID();
|
||||
const environmentId = randomUUID(), leaseId = randomUUID(), pluginId = randomUUID();
|
||||
const providerLeaseId = `sandbox-${randomUUID()}`;
|
||||
const pluginKey = `paperclip.lease-release-${pluginId.slice(0, 8)}`;
|
||||
await db.insert(plugins).values({ id: pluginId, pluginKey, packageName: "@paperclipai/plugin-fake-sandbox", version: "1.0.0",
|
||||
apiVersion: 1, categories: ["automation"], status: "ready", installOrder: 1, updatedAt: new Date(),
|
||||
manifestJson: { id: pluginKey, apiVersion: 1, version: "1.0.0", displayName: "Fake sandbox", description: "Test provider",
|
||||
author: "Paperclip", categories: ["automation"], capabilities: ["environment.drivers.register"],
|
||||
entrypoints: { worker: "dist/worker.js" },
|
||||
environmentDrivers: [{ driverKey: "fake-plugin", kind: "sandbox_provider", displayName: "Fake Plugin",
|
||||
configSchema: { type: "object" } }] } } as never);
|
||||
await db.insert(companies).values({ id: companyId, name: "Paperclip",
|
||||
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`, requireBoardApprovalForNewAgents: false });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "OpenCoder", role: "engineer", status: "running",
|
||||
adapterType: "paperclip_runner", adapterConfig: { provider: "opencode" }, runtimeConfig: {}, permissions: {} });
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Short task", status: "in_progress",
|
||||
priority: "medium", assigneeAgentId: agentId });
|
||||
const config = { provider: "fake-plugin", image: "fake:test", timeoutMs: 1234, reuseLease: false };
|
||||
await db.insert(environments).values({ id: environmentId, name: `Fake sandbox ${environmentId}`, driver: "sandbox",
|
||||
status: "active", config });
|
||||
const startedAt = new Date(Date.now() - 10_000);
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "assignment", status: "running",
|
||||
runtimeMode: "native", runtimeModeResolvedAt: startedAt, issueId, nativeIssueId: issueId, startedAt,
|
||||
contextSnapshot: { issueId }, nextEventSeq: 1,
|
||||
runnerProfileJson: { nativeWorkspaceSync: {
|
||||
schema: "paperclip.native-workspace-sync/v3", state: "prepared", descriptorSha256: "a".repeat(64),
|
||||
baselineSha256: "b".repeat(64), finalHostSha256: null, workspaceId: randomUUID(), leaseId, providerLeaseId,
|
||||
remoteCwd: "/workspace", resourceDisposition: "destroy" } } });
|
||||
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
|
||||
await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed", attempt: 1,
|
||||
controllerGeneration: 1, leaseOwner: `executor-${runId}`, leaseExpiresAt: new Date(Date.now() - 1_000) });
|
||||
await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: runId, issueId,
|
||||
status: "active", leasePolicy: "ephemeral", provider: "fake-plugin", providerLeaseId,
|
||||
metadata: { ...config, agentId, driver: "sandbox", pluginId, pluginKey, sandboxProviderPlugin: true,
|
||||
remoteCwd: "/workspace", sandboxState: "started" } });
|
||||
const events: Array<{ eventType: string; sourceEventId?: string }> = [];
|
||||
if (!PRE_LAUNCH.includes(window)) events.push({ eventType: PROCESS_START_REQUESTED });
|
||||
if (window === "transport_connect" || window === "session_open") events.push({ eventType: PROCESS_IDENTITY_RECORDED });
|
||||
if (window === "session_open") events.push({ eventType: "session.started", sourceEventId: randomUUID() });
|
||||
for (const [index, event] of events.entries()) {
|
||||
await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId, seq: index + 1, eventType: event.eventType,
|
||||
stream: "system", level: "info", message: event.eventType, sourceEventId: event.sourceEventId ?? null });
|
||||
}
|
||||
await db.update(heartbeatRuns).set({ nextEventSeq: events.length + 1 }).where(eq(heartbeatRuns.id, runId));
|
||||
return { companyId, agentId, issueId, runId, leaseId, providerLeaseId, ...providerWorker(pluginId) };
|
||||
}
|
||||
|
||||
async function lease(leaseId: string) {
|
||||
return (await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0]!;
|
||||
}
|
||||
|
||||
async function run(runId: string) {
|
||||
return (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0]!;
|
||||
}
|
||||
|
||||
async function expectSandboxReleased(fixture: Awaited<ReturnType<typeof seed>>) {
|
||||
let row = await lease(fixture.leaseId);
|
||||
if (row.status === "pending_cleanup") {
|
||||
await heartbeatService(db, { pluginWorkerManager: fixture.manager }).sweepPendingCleanupLeases({ backoffMs: 0 });
|
||||
row = await lease(fixture.leaseId);
|
||||
}
|
||||
expect(row.status).not.toBe("active");
|
||||
expect(row.status).not.toBe("pending_cleanup");
|
||||
expect(row.releasedAt).not.toBeNull();
|
||||
expect(fixture.teardownCalls()).toContainEqual([expect.any(String), expect.any(String),
|
||||
expect.objectContaining({ providerLeaseId: fixture.providerLeaseId }), expect.any(Number)]);
|
||||
}
|
||||
|
||||
it.each(ALL_WINDOWS)("terminating the agent releases a sandbox leased during %s", async window => {
|
||||
const fixture = await seed(window);
|
||||
const lifecycle = createAgentLifecycle(db);
|
||||
const worker = configureAgentLifecycle(db, createLifecycleDriver(db, fixture.manager));
|
||||
workers.push(worker);
|
||||
await lifecycle.pauseAgent(fixture.agentId);
|
||||
await worker.process(fixture.agentId);
|
||||
await lifecycle.terminateAgent(fixture.agentId);
|
||||
let agent = (await db.select().from(agents).where(eq(agents.id, fixture.agentId)))[0]!;
|
||||
let passes = 0;
|
||||
for (; agent.lifecycleState !== "terminated" && passes < 4; passes++) {
|
||||
await db.update(agents).set({ lifecycleOperation: { ...agent.lifecycleOperation!, retryAt: undefined } })
|
||||
.where(eq(agents.id, fixture.agentId));
|
||||
await worker.process(fixture.agentId);
|
||||
agent = (await db.select().from(agents).where(eq(agents.id, fixture.agentId)))[0]!;
|
||||
}
|
||||
expect(agent.lifecycleState).toBe("terminated");
|
||||
expect(passes).toBeLessThanOrEqual(1);
|
||||
const stopped = await run(fixture.runId);
|
||||
expect(stopped.status).toBe("cancelled");
|
||||
await expectSandboxReleased(fixture);
|
||||
if (PRE_LAUNCH.includes(window)) {
|
||||
expect(stopped.runnerProfileJson).not.toHaveProperty("nativeWorkspaceSync");
|
||||
expect(stopped.runnerProfileJson).toHaveProperty("nativeWorkspaceSyncReleasedUnchanged.state", "prepared");
|
||||
} else {
|
||||
expect(stopped.resultJson).toHaveProperty("workspaceRestoreRecovery.schema", "paperclip.workspace-restore-recovery.v1");
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it.each(ALL_WINDOWS)("stopping the run releases a sandbox leased during %s", async window => {
|
||||
const fixture = await seed(window);
|
||||
const heartbeat = heartbeatService(db, { pluginWorkerManager: fixture.manager });
|
||||
await heartbeat.cancelRun(fixture.runId, "Cancelled by a board operator", {
|
||||
resultJson: { cancelledByActorType: "user", cancelledByUserId: "operator" } });
|
||||
expect((await run(fixture.runId)).status).toBe("cancelled");
|
||||
await heartbeat.sweepOrphanedActiveLeases({ companyId: fixture.companyId, leaseId: fixture.leaseId, backoffMs: 5 * 60_000 });
|
||||
await expectSandboxReleased(fixture);
|
||||
}, 60_000);
|
||||
|
||||
it("records a release a live workspace owner holds back and finishes it in the background once due", async () => {
|
||||
const fixture = await seed("runner_launch");
|
||||
const ownerUntil = new Date(Date.now() + 60_000);
|
||||
await db.update(nativeRunFinalizations).set({ leaseExpiresAt: ownerUntil }).where(eq(nativeRunFinalizations.runId, fixture.runId));
|
||||
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), errorCode: "cancelled" })
|
||||
.where(eq(heartbeatRuns.id, fixture.runId));
|
||||
const heartbeat = heartbeatService(db, { pluginWorkerManager: fixture.manager });
|
||||
await heartbeat.releaseEnvironmentLeasesForRun({ runId: fixture.runId, companyId: fixture.companyId,
|
||||
agentId: fixture.agentId, status: "cancelled", providerResourceDisposition: "destroy" });
|
||||
const deferred = await lease(fixture.leaseId);
|
||||
expect(deferred.status).toBe("active");
|
||||
expect(deferred.metadata?.releaseDeferral).toMatchObject({ reason: "workspace_owner_active", attempts: 1,
|
||||
providerResourceDisposition: "destroy" });
|
||||
expect(fixture.teardownCalls()).toHaveLength(0);
|
||||
|
||||
const deadlines: number[] = [];
|
||||
await heartbeat.sweepOrphanedActiveLeases({ companyId: fixture.companyId, leaseId: fixture.leaseId, backoffMs: 5 * 60_000,
|
||||
onDeferredDeadline: at => deadlines.push(at) });
|
||||
expect((await lease(fixture.leaseId)).status).toBe("active");
|
||||
expect(deadlines).toContain(Date.parse(String((deferred.metadata?.releaseDeferral as { retryAt: string }).retryAt)));
|
||||
|
||||
await db.update(nativeRunFinalizations).set({ leaseExpiresAt: new Date(Date.now() - 1_000) })
|
||||
.where(eq(nativeRunFinalizations.runId, fixture.runId));
|
||||
await db.update(environmentLeases).set({ metadata: { ...deferred.metadata,
|
||||
releaseDeferral: { ...(deferred.metadata?.releaseDeferral as object), retryAt: new Date(Date.now() - 1_000).toISOString() } } })
|
||||
.where(eq(environmentLeases.id, fixture.leaseId));
|
||||
await heartbeat.sweepOrphanedActiveLeases({ companyId: fixture.companyId, leaseId: fixture.leaseId, backoffMs: 5 * 60_000 });
|
||||
await expectSandboxReleased(fixture);
|
||||
}, 60_000);
|
||||
|
||||
async function terminate(fixture: Awaited<ReturnType<typeof seed>>) {
|
||||
const lifecycle = createAgentLifecycle(db);
|
||||
const worker = configureAgentLifecycle(db, createLifecycleDriver(db, fixture.manager));
|
||||
workers.push(worker);
|
||||
await lifecycle.terminateAgent(fixture.agentId);
|
||||
await worker.process(fixture.agentId);
|
||||
return (await db.select().from(agents).where(eq(agents.id, fixture.agentId)))[0]!;
|
||||
}
|
||||
|
||||
it("finishes a release that lock conflicts held back, preserving the files, once the locks clear", async () => {
|
||||
const fixture = await seed("runner_launch");
|
||||
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), errorCode: "cancelled" })
|
||||
.where(eq(heartbeatRuns.id, fixture.runId));
|
||||
const heartbeat = heartbeatService(db, { pluginWorkerManager: fixture.manager });
|
||||
let ready!: () => void, unlock!: () => void;
|
||||
const locked = new Promise<void>(resolve => { ready = resolve; });
|
||||
const released = new Promise<void>(resolve => { unlock = resolve; });
|
||||
const holder = db.transaction(async tx => {
|
||||
await tx.select({ id: issues.id }).from(issues).where(eq(issues.id, fixture.issueId)).for("update");
|
||||
ready(); await released;
|
||||
});
|
||||
await locked;
|
||||
try {
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
await heartbeat.releaseEnvironmentLeasesForRun({ runId: fixture.runId, companyId: fixture.companyId,
|
||||
agentId: fixture.agentId, status: "cancelled", providerResourceDisposition: "destroy" });
|
||||
expect((await lease(fixture.leaseId)).metadata?.releaseDeferral).toMatchObject({ reason: "workspace_retention_busy", attempts: attempt });
|
||||
}
|
||||
} finally { unlock(); await holder; }
|
||||
const deferred = await lease(fixture.leaseId);
|
||||
await db.update(environmentLeases).set({ metadata: { ...deferred.metadata, releaseDeferral: {
|
||||
...(deferred.metadata?.releaseDeferral as object), retryAt: new Date(Date.now() - 1_000).toISOString() } } })
|
||||
.where(eq(environmentLeases.id, fixture.leaseId));
|
||||
await heartbeat.sweepOrphanedActiveLeases({ companyId: fixture.companyId, leaseId: fixture.leaseId, backoffMs: 5 * 60_000 });
|
||||
await expectSandboxReleased(fixture);
|
||||
expect((await run(fixture.runId)).resultJson).toHaveProperty("workspaceRestoreRecovery.schema", "paperclip.workspace-restore-recovery.v1");
|
||||
expect((await terminate(fixture)).lifecycleState).toBe("terminated");
|
||||
}, 60_000);
|
||||
|
||||
it("attempts a slow-phase deferred release at once when the agent is terminated", async () => {
|
||||
const fixture = await seed("runner_launch");
|
||||
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), errorCode: "cancelled" })
|
||||
.where(eq(heartbeatRuns.id, fixture.runId));
|
||||
const current = await lease(fixture.leaseId);
|
||||
await db.update(environmentLeases).set({ metadata: { ...current.metadata, releaseDeferral: { reason: "release_failed",
|
||||
attempts: 8, retryAt: new Date(Date.now() + 60 * 60_000).toISOString(), failingSince: new Date(Date.now() - 3 * 3_600_000).toISOString(),
|
||||
providerResourceDisposition: "destroy" } } }).where(eq(environmentLeases.id, fixture.leaseId));
|
||||
expect((await terminate(fixture)).lifecycleState).toBe("terminated");
|
||||
await expectSandboxReleased(fixture);
|
||||
}, 60_000);
|
||||
|
||||
it("gives each overlapping stop operation one immediate attempt, then respects the stored retry time", async () => {
|
||||
const fixture = await seed("runner_launch");
|
||||
await db.update(nativeRunFinalizations).set({ leaseExpiresAt: new Date(Date.now() + 60 * 60_000) })
|
||||
.where(eq(nativeRunFinalizations.runId, fixture.runId));
|
||||
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), errorCode: "cancelled" })
|
||||
.where(eq(heartbeatRuns.id, fixture.runId));
|
||||
const heartbeat = heartbeatService(db, { pluginWorkerManager: fixture.manager });
|
||||
const parent = `lifecycle:${randomUUID()}`, child = `lifecycle:${randomUUID()}`;
|
||||
for (let pass = 0; pass < 30; pass++) {
|
||||
expect(await heartbeat.agentInvocationStopBlocker([fixture.agentId], "Agent lifecycle stop requested",
|
||||
{ trigger: pass % 2 === 0 ? parent : child })).toMatch(/^environment_lease_release_deferred:workspace_owner_active$/);
|
||||
}
|
||||
expect((await lease(fixture.leaseId)).metadata?.releaseDeferral).toMatchObject({ reason: "workspace_owner_active",
|
||||
attempts: 2, triggers: [parent, child] });
|
||||
expect(fixture.teardownCalls()).toHaveLength(0);
|
||||
}, 60_000);
|
||||
|
||||
it.each(PRE_LAUNCH)("the orphan lease check releases a sandbox a cancelled run leaked during %s", async window => {
|
||||
const fixture = await seed(window);
|
||||
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(), errorCode: "cancelled" })
|
||||
.where(eq(heartbeatRuns.id, fixture.runId));
|
||||
const heartbeat = heartbeatService(db, { pluginWorkerManager: fixture.manager });
|
||||
await heartbeat.sweepOrphanedActiveLeases({ companyId: fixture.companyId, leaseId: fixture.leaseId, backoffMs: 5 * 60_000 });
|
||||
await expectSandboxReleased(fixture);
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
agents,
|
||||
companies,
|
||||
createDb,
|
||||
environmentLeases,
|
||||
environments,
|
||||
heartbeatRunEvents,
|
||||
heartbeatRuns,
|
||||
issues,
|
||||
nativeRunFinalizations,
|
||||
plugins,
|
||||
} from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
|
||||
const mockTelemetryClient = vi.hoisted(() => ({ track: vi.fn() }));
|
||||
vi.mock("../telemetry.ts", () => ({ getTelemetryClient: () => mockTelemetryClient }));
|
||||
|
||||
import { createLifecycleDriver } from "../services/agent-lifecycle-driver.js";
|
||||
import { configureAgentLifecycle, createAgentLifecycle } from "../services/agent-lifecycle.js";
|
||||
import { PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED } from "../services/native-local-process-stop.js";
|
||||
import type { PluginWorkerManager } from "../services/plugin-worker-manager.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = support.supported ? describe : describe.skip;
|
||||
|
||||
describeEmbeddedPostgres("terminating an agent whose failed run has a scheduled bootstrap retry", () => {
|
||||
let db!: ReturnType<typeof createDb>;
|
||||
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
||||
const workers: Array<{ stop(): Promise<void> }> = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-terminate-pending-retry-");
|
||||
db = createDb(tempDb.connectionString);
|
||||
}, 30_000);
|
||||
|
||||
afterEach(async () => {
|
||||
for (const worker of workers.splice(0)) await worker.stop();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await tempDb?.cleanup();
|
||||
});
|
||||
|
||||
async function seed(issueStatus: "in_progress" | "cancelled") {
|
||||
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID();
|
||||
const environmentId = randomUUID(), leaseId = randomUUID(), pluginId = randomUUID();
|
||||
const providerLeaseId = `sandbox-${randomUUID()}`;
|
||||
const pluginKey = `paperclip.pending-retry-${pluginId.slice(0, 8)}`;
|
||||
await db.insert(plugins).values({ id: pluginId, pluginKey, packageName: "@paperclipai/plugin-fake-sandbox", version: "1.0.0",
|
||||
apiVersion: 1, categories: ["automation"], status: "ready", installOrder: 1, updatedAt: new Date(),
|
||||
manifestJson: { id: pluginKey, apiVersion: 1, version: "1.0.0", displayName: "Fake sandbox", description: "Test provider",
|
||||
author: "Paperclip", categories: ["automation"], capabilities: ["environment.drivers.register"],
|
||||
entrypoints: { worker: "dist/worker.js" },
|
||||
environmentDrivers: [{ driverKey: "fake-plugin", kind: "sandbox_provider", displayName: "Fake Plugin",
|
||||
configSchema: { type: "object" } }] } } as never);
|
||||
await db.insert(companies).values({ id: companyId, name: "Paperclip",
|
||||
issuePrefix: `T${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`, requireBoardApprovalForNewAgents: false });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "OpenCoder", role: "engineer", status: "idle",
|
||||
adapterType: "paperclip_runner", adapterConfig: { provider: "opencode" }, runtimeConfig: {}, permissions: {} });
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Short task", status: issueStatus,
|
||||
priority: "medium", assigneeAgentId: agentId });
|
||||
const config = { provider: "fake-plugin", image: "fake:test", timeoutMs: 1234, reuseLease: false };
|
||||
await db.insert(environments).values({ id: environmentId, name: `Fake sandbox ${environmentId}`, driver: "sandbox",
|
||||
status: "active", config });
|
||||
const failedAt = new Date(Date.now() - 5_000);
|
||||
const retryAt = new Date(Date.now() + 17 * 60_000);
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "assignment", status: "failed",
|
||||
runtimeMode: "native", runtimeModeResolvedAt: failedAt, issueId, nativeIssueId: issueId, startedAt: failedAt,
|
||||
finishedAt: failedAt, errorCode: "native_runner_process_exited", error: "The runner process exited",
|
||||
contextSnapshot: { issueId }, nextEventSeq: 3, nativePhase: "retryable_failure",
|
||||
resultJson: { executionRecovery: { kind: "bootstrap", recoverable: true, recoveryMode: "bootstrap_retry",
|
||||
nextAttemptAt: retryAt.toISOString() } },
|
||||
runnerProfileJson: { nativeWorkspaceSync: {
|
||||
schema: "paperclip.native-workspace-sync/v3", state: "prepared", descriptorSha256: "a".repeat(64),
|
||||
baselineSha256: "b".repeat(64), finalHostSha256: null, workspaceId: randomUUID(), leaseId, providerLeaseId,
|
||||
remoteCwd: "/workspace", resourceDisposition: "destroy" } } });
|
||||
await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "retryable_failure", attempt: 1,
|
||||
controllerGeneration: 1, failureCode: "native_runner_process_exited", recoveryState: "scheduled", nextAttemptAt: retryAt });
|
||||
await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: runId, issueId,
|
||||
status: "active", leasePolicy: "ephemeral", provider: "fake-plugin", providerLeaseId,
|
||||
metadata: { ...config, agentId, driver: "sandbox", pluginId, pluginKey, sandboxProviderPlugin: true,
|
||||
remoteCwd: "/workspace", sandboxState: "started" } });
|
||||
for (const [index, eventType] of [PROCESS_START_REQUESTED, PROCESS_IDENTITY_RECORDED].entries()) {
|
||||
await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId, seq: index + 1, eventType,
|
||||
stream: "system", level: "info", message: eventType });
|
||||
}
|
||||
const call = vi.fn(async (_pluginId: string, method: string, params: { providerLeaseId?: string }) => {
|
||||
if (method === "environmentStopLease") return { providerLeaseId: params.providerLeaseId, state: "stopped" };
|
||||
if (method === "environmentDestroyLease" || method === "environmentReleaseLease") {
|
||||
return { providerLeaseId: params.providerLeaseId, state: "destroyed" };
|
||||
}
|
||||
throw new Error(`Unexpected provider method ${method}`);
|
||||
});
|
||||
const manager = {
|
||||
isRunning: vi.fn((id: string) => id === pluginId),
|
||||
getWorker: vi.fn(() => ({ supportedMethods: ["environmentReleaseLease", "environmentDestroyLease", "environmentStopLease"] })),
|
||||
call,
|
||||
} as unknown as PluginWorkerManager;
|
||||
return { companyId, agentId, issueId, runId, leaseId, providerLeaseId, manager, call };
|
||||
}
|
||||
|
||||
it.each([
|
||||
["in_progress", "in_progress"],
|
||||
["cancelled", "cancelled"],
|
||||
] as const)("cancels the pending retry and releases its sandbox at once (task %s)", async (issueStatus, finalStatus) => {
|
||||
const fixture = await seed(issueStatus);
|
||||
const lifecycle = createAgentLifecycle(db);
|
||||
const worker = configureAgentLifecycle(db, createLifecycleDriver(db, fixture.manager));
|
||||
workers.push(worker);
|
||||
const startedAt = Date.now();
|
||||
await lifecycle.pauseAgent(fixture.agentId);
|
||||
await worker.process(fixture.agentId);
|
||||
await lifecycle.terminateAgent(fixture.agentId);
|
||||
await worker.process(fixture.agentId);
|
||||
const agent = (await db.select().from(agents).where(eq(agents.id, fixture.agentId)))[0]!;
|
||||
expect(agent.lifecycleState).toBe("terminated");
|
||||
expect(Date.now() - startedAt).toBeLessThan(15_000);
|
||||
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.runId));
|
||||
expect(run!.status).toBe("cancelled");
|
||||
const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, fixture.runId));
|
||||
expect(coordinator).toMatchObject({ phase: "terminal_failure", nextAttemptAt: null, leaseOwner: null });
|
||||
|
||||
const [lease] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, fixture.leaseId));
|
||||
expect(lease!.status).not.toBe("active");
|
||||
expect(lease!.releasedAt).not.toBeNull();
|
||||
expect(fixture.call).toHaveBeenCalledWith(expect.any(String), expect.stringMatching(/^environment(Stop|Destroy|Release)Lease$/),
|
||||
expect.objectContaining({ providerLeaseId: fixture.providerLeaseId }), expect.any(Number));
|
||||
|
||||
expect(await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, fixture.companyId),
|
||||
eq(heartbeatRuns.retryOfRunId, fixture.runId)))).toHaveLength(0);
|
||||
const [task] = await db.select().from(issues).where(eq(issues.id, fixture.issueId));
|
||||
expect(task!.status).toBe(finalStatus);
|
||||
expect(run!.resultJson).toMatchObject({ pauseStop: { holds: ["manual"] },
|
||||
workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [fixture.leaseId] } });
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { createDb, environments, companies, instanceSettings, type Db } from "@paperclipai/db";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { createStatementCensus } from "./helpers/statement-census.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
import { INSTANCE_SETTINGS_CACHE_TTL_MS, INSTANCE_SETTINGS_CHANGED_TOPIC, invalidateInstanceSettingsCache, readThroughInstanceSettings } from "../services/instance-settings-cache.js";
|
||||
import { DATABASE_WORK_CHANNEL, enableDatabaseWorkNotifications, receiveDatabaseWorkNotification } from "@paperclipai/db/work-signals";
|
||||
import { fillUnsetInstanceDefault } from "../services/managed-instance-default.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
|
||||
async function waitUntil(check: () => Promise<boolean>, timeoutMs: number) {
|
||||
const started = Date.now();
|
||||
while (Date.now() - started < timeoutMs) {
|
||||
if (await check()) return Date.now() - started;
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
}
|
||||
throw new Error(`condition not met within ${timeoutMs} ms`);
|
||||
}
|
||||
|
||||
(support.supported ? describe : describe.skip)("instance settings read-through cache", () => {
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: Db;
|
||||
let otherProcess: Db;
|
||||
|
||||
beforeAll(async () => {
|
||||
database = await startEmbeddedPostgresTestDatabase("instance-settings-cache-");
|
||||
db = createDb(database.connectionString);
|
||||
otherProcess = createDb(database.connectionString);
|
||||
await db.insert(companies).values({ name: "Settings cache", issuePrefix: "SCC" });
|
||||
}, 90_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await Promise.all([db?.$client.end({ timeout: 0 }), otherProcess?.$client.end({ timeout: 0 })]);
|
||||
await database?.cleanup();
|
||||
}, 60_000);
|
||||
|
||||
beforeEach(async () => {
|
||||
await db.delete(instanceSettings);
|
||||
invalidateInstanceSettingsCache();
|
||||
});
|
||||
|
||||
it("serves repeated hot reads from one statement", async () => {
|
||||
const census = createStatementCensus(db);
|
||||
try {
|
||||
const settings = instanceSettingsService(db);
|
||||
await settings.get();
|
||||
const measured = await census.measure(async () => {
|
||||
for (let index = 0; index < 50; index++) {
|
||||
await Promise.all([settings.getGeneral(), settings.getExperimental(), instanceSettingsService(db).get()]);
|
||||
}
|
||||
});
|
||||
expect(measured.statements).toBe(0);
|
||||
invalidateInstanceSettingsCache();
|
||||
const concurrent = await census.measure(() => Promise.all(Array.from({ length: 20 }, () => settings.getExperimental())));
|
||||
expect(concurrent.statements).toBe(1);
|
||||
} finally {
|
||||
census.uninstall();
|
||||
}
|
||||
});
|
||||
|
||||
it("reads its own writes in this process at once", async () => {
|
||||
const settings = instanceSettingsService(db);
|
||||
expect((await settings.getExperimental()).enableIsolatedWorkspaces).toBe(false);
|
||||
await settings.updateExperimental({ enableIsolatedWorkspaces: true });
|
||||
expect((await instanceSettingsService(db).getExperimental()).enableIsolatedWorkspaces).toBe(true);
|
||||
expect((await settings.getGeneral()).censorUsernameInLogs).toBe(false);
|
||||
await settings.updateGeneral({ censorUsernameInLogs: true });
|
||||
expect((await settings.getGeneral()).censorUsernameInLogs).toBe(true);
|
||||
});
|
||||
|
||||
it("sees a default environment committed in a caller's transaction once it commits", async () => {
|
||||
const settings = instanceSettingsService(db);
|
||||
expect((await settings.get()).defaultEnvironmentId).toBeNull();
|
||||
const [environment] = await db.insert(environments).values({
|
||||
name: "Managed Sandbox", driver: "sandbox", status: "active", config: {},
|
||||
}).returning({ id: environments.id });
|
||||
expect((await fillUnsetInstanceDefault(db, environment!.id)).filled).toBe(true);
|
||||
expect((await settings.get()).defaultEnvironmentId).toBe(environment!.id);
|
||||
});
|
||||
|
||||
it("takes a change made by another process within the cache bound", async () => {
|
||||
const settings = instanceSettingsService(db);
|
||||
expect((await settings.getExperimental()).enableIsolatedWorkspaces).toBe(false);
|
||||
const changedAt = Date.now();
|
||||
await otherProcess.update(instanceSettings)
|
||||
.set({ experimental: sql`coalesce(${instanceSettings.experimental}, '{}'::jsonb) || '{"enableIsolatedWorkspaces":true}'::jsonb` })
|
||||
.where(eq(instanceSettings.singletonKey, "default"));
|
||||
await waitUntil(async () => (await settings.getExperimental()).enableIsolatedWorkspaces === true,
|
||||
INSTANCE_SETTINGS_CACHE_TTL_MS + 1_000);
|
||||
expect(Date.now() - changedAt).toBeLessThanOrEqual(INSTANCE_SETTINGS_CACHE_TTL_MS + 500);
|
||||
});
|
||||
|
||||
it("never shares cached rows with callers that mutate them", async () => {
|
||||
const settings = instanceSettingsService(db);
|
||||
const first = await settings.get();
|
||||
(first.experimental as unknown as Record<string, unknown>).enableIsolatedWorkspaces = true;
|
||||
expect((await settings.get()).experimental.enableIsolatedWorkspaces).toBe(false);
|
||||
});
|
||||
|
||||
it("reads inside a transaction bypass the cache", async () => {
|
||||
const settings = instanceSettingsService(db);
|
||||
expect((await settings.getExperimental()).enableIsolatedWorkspaces).toBe(false);
|
||||
await db.transaction(async tx => {
|
||||
await tx.update(instanceSettings).set({ experimental: { enableIsolatedWorkspaces: true } })
|
||||
.where(eq(instanceSettings.singletonKey, "default"));
|
||||
const inside = instanceSettingsService(tx as unknown as Db);
|
||||
expect((await inside.getExperimental()).enableIsolatedWorkspaces).toBe(true);
|
||||
const census = createStatementCensus(db);
|
||||
try {
|
||||
const reads = await census.measure(async () => { await inside.getExperimental(); await inside.getGeneral(); });
|
||||
expect(reads.statements).toBe(2);
|
||||
} finally {
|
||||
census.uninstall();
|
||||
}
|
||||
throw new Error("rollback");
|
||||
}).catch(() => undefined);
|
||||
expect((await settings.getExperimental()).enableIsolatedWorkspaces).toBe(false);
|
||||
});
|
||||
|
||||
it("never stores a read that started before an invalidation", async () => {
|
||||
const owner = {};
|
||||
let resolveFirst!: (value: string) => void;
|
||||
const first = readThroughInstanceSettings(owner, () => new Promise<string>(resolve => { resolveFirst = resolve; }));
|
||||
invalidateInstanceSettingsCache();
|
||||
resolveFirst("before the write");
|
||||
expect(await first).toBe("before the write");
|
||||
let loads = 0;
|
||||
expect(await readThroughInstanceSettings(owner, async () => { loads += 1; return "after the write"; })).toBe("after the write");
|
||||
expect(await readThroughInstanceSettings(owner, async () => { loads += 1; return "unexpected"; })).toBe("after the write");
|
||||
expect(loads).toBe(1);
|
||||
});
|
||||
|
||||
it("drops the cached row when another process announces a settings change", async () => {
|
||||
const settings = instanceSettingsService(db);
|
||||
await settings.getExperimental();
|
||||
const census = createStatementCensus(db);
|
||||
try {
|
||||
const cached = await census.measure(() => settings.getExperimental());
|
||||
expect(cached.statements).toBe(0);
|
||||
receiveDatabaseWorkNotification(db, JSON.stringify({ version: 1, origin: "another-process", topic: INSTANCE_SETTINGS_CHANGED_TOPIC }));
|
||||
const refreshed = await census.measure(() => settings.getExperimental());
|
||||
expect(refreshed.statements).toBe(1);
|
||||
} finally {
|
||||
census.uninstall();
|
||||
}
|
||||
});
|
||||
|
||||
it("announces a settings change before the other wakes of the same write", async () => {
|
||||
const payloads: string[] = [];
|
||||
const listener = await otherProcess.$client.listen(DATABASE_WORK_CHANNEL, payload => { payloads.push(payload); });
|
||||
enableDatabaseWorkNotifications(db);
|
||||
try {
|
||||
await instanceSettingsService(db).updateExperimental({ enableStatusCards: true });
|
||||
await waitUntil(async () => payloads.length > 1, 5_000);
|
||||
const topics = payloads.map(payload => (JSON.parse(payload) as { topic: string }).topic);
|
||||
expect(topics[0]).toBe(INSTANCE_SETTINGS_CHANGED_TOPIC);
|
||||
expect(topics).toContain("status-card-evaluation");
|
||||
payloads.length = 0;
|
||||
await instanceSettingsService(db).updateGeneral({ censorUsernameInLogs: true });
|
||||
await waitUntil(async () => payloads.length > 0, 5_000);
|
||||
expect(payloads.map(payload => (JSON.parse(payload) as { topic: string }).topic)).toEqual([INSTANCE_SETTINGS_CHANGED_TOPIC]);
|
||||
} finally {
|
||||
await listener.unlisten();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,215 @@
|
||||
import { appendFileSync } from "node:fs";
|
||||
import { createServer } from "node:http";
|
||||
import { setImmediate as immediate } from "node:timers/promises";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { agents, heartbeatRunEvents, heartbeatRuns, issueComments, issues } from "@paperclipai/db";
|
||||
import { trimWorkSignalStack, workSignalDebug } from "@paperclipai/db/work-signal-debug";
|
||||
import { issueService } from "../services/issues.js";
|
||||
import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js";
|
||||
import { seedRecoveryPopulation } from "./helpers/recovery-population.js";
|
||||
|
||||
vi.hoisted(() => { process.env.PAPERCLIP_DEBUG_WORK_SIGNALS = "stranded-assignments:1,assigned-work-invariant:1"; });
|
||||
|
||||
const MINUTE = 60_000;
|
||||
const measuring = Boolean(process.env.RECOVERY_ACTIVITY_REPORT);
|
||||
const report = (label: string, summary: unknown) => {
|
||||
if (process.env.RECOVERY_ACTIVITY_REPORT) appendFileSync(process.env.RECOVERY_ACTIVITY_REPORT, `${label} ${JSON.stringify(summary, null, 1)}\n`);
|
||||
};
|
||||
const TASK_QUEUES = new Set(["stranded-assignments", "assigned-work-invariant", "resolved-dependencies", "stale-issue-locks"]);
|
||||
type Recorded = { at: number; topic: string; name: string; fields: Record<string, unknown> };
|
||||
|
||||
describeIssueRecovery("recovery checks while runs are active in a staging-shaped company", () => {
|
||||
const state = issueRecoveryFixture({ meter: true });
|
||||
|
||||
async function advance(ms: number) {
|
||||
const until = Date.now() + ms;
|
||||
while (Date.now() < until) {
|
||||
await vi.advanceTimersByTimeAsync(Math.min(1000, until - Date.now()));
|
||||
await Promise.allSettled([...state.passes]); await immediate();
|
||||
}
|
||||
}
|
||||
|
||||
function record() {
|
||||
const events: Recorded[] = [];
|
||||
vi.spyOn(workSignalDebug, "event").mockImplementation((topic, name, fields = {}) => {
|
||||
if (name === "check") events.push({ at: Date.now(), topic, name, fields });
|
||||
});
|
||||
vi.spyOn(workSignalDebug, "signal").mockImplementation((topic, hint) => {
|
||||
if (!TASK_QUEUES.has(topic)) return;
|
||||
const holder: { stack?: string } = {};
|
||||
const limit = Error.stackTraceLimit;
|
||||
Error.stackTraceLimit = 40;
|
||||
Error.captureStackTrace(holder);
|
||||
Error.stackTraceLimit = limit;
|
||||
const frames = trimWorkSignalStack(holder.stack, 30).filter(line => !/issue-recovery-notifications|run-dispatch-notifications|external-conversation-settlement-notifications|native-status-reassessment-notifications|execution-control-notifications|issue-review-state-notifications|mockImplementation|spy|vitest/.test(line));
|
||||
const short = (line: string) => line.replace(/^at (async )?/, "").replace(/\(?\/.*\/server\/src\//, "(").replace(/:\d+\)?$/, ")");
|
||||
const app = frames.filter(line => /services|modules|routes/.test(line));
|
||||
const caller = app.length ? app.slice(0, process.env.RECOVERY_ACTIVITY_FRAMES ? Number(process.env.RECOVERY_ACTIVITY_FRAMES) : 1).map(short).join(" < ")
|
||||
: short(frames[0] ?? "unknown");
|
||||
const kind = hint === undefined || hint === "*" ? "all" : (() => {
|
||||
const scope = JSON.parse(hint) as Record<string, unknown>;
|
||||
return scope.issueId ? "task" : scope.graphRunId || scope.graphIssueId ? "graph" : scope.backstop ? "backstop" : "company";
|
||||
})();
|
||||
events.push({ at: Date.now(), topic, name: "signal", fields: { kind, caller } });
|
||||
});
|
||||
return events;
|
||||
}
|
||||
|
||||
function summarize(events: Recorded[], seconds: number) {
|
||||
const checks: Record<string, Record<string, number>> = {}, signals: Record<string, number> = {}, scoped: Record<string, number> = {};
|
||||
for (const event of events) {
|
||||
if (event.name === "check") {
|
||||
const byQueue = checks[event.topic] ??= {};
|
||||
byQueue[String(event.fields.wake)] = (byQueue[String(event.fields.wake)] ?? 0) + 1;
|
||||
} else if (event.topic === "stranded-assignments" && (event.fields.kind === "task" || event.fields.kind === "graph")) {
|
||||
const key = `${event.fields.kind} ${event.fields.caller}`;
|
||||
scoped[key] = (scoped[key] ?? 0) + 1;
|
||||
} else if (event.fields.kind !== "task" && event.fields.kind !== "graph") {
|
||||
const key = `${event.topic} ${event.fields.kind} ${event.fields.caller}`;
|
||||
signals[key] = (signals[key] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
const perSecond = Object.fromEntries(Object.entries(checks).map(([queue, byReason]) => [queue, Object.fromEntries(
|
||||
Object.entries(byReason).map(([reason, count]) => [reason, Number((count / seconds).toFixed(2))]))]));
|
||||
const total = (queue: string) => Object.values(checks[queue] ?? {}).reduce((sum, count) => sum + count, 0);
|
||||
return { checks, perSecond, signals, scoped, stranded: total("stranded-assignments"), assigned: total("assigned-work-invariant") };
|
||||
}
|
||||
|
||||
async function provider(companyId: string, workerIds: string[]) {
|
||||
const failures: unknown[] = [];
|
||||
const listener = createServer(async (request, response) => {
|
||||
try {
|
||||
let body = "";
|
||||
for await (const chunk of request) body += chunk;
|
||||
const { runId } = JSON.parse(body) as { runId: string };
|
||||
const [run] = await state.db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId)));
|
||||
if (!run!.contextSnapshot?.issueId) { response.end("ok"); return; }
|
||||
const issueId = String(run!.contextSnapshot?.issueId);
|
||||
const deadlocked = (error: unknown): boolean => typeof error === "object" && error !== null
|
||||
&& ((error as { code?: string }).code === "40P01" || deadlocked((error as { cause?: unknown }).cause));
|
||||
const retryDeadlock = async (write: () => Promise<unknown>) => {
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
try { return await write(); } catch (error) { if (attempt >= 3 || !deadlocked(error)) throw error; }
|
||||
}
|
||||
};
|
||||
await retryDeadlock(() => issueService(state.db).addComment(issueId, "Progress: done with this step", { agentId: run!.agentId, runId }));
|
||||
await retryDeadlock(() => issueService(state.db).update(issueId, { status: "in_review" }));
|
||||
response.end("ok");
|
||||
} catch (error) { failures.push(error); response.statusCode = 500; response.end("failed"); }
|
||||
});
|
||||
await new Promise<void>(resolve => listener.listen(0, "127.0.0.1", resolve));
|
||||
const port = (listener.address() as { port: number }).port;
|
||||
const script = `fetch("http://127.0.0.1:${port}/progress",{method:"POST",body:JSON.stringify({runId:process.env.PAPERCLIP_RUN_ID})}).then(r=>{if(!r.ok)process.exitCode=1;console.log("ok")})`;
|
||||
await state.db.update(agents).set({ adapterConfig: { command: process.execPath, args: ["-e", script], cwd: process.cwd() } })
|
||||
.where(inArray(agents.id, workerIds));
|
||||
return { failures, close: async () => { listener.closeAllConnections(); await new Promise<void>(resolve => listener.close(() => resolve())); } };
|
||||
}
|
||||
|
||||
async function measure(runsPerMinute: number, minutes: number, timerRunsPerMinute = 0) {
|
||||
const f = await state.fixture();
|
||||
const population = await seedRecoveryPopulation(state.db, f.companyId, { agents: 50, inReview: 780, inProgress: 40, todo: 30,
|
||||
recoveryActions: 12, terminated: 3 });
|
||||
const workers = population.agentIds.slice(7, 7 + 41);
|
||||
const fake = await provider(f.companyId, workers);
|
||||
const events = record();
|
||||
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
|
||||
await state.start({});
|
||||
await advance(10 * MINUTE);
|
||||
events.length = 0;
|
||||
const counts = async () => {
|
||||
const [runs] = await state.db.select({ finished: sql<number>`count(*) filter (where ${heartbeatRuns.status} = 'succeeded')::int`,
|
||||
failed: sql<number>`count(*) filter (where ${heartbeatRuns.status} = 'failed')::int`, all: sql<number>`count(*)::int` })
|
||||
.from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), eq(heartbeatRuns.runtimeMode, "legacy")));
|
||||
const [events] = await state.db.select({ n: sql<number>`count(*)::int` }).from(heartbeatRunEvents)
|
||||
.where(eq(heartbeatRunEvents.companyId, f.companyId));
|
||||
const [comments] = await state.db.select({ n: sql<number>`count(*)::int` }).from(issueComments)
|
||||
.where(and(eq(issueComments.companyId, f.companyId), sql`${issueComments.authorAgentId} is not null`));
|
||||
return { ...runs!, events: events!.n, agentComments: comments!.n };
|
||||
};
|
||||
const workBefore = await counts();
|
||||
const before = state.meter.read();
|
||||
const startedAt = Date.now();
|
||||
const byCheck: Record<string, number> = {}, settingsCallers: Record<string, number> = {};
|
||||
const tally = (log: ReturnType<typeof state.meter.stopLog>) => {
|
||||
for (const entry of log) {
|
||||
const stack = entry.stack ?? "";
|
||||
const owner = stack.includes("reconcileStrandedAssignedIssues") ? "stranded-assignments"
|
||||
: /assigned-work-sweep|checkIssue/.test(stack) ? "assigned-work-invariant"
|
||||
: stack.includes("sweepStaleIssueLocks") ? "stale-issue-locks" : stack.includes("recovery/work.ts") ? "recovery-loads" : "other";
|
||||
byCheck[owner] = (byCheck[owner] ?? 0) + 1;
|
||||
if (/from "instance_settings"/.test(entry.sql)) {
|
||||
const frame = stack.split("\n").map(line => line.trim()).find(line => /server\/src\/services\//.test(line) && !/instance-settings/.test(line)) ?? "unknown";
|
||||
const key = `${owner} ${frame.replace(/^at (async )?/, "").replace(/\(?\/.*\/server\/src\//, "(").replace(/:\d+\)?$/, ")")}`;
|
||||
settingsCallers[key] = (settingsCallers[key] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
};
|
||||
if (measuring) state.meter.startLog({ stacks: true });
|
||||
let next = 12;
|
||||
for (let minute = 0; minute < minutes; minute++) {
|
||||
const minuteEnds = startedAt + (minute + 1) * MINUTE;
|
||||
for (let started = 0; started < runsPerMinute; started++) {
|
||||
const issueId = population.inReview[next++ % population.inReview.length]!;
|
||||
const comment = await issueService(state.db).addComment(issueId, "Please take another pass", { userId: "recovery-user" });
|
||||
const [task] = await state.db.select({ assigneeAgentId: issues.assigneeAgentId }).from(issues).where(eq(issues.id, issueId));
|
||||
await state.heartbeat.wakeup(task!.assigneeAgentId!, { source: "automation", triggerDetail: "system", reason: "issue_commented",
|
||||
payload: { issueId, commentId: comment.id, mutation: "comment" }, requestedByActorType: "user", requestedByActorId: "recovery-user",
|
||||
contextSnapshot: { issueId, taskId: issueId, commentId: comment.id, wakeCommentId: comment.id, source: "issue.comment",
|
||||
wakeReason: "issue_commented" } });
|
||||
await vi.advanceTimersByTimeAsync(Math.floor(MINUTE / runsPerMinute / 4));
|
||||
}
|
||||
for (let timer = 0; timer < timerRunsPerMinute; timer++) {
|
||||
await state.heartbeat.wakeup(workers[(minute * timerRunsPerMinute + timer) % workers.length]!, { source: "on_demand", triggerDetail: "manual",
|
||||
reason: "manual", requestedByActorType: "user", requestedByActorId: "recovery-user",
|
||||
contextSnapshot: { source: "scheduler", reason: "interval_elapsed", now: new Date().toISOString() } });
|
||||
}
|
||||
await advance(minuteEnds - Date.now());
|
||||
await state.heartbeat.drainActiveRunExecutions();
|
||||
if (measuring) tally(state.meter.stopLog());
|
||||
if (measuring) state.meter.startLog({ stacks: true });
|
||||
}
|
||||
const seconds = (Date.now() - startedAt) / 1000;
|
||||
const after = state.meter.read();
|
||||
if (measuring) tally(state.meter.stopLog());
|
||||
const workAfter = await counts();
|
||||
const work = { started: workAfter.all - workBefore.all, finished: workAfter.finished - workBefore.finished,
|
||||
failed: workAfter.failed - workBefore.failed, events: workAfter.events - workBefore.events,
|
||||
agentComments: workAfter.agentComments - workBefore.agentComments };
|
||||
const summary = { ...summarize(events, seconds), seconds, work,
|
||||
statementsPerSecond: Number(((after.statements - before.statements) / seconds).toFixed(1)),
|
||||
agentWriteFailures: fake.failures.length,
|
||||
statementsPerSecondBy: Object.fromEntries(Object.entries(byCheck).map(([owner, count]) => [owner, Number((count / seconds).toFixed(1))])),
|
||||
instanceSettingsReads: settingsCallers };
|
||||
await fake.close();
|
||||
return summary;
|
||||
}
|
||||
|
||||
function expectWorkload(summary: Awaited<ReturnType<typeof measure>>, taskRuns: number, tasklessRuns: number) {
|
||||
expect(summary.agentWriteFailures).toBe(0);
|
||||
expect(summary.work.started).toBeGreaterThanOrEqual(taskRuns + tasklessRuns);
|
||||
expect(summary.work.finished).toBeGreaterThanOrEqual(taskRuns + tasklessRuns);
|
||||
expect(summary.work.failed).toBeLessThanOrEqual(Math.ceil(0.1 * summary.work.started));
|
||||
expect(summary.work.agentComments).toBeGreaterThanOrEqual(taskRuns);
|
||||
expect(summary.work.events).toBeGreaterThan(summary.work.finished);
|
||||
}
|
||||
|
||||
it("re-checks only the tasks seven runs a minute touch, among 850 open tasks", async () => {
|
||||
const minutes = measuring ? 10 : 4;
|
||||
const summary = await measure(7, minutes, 1);
|
||||
report("7 runs/min", summary);
|
||||
expectWorkload(summary, 7 * minutes, minutes);
|
||||
expect(summary.checks["stranded-assignments"]?.company ?? 0).toBe(0);
|
||||
expect(summary.signals).toEqual({});
|
||||
expect(summary.stranded / summary.seconds).toBeLessThan(2);
|
||||
}, 1_800_000);
|
||||
|
||||
it.runIf(measuring)("re-checks only the tasks fifty runs a minute touch, among 850 open tasks", async () => {
|
||||
const summary = await measure(50, 6, 5);
|
||||
report("50 runs/min", summary);
|
||||
expectWorkload(summary, 300, 30);
|
||||
expect(summary.checks["stranded-assignments"]?.company ?? 0).toBe(0);
|
||||
expect(summary.signals).toEqual({});
|
||||
expect(summary.stranded / summary.seconds).toBeLessThan(3);
|
||||
}, 1_800_000);
|
||||
});
|
||||
@@ -8,12 +8,15 @@ import { heartbeatService } from "../services/heartbeat.js";
|
||||
import { issueService } from "../services/issues.js";
|
||||
import { issueRecoveryActionService } from "../services/issue-recovery-actions.js";
|
||||
import { registerIssueRecoveryWork } from "../services/recovery/work.js";
|
||||
import { changedTaskCondition } from "../services/recovery/changed-tasks.js";
|
||||
import { recoveryService } from "../services/recovery/service.js";
|
||||
import { ISSUE_RECOVERY_BACKSTOP_MS, ISSUE_RECOVERY_MAX_ISSUE_IDS, notifyIssueRecovery, resolveIssueGraph }
|
||||
from "../services/issue-recovery-notifications.js";
|
||||
import { notifyNativeStatusReassessment } from "../services/native-status-reassessment-notifications.js";
|
||||
import { notifyExecutionRunWork } from "../services/execution-control-notifications.js";
|
||||
import { notifyRunDispatch } from "../services/run-dispatch-notifications.js";
|
||||
import { notifyExternalConversationSettlement } from "../services/external-conversation-settlement-notifications.js";
|
||||
import { notifyChatInboundWakeNotices } from "../services/chat-inbound-wake-notice-notifications.js";
|
||||
import { promoteDeferredWorkIntents } from "../services/work-intent-outbox.js";
|
||||
import { taskWatchdogService } from "../services/task-watchdogs.js";
|
||||
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
|
||||
@@ -183,6 +186,68 @@ describeIssueRecovery("issue recovery production producers and deadlines", () =>
|
||||
await graph.backlog(4000);
|
||||
expect(await lifecycleEvent(finished())).toBe(first);
|
||||
});
|
||||
it("re-checks a run's own tasks for its settlement, lease and dispatch writers, and nothing for a run without a task", async () => {
|
||||
const f = await fixture();
|
||||
const graph = await runGraph(f.companyId, f.agentId);
|
||||
await graph.backlog(300);
|
||||
const [taskless] = await state.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "succeeded",
|
||||
finishedAt: new Date(), contextSnapshot: { source: "scheduler" } }).returning({ id: heartbeatRuns.id });
|
||||
const checked: string[] = [];
|
||||
const assigned: string[] = [];
|
||||
await recordedRecovery({
|
||||
stranded: async scope => { checked.push(scope.issueId); },
|
||||
assignedWork: {
|
||||
listSuspects: (scope, cursor, limit) => recoveryService(state.db, { enqueueWakeup: async () => null })
|
||||
.assignedWork.listSuspects(scope, cursor, limit),
|
||||
checkIssue: async scope => { assigned.push(scope.issueId); },
|
||||
},
|
||||
}, { backstopMs: 60 * 60_000 });
|
||||
await settleWork({ backstopPending: true });
|
||||
const writers = (runId: string): Array<(tx: object) => Promise<unknown>> => [
|
||||
tx => notifyRunDispatch(tx, { companyId: f.companyId, runId }),
|
||||
tx => notifyExecutionRunWork(tx, { companyId: f.companyId, runId }),
|
||||
tx => notifyExternalConversationSettlement(tx, { companyId: f.companyId, runId }),
|
||||
tx => notifyChatInboundWakeNotices(tx, { companyId: f.companyId, runId }),
|
||||
tx => promoteDeferredWorkIntents(tx, { companyId: f.companyId, trigger: "lock_released", issueId: null, runId }),
|
||||
];
|
||||
for (const [runId, expected] of [[graph.runId, graph.affected], [taskless.id, []]] as Array<[string, string[]]>) {
|
||||
for (const writer of writers(runId)) {
|
||||
checked.length = 0; assigned.length = 0;
|
||||
await state.db.transaction(tx => writer(tx));
|
||||
await settleWork({ backstopPending: true });
|
||||
expect([...new Set(checked)].sort()).toEqual(expected);
|
||||
expect(assigned.every(id => expected.includes(id))).toBe(true);
|
||||
await vi.advanceTimersByTimeAsync(31_000);
|
||||
}
|
||||
}
|
||||
checked.length = 0; assigned.length = 0;
|
||||
await issueService(state.db).addComment(graph.siblingId, "A note on the next task", { userId: "recovery-user" });
|
||||
await settleWork({ backstopPending: true });
|
||||
expect(checked).toEqual([graph.siblingId]);
|
||||
expect(assigned.every(id => id === graph.siblingId)).toBe(true);
|
||||
});
|
||||
it("counts an agent's own run heartbeat as no change to its other tasks, and a resume as a change", async () => {
|
||||
const f = await fixture();
|
||||
const old = new Date(Date.now() - 60 * 60_000);
|
||||
const tasks = await state.db.insert(issues).values(Array.from({ length: 5 }, (_, index) => ({ companyId: f.companyId,
|
||||
title: `Waiting ${index}`, status: "todo", assigneeAgentId: f.agentId, createdAt: old, updatedAt: old }))).returning({ id: issues.id });
|
||||
const since = new Date(Date.now() - 5 * 60_000);
|
||||
const changed = async () => (await state.db.select({ id: issues.id }).from(issues)
|
||||
.where(and(eq(issues.companyId, f.companyId), changedTaskCondition(since)))).map(row => row.id).sort();
|
||||
const heartbeatAt = new Date();
|
||||
await state.db.update(agents).set({ status: "idle", lastHeartbeatAt: heartbeatAt, updatedAt: heartbeatAt }).where(eq(agents.id, f.agentId));
|
||||
expect(await changed()).toEqual([]);
|
||||
await state.db.update(agents).set({ status: "idle", updatedAt: new Date(heartbeatAt.getTime() + 1000) }).where(eq(agents.id, f.agentId));
|
||||
expect(await changed()).toEqual(tasks.map(row => row.id).sort());
|
||||
});
|
||||
it("resolves a run without a task to no tasks and a missing task to the whole company", async () => {
|
||||
const f = await fixture();
|
||||
const [taskless] = await state.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running",
|
||||
contextSnapshot: { source: "scheduler" } }).returning({ id: heartbeatRuns.id });
|
||||
expect(await resolveIssueGraph(state.db, { companyId: f.companyId, runId: taskless.id })).toEqual([]);
|
||||
expect(await resolveIssueGraph(state.db, { companyId: f.companyId, runId: randomUUID() })).toEqual([]);
|
||||
expect(await resolveIssueGraph(state.db, { companyId: f.companyId, issueId: randomUUID() })).toBeNull();
|
||||
});
|
||||
it("resolves a run's task graph through index lookups, not the backlog", async () => {
|
||||
const f = await fixture();
|
||||
const graph = await runGraph(f.companyId, f.agentId);
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { expect, it } from "vitest";
|
||||
import { heartbeatRuns, issues } from "@paperclipai/db";
|
||||
import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js";
|
||||
|
||||
describeIssueRecovery("stranded-task check of a terminal latest run", () => {
|
||||
const state = issueRecoveryFixture({ meter: true });
|
||||
|
||||
async function seed(run: Partial<typeof heartbeatRuns.$inferInsert>) {
|
||||
const f = await state.fixture();
|
||||
const issueId = randomUUID(), runId = randomUUID();
|
||||
await state.db.insert(issues).values({ id: issueId, companyId: f.companyId, title: "Checked task", status: "in_progress",
|
||||
assigneeAgentId: f.agentId });
|
||||
await state.db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "failed",
|
||||
invocationSource: "manual", contextSnapshot: { issueId }, finishedAt: new Date(Date.now() - 60_000), errorCode: "process_lost",
|
||||
...run });
|
||||
return { ...f, issueId, runId };
|
||||
}
|
||||
|
||||
async function leaseReads(f: { companyId: string; issueId: string }) {
|
||||
state.meter.startLog();
|
||||
await state.heartbeat.reconcileStrandedAssignedIssues({ companyId: f.companyId, issueId: f.issueId,
|
||||
skipExternalConversationSettlement: true, skipRelatedRecovery: true });
|
||||
return state.meter.stopLog().filter(entry => /^select "controller_lease_expires_at" from "heartbeat_runs"/.test(entry.sql.trim()));
|
||||
}
|
||||
|
||||
it("does not read the controller lease of a native latest run, which can never still be settling", async () => {
|
||||
const f = await seed({ runtimeMode: "native", controllerBootId: randomUUID(),
|
||||
controllerLeaseExpiresAt: new Date(Date.now() + 60_000) });
|
||||
expect(await leaseReads(f)).toEqual([]);
|
||||
}, 120_000);
|
||||
|
||||
it("still reads the unexpired controller lease of a legacy run another server is settling", async () => {
|
||||
const f = await seed({ runtimeMode: "legacy", controllerBootId: randomUUID(),
|
||||
controllerLeaseExpiresAt: new Date(Date.now() + 60_000) });
|
||||
expect(await leaseReads(f)).toHaveLength(1);
|
||||
}, 120_000);
|
||||
});
|
||||
@@ -98,6 +98,24 @@ describe.skipIf(!support.supported)("provider-owned fresh retry reservations", (
|
||||
expect(settled.metadata?.workspaceProviderRemoved).toBe(true);
|
||||
expect(cache.release).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
it("prepares provider storage for a fresh retry that follows a workspace the provider does not own", async () => {
|
||||
const f = await createPluginWorkspaceFixture(db); await enable(f.pluginId);
|
||||
const [previous] = await db.insert(executionWorkspaces).values({ companyId: f.companyId, projectId: f.input.projectId,
|
||||
projectWorkspaceId: f.input.projectWorkspaceId, sourceIssueId: f.issueId, mode: "isolated_workspace",
|
||||
strategyType: "project_primary", name: "Fresh task workspace", status: "active", providerType: "adapter_managed" }).returning();
|
||||
await db.update(issues).set({ executionWorkspaceId: previous.id, workspaceBindingRevision: 1 }).where(eq(issues.id, f.issueId));
|
||||
await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, f.runId));
|
||||
const [run] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.input.agentId,
|
||||
issueId: f.issueId, status: "running" }).returning();
|
||||
const fresh = { attemptId: randomUUID(), sourceRunId: f.runId, previousWorkspaceId: previous.id, recoverySnapshots: [] };
|
||||
const workspace = await preparePluginWorkspace(db, f.workers, { ...f.input, runId: run.id,
|
||||
existingWorkspaceId: previous.id, fresh, expectedBindingRevision: 1 });
|
||||
expect(workspace).not.toBeNull();
|
||||
expect(workspace!.id).not.toBe(previous.id);
|
||||
expect(workspace!.providerType).toBe("plugin");
|
||||
expect(f.calls).toHaveLength(1);
|
||||
expect(f.calls[0].operation).toMatchObject({ kind: "prepare", fresh, branchName: null });
|
||||
});
|
||||
it("rejects a changed task revision before calling the provider", async () => {
|
||||
const f = await fixture(); await enable(f.pluginId);
|
||||
await db.update(issues).set({ workspaceBindingRevision: 2 }).where(eq(issues.id, f.issueId));
|
||||
|
||||
@@ -15,6 +15,7 @@ import { projectRoutes } from "../routes/projects.js";
|
||||
import { errorHandler } from "../middleware/index.js";
|
||||
import { createPluginWorkspaceFixture } from "./helpers/plugin-workspaces.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { invalidateInstanceSettingsCache } from "../services/instance-settings-cache.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
describe.skipIf(!support.supported)("project environment compatibility", () => {
|
||||
@@ -43,6 +44,7 @@ describe.skipIf(!support.supported)("project environment compatibility", () => {
|
||||
{ name: "Build host", driver: "ssh", config: { host: "build.example.com" } },
|
||||
]).returning();
|
||||
await db.insert(instanceSettings).values({ defaultEnvironmentId: sandbox.id });
|
||||
invalidateInstanceSettingsCache();
|
||||
return { ...f, plugin, computer, local, sandbox, ssh };
|
||||
}
|
||||
|
||||
@@ -85,6 +87,7 @@ describe.skipIf(!support.supported)("project environment compatibility", () => {
|
||||
await db.update(agents).set({ defaultEnvironmentId: null }).where(eq(agents.id, f.input.agentId));
|
||||
expect((await projectEnvironmentOptions(db, f.companyId, { userId: "person" })).defaultEnvironmentId).toBe(f.sandbox.id);
|
||||
await db.update(instanceSettings).set({ defaultEnvironmentId: null });
|
||||
invalidateInstanceSettingsCache();
|
||||
expect((await projectEnvironmentOptions(db, f.companyId)).defaultEnvironmentId).toBe(f.local.id);
|
||||
});
|
||||
|
||||
@@ -101,6 +104,7 @@ describe.skipIf(!support.supported)("project environment compatibility", () => {
|
||||
expect(await withDefaultProjectStorage(db, f.companyId, explicit)).toEqual(explicit);
|
||||
await expect(withDefaultProjectStorage(db, f.companyId, explicit, { environmentId: f.computer.id })).rejects.toMatchObject({ status: 409 });
|
||||
await db.update(instanceSettings).set({ defaultEnvironmentId: f.computer.id });
|
||||
invalidateInstanceSettingsCache();
|
||||
expect((await svc.getById(sandboxProject.id))?.workspaceProvider?.pluginId).toBeNull();
|
||||
});
|
||||
|
||||
@@ -175,6 +179,7 @@ describe.skipIf(!support.supported)("project environment compatibility", () => {
|
||||
it("keeps a cold worker's storage identity, and uses the only storage left after its default is archived", async () => {
|
||||
const f = await fixture();
|
||||
await db.update(instanceSettings).set({ defaultEnvironmentId: f.computer.id });
|
||||
invalidateInstanceSettingsCache();
|
||||
await db.update(plugins).set({ status: "error" }).where(eq(plugins.id, f.pluginId));
|
||||
expect(await withDefaultProjectStorage(db, f.companyId, null)).toMatchObject({ storageProviderPluginId: f.pluginId });
|
||||
await db.update(environments).set({ status: "archived" }).where(eq(environments.id, f.computer.id));
|
||||
@@ -186,6 +191,7 @@ describe.skipIf(!support.supported)("project environment compatibility", () => {
|
||||
const f = await fixture();
|
||||
const [fake] = await db.insert(environments).values({ name: "Fake", driver: "sandbox", config: { provider: "fake" } }).returning();
|
||||
await db.update(instanceSettings).set({ defaultEnvironmentId: fake.id });
|
||||
invalidateInstanceSettingsCache();
|
||||
const options = await projectEnvironmentOptions(db, f.companyId);
|
||||
expect(options.groups).toHaveLength(2);
|
||||
expect(options.defaultEnvironmentId).toBeNull();
|
||||
@@ -197,6 +203,7 @@ describe.skipIf(!support.supported)("project environment compatibility", () => {
|
||||
const f = await fixture();
|
||||
await db.update(environments).set({ status: "archived" }).where(inArray(environments.id, [f.sandbox.id, f.ssh.id]));
|
||||
await db.update(instanceSettings).set({ experimental: { enableManagedSandboxOnly: true } });
|
||||
invalidateInstanceSettingsCache();
|
||||
const options = await projectEnvironmentOptions(db, f.companyId);
|
||||
expect(options).toEqual({
|
||||
groups: [{ storageProviderPluginId: f.pluginId, environments: [{ id: f.computer.id, name: f.computer.name }] }],
|
||||
@@ -214,8 +221,10 @@ describe.skipIf(!support.supported)("project environment compatibility", () => {
|
||||
await db.insert(companyMemberships).values({ companyId: f.companyId, principalType: "user", principalId: userId,
|
||||
status: "active", membershipRole: "operator" });
|
||||
await db.update(environments).set({ status: "archived" }).where(eq(environments.id, f.computer.id));
|
||||
if (source === "instance") await db.update(instanceSettings).set({ defaultEnvironmentId: f.computer.id });
|
||||
else {
|
||||
if (source === "instance") {
|
||||
await db.update(instanceSettings).set({ defaultEnvironmentId: f.computer.id });
|
||||
invalidateInstanceSettingsCache();
|
||||
} else {
|
||||
await db.update(agents).set({ defaultEnvironmentId: f.computer.id }).where(eq(agents.id, f.input.agentId));
|
||||
await db.insert(userCompanyPreferences).values({ companyId: f.companyId, userId, primaryAgentId: f.input.agentId });
|
||||
}
|
||||
@@ -231,10 +240,12 @@ describe.skipIf(!support.supported)("project environment compatibility", () => {
|
||||
const f = await fixture();
|
||||
await db.update(environments).set({ metadata: { managedByPaperclip: true, managedKubernetesSandbox: true } }).where(eq(environments.id, f.sandbox.id));
|
||||
await db.update(instanceSettings).set({ defaultEnvironmentId: f.local.id, experimental: { enableManagedSandboxOnly: true } });
|
||||
invalidateInstanceSettingsCache();
|
||||
const managed = await projectEnvironmentOptions(db, f.companyId);
|
||||
expect(managed.defaultEnvironmentId).toBe(f.sandbox.id);
|
||||
expect(managed.groups.flatMap(group => group.environments).map(value => value.id)).not.toContain(f.local.id);
|
||||
await db.update(instanceSettings).set({ general: { executionMode: "kubernetes" } });
|
||||
invalidateInstanceSettingsCache();
|
||||
const forced = await projectEnvironmentOptions(db, f.companyId);
|
||||
expect(forced.groups).toEqual([{ storageProviderPluginId: null, environments: [{ id: f.sandbox.id, name: f.sandbox.name }] }]);
|
||||
await expect(withDefaultProjectStorage(db, f.companyId, null, { environmentId: f.computer.id })).rejects.toMatchObject({ status: 409 });
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { agents, companies, createDb, environmentLeases, executionWorkspaceSnapshots, executionWorkspaces, heartbeatRuns,
|
||||
issues, nativeRunFinalizations, workspaceOperations } from "@paperclipai/db";
|
||||
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
|
||||
import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js";
|
||||
import { notifyExecutionRunWork } from "../services/execution-control-notifications.js";
|
||||
import { executionControlSchedule, registerExecutionControlWork } from "../services/execution-control-work.js";
|
||||
import { registerOwnershipReconciliationWork } from "../services/native-runtime/native-finalization-reconciler.js";
|
||||
import { OWNABLE_KINDS } from "../services/recovery/ownership-registry.js";
|
||||
import { createOwnershipReportState, recheckSettlingKinds, runOwnershipReconciliationPass } from "../services/recovery/ownership-invariant-report.js";
|
||||
import { invalidateNativeReplacementDiscovery, reconcileSafeNativeReplacements } from "../services/native-runtime/native-safe-replacement.js";
|
||||
import { notifyRunDispatch } from "../services/run-dispatch-notifications.js";
|
||||
import { readRemoteWorkspaceAuthority } from "@paperclipai/shared";
|
||||
import { idleWorkSnapshot } from "../services/task-admission.js";
|
||||
import { meterDatabaseStatements } from "./helpers/database-statement-meter.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
const minutesAgo = (minutes: number) => new Date(Date.now() - minutes * 60_000);
|
||||
const quiesced = () => ({ schema: "paperclip.remote-workspace-save-work.v1", activeIds: [], unknown: false,
|
||||
owners: {}, quiescedAt: minutesAgo(600).toISOString() });
|
||||
|
||||
type Census = { statements: number; locks: number; byShape: Map<string, { count: number; locks: number }> };
|
||||
|
||||
function shapeOf(query: string) {
|
||||
const text = query.replace(/\s+/g, " ").trim();
|
||||
const table = /\bfrom "?([a-z_]+)"?/i.exec(text)?.[1] ?? /^(?:update|insert into) "?([a-z_]+)"?/i.exec(text)?.[1] ?? "?";
|
||||
const verb = text.split(" ")[0]!.toLowerCase();
|
||||
return `${verb} ${table}${/ for (update|share|no key update)\b/i.test(text) ? " FOR UPDATE" : ""}`;
|
||||
}
|
||||
|
||||
function callerOf(stack: string) {
|
||||
const frame = stack.split("\n").slice(1).find(line => line.includes("/server/src/services/")
|
||||
&& !line.includes("delivery-work-coordinator") && !line.includes("task-admission") && !line.includes("activity-log"));
|
||||
const match = frame && /services\/([^:)]+):(\d+)/.exec(frame);
|
||||
return match ? `${match[1]}:${match[2]}` : "?";
|
||||
}
|
||||
|
||||
describe.skipIf(!support.supported)("recovery passes over settled records (census)", () => {
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let meter: ReturnType<typeof meterDatabaseStatements>;
|
||||
let home: string;
|
||||
let coordinator: ReturnType<typeof createDeliveryWorkCoordinator> | undefined;
|
||||
const errors: unknown[] = [];
|
||||
let companyId: string, agentId: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
home = await mkdtemp(join(tmpdir(), "recovery-census-home-"));
|
||||
vi.stubEnv("PAPERCLIP_HOME", home);
|
||||
vi.stubEnv("SANDBOX_ORPHAN_CLEANUP_SPOOL_DIR", join(home, "orphan-spool"));
|
||||
database = await startEmbeddedPostgresTestDatabase("recovery-settled-census-");
|
||||
db = createDb(database.connectionString, { maxConnections: 4, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0 });
|
||||
meter = meterDatabaseStatements(db, database.connectionString);
|
||||
}, 120_000);
|
||||
afterAll(async () => {
|
||||
meter?.uninstall(); await db?.$client.end({ timeout: 1 }); await database?.cleanup();
|
||||
vi.unstubAllEnvs();
|
||||
await rm(home, { recursive: true, force: true });
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await db.execute(sql`truncate execution_workspace_snapshots, workspace_operations, execution_workspaces, activity_log,
|
||||
native_run_finalizations, heartbeat_runs, issues, agents, companies cascade`);
|
||||
companyId = randomUUID(); agentId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "Census", issuePrefix: `C${companyId.slice(0, 6)}` });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Worker", role: "engineer", adapterType: "paperclip_runner" });
|
||||
});
|
||||
afterEach(async () => {
|
||||
await coordinator?.stop(); coordinator = undefined;
|
||||
vi.useRealTimers();
|
||||
expect(errors.splice(0)).toEqual([]);
|
||||
});
|
||||
|
||||
const runRow = (values: Partial<typeof heartbeatRuns.$inferInsert> = {}) => ({ id: randomUUID(), companyId, agentId,
|
||||
status: "failed", invocationSource: "manual", finishedAt: minutesAgo(600), errorCode: "process_lost", ...values });
|
||||
|
||||
const workspaceRow = (authority: { epoch: number; writerRunId: string | null; dirty: boolean; location?: boolean }) => {
|
||||
const id = randomUUID();
|
||||
return { id, companyId, mode: "isolated_workspace", strategyType: "test", name: id,
|
||||
metadata: { remoteWorkspace: { schema: "paperclip.remote-workspace.v1", epoch: authority.epoch, snapshotId: null,
|
||||
source: { kind: "git", repoUrl: "https://example.invalid/repo.git", ref: null }, dirty: authority.dirty,
|
||||
writerRunId: authority.writerRunId,
|
||||
location: authority.location ? { environmentId: randomUUID(), leaseId: randomUUID(), providerLeaseId: `sandbox-${id}`,
|
||||
remoteCwd: "/workspace/root" } : null } } };
|
||||
};
|
||||
|
||||
type Rows = { runs: Array<ReturnType<typeof runRow>>; workspaces: Array<ReturnType<typeof workspaceRow>>;
|
||||
operations: Array<typeof workspaceOperations.$inferInsert>; snapshots: Array<typeof executionWorkspaceSnapshots.$inferInsert> };
|
||||
|
||||
function ledgerRow(rows: Rows, input: { workspaceId: string; runId: string; epoch: number; status: "pending" | "uploaded"; objectKey?: string | null }) {
|
||||
const operationId = randomUUID(), snapshotId = randomUUID();
|
||||
rows.operations.push({ id: operationId, companyId, executionWorkspaceId: input.workspaceId,
|
||||
heartbeatRunId: input.runId, phase: "remote_workspace_snapshot", status: "failed",
|
||||
metadata: { epoch: input.epoch, boundary: "final", generation: 1, saveWork: quiesced() } });
|
||||
rows.snapshots.push({ id: snapshotId, companyId, executionWorkspaceId: input.workspaceId,
|
||||
sourceOperationId: operationId, sourceRunId: input.runId, generation: 1, epoch: input.epoch, status: input.status,
|
||||
objectKey: input.objectKey ?? null, deleteAfter: new Date(Date.now() + 7 * 86400_000), createdAt: minutesAgo(600),
|
||||
updatedAt: minutesAgo(600) });
|
||||
return snapshotId;
|
||||
}
|
||||
|
||||
async function insert(rows: Rows) {
|
||||
if (rows.runs.length) await db.insert(heartbeatRuns).values(rows.runs);
|
||||
if (rows.workspaces.length) await db.insert(executionWorkspaces).values(rows.workspaces);
|
||||
if (rows.operations.length) await db.insert(workspaceOperations).values(rows.operations);
|
||||
if (rows.snapshots.length) await db.insert(executionWorkspaceSnapshots).values(rows.snapshots);
|
||||
}
|
||||
|
||||
/** The staging shape: history that recovery can no longer change, plus a few live runs. */
|
||||
async function seedStagingShape() {
|
||||
const rows: Rows = { runs: [], workspaces: [], operations: [], snapshots: [] };
|
||||
for (let index = 0; index < 100; index++) {
|
||||
const writer = runRow(index % 2 === 0 ? { executionStage: "executing", runtimeMode: "native",
|
||||
runtimeModeResolvedAt: minutesAgo(601) } : { status: "succeeded", executionStage: "executing" });
|
||||
const workspace = workspaceRow({ epoch: 1, writerRunId: writer.id, dirty: true, location: true });
|
||||
rows.runs.push(writer); rows.workspaces.push(workspace);
|
||||
if (index % 2 === 0) ledgerRow(rows, { workspaceId: workspace.id, runId: writer.id, epoch: 1, status: "pending" });
|
||||
}
|
||||
for (let index = 0; index < 100; index++) {
|
||||
const source = runRow({ status: "succeeded" });
|
||||
const workspace = workspaceRow({ epoch: 2, writerRunId: null, dirty: false });
|
||||
rows.runs.push(source); rows.workspaces.push(workspace);
|
||||
ledgerRow(rows, { workspaceId: workspace.id, runId: source.id, epoch: 1, status: "uploaded",
|
||||
objectKey: `${companyId}/snapshots/${index}.pcws` });
|
||||
}
|
||||
const finished: Array<typeof issues.$inferInsert> = [], finalizations: Array<typeof nativeRunFinalizations.$inferInsert> = [];
|
||||
for (let index = 0; index < 20; index++) {
|
||||
const issueId = randomUUID();
|
||||
finished.push({ id: issueId, companyId, title: `Finished ${index}`, status: "done", assigneeAgentId: agentId });
|
||||
const failed = runRow({ runtimeMode: "native", nativeIssueId: issueId, contextSnapshot: { issueId },
|
||||
runnerProfileJson: { recoveryEventInventoryVersion: 1, nativeExecutionInput: { provider: { kind: "codex" },
|
||||
workspace: { cwd: tmpdir() } } } });
|
||||
rows.runs.push(failed);
|
||||
finalizations.push({ runId: failed.id, companyId, issueId, phase: "terminal_failure", attempt: 1,
|
||||
failureCode: "native_provider_terminal_failed", failureDetail: { originalFailureCode: "fixture_checkpoint_unusable" } });
|
||||
}
|
||||
const live: Array<{ runId: string; issueId: string }> = [];
|
||||
for (let index = 0; index < 7; index++) {
|
||||
const issueId = randomUUID();
|
||||
const liveRun = runRow({ status: "running", runtimeMode: "native", nativeIssueId: issueId, contextSnapshot: { issueId },
|
||||
finishedAt: null, errorCode: null, startedAt: minutesAgo(1) });
|
||||
finished.push({ id: issueId, companyId, title: `Live ${index}`, status: "in_progress", assigneeAgentId: agentId });
|
||||
rows.runs.push(liveRun);
|
||||
live.push({ runId: liveRun.id, issueId });
|
||||
}
|
||||
await db.insert(issues).values(finished);
|
||||
await insert(rows);
|
||||
await db.insert(nativeRunFinalizations).values(finalizations);
|
||||
for (const entry of live) await db.update(issues).set({ executionRunId: entry.runId }).where(sql`id = ${entry.issueId}`);
|
||||
return live;
|
||||
}
|
||||
|
||||
async function start() {
|
||||
coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, canReconcile: () => true,
|
||||
onError: error => errors.push(error) });
|
||||
const ownership = registerOwnershipReconciliationWork(db, coordinator, () => true);
|
||||
const replacement = registerExecutionControlWork(coordinator, [replacementDuty()]);
|
||||
await Promise.all([ownership.ready, replacement.ready]);
|
||||
}
|
||||
|
||||
function replacementDuty() {
|
||||
return { queue: DELIVERY_QUEUES.executionReplacement,
|
||||
run: () => reconcileSafeNativeReplacements(db, new Date(), { verifyStoppedSession: async () => null }),
|
||||
next: executionControlSchedule(db).replacement, onSettled: () => invalidateNativeReplacementDiscovery(db),
|
||||
settleEmptyWhilePaused: true };
|
||||
}
|
||||
|
||||
async function advance(ms: number, onTick?: () => Promise<void>) {
|
||||
const until = Date.now() + ms;
|
||||
while (Date.now() < until) {
|
||||
await onTick?.();
|
||||
await vi.advanceTimersByTimeAsync(Math.min(10_000, until - Date.now())); await delay(1);
|
||||
while (idleWorkSnapshot().active > 0) await delay(5);
|
||||
}
|
||||
}
|
||||
|
||||
async function census(work: () => Promise<unknown>): Promise<Census> {
|
||||
const result: Census = { statements: 0, locks: 0, byShape: new Map() };
|
||||
meter.startLog({ stacks: true });
|
||||
try { await work(); } finally {
|
||||
for (const entry of meter.stopLog()) {
|
||||
const lock = / for (update|share|no key update)\b/i.test(entry.sql);
|
||||
const key = `${shapeOf(entry.sql)} <- ${callerOf(entry.stack ?? "")}`;
|
||||
const row = result.byShape.get(key) ?? { count: 0, locks: 0 };
|
||||
row.count += 1; if (lock) row.locks += 1;
|
||||
result.byShape.set(key, row);
|
||||
result.statements += 1; if (lock) result.locks += 1;
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function table(label: string, result: Census) {
|
||||
const rows = [...result.byShape].sort((a, b) => b[1].count - a[1].count).slice(0, 20)
|
||||
.map(([key, value]) => ` ${String(value.count).padStart(6)} ${String(value.locks).padStart(5)} ${key}`);
|
||||
return `${label}: ${result.statements} statements, ${result.locks} row locks\n${rows.join("\n")}`;
|
||||
}
|
||||
|
||||
const hint = async (live: Array<{ runId: string; issueId: string }>) => {
|
||||
for (const { runId, issueId } of live) {
|
||||
await db.transaction(async tx => {
|
||||
await notifyRunDispatch(tx, { companyId, runId, issueId });
|
||||
await notifyExecutionRunWork(tx, { companyId, runId, issueId });
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
it("counts statements and row locks of one pass of each worker over staging-shaped history", async () => {
|
||||
await seedStagingShape();
|
||||
const state = createOwnershipReportState();
|
||||
await runOwnershipReconciliationPass(db, { state });
|
||||
await runOwnershipReconciliationPass(db, { state });
|
||||
const fullPass = await census(() => runOwnershipReconciliationPass(db, { state }));
|
||||
const watchPass = await census(() => recheckSettlingKinds(db));
|
||||
const duty = replacementDuty();
|
||||
await duty.run();
|
||||
invalidateNativeReplacementDiscovery(db);
|
||||
const replacementPass = await census(async () => { await duty.run(); await duty.next(); });
|
||||
console.log([table("ownership full pass", fullPass), table("ownership watch re-check", watchPass),
|
||||
table("execution replacement pass", replacementPass)].join("\n\n"));
|
||||
const settled = (result: Census) => [...result.byShape.keys()].filter(key =>
|
||||
/remote-(workspace-unsaved-files|snapshot-ledger)-settlement/.test(key));
|
||||
expect({ full: settled(fullPass), watch: settled(watchPass) }).toEqual({ full: [], watch: [] });
|
||||
expect(fullPass.locks).toBe(0);
|
||||
expect(watchPass.statements).toBeLessThanOrEqual(30);
|
||||
expect(replacementPass.statements).toBeLessThanOrEqual(3);
|
||||
}, 300_000);
|
||||
|
||||
it("runs no statements for half an hour once only settled history is left, and takes no row locks while runs are active", async () => {
|
||||
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
|
||||
const live = await seedStagingShape();
|
||||
await start(); await advance(60_000);
|
||||
await db.update(issues).set({ executionRunId: null, status: "done" }).where(sql`execution_run_id is not null`);
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(sql`status = 'running'`);
|
||||
await advance(60_000);
|
||||
const idle = await census(() => advance(30 * 60_000));
|
||||
await db.update(heartbeatRuns).set({ status: "running", finishedAt: null })
|
||||
.where(sql`id in (${sql.join(live.map(entry => sql`${entry.runId}`), sql`, `)})`);
|
||||
const active = await census(() => advance(10 * 60_000, () => hint(live)));
|
||||
console.log([table("idle 30 min", idle), table("active 10 min", active)].join("\n\n"));
|
||||
expect(idle.statements).toBe(0);
|
||||
expect(active.locks).toBe(0);
|
||||
expect([...active.byShape.keys()].filter(key => /remote-(workspace-unsaved-files|snapshot-ledger)-settlement/.test(key))).toEqual([]);
|
||||
}, 1_200_000);
|
||||
|
||||
it("still settles every record that can change promptly, beside staging-shaped history", async () => {
|
||||
await seedStagingShape();
|
||||
const rows: Rows = { runs: [], workspaces: [], operations: [], snapshots: [] };
|
||||
const preparing = runRow({ executionStage: "preparing", finishedAt: minutesAgo(2) });
|
||||
const preparedWorkspace = workspaceRow({ epoch: 1, writerRunId: preparing.id, dirty: true, location: true });
|
||||
const saver = runRow({ executionStage: "executing", finishedAt: minutesAgo(2) });
|
||||
const movedWorkspace = workspaceRow({ epoch: 3, writerRunId: null, dirty: false });
|
||||
const stuckWriter = runRow({ executionStage: "executing", finishedAt: minutesAgo(2) });
|
||||
const stuckWorkspace = workspaceRow({ epoch: 1, writerRunId: stuckWriter.id, dirty: true, location: true });
|
||||
const leaseRun = runRow({ finishedAt: minutesAgo(2) });
|
||||
rows.runs.push(preparing, saver, stuckWriter, leaseRun);
|
||||
rows.workspaces.push(preparedWorkspace, movedWorkspace, stuckWorkspace);
|
||||
const abandoned = ledgerRow(rows, { workspaceId: movedWorkspace.id, runId: saver.id, epoch: 1, status: "pending" });
|
||||
const held = ledgerRow(rows, { workspaceId: stuckWorkspace.id, runId: stuckWriter.id, epoch: 1, status: "pending" });
|
||||
await insert(rows);
|
||||
const [lease] = await db.insert(environmentLeases).values({ companyId, heartbeatRunId: leaseRun.id, status: "active" }).returning();
|
||||
const ledger = async (id: string) => (await db.select().from(executionWorkspaceSnapshots)
|
||||
.where(eq(executionWorkspaceSnapshots.id, id)))[0]!;
|
||||
|
||||
const state = createOwnershipReportState();
|
||||
const first = await runOwnershipReconciliationPass(db, { state });
|
||||
const kind = (id: string) => first.kinds.find(entry => entry.kind === id)!;
|
||||
expect(kind("remote_workspace_unsaved_files")).toMatchObject({ settled: 1 });
|
||||
expect(readRemoteWorkspaceAuthority((await db.select().from(executionWorkspaces)
|
||||
.where(eq(executionWorkspaces.id, preparedWorkspace.id)))[0]!.metadata)).toMatchObject({ dirty: false, writerRunId: null, epoch: 2 });
|
||||
expect((await ledger(abandoned)).status).toBe("deleted");
|
||||
expect((await ledger(held)).status).toBe("pending");
|
||||
expect(kind("environment_run_lease_active")).toMatchObject({ inProgress: 1, settled: 1 });
|
||||
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, lease!.id)))[0]!.status).toBe("pending_cleanup");
|
||||
|
||||
await db.update(executionWorkspaces).set({ metadata: { remoteWorkspace: { ...readRemoteWorkspaceAuthority(stuckWorkspace.metadata)!,
|
||||
epoch: 2, writerRunId: null, dirty: false, location: null } } }).where(eq(executionWorkspaces.id, stuckWorkspace.id));
|
||||
const second = await runOwnershipReconciliationPass(db, { state });
|
||||
expect(second.kinds.find(entry => entry.kind === "remote_snapshot_ledger")).toMatchObject({ settled: 1 });
|
||||
expect((await ledger(held)).status).toBe("deleted");
|
||||
const settledPass = await census(() => runOwnershipReconciliationPass(db, { state }));
|
||||
expect([...settledPass.byShape.keys()].filter(key => /remote-(workspace-unsaved-files|snapshot-ledger)-settlement/.test(key))).toEqual([]);
|
||||
}, 300_000);
|
||||
|
||||
it("skips a dirty workspace whose writer id is not a UUID without failing the listing", async () => {
|
||||
const valid = runRow({ executionStage: "preparing", finishedAt: minutesAgo(2) });
|
||||
const rows: Rows = { runs: [valid], workspaces: [workspaceRow({ epoch: 1, writerRunId: valid.id, dirty: true, location: true })],
|
||||
operations: [], snapshots: [] };
|
||||
const malformed = workspaceRow({ epoch: 1, writerRunId: null, dirty: true, location: true });
|
||||
malformed.metadata.remoteWorkspace.writerRunId = "not-a-run-id" as unknown as null;
|
||||
rows.workspaces.push(malformed);
|
||||
await insert(rows);
|
||||
const kind = OWNABLE_KINDS.find(entry => entry.id === "remote_workspace_unsaved_files")!;
|
||||
const listed = await kind.listInProgress!(db, 200, 0);
|
||||
expect(listed.records.map(record => record.recordId)).toEqual([rows.workspaces[0]!.id]);
|
||||
}, 120_000);
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import fs from "node:fs";
|
||||
import { createIsolatedTestHome } from "./helpers/isolated-test-home.js";
|
||||
import { beforeEach } from "vitest";
|
||||
import { createRequire } from "node:module";
|
||||
import type { AddressInfo, Server as NetServer } from "node:net";
|
||||
import os from "node:os";
|
||||
@@ -76,3 +77,8 @@ if (!SupertestTest.prototype.__paperclipLoopbackPatched) {
|
||||
|
||||
SupertestTest.prototype.__paperclipLoopbackPatched = true;
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
const { invalidateInstanceSettingsCache } = await import("../services/instance-settings-cache.js");
|
||||
invalidateInstanceSettingsCache();
|
||||
});
|
||||
@@ -28,6 +28,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } fro
|
||||
import { smokeLabRoutes } from "../routes/smoke-lab.js";
|
||||
import { SMOKE_LAB_OAUTH_SCOPE } from "../services/smoke-lab.js";
|
||||
import { errorHandler } from "../middleware/index.js";
|
||||
import { invalidateInstanceSettingsCache } from "../services/instance-settings-cache.js";
|
||||
|
||||
const externalTestDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_SMOKE_LAB_TEST_DATABASE_URL");
|
||||
const embeddedPostgresSupport = externalTestDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport();
|
||||
@@ -50,6 +51,7 @@ async function enableSmokeLab(db: TestDb) {
|
||||
target: [instanceSettings.singletonKey],
|
||||
set: { experimental: { enableSmokeLab: true }, updatedAt: new Date() },
|
||||
});
|
||||
invalidateInstanceSettingsCache();
|
||||
}
|
||||
|
||||
async function createAgent(db: TestDb, companyId: string) {
|
||||
|
||||
@@ -279,7 +279,7 @@ describe("resolveCloudTenantActor (shared-pool hardening)", () => {
|
||||
expect(insertedTables.filter((table) => table === companyMemberships)).toHaveLength(3);
|
||||
});
|
||||
|
||||
it("coalesces concurrent identical syncs while keeping authority reads and stale-admin purges per request", async () => {
|
||||
it("coalesces concurrent identical syncs and settings reads while keeping membership reads and stale-admin purges per request", async () => {
|
||||
let release!: () => void;
|
||||
let entered!: () => void;
|
||||
const blocked = new Promise<void>(resolve => { release = resolve; });
|
||||
@@ -294,7 +294,7 @@ describe("resolveCloudTenantActor (shared-pool hardening)", () => {
|
||||
const actors = await Promise.all(requests);
|
||||
expect(insertedTables.filter(table => table === companyMemberships)).toHaveLength(1);
|
||||
expect(deletedTables.filter(table => table === instanceUserRoles)).toHaveLength(20);
|
||||
expect(selectWheres.filter(entry => entry.table === instanceSettings)).toHaveLength(20);
|
||||
expect(selectWheres.filter(entry => entry.table === instanceSettings)).toHaveLength(1);
|
||||
expect(selectWheres.filter(entry => entry.table === companyMemberships && !entry.locked)).toHaveLength(20);
|
||||
expect(selectWheres.filter(entry => entry.table === companyMemberships && entry.locked)).toHaveLength(1);
|
||||
expect(actors.every(actor => actor?.memberships?.[0]?.membershipRole === "owner")).toBe(true);
|
||||
|
||||
@@ -11,6 +11,7 @@ import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } fro
|
||||
import { cloudActorHeaderSourceFromHeaders, resolveCloudTenantActor } from "./auth.js";
|
||||
import { errorHandler } from "./error-handler.js";
|
||||
import { userProfileRoutes } from "../routes/user-profiles.js";
|
||||
import { invalidateInstanceSettingsCache } from "../services/instance-settings-cache.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
const aliasFields = ["name", "email-local", "email", "principal"] as const;
|
||||
@@ -172,11 +173,13 @@ const aliasFields = ["name", "email-local", "email", "principal"] as const;
|
||||
await db.update(companyMemberships).set({ status: "inactive" }).where(and(eq(companyMemberships.companyId, importedCompanyId), eq(companyMemberships.principalId, userId)));
|
||||
await db.insert(instanceSettings).values({ singletonKey: "default", experimental: { enableOwnerInstanceAdmin: true } })
|
||||
.onConflictDoUpdate({ target: instanceSettings.singletonKey, set: { experimental: { enableOwnerInstanceAdmin: true } } });
|
||||
invalidateInstanceSettingsCache();
|
||||
const elevated = await resolve(db, value);
|
||||
expect(elevated?.isInstanceAdmin).toBe(true);
|
||||
expect(elevated?.companyIds).toEqual(actor!.companyIds);
|
||||
expect(await db.select().from(instanceUserRoles).where(eq(instanceUserRoles.userId, userId))).toEqual([]);
|
||||
await db.update(instanceSettings).set({ experimental: { enableOwnerInstanceAdmin: false } });
|
||||
invalidateInstanceSettingsCache();
|
||||
expect((await resolve(db, value))?.isInstanceAdmin).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const stop = vi.hoisted(() => vi.fn(async () => true));
|
||||
vi.mock("../../../services/heartbeat.js", () => ({ heartbeatService: () => ({ stopInvocationsForAgents: stop }) }));
|
||||
const stop = vi.hoisted(() => vi.fn(async () => null));
|
||||
vi.mock("../../../services/heartbeat.js", () => ({ heartbeatService: () => ({ agentInvocationStopBlocker: stop }) }));
|
||||
vi.mock("../../../services/agent-harness-verification.js", () => ({ agentHarnessVerificationService: () => ({ verify: vi.fn() }) }));
|
||||
import { createLifecycleDriver } from "../../../services/agent-lifecycle-driver.js";
|
||||
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { agents, companies, createDb, type Db } from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
|
||||
import { configureAgentLifecycle, createAgentLifecycle } from "../../../services/agent-lifecycle.js";
|
||||
import { lifecyclePendingRetryDelayMs } from "../adapters/postgres.js";
|
||||
import { wakeStoppingAgentLifecycle } from "../../../services/environment-lease-release-deferral.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
|
||||
(support.supported ? describe : describe.skip)("lifecycle host step that stays pending", () => {
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
|
||||
let db: Db;
|
||||
|
||||
beforeAll(async () => {
|
||||
database = await startEmbeddedPostgresTestDatabase("paperclip-lifecycle-pending-backoff-");
|
||||
db = createDb(database.connectionString);
|
||||
}, 60_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await database?.cleanup();
|
||||
});
|
||||
|
||||
it("records why termination is waiting and spaces out its passes", async () => {
|
||||
const companyId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "Lifecycle", issuePrefix: `P${companyId.slice(0, 7)}` });
|
||||
const [agent] = await db.insert(agents).values({ companyId, name: "Stuck", role: "engineer", status: "idle",
|
||||
adapterType: "process", adapterConfig: {}, runtimeConfig: {}, permissions: {} }).returning();
|
||||
let hostCalls = 0;
|
||||
const worker = configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete",
|
||||
runHost: async () => { hostCalls += 1; return { pending: "environment_lease_unreleased" }; } });
|
||||
try {
|
||||
await createAgentLifecycle(db).terminateAgent(agent!.id);
|
||||
const delays: number[] = [];
|
||||
for (let pass = 1; pass <= 7; pass++) {
|
||||
const before = Date.now();
|
||||
await worker.process(agent!.id);
|
||||
await worker.process(agent!.id);
|
||||
const [current] = await db.select().from(agents).where(eq(agents.id, agent!.id));
|
||||
expect(current!.lifecycleState).toBe("terminating");
|
||||
expect(current!.lifecycleOperation).toMatchObject({ pendingReason: "environment_lease_unreleased", pendingPasses: pass });
|
||||
delays.push(Date.parse(current!.lifecycleOperation!.retryAt!) - before);
|
||||
await db.update(agents).set({ lifecycleOperation: { ...current!.lifecycleOperation!, retryAt: new Date(0).toISOString() } })
|
||||
.where(eq(agents.id, agent!.id));
|
||||
}
|
||||
expect(hostCalls).toBe(7);
|
||||
for (const [index, delay] of delays.entries()) {
|
||||
expect(delay).toBeGreaterThanOrEqual(lifecyclePendingRetryDelayMs(index + 1) - 1_000);
|
||||
}
|
||||
expect(delays.at(-1)).toBeGreaterThanOrEqual(60_000 - 1_000);
|
||||
expect(delays.at(-1)).toBeLessThanOrEqual(60_000 + 1_000);
|
||||
expect(lifecyclePendingRetryDelayMs(11)).toBe(60_000);
|
||||
expect(lifecyclePendingRetryDelayMs(500)).toBe(60_000);
|
||||
} finally {
|
||||
await worker.stop();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it("finishes a stop at once when its blocker clears, without waiting out the backoff", async () => {
|
||||
const companyId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "Lifecycle", issuePrefix: `W${companyId.slice(0, 7)}` });
|
||||
const [agent] = await db.insert(agents).values({ companyId, name: "Waiting", role: "engineer", status: "idle",
|
||||
adapterType: "process", adapterConfig: {}, runtimeConfig: {}, permissions: {} }).returning();
|
||||
let blocked = true;
|
||||
const worker = configureAgentLifecycle(db, { requiredPluginIds: async () => [], runPlugin: async () => "complete",
|
||||
runHost: async () => blocked ? { pending: "environment_lease_unreleased" } : "complete" });
|
||||
try {
|
||||
await createAgentLifecycle(db).terminateAgent(agent!.id);
|
||||
for (let pass = 1; pass <= 11; pass++) {
|
||||
await worker.process(agent!.id);
|
||||
const [current] = await db.select().from(agents).where(eq(agents.id, agent!.id));
|
||||
if (pass < 11) await db.update(agents).set({ lifecycleOperation: { ...current!.lifecycleOperation!,
|
||||
retryAt: new Date(0).toISOString() } }).where(eq(agents.id, agent!.id));
|
||||
}
|
||||
const [waiting] = await db.select().from(agents).where(eq(agents.id, agent!.id));
|
||||
expect(Date.parse(waiting!.lifecycleOperation!.retryAt!)).toBeGreaterThan(Date.now() + 30_000);
|
||||
blocked = false;
|
||||
expect(await db.transaction(tx => wakeStoppingAgentLifecycle(tx as unknown as Db, agent!.id))).toBe(true);
|
||||
await worker.process(agent!.id);
|
||||
expect((await db.select().from(agents).where(eq(agents.id, agent!.id)))[0]!.lifecycleState).toBe("terminated");
|
||||
} finally {
|
||||
await worker.stop();
|
||||
}
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -11,6 +11,13 @@ export function assertRootDatabase(db: Db) {
|
||||
}
|
||||
|
||||
type LifecycleRow = typeof agents.$inferSelect;
|
||||
|
||||
const LIFECYCLE_PENDING_BASE_MS = 2_000;
|
||||
const LIFECYCLE_PENDING_MAX_MS = 60_000;
|
||||
|
||||
export function lifecyclePendingRetryDelayMs(passes: number) {
|
||||
return Math.min(LIFECYCLE_PENDING_MAX_MS, LIFECYCLE_PENDING_BASE_MS * 2 ** Math.max(0, passes - 1));
|
||||
}
|
||||
type ChangeOptions = { version?: number; owner?: string; reason?: string };
|
||||
|
||||
// Prepared drafts wait for the wizard; they have no background verification obligation.
|
||||
@@ -83,6 +90,24 @@ export async function requestAgentLifecycleRecheckInTransaction(
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function wakeStoppingAgentLifecycleInTransaction(
|
||||
tx: Pick<Db, "select" | "update">,
|
||||
agentId: string,
|
||||
notify: () => Promise<void>,
|
||||
): Promise<boolean> {
|
||||
if (!("nestedIndex" in tx)) throw new AgentLifecycleConflict("Lifecycle wakes require the producer transaction");
|
||||
const [agent] = await tx.select({ lifecycleState: agents.lifecycleState, lifecycleOperation: agents.lifecycleOperation })
|
||||
.from(agents).where(eq(agents.id, agentId)).for("update");
|
||||
const operation = agent?.lifecycleOperation;
|
||||
if (!agent || !operation || !["pausing", "terminating", "cleaning_up"].includes(agent.lifecycleState)
|
||||
|| (!operation.retryAt && !operation.leaseOwner)) return false;
|
||||
await notify();
|
||||
await tx.update(agents).set({ lifecycleOperation: sql`(${agents.lifecycleOperation} - 'retryAt')
|
||||
|| case when ${agents.lifecycleOperation} ? 'leaseOwner' then '{"recheckRequested":true}'::jsonb else '{}'::jsonb end` })
|
||||
.where(eq(agents.id, agentId));
|
||||
return true;
|
||||
}
|
||||
|
||||
/** The caller owns the accounting transaction and has locked this agent. */
|
||||
async function changeLockedAgent(tx: Db, effects: LifecycleEffects, agent: LifecycleRow,
|
||||
command: LifecycleCommand, options: ChangeOptions = {}, policyHolds?: string[], restartPause = false) {
|
||||
@@ -268,9 +293,12 @@ export function createLifecycleStore(db: Db, effects: LifecycleEffects): Lifecyc
|
||||
sql`${agents.lifecycleOperation}->>'leaseOwner' = ${owner}`)).returning({ id: agents.id });
|
||||
return rows.length > 0;
|
||||
}
|
||||
const previousPasses = (agent.lifecycleOperation as { pendingPasses?: unknown } | null)?.pendingPasses;
|
||||
const pendingPasses = options?.pendingReason ? (typeof previousPasses === "number" ? previousPasses : 0) + 1 : undefined;
|
||||
const retry: Partial<AgentLifecycleOperation> = options?.retryRequired && ["verifying", "resuming"].includes(agent.lifecycleState)
|
||||
? { retryRequired: true }
|
||||
: { retryAt: new Date(now.getTime() + (error ? 60_000 : 2_000)).toISOString() };
|
||||
: { retryAt: new Date(now.getTime() + (error ? 60_000 : pendingPasses ? lifecyclePendingRetryDelayMs(pendingPasses) : 2_000)).toISOString() };
|
||||
if (options?.pendingReason && pendingPasses) Object.assign(retry, { pendingReason: options.pendingReason, pendingPasses });
|
||||
if (options?.verificationFailures !== undefined && agent.lifecycleState === "verifying") {
|
||||
retry.verificationFailures = options.verificationFailures;
|
||||
}
|
||||
|
||||
@@ -20,14 +20,14 @@ export interface LifecycleStore {
|
||||
setRequiredPlugins(agent: LifecycleAgent, owner: string, pluginIds: string[]): Promise<boolean>;
|
||||
completeHost(agent: LifecycleAgent, owner: string): Promise<boolean>;
|
||||
completePlugin(agent: LifecycleAgent, owner: string, pluginId: string): Promise<boolean>;
|
||||
defer(agent: LifecycleAgent, owner: string, error: string | null, now: Date, options?: { retryRequired?: boolean; verificationFailures?: number; waitForSignal?: boolean }): Promise<boolean>;
|
||||
defer(agent: LifecycleAgent, owner: string, error: string | null, now: Date, options?: { retryRequired?: boolean; verificationFailures?: number; waitForSignal?: boolean; pendingReason?: string }): Promise<boolean>;
|
||||
pending(limit: number, now: Date): Promise<string[]>;
|
||||
}
|
||||
|
||||
export interface LifecycleDriver {
|
||||
requiredPluginIds(agent: LifecycleAgent): Promise<string[]>;
|
||||
/** waiting is only a healthy verifying phase owned by an external event. */
|
||||
runHost(agent: LifecycleAgent): Promise<"complete" | "pending" | "waiting">;
|
||||
runHost(agent: LifecycleAgent): Promise<"complete" | "pending" | "waiting" | { pending: string }>;
|
||||
runPlugin(agent: LifecycleAgent, pluginId: string): Promise<"complete" | "pending">;
|
||||
/** Notify the scheduler only after readiness has committed. */
|
||||
onReady?(agent: LifecycleAgent): Promise<void>;
|
||||
|
||||
@@ -51,8 +51,9 @@ export function createLifecycleWorker(store: LifecycleStore, driver: LifecycleDr
|
||||
if (!await runStep("defer", () => store.defer(agent, owner, null, new Date(), { waitForSignal: true }))) continue;
|
||||
return;
|
||||
}
|
||||
if (host === "pending") {
|
||||
if (!await runStep("defer", () => store.defer(agent, owner, null, new Date()))) continue;
|
||||
if (host === "pending" || typeof host === "object") {
|
||||
const pendingReason = typeof host === "object" ? host.pending : "host_step_pending";
|
||||
if (!await runStep("defer", () => store.defer(agent, owner, null, new Date(), { pendingReason }))) continue;
|
||||
return;
|
||||
}
|
||||
if (!await runStep("complete_host", () => store.completeHost(agent, owner))) continue;
|
||||
@@ -65,7 +66,7 @@ export function createLifecycleWorker(store: LifecycleStore, driver: LifecycleDr
|
||||
}
|
||||
if (!await runStep("renew", () => store.renew(agent, owner, new Date()))) continue phase;
|
||||
if (await runStep("plugin", () => driver.runPlugin(agent, pluginId), pluginId) === "pending") {
|
||||
if (!await runStep("defer", () => store.defer(agent, owner, null, new Date()))) continue phase;
|
||||
if (!await runStep("defer", () => store.defer(agent, owner, null, new Date(), { pendingReason: "plugin_step_pending" }))) continue phase;
|
||||
return;
|
||||
}
|
||||
if (!await runStep("complete_plugin", () => store.completePlugin(agent, owner, pluginId), pluginId)) continue phase;
|
||||
|
||||
@@ -15,7 +15,7 @@ import { hasCompanyHoldMismatch, projectCompanyHolds } from "./adapters/company-
|
||||
import { createLifecycleWorker } from "./application/worker.js";
|
||||
import type { LifecycleDriver } from "./application/ports.js";
|
||||
|
||||
export { applyAgentPolicyHoldsInTransaction, releaseAgentLifecycleLeaseOfHolderInTransaction, requestAgentLifecycleRecheckInTransaction } from "./adapters/postgres.js";
|
||||
export { applyAgentPolicyHoldsInTransaction, releaseAgentLifecycleLeaseOfHolderInTransaction, requestAgentLifecycleRecheckInTransaction, wakeStoppingAgentLifecycleInTransaction } from "./adapters/postgres.js";
|
||||
export { companyHoldMismatch, fenceActiveCompanyAgentStopsInTransaction } from "./adapters/company-policy.js";
|
||||
|
||||
export { AgentLifecycleConflict, canConfigureAgentConnection, isAgentAwaitingSetup, isAgentSetupDraft } from "./domain/policy.js";
|
||||
|
||||
@@ -2892,7 +2892,9 @@ export function accessRoutes(
|
||||
res.json({
|
||||
user: accessSnapshot.user,
|
||||
userId: req.actor.userId,
|
||||
isInstanceAdmin: accessSnapshot.isInstanceAdmin,
|
||||
isInstanceAdmin: req.actor.source === "cloud_tenant"
|
||||
? req.actor.isInstanceAdmin === true
|
||||
: accessSnapshot.isInstanceAdmin,
|
||||
companyIds: accessSnapshot.companyIds,
|
||||
memberships: accessSnapshot.memberships,
|
||||
source: req.actor.source ?? "none",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { readProcessStartedAt } from "./hot-restart.js";
|
||||
import { readLeaseReleaseDeferral } from "./environment-lease-release-deferral.js";
|
||||
import { runUsedConversationAdapter } from "./conversation-continuation.js";
|
||||
import { and, eq, inArray, isNull, or, sql } from "drizzle-orm";
|
||||
import { environmentLeases, heartbeatRuns, nativeRunFinalizations, type Db } from "@paperclipai/db";
|
||||
@@ -8,20 +9,26 @@ import { isCancelledNativeStartup } from "./cancelled-native-startup.js";
|
||||
|
||||
/** Cancellation changes admission. Process and lease evidence controls cleanup. */
|
||||
export async function agentExecutionsHaveStopped(db: Db, agentIds: string[]) {
|
||||
if (!agentIds.length) return true;
|
||||
return (await agentExecutionStopBlocker(db, agentIds)) === null;
|
||||
}
|
||||
|
||||
export async function agentExecutionStopBlocker(db: Db, agentIds: string[]): Promise<string | null> {
|
||||
if (!agentIds.length) return null;
|
||||
const runs = await db.select().from(heartbeatRuns).where(inArray(heartbeatRuns.agentId, agentIds));
|
||||
const runIds = db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(inArray(heartbeatRuns.agentId, agentIds));
|
||||
const leases = await db.select().from(environmentLeases).where(or(
|
||||
inArray(environmentLeases.heartbeatRunId, runIds),
|
||||
inArray(sql`${environmentLeases.metadata}->>'agentId'`, agentIds),
|
||||
));
|
||||
if (leases.some(lease => (!lease.releasedAt && !(lease.status === "retained" && lease.cleanupStatus === "success")) || lease.status === "pending_cleanup" || lease.cleanupStatus === "failed")) return false;
|
||||
const deferred = leases.find(lease => lease.status === "active" && readLeaseReleaseDeferral(lease.metadata));
|
||||
if (deferred) return `environment_lease_release_deferred:${readLeaseReleaseDeferral(deferred.metadata)!.reason}`;
|
||||
if (leases.some(lease => (!lease.releasedAt && !(lease.status === "retained" && lease.cleanupStatus === "success")) || lease.status === "pending_cleanup" || lease.cleanupStatus === "failed")) return "environment_lease_unreleased";
|
||||
const coordinators = await db.select().from(nativeRunFinalizations)
|
||||
.where(inArray(nativeRunFinalizations.runId, runIds));
|
||||
const now = new Date();
|
||||
const abandoned = coordinators.filter(row => row.leaseOwner);
|
||||
if (abandoned.some(row => !row.leaseExpiresAt || row.leaseExpiresAt > now || row.resultId ||
|
||||
runs.find(run => run.id === row.runId)?.status !== "cancelled")) return false;
|
||||
runs.find(run => run.id === row.runId)?.status !== "cancelled")) return "native_finalization_owned";
|
||||
const absent = (pid: number) => {
|
||||
try { process.kill(pid, 0); return false; }
|
||||
catch (error) { return (error as NodeJS.ErrnoException).code === "ESRCH"; }
|
||||
@@ -30,14 +37,14 @@ export async function agentExecutionsHaveStopped(db: Db, agentIds: string[]) {
|
||||
if (!coordinator.controllerPid || absent(coordinator.controllerPid)) continue;
|
||||
const observed = await readProcessStartedAt(coordinator.controllerPid).catch(() => null);
|
||||
if (!observed || !coordinator.controllerProcessStartedAt ||
|
||||
new Date(observed).getTime() === coordinator.controllerProcessStartedAt.getTime()) return false;
|
||||
new Date(observed).getTime() === coordinator.controllerProcessStartedAt.getTime()) return "native_controller_alive";
|
||||
}
|
||||
for (const run of runs) {
|
||||
if (!["succeeded", "failed", "cancelled", "timed_out", "interrupted"].includes(run.status)) return false;
|
||||
if (run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date()) return false;
|
||||
if (!["succeeded", "failed", "cancelled", "timed_out", "interrupted"].includes(run.status)) return "run_not_terminal";
|
||||
if (run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date()) return "run_controller_lease_held";
|
||||
const runLeases = leases.filter(lease => lease.heartbeatRunId === run.id);
|
||||
if (runLeases.some(lease => lease.provider && lease.provider !== "local")) {
|
||||
if (run.status === "cancelled" && !runLeases.every(hasRemoteTerminationReceipt)) return false;
|
||||
if (run.status === "cancelled" && !runLeases.every(hasRemoteTerminationReceipt)) return "remote_stop_unconfirmed";
|
||||
continue;
|
||||
}
|
||||
let processAlive = Boolean(run.processPid && !absent(run.processPid));
|
||||
@@ -49,15 +56,15 @@ export async function agentExecutionsHaveStopped(db: Db, agentIds: string[]) {
|
||||
if (run.processGroupId === run.processPid) groupAlive = false;
|
||||
}
|
||||
}
|
||||
if (processAlive || groupAlive) return false;
|
||||
if (processAlive || groupAlive) return "run_process_alive";
|
||||
if (run.status !== "cancelled" || !run.startedAt) continue;
|
||||
if (run.runtimeMode === "native" && !run.processPid && !run.processGroupId &&
|
||||
!await hasNativeLocalProcessStop(db, run.companyId, run.id) &&
|
||||
!await isCancelledNativeStartup(db, run, coordinators.find(row => row.runId === run.id))) return false;
|
||||
!await isCancelledNativeStartup(db, run, coordinators.find(row => row.runId === run.id))) return "native_stop_unproven";
|
||||
if (run.runtimeMode === "legacy" && !run.processPid && !run.processGroupId &&
|
||||
(run.resultJson?.executionCancellation as Record<string, unknown> | undefined)?.state !== "acknowledged" &&
|
||||
!(run.executionStage === "settled" && !await runUsedConversationAdapter(db, run)) &&
|
||||
!await isCancelledNativeStartup(db, run, coordinators.find(row => row.runId === run.id))) return false;
|
||||
!await isCancelledNativeStartup(db, run, coordinators.find(row => row.runId === run.id))) return "legacy_stop_unproven";
|
||||
}
|
||||
// Release an expired owner only after its cancelled execution has stop proof.
|
||||
for (const coordinator of abandoned) {
|
||||
@@ -68,7 +75,7 @@ export async function agentExecutionsHaveStopped(db: Db, agentIds: string[]) {
|
||||
eq(nativeRunFinalizations.controllerGeneration, coordinator.controllerGeneration),
|
||||
eq(nativeRunFinalizations.phase, coordinator.phase), isNull(nativeRunFinalizations.resultId)))
|
||||
.returning({ runId: nativeRunFinalizations.runId });
|
||||
if (!cleared) return false;
|
||||
if (!cleared) return "native_finalization_release_raced";
|
||||
}
|
||||
return true;
|
||||
return null;
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { and, eq, inArray, or, sql } from "drizzle-orm";
|
||||
import { pendingFailedNativeRetryCancellationCondition } from "./native-runtime/native-cancellation-request.js";
|
||||
import { CANCELLABLE_HEARTBEAT_RUN_STATUSES } from "./heartbeat/recovery.js";
|
||||
import { promoteDeferredWorkIntents } from "./work-intent-outbox.js";
|
||||
import { agents, companies, environments, heartbeatRuns, plugins, pluginCompanySettings, type Db } from "@paperclipai/db";
|
||||
@@ -87,11 +88,13 @@ export function createLifecycleDriver(db: Db, manager: PluginWorkerManager): Lif
|
||||
await db.update(heartbeatRuns).set({
|
||||
resultJson: sql`coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) || ${pauseStop}`,
|
||||
}).where(and(eq(heartbeatRuns.companyId, agent.companyId), eq(heartbeatRuns.agentId, agent.id),
|
||||
inArray(heartbeatRuns.status, [...CANCELLABLE_HEARTBEAT_RUN_STATUSES]),
|
||||
or(inArray(heartbeatRuns.status, [...CANCELLABLE_HEARTBEAT_RUN_STATUSES]), pendingFailedNativeRetryCancellationCondition()),
|
||||
sql`not (coalesce(${heartbeatRuns.resultJson}, '{}'::jsonb) ? 'pauseStop')`));
|
||||
}
|
||||
if (!await heartbeat.stopInvocationsForAgents(ids, reason,
|
||||
{ preservePauseDeferred: agent.lifecycleState === "pausing" })) return "pending";
|
||||
const blocker = await heartbeat.agentInvocationStopBlocker(ids, reason,
|
||||
{ preservePauseDeferred: agent.lifecycleState === "pausing",
|
||||
...(agent.lifecycleOperation?.id ? { trigger: `lifecycle:${agent.lifecycleOperation.id}` } : {}) });
|
||||
if (blocker) return { pending: blocker };
|
||||
}
|
||||
return "complete";
|
||||
},
|
||||
|
||||
@@ -2,7 +2,8 @@ import { notifyExternalConversationSettlement } from "./external-conversation-se
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
|
||||
import type { InboundWakeNoticeScope } from "./chat-channels/inbound/wakeup-notices.js";
|
||||
|
||||
export async function notifyChatInboundWakeNotices(tx: object, scope: InboundWakeNoticeScope, options: { notifySettlement?: boolean } = {}) {
|
||||
export async function notifyChatInboundWakeNotices(tx: object, scope: InboundWakeNoticeScope & { runId?: string },
|
||||
options: { notifySettlement?: boolean } = {}) {
|
||||
if (options.notifySettlement !== false) await notifyExternalConversationSettlement(tx, scope);
|
||||
const hint = JSON.stringify({ companyId: scope.companyId, issueId: scope.issueId });
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.chatInboundWakeNotices, hint);
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
const boot = vi.hoisted(() => ({ id: "boot-a" }));
|
||||
vi.mock("./controller-process-identity.js", async importOriginal => ({
|
||||
...await importOriginal<typeof import("./controller-process-identity.js")>(),
|
||||
currentControllerBootId: () => boot.id,
|
||||
}));
|
||||
|
||||
import { leaseReleaseRetryDueAt, nextLeaseReleaseBootIds, nextLeaseReleaseRetryAt,
|
||||
type LeaseReleaseDeferral } from "./environment-lease-release-deferral.js";
|
||||
|
||||
describe("lease release retry across live server boots", () => {
|
||||
function fail(previous: LeaseReleaseDeferral | null, now: number): LeaseReleaseDeferral {
|
||||
const attempts = (previous?.attempts ?? 0) + 1;
|
||||
return { reason: "release_failed", attempts, retryAt: nextLeaseReleaseRetryAt(previous, attempts, now),
|
||||
failingSince: previous?.failingSince ?? new Date(now).toISOString(), attemptedByBootIds: nextLeaseReleaseBootIds(previous),
|
||||
providerResourceDisposition: null };
|
||||
}
|
||||
|
||||
function simulate(boots: string[]) {
|
||||
const start = Date.parse("2026-11-15T12:00:00Z");
|
||||
boot.id = boots[0]!;
|
||||
let deferral = fail(null, start);
|
||||
let attempts = 1;
|
||||
let latestRetryAt = Date.parse(deferral.retryAt);
|
||||
for (let minute = 1; minute <= 60; minute++) {
|
||||
const now = start + minute * 60_000;
|
||||
for (const id of [...boots].reverse()) {
|
||||
boot.id = id;
|
||||
if (leaseReleaseRetryDueAt(deferral, now) > now) continue;
|
||||
deferral = fail(deferral, now);
|
||||
attempts += 1;
|
||||
const retryAt = Date.parse(deferral.retryAt);
|
||||
expect(retryAt).toBeGreaterThanOrEqual(latestRetryAt);
|
||||
latestRetryAt = retryAt;
|
||||
}
|
||||
}
|
||||
return { deferral, attempts };
|
||||
}
|
||||
|
||||
it("keeps the saved retry time for every live boot after each has made its first attempt", () => {
|
||||
const single = simulate(["boot-a"]);
|
||||
const overlapping = simulate(["boot-a", "boot-b"]);
|
||||
expect(overlapping.deferral.attemptedByBootIds).toEqual(["boot-a", "boot-b"]);
|
||||
expect(overlapping.attempts).toBeLessThanOrEqual(single.attempts + 1);
|
||||
});
|
||||
|
||||
it("gives a restarted server one immediate attempt and keeps the boot list bounded", () => {
|
||||
const now = Date.parse("2026-11-15T12:00:00Z");
|
||||
let deferral: LeaseReleaseDeferral | null = null;
|
||||
for (let index = 0; index < 15; index++) {
|
||||
boot.id = `boot-${index}`;
|
||||
deferral = fail(deferral, now);
|
||||
}
|
||||
expect(deferral!.attemptedByBootIds).toHaveLength(10);
|
||||
boot.id = "boot-restarted";
|
||||
expect(leaseReleaseRetryDueAt(deferral!, now)).toBe(now);
|
||||
boot.id = "boot-14";
|
||||
expect(leaseReleaseRetryDueAt(deferral!, now)).toBe(Date.parse(deferral!.retryAt));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { environmentLeases, heartbeatRunEvents, heartbeatRuns, type Db } from "@paperclipai/db";
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
|
||||
import { currentControllerBootId } from "./controller-process-identity.js";
|
||||
import { wakeStoppingAgentLifecycleInTransaction } from "../modules/agent-lifecycle/index.js";
|
||||
import type { ProviderResourceDisposition } from "./environment-runtime.js";
|
||||
import { executionStartedEventPredicate } from "./pre-dispatch-execution-evidence.js";
|
||||
|
||||
export const LEASE_RELEASE_DEFERRAL_KEY = "releaseDeferral";
|
||||
const LEASE_RELEASE_RETRY_BASE_MS = 30_000;
|
||||
const LEASE_RELEASE_RETRY_MAX_MS = 15 * 60_000;
|
||||
export const LEASE_RELEASE_FAST_ATTEMPTS = 6;
|
||||
export const LEASE_RELEASE_SLOW_RETRY_MS = 60 * 60_000;
|
||||
|
||||
export type LeaseReleaseDeferral = {
|
||||
reason: string;
|
||||
attempts: number;
|
||||
retryAt: string;
|
||||
failingSince: string;
|
||||
triggers?: string[];
|
||||
attemptedByBootIds?: string[];
|
||||
providerResourceDisposition: ProviderResourceDisposition | null;
|
||||
};
|
||||
|
||||
const LEASE_RELEASE_TRIGGER_LIMIT = 20;
|
||||
|
||||
const LEASE_RELEASE_BOOT_LIMIT = 10;
|
||||
|
||||
export function leaseReleaseAttemptedByThisBoot(deferral: LeaseReleaseDeferral | null) {
|
||||
return Boolean(deferral?.attemptedByBootIds?.includes(currentControllerBootId()));
|
||||
}
|
||||
|
||||
export function leaseReleaseRetryDueAt(deferral: LeaseReleaseDeferral, now = Date.now()) {
|
||||
if (!leaseReleaseAttemptedByThisBoot(deferral)) return now;
|
||||
const retryAt = Date.parse(deferral.retryAt);
|
||||
return Number.isFinite(retryAt) ? retryAt : now;
|
||||
}
|
||||
|
||||
export function nextLeaseReleaseBootIds(previous: LeaseReleaseDeferral | null) {
|
||||
const current = currentControllerBootId();
|
||||
const bootIds = (previous?.attemptedByBootIds ?? []).filter(bootId => bootId !== current);
|
||||
return [...bootIds, current].slice(-LEASE_RELEASE_BOOT_LIMIT);
|
||||
}
|
||||
|
||||
export function nextLeaseReleaseRetryAt(previous: LeaseReleaseDeferral | null, attempts: number, now = Date.now()) {
|
||||
const scheduled = now + leaseReleaseRetryDelayMs(attempts);
|
||||
const saved = previous ? Date.parse(previous.retryAt) : Number.NaN;
|
||||
return new Date(Number.isFinite(saved) && saved > scheduled ? saved : scheduled).toISOString();
|
||||
}
|
||||
|
||||
export function nextLeaseReleaseTriggers(previous: LeaseReleaseDeferral | null, trigger: string | undefined) {
|
||||
const triggers = [...(previous?.triggers ?? [])];
|
||||
if (trigger && !triggers.includes(trigger)) triggers.push(trigger);
|
||||
return triggers.slice(-LEASE_RELEASE_TRIGGER_LIMIT);
|
||||
}
|
||||
|
||||
export function readLeaseReleaseDeferral(metadata: Record<string, unknown> | null | undefined): LeaseReleaseDeferral | null {
|
||||
const value = metadata?.[LEASE_RELEASE_DEFERRAL_KEY];
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||||
const deferral = value as Record<string, unknown>;
|
||||
if (typeof deferral.reason !== "string" || typeof deferral.retryAt !== "string" || typeof deferral.attempts !== "number") return null;
|
||||
return deferral as LeaseReleaseDeferral;
|
||||
}
|
||||
|
||||
export function leaseReleaseRetryDelayMs(attempts: number) {
|
||||
if (attempts > LEASE_RELEASE_FAST_ATTEMPTS) return LEASE_RELEASE_SLOW_RETRY_MS;
|
||||
return Math.min(LEASE_RELEASE_RETRY_MAX_MS, LEASE_RELEASE_RETRY_BASE_MS * 2 ** Math.max(0, attempts - 1));
|
||||
}
|
||||
|
||||
export function wakeStoppingAgentLifecycle(tx: Db, agentId: string) {
|
||||
return wakeStoppingAgentLifecycleInTransaction(tx, agentId, () => notifyDeliveryWork(tx, DELIVERY_QUEUES.agentLifecycle));
|
||||
}
|
||||
|
||||
export async function settleUnchangedNativeWorkspace(db: Db, runId: string, companyId: string): Promise<boolean> {
|
||||
const settled = await db.update(heartbeatRuns).set({
|
||||
runnerProfileJson: sql`(${heartbeatRuns.runnerProfileJson} - 'nativeWorkspaceSync')
|
||||
|| jsonb_build_object('nativeWorkspaceSyncReleasedUnchanged', ${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync')`,
|
||||
}).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.status, "cancelled"),
|
||||
sql`${heartbeatRuns.runnerProfileJson}->'nativeWorkspaceSync'->>'state' = 'prepared'`,
|
||||
sql`coalesce(${heartbeatRuns.runnerProfileJson}->'remoteWorkspace', 'null'::jsonb) = 'null'::jsonb`,
|
||||
sql`not exists (select 1 from ${environmentLeases} where ${environmentLeases.companyId} = ${companyId}
|
||||
and ${environmentLeases.heartbeatRunId} = ${runId} and (${environmentLeases.status} in ('active', 'pending_cleanup', 'retained')
|
||||
or coalesce(${environmentLeases.metadata}, '{}'::jsonb) ? 'sandboxStopAndRetainReceipt'))`))
|
||||
.returning({ id: heartbeatRuns.id });
|
||||
return settled.length > 0;
|
||||
}
|
||||
|
||||
export async function nativeRunNeverLaunchedRunner(db: Db, runId: string, companyId: string): Promise<boolean> {
|
||||
const [run] = await db.select({ processPid: heartbeatRuns.processPid, processGroupId: heartbeatRuns.processGroupId })
|
||||
.from(heartbeatRuns).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId)));
|
||||
if (!run || run.processPid || run.processGroupId) return false;
|
||||
const [started] = await db.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents).where(and(
|
||||
eq(heartbeatRunEvents.companyId, companyId), eq(heartbeatRunEvents.runId, runId), executionStartedEventPredicate(),
|
||||
)).limit(1);
|
||||
return !started;
|
||||
}
|
||||
@@ -1778,7 +1778,7 @@ export function environmentService(db: Db) {
|
||||
(options?.cleanupStatus !== undefined && previous.cleanupStatus !== options.cleanupStatus) ||
|
||||
(status !== "retained" && !previous.releasedAt))) {
|
||||
await notifyChatInboundWakeNotices(tx, {
|
||||
companyId: previous.companyId, issueId: previous.issueId ?? undefined,
|
||||
companyId: previous.companyId, issueId: previous.issueId ?? undefined, runId: previous.heartbeatRunId,
|
||||
});
|
||||
}
|
||||
if (previous.heartbeatRunId && ["active", "pending_cleanup"].includes(previous.status)
|
||||
@@ -1789,7 +1789,8 @@ export function environmentService(db: Db) {
|
||||
// Messages saved behind a finished run wait for its cleanup to
|
||||
// settle. Reconsider them through normal deferred admission.
|
||||
await notifyDeferredExecutionWork(tx, { companyId: previous.companyId });
|
||||
await promoteDeferredWorkIntents(tx, { companyId: previous.companyId, trigger: "lock_released", issueId: previous.issueId });
|
||||
await promoteDeferredWorkIntents(tx, { companyId: previous.companyId, trigger: "lock_released", issueId: previous.issueId,
|
||||
runId: previous.heartbeatRunId });
|
||||
}
|
||||
if (previous.creationOperationId && previous.status === "pending_cleanup" && options?.cleanupStatus === "success" && status !== "pending_cleanup") {
|
||||
await tx.update(sandboxCreationOperations).set({ state: "resolved", updatedAt: now })
|
||||
@@ -1932,7 +1933,7 @@ export function environmentService(db: Db) {
|
||||
await notifyRetainedNativeSessionCleanup(tx, { companyId: run.companyId, runId: heartbeatRunId });
|
||||
await notifyDeferredExecutionWork(tx, { companyId: run.companyId });
|
||||
await promoteDeferredWorkIntents(tx, { companyId: run.companyId, trigger: "lock_released",
|
||||
issueId: run.issueId && /^[0-9a-f-]{36}$/i.test(run.issueId) ? run.issueId : null });
|
||||
issueId: run.issueId && /^[0-9a-f-]{36}$/i.test(run.issueId) ? run.issueId : null, runId: heartbeatRunId });
|
||||
}
|
||||
return tx.update(environmentLeases)
|
||||
.set({
|
||||
|
||||
@@ -267,7 +267,7 @@ export async function reconcileAbandonedExecutionControl(
|
||||
await notifyNativeEnvironmentSettlement(tx, { companyId: run.companyId, runId: run.id });
|
||||
await notifyCancelledWorkspacePreservation(tx, { companyId: run.companyId, runId: run.id });
|
||||
await notifyUnsafeWorkspaceExportRunChange(tx, run);
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id });
|
||||
const [updatedRun] = await tx
|
||||
.update(heartbeatRuns)
|
||||
.set({
|
||||
|
||||
@@ -827,7 +827,7 @@ export async function settleUnrecoverableExecutions(
|
||||
companyId: run.companyId, issueId: task.id, runId: run.id,
|
||||
}).limit(1).for("update") : [];
|
||||
if (!hold) return void await continueNativeInterruption(tx as unknown as Db, { action, run, coordinator, now });
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id });
|
||||
const note = "Exact session recovery stopped. The recorded workspace recovery holds this execution without replaying its actions.";
|
||||
await tx.update(issueRecoveryActions).set({ status: "cancelled", outcome: "cancelled",
|
||||
resolvedAt: now, updatedAt: now, wakePolicy: null, monitorPolicy: null,
|
||||
@@ -962,7 +962,7 @@ export async function settleUnrecoverableExecutions(
|
||||
replay: "not_authorized",
|
||||
},
|
||||
});
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id });
|
||||
await tx
|
||||
.update(heartbeatRuns)
|
||||
.set({ executionStatusDeliveryId: randomUUID() })
|
||||
|
||||
@@ -51,6 +51,7 @@ import { getRunLogStore, isRunLogStoreType } from "./run-log-store.js";
|
||||
import { isObjectJournalBusyError } from "./object-byte-journal.js";
|
||||
import { recoverSettledNativeRunLog } from "./native-runtime/native-run-log-recovery.js";
|
||||
import { getOperatorSettingDefaults } from "./setting-defaults.js";
|
||||
import { announceInstanceSettingsChange } from "./instance-settings-cache.js";
|
||||
|
||||
const FEEDBACK_SCHEMA_VERSION = "paperclip-feedback-envelope-v2";
|
||||
const FEEDBACK_BUNDLE_VERSION = "paperclip-feedback-bundle-v2";
|
||||
@@ -2027,6 +2028,7 @@ export function feedbackService(db: Db, options: FeedbackServiceOptions = {}) {
|
||||
getOperatorSettingDefaults(),
|
||||
);
|
||||
if (currentInstanceSettings && currentGeneral.feedbackDataSharingPreference === "prompt") {
|
||||
await announceInstanceSettingsChange(tx);
|
||||
const nextSharingPreference = sharedWithLabs ? "allowed" : "not_allowed";
|
||||
const currentGeneralRaw = asRecord(currentInstanceSettings.general) ?? {};
|
||||
await tx
|
||||
|
||||
@@ -81,7 +81,7 @@ import {
|
||||
formatIssueIdentifierLink,
|
||||
} from "./heartbeat/scheduling.js";
|
||||
import { canApplyTaskWorkspaceSelectionAtAdmission, taskWorkspaceRuntimeSelectionEnabled } from "./execution-workspace-policy.js";
|
||||
import { agentExecutionsHaveStopped } from "./agent-execution-stop.js";
|
||||
import { agentExecutionStopBlocker } from "./agent-execution-stop.js";
|
||||
import {
|
||||
cancelHeartbeatNativeRun,
|
||||
terminateHeartbeatRunProcess,
|
||||
@@ -4444,31 +4444,45 @@ export function heartbeatService(
|
||||
}
|
||||
}
|
||||
|
||||
async function stopInvocationsForAgents(agentIds: string[], reason: string, options: StopInvocationOptions = {}) {
|
||||
async function agentInvocationStopBlocker(agentIds: string[], reason: string, options: StopInvocationOptions = {}) {
|
||||
await cancelInvocationsForAgentsInternal(agentIds, reason, options);
|
||||
const runs = await db.select().from(heartbeatRuns).where(inArray(heartbeatRuns.agentId, agentIds));
|
||||
const leasesToRelease = await db.select({ runId: environmentLeases.heartbeatRunId }).from(environmentLeases)
|
||||
.innerJoin(heartbeatRuns, eq(heartbeatRuns.id, environmentLeases.heartbeatRunId))
|
||||
.where(and(inArray(heartbeatRuns.agentId, agentIds),
|
||||
or(and(eq(heartbeatRuns.status, "cancelled"), inArray(environmentLeases.status, ["active", "pending_cleanup"])),
|
||||
and(eq(environmentLeases.status, "retained"), eq(environmentLeases.cleanupStatus, "failed")))));
|
||||
and(eq(environmentLeases.status, "retained"), eq(environmentLeases.cleanupStatus, "failed"))),
|
||||
sql`not (coalesce((${environmentLeases.metadata}->'releaseDeferral'->>'retryAt')::timestamptz > now(), false)
|
||||
and (${options.trigger ?? null}::text is null
|
||||
or coalesce(${environmentLeases.metadata}->'releaseDeferral'->'triggers', '[]'::jsonb) ? ${options.trigger ?? ""}::text))`));
|
||||
const needsRelease = new Set(leasesToRelease.map(lease => lease.runId));
|
||||
let blocker: string | null = null;
|
||||
for (const run of runs) {
|
||||
if (!isHeartbeatRunTerminalStatus(run.status) || liveRunExecutions.has(run.id) ||
|
||||
adapterExecutionControls.has(run.id) || processRunCancellationSettlements.has(run.id) ||
|
||||
(run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date())) return false;
|
||||
const runBlocker = !isHeartbeatRunTerminalStatus(run.status) ? "run_not_terminal"
|
||||
: liveRunExecutions.has(run.id) || adapterExecutionControls.has(run.id) || processRunCancellationSettlements.has(run.id)
|
||||
? "run_executing_here"
|
||||
: run.controllerLeaseExpiresAt && run.controllerLeaseExpiresAt > new Date() ? "run_controller_lease_held" : null;
|
||||
if (runBlocker) {
|
||||
blocker ??= runBlocker;
|
||||
continue;
|
||||
}
|
||||
if (needsRelease.has(run.id)) {
|
||||
// Retry incomplete cleanup after a run becomes terminal.
|
||||
await releaseEnvironmentLeasesForRun({ runId: run.id, companyId: run.companyId,
|
||||
agentId: run.agentId, status: run.status, providerResourceDisposition: "destroy" });
|
||||
agentId: run.agentId, status: run.status, providerResourceDisposition: "destroy",
|
||||
...(options.trigger ? { trigger: options.trigger } : {}) });
|
||||
}
|
||||
}
|
||||
return agentExecutionsHaveStopped(db, agentIds);
|
||||
return blocker ?? agentExecutionStopBlocker(db, agentIds);
|
||||
}
|
||||
|
||||
async function stopInvocationsForAgents(agentIds: string[], reason: string, options: StopInvocationOptions = {}) {
|
||||
return (await agentInvocationStopBlocker(agentIds, reason, options)) === null;
|
||||
}
|
||||
|
||||
return {
|
||||
recoverLegacyAccountingReceipt,
|
||||
stopInvocationsForAgents,
|
||||
agentInvocationStopBlocker,
|
||||
waitForRunExecutionDrain: async (
|
||||
runId: string,
|
||||
options: { timeoutMs?: number; intervalMs?: number } = {},
|
||||
|
||||
@@ -7,6 +7,12 @@ import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator
|
||||
import { DELIVERY_QUEUES, type DeliveryQueue } from "../delivery-work-notifications.js";
|
||||
import type { LiveResourceRecoveryScope, LiveRunRecoveryScope } from "../live-run-recovery-notifications.js";
|
||||
import { registerScopedDeadlineWork } from "../scoped-deadline-work.js";
|
||||
import { leaseReleaseRetryDueAt, readLeaseReleaseDeferral } from "../environment-lease-release-deferral.js";
|
||||
|
||||
function leaseDueAt(metadata: Record<string, unknown> | null) {
|
||||
const deferral = readLeaseReleaseDeferral(metadata);
|
||||
return deferral ? leaseReleaseRetryDueAt(deferral) : 0;
|
||||
}
|
||||
|
||||
const TERMINAL = ["succeeded", "failed", "cancelled", "timed_out", "interrupted"];
|
||||
const SETTLED_PENDING_BASE_DELAY_MS = 30_000;
|
||||
@@ -64,7 +70,8 @@ export function registerLiveRecoveryWork(db: Db, coordinator: ReturnType<typeof
|
||||
dueAt: kind === "orphanLease"
|
||||
// A run lease is judged by its holder proof, not by age. A run-less
|
||||
// (login/probe) lease keeps its idle backoff until its kind moves.
|
||||
? row.runId ? row.updatedAt.getTime() : row.updatedAt.getTime() + 5 * 60_000
|
||||
? row.runId ? Math.max(row.updatedAt.getTime(), leaseDueAt(row.metadata))
|
||||
: row.updatedAt.getTime() + 5 * 60_000
|
||||
: Date.parse(String((row.metadata?.legacyShutdownWorkspaceSettlement as Record<string, unknown>)?.deadlineAt)) || Date.now(),
|
||||
}));
|
||||
} else if (kind === "settled") {
|
||||
|
||||
@@ -10,7 +10,7 @@ import { refreshRunStartYieldIfStale } from "../run-start-handover.js";
|
||||
import { deliveredQueuedCommentIds } from "../queued-comment-delivery.js";
|
||||
import { hasAutomaticInteractionDeliveryHold, INTERACTION_DELIVERY_DENIED, recheckQueuedRunInteractions, withInteractionDeliveryOrigin } from "../agent-interaction-delivery.js";
|
||||
import { deferredWorkIntentWait } from "../work-intent-outbox.js";
|
||||
import { notifyIssueRecovery } from "../issue-recovery-notifications.js";
|
||||
import { notifyIssueGraphRecovery } from "../issue-recovery-notifications.js";
|
||||
import { createHeartbeatTimerPolicy } from "./timer-policy.js";
|
||||
import { QUEUED_RUN_AGING_MS, RECOVERY_WAKE_REASONS, createQueuedRunDispatcher, hasQueuedRunAged, queuedRunDispatchClass } from "./queued-run-dispatch-order.js";
|
||||
import { reserveAutomaticRunStart } from "../recovery/automatic-run-brake.js";
|
||||
@@ -587,7 +587,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
const receipts = await tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(owned).for("update");
|
||||
if (!receipts.length) return;
|
||||
// Register the recovery signal before the write it announces.
|
||||
await notifyIssueRecovery(tx, { companyId: run.companyId });
|
||||
await notifyIssueGraphRecovery(tx, { companyId: run.companyId, runId: run.id });
|
||||
await tx.update(agentWakeupRequests).set({
|
||||
idempotencyKey: null,
|
||||
payload: sql`coalesce(${agentWakeupRequests.payload}, '{}'::jsonb)
|
||||
@@ -5392,8 +5392,10 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
return mergedRun;
|
||||
}
|
||||
|
||||
const queuedRunId = randomUUID();
|
||||
const queueOutcome = await db.transaction(async (tx) => {
|
||||
await notifyRunDispatch(tx, { companyId: agent.companyId, issueId: readNonEmptyString(enrichedContextSnapshot.issueId) });
|
||||
await notifyRunDispatch(tx, { companyId: agent.companyId, issueId: readNonEmptyString(enrichedContextSnapshot.issueId),
|
||||
runId: readNonEmptyString(enrichedContextSnapshot.issueId) ? undefined : queuedRunId });
|
||||
await tx.execute(
|
||||
sql`select id from agents where id = ${agentId} and company_id = ${agent.companyId} for update`,
|
||||
);
|
||||
@@ -5463,6 +5465,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
const newRun = await tx
|
||||
.insert(heartbeatRuns)
|
||||
.values({
|
||||
id: queuedRunId,
|
||||
companyId: agent.companyId,
|
||||
agentId,
|
||||
scopeKind: readNonEmptyString(enrichedContextSnapshot.issueId) ? "issue" : "company",
|
||||
|
||||
@@ -2,6 +2,7 @@ import { settleOwnableKind } from "../recovery/ownership-invariant-report.js";
|
||||
import { isRunHandedOffForShutdown, markRunHandedOffForShutdown } from "./shutdown-handoff.js";
|
||||
import { ORPHANED_RUN_LEASE_FAILURE_REASON } from "../environment-run-lease-settlement.js";
|
||||
import { ENVIRONMENT_LEASE_CONTROLLER_KEY } from "../environment-lease-controller.js";
|
||||
import { leaseReleaseRetryDueAt, readLeaseReleaseDeferral } from "../environment-lease-release-deferral.js";
|
||||
import { readNativeStartupCleanup, readNativeStartupContext } from "../native-runtime/native-startup-cleanup.js";
|
||||
import { legacyWorkspaceRecoveryNotMigrated } from "../legacy-workspace-recovery-migration.js";
|
||||
import { pendingFailedNativeRetryCancellationCondition } from "../native-runtime/native-cancellation-request.js";
|
||||
@@ -1676,6 +1677,40 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
);
|
||||
}
|
||||
|
||||
async function retryTerminalRunLeaseRelease(lease: typeof environmentLeases.$inferSelect,
|
||||
localRuns: { has(runId: string): boolean }, onDeferredDeadline?: (at: number) => void): Promise<boolean> {
|
||||
if (!lease.heartbeatRunId || localRuns.has(lease.heartbeatRunId)) return false;
|
||||
const deferral = readLeaseReleaseDeferral(lease.metadata);
|
||||
const dueAt = deferral ? leaseReleaseRetryDueAt(deferral) : Number.NaN;
|
||||
if (deferral && dueAt > Date.now()) {
|
||||
onDeferredDeadline?.(dueAt);
|
||||
return false;
|
||||
}
|
||||
const [run] = await db.select({ id: heartbeatRuns.id, companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId,
|
||||
status: heartbeatRuns.status, error: heartbeatRuns.error, runtimeMode: heartbeatRuns.runtimeMode,
|
||||
controllerLeaseExpiresAt: heartbeatRuns.controllerLeaseExpiresAt })
|
||||
.from(heartbeatRuns).where(and(eq(heartbeatRuns.id, lease.heartbeatRunId), eq(heartbeatRuns.companyId, lease.companyId)));
|
||||
if (!run || !HEARTBEAT_RUN_TERMINAL_STATUSES.some(status => status === run.status)) return false;
|
||||
if (!deferral && !(run.runtimeMode === "native" && run.status === "cancelled")) return false;
|
||||
const [owner] = await db.select({ leaseOwner: nativeRunFinalizations.leaseOwner, leaseExpiresAt: nativeRunFinalizations.leaseExpiresAt })
|
||||
.from(nativeRunFinalizations).where(and(eq(nativeRunFinalizations.runId, run.id), eq(nativeRunFinalizations.companyId, run.companyId)));
|
||||
const heldUntil = Math.max(run.controllerLeaseExpiresAt?.getTime() ?? 0,
|
||||
owner?.leaseOwner ? owner.leaseExpiresAt?.getTime() ?? 0 : 0);
|
||||
if (heldUntil > Date.now()) {
|
||||
onDeferredDeadline?.(heldUntil);
|
||||
return false;
|
||||
}
|
||||
await releaseEnvironmentLeasesForRun({ runId: run.id, companyId: run.companyId, agentId: run.agentId,
|
||||
status: run.status, failureReason: run.error ?? undefined,
|
||||
providerResourceDisposition: deferral ? deferral.providerResourceDisposition ?? undefined : "destroy" });
|
||||
const [after] = await db.select({ status: environmentLeases.status, metadata: environmentLeases.metadata })
|
||||
.from(environmentLeases).where(eq(environmentLeases.id, lease.id));
|
||||
if (after?.status !== "active") return true;
|
||||
const next = readLeaseReleaseDeferral(after.metadata);
|
||||
if (next) onDeferredDeadline?.(Date.parse(next.retryAt));
|
||||
return false;
|
||||
}
|
||||
|
||||
// A run's active lease outlives a crash between the terminal run write and
|
||||
// the lease release, or a release that skipped the lease (for example when
|
||||
// its environment row is gone). No production query finds such a lease by
|
||||
@@ -1730,6 +1765,9 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
&& await nativeWorkspaceExportPendingForLease(db, lease)
|
||||
&& await preserveOrphanedNativeWorkspace(db, lease, { onDeferredDeadline: opts.onDeferredDeadline })) recovered += 1;
|
||||
}
|
||||
for (const { lease } of scoped) {
|
||||
if (await retryTerminalRunLeaseRelease(lease, localRuns, opts.onDeferredDeadline)) recovered += 1;
|
||||
}
|
||||
|
||||
const runIds = [...new Set(scoped.flatMap(({ lease }) => lease.heartbeatRunId ? [lease.heartbeatRunId] : []))];
|
||||
if (runIds.length > 0) {
|
||||
|
||||
@@ -30,6 +30,8 @@ import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js";
|
||||
import { acknowledgedNativeApiStopExecutionHasStopped } from "../acknowledged-native-stop.js";
|
||||
import { nativeSha256 } from "../native-runtime/canonical.js";
|
||||
import { callbacks, runControlPostgresSupport, setupRunControlDatabase } from "./__tests__/run-control-fixtures.js";
|
||||
import { LEASE_RELEASE_FAST_ATTEMPTS, LEASE_RELEASE_SLOW_RETRY_MS } from "../environment-lease-release-deferral.js";
|
||||
import { agentExecutionStopBlocker } from "../agent-execution-stop.js";
|
||||
|
||||
vi.mock("../live-events.js", () => ({ publishLiveEvent: vi.fn() }));
|
||||
vi.mock("../acknowledged-native-stop.js", async (importOriginal) => {
|
||||
@@ -125,7 +127,7 @@ describe("heartbeat run-control module boundary", () => {
|
||||
expect(database.access).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("defers destruction when a warm session remains busy", async () => {
|
||||
it("defers destruction and records a retry when a warm session remains busy", async () => {
|
||||
const database = guardedDatabase();
|
||||
const deps = callbacks(database.db);
|
||||
deps.getRunCleanupState.mockResolvedValue({ status: "failed", runtimeMode: "legacy" } as Run);
|
||||
@@ -133,7 +135,7 @@ describe("heartbeat run-control module boundary", () => {
|
||||
await createHeartbeatRunControl(database.db, deps).releaseEnvironmentLeasesForRun({ runId: "busy", companyId: "company", agentId: "agent", status: "failed", providerResourceDisposition: "destroy" });
|
||||
expect(deps.options.closeWarmNativeSessionsForRun).toHaveBeenCalledWith({ runId: "busy", reason: "terminal heartbeat run destroyed its environment lease" });
|
||||
expect(deps.envOrchestrator.releaseForRun).not.toHaveBeenCalled();
|
||||
expect(database.access).not.toHaveBeenCalled();
|
||||
expect(database.access).toHaveBeenCalledWith(expect.anything(), "select", expect.anything());
|
||||
});
|
||||
});
|
||||
|
||||
@@ -869,6 +871,8 @@ describe.skipIf(!runControlPostgresSupport.supported)("heartbeat run-control dat
|
||||
await db.insert(environmentLeases).values({ id: leaseId, companyId: company.id, heartbeatRunId: runId,
|
||||
issueId: issue.id, provider: "daytona", providerLeaseId, status: "active", leasePolicy,
|
||||
metadata: { driver: "sandbox", pluginId: randomUUID(), sandboxProviderPlugin: true, remoteCwd: "/work" } });
|
||||
await db.insert(heartbeatRunEvents).values({ companyId: company.id, runId, agentId: agent.id, seq: 1,
|
||||
eventType: "native.process_start_requested", stream: "system", level: "info", message: "Runner launch requested" });
|
||||
const deps = callbacks(db), control = createHeartbeatRunControl(db, deps);
|
||||
let ready!: () => void, release!: () => void;
|
||||
const acquired = new Promise<void>(resolve => { ready = resolve; });
|
||||
@@ -883,7 +887,8 @@ describe.skipIf(!runControlPostgresSupport.supported)("heartbeat run-control dat
|
||||
status: "cancelled", providerResourceDisposition: "stop_and_retain" });
|
||||
expect(deps.envOrchestrator.releaseForRun).not.toHaveBeenCalled();
|
||||
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0])
|
||||
.toMatchObject({ status: "active", leasePolicy });
|
||||
.toMatchObject({ status: "active", leasePolicy, metadata: expect.objectContaining({ releaseDeferral: expect.objectContaining({
|
||||
reason: "workspace_retention_busy", attempts: 1, providerResourceDisposition: "stop_and_retain" }) }) });
|
||||
} finally { release(); await holding; }
|
||||
await preserveCancelledNativeWorkspaces(db);
|
||||
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0])
|
||||
@@ -898,6 +903,109 @@ describe.skipIf(!runControlPostgresSupport.supported)("heartbeat run-control dat
|
||||
expect((await db.select().from(issues).where(eq(issues.id, issue.id)))[0].status).toBe("in_progress");
|
||||
}, 15_000);
|
||||
|
||||
async function deferralFixture(runtimeMode: "legacy" | "native") {
|
||||
const { company, agent } = await fixture();
|
||||
const runId = randomUUID(), leaseId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: company.id, agentId: agent.id, runtimeMode,
|
||||
status: "cancelled", finishedAt: new Date() });
|
||||
await db.insert(environmentLeases).values({ id: leaseId, companyId: company.id, heartbeatRunId: runId,
|
||||
provider: "daytona", providerLeaseId: randomUUID(), status: "active", leasePolicy: "ephemeral",
|
||||
metadata: { driver: "sandbox", pluginId: randomUUID(), sandboxProviderPlugin: true } });
|
||||
if (runtimeMode === "native") await db.insert(heartbeatRunEvents).values({ companyId: company.id, runId, agentId: agent.id,
|
||||
seq: 1, eventType: "native.process_start_requested", stream: "system", level: "info", message: "Runner launch requested" });
|
||||
const deferral = async () => (await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0]!
|
||||
.metadata?.releaseDeferral as { reason: string; attempts: number; retryAt: string; providerResourceDisposition: string | null };
|
||||
return { company, agent, runId, deferral };
|
||||
}
|
||||
|
||||
it("records a failed release with its disposition and a growing retry time", async () => {
|
||||
const { company, agent, runId, deferral } = await deferralFixture("legacy");
|
||||
const deps = callbacks(db);
|
||||
vi.mocked(deps.envOrchestrator.releaseForRun).mockResolvedValue({ released: [], errors: [{ leaseId: "*", error: new Error("provider down") }] });
|
||||
const control = createHeartbeatRunControl(db, deps);
|
||||
const before = Date.now();
|
||||
await control.releaseEnvironmentLeasesForRun({ runId, companyId: company.id, agentId: agent.id, status: "cancelled" });
|
||||
const first = await deferral();
|
||||
expect(first).toMatchObject({ reason: "release_failed", attempts: 1, providerResourceDisposition: null });
|
||||
expect(Date.parse(first.retryAt) - before).toBeGreaterThanOrEqual(30_000);
|
||||
expect(Date.parse(first.retryAt) - before).toBeLessThan(40_000);
|
||||
await control.releaseEnvironmentLeasesForRun({ runId, companyId: company.id, agentId: agent.id, status: "cancelled" });
|
||||
const second = await deferral();
|
||||
expect(second).toMatchObject({ reason: "release_failed", attempts: 2 });
|
||||
expect(Date.parse(second.retryAt) - before).toBeGreaterThanOrEqual(60_000);
|
||||
});
|
||||
|
||||
it("never gives up on a failing release: hourly retries after the fast backoff, then release and wake the stopping agent", async () => {
|
||||
const { company, agent, runId, deferral } = await deferralFixture("legacy");
|
||||
const leaseId = (await db.select().from(environmentLeases).where(eq(environmentLeases.heartbeatRunId, runId)))[0]!.id;
|
||||
await db.update(agents).set({ lifecycleState: "terminating", lifecycleOperation: { id: randomUUID(), hostComplete: false,
|
||||
completedPluginIds: [], attempts: 3, retryAt: new Date(Date.now() + 60_000).toISOString() } }).where(eq(agents.id, agent.id));
|
||||
const deps = callbacks(db);
|
||||
let outageCalls = 0;
|
||||
vi.mocked(deps.envOrchestrator.releaseForRun).mockImplementation(async () => {
|
||||
outageCalls += 1;
|
||||
return { released: [], errors: [{ leaseId: "*", error: new Error("provider down") }] };
|
||||
});
|
||||
const control = createHeartbeatRunControl(db, deps);
|
||||
const fastSteps = LEASE_RELEASE_FAST_ATTEMPTS;
|
||||
const dueRetriesInThreeHours = fastSteps + 3;
|
||||
let firstFailure: string | undefined;
|
||||
for (let attempt = 1; attempt <= dueRetriesInThreeHours; attempt++) {
|
||||
const before = Date.now();
|
||||
await control.releaseEnvironmentLeasesForRun({ runId, companyId: company.id, agentId: agent.id, status: "cancelled" });
|
||||
const current = await deferral() as Record<string, unknown> & { retryAt: string };
|
||||
firstFailure ??= current.failingSince as string;
|
||||
expect(current).toMatchObject({ reason: "release_failed", attempts: attempt, failingSince: firstFailure });
|
||||
const delay = Date.parse(current.retryAt) - before;
|
||||
if (attempt > fastSteps) expect(delay).toBeGreaterThanOrEqual(LEASE_RELEASE_SLOW_RETRY_MS - 1_000);
|
||||
else expect(delay).toBeLessThanOrEqual(15 * 60_000 + 1_000);
|
||||
}
|
||||
expect(outageCalls).toBe(dueRetriesInThreeHours);
|
||||
expect(await agentExecutionStopBlocker(db, [agent.id])).toBe("environment_lease_release_deferred:release_failed");
|
||||
vi.mocked(deps.envOrchestrator.releaseForRun).mockImplementation(async () => {
|
||||
await db.update(environmentLeases).set({ status: "expired", releasedAt: new Date(), cleanupStatus: "success" })
|
||||
.where(eq(environmentLeases.id, leaseId));
|
||||
return { released: [{} as never], errors: [] };
|
||||
});
|
||||
await control.releaseEnvironmentLeasesForRun({ runId, companyId: company.id, agentId: agent.id, status: "cancelled" });
|
||||
expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, leaseId)))[0]!.status).toBe("expired");
|
||||
expect((await db.select().from(agents).where(eq(agents.id, agent.id)))[0]!.lifecycleOperation).not.toHaveProperty("retryAt");
|
||||
});
|
||||
|
||||
it("records a destroy held back by a busy warm session", async () => {
|
||||
const { company, agent, runId, deferral } = await deferralFixture("native");
|
||||
const deps = callbacks(db);
|
||||
deps.options.closeWarmNativeSessionsForRun.mockResolvedValue({ closed: 0, busy: 1, failed: 0 });
|
||||
await createHeartbeatRunControl(db, deps).releaseEnvironmentLeasesForRun({ runId, companyId: company.id,
|
||||
agentId: agent.id, status: "cancelled", providerResourceDisposition: "destroy" });
|
||||
expect(deps.envOrchestrator.releaseForRun).not.toHaveBeenCalled();
|
||||
expect(await deferral()).toMatchObject({ reason: "warm_session_busy", attempts: 1, providerResourceDisposition: "destroy" });
|
||||
});
|
||||
|
||||
it("stops and retains a launched cancelled run's sandbox when no file retention is owed", async () => {
|
||||
const { company, agent } = await fixture();
|
||||
const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Stopped task",
|
||||
status: "in_progress", assigneeAgentId: agent.id }).returning();
|
||||
const runId = randomUUID(), leaseId = randomUUID(), providerLeaseId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId: company.id, agentId: agent.id,
|
||||
issueId: issue.id, nativeIssueId: issue.id, runtimeMode: "native", status: "cancelled", finishedAt: new Date(),
|
||||
runnerProfileJson: { nativeWorkspaceSync: { schema: "paperclip.native-workspace-sync/v3", state: "prepared",
|
||||
descriptorSha256: "a".repeat(64), baselineSha256: "b".repeat(64), finalHostSha256: null,
|
||||
workspaceId: randomUUID(), leaseId, providerLeaseId, remoteCwd: "/work", resourceDisposition: "destroy" } } });
|
||||
await db.insert(nativeRunFinalizations).values({ runId, companyId: company.id, issueId: issue.id,
|
||||
phase: "terminal_failure", failureCode: "native_retry_cancelled" });
|
||||
await db.insert(environmentLeases).values({ id: leaseId, companyId: company.id, heartbeatRunId: runId,
|
||||
issueId: null, provider: "daytona", providerLeaseId, status: "active", leasePolicy: "ephemeral",
|
||||
metadata: { driver: "sandbox", pluginId: randomUUID(), sandboxProviderPlugin: true, remoteCwd: "/work" } });
|
||||
await db.insert(heartbeatRunEvents).values({ companyId: company.id, runId, agentId: agent.id, seq: 1,
|
||||
eventType: "native.process_start_requested", stream: "system", level: "info", message: "Runner launch requested" });
|
||||
const deps = callbacks(db);
|
||||
await createHeartbeatRunControl(db, deps).releaseEnvironmentLeasesForRun({ runId, companyId: company.id,
|
||||
agentId: agent.id, status: "cancelled", providerResourceDisposition: "destroy" });
|
||||
expect(deps.envOrchestrator.releaseForRun).toHaveBeenCalledWith(expect.objectContaining({
|
||||
heartbeatRunId: runId, providerResourceDisposition: "stop_and_retain" }));
|
||||
});
|
||||
|
||||
it("reports a missing run without entering cancellation", async () => {
|
||||
const deps = callbacks(db);
|
||||
await expect(createHeartbeatRunControl(db, deps).cancelRunInternal(randomUUID())).rejects.toThrow("Heartbeat run not found");
|
||||
|
||||
@@ -7,6 +7,10 @@ import { notifyChatInboundWakeNotices } from "../chat-inbound-wake-notice-notifi
|
||||
import { resumeDeferredChatWake } from "../durable-chat-wakeup.js";
|
||||
import { notifyEnvironmentCleanup } from "../environment-cleanup-notifications.js";
|
||||
import { readNativeStopExecutionEvidence } from "./native-stop-evidence-read.js";
|
||||
import { LEASE_RELEASE_DEFERRAL_KEY, nativeRunNeverLaunchedRunner, readLeaseReleaseDeferral,
|
||||
settleUnchangedNativeWorkspace, wakeStoppingAgentLifecycle, nextLeaseReleaseTriggers, nextLeaseReleaseBootIds, nextLeaseReleaseRetryAt,
|
||||
type LeaseReleaseDeferral } from "../environment-lease-release-deferral.js";
|
||||
import { pendingFailedNativeRetryCancellationCondition } from "../native-runtime/native-cancellation-request.js";
|
||||
import { readTaskRetryIntent, reconcileTaskChatRetryReceipts } from "../task-retry.js";
|
||||
import { PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED, readNativeLocalProcessStop, recordedLocalExecutionStopped } from "../native-local-process-stop.js";
|
||||
import { isHeartbeatRunTerminalStatus } from "./run-lifecycle.js";
|
||||
@@ -20,8 +24,9 @@ import {
|
||||
type WakeupOptions,
|
||||
} from "./run-preparation.js";
|
||||
import { preserveWorkspaceRestoreRecoveryMetadataSql } from "../legacy-workspace-restore-recovery.js";
|
||||
import { hasRequiredWorkspaceRecovery, nativeRunHasNoWorkspaceAccess } from "../workspace-restore-recovery-state.js";
|
||||
import { nativeRunHasNoWorkspaceAccess } from "../workspace-restore-recovery-state.js";
|
||||
import { preserveNativeFailedWorkspace } from "../native-runtime/native-failed-workspace-recovery.js";
|
||||
import { NativeWorkspaceFinalizationBusyError } from "../native-runtime/native-workspace-finalization-ownership.js";
|
||||
import { readNativeWorkspaceSyncReference } from "../native-runtime/native-workspace-sync.js";
|
||||
import { isAiAuthenticationBlocked } from "../ai-auth-failure.js";
|
||||
import {
|
||||
@@ -182,7 +187,7 @@ async function withBudgetStopDelivery<T>(db: Db, work: () => Promise<T>): Promis
|
||||
|
||||
/** `preservePauseDeferred`: the stop comes from a pause, which keeps the
|
||||
* messages it deferred for delivery once the pause lifts. */
|
||||
export type StopInvocationOptions = { preservePauseDeferred?: boolean };
|
||||
export type StopInvocationOptions = { preservePauseDeferred?: boolean; trigger?: string };
|
||||
|
||||
/** Cancellation shares executor ownership and delegates lifecycle and admission effects. */
|
||||
|
||||
@@ -382,6 +387,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont
|
||||
failureReason?: string | null;
|
||||
providerResourceDisposition?: ProviderResourceDisposition;
|
||||
respectCleanupDeadlines?: boolean;
|
||||
trigger?: string;
|
||||
nativeLifecycleTelemetry?: {
|
||||
provider: string;
|
||||
harness: string;
|
||||
@@ -402,21 +408,34 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont
|
||||
input.providerResourceDisposition,
|
||||
status,
|
||||
);
|
||||
let neverLaunched: boolean | undefined;
|
||||
const runnerNeverLaunched = async () => neverLaunched ??= leaseOwnerRun?.runtimeMode === "native"
|
||||
&& isHeartbeatRunTerminalStatus(status) && await nativeRunNeverLaunchedRunner(db, input.runId, input.companyId);
|
||||
const defer = (reason: string) => deferEnvironmentLeaseRelease(input, reason, providerResourceDisposition);
|
||||
if (cancelledRun?.runtimeMode === "native" && status === "cancelled"
|
||||
&& readNativeWorkspaceSyncReference(cancelledRun.runnerProfileJson?.nativeWorkspaceSync)?.state === "prepared"
|
||||
&& !nativeRunHasNoWorkspaceAccess(cancelledRun)) {
|
||||
try {
|
||||
const preserved = await preserveNativeFailedWorkspace(db, cancelledRun, { allowPreterminal: true });
|
||||
if (!preserved || !hasRequiredWorkspaceRecovery(preserved.resultJson)) return;
|
||||
} catch {
|
||||
&& !nativeRunHasNoWorkspaceAccess(cancelledRun) && !await runnerNeverLaunched()) {
|
||||
let deferral: string | null = null;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
try {
|
||||
await preserveNativeFailedWorkspace(db, cancelledRun, { allowPreterminal: true });
|
||||
deferral = null;
|
||||
break;
|
||||
} catch (error) {
|
||||
const busy = error instanceof NativeWorkspaceFinalizationBusyError;
|
||||
deferral = busy ? "workspace_owner_active" : "workspace_retention_busy";
|
||||
if (!busy || attempt > 0 || !await clearExpiredNativeFinalizationOwner(input.runId, input.companyId)) break;
|
||||
}
|
||||
}
|
||||
if (deferral) {
|
||||
// Keep the active source eligible for the bounded retention sweep.
|
||||
// Teardown must not release it after retention lost a lock or DB write.
|
||||
logger.warn({ runId: input.runId }, "Deferred cancelled workspace teardown until file retention is recorded");
|
||||
return;
|
||||
return await defer(deferral);
|
||||
}
|
||||
providerResourceDisposition = "stop_and_retain";
|
||||
}
|
||||
if (providerResourceDisposition === "destroy") {
|
||||
if (providerResourceDisposition === "destroy" && !await runnerNeverLaunched()) {
|
||||
const closeResult = await (
|
||||
options.closeWarmNativeSessionsForRun ??
|
||||
(async ({ runId, reason }) => {
|
||||
@@ -476,7 +495,7 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont
|
||||
{ runId: input.runId, warmNativeSessions: closeResult },
|
||||
"deferred environment lease destruction until warm native sessions close",
|
||||
);
|
||||
return;
|
||||
return await defer(closeResult.busy > 0 ? "warm_session_busy" : "warm_session_close_failed");
|
||||
}
|
||||
}
|
||||
const releaseResult = await envOrchestrator
|
||||
@@ -507,9 +526,71 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont
|
||||
"failed to release environment lease for heartbeat run",
|
||||
);
|
||||
}
|
||||
if (isHeartbeatRunTerminalStatus(status) && (!releaseResult || releaseResult.errors.length > 0)) await defer("release_failed");
|
||||
else if (isHeartbeatRunTerminalStatus(status) && leaseOwnerRun?.runtimeMode === "native") await defer("release_skipped");
|
||||
if (cancelledRun && neverLaunched
|
||||
&& readNativeWorkspaceSyncReference(cancelledRun.runnerProfileJson?.nativeWorkspaceSync)?.state === "prepared") {
|
||||
await settleUnchangedNativeWorkspace(db, input.runId, input.companyId).catch(() => {
|
||||
logger.warn({ runId: input.runId }, "could not record that a stopped run left no files to recover");
|
||||
});
|
||||
}
|
||||
if (isHeartbeatRunTerminalStatus(status) && releaseResult?.released.length) await wakeAgentAfterRunLeasesSettled(input).catch(() => {
|
||||
logger.warn({ runId: input.runId }, "could not wake the agent's stop after its run leases settled");
|
||||
});
|
||||
await acknowledgeRemoteStop(input.runId, input.companyId);
|
||||
}
|
||||
|
||||
async function wakeAgentAfterRunLeasesSettled(input: { runId: string; companyId: string; agentId: string }) {
|
||||
const [unsettled] = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and(
|
||||
eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.heartbeatRunId, input.runId),
|
||||
inArray(environmentLeases.status, ["active", "pending_cleanup"]))).limit(1);
|
||||
if (!unsettled) await db.transaction(tx => wakeStoppingAgentLifecycle(tx as unknown as Db, input.agentId));
|
||||
}
|
||||
|
||||
async function clearExpiredNativeFinalizationOwner(runId: string, companyId: string) {
|
||||
const cleared = await db.update(nativeRunFinalizations).set({ leaseOwner: null, leaseExpiresAt: null, updatedAt: new Date() })
|
||||
.where(and(eq(nativeRunFinalizations.runId, runId), eq(nativeRunFinalizations.companyId, companyId),
|
||||
isNotNull(nativeRunFinalizations.leaseOwner), lte(nativeRunFinalizations.leaseExpiresAt, new Date()),
|
||||
isNull(nativeRunFinalizations.resultId),
|
||||
sql`exists (select 1 from ${heartbeatRuns} where ${heartbeatRuns.id} = ${runId}
|
||||
and ${heartbeatRuns.companyId} = ${companyId} and ${heartbeatRuns.status} = 'cancelled')`))
|
||||
.returning({ runId: nativeRunFinalizations.runId });
|
||||
return cleared.length > 0;
|
||||
}
|
||||
|
||||
async function deferEnvironmentLeaseRelease(input: { runId: string; companyId: string; trigger?: string }, reason: string,
|
||||
providerResourceDisposition: ProviderResourceDisposition | undefined) {
|
||||
const leases = await Promise.resolve().then(() => db.select({ id: environmentLeases.id, metadata: environmentLeases.metadata })
|
||||
.from(environmentLeases).where(and(eq(environmentLeases.companyId, input.companyId),
|
||||
eq(environmentLeases.heartbeatRunId, input.runId), eq(environmentLeases.status, "active"))))
|
||||
.catch(() => {
|
||||
logger.warn({ runId: input.runId, reason }, "could not record a deferred environment lease release");
|
||||
return [];
|
||||
});
|
||||
for (const lease of leases) {
|
||||
const previous = readLeaseReleaseDeferral(lease.metadata);
|
||||
const attempts = (previous?.attempts ?? 0) + 1;
|
||||
const deferral: LeaseReleaseDeferral = { reason, attempts,
|
||||
retryAt: nextLeaseReleaseRetryAt(previous, attempts),
|
||||
failingSince: previous?.failingSince ?? new Date().toISOString(),
|
||||
triggers: nextLeaseReleaseTriggers(previous, input.trigger), attemptedByBootIds: nextLeaseReleaseBootIds(previous),
|
||||
providerResourceDisposition: providerResourceDisposition ?? null };
|
||||
const recorded = await db.transaction(async tx => {
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.orphanActiveLeases,
|
||||
JSON.stringify({ companyId: input.companyId, runId: input.runId, leaseId: lease.id }));
|
||||
await tx.update(environmentLeases).set({ metadata: sql`coalesce(${environmentLeases.metadata}, '{}'::jsonb)
|
||||
|| ${JSON.stringify({ [LEASE_RELEASE_DEFERRAL_KEY]: deferral })}::jsonb` })
|
||||
.where(and(eq(environmentLeases.id, lease.id), eq(environmentLeases.status, "active")));
|
||||
}).then(() => true, () => false);
|
||||
if (!recorded) {
|
||||
logger.warn({ runId: input.runId, leaseId: lease.id, reason }, "could not record a deferred environment lease release");
|
||||
continue;
|
||||
}
|
||||
logger.warn({ runId: input.runId, leaseId: lease.id, reason, attempts, retryAt: deferral.retryAt,
|
||||
failingSince: deferral.failingSince }, "deferred environment lease release; a background pass retries it");
|
||||
}
|
||||
}
|
||||
|
||||
async function acknowledgeRemoteStop(runId: string, companyId: string) {
|
||||
// The provider receipt arrives after adapter settlement. A remote ACP child
|
||||
// has no host PID, so only this target-aware boundary can acknowledge Stop.
|
||||
@@ -1728,12 +1809,13 @@ export function createHeartbeatRunControl(db: Db, dependencies: HeartbeatRunCont
|
||||
errorCode = "cancelled",
|
||||
) {
|
||||
const runs = await db
|
||||
.select()
|
||||
.select({ id: heartbeatRuns.id })
|
||||
.from(heartbeatRuns)
|
||||
.where(
|
||||
and(
|
||||
eq(heartbeatRuns.agentId, agentId),
|
||||
inArray(heartbeatRuns.status, [...CANCELLABLE_HEARTBEAT_RUN_STATUSES]),
|
||||
or(inArray(heartbeatRuns.status, [...CANCELLABLE_HEARTBEAT_RUN_STATUSES]),
|
||||
pendingFailedNativeRetryCancellationCondition()),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { is } from "drizzle-orm";
|
||||
import { PgTransaction } from "drizzle-orm/pg-core";
|
||||
import { publishDatabaseWorkHint, publishDatabaseWorkSettled, subscribeDatabaseWork } from "@paperclipai/db/work-signals";
|
||||
|
||||
export const INSTANCE_SETTINGS_CACHE_TTL_MS = 2_000;
|
||||
export const INSTANCE_SETTINGS_CHANGED_TOPIC = "instance-settings-changed";
|
||||
|
||||
type Entry = { generation: number; at: number; value?: unknown; pending?: Promise<unknown> };
|
||||
|
||||
let generation = 0;
|
||||
const entries = new WeakMap<object, Entry>();
|
||||
const subscribed = new WeakSet<object>();
|
||||
|
||||
export function invalidateInstanceSettingsCache() {
|
||||
generation += 1;
|
||||
}
|
||||
|
||||
export async function announceInstanceSettingsChange(connection: object) {
|
||||
invalidateInstanceSettingsCache();
|
||||
publishDatabaseWorkSettled(connection, INSTANCE_SETTINGS_CHANGED_TOPIC);
|
||||
if (!is(connection, PgTransaction)) {
|
||||
await publishDatabaseWorkHint(connection, INSTANCE_SETTINGS_CHANGED_TOPIC).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
|
||||
function subscribeToChanges(db: object) {
|
||||
if (subscribed.has(db)) return;
|
||||
subscribed.add(db);
|
||||
try {
|
||||
subscribeDatabaseWork(db, INSTANCE_SETTINGS_CHANGED_TOPIC, invalidateInstanceSettingsCache);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
export async function readThroughInstanceSettings<T>(db: object, load: () => Promise<T>): Promise<T> {
|
||||
if (is(db, PgTransaction)) return load();
|
||||
subscribeToChanges(db);
|
||||
const current = entries.get(db);
|
||||
if (current && current.generation === generation) {
|
||||
if ("value" in current && Date.now() - current.at < INSTANCE_SETTINGS_CACHE_TTL_MS) {
|
||||
return structuredClone(current.value as T);
|
||||
}
|
||||
if (current.pending) return structuredClone(await (current.pending as Promise<T>));
|
||||
}
|
||||
const startedAt = Date.now();
|
||||
const startedGeneration = generation;
|
||||
const entry: Entry = { generation: startedGeneration, at: startedAt };
|
||||
const pending = load();
|
||||
entry.pending = pending;
|
||||
entries.set(db, entry);
|
||||
try {
|
||||
const value = await pending;
|
||||
if (entries.get(db) === entry) {
|
||||
if (generation === startedGeneration) entries.set(db, { generation: startedGeneration, at: startedAt, value });
|
||||
else entries.delete(db);
|
||||
}
|
||||
return structuredClone(value);
|
||||
} catch (error) {
|
||||
if (entries.get(db) === entry) entries.delete(db);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,7 @@ import { getManagedInstanceConfig, type ManagedInstanceConfig } from "./managed-
|
||||
import { getOperatorSettingDefaults } from "./setting-defaults.js";
|
||||
import { isCloudStagingExperimentalSetting, isCloudStagingInstance } from "./cloud-instance.js";
|
||||
import { forbidden } from "../errors.js";
|
||||
import { announceInstanceSettingsChange, readThroughInstanceSettings } from "./instance-settings-cache.js";
|
||||
|
||||
const DEFAULT_SINGLETON_KEY = "default";
|
||||
const instanceGeneralSettingsStorageSchema = instanceGeneralSettingsSchema.strip();
|
||||
@@ -552,8 +553,12 @@ export function instanceSettingsService(db: Db, options: InstanceSettingsService
|
||||
throw new Error("Failed to initialize instance settings row");
|
||||
}
|
||||
|
||||
function getCachedRow(runner: InstanceSettingsWriteDb = db) {
|
||||
return readThroughInstanceSettings(runner, () => getOrCreateRow(runner));
|
||||
}
|
||||
|
||||
return {
|
||||
get: async (): Promise<InstanceSettings> => toInstanceSettings(await getOrCreateRow()),
|
||||
get: async (): Promise<InstanceSettings> => toInstanceSettings(await getCachedRow()),
|
||||
|
||||
update: async (
|
||||
patch: PatchInstanceSettings,
|
||||
@@ -576,13 +581,14 @@ export function instanceSettingsService(db: Db, options: InstanceSettingsService
|
||||
})
|
||||
.where(eq(instanceSettings.id, current.id))
|
||||
.returning();
|
||||
await announceInstanceSettingsChange(runner);
|
||||
return toInstanceSettings(updated ?? current);
|
||||
},
|
||||
|
||||
getGeneral: async (
|
||||
readOptions?: { db?: InstanceSettingsWriteDb },
|
||||
): Promise<InstanceGeneralSettings> => {
|
||||
const row = await getOrCreateRow(readOptions?.db);
|
||||
const row = await getCachedRow(readOptions?.db);
|
||||
return toGeneralView(row.general);
|
||||
},
|
||||
|
||||
@@ -593,7 +599,7 @@ export function instanceSettingsService(db: Db, options: InstanceSettingsService
|
||||
},
|
||||
|
||||
getExperimental: async (): Promise<InstanceExperimentalSettingsWithManaged> => {
|
||||
const row = await getOrCreateRow();
|
||||
const row = await getCachedRow();
|
||||
return toExperimentalView(row.experimental);
|
||||
},
|
||||
|
||||
@@ -617,6 +623,7 @@ export function instanceSettingsService(db: Db, options: InstanceSettingsService
|
||||
})
|
||||
.where(eq(instanceSettings.id, current.id))
|
||||
.returning();
|
||||
await announceInstanceSettingsChange(db);
|
||||
return toInstanceSettings(updated ?? current);
|
||||
},
|
||||
|
||||
@@ -651,6 +658,7 @@ export function instanceSettingsService(db: Db, options: InstanceSettingsService
|
||||
&& toExperimentalView(nextExperimental).enableAgentChat;
|
||||
const now = new Date();
|
||||
const [updated] = await db.transaction(async tx => {
|
||||
await announceInstanceSettingsChange(tx);
|
||||
if (patch.enableStatusCards !== undefined) await notifyStatusCardEvaluation(tx);
|
||||
if (chatBecameEnabled) await notifyDeferredExecutionEligibility(tx);
|
||||
if(toExperimentalView(current.experimental).enablePublicMcp!==toExperimentalView(nextExperimental).enablePublicMcp)await prepareMcpClientMirrorPolicy(tx as unknown as Db,toExperimentalView(nextExperimental).enablePublicMcp);
|
||||
|
||||
@@ -20,11 +20,8 @@ const TASK_QUEUES: DeliveryQueue[] = [DELIVERY_QUEUES.strandedAssignments, DELIV
|
||||
export async function notifyIssueRecovery(transaction: object, scope?: IssueRecoveryScope) {
|
||||
const companyHint = scope ? JSON.stringify({ companyId: scope.companyId }) : "*";
|
||||
const issueHint = scope ? JSON.stringify({ companyId: scope.companyId, issueId: scope.issueId }) : "*";
|
||||
for (const queue of [DELIVERY_QUEUES.orphanBlockers, DELIVERY_QUEUES.activeRecoveryActions, DELIVERY_QUEUES.strandedAssignments, DELIVERY_QUEUES.assignedWorkInvariant, DELIVERY_QUEUES.resolvedDependencies,
|
||||
DELIVERY_QUEUES.taskWatchdogs, DELIVERY_QUEUES.staleIssueLocks]) {
|
||||
await notifyDeliveryWork(transaction, queue,
|
||||
queue === DELIVERY_QUEUES.strandedAssignments || queue === DELIVERY_QUEUES.staleIssueLocks ? issueHint : companyHint);
|
||||
}
|
||||
for (const queue of COMPANY_QUEUES) await notifyDeliveryWork(transaction, queue, companyHint);
|
||||
for (const queue of TASK_QUEUES) await notifyDeliveryWork(transaction, queue, issueHint);
|
||||
}
|
||||
|
||||
export function issueRecoveryBackstopHint(companyId: string) {
|
||||
@@ -71,5 +68,6 @@ export async function resolveIssueGraph(db: Db, scope: { companyId: string; runI
|
||||
and issue_id in (select id from seed) limit ${ISSUE_RECOVERY_MAX_ISSUE_IDS + 1})
|
||||
) select id::text as id from affected limit ${ISSUE_RECOVERY_MAX_ISSUE_IDS + 1}`);
|
||||
const issueIds = rows.map(row => row.id).sort();
|
||||
return issueIds.length && issueIds.length <= ISSUE_RECOVERY_MAX_ISSUE_IDS ? issueIds : null;
|
||||
if (issueIds.length === 0) return scope.issueId ? null : [];
|
||||
return issueIds.length <= ISSUE_RECOVERY_MAX_ISSUE_IDS ? issueIds : null;
|
||||
}
|
||||
@@ -12,8 +12,8 @@ import os from "node:os";
|
||||
import { currentProcessSpaceHash, UNKNOWN_PROCESS_SPACE } from "./controller-process-identity.js";
|
||||
import { proveOwnerGone } from "./owner-proof.js";
|
||||
|
||||
export const PROCESS_START_REQUESTED = "native.process_start_requested";
|
||||
export const PROCESS_IDENTITY_RECORDED = "native.process_identity_recorded";
|
||||
import { PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED } from "./native-process-start-events.js";
|
||||
export { PROCESS_IDENTITY_RECORDED, PROCESS_START_REQUESTED };
|
||||
/** Server-authored: the runner-state fence refused this run before it asked for
|
||||
* a runner, because a prior run's saved state could not be proven finished. */
|
||||
export const PRIOR_OWNER_FENCE_REFUSED = "native.prior_owner_fence_refused";
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
export const PROCESS_START_REQUESTED = "native.process_start_requested";
|
||||
export const PROCESS_IDENTITY_RECORDED = "native.process_identity_recorded";
|
||||
|
||||
/** Server-authored events (no source event ID) that prove a run started its own process. */
|
||||
export const OWN_PROCESS_START_EVENT_TYPES = [PROCESS_START_REQUESTED, PROCESS_IDENTITY_RECORDED] as const;
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { agents, companies, createDb, environmentLeases, environments, heartbeatRunEvents, heartbeatRuns, issues,
|
||||
nativeRunFinalizations } from "@paperclipai/db";
|
||||
import { recoveryPostgresSupport, startRecoveryPostgres } from "../../__tests__/helpers/recovery-postgres.js";
|
||||
import { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js";
|
||||
import { registerCancelledWorkspacePreservationWork } from "./native-failed-workspace-recovery.js";
|
||||
|
||||
(recoveryPostgresSupport.supported ? describe : describe.skip)("cancelled workspace preservation idle cost", () => {
|
||||
let database: Awaited<ReturnType<typeof startRecoveryPostgres>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
const fixtures = new Set<string>();
|
||||
|
||||
async function seed(input: { launched: boolean; lease: "destroyed" | "active" }) {
|
||||
if (!database) {
|
||||
database = await startRecoveryPostgres("cancelled-workspace-idle-");
|
||||
db = createDb(database.connectionString);
|
||||
}
|
||||
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID();
|
||||
const leaseId = randomUUID(), environmentId = randomUUID(), providerLeaseId = `allocation-${randomUUID()}`;
|
||||
fixtures.add(runId);
|
||||
await db.insert(companies).values({ id: companyId, name: "Stopped native files", issuePrefix: companyId.slice(0, 8) });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Stopped worker", adapterType: "paperclip_runner",
|
||||
status: "terminated", lifecycleState: "terminating" });
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Stopped task", status: "in_progress", assigneeAgentId: agentId });
|
||||
await db.insert(environments).values({ id: environmentId, name: `Idle ${runId}`, driver: "sandbox" });
|
||||
const nativeCancellation = { schema: "paperclip.native-cancellation.v1", companyId, issueId, runId,
|
||||
scope: "run", reasonCode: "cancellation_run_only", dispatchState: "acknowledged", dispatched: true,
|
||||
intentAuditId: randomUUID(), acknowledgementAuditId: randomUUID(), acknowledgedAt: new Date().toISOString(),
|
||||
effects: ["release_run_resources"] };
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, issueId, nativeIssueId: issueId,
|
||||
runtimeMode: "native", runtimeModeResolvedAt: new Date(), status: "cancelled", errorCode: "cancelled",
|
||||
error: "Agent lifecycle stop requested", finishedAt: new Date(), contextSnapshot: { issueId },
|
||||
nextEventSeq: input.launched ? 2 : 1,
|
||||
runnerProfileJson: { nativeWorkspaceSync: { schema: "paperclip.native-workspace-sync/v3", state: "prepared",
|
||||
descriptorSha256: "a".repeat(64), baselineSha256: "b".repeat(64), finalHostSha256: null,
|
||||
workspaceId: randomUUID(), leaseId, providerLeaseId, remoteCwd: "/work", resourceDisposition: "destroy" } },
|
||||
resultJson: { nativeCancellation, startupCancellation: { beforeNativeSelection: false } } });
|
||||
await db.insert(nativeRunFinalizations).values(input.launched
|
||||
? { runId, companyId, issueId, phase: "terminal_failure", failureCode: "native_retry_cancelled" }
|
||||
: { runId, companyId, issueId, phase: "observed", attempt: 1, controllerGeneration: 1,
|
||||
leaseOwner: `executor-${runId}`, leaseExpiresAt: new Date(Date.now() - 60_000) });
|
||||
if (input.launched) await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId, seq: 1,
|
||||
eventType: "native.process_start_requested", stream: "system", level: "info", message: "Runner launch requested" });
|
||||
const destroyed = input.lease === "destroyed";
|
||||
await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: runId, issueId,
|
||||
provider: "daytona", providerLeaseId, leasePolicy: "ephemeral", status: destroyed ? "expired" : "active",
|
||||
releasedAt: destroyed ? new Date() : null, cleanupStatus: destroyed ? "success" : null,
|
||||
metadata: { driver: "sandbox", pluginId: randomUUID(), sandboxProviderPlugin: true, remoteCwd: "/work",
|
||||
...(destroyed ? { remoteExecutionTermination: { schema: "paperclip.remote-termination.v1", state: "destroyed",
|
||||
runId, leaseId, companyId, provider: "daytona", providerLeaseId, confirmedAt: new Date().toISOString() } } : {}) } });
|
||||
return { companyId, runId, leaseId };
|
||||
}
|
||||
|
||||
afterAll(async () => { await db?.$client.end(); await database?.cleanup(); });
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers(); vi.restoreAllMocks();
|
||||
if (fixtures.size) await db.update(heartbeatRuns).set({ status: "failed" }).where(inArray(heartbeatRuns.id, [...fixtures]));
|
||||
fixtures.clear();
|
||||
});
|
||||
|
||||
async function idleStatements(minutes: number) {
|
||||
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
|
||||
const reads = vi.spyOn(db, "select"), transactions = vi.spyOn(db, "transaction"), writes = vi.spyOn(db, "update");
|
||||
await vi.advanceTimersByTimeAsync(minutes * 60_000);
|
||||
const count = reads.mock.calls.length + transactions.mock.calls.length + writes.mock.calls.length;
|
||||
reads.mockRestore(); transactions.mockRestore(); writes.mockRestore(); vi.useRealTimers();
|
||||
return count;
|
||||
}
|
||||
|
||||
it("leaves a stopped run that never started a runner alone, before and after a restart", async () => {
|
||||
const f = await seed({ launched: false, lease: "destroyed" });
|
||||
for (let boot = 0; boot < 2; boot++) {
|
||||
const worker = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => { throw error; } });
|
||||
const checks = vi.spyOn(db, "update");
|
||||
try {
|
||||
await registerCancelledWorkspacePreservationWork(db, worker, () => true, async () => true).ready;
|
||||
expect(checks.mock.calls.length).toBe(boot === 0 ? 1 : 0);
|
||||
checks.mockRestore();
|
||||
expect(worker.nextWakeAt()).toBeNull();
|
||||
expect(await idleStatements(30)).toBe(0);
|
||||
} finally { checks.mockRestore(); await worker.stop(); }
|
||||
}
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
|
||||
expect(run.runnerProfileJson).not.toHaveProperty("nativeWorkspaceSync");
|
||||
expect(run.runnerProfileJson).toHaveProperty("nativeWorkspaceSyncReleasedUnchanged.state", "prepared");
|
||||
expect(run.resultJson).not.toHaveProperty("workspaceRestoreRecovery");
|
||||
}, 120_000);
|
||||
|
||||
it("still preserves the files of a stopped run that started a runner, then goes idle", async () => {
|
||||
const f = await seed({ launched: true, lease: "active" });
|
||||
const worker = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => { throw error; } });
|
||||
try {
|
||||
await registerCancelledWorkspacePreservationWork(db, worker, () => true, async () => true).ready;
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId));
|
||||
expect(run.resultJson).toMatchObject({ workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1",
|
||||
leaseIds: [f.leaseId] } });
|
||||
expect(worker.nextWakeAt()).toBeNull();
|
||||
expect(await idleStatements(30)).toBe(0);
|
||||
} finally { await worker.stop(); }
|
||||
}, 120_000);
|
||||
});
|
||||
@@ -8,14 +8,15 @@ import { createHash, randomUUID } from "node:crypto";
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agentTaskSessions, agents, companies, controllerInstances, createDb, environmentLeases, environments, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults, nativeRunnerCheckpoints } from "@paperclipai/db";
|
||||
import { DurablePrpControlPlane, parseNativeExecutionInput, type PersistedNativeSession } from "../../vendor/paperclip-runner/index.js";
|
||||
import { startRecoveryPostgres, recoveryPostgresSupport } from "../../__tests__/helpers/recovery-postgres.js";
|
||||
import { createIsolatedTestHome } from "../../__tests__/helpers/isolated-test-home.js";
|
||||
import { prepareNativeHeartbeatRun } from "./prepare-native-run.js";
|
||||
import { nativeRunnerCheckpointWriter } from "./native-runner-checkpoint.js";
|
||||
import { assertNativeRunnerCheckpointOwner, loadNativeRunnerCheckpoint, nativeRunnerCheckpointWriter } from "./native-runner-checkpoint.js";
|
||||
import { assertNativeHarnessBackupOwner, nativeHarnessBackupOwner } from "./native-harness-backup-storage.js";
|
||||
import { assertNativeRetainedSandboxBinding, createNativeControllerRecovery, deferNativeControllerRecovery, deferNativeRunForBusyAgentDirectory, NATIVE_AGENT_DIRECTORY_BUSY_WAIT, importNativeControllerRecovery, NativeControllerRecoveryWaitingError, NATIVE_RETAINED_OWNER_WAIT, resolveNativeControllerRecovery } from "./native-controller-recovery.js";
|
||||
import { claimNativeSessionResumptions } from "./native-finalization-reconciler.js";
|
||||
import { claimNativeRestartRecoveries, currentNativeControllerIdentity } from "./native-restart-recovery.js";
|
||||
@@ -27,6 +28,7 @@ import { inspectRemoteWarmSessionRecovery, waitForLiveWarmSessionOwner } from ".
|
||||
import { currentProcessSpaceHash } from "../controller-process-identity.js";
|
||||
import { registerControllerInstanceDb, resetControllerInstanceLeaseForTests } from "../controller-instance-lease.js";
|
||||
import { readProcessStartedAt } from "../hot-restart.js";
|
||||
import { PROCESS_START_REQUESTED } from "../native-process-start-events.js";
|
||||
|
||||
describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable discovery and import", () => {
|
||||
let database: Awaited<ReturnType<typeof startRecoveryPostgres>>;
|
||||
@@ -433,6 +435,27 @@ describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable d
|
||||
expect(await claimNativeSessionResumptions({ db, runnerInstanceId: "successor", runIds: [runId], now: nextDeadline })).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps a warm follow-up that inherited its predecessor's process identity on the same run until the outgoing owner's deadline", async () => {
|
||||
const fixture = await seed(), runId = randomUUID();
|
||||
const scope = { ...fixture.scope, runId };
|
||||
const deadline = new Date(Date.now() + 60_000);
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: scope.issueId,
|
||||
nativeSessionId: scope.normalizedSessionId, status: "running", runtimeMode: "native",
|
||||
processPid: 609, processGroupId: 609, processStartedAt: new Date(Date.now() - 120_000),
|
||||
runnerProfileJson: { nativeExecutionInput: { binding: scope }, inheritedProcessIdentityRunId: fixture.scope.runId } });
|
||||
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, scope.issueId));
|
||||
await db.insert(nativeRunFinalizations).values({ companyId, issueId: scope.issueId, runId, phase: "observed" });
|
||||
await deferNativeControllerRecovery(db, { ...scope, retryAt: deadline });
|
||||
const [finalization] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId));
|
||||
expect(finalization).toMatchObject({ phase: "retryable_failure", attempt: 0, leaseOwner: null,
|
||||
nextAttemptAt: deadline, failureCode: NATIVE_RETAINED_OWNER_WAIT });
|
||||
const [run] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
||||
expect(run).toMatchObject({ processPid: null, processGroupId: null, processStartedAt: null });
|
||||
expect(run.runnerProfileJson).toMatchObject({ inheritedProcessIdentityRunId: fixture.scope.runId });
|
||||
expect(await claimNativeSessionResumptions({ db, runnerInstanceId: "successor", runIds: [runId] })).toEqual([]);
|
||||
expect(await claimNativeSessionResumptions({ db, runnerInstanceId: "successor", runIds: [runId], now: deadline })).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each(["committed", "workspace_finalizing"])("defers a remote warm continuation while its %s predecessor has a finalization lease", async phase => {
|
||||
const fixture = await seed(), runId = randomUUID(), environmentId = randomUUID();
|
||||
const previous = parseNativeExecutionInput({
|
||||
@@ -589,17 +612,20 @@ describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable d
|
||||
await new Promise(resolve => oldServer.once("spawn", resolve));
|
||||
const startedAt = await readProcessStartedAt(oldServer.pid!);
|
||||
expect(startedAt).toBeTruthy();
|
||||
const { inspect, recordOwner, runId, current } = await seedWarmFollowUpOnOldServer();
|
||||
await recordOwner({ controllerBootId: randomUUID(), controllerPid: oldServer.pid!, controllerHostHash: currentProcessSpaceHash(),
|
||||
const { inspect, recordOwner, runId, current, fixture } = await seedWarmFollowUpOnOldServer();
|
||||
const outgoingBoot = randomUUID();
|
||||
await recordOwner({ controllerBootId: outgoingBoot, controllerPid: oldServer.pid!, controllerHostHash: currentProcessSpaceHash(),
|
||||
controllerProcessStartedAt: new Date(startedAt!), leaseOwner: null, leaseExpiresAt: null });
|
||||
const before = Date.now();
|
||||
const waiting = await inspect().catch(error => error);
|
||||
expect(waiting).toBeInstanceOf(NativeControllerRecoveryWaitingError);
|
||||
expect(waiting.owner).toEqual({ runId: fixture.scope.runId, controllerBootId: outgoingBoot });
|
||||
expect(waiting.retryAt.getTime()).toBeGreaterThan(before);
|
||||
expect(waiting.retryAt.getTime()).toBeLessThanOrEqual(Date.now() + 10_000);
|
||||
await deferNativeControllerRecovery(db, { ...current.binding, retryAt: waiting.retryAt });
|
||||
await deferNativeControllerRecovery(db, { ...current.binding, retryAt: waiting.retryAt, waitingForOwner: waiting.owner });
|
||||
expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)))[0])
|
||||
.toMatchObject({ phase: "retryable_failure", attempt: 0, failureCode: NATIVE_RETAINED_OWNER_WAIT, resultId: null });
|
||||
.toMatchObject({ phase: "retryable_failure", attempt: 0, failureCode: NATIVE_RETAINED_OWNER_WAIT, resultId: null,
|
||||
failureDetail: expect.objectContaining({ waitingForOwner: { runId: fixture.scope.runId, controllerBootId: outgoingBoot } }) });
|
||||
const [task] = await db.select().from(issues).where(eq(issues.executionRunId, runId));
|
||||
expect(task?.status).toBe("in_progress");
|
||||
|
||||
@@ -664,6 +690,129 @@ describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable d
|
||||
} finally { resetControllerInstanceLeaseForTests(); }
|
||||
});
|
||||
|
||||
async function parkFollowUpBehindOutgoingServer(waitingFor?: (owner: { runId: string; controllerBootId: string }) => { runId: string; controllerBootId: string }) {
|
||||
const seeded = await seedWarmFollowUpOnOldServer();
|
||||
const { fixture, current, identity, recordOwner, runId } = seeded;
|
||||
const outgoingBoot = fixture.owner.bootId;
|
||||
await recordOwner({ controllerBootId: outgoingBoot, controllerPid: 7, controllerHostHash: "outgoing-container",
|
||||
controllerProcessStartedAt: new Date(Date.now() - 600_000), leaseOwner: null, leaseExpiresAt: null });
|
||||
await db.insert(controllerInstances).values({ bootId: outgoingBoot, processSpace: "outgoing-container", pid: 7,
|
||||
leaseExpiresAt: new Date(Date.now() + 90_000) });
|
||||
await db.update(nativeRunFinalizations).set({ controllerBootId: randomUUID() }).where(eq(nativeRunFinalizations.runId, runId));
|
||||
const wait = (checkpointedAt: Date | null) => waitForLiveWarmSessionOwner({ db, execution: current,
|
||||
priorRunId: fixture.scope.runId, checkpointedAt: async () => checkpointedAt });
|
||||
const waiting = await wait(null).catch(error => error);
|
||||
expect(waiting).toBeInstanceOf(NativeControllerRecoveryWaitingError);
|
||||
expect(waiting.owner).toEqual({ runId: fixture.scope.runId, controllerBootId: outgoingBoot });
|
||||
const parkedAt = Date.now();
|
||||
await deferNativeControllerRecovery(db, { ...current.binding, retryAt: waiting.retryAt,
|
||||
waitingForOwner: waitingFor ? waitingFor(waiting.owner) : waiting.owner });
|
||||
const outgoingRoot = join(root, `${fixture.scope.runId}-outgoing`);
|
||||
(await loadNativeRunnerCheckpoint(db, { companyId, issueId: fixture.scope.issueId, runId: fixture.scope.runId }))!
|
||||
.restoreSessionDirectory(outgoingRoot);
|
||||
const outgoing = new DurablePrpControlPlane({ stateDirectory: join(outgoingRoot, "control-plane"), identity,
|
||||
expectedRunnerVersion: "discovery-fixture", expectedRunnerDigest: `sha256:${"a".repeat(64)}` });
|
||||
outgoing.setCheckpointPersistence(nativeRunnerCheckpointWriter(db, fixture.owner));
|
||||
const fenceHarnessBackup = async () => assertNativeHarnessBackupOwner(db, await nativeHarnessBackupOwner(db, {
|
||||
companyId, issueId: fixture.scope.issueId, runId: fixture.scope.runId, bootId: outgoingBoot }));
|
||||
const saveSuspend = async () => {
|
||||
outgoing.queueCommand("runner.suspend", {}, `idle-close-${randomUUID()}`);
|
||||
await outgoing.flushCheckpoint();
|
||||
};
|
||||
const closeIdleSession = async () => {
|
||||
await fenceHarnessBackup();
|
||||
await saveSuspend();
|
||||
return new Date();
|
||||
};
|
||||
return { ...seeded, wait, waiting: waiting as NativeControllerRecoveryWaitingError, parkedAt, outgoing,
|
||||
fenceHarnessBackup, saveSuspend, closeIdleSession };
|
||||
}
|
||||
|
||||
it("the outgoing server checkpoints and closes its idle warm session while the incoming server's follow-up waits for it, and the follow-up resumes within one recheck", async () => {
|
||||
registerControllerInstanceDb(db);
|
||||
const parked = await parkFollowUpBehindOutgoingServer();
|
||||
try {
|
||||
const { fixture, runId, wait, waiting, parkedAt, outgoing, closeIdleSession } = parked;
|
||||
expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)))[0])
|
||||
.toMatchObject({ phase: "retryable_failure", attempt: 0, leaseOwner: null, failureCode: NATIVE_RETAINED_OWNER_WAIT,
|
||||
failureDetail: expect.objectContaining({ waitingForOwner: waiting.owner }) });
|
||||
const [prior] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.scope.runId));
|
||||
const ownerExitDeadline = prior!.finishedAt!.getTime() + 600_000 + 120_000;
|
||||
|
||||
const checkpointedAt = await closeIdleSession();
|
||||
const saved = await loadNativeRunnerCheckpoint(db, { companyId, issueId: fixture.scope.issueId, runId: fixture.scope.runId });
|
||||
const restoredRoot = join(root, `${runId}-idle-close`);
|
||||
saved!.restoreSessionDirectory(restoredRoot);
|
||||
const restored = JSON.parse(await readFile(join(restoredRoot, "control-plane", "control-plane-state.json"), "utf8"));
|
||||
expect(restored.commands).toContainEqual(expect.objectContaining({ type: "runner.suspend" }));
|
||||
await outgoing.stop();
|
||||
|
||||
expect(await claimNativeSessionResumptions({ db, runnerInstanceId: "incoming", runIds: [runId] })).toEqual([]);
|
||||
const claims = await claimNativeSessionResumptions({ db, runnerInstanceId: "incoming", runIds: [runId], now: waiting.retryAt });
|
||||
expect(claims).toHaveLength(1);
|
||||
await expect(wait(checkpointedAt)).resolves.toBeUndefined();
|
||||
const waitedMs = Math.max(waiting.retryAt.getTime(), checkpointedAt.getTime()) - parkedAt;
|
||||
expect(waitedMs).toBeLessThanOrEqual(5_000);
|
||||
expect(ownerExitDeadline - parkedAt).toBeGreaterThan(600_000);
|
||||
} finally {
|
||||
await parked.outgoing.stop();
|
||||
resetControllerInstanceLeaseForTests();
|
||||
}
|
||||
});
|
||||
|
||||
it("holds a resumption claim of the parked follow-up until the outgoing server's save commits", async () => {
|
||||
registerControllerInstanceDb(db);
|
||||
const parked = await parkFollowUpBehindOutgoingServer();
|
||||
try {
|
||||
const { fixture, runId, waiting } = parked;
|
||||
let claim!: Promise<Awaited<ReturnType<typeof claimNativeSessionResumptions>>>;
|
||||
let claimSettled = false;
|
||||
await db.transaction(async tx => {
|
||||
await assertNativeRunnerCheckpointOwner(tx, fixture.owner, false);
|
||||
claim = claimNativeSessionResumptions({ db, runnerInstanceId: "incoming", runIds: [runId], now: waiting.retryAt });
|
||||
void claim.finally(() => { claimSettled = true; });
|
||||
await vi.waitFor(async () => {
|
||||
const [blocked] = await db.execute<{ count: number }>(sql`select count(*)::int as count from pg_stat_activity
|
||||
where datname = current_database() and wait_event_type = 'Lock' and query ilike '%native_run_finalizations%'`);
|
||||
expect(blocked.count).toBeGreaterThan(0);
|
||||
}, { timeout: 1_500, interval: 20 });
|
||||
expect(claimSettled).toBe(false);
|
||||
});
|
||||
expect(await claim).toHaveLength(1);
|
||||
await expect(parked.saveSuspend()).rejects.toThrow("native_runner_checkpoint_owner_lost");
|
||||
} finally {
|
||||
await parked.outgoing.stop();
|
||||
resetControllerInstanceLeaseForTests();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["own-process", "own-process-event", "own-checkpoint", "claimed", "other-owner-boot", "other-owner-run"] as const)(
|
||||
"refuses the outgoing server's idle checkpoint when the parked follow-up is no longer waiting on it: %s", async scenario => {
|
||||
registerControllerInstanceDb(db);
|
||||
const parked = await parkFollowUpBehindOutgoingServer(owner => scenario === "other-owner-boot"
|
||||
? { ...owner, controllerBootId: randomUUID() } : scenario === "other-owner-run" ? { ...owner, runId: randomUUID() } : owner);
|
||||
try {
|
||||
const { fixture, runId, waiting, fenceHarnessBackup, saveSuspend } = parked;
|
||||
if (scenario === "own-process") {
|
||||
await db.update(heartbeatRuns).set({ processPid: 4242, processGroupId: 4242, processStartedAt: new Date() }).where(eq(heartbeatRuns.id, runId));
|
||||
} else if (scenario === "own-process-event") {
|
||||
await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId, seq: 1, eventType: PROCESS_START_REQUESTED });
|
||||
} else if (scenario === "own-checkpoint") {
|
||||
await db.insert(nativeRunnerCheckpoints).values({ companyId, issueId: fixture.scope.issueId, runId, part: "header", material: {} });
|
||||
} else if (scenario === "claimed") {
|
||||
expect(await claimNativeSessionResumptions({ db, runnerInstanceId: "incoming", runIds: [runId], now: waiting.retryAt })).toHaveLength(1);
|
||||
}
|
||||
const before = await loadNativeRunnerCheckpoint(db, { companyId, issueId: fixture.scope.issueId, runId: fixture.scope.runId });
|
||||
await expect(fenceHarnessBackup()).rejects.toThrow("native_runner_checkpoint_owner_lost");
|
||||
await expect(saveSuspend()).rejects.toThrow("native_runner_checkpoint_owner_lost");
|
||||
expect((await loadNativeRunnerCheckpoint(db, { companyId, issueId: fixture.scope.issueId, runId: fixture.scope.runId }))?.records)
|
||||
.toEqual(before?.records);
|
||||
} finally {
|
||||
await parked.outgoing.stop();
|
||||
resetControllerInstanceLeaseForTests();
|
||||
}
|
||||
});
|
||||
|
||||
it("sends a re-wake after a crash restart to a fresh sandbox when the parked predecessor's warm Runner cannot be adopted", async () => {
|
||||
const fixture = await seed(), runId = randomUUID(), environmentId = randomUUID(), leaseId = randomUUID();
|
||||
const previous = parseNativeExecutionInput({
|
||||
@@ -935,14 +1084,21 @@ describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable d
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["live-owner", "expired-owner", "provider-attempt", "stopped", "operator-stop"])("does not publish an admission wait after authority changes: %s", async scenario => {
|
||||
it.each(["live-owner", "expired-owner", "provider-attempt", "stopped", "operator-stop", "own-process", "inherited-then-own-process", "inherited-then-own-identity"])("does not publish an admission wait after authority changes: %s", async scenario => {
|
||||
const fixture = await seed(), runId = randomUUID();
|
||||
const scope = { ...fixture.scope, runId };
|
||||
const ownProcess = scenario.startsWith("own-process") || scenario.startsWith("inherited-then-own");
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, nativeIssueId: scope.issueId,
|
||||
status: scenario === "stopped" ? "cancelled" : "running", runtimeMode: "native",
|
||||
resultJson: scenario === "operator-stop" ? { cancellation: { source: "operator", expected: true,
|
||||
initiator: { type: "user" }, reason: "Stop", recordedAt: new Date().toISOString() } } : null,
|
||||
runnerProfileJson: { nativeExecutionInput: { binding: scope } } });
|
||||
...(ownProcess ? { processPid: 4242, processGroupId: 4242, processStartedAt: new Date() } : {}),
|
||||
runnerProfileJson: { nativeExecutionInput: { binding: scope },
|
||||
...(scenario.startsWith("inherited-then-own") ? { inheritedProcessIdentityRunId: fixture.scope.runId } : {}) } });
|
||||
if (scenario.startsWith("inherited-then-own")) {
|
||||
await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId, seq: 1,
|
||||
eventType: scenario === "inherited-then-own-process" ? "native.process_start_requested" : "native.process_identity_recorded" });
|
||||
}
|
||||
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, scope.issueId));
|
||||
await db.insert(nativeRunFinalizations).values({ companyId, issueId: scope.issueId, runId, phase: "observed",
|
||||
attempt: scenario === "provider-attempt" ? 1 : 0,
|
||||
@@ -953,6 +1109,9 @@ describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable d
|
||||
retryAt: new Date(Date.now() + 60_000) }))
|
||||
.rejects.toThrow("wait_authority_changed");
|
||||
expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)))[0].phase).toBe("observed");
|
||||
if (ownProcess) {
|
||||
expect((await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId)))[0].processPid).toBe(4242);
|
||||
}
|
||||
});
|
||||
|
||||
it("reports bounded retained-pointer coverage without loading historical payloads", async () => {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { posix } from "node:path";
|
||||
import { and, eq, inArray, ne, or, sql } from "drizzle-orm";
|
||||
import { environmentLeases, heartbeatRuns, issues, nativeRunFinalizations, nativeRunnerCheckpoints, type Db } from "@paperclipai/db";
|
||||
import { and, eq, inArray, isNull, ne, or, sql } from "drizzle-orm";
|
||||
import { environmentLeases, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations, nativeRunnerCheckpoints, type Db } from "@paperclipai/db";
|
||||
import type { AdapterExecutionTarget } from "@paperclipai/adapter-utils/execution-target";
|
||||
import { captureLegacyDurablePrpCheckpoint, parseNativeExecutionInput, type DurablePrpCheckpoint, type PersistedNativeSession } from "../../vendor/paperclip-runner/index.js";
|
||||
import { notifyNativeFinalizationWork } from "../native-finalization-notifications.js";
|
||||
import { readRunCancellation } from "../run-cancellation.js";
|
||||
import { OWN_PROCESS_START_EVENT_TYPES } from "../native-process-start-events.js";
|
||||
import { nativeSha256 } from "./canonical.js";
|
||||
import { findNativeSessionResumeRun, isNativeSessionId, isUnusedNativeSessionBootstrap, nativeSessionProviderEvidence } from "./native-session-resume.js";
|
||||
import { insertMigratedNativeRunnerCheckpoint, loadNativeRunnerCheckpoint } from "./native-runner-checkpoint.js";
|
||||
@@ -69,8 +70,10 @@ export type NativeControllerRecoveryOutcome =
|
||||
|
||||
export const NATIVE_RETAINED_OWNER_WAIT = "native_controller_recovery_waiting_for_owner";
|
||||
|
||||
export type NativeRetainedOwnerWait = { runId: string; controllerBootId: string };
|
||||
|
||||
export class NativeControllerRecoveryWaitingError extends Error {
|
||||
constructor(readonly retryAt: Date) {
|
||||
constructor(readonly retryAt: Date, readonly owner?: NativeRetainedOwnerWait) {
|
||||
super(NATIVE_RETAINED_OWNER_WAIT);
|
||||
this.name = "NativeControllerRecoveryWaitingError";
|
||||
}
|
||||
@@ -82,7 +85,7 @@ export class NativeControllerRecoveryWaitingError extends Error {
|
||||
* permissions and task ownership when this deadline arrives. */
|
||||
export async function deferNativeControllerRecovery(db: Db, input: {
|
||||
companyId: string; agentId: string; issueId: string; runId: string;
|
||||
leaseOwner?: string; retryAt: Date;
|
||||
leaseOwner?: string; retryAt: Date; waitingForOwner?: NativeRetainedOwnerWait;
|
||||
}): Promise<void> {
|
||||
await db.transaction(async tx => {
|
||||
const [task] = await tx.select({ executionRunId: issues.executionRunId }).from(issues)
|
||||
@@ -99,16 +102,27 @@ export async function deferNativeControllerRecovery(db: Db, input: {
|
||||
const cancellation = record(run?.resultJson?.nativeCancellation);
|
||||
const stop = readRunCancellation(run?.resultJson);
|
||||
const [clock] = await tx.execute<{ now: Date }>(sql`select clock_timestamp() as now`);
|
||||
const hasProcessIdentity = Boolean(run?.processPid || run?.processGroupId || run?.processStartedAt);
|
||||
const inheritedProcessIdentity = hasProcessIdentity
|
||||
&& typeof record(run?.runnerProfileJson).inheritedProcessIdentityRunId === "string"
|
||||
&& !(await tx.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents).where(and(
|
||||
eq(heartbeatRunEvents.companyId, input.companyId), eq(heartbeatRunEvents.runId, input.runId),
|
||||
isNull(heartbeatRunEvents.sourceEventId),
|
||||
inArray(heartbeatRunEvents.eventType, [...OWN_PROCESS_START_EVENT_TYPES]))).limit(1)).length;
|
||||
if (!run || run.runtimeMode !== "native" || run.status !== "running" || task?.executionRunId !== input.runId
|
||||
|| !owner || owner.phase !== "observed" || owner.resultId || owner.attempt !== 0
|
||||
|| owner.controllerGeneration !== 0 || owner.leaseOwner !== (input.leaseOwner ?? null)
|
||||
|| (input.leaseOwner && (!owner.leaseExpiresAt || owner.leaseExpiresAt <= new Date(clock.now)))
|
||||
|| run.processPid || run.processGroupId || run.processStartedAt || authority || progress.size
|
||||
|| (hasProcessIdentity && !inheritedProcessIdentity) || authority || progress.size
|
||||
|| !record(run.runnerProfileJson).nativeExecutionInput || run.resultJson?.startupCancellation
|
||||
|| (stop?.source === "operator" && stop.expected)
|
||||
|| (["run", "issue"].includes(String(cancellation.scope)) && ["pending", "acknowledged"].includes(String(cancellation.dispatchState)))) {
|
||||
throw new Error("native_controller_recovery_wait_authority_changed");
|
||||
}
|
||||
if (inheritedProcessIdentity) {
|
||||
await tx.update(heartbeatRuns).set({ processPid: null, processGroupId: null, processStartedAt: null, updatedAt: new Date() })
|
||||
.where(eq(heartbeatRuns.id, input.runId));
|
||||
}
|
||||
await notifyNativeFinalizationWork(tx, input);
|
||||
await tx.update(nativeRunFinalizations).set({
|
||||
phase: "retryable_failure", leaseOwner: null, leaseExpiresAt: null, controlDeadlineAt: null,
|
||||
@@ -116,7 +130,9 @@ export async function deferNativeControllerRecovery(db: Db, input: {
|
||||
failureDetail: { originalFailureCode: NATIVE_RETAINED_OWNER_WAIT,
|
||||
message: "Waiting for the retained native controller owner to release its lease.",
|
||||
recoveryMode: record(run.runnerProfileJson).sessionCheckpoint ? "same_session_resume" : "bootstrap_retry",
|
||||
providerSessionEstablished: false, providerEventsExist: false },
|
||||
providerSessionEstablished: false, providerEventsExist: false,
|
||||
...(input.waitingForOwner ? { waitingForOwner: { runId: input.waitingForOwner.runId,
|
||||
controllerBootId: input.waitingForOwner.controllerBootId } } : {}) },
|
||||
updatedAt: new Date(),
|
||||
}).where(eq(nativeRunFinalizations.runId, input.runId));
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ import { recordRequiredWorkspaceRestoreFailure } from "../legacy-execution-recov
|
||||
import { hasRequiredWorkspaceRecovery, nativeRunHasNoWorkspaceAccess } from "../workspace-restore-recovery-state.js";
|
||||
import { logActivity } from "../activity-log.js";
|
||||
import { readNativeWorkspaceSyncReference } from "./native-workspace-sync.js";
|
||||
import { nativeRunNeverLaunchedRunner, settleUnchangedNativeWorkspace } from "../environment-lease-release-deferral.js";
|
||||
import type { NativeRestartRecoveryClaim } from "./native-restart-recovery.js";
|
||||
import { NativeWorkspaceFinalizationBusyError } from "./native-workspace-finalization-ownership.js";
|
||||
import { hasAcknowledgedNativeRunStopRequest } from "../acknowledged-native-stop.js";
|
||||
@@ -161,7 +162,7 @@ export async function preserveNativeFailedWorkspace(db: Db, selected: Pick<typeo
|
||||
let retained = !retainFiles || alreadyRetained ? run : await recordRequiredWorkspaceRestoreFailure(tx as unknown as Db, run, { workspaceRestoreFailure: "restore_failed" }, source);
|
||||
if (!retained || retainFiles && !hasRequiredWorkspaceRecovery(retained.resultJson)) return;
|
||||
if (options.allowPreterminal && coordinator.phase === "observed") {
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id });
|
||||
const [settled] = await tx.update(nativeRunFinalizations).set({ phase: "terminal_failure",
|
||||
leaseOwner: null, leaseExpiresAt: null, controlDeadlineAt: null, nextAttemptAt: null,
|
||||
recoveryState: "blocked", failureCode: coordinator.failureCode ?? "native_continuation_requires_reconciliation", updatedAt: new Date(),
|
||||
@@ -329,9 +330,16 @@ export function registerCancelledWorkspacePreservationWork(db: Db,
|
||||
eq(nativeRunFinalizations.issueId, run.nativeIssueId!),
|
||||
));
|
||||
if (finalization?.resultId && !stoppedAcceptedCopyback(finalization)) return null;
|
||||
if (finalization?.phase !== "terminal_failure" || finalization.leaseOwner)
|
||||
if (finalization?.phase !== "terminal_failure" || finalization.leaseOwner) {
|
||||
const ownerDeadline = finalization?.leaseOwner ? finalization.leaseExpiresAt?.getTime() ?? null : null;
|
||||
if (ownerDeadline && ownerDeadline > Date.now()) return { ...entry, dueAt: ownerDeadline };
|
||||
if (await nativeRunNeverLaunchedRunner(db, run.id, run.companyId)
|
||||
&& await settleUnchangedNativeWorkspace(db, run.id, run.companyId)) return null;
|
||||
return { ...entry, dueAt: Date.now() + 30_000 };
|
||||
}
|
||||
if (await cancelledWorkspaceSource(db, run)) await preserveNativeFailedWorkspace(db, run, { allowPreterminal: true, requireCancelledStop: true });
|
||||
else if (await nativeRunNeverLaunchedRunner(db, run.id, run.companyId)
|
||||
&& await settleUnchangedNativeWorkspace(db, run.id, run.companyId)) return null;
|
||||
const [current] = await db.select().from(heartbeatRuns)
|
||||
.where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, run.companyId)));
|
||||
const currentControllerDeadline = current?.controllerLeaseExpiresAt?.getTime();
|
||||
|
||||
@@ -27,7 +27,7 @@ export async function settleFailedNativeRecoveryPreparation(db: Db, input: {
|
||||
if (run?.status !== "failed") return false;
|
||||
// Register the work before the writes it announces. A spare wake when no
|
||||
// coordinator matches below is harmless.
|
||||
await notifyExecutionRunWork(tx as unknown as Db, { companyId: input.companyId });
|
||||
await notifyExecutionRunWork(tx as unknown as Db, { companyId: input.companyId, runId: input.runId });
|
||||
const now = new Date();
|
||||
const [settled] = await tx.update(nativeRunFinalizations).set({
|
||||
phase: "terminal_failure", leaseOwner: null, leaseExpiresAt: null, nextAttemptAt: null, controlDeadlineAt: null,
|
||||
|
||||
@@ -1030,7 +1030,7 @@ async function endNamespaceUnverifiedRun(tx: Db, row: {
|
||||
run: typeof heartbeatRuns.$inferSelect; coordinator: typeof nativeRunFinalizations.$inferSelect;
|
||||
issueAssigneeAgentId: string | null; issueStatus: string;
|
||||
}, now: Date, reason: string, event: ReturnType<typeof historyEntry>, recoveryRequestId: string | null) {
|
||||
await notifyExecutionRunWork(tx, { companyId: row.run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: row.run.companyId, runId: row.run.id });
|
||||
await tx.update(nativeRunFinalizations).set({ phase: "terminal_failure", leaseOwner: null, leaseExpiresAt: null,
|
||||
nextAttemptAt: null, failureCode: "native_restart_recovery_blocked",
|
||||
failureDetail: { ...row.coordinator.failureDetail, reason, executorStopEvidence: "unverified" },
|
||||
@@ -1932,7 +1932,7 @@ export async function claimNativeRestartRecoveries(input: {
|
||||
recycledProviderPids: providerProcesses.recycledPids,
|
||||
stderrTail: row.run.stderrExcerpt,
|
||||
});
|
||||
await notifyExecutionRunWork(tx, { companyId: row.run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: row.run.companyId, runId: row.run.id });
|
||||
await tx
|
||||
.update(nativeRunFinalizations)
|
||||
.set({
|
||||
|
||||
@@ -405,7 +405,7 @@ export async function endSupersededNativeFinalizationRuns(db: Db, runIds?: reado
|
||||
: accepted === "succeeded" ? "succeeded" as const : accepted === "cancelled" ? "cancelled" as const : "failed" as const;
|
||||
await notifyNativeFinalizationWork(tx, { companyId: run.companyId, runId: run.id });
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.accounting, run.companyId);
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id });
|
||||
await notifyChatRunMilestones(tx, { companyId: run.companyId, issueId: coordinator.issueId });
|
||||
await notifyInstructionCollection(tx, { companyId: run.companyId, runId: run.id });
|
||||
await notifyCancelledWorkspacePreservation(tx, { companyId: run.companyId, runId: run.id });
|
||||
@@ -626,7 +626,7 @@ async function recordRetryableFailure(input: {
|
||||
if (phase === "terminal_failure" && failureCode === "native_workspace_sync_out_unsafe_archive") {
|
||||
await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: input.run.companyId, issueId: input.coordinator.issueId });
|
||||
}
|
||||
await notifyExecutionRunWork(tx, { companyId: input.run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: input.run.companyId, runId: input.run.id });
|
||||
await notifyChatRunMilestones(tx, { companyId: input.run.companyId, issueId: input.coordinator.issueId });
|
||||
await tx
|
||||
.update(nativeRunFinalizations)
|
||||
@@ -2077,7 +2077,7 @@ export async function finalizeNativeRun(input: {
|
||||
if (input.projectRunStatus) await notifyCancelledWorkspacePreservation(tx, { companyId: run.companyId, runId: run.id });
|
||||
if (input.projectRunStatus) await notifyUnsafeWorkspaceExportRunChange(tx, run);
|
||||
if (input.projectRunStatus) await notifyDeliveryWork(tx, DELIVERY_QUEUES.accounting, run.companyId);
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id });
|
||||
await notifyChatRunMilestones(tx, { companyId: run.companyId, issueId: coordinator.issueId });
|
||||
const [after] = await projectRun(tx);
|
||||
if (after && input.projectRunStatus) await settleNativeTerminalWake(tx, after);
|
||||
|
||||
@@ -18,6 +18,7 @@ import { createObjectRunLogStore } from "../object-run-log-store.js";
|
||||
import { nativeSha256 } from "./canonical.js";
|
||||
import { createNativeRunLogCoverageVerifier, formatNativeRunLogEvent } from "./native-run-log-export.js";
|
||||
import { readRecoverableRunLog, recoverSettledNativeRunLog } from "./native-run-log-recovery.js";
|
||||
import { invalidateInstanceSettingsCache } from "../instance-settings-cache.js";
|
||||
|
||||
// Use an explicit guarded test database or a new owned embedded fixture.
|
||||
const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_NATIVE_LOG_WATERMARK_DATABASE_URL");
|
||||
@@ -348,7 +349,7 @@ describe.skipIf(!support.supported)("native run log source watermarks", () => {
|
||||
const f = await fixture();
|
||||
const setMasking = async (value: boolean) => db.execute(sql`insert into instance_settings(general)
|
||||
values(${JSON.stringify({ censorUsernameInLogs: value })}::jsonb)
|
||||
on conflict(singleton_key) do update set general=excluded.general`);
|
||||
on conflict(singleton_key) do update set general=excluded.general`).finally(invalidateInstanceSettingsCache);
|
||||
const redaction = async () => ({ enabled: (await instanceSettingsService(db).getGeneral()).censorUsernameInLogs,
|
||||
userNames: ["fixture-operator"], homeDirs: ["/home/fixture-operator"] });
|
||||
await setMasking(enabled);
|
||||
|
||||
@@ -51,7 +51,7 @@ export async function settleNativeTerminalWake(tx: Db, run: Pick<typeof heartbea
|
||||
const [current] = await tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests)
|
||||
.where(claim).for("update").limit(1);
|
||||
if (!current) return;
|
||||
await notifyExternalConversationSettlement(tx, { companyId: run.companyId });
|
||||
await notifyExternalConversationSettlement(tx, { companyId: run.companyId, runId: run.id });
|
||||
await notifyStrandedAgentStatus(tx, { companyId: run.companyId, agentId: run.agentId });
|
||||
await tx.update(agentWakeupRequests).set({
|
||||
status: run.status === "succeeded" ? "completed" : run.status,
|
||||
@@ -174,7 +174,7 @@ export async function projectCommittedRun(input: {
|
||||
await notifyCancelledWorkspacePreservation(tx, { companyId: input.run.companyId, runId: input.run.id });
|
||||
await notifyUnsafeWorkspaceExportRunChange(tx, input.run);
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.accounting, input.run.companyId);
|
||||
await notifyExecutionRunWork(tx, { companyId: input.run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: input.run.companyId, runId: input.run.id });
|
||||
await notifyChatRunMilestones(tx, { companyId: input.run.companyId, issueId: input.coordinator.issueId });
|
||||
const [after] = await tx
|
||||
.update(heartbeatRuns)
|
||||
|
||||
@@ -69,6 +69,18 @@ function createRecordingTraceContext(): {
|
||||
}
|
||||
|
||||
describe("native runner performance trace", () => {
|
||||
it("records the named check of a failed measurement on its run event", async () => {
|
||||
const {traceContext}=createRecordingTraceContext();
|
||||
const events: Array<Record<string, unknown>> = [];
|
||||
const trace=createNativeRunTrace({runId:"provider-pack-check",startedAtMs:1000,traceContext,
|
||||
onEvent:async event=>{events.push(event.payload as Record<string, unknown>);}});
|
||||
const rejected=Object.assign(new Error("runner_remote_provider_artifact_incompatible: incompatible"),{failureCheck:"contract_digest"});
|
||||
await expect(trace.measure("provider_pack.compatibility",async()=>{throw rejected;},{attributes:{target:"image"}})).rejects.toBe(rejected);
|
||||
await expect(trace.measure("provider_pack.verify",async()=>{throw Object.assign(new Error("x"),{failureCheck:"has space"});})).rejects.toThrow("x");
|
||||
await trace.finish("ok");
|
||||
expect(events.find(event=>event.span==="provider_pack.compatibility")).toMatchObject({outcome:"failed",target:"image",check:"contract_digest"});
|
||||
expect(events.find(event=>event.span==="provider_pack.verify")).not.toHaveProperty("check");
|
||||
});
|
||||
it("projects a full durable diagnostic batch without waiting on duplicate run-log writes", async () => {
|
||||
const {traceContext, spans}=createRecordingTraceContext();
|
||||
let release!: () => void;
|
||||
|
||||
@@ -210,6 +210,7 @@ const SAFE_NATIVE_RUN_SPAN_ATTRIBUTE_KEYS = new Set([
|
||||
"adapter",
|
||||
"anchor",
|
||||
"bytesTransferred",
|
||||
"check",
|
||||
"inputBytes", "toolSchemaBytes", "toolCount", "contextReused", "tokenDataAvailable",
|
||||
"connectionOwner",
|
||||
"driver",
|
||||
@@ -229,6 +230,11 @@ const SAFE_NATIVE_RUN_SPAN_ATTRIBUTE_KEYS = new Set([
|
||||
"target",
|
||||
]);
|
||||
|
||||
export function nativeRunFailureCheck(error: unknown): string | undefined {
|
||||
const check = (error as { failureCheck?: unknown } | null)?.failureCheck;
|
||||
return typeof check === "string" && /^[A-Za-z0-9_.:,@/-]{1,120}$/.test(check) ? check : undefined;
|
||||
}
|
||||
|
||||
function finiteMs(value: number): number {
|
||||
return Number.isFinite(value) ? Math.max(0, value) : 0;
|
||||
}
|
||||
@@ -630,6 +636,8 @@ export function createNativeRunTrace(input: {
|
||||
return await run(scope, fn);
|
||||
} catch (error) {
|
||||
outcome = "failed";
|
||||
const check = nativeRunFailureCheck(error);
|
||||
if (check) annotate(scope, { check });
|
||||
throw error;
|
||||
} finally {
|
||||
await end(scope, { outcome });
|
||||
|
||||
@@ -3,12 +3,14 @@ import { NATIVE_PREPARATION_FENCING_VERSION } from "./native-active-runs.js";
|
||||
import { notifyLiveRunRecovery } from "../live-run-recovery-notifications.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { and, eq, exists, gt, isNull, lte, inArray, notExists, or, sql, type SQL } from "drizzle-orm";
|
||||
import { checkpointDb, heartbeatRuns, issues, nativeRunFinalizations, nativeRunnerCheckpoints, primeDatabaseWorkTransactionId, type Db } from "@paperclipai/db";
|
||||
import { checkpointDb, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations, nativeRunnerCheckpoints, primeDatabaseWorkTransactionId, type Db } from "@paperclipai/db";
|
||||
import { inspectDurablePrpCheckpointHeader, inspectUnauthenticatedBootstrapCheckpoint, inspectUnclaimedBootstrapCheckpoint, decodeDurablePrpCheckpoint, type DurablePrpCheckpoint, type DurablePrpControlPlane, type DurableRecoveryIdentity } from "../../vendor/paperclip-runner/index.js";
|
||||
import { createLocalEncryptedCipher, deriveLocalEncryptedInstanceSecret } from "../../secrets/local-encrypted-provider.js";
|
||||
import { legacyControllerBootId } from "../legacy-controller-lease.js";
|
||||
import { assertNativeSourceCheckpointConsumer, lockSourceRecoveryCoordinators } from "./native-source-recovery-ownership.js";
|
||||
import { runnerdStateHasNoProviderTurn, runnerdStateIsIncompleteBootstrap } from "./native-bootstrap-proof.js";
|
||||
import { NATIVE_RETAINED_OWNER_WAIT } from "./native-controller-recovery.js";
|
||||
import { OWN_PROCESS_START_EVENT_TYPES } from "../native-process-start-events.js";
|
||||
|
||||
type Binding = { companyId: string; issueId: string; runId: string };
|
||||
export const NATIVE_CHECKPOINT_HEADER_INSPECTION_MAX_BYTES = 1024 * 1024;
|
||||
@@ -116,13 +118,37 @@ export async function validateNativeRunnerCheckpointOwner(
|
||||
eq(heartbeatRuns.issueId, owner.issueId), inArray(heartbeatRuns.status, ["queued", "scheduled_retry"]),
|
||||
notExists(tx.select({ runId: nativeRunFinalizations.runId }).from(nativeRunFinalizations)
|
||||
.where(eq(nativeRunFinalizations.runId, heartbeatRuns.id))))) : [];
|
||||
const [parkedSuccessor] = !successor && !preparingSuccessor && !waitingSuccessor && task?.executionRunId && task.executionRunId !== owner.runId
|
||||
? await parkedSuccessorWaitingForOwner(tx, owner, task.executionRunId) : [];
|
||||
if (!current.resultId || newWork || !task
|
||||
|| (task.executionRunId && task.executionRunId !== owner.runId && !successor && !preparingSuccessor && !waitingSuccessor)) {
|
||||
|| (task.executionRunId && task.executionRunId !== owner.runId && !successor && !preparingSuccessor && !waitingSuccessor && !parkedSuccessor)) {
|
||||
throw new Error("native_runner_checkpoint_owner_lost");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function parkedSuccessorWaitingForOwner(tx: CheckpointTransaction, owner: NativeRunnerCheckpointFenceOwner, successorRunId: string) {
|
||||
return tx.select({ runId: nativeRunFinalizations.runId }).from(nativeRunFinalizations)
|
||||
.innerJoin(heartbeatRuns, eq(heartbeatRuns.id, nativeRunFinalizations.runId)).where(and(
|
||||
eq(nativeRunFinalizations.runId, successorRunId), eq(nativeRunFinalizations.companyId, owner.companyId),
|
||||
eq(nativeRunFinalizations.issueId, owner.issueId), eq(nativeRunFinalizations.phase, "retryable_failure"),
|
||||
eq(nativeRunFinalizations.failureCode, NATIVE_RETAINED_OWNER_WAIT), eq(nativeRunFinalizations.attempt, 0),
|
||||
isNull(nativeRunFinalizations.resultId), isNull(nativeRunFinalizations.leaseOwner),
|
||||
sql`${nativeRunFinalizations.failureDetail}->'waitingForOwner'->>'runId' = ${owner.runId}`,
|
||||
sql`${nativeRunFinalizations.failureDetail}->'waitingForOwner'->>'controllerBootId' = ${owner.bootId}`,
|
||||
eq(heartbeatRuns.companyId, owner.companyId), eq(heartbeatRuns.nativeIssueId, owner.issueId),
|
||||
eq(heartbeatRuns.runtimeMode, "native"), eq(heartbeatRuns.status, "running"),
|
||||
isNull(heartbeatRuns.processPid), isNull(heartbeatRuns.processGroupId), isNull(heartbeatRuns.processStartedAt),
|
||||
sql`${heartbeatRuns.nativeSessionId} = (select source.native_session_id from heartbeat_runs source
|
||||
where source.id = ${owner.runId} and source.company_id = ${owner.companyId})`,
|
||||
notExists(tx.select({ runId: nativeRunnerCheckpoints.runId }).from(nativeRunnerCheckpoints).where(and(
|
||||
eq(nativeRunnerCheckpoints.companyId, owner.companyId), eq(nativeRunnerCheckpoints.runId, successorRunId)))),
|
||||
notExists(tx.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents).where(and(
|
||||
eq(heartbeatRunEvents.companyId, owner.companyId), eq(heartbeatRunEvents.runId, successorRunId),
|
||||
isNull(heartbeatRunEvents.sourceEventId), inArray(heartbeatRunEvents.eventType, [...OWN_PROCESS_START_EVENT_TYPES])))),
|
||||
)).for("share", { of: nativeRunFinalizations });
|
||||
}
|
||||
|
||||
export async function assertNativeRunnerCheckpointOwner(tx: CheckpointTransaction, owner: NativeRunnerCheckpointOwner, newWork: boolean) {
|
||||
const locked = await lockNativeRunnerCheckpointOwner(tx, owner);
|
||||
await validateNativeRunnerCheckpointOwner(tx, owner, locked, newWork);
|
||||
|
||||
@@ -610,7 +610,7 @@ export async function reconcileSafeNativeReplacements(
|
||||
(ownershipBound && !await ownershipProofExpired(tx, run))
|
||||
)
|
||||
return;
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id });
|
||||
await tx
|
||||
.update(nativeRunFinalizations)
|
||||
.set({
|
||||
|
||||
@@ -434,6 +434,8 @@ import {
|
||||
nativeSessionWorkspaceScope,
|
||||
reserveWarmNativeInstructionDirectory,
|
||||
closeIdleWarmNativeSessionsForRestart,
|
||||
WARM_IDLE_CLOSE_MAX_RETRIES,
|
||||
WARM_IDLE_CLOSE_RETRY_MS,
|
||||
readNativeSessionIdleWork,
|
||||
createGovernedWaitEventObservation,
|
||||
createRemoteRunnerProcessLauncher,
|
||||
@@ -11614,10 +11616,12 @@ describe("native warm session supervision", () => {
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ lease: "pending_cleanup", forgotten: true },
|
||||
{ lease: "released", forgotten: true },
|
||||
{ lease: "stopped-receipt", forgotten: true },
|
||||
{ lease: "destroyed-receipt", forgotten: true },
|
||||
{ lease: "pending_cleanup", forgotten: false },
|
||||
{ lease: "released", forgotten: false },
|
||||
{ lease: "retained", forgotten: false },
|
||||
])("forgets a warm owner whose idle close failed only once the host gave up its sandbox: $lease", async ({ lease, forgotten }) => {
|
||||
])("forgets a warm owner whose idle close failed only once its sandbox has a stop or destroy receipt: $lease", async ({ lease, forgotten }) => {
|
||||
const identity = `warm-idle-close-sandbox-${lease}`;
|
||||
const warmExecution = { ...execution, binding: { ...execution.binding, runId: identity, executionWorkspaceId: `${identity}-workspace` },
|
||||
session: { ...execution.session, normalizedSessionId: identity, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 50 } },
|
||||
@@ -11632,7 +11636,7 @@ describe("native warm session supervision", () => {
|
||||
});
|
||||
const copy = (runId: string) => ({ runId, root: `/tmp/${identity}`, preparationKey: "same", hasChanges: async () => false,
|
||||
collectStopped: async () => undefined, retirementFailed: async () => undefined });
|
||||
let leaseRows: Array<{ status: string }> = [];
|
||||
let leaseRows: Array<Record<string, unknown>> = [];
|
||||
const base = leaseDb(warmExecution);
|
||||
const db = { ...base, select: (fields?: unknown) => ({ from: (table: unknown) => table === environmentLeases
|
||||
? { where: async () => leaseRows } : base.select(fields as never).from(table as never) }) } as unknown as Db;
|
||||
@@ -11641,7 +11645,14 @@ describe("native warm session supervision", () => {
|
||||
runnerExecutionTarget: { kind: "remote", transport: "sandbox", environmentId: identity, remoteCwd: `/tmp/${identity}`,
|
||||
sandboxLeaseAcquisition: { providerLeaseId: `${identity}-sandbox` } } as never,
|
||||
instructionWorkingCopy: copy(identity) });
|
||||
leaseRows = [{ status: lease }];
|
||||
const receipt = lease.endsWith("-receipt") ? lease.slice(0, -"-receipt".length) : null;
|
||||
leaseRows = [{ id: `${identity}-lease`, companyId: warmExecution.binding.companyId, environmentId: identity,
|
||||
heartbeatRunId: identity, provider: "daytona", providerLeaseId: `${identity}-sandbox`,
|
||||
status: receipt ? "released" : lease, releasedAt: lease === "retained" ? null : new Date(),
|
||||
cleanupStatus: receipt || lease === "released" ? "success" : "failed", leasePolicy: "reuse_by_environment",
|
||||
metadata: receipt ? { remoteExecutionTermination: { schema: "paperclip.remote-termination.v1",
|
||||
companyId: warmExecution.binding.companyId, runId: identity, leaseId: `${identity}-lease`, provider: "daytona",
|
||||
providerLeaseId: `${identity}-sandbox`, state: receipt, confirmedAt: new Date().toISOString() } } : {} }];
|
||||
await vi.waitFor(() => expect(session.close).toHaveBeenCalledTimes(1));
|
||||
const followUpRunId = `${identity}-follow-up`;
|
||||
const adopt = vi.fn(async () => null);
|
||||
@@ -12197,6 +12208,79 @@ describe("native warm session supervision", () => {
|
||||
expect(collectStopped).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("an idle warm session whose close fails with runner_remote_process_identity_unavailable and whose Runner is proven gone is released at controller restart", async () => {
|
||||
const name = "warm-close-runner-gone";
|
||||
const current = { ...execution,
|
||||
binding: { ...execution.binding, runId: name, executionWorkspaceId: name },
|
||||
session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } },
|
||||
} as NativeExecutionInputV1;
|
||||
const close = vi.fn<() => Promise<void>>(async () => {
|
||||
throw new RemoteRunnerRecoveryError({ stage: "process_verification", reason: "process_not_running" });
|
||||
});
|
||||
state.execute.mockReset().mockImplementationOnce(async options => {
|
||||
await options.onSession?.({ close });
|
||||
return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" },
|
||||
turnId: name, normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1",
|
||||
nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null };
|
||||
});
|
||||
await expect(executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name }))
|
||||
.resolves.toMatchObject({ exitCode: 0 });
|
||||
expect(close).not.toHaveBeenCalled();
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toEqual({ closed: 1, busy: 0, failed: 0, failures: [] });
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toEqual({ closed: 0, busy: 0, failed: 0, failures: [] });
|
||||
});
|
||||
|
||||
it("names the Runner check in a warm close failure and keeps an unproven owner registered at controller restart", async () => {
|
||||
const name = "warm-close-marker-missing";
|
||||
const current = { ...execution,
|
||||
binding: { ...execution.binding, runId: name, executionWorkspaceId: name },
|
||||
session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } },
|
||||
} as NativeExecutionInputV1;
|
||||
const close = vi.fn<() => Promise<void>>(async () => {
|
||||
throw new RemoteRunnerRecoveryError({ stage: "process_verification", reason: "marker_missing" });
|
||||
});
|
||||
state.execute.mockReset().mockImplementationOnce(async options => {
|
||||
await options.onSession?.({ close });
|
||||
return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" },
|
||||
turnId: name, normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1",
|
||||
nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null };
|
||||
});
|
||||
await executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name });
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 0, failed: 1, failures: [{ runId: name,
|
||||
reason: "close failed: runner_remote_process_identity_unavailable: runner_remote_process_identity_unavailable [process_verification/marker_missing]" }] });
|
||||
close.mockResolvedValue(undefined);
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 1, failed: 0 });
|
||||
});
|
||||
|
||||
it("retries a failed idle warm close a bounded number of times", async () => {
|
||||
const name = "warm-idle-close-retry";
|
||||
const current = { ...execution,
|
||||
binding: { ...execution.binding, runId: name, executionWorkspaceId: name },
|
||||
session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 20 } },
|
||||
} as NativeExecutionInputV1;
|
||||
const close = vi.fn<() => Promise<void>>(async () => { throw new Error("native_runner_checkpoint_owner_lost"); });
|
||||
state.execute.mockReset().mockImplementationOnce(async options => {
|
||||
await options.onSession?.({ close });
|
||||
return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" },
|
||||
turnId: name, normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1",
|
||||
nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null };
|
||||
});
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
||||
try {
|
||||
await executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name });
|
||||
await vi.advanceTimersByTimeAsync(20);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
await vi.advanceTimersByTimeAsync(WARM_IDLE_CLOSE_RETRY_MS);
|
||||
expect(close).toHaveBeenCalledTimes(2);
|
||||
await vi.advanceTimersByTimeAsync(WARM_IDLE_CLOSE_RETRY_MS * 10);
|
||||
expect(close).toHaveBeenCalledTimes(1 + WARM_IDLE_CLOSE_MAX_RETRIES);
|
||||
expect(readNativeSessionIdleWork()).toBe("present");
|
||||
} finally { vi.useRealTimers(); }
|
||||
close.mockResolvedValue(undefined);
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 1, failed: 0 });
|
||||
});
|
||||
|
||||
it.each(["failed", "cancelled"] as const)("retires a %s session even if its warm checkpoint rejects", async (runTerminalState) => {
|
||||
const name = `warm-checkpoint-rejects-${runTerminalState}`;
|
||||
const current = { ...execution,
|
||||
@@ -13245,6 +13329,48 @@ describe("native warm session supervision", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ lease: "released-stop-receipt", closed: 1 },
|
||||
{ lease: "pending_cleanup", closed: 0 },
|
||||
{ lease: "released-without-receipt", closed: 0 },
|
||||
{ lease: "stop-receipt-for-another-run", closed: 0 },
|
||||
] as const)("reads the warm owner's own lease rows at controller restart: $lease", async ({ lease: kind, closed }) => {
|
||||
const { base } = fixture(`restart-lease-${kind}`);
|
||||
const environmentId = `restart-lease-env-${kind}`, providerLeaseId = `restart-lease-sandbox-${kind}`;
|
||||
const close = vi.fn(async (): Promise<void> => { throw new Error("owned close not yet confirmed"); });
|
||||
state.execute.mockReset().mockImplementationOnce(async options => {
|
||||
await options.onSession?.({ close }); return result;
|
||||
});
|
||||
const leaseRunId = kind === "stop-receipt-for-another-run" ? "earlier-run" : base.binding.runId;
|
||||
const terminal = kind !== "pending_cleanup";
|
||||
const row = { id: `lease-${kind}`, companyId: base.binding.companyId, environmentId, heartbeatRunId: leaseRunId,
|
||||
provider: "daytona", providerLeaseId, status: terminal ? "released" : "pending_cleanup", releasedAt: new Date(),
|
||||
cleanupStatus: terminal ? "success" : "failed", leasePolicy: "reuse_by_environment",
|
||||
metadata: kind === "released-stop-receipt" || kind === "stop-receipt-for-another-run"
|
||||
? { remoteExecutionTermination: { schema: "paperclip.remote-termination.v1", companyId: base.binding.companyId,
|
||||
runId: leaseRunId, leaseId: `lease-${kind}`, provider: "daytona", providerLeaseId, state: "stopped",
|
||||
confirmedAt: new Date().toISOString() } }
|
||||
: { failureReason: "sandbox_stop_pending" } };
|
||||
let leaseRows: unknown[] = [];
|
||||
const ownerDb = leaseDb(base), select = ownerDb.select.bind(ownerDb);
|
||||
ownerDb.select = ((fields?: Record<string, unknown>) => ({ from: (table: unknown) => {
|
||||
if (table !== environmentLeases) return select(fields as never).from(table as never);
|
||||
const query = { then: (...args: Parameters<Promise<unknown[]>["then"]>) => Promise.resolve(leaseRows).then(...args),
|
||||
where: () => query, limit: () => query };
|
||||
return query;
|
||||
} })) as unknown as Db["select"];
|
||||
try {
|
||||
await executePaperclipNativeSession({ db: ownerDb, execution: base, runnerInstanceId: "runner",
|
||||
runnerExecutionTarget: { kind: "remote", transport: "sandbox", environmentId, remoteCwd: `/tmp/${environmentId}`,
|
||||
sandboxLeaseAcquisition: { outcome: "created", providerLeaseId } } });
|
||||
leaseRows = [row];
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed, failed: 1 - closed });
|
||||
} finally {
|
||||
close.mockResolvedValue(undefined);
|
||||
await closeIdleWarmNativeSessionsForRestart();
|
||||
}
|
||||
});
|
||||
|
||||
it("retains failed retirement for retry and never launches over an uncontained owner", async () => {
|
||||
const { base, next, run } = fixture("identity-close-failure");
|
||||
const close = vi.fn().mockRejectedValueOnce(new Error("containment unavailable")).mockResolvedValue(undefined);
|
||||
|
||||
@@ -50,7 +50,7 @@ import { notifyCancelledWorkspacePreservation } from "../cancelled-workspace-pre
|
||||
import { notifyInstructionCollection } from "../instruction-collection-notifications.js";
|
||||
import { providerPackWorkspaceId, recordAdmittedRemoteProviderPack, resolveRemoteProviderPackAuthority } from "./remote-provider-pack-authority.js";
|
||||
import { nativeProviderPackAdmissionFailureCode, prepareNativeProviderPackAdmission, rememberAdmittedNativeProviderPack, rememberRecoveredNativeProviderPack, recordNativeProviderPackAdmission, type NativeProviderPackAdmissionSource } from "./native-provider-pack-admission.js";
|
||||
import { type ProviderPackInstallation, verifyRemoteProviderPack as verifyRemoteProviderPackIdentity } from "./remote-provider-pack-verification.js";
|
||||
import { type ProviderPackInstallation, providerPackIncompatible, verifyRemoteProviderPack as verifyRemoteProviderPackIdentity } from "./remote-provider-pack-verification.js";
|
||||
import { writeEnvironmentCleanup } from "../environment-cleanup-notifications.js";
|
||||
import { NATIVE_SESSION_EXECUTION_LEASE_TTL_MS, lockNativeExecutionLeaseForReacquire, nativeExecutionLeaseHeldCondition, releaseUnstartedNativeExecutionClaim, startNativeSessionExecutionLeaseRenewal, type NativeExecutionLeaseRenewal } from "./native-execution-lease.js";
|
||||
export { renewNativeSessionExecutionLease } from "./native-execution-lease.js";
|
||||
@@ -130,7 +130,7 @@ import { copyBackCodexAuth } from "@paperclipai/adapter-codex-local/server";
|
||||
import { nativeCompletionFeedback } from "./native-completion-feedback.js";
|
||||
import { hasAcknowledgedNativeLifecycleStopIntent, hasAcknowledgedNativeReassignmentStopIntent, hasAcknowledgedNativeStopIntent, hasAcknowledgedNativeRunStopReceipt } from "../acknowledged-native-stop.js";
|
||||
import { stoppedCodexTurnIsTextOnly } from "./stopped-codex-turn.js";
|
||||
import { prepareVerifiedRemoteProviderPack, useVerifiedPreinstalledRemoteProviderPack, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js";
|
||||
import { prepareVerifiedRemoteProviderPack, providerPackProvenanceReuseAllowed, useVerifiedPreinstalledRemoteProviderPack, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js";
|
||||
import { uploadVerifiedProviderPack } from "./provider-pack-upload.js";
|
||||
import { selectRemotePiCompanion } from "./remote-pi-companion.js";
|
||||
import { scheduledResumeContinuationAllowed } from "./scheduled-resume-continuation.js";
|
||||
@@ -743,12 +743,15 @@ type WarmNativeSession = {
|
||||
controllerDetachedForRestart?: boolean;
|
||||
finishRelease?: () => Promise<void>;
|
||||
closeOnReleaseReason?: string;
|
||||
idleCloseRetries?: number;
|
||||
idleTimer: ReturnType<typeof setTimeout> | null;
|
||||
lastActivityAt: string;
|
||||
};
|
||||
|
||||
const WARM_CLOSE_FAILURE_DETAIL_MAX = 2_000;
|
||||
const WARM_NATIVE_SESSION_CLOSE_CONCURRENCY = 4;
|
||||
export const WARM_IDLE_CLOSE_RETRY_MS = 5_000;
|
||||
export const WARM_IDLE_CLOSE_MAX_RETRIES = 3;
|
||||
|
||||
export function describeWarmCloseFailure(error: unknown): string {
|
||||
const describe = (value: unknown): string => {
|
||||
@@ -757,8 +760,10 @@ export function describeWarmCloseFailure(error: unknown): string {
|
||||
const code = "code" in value && typeof value.code === "string" ? `${value.code}: ` : "";
|
||||
const settlement = value instanceof NativeSessionCloseUnrecoverableError && value.settlement
|
||||
? ` ${JSON.stringify(value.settlement)}` : "";
|
||||
const remote = readRemoteRunnerRecoveryError(value);
|
||||
const recovery = remote ? ` [${remote.stage}/${remote.reason}${remote.runnerLifecycle ? `/${remote.runnerLifecycle}` : ""}]` : "";
|
||||
const cause = value.cause === undefined ? "" : ` (cause: ${describe(value.cause)})`;
|
||||
return `${code}${value.message}${settlement}${cause}`;
|
||||
return `${code}${value.message}${recovery}${settlement}${cause}`;
|
||||
};
|
||||
const text = describe(error).replaceAll(/[\r\n]+/g, " ");
|
||||
return text.length > WARM_CLOSE_FAILURE_DETAIL_MAX ? `${text.slice(0, WARM_CLOSE_FAILURE_DETAIL_MAX)}…` : text;
|
||||
@@ -1107,17 +1112,7 @@ export async function closeWarmNativeSessionsForEnvironment(input: {
|
||||
return closeIdleWarmNativeSessions(input);
|
||||
}
|
||||
|
||||
async function warmSandboxGivenUpByHost(entry: WarmNativeSession): Promise<boolean> {
|
||||
if (!entry.sandboxLeaseDb || !entry.providerLeaseId || !entry.environmentId) return false;
|
||||
const leases = await entry.sandboxLeaseDb.select({ status: environmentLeases.status }).from(environmentLeases).where(and(
|
||||
eq(environmentLeases.companyId, entry.companyId),
|
||||
eq(environmentLeases.environmentId, entry.environmentId),
|
||||
eq(environmentLeases.providerLeaseId, entry.providerLeaseId),
|
||||
));
|
||||
return leases.length > 0 && leases.every(lease => lease.status !== "active" && lease.status !== "retained");
|
||||
}
|
||||
|
||||
async function warmSandboxDestroyed(db: Db, entry: WarmNativeSession): Promise<boolean> {
|
||||
async function warmSandboxTerminated(db: Db, entry: WarmNativeSession): Promise<boolean> {
|
||||
if (!entry.providerLeaseId || !entry.environmentId) return false;
|
||||
const leases = await db.select().from(environmentLeases).where(and(
|
||||
eq(environmentLeases.companyId, entry.companyId),
|
||||
@@ -1125,8 +1120,23 @@ async function warmSandboxDestroyed(db: Db, entry: WarmNativeSession): Promise<b
|
||||
eq(environmentLeases.providerLeaseId, entry.providerLeaseId),
|
||||
));
|
||||
const resolved = await Promise.all(leases.map(lease => resolveRemoteTerminationLease(db, lease)));
|
||||
return resolved.some(lease => hasRemoteTerminationReceipt(lease)
|
||||
&& (lease.metadata?.remoteExecutionTermination as { state?: unknown } | undefined)?.state === "destroyed");
|
||||
return resolved.some(lease => {
|
||||
if (!hasRemoteTerminationReceipt(lease)) return false;
|
||||
const state = (lease.metadata?.remoteExecutionTermination as { state?: unknown } | undefined)?.state;
|
||||
return state === "destroyed" || (state === "stopped" && lease.heartbeatRunId === entry.runId);
|
||||
});
|
||||
}
|
||||
|
||||
/** A failed close is complete when its Runner is proven gone, its sandbox is destroyed, or the run's own sandbox lease has a stop receipt. */
|
||||
async function warmCloseFailureProvesOwnerGone(entry: WarmNativeSession, error: unknown, db = entry.sandboxLeaseDb): Promise<boolean> {
|
||||
const diagnostic = readRemoteRunnerRecoveryError(error);
|
||||
if (diagnostic?.stage === "process_verification" && diagnostic.reason === "process_not_running") return true;
|
||||
try {
|
||||
return db ? await warmSandboxTerminated(db, entry) : false;
|
||||
} catch (proofError) {
|
||||
logger.warn({ err: proofError, runId: entry.runId }, "could not read the warm session's sandbox lease");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Detach released owners and checkpoint unreleased owners before a controller
|
||||
@@ -1195,16 +1205,10 @@ async function closeIdleWarmNativeSessions(input: {
|
||||
busy += 1;
|
||||
return;
|
||||
}
|
||||
const destroyed = !detach && input.forceStopUnsettled && input.db
|
||||
? await warmSandboxDestroyed(input.db, entry).catch(proofError => {
|
||||
logger.warn({ err: proofError, runId: entry.runId }, "could not read the warm session's sandbox lease");
|
||||
return false;
|
||||
})
|
||||
: false;
|
||||
if (destroyed) {
|
||||
if (!detach && await warmCloseFailureProvesOwnerGone(entry, error, input.db ?? entry.sandboxLeaseDb)) {
|
||||
logger.warn({ runId: entry.runId, issueId: entry.issueId, environmentId: entry.environmentId,
|
||||
providerLeaseId: entry.providerLeaseId ?? null, reason: input.reason, closeFailure: describeWarmCloseFailure(error) },
|
||||
"warm native session's sandbox was already destroyed; released its owner");
|
||||
"warm native session's Runner or sandbox is gone; released its owner");
|
||||
forgetWarmNativeSession(sessionId, entry);
|
||||
closed += 1;
|
||||
return;
|
||||
@@ -8860,17 +8864,21 @@ function armWarmNativeSessionIdleTimer(
|
||||
return;
|
||||
}
|
||||
logger.warn({ runId: current.runId, issueId: current.issueId, environmentId: current.environmentId,
|
||||
providerLeaseId: current.providerLeaseId ?? null, closeFailure: describeWarmCloseFailure(error) },
|
||||
providerLeaseId: current.providerLeaseId ?? null, closeFailure: describeWarmCloseFailure(error),
|
||||
closeAttempt: (current.idleCloseRetries ?? 0) + 1 },
|
||||
released ? "idle warm native session detach failed" : "idle warm native session close failed");
|
||||
if (released) return;
|
||||
return warmSandboxGivenUpByHost(current).then(givenUp => {
|
||||
if (!givenUp) return;
|
||||
logger.warn({ runId: current.runId, issueId: current.issueId, environmentId: current.environmentId,
|
||||
providerLeaseId: current.providerLeaseId ?? null },
|
||||
"warm native session's sandbox was stopped by the host; released its owner");
|
||||
forgetWarmNativeSession(sessionId, current);
|
||||
}, proofError => {
|
||||
logger.warn({ err: proofError, runId: current.runId }, "could not read the warm session's sandbox lease");
|
||||
return warmCloseFailureProvesOwnerGone(current, error).then(gone => {
|
||||
if (gone) {
|
||||
logger.warn({ runId: current.runId, issueId: current.issueId, environmentId: current.environmentId,
|
||||
providerLeaseId: current.providerLeaseId ?? null },
|
||||
"warm native session's Runner or sandbox is gone; released its owner");
|
||||
forgetWarmNativeSession(sessionId, current);
|
||||
return;
|
||||
}
|
||||
if ((current.idleCloseRetries ?? 0) >= WARM_IDLE_CLOSE_MAX_RETRIES) return;
|
||||
current.idleCloseRetries = (current.idleCloseRetries ?? 0) + 1;
|
||||
armWarmNativeSessionIdleTimer(sessionId, current, WARM_IDLE_CLOSE_RETRY_MS);
|
||||
});
|
||||
})
|
||||
.finally(() => {
|
||||
@@ -10727,7 +10735,7 @@ export async function executePaperclipNativeSession(input: {
|
||||
executionFailure = error;
|
||||
if (error instanceof NativeControllerRecoveryWaitingError) {
|
||||
await deferNativeControllerRecovery(input.db, { ...input.execution.binding,
|
||||
leaseOwner: input.leaseOwner, retryAt: error.retryAt });
|
||||
leaseOwner: input.leaseOwner, retryAt: error.retryAt, waitingForOwner: error.owner });
|
||||
}
|
||||
if (!(error instanceof NativeRunnerOwnershipUnverifiedError) && !(error instanceof NativeStartupCleanupPendingError) && startup.stopRequested && startup.executionContext?.signal.reason instanceof Error &&
|
||||
startup.executionContext.signal.reason.message === "native_session_cancelled") {
|
||||
@@ -13027,7 +13035,7 @@ async function executePaperclipNativeSessionAttempt(
|
||||
eq(nativeRunFinalizations.runId, input.execution.binding.runId),
|
||||
eq(nativeRunFinalizations.leaseOwner, leaseOwner),
|
||||
),
|
||||
), { companyId: input.execution.binding.companyId });
|
||||
), { companyId: input.execution.binding.companyId, runId: input.execution.binding.runId });
|
||||
|
||||
const failedAtMs = Date.now();
|
||||
const executionFailureMessage = redactOutputText(
|
||||
@@ -13092,7 +13100,7 @@ async function executePaperclipNativeSessionAttempt(
|
||||
eq(nativeRunFinalizations.leaseOwner, leaseOwner),
|
||||
eq(nativeRunFinalizations.attempt, attempt),
|
||||
isNull(nativeRunFinalizations.resultId),
|
||||
)).returning({ runId: nativeRunFinalizations.runId }), { companyId: input.execution.binding.companyId });
|
||||
)).returning({ runId: nativeRunFinalizations.runId }), { companyId: input.execution.binding.companyId, runId: input.execution.binding.runId });
|
||||
if (settled) {
|
||||
await stoppedLeaseRenewal;
|
||||
if (warmSessionId !== null && lifecyclePolicy.mode === "warm") {
|
||||
@@ -13281,7 +13289,7 @@ async function executePaperclipNativeSessionAttempt(
|
||||
// Issue → coordinator → run, as below. A lease that lapsed untouched
|
||||
// (host sleep) is still this owner's to settle; see the held condition.
|
||||
await lockNativeExecutionLeaseForReacquire(tx, { ...input.execution.binding, leaseOwner, preResultOnly: true });
|
||||
await notifyExecutionRunWork(tx, { companyId: input.execution.binding.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: input.execution.binding.companyId, runId: input.execution.binding.runId });
|
||||
await notifyNativeFinalizationWork(tx, input.execution.binding);
|
||||
const updated = await tx
|
||||
.update(nativeRunFinalizations)
|
||||
@@ -14664,6 +14672,7 @@ export async function prepareRemoteProviderPackOnTarget(input: {
|
||||
signal?: AbortSignal;
|
||||
trace?: NativeRunTrace;
|
||||
onLog?: (stream: "stdout" | "stderr", chunk: string) => void | Promise<void>;
|
||||
acceptProvenanceDifferences?: boolean;
|
||||
}): Promise<{ root: string; manifest: RemoteProviderPackManifest; source: "staged" | "preinstalled" | "uploaded" }> {
|
||||
const remoteTarget = input.target, remoteCommandRunner = input.runner;
|
||||
const configuredProviderPackRoot = input.configuredProviderPackRoot;
|
||||
@@ -14671,10 +14680,10 @@ export async function prepareRemoteProviderPackOnTarget(input: {
|
||||
const stagedRemoteProviderPackRoot = posix.join(remoteTarget.remoteCwd, ".paperclip-runtime", "paperclip-runner", "provider-pack");
|
||||
let activeRemoteProviderPackRoot: string | null = null;
|
||||
let preinstalledProviderPackRoots: string[] = [];
|
||||
const verifyRemoteProviderPack = async (packRoot: string) => {
|
||||
await verifyRemoteProviderPackIdentity({ runner: remoteCommandRunner,
|
||||
cwd: remoteTarget.remoteCwd, packRoot, manifest: expectedProviderPackManifest });
|
||||
};
|
||||
let selectedProviderPackManifest = expectedProviderPackManifest;
|
||||
const verifyRemoteProviderPack = (packRoot: string, acceptProvenance = false) =>
|
||||
verifyRemoteProviderPackIdentity({ runner: remoteCommandRunner, cwd: remoteTarget.remoteCwd, packRoot,
|
||||
manifest: expectedProviderPackManifest, acceptProvenance: acceptProvenance && input.acceptProvenanceDifferences === true });
|
||||
const discoverPreinstalledProviderPack = async () => {
|
||||
if (!remoteTarget || !remoteCommandRunner) return [];
|
||||
const result = await remoteCommandRunner.execute({
|
||||
@@ -14696,15 +14705,16 @@ export async function prepareRemoteProviderPackOnTarget(input: {
|
||||
verifyStaged: () => measureNativeRunnerSpan(
|
||||
input.trace,
|
||||
"provider_pack.verify",
|
||||
() => verifyRemoteProviderPack(stagedRemoteProviderPackRoot),
|
||||
async () => { selectedProviderPackManifest = await verifyRemoteProviderPack(stagedRemoteProviderPackRoot, true); },
|
||||
),
|
||||
usePreinstalled: async () => useVerifiedPreinstalledRemoteProviderPack({
|
||||
usePreinstalled: async (onRejected) => useVerifiedPreinstalledRemoteProviderPack({
|
||||
onRejected,
|
||||
candidates: preinstalledProviderPackRoots = await measureNativeRunnerSpan(input.trace, "provider_pack.discover", discoverPreinstalledProviderPack),
|
||||
verifyAndLink: async (preinstalledProviderPack) => {
|
||||
await measureNativeRunnerSpan(
|
||||
const preinstalledManifest = await measureNativeRunnerSpan(
|
||||
input.trace,
|
||||
"provider_pack.verify_preinstalled",
|
||||
() => verifyRemoteProviderPack(preinstalledProviderPack),
|
||||
() => verifyRemoteProviderPack(preinstalledProviderPack, true),
|
||||
);
|
||||
const escapedSource = preinstalledProviderPack.replaceAll(
|
||||
"'",
|
||||
@@ -14728,11 +14738,10 @@ export async function prepareRemoteProviderPackOnTarget(input: {
|
||||
timeoutMs: 10_000,
|
||||
}));
|
||||
if (linked.exitCode !== 0 || linked.timedOut) {
|
||||
throw new Error(
|
||||
"runner_remote_provider_artifact_incompatible: preinstalled provider pack could not be linked",
|
||||
);
|
||||
throw providerPackIncompatible("link_failed", "preinstalled provider pack could not be linked");
|
||||
}
|
||||
activeRemoteProviderPackRoot = stagedRemoteProviderPackRoot;
|
||||
selectedProviderPackManifest = preinstalledManifest;
|
||||
await input.onLog?.(
|
||||
"stderr",
|
||||
"[paperclip-runner] using manifest-matched preinstalled provider pack\n",
|
||||
@@ -14767,9 +14776,10 @@ export async function prepareRemoteProviderPackOnTarget(input: {
|
||||
targetPath: stagedRemoteProviderPackRoot,
|
||||
mode: 0o700,
|
||||
}),
|
||||
verifyUploaded: () => verifyRemoteProviderPack(stagedRemoteProviderPackRoot),
|
||||
verifyUploaded: async () => { await verifyRemoteProviderPack(stagedRemoteProviderPackRoot); },
|
||||
});
|
||||
activeRemoteProviderPackRoot = stagedRemoteProviderPackRoot;
|
||||
selectedProviderPackManifest = expectedProviderPackManifest;
|
||||
},
|
||||
});
|
||||
activeRemoteProviderPackRoot = stagedRemoteProviderPackRoot;
|
||||
@@ -14779,7 +14789,7 @@ export async function prepareRemoteProviderPackOnTarget(input: {
|
||||
"[paperclip-runner] reusing manifest-matched provider pack from the workspace\n",
|
||||
);
|
||||
}
|
||||
return { root: activeRemoteProviderPackRoot!, manifest: expectedProviderPackManifest, source: packSource };
|
||||
return { root: activeRemoteProviderPackRoot!, manifest: selectedProviderPackManifest, source: packSource };
|
||||
}
|
||||
|
||||
/** Read selection identity only; verify controller contents only if upload is needed. */
|
||||
@@ -17143,7 +17153,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
requireExactIdentity: retainProviderPack || explicitProviderPackSelection,
|
||||
requireCurrentOpenCodeProxy: !retainProviderPack
|
||||
&& runnerEnvironment?.PAPERCLIP_OPENCODE_PERFORMANCE_DIAGNOSTICS === "1",
|
||||
}));
|
||||
}), { attributes: { target: installation.root === stagedRemoteProviderPackRoot ? "workspace" : "image" } });
|
||||
if (!retainProviderPack) providerPackAuthority!.select(manifest);
|
||||
expectedProviderPackManifest = manifest;
|
||||
activeRemoteProviderPackRoot = installation.root;
|
||||
@@ -17207,7 +17217,13 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
target: remoteTarget, runner: remoteCommandRunner, configuredProviderPackRoot,
|
||||
manifest: expectedProviderPackManifest, trace: input.trace, onLog: input.onLog,
|
||||
signal: sourceSignals.length ? AbortSignal.any(sourceSignals) : undefined,
|
||||
acceptProvenanceDifferences: providerPackProvenanceReuseAllowed({ retainProviderPack, explicitProviderPackSelection,
|
||||
authoritySelectable: providerPackAuthority !== null }),
|
||||
});
|
||||
if (prepared.manifest.digest !== expectedProviderPackManifest.digest) {
|
||||
providerPackAuthority!.select(prepared.manifest);
|
||||
expectedProviderPackManifest = prepared.manifest;
|
||||
}
|
||||
activeRemoteProviderPackRoot = prepared.root;
|
||||
providerPackVerified = true;
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ export async function retireSupersededNativeRetry(db: Db, input: {
|
||||
)).limit(1);
|
||||
if (!source) return false;
|
||||
|
||||
await notifyExecutionRunWork(db, { companyId: run.companyId });
|
||||
await notifyExecutionRunWork(db, { companyId: run.companyId, runId: run.id });
|
||||
await db.update(nativeRunFinalizations).set({ phase: "terminal_failure", nextAttemptAt: null,
|
||||
leaseExpiresAt: null, controlDeadlineAt: null, recoveryState: "blocked",
|
||||
failureCode: "native_retry_superseded", failureDetail: { ...coordinator.failureDetail,
|
||||
|
||||
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user