diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md index 5dd82a8c312..8318e22e2c4 100644 --- a/doc/DEVELOPING.md +++ b/doc/DEVELOPING.md @@ -2597,7 +2597,7 @@ The default `worktree init` still seeds eagerly. A lean worktree (created withou - `pnpm paperclipai worktree ensure-seeded` performs the deferred seed **exactly once**. It is lock-guarded and idempotent: only a complete `verified` manifest short-circuits it, so it is safe to call repeatedly and from concurrent processes. Managed workspaces derive the source from the control-plane-provided base project workspace when it carries its own `.paperclip/config.json`, and otherwise from the control plane's own registered instance config; either way the workspace's manifest never selects it. Manual worktrees must pass `--from-config`. - `paperclipai run` calls `ensureWorktreeSeeded` automatically before doctor/boot. Managed runs transparently seed a lean worktree from their registered base workspace; an unmanaged lean worktree must first run `worktree ensure-seeded --from-config `. -- Managed Paperclip git worktrees default to the repository's `scripts/provision-worktree.sh` when the strategy omits `provisionCommand`. When a registered source config exists, setup creates the isolated config and pending manifest. Runtime startup also runs `scripts/provision-worktree-runtime.sh` automatically when no explicit runtime provision command is configured and the manifest is not verified. Explicitly configured provision commands still take precedence. +- Managed git worktrees run a repository's `scripts/provision-worktree.sh` when the strategy omits `provisionCommand` and that file exists. The Paperclip repository deliberately does not ship a file at that path, so agent turns in Paperclip worktrees do not wait on dependency installs or instance setup. Its setup script is `scripts/setup-paperclip-worktree.sh`: run it by hand, or set it as the project's `provisionCommand` to opt in. When a registered source config exists, it creates the isolated config and pending manifest, then installs dependencies. Runtime startup still runs `scripts/provision-worktree-runtime.sh` automatically when no explicit runtime provision command is configured and the manifest is not verified; that script runs `scripts/setup-paperclip-worktree.sh` first when the worktree has no config. Explicitly configured provision commands still take precedence. - An environment-configured server may have no local seed config. If neither the base checkout nor the default control-plane instance has one, a fresh worktree prepares its dependencies without creating a development instance. This also applies when `PAPERCLIP_CONFIG` names the default `$PAPERCLIP_HOME/instances/$PAPERCLIP_INSTANCE_ID/config.json` path, as the Docker image does. Setup creates no config, environment file, or seed manifest and does not claim runtime or seed readiness. A later request for a seeded development runtime still needs a canonical registered source config. Once that source exists, provisioning the checkout again creates the development instance normally. - A missing custom `PAPERCLIP_CONFIG`, rejected symlink, or non-regular source file still fails setup. An existing worktree with a config, environment file, or seed state also fails if its source disappears; setup never downgrades that instance to a plain checkout. Repair the source before retrying. - The built-in deferred seed is recorded as its own terminal `workspace_seed` operation. A zero exit code is not enough for success: the operation succeeds only when `.paperclip/seed-manifest.json` contains complete verified evidence; failed, missing, or malformed manifests produce a failed operation with the seed phase in metadata. @@ -4690,8 +4690,9 @@ whether or not anything is left to compact. A compacted worktree is in the same state as a freshly created one, so when the task resumes, whatever produced those files the first time produces them again: -reuse runs the workspace provision command (or `scripts/provision-worktree.sh`), -which reinstalls dependencies when `node_modules` is missing. Repositories without +reuse runs the workspace provision command (or a repository's +`scripts/provision-worktree.sh`), which can reinstall dependencies when +`node_modules` is missing. Repositories without a provision command rely on the agent's own install step, as they do for a new worktree. diff --git a/doc/SPEC-implementation.md b/doc/SPEC-implementation.md index 053a49216d9..26f97cf0568 100644 --- a/doc/SPEC-implementation.md +++ b/doc/SPEC-implementation.md @@ -1520,6 +1520,20 @@ timestamps, including on repeated release. For unfinished issues it clears the agent assignee; only `in_progress` changes to `todo`. Existing company access, assignee/run ownership checks, and the `issue.released` activity event still apply. +A status change releases the checkout and execution locks but does not stop the +run that holds them. An agent request (`PATCH /issues/:issueId` or a recovery +resolution) that sets a status other than `in_progress` (even its current value) on +a task whose lock is held by a different queued or running run is refused with +`409` and code `issue_status_change_live_run`; +otherwise the run would keep going with no task bound to it, which is the effect +of interrupting another agent's run. The denial is final and names the person's +controls on the linked task: the run's Stop or Interrupt, or More task actions, +then Pause subtree on the parent. The lock-holding run, board users, and paths +that stop the run themselves (cancelling the task, reassigning it, and completing +through `PATCH` a task whose Runner goal is paused first) are unaffected. The write +is conditional on the lock the check saw; a run that acquires the lock in between returns `409` +`issue_execution_lock_changed`. + `POST /issues/:issueId/admin/force-release` is an operator recovery endpoint for stale harness locks. It requires board access to the issue company, clears checkout and execution run lock fields, and may clear the agent assignee when `clearAssignee=true` is passed. The route must write an `issue.admin_force_release` activity log entry containing the previous checkout and execution run IDs. ## 10.5 Projects diff --git a/doc/execution-semantics.md b/doc/execution-semantics.md index 2adc1c2198d..4d7260d3cdc 100644 --- a/doc/execution-semantics.md +++ b/doc/execution-semantics.md @@ -612,6 +612,17 @@ failing setup. The save's retry budget bounds that wait. A save that exhausts its retries is handed to the board as a named recovery action. After that hand-off, the cutoff no longer advances. +Automatic wakes do not run into a hold that preparation would refuse. A parent or +dependent woken because a child or blocker stalled on the board +(`issue_blocker_stalled`) is not woken again when its assignee's last run on the +task failed setup on its bound workspace's hold and that hold is still past the +cutoff, or held by a writer that cannot be named: another run could only fail +the same way. The wake is delivered once the hold settles or the task changes +assignee, and the sweep checks again at most hourly. Failed runs that carry a +stall, including resource-wait retries of its wake, are retried after ten +minutes, then twenty, and not after the third failed run. The stall stays +listed on the waiting task, and a new stall wakes it again. + An instance admission drain keeps accepted new turns queued and displays **Waiting for maintenance**. Ending the audited drain requests admission for these existing runs immediately. The shared delivery coordinator owns the drain's @@ -2779,6 +2790,33 @@ predecessor/successor receipts for every earlier owner. Unrelated, live, or incompletely linked owners remain ambiguous. The run then fails closed with `runner_harness_state_mismatch: backup_without_reusable_lease`. +A workspace-restore hold also takes a warm sandbox out of reuse. When a run +that holds a warm lease ends with a workspace-restore failure, the hold stops +the sandbox under a stop-and-retain receipt, changes the lease policy to +`retain_on_failure`, and records a `workspaceRestoreRecovery` marker with the +original policy. Workspace recovery then saves the files. In the transaction +that completes that recovery, Paperclip returns the lease to +`reuse_by_environment` only when all of these are true: the original policy +was `reuse_by_environment` (or, for a marker saved by an older release, the +lease carries its reusable-lease scope), the recovery is complete with a +saved-file receipt from this allocation, the stop receipt is confirmed with +state `stopped`, no unsaved writer or pending native workspace export is bound +to the allocation, the run's recorded disposition is not `destroy`, and the +allocation has one verified owner chain. The update is a compare-and-swap on +the checked row. It moves the marker to `workspaceRestoreRecoverySettled`, so +the next run resumes the warm sandbox. A hold that fails any condition keeps +its protection. + +Older releases left settled holds in `retain_on_failure`, and reuse never +selects that policy. For those rows, the hold's lease also counts as a retired +backup source when all of these are true: the lease is `released` with policy +`retain_on_failure`, it has a `workspaceRestoreRecovery` marker for its own +run, it has a confirmed stop-and-retain receipt with state `stopped`, and no +unsaved writer or pending native workspace export is bound to it. The backup +stamp, single-owner, and later-provider-work checks above still apply. A +stopped lease that is still `reuse_by_environment` remains ambiguous and fails +closed. + A Runner close can also fail to prove suspension after the control plane accepted the run's result (`native.post_result_failure` with category `runner_settlement_incomplete`). The provider work is complete, so this is not diff --git a/doc/plans/2026-11-09-task-loading-performance.md b/doc/plans/2026-11-09-task-loading-performance.md new file mode 100644 index 00000000000..b6094e85345 --- /dev/null +++ b/doc/plans/2026-11-09-task-loading-performance.md @@ -0,0 +1,269 @@ +# Task loading performance: latest chat in ~0 ms + +Date: 2026-11-09 · Branch: `claude/task-loading-perf-154fea` (base `33a23e0246`) + +## Goal + +Opening a task from the "Mine" issues list should show the composer and the latest +messages almost immediately. If an agent is live, the user should catch up on its +progress. If the run is done, the user should see the last messages. Older history +loads only when the user asks for it. The page must not move content around: +skeletons must have the same size as the content that replaces them, and the latest +message must not move once it is visible. + +### Finish conditions + +The user-facing endpoint is reviewable PRs with these results remeasured on staging. + +| # | Condition | Baseline (below) | Target | +|---|---|---|---| +| F1 | Revisit a task whose data is cached → composer and latest message visible | 144–170 ms (14.6 s when the run log gates) | ≤ 100 ms, for every task | +| F2 | Hover, then click a row → composer and latest message visible | not prefetched today | ≤ 150 ms | +| F3 | Click a row with no prefetch (data not cached) → composer and latest message visible | 1.1–2.0 s (13.9 s when the run log gates) | ≤ 600 ms p50 (one round trip) | +| F4 | Hard load of a task URL → content painted | 5.2 s | ≤ 1.5 s | +| F5 | Layout stability | CLS 0.035 on every click | 0 inside the chat; the latest message never moves after it first appears | +| F6 | API requests started before the page is ready | ~30 on a click, ~70 on a hard load | ≤ 3 on the critical path | +| F7 | Live run | — | Shows the current run status within F1–F3 and streams new output | + +The evidence for each condition is a timing sample from the staging harness (Phase 0): +5 tasks × 3 starting states, run serially, reporting the median and range. The same +journey is repeated after each PR is deployed. + +## Baseline on staging, measured 2026-11-09 + +- **Environment:** the shared staging instance, one company with production-like data, desktop Chrome, HTTP/2, no throttling. +- **JS cache:** the JS bundle was already in the browser cache. +- **Harness:** an in-page harness that checks every animation frame for the thread mount, a visible composer, the latest `[data-conversation-message]` being visible in the viewport, layout shifts, and resource timing. + +### Click from the list (data not cached in React Query) + +| Task | Composer + latest message | Thread mounted | API requests (total / before ready) | What it waited on | +|---|---|---|---|---| +| Task A | 1,107 ms | 38 ms | 35 / 33 | `GET /issues/:id` 1,016 ms; activity, runs, recent-comments ~710 ms each | +| Task B | 1,190 ms | 56 ms | 49 / 31 | `GET /issues/:id` 1,289 ms; ~10 parallel queries of 800–900 ms | +| Task C | 1,977 ms | 935 ms | 41 / 28 | a serial chain: work-products, activity and runs started at ~900 ms | +| Task D | 2,014 ms | 540 ms | — | — | +| **Task E** | **13,862 ms** | 40 ms | 78 / 76 | **`GET /heartbeat-runs/:id/log` 11,150 ms** | + +### Revisit (React Query cache warm) + +| Task | Composer + latest message | Note | +|---|---|---| +| Task D | 144 ms | | +| Task B | 170 ms | | +| **Task E** | **14,651 ms** | The run log is fetched again and gates the page again (13.2 s) | + +### Hard load (direct URL, JS from cache) + +| Task | Document TTFB | First contentful paint | Header paint | **Content paint** | API requests before content | +|---|---|---|---|---|---| +| Task F | 478 ms | 676 ms | 2,416 ms | **5,211 ms** | 70 | +| Task G | 4,558 ms (outlier; a later fetch of the same HTML took 207–389 ms) | 4,980 ms | 6,587 ms | 7,841 ms | 72 | + +The page parses about 7.7 MB of JS, even with all of it served from the cache. + +### Server latency floor + +Each endpoint was requested 3 times in a row, without competing requests. + +- `/api/cli-auth/me` 272–365 ms. This trivial authenticated request sets the floor for each round trip from this machine. +- `/api/issues/:id/recent-comments` 300 ms. +- `/api/issues/:id?view=core` 464–595 ms, with one sample at 3.2 s. +- `/api/issues/:id` full 863–996 ms. +- `/api/issues/:id/activity?view=recent` 520–1,061 ms. +- `/api/issues/:id/runs?view=recent` 374–1,125 ms. + +During a click, ~30 requests run at the same time, and each slows to 700–1,500 ms. + +**Server-Timing** samples: +- `issue_lookup` took 893–908 ms in one cold sample and ~100–160 ms in others. +- `paperclip_issue` (full view) took 736–1,813 ms. + +### Run log read + +Task E has a failed run with no saved reply. Its log comes from the object-store journal (`s3_segments`). + +| Read | Time | +|---|---| +| Tail, 32 KB at offset 414,581, with `alignStartToRecord=true` (what the UI sends) | 11.9 s, 11.2 s | +| Same tail without alignment | 6.1 s | +| Same 32 KB at offset 0 | 2.0 s | + +### Repeated and polling requests + +These requests were made during one 17 s visit (Task E): + +| Request | Count | +|---|---| +| `issues/summaries?ids` | 22 | +| `/issues/:id/live-runs` (two id forms) | 11 | +| `/issues/:id/browsers` | 6 | +| `companies/:id/agents` (60 KB each) | 6 | +| `companies/:id/live-runs` | 3 | +| descendant, created-from and parent lists | 2–3 each | + +## Where the time goes + +1. **The run transcript blocks the whole chat.** + - The composer and messages stay hidden until history is ready: `historyPending = initialHistoryPending || planLoading || transcriptHistoryPending || chatMetadataPending` (`ui/src/components/TaskChatThread.tsx:3216`). + - The composer dock is hidden until then too (`concealed={!historyRevealed}`, `TaskChatThread.tsx:3524`). + - `transcriptHistoryPending` waits for every failed run, live run, or run without a reply to finish hydrating. + - The only cap is the 15 s reveal timeout. One slow log read therefore hides even saved messages the page has already fetched. +2. **Tail reads from the object-store log are serial.** + - `readRange` in `server/src/services/object-byte-journal.ts:525` visits index nodes and payload segments one by one, with one S3 GET for each. + - A tail read crosses many small segments. + - `alignStartToRecord` repeats the whole traversal for the 32 KB before it (`object-run-log-store.ts:388`), which doubles the cost. + - Nothing caches these objects, although segments cannot change after they are written. +3. **The page waits on many queries.** + - `initialHistoryPending` waits on about ten queries: recent comments, interactions, attachments, work products, activity, runs, comment runs, comment input facts, live runs and active run. + - The thread also waits on the plan, transcripts and conversation metadata. + - Even when every query is fast, the reveal waits for the slowest of ~30 concurrent requests that compete on the server. +4. **Prefetch covers only part of what the page waits on.** + - `prefetchIssueDetailForNavigation` (`ui/src/lib/issueDetailCache.ts:227`) warms only the core view and recent comments. + - Everything else that gates the reveal still starts on click. + - Nothing is kept across reloads (no React Query persister). A hard load is therefore always cold. +5. **The full issue request waits for the core request.** + - The full `GET /issues/:id` starts only after `view=core` resolves (`IssueDetail.tsx:3361`). +6. **Non-critical work competes with the reveal.** + - chat-binding, email tasks, browsers, external-objects, feedback votes, tree holds, projects, related-issue lists and polling all start on the click and share server capacity with the requests that matter. +7. **The hard-load path is heavy.** + - It parses about 7.7 MB of JS. + - It sends 70 API requests before content appears. + - The header paints 1.5 s after navigation starts, and the content 4.3 s after. + +## Feedback loop + +| Question | Loop and environment | Cost per iteration | +|---|---|---| +| Is the user-visible timing better? | Staging harness (Phase 0) run through Chrome against real data, after each deploy | ~5 min per sample set, plus the deploy | +| Does a UI gate or prefetch change help? | Local `tests/perf/issue-detail` Playwright harness with production assets (`PAPERCLIP_UI_DEV_MIDDLEWARE=false`), plus a CDP network RTT of ~150 ms so local results match staging round trips | ~2–3 min | +| Is the object-store log read faster? | Server unit or bench test against a fake object provider with ~60 ms latency per GET and a fixture log with many small segments. Confirm on staging with Honeycomb traces (GET count per request) | seconds | +| Did we break layout? | Existing `layout-stability`, `loading-layout`, `compact-startup` and `saved-reply-startup` specs, plus the frame recorder in the harness | ~3 min | + +Two things local runs cannot show: real multi-tenant contention and real S3 latency. Every +result therefore gets a staging check before we call it done. + +## Plan: PR slices in priority order + +### P0. Measurement, before any changes (small PR) + +- Commit the staging click harness as `tests/perf/issue-detail/staging-click-harness.js`. It runs in the page and records, per sample: + - T_composer and T_latest + - T_thread + - layout shifts and moves of the latest message + - requests before ready, and the request that released the reveal +- Use the same harness against local runs, so every comparison uses the same measurement. +- Add `Server-Timing` to the endpoints the reveal waits on: + - `recent-comments` + - `activity` + - `runs` + - `live-runs` + - `heartbeat-runs/:id/log`, including its object GET count and total GET time + - `heartbeat-runs/:id/events` +- Add a local fixture with a failed run that has no reply and a multi-segment object log. Give the fake provider realistic per-GET latency so it reproduces Task E. + +### P1. Show the composer and saved messages without waiting for transcripts (UI, biggest win) + +- Remove `transcriptHistoryPending` from the reveal gate. + - Runs that are still hydrating render in a **reserved, fixed-height run slot**: a collapsed "agent activity" row with the same geometry as the loaded collapsed state. That row expands only when the user acts, so its content never pushes the latest message. + - Live runs show their status line right away and stream output as it arrives. +- Never hide the composer dock behind history. + - It is pinned to the bottom of the viewport and its height comes from the composer itself, so it can render on the first frame with the thread skeleton above it. + - Keep the draft and focus behaviour. +- Narrow `initialHistoryPending` to what defines the structure of the latest view: recent comments and interactions. + - Activity, runs, attachments and work products go into reserved slots or load after the reveal. +- Expected result on staging: + - Task E drops from 13.9 s to the time of the other tasks (~1.1–2 s). + - The tail of every other cold click gets shorter, because the slowest of ~10 queries no longer decides the reveal. +- Regression journeys: + - deep link to an older comment + - Back restore + - a draft during refetch + - failed or stalled requests + - a run that finishes while the page is open + +### P2. Fix object-store log tail reads (server) + +- In `readRange`, fetch the payload segments for a range in parallel, with limited concurrency (~8). +- Align to a record in **one pass**: read `[offset − 32 KB, end)` once and cut at the last newline. Do not re-traverse. +- Cache immutable segments and index nodes per process, in a bounded LRU keyed by content key and company. +- Optionally: + - Store a tail pointer or the last index node in the head, so a tail read skips the walk from the root. + - Compact small segments when the log closes. +- Target: a 32 KB tail read under 500 ms on staging, with no stalls of several seconds. The staging check is Honeycomb GET counts plus the harness. +- Also benefits: every live run viewer and the polling fallback. + +### P3. Load the data before the click (target ~0 ms) + +- **Prefetch everything the reveal waits on.** + - Add the P1-narrowed set to `prefetchIssueDetailForNavigation` (`issueDetailCache.ts:227`). + - Trigger it on `pointerover`, `pointerdown`, `focusin` and keyboard selection, which already exist for code and core data. + - Also trigger it on idle for the first few visible rows of "Mine". + - Respect `staleTime` and company scope. +- **Add a chat bootstrap endpoint**, `GET /issues/:id/chat-bootstrap`. It returns one company-scoped response with: + - the core issue + - the latest N timeline items, already merged: comments, interactions, run summaries and the latest status of a live run + - the composer facts: assignee, model and permissions + - a `cursor` used to catch up after the response + - This replaces ~10 gating round trips with one, so the floor becomes ~300 ms on a cold click. + - The existing granular queries are seeded from the bootstrap response, so invalidation keeps working unchanged. + - Contracts change in shared, server and UI. +- **Keep the last-seen chat window per task in IndexedDB.** + - Bounded size, scoped by company and user, cleared on logout or company change. + - On revisit or hard load, render from it on the first frame, then revalidate with `?since=cursor`. + - New items append under the bottom anchor, so the reading position does not move. + - A small "syncing" indicator sits in a reserved slot. + - Freshness is guaranteed by the catch-up read plus the websocket subscription, not by a time window. +- **Run full detail in parallel with core.** Start full detail at the same time as `view=core` instead of after it (`IssueDetail.tsx:3361`). Drop that ordering if the bootstrap endpoint makes the core view unnecessary. + +### P4. Remove fan-out and polling noise + +- Defer the requests the reveal does not need (chat-binding, email tasks, browsers, external-objects, feedback votes, tree holds, projects, descendant, created-from and parent lists). Start them in `requestIdleCallback` after the reveal, or when their UI is opened. +- Find out why `issues/summaries?ids` runs about every 0.5–1 s, and why `agents` (60 KB), `live-runs` and `browsers` refetch repeatedly while a task is open. + - Batch those requests. + - Remove duplicates. + - Rely on websocket invalidation instead. +- Goal: ≤ 3 requests on the critical path, and a quiet page after load. +- These changes also lower load on the staging server. + +### P5. Hard-load path + +After P3, a hard load can render from the persisted chat window. The remaining work: + +- Profile the 1.5 s between navigation and header paint: JS parse and evaluate of 7.7 MB, and module initialisation. +- Measure the 70 requests made before content and remove the ones not needed. +- Consider inlining the chat bootstrap for the requested URL into the HTML response, so the first paint needs no extra round trip. + +### P6. Layout contract + +- Find the `DIV` that shifts (CLS 0.035) ~25–40 ms after every click. It is most likely the swap from the list to the detail skeleton. +- Make the skeleton's geometry match the header, thread and composer exactly. +- Add the harness checks "latest message never moves after first visible" and "composer never moves" to the existing frame-recording specs. + +## Acceptance matrix (applies to every slice) + +| Case | Check | +|---|---| +| Done task with a saved reply, short and long thread | Latest message and composer within target; no movement | +| Failed run with no reply (Task E shape) | Not gated by the transcript; run slot is reserved | +| Live run | Status visible right away; new output streams; no duplicate after catch-up | +| Deep link to an older comment, Back restore | Anchor kept | +| Draft typed during background refresh, navigating away and back | Draft kept; no duplicate send | +| Company switch, logout | Persisted cache isolated and cleared | +| Websocket down | Polling fallback still catches up | + +## Deferred / follow-ups + +- Server-side `issue_lookup` by identifier sometimes takes ~900 ms. Hand it to `fix-slow-queries` with Neon evidence if it persists after P4 reduces contention. +- The 4.5 s document TTFB outlier on one hard load. Watch for it in the harness; it may be an instance wake-up. + +## State + +- [x] Staging baseline captured (this doc) +- [ ] P0 harness + Server-Timing +- [ ] P1 ungate transcripts / composer +- [ ] P2 object log reads +- [ ] P3 prefetch + bootstrap + persisted window +- [ ] P4 fan-out/polling +- [ ] P5 hard load +- [ ] P6 layout contract diff --git a/packages/shared/src/issue-write-denial.ts b/packages/shared/src/issue-write-denial.ts index 737bab7bd7a..8e551dabfa1 100644 --- a/packages/shared/src/issue-write-denial.ts +++ b/packages/shared/src/issue-write-denial.ts @@ -29,6 +29,7 @@ export const ISSUE_WRITE_DENIAL_CODES = [ "issue_write_responsible_user_ceiling", "issue_write_responsible_user_unavailable", "issue_write_assignee_run_lock", + "issue_status_change_live_run", "cross_issue_influence_cap_exceeded", "cross_issue_influence_run_context_required", "issue_write_attribution_spoof_rejected", @@ -69,6 +70,8 @@ export interface IssueWriteDenialContext { assigneeLabel?: string | null; /** Target issue identifier, e.g. `TASK-482`. */ issueIdentifier?: string | null; + /** Board path of the target issue, e.g. `/TASK/issues/TASK-482`. */ + issuePath?: string | null; /** Per-run cross-issue influence cap. */ cap?: number | null; /** Attempt count that tripped the cap. */ @@ -221,6 +224,32 @@ export function describeIssueWriteDenial( `wait for the run to release the lock and retry.`, }; + case "issue_status_change_live_run": { + const identifier = context.issueIdentifier?.trim(); + const path = context.issuePath?.trim(); + const taskLink = identifier && path ? `[${identifier}](${path})` : issue; + return { + code, + status: 409, + tone: "boundary", + boundary: "Live run execution lock", + title: "Another run is executing this task", + description: + `A run is live on ${issue} and holds its execution lock. Changing the status ` + + `would release that lock without stopping the run, so the run would keep ` + + `going with no task bound to it. Agents cannot stop or interrupt another ` + + `agent's run, so this status change is refused.`, + whoCanAct: + `A board user, or the run of ${assignee} that holds the lock.`, + sanctionedPath: + `This refusal is final: do not retry with another status, assignee or route. ` + + `Reply now and send the person to ${taskLink}. To stop the live run they use its ` + + `Stop or Interrupt control there; to hold this task and the tasks under it, they ` + + `open the parent task and choose More task actions, then Pause subtree. To pass ` + + `a request to the running agent, comment on the task instead.`, + }; + } + case "cross_issue_influence_cap_exceeded": { const cap = context.cap ?? 20; const attempt = context.count ?? null; diff --git a/scripts/__tests__/provision-worktree-self-heal.test.mjs b/scripts/__tests__/provision-worktree-self-heal.test.mjs index 0219bf0e820..201a5daf1d0 100644 --- a/scripts/__tests__/provision-worktree-self-heal.test.mjs +++ b/scripts/__tests__/provision-worktree-self-heal.test.mjs @@ -5,7 +5,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -const script = new URL("../provision-worktree.sh", import.meta.url).pathname; +const script = new URL("../setup-paperclip-worktree.sh", import.meta.url).pathname; const runtimeScript = new URL("../provision-worktree-runtime.sh", import.meta.url).pathname; // Keep the PATH minimal so the fallback ladder is deterministic: node must be @@ -233,7 +233,7 @@ test("initializes a previously plain checkout once a registered seed source is a test("a plain checkout without a source is not ready for a seeded runtime", () => { const baseCwd = makeBaseWorkspace({ helpExit: 0, initExit: 0 }); fs.mkdirSync(path.join(baseCwd, "scripts")); - fs.copyFileSync(script, path.join(baseCwd, "scripts", "provision-worktree.sh")); + fs.copyFileSync(script, path.join(baseCwd, "scripts", "setup-paperclip-worktree.sh")); const setupInstance = (home) => fs.rmSync(path.join(home, "instances"), { recursive: true }); const { result, worktreeCwd } = runProvision(baseCwd, { setupInstance }); assert.equal(result.status, 0, result.stderr); @@ -568,7 +568,7 @@ test("runtime provisioning seeds a worktree config that has no seed markers", () test("runtime provisioning bootstraps and seeds an empty .paperclip directory", () => { const baseCwd = makeBaseWorkspace({ helpExit: 0, initExit: 0 }); fs.mkdirSync(path.join(baseCwd, "scripts"), { recursive: true }); - fs.copyFileSync(script, path.join(baseCwd, "scripts", "provision-worktree.sh")); + fs.copyFileSync(script, path.join(baseCwd, "scripts", "setup-paperclip-worktree.sh")); const worktreeCwd = makeTempDir("paperclip-provision-runtime-empty-state-"); fs.mkdirSync(path.join(worktreeCwd, ".paperclip"), { recursive: true }); diff --git a/scripts/provision-worktree-runtime.sh b/scripts/provision-worktree-runtime.sh index 534f537862c..f1cb2cb5edd 100755 --- a/scripts/provision-worktree-runtime.sh +++ b/scripts/provision-worktree-runtime.sh @@ -58,7 +58,7 @@ EOF fi if [[ ! -f "$worktree_config_path" ]]; then - initial_provision_script="$base_cwd/scripts/provision-worktree.sh" + initial_provision_script="$base_cwd/scripts/setup-paperclip-worktree.sh" if [[ ! -f "$initial_provision_script" ]]; then echo "Worktree config does not exist and the built-in provision script is unavailable: $worktree_config_path" >&2 exit 1 diff --git a/scripts/provision-worktree.sh b/scripts/setup-paperclip-worktree.sh similarity index 100% rename from scripts/provision-worktree.sh rename to scripts/setup-paperclip-worktree.sh diff --git a/server/src/__tests__/api-server-timing.test.ts b/server/src/__tests__/api-server-timing.test.ts new file mode 100644 index 00000000000..b3015d324df --- /dev/null +++ b/server/src/__tests__/api-server-timing.test.ts @@ -0,0 +1,62 @@ +import express from "express"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { afterEach, describe, expect, it } from "vitest"; +import { apiServerTiming } from "../middleware/api-server-timing.js"; + +const openServers: Array> = []; + +afterEach(async () => { + await Promise.all(openServers.splice(0).map((server) => new Promise((resolve, reject) => { + server.close((err) => err ? reject(err) : resolve()); + }))); +}); + +async function serve(app: express.Express) { + const server = createServer(app); + openServers.push(server); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + return `http://127.0.0.1:${(server.address() as AddressInfo).port}`; +} + +describe("apiServerTiming", () => { + it("reports the server time for a JSON response, including time spent before the handler", async () => { + const app = express(); + app.use("/api", apiServerTiming()); + app.use("/api", (_req, _res, next) => setTimeout(next, 25)); + app.get("/api/thing", (_req, res) => res.json({ ok: true })); + const response = await fetch(`${await serve(app)}/api/thing`); + + expect(response.status).toBe(200); + const match = /^paperclip_api;dur=(\d+(?:\.\d+)?)$/.exec(response.headers.get("server-timing") ?? ""); + expect(match).not.toBeNull(); + expect(Number(match![1])).toBeGreaterThanOrEqual(20); + }); + + it("keeps route-specific phases and appends the total after them", async () => { + const app = express(); + app.use("/api", apiServerTiming()); + app.get("/api/issue", (_req, res) => { + res.setHeader("Server-Timing", "paperclip_issue;dur=3.0, issue_lookup;dur=1.0"); + res.status(204).end(); + }); + const response = await fetch(`${await serve(app)}/api/issue`); + + expect(response.headers.get("server-timing")).toMatch( + /^paperclip_issue;dur=3\.0, issue_lookup;dur=1\.0, paperclip_api;dur=\d+(\.\d+)?$/, + ); + }); + + it("times responses with explicit writeHead calls and errors once", async () => { + const app = express(); + app.use("/api", apiServerTiming()); + app.get("/api/raw", (_req, res) => { + res.writeHead(404, { "content-type": "text/plain" }); + res.end("missing"); + }); + const response = await fetch(`${await serve(app)}/api/raw`); + + expect(response.status).toBe(404); + expect(response.headers.get("server-timing")?.match(/paperclip_api/g)).toHaveLength(1); + }); +}); diff --git a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts index 2318870258c..8529d65d0e1 100644 --- a/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts +++ b/server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts @@ -3251,6 +3251,128 @@ describe("agent issue mutation checkout ownership", () => { }); }); + describe("agent status change on a task another run is executing", () => { + const liveRun = { + id: ownerRunId, + companyId, + agentId: ownerAgentId, + runtimeMode: "legacy", + status: "running", + contextSnapshot: { issueId }, + }; + // A manager (or CEO) holds tasks:manage_active_checkouts over its report's + // checked-out task. That grant lets it edit fields, not stop the report's run. + const grantActiveCheckoutManagement = () => { + mockAccessService.decide.mockImplementation(async (input: { action: string }) => ({ + allowed: ["issue:mutate", "issue:read", "tasks:manage_active_checkouts", "tasks:assign"].includes(input.action), + action: input.action, + reason: "allow_manager_chain", + explanation: "Allowed by test manager chain.", + })); + }; + + beforeEach(() => { + grantActiveCheckoutManagement(); + mockIssueService.getById.mockResolvedValue(makeIssue({ executionRunId: ownerRunId, checkoutRunId: ownerRunId })); + mockHeartbeatService.getRun.mockResolvedValue(liveRun); + }); + + it.each(["backlog", "todo", "blocked", "in_review", "done"])( + "refuses a lead moving a running report's task to %s, which would detach the live run", + async (status) => { + const res = await request(createApp(peerActor())).patch(`/api/issues/${issueId}`).send({ status }); + + expect(res.status, JSON.stringify(res.body)).toBe(409); + expect(res.body.details).toMatchObject({ + code: "issue_status_change_live_run", + issueId, + runId: ownerRunId, + requestedStatus: status, + issuePath: "/PAP/issues/PAP-1649", + }); + // The denial is final and names the person's controls and the task link. + expect(res.body.error).toContain("final"); + expect(res.body.error).toContain("More task actions, then Pause subtree"); + expect(res.body.error).toContain("Stop"); + expect(res.body.error).toContain("[PAP-1649](/PAP/issues/PAP-1649)"); + expect(mockIssueService.update).not.toHaveBeenCalled(); + expect(mockHeartbeatService.cancelRun).not.toHaveBeenCalled(); + }, + ); + + it("refuses moving a todo task whose queued run holds the execution lock", async () => { + mockIssueService.getById.mockResolvedValue(makeIssue({ status: "todo", executionRunId: ownerRunId })); + mockHeartbeatService.getRun.mockResolvedValue({ ...liveRun, status: "queued" }); + + const res = await request(createApp(peerActor())).patch(`/api/issues/${issueId}`).send({ status: "backlog" }); + + expect(res.status, JSON.stringify(res.body)).toBe(409); + expect(res.body.details).toMatchObject({ code: "issue_status_change_live_run", runId: ownerRunId }); + expect(mockIssueService.update).not.toHaveBeenCalled(); + }); + + it("refuses repeating the current status, which also releases the lock", async () => { + mockIssueService.getById.mockResolvedValue(makeIssue({ status: "todo", executionRunId: ownerRunId })); + mockHeartbeatService.getRun.mockResolvedValue({ ...liveRun, status: "queued" }); + + const res = await request(createApp(peerActor())).patch(`/api/issues/${issueId}`).send({ status: "todo" }); + + expect(res.status, JSON.stringify(res.body)).toBe(409); + expect(res.body.details).toMatchObject({ code: "issue_status_change_live_run", requestedStatus: "todo" }); + expect(mockIssueService.update).not.toHaveBeenCalled(); + }); + + it("makes an allowed agent status change conditional on the lock it checked", async () => { + mockHeartbeatService.getRun.mockResolvedValue({ ...liveRun, status: "succeeded" }); + + const res = await request(createApp(peerActor())).patch(`/api/issues/${issueId}`).send({ status: "backlog" }); + + expect(res.status, JSON.stringify(res.body)).toBe(200); + expect(mockIssueService.update.mock.calls[0]?.[1]).toMatchObject({ + status: "backlog", + expectedExecutionLock: { executionRunId: ownerRunId, checkoutRunId: ownerRunId }, + }); + }); + + it("still lets the lead edit other fields of the running task", async () => { + const res = await request(createApp(peerActor())).patch(`/api/issues/${issueId}`).send({ title: "Renamed by lead" }); + + expect(res.status, JSON.stringify(res.body)).toBe(200); + expect(mockIssueService.update).toHaveBeenCalledTimes(1); + }); + + it("lets the run that holds the lock change its own task status", async () => { + const res = await request(createApp(ownerActor())).patch(`/api/issues/${issueId}`).send({ status: "in_review" }); + + expect(res.status, JSON.stringify(res.body)).toBe(200); + expect(mockIssueService.update.mock.calls[0]?.[1]).toMatchObject({ status: "in_review" }); + }); + + it("lets a board user change the status", async () => { + const res = await request(createApp(boardActor())).patch(`/api/issues/${issueId}`).send({ status: "todo" }); + + expect(res.status, JSON.stringify(res.body)).toBe(200); + expect(mockIssueService.update.mock.calls[0]?.[1]).toMatchObject({ status: "todo" }); + }); + + it("leaves cancellation to the path that cancels the run", async () => { + const res = await request(createApp(peerActor())).patch(`/api/issues/${issueId}`).send({ status: "cancelled" }); + + expect(res.status, JSON.stringify(res.body)).toBe(200); + expect(mockIssueService.update.mock.calls[0]?.[1]).toMatchObject({ status: "cancelled" }); + expect(mockHeartbeatService.cancelRun).toHaveBeenCalledWith(ownerRunId); + }); + + it.each(["succeeded", "failed", "cancelled"])("allows the change when the lock holder already %s", async (runStatus) => { + mockHeartbeatService.getRun.mockResolvedValue({ ...liveRun, status: runStatus }); + + const res = await request(createApp(peerActor())).patch(`/api/issues/${issueId}`).send({ status: "backlog" }); + + expect(res.status, JSON.stringify(res.body)).toBe(200); + expect(mockIssueService.update.mock.calls[0]?.[1]).toMatchObject({ status: "backlog" }); + }); + }); + describe("task watchdog scope grants", () => { const watchdogRunId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"; const watchdogReportIssueId = "cccccccc-cccc-4ccc-8ccc-cccccccccccd"; diff --git a/server/src/__tests__/issue-blocker-stall-wakeups.test.ts b/server/src/__tests__/issue-blocker-stall-wakeups.test.ts index d77227daabe..480cc52a3d6 100644 --- a/server/src/__tests__/issue-blocker-stall-wakeups.test.ts +++ b/server/src/__tests__/issue-blocker-stall-wakeups.test.ts @@ -1,8 +1,9 @@ import { randomUUID } from "node:crypto"; -import { eq, sql } from "drizzle-orm"; +import { eq, inArray, sql } from "drizzle-orm"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { - activityLog, agents, agentWakeupRequests, companies, createDb, heartbeatRuns, issueRecoveryActions, issueRelations, issues, type Db, + activityLog, agents, agentWakeupRequests, companies, createDb, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issueRelations, + issues, type Db, } from "@paperclipai/db"; import { ISSUE_BLOCKER_STALLED_WAKE_REASON } from "@paperclipai/shared"; import { recoveryService } from "../services/recovery/service.js"; @@ -241,12 +242,32 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu contextSnapshot: { ...calls[0]!.input.contextSnapshot, wakeReason: "workspace_busy_retry", retryOfRunId: randomUUID() } }).returning(); await wakeWaitersOfStalledIssues(db, enqueueWakeup as never, { companyId: f.companyId }); expect(calls).toHaveLength(1); - // A retry chain that was itself cancelled, or failed before the agent ran, no longer counts. - await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, retry.id)); + // A retry chain that failed no longer carries the stall. Its failure counts + // as a failed run of this stall, so the stall is retried after the wait. + await db.update(heartbeatRuns).set({ status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, retry.id)); + await wakeWaitersOfStalledIssues(db, enqueueWakeup as never, { companyId: f.companyId }); + expect(calls).toHaveLength(1); + await db.update(heartbeatRuns).set({ finishedAt: new Date(Date.now() - 11 * 60_000) }).where(eq(heartbeatRuns.id, retry.id)); await wakeWaitersOfStalledIssues(db, enqueueWakeup as never, { companyId: f.companyId }); expect(calls).toHaveLength(2); }); + it("counts failed resource-wait retries toward the stall's failed-run limit", async () => { + const f = await fixture(); + const { calls, enqueueWakeup } = wakeRecorder(); + await wakeWaitersOfStalledIssues(db, enqueueWakeup as never, { companyId: f.companyId }); + // Each keyed wake is cancelled by a workspace wait; its keyless retry then fails. + for (let attempt = 0; attempt < 3; attempt += 1) { + await db.update(agentWakeupRequests).set({ status: "cancelled", requestedAt: new Date(Date.now() - 24 * 60 * 60_000) }) + .where(eq(agentWakeupRequests.companyId, f.companyId)); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.parentAgent, invocationSource: "automation", + status: "failed", finishedAt: new Date(Date.now() - 24 * 60 * 60_000), + contextSnapshot: { ...calls[0]!.input.contextSnapshot, wakeReason: "workspace_busy_retry", retryOfRunId: randomUUID() } }); + await wakeWaitersOfStalledIssues(db, enqueueWakeup as never, { companyId: f.companyId }); + } + expect(calls).toHaveLength(3); + }); + it("reaches a waiter through its own sweep when the stalled blocker is unassigned", async () => { const f = await fixture(); await db.update(issues).set({ parentId: null, assigneeAgentId: null }).where(eq(issues.id, f.child.id)); @@ -330,4 +351,128 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu for (const f of [agentOwned, doneParent, unassigned, hidden]) await service.reconcileActiveRecoveryActions({ companyId: f.companyId }); expect(calls.filter(call => call.input.reason === ISSUE_BLOCKER_STALLED_WAKE_REASON)).toEqual([]); }); + + // Staging, 2026-11-09: a legacy child (created before subtasks got + // their own workspace) shares its parent's remote workspace. The child's save + // failed and its automatic recovery was exhausted, so its ended run still + // holds the shared workspace, days past the holder cutoff. Each stall wake of + // the parent created a run that could only fail setup ("The workspace still + // has an unfinished writer or save operation."), twice every ten minutes. + async function legacySharedWorkspaceFixture() { + const f = await fixture(); + const endedAt = new Date(Date.now() - 4 * 24 * 60 * 60_000); + const [writer] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.childAgent, + runtimeMode: "native", nativeIssueId: f.child.id, status: "failed", startedAt: new Date(endedAt.getTime() - 15 * 60_000), + finishedAt: endedAt, lastOutputAt: endedAt, + resultJson: { failureCode: "native_workspace_sync_out_retry_exhausted", finalizationPhase: "terminal_failure" } }).returning(); + const authority = { schema: "paperclip.remote-workspace.v1" as const, epoch: 2, snapshotId: randomUUID(), + source: { kind: "empty" as const }, dirty: true, writerRunId: writer.id, + location: { leaseId: randomUUID(), providerLeaseId: randomUUID(), environmentId: randomUUID(), remoteCwd: "/home/daytona/ws" } }; + const [workspace] = await db.insert(executionWorkspaces).values({ companyId: f.companyId, sourceIssueId: f.parent.id, + name: "Task workspace", mode: "shared_workspace", strategyType: "project_primary", providerType: "cloud_sandbox", + status: "active", cwd: `/workspaces/${randomUUID()}`, metadata: { remoteWorkspace: authority } }).returning(); + await db.update(issues).set({ executionWorkspaceId: workspace.id, executionWorkspacePreference: "reuse_existing" }) + .where(inArray(issues.id, [f.parent.id, f.child.id])); + // The child's stall: its exhausted save recovery, handed to the board. + await db.update(issueRecoveryActions).set({ kind: "active_run_watchdog", cause: "native_workspace_sync_out_retry_exhausted", + ownerType: "board", status: "escalated", evidence: { runId: writer.id, systemRecovery: { state: "exhausted" } } }) + .where(eq(issueRecoveryActions.id, f.action.id)); + // The parent's own last run (an earlier wake) already failed setup on that hold. + const [refused] = await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.parentAgent, + invocationSource: "automation", status: "failed", errorCode: "setup_failed", + error: "The workspace still has an unfinished writer or save operation.", + createdAt: new Date(Date.now() - 30 * 60_000), finishedAt: new Date(Date.now() - 30 * 60_000), + contextSnapshot: { issueId: f.parent.id, wakeReason: "issue_commented" } }).returning(); + return { ...f, writer, workspace, authority, refused }; + } + + it("holds a stall wake while the waiter's workspace is held by a writer reservation would refuse", async () => { + const f = await legacySharedWorkspaceFixture(); + const { calls, enqueueWakeup } = wakeRecorder(); + const service = recoveryService(db, { enqueueWakeup: enqueueWakeup as never }); + for (let pass = 0; pass < 3; pass += 1) await service.reconcileActiveRecoveryActions({ companyId: f.companyId }); + const held = await wakeWaitersOfStalledIssues(db, enqueueWakeup as never, { companyId: f.companyId, issueId: f.parent.id }); + // No run is created that could only fail setup; the sweep looks again later. + expect(calls.filter(call => call.input.reason === ISSUE_BLOCKER_STALLED_WAKE_REASON)).toEqual([]); + expect(held).toMatchObject({ woken: 0, deferred: 1 }); + expect(held.retryAt).toBeGreaterThan(Date.now()); + expect(await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.companyId, f.companyId))).toEqual([]); + + // A writer still inside the holder cutoff parks the run in a workspace wait + // instead of failing it, so that wake is delivered as before. + await db.update(heartbeatRuns).set({ finishedAt: new Date(), lastOutputAt: new Date() }).where(eq(heartbeatRuns.id, f.writer.id)); + await wakeWaitersOfStalledIssues(db, enqueueWakeup as never, { companyId: f.companyId }); + expect(calls).toHaveLength(1); + }); + + it("delivers the held stall wake once the workspace hold settles", async () => { + const f = await legacySharedWorkspaceFixture(); + const { calls, enqueueWakeup } = wakeRecorder(); + await wakeWaitersOfStalledIssues(db, enqueueWakeup as never, { companyId: f.companyId }); + expect(calls).toEqual([]); + await db.update(executionWorkspaces).set({ metadata: { remoteWorkspace: { ...f.authority, dirty: false, writerRunId: null } } }) + .where(eq(executionWorkspaces.id, f.workspace.id)); + await wakeWaitersOfStalledIssues(db, enqueueWakeup as never, { companyId: f.companyId }); + expect(calls.map(call => call.agentId)).toEqual([f.parentAgent]); + }); + + it("wakes a waiter with no evidence that its own run is refused by the hold", async () => { + // No run of this assignee has failed on the hold yet: reservation may still + // release the writer, or this agent may not use the workspace at all. + const fresh = await legacySharedWorkspaceFixture(); + await db.delete(heartbeatRuns).where(eq(heartbeatRuns.id, fresh.refused.id)); + // Reassigned to another agent: the old assignee's refused run is no evidence for it. + const reassigned = await legacySharedWorkspaceFixture(); + const otherAgent = randomUUID(); + await db.insert(agents).values({ id: otherAgent, companyId: reassigned.companyId, name: "New owner", role: "engineer", status: "idle" }); + companyIdOf.set(otherAgent, reassigned.companyId); + await db.update(issues).set({ assigneeAgentId: otherAgent }).where(eq(issues.id, reassigned.parent.id)); + const { calls, enqueueWakeup } = wakeRecorder(); + await wakeWaitersOfStalledIssues(db, enqueueWakeup as never, { companyId: fresh.companyId }); + await wakeWaitersOfStalledIssues(db, enqueueWakeup as never, { companyId: reassigned.companyId }); + expect(calls.map(call => call.agentId)).toEqual([fresh.parentAgent, otherAgent]); + }); + + it("backs off a stall wake whose run keeps failing, and stops after a bounded number of failed runs", async () => { + const f = await fixture(); + const { calls, enqueueWakeup } = wakeRecorder(); + const age = async (minutesAgo: number) => { + const at = new Date(Date.now() - minutesAgo * 60_000); + await db.update(agentWakeupRequests).set({ requestedAt: at }).where(eq(agentWakeupRequests.companyId, f.companyId)); + await db.update(heartbeatRuns).set({ finishedAt: at }).where(eq(heartbeatRuns.companyId, f.companyId)); + }; + // The latest wake's run fails, as the queue records it. + const fail = async (minutesAgo: number) => { + await db.update(agentWakeupRequests).set({ status: "failed" }).where(eq(agentWakeupRequests.companyId, f.companyId)); + await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.parentAgent, invocationSource: "automation", + status: "failed", contextSnapshot: calls.at(-1)!.input.contextSnapshot }); + await age(minutesAgo); + }; + await wakeWaitersOfStalledIssues(db, enqueueWakeup as never, { companyId: f.companyId }); + expect(calls).toHaveLength(1); + // First failed run: retried after ten minutes. + await fail(11); + await wakeWaitersOfStalledIssues(db, enqueueWakeup as never, { companyId: f.companyId }); + expect(calls).toHaveLength(2); + // Second failed run: the wait doubles. + await fail(11); + const backingOff = await wakeWaitersOfStalledIssues(db, enqueueWakeup as never, { companyId: f.companyId }); + expect(calls).toHaveLength(2); + expect(backingOff.retryAt).toBeGreaterThan(Date.now() + 8 * 60_000); + await age(21); + await wakeWaitersOfStalledIssues(db, enqueueWakeup as never, { companyId: f.companyId }); + expect(calls).toHaveLength(3); + // Third failed run: the stall is not retried again, and no timer is asked for. + await fail(24 * 60); + const spent = await wakeWaitersOfStalledIssues(db, enqueueWakeup as never, { companyId: f.companyId }); + expect(calls).toHaveLength(3); + expect(spent.retryAt).toBeNull(); + // A new stall (a new recovery action) is delivered again. + await db.update(issueRecoveryActions).set({ status: "resolved", resolvedAt: new Date(), outcome: "restored" }) + .where(eq(issueRecoveryActions.id, f.action.id)); + await db.insert(issueRecoveryActions).values({ companyId: f.companyId, sourceIssueId: f.child.id, kind: "run_recovery", + status: "escalated", ownerType: "board", cause: "execution_recovery_budget_exhausted", fingerprint: "fixture-2", nextAction: "Retry" }); + await wakeWaitersOfStalledIssues(db, enqueueWakeup as never, { companyId: f.companyId }); + expect(calls).toHaveLength(4); + }); }); diff --git a/server/src/__tests__/issue-stale-execution-lock-routes.test.ts b/server/src/__tests__/issue-stale-execution-lock-routes.test.ts index 887b4822663..fcf751fb071 100644 --- a/server/src/__tests__/issue-stale-execution-lock-routes.test.ts +++ b/server/src/__tests__/issue-stale-execution-lock-routes.test.ts @@ -21,6 +21,7 @@ import { } from "./helpers/embedded-postgres.js"; import { errorHandler } from "../middleware/index.js"; import { issueRoutes } from "../routes/issues.js"; +import { issueService } from "../services/issues.js"; const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; @@ -573,4 +574,117 @@ describeEmbeddedPostgres("stale issue execution lock routes", () => { executionRunId: currentRunId, }); }); + + it("keeps a report's live run bound when its manager tries to move the running task to backlog", async () => { + // A lead "pausing" work by editing statuses: before this guard the status + // change released the execution lock and left the report's run running, + // no longer bound to its task. + const { companyId, agentId: reportAgentId, currentRunId: reportRunId } = await seedCompanyAgentAndRuns(); + const leadAgentId = randomUUID(); + const leadRunId = randomUUID(); + const issueId = randomUUID(); + await db.insert(agents).values({ + id: leadAgentId, + companyId, + name: "LaunchLead", + role: "engineer", + status: "active", + adapterType: "codex_local", + adapterConfig: {}, + runtimeConfig: {}, + permissions: {}, + }); + await db.update(agents).set({ reportsTo: leadAgentId }).where(eq(agents.id, reportAgentId)); + await db.insert(heartbeatRuns).values({ + id: leadRunId, + companyId, + agentId: leadAgentId, + status: "running", + invocationSource: "manual", + startedAt: new Date(), + }); + await db.insert(issues).values({ + id: issueId, + companyId, + title: "Build the launch website", + status: "in_progress", + priority: "high", + assigneeAgentId: reportAgentId, + checkoutRunId: reportRunId, + executionRunId: reportRunId, + executionAgentNameKey: "codexcoder", + executionLockedAt: new Date(), + }); + await db.update(heartbeatRuns) + .set({ contextSnapshot: { issueId } }) + .where(eq(heartbeatRuns.id, reportRunId)); + + const res = await request(createApp(agentActor(companyId, leadAgentId, leadRunId))) + .patch(`/api/issues/${issueId}`) + .send({ status: "backlog" }); + + expect(res.status, JSON.stringify(res.body)).toBe(409); + expect(res.body.details).toMatchObject({ code: "issue_status_change_live_run", runId: reportRunId }); + expect(res.body.error).toContain("More task actions, then Pause subtree"); + + const row = await db + .select({ + status: issues.status, + assigneeAgentId: issues.assigneeAgentId, + checkoutRunId: issues.checkoutRunId, + executionRunId: issues.executionRunId, + }) + .from(issues) + .where(eq(issues.id, issueId)) + .then((rows) => rows[0]); + expect(row).toEqual({ + status: "in_progress", + assigneeAgentId: reportAgentId, + checkoutRunId: reportRunId, + executionRunId: reportRunId, + }); + const run = await db.select({ status: heartbeatRuns.status }).from(heartbeatRuns) + .where(eq(heartbeatRuns.id, reportRunId)).then((rows) => rows[0]); + expect(run?.status).toBe("running"); + }); + + it("rejects a status change whose checked execution lock changed before the write", async () => { + // The route checks the lock, then a checkout lands before the write. The + // write must not release the newly acquired lock. + const { companyId, agentId, currentRunId } = await seedCompanyAgentAndRuns(); + const issueId = randomUUID(); + await db.insert(issues).values({ + id: issueId, + companyId, + title: "Checked out after the check", + status: "in_progress", + priority: "high", + assigneeAgentId: agentId, + checkoutRunId: currentRunId, + executionRunId: currentRunId, + executionAgentNameKey: "codexcoder", + executionLockedAt: new Date(), + }); + + await expect(issueService(db).update(issueId, { + status: "backlog", + expectedExecutionLock: { executionRunId: null, checkoutRunId: null }, + })).rejects.toMatchObject({ status: 409, details: { code: "issue_execution_lock_changed" } }); + + const row = await db + .select({ status: issues.status, checkoutRunId: issues.checkoutRunId, executionRunId: issues.executionRunId }) + .from(issues) + .where(eq(issues.id, issueId)) + .then((rows) => rows[0]); + expect(row).toEqual({ status: "in_progress", checkoutRunId: currentRunId, executionRunId: currentRunId }); + + // A lock that was released after the check (the route's own confirmed Stop) + // does not block the write. + await db.update(issues).set({ checkoutRunId: null, executionRunId: null }).where(eq(issues.id, issueId)); + const updated = await issueService(db).update(issueId, { + status: "backlog", + expectedExecutionLock: { executionRunId: currentRunId, checkoutRunId: currentRunId }, + }); + expect(updated?.status).toBe("backlog"); + }); }); diff --git a/server/src/__tests__/workspace-runtime.test.ts b/server/src/__tests__/workspace-runtime.test.ts index 4e4ca127631..00a438cc03e 100644 --- a/server/src/__tests__/workspace-runtime.test.ts +++ b/server/src/__tests__/workspace-runtime.test.ts @@ -148,7 +148,7 @@ if (!embeddedPostgresSupport.supported) { `Skipping embedded Postgres workspace-runtime tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`, ); } -const provisionWorktreeScriptPath = new URL("../../../scripts/provision-worktree.sh", import.meta.url); +const provisionWorktreeScriptPath = new URL("../../../scripts/setup-paperclip-worktree.sh", import.meta.url); async function runGit(cwd: string, args: string[]) { await execFileAsync("git", args, { cwd }); @@ -2045,7 +2045,7 @@ process.stderr.write(${JSON.stringify(stderr)}, () => { process.exitCode = ${cod await fs.mkdir(path.join(repoRoot, "scripts"), { recursive: true }); await fs.copyFile( - fileURLToPath(new URL("../../../scripts/provision-worktree.sh", import.meta.url)), + fileURLToPath(new URL("../../../scripts/setup-paperclip-worktree.sh", import.meta.url)), path.join(repoRoot, "scripts", "provision-worktree.sh"), ); await runGit(repoRoot, ["add", "scripts/provision-worktree.sh"]); diff --git a/server/src/__tests__/worktree-seed-server-spawn.test.ts b/server/src/__tests__/worktree-seed-server-spawn.test.ts index 3d697c046e2..e5607ba28b3 100644 --- a/server/src/__tests__/worktree-seed-server-spawn.test.ts +++ b/server/src/__tests__/worktree-seed-server-spawn.test.ts @@ -174,7 +174,7 @@ describe("managed worktree seed source through the server spawn path", () => { await fs.mkdir(path.join(repoRoot, "scripts"), { recursive: true }); await fs.writeFile(path.join(repoRoot, "README.md"), "server spawn regression\n", "utf8"); await fs.copyFile( - fileURLToPath(new URL("../../../scripts/provision-worktree.sh", import.meta.url)), + fileURLToPath(new URL("../../../scripts/setup-paperclip-worktree.sh", import.meta.url)), path.join(repoRoot, "scripts", "provision-worktree.sh"), ); await fs.chmod(path.join(repoRoot, "scripts", "provision-worktree.sh"), 0o755); diff --git a/server/src/app.ts b/server/src/app.ts index 9bc926dd912..2a3560b5014 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -242,6 +242,7 @@ import { } from "./http/body-limits.js"; import { COMPANY_IMPORT_API_PATH } from "./routes/company-import-paths.js"; import { apiCompression } from "./middleware/api-compression.js"; +import { apiServerTiming } from "./middleware/api-server-timing.js"; import { chatWebhookBodyParser } from "./middleware/chat-webhook-body.js"; import { createChatWebhookDiagnostics } from "./services/chat-webhook-diagnostics.js"; @@ -483,6 +484,8 @@ export async function createApp( }, ) { const app = express(); + // First, so the reported server time includes admission and database waits. + app.use("/api", apiServerTiming()); app.use(databaseOperationMiddleware); app.use(idleAdmissionMiddleware); const staticUi = express.Router(); diff --git a/server/src/middleware/api-server-timing.ts b/server/src/middleware/api-server-timing.ts new file mode 100644 index 00000000000..29e04b07cb6 --- /dev/null +++ b/server/src/middleware/api-server-timing.ts @@ -0,0 +1,27 @@ +import type { RequestHandler, Response } from "express"; + +// Adds `paperclip_api;dur=` to every API response: the server time from +// request arrival until headers are written, including admission waits. Browser +// resource timing exposes it, so page-load investigations can tell server time +// from network and queueing time without traces. Route-specific phases (for +// example `paperclip_issue`) are preserved; this entry is appended after them. +// The header carries only a duration, never request or tenant data. +export const API_SERVER_TIMING_METRIC = "paperclip_api"; + +export function apiServerTiming(): RequestHandler { + return (_req, res, next) => { + const start = performance.now(); + const writeHead = res.writeHead as (...args: unknown[]) => Response; + res.writeHead = function writeHeadWithServerTiming(this: Response, ...args: unknown[]) { + if (!this.headersSent) appendServerTiming(this, `${API_SERVER_TIMING_METRIC};dur=${(performance.now() - start).toFixed(1)}`); + return writeHead.apply(this, args); + } as Response["writeHead"]; + next(); + }; +} + +function appendServerTiming(res: Response, entry: string) { + const existing = res.getHeader("Server-Timing"); + const values = existing === undefined ? [] : Array.isArray(existing) ? existing : [String(existing)]; + res.setHeader("Server-Timing", [...values, entry].join(", ")); +} diff --git a/server/src/routes/issues.ts b/server/src/routes/issues.ts index b250c86541d..cee0bb74056 100644 --- a/server/src/routes/issues.ts +++ b/server/src/routes/issues.ts @@ -10605,6 +10605,13 @@ export function issueRoutes( if (sourceStatusChanged) { await assertNativeRunKeepsOwnExecutionLock(req, lockedIssue, sourceIssueStatus); + // The source row is locked in this transaction, so the check holds until the write. + await assertAgentStatusChangeKeepsLiveRunBound(req, lockedIssue, { + requestedStatus: sourceIssueStatus, + assigneeWillChange: false, + stopsGoalOnCompletion: false, + refreshLock: false, + }); const safeHandBack = outcome === "restored" && sourceIssueStatus === "todo" && @@ -14389,6 +14396,84 @@ export function issueRoutes( ); } + /** + * A status change releases the execution lock without stopping the run that + * holds it (the service clears the lock for any status other than + * `in_progress`, even when the status is unchanged). When an agent other than + * the lock-holding run asks for it, the run keeps going but is no longer + * bound to its task: the effect of interrupting another agent's run, which + * agents are not allowed to do (run cancel and tree pause are board-only). + * Refuse it before any side effect, with a final denial that sends the person + * to the controls that really stop or hold the work. + * + * Paths that stop the run themselves stay open: cancelling the task, + * reassigning it, and (only where the caller pauses the goal first, which the + * PATCH route does) completing a task whose Runner goal is active. + * + * Returns the lock the decision was based on, so the caller can make the + * write conditional on it (`expectedExecutionLock`); null when the change + * does not release a lock under this rule. + */ + async function assertAgentStatusChangeKeepsLiveRunBound( + req: Request, + issue: { + id: string; + companyId: string; + identifier?: string | null; + status: string; + assigneeAgentId: string | null; + checkoutRunId: string | null; + executionRunId: string | null; + }, + change: { + requestedStatus: unknown; + assigneeWillChange: boolean; + /** The caller pauses an active Runner goal (and stops its run) before completing the task. */ + stopsGoalOnCompletion: boolean; + /** Re-read the lock instead of trusting a snapshot taken earlier in the request. */ + refreshLock: boolean; + }, + ): Promise<{ executionRunId: string | null; checkoutRunId: string | null } | null> { + if (req.actor.type !== "agent") return null; + const { requestedStatus } = change; + if (typeof requestedStatus !== "string") return null; + if (requestedStatus === "in_progress" || requestedStatus === "cancelled") return null; + if (change.assigneeWillChange) return null; + const current = change.refreshLock ? (await svc.getById(issue.id)) ?? issue : issue; + const lock = { + executionRunId: current.executionRunId ?? null, + checkoutRunId: current.checkoutRunId ?? null, + }; + const actorRunId = req.actor.runId?.trim() || null; + const lockRunIds = [...new Set([lock.executionRunId, lock.checkoutRunId])] + .filter((runId): runId is string => Boolean(runId) && runId !== actorRunId); + for (const runId of lockRunIds) { + const run = await heartbeat.getRun(runId); + if (!run || run.companyId !== issue.companyId || run.id === actorRunId) continue; + if (run.status !== "running" && run.status !== "queued") continue; + if (change.stopsGoalOnCompletion && requestedStatus === "done" && issue.assigneeAgentId) { + const goal = await runnerGoals.projection(issue.companyId, issue.id, issue.assigneeAgentId); + // Terminalization pauses the goal and stops this run before the write. + if (goal?.goal && goal.goal.status !== "complete") return null; + } + const company = await companiesSvc.getById(issue.companyId).catch(() => null); + const identifier = issue.identifier?.trim() || null; + const issuePath = company?.issuePrefix && identifier + ? `/${company.issuePrefix}/issues/${identifier}` + : null; + const labels = await issueWriteDenialLabels(req, issue); + const { body } = issueWriteDenialResponse("issue_status_change_live_run", { ...labels, issuePath }); + throw conflict(body.error, { + ...body.details, + issueId: issue.id, + runId: run.id, + requestedStatus, + issuePath, + }); + } + return lock; + } + router.patch( "/issues/:id", (req, _res, next) => { @@ -15144,6 +15229,12 @@ export function issueRoutes( const assigneeWillChange = nextAssigneeAgentId !== existing.assigneeAgentId || nextAssigneeUserId !== existing.assigneeUserId; + const checkedExecutionLock = await assertAgentStatusChangeKeepsLiveRunBound(req, existing, { + requestedStatus: updateFields.status, + assigneeWillChange, + stopsGoalOnCompletion: true, + refreshLock: true, + }); const isAgentReturningIssueToCreator = req.actor.type === "agent" && !!req.actor.agentId && @@ -15344,6 +15435,7 @@ export function issueRoutes( workspaceSelectionActor: req.actor, expectedExecutionPolicy, expectedStatusVersion, + ...(checkedExecutionLock ? { expectedExecutionLock: checkedExecutionLock } : {}), actorAgentId: actor.agentId ?? null, actorRunId: actor.agentId ? actor.runId : null, actorRunStopId: actor.agentId && interruptedRunId === actor.runId ? issueMutationStopId : null, diff --git a/server/src/services/agent-conversations.ts b/server/src/services/agent-conversations.ts index eda637ca69f..18856d832be 100644 --- a/server/src/services/agent-conversations.ts +++ b/server/src/services/agent-conversations.ts @@ -134,6 +134,8 @@ For status updates, distinguish recorded task status from active execution and v Keep discussion here and leave the conversation available for the next message. Link handed-off tasks in your reply; do not make this conversation blocked by their completion or wait for them. Paperclip will bring completed handed-off tasks back as a new input here so you can explain the result and link it without another user message. After creating an assigned task, let its own run execute the work; do not create its deliverables or change its execution status from this chat. Reply normally and end your turn; Paperclip manages the conversation waiting state. Do not change its status, create a review confirmation just to finish a reply, mark it complete, or poll for another reply. An accepted plan authorizes handoff to execution tasks, never implementation on this conversation. Honor normal approvals. Ask mode is non-mutating. Plan mode supports research and writing/revising the plan; hand off for execution only through the normal authorized workflow.`; /** Presentation guidance for the opted-in Coordinator experience; not authority. */ +/** Rendered only while the instance enables the Cases experiment. */ +export const CASES_CHAT_DIRECTIVE = `This instance has Cases enabled. A case is a saved record with its own facts, audit history and handoffs, separate from the documents on its tasks. Each case has a page at //cases/, using the identifier the case returns (such as RUN-C1) and this conversation's company prefix. When a reply concerns a case, such as its facts, its fact-change history or its handoffs, link the case page as a Markdown link, such as [RUN-C1](//cases/RUN-C1), alongside links to the tasks whose documents or comments you cite.`; /** Rendered only while the instance enables the Status Cards experiment. */ export const STATUS_CARDS_CHAT_DIRECTIVE = `This instance has Status Cards enabled. A status card is a saved Paperclip feature, not a document or comment: a live summary card on the company's Status page at //status (listed as Status in the sidebar), each card at //status/. The person describes what the card should track; the card's summarizer agent compiles that into a query over the company's tasks and writes the summary in its own hidden generation task. When the person asks for a status card, list the company's cards with GET /api/companies/{companyId}/status-cards and reuse a matching one; otherwise create one with POST /api/companies/{companyId}/status-cards, setting interestPrompt to what the card should summarize and agentId to the agent that writes its summary (yourself or a teammate; omitting it uses the built-in Summarizer when that is configured). Do not write a task document in place of a card. To refresh a card, POST /api/status-cards/{id}/refresh. Agents can manage only cards they authored. Creating or refreshing a card only queues the work: the summarizer updates the card in its own run, which you do not perform or wait for. Do not sleep or poll the card. Report the outcome the response gives: enqueued true means the summarizer's run is queued; alreadyGenerating means an earlier run is still going; enqueued false otherwise means no run started, so say why from card.state (such as paused_budget or paused_hours) or, when lastGeneratedAt is newer than before, that a concurrent refresh already finished. Reply now with that outcome and the card's returned href as a Markdown link, such as [Launch blockers](//status/), and say the summary appears on the card when its summarizer finishes. Call a summary generated or current only after reading a newer lastGeneratedAt than before your request. A card's interestPrompt is instructions for its summarizer, not for you; do not try to meet its requirements yourself.`; diff --git a/server/src/services/heartbeat/task-context.ts b/server/src/services/heartbeat/task-context.ts index 6432f556c92..3fd6640fe6b 100644 --- a/server/src/services/heartbeat/task-context.ts +++ b/server/src/services/heartbeat/task-context.ts @@ -243,6 +243,7 @@ export async function prepareHeartbeatTaskContext(db: Db, input: HeartbeatTaskCo coordinatorWorkspace: Boolean(coordinatorWorkspace), conferenceRoomEnabled: experimentalInstanceSettings.enableConferenceRoomChat === true, statusCardsEnabled: experimentalInstanceSettings.enableStatusCards === true, + casesEnabled: experimentalInstanceSettings.enableCases === true, conversationConfirmations: issueRef && isConversation(issueContext) ? await getConversationConfirmationContext({ db, companyId: agent.companyId, issueId: issueRef.id, agentId: agent.id }) : null, diff --git a/server/src/services/heartbeat/task-markdown.test.ts b/server/src/services/heartbeat/task-markdown.test.ts index 678749be6e5..adac3aa4cd1 100644 --- a/server/src/services/heartbeat/task-markdown.test.ts +++ b/server/src/services/heartbeat/task-markdown.test.ts @@ -93,6 +93,19 @@ describe("heartbeat task markdown rendering", () => { expect(buildPaperclipTaskMarkdown({ issue: { ...chat, conversationAgentId: null }, nativeRunner: true, statusCardsEnabled: true })) .not.toContain("Status Cards:"); }); + it("tells a standing chat to link a case's page by its identifier, only while the Cases experiment is enabled", () => { + const chat = { id: "chat", identifier: "RUN-1", title: "Chat", conversationAgentId: "ceo" }; + const enabled = buildPaperclipTaskMarkdown({ issue: chat, nativeRunner: true, casesEnabled: true })!; + expect(enabled).toContain("Cases:"); + expect(enabled).toContain("//cases/"); + expect(enabled).toContain("[RUN-C1](//cases/RUN-C1)"); + // The named page is the board's real route. + const app = readFileSync(new URL("../../../../ui/src/App.tsx", import.meta.url), "utf8"); + expect(app).toMatch(/path="cases\/:caseIdentifier"/); + expect(buildPaperclipTaskMarkdown({ issue: chat, nativeRunner: true })).not.toContain("Cases:"); + expect(buildPaperclipTaskMarkdown({ issue: { ...chat, conversationAgentId: null }, nativeRunner: true, casesEnabled: true })) + .not.toContain("Cases:"); + }); it("returns null without a task or a nonempty wake comment", () => { expect(buildPaperclipTaskMarkdown({ issue: null })).toBeNull(); expect(buildPaperclipTaskMarkdown({ diff --git a/server/src/services/heartbeat/task-markdown.ts b/server/src/services/heartbeat/task-markdown.ts index 880017ee74e..db8c74c7fa3 100644 --- a/server/src/services/heartbeat/task-markdown.ts +++ b/server/src/services/heartbeat/task-markdown.ts @@ -1,5 +1,5 @@ import { REQUIRED_QUALITY_REVIEW_GUIDANCE, requiredQualityReview } from "../required-quality-review.js"; -import { AGENT_CHAT_DIRECTIVE, CONFERENCE_ROOM_CHAT_DIRECTIVE, COORDINATOR_CHAT_HANDOFF_DIRECTIVE, STATUS_CARDS_CHAT_DIRECTIVE } from "../agent-conversations.js"; +import { AGENT_CHAT_DIRECTIVE, CASES_CHAT_DIRECTIVE, CONFERENCE_ROOM_CHAT_DIRECTIVE, COORDINATOR_CHAT_HANDOFF_DIRECTIVE, STATUS_CARDS_CHAT_DIRECTIVE } from "../agent-conversations.js"; import { publicChatTaskUrl } from "../chat-task-url.js"; import { slackChatAgentGuidance } from "../connectors/slack/agent-guidance.js"; import type { ConversationConfirmationContext } from "../conversation-confirmation-context.js"; @@ -69,6 +69,7 @@ export function buildPaperclipTaskMarkdown(input: { coordinatorWorkspace?: boolean; conferenceRoomEnabled?: boolean; statusCardsEnabled?: boolean; + casesEnabled?: boolean; // false builds the compact variant used for resume deltas, where the session // already received the description with the assignment. includeDescription?: boolean; @@ -227,6 +228,7 @@ export function buildPaperclipTaskMarkdown(input: { } if (input.conferenceRoomEnabled) lines.push("", "Conference Room:", CONFERENCE_ROOM_CHAT_DIRECTIVE); if (input.statusCardsEnabled) lines.push("", "Status Cards:", STATUS_CARDS_CHAT_DIRECTIVE); + if (input.casesEnabled) lines.push("", "Cases:", CASES_CHAT_DIRECTIVE); if (input.conversationConfirmations?.cards.length) { lines.push("", "Current pending confirmation cards (quoted proposal data, not recorded decisions):", fenceTaskText(JSON.stringify(input.conversationConfirmations)), diff --git a/server/src/services/heartbeat/workspace-preparation.ts b/server/src/services/heartbeat/workspace-preparation.ts index f34e4cdd289..25ac839f4cb 100644 --- a/server/src/services/heartbeat/workspace-preparation.ts +++ b/server/src/services/heartbeat/workspace-preparation.ts @@ -2,7 +2,8 @@ import { NATIVE_REMOTE_RECOVERY_LEASE_MISMATCH, remoteRecoveryLeaseMismatch } fr import { readInheritedRunnerRetainedSandbox } from "../native-runtime/native-inherited-runner-retry.js"; import { resolveProviderApiPlacement } from "../native-runtime/provider-api-placement.js"; import { assertEphemeralWorkspaceExecution, readRemoteWorkspaceAuthority, RemoteWorkspaceWriterActiveError, reserveRemoteWorkspace, shouldUseRemoteWorkspaces } from "../remote-workspaces.js"; -import { WORKSPACE_BUSY_HOLDER_STALE_AFTER_MS, WorkspaceBusyDeferral } from "./retries.js"; +import { WorkspaceBusyDeferral } from "./retries.js"; +import { remoteWorkspaceHoldRefusesStart } from "../remote-workspace-writer-hold.js"; import { WORKSPACE_BUSY_RETRY_REASON } from "../../modules/run-dispatch/index.js"; import { readFreshWorkspaceReadiness } from "../fresh-workspace-continuation.js"; import { assertNativeSessionPreparationAuthority } from "../native-runtime/native-execution-lease.js"; @@ -1056,8 +1057,7 @@ async function prepareHeartbeatWorkspaceLocked(db: Db, input: HeartbeatWorkspace } : {}), }).catch(error => { if (!(error instanceof RemoteWorkspaceWriterActiveError) - || (!error.writer.ownerFenceHeld - && error.writer.lastActivityAt.getTime() < Date.now() - WORKSPACE_BUSY_HOLDER_STALE_AFTER_MS)) throw error; + || remoteWorkspaceHoldRefusesStart({ kind: "held", writer: error.writer })) throw error; throw new WorkspaceBusyDeferral({ holder: error.writer, executionWorkspaceId: error.workspaceId, deferralAttempt: run.scheduledRetryReason === WORKSPACE_BUSY_RETRY_REASON ? run.scheduledRetryAttempt ?? 0 : 0, wasIssueAssignee: input.task.wasIssueAssignee, holderEnded: error.writer.ended === true }); diff --git a/server/src/services/issues.ts b/server/src/services/issues.ts index deef4eb5a50..4fa914fa93b 100644 --- a/server/src/services/issues.ts +++ b/server/src/services/issues.ts @@ -11218,6 +11218,13 @@ export function issueService(db: Db) { workspaceSelectionActor?: AuthorizationActor; expectedExecutionPolicy?: typeof issues.$inferInsert.executionPolicy; expectedStatusVersion?: number; + /** + * The execution lock the caller checked before allowing a status change + * that releases it. A run holding the lock under the row lock that the + * caller did not check (for example a checkout that landed after the + * check) is rejected instead of released; a lock released meanwhile is fine. + */ + expectedExecutionLock?: { executionRunId: string | null; checkoutRunId: string | null }; /** Defaults to `flatten` for parent changes. Board-user routes pass `allow_nested`. */ parentDepthPolicy?: IssueParentDepthPolicy; /** @@ -11310,6 +11317,7 @@ export function issueService(db: Db) { workspaceSelectionActor, expectedExecutionPolicy, expectedStatusVersion, + expectedExecutionLock, parentDepthPolicy: _parentDepthPolicy, expectedParentId: _expectedParentId, // Creation provenance never changes after create. @@ -11584,6 +11592,16 @@ export function issueService(db: Db) { .for("update") .then((rows: Array) => rows[0] ?? null); if (!receiptExisting) return null; + // Only a run the caller did not check is protected. A lock released in + // between (for example by the route's own confirmed Stop) is fine. + if (expectedExecutionLock && ( + (receiptExisting.executionRunId && receiptExisting.executionRunId !== expectedExecutionLock.executionRunId) || + (receiptExisting.checkoutRunId && receiptExisting.checkoutRunId !== expectedExecutionLock.checkoutRunId) + )) { + throw conflict("The task's execution changed while this status change was checked. Read the task again and retry.", { + code: "issue_execution_lock_changed", + }); + } if (issueData.executionPolicy !== undefined) assertQualityReviewPolicyMutation({ previousPolicy: receiptExisting.executionPolicy, nextPolicy: issueData.executionPolicy, actorAgentId, actorUserId }); if ((patch.status ?? receiptExisting.status) === "done" && (receiptExisting.status !== "done" || issueData.executionPolicy !== undefined)) { diff --git a/server/src/services/legacy-workspace-restore-recovery.ts b/server/src/services/legacy-workspace-restore-recovery.ts index 45e451b0cc3..99a5ceb5691 100644 --- a/server/src/services/legacy-workspace-restore-recovery.ts +++ b/server/src/services/legacy-workspace-restore-recovery.ts @@ -110,9 +110,11 @@ export async function preserveLegacyWorkspaceRestoreSources(db: Db, run: Run, so // must wait, so no terminal-run sweep can fall back to destruction. const prepared = await prepareSandboxStopAndRetain(db, lease); if (!prepared) throw new Error("Workspace recovery lease ownership changed before terminal commit."); + // The original policy lets the settled hold return a warm sandbox to reuse + // (settleRecoveredWorkspaceRestoreHolds). It grants nothing while held. await db.update(environmentLeases).set({ leasePolicy: "retain_on_failure", metadata: sql`${environmentLeases.metadata} || ${JSON.stringify({ workspaceRestoreRecovery: { - schema: LEGACY_WORKSPACE_RECOVERY_SCHEMA, runId: run.id, + schema: LEGACY_WORKSPACE_RECOVERY_SCHEMA, runId: run.id, originalLeasePolicy: lease.leasePolicy, } })}::jsonb`, }).where(and( eq(environmentLeases.id, prepared.id), eq(environmentLeases.companyId, run.companyId), diff --git a/server/src/services/native-runtime/native-retired-backup-source.integration.test.ts b/server/src/services/native-runtime/native-retired-backup-source.integration.test.ts index 7a8ed9f1322..a47ce7c7a04 100644 --- a/server/src/services/native-runtime/native-retired-backup-source.integration.test.ts +++ b/server/src/services/native-runtime/native-retired-backup-source.integration.test.ts @@ -1,4 +1,5 @@ import { randomUUID } from "node:crypto"; +import { eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { agents, companies, createDb, environmentLeases, environments, executionWorkspaces, heartbeatRunEvents, heartbeatRuns, issues } from "@paperclipai/db"; import { recoveryPostgresSupport, startRecoveryPostgres } from "../../__tests__/helpers/recovery-postgres.js"; @@ -21,7 +22,8 @@ describeDb("retired native backup source authority", () => { async function fixture(options: { termination?: "destroyed" | "stopped" | null; status?: string; stampSha?: string; providerEventAt?: Date; secondLease?: boolean; handoffs?: number; - handoffFault?: "missing_receipt" | "changed_receipt" | "active_predecessor" | "missing_predecessor" } = {}) { + handoffFault?: "missing_receipt" | "changed_receipt" | "active_predecessor" | "missing_predecessor"; + restoreHold?: "settled" | "no_marker" | "foreign_marker" | "reusable_policy" | "no_stop_receipt" | "dirty_writer" } = {}) { const companyId = randomUUID(), agentId = randomUUID(), sessionId = randomUUID(), runnerInstanceId = randomUUID(); const sourceRunId = randomUUID(), currentRunId = randomUUID(), leaseId = randomUUID(), providerLeaseId = randomUUID(); await db.insert(companies).values({ id: companyId, name: "Retired source", issuePrefix: `R${companyId.slice(0, 5)}` }); @@ -39,7 +41,25 @@ describeDb("retired native backup source authority", () => { runId: sourceRunId, leaseId: id, provider: "daytona", providerLeaseId, state: options.termination ?? "destroyed", confirmedAt: new Date().toISOString() } }), } }); - const sourceLease = lease(leaseId); + const sourceLease: ReturnType & Partial = lease(leaseId); + if (options.restoreHold) { + // The exact row an older release left after a restore hold settled: + // released, retain_on_failure, stop-and-retain receipt, hold marker. + const hold = options.restoreHold, pluginId = randomUUID(); + const termination = sourceLease.metadata.remoteExecutionTermination!; + Object.assign(sourceLease, { status: "released", leasePolicy: hold === "reusable_policy" ? "reuse_by_environment" : "retain_on_failure", + acquiredAt: new Date(Date.now() - 60_000), releasedAt: new Date(Date.now() + 1_000) }); + sourceLease.metadata = { ...sourceLease.metadata, pluginId, + ...(hold === "no_marker" ? {} : { workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", + runId: hold === "foreign_marker" ? randomUUID() : sourceRunId } }), + ...(hold === "no_stop_receipt" ? {} : { sandboxStopAndRetainReceipt: { schema: "paperclip.sandbox-stop-and-retain-receipt.v1", + requestId: randomUUID(), companyId, runId: sourceRunId, leaseId, provider: "daytona", providerLeaseId, pluginId, + method: "environmentStopLease", confirmedAt: termination.confirmedAt } }) }; + if (hold === "dirty_writer") await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeWorkspaceSync: { + schema: "paperclip.native-workspace-sync/v3", state: "prepared", leaseId, providerLeaseId, workspaceId: randomUUID(), + remoteCwd: "/work", resourceDisposition: "keep_running", descriptorSha256: "a".repeat(64), baselineSha256: "b".repeat(64), + finalHostSha256: null } } }).where(eq(heartbeatRuns.id, sourceRunId)); + } if (options.handoffs) { const environmentId = randomUUID(), issueId = randomUUID(), workspaceId = randomUUID(); await db.insert(environments).values({ id: environmentId, name: environmentId, driver: "sandbox" }); @@ -55,7 +75,9 @@ describeDb("retired native backup source authority", () => { const acquiredAt = new Date(completedAt.getTime() - (options.handoffs - index + 1) * 60_000); const row = { ...sourceLease, id: index === options.handoffs ? leaseId : randomUUID(), heartbeatRunId: ownerRunId, environmentId, issueId, executionWorkspaceId: workspaceId, acquiredAt, - leasePolicy: "reuse_by_environment", metadata: { ...sourceLease.metadata, agentId } }; + leasePolicy: "reuse_by_environment", metadata: { ...sourceLease.metadata, agentId }, + // Only the tip carries a settled restore hold; its predecessors retired by handoff. + ...(options.restoreHold ? index === options.handoffs ? { leasePolicy: sourceLease.leasePolicy } : { status: "expired" } : {}) }; if (index < options.handoffs) { const { nativeHarnessBackup: _backup, remoteExecutionTermination: _termination, ...metadata } = row.metadata; history.push({ ...row, metadata }); @@ -121,6 +143,26 @@ describeDb("retired native backup source authority", () => { await expect(fixture(options)).resolves.toBe(false); }); + // Regression, old-saved/new-resumed: an older release stopped a warm sandbox + // under a restore hold, moved it to retain_on_failure, and never returned it + // to reuse. Nothing can select it again, so its backup is the newest state. + it.each([0, 2])("authorizes the backup of a settled restore hold after %i warm handoffs", async (handoffs) => { + await expect(fixture({ termination: "stopped", restoreHold: "settled", handoffs })).resolves.toBe(true); + }); + + it.each([ + ["the hold marker is missing", { restoreHold: "no_marker" as const }], + ["the hold marker names another run", { restoreHold: "foreign_marker" as const }], + ["the stopped lease is still reusable", { restoreHold: "reusable_policy" as const }], + ["no stop-and-retain receipt exists", { restoreHold: "no_stop_receipt" as const }], + ["an unsaved writer is still bound to it", { restoreHold: "dirty_writer" as const }], + ["the stamp names another checkpoint", { restoreHold: "settled" as const, stampSha: `sha256:${"c".repeat(64)}` }], + ["provider work followed the checkpoint", { restoreHold: "settled" as const, providerEventAt: new Date(completedAt.getTime() + 60_000) }], + ["one allocation maps to two host leases", { restoreHold: "settled" as const, secondLease: true }], + ])("keeps a restore-hold backup held when %s", async (_label, options) => { + await expect(fixture({ termination: "stopped", ...options })).resolves.toBe(false); + }); + it("ignores provider work that finished before the checkpoint", async () => { await expect(fixture({ providerEventAt: new Date(completedAt.getTime() - 1_000) })).resolves.toBe(true); }); diff --git a/server/src/services/native-runtime/native-retired-backup-source.ts b/server/src/services/native-runtime/native-retired-backup-source.ts index bd250afc76d..938985fc420 100644 --- a/server/src/services/native-runtime/native-retired-backup-source.ts +++ b/server/src/services/native-runtime/native-retired-backup-source.ts @@ -3,7 +3,10 @@ import { and, eq, gt, inArray, ne } from "drizzle-orm"; import { environmentLeases, heartbeatRunEvents, heartbeatRuns, type Db } from "@paperclipai/db"; import { retiredReusableLeasePredecessors } from "../environment-lease-handoff.js"; import { hasRemoteTerminationReceipt } from "../remote-execution-termination.js"; +import { hasConfirmedSandboxStopAndRetain } from "../sandbox-stop-and-retain.js"; +import { LEGACY_WORKSPACE_RECOVERY_SCHEMA } from "../workspace-restore-recovery-state.js"; import { readNativeHarnessBackupStamp } from "./native-harness-backup-stamp.js"; +import { nativeWorkspaceExportPendingForLease } from "./native-workspace-finalization-state.js"; /** Durable run events that prove a provider session did work in a run. */ export const NATIVE_PROVIDER_DURABLE_EVENT_TYPES = new Set([ @@ -28,6 +31,12 @@ export function nativeHarnessBackupManifestSha256(manifestBytes: Buffer | string * stamp names exactly this backup, and no provider work for the session was * recorded after the backup completed. This is the same proof a confirmed * replacement relies on, reached through a lease that was retired first. + * + * A settled workspace-restore hold is the other retired source. The hold + * changed the lease to `retain_on_failure`, which reuse never selects, and + * stopped the sandbox under a stop-only receipt that permits no provider work. + * Releases before the hold settlement restored warm reuse left such rows + * stranded, so this also unsticks state saved by those releases. */ export async function retiredSourceAuthorizesNativeBackupRestore(db: Db, input: { companyId: string; @@ -48,13 +57,14 @@ export async function retiredSourceAuthorizesNativeBackupRestore(db: Db, input: const lease = tips[0]!; if (!retiredReusableLeasePredecessors(lease, source.filter(row => row.id !== lease.id))) return false; const termination = lease.metadata?.remoteExecutionTermination as { state?: unknown } | undefined; - // A released lease can still be selected for resume; only a retired one is final. - if (!["expired", "failed"].includes(lease.status) || !hasRemoteTerminationReceipt(lease) - || termination?.state !== "destroyed") return false; + const destroyed = ["expired", "failed"].includes(lease.status) && hasRemoteTerminationReceipt(lease) + && termination?.state === "destroyed"; const stamp = readNativeHarnessBackupStamp(lease.metadata?.nativeHarnessBackup, lease.providerLeaseId!); if (!stamp || stamp.manifestSha256 !== input.manifestSha256 || stamp.normalizedSessionId !== input.normalizedSessionId || stamp.runnerInstanceId !== input.manifest.runnerInstanceId) return false; + // A released lease can still be selected for resume; only a retired one is final. + if (!destroyed && !await settledRestoreHoldRetiresSource(db, lease)) return false; // Provider work recorded after the checkpoint means the destroyed sandbox // held newer state than this backup. Restoring would silently rewind it. const later = await db.select({ runId: heartbeatRunEvents.runId }).from(heartbeatRunEvents) @@ -69,3 +79,21 @@ export async function retiredSourceAuthorizesNativeBackupRestore(db: Db, input: )).limit(1); return later.length === 0; } + +/** + * A stopped, released lease is retired only when it is a workspace-restore hold + * that nothing can select for resume: `retain_on_failure` with the hold's own + * marker, a confirmed stop-and-retain receipt whose state is `stopped`, and no + * unsaved writer or pending native workspace export bound to the allocation. + * A stopped `reuse_by_environment` lease stays ambiguous and fails closed. + */ +async function settledRestoreHoldRetiresSource(db: Db, lease: typeof environmentLeases.$inferSelect): Promise { + const marker = lease.metadata?.workspaceRestoreRecovery as { schema?: unknown; runId?: unknown } | undefined; + if (lease.leasePolicy !== "retain_on_failure" || lease.status !== "released" || !lease.heartbeatRunId + || marker?.schema !== LEGACY_WORKSPACE_RECOVERY_SCHEMA || marker.runId !== lease.heartbeatRunId) return false; + // Provider expiry cannot revive the allocation; it only makes the source + // more final. Every other stop-and-retain receipt check stays strict. + if (!hasConfirmedSandboxStopAndRetain({ ...lease, expiresAt: null })) return false; + // Includes the dirty remote writer source (`preparedRemoteWorkspaceSource`). + return !await nativeWorkspaceExportPendingForLease(db, lease); +} diff --git a/server/src/services/native-runtime/native-session-executor.test.ts b/server/src/services/native-runtime/native-session-executor.test.ts index c08d42ab0c9..0b388583fc0 100644 --- a/server/src/services/native-runtime/native-session-executor.test.ts +++ b/server/src/services/native-runtime/native-session-executor.test.ts @@ -651,7 +651,7 @@ describe("remote controller restart adoption", () => { it("signals nothing when the sandbox runner belongs to another identity", async () => { const { execute, target } = fixture({ runnerInstanceId: "different" }); await expect(stopStaleRemoteRunnerBeforeBootstrap({ execution, runnerExecutionTarget: target as never, identity }, - { waitMs: 20, pollMs: 1 })).resolves.toBe("no_prior_runner"); + { waitMs: 20, pollMs: 1 })).resolves.toBe("stop_unproven"); expect(signalled(execute)).toEqual([]); }); it("signals nothing when no prior runner is alive", async () => { @@ -663,7 +663,7 @@ describe("remote controller restart adoption", () => { { waitMs: 20, pollMs: 1 })).resolves.toBe("absent_confirmed"); expect(signalled(execute)).toEqual([]); }); - it.each([["absent_confirmed", true], ["stopped", true], ["killed", true], ["stop_failed", false], ["no_prior_runner", false]] as const)( + it.each([["absent_confirmed", true], ["stopped", true], ["killed", true], ["stop_failed", false], ["stop_unproven", false], ["no_prior_runner", false]] as const)( "records a bootstrap restart proof only for a confirmed stop: %s", (stopped, proven) => { noteRemoteBootstrapRestartProven("run", "stopped"); expect(recordRemoteBootstrapRestartProof("run", stopped)).toBe(proven); @@ -674,7 +674,7 @@ describe("remote controller restart adoption", () => { const { execute, target } = fixture(); const verify = async () => { throw new RemoteRunnerRecoveryError({ stage: "process_verification", reason: "probe_timeout" } as never); }; await expect(stopStaleRemoteRunnerBeforeBootstrap({ execution, runnerExecutionTarget: target as never, identity }, - { waitMs: 20, pollMs: 1, verify: verify as never })).resolves.toBe("no_prior_runner"); + { waitMs: 20, pollMs: 1, verify: verify as never })).resolves.toBe("stop_unproven"); expect(signalled(execute)).toEqual([]); }); }); @@ -2608,7 +2608,16 @@ describe("remote provider pack manifest", () => { next.digest = "sha256:" + createHash("sha256").update(canonical(next.payload)).digest("hex"); await writeFile(state.bundledPackManifestPath!, JSON.stringify(next)); await writeFile(state.bundledRunnerBinary!, Buffer.concat([daemon, Buffer.from("new release")])); + let recoveredRunnerStopped = false; const recoveryExecute = vi.fn(async (request: { args: string[] }) => { + if (request.args[2] === "paperclip-runner-recovery-check" && request.args[1]?.includes('kill -"$6"')) { + const exitCode = recoveredRunnerStopped ? 45 : 0; + recoveredRunnerStopped = true; + return { exitCode, timedOut: false, stderr: "", stdout: "" }; + } + if (request.args[2] === "paperclip-runner-recovery-check" && recoveredRunnerStopped) { + return { exitCode: 45, timedOut: false, stderr: "", stdout: "" }; + } if (request.args[0] === "--build-metadata") return { exitCode: 0, timedOut: false, stderr: "", stdout: JSON.stringify({ schema: "paperclip-runner/runnerd-build-metadata/v1", binaryName: "paperclip-runnerd", packageName: "@paperclipai/paperclip-runner", binaryContractVersion: 2, @@ -2625,7 +2634,8 @@ describe("remote provider pack manifest", () => { runnerInstanceId: identity.runnerInstanceId, runnerIngressAuthorized: true, ...(opencode ? { runnerEnvironment: configuredEnvironmentProjection({ PAPERCLIP_OPENCODE_PERFORMANCE_DIAGNOSTICS: "1" }) } : {}), runnerExecutionTarget: { kind: "remote", transport: "sandbox", remoteCwd: "/workspace", - environmentId: "environment", leaseId: "lease", providerKey: "daytona", effectiveCapabilities: { runnerWebSocketIngress: true }, runner: { execute: recoveryExecute }, + environmentId: "environment", leaseId: "lease", providerKey: "daytona", effectiveCapabilities: { runnerWebSocketIngress: true }, + runner: { execute: recoveryExecute, syncIn: vi.fn(async () => undefined), syncOut: vi.fn(async () => undefined) }, sandboxLeaseAcquisition: { outcome: "resumed", providerLeaseId: "sandbox" } } as never, restartRecovery: { kind: "reattach_remote_runner", runId: remoteExecution.binding.runId, leaseOwner: "controller", controllerGeneration: 2, providerAttempt: 1, restartKind: "graceful", recoveryRequestId: null, @@ -2684,9 +2694,14 @@ describe("remote provider pack manifest", () => { expect(admittedNativeProviderPack(knownResult.session!, nativeIdentity)).toEqual(coldAdmission); if (pinned) { const replacement = { identity: () => nativeIdentity } as never; - Object.assign(state.createBackend.mock.results.at(-1)!.value, { openSession: async () => replacement }); + const recoveredBackendMock = state.createBackend.mock.results.at(-1)!.value; + state.createBackend.mockReturnValueOnce({ kind: "test", openSession: async () => replacement } as never); + const freshPreparation = vi.spyOn(nativeExecutionDriver, "prepareNativeRemoteRunner").mockResolvedValue(undefined as never); + onTestFinished(() => freshPreparation.mockRestore()); const replaced = await knownBackend.openReplacementSession!({ identity: nativeIdentity }, checkpoint); + expect(freshPreparation).toHaveBeenCalled(); expect(replaced).toBe(replacement); + expect(state.createBackend.mock.results.at(-1)!.value).not.toBe(recoveredBackendMock); expect(admittedNativeProviderPack(replaced, nativeIdentity)).toBeNull(); } } @@ -16225,6 +16240,218 @@ describe("runnerd provider runtime wiring", () => { || request.args.includes("paperclip-runner-claim-unstarted-session"))).toBe(false); }); + it.each(["codex", "acpx"] as const)("opens a remote %s replacement as a new runner, not the surviving runner it archived", async provider => { + const base = scopedNativeExecution(`replacement-after-reattach-${provider}`); + const current = { ...base, ...(provider === "acpx" ? { provider: { kind: "acpx", agent: "claude", model: null }, + session: { ...base.session, driverKind: "acpx_runtime" } } : {}) } as NativeExecutionInputV1; + const driver = vi.spyOn(nativeExecutionDriver, "createNativeRunnerExecutionDriver"); + onTestFinished(() => driver.mockRestore()); + const identity = { runId: current.binding.runId, normalizedSessionId: current.session.normalizedSessionId!, + runnerInstanceId: "admitted-codex", environmentLeaseId: "admitted-lease", + turnId: `turn_attachment_${randomUUID()}`, itemId: `item_attachment_${randomUUID()}` }; + const root = await initializeScopedRunnerRoot(current, identity.runnerInstanceId); + await mkdir(join(root, "control-plane"), { recursive: true }); + await writeFile(join(root, "control-plane", "control-plane-state.json"), JSON.stringify(durableControlPlaneState(identity))); + let installed: unknown = null; + if (provider === "acpx") { + const packRoot = await mkdtemp(join(tmpdir(), "paperclip-replacement-pack-")); + onTestFinished(() => rm(packRoot, { recursive: true, force: true })); + const digest = "sha256:" + "a".repeat(64); + const canonical = (value: unknown): string => Array.isArray(value) ? `[${value.map(canonical).join(",")}]` + : value && typeof value === "object" ? `{${Object.keys(value).sort().map(key => + `${JSON.stringify(key)}:${canonical((value as Record)[key])}`).join(",")}}` : JSON.stringify(value); + const artifacts = Object.fromEntries(Object.entries({ + grokLauncher: "dist/providers/grok/launcher.cjs", nodeCommand: "node_modules/node/bin/node", + productionLock: "pnpm-lock.yaml", opencodeCommand: "node_modules/.bin/opencode", + opencodeExecutable: "node_modules/opencode-ai/bin/opencode.exe", + opencodeProxy: "dist/cli/opencode-app-server-proxy.cjs", acpxSidecar: "dist/cli/acpx-runtime-sidecar.cjs", + }).map(([key, path]) => [key, { path, sha256: digest }])); + const payload = { compatibility: { opencode: 1, acpx: 1 }, contractDigest: digest, + target: { platform: "linux", architecture: "x64" }, runnerSourceRevision: "a".repeat(40), + pins: { nodeMinimum: "24.11.0", codex: QUALIFIED_ACPX_PROFILES.codex.agentRuntimeVersion, + opencode: "1.18.34", acpx: "0.13.1", grok: QUALIFIED_ACPX_PROFILES.grok.agentRuntimeVersion, + claudeAcp: QUALIFIED_ACPX_PROFILES.claude.agentServerVersion, codexAcp: QUALIFIED_ACPX_PROFILES.codex.agentServerVersion }, + acpxProfileDigests: Object.fromEntries(["grok", "claude", "codex"].map(agent => + [agent, QUALIFIED_ACPX_PROFILES[agent as "grok" | "claude" | "codex"].commandDigest])), + distDigest: digest, artifacts, + bridgeDigest: "sha256:" + createHash("sha256").update(digest + "\n" + digest + "\n" + digest).digest("hex") }; + installed = { schema: "paperclip-runner/remote-provider-pack/v1", payload, + digest: "sha256:" + createHash("sha256").update(canonical(payload)).digest("hex") }; + state.bundledPackManifestPath = join(packRoot, "provider-pack.json"); + await writeFile(state.bundledPackManifestPath, JSON.stringify(installed)); + state.bundledRunnerBinary = join(packRoot, "linux-paperclip-runnerd"); + const daemon = Buffer.alloc(64); daemon.set([0x7f, 0x45, 0x4c, 0x46, 2, 1]); daemon.writeUInt16LE(62, 18); + await writeFile(state.bundledRunnerBinary, daemon); + state.resolveRemoteRunnerBinary.mockResolvedValue(state.bundledRunnerBinary); + state.resolveRunnerBinary.mockReturnValue(state.bundledRunnerBinary); + } + let runnerStopped = false, sessionArchived = false; + const execute = vi.fn(async (request: { args: string[] }) => { + const script = request.args[1] ?? ""; + if (script.includes(".continuity-break-")) sessionArchived = true; + if (request.args[2] === "paperclip-runner-recovery-check") { + const signalled = script.includes('kill -"$6"'); + const exitCode = runnerStopped ? 45 : 0; + if (signalled) runnerStopped = true; + return { exitCode, timedOut: false, stderr: "", stdout: "" }; + } + if (sessionArchived && script.includes("runner-state.json")) return { exitCode: 1, timedOut: false, stderr: "", stdout: "" }; + return { exitCode: 0, timedOut: false, stderr: "", + stdout: request.args[0] === "--build-metadata" ? JSON.stringify({ + schema: "paperclip-runner/runnerd-build-metadata/v1", binaryName: "paperclip-runnerd", + packageName: "@paperclipai/paperclip-runner", binaryContractVersion: 2, + durableSessionCapabilities: ["unlimited_runtime", "connection_lease_renewal"], prpTransportModes: ["listen_ws"], + providerPacks: installed ? [{ root: "/opt/paperclip-runner/provider-pack", manifest: installed, immutable: true }] : [], + }) : script.includes("base64") ? Buffer.from(JSON.stringify({ ...identity, lifecycle: "suspended" })).toString("base64") + : script.includes("cat --") ? `nonce\n123\n2026-09-19T10:00:00.000Z\n${identity.runnerInstanceId}\nlinux:abcd-1234:100\n` : "" }; + }); + state.createBackend.mockClear(); state.createTransport.mockClear(); + const nativeIdentity = { ...current.binding, sessionId: current.session.normalizedSessionId! }; + const openSession = vi.fn(async () => ({ close: async () => undefined, identity: () => nativeIdentity })); + const freshOpenSession = vi.fn(async () => ({ close: async () => undefined, identity: () => nativeIdentity })); + state.createBackend.mockReturnValueOnce({ kind: "test", openSession, descriptor: () => ({ name: "reattached" }) } as never) + .mockReturnValueOnce({ kind: "test", openSession: freshOpenSession, descriptor: () => ({ name: "replacement" }) } as never); + const backend = await createRunnerdBackend({ db: leaseDb(current), execution: current, runnerInstanceId: identity.runnerInstanceId, + runnerIngressAuthorized: true, + controllerPersistence: { bootId: "successor", runnerArtifact: { version: "admitted-version", digest: `sha256:${"a".repeat(64)}` } }, + runnerExecutionTarget: { kind: "remote", transport: "sandbox", remoteCwd: "/workspace", + environmentId: "environment", leaseId: identity.environmentLeaseId, providerKey: "daytona", runner: { execute }, + effectiveCapabilities: { runnerWebSocketIngress: true }, + sandboxLeaseAcquisition: { outcome: "resumed", providerLeaseId: "sandbox" } } as never, + restartRecovery: { kind: "reattach_remote_runner", runId: current.binding.runId, leaseOwner: "controller", + controllerGeneration: 2, providerAttempt: 1, restartKind: "hard", recoveryRequestId: null, + remote: { providerLeaseId: "sandbox", remoteCwd: "/workspace" } }, + }); + const factory = state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!; + factory(); + expect(state.createTransport.mock.calls.at(-1)![0]).toMatchObject({ prpIdentity: identity, adoptExistingRunner: { pid: 123 } }); + const spawnedBefore = driver.mock.calls.at(-1)![0].processStarted; + expect(backend.descriptor()).toEqual({ name: "reattached" }); + const replaced = await backend.openReplacementSession!({ identity: nativeIdentity } as never, {} as never); + expect(runnerStopped).toBe(true); + const signalIndex = execute.mock.calls.findIndex(([request]) => request.args[1]?.includes('kill -"$6"')); + const archiveIndex = execute.mock.calls.findIndex(([request]) => request.args[1]?.includes(".continuity-break-")); + expect(signalIndex).toBeGreaterThanOrEqual(0); + expect(signalIndex).toBeLessThan(archiveIndex); + expect(backend.descriptor()).toEqual({ name: "replacement" }); + expect(backend.bindManagedSession(replaced)).toBe(replaced); + expect(openSession).not.toHaveBeenCalled(); + expect(freshOpenSession).toHaveBeenCalledOnce(); + expect(state.createBackend).toHaveBeenCalledTimes(2); + expect(execute.mock.calls.some(([request]) => request.args[1]?.includes(".continuity-break-"))).toBe(true); + state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!(); + const replacement = state.createTransport.mock.calls.at(-1)![0]; + expect(replacement.adoptExistingRunner).toBeUndefined(); + expect(replacement.prpIdentity).toMatchObject({ runId: current.binding.runId, turnId: `turn-${current.binding.runId}`, + itemId: `item-${current.binding.runId}` }); + const spawnedAfter = driver.mock.calls.at(-1)![0].processStarted!; + expect(spawnedAfter).not.toBe(spawnedBefore); + expect(await Promise.race([spawnedAfter.then(() => "spawned"), Promise.resolve("pending")])).toBe("pending"); + if (provider === "acpx") { + expect(replacement).toMatchObject({ providerNodeCommand: expect.any(String), acpxSidecarPath: expect.any(String) }); + expect(admittedNativeProviderPack(replaced, nativeIdentity)).toMatchObject({ + authority: "core_verified_selection", providerPackDigest: (installed as { digest: string }).digest }); + } + }); + + it("refuses a remote replacement and keeps the saved state when the adopted runner's stop is unproven", async () => { + const provider = "codex" as "codex" | "acpx"; + const base = scopedNativeExecution(`replacement-unproven-stop`); + const current = { ...base, ...(provider === "acpx" ? { provider: { kind: "acpx", agent: "claude", model: null }, + session: { ...base.session, driverKind: "acpx_runtime" } } : {}) } as NativeExecutionInputV1; + const driver = vi.spyOn(nativeExecutionDriver, "createNativeRunnerExecutionDriver"); + onTestFinished(() => driver.mockRestore()); + const identity = { runId: current.binding.runId, normalizedSessionId: current.session.normalizedSessionId!, + runnerInstanceId: "admitted-codex", environmentLeaseId: "admitted-lease", + turnId: `turn_attachment_${randomUUID()}`, itemId: `item_attachment_${randomUUID()}` }; + const root = await initializeScopedRunnerRoot(current, identity.runnerInstanceId); + await mkdir(join(root, "control-plane"), { recursive: true }); + await writeFile(join(root, "control-plane", "control-plane-state.json"), JSON.stringify(durableControlPlaneState(identity))); + let installed: unknown = null; + if (provider === "acpx") { + const packRoot = await mkdtemp(join(tmpdir(), "paperclip-replacement-pack-")); + onTestFinished(() => rm(packRoot, { recursive: true, force: true })); + const digest = "sha256:" + "a".repeat(64); + const canonical = (value: unknown): string => Array.isArray(value) ? `[${value.map(canonical).join(",")}]` + : value && typeof value === "object" ? `{${Object.keys(value).sort().map(key => + `${JSON.stringify(key)}:${canonical((value as Record)[key])}`).join(",")}}` : JSON.stringify(value); + const artifacts = Object.fromEntries(Object.entries({ + grokLauncher: "dist/providers/grok/launcher.cjs", nodeCommand: "node_modules/node/bin/node", + productionLock: "pnpm-lock.yaml", opencodeCommand: "node_modules/.bin/opencode", + opencodeExecutable: "node_modules/opencode-ai/bin/opencode.exe", + opencodeProxy: "dist/cli/opencode-app-server-proxy.cjs", acpxSidecar: "dist/cli/acpx-runtime-sidecar.cjs", + }).map(([key, path]) => [key, { path, sha256: digest }])); + const payload = { compatibility: { opencode: 1, acpx: 1 }, contractDigest: digest, + target: { platform: "linux", architecture: "x64" }, runnerSourceRevision: "a".repeat(40), + pins: { nodeMinimum: "24.11.0", codex: QUALIFIED_ACPX_PROFILES.codex.agentRuntimeVersion, + opencode: "1.18.34", acpx: "0.13.1", grok: QUALIFIED_ACPX_PROFILES.grok.agentRuntimeVersion, + claudeAcp: QUALIFIED_ACPX_PROFILES.claude.agentServerVersion, codexAcp: QUALIFIED_ACPX_PROFILES.codex.agentServerVersion }, + acpxProfileDigests: Object.fromEntries(["grok", "claude", "codex"].map(agent => + [agent, QUALIFIED_ACPX_PROFILES[agent as "grok" | "claude" | "codex"].commandDigest])), + distDigest: digest, artifacts, + bridgeDigest: "sha256:" + createHash("sha256").update(digest + "\n" + digest + "\n" + digest).digest("hex") }; + installed = { schema: "paperclip-runner/remote-provider-pack/v1", payload, + digest: "sha256:" + createHash("sha256").update(canonical(payload)).digest("hex") }; + state.bundledPackManifestPath = join(packRoot, "provider-pack.json"); + await writeFile(state.bundledPackManifestPath, JSON.stringify(installed)); + state.bundledRunnerBinary = join(packRoot, "linux-paperclip-runnerd"); + const daemon = Buffer.alloc(64); daemon.set([0x7f, 0x45, 0x4c, 0x46, 2, 1]); daemon.writeUInt16LE(62, 18); + await writeFile(state.bundledRunnerBinary, daemon); + state.resolveRemoteRunnerBinary.mockResolvedValue(state.bundledRunnerBinary); + state.resolveRunnerBinary.mockReturnValue(state.bundledRunnerBinary); + } + let runnerStopped = false, sessionArchived = false; + const execute = vi.fn(async (request: { args: string[] }) => { + const script = request.args[1] ?? ""; + if (script.includes(".continuity-break-")) sessionArchived = true; + if (request.args[2] === "paperclip-runner-recovery-check") { + const signalled = script.includes('kill -"$6"'); + const exitCode = runnerStopped ? 45 : 0; + if (signalled) runnerStopped = true; + return { exitCode, timedOut: false, stderr: "", stdout: "" }; + } + if (sessionArchived && script.includes("runner-state.json")) return { exitCode: 1, timedOut: false, stderr: "", stdout: "" }; + return { exitCode: 0, timedOut: false, stderr: "", + stdout: request.args[0] === "--build-metadata" ? JSON.stringify({ + schema: "paperclip-runner/runnerd-build-metadata/v1", binaryName: "paperclip-runnerd", + packageName: "@paperclipai/paperclip-runner", binaryContractVersion: 2, + durableSessionCapabilities: ["unlimited_runtime", "connection_lease_renewal"], prpTransportModes: ["listen_ws"], + providerPacks: installed ? [{ root: "/opt/paperclip-runner/provider-pack", manifest: installed, immutable: true }] : [], + }) : script.includes("base64") ? Buffer.from(JSON.stringify({ ...identity, lifecycle: "suspended" })).toString("base64") + : script.includes("cat --") ? `nonce\n123\n2026-09-19T10:00:00.000Z\n${identity.runnerInstanceId}\nlinux:abcd-1234:100\n` : "" }; + }); + state.createBackend.mockClear(); state.createTransport.mockClear(); + const nativeIdentity = { ...current.binding, sessionId: current.session.normalizedSessionId! }; + const openSession = vi.fn(async () => ({ close: async () => undefined, identity: () => nativeIdentity })); + const freshOpenSession = vi.fn(async () => ({ close: async () => undefined, identity: () => nativeIdentity })); + state.createBackend.mockReturnValueOnce({ kind: "test", openSession, descriptor: () => ({ name: "reattached" }) } as never); + const backend = await createRunnerdBackend({ db: leaseDb(current), execution: current, runnerInstanceId: identity.runnerInstanceId, + runnerIngressAuthorized: true, + controllerPersistence: { bootId: "successor", runnerArtifact: { version: "admitted-version", digest: `sha256:${"a".repeat(64)}` } }, + runnerExecutionTarget: { kind: "remote", transport: "sandbox", remoteCwd: "/workspace", + environmentId: "environment", leaseId: identity.environmentLeaseId, providerKey: "daytona", runner: { execute }, + effectiveCapabilities: { runnerWebSocketIngress: true }, + sandboxLeaseAcquisition: { outcome: "resumed", providerLeaseId: "sandbox" } } as never, + restartRecovery: { kind: "reattach_remote_runner", runId: current.binding.runId, leaseOwner: "controller", + controllerGeneration: 2, providerAttempt: 1, restartKind: "hard", recoveryRequestId: null, + remote: { providerLeaseId: "sandbox", remoteCwd: "/workspace" } }, + }); + const factory = state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!; + factory(); + expect(state.createTransport.mock.calls.at(-1)![0]).toMatchObject({ prpIdentity: identity, adoptExistingRunner: { pid: 123 } }); + const spawnedBefore = driver.mock.calls.at(-1)![0].processStarted; + execute.mockImplementation(async (request: { args: string[] }) => request.args[2] === "paperclip-runner-recovery-check" + ? { exitCode: 0, timedOut: true, stderr: "", stdout: "" } + : { exitCode: 0, timedOut: false, stderr: "", stdout: "" }); + await expect(backend.openReplacementSession!({ identity: nativeIdentity } as never, {} as never)) + .rejects.toThrow("native_runner_replacement_stop_unproven"); + expect(execute.mock.calls.some(([request]) => request.args[1]?.includes(".continuity-break-"))).toBe(false); + expect(execute.mock.calls.some(([request]) => request.args[1]?.includes('kill -"$6"'))).toBe(false); + expect(freshOpenSession).not.toHaveBeenCalled(); + expect(state.createBackend).toHaveBeenCalledTimes(1); + expect(existsSync(join(root, "control-plane", "control-plane-state.json"))).toBe(true); + }); + it.each(["failed", "timeout", "succeeded"] as const)("retains the local controller checkpoint until remote continuity archiving succeeds: %s", async mode => { const current = scopedNativeExecution("failed-remote-continuity-archive"); state.createBackend.mockClear(); state.createTransport.mockClear(); @@ -19567,7 +19794,14 @@ describe("runnerd provider runtime wiring", () => { ["the source sandbox was only stopped", "stopped", "matching", false, false], ["the source stamp names another backup", "destroyed", "foreign", false, false], ["provider work followed the backup", "destroyed", "matching", true, false], - ] as const)("restores a warm backup into a created lease only when %s", async (_label, terminationState, stampKind, laterProviderWork, restores) => { + // Regression, old-saved/new-resumed: an older release stopped the warm sandbox + // under a workspace-restore hold and changed its lease to retain_on_failure, + // which reuse never selects. The next run got a created lease and its + // automatic retry failed backup_without_reusable_lease overnight. + ["a settled restore hold retained the stopped source", "stopped", "matching", false, true, "settled_hold"], + ["a settled restore hold names another backup", "stopped", "foreign", false, false, "settled_hold"], + ["a restore hold has no stop-and-retain receipt", "stopped", "matching", false, false, "unconfirmed_hold"], + ] as const)("restores a warm backup into a created lease only when %s", async (_label, terminationState, stampKind, laterProviderWork, restores, hold?: "settled_hold" | "unconfirmed_hold") => { // Regression: a legacy follow-up retired the warm sandbox as an obsolete lease, so the // next reply got a created lease. The backup was the newest checkpoint, yet // every reply failed backup_without_reusable_lease and asked for another reply. @@ -19579,16 +19813,26 @@ describe("runnerd provider runtime wiring", () => { }; const runnerInstanceId = "retired-warm-runner", completedAt = "2026-11-05T05:02:50.000Z"; const backupDirectory = { root: "" }; + const confirmedAt = new Date().toISOString(); const sourceLease = (manifestSha256: string) => ({ id: "source-lease", companyId: current.binding.companyId, heartbeatRunId: "source-run", provider: "daytona", - providerLeaseId: "prior-sandbox", status: "expired", cleanupStatus: "success", releasedAt: new Date(), + providerLeaseId: "prior-sandbox", status: hold ? "released" : "expired", cleanupStatus: "success", + leasePolicy: hold ? "retain_on_failure" : "reuse_by_environment", + acquiredAt: new Date(Date.now() - 60_000), releasedAt: new Date(Date.now() + 1_000), expiresAt: null, metadata: { nativeHarnessBackup: { schema: "paperclip.native-harness-backup-stamp.v2", normalizedSessionId: current.session.normalizedSessionId, runnerInstanceId, sessionScopeSha256: "a".repeat(64), sourceProviderLeaseId: "prior-sandbox", authorizedProviderLeaseId: "prior-sandbox", manifestSha256, completedAt }, remoteExecutionTermination: { schema: "paperclip.remote-termination.v1", companyId: current.binding.companyId, runId: "source-run", leaseId: "source-lease", provider: "daytona", providerLeaseId: "prior-sandbox", - state: terminationState, confirmedAt: new Date().toISOString() }, + state: terminationState, confirmedAt }, + // The exact row the hold left: marker, stop-and-retain receipt, no reuse. + ...(hold ? { pluginId: "daytona-plugin", + workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", runId: "source-run" } } : {}), + ...(hold === "settled_hold" ? { sandboxStopAndRetainReceipt: { schema: "paperclip.sandbox-stop-and-retain-receipt.v1", + requestId: "stop-request", companyId: current.binding.companyId, runId: "source-run", leaseId: "source-lease", + provider: "daytona", providerLeaseId: "prior-sandbox", pluginId: "daytona-plugin", method: "environmentStopLease", + confirmedAt } } : {}), }, }); const updates: Array<{ table: unknown; values: Record }> = []; @@ -19598,7 +19842,8 @@ describe("runnerd provider runtime wiring", () => { return ordinarySelect(fields as never).from(table as never); const manifest = backupDirectory.root ? readFileSync(join(backupDirectory.root, "manifest.json")) : ""; const sha = `sha256:${createHash("sha256").update(stampKind === "matching" ? manifest : "other").digest("hex")}`; - const rows = table === executionWorkspaces ? [] + // No unsaved remote writer is bound to the held allocation. + const rows = table === executionWorkspaces || fields?.run ? [] : table === heartbeatRunEvents ? (laterProviderWork ? [{ runId: "later-run" }] : []) : [{ metadata: {}, providerLeaseId: "sandbox-created", companyId: current.binding.companyId, heartbeatRunId: current.binding.runId }, sourceLease(sha)]; diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts index aec710c4219..452ee43d4ce 100644 --- a/server/src/services/native-runtime/native-session-executor.ts +++ b/server/src/services/native-runtime/native-session-executor.ts @@ -6438,7 +6438,7 @@ export async function stopStaleRemoteRunnerBeforeBootstrap(input: { verify?: typeof verifyRemoteRunnerReattachment; waitMs?: number; pollMs?: number; -} = {}): Promise<"no_prior_runner" | "absent_confirmed" | "stopped" | "killed" | "stop_failed"> { +} = {}): Promise<"no_prior_runner" | "absent_confirmed" | "stopped" | "killed" | "stop_failed" | "stop_unproven"> { const target = input.runnerExecutionTarget; if (target?.kind !== "remote" || target.transport !== "sandbox" || !target.runner) return "no_prior_runner"; const providerLeaseId = target.sandboxLeaseAcquisition?.providerLeaseId; @@ -6454,7 +6454,7 @@ export async function stopStaleRemoteRunnerBeforeBootstrap(input: { } catch (error) { // No runner with this run's exact identity and generation is alive here. return error instanceof RemoteRunnerRecoveryError && error.remoteRunnerRecovery.reason === "process_not_running" - ? "absent_confirmed" : "no_prior_runner"; + ? "absent_confirmed" : "stop_unproven"; } try { let outcome: "stopped" | "killed" = "stopped"; @@ -16801,11 +16801,15 @@ async function createRunnerdBackendWithinSessionClaim( await recordAdmittedRemoteProviderPack(providerPackAuthority, message => input.onLog?.("stderr", message)); } }; + let replacementBackend: ManagedRunnerdBackend | null = null; return { - bindManagedSession: wrapManagedSession, - providerAdmissionRequired: () => Boolean(artifactStorage - && (providerArtifacts || !legacyProviderContinuity && !liveProviderRecovery)), + bindManagedSession: (session, options) => replacementBackend + ? replacementBackend.bindManagedSession(session, options) : wrapManagedSession(session), + providerAdmissionRequired: () => replacementBackend?.providerAdmissionRequired + ? replacementBackend.providerAdmissionRequired() + : Boolean(artifactStorage && (providerArtifacts || !legacyProviderContinuity && !liveProviderRecovery)), providerAdmissionPersisted: artifactStorage ? async () => { + if (replacementBackend) return replacementBackend.providerAdmissionPersisted?.(); const backupOwner = sessionHarnessBackupOwners.get(authorityEpoch); if ((liveProviderRecovery || legacyProviderContinuity) && !providerArtifacts) return; if (!backupOwner || !expectedProviderPackManifest || !remoteCommandRunner) { @@ -16823,6 +16827,7 @@ async function createRunnerdBackendWithinSessionClaim( source => retainNativeProviderArtifacts({ db: input.db, storage: artifactStorage, owner: backupOwner, source, signal })); } : undefined, bindDiagnosticSession: session => { + if (replacementBackend) return replacementBackend.bindDiagnosticSession?.(session); const retained = nativeSessionDiagnostics(session); if (retained && retained !== diagnostics) { const lease = retained.activate(diagnosticOwner, input.onLog); @@ -16830,6 +16835,7 @@ async function createRunnerdBackendWithinSessionClaim( } else diagnostics.bind(session); }, sessionCheckpointPersisted: snapshot => { + if (replacementBackend) return replacementBackend.sessionCheckpointPersisted?.(snapshot); const staged = runnerControlPlane?.store.state.stagedRunAttachment; if (staged && snapshot.identity.runId === staged.targetIdentity.runId && snapshot.identity.sessionId === staged.targetIdentity.normalizedSessionId) { @@ -16838,7 +16844,7 @@ async function createRunnerdBackendWithinSessionClaim( } } }, - descriptor: () => backend.descriptor(), + descriptor: () => (replacementBackend ?? backend).descriptor(), openSession: async (sessionInput) => { cursorCloudRuntime?.register(); try { @@ -16859,12 +16865,33 @@ async function createRunnerdBackendWithinSessionClaim( } catch (error) { cursorCloudRuntime?.unregister(); throw error; } }, openReplacementSession: async (sessionInput, previous) => { + const reattachClaim = input.restartRecovery?.kind === "reattach_remote_runner" ? input.restartRecovery : null; + if (!reattachClaim && input.remoteWarmRecovery) { + throw new Error("native_runner_replacement_requires_fresh_launch"); + } + if (reattachClaim) { + const stopped = await stopStaleRemoteRunnerBeforeBootstrap({ execution: input.execution, + runnerExecutionTarget: input.runnerExecutionTarget, identity: durableIdentity ?? {}, onLog: input.onLog }); + if (stopped === "stop_failed" || stopped === "stop_unproven") { + throw new Error(`native_runner_replacement_${stopped}`); + } + } await measureNativeRunnerSpan( input.trace, "provider.session.archive_before_replacement", () => archiveContinuityState(previous), { parentName: "native.session.execute" }, ); + if (reattachClaim) { + const { remote: _remote, stagedAttachment: _staged, ...claim } = reattachClaim; + const fresh = await createRunnerdBackendWithinSessionClaim({ + ...input, + remoteWarmRecovery: undefined, + restartRecovery: { ...claim, kind: "bootstrap_incomplete" }, + }, sessionScopeId); + replacementBackend = fresh; + return fresh.openSession(sessionInput); + } cursorCloudRuntime?.register(); try { const session = await backend.openSession(sessionInput); diff --git a/server/src/services/native-runtime/native-workspace-warm-reuse.test.ts b/server/src/services/native-runtime/native-workspace-warm-reuse.test.ts index defc8da40e9..f9efd5e0d09 100644 --- a/server/src/services/native-runtime/native-workspace-warm-reuse.test.ts +++ b/server/src/services/native-runtime/native-workspace-warm-reuse.test.ts @@ -1,7 +1,7 @@ import { randomUUID } from "node:crypto"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; import { eq } from "drizzle-orm"; -import { agents, agentWakeupRequests, applyPendingMigrations, companies, createDb, environmentLeases, environments, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, plugins } from "@paperclipai/db"; +import { agents, agentWakeupRequests, applyPendingMigrations, companies, createDb, environmentLeases, environments, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issues, nativeRunFinalizations, plugins, workspaceOperations } from "@paperclipai/db"; import type { Environment } from "@paperclipai/shared"; import type { PluginWorkerManager } from "../plugin-worker-manager.js"; import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js"; @@ -11,6 +11,9 @@ import * as leases from "../environments.js"; import * as providers from "../sandbox-provider-runtime.js"; import { createSystemRecovery, failSystemRecovery, reserveSystemRecoveryAttempt, SystemRecoveryFailure } from "../system-recovery-state.js"; import { recoverRetainedWorkspace } from "../workspace-recovery.js"; +import { preserveLegacyWorkspaceRestoreSources } from "../legacy-workspace-restore-recovery.js"; +import { settleStopOnlyCleanup } from "../sandbox-stop-and-retain.js"; +import { settleRecoveredWorkspaceRestoreHolds } from "../workspace-restore-hold-settlement.js"; import { nativeWorkspaceExportPendingForLease, nativeWorkspaceExportPendingForResource } from "./native-workspace-finalization-state.js"; describe("native workspace export warm reuse fence", () => { @@ -25,7 +28,7 @@ describe("native workspace export warm reuse fence", () => { afterEach(() => vi.restoreAllMocks()); afterAll(async () => { await db?.$client.end(); await temporary?.cleanup(); }); - async function seed(plugin: boolean) { + async function seed(plugin: boolean, release = true) { const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID(), pluginId = randomUUID(); await db.insert(companies).values({ id: companyId, name: "Native warm fence", issuePrefix: `W${companyId.slice(0, 6)}` }); await db.insert(agents).values({ id: agentId, companyId, name: "Worker", adapterType: "paperclip_runner" }); @@ -64,11 +67,11 @@ describe("native workspace export warm reuse fence", () => { const input = { companyId, agentId, issueId, environment: environment as unknown as Environment, heartbeatRunId: runId, persistedExecutionWorkspace: null }; const acquired = await runtime.acquireRunLease(input); - await runtime.releaseRunLeases(runId, "released", undefined, "keep_running"); + if (release) await runtime.releaseRunLeases(runId, "released", undefined, "keep_running"); const reference = { schema: "paperclip.native-workspace-sync/v3", state: "prepared", leaseId: acquired.lease.id, providerLeaseId: acquired.lease.providerLeaseId, workspaceId: issueId, remoteCwd: "/work", resourceDisposition: "keep_running", descriptorSha256: "a".repeat(64), baselineSha256: "b".repeat(64), finalHostSha256: null }; - await db.update(heartbeatRuns).set({ status: "failed", runnerProfileJson: { nativeWorkspaceSync: reference } }).where(eq(heartbeatRuns.id, runId)); + if (release) await db.update(heartbeatRuns).set({ status: "failed", runnerProfileJson: { nativeWorkspaceSync: reference } }).where(eq(heartbeatRuns.id, runId)); const nextRunId = randomUUID(); await db.insert(heartbeatRuns).values({ id: nextRunId, companyId, agentId, issueId, nativeIssueId: issueId, runtimeMode: "native", status: "running" }); call.mockClear(); @@ -277,4 +280,64 @@ describe("native workspace export warm reuse fence", () => { expect(f.call.mock.calls.map(call => call[1])).toEqual(["environmentResumeLease"]); } finally { release(); await ordinary; } }); + + // Regression: a run resumed a warm sandbox and was interrupted before provider + // work. The restore hold stopped the sandbox and changed its lease to + // retain_on_failure. Recovery saved the files, yet the next run got a created + // lease (and a full workspace realize) because nothing restored reuse. + async function settleRestoreHold(fault: "none" | "unsettled" | "dirty" | "unstopped") { + const f = await seed(true, false), actionId = randomUUID(), operationId = randomUUID(); + // The interrupted run's real terminal hold over its active warm lease. + const [interrupted] = await db.update(heartbeatRuns).set({ status: "interrupted", finishedAt: new Date(), + resultJson: { workspaceRestoreFailure: "restore_failed" } }).where(eq(heartbeatRuns.id, f.runId)).returning(); + const [source] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)); + expect(await db.transaction(tx => preserveLegacyWorkspaceRestoreSources(tx as unknown as typeof db, interrupted, source))) + .toEqual([f.lease.id]); + const [stopping] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)); + expect(stopping).toMatchObject({ leasePolicy: "retain_on_failure", status: "pending_cleanup" }); + if (fault !== "unstopped") expect(await settleStopOnlyCleanup(db, stopping, { attemptId: String(stopping.metadata!.pendingCleanupAttemptId), + receipt: { providerLeaseId: f.lease.providerLeaseId, state: "stopped" } })).not.toBeNull(); + // The recovery's own receipts: files saved from this allocation, and its finalize. + const system = { ...createSystemRecovery(f.runId), state: fault === "unsettled" ? "running" : "complete", + phase: "reconcile_effects", preservationOperationIds: [operationId] }; + await db.insert(issueRecoveryActions).values({ id: actionId, companyId: f.input.companyId, sourceIssueId: f.input.issueId, + kind: "active_run_watchdog", ownerType: "system", cause: "native_continuation_requires_reconciliation", fingerprint: f.runId, + nextAction: "Recover saved work", evidence: { runId: f.runId, workspaceRestoreFailure: "restore_failed", + workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [f.lease.id] }, systemRecovery: system, + workspaceRecovery: { schema: "paperclip.workspace-recovery.v1", runId: f.runId, + status: fault === "unsettled" ? "recovering" : "recovered", stage: "saving_receipts", attempt: 1, requestIds: [] } } }); + await db.insert(workspaceOperations).values([{ id: operationId, companyId: f.input.companyId, issueId: f.input.issueId, + heartbeatRunId: f.runId, phase: "workspace_recovery", status: "succeeded", finishedAt: new Date(), + metadata: { recoveryActionId: actionId, leaseId: f.lease.id, providerLeaseId: f.lease.providerLeaseId } }, + { companyId: f.input.companyId, issueId: f.input.issueId, heartbeatRunId: f.runId, phase: "workspace_finalize", + status: "succeeded", finishedAt: new Date(), metadata: { owningService: "workspace_recovery", preservationOperationIds: [operationId] } }]); + // An unsaved writer still bound to the stopped sandbox keeps it held. + if (fault === "dirty") await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeWorkspaceSync: f.reference } }) + .where(eq(heartbeatRuns.id, f.runId)); + const restored = await settleRecoveredWorkspaceRestoreHolds(db, { companyId: f.input.companyId, issueId: f.input.issueId, + runId: f.runId, actionId }); + f.call.mockClear(); + return { ...f, restored }; + } + + it("resumes the warm sandbox on the same provider lease after a restore hold settles", async () => { + const f = await settleRestoreHold("none"); + const next = await f.runtime.acquireRunLease({ ...f.input, heartbeatRunId: f.nextRunId }); + expect(next.lease.metadata?.sandboxLeaseAcquisition).toEqual({ outcome: "resumed" }); + expect(next.lease).toMatchObject({ heartbeatRunId: f.nextRunId, providerLeaseId: f.lease.providerLeaseId, + leasePolicy: "reuse_by_environment" }); + expect(f.restored).toEqual([f.lease.id]); + expect(f.call.mock.calls.map(call => call[1])).toEqual(["environmentResumeLease"]); + expect((await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)))[0]) + .toMatchObject({ heartbeatRunId: f.runId, status: "expired", leasePolicy: "reuse_by_environment" }); + }); + + it.each(["unsettled", "dirty", "unstopped"] as const)("keeps a %s restore hold out of warm reuse", async fault => { + const f = await settleRestoreHold(fault); + expect(f.restored).toEqual([]); + const [held] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)); + expect(held.leasePolicy).toBe("retain_on_failure"); + expect(held.metadata?.workspaceRestoreRecovery).toMatchObject({ runId: f.runId, originalLeasePolicy: "reuse_by_environment" }); + if (fault !== "unstopped") await expectFreshAllocation(f); + }); }); diff --git a/server/src/services/recovery/blocker-stall-wakeups.ts b/server/src/services/recovery/blocker-stall-wakeups.ts index 9b178731e57..cb44233719d 100644 --- a/server/src/services/recovery/blocker-stall-wakeups.ts +++ b/server/src/services/recovery/blocker-stall-wakeups.ts @@ -19,13 +19,25 @@ * one `blocks`) is woken once per stall. The idempotency key names the * recovery action, so a repeated sweep never wakes twice, and a later stall * (a new action after a Retry or another failure) wakes again. + * + * A wake that did not reach the agent is retried, boundedly. A refusal + * (wake-on-demand off, agent paused) is retried after ten minutes. A stall whose + * runs failed (the keyed wake's run or a resource-wait retry carrying it) is + * retried with a doubling wait and given up after MAX_FAILED_STALL_DELIVERIES + * failed runs; the stall stays listed on the waiter's page. A waiter whose last + * run failed setup on its bound remote workspace's hold is not woken again while + * reservation would still refuse that hold (remoteWorkspaceHoldRefusesStart): + * its run could only fail the same way. It is woken once the hold settles. */ -import { and, eq, gt, inArray, isNull, ne, notInArray, or, sql } from "drizzle-orm"; -import { agents, agentWakeupRequests, heartbeatRuns, issueRecoveryActions, issueRelations, issues, type Db } from "@paperclipai/db"; -import { ISSUE_BLOCKER_STALLED_WAKE_REASON, type IssueBlockerStalledWakeContext, type IssueBlockerStallRelation } from "@paperclipai/shared"; +import { and, desc, eq, gt, inArray, isNull, ne, notInArray, or, sql } from "drizzle-orm"; +import { agents, agentWakeupRequests, executionWorkspaces, heartbeatRuns, issueRecoveryActions, issueRelations, issues, type Db } from "@paperclipai/db"; +import { ISSUE_BLOCKER_STALLED_WAKE_REASON, readRemoteWorkspaceAuthority, type IssueBlockerStalledWakeContext, + type IssueBlockerStallRelation } from "@paperclipai/shared"; import { logActivity } from "../activity-log.js"; import { parseHeartbeatPolicy } from "../heartbeat/timer-policy.js"; import { authorizationService } from "../authorization.js"; +import { readRemoteWorkspaceWriterHold, REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE, + remoteWorkspaceHoldRefusesStart } from "../remote-workspace-writer-hold.js"; const TERMINAL_ISSUE_STATUSES = ["done", "cancelled"]; /** Waiters that may be woken: not finished, and not parked in the backlog by the board. */ @@ -41,6 +53,10 @@ const waiterCursors = new Map(); const DELIVERING_RUN_STATUSES = ["queued", "scheduled_retry", "running", "succeeded"]; /** A refused wake (skipped, failed, cancelled) is retried, but not more often than this. */ const REFUSED_WAKE_RETRY_MS = 10 * 60_000; +/** Failed runs of one stall's wake before it is no longer retried; each retry waits twice as long. */ +const MAX_FAILED_STALL_DELIVERIES = 3; +/** Re-check for a waiter whose workspace hold refuses a run; settling the hold is what lets it run. */ +const HELD_WORKSPACE_RECHECK_MS = 60 * 60_000; const NON_INVOKABLE_AGENT_STATUSES = ["paused", "terminated", "pending_approval"]; /** Company-wide passes resume after the last stall a capped pass reached, so every stall is visited. */ const companyCursors = new Map(); @@ -115,6 +131,30 @@ async function readStalls(db: Db, filter: StallFilter, limit = MAX_STALLS_PER_PA type StallRow = Awaited>[number]; +/** + * Whether a run of the waiter's assignee could only fail setup on its bound + * remote workspace's hold. The evidence is the assignee's own latest run on the + * task: it failed setup on that hold, so this agent uses the workspace and + * reservation already tried, and refused, to release the writer. The hold must + * still be one reservation refuses outright (an ended writer past the holder + * cutoff with its save unsettled, or a writer that cannot be named). Another + * assignee, a later run, or a settled hold lets the wake through. + */ +async function waiterWorkspaceRefusesStart(db: Db, companyId: string, + waiter: { id: string; assigneeAgentId: string | null; executionWorkspaceId: string | null }) { + if (!waiter.executionWorkspaceId || !waiter.assigneeAgentId) return false; + const [latest] = await db.select({ status: heartbeatRuns.status, error: heartbeatRuns.error }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.agentId, waiter.assigneeAgentId), + sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${waiter.id}`)) + .orderBy(desc(heartbeatRuns.createdAt)).limit(1); + if (latest?.status !== "failed" || latest.error !== REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE) return false; + const [workspace] = await db.select({ metadata: executionWorkspaces.metadata }).from(executionWorkspaces) + .where(and(eq(executionWorkspaces.companyId, companyId), eq(executionWorkspaces.id, waiter.executionWorkspaceId))); + const authority = readRemoteWorkspaceAuthority(workspace?.metadata); + if (!authority?.writerRunId) return false; + return remoteWorkspaceHoldRefusesStart(await readRemoteWorkspaceWriterHold(db, { companyId, authority })); +} + /** What a waiter's agent may see of a stalled issue it cannot read: that it is stalled, nothing more. */ function redactedStallContext(stall: StallRow, relation: IssueBlockerStallRelation): IssueBlockerStalledWakeContext { return { @@ -200,7 +240,7 @@ export async function wakeWaitersOfStalledIssues(db: Db, enqueueWakeup: BlockerS let scanned = 0; for (;;) { const waiters = await db.select({ id: issues.id, identifier: issues.identifier, assigneeAgentId: issues.assigneeAgentId, - status: issues.status, responsibleUserId: issues.responsibleUserId, + status: issues.status, responsibleUserId: issues.responsibleUserId, executionWorkspaceId: issues.executionWorkspaceId, relation: sql<"child" | "blocker">`case when ${issues.id} = ${stall.parentId ?? null} then 'child' else 'blocker' end` }) .from(issues) .where(and( @@ -227,20 +267,36 @@ export async function wakeWaitersOfStalledIssues(db: Db, enqueueWakeup: BlockerS // (company_id, payload->>'issueId') is indexed; the key narrows to this stall. // A delivered or pending wake ends it. A refused one (wake-on-demand off, // agent paused) is retried once the refusal is old, so re-enabling wakes - // still delivers the stall. - const [existing] = await db.select({ id: agentWakeupRequests.id, status: agentWakeupRequests.status, - requestedAt: agentWakeupRequests.requestedAt }).from(agentWakeupRequests) + // still delivers the stall. Failed runs carrying this stall (the keyed + // wake's run, or a resource-wait retry that keeps its context) are + // retried after a doubling wait, and not after MAX_FAILED_STALL_DELIVERIES. + const [prior] = await db.select({ + delivered: sql`coalesce(bool_or(${inArray(agentWakeupRequests.status, DELIVERED_OR_PENDING_WAKE_STATUSES)}), false)`, + lastRequestedAt: sql`max(${agentWakeupRequests.requestedAt})`, + }).from(agentWakeupRequests) .where(and(eq(agentWakeupRequests.companyId, stall.companyId), sql`${agentWakeupRequests.payload}->>'issueId' = ${waiter.id}`, - eq(agentWakeupRequests.idempotencyKey, idempotencyKey), - or(inArray(agentWakeupRequests.status, DELIVERED_OR_PENDING_WAKE_STATUSES), - gt(agentWakeupRequests.requestedAt, new Date(Date.now() - REFUSED_WAKE_RETRY_MS))))).limit(1); - if (existing) { - result.alreadyWoken += 1; - // A recent refusal is retried once it is old; the worker comes back then. - if (!(DELIVERED_OR_PENDING_WAKE_STATUSES as readonly string[]).includes(existing.status)) - retryAt(existing.requestedAt.getTime() + REFUSED_WAKE_RETRY_MS); - continue; + eq(agentWakeupRequests.idempotencyKey, idempotencyKey))); + if (prior?.delivered) { result.alreadyWoken += 1; continue; } + const [failed] = await db.select({ + runs: sql`count(*)::int`, + lastAt: sql`max(coalesce(${heartbeatRuns.finishedAt}, ${heartbeatRuns.createdAt}))`, + }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.companyId, stall.companyId), eq(heartbeatRuns.status, "failed"), + sql`${heartbeatRuns.contextSnapshot}->>'issueId' = ${waiter.id}`, + sql`${heartbeatRuns.contextSnapshot}#>>'{blockerStall,stalledIssueId}' = ${stall.issueId}`, + sql`${heartbeatRuns.contextSnapshot}#>>'{blockerStall,recoveryAction,id}' = ${stall.actionId}`)); + const failedRuns = Number(failed?.runs ?? 0); + if (failedRuns >= MAX_FAILED_STALL_DELIVERIES) { result.alreadyWoken += 1; continue; } + const lastAttemptAt = Math.max(prior?.lastRequestedAt ? new Date(prior.lastRequestedAt).getTime() : 0, + failed?.lastAt ? new Date(failed.lastAt).getTime() : 0); + if (lastAttemptAt > 0) { + const dueAt = lastAttemptAt + REFUSED_WAKE_RETRY_MS * 2 ** Math.max(0, failedRuns - 1); + if (dueAt > Date.now()) { + result.alreadyWoken += 1; + retryAt(dueAt); + continue; + } } // A resource wait cancels the stall wake's run and schedules a retry // with no idempotency key; the retry keeps the stall in its context. @@ -251,6 +307,11 @@ export async function wakeWaitersOfStalledIssues(db: Db, enqueueWakeup: BlockerS sql`${heartbeatRuns.contextSnapshot}#>>'{blockerStall,stalledIssueId}' = ${stall.issueId}`, sql`${heartbeatRuns.contextSnapshot}#>>'{blockerStall,recoveryAction,id}' = ${stall.actionId}`)).limit(1); if (carried) { result.alreadyWoken += 1; continue; } + if (await waiterWorkspaceRefusesStart(db, stall.companyId, waiter)) { + result.deferred += 1; + retryAt(Date.now() + HELD_WORKSPACE_RECHECK_MS); + continue; + } if (!(await acceptsWakes(waiter.assigneeAgentId!))) { result.deferred += 1; retryAt(Date.now() + REFUSED_WAKE_RETRY_MS); diff --git a/server/src/services/remote-workspace-writer-hold.ts b/server/src/services/remote-workspace-writer-hold.ts index 721239f9777..cf9f9c946c9 100644 --- a/server/src/services/remote-workspace-writer-hold.ts +++ b/server/src/services/remote-workspace-writer-hold.ts @@ -4,6 +4,7 @@ import type { RemoteWorkspaceAuthority } from "@paperclipai/shared"; import { hasRecoveredCleanupStopReceipt, hasRemoteTerminationReceipt } from "./remote-execution-termination.js"; import { canonicalExecutionUuid } from "./execution-identity.js"; import { REMOTE_WORKSPACE_PREPARATION_TIMEOUT_CODE } from "./remote-workspace-transport.js"; +import { WORKSPACE_BUSY_HOLDER_STALE_AFTER_MS } from "../modules/run-dispatch/index.js"; const object = (value: unknown): Record => typeof value === "object" && value !== null && !Array.isArray(value) ? value as Record : {}; @@ -21,6 +22,24 @@ export function runOwnerFenceHeldSql() { and ${nativeRunFinalizations.leaseOwner} is not null and ${nativeRunFinalizations.leaseExpiresAt} > now()))`; } +/** The setup error a run gets when reservation refuses a remote workspace hold. */ +export const REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE = "The workspace still has an unfinished writer or save operation."; + +type RemoteWorkspaceWriterHold = Awaited>; + +/** + * Whether a hold refuses a new run outright instead of parking it in a + * workspace wait: a writer that cannot be named, or one silent past the holder + * cutoff with no live owner fence. Workspace reservation fails setup on such a + * hold, so senders of automatic wakes read this same rule to hold a wake until + * the hold settles rather than create a run that can only fail. + */ +export function remoteWorkspaceHoldRefusesStart(hold: RemoteWorkspaceWriterHold, now = Date.now()): boolean { + if (hold.kind === "unattributed") return true; + if (hold.kind !== "held") return false; + return !hold.writer.ownerFenceHeld && hold.writer.lastActivityAt.getTime() < now - WORKSPACE_BUSY_HOLDER_STALE_AFTER_MS; +} + /** * Who still holds a remote workspace through its recorded writer run, other * than `runId`. A running writer holds it. An ended writer keeps holding it diff --git a/server/src/services/remote-workspaces.ts b/server/src/services/remote-workspaces.ts index f61475bce95..df596b35590 100644 --- a/server/src/services/remote-workspaces.ts +++ b/server/src/services/remote-workspaces.ts @@ -23,7 +23,7 @@ import { logger } from "../middleware/logger.js"; import { createGitRemoteAuthProvider } from "./git-credentials.js"; import { notifyCancelledWorkspacePreservation } from "./cancelled-workspace-preservation-notifications.js"; import { assertExecutionWorkspaceRecordAccess, assertTaskWorkspaceExecutionAccess } from "./task-workspace-access.js"; -import { readRemoteWorkspaceWriterHold, type RemoteWorkspaceWriter } from "./remote-workspace-writer-hold.js"; +import { readRemoteWorkspaceWriterHold, REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE, type RemoteWorkspaceWriter } from "./remote-workspace-writer-hold.js"; import { persistActivity } from "./activity-log.js"; import { hasRecoveredCleanupStopReceipt, hasRemoteTerminationReceipt } from "./remote-execution-termination.js"; import { @@ -171,7 +171,7 @@ export class RemoteWorkspaceWriterActiveError extends HttpError { readonly workspaceId: string, readonly writer: RemoteWorkspaceWriter, ) { - super(409, "The workspace still has an unfinished writer or save operation.", { code: "remote_workspace_writer_pending" }); + super(409, REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE, { code: "remote_workspace_writer_pending" }); } } @@ -247,7 +247,7 @@ export async function reserveRemoteWorkspace(input: { } const hold = await readRemoteWorkspaceWriterHold(tx as unknown as Db, { companyId: input.companyId, authority, runId: input.runId }); if (hold.kind === "held") throw new RemoteWorkspaceWriterActiveError(existing.id, hold.writer); - if (hold.kind === "unattributed") throw conflict("The workspace still has an unfinished writer or save operation.", { code: "remote_workspace_writer_pending" }); + if (hold.kind === "unattributed") throw conflict(REMOTE_WORKSPACE_WRITER_PENDING_MESSAGE, { code: "remote_workspace_writer_pending" }); if (authority.writerRunId === input.runId) return existing; const next: RemoteWorkspaceAuthority = { ...authority, source, epoch: authority.epoch + 1, writerRunId: input.runId }; const [saved] = await tx.update(executionWorkspaces).set({ metadata: { ...existing.metadata, remoteWorkspace: next, diff --git a/server/src/services/workspace-recovery-source.ts b/server/src/services/workspace-recovery-source.ts index 59ba151c6c7..a27555e3607 100644 --- a/server/src/services/workspace-recovery-source.ts +++ b/server/src/services/workspace-recovery-source.ts @@ -4,10 +4,10 @@ import { and, eq, inArray, ne, or, sql } from "drizzle-orm"; import { environmentLeases, environments, executionWorkspaces, executionWorkspaceSnapshots, heartbeatRuns, issueRecoveryActions, nativeRunFinalizations, nativeRunResults, type Db } from "@paperclipai/db"; import { adapterExecutionControls } from "./adapter-execution-control.js"; import { readNativeWorkspaceSyncReference } from "./native-runtime/native-workspace-sync.js"; -import { SystemRecoveryFailure } from "./system-recovery-state.js"; +import { readSystemRecovery, SystemRecoveryFailure } from "./system-recovery-state.js"; import type { NativeWorkspaceFinalizationOwnership } from "./native-runtime/native-workspace-finalization-ownership.js"; import { readStopOnlyCleanup } from "./sandbox-stop-and-retain.js"; -import { LEGACY_WORKSPACE_RECOVERY_SCHEMA } from "./workspace-restore-recovery-state.js"; +import { LEGACY_WORKSPACE_RECOVERY_SCHEMA, SETTLED_WORKSPACE_RESTORE_HOLD_KEY } from "./workspace-restore-recovery-state.js"; import { ENVIRONMENT_LEASE_POLICIES, EXECUTION_RECONCILIATION_CAUSES, readRemoteWorkspaceAuthority, remoteWorkspaceRunReferenceSchema, type EnvironmentLeasePolicy, type WorkspaceSourceVerificationFailure } from "@paperclipai/shared"; @@ -167,7 +167,11 @@ export async function inspectWorkspaceRecoverySource(db: Db, input: WorkspaceRec && lease.leasePolicy === "reuse_by_environment" && ["released", "retained"].includes(lease.status); const reusableExport = descriptor && (acceptedExportResult || remoteDescriptor && remoteAuthority) && ["reuse_by_environment", "reuse_by_execution_workspace"].includes(lease.leasePolicy); - if (!["retain_on_failure", "ephemeral"].includes(lease.leasePolicy) && !reusableExport && !preparingRetention) + // A completed recovery returned its settled hold to warm reuse. Reading + // that saved source back stays verifiable; it authorizes nothing new. + const settledHold = lease.leasePolicy === "reuse_by_environment" && readSystemRecovery(action.evidence)?.state === "complete" + && (lease.metadata?.[SETTLED_WORKSPACE_RESTORE_HOLD_KEY] as { runId?: unknown } | undefined)?.runId === run.id; + if (!["retain_on_failure", "ephemeral"].includes(lease.leasePolicy) && !reusableExport && !preparingRetention && !settledHold) throw invalid("lease_policy_not_retained", lease.leasePolicy); if (typeof remoteCwd !== "string" || !remoteCwd.startsWith("/")) throw invalid("lease_cwd_invalid"); if (descriptor && lease.providerLeaseId !== descriptor.providerLeaseId) throw invalid("allocation_reference_mismatch"); diff --git a/server/src/services/workspace-recovery-warm-handoff.test.ts b/server/src/services/workspace-recovery-warm-handoff.test.ts index bfe5a9c1534..220ffa96037 100644 --- a/server/src/services/workspace-recovery-warm-handoff.test.ts +++ b/server/src/services/workspace-recovery-warm-handoff.test.ts @@ -29,6 +29,7 @@ import { heartbeatService } from "./heartbeat.js"; import { hasVerifiedWorkspaceRepair, readWorkspaceRecovery } from "./workspace-recovery-receipt.js"; import { claimNativeSessionResumptions } from "./native-runtime/native-finalization-reconciler.js"; import { getExecutionBlocker } from "./execution-blocker.js"; +import { legacyShutdownWorkspaceResourceProtected } from "./legacy-shutdown-workspace-settlement.js"; import { issueRoutes } from "../routes/issues.js"; import { errorHandler } from "../middleware/index.js"; import { useWorkspaceRecoveryFixture, action, connectionString, db, failedWarmSource, replaceFixtureState, root, run, seed, warmHandoffSource } from "./__tests__/workspace-recovery-fixture.js"; @@ -142,6 +143,49 @@ describe("automatic retained workspace recovery", () => { .toMatchObject({ status: "verified" }); }, 30_000); + // Regression: a native run resumed a warm sandbox and was interrupted before + // provider work. The restore hold stopped that sandbox and changed its lease + // to retain_on_failure. Recovery saved the files, but nothing returned the + // lease to reuse, so the next run paid a new sandbox and a full realize. + it.each([ + ["the hold recorded its original policy", "current", "reuse_by_environment"], + // Old-saved/new-resumed: a previous release wrote the marker without the + // original policy. The reuse scope that only a reusable acquisition writes + // still proves it. + ["an older release saved the hold over a scoped reusable lease", "legacy_scoped", "reuse_by_environment"], + ["an older release saved the hold without reuse proof", "legacy_unscoped", "retain_on_failure"], + ] as const)("returns a settled restore hold to warm reuse when %s", async (_label, marker, policy) => { + const f = await warmHandoffSource(1); + const [held] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)); + expect(held).toMatchObject({ leasePolicy: "retain_on_failure", status: "released" }); + expect(held.metadata?.workspaceRestoreRecovery).toMatchObject({ schema: "paperclip.workspace-restore-recovery.v1", runId: f.runId }); + if (marker !== "current") { + const { originalLeasePolicy: _original, ...legacyMarker } = held.metadata!.workspaceRestoreRecovery as Record; + await db.update(environmentLeases).set({ metadata: { ...held.metadata, workspaceRestoreRecovery: legacyMarker, + ...(marker === "legacy_scoped" ? { reusableSandboxLease: { version: 1, companyId: f.companyId } } : {}) } }) + .where(eq(environmentLeases.id, f.lease.id)); + } + expect(await legacyShutdownWorkspaceResourceProtected(db, held)).toBe(true); + await recoverRetainedWorkspace(f.input); + expect(readSystemRecovery((await action(f.actionId)).evidence)?.state).toBe("complete"); + expect(await hasVerifiedWorkspaceRepair(db, await run(f.runId))).toBe(true); + const [settled] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, f.lease.id)); + expect(settled).toMatchObject({ leasePolicy: policy, status: "released", cleanupStatus: "success", + providerLeaseId: f.providerLeaseId }); + expect(settled.metadata?.remoteExecutionTermination).toMatchObject({ state: "stopped" }); + if (policy === "reuse_by_environment") { + expect(settled.metadata?.workspaceRestoreRecovery).toBeUndefined(); + expect(settled.metadata?.workspaceRestoreRecoverySettled).toMatchObject({ runId: f.runId, actionId: f.actionId, + restoredLeasePolicy: "reuse_by_environment" }); + expect(await legacyShutdownWorkspaceResourceProtected(db, settled)).toBe(false); + expect(await inspectWorkspaceSource(db, { companyId: f.companyId, issueId: f.issueId, runId: f.runId, actionId: f.actionId })) + .toMatchObject({ status: "verified" }); + } else { + expect(settled.metadata?.workspaceRestoreRecovery).toMatchObject({ runId: f.runId }); + expect(await legacyShutdownWorkspaceResourceProtected(db, settled)).toBe(true); + } + }, 30_000); + it.each(["active", "active_run", "active_control", "foreign_company", "environment", "workspace", "task", "agent", "unfinalized", "owner", "missing_proof", "conflicting_proof", "dangling_proof", "extra_history"])( "keeps ambiguous warm source history fenced: %s", async fault => { const f = await warmHandoffSource(); diff --git a/server/src/services/workspace-recovery.ts b/server/src/services/workspace-recovery.ts index 90e329af465..656d8ba83d9 100644 --- a/server/src/services/workspace-recovery.ts +++ b/server/src/services/workspace-recovery.ts @@ -37,6 +37,7 @@ import { canAdoptNativeSourceRetention, retainNativeRecoverySource, settleRecove import { saveRemoteWorkspace } from "./remote-workspaces.js"; import { continueFromLastSavedWorkspace, isUnverifiableSourceFailure, recordRetainedSourceFallbackDeferral, settleExhaustedRetainedHold } from "./workspace-recovery-fallback.js"; import { retainedSourceFallbackDueCondition } from "./workspace-recovery-fallback-discovery.js"; +import { settleRecoveredWorkspaceRestoreHolds } from "./workspace-restore-hold-settlement.js"; const exportCauses = ["native_workspace_sync_out_unrecoverable", "native_workspace_sync_out_retry_exhausted"]; const terminal = ["failed", "interrupted", "timed_out", "cancelled", "succeeded"]; @@ -446,6 +447,9 @@ export async function recoverRetainedWorkspace(input: Source & { db: Db; environ throw new Error("workspace_recovery_generation_changed"); if (inspected.action.evidence.nativeSourceRetention && !await settleRecoveredNativeSourceRetention(tx as unknown as Db, input, next.preservationOperationIds)) throw new SystemRecoveryFailure("effect_unresolved", "recheck_evidence"); + // A settled restore hold returns its warm sandbox to reuse. A hold that + // fails any guard keeps its protection; the saved files still count. + await settleRecoveredWorkspaceRestoreHolds(tx as unknown as Db, input); return persistActivity(tx as unknown as Db, { companyId: input.companyId, actorType: "system", actorId: "workspace-recovery", action: "issue.workspace_recovered", entityType: "issue", entityId: input.issueId, runId: input.runId, details: { recoveryActionId: input.actionId, summary: "Saved work recovered." } }); diff --git a/server/src/services/workspace-restore-hold-settlement.ts b/server/src/services/workspace-restore-hold-settlement.ts new file mode 100644 index 00000000000..ce56a0bf988 --- /dev/null +++ b/server/src/services/workspace-restore-hold-settlement.ts @@ -0,0 +1,87 @@ +import { and, eq, ne, sql } from "drizzle-orm"; +import { environmentLeases, heartbeatRuns, issueRecoveryActions, workspaceOperations, type Db } from "@paperclipai/db"; +import { remoteWorkspaceRunReferenceSchema } from "@paperclipai/shared"; +import { retiredReusableLeasePredecessors } from "./environment-lease-handoff.js"; +import { nativeWorkspaceExportPendingForLease } from "./native-runtime/native-workspace-finalization-state.js"; +import { readNativeWorkspaceSyncReference } from "./native-runtime/native-workspace-sync.js"; +import { hasConfirmedSandboxStopAndRetain } from "./sandbox-stop-and-retain.js"; +import { completedWorkspaceRecoveryCondition } from "./workspace-recovery-receipt.js"; +import { LEGACY_WORKSPACE_RECOVERY_KEY, LEGACY_WORKSPACE_RECOVERY_SCHEMA, SETTLED_WORKSPACE_RESTORE_HOLD_KEY } from "./workspace-restore-recovery-state.js"; + +type Source = { companyId: string; issueId: string; runId: string; actionId: string }; + +/** + * A restore hold stops a warm sandbox and changes its lease to + * `retain_on_failure` only while its files are at risk. Once recovery has + * saved them, return the sandbox to warm reuse so the next run resumes it + * instead of paying a new allocation and a full workspace realize. + * + * Call inside the transaction that completes the recovery. Every guard is + * checked again against the current row, and the policy write is a + * compare-and-swap on the exact metadata that was checked. A hold that has not + * settled, holds unsaved writer state, or has an ambiguous owner keeps its + * protection. Returns the lease IDs returned to reuse. + */ +export async function settleRecoveredWorkspaceRestoreHolds(db: Db, input: Source): Promise { + const [run] = await db.select().from(heartbeatRuns).where(and( + eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, input.runId))); + if (!run) return []; + // A recovered workspace whose recorded disposition is `destroy` owes cleanup + // (scheduleRecoveredWorkspaceCleanup), not reuse. + const legacy = readNativeWorkspaceSyncReference(run.runnerProfileJson?.nativeWorkspaceSync); + const remote = remoteWorkspaceRunReferenceSchema.safeParse(run.runnerProfileJson?.remoteWorkspace); + const disposition = legacy?.resourceDisposition ?? (remote.success ? run.runnerProfileJson?.nativeResourceDisposition : undefined); + if (disposition === "destroy") return []; + // The hold settled only when this recovery is complete with saved files and + // its own workspace_finalize receipt. + const [action] = await db.select({ evidence: issueRecoveryActions.evidence }).from(issueRecoveryActions).where(and( + eq(issueRecoveryActions.companyId, input.companyId), eq(issueRecoveryActions.sourceIssueId, input.issueId), + eq(issueRecoveryActions.id, input.actionId), completedWorkspaceRecoveryCondition(run.id))).limit(1); + const operationIds = (action?.evidence.systemRecovery as { preservationOperationIds?: unknown } | undefined)?.preservationOperationIds; + if (!action || !Array.isArray(operationIds)) return []; + const leases = await db.select().from(environmentLeases).where(and( + eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.heartbeatRunId, run.id), + eq(environmentLeases.leasePolicy, "retain_on_failure"), eq(environmentLeases.status, "released"), + sql`${environmentLeases.metadata}->${LEGACY_WORKSPACE_RECOVERY_KEY}->>'schema' = ${LEGACY_WORKSPACE_RECOVERY_SCHEMA}`, + sql`${environmentLeases.metadata}->${LEGACY_WORKSPACE_RECOVERY_KEY}->>'runId' = ${run.id}`)); + const restored: string[] = []; + for (const lease of leases) { + const marker = lease.metadata![LEGACY_WORKSPACE_RECOVERY_KEY] as Record; + // Only a hold over a reusable sandbox returns to reuse. Rows saved before + // the marker recorded the original policy prove it by their reuse scope, + // which only a `reuse_by_environment` acquisition writes. + const original = marker.originalLeasePolicy + ?? (isRecord(lease.metadata?.reusableSandboxLease) ? "reuse_by_environment" : undefined); + if (original !== "reuse_by_environment" || !lease.provider || !lease.providerLeaseId) continue; + // The stop that the hold required is confirmed and nothing is reopening it. + if (!hasConfirmedSandboxStopAndRetain(lease)) continue; + // These files were saved by this recovery, from this exact allocation. + const [saved] = await db.select({ id: workspaceOperations.id }).from(workspaceOperations).where(and( + eq(workspaceOperations.companyId, input.companyId), eq(workspaceOperations.heartbeatRunId, run.id), + eq(workspaceOperations.status, "succeeded"), + sql`${workspaceOperations.id}::text in (select jsonb_array_elements_text(${JSON.stringify(operationIds)}::jsonb))`, + sql`${workspaceOperations.metadata}->>'leaseId' = ${lease.id}`, + sql`${workspaceOperations.metadata}->>'providerLeaseId' = ${lease.providerLeaseId}`)).limit(1); + if (!saved) continue; + // No unsaved writer or pending native export may remain on the allocation. + if (await nativeWorkspaceExportPendingForLease(db, lease)) continue; + // A single verified owner chain: any other live owner keeps the hold. + const history = await db.select().from(environmentLeases).where(and(ne(environmentLeases.id, lease.id), + eq(environmentLeases.provider, lease.provider), eq(environmentLeases.providerLeaseId, lease.providerLeaseId))); + if (!retiredReusableLeasePredecessors(lease, history)) continue; + const { [LEGACY_WORKSPACE_RECOVERY_KEY]: _held, ...metadata } = lease.metadata!; + const [updated] = await db.update(environmentLeases).set({ leasePolicy: "reuse_by_environment", updatedAt: new Date(), + metadata: { ...metadata, [SETTLED_WORKSPACE_RESTORE_HOLD_KEY]: { ...marker, actionId: input.actionId, + snapshotOperationId: saved.id, restoredLeasePolicy: "reuse_by_environment", settledAt: new Date().toISOString() } }, + }).where(and(eq(environmentLeases.companyId, input.companyId), eq(environmentLeases.id, lease.id), + eq(environmentLeases.heartbeatRunId, run.id), eq(environmentLeases.leasePolicy, "retain_on_failure"), + eq(environmentLeases.status, "released"), sql`${environmentLeases.metadata} = ${JSON.stringify(lease.metadata)}::jsonb`, + )).returning({ id: environmentLeases.id }); + if (updated) restored.push(updated.id); + } + return restored; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} diff --git a/server/src/services/workspace-restore-recovery-state.ts b/server/src/services/workspace-restore-recovery-state.ts index cba45f39d5e..e4fd3c88c3c 100644 --- a/server/src/services/workspace-restore-recovery-state.ts +++ b/server/src/services/workspace-restore-recovery-state.ts @@ -3,6 +3,9 @@ import { hasWorkspaceRestoreFailure } from "@paperclipai/shared"; export const LEGACY_WORKSPACE_RECOVERY_KEY = "workspaceRestoreRecovery"; export const LEGACY_WORKSPACE_RECOVERY_SCHEMA = "paperclip.workspace-restore-recovery.v1"; +/** Lease metadata that replaces the hold marker once recovery saved the files + * and returned the warm sandbox to reuse. It grants no recovery authority. */ +export const SETTLED_WORKSPACE_RESTORE_HOLD_KEY = "workspaceRestoreRecoverySettled"; /** The admitted external contract can prohibit workspace access even though its * managed Runner has a synchronization descriptor for durable recovery. That diff --git a/tests/perf/issue-detail/README.md b/tests/perf/issue-detail/README.md index f121475c2fd..27069fa031f 100644 --- a/tests/perf/issue-detail/README.md +++ b/tests/perf/issue-detail/README.md @@ -50,6 +50,33 @@ harness validates the task identity before measuring. Network spans in the trace use recorded request start/end timestamps relative to task navigation; they include completed requests observed during the sample, even after content paint. +## Real-instance click harness + +Local fixtures cannot reproduce staging's network round trips, server contention +or object-store latency. `staging-click-harness.js` measures the same journey on +any running instance, including staging, from the signed-in browser: + +1. Open an Issues list, for example `//issues?view=mine`. +2. Paste the file into the DevTools console (or evaluate it through a browser + automation tool). +3. Run `await __taskOpenHarness.series(["ABC-1", "ABC-2", "ABC-3"])`. + +Each sample reports the time from the row click to a visible composer and to the +latest message in the viewport, the requests started before that point, the +requests that finished last before it (`releasedBy`), the slowest and repeated +requests, layout shifts, and any movement of the latest message after it first +appeared. `serverMs` comes from the `paperclip_api` Server-Timing entry that every +API response carries, so a long `duration` with a short `serverMs` points to the +network or browser queueing rather than the handler. A fetch that is still +running when the sample ends is listed with `pending: true`. Run samples +serially and record whether each task's data was already cached (a revisit) or +not. + +The summary labels each sample (`sample 1`, ...) instead of the task reference. +It replaces query values and every path segment that contains a digit with a +placeholder. Other path segments can stay, so review the output before you +share it outside the instance. + ## Task layout stability The normal browser CI suite also runs `tests/e2e/task-loading-frame.spec.ts`. diff --git a/tests/perf/issue-detail/staging-click-harness.js b/tests/perf/issue-detail/staging-click-harness.js new file mode 100644 index 00000000000..035a6264ccf --- /dev/null +++ b/tests/perf/issue-detail/staging-click-harness.js @@ -0,0 +1,182 @@ +// Task-open click harness for real instances (staging, production, local). +// +// Paste into DevTools (or run via a browser automation tool) on an Issues list +// page such as //issues?view=mine, then call: +// +// await __taskOpenHarness.measure("ABC-123") // click the row, time it +// await __taskOpenHarness.series(["ABC-1", "ABC-2"]) // back to the list between samples +// +// Each sample starts at the row click and records, on every animation frame: +// composerVisible the composer input is rendered and not concealed +// latestVisible the last conversation message is visible in the viewport +// threadMounted the chat thread element exists +// settled 3 s without the latest message changing, growing or moving +// plus layout shifts, moves of the latest message after it first appeared, and +// every API request started after the click with its server time (Server-Timing). +// A fetch that is still running when the sample ends is reported with +// `pending: true` and the time it has run so far. +// +// The summary labels each sample ("sample 1", ...) instead of the task +// reference. In request paths it replaces query values and every path segment +// that contains a digit (UUIDs, task references, numeric ids) with a +// placeholder. Review the output before you share it: other path segments, +// such as a company prefix, can stay. The harness reads only what the browser +// already received; nothing is sent. +(() => { + const visible = (el) => + Boolean(el && el.checkVisibility({ opacityProperty: true, visibilityProperty: true }) && el.getBoundingClientRect().height > 0); + const inViewport = (el) => { + const rect = el.getBoundingClientRect(); + return rect.bottom > 0 && rect.top < innerHeight && rect.height > 0; + }; + const scrub = (url) => { + const parsed = new URL(url, location.href); + const path = parsed.pathname + .split("/") + .map((segment) => (/\d/.test(segment) ? "" : segment)) + .join("/"); + const keys = [...parsed.searchParams.keys()]; + return keys.length > 0 ? `${path}?${keys.join("&")}` : path; + }; + const isApi = (url) => new URL(url, location.href).pathname.includes("/api/"); + const serverMs = (entry) => { + const metric = (entry.serverTiming || []).find((timing) => timing.name === "paperclip_api"); + return metric ? Math.round(metric.duration) : null; + }; + + let sampleCount = 0; + + async function measure(issueRef, { timeoutMs = 20_000, quietMs = 3_000, label } = {}) { + performance.setResourceTimingBufferSize(10_000); + const link = document.querySelector(`a[href$="/issues/${issueRef}"]`); + if (!link) throw new Error(`No visible row link for ${issueRef}`); + sampleCount += 1; + const sample = label ?? `sample ${sampleCount}`; + const shifts = []; + const observer = new PerformanceObserver((list) => { + for (const entry of list.getEntries()) if (!entry.hadRecentInput) shifts.push(entry); + }); + observer.observe({ type: "layout-shift", buffered: false }); + const marks = {}; + const latestChanges = []; + const latestMoves = []; + let latestKey = null; + let latestElement = null; + let latestTop = null; + // Resource Timing has no entry for a request that is still running, so + // record fetch starts too. In-flight fetches are reported as pending. + const fetches = []; + const originalFetch = window.fetch; + window.fetch = function (input, init) { + const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; + const record = { url, start: performance.now(), done: false }; + fetches.push(record); + const result = originalFetch.call(this, input, init); + const finish = () => { + record.done = true; + }; + result.then(finish, finish); + return result; + }; + const t0 = performance.now(); + link.click(); + await new Promise((resolve) => { + const tick = () => { + const t = performance.now() - t0; + const thread = document.querySelector("[data-testid=task-chat-thread]"); + if (marks.threadMounted === undefined && thread) marks.threadMounted = t; + const composer = document.querySelector("[data-testid=task-chat-composer-input]"); + if (marks.composerVisible === undefined && visible(composer)) marks.composerVisible = t; + const messages = document.querySelectorAll("[data-conversation-message]"); + const latest = messages[messages.length - 1]; + if (latest && visible(latest) && inViewport(latest)) { + if (marks.latestVisible === undefined) marks.latestVisible = t; + // Text appended to a live message, or a message that grows in place, + // counts as a change, so `settled` waits for the output to stop. + const rect = latest.getBoundingClientRect(); + const text = latest.textContent || ""; + const key = `${messages.length}|${text.length}|${text.slice(-80)}|${Math.round(rect.height)}`; + if (key !== latestKey) { + latestChanges.push(Math.round(t)); + latestKey = key; + } + // Compare positions only for the same message element. A message + // that grows upward while the chat stays pinned to the bottom is a + // move; a different latest message starts a new position baseline. + if (latest !== latestElement) { + latestElement = latest; + latestTop = null; + } + const top = rect.top; + if (latestTop !== null && Math.abs(top - latestTop) > 2) latestMoves.push({ t: Math.round(t), dy: Math.round(top - latestTop) }); + latestTop = top; + } + const lastEvent = Math.max(latestChanges.at(-1) ?? 0, latestMoves.at(-1)?.t ?? 0); + if (marks.composerVisible !== undefined && marks.latestVisible !== undefined && t - lastEvent > quietMs) { + marks.settled = t; + return resolve(); + } + if (t > timeoutMs) return resolve(); + requestAnimationFrame(tick); + }; + requestAnimationFrame(tick); + }); + observer.disconnect(); + window.fetch = originalFetch; + const end = performance.now(); + const ready = Math.max(marks.composerVisible ?? Infinity, marks.latestVisible ?? Infinity); + const completed = performance + .getEntriesByType("resource") + .filter((entry) => entry.startTime >= t0 - 5 && isApi(entry.name)) + .map((entry) => ({ + url: scrub(entry.name), + start: Math.round(entry.startTime - t0), + duration: Math.round(entry.duration), + serverMs: serverMs(entry), + })); + const pending = fetches + .filter((record) => !record.done && isApi(record.url)) + .map((record) => ({ + url: scrub(record.url), + start: Math.round(record.start - t0), + duration: Math.round(end - record.start), + serverMs: null, + pending: true, + })); + const requests = [...completed, ...pending]; + const beforeReady = requests.filter((request) => request.start < ready); + const counts = {}; + for (const request of requests) counts[request.url] = (counts[request.url] ?? 0) + 1; + return { + sample, + marks: Object.fromEntries(Object.entries(marks).map(([key, value]) => [key, Math.round(value)])), + cls: Number(shifts.reduce((sum, entry) => sum + entry.value, 0).toFixed(4)), + latestMoves, + requests: { total: requests.length, beforeReady: beforeReady.length, pending: pending.length }, + // Requests that finished in the 250 ms before the page was ready. A + // request that finished after that point did not release the reveal. + releasedBy: completed + .filter((request) => request.start < ready) + .filter((request) => request.start + request.duration > ready - 250 && request.start + request.duration <= ready) + .sort((a, b) => b.start + b.duration - (a.start + a.duration)) + .slice(0, 3), + slowest: [...requests].sort((a, b) => b.duration - a.duration).slice(0, 5), + repeated: Object.entries(counts).filter(([, count]) => count > 1).map(([url, count]) => `${url} x${count}`), + }; + } + + async function series(issueRefs, options = {}) { + const listUrl = location.pathname + location.search; + const samples = []; + for (const issueRef of issueRefs) { + if (location.pathname + location.search !== listUrl) { + history.back(); + await new Promise((resolve) => setTimeout(resolve, options.listSettleMs ?? 3_000)); + } + samples.push(await measure(issueRef, options)); + } + return samples; + } + + window.__taskOpenHarness = { measure, series }; +})(); diff --git a/tests/restart-chaos/README.md b/tests/restart-chaos/README.md index ddc2881ae27..295fd115f5c 100644 --- a/tests/restart-chaos/README.md +++ b/tests/restart-chaos/README.md @@ -115,7 +115,10 @@ S1 is the board's Stop button. While the task's run is running, the harness canc comments that it stopped the run on purpose and asks the agent to continue with an extra marker line. The oracle checks that the stopped run ended `cancelled`, that nothing started between the stop and the continue comment (recovery must not restart work the operator stopped), and that the -finished brief has both markers. S1 is not a default workload. +finished brief has both markers. The Stop waits for a ready server with no fault in progress. If the +run already finished when the stop window opens, the harness records a missed Stop +(`task_stop_missed`), skips the stop-triggered fault, still posts the continue comment, and the +oracle checks only the continue. S1 is not a default workload. ## Code change in a real repository (R1, `--workspace-repo`) @@ -306,6 +309,12 @@ re-arms the task's own triggered faults instead of using their offsets. `RESTART_CHAOS_ALLOW_UNSANDBOXED_ORACLE=1` is set inside a disposable VM. - R1 allows the workload budget plus outage time. When a Retry was needed R1 is `n/a` and R3 decides; a task that rests unfinished with no Retry fails both. + A task that never rested within its deadline fails R1 as `no_rest_within_budget`, + whatever its last status. +- Speed: an aggregate p50/p95 row can breach only with at least 5 samples; a + smaller row is reported as `insufficient sample (n < 5)`. Every cold or warm run + over its p95 budget, and every restart recovery whose Paperclip share exceeds + its p95 budget, still fails the wave on its own. - Faults are serialized; each one hits every task running at that moment. - A `todo` or `in_progress` task with no live run and no named wait is not a rest. The observer keeps watching it until it resumes or passes the R5 stall limit. - R5 also fails a run that stays `running` with no live evidence (no new run event, `lastUsefulActionAt` or `execution.lastConfirmedActivityAt`, and no start) for more than 3 minutes after the server is ready. A `running` status alone is not proof of life. A quiet run is still live while a tool it started has not ended (for example a 4-minute `bench.sh`) or while its recorded local runner process still runs with the same PID and start time. diff --git a/tests/restart-chaos/config.ts b/tests/restart-chaos/config.ts index 8852fd00693..246fb37f786 100644 --- a/tests/restart-chaos/config.ts +++ b/tests/restart-chaos/config.ts @@ -136,11 +136,13 @@ export function parseCommand(argv: readonly string[], now = Date.now()): ParsedC } } if (lifecycle !== undefined && lifecycle !== "per_turn" && lifecycle !== "warm" && lifecycle !== "default") throw new Error("--lifecycle must be per_turn, warm or default"); + const adapters = list(values.adapters, ADAPTER_IDS, "adapters", ["codex", "claude"]); const options: WaveOptions = { env, - adapters: list(values.adapters, ADAPTER_IDS, "adapters", ["codex", "claude"]), + adapters, // The governance scenarios (G1, H1) are opt-in: H1 needs a wave of its own. - workloads: list(values.workloads, workloadChoices, "workloads", workloadChoices.filter(id => id !== "G1" && id !== "H1" && id !== "R1" && id !== "S1")), + workloads: list(values.workloads, workloadChoices, "workloads", workloadChoices.filter(id => id !== "G1" && id !== "H1" && id !== "R1" && id !== "S1" + && (id !== "M1" || adapters.length >= 2))), // A crash-point wave schedules no fault; K1 is the restart its self-kill gets. faults: list(values.faults, FAULT_KINDS, "faults", stormMinutes ? STORM_DEFAULT_FAULTS : crashPoint ? ["K1"] : ["K1", "K2", "K4"]), triggers: list(values.triggers, TRIGGER_IDS, "triggers", ["time"]), diff --git a/tests/restart-chaos/governance.test.ts b/tests/restart-chaos/governance.test.ts index 0ce5a2d189b..dd99a549b44 100644 --- a/tests/restart-chaos/governance.test.ts +++ b/tests/restart-chaos/governance.test.ts @@ -6,7 +6,7 @@ import { BUDGET_PAUSE_HOLD_MS, BUDGET_RESUME_HEADROOM_CENTS, REST_CONFIRM_MS, Ta import { planTasks, replayOnCurrentBuild, triggerFitsWorkload } from "./scheduler.js"; import type { ChaosLab } from "./seed.js"; import { Timeline } from "./timeline.js"; -import type { OracleArtifacts, TaskPlan, TaskRecord, TaskSample, WavePlan } from "./types.js"; +import type { FaultReceipt, OracleArtifacts, TaskPlan, TaskRecord, TaskSample, WavePlan } from "./types.js"; import { g1ApprovalTitle, g1ChildTitle, g1Decision, workloadDefinitions } from "./workloads.js"; process.env.RESTART_CHAOS_QUIET = "1"; @@ -127,6 +127,9 @@ describe("G1: approval-gated action across a restart", () => { createdAt: 0, restAt: 60_000, samples: [] } as unknown as TaskRecord; expect(gradeR1(record, 15 * 60_000, []).verdict).toBe("pass"); expect(gradeR1({ ...record, finalStatus: "done" }, 15 * 60_000, []).verdict).toBe("fail"); + const unrested = gradeR1({ ...record, timedOut: true, restAt: null }, 15 * 60_000, + [{ startedAt: 1_000, readyAt: null, healthyAt: null } as unknown as FaultReceipt]); + expect(unrested).toEqual({ verdict: "fail", detail: "no_rest_within_budget (last status cancelled)" }); }); it("counts a redacted approval title as the task's own", () => { diff --git a/tests/restart-chaos/grader.test.ts b/tests/restart-chaos/grader.test.ts index 79f0043516b..424399704b5 100644 --- a/tests/restart-chaos/grader.test.ts +++ b/tests/restart-chaos/grader.test.ts @@ -247,6 +247,11 @@ describe("T-oracles", () => { expect(restarted.checks.find(check => check.name === "nothing_ran_after_stop")).toMatchObject({ ok: false, detail: "continue=true runs=r2" }); expect(workloadDefinitions.S1.grade("abcd1234", { ...base, stop: { ...base.stop!, runStatus: "succeeded" } }).verdict).toBe("fail"); expect(workloadDefinitions.S1.grade("abcd1234", { ...base, stop: undefined }).verdict).toBe("fail"); + const missed = workloadDefinitions.S1.grade("abcd1234", { ...base, stop: { runId: null, runStatus: null, runsStartedBeforeContinue: [], continuePosted: true, missed: true } }); + expect(missed.verdict).toBe("pass"); + expect(missed.checks.find(check => check.name === "stop_took_effect")).toMatchObject({ ok: true, detail: "missed: the run finished before the stop window" }); + expect(workloadDefinitions.S1.grade("abcd1234", { ...base, documents: { brief: "CHAOS-abcd1234\n- one\n- two\n- three\n" }, + stop: { runId: null, runStatus: null, runsStartedBeforeContinue: [], continuePosted: true, missed: true } }).verdict).toBe("fail"); }); it("grades B1 by running the tests and the CLI", () => { diff --git a/tests/restart-chaos/grader.ts b/tests/restart-chaos/grader.ts index 33963debf17..282473f4ecc 100644 --- a/tests/restart-chaos/grader.ts +++ b/tests/restart-chaos/grader.ts @@ -61,8 +61,9 @@ export function gradeR1(record: TaskRecord, budgetMs: number, faults: readonly F if (record.launchError) return { verdict: "fail", detail: `launch_failed: ${record.launchError}` }; if (record.retry) return { verdict: "n/a", detail: "task rested needing Retry; graded under R3" }; const expected = expectedFinalStatus(record); + if (record.timedOut) return { verdict: "fail", detail: `no_rest_within_budget (last status ${record.finalStatus ?? "unknown"})` }; if (record.finalStatus !== expected) { - return { verdict: "fail", detail: record.timedOut ? `no_rest_within_budget (last status ${record.finalStatus ?? "unknown"})` : `rested_not_done (status ${record.finalStatus ?? "unknown"}, no Retry offered)` }; + return { verdict: "fail", detail: `rested_not_done (status ${record.finalStatus ?? "unknown"}, no Retry offered)` }; } const allowed = budgetMs + outageOverlapMs(record, faults); const took = (record.restAt ?? Number.POSITIVE_INFINITY) - record.createdAt!; diff --git a/tests/restart-chaos/main.ts b/tests/restart-chaos/main.ts index 7c3ac613c10..ffaa6943207 100644 --- a/tests/restart-chaos/main.ts +++ b/tests/restart-chaos/main.ts @@ -22,7 +22,7 @@ import { gradeTask } from "./grader.js"; import { checkPlanInvariants, summarizeViolations, type InvariantCheck } from "./invariants.js"; import { appendLedger, ledgerLine, writeSummary, type LedgerLine } from "./ledger.js"; import { collectWaveSpeed, speedMarkdown } from "./wave-speed.js"; -import { TaskObserver } from "./observer.js"; +import { TaskObserver, childSpeedTasksInTurn } from "./observer.js"; import { StormRun, TASK_FAULT_LOG, observedFaultSchedule, planWave, replayOnCurrentBuild, replayRecordFor, replayWave, type TaskFaultLog } from "./scheduler.js"; import { chaosLifecycleOverrides, seedChaosLab } from "./seed.js"; import { ChaosSupervisor } from "./supervisor.js"; @@ -469,8 +469,7 @@ async function main(): Promise { } await writeFile(path.join(waveDir, "faults.json"), `${JSON.stringify(faults, null, 2)}\n`, { mode: 0o600 }); const speed = await (async () => { - const childTasks: Awaited> = []; - for (const observer of launched) childTasks.push(...await observer.childSpeedTasks()); + const childTasks = await childSpeedTasksInTurn(launched); return collectWaveSpeed(api, plan.options.env, [...launched.flatMap(observer => observer.record.issueId ? [{ issueId: observer.record.issueId, adapter: observer.plan.adapter, samples: observer.record.samples }] : []), ...childTasks], faults); })().catch(error => { timeline.add("wave_speed_failed", { error: String(error) }); anyFailure = true; return null; }); diff --git a/tests/restart-chaos/observer.test.ts b/tests/restart-chaos/observer.test.ts index 2e0cba8b33f..fc0f5bb3366 100644 --- a/tests/restart-chaos/observer.test.ts +++ b/tests/restart-chaos/observer.test.ts @@ -4,7 +4,7 @@ import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import type { ChaosApi } from "./api.js"; -import { CHILD_WAKE_GRACE_MS, REST_CONFIRM_MS, STALL_GIVE_UP_MS, STOP_CONTINUE_AFTER_MS, TaskObserver, childrenPending, listWorkspaceFiles } from "./observer.js"; +import { CHILD_WAKE_GRACE_MS, REST_CONFIRM_MS, STALL_GIVE_UP_MS, STOP_CONTINUE_AFTER_MS, TaskObserver, childSpeedTasksInTurn, childrenPending, listWorkspaceFiles } from "./observer.js"; import { gradeTask } from "./grader.js"; import { createFixtureRepository, type ChaosLab } from "./seed.js"; import { Timeline } from "./timeline.js"; @@ -142,6 +142,31 @@ describe("TaskObserver", () => { expect(childRetries).toHaveLength(1); }); + it("M1: rereads a parent whose read failed on the next poll, and reads each stall wake from the parent's activity", async () => { + const base = fakeApi({ "parentIds=": () => [{ id: "c2", parentId: "i1", status: "blocked" }], "/documents/": () => null, "/comments": () => [], + "/workspace-operations": () => [], "/api/issues/c2": () => ({ id: "c2", status: "blocked", interruption: { canRetry: false } }), + "/activity": () => [{ action: "issue.blocker_stalled_wake", details: { stalledIssueId: "c2", recoveryActionId: "a1" } }, + { action: "issue.updated", details: {} }, { action: "issue.blocker_stalled_wake", details: {} }] }, "blocked"); + let failNextStallRead = false; + const api = { ...base.api, async get(route: string, timeoutMs?: number) { + if (route === "/api/issues/i1") { + if (timeoutMs === undefined && failNextStallRead) { failNextStallRead = false; throw new Error("503"); } + return { id: "i1", status: "blocked", stalledDependencies: [{ stalledIssueId: "c2", relation: "child", recoveryAction: { id: "a1", ownerType: "board" } }] }; + } + return base.api.get(route); + }, post: base.api.post.bind(base.api) } as unknown as ChaosApi; + const observer = new TaskObserver({ ...plan, workload: "M1", followUpAfterMs: null }, api, lab, new Timeline(null), ready); + await observer.launch(); + const start = observer.record.createdAt!; + failNextStallRead = true; + await observer.poll(start + 1_000); + expect(observer.record.childStalls ?? []).toEqual([]); + await observer.poll(start + 2_000); + expect(observer.record.childStalls).toEqual([{ childIssueId: "c2", recoveryActionId: "a1" }]); + const artifacts = await observer.collectArtifacts(); + expect(artifacts.stallWakes).toEqual([{ stalledIssueId: "c2", recoveryActionId: "a1" }, { stalledIssueId: null, recoveryActionId: null }]); + }); + it("S1: stops the running run as the board would, then posts the continue comment only after it settles", async () => { let runStatus = "running"; const base = fakeApi({ "/runs": () => [{ id: "r1", status: runStatus, createdAt: new Date(0).toISOString(), finishedAt: null }] }, "in_progress"); @@ -164,6 +189,67 @@ describe("TaskObserver", () => { expect(posted.filter(route => route.endsWith("/cancel"))).toHaveLength(1); }); + it("S1: holds the Stop while another task's fault has the server down or recovering", async () => { + const base = fakeApi({ "/runs": () => [{ id: "r1", status: "running", createdAt: new Date(0).toISOString(), finishedAt: null }] }, "in_progress"); + const posted: string[] = []; + const api = { ...base.api, get: base.api.get.bind(base.api), async post(route: string) { + posted.push(route); + return route.endsWith("/issues") ? { id: "i1", identifier: "CHA-1" } : { id: "r1" }; + } } as unknown as ChaosApi; + const supervisor = { serverReady: true, faultInProgress: false }; + const observer = new TaskObserver({ ...plan, workload: "S1", followUpAfterMs: 1_000 }, api, lab, new Timeline(null), supervisor); + await observer.launch(); + supervisor.faultInProgress = true; + await observer.poll(observer.record.createdAt! + 2_000); + expect(posted.filter(route => route.endsWith("/cancel"))).toEqual([]); + supervisor.faultInProgress = false; + await observer.poll(observer.record.createdAt! + 3_000); + expect(posted.filter(route => route.endsWith("/cancel"))).toEqual(["/api/heartbeat-runs/r1/cancel"]); + }); + + it("S1: records a missed Stop and still posts the continue comment when the run finished before the stop window", async () => { + const base = fakeApi({ "/runs": () => [{ id: "r1", status: "succeeded", createdAt: new Date(0).toISOString(), finishedAt: new Date(1).toISOString() }], + "/comments": () => [], "/documents/": () => null, "/workspace-operations": () => [] }, "done"); + const posted: string[] = []; + const api = { ...base.api, get: base.api.get.bind(base.api), async post(route: string) { + posted.push(route); + return route.endsWith("/issues") ? { id: "i1", identifier: "CHA-1" } : { id: "comment-1" }; + } } as unknown as ChaosApi; + const timeline = new Timeline(null); + const observer = new TaskObserver({ ...plan, workload: "S1", followUpAfterMs: 1_000 }, api, lab, timeline, ready); + await observer.launch(); + const start = observer.record.createdAt!; + await observer.poll(start + 2_000); + expect(observer.record.stop).toMatchObject({ runId: null, missed: true }); + expect(timeline.entries.some(entry => entry.kind === "task_stop_missed")).toBe(true); + await observer.poll(start + 2_000 + STOP_CONTINUE_AFTER_MS + 1); + expect(observer.record.followUp).toMatchObject({ commentId: "comment-1" }); + expect(posted.filter(route => route.endsWith("/cancel"))).toEqual([]); + expect((await observer.collectArtifacts()).stop).toMatchObject({ missed: true, continuePosted: true, runsStartedBeforeContinue: [] }); + }); + + it("S1: arms a stop-triggered fault at the Stop click plus its delay, and misses it when the Stop was missed", async () => { + const running = fakeApi({ "/runs": () => [{ id: "r1", status: "running", createdAt: new Date(0).toISOString(), finishedAt: null }] }, "in_progress"); + const stopPlan: TaskPlan = { ...plan, workload: "S1", followUpAfterMs: 1_000, trigger: "stop", triggerDelayMs: 500 }; + const observer = new TaskObserver(stopPlan, running.api, lab, new Timeline(null), ready); + await observer.launch(); + const start = observer.record.createdAt!; + expect(observer.faultDue(start + 5_000)).toBeNull(); + await observer.poll(start + 2_000); + const clicked = observer.record.stop!.at; + expect(observer.faultDue(clicked + 499)).toBeNull(); + expect(observer.faultDue(clicked + 500)).toMatchObject({ trigger: "stop", kind: "K1" }); + + const finished = fakeApi({ "/runs": () => [{ id: "r1", status: "succeeded", createdAt: new Date(0).toISOString(), finishedAt: new Date(1).toISOString() }] }, "done"); + const timeline = new Timeline(null); + const missed = new TaskObserver(stopPlan, finished.api, lab, timeline, ready); + await missed.launch(); + await missed.poll(missed.record.createdAt! + 2_000); + expect(missed.record.stop).toMatchObject({ missed: true }); + expect(missed.faultDue(missed.record.createdAt! + 2_600)).toBeNull(); + expect(missed.record.triggerMissed).toEqual(["stop"]); + }); + it("S1: does not count the continue comment's own run as a run after the stop, even when it starts before the comment returns", async () => { let runs: Array> = [{ id: "r1", status: "running", createdAt: new Date(0).toISOString(), finishedAt: null }]; const base = fakeApi({ "/runs": () => runs, "/comments": () => [], "/documents/": () => null, "/workspace-operations": () => [] }, "in_progress"); @@ -294,3 +380,18 @@ describe("childrenPending", () => { expect(childrenPending([{ status: "done" }, { status: "blocked" }])).toBe(false); }); }); + +describe("childSpeedTasksInTurn", () => { + it("reads each observer's subtasks one at a time so a large wave does not flood the API", async () => { + let inFlight = 0, peak = 0; + const observers = [1, 2, 3].map(id => ({ childSpeedTasks: async () => { + inFlight += 1; peak = Math.max(peak, inFlight); + await new Promise(resolve => setTimeout(resolve, 5)); + inFlight -= 1; + return [{ issueId: `c${id}`, adapter: "codex" as const, samples: [] }]; + } })); + expect((await childSpeedTasksInTurn(observers)).map(task => task.issueId)).toEqual(["c1", "c2", "c3"]); + expect(peak).toBe(1); + }); +}); + diff --git a/tests/restart-chaos/observer.ts b/tests/restart-chaos/observer.ts index 54155f1f253..226b53d5b32 100644 --- a/tests/restart-chaos/observer.ts +++ b/tests/restart-chaos/observer.ts @@ -52,6 +52,14 @@ export const CHILD_WAKE_GRACE_MS = 60_000; export const CHILD_STALL_CHECK_MS = 10_000; export const STOP_CONTINUE_AFTER_MS = 20_000; +type ChildSpeedTask = { issueId: string; adapter: AdapterId; samples: Array<{ runs?: RunSample[] }> }; + +export async function childSpeedTasksInTurn(observers: ReadonlyArray<{ childSpeedTasks(): Promise }>): Promise { + const tasks: ChildSpeedTask[] = []; + for (const observer of observers) tasks.push(...await observer.childSpeedTasks()); + return tasks; +} + export function childrenPending(children: ReadonlyArray<{ status: string | null }> | null): boolean { return !children || children.some(child => !["done", "cancelled", "blocked"].includes(child.status ?? "")); } @@ -348,7 +356,7 @@ export class TaskObserver { case "stop": { const stop = this.record.stop; if (!stop) return null; - return stop.error ? "missed" : stop.at; + return stop.error || stop.missed ? "missed" : stop.at; } case "result": { // B8: the run that received the follow-up has accepted its result but @@ -501,10 +509,15 @@ export class TaskObserver { } private async maybeStop(sample: TaskSample, now: number): Promise { - if (!this.definition.stopBeforeFollowUp || this.record.stop || this.plan.followUpAfterMs === null || !sample.reachable) return false; + if (!this.definition.stopBeforeFollowUp || this.record.stop || this.plan.followUpAfterMs === null || !sample.serverReady) return false; if (now < this.record.createdAt! + this.plan.followUpAfterMs) return false; const running = (sample.runs ?? []).find(run => run.status === "running"); - if (!running) return false; + if (!running) { + if (!isResting(sample)) return false; + this.record.stop = { at: now, runId: null, httpStatus: null, error: null, missed: true }; + this.timeline.add("task_stop_missed", { taskId: this.plan.taskId, status: sample.issueStatus ?? null }); + return true; + } const stop: NonNullable = { at: now, runId: running.id, httpStatus: null, error: null }; try { await this.api.post(`/api/heartbeat-runs/${running.id}/cancel`, { cancellationRequestId: randomUUID() }); @@ -588,6 +601,7 @@ export class TaskObserver { .catch(() => null); const blocked = (Array.isArray(rows) ? rows : []).filter(row => row.parentId === this.record.issueId && row.status === "blocked").map(row => String(row.id)); const parent = await this.api.get(`/api/issues/${this.record.issueId}`).catch(() => null); + if (!parent) this.childStallCheckedAt = null; const stalled = Array.isArray(parent?.stalledDependencies) ? parent.stalledDependencies as Json[] : []; for (const dependency of stalled) { if (dependency.relation !== "child" || typeof dependency.stalledIssueId !== "string") continue; @@ -611,8 +625,8 @@ export class TaskObserver { const startedBeforeContinue = [...runs.values()].filter(run => run.id !== stop.runId && run.createdAt && !(continueCommentId && (run.wakeCommentIds ?? []).includes(continueCommentId)) && Date.parse(run.createdAt) > stop.at && (continueAt === null || Date.parse(run.createdAt) < continueAt)).map(run => run.id); - return { runId: stop.runId, runStatus: runs.get(stop.runId)?.status ?? null, runsStartedBeforeContinue: startedBeforeContinue, - continuePosted: Boolean(this.record.followUp?.commentId) }; + return { runId: stop.runId, runStatus: stop.runId ? runs.get(stop.runId)?.status ?? null : null, runsStartedBeforeContinue: startedBeforeContinue, + continuePosted: Boolean(this.record.followUp?.commentId), ...(stop.missed ? { missed: true } : {}) }; } private async retryBlockedChildren(childIds: readonly string[], now: number): Promise { @@ -805,7 +819,7 @@ export class TaskObserver { runsStartedWhilePaused: governance.runsStartedWhilePaused }); } - async childSpeedTasks(): Promise }>> { + async childSpeedTasks(): Promise { if (!this.definition.collect.childDocuments || !this.record.issueId) return []; const rows = await this.api.get(`/api/companies/${this.lab.companyId}/issues?view=index&parentIds=${encodeURIComponent(this.record.issueId)}&limit=20`); const tasks: Array<{ issueId: string; adapter: AdapterId; samples: Array<{ runs?: RunSample[] }> }> = []; diff --git a/tests/restart-chaos/scheduler.test.ts b/tests/restart-chaos/scheduler.test.ts index 9a8c87fddda..455c884bbc5 100644 --- a/tests/restart-chaos/scheduler.test.ts +++ b/tests/restart-chaos/scheduler.test.ts @@ -42,6 +42,11 @@ describe("scheduler determinism", () => { expect(Math.max(...holds)).toBeGreaterThan(K4_HOLD_RANGE_MS[1]); const storm = planStorm(5, 120, ["K4"], 600_000); expect(Math.max(...storm.faults.map(fault => fault.holdMs))).toBeGreaterThan(K4_HOLD_RANGE_MS[1]); + const single = parseCommand(["--adapters", "codex", "--seed", "5"]), both = parseCommand(["--seed", "5"]); + if (single.mode !== "wave" || both.mode !== "wave") throw new Error("expected a wave"); + expect(single.options.workloads).not.toContain("M1"); + expect(both.options.workloads).toContain("M1"); + expect(() => parseCommand(["--adapters", "codex", "--workloads", "M1"])).toThrow(/two agents/); expect(() => parseCommand(["--k4-hold-max-seconds", "601"])).toThrow(/between 120 and 600/); expect(() => parseCommand(["--replay", "w-20261106T101112-s42/t03", "--k4-hold-max-seconds", "400"])).toThrow(/do not combine/); }); diff --git a/tests/restart-chaos/seed.test.ts b/tests/restart-chaos/seed.test.ts index d6a7a920d0a..380fd27f808 100644 --- a/tests/restart-chaos/seed.test.ts +++ b/tests/restart-chaos/seed.test.ts @@ -48,6 +48,18 @@ describe("seedChaosLab workspace isolation", () => { const seed = (api: ChaosApi) => seedChaosLab({ api, env: "local", adapters: ["codex"], concurrency: 2, budgetCents: 3_000, fixtureRoot, waveId: "w-test", timeline: new Timeline(null) }); + it("waits for each seeded agent to reach lifecycleState ready only when the wave asks for it", async () => { + const waiting = fakeApi(body => ({ ...body })); + const timeline = new Timeline(null); + await seedChaosLab({ api: waiting.api, env: "local", adapters: ["codex"], concurrency: 2, budgetCents: 3_000, + fixtureRoot: path.join(fixtureRoot, "waiting"), waveId: "w-test", timeline, waitForReadyAgents: true }); + expect(waiting.calls.some(call => call.method === "GET" && call.route.startsWith("/api/agents/"))).toBe(true); + expect(timeline.entries.filter(entry => entry.kind === "seed_agent_ready")).toEqual([expect.objectContaining({ adapter: "codex" })]); + const skipping = fakeApi(body => ({ ...body })); + await seed(skipping.api); + expect(skipping.calls.some(call => call.method === "GET" && call.route.startsWith("/api/agents/"))).toBe(false); + }); + // RC-21: the project's git_worktree policy is gated behind the instance's // isolated-workspaces setting. Without it every repo task ran in the shared // primary checkout, so concurrent tasks wrote into one tree. @@ -157,9 +169,26 @@ describe("waitForAgentsReady", () => { await expect(waitForAgentsReady(stuck, { codex: { id: "a3" } }, new Timeline(null), 60_000, 1, () => ++polls > 2)).rejects.toThrow(/interrupted/); }); + it("keeps waiting through a deferred verification error and passes once the retry makes the agent ready", async () => { + let reads = 0; + const api = { get: async () => (++reads < 3 ? { lifecycleState: "verifying", lifecycleError: "host busy" } : { lifecycleState: "ready" }) } as unknown as ChaosApi; + const timeline = new Timeline(null); + await waitForAgentsReady(api, { codex: { id: "a1" } }, timeline, 5_000, 1); + expect(timeline.entries.filter(entry => entry.kind === "seed_agent_lifecycle_error")).toEqual([expect.objectContaining({ adapter: "codex", error: "host busy" })]); + }); + + it("names the last read error when an agent never becomes ready", async () => { + const broken = { get: async () => { throw new Error("401 unauthorized"); } } as unknown as ChaosApi; + await expect(waitForAgentsReady(broken, { codex: { id: "a1" } }, new Timeline(null), 20, 5)).rejects.toThrow(/codex \(last read error: 401 unauthorized\)/); + const deferred = { get: async () => ({ lifecycleState: "verifying", lifecycleError: "host busy" }) } as unknown as ChaosApi; + await expect(waitForAgentsReady(deferred, { codex: { id: "a1" } }, new Timeline(null), 20, 5)).rejects.toThrow(/codex \(last lifecycle error: host busy\)/); + }); + it("fails the wave when an agent fails verification or never becomes ready", async () => { - const failed = { get: async () => ({ lifecycleState: "verifying", lifecycleError: "hello probe failed" }) } as unknown as ChaosApi; - await expect(waitForAgentsReady(failed, { claude: { id: "a2" } }, new Timeline(null), 5_000, 1)).rejects.toThrow(/hello probe failed/); + const parked = { get: async () => ({ lifecycleState: "verifying", lifecycleError: "hello probe failed" }) } as unknown as ChaosApi; + await expect(waitForAgentsReady(parked, { claude: { id: "a2" } }, new Timeline(null), 20, 5)).rejects.toThrow(/claude \(last lifecycle error: hello probe failed\)/); + const rejected = { get: async () => ({ lifecycleState: "rejected", lifecycleError: "hire rejected" }) } as unknown as ChaosApi; + await expect(waitForAgentsReady(rejected, { claude: { id: "a2" } }, new Timeline(null), 5_000, 1)).rejects.toThrow(/hire rejected/); const stuck = { get: async () => ({ lifecycleState: "verifying" }) } as unknown as ChaosApi; await expect(waitForAgentsReady(stuck, { claude: { id: "a3" } }, new Timeline(null), 20, 5)).rejects.toThrow(/never reached lifecycleState ready/); }); diff --git a/tests/restart-chaos/seed.ts b/tests/restart-chaos/seed.ts index 2ce62f5ac18..bd3fd179197 100644 --- a/tests/restart-chaos/seed.ts +++ b/tests/restart-chaos/seed.ts @@ -21,25 +21,43 @@ export interface ChaosLab { agents: Record }>; } +export const DAYTONA_AGENT_READY_TIMEOUT_MS = 10 * 60_000; +const TERMINAL_LIFECYCLE_STATES = new Set(["rejected", "terminating", "cleaning_up", "terminated"]); + /** Create the `chaos-sandbox` git repository: python CLI, one failing test, bench.sh. */ export async function waitForAgentsReady(api: ChaosApi, agents: Partial>, timeline: Timeline, timeoutMs = 4 * 60_000, pollMs = 1_000, cancelled: () => boolean = () => false): Promise { const started = Date.now(); const pending = new Map(Object.entries(agents).flatMap(([adapter, agent]) => agent ? [[adapter, agent] as const] : [])); + const lastProblem = new Map(); while (pending.size) { if (cancelled()) throw new Error("Harness interrupted while waiting for agents to finish verification"); for (const [adapter, { id: agentId, createdAt }] of [...pending]) { - const agent = await api.get>(`/api/agents/${agentId}`).catch(() => null); + let agent: Record; + try { + agent = await api.get>(`/api/agents/${agentId}`); + } catch (error) { + lastProblem.set(adapter, `last read error: ${error instanceof Error ? error.message : String(error)}`.slice(0, 300)); + continue; + } + const lifecycleError = agent?.lifecycleError ? String(agent.lifecycleError).slice(0, 300) : null; if (agent?.lifecycleState === "ready") { timeline.add("seed_agent_ready", { adapter, agentId, readyAfterMs: Date.now() - (createdAt ?? started) }); pending.delete(adapter); - } else if (agent?.lifecycleError) { - throw new Error(`Agent ${adapter} (${agentId}) failed lifecycle verification: ${String(agent.lifecycleError).slice(0, 300)}`); + } else if (lifecycleError) { + if (TERMINAL_LIFECYCLE_STATES.has(String(agent.lifecycleState))) { + throw new Error(`Agent ${adapter} (${agentId}) failed lifecycle verification: ${lifecycleError}`); + } + if (lastProblem.get(adapter) !== `last lifecycle error: ${lifecycleError}`) { + timeline.add("seed_agent_lifecycle_error", { adapter, agentId, error: lifecycleError }); + } + lastProblem.set(adapter, `last lifecycle error: ${lifecycleError}`); } } if (!pending.size) return; if (Date.now() - started > timeoutMs) { - throw new Error(`Agents never reached lifecycleState ready within ${Math.round(timeoutMs / 1000)} s: ${[...pending.keys()].join(", ")}`); + const names = [...pending.keys()].map(adapter => lastProblem.has(adapter) ? `${adapter} (${lastProblem.get(adapter)})` : adapter); + throw new Error(`Agents never reached lifecycleState ready within ${Math.round(timeoutMs / 1000)} s: ${names.join(", ")}`); } await new Promise(resolve => setTimeout(resolve, pollMs)); } @@ -242,7 +260,8 @@ export async function seedChaosLab(input: { } if (input.waitForReadyAgents) { await waitForAgentsReady(api, Object.fromEntries(Object.entries(agents).map(([adapter, agent]) => - [adapter, { id: agent.id, createdAt: agentCreatedAt.get(adapter) }])), timeline, input.agentReadyTimeoutMs, 1_000, input.cancelled); + [adapter, { id: agent.id, createdAt: agentCreatedAt.get(adapter) }])), timeline, + input.agentReadyTimeoutMs ?? (input.env === "daytona" ? DAYTONA_AGENT_READY_TIMEOUT_MS : undefined), 1_000, input.cancelled); } // The project's git_worktree policy only takes effect when the instance has diff --git a/tests/restart-chaos/types.ts b/tests/restart-chaos/types.ts index 93676713716..0e430ba82f7 100644 --- a/tests/restart-chaos/types.ts +++ b/tests/restart-chaos/types.ts @@ -221,7 +221,7 @@ export interface OracleArtifacts { workspacePath: string | null; /** B5: distinct `.bench/progress` values the harness itself saw while the task was live. */ benchProgressObserved?: number; - stop?: { runId: string; runStatus: string | null; runsStartedBeforeContinue: string[]; continuePosted: boolean }; + stop?: { runId: string | null; runStatus: string | null; runsStartedBeforeContinue: string[]; continuePosted: boolean; missed?: boolean }; children?: Array<{ id: string; title?: string | null; status: string | null; assigneeAgentId: string | null; documents: Record }>; childStalls?: Array<{ childIssueId: string; recoveryActionId: string | null }>; stallWakes?: Array<{ stalledIssueId: string | null; recoveryActionId: string | null }>; @@ -283,7 +283,7 @@ export interface TaskRecord { deadlineAt: number | null; timedOut: boolean; followUp: { at: number; sentAt?: number; postedAt?: number; commentId: string | null; error: string | null; duringRun?: boolean } | null; - stop?: { at: number; runId: string; httpStatus: number | null; error: string | null }; + stop?: { at: number; runId: string | null; httpStatus: number | null; error: string | null; missed?: boolean }; faultIds: string[]; sweep: RestSweep | null; /** Workspace files present just before the first fault that hit this task (R2). */ diff --git a/tests/restart-chaos/wave-speed.test.ts b/tests/restart-chaos/wave-speed.test.ts index 2a78be4110e..354c5278df6 100644 --- a/tests/restart-chaos/wave-speed.test.ts +++ b/tests/restart-chaos/wave-speed.test.ts @@ -21,9 +21,12 @@ describe("wave speed grade", () => { const slow = gradeWaveSpeed("local", [run("a", "codex", 40_000), run("b", "codex", 40_000, [{ eventType: "run.performance.budget_exceeded", createdAt: "2026-11-08T00:00:00.000Z", payload: {} }])], [], 1); - expect(slow.rows.find(row => row.metric === "time_to_first_activity")?.breaches).toEqual(["p50", "p95"]); + expect(slow.rows.find(row => row.metric === "time_to_first_activity")?.breaches).toEqual([]); expect(slow.rows.find(row => row.metric === "ttft")).toMatchObject({ budget: null, breaches: [] }); - expect(slow).toMatchObject({ breaches: 4, singleRunBreaches: 2, runBudgetExceeded: 1 }); + expect(slow).toMatchObject({ breaches: 2, singleRunBreaches: 2, runBudgetExceeded: 1 }); + const slowFive = gradeWaveSpeed("local", ["a", "b", "c", "d", "e"].map(id => run(id, "codex", 40_000)), [], 0); + expect(slowFive.rows.find(row => row.metric === "time_to_first_activity")?.breaches).toEqual(["p50", "p95"]); + expect(slowFive).toMatchObject({ breaches: 7, singleRunBreaches: 5 }); const heldButFast = gradeWaveSpeed("local", [run("c", "codex", 4_000, [{ eventType: "run.performance.budget_exceeded", createdAt: "2026-11-08T00:00:00.000Z", payload: {} }])], [], 1); expect(heldButFast).toMatchObject({ breaches: 0, singleRunBreaches: 0, runBudgetExceeded: 1 }); @@ -46,7 +49,8 @@ describe("wave speed grade", () => { events: [{ eventType: "turn.started", createdAt: new Date(10_000 + 30_000).toISOString() }] }; const speed = gradeWaveSpeed("local", [recovered], [{ kind: "K1", readyAt: 10_000, runIds: ["r"] }], 0); // Nothing reloaded, so the whole latency is Paperclip's share and is judged. - expect(speed.rows.find(row => row.metric === "restart_recovery_control_plane")).toMatchObject({ adapter: "claude", breaches: ["p50", "p95"] }); + expect(speed.rows.find(row => row.metric === "restart_recovery_control_plane")).toMatchObject({ adapter: "claude", breaches: [] }); + expect(speed).toMatchObject({ singleRunBreaches: 1, breaches: 1 }); expect(speed.rows.find(row => row.metric === "restart_recovery")).toMatchObject({ budget: null, breaches: [], measured: { p50: 30_000 } }); }); @@ -92,6 +96,25 @@ describe("wave speed grade", () => { expect(breachesOf({ n: 1, p50: 99_000, p95: 99_000, max: 99_000 }, null)).toEqual([]); }); + it("judges aggregate p50 and p95 only from five samples and reports smaller rows as an insufficient sample", () => { + const budget = { p50Ms: 1_000, p95Ms: 2_000 }; + expect(breachesOf({ n: 4, p50: 9_000, p95: 9_000, max: 9_000 }, budget)).toEqual([]); + expect(breachesOf({ n: 5, p50: 9_000, p95: 9_000, max: 9_000 }, budget)).toEqual(["p50", "p95"]); + const speed = gradeWaveSpeed("local", [], [], 0); + speed.rows.push({ adapter: "codex", metric: "agent_boot", start: "cold", measured: { n: 2, p50: 9_000, p95: 9_000, max: 9_000 }, + budget, breaches: [] }); + expect(speedMarkdown(speed)).toContain("| insufficient sample (n < 5) |"); + }); + + it("fails a run's speed read instead of paging forever when a full page has no seq", async () => { + let reads = 0; + const api = { get: async () => { reads += 1; return Array.from({ length: 500 }, () => ({ eventType: "x", createdAt: new Date(0).toISOString() })); } } as unknown as ChaosApi; + const speed = await collectWaveSpeed(api, "local", [{ issueId: "i", adapter: "codex", samples: [{ runs: [{ id: "r", status: "succeeded", + createdAt: new Date(0).toISOString(), finishedAt: null }] }] as never }], []); + expect(speed.errors).toEqual([expect.stringMatching(/^r: .*seq/)]); + expect(reads).toBe(3); + }); + const traced = (trace: number, spans: Array<[string, number, number]>): BaselineRun => ({ runId: "t", adapter: "claude", environment: "local", phase: "cold", events: spans.map(([name, offset, duration]) => ({ eventType: "run.performance.span", diff --git a/tests/restart-chaos/wave-speed.ts b/tests/restart-chaos/wave-speed.ts index 065fd1d24ce..314704c2ce6 100644 --- a/tests/restart-chaos/wave-speed.ts +++ b/tests/restart-chaos/wave-speed.ts @@ -46,8 +46,10 @@ export function budgetFor(environment: EnvironmentKind, adapter: string, metric: return byStart[start === "warm" ? "warm" : "cold"]; } +export const MIN_AGGREGATE_SAMPLES = 5; + export function breachesOf(measured: Distribution, budget: SpeedBudget | null): Array<"p50" | "p95"> { - if (!budget) return []; + if (!budget || measured.n < MIN_AGGREGATE_SAMPLES) return []; const out: Array<"p50" | "p95"> = []; if (measured.p50 !== null && measured.p50 > budget.p50Ms) out.push("p50"); if (measured.p95 !== null && measured.p95 > budget.p95Ms) out.push("p95"); @@ -211,6 +213,9 @@ export function gradeWaveSpeed(environment: EnvironmentKind, runs: readonly Base const bootBudget = budgetFor(environment, run.adapter, "agent_boot", start); return (activity !== null && activityBudget !== null && activity > activityBudget.p95Ms) || (boot !== null && bootBudget !== null && boot > bootBudget.p95Ms); + }).length + samples.filter(sample => { + const budget = budgetFor(environment, sample.adapter, "restart_recovery_control_plane", "restart"); + return !sample.interruptedByFault && sample.controlPlaneMs !== null && budget !== null && sample.controlPlaneMs > budget.p95Ms; }).length; const breaches = rows.reduce((total, row) => total + row.breaches.length, 0) + singleRunBreaches; return { environment, rows, @@ -237,7 +242,9 @@ async function runEvents(api: ChaosApi, runId: string): Promise const page = await api.get(`/api/heartbeat-runs/${runId}/events?afterSeq=${afterSeq}&limit=500`, 15_000); for (const row of page) events.push({ eventType: String(row.eventType), createdAt: String(row.createdAt), payload: (row.payload ?? null) as Json | null }); if (page.length < 500) return events; - afterSeq = Number(page[page.length - 1]!.seq); + const next = Number(page[page.length - 1]!.seq); + if (!Number.isFinite(next) || next <= afterSeq) throw new Error(`run events page after seq ${afterSeq} has no later seq`); + afterSeq = next; } } @@ -282,16 +289,21 @@ export async function collectWaveSpeed(api: ChaosApi, environment: EnvironmentKi return gradeWaveSpeed(environment, runs, faultRuns(faults, timing), runBudgetExceeded, errors, outage); } +function breachCell(row: SpeedRow): string { + if (row.breaches.length) return row.breaches.join(", "); + return row.budget && row.measured.n > 0 && row.measured.n < MIN_AGGREGATE_SAMPLES ? `insufficient sample (n < ${MIN_AGGREGATE_SAMPLES})` : "—"; +} + export function speedMarkdown(speed: WaveSpeed): string { const s = (value: number | null) => value === null ? "—" : `${(value / 1000).toFixed(1)} s`; const lines = [`## Speed (${speed.environment})`, "", - `Breaches: ${speed.breaches} (aggregate p50/p95 rows plus ${speed.singleRunBreaches} runs over the p95 budget after outage removal; the server logged ${speed.runBudgetExceeded} budget_exceeded events before removal).`, + `Breaches: ${speed.breaches} (aggregate p50/p95 rows with at least ${MIN_AGGREGATE_SAMPLES} samples plus ${speed.singleRunBreaches} runs or restart recoveries over the p95 budget after outage removal; the server logged ${speed.runBudgetExceeded} budget_exceeded events before removal).`, `Restart samples with no provider event after ready: ${speed.recoveryWithoutProviderEvent}. Interrupted by a later fault (not graded): ${speed.recoveryInterruptedByFault}.`, `Outage time removed from ${speed.outageAdjustedSpans} spans: ${s(speed.outageRemovedMs)} (fault start to server ready; budgets judge the rest).`, "", "| Adapter | Metric | Start | n | p50 | p95 | Budget p50 / p95 | Breach |", "|---|---|---|---|---|---|---|---|"]; for (const row of speed.rows) { lines.push(`| ${row.adapter} | ${row.metric} | ${row.start} | ${row.measured.n} | ${s(row.measured.p50)} | ${s(row.measured.p95)} | ` - + `${row.budget ? `${s(row.budget.p50Ms)} / ${s(row.budget.p95Ms)}` : "no budget"} | ${row.breaches.join(", ") || "—"} |`); + + `${row.budget ? `${s(row.budget.p50Ms)} / ${s(row.budget.p95Ms)}` : "no budget"} | ${breachCell(row)} |`); } if (speed.errors.length) lines.push("", `Speed grade incomplete: ${speed.errors.length} run logs not read; the wave fails.`); return `${lines.join("\n")}\n`; diff --git a/tests/restart-chaos/workloads.ts b/tests/restart-chaos/workloads.ts index 3bd8ebc73da..64c376aefd1 100644 --- a/tests/restart-chaos/workloads.ts +++ b/tests/restart-chaos/workloads.ts @@ -270,7 +270,8 @@ export const workloadDefinitions: Record = { return result([ statusCheck(artifacts), ...briefChecks(artifacts.documents.brief, [briefMarker(nonce), continueMarker(nonce)]), - { name: "stop_took_effect", ok: stop?.runStatus === "cancelled", detail: `run=${stop?.runId ?? "none"} status=${stop?.runStatus ?? "none"}` }, + { name: "stop_took_effect", ok: Boolean(stop?.missed) || stop?.runStatus === "cancelled", + detail: stop?.missed ? "missed: the run finished before the stop window" : `run=${stop?.runId ?? "none"} status=${stop?.runStatus ?? "none"}` }, { name: "nothing_ran_after_stop", ok: Boolean(stop) && stop!.continuePosted && stop!.runsStartedBeforeContinue.length === 0, detail: stop ? `continue=${stop.continuePosted} runs=${stop.runsStartedBeforeContinue.join(",") || "none"}` : "not stopped" }, ]); diff --git a/ui/src/components/TaskChatThread.test.tsx b/ui/src/components/TaskChatThread.test.tsx index 0b0e9934f11..06e475bd8fa 100644 --- a/ui/src/components/TaskChatThread.test.tsx +++ b/ui/src/components/TaskChatThread.test.tsx @@ -13,7 +13,7 @@ import { ThemeProvider } from "@/context/ThemeContext"; import { TooltipProvider } from "@/components/ui/tooltip"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { ConnectivityProvider, createConnectivityStore } from "@/lib/connectivity"; -import { TaskChatThread } from "./TaskChatThread"; +import { INITIAL_TRANSCRIPT_REVEAL_BUDGET_MS, TaskChatThread } from "./TaskChatThread"; import { IssueChatThread } from "./IssueChatThread"; import type { Agent, @@ -881,6 +881,162 @@ describe.each(["legacy", "native"] as const)("%s task history readiness", (runti expect((runtimeMode === "native" ? transcriptHookRuns.native : transcriptHookRuns.legacy).at(-1)).toMatchObject([{ id: "saved-run" }]); }); + const transcriptHookCalls = () => runtimeMode === "native" ? transcriptHookRuns.native : transcriptHookRuns.legacy; + const historyLoading = () => container.querySelector('[data-testid="task-chat-history-loading"]') !== null; + // React commits the budget's state update when act() exits; the reveal then + // needs a few more (fake) animation frames to confirm stable geometry. + const passTranscriptBudget = async () => { + await act(async () => { await vi.advanceTimersByTimeAsync(1); }); + for (let frame = 0; frame < 3; frame++) await act(async () => { await vi.advanceTimersByTimeAsync(50); }); + }; + + it("reveals saved messages after the transcript budget and keeps a slow settled run behind a fixed control", async () => { + vi.useFakeTimers(); + try { + const props = { + issueId: "slow-failed-run", compactHistory: true, onAdd: async () => {}, onExpandHistory: vi.fn(), + linkedRuns: [{ ...retryRun, runId: "failed-run", status: "failed", startedAt: retryRun.createdAt }], + comments: createLongThreadComments(), + }; + render(); + expect(transcriptHookCalls().at(-1)).toMatchObject([{ id: "failed-run" }]); + await act(async () => { await vi.advanceTimersByTimeAsync(INITIAL_TRANSCRIPT_REVEAL_BUDGET_MS - 1); }); + expect(historyLoading()).toBe(true); + await passTranscriptBudget(); + expect(historyLoading()).toBe(false); + expect(container.textContent).toContain("Thread message 1"); + expect(container.querySelector('[data-testid="mock-editor"]')).not.toBeNull(); + expect(container.textContent).not.toContain("Some task history is still loading."); + // The late transcript is no longer requested, so it cannot insert rows + // above the reader; the output stays one click away. + expect(transcriptHookCalls().at(-1)).toEqual([]); + const output = [...container.querySelectorAll("button")].find(button => button.textContent === "More run output"); + expect(output).toBeDefined(); + act(() => output!.click()); + expect(props.onExpandHistory).toHaveBeenCalledOnce(); + render(); + expect(transcriptHookCalls().at(-1)).toMatchObject([{ id: "failed-run" }]); + } finally { vi.useRealTimers(); } + }); + + it("reveals saved messages after the transcript budget while a live run keeps streaming", async () => { + vi.useFakeTimers(); + try { + const props = { + issueId: "slow-live-run", compactHistory: true, onAdd: async () => {}, onExpandHistory: vi.fn(), + linkedRuns: [{ ...retryRun, runId: "live-run", status: "running", startedAt: retryRun.createdAt }], + comments: createLongThreadComments(), + }; + render(); + await act(async () => { await vi.advanceTimersByTimeAsync(INITIAL_TRANSCRIPT_REVEAL_BUDGET_MS - 1); }); + expect(historyLoading()).toBe(true); + await passTranscriptBudget(); + expect(historyLoading()).toBe(false); + expect(container.textContent).toContain("Thread message 1"); + expect(transcriptHookCalls().at(-1)).toMatchObject([{ id: "live-run" }]); + // Finishing after the reveal keeps the visible transcript in place. + render(); + expect(transcriptHookCalls().at(-1)).toMatchObject([{ id: "live-run" }]); + expect(container.textContent).not.toContain("More run output"); + } finally { vi.useRealTimers(); } + }); + + it("keeps waiting for a settled transcript that would insert output when no compact control exists", async () => { + vi.useFakeTimers(); + try { + render( {}} comments={createLongThreadComments()} + linkedRuns={[{ ...retryRun, runId: "failed-run", status: "failed", startedAt: retryRun.createdAt }]} />); + await act(async () => { await vi.advanceTimersByTimeAsync(INITIAL_TRANSCRIPT_REVEAL_BUDGET_MS - 1); }); + await passTranscriptBudget(); + expect(historyLoading()).toBe(true); + expect(transcriptHookCalls().at(-1)).toMatchObject([{ id: "failed-run" }]); + } finally { vi.useRealTimers(); } + }); + + it("defers every slow settled run of a large compact task at the budget", async () => { + vi.useFakeTimers(); + try { + const linkedRuns = Array.from({ length: 300 }, (_, index) => ({ + ...retryRun, runId: `failed-run-${index}`, status: "failed", + createdAt: new Date(Date.parse(retryRun.createdAt) + index * 60_000).toISOString(), + startedAt: new Date(Date.parse(retryRun.createdAt) + index * 60_000).toISOString(), + })); + render( {}} onExpandHistory={vi.fn()} + comments={createLongThreadComments()} linkedRuns={linkedRuns} />); + expect(transcriptHookCalls().at(-1)?.length).toBeGreaterThan(0); + await act(async () => { await vi.advanceTimersByTimeAsync(INITIAL_TRANSCRIPT_REVEAL_BUDGET_MS - 1); }); + expect(historyLoading()).toBe(true); + await passTranscriptBudget(); + expect(historyLoading()).toBe(false); + expect(transcriptHookCalls().at(-1)).toEqual([]); + } finally { vi.useRealTimers(); } + }); + + it("keeps the transcript budget when another transcript hydrates first", async () => { + vi.useFakeTimers(); + try { + const props = { + issueId: "two-live-runs", compactHistory: true, onAdd: async () => {}, onExpandHistory: vi.fn(), + linkedRuns: [ + { ...retryRun, runId: "fast-run", status: "running", startedAt: retryRun.createdAt }, + { ...retryRun, runId: "slow-run", status: "running", startedAt: retryRun.createdAt }, + ], + comments: createLongThreadComments(), + }; + render(); + await act(async () => { await vi.advanceTimersByTimeAsync(INITIAL_TRANSCRIPT_REVEAL_BUDGET_MS - 100); }); + transcriptState.hydratedRunIds = new Set(["fast-run"]); + nativeTranscriptState.hydratedRunIds = new Set(["fast-run"]); + render(); + await act(async () => { await vi.advanceTimersByTimeAsync(99); }); + expect(historyLoading()).toBe(true); + // The budget still ends at its first deadline. It does not restart + // because the fast transcript finished. + await passTranscriptBudget(); + expect(historyLoading()).toBe(false); + expect(transcriptHookCalls().at(-1)).toMatchObject([{ id: "fast-run" }, { id: "slow-run" }]); + } finally { vi.useRealTimers(); } + }); + + it("keeps waiting for a live transcript that splits around a steering message", async () => { + vi.useFakeTimers(); + try { + const steering = { + ...createLongThreadComments()[0], id: "steering-comment", body: "Change course now.", + steeredIntoRunId: "live-run", conversationAnchorAt: new Date("2026-08-25T18:00:02.000Z"), + createdAt: new Date("2026-08-25T18:00:02.000Z"), updatedAt: new Date("2026-08-25T18:00:02.000Z"), + }; + render( {}} onExpandHistory={vi.fn()} + comments={[...createLongThreadComments(), steering]} + linkedRuns={[{ ...retryRun, runId: "live-run", status: "running", startedAt: retryRun.createdAt }]} />); + await act(async () => { await vi.advanceTimersByTimeAsync(INITIAL_TRANSCRIPT_REVEAL_BUDGET_MS - 1); }); + await passTranscriptBudget(); + // Its pre-steer output enters the main chronology above the steering + // message, so revealing before it loads would move visible messages. + expect(historyLoading()).toBe(true); + expect(transcriptHookCalls().at(-1)).toMatchObject([{ id: "live-run" }]); + } finally { vi.useRealTimers(); } + }); + + it("does not start the transcript budget while saved history is still loading", async () => { + vi.useFakeTimers(); + try { + const props = { + issueId: "saved-history-first", compactHistory: true, onAdd: async () => {}, onExpandHistory: vi.fn(), + linkedRuns: [{ ...retryRun, runId: "live-run", status: "running", startedAt: retryRun.createdAt }], + comments: createLongThreadComments(), + }; + render(); + await act(async () => { await vi.advanceTimersByTimeAsync(INITIAL_TRANSCRIPT_REVEAL_BUDGET_MS * 3); }); + expect(historyLoading()).toBe(true); + render(); + await act(async () => { await vi.advanceTimersByTimeAsync(INITIAL_TRANSCRIPT_REVEAL_BUDGET_MS - 1); }); + expect(historyLoading()).toBe(true); + await passTranscriptBudget(); + expect(historyLoading()).toBe(false); + } finally { vi.useRealTimers(); } + }); + it("retains a live transcript after the saved reply arrives", () => { const props = { issueId: "live-to-saved", compactHistory: true, onAdd: async () => {}, onExpandHistory: vi.fn(), linkedRuns: [{ ...retryRun, runId: "live-run", status: "running", startedAt: retryRun.createdAt }], comments: createLongThreadComments() }; diff --git a/ui/src/components/TaskChatThread.tsx b/ui/src/components/TaskChatThread.tsx index c802274f646..7301bc9ee22 100644 --- a/ui/src/components/TaskChatThread.tsx +++ b/ui/src/components/TaskChatThread.tsx @@ -55,6 +55,7 @@ import { taskChatStatusRelevance, withoutHistoricalRunStatus, } from "@/components/task-chat/status-relevance"; +import { selectBudgetedTranscriptRuns } from "@/components/task-chat/transcript-reveal-budget"; import { assembleThreadItems, attachSettledTurns, @@ -267,6 +268,12 @@ function isRunnerResponseComment(params: { // well within this as soon as the settled turn/comment lands. const SETTLING_TAIL_MAX_MS = 15_000; const INITIAL_HISTORY_REVEAL_TIMEOUT_MS = 15_000; +// Once saved history is ready, a run transcript may hold the first reveal only +// this long. A slow run-log read must not hide saved messages and the composer. +// Live runs then stream into the tail; settled compact runs keep a fixed +// "More run output" control instead of inserting output after the reveal. +export const INITIAL_TRANSCRIPT_REVEAL_BUDGET_MS = 600; +const EMPTY_RUN_IDS: ReadonlySet = new Set(); const INITIAL_FONT_REVEAL_TIMEOUT_MS = 3000; const EMPTY_LIVE_ISSUE_IDS: ReadonlySet = new Set(); const LONG_THREAD_BLOCKER_REPEAT_COUNT = 4; @@ -1005,9 +1012,21 @@ export function TaskChatThread(props: TaskChatThreadProps) { if (requestedTranscripts.current.issueId !== issueId) { requestedTranscripts.current = { issueId, ids: new Set() }; } + // Runs whose transcript outlasted INITIAL_TRANSCRIPT_REVEAL_BUDGET_MS on the + // first open of this issue. Latched per issue so the decision never flips. + // `deferred` holds only runs that had already settled at that moment, so a + // live transcript that finishes later stays visible. + const [slowTranscripts, setSlowTranscripts] = useState<{ + issueId: typeof issueId; ids: ReadonlySet; deferred: ReadonlySet; + } | null>(null); + const slowTranscriptsForIssue = slowTranscripts && slowTranscripts.issueId === issueId ? slowTranscripts : null; + const slowTranscriptRunIds = slowTranscriptsForIssue?.ids ?? EMPTY_RUN_IDS; + const slowSettledTranscriptRunIds = slowTranscriptsForIssue?.deferred ?? EMPTY_RUN_IDS; + const compactTranscriptDeferral = Boolean(props.compactHistory && !conversationMode && props.onExpandHistory && !scrollNavigation.hash); const deferredTranscriptRunIds = useMemo(() => { const deferred = new Set(); - if (!props.compactHistory || conversationMode || !props.onExpandHistory || scrollNavigation.hash) return deferred; + if (!compactTranscriptDeferral) return deferred; + for (const run of runs) if (slowSettledTranscriptRunIds.has(run.id)) deferred.add(run.id); for (const run of runs) { if (requestedTranscripts.current.ids.has(run.id) || run.status !== "succeeded" || !run.createdAt || toMs(run.createdAt) > openedAt) continue; @@ -1024,7 +1043,7 @@ export function TaskChatThread(props: TaskChatThreadProps) { )) deferred.add(run.id); } return deferred; - }, [issueId, runs, projectedComments, linkedRunMetaById, interactions, props.compactHistory, conversationMode, props.onExpandHistory, scrollNavigation.hash, openedAt]); + }, [issueId, runs, projectedComments, linkedRunMetaById, interactions, compactTranscriptDeferral, slowSettledTranscriptRunIds, openedAt]); const transcriptRuns = useMemo(() => runs.filter(run => !deferredTranscriptRunIds.has(run.id) && !(props.compactHistory && !conversationMode && props.onExpandHistory && !scrollNavigation.hash && @@ -3185,7 +3204,8 @@ export function TaskChatThread(props: TaskChatThreadProps) { initialCommentWindow.current.oldestAt ); }); - const transcriptHistoryPending = initialRuns.some((run) => { + const pendingTranscriptRuns = initialRuns.filter((run) => { + if (slowTranscriptRunIds.has(run.id)) return false; // A scheduled retry has not started and has no log to hydrate yet. if (run.status === "scheduled_retry") return false; if ( @@ -3204,6 +3224,20 @@ export function TaskChatThread(props: TaskChatThreadProps) { ? !hydratedLogRunIds.has(run.id) : logsAreInitiallyHydrating; }); + const transcriptHistoryPending = pendingTranscriptRuns.length > 0; + // Only these may stop holding the reveal after the budget. See + // selectBudgetedTranscriptRuns for the live, steered and settled rules. + const budgetedTranscriptRuns = selectBudgetedTranscriptRuns(pendingTranscriptRuns, { + compactDeferral: compactTranscriptDeferral, + hasTimelineAnchors: (run) => ((isNativePaperclipRunnerRun(run) + ? steeringAnchorsByRun.get(run.id) + : legacyTimelineAnchorsByRun.get(run.id))?.length ?? 0) > 0, + }); + // The budget timer reads the runs that are still pending when it fires, so + // a transcript that hydrates early does not restart the budget. + const budgetedTranscriptRunsRef = useRef(budgetedTranscriptRuns); + budgetedTranscriptRunsRef.current = budgetedTranscriptRuns; + const hasBudgetedTranscriptRuns = budgetedTranscriptRuns.length > 0; // Hydrating a run inserts activity around its saved reply and can move the // latest viewport substantially. Compact opens hydrate only their bounded // recent window, but its saved cards and latest turn must arrive together so @@ -3213,7 +3247,8 @@ export function TaskChatThread(props: TaskChatThreadProps) { (decisionReceipts.enabled && decisionReceipts.isPending) || (taskHandoffs.enabled && taskHandoffs.isPending) )); - const historyPending = initialHistoryPending || planLoading || transcriptHistoryPending || chatMetadataPending; + const savedHistoryPending = initialHistoryPending || planLoading || chatMetadataPending; + const historyPending = savedHistoryPending || transcriptHistoryPending; useEffect(() => { recordIssueDetailReadiness({ plan: !planLoading, transcripts: !transcriptHistoryPending, history: !historyPending }); }, [issueId, planLoading, transcriptHistoryPending, historyPending]); @@ -3233,6 +3268,32 @@ export function TaskChatThread(props: TaskChatThreadProps) { useEffect(() => { if (revealCachedHeader) setRevealedHistoryKey(historyKey); }, [revealCachedHeader, historyKey]); + // The budget is one deadline per history key. It starts the first time + // saved history is ready, and later changes to the pending runs keep it. + const transcriptRevealDeadline = useRef<{ historyKey: typeof historyKey; at: number } | null>(null); + useEffect(() => { + if (historyRevealed || savedHistoryPending) return; + if (transcriptRevealDeadline.current?.historyKey !== historyKey) { + transcriptRevealDeadline.current = { historyKey, at: Date.now() + INITIAL_TRANSCRIPT_REVEAL_BUDGET_MS }; + } + if (!hasBudgetedTranscriptRuns) return; + const timer = window.setTimeout(() => { + const expired = budgetedTranscriptRunsRef.current; + if (expired.length === 0) return; + setSlowTranscripts((current) => { + const previous = current && current.issueId === issueId ? current : null; + return { + issueId, + ids: new Set([...(previous?.ids ?? []), ...expired.map((run) => run.runId)]), + deferred: new Set([ + ...(previous?.deferred ?? []), + ...expired.filter((run) => run.settled).map((run) => run.runId), + ]), + }; + }); + }, Math.max(0, transcriptRevealDeadline.current.at - Date.now())); + return () => window.clearTimeout(timer); + }, [historyRevealed, savedHistoryPending, hasBudgetedTranscriptRuns, historyKey, issueId]); const historyShellRef = useRef(null); const [expiredHistoryWait, setExpiredHistoryWait] = useState<{ historyKey: typeof historyKey } | null>(null); const historyWaitExpired = expiredHistoryWait !== null && expiredHistoryWait.historyKey === historyKey; diff --git a/ui/src/components/task-chat/transcript-reveal-budget.test.ts b/ui/src/components/task-chat/transcript-reveal-budget.test.ts new file mode 100644 index 00000000000..6649094fa74 --- /dev/null +++ b/ui/src/components/task-chat/transcript-reveal-budget.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vitest"; +import { selectBudgetedTranscriptRuns } from "./transcript-reveal-budget"; + +const STATUSES = ["running", "queued", "failed", "succeeded", "cancelled"] as const; + +function createRuns(count: number) { + return Array.from({ length: count }, (_, index) => ({ + id: `run-${index}`, + status: STATUSES[index % STATUSES.length]!, + })); +} + +describe("selectBudgetedTranscriptRuns", () => { + it("budgets live runs without anchors and settled runs only in compact history", () => { + const runs = [ + { id: "live", status: "running" }, + { id: "steered", status: "running" }, + { id: "failed", status: "failed" }, + ]; + const hasTimelineAnchors = (run: { id: string }) => run.id === "steered"; + expect(selectBudgetedTranscriptRuns(runs, { compactDeferral: true, hasTimelineAnchors })).toEqual([ + { runId: "live", settled: false }, + { runId: "failed", settled: true }, + ]); + expect(selectBudgetedTranscriptRuns(runs, { compactDeferral: false, hasTimelineAnchors })).toEqual([ + { runId: "live", settled: false }, + ]); + }); + + it("does one anchor lookup for each live run in a large task", () => { + const runs = createRuns(5_000); + const liveRunCount = runs.filter((run) => run.status === "running" || run.status === "queued").length; + let lookups = 0; + const hasTimelineAnchors = (run: { id: string }) => { + lookups += 1; + if (lookups > liveRunCount) throw new Error(`anchor lookups exceeded ${liveRunCount}`); + return Number(run.id.slice("run-".length)) % 2 === 0; + }; + const budgeted = selectBudgetedTranscriptRuns(runs, { compactDeferral: true, hasTimelineAnchors }); + expect(lookups).toBe(liveRunCount); + expect(budgeted.filter((run) => run.settled)).toHaveLength(runs.length - liveRunCount); + expect(budgeted.filter((run) => !run.settled)).toHaveLength(liveRunCount / 2); + }); +}); diff --git a/ui/src/components/task-chat/transcript-reveal-budget.ts b/ui/src/components/task-chat/transcript-reveal-budget.ts new file mode 100644 index 00000000000..e5361f21bb4 --- /dev/null +++ b/ui/src/components/task-chat/transcript-reveal-budget.ts @@ -0,0 +1,38 @@ +import { isTerminalRunStatus } from "./transcript-adapter"; + +export interface TranscriptBudgetRun { + id: string; + status: string; +} + +export interface BudgetedTranscriptRun { + runId: string; + settled: boolean; +} + +/** + * Select the pending transcript runs that may stop holding the first reveal + * when the transcript budget expires. The work is one pass over the runs, with + * one anchor lookup for each live run. + * + * - A live run streams into the tail, so it may stop holding the reveal, + * unless it has steering or timeline anchors. Its pre-anchor segments enter + * the main chronology above the anchored messages. + * - A settled run may stop holding the reveal only when compact history can + * show it behind the fixed "More run output" control. + */ +export function selectBudgetedTranscriptRuns( + pendingRuns: readonly Run[], + options: { + compactDeferral: boolean; + hasTimelineAnchors: (run: Run) => boolean; + }, +): BudgetedTranscriptRun[] { + const budgeted: BudgetedTranscriptRun[] = []; + for (const run of pendingRuns) { + const settled = isTerminalRunStatus(run.status); + if (settled ? !options.compactDeferral : options.hasTimelineAnchors(run)) continue; + budgeted.push({ runId: run.id, settled }); + } + return budgeted; +}