mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-06 07:38:47 +01:00
Merge current master into hosted external recovery work
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
commit
d82c84e2c7
180 files changed
+9237
-825
No files matched your search
+104
-7
@@ -328,6 +328,15 @@ Messages from the same conversation still coalesce into one run. Messages from
|
||||
different conversations queue separately and run one after the other. Wakes
|
||||
without a conversation keep their normal coalescing.
|
||||
|
||||
The comparison uses the conversations of the messages themselves, not only the
|
||||
conversation a wake records. A wake that the work-intent outbox saved for
|
||||
unanswered chat messages records no conversation, so a message from another
|
||||
conversation does not join it, and is not folded into a run promoted from it.
|
||||
Board comments have no conversation and still join any batch. A saved chat wake
|
||||
that older code already merged across two conversations is split when it is
|
||||
promoted: the other conversation's messages run first as saved messages, then
|
||||
the recorded conversation runs with its own messages.
|
||||
|
||||
If reviewed chat attestation exhausts its short lock or delivery wait before
|
||||
provider dispatch, the run records `reviewed_chat_execution_binding_not_ready`.
|
||||
The existing durable retry scheduler permits at most two further attempts. Each
|
||||
@@ -1440,6 +1449,22 @@ folder), or an exhausted budget leaves a board-owned recovery action. Stranded-w
|
||||
recovery names this failure for the statuses it scans; for other statuses, such as
|
||||
a `blocked` task woken by a reply, the failure path records the action directly.
|
||||
|
||||
A restore needs about one workspace of sandbox disk, not two. The uploaded
|
||||
archive is a disposable copy of a saved version that control-plane storage
|
||||
already holds, and the sandbox checks every file against that version's
|
||||
manifest. Extraction writes the files from the last to the first and shortens the
|
||||
archive behind each one, so the archive and the restored tree together need the
|
||||
workspace size plus the largest file. Before the upload, a reclaim step takes the
|
||||
root's restore lock and checks the epoch fence. It removes what an earlier attempt
|
||||
on that root left when it died: a `<root>.restoring-*` partial tree, an archive it
|
||||
was uploading or consuming, and archive staging that names the same root. Each
|
||||
attempt names its staging before its upload starts. Staging that an earlier
|
||||
release left without that name is kept. A sandbox that still cannot hold one copy
|
||||
fails with `reason=sandbox_disk_full` at the stage that ran out of space (`helper`,
|
||||
`upload`, or a restore script stage). A retry on the same disk would fail again,
|
||||
so it is not retried automatically. The board recovery action's Retry works once
|
||||
the sandbox has room for the workspace.
|
||||
|
||||
A retained sandbox can still hold a workspace's earlier root after the workspace
|
||||
moved to another allocation, for example when child tasks that an older release
|
||||
bound to a parent's workspace saved newer work on their own sandboxes. When the parent wakes on its
|
||||
@@ -1449,7 +1474,12 @@ recorded use of that root on this sandbox is an earlier epoch that ended in a
|
||||
quiesced, committed final save, and the folder carries a Paperclip preparation or
|
||||
restore receipt. Its files are then already part of the saved lineage being
|
||||
restored. Any other occupant (no receipt, a later unsaved use, or a sandbox that
|
||||
never saved that root) is still refused with `reason=occupied_root`. The replaced
|
||||
never saved that root) is still refused with `reason=occupied_root`, and none of
|
||||
its files are removed. After that proof, the reclaim step removes the root's files
|
||||
before the saved archive is uploaded, so the old copy never shares the disk with
|
||||
the new one. Its receipt and `.paperclip-runtime` stay until the restored root is
|
||||
published, so a restore interrupted after the removal proves the same root again
|
||||
and finishes from the saved version. The replaced
|
||||
root's `.paperclip-runtime` state, such as a retained runner session, is never in
|
||||
a snapshot and belongs to the sandbox, so it moves into the restored root. Only the
|
||||
old preparation or restore receipt and export staging are dropped. A retained
|
||||
@@ -1579,6 +1609,8 @@ An explicit recovery action is a typed liveness repair path for a source issue.
|
||||
|
||||
A terminal native failure can retain a result accepted before checkpoint or cleanup failed. That result is historical evidence, not a live controller. New user input may start a fresh turn after the controller and execution environment have stopped and ordinary admission checks pass. Preserve the failed run, its result, and its recovery budget. Do not commit the old result, infer action outcomes, or replay the failed turn. A message saved while cleanup is pending must be reconsidered after verified cleanup and delivered once. External chat messages retain their original inbound action, wake receipt and actor. Cleanup delegates reconsideration to the live inbound owner, which revalidates the endpoint, conversation generation, principal and exact saved source before normal admission. The existing stranded-queue sweep uses the same owner after a lost callback or restart; it cannot substitute a generic assignment wake. A rejected source must not prevent other saved messages from being reconsidered. Admission must consume its deferred receipt in the same transaction that creates the new run, including in agent chat, where later messages keep their separate turns. Completing that run must not promote the consumed receipt again. Workspace-export repair retains its separate saved-result recovery path.
|
||||
|
||||
When a native run's accepted result reports a failed turn without a classified provider error (`run_failed_partial_evidence_preserved`, for example an OpenCode server that was killed or ended without an answer), the status decision keeps the task's status and queues one same-agent `schedule_retry` wake. The wake dispatcher accepts that committed decision effect as the continuation's provenance, exactly like an `enqueue_continuation` effect, so the task always has queued work, and the retry answers the same external chat conversation. The automatic continuation is used once per chain: if the run started from that wake fails the same way, the decision is `native_run_failed_continuation_exhausted`, the task is blocked with a board blocker, and the visible Retry starts the next attempt.
|
||||
|
||||
A host-verified workspace copy-back receipt also permits new user input after
|
||||
a native coordinator reaches terminal failure with a retained result. The receipt
|
||||
must bind the company, task, run, allocation, descriptor and final file digest.
|
||||
@@ -3060,9 +3092,28 @@ account at once. ACP harnesses report an exhausted allowance as a generic
|
||||
terminal limit failure; Runner adds the provider's typed session-failure title,
|
||||
and only a rate-limit or quota title becomes `rate_limit` or `quota_exhausted`.
|
||||
Context, turn and configured budget limits stay ordinary terminal failures. A
|
||||
reset clock in the provider's wording, such as "resets 2am (UTC)", is used as
|
||||
reset clock in the provider's wording, such as "resets 2am (UTC)", or a
|
||||
calendar reset such as a weekly limit's "resets Nov 12, 6pm (UTC)", is used as
|
||||
the reset time.
|
||||
|
||||
A native run whose provider ends a turn with an exhausted allowance
|
||||
(`native_provider_usage_limit`) still blocks its task with a recovery action.
|
||||
When the run's last turn event is a provider-observed `turn.failed` that reports
|
||||
a reset within eight days, the action says when the limit resets, and at that
|
||||
time Paperclip requests the task's Retry itself, on behalf of the user who
|
||||
requested the run or, for automatic wakes, the run's accountable user. That is
|
||||
the same Retry the user would click: admission keeps every gate (stop proof,
|
||||
saved-work recovery and action reconciliation), so it never starts work a
|
||||
user's Retry could not. The request is idempotent per run, and at most three
|
||||
automatic Retries follow one another without a successful run between them.
|
||||
A hold whose reset is more than eight days out (for example a monthly limit)
|
||||
still names its reset but leaves the Retry to the user. A hold whose reset is
|
||||
unknown, more than a day in the past, or that has no accountable user keeps its
|
||||
visible Retry, and its message says why. A connected chat conversation's Retry
|
||||
is prepared through the chat service, as a user's is. The
|
||||
reset deadline is rebuilt from the active holds at startup, so holds saved by an
|
||||
earlier release are covered too.
|
||||
|
||||
An ingress endpoint failure can use that same bounded retry only when the
|
||||
environment provider returns a structured HTTP 429 or 5xx failure and the
|
||||
complete, encrypted controller checkpoint proves that this exact run never
|
||||
@@ -3258,6 +3309,26 @@ admission applies the same checks as for a per-turn owner. The journal of a
|
||||
warm owner has no `runner.suspend` command. A local warm Runner and a resumed
|
||||
sandbox that still holds the Runner keep the live adoption path.
|
||||
|
||||
A remote Runner whose sandbox lease for the prior run ended (`released` or
|
||||
`expired`, with a release time) on a different sandbox than this run's is gone
|
||||
by record. No process remains that could act on a command it never
|
||||
acknowledged. For such an owner, these unfinished commands do not hold the
|
||||
retirement:
|
||||
|
||||
- its own lifecycle commands (`runner.suspend`, `runner.drain`,
|
||||
`runner.shutdown`);
|
||||
- deliveries that only that Runner could receive: `run.attach`,
|
||||
`semantic_tool.result`, `session.snapshot` and `session.goal.get`. A
|
||||
journaled `semantic_tool.result` also answers its tool input, because the
|
||||
controller journals the answer after the tool ran.
|
||||
|
||||
Retirement replays none of these commands. Any other unfinished command, such
|
||||
as `turn.start`, `turn.steer`, `request.resolve` or
|
||||
`external_provider.operation`, still holds the owner. A tool input with no
|
||||
journaled answer still holds it with `journal_tool_input_unanswered`. A
|
||||
retained lease, a lease on this run's sandbox, or a missing lease record keeps
|
||||
every unfinished command decisive.
|
||||
|
||||
The provider session then follows the normal resume-or-replace policy. A
|
||||
resumed sandbox, a local warm session, a plugin task, a restart claim, or any
|
||||
missing proof keeps the existing `prior_owner_terminal_state_indeterminate`
|
||||
@@ -3349,9 +3420,14 @@ that process is gone. Second, the resume claimed a provider attempt within the
|
||||
three-attempt budget from a `retryable_failure` coordinator. Third, that failure
|
||||
saved `recoveryMode: "exact_checkpoint_resume"`, `recoverable`,
|
||||
`providerSessionEstablished` and `checkpointExists`, with no replacement recorded,
|
||||
and the runner restores that same checkpointed conversation. A remote run, a
|
||||
bootstrap retry, an ambiguous state, a missing or superseded stop record, an
|
||||
exhausted budget, or a replacement session keeps the existing failure.
|
||||
and the runner restores that same checkpointed conversation. The resume reconciler
|
||||
clears the saved failure when it claims the run. So it first appends a
|
||||
`same_run_resume` entry to `recovery_history` that copies those fields, together
|
||||
with its controller boot. The executor then reads that entry. It must be the last
|
||||
entry, and it must name the executor's boot. A remote run, a bootstrap retry, an
|
||||
ambiguous state, a missing or superseded stop record, an exhausted budget, a
|
||||
replacement session, or a claim entry from another boot or followed by another
|
||||
entry keeps the existing failure.
|
||||
|
||||
A restart can also land after the agent proposed its result but before the
|
||||
provider turn ended. When the restored runner proves that turn ended with the
|
||||
@@ -3749,7 +3825,20 @@ infrastructure certification, and grants no agent or provider execution authorit
|
||||
Each completed export frees its own slot and wakes the next scan. A slow export
|
||||
does not hold a free slot. Completed cleanup and saved-input obligations receive
|
||||
one bounded pass through unvisited sources. The pass stops at its tail so paused
|
||||
input does not keep the worker active; a committed change starts a fresh pass.
|
||||
input does not keep the worker active; a committed change starts a fresh pass
|
||||
once the current pass reaches its tail. A pass is never restarted midway, so on
|
||||
a busy instance, where changes commit continuously, every candidate is still
|
||||
visited: the due re-arms and fallbacks of older exhausted holds included.
|
||||
Discovery is instance-wide and draws from separate lanes, each paged by its own
|
||||
cursor: unfinished saves, exhausted holds whose re-arm or fallback is due, and
|
||||
this pass. Each lane with work takes one free slot before any lane takes a
|
||||
second, and the lane that goes first rotates on each run. A save that another
|
||||
server owns, a long local export, or hundreds of holds whose saved input waits
|
||||
therefore cannot starve a due hold: it is reached within a few runs of the
|
||||
worker. The due lane wraps at its tail, so a hold that becomes due
|
||||
by time alone (a lease expiry or a re-arm backoff) is reached even after the
|
||||
pass completed with no committed change. Lane positions are kept in memory; a
|
||||
restart starts each lane from its first candidate, with no migration.
|
||||
Shutdown joins this worker's exports before closing the database. Repeated Retry
|
||||
during physical preservation binds the canonical intent
|
||||
without changing the attempt's generation or revision. Progress writes preserve
|
||||
@@ -4540,7 +4629,15 @@ That transfer can stream without another sandbox archive. Provider exclusions ca
|
||||
also omit a nested entry with the same name; credentials remain excluded. Other
|
||||
copy failures and timeouts still fail. Workspace capture itself still needs free
|
||||
sandbox space. Its failed save operation names `remote_workspace_sandbox_disk_full`
|
||||
when that capacity is exhausted, without changing retry or ownership rules.
|
||||
when that capacity is exhausted, without changing ownership rules. Finalization
|
||||
does not retry that copy-back: nothing frees the sandbox between its attempts.
|
||||
The first full-disk failure ends finalization as
|
||||
`native_workspace_sync_out_retry_exhausted` and keeps the accepted result. Saved-work
|
||||
recovery then reclaims the retained sandbox's inactive provider cache and saves the
|
||||
files again with no provider turn. The export Retry stays available. A read-only
|
||||
fallback that only lost its connection (a closed transport, a provider 5xx or rate
|
||||
limit, or a sandbox state change) reports its own cause instead, and finalization
|
||||
keeps its bounded retry for it.
|
||||
|
||||
Native assigned app tools save governed responses above 500,000 encoded bytes before returning
|
||||
a bounded reference through PRP. `read_tool_result` retrieves the saved JSON in
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# Durable records for cut-off turn starts and orphaned tool calls
|
||||
|
||||
Status: approved by Dotta (2026-11-10), being implemented in two PRs
|
||||
Goal: after a control-plane restart or freeze, 0% of tasks need Retry, and Retry still works whenever it is shown.
|
||||
Parent plan: `2026-11-07-durable-ownership-and-reconciliation.md`, section B (write-ahead intents) and section F (charge only on recorded outcomes).
|
||||
|
||||
## Rule
|
||||
|
||||
Recovery may resend, replay or continue only when a durable record proves that no provider work and no tool effect can be duplicated or lost. A duplicated prompt or a second write is worse than a Retry click. When the record cannot prove it, the existing behaviour stays: a working Retry.
|
||||
|
||||
## Change 1: a turn start cut off before the prompt reached the provider
|
||||
|
||||
**What happens today.** Restart-chaos wave `w-20261110T185315-s9107`, task t05 (claude, workload C1, fault TM2). A follow-up run's `turn.start` reaches the Runner, which saves the ACPX session as `turn_starting` and asks the ACPX sidecar to start the turn. For a resumed Claude session the sidecar first starts Claude and loads the conversation; the prompt is sent only after that. Under load this took more than 24 s. Then the harness froze the server, the Runner, the sidecar and Claude together (SIGSTOP) for 33 s. On thaw the Runner's 30 s sidecar request deadline had passed, so it reaped the sidecar and saved the session as `closed`. Every same-run resume then failed with `ACPX session is not open`, recovery stopped with `native_session_retry_exhausted`, and a person had to click Retry.
|
||||
|
||||
The Runner cannot tell from its own state whether Claude received the prompt. Resending could duplicate it; a continuation could lose it.
|
||||
|
||||
**The record: a sidecar prompt-dispatch journal.** The ACPX sidecar writes one small file in the session's private runtime directory (`0700`) for each turn:
|
||||
|
||||
1. When the runtime port starts the turn, before any provider work: one line `{"schema":…,"turnId":X,"phase":"received"}`, truncating the previous turn's file. No fsync.
|
||||
2. When ACPX is about to write that turn's first `session/prompt` request to the provider's stdin: one appended line `{"phase":"dispatched"}`, then `fsync`, and only then the write. ACPX calls the host's `onAcpMessage("outbound", …)` hook synchronously before it hands the bytes to the provider stream, so a failed journal write aborts the prompt write.
|
||||
|
||||
The file name and record shape are declared in `protocol/provider-schemas/acpx-sidecar.schema.json` and generated into TypeScript and Rust, so the pack contract digest covers them.
|
||||
|
||||
**What it proves.** The Runner reads the journal only after it has proved that the sidecar and the provider are gone (it terminated the sidecar and acquired the provider lifetime fence, the same proof the existing lost-turn restore uses). A dead sidecar cannot write or send anything more.
|
||||
|
||||
| Journal for the active turn | Meaning | Recovery |
|
||||
|---|---|---|
|
||||
| exactly one complete `received` line | the prompt was never written to the provider | restore the session with no active turn; emit `harness.diagnostic` `acpx_turn_start_not_dispatched`; the same-run resume sends the run's `turn.start` once |
|
||||
| a `dispatched` line | the provider may have the prompt | unchanged: the existing lost-turn path (restore and continue in the same conversation, or close) |
|
||||
| missing, another turn, malformed, torn | unknown | unchanged |
|
||||
|
||||
Both cut-off shapes use it: a sidecar request that failed in flight (timeout or sidecar exit), and a Runner killed while the session was `turn_starting`.
|
||||
|
||||
**Resend exactly once.** The cut-off `turn.start` command stays failed; it is never executed again. The restored session has no active turn, so the next same-run resume starts the turn with the run's own input. If that start is cut off too, the journal decides again.
|
||||
|
||||
## Change 2: a tool call orphaned by a restart
|
||||
|
||||
**What happens today.** Daytona wave `w-20261110T174930-s9205`, task t01 (codex, C1, RR2): a restart cut a `write_document` callback after the Runner journaled its input and before a result was saved. Close could not prove the provider drained, so the session quarantined (`native_session_cleanup_quarantined`). Since #20628 a callback admitted by an earlier controller settles as `tool_call_interrupted_by_restart` (unknown outcome, never executed again); a callback the current controller admitted still stays pending.
|
||||
|
||||
**The record already exists.** The intent is the Runner's durable semantic input (committed before dispatch, keyed by call ID). The outcome is the server's idempotency receipt in `heartbeat_runs.result_json.semanticToolReceipts`. For `write_document` the revision, the activity row and the receipt commit in one transaction under the run and issue row locks, and the revision is compare-and-swap on `baseRevisionId`.
|
||||
|
||||
**What it proves.** Receipt present: applied. Receipt absent: not applied, because the effect cannot commit without it. So recovery runs the same receipt-guarded mutation. It replays the saved result or applies the write for the first time, never twice. A late original callback then replays the receipt. A stale base, a reused key or invalid input is the call's definite outcome and settles as a tool error. Any other failure leaves the call unsettled, as before. The set of operations with this proof is explicit (`TRANSACTIONAL_RECEIPT_OPERATIONS`, `write_document` only); other tools keep their current rules.
|
||||
|
||||
This makes the gateway call idempotent on its durable input, which is the cleaner proof the brief allowed. It needs no Runner change and no new image.
|
||||
|
||||
**Not done.** Exposing the cleanup-gate owner's run id so the server can drop the 50-run scan bound from #20639 (optional in the brief) is left out to keep scope.
|
||||
|
||||
## Upgrade safety
|
||||
|
||||
- Old saved state, new code. A `turn_starting` session saved by an older Runner has no journal (or one for another turn): unknown, so the old lost-turn path runs unchanged. Old receipts already have the shape the transactional recovery reads.
|
||||
- New state, old code mid-deploy. Change 1 adds no field to `acpx-provider-state.json` (its decoder denies unknown fields). It only saves lifecycles an old Runner already handles (`prepared`, then `suspended`/`session_open`). An old Runner ignores the journal file. Change 2 changes no saved shape.
|
||||
- New Runner, old sidecar. Possible only with a stale pack; the contract digest prevents reuse. If it happens anyway, an old sidecar writes no `received` line, so the proof never forms.
|
||||
|
||||
## Time to first token
|
||||
|
||||
Change 2 touches only recovery. Change 1 adds to every turn, before the prompt reaches the provider: one small unsynced file write when the turn starts, and one append plus `fsync` immediately before the prompt write. It adds no wait, no file transfer and no round trip. Measured with the same open/write/fsync sequence on a loaded macOS host (APFS, load average ~11, 300 samples): the `received` write p50 0.24 ms, p95 0.59 ms; the `dispatched` append and fsync p50 4.7 ms, p95 11.5 ms. Against a Claude TTFT budget of 9.5–16.5 s p50 this is under 0.1%. Linux overlay disks in Daytona were not measured. Recovery-time work (fence proof, journal read) runs only after a failure.
|
||||
|
||||
## Not covered: a remote Runner gone mid-turn with tools running
|
||||
|
||||
Staging class R, item 1 (`runner_remote_process_identity_unavailable`, mostly OpenCode on Daytona). A deploy stops the controller for 4–7 min while a turn runs tools. On recovery the remote Runner is gone (`process_not_running`, `runnerSettled: false`), or it is adopted and `session.snapshot` then times out. The turn is unsettled and tool effects are possible, so recovery refuses (`provider_turn_unsettled`) and Retry is needed. Retry works.
|
||||
|
||||
The question is whether a durable record can prove "no tool call was in flight when the Runner stopped" (every intent has an outcome), so recovery could continue from the checkpoint. **These two changes do not cover it.** What they give, and what is missing:
|
||||
|
||||
- **Paperclip semantic tools** (calls that reach the server's tool gateway). The intent is the controller's committed semantic input, keyed by call ID. The outcome is the server receipt or the journaled result command. Both live on the control plane, so they are readable without a live Runner. Change 2 makes `write_document` settle exactly once from its receipt. Other semantic tools keep their rules.
|
||||
- **Provider-native tools** (OpenCode's shell and file edits, Claude's built-in tools). These are the class R calls, and they have **no write-ahead intent record**. The Runner learns of a tool only from a provider event (`tool.execution.started`), which the provider emits after it decided to run the tool, and often after it started it. A missing `started` event therefore does not prove that no tool ran. A complete record needs a hook that runs before execution: a permission or pre-tool callback that the provider waits on (OpenCode plugins and ACP permission requests can serve), which journals the intent durably in the Runner's state before it answers.
|
||||
- **Readable without a live Runner.** The Runner's journal (`runner-state.json`, provider state) is in the sandbox. Commands already delivered stay on the controller, but events the Runner had not yet delivered are only in the sandbox. The server would need to read the sandbox files through the provider API (Daytona filesystem) after it proves the Runner and provider processes are stopped. It would also need a way to trust those bytes: today they carry no signature that binds them to the Runner's authenticated session. Process proof alone is not enough for an adopted Runner whose `session.snapshot` timed out; that case needs the same file read after a forced stop.
|
||||
- **The rule it would enable.** Every journaled intent has a matching outcome, the provider and Runner are proven stopped, and the last checkpoint covers the last outcome: recovery may resume from the checkpoint and send a same-conversation continuation. Anything else keeps Retry.
|
||||
|
||||
This is a follow-up, not part of these PRs.
|
||||
@@ -0,0 +1,309 @@
|
||||
# Staging failures vs chaos-harness coverage (2026-11-09 00:00Z to 2026-11-11 00:05Z)
|
||||
|
||||
Question from Dotta: what failed on `paperclip.staging.paperclip.app` in the last 48 hours, why
|
||||
did the restart-chaos harness (`tests/restart-chaos/`) not find it first, and what must the harness
|
||||
add so it would.
|
||||
|
||||
## Answer first
|
||||
|
||||
1. **276 runs failed, were cancelled or were interrupted in 48 hours, across 114 tasks.** At census
|
||||
time, 63 of those tasks (55%) were still `blocked`.
|
||||
2. **Staging is a continuous deploy target.** There were 47 server process starts in 48 hours. 45 of
|
||||
them were new Railway deployments: about one deploy every 40 minutes in working hours. Each deploy
|
||||
replaces the container, so the new server runs in a **different process space** (host, kernel boot
|
||||
and PID namespace) with **newer code**. Remote Daytona sandboxes keep the previous runner.
|
||||
3. **The harness restarts the same build on the same Mac, at once.** A harness restart keeps the
|
||||
process space and has no deployment identity. It is back in seconds. A staging deploy has three
|
||||
differences:
|
||||
- it sends a graceful SIGTERM, often 1–3 s after a native coordinator claim;
|
||||
- the server stays down for 4–7 minutes;
|
||||
- it has a new deployment identity.
|
||||
|
||||
Native recovery uses the deployment proof (`proveOwnerGone`, `deployment_replaced`), not PID
|
||||
proofs. So the process space matters less than first assumed. This was corrected after review.
|
||||
The open gap is the long, mid-turn outage, during which the remote Runner is lost (class R
|
||||
below). The harness passed D1 8/8 and D5 6/6 on master while staging blocked tasks.
|
||||
4. **The Daytona matrix does not use the staging workload mix.** Staging runs OpenCode in 66% of
|
||||
native runs (1266 of 1917), uses reusable sandboxes (saved epochs up to 5), runs 25 agents and has
|
||||
long-lived parent/child task trees. The Daytona matrix runs only `codex,claude` on fresh
|
||||
per-run sandboxes, one task tree deep, with waves shorter than one hour.
|
||||
5. **The harness never builds old saved state.** In the largest class by count, automatic wakes
|
||||
failed 99 times in a row on one parent task over 8.5 hours. That needed a workspace shared under a
|
||||
policy retired on 2026-11-07, and every wave starts from an empty database. The existing U2 check
|
||||
would have failed the task, so grading was not the gap.
|
||||
|
||||
## Method and sources (read-only)
|
||||
|
||||
Task labels `T01`–`T60` stand in for staging task identifiers, which are instance-local. The census
|
||||
owner keeps the mapping outside the repository.
|
||||
|
||||
- Staging API, GET only, with the operator's existing CLI token loaded into a child process:
|
||||
- `/api/health`;
|
||||
- `/api/companies/:id/heartbeat-runs` (company and per agent);
|
||||
- `/api/heartbeat-runs/:id`;
|
||||
- `/api/heartbeat-runs/:id/events`;
|
||||
- `/api/issues/:id`, `/runs`, `/activity` and `/recovery-actions`.
|
||||
|
||||
One company exists. There were 1917 runs in the window.
|
||||
- Deploy and restart times: every run record carries `controllerProcess`, with `processStartedAt`,
|
||||
`bootId` and the Railway `deploymentId`. The timeline below is built from those fields.
|
||||
GitHub has no staging deployment records, because staging deploys from Railway.
|
||||
- `git log origin/master` for fixes that touch each failure code.
|
||||
- Window: a failure counts when its run finished at or after 2026-11-09T00:00Z.
|
||||
|
||||
### Data the census could not read
|
||||
|
||||
- **Sentry and Honeycomb:** no read credentials for staging were available. The only keys are
|
||||
ingest/test-config keys. Sentry triage was not run.
|
||||
- **a PR-review agent runs:** runs from 2026-11-09 00:00–14:52Z are missing. That agent made more than
|
||||
1000 runs in the window, and the run list caps at 1000 with no cursor. Other agents are complete.
|
||||
- **Commit per deploy:** Railway deployment IDs do not map to git SHAs through the API. Only the
|
||||
current SHA (`358977454b`, #20649) is visible. "Fixed on master" therefore means "a merged PR
|
||||
changes this path". It does not mean the fix was proven live on staging.
|
||||
- **Brief staging outage:** staging was in a maintenance window, `tenant_app_unavailable`, at about
|
||||
00:11Z on 2026-11-11, during the census. That was another deploy. Data read before the window is
|
||||
complete.
|
||||
|
||||
## Class table
|
||||
|
||||
The share column is the share of the 276 failed runs. The "Blocked now" column counts tasks still
|
||||
blocked at census time.
|
||||
|
||||
| Class | Runs | Share | Tasks | Blocked now | Mechanism (root) | Fixed on master? | Why the harness missed it | Proposed scenario |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| W: wake loop on a held shared workspace | 103 | 37% | 4 | 1 | A parent shares a legacy execution workspace with a child that stranded a writer hold on Nov 5. The new stall-wake feature (#20098) woke the parent every 10 min. Each wake failed setup with no backoff. T01 had 99 runs from 07:27 to 15:53Z. | **Fixed:** #20273, #20295, #20314 | Fresh database every wave, so there was no legacy shared-workspace state. The feature landed between waves. U2 would have caught the loop. | None (fixed). If needed: K14 from a pre-2026-11-07 build with M1. |
|
||||
| R: remote recovery refuses after a deploy | 34 | 12% | 32 | **24** | Recovery after a deploy refuses to continue. Codes include `runner_remote_process_identity_unavailable` (9), `native_remote_recovery_lease_mismatch …identity_run_id` (8), `prior_owner_terminal_state_indeterminate` (6), `cleanup_quarantined` (4) and `missing_evidence` (3). 27 of 34 failed within 10 min of a process start. | **Mostly fixed:** `identity_run_id` by #20642, `prior_owner…` by #20677, others by #20639, #20631, #20666, #20662 and #20650. **Open:** `runner_remote_process_identity_unavailable`, where the remote Runner is gone after a 4–7 min mid-turn outage. | Harness restarts come back at once, with no long mid-turn outage. There were no OpenCode cells on Daytona (19 of 34 are OpenCode). No Daytona workload keeps a tool running across the fault. | **K15 redeploy** (implemented). A long-hold and mid-tool variant with sandbox-side Runner log capture is the follow-up. |
|
||||
| F: finalization and workspace save-back | 24 | 9% | 15 | 8 | A saved result cannot be copied back or restored. Causes: sandbox disk full (ENOSPC in 2 runs), unsafe symlink in the archive, `recovery_receipt_invalid` (7), a stuck "Recovering saved work…" phase (8) and an exhausted finalization budget (3). | **Partly fixed:** #20666 (receipt), #20578 (re-finalize). Nothing for disk full or symlinks. | Workloads write small files. They never fill the sandbox disk and never create symlinks. ST faults hit S3, not the sandbox disk. | **F1 symlink** workload (built; passes on master). **DF1 sandbox disk full** (proposed). |
|
||||
| E: Daytona capacity outage | 18 | 7% | 13 | 4 | Daytona returned HTTP 502 and the worker hit SIGKILL from 16:36 to 17:02Z on Nov 10. Reusable sandbox resume failed, plus a git clone network failure. | **Mostly recovers:** 8 tasks recovered automatically and bounded retry works. 4 tasks still blocked. | The harness has no environment-provider fault. All faults hit the control plane or S3. | **EP1 environment provider 5xx window** (proposed, not built). |
|
||||
| U: provider usage limit | 17 | 6% | 12 | 8 | `provider_limit_wait` waits as designed. The ACPX "terminal limit failure" (7) fails the run, where it should wait. | **Open:** ACPX limit classification. | Not a restart class. Provider shims have no usage-limit message. | Add a usage-limit message to PV faults (proposed). |
|
||||
| P: provider session resume after a deploy | 16 | 6% | 16 | **11** | The runner or provider cannot resume its session after the controller moved. Codes: `PRP provider resume state is unavailable` (5), `runner_harness_state_mismatch` (8) with sub-codes `provider_identity_incomplete`, `resumed_unavailable` and `backup_without_reusable_lease`, plus `ingress_auth_failed` and `run.attach provider_side_effect_pending`. 8 of the 16 are ACPX and 5 are OpenCode. | **Partly fixed:** #20627 (warm backup). `resume state unavailable` is open. | Same as R: same process space, no OpenCode, no reusable warm sandboxes across deploys. | K15 with `--daytona-warm` and `--adapters claude,opencode`. |
|
||||
| O: other or unclassified native failures | 13 | 5% | 13 | 5 | `native_run_failed` with no classified error (3), ACPX `session.open` rejected (2), `local_runtime_api_listener_unavailable` (2), `tool.resolve provider_tool_call_retired`, a DB query error, and `Object not found`. | **Open:** classification. | Not deploy-correlated (0 of 13 within 10 min). | None. These are product triage items. |
|
||||
| B: authorization or binding readiness | 13 | 5% | 9 | 3 | `reviewed_chat_execution_binding_not_authorized` (7) and `not_ready` (2), a credential not shared with the responsible user (2), and a skill package still uploading (2). | **Open** | The harness uses one operator. There are no chat bindings, no shared credentials and no skill uploads. | Out of scope for restart chaos. Route to product. |
|
||||
| L: legacy runtime lost across a deploy | 12 | 4% | 12 | 5 | Legacy (non-native) runs: `process_lost` (5), `Legacy controller lease lost` (4), graceful SIGTERM (1) and `lease_released_before_terminal` (2). | **Recovers in most cases:** 7 of 12 tasks recovered. | The matrix runs native adapters only. | K15 with a legacy adapter cell (proposed). |
|
||||
| X: expected cancellations | 11 | 4% | 9 | 2 | Reassignment, ownership changes, dependency blocks and operator interrupts. | No fix needed | n/a | none |
|
||||
| A: runner or provider-pack artifact incompatible after an upgrade | 8 | 3% | 8 | 4 | New code meets a sandbox prepared by older code. Codes: `OpenCode executable is missing from the provider pack`, `ACPX launch profile omitted its provider-pack authority`, `native_provider_artifacts_admission_unverified` (3), `runner_remote_artifact_platform_mismatch` and `runner_revision_mismatch`. | **Open** | Daytona waves require the runner content to match the image and refuse mismatches. That is exactly the mixed-version state staging lives in. K14 is local only. | **K15 with `--upgrade-from` on Daytona** (allows mixed runner/image versions; proposed follow-up). |
|
||||
| V: runner event commit stall | 7 | 3% | 5 | 2 | `native_event_replay_conflict: runner_event_commit_stalled`, Codex and ACPX, 20:49–23:55Z on Nov 9. No deploy correlation. | **Likely fixed:** #20385 (usage receipt stalls). No occurrence after 23:55Z on Nov 9. | Database contention (L1) used one-row pressure, not the receipt-update pattern. | none (fixed) |
|
||||
|
||||
Totals: 276 runs and 114 tasks. Classes R, P, A and L together are the deploy-crossing failures:
|
||||
70 runs (25%) and **44 currently blocked tasks**, which is most of the user-visible harm. Class W is
|
||||
the largest by count but is fixed.
|
||||
|
||||
## Deploy timeline (Railway, from run records)
|
||||
|
||||
47 process starts between 2026-11-08T22:03Z and 2026-11-10T23:23Z. All but one are new
|
||||
`deploymentId`s. The exception is a same-deployment restart at 2026-11-09T14:28Z. The median gap in
|
||||
working hours is about 40 minutes. Every native run longer than about 40 minutes crosses a deploy.
|
||||
|
||||
67 of 276 failures (24%) finished within 10 minutes after a process start. In classes R and P, 30 of
|
||||
50 did. In classes E, O and V, almost none did.
|
||||
|
||||
## Per-class detail
|
||||
|
||||
### W: wake loop on a held shared workspace (103 runs, fixed)
|
||||
|
||||
- Examples: T01 (99 runs), T02, T03 and T04.
|
||||
- Timeline:
|
||||
1. On Nov 5, child T05 failed setup (`workspace_busy`, then `setup_failed`). Its parent
|
||||
T01 shared the workspace, a pre-2026-11-07 policy.
|
||||
2. On Nov 9, #20098 ("wake the parent once when a child stalls") reached staging. At 07:27Z the
|
||||
parent began to be woken about every 10 min by `issue.blocker_stalled_wake`.
|
||||
3. Every wake failed with `The workspace still has an unfinished writer or save operation.`
|
||||
4. At 15:53Z the parent became `blocked`.
|
||||
- Fixed by:
|
||||
- #20273, which stops stall wakes from failing setup on a held workspace;
|
||||
- #20295, which re-proves an exhausted save's agent stop;
|
||||
- #20314, which moves stranded legacy subtasks off a parent's held workspace.
|
||||
- Why the harness missed it:
|
||||
- **Old saved state:** every wave starts from an empty database, so a parent/child pair sharing a
|
||||
workspace (the legacy policy) never exists.
|
||||
- **Missing feature in the tested build:** #20098 landed at 00:26Z on Nov 9, after the last wave
|
||||
that had a stalled child.
|
||||
- **Timing window:** the loop starts only after a child stalls for longer than the stall threshold.
|
||||
- **Grading is not the gap.** The enforced U2 check already fails a task after more than three
|
||||
failures with the same code and no status change. The parent would have failed U2 on its fourth
|
||||
wake, if a wave had created the legacy state.
|
||||
- Scenario: none is built in this pass, because the class is fixed and the shared-workspace policy
|
||||
is retired for new subtasks. A K14 wave from a pre-2026-11-07 build with M1 would recreate the
|
||||
legacy state, if the fix needs regression cover.
|
||||
|
||||
### R: remote native recovery refuses after a deploy (34 runs, 24 tasks blocked)
|
||||
|
||||
- Examples:
|
||||
- T06, T07, T08 and T09 (`lease_mismatch identity_run_id`);
|
||||
- T10, T11, T12 and T13 (`identity_unavailable`);
|
||||
- T14, T15, T16 and T17 (`prior_owner_terminal_state_indeterminate`, with
|
||||
`retirement_refused=journal_commands_unsettled(run.attach.pending | semantic_tool.result.pending)`);
|
||||
- T18 and T19 (`cleanup_quarantined`).
|
||||
- Mechanism, per sub-code. This was corrected after review by the class R fix owner.
|
||||
- Native recovery does **not** depend on PID proofs. It uses `proveOwnerGone`, which accepts a
|
||||
replaced Railway deployment on an exclusive volume (`deployment_replaced`) or a stopped or fenced
|
||||
boot row. The only PID-only caller left is the runtime skill cache lock (#20688).
|
||||
- `native_remote_recovery_lease_mismatch … identity_run_id`: the leases were ephemeral and the
|
||||
sandboxes fresh, so a reused sandbox was not the cause. This is the shape that #20642 fixed. The
|
||||
last staging occurrence was 14:43Z on Nov 10.
|
||||
- `prior_owner_terminal_state_indeterminate` with unsettled `run.attach` or `semantic_tool.result`:
|
||||
fixed by #20677. Retirement is no longer held when the prior ephemeral sandbox is provably
|
||||
destroyed.
|
||||
- `runner_remote_process_identity_unavailable` is **still open**:
|
||||
1. The controller dies mid-turn while tools run.
|
||||
2. Recovery starts 4–7 minutes later.
|
||||
3. By then the remote Runner process is gone, or its `session.snapshot` times out.
|
||||
|
||||
Why the Runner exits despite its 60-minute connection lease is not yet known.
|
||||
- Last occurrences: `identity_unavailable` 2026-11-10T08:10Z, `lease_mismatch` 14:43Z, `prior_owner…`
|
||||
18:56Z and `cleanup_quarantined` 17:48Z.
|
||||
- Code pointers:
|
||||
- `server/src/services/native-runtime/native-session-executor.ts:14247` (identity wait);
|
||||
- `server/src/services/native-runtime/remote-recovery-lease-mismatch.ts`;
|
||||
- `server/src/services/heartbeat/restart-interrupted-turn.ts`.
|
||||
- Why the harness missed it:
|
||||
1. **Deploy timing:** a staging deploy sends a graceful SIGTERM, often 1–3 s after
|
||||
`native.coordinator.claim`, and the server stays down for 4–7 minutes. K2 restarts at once,
|
||||
and K4's long hold uses SIGKILL.
|
||||
2. **Missing adapter:** OpenCode (19 of 34) never ran in a Daytona cell.
|
||||
3. **Mid-turn Runner loss:** no Daytona workload keeps a tool running across the fault. The
|
||||
`tool` trigger covers only the local B5 shell bench, so the remote Runner is never under a
|
||||
running tool when the controller goes away.
|
||||
4. **Missing environment shape:** `--daytona-reuse-lease` and `--daytona-warm` are not in the
|
||||
matrix.
|
||||
- Scenario: **K15 redeploy** (implemented). The fault does a graceful SIGTERM like K2. The
|
||||
replacement then starts in a new emulated process space (a new hostname through a preload, so
|
||||
`processSpaceHash` changes) and with a new Railway-shaped deployment identity on the same volume.
|
||||
Selected with `--faults K15`. RED wave: see "Harness expansion" below.
|
||||
|
||||
### F: finalization and workspace save-back (24 runs, 8 tasks blocked)
|
||||
|
||||
- Examples:
|
||||
- T20 (`sync_out_retry_exhausted` from disk full, then the finalization budget, three times);
|
||||
- T21 (`remote_workspace_archive_unsafe_symlink`);
|
||||
- T22, T23 and T24 (`remote_workspace_recovery_receipt_invalid`);
|
||||
- T25 and T10 ("Recovering saved work…" phase cancelled with
|
||||
`execution_reconciliation_required`);
|
||||
- T26, T27 and T28 (07:26Z on Nov 9, right after a deploy).
|
||||
- Fixed: #20666 (skip unverifiable recovery sources) covers `receipt_invalid`, which last occurred
|
||||
at 22:35Z, before that fix was deployed. Disk-full and symlink save-back have no fix and no
|
||||
scenario.
|
||||
- Why the harness missed it: **missing workload.** The workloads write a few KB, never fill the
|
||||
sandbox disk and never create symlinks. ST faults break S3, not the sandbox file system.
|
||||
- Built: the **F1** workload (`--workloads F1`). The agent keeps an absolute symlink to `/etc/hosts`
|
||||
in its repository workspace. Wave `w-20261111T012523-s9304` (Daytona, `--storage s3`, K2, Codex
|
||||
and OpenCode) passed 2 of 2 on master. The save-back did not block the task. The harness keeps no
|
||||
evidence for passing tasks, so it is not verified that the link existed at save-back time.
|
||||
- Proposed (not built): `DF1`, which fills the sandbox disk to ENOSPC before result copy-back.
|
||||
|
||||
### E: Daytona capacity outage (18 runs, mostly self-healing)
|
||||
|
||||
- 2026-11-10 16:36–17:02Z:
|
||||
- `Daytona sandbox creation failed (HTTP 502)` (10);
|
||||
- `Worker process exited (code=null, signal=SIGKILL)` (3);
|
||||
- `Reusable sandbox lease … could not be resumed (cause=provider_error | transport_timeout)` (3).
|
||||
- Plus one `git=network` clone failure and one Daytona rate-limit failure.
|
||||
- Bounded retry recovered 8 of 13 tasks. 4 remain blocked (T29, T30, T31 and
|
||||
T32 are examples).
|
||||
- Fix #20626 (retry and replace a reusable sandbox that will not resume) shipped before the outage.
|
||||
Its effect at this scale is not verified.
|
||||
- Why the harness missed it: **missing fault type.** There is no environment-provider fault. All
|
||||
harness faults hit the control plane, S3 or the provider message stream.
|
||||
- Proposed: `EP1`, a proxy in front of the Daytona API that returns 502 or times out for a window.
|
||||
|
||||
### U: provider usage limit (17 runs)
|
||||
|
||||
- `provider_limit_wait` (10) is the designed wait.
|
||||
- The ACPX "terminal limit failure" (7, an error-triage agent) fails the run. It should wait. This is a product
|
||||
classification gap in the ACPX limit mapping.
|
||||
|
||||
### P: provider session resume after a deploy (16 runs, 11 tasks blocked)
|
||||
|
||||
- Examples:
|
||||
- T33, T34, T35 and T25 (`PRP provider resume state is unavailable`);
|
||||
- T36, T37, T38 and T39 (`runner_harness_state_mismatch …`);
|
||||
- T40 (`run.attach provider_side_effect_pending`).
|
||||
- Last occurrence: 2026-11-10T21:06Z.
|
||||
- #20627 (restore a warm backup when its source sandbox is idle) covers `backup_without_reusable_lease`
|
||||
and `resumed_unavailable`. `resume state is unavailable` and `provider_identity_incomplete` have no
|
||||
fix.
|
||||
- Why the harness missed it: the same reasons as R, plus ACPX (8) and OpenCode (5) on warm reusable
|
||||
sandboxes, which the matrix does not run.
|
||||
|
||||
### O: other (13 runs)
|
||||
|
||||
- Not deploy-correlated.
|
||||
- `native_run_failed` without a classified provider error appeared on T41, T42 and
|
||||
T43. Those runs reached `run.result.accepted` after two `turn.failed` events.
|
||||
- ACPX `session.open` was rejected on T44 and T45.
|
||||
- These are product triage items, not chaos gaps.
|
||||
|
||||
### B: authorization or binding readiness (13 runs)
|
||||
|
||||
- `reviewed_chat_execution_binding_not_authorized`: 7 runs on a PR-review agent (T30 and T46).
|
||||
- A credential not shared with the responsible user.
|
||||
- Skill package uploads still in flight (T47).
|
||||
- These are product authorization and readiness checks. They are outside the restart-chaos domain.
|
||||
|
||||
### L: legacy runtime lost across a deploy (12 runs)
|
||||
|
||||
- Examples:
|
||||
- `process_lost` on T26, T27 and T48 (07:11Z on Nov 9, three minutes after a
|
||||
deploy);
|
||||
- `Legacy controller lease lost` on T49, T50, T51 and T52 (08:14–08:19Z on
|
||||
Nov 10, 20 minutes after a deploy).
|
||||
- 7 of 12 tasks recovered.
|
||||
- The matrix has no legacy adapter cell. K15 could run one, but this was not done in this pass.
|
||||
|
||||
### A: artifact incompatible after an upgrade (8 runs)
|
||||
|
||||
- Examples: T53 and T54 (`OpenCode executable is missing from the provider pack`), T55
|
||||
(`ACPX launch profile omitted …`), T56, T57 and T58
|
||||
(`native_provider_artifacts_admission_unverified`), and T59 (`runner_revision_mismatch`).
|
||||
- Mechanism: a sandbox prepared and admitted by older code is resumed by newer code that expects
|
||||
new launch-profile fields or provider-pack contents.
|
||||
- Why the harness missed it: Daytona waves refuse to run unless the runner content ID equals the
|
||||
image (`daytona-image.ts`). This is deliberate, and it excludes exactly this mixed-version state.
|
||||
- Follow-up: K15 with `--upgrade-from` on Daytona, with the image of the older checkout.
|
||||
|
||||
### V: runner event commit stall (7 runs, likely fixed)
|
||||
|
||||
- Examples: T60 and T22 (Nov 9, 20:49–23:55Z).
|
||||
- #20385 (usage receipt stalls during streamed run updates) merged at 23:35Z, and the class has not
|
||||
occurred since.
|
||||
|
||||
## Harness expansion (this pass)
|
||||
|
||||
| Scenario | Classes | Selector | Status |
|
||||
| --- | --- | --- | --- |
|
||||
| K15 redeploy into a new process space and deployment identity | R, P, L (and A with `--upgrade-from`) | `--faults K15` | Implemented, unit-tested. Five Daytona waves are recorded below. |
|
||||
| EP1 environment-provider 5xx window | E | — | Proposed |
|
||||
| F1 absolute symlink kept in the repository workspace | F (unsafe-symlink save-back) | `--workloads F1` | Implemented, unit-tested. Daytona wave: 2 of 2 pass on master. |
|
||||
| DF1 sandbox disk full | F (ENOSPC save-back) | — | Proposed |
|
||||
|
||||
### Waves on master 8f6ca25976
|
||||
|
||||
All waves ran on Daytona image `ghcr.io/paperclipai/paperclip-daytona-runner@sha256:bc7ca92d…`
|
||||
(runner content `d7e4d82a…`).
|
||||
|
||||
| Wave | Args | Result |
|
||||
| --- | --- | --- |
|
||||
| `w-20261111T002313-s9301` | `--faults K15 --adapters opencode,claude --workloads A1,C1 --daytona-reuse-lease --concurrency 3 --tasks 6` | 5 of 6 pass. t05 (OpenCode, C1) failed R5 `silent_dead_run`: its run stayed `running` with no event, activity or start evidence for 183 s after the redeploy, then succeeded. No Retry was needed. |
|
||||
| `w-20261111T004241-s9301` (control) | the same seed and cells with `--faults K2` | 6 of 6 pass |
|
||||
| `w-20261111T005008-s9302` | `--faults K15 --triggers time,comment --adapters opencode,claude --workloads C1 --daytona-warm --concurrency 4 --tasks 4` | 4 of 4 pass |
|
||||
| `w-20261111T010000-s9303` | `--faults K15 --adapters opencode --workloads A1,C1 --daytona-reuse-lease --concurrency 4 --tasks 8` | 8 of 8 pass |
|
||||
| `w-20261111T011044-s9303` (control) | the same seed and cells with `--faults K2` | 8 of 8 pass |
|
||||
|
||||
What this shows:
|
||||
|
||||
- Under K15, 17 of 18 tasks passed. Under K2 with the same seeds, 14 of 14 passed. The one failure,
|
||||
a 183 s silent OpenCode run after a redeploy, occurred only under K15. One failure in 18 is not a
|
||||
stable reproduction.
|
||||
- The staging refusal codes of classes R and P did **not** reproduce on current master with K15
|
||||
alone. Examples are `identity_run_id` lease mismatch, `runner_remote_process_identity_unavailable`
|
||||
and `prior_owner_terminal_state_indeterminate`. Two explanations remain open:
|
||||
- The fixes merged during the window (#20625, #20631, #20639, #20650, #20662, #20666) cover them.
|
||||
Staging ran older revisions for most of the window.
|
||||
- They need conditions that K15 does not emulate yet:
|
||||
- a code change at the deploy, where new server code meets saved state and a sandbox runner from
|
||||
the older build (class A);
|
||||
- one sandbox reused across different tasks of one agent;
|
||||
- many agents and concurrent tasks under load.
|
||||
- The next scenario to build is **K15 with `--upgrade-from` on Daytona**: start with the older
|
||||
checkout and its image, redeploy to the current checkout, and keep the older runner in the
|
||||
retained sandboxes. Today the Daytona image check refuses that mixed state on purpose.
|
||||
@@ -658,6 +658,20 @@ for file storage before <step>; it was still unavailable." Its payload holds
|
||||
`reason: "storage_outage_wait"`, `purpose` (the step), `waitedMs`, and
|
||||
`recovered`. The record stays in the instance run log.
|
||||
|
||||
When the outage outlasts that wait, the run fails. Only a run recorded with
|
||||
`errorCode: "storage_unavailable"` gets a storage wait: a bounded retry
|
||||
(`retryReason: "storage_unavailable_wait"`) that starts again after storage is
|
||||
back. Its error says "Paperclip will retry automatically when storage is back"
|
||||
only while that retry is scheduled. When the retry budget is spent, the error
|
||||
says so and asks for Retry. When no storage wait follows, the error says
|
||||
"Paperclip is not retrying it automatically. Retry or send a message to
|
||||
continue." That happens when a native recovery already holds the run under
|
||||
another code (for example `native_continuation_requires_reconciliation`, where
|
||||
its files are kept and its unfinished turn is not replayed), or when the retry
|
||||
is refused or cannot be written. A run saved by an earlier release with the
|
||||
retry promise under another code reads with the same Retry text, with no
|
||||
migration.
|
||||
|
||||
## Durable storage timing
|
||||
|
||||
A saved remote workspace is one encrypted archive in durable object storage.
|
||||
|
||||
@@ -112,6 +112,55 @@ unconfirmed cleanup do not qualify. Error messages cannot authorize recovery.
|
||||
An arbitrary `closed` provider state stays closed. This path does not establish
|
||||
recovery for a Runner killed during an accepted turn.
|
||||
|
||||
## ACPX turn starts cut off before the prompt left
|
||||
|
||||
A turn start can fail without a definite answer: the sidecar's reply is lost or
|
||||
late (for example, a host freeze outlasts the request deadline), or the sidecar
|
||||
or Runner dies while the start is in flight. Resending the prompt could
|
||||
duplicate it, and a continuation could lose it.
|
||||
|
||||
The sidecar's runtime port keeps a prompt-dispatch journal,
|
||||
`paperclip-turn-dispatch.jsonl`, in the session's private runtime directory
|
||||
(`turnDispatchJournalFile` and `turnDispatchJournalRecord` in the sidecar
|
||||
schema). When it starts a turn, before any provider work, it truncates the file
|
||||
and writes a `received` record. Immediately before ACPX writes the turn's first
|
||||
`session/prompt` request to the provider, it appends a `dispatched` record and
|
||||
fsyncs it. ACPX calls the host's `onAcpMessage("outbound")` hook synchronously
|
||||
before it writes the bytes, so a failed journal write aborts the prompt write.
|
||||
|
||||
The Runner reads the journal only after it acquires the provider lifetime fence,
|
||||
which proves that the sidecar and the provider are gone.
|
||||
|
||||
- A lone, complete `received` record for the turn proves that the prompt never
|
||||
reached the provider. A start that failed in flight saves the session
|
||||
`prepared`, with no active turn, and fails the command with
|
||||
`ACPX turn start failed before its prompt reached the provider`. The run's
|
||||
next `turn.start` reopens the conversation and sends the prompt once. A
|
||||
Runner that died while the session was `turn_starting` restores the session
|
||||
idle, emits `session.resumed` and no `turn.failed`, and the same-run resume
|
||||
starts the turn once.
|
||||
- A `dispatched` record, a record of another turn, a torn or malformed file, or
|
||||
no file (an older sidecar) proves nothing. The earlier behavior applies
|
||||
unchanged: a failed start closes the session, and a killed Runner uses
|
||||
lost-turn recovery.
|
||||
- A session this run closed cannot reopen for the same run. The failed start,
|
||||
and every later `turn.start` of the run, fail with the closed class
|
||||
`provider_session_closed` in the command result. The controller records
|
||||
`native_provider_session_closed`, stops same-run retries, and the board offers
|
||||
Retry at once. Retry starts a new run with a fresh provider conversation and
|
||||
the saved task context. An older Runner sends the same text without the class; the
|
||||
controller then keeps its bounded same-run retries, because the same text
|
||||
also covers a session that can reopen after a restart.
|
||||
|
||||
Until a proof settles it, the saved session stays `turn_starting`, so a Runner
|
||||
killed during the proof restores through the same check. The cut-off command is
|
||||
never executed again. Saved state gains no field, so an older Runner reading it
|
||||
mid-deploy sees only lifecycles it already handles.
|
||||
|
||||
On the normal path the journal costs one small unsynced write when the turn
|
||||
starts and one append and fsync just before the prompt is written. It adds no
|
||||
wait, round trip or file transfer.
|
||||
|
||||
## ACPX cancellation without a reply
|
||||
|
||||
The Runner serves controller commands one at a time. It therefore waits at most
|
||||
@@ -178,6 +227,16 @@ protected launch argument fails with the closed classification
|
||||
controller never opens a replacement session after either class, whatever the
|
||||
checkpoint's recovery policy, and stops the run for an operator.
|
||||
|
||||
A remote session whose saved working directory is not the run's assigned
|
||||
workspace root (its workspace epoch was abandoned, so the saved version was
|
||||
restored into a new root) cannot resume there. The driver declines it before
|
||||
any Runner or provider process starts. An idle session reports
|
||||
`provider_state_incompatible`: a replacement opens in the assigned root when the
|
||||
checkpoint allows it, and otherwise the run fails with
|
||||
`native_provider_state_incompatible`. A session with an unfinished provider turn
|
||||
or a pending runtime request reports `provider_side_effect_pending` and stops
|
||||
for an operator, whatever its recovery policy.
|
||||
|
||||
A restart can kill the runner after it journaled a run's own cold `run.attach`
|
||||
and before the attachment finished. The restored runner settles that command as
|
||||
`execution_indeterminate` and never executes it again. When the journal shows no
|
||||
@@ -192,6 +251,25 @@ Attaching starts no turn, and the runner admits the new command only for a
|
||||
settled session, so the run continues instead of failing on the old command.
|
||||
Warm transitions and staged attachments keep their exact replay paths.
|
||||
|
||||
A restart can kill the runner inside `runner.suspend` in the same way. The
|
||||
next runner replays it from the welcome as `execution_indeterminate`, sends it
|
||||
as `failed`, and still treats it as terminal: it records `suspended` and exits
|
||||
once the controller acknowledges the result. The controller therefore keeps the
|
||||
terminal fence for that result (it lifts the fence only for a suspension the
|
||||
runner refused), and its acknowledgement names the runner's journal status
|
||||
`indeterminate`. Current runners accept either `indeterminate` or `failed`; older
|
||||
runners accept only `indeterminate` and otherwise exit with "terminal command
|
||||
result acknowledgement changed its durable identity".
|
||||
|
||||
That runner exits before it accepts any command of the new attempt. During
|
||||
startup, the controller restarts it in place once, so the attempt continues.
|
||||
It does this only when the runner's durable journal proves the exit: its last
|
||||
command is exactly the suspend that an earlier attempt journaled, the
|
||||
controller has settled that suspend, the runner rests `suspended` with no
|
||||
terminal or provider cleanup fence, and no command of this attempt has a
|
||||
result. The runner file is read only after such an exit. Any other exit keeps
|
||||
its earlier failure.
|
||||
|
||||
A kill during that attachment's provider launch can also leave a `spawned`
|
||||
startup fence over a `prepared` state that holds a saved thread. The next runner
|
||||
retires that fence once the recorded provider process and its group have exited,
|
||||
@@ -603,6 +681,18 @@ callback that this process is not running (`dispatchToolCallback`) as
|
||||
earlier controller can never record a result, so this is the callback's only
|
||||
settlement, and it never executes the operation again. Every other unresolved
|
||||
input stays unsettled.
|
||||
|
||||
`write_document` needs neither fallback. Its revision and its idempotency
|
||||
receipt commit in one transaction under the run and issue row locks, and the
|
||||
revision is compare-and-swap on `baseRevisionId`. The receipt is therefore the
|
||||
durable outcome record: present means the write applied, absent means it did
|
||||
not. Recovery runs the same receipt-guarded mutation, whichever controller
|
||||
admitted the callback. It returns the saved result when the receipt exists and
|
||||
applies the write once when it does not. A stale base, a reused key or invalid
|
||||
input is the call's real outcome and settles as a tool error. Any other failure
|
||||
leaves the call unsettled. A late original callback then replays the receipt,
|
||||
so the document is never written twice.
|
||||
|
||||
A different case is a runner crash after the controller saved the result but
|
||||
before its delivery command completed. Codex/OpenCode explicitly opt in to
|
||||
reconciling that exact `semantic_tool.result` command through their durable tool
|
||||
|
||||
@@ -9,6 +9,21 @@
|
||||
],
|
||||
"$defs": {
|
||||
"protocolVersion": { "const": 2 },
|
||||
"turnDispatchJournalFile": {
|
||||
"description": "File name of the sidecar's prompt-dispatch journal in the session runtime directory. It holds turnDispatchJournalRecord lines for the latest turn only.",
|
||||
"const": "paperclip-turn-dispatch.jsonl"
|
||||
},
|
||||
"turnDispatchJournalRecord": {
|
||||
"description": "One journal line. The runtime port truncates the file and writes `received` when it starts the turn, before any provider work. It appends `dispatched` and fsyncs it immediately before the turn's first session/prompt request is written to the provider. The Runner reads the journal only after it proves that the sidecar and provider are gone: a lone `received` line proves the prompt never reached the provider.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"schema": { "const": "paperclip.acpx-turn-dispatch.v1" },
|
||||
"turnId": { "type": "string", "minLength": 1 },
|
||||
"phase": { "enum": ["received", "dispatched"] }
|
||||
},
|
||||
"required": ["schema", "turnId", "phase"],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"command": {
|
||||
"enum": [
|
||||
"initialize",
|
||||
|
||||
@@ -22,12 +22,14 @@ use crate::acpx_provider_session::{
|
||||
PiThinkingLevel,
|
||||
};
|
||||
use crate::acpx_sidecar_transport::AcpxSidecarTransportConfig;
|
||||
use crate::acpx_turn_dispatch::{read_turn_dispatch_journal, TurnDispatchEvidence};
|
||||
#[cfg(test)]
|
||||
use crate::durable::QualifiedLaunchArtifact;
|
||||
use crate::durable::{
|
||||
create_private_temporary_file, open_private_regular_file, verify_private_directory,
|
||||
AcpxLaunchProfile, Command, CommandExecution, CommandExecutor, DurableRunnerConfig,
|
||||
DurableRunnerError, EventPriority, PolledEvent, PROVIDER_STATE_INCOMPATIBLE,
|
||||
DurableRunnerError, EventPriority, PolledEvent, PROVIDER_SESSION_CLOSED,
|
||||
PROVIDER_STATE_INCOMPATIBLE,
|
||||
};
|
||||
use crate::generated_acpx_sidecar_contract::GeneratedAcpxSidecarCommand;
|
||||
use crate::process_supervisor::{VerifiedProcessArgument, VerifiedProcessLaunch};
|
||||
@@ -1299,6 +1301,66 @@ impl AcpxCommandExecutor {
|
||||
self.save_state()
|
||||
}
|
||||
|
||||
/// A turn start that failed without a definite answer (a lost or late
|
||||
/// reply, an exited or frozen sidecar) leaves the prompt's fate unknown:
|
||||
/// resending could duplicate it and continuing could lose it. Once the
|
||||
/// sidecar and provider are proven gone, the sidecar's dispatch journal
|
||||
/// can prove that the prompt never left. Then the session is saved
|
||||
/// reopenable with no active turn, so the run's next `turn.start` sends
|
||||
/// the prompt once. Returns false, changing nothing, without that proof.
|
||||
fn reopen_after_undispatched_turn_start(
|
||||
&mut self,
|
||||
turn_id: &str,
|
||||
) -> Result<bool, DurableRunnerError> {
|
||||
let session_identity = self
|
||||
.session
|
||||
.as_ref()
|
||||
.map(|session| session.identity().clone());
|
||||
let Some(state) = self.state.as_ref() else {
|
||||
return Ok(false);
|
||||
};
|
||||
let Some(identity) = state.identity.clone() else {
|
||||
return Ok(false);
|
||||
};
|
||||
if session_identity.as_ref() != Some(&identity)
|
||||
|| state.lifecycle != "turn_starting"
|
||||
|| state.active_turn_id.as_deref() != Some(turn_id)
|
||||
|| state.provider_exit_unconfirmed
|
||||
|| !state.pending_runtime_requests.is_empty()
|
||||
|| state.semantic_result.is_some()
|
||||
|| !state
|
||||
.pending_events
|
||||
.iter()
|
||||
.all(|event| event.event_type == "session.resumed")
|
||||
|| !(state.goal_projection.is_null() || goal_is_dormant(&state.goal_projection))
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
// The saved state still says `turn_starting` until a proof settles it,
|
||||
// so a Runner killed during this wait restores through the same check.
|
||||
self.session = None;
|
||||
let Ok(_provider_lifetime_fence) =
|
||||
await_provider_lifetime_fence(identity.provider_lifetime_fence_candidates)
|
||||
else {
|
||||
return Ok(false);
|
||||
};
|
||||
let runtime_directory = state.descriptor.runtime_directory.clone();
|
||||
if read_turn_dispatch_journal(&runtime_directory, turn_id)
|
||||
!= TurnDispatchEvidence::NotDispatched
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let state = self
|
||||
.state
|
||||
.as_mut()
|
||||
.expect("ACPX state remains available after an undispatched turn start");
|
||||
state.lifecycle = "prepared".to_owned();
|
||||
state.active_turn_id = None;
|
||||
self.context.provider_turn_id = None;
|
||||
self.save_state()?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Restores the conversation of a turn that was active when the runner
|
||||
/// died, without inventing its outcome. The original provider lifetime
|
||||
/// must have lost its fence quorum first, so no second provider can act on
|
||||
@@ -1326,11 +1388,29 @@ impl AcpxCommandExecutor {
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
match await_provider_lifetime_fence(identity.provider_lifetime_fence_candidates) {
|
||||
// Release the quorum so the restored provider can inherit it.
|
||||
Ok(listeners) => drop(listeners),
|
||||
Err(_) => return Ok(false),
|
||||
}
|
||||
// A Runner killed while the start was in flight saved `turn_starting`.
|
||||
// When the sidecar's journal proves the prompt never left, no
|
||||
// provider turn exists: restore the session idle so the run's next
|
||||
// turn.start sends the prompt once, instead of a continuation that
|
||||
// would lose it.
|
||||
let start_turn_id = (state.lifecycle == "turn_starting")
|
||||
.then(|| previous_turn.clone())
|
||||
.flatten();
|
||||
let runtime_directory = state.descriptor.runtime_directory.clone();
|
||||
let undispatched =
|
||||
match await_provider_lifetime_fence(identity.provider_lifetime_fence_candidates) {
|
||||
// Read the journal while the quorum proves the sidecar is gone,
|
||||
// then release it so the restored provider can inherit it.
|
||||
Ok(listeners) => {
|
||||
let undispatched = start_turn_id.is_some_and(|turn_id| {
|
||||
read_turn_dispatch_journal(&runtime_directory, &turn_id)
|
||||
== TurnDispatchEvidence::NotDispatched
|
||||
});
|
||||
drop(listeners);
|
||||
undispatched
|
||||
}
|
||||
Err(_) => return Ok(false),
|
||||
};
|
||||
let Ok(session) = self.start_session(true) else {
|
||||
return Ok(false);
|
||||
};
|
||||
@@ -1353,6 +1433,12 @@ impl AcpxCommandExecutor {
|
||||
priority: EventPriority::P0,
|
||||
payload: session_event_payload(&state.descriptor, &identity, process_id, turn_controls),
|
||||
})?;
|
||||
if undispatched {
|
||||
self.recovery_pending_effects = None;
|
||||
self.session = Some(session);
|
||||
self.save_state()?;
|
||||
return Ok(true);
|
||||
}
|
||||
state.push(NormalizedProviderEvent {
|
||||
event_type: "turn.failed".to_owned(),
|
||||
priority: EventPriority::P0,
|
||||
@@ -1976,7 +2062,8 @@ impl AcpxCommandExecutor {
|
||||
DurableRunnerError::invalid(format!("ACPX turn start failed closed: {error}"))
|
||||
}
|
||||
None => DurableRunnerError::invalid("ACPX session is not open"),
|
||||
});
|
||||
}
|
||||
.with_classification(PROVIDER_SESSION_CLOSED));
|
||||
}
|
||||
let reopenable = self.session.is_none()
|
||||
&& self.state.as_ref().is_some_and(|state| {
|
||||
@@ -2043,7 +2130,17 @@ impl AcpxCommandExecutor {
|
||||
self.retain_buffered_provider_events()?;
|
||||
}
|
||||
if self.session.is_none() {
|
||||
return Err(DurableRunnerError::invalid("ACPX session is not open"));
|
||||
let error = DurableRunnerError::invalid("ACPX session is not open");
|
||||
// Only a session this run closed is permanently closed for it. A
|
||||
// session awaiting provider-exit proof can reopen after a restart.
|
||||
let closed_for_run = self.state.as_ref().is_some_and(|state| {
|
||||
state.lifecycle == "closed" && state.descriptor.run_id == self.context.run_id
|
||||
});
|
||||
return Err(if closed_for_run {
|
||||
error.with_classification(PROVIDER_SESSION_CLOSED)
|
||||
} else {
|
||||
error
|
||||
});
|
||||
}
|
||||
let (provider_process_will_be_replaced, previous_process_id) = self
|
||||
.session
|
||||
@@ -2103,6 +2200,13 @@ impl AcpxCommandExecutor {
|
||||
})
|
||||
})
|
||||
.cloned();
|
||||
if rejected_checkpoint.is_none()
|
||||
&& self.reopen_after_undispatched_turn_start(&provider_turn_id)?
|
||||
{
|
||||
return Err(DurableRunnerError::invalid(format!(
|
||||
"ACPX turn start failed before its prompt reached the provider: {error}"
|
||||
)));
|
||||
}
|
||||
let state = self
|
||||
.state
|
||||
.as_mut()
|
||||
@@ -2114,6 +2218,7 @@ impl AcpxCommandExecutor {
|
||||
}
|
||||
.to_owned();
|
||||
state.provider_exit_unconfirmed = rejected_checkpoint.is_some();
|
||||
let rejected_checkpoint_reopenable = rejected_checkpoint.is_some();
|
||||
state.active_turn_id = None;
|
||||
self.context.provider_turn_id = None;
|
||||
self.session = None;
|
||||
@@ -2133,9 +2238,15 @@ impl AcpxCommandExecutor {
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
return Err(DurableRunnerError::invalid(format!(
|
||||
"ACPX turn start failed closed: {error}"
|
||||
)));
|
||||
let failure =
|
||||
DurableRunnerError::invalid(format!("ACPX turn start failed closed: {error}"));
|
||||
// A rejected checkpoint stays `prepared` and reopens on the next
|
||||
// start. A `closed` session cannot reopen for this run.
|
||||
return Err(if rejected_checkpoint_reopenable {
|
||||
failure
|
||||
} else {
|
||||
failure.with_classification(PROVIDER_SESSION_CLOSED)
|
||||
});
|
||||
}
|
||||
// Copy numeric timing fields only. Sidecar contents never enter the receipt.
|
||||
let timing = if measure {
|
||||
|
||||
@@ -21,6 +21,46 @@ pub const ACPX_SIDECAR_MAX_FRAME_BYTES: usize = 1024 * 1024;
|
||||
const MAX_BUFFERED_EVENTS: usize = 512;
|
||||
const MAX_EVENT_POLL_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
const MAX_JSON_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
|
||||
/// A response wait blocks in slices of at most this long.
|
||||
const RESPONSE_WAIT_SLICE: Duration = Duration::from_secs(1);
|
||||
/// A slice that returns this much later than it asked was not waiting: this
|
||||
/// process was stopped (SIGSTOP, a frozen container, a whole-process stall).
|
||||
const STOPPED_TIME_THRESHOLD: Duration = Duration::from_secs(2);
|
||||
/// After a stop, the thawed sidecar keeps at least this long to answer.
|
||||
const POST_STOP_GRACE: Duration = Duration::from_secs(5);
|
||||
/// One request never credits more stopped time than this in total.
|
||||
const MAX_STOPPED_CREDIT: Duration = Duration::from_secs(15 * 60);
|
||||
|
||||
/// Moves `deadline` later after a wait slice that this process spent stopped.
|
||||
///
|
||||
/// The sidecar is a child of this process and is normally stopped with it, so
|
||||
/// it could not answer either. Without this, a thaw found the deadline already
|
||||
/// past and failed the request before either process ran (chaos t05: a 61 s
|
||||
/// freeze failed a turn start against its 30 s bound). The slice overshoot is
|
||||
/// credited, and the deadline is at least `POST_STOP_GRACE` after the thaw, so
|
||||
/// a stop in the last slice still leaves the sidecar time to answer. Total
|
||||
/// credit is capped, so a process that never runs normally still times out.
|
||||
/// `credited` carries the request's total credit between slices.
|
||||
pub(crate) fn credit_stopped_time(
|
||||
deadline: Instant,
|
||||
slice: Duration,
|
||||
slice_ended: Instant,
|
||||
elapsed: Duration,
|
||||
credited: &mut Duration,
|
||||
) -> Instant {
|
||||
let Some(stopped) = elapsed.checked_sub(slice) else {
|
||||
return deadline;
|
||||
};
|
||||
if stopped <= STOPPED_TIME_THRESHOLD || *credited >= MAX_STOPPED_CREDIT {
|
||||
return deadline;
|
||||
}
|
||||
let extended = (deadline + stopped).max(slice_ended + POST_STOP_GRACE);
|
||||
let credit = extended
|
||||
.saturating_duration_since(deadline)
|
||||
.min(MAX_STOPPED_CREDIT - *credited);
|
||||
*credited += credit;
|
||||
deadline + credit
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AcpxSidecarTransportConfig {
|
||||
@@ -710,13 +750,26 @@ impl AcpxSidecarTransport {
|
||||
request_id: u64,
|
||||
deadline: Instant,
|
||||
) -> Result<Option<CommandOutcome>, LocalRunnerError> {
|
||||
let mut deadline = deadline;
|
||||
let mut credited = Duration::ZERO;
|
||||
loop {
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
let slice_started = Instant::now();
|
||||
let remaining = deadline.saturating_duration_since(slice_started);
|
||||
if remaining.is_zero() {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(line) = self.receive_stdout_line(remaining, command.as_str())? else {
|
||||
return Ok(None);
|
||||
let slice = remaining.min(RESPONSE_WAIT_SLICE);
|
||||
let received = self.receive_stdout_line(slice, command.as_str())?;
|
||||
let slice_ended = Instant::now();
|
||||
deadline = credit_stopped_time(
|
||||
deadline,
|
||||
slice,
|
||||
slice_ended,
|
||||
slice_ended.saturating_duration_since(slice_started),
|
||||
&mut credited,
|
||||
);
|
||||
let Some(line) = received else {
|
||||
continue;
|
||||
};
|
||||
match parse_frame(&line)? {
|
||||
ParsedFrame::Event(event) => self.buffer_event(event)?,
|
||||
@@ -1287,6 +1340,61 @@ fn response_error_classification(error: &ResponseError) -> &'static str {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn credits_a_stop_and_leaves_the_sidecar_time_to_answer() {
|
||||
let start = Instant::now();
|
||||
let deadline = start + Duration::from_secs(30);
|
||||
let slice = Duration::from_secs(1);
|
||||
let mut credited = Duration::ZERO;
|
||||
// A slice that returned on time, or a little late on a loaded host.
|
||||
for elapsed in [Duration::from_millis(400), Duration::from_millis(2_900)] {
|
||||
assert_eq!(
|
||||
credit_stopped_time(deadline, slice, start + elapsed, elapsed, &mut credited),
|
||||
deadline
|
||||
);
|
||||
}
|
||||
assert_eq!(credited, Duration::ZERO);
|
||||
// A 61 s freeze inside a 1 s slice early in the wait: 60 s are credited.
|
||||
let ended = start + Duration::from_secs(61);
|
||||
assert_eq!(
|
||||
credit_stopped_time(
|
||||
deadline,
|
||||
slice,
|
||||
ended,
|
||||
Duration::from_secs(61),
|
||||
&mut credited
|
||||
),
|
||||
deadline + Duration::from_secs(60)
|
||||
);
|
||||
// A freeze in the last 0.5 s slice still leaves the grace after thaw.
|
||||
let mut credited = Duration::ZERO;
|
||||
let last = start + Duration::from_millis(29_500);
|
||||
let half = Duration::from_millis(500);
|
||||
let ended = last + Duration::from_secs(60);
|
||||
assert_eq!(
|
||||
credit_stopped_time(
|
||||
deadline,
|
||||
half,
|
||||
ended,
|
||||
Duration::from_secs(60),
|
||||
&mut credited
|
||||
),
|
||||
ended + POST_STOP_GRACE
|
||||
);
|
||||
// Total credit is capped.
|
||||
let mut credited = MAX_STOPPED_CREDIT;
|
||||
assert_eq!(
|
||||
credit_stopped_time(
|
||||
deadline,
|
||||
slice,
|
||||
ended,
|
||||
Duration::from_secs(61),
|
||||
&mut credited
|
||||
),
|
||||
deadline
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(unix)]
|
||||
fn a_timed_out_turn_start_never_establishes_a_resumable_rejection() {
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
//! Reads the ACPX sidecar's prompt-dispatch journal.
|
||||
//!
|
||||
//! The sidecar's runtime port writes `received` for a turn before any provider
|
||||
//! work and appends a synced `dispatched` immediately before the turn's first
|
||||
//! `session/prompt` request reaches the provider (see the TypeScript
|
||||
//! `turn-dispatch-journal.ts` and `turnDispatchJournalRecord` in the sidecar
|
||||
//! schema). Callers read it only after they prove that the sidecar and the
|
||||
//! provider are gone, so neither can still write or send.
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
|
||||
use serde::Deserialize;
|
||||
|
||||
use crate::durable::open_private_regular_file;
|
||||
use crate::generated_acpx_sidecar_contract::{
|
||||
GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE, GENERATED_ACPX_TURN_DISPATCH_SCHEMA,
|
||||
};
|
||||
|
||||
// Two records of one bounded turn ID fit easily; anything larger is not ours.
|
||||
const MAX_JOURNAL_BYTES: u64 = 4 * 1024;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum TurnDispatchEvidence {
|
||||
/// The sidecar started this turn and never wrote its prompt to the provider.
|
||||
NotDispatched,
|
||||
/// The prompt may have reached the provider.
|
||||
Dispatched,
|
||||
/// No usable record for this turn: an older sidecar, another turn, or a
|
||||
/// damaged file. Recovery must not assume either outcome.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct Record {
|
||||
schema: String,
|
||||
#[serde(rename = "turnId")]
|
||||
turn_id: String,
|
||||
phase: String,
|
||||
}
|
||||
|
||||
pub(crate) fn read_turn_dispatch_journal(
|
||||
runtime_directory: &Path,
|
||||
turn_id: &str,
|
||||
) -> TurnDispatchEvidence {
|
||||
let path = runtime_directory.join(GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE);
|
||||
let Ok(file) = open_private_regular_file(&path) else {
|
||||
return TurnDispatchEvidence::Unknown;
|
||||
};
|
||||
let mut bytes = Vec::new();
|
||||
if file
|
||||
.take(MAX_JOURNAL_BYTES + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.is_err()
|
||||
|| bytes.len() as u64 > MAX_JOURNAL_BYTES
|
||||
{
|
||||
return TurnDispatchEvidence::Unknown;
|
||||
}
|
||||
classify(&bytes, turn_id)
|
||||
}
|
||||
|
||||
fn classify(bytes: &[u8], turn_id: &str) -> TurnDispatchEvidence {
|
||||
// Every record ends with a newline; a torn tail proves nothing.
|
||||
let Some(body) = bytes.strip_suffix(b"\n") else {
|
||||
return TurnDispatchEvidence::Unknown;
|
||||
};
|
||||
let mut phases = Vec::new();
|
||||
for line in body.split(|byte| *byte == b'\n') {
|
||||
let Ok(record) = serde_json::from_slice::<Record>(line) else {
|
||||
return TurnDispatchEvidence::Unknown;
|
||||
};
|
||||
if record.schema != GENERATED_ACPX_TURN_DISPATCH_SCHEMA || record.turn_id != turn_id {
|
||||
return TurnDispatchEvidence::Unknown;
|
||||
}
|
||||
phases.push(record.phase);
|
||||
}
|
||||
match phases.as_slice() {
|
||||
[received] if received == "received" => TurnDispatchEvidence::NotDispatched,
|
||||
[received, rest @ ..]
|
||||
if received == "received"
|
||||
&& !rest.is_empty()
|
||||
&& rest.iter().all(|phase| phase == "dispatched") =>
|
||||
{
|
||||
TurnDispatchEvidence::Dispatched
|
||||
}
|
||||
_ => TurnDispatchEvidence::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn line(turn: &str, phase: &str) -> String {
|
||||
format!(
|
||||
"{{\"schema\":\"{GENERATED_ACPX_TURN_DISPATCH_SCHEMA}\",\"turnId\":\"{turn}\",\"phase\":\"{phase}\"}}\n"
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_lone_received_record_of_this_turn_proves_the_prompt_never_left() {
|
||||
let received = line("turn-1", "received");
|
||||
let dispatched = format!("{received}{}", line("turn-1", "dispatched"));
|
||||
assert_eq!(
|
||||
classify(received.as_bytes(), "turn-1"),
|
||||
TurnDispatchEvidence::NotDispatched
|
||||
);
|
||||
assert_eq!(
|
||||
classify(dispatched.as_bytes(), "turn-1"),
|
||||
TurnDispatchEvidence::Dispatched
|
||||
);
|
||||
for unknown in [
|
||||
String::new(),
|
||||
received.trim_end().to_owned(),
|
||||
line("turn-0", "received"),
|
||||
line("turn-1", "dispatched"),
|
||||
format!("{received}{}", line("turn-0", "dispatched")),
|
||||
format!("{received}{{\"schema\":"),
|
||||
format!("{received}{received}"),
|
||||
received.replace(
|
||||
"paperclip.acpx-turn-dispatch.v1",
|
||||
"paperclip.acpx-turn-dispatch.v0",
|
||||
),
|
||||
received.replace("}\n", ",\"extra\":true}\n"),
|
||||
] {
|
||||
assert_eq!(
|
||||
classify(unknown.as_bytes(), "turn-1"),
|
||||
TurnDispatchEvidence::Unknown,
|
||||
"{unknown:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
use std::io::{self, BufRead, Write};
|
||||
use std::time::Duration;
|
||||
|
||||
use paperclip_runner_core::generated_acpx_sidecar_contract::GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION;
|
||||
use paperclip_runner_core::generated_acpx_sidecar_contract::{
|
||||
GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION, GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE,
|
||||
GENERATED_ACPX_TURN_DISPATCH_SCHEMA,
|
||||
};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
const PROJECTED_INPUT_PROVIDER_ID: &str = "input / réquest";
|
||||
@@ -69,6 +72,7 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut source_run = String::new();
|
||||
let mut source_pending_completion: Option<String> = None;
|
||||
let mut source_goal_revision = 0_u64;
|
||||
let mut runtime_directory: Option<std::path::PathBuf> = None;
|
||||
// `--cancel-reply lost|late`: the provider stops its prompt, but the reply
|
||||
// to turn.cancel is dropped, or written only before the next request.
|
||||
let cancel_reply = args
|
||||
@@ -252,6 +256,47 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
|
||||
response = json!({"protocolVersion":GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION,"id":id,"ok":false,
|
||||
"error":{"code":"temporarily_unavailable","message":"Optional read is temporarily unavailable.","retryable":true}});
|
||||
}
|
||||
if command == "session.open" {
|
||||
runtime_directory = request["params"]["runtimeDirectory"]
|
||||
.as_str()
|
||||
.map(std::path::PathBuf::from);
|
||||
}
|
||||
// Like the real runtime port: journal the turn, then its prompt
|
||||
// dispatch, before the provider can see the prompt.
|
||||
// `hang-before-dispatch` / `hang-after-dispatch` freeze the start
|
||||
// on either side of that boundary without replying.
|
||||
if command == "turn.start" {
|
||||
if let Some(directory) = runtime_directory.as_ref() {
|
||||
let turn = request["params"]["turnId"].as_str().unwrap();
|
||||
let path = directory.join(GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE);
|
||||
let record = |phase: &str| {
|
||||
format!(
|
||||
"{}\n",
|
||||
json!({"schema":GENERATED_ACPX_TURN_DISPATCH_SCHEMA,"turnId":turn,"phase":phase})
|
||||
)
|
||||
};
|
||||
let mut options = std::fs::OpenOptions::new();
|
||||
options.write(true).create(true).truncate(true);
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
|
||||
options
|
||||
.open(&path)?
|
||||
.write_all(record("received").as_bytes())?;
|
||||
if fault == "hang-before-dispatch" {
|
||||
loop {
|
||||
std::thread::sleep(std::time::Duration::from_secs(60));
|
||||
}
|
||||
}
|
||||
let mut journal = std::fs::OpenOptions::new().append(true).open(&path)?;
|
||||
journal.write_all(record("dispatched").as_bytes())?;
|
||||
// The runtime port fsyncs here; the fixture skips it to stay fast.
|
||||
if fault == "hang-after-dispatch" {
|
||||
loop {
|
||||
std::thread::sleep(std::time::Duration::from_secs(60));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if command == "session.open" && fault == "slow-open" {
|
||||
std::thread::sleep(std::time::Duration::from_secs(10));
|
||||
}
|
||||
|
||||
@@ -51,6 +51,12 @@ pub const PROVIDER_ATTACH_REFUSED: &str = "provider_attach_refused";
|
||||
/// recorded result. Replacing the session could repeat or lose that action.
|
||||
pub const PROVIDER_SIDE_EFFECT_PENDING: &str = "provider_side_effect_pending";
|
||||
|
||||
/// The runner closed this run's provider session after a turn start whose
|
||||
/// prompt may have reached the provider. No later `turn.start` of the same run
|
||||
/// can reopen it; only a new run's attachment can. Resending could duplicate
|
||||
/// the prompt, so the controller stops same-run retries and offers Retry.
|
||||
pub const PROVIDER_SESSION_CLOSED: &str = "provider_session_closed";
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct DurableRunnerError(String, Option<serde_json::Value>, Option<&'static str>);
|
||||
|
||||
|
||||
@@ -1752,13 +1752,18 @@ fn wait_for_terminal_result_ack(
|
||||
"terminal command result acknowledgement payload is required",
|
||||
)
|
||||
})?;
|
||||
// The controller acknowledges the status it received. An
|
||||
// indeterminate journal entry travels as `failed`, so either
|
||||
// spelling names this exact receipt.
|
||||
let status = payload.get("status").and_then(Value::as_str);
|
||||
if payload.get("commandId").and_then(Value::as_str)
|
||||
!= Some(result.command_id.as_str())
|
||||
|| payload.get("commandType").and_then(Value::as_str)
|
||||
!= Some(result.command_type.as_str())
|
||||
|| payload.get("controllerSeq").and_then(Value::as_u64)
|
||||
!= Some(result.controller_seq)
|
||||
|| payload.get("status").and_then(Value::as_str) != Some(result.status.as_str())
|
||||
|| (status != Some(result.status.as_str())
|
||||
&& status != Some(wire_command_status(result)))
|
||||
{
|
||||
return Err(DurableRunnerError::invalid(
|
||||
"terminal command result acknowledgement changed its durable identity",
|
||||
@@ -2551,18 +2556,24 @@ fn send_outbox(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// "indeterminate" is an internal crash-recovery journal state. On the wire it
|
||||
/// is a failed command with the preserved execution_indeterminate reason so the
|
||||
/// controller can settle the command and continue replay.
|
||||
fn wire_command_status(result: &StoredCommandResult) -> &str {
|
||||
if result.status == "indeterminate" {
|
||||
"failed"
|
||||
} else {
|
||||
result.status.as_str()
|
||||
}
|
||||
}
|
||||
|
||||
fn command_result_envelope(
|
||||
state: &DurableState,
|
||||
result: &StoredCommandResult,
|
||||
protocol_version: u64,
|
||||
) -> Value {
|
||||
let mut payload = json!(result);
|
||||
// "indeterminate" is an internal crash-recovery journal state. On the
|
||||
// wire it is a failed command with the preserved execution_indeterminate
|
||||
// reason so the controller can settle the command and continue replay.
|
||||
if result.status == "indeterminate" {
|
||||
payload["status"] = json!("failed");
|
||||
}
|
||||
payload["status"] = json!(wire_command_status(result));
|
||||
json!({
|
||||
"protocol": PROTOCOL,
|
||||
"version": protocol_version,
|
||||
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
/// A runnerd killed inside `runner.suspend` leaves it journaled but unfinished.
|
||||
/// The next process replays it as `indeterminate`, sends it as `failed`, and the
|
||||
/// controller acknowledges the `failed` it received. That acknowledgement names
|
||||
/// the same receipt: the runner finishes the suspension instead of exiting with
|
||||
/// "terminal command result acknowledgement changed its durable identity".
|
||||
#[test]
|
||||
fn indeterminate_suspend_replay_accepts_the_acknowledged_wire_status() {
|
||||
for acknowledged in ["failed", "indeterminate"] {
|
||||
indeterminate_suspend_replay_is_acknowledged(acknowledged);
|
||||
}
|
||||
}
|
||||
|
||||
fn indeterminate_suspend_replay_is_acknowledged(acknowledged_status: &'static str) {
|
||||
struct NeverExecutes;
|
||||
|
||||
impl super::super::CommandExecutor for NeverExecutes {
|
||||
fn execute(
|
||||
&mut self,
|
||||
command: &Command,
|
||||
) -> Result<super::super::CommandExecution, DurableRunnerError> {
|
||||
panic!("an indeterminate {} must never execute again", command.command_type);
|
||||
}
|
||||
}
|
||||
|
||||
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let port = listener.local_addr().unwrap().port();
|
||||
let mut config = config(port);
|
||||
config.max_runtime = Duration::from_secs(5);
|
||||
let directory = std::env::temp_dir().join(format!(
|
||||
"paperclip-runner-indeterminate-terminal-ack-{}-{acknowledged_status}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&directory);
|
||||
config.state_dir = directory.clone();
|
||||
let suspend = json!({
|
||||
"schema": "paperclip.prp.command.v1",
|
||||
"commandId": "command_suspend",
|
||||
"controllerSeq": 1,
|
||||
"type": "runner.suspend",
|
||||
"issuedAt": "2026-11-11T01:34:11.000Z",
|
||||
"payload": {},
|
||||
});
|
||||
{
|
||||
// The prior process journaled the suspend before its effect and died.
|
||||
let store = super::super::DurableStateStore::new(&directory).unwrap();
|
||||
let (mut state, _) = store.load_or_create(&config).unwrap();
|
||||
let command: Command = serde_json::from_value(suspend.clone()).unwrap();
|
||||
assert_eq!(
|
||||
state.begin_command(&command).unwrap(),
|
||||
super::super::CommandDisposition::Execute
|
||||
);
|
||||
store.save(&state).unwrap();
|
||||
}
|
||||
|
||||
let state = test_state(&config);
|
||||
let expires = current_unix_ms().unwrap() + 60_000;
|
||||
let server_config = config.clone();
|
||||
let server_state = state.clone();
|
||||
let server = thread::spawn(move || {
|
||||
let (stream, _) = listener.accept().unwrap();
|
||||
let mut socket = accept(stream).unwrap();
|
||||
let mut secure = server_authenticate(
|
||||
&mut socket,
|
||||
&server_config,
|
||||
&server_state,
|
||||
ServerCredential {
|
||||
token: "bootstrap-secret",
|
||||
kind: "bootstrap",
|
||||
lease_id: None,
|
||||
expires_at_unix_ms: expires,
|
||||
revocation_epoch: 0,
|
||||
},
|
||||
);
|
||||
send_secure(
|
||||
&mut socket,
|
||||
&mut secure,
|
||||
&server_config,
|
||||
&welcome(
|
||||
&server_state,
|
||||
"connection_1",
|
||||
Some("lease-secret"),
|
||||
expires,
|
||||
0,
|
||||
vec![suspend],
|
||||
),
|
||||
);
|
||||
let result = receive_secure(&mut socket, &mut secure, &server_config);
|
||||
assert_eq!(result["kind"], "command_result");
|
||||
assert_eq!(result["payload"]["commandId"], "command_suspend");
|
||||
assert_eq!(result["payload"]["status"], "failed");
|
||||
assert_eq!(
|
||||
result["payload"]["result"]["code"],
|
||||
"execution_indeterminate"
|
||||
);
|
||||
send_secure(
|
||||
&mut socket,
|
||||
&mut secure,
|
||||
&server_config,
|
||||
&control(
|
||||
&server_state,
|
||||
"connection_1",
|
||||
"command_result_ack",
|
||||
json!({
|
||||
"commandId": "command_suspend",
|
||||
"commandType": "runner.suspend",
|
||||
"controllerSeq": 1,
|
||||
"status": acknowledged_status,
|
||||
}),
|
||||
),
|
||||
);
|
||||
// Acknowledge any terminal suffix until the runner closes.
|
||||
while let Ok(frame) = receive_plain(&mut socket, server_config.max_frame_bytes) {
|
||||
let message = secure.decrypt(&frame, true).unwrap();
|
||||
if message["kind"] == "event" {
|
||||
send_secure(
|
||||
&mut socket,
|
||||
&mut secure,
|
||||
&server_config,
|
||||
&control(
|
||||
&server_state,
|
||||
"connection_1",
|
||||
"ack",
|
||||
json!({"ackedSourceSeq": message["payload"]["sourceSeq"]}),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
super::super::run_durable_runner(
|
||||
config.clone(),
|
||||
BootstrapTicket::new("bootstrap-secret".to_owned()).unwrap(),
|
||||
NeverExecutes,
|
||||
)
|
||||
.unwrap();
|
||||
server.join().unwrap();
|
||||
let store = super::super::DurableStateStore::new(&directory).unwrap();
|
||||
let (state, _) = store.load_or_create(&config).unwrap();
|
||||
assert_eq!(state.lifecycle, "suspended");
|
||||
assert!(state.pending_terminal_delivery.is_none());
|
||||
std::fs::remove_dir_all(directory).unwrap();
|
||||
}
|
||||
@@ -1764,6 +1764,7 @@ mod tests {
|
||||
#[cfg(unix)]
|
||||
include!("tests/hosted_retention.rs");
|
||||
include!("tests/ack_release_poll.rs");
|
||||
include!("tests/indeterminate_terminal_ack.rs");
|
||||
|
||||
use std::net::{IpAddr, Ipv4Addr, TcpListener};
|
||||
use std::path::PathBuf;
|
||||
|
||||
+2
@@ -1,6 +1,8 @@
|
||||
// Generated by scripts/generate-acpx-sidecar-contract.mjs. Do not edit.
|
||||
|
||||
pub const GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION: u64 = 2;
|
||||
pub const GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE: &str = "paperclip-turn-dispatch.jsonl";
|
||||
pub const GENERATED_ACPX_TURN_DISPATCH_SCHEMA: &str = "paperclip.acpx-turn-dispatch.v1";
|
||||
|
||||
pub const GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE: &[(&str, &[&str])] = &[
|
||||
("edit", &["edit", "write", "patch"]),
|
||||
|
||||
@@ -9,6 +9,7 @@ pub mod acpx_provider_checkpoint;
|
||||
pub mod acpx_provider_session;
|
||||
pub mod acpx_provider_state;
|
||||
pub mod acpx_sidecar_transport;
|
||||
mod acpx_turn_dispatch;
|
||||
pub mod aws_agentcore_provider;
|
||||
pub mod claude_managed_provider;
|
||||
pub mod codex_provider;
|
||||
|
||||
@@ -17,6 +17,9 @@ use sha2::{Digest, Sha256};
|
||||
#[path = "support/acpx_turn_end_restart.rs"]
|
||||
mod turn_end_restart;
|
||||
|
||||
#[path = "support/acpx_cut_turn_start.rs"]
|
||||
mod cut_turn_start;
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
//! Runs alone in its own test binary: it stops this whole test process.
|
||||
#![cfg(unix)]
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use paperclip_runner_core::acpx_sidecar_transport::{
|
||||
AcpxSidecarTransport, AcpxSidecarTransportConfig,
|
||||
};
|
||||
use paperclip_runner_core::generated_acpx_sidecar_contract::{
|
||||
GeneratedAcpxSidecarCommand, GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION,
|
||||
};
|
||||
use serde_json::json;
|
||||
|
||||
/// Chaos w-20261111T011704-s9107/t05: the Runner and its ACPX sidecar were
|
||||
/// stopped together (SIGSTOP, a host-sleep stand-in) past the sidecar request
|
||||
/// bound. On thaw the bound had already passed, so the Runner failed the turn
|
||||
/// start before the sidecar could answer. Here the sidecar stops this process
|
||||
/// for 6 s against a 3 s bound and answers 0.5 s after the thaw: once early in
|
||||
/// the wait, and once in its last half second. Both cases share one test so
|
||||
/// no other test thread runs while this process is stopped.
|
||||
#[test]
|
||||
fn a_request_answered_after_this_process_was_stopped_past_its_bound_succeeds() {
|
||||
for stop_after in ["0", "2.5"] {
|
||||
answered_after_stop(stop_after);
|
||||
}
|
||||
}
|
||||
|
||||
fn answered_after_stop(stop_after: &str) {
|
||||
let response = json!({
|
||||
"protocolVersion": GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION,
|
||||
"id": 1, "ok": true, "result": { "answered": true },
|
||||
});
|
||||
let runner = std::process::id();
|
||||
let script = format!(
|
||||
"IFS= read -r request; sleep {stop_after}; \
|
||||
(sleep 6; kill -CONT {runner}; sleep 0.5; printf '%s\\n' '{response}') & \
|
||||
kill -STOP {runner}; wait; IFS= read -r next"
|
||||
);
|
||||
let mut transport = AcpxSidecarTransport::start(&AcpxSidecarTransportConfig {
|
||||
command: PathBuf::from("/bin/sh"),
|
||||
args: vec!["-c".to_owned(), script],
|
||||
verified_launch: None,
|
||||
request_timeout: Duration::from_secs(3),
|
||||
shutdown_grace: Duration::from_millis(100),
|
||||
})
|
||||
.expect("sidecar should start");
|
||||
let started = Instant::now();
|
||||
let result = transport
|
||||
.request(GeneratedAcpxSidecarCommand::Initialize, json!({}))
|
||||
.expect("stopped time must not count against the request bound");
|
||||
assert_eq!(result["answered"], true);
|
||||
assert!(started.elapsed() >= Duration::from_secs(6));
|
||||
transport.shutdown().expect("sidecar should stop");
|
||||
}
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
//! A `turn.start` cut off between the Runner's request and the sidecar's
|
||||
//! reply (a frozen or killed sidecar, a timeout). The sidecar's dispatch
|
||||
//! journal decides whether the prompt could have reached the provider.
|
||||
|
||||
use super::*;
|
||||
use paperclip_runner_core::durable::PROVIDER_SESSION_CLOSED;
|
||||
|
||||
const JOURNAL: &str = "paperclip-turn-dispatch.jsonl";
|
||||
|
||||
fn journal_phases(harness: &Harness) -> Vec<String> {
|
||||
fs::read_to_string(harness.fixture.0.join(JOURNAL))
|
||||
.unwrap_or_default()
|
||||
.lines()
|
||||
.map(|line| {
|
||||
serde_json::from_str::<Value>(line).unwrap()["phase"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn kill(pid: &Value) {
|
||||
std::process::Command::new("kill")
|
||||
.args(["-9", &pid.to_string()])
|
||||
.status()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Starts `turn` against a sidecar that freezes at `fault`, then kills the
|
||||
/// sidecar once the journal shows `phases`, and returns the start's error and
|
||||
/// its closed classification.
|
||||
fn cut_turn_start(
|
||||
harness: &mut Harness,
|
||||
turn: &str,
|
||||
fault: &str,
|
||||
phases: &[&str],
|
||||
) -> (String, Option<&'static str>) {
|
||||
harness.fixture.fault(fault);
|
||||
let sidecar = harness.fixture.process_starts().last().unwrap()["processStart"].clone();
|
||||
let root = harness.fixture.0.clone();
|
||||
let expected = phases
|
||||
.iter()
|
||||
.map(|phase| phase.to_string())
|
||||
.collect::<Vec<_>>();
|
||||
let killer = std::thread::spawn(move || {
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
let seen = fs::read_to_string(root.join(JOURNAL))
|
||||
.unwrap_or_default()
|
||||
.lines()
|
||||
.map(|line| {
|
||||
serde_json::from_str::<Value>(line).unwrap()["phase"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
if seen == expected {
|
||||
break;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"the sidecar never reached {expected:?}"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
kill(&sidecar);
|
||||
});
|
||||
harness.sequence += 1;
|
||||
let error = harness
|
||||
.executor
|
||||
.execute(&command(
|
||||
harness.sequence,
|
||||
"turn.start",
|
||||
json!({"turnId": turn, "text": "Write the brief."}),
|
||||
))
|
||||
.unwrap_err();
|
||||
killer.join().unwrap();
|
||||
harness.fixture.fault("");
|
||||
(error.to_string(), error.classification())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_start_cut_off_before_the_prompt_left_reopens_and_sends_the_prompt_once() {
|
||||
let mut harness = Harness::new();
|
||||
let (error, classification) =
|
||||
cut_turn_start(&mut harness, "cut", "hang-before-dispatch", &["received"]);
|
||||
assert!(
|
||||
error.contains("before its prompt reached the provider"),
|
||||
"{error}"
|
||||
);
|
||||
// The run recovers by itself: the controller must keep retrying it.
|
||||
assert_eq!(classification, None);
|
||||
let saved = harness.fixture.state();
|
||||
assert_eq!(saved["lifecycle"], "prepared", "{saved}");
|
||||
assert_eq!(saved["activeTurnId"], Value::Null);
|
||||
assert_eq!(saved["providerExitUnconfirmed"], false);
|
||||
// The run's next start reopens the conversation and delivers its prompt.
|
||||
let before = harness.fixture.journal().len();
|
||||
let events = harness.complete_turn("resent");
|
||||
assert!(
|
||||
events.iter().all(|event| event["type"] != "turn.failed"),
|
||||
"{events:?}"
|
||||
);
|
||||
let starts = harness.fixture.journal()[before..]
|
||||
.iter()
|
||||
.filter(|line| line["command"] == "turn.start")
|
||||
.map(|line| line["params"]["turnId"].clone())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(starts, [json!("resent")]);
|
||||
assert_eq!(journal_phases(&harness), ["received", "dispatched"]);
|
||||
harness.executor.shutdown().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_start_cut_off_after_the_prompt_left_stays_closed_and_never_resends() {
|
||||
let mut harness = Harness::new();
|
||||
let (error, classification) = cut_turn_start(
|
||||
&mut harness,
|
||||
"cut",
|
||||
"hang-after-dispatch",
|
||||
&["received", "dispatched"],
|
||||
);
|
||||
assert!(error.contains("failed closed"), "{error}");
|
||||
// No later start of this run can reopen it: the controller offers Retry at once.
|
||||
assert_eq!(classification, Some(PROVIDER_SESSION_CLOSED));
|
||||
assert_eq!(harness.fixture.state()["lifecycle"], "closed");
|
||||
let starts = harness.fixture.process_starts().len();
|
||||
harness.sequence += 1;
|
||||
let refused = harness
|
||||
.executor
|
||||
.execute(&command(
|
||||
harness.sequence,
|
||||
"turn.start",
|
||||
json!({"turnId": "resent", "text": "Write the brief."}),
|
||||
))
|
||||
.unwrap_err();
|
||||
assert_eq!(refused.to_string(), "ACPX session is not open");
|
||||
assert_eq!(refused.classification(), Some(PROVIDER_SESSION_CLOSED));
|
||||
assert_eq!(harness.fixture.process_starts().len(), starts);
|
||||
}
|
||||
|
||||
/// The Runner itself dies while the session is saved `turn_starting`.
|
||||
fn restore_cut_runner(harness: &mut Harness, phases: &[&str]) -> Vec<Value> {
|
||||
let mut saved = harness.fixture.state();
|
||||
harness.executor.shutdown().unwrap();
|
||||
saved["lifecycle"] = json!("turn_starting");
|
||||
saved["activeTurnId"] = json!("cut");
|
||||
fs::write(
|
||||
harness.fixture.0.join("acpx-provider-state.json"),
|
||||
serde_json::to_vec_pretty(&saved).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let journal = phases
|
||||
.iter()
|
||||
.map(|phase| {
|
||||
format!(
|
||||
"{}\n",
|
||||
json!({"schema":"paperclip.acpx-turn-dispatch.v1","turnId":"cut","phase":phase})
|
||||
)
|
||||
})
|
||||
.collect::<String>();
|
||||
let path = harness.fixture.0.join(JOURNAL);
|
||||
let _ = fs::remove_file(&path);
|
||||
if !phases.is_empty() {
|
||||
fs::write(&path, journal).unwrap();
|
||||
fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
}
|
||||
harness.executor =
|
||||
NativeProviderCommandExecutor::with_runner_config(&harness.fixture.0, &harness.config);
|
||||
harness.sequence += 1;
|
||||
let snapshot = harness
|
||||
.executor
|
||||
.execute(&command(harness.sequence, "session.snapshot", json!({})))
|
||||
.unwrap();
|
||||
let mut events = snapshot
|
||||
.events
|
||||
.iter()
|
||||
.map(|(kind, _, payload)| json!({"type":kind,"payload":payload}))
|
||||
.collect::<Vec<_>>();
|
||||
events.extend(harness.drain());
|
||||
events
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_runner_killed_before_the_prompt_left_restores_an_idle_session() {
|
||||
let mut harness = Harness::new();
|
||||
let events = restore_cut_runner(&mut harness, &["received"]);
|
||||
let kinds = events
|
||||
.iter()
|
||||
.map(|event| event["type"].clone())
|
||||
.collect::<Vec<_>>();
|
||||
assert!(kinds.contains(&json!("session.resumed")), "{events:?}");
|
||||
assert!(!kinds.contains(&json!("turn.failed")), "{events:?}");
|
||||
let saved = harness.fixture.state();
|
||||
assert_eq!(saved["lifecycle"], "session_open");
|
||||
assert_eq!(saved["activeTurnId"], Value::Null);
|
||||
harness.complete_turn("resent");
|
||||
harness.executor.shutdown().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_runner_killed_after_the_prompt_left_or_without_a_journal_reports_the_lost_turn() {
|
||||
for phases in [&["received", "dispatched"][..], &[][..]] {
|
||||
let mut harness = Harness::new();
|
||||
let events = restore_cut_runner(&mut harness, phases);
|
||||
let lost = events
|
||||
.iter()
|
||||
.find(|event| event["type"] == "turn.failed")
|
||||
.unwrap_or_else(|| panic!("{phases:?}: {events:?}"));
|
||||
assert_eq!(lost["payload"]["code"], "provider_turn_lost_on_restore");
|
||||
harness.executor.shutdown().unwrap();
|
||||
}
|
||||
}
|
||||
+7
-3
@@ -437,9 +437,13 @@ fn a_runner_restart_in_the_same_run_keeps_the_failed_turn_end_restart_closed() {
|
||||
"turn.start",
|
||||
json!({"turnId": "second", "text": "Complete the work."}),
|
||||
))
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert_eq!(failed, "ACPX session is not open");
|
||||
.unwrap_err();
|
||||
assert_eq!(failed.to_string(), "ACPX session is not open");
|
||||
// No same-run start can reopen it: the controller offers Retry at once.
|
||||
assert_eq!(
|
||||
failed.classification(),
|
||||
Some(paperclip_runner_core::durable::PROVIDER_SESSION_CLOSED)
|
||||
);
|
||||
assert_eq!(harness.fixture.process_starts().len(), starts);
|
||||
// Neither session.open nor a same-run attach reopens it.
|
||||
let reopened = harness
|
||||
|
||||
@@ -33,6 +33,21 @@ const toolOperationPrecedence = [
|
||||
["list", ["list", "glob"]],
|
||||
];
|
||||
const protocolVersion = readAcpxSidecarProtocolVersion(schema);
|
||||
// The prompt-dispatch journal is a file contract between the sidecar (writer)
|
||||
// and the Runner (reader after the sidecar is proven gone).
|
||||
const turnDispatchJournalFile = schema.$defs.turnDispatchJournalFile?.const;
|
||||
const turnDispatchRecord = schema.$defs.turnDispatchJournalRecord;
|
||||
const turnDispatchSchema = turnDispatchRecord?.properties?.schema?.const;
|
||||
const turnDispatchPhases = turnDispatchRecord?.properties?.phase?.enum;
|
||||
if (
|
||||
typeof turnDispatchJournalFile !== "string" ||
|
||||
!/^[a-z0-9.-]+$/.test(turnDispatchJournalFile) ||
|
||||
typeof turnDispatchSchema !== "string" ||
|
||||
JSON.stringify(turnDispatchPhases) !== JSON.stringify(["received", "dispatched"]) ||
|
||||
turnDispatchRecord?.additionalProperties !== false
|
||||
) {
|
||||
throw new Error("ACPX turn dispatch journal contract must declare its file, schema and closed phases");
|
||||
}
|
||||
const quote = (value) => JSON.stringify(value);
|
||||
const rustVariant = (value) =>
|
||||
value
|
||||
@@ -40,8 +55,8 @@ const rustVariant = (value) =>
|
||||
.map((part) => part[0].toUpperCase() + part.slice(1))
|
||||
.join("");
|
||||
|
||||
const typescript = `// Generated by scripts/generate-acpx-sidecar-contract.mjs. Do not edit.\n\nexport const GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION = ${protocolVersion} as const;\nexport const GENERATED_ACPX_SIDECAR_COMMANDS = [\n${commands.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\nexport type GeneratedAcpxSidecarCommand =\n (typeof GENERATED_ACPX_SIDECAR_COMMANDS)[number];\n\nexport const GENERATED_ACPX_SIDECAR_EVENT_TYPES = [\n${events.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\nexport type GeneratedAcpxSidecarEventType =\n (typeof GENERATED_ACPX_SIDECAR_EVENT_TYPES)[number];\n\nexport const GENERATED_ACPX_SIDECAR_OPEN_PARAMS = [\n${openParams.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\n\nexport const GENERATED_ACPX_SIDECAR_PROVIDER_POLICY_FIELDS = [\n${providerPolicyFields.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\n\nexport type GeneratedAcpxToolOperation =\n | "read"\n | "search"\n | "list"\n | "edit"\n | "execute"\n | "unknown";\n\nexport const GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE = [\n${toolOperationPrecedence.map(([operation, tokens]) => ` { operation: ${quote(operation)}, tokens: [${tokens.map(quote).join(", ")}] },`).join("\n")}\n] as const;\n\nexport function classifyGeneratedAcpxToolOperation(\n toolKind: unknown,\n toolTitle: unknown,\n): GeneratedAcpxToolOperation {\n const candidate =\n typeof toolKind === "string" && toolKind\n ? toolKind\n : typeof toolTitle === "string"\n ? toolTitle\n : "";\n const normalized = candidate.slice(0, 240).toLowerCase();\n for (const { operation, tokens } of GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE) {\n if (tokens.some((token) => normalized.includes(token))) return operation;\n }\n return normalized ? "execute" : "unknown";\n}\n`;
|
||||
const rust = `// Generated by scripts/generate-acpx-sidecar-contract.mjs. Do not edit.\n\npub const GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION: u64 = ${protocolVersion};\n\npub const GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE: &[(&str, &[&str])] = &[\n${toolOperationPrecedence.map(([operation, tokens]) => ` (${quote(operation)}, &[${tokens.map(quote).join(", ")}]),`).join("\n")}\n];\n\npub fn classify_generated_acpx_tool_operation(kind: &str, title: &str) -> &'static str {\n let kind = kind.to_ascii_lowercase();\n let title = title.to_ascii_lowercase();\n let candidate = if kind.is_empty() { &title } else { &kind };\n for (operation, tokens) in GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE {\n if tokens.iter().any(|token| candidate.contains(token)) {\n return operation;\n }\n }\n if candidate.is_empty() {\n "unknown"\n } else {\n "execute"\n }\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum GeneratedAcpxSidecarCommand {\n${commands.map((value) => ` ${rustVariant(value)},`).join("\n")}\n}\n\nimpl GeneratedAcpxSidecarCommand {\n pub const fn as_str(self) -> &'static str {\n match self {\n${commands.map((value) => ` Self::${rustVariant(value)} => ${quote(value)},`).join("\n")}\n }\n }\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)]\npub enum GeneratedAcpxSidecarEventType {\n${events.map((value) => ` #[serde(rename = ${quote(value)})]\n ${rustVariant(value)},`).join("\n")}\n}\n`;
|
||||
const typescript = `// Generated by scripts/generate-acpx-sidecar-contract.mjs. Do not edit.\n\nexport const GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION = ${protocolVersion} as const;\nexport const GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE = ${quote(turnDispatchJournalFile)};\nexport const GENERATED_ACPX_TURN_DISPATCH_SCHEMA = ${quote(turnDispatchSchema)};\nexport const GENERATED_ACPX_SIDECAR_COMMANDS = [\n${commands.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\nexport type GeneratedAcpxSidecarCommand =\n (typeof GENERATED_ACPX_SIDECAR_COMMANDS)[number];\n\nexport const GENERATED_ACPX_SIDECAR_EVENT_TYPES = [\n${events.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\nexport type GeneratedAcpxSidecarEventType =\n (typeof GENERATED_ACPX_SIDECAR_EVENT_TYPES)[number];\n\nexport const GENERATED_ACPX_SIDECAR_OPEN_PARAMS = [\n${openParams.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\n\nexport const GENERATED_ACPX_SIDECAR_PROVIDER_POLICY_FIELDS = [\n${providerPolicyFields.map((value) => ` ${quote(value)},`).join("\n")}\n] as const;\n\nexport type GeneratedAcpxToolOperation =\n | "read"\n | "search"\n | "list"\n | "edit"\n | "execute"\n | "unknown";\n\nexport const GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE = [\n${toolOperationPrecedence.map(([operation, tokens]) => ` { operation: ${quote(operation)}, tokens: [${tokens.map(quote).join(", ")}] },`).join("\n")}\n] as const;\n\nexport function classifyGeneratedAcpxToolOperation(\n toolKind: unknown,\n toolTitle: unknown,\n): GeneratedAcpxToolOperation {\n const candidate =\n typeof toolKind === "string" && toolKind\n ? toolKind\n : typeof toolTitle === "string"\n ? toolTitle\n : "";\n const normalized = candidate.slice(0, 240).toLowerCase();\n for (const { operation, tokens } of GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE) {\n if (tokens.some((token) => normalized.includes(token))) return operation;\n }\n return normalized ? "execute" : "unknown";\n}\n`;
|
||||
const rust = `// Generated by scripts/generate-acpx-sidecar-contract.mjs. Do not edit.\n\npub const GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION: u64 = ${protocolVersion};\npub const GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE: &str = ${quote(turnDispatchJournalFile)};\npub const GENERATED_ACPX_TURN_DISPATCH_SCHEMA: &str = ${quote(turnDispatchSchema)};\n\npub const GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE: &[(&str, &[&str])] = &[\n${toolOperationPrecedence.map(([operation, tokens]) => ` (${quote(operation)}, &[${tokens.map(quote).join(", ")}]),`).join("\n")}\n];\n\npub fn classify_generated_acpx_tool_operation(kind: &str, title: &str) -> &'static str {\n let kind = kind.to_ascii_lowercase();\n let title = title.to_ascii_lowercase();\n let candidate = if kind.is_empty() { &title } else { &kind };\n for (operation, tokens) in GENERATED_ACPX_TOOL_OPERATION_PRECEDENCE {\n if tokens.iter().any(|token| candidate.contains(token)) {\n return operation;\n }\n }\n if candidate.is_empty() {\n "unknown"\n } else {\n "execute"\n }\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum GeneratedAcpxSidecarCommand {\n${commands.map((value) => ` ${rustVariant(value)},`).join("\n")}\n}\n\nimpl GeneratedAcpxSidecarCommand {\n pub const fn as_str(self) -> &'static str {\n match self {\n${commands.map((value) => ` Self::${rustVariant(value)} => ${quote(value)},`).join("\n")}\n }\n }\n}\n\n#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Deserialize)]\npub enum GeneratedAcpxSidecarEventType {\n${events.map((value) => ` #[serde(rename = ${quote(value)})]\n ${rustVariant(value)},`).join("\n")}\n}\n`;
|
||||
|
||||
// Classification must inspect the same complete provider value in both
|
||||
// languages. Display-field truncation happens only after operation selection.
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
WORKSPACE,
|
||||
} from "../drivers/codex/codex-app-server-driver.test-support.js";
|
||||
import { createNativeSessionBackend } from "../index.js";
|
||||
import { PROVIDER_SIDE_EFFECT_PENDING, PROVIDER_STATE_INCOMPATIBLE } from "../contracts/harness-driver.js";
|
||||
import { createCodexNativeSessionBackend, createRunnerdNativeSessionBackend } from "./codex-native-backend.js";
|
||||
import { createOpenCodeNativeSessionBackend } from "./opencode-native-backend.js";
|
||||
|
||||
@@ -407,6 +408,92 @@ describe("native backend factory", () => {
|
||||
if (recovered.recovered) await recovered.session!.close({ reason: "test complete" });
|
||||
});
|
||||
|
||||
// An abandoned remote workspace epoch is restored into a new sibling root
|
||||
// under `.paperclip-workspaces`, while the follow-up inherits a checkpoint
|
||||
// that names the old root. Resume there is impossible, and retrying cannot
|
||||
// move the saved session: the runner reports provider state incompatible.
|
||||
// The runtime then replaces the session when the checkpoint allows it, and
|
||||
// otherwise ends the run with the permanent named code
|
||||
// native_provider_state_incompatible, never a generic retryable failure.
|
||||
it.each([
|
||||
["Codex", execution()],
|
||||
["ACPX Claude", acpxExecution("claude")],
|
||||
])("declines to recover a %s session saved under a moved remote workspace root", async (_label, input) => {
|
||||
const { transport, factory, backend, snapshot } = movedRootRecovery(input);
|
||||
const recovered = await backend.recoverSession!(snapshot as never, { signal: new AbortController().signal });
|
||||
expect(recovered).toEqual({
|
||||
recovered: false,
|
||||
reason: "persisted session working directory is not the assigned remote workspace",
|
||||
failureClass: PROVIDER_STATE_INCOMPATIBLE,
|
||||
});
|
||||
// No Runner or provider process is started for a session that cannot resume here.
|
||||
expect(factory).not.toHaveBeenCalled();
|
||||
expect(transport.calls).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["an active turn", { activeTurnId: "turn-in-flight" }],
|
||||
["a pending runtime request", { pendingRuntimeRequests: [{ requestId: "request-1" }] }],
|
||||
])("stops a moved-root session that holds %s for reconciliation, never replacing it", async (_label, inFlight) => {
|
||||
const { factory, backend, snapshot } = movedRootRecovery(acpxExecution("claude"));
|
||||
await expect(backend.recoverSession!({ ...snapshot, ...inFlight } as never, { signal: new AbortController().signal }))
|
||||
.resolves.toEqual({
|
||||
recovered: false,
|
||||
reason: "persisted session working directory is not the assigned remote workspace, and a provider turn or runtime request was in flight",
|
||||
failureClass: PROVIDER_SIDE_EFFECT_PENDING,
|
||||
});
|
||||
expect(factory).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("treats a moved-root active turn that already has a terminal record as finished", async () => {
|
||||
const { factory, backend, snapshot } = movedRootRecovery(acpxExecution("claude"));
|
||||
await expect(backend.recoverSession!({ ...snapshot, activeTurnId: "turn-1",
|
||||
terminalTurns: [{ turnId: "turn-1", fingerprint: "{\"status\":\"completed\"}" }] } as never, { signal: new AbortController().signal }))
|
||||
.resolves.toMatchObject({ recovered: false, failureClass: PROVIDER_STATE_INCOMPATIBLE });
|
||||
expect(factory).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("names the agent generically when a remote Claude session opens outside its workspace", async () => {
|
||||
const { factory, backend } = movedRootRecovery(acpxExecution("claude"));
|
||||
const failure = await backend.openSession({
|
||||
identity: { runId: "run", sessionId: "session", companyId: "company", issueId: "issue", agentId: "agent" },
|
||||
workingDirectory: "/home/daytona/paperclip-workspace/.paperclip-workspaces/elsewhere",
|
||||
}).catch((error: unknown) => error);
|
||||
// A Claude run must not be told its working directory is a Codex one.
|
||||
expect((failure as Error).message).toBe("Remote agent working directory does not match the assigned workspace");
|
||||
expect(factory).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a filesystem root", "/", "Agent working directory cannot be a filesystem root"],
|
||||
["an unnormalized path", "/home/daytona/../root", "normalized absolute path"],
|
||||
])("keeps refusing a saved session whose working directory is %s", async (_label, workingDirectory, message) => {
|
||||
const { factory, backend, snapshot } = movedRootRecovery(acpxExecution("claude"));
|
||||
await expect(backend.recoverSession!({ ...snapshot, workingDirectory } as never, { signal: new AbortController().signal }))
|
||||
.rejects.toThrow(message);
|
||||
expect(factory).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
function movedRootRecovery(input: NativeExecutionInputV1) {
|
||||
const parent = "/home/daytona/paperclip-workspace/.paperclip-workspaces";
|
||||
const workspaceId = "a5a34403-04fe-4e7e-97cf-d8f371a802a4";
|
||||
const savedRoot = `${parent}/${workspaceId}-1-80214561-2151-4112-a43a-7d65f3071b56`;
|
||||
const assignedRoot = `${parent}/${workspaceId}-5-ef79592c-6784-438f-8a17-9800dd2fa2fc`;
|
||||
const transport = new FakeCodexTransport();
|
||||
const factory = vi.fn(() => transport);
|
||||
const backend = createNativeSessionBackend(input, {
|
||||
codexTransportFactory: factory, workingDirectoryAuthority: "remote_runner",
|
||||
environment: { PAPERCLIP_WORKSPACE_CWD: assignedRoot },
|
||||
});
|
||||
const snapshot = {
|
||||
schema: "paperclip.native-session.v1", backendKind: "codex_app_server", driverKind: "codex_app_server",
|
||||
sessionId: transport.threadId, providerSessionId: transport.providerSessionId, workingDirectory: savedRoot,
|
||||
identity: { runId: "run", sessionId: "session", companyId: "company", issueId: "issue", agentId: "agent" },
|
||||
activeTurnId: null, terminalTurns: [], pendingRuntimeRequests: [], lastCursor: null,
|
||||
};
|
||||
return { transport, factory, backend, snapshot };
|
||||
}
|
||||
|
||||
describe("runner-prepared launch working directory", () => {
|
||||
// The transport reports the prepared directory; it exists only on the VM.
|
||||
class PreparedLaunchTransport extends FakeCodexTransport {
|
||||
@@ -473,7 +560,7 @@ describe("native backend factory", () => {
|
||||
|
||||
it.each([
|
||||
["thread read", { read: "/projects/other", resume: "/home/agent", reason: "provider read a different working directory" }],
|
||||
["thread resume", { read: "/home/agent", resume: "/projects/other", reason: "Error: Codex thread response changed the assigned working directory" }],
|
||||
["thread resume", { read: "/home/agent", resume: "/projects/other", reason: "Error: Provider thread response changed the assigned working directory" }],
|
||||
])("does not recover when the %s reports another cwd", async (_label, cwds) => {
|
||||
const transport = new PreparedLaunchTransport(cwds.resume);
|
||||
transport.readResponse = { thread: { id: transport.threadId, sessionId: transport.providerSessionId, cwd: cwds.read, turns: [] } };
|
||||
@@ -492,7 +579,7 @@ describe("native backend factory", () => {
|
||||
codexTransportFactory: () => new PreparedLaunchTransport("/home/agent"), workingDirectoryAuthority: "remote_runner", environment: {},
|
||||
});
|
||||
await expect(backend.openSession({ identity, workingDirectory: "/home/agent" }))
|
||||
.rejects.toThrow("Remote Codex working directory requires an assigned workspace");
|
||||
.rejects.toThrow("Remote agent working directory requires an assigned workspace");
|
||||
});
|
||||
|
||||
it("does not allow prepared launch authority without runnerd", () => {
|
||||
|
||||
@@ -114,6 +114,7 @@ import {
|
||||
} from "./acpx-sidecar-lifecycle.js";
|
||||
|
||||
import { AcpxTurnControlLedger, parseAcpxTurnControl } from "../drivers/acpx/turn-controls.js";
|
||||
import { createAcpxTurnDispatchJournal } from "../drivers/acpx/turn-dispatch-journal.js";
|
||||
|
||||
const turnControls = new AcpxTurnControlLedger();
|
||||
const MAX_PENDING_TOOLS = 512;
|
||||
@@ -488,6 +489,8 @@ async function dispatch(
|
||||
onPermissionRequest: (providerRequest, context) =>
|
||||
waitForPermission(currentTurnId, activeAgent, providerRequest, context, toolEvidence),
|
||||
onTerminalSessionFailure: (failure) => { sessionFailure.value = failure; },
|
||||
// Lets a Runner that lost this request prove whether the prompt left.
|
||||
dispatchJournal: createAcpxTurnDispatchJournal(openParams!.runtimeDirectory, currentTurnId),
|
||||
});
|
||||
} catch (error) {
|
||||
turnId = null;
|
||||
|
||||
@@ -498,7 +498,9 @@ export interface PersistedHarnessSession {
|
||||
}
|
||||
|
||||
/** Runner proof that saved provider state cannot be restored by this runner
|
||||
* build. Restoring the same state again fails the same way. */
|
||||
* build, or in the workspace assigned to this run (for example, a remote
|
||||
* workspace root that moved after its epoch was abandoned). Restoring the same
|
||||
* state again fails the same way. */
|
||||
export const PROVIDER_STATE_INCOMPATIBLE = "provider_state_incompatible";
|
||||
/** Runner refused to attach a new run to the saved session (for example, a
|
||||
* protected launch argument or the durable provider profile would change).
|
||||
|
||||
@@ -5377,6 +5377,54 @@ describe("DurablePrpControlPlane", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("acknowledges an indeterminate suspension in the Runner's journal status and keeps its fence", async () => {
|
||||
// A runnerd killed inside runner.suspend journals it as indeterminate. The
|
||||
// next runnerd replays it from the welcome as `failed` with
|
||||
// execution_indeterminate and then exits as suspended. Shipped Runners
|
||||
// compare the acknowledgement with their journal status and exited with
|
||||
// "terminal command result acknowledgement changed its durable identity".
|
||||
const root = mkdtempSync(resolve(tmpdir(), "paperclip-prp-indeterminate-suspend-"));
|
||||
const controlPlane = new DurablePrpControlPlane({
|
||||
stateDirectory: root,
|
||||
identity,
|
||||
expectedRunnerVersion,
|
||||
expectedRunnerDigest,
|
||||
});
|
||||
try {
|
||||
await controlPlane.start();
|
||||
const stale = controlPlane.queueCommand("runner.suspend", {}, "command-suspend-stale");
|
||||
const next = controlPlane.queueCommand("session.snapshot", {}, "command-snapshot-next");
|
||||
const client = await authenticate(controlPlane, controlPlane.issueBootstrapTicket());
|
||||
sendSecure(client!, {
|
||||
protocol: "paperclip.runner", version: 1, kind: "command_result",
|
||||
payload: {
|
||||
commandId: stale.commandId, commandType: stale.type, controllerSeq: stale.controllerSeq,
|
||||
status: "failed",
|
||||
result: {
|
||||
code: "execution_indeterminate",
|
||||
message: "runner recovered after journaling this command; it will not execute twice",
|
||||
},
|
||||
},
|
||||
});
|
||||
await expect(receiveSecure(client!)).resolves.toMatchObject({
|
||||
kind: "command_result_ack",
|
||||
payload: {
|
||||
commandId: "command-suspend-stale",
|
||||
commandType: "runner.suspend",
|
||||
controllerSeq: stale.controllerSeq,
|
||||
status: "indeterminate",
|
||||
},
|
||||
});
|
||||
expect(controlPlane.getCommand(stale.commandId)?.status).toBe("failed");
|
||||
// The Runner is leaving as suspended; nothing may follow on this connection.
|
||||
expect(controlPlane.store.state.commandDeliveryCounts[next.commandId]).toBeUndefined();
|
||||
client?.socket.destroy();
|
||||
} finally {
|
||||
await controlPlane.stop();
|
||||
rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("acknowledges terminal command results after persisting them", async () => {
|
||||
const root = mkdtempSync(resolve(tmpdir(), "paperclip-prp-terminal-ack-"));
|
||||
const controlPlane = new DurablePrpControlPlane({
|
||||
|
||||
@@ -84,6 +84,15 @@ export function isRunnerRecoveryMaintenanceCommand(type: string): boolean {
|
||||
return ["session.snapshot", "session.goal.get", "runner.drain", "runner.suspend", "runner.shutdown", "turn.stop"].includes(type);
|
||||
}
|
||||
|
||||
/** The Runner journaled this command before its effect, then died. It sends
|
||||
* that `indeterminate` entry as `failed` with `execution_indeterminate`, never
|
||||
* executes it again, and still treats a lifecycle command as terminal. */
|
||||
function isIndeterminateCommandResult(command: DurableRecoveryCoreCommand): boolean {
|
||||
if (command.status === "indeterminate") return true;
|
||||
const detail = command.result?.result;
|
||||
return command.status === "failed" && isRecord(detail) && detail.code === "execution_indeterminate";
|
||||
}
|
||||
|
||||
const commandTypes = new Set([
|
||||
"run.prepare",
|
||||
"run.attach",
|
||||
@@ -4102,7 +4111,8 @@ export class DurablePrpControlPlane {
|
||||
* A rejected runner.suspend changes no provider state, and the runner keeps
|
||||
* serving this connection. Lift the terminal-lifecycle fence it installed
|
||||
* so the controller's next command (a fresh suspend) can be delivered.
|
||||
* Completed suspensions and every shutdown keep the fence.
|
||||
* Completed suspensions and every shutdown keep the fence. So does an
|
||||
* indeterminate suspension: the Runner treats it as terminal and exits.
|
||||
*/
|
||||
#releaseServingLifecycle(
|
||||
connection: AuthorityConnection,
|
||||
@@ -4111,6 +4121,7 @@ export class DurablePrpControlPlane {
|
||||
if (
|
||||
command.type === "runner.suspend" &&
|
||||
(command.status === "failed" || command.status === "rejected") &&
|
||||
!isIndeterminateCommandResult(command) &&
|
||||
connection.terminalLifecycleCommandId === command.commandId
|
||||
) {
|
||||
connection.terminalLifecycleCommandId = null;
|
||||
@@ -4159,7 +4170,11 @@ export class DurablePrpControlPlane {
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
controllerSeq: command.controllerSeq,
|
||||
status: command.status,
|
||||
// A Runner journals a command it may have started before dying as
|
||||
// `indeterminate` and sends it as `failed`. Runners compare this
|
||||
// acknowledgement with their journal, so name that journal status;
|
||||
// current Runners accept either spelling.
|
||||
status: isIndeterminateCommandResult(command) ? "indeterminate" : command.status,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
@@ -15,6 +15,13 @@
|
||||
* callback settles as interrupted with an unknown outcome. It is never
|
||||
* executed again. A callback that this process is still running, or that this
|
||||
* process dispatched and saw fail, stays pending.
|
||||
*
|
||||
* Exception: an authority may settle a transactional write itself, for any
|
||||
* admission, when its effect and receipt commit in one locked transaction
|
||||
* (server `TRANSACTIONAL_RECEIPT_OPERATIONS`, today only `write_document`).
|
||||
* Its `recover` then runs the receipt-guarded write, which replays the saved
|
||||
* result or applies it once; the owner-gone guard here is not what makes that
|
||||
* safe.
|
||||
*/
|
||||
|
||||
import type { SemanticInputAdmission } from "./durable-prp-control-plane.js";
|
||||
|
||||
@@ -1005,6 +1005,72 @@ describe("Codex ACPX runtime adapter", () => {
|
||||
} finally { await port.close({ reason: "fixture done" }); }
|
||||
});
|
||||
|
||||
it("journals a turn before provider work and its prompt dispatch before the prompt write", async () => {
|
||||
const runtime = fakeRuntime();
|
||||
let created!: AcpRuntimeOptions;
|
||||
const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(),
|
||||
createRuntime: value => { created = value; return runtime; } });
|
||||
const order: string[] = [];
|
||||
const journal = {
|
||||
markReceived: vi.fn(() => { order.push("received"); return true; }),
|
||||
markDispatched: vi.fn(() => { order.push("dispatched"); }),
|
||||
};
|
||||
const pending = pendingExtensionTurn("journaled-turn");
|
||||
vi.mocked(runtime.startTurn).mockImplementation(() => { order.push("runtime.startTurn"); return pending.turn; });
|
||||
try {
|
||||
const turn = port.startTurn({ requestId: "journaled-turn", text: "fixture", dispatchJournal: journal });
|
||||
expect(order).toEqual(["received", "runtime.startTurn"]);
|
||||
// Other outbound traffic never counts as the prompt.
|
||||
created.onAcpMessage?.("outbound", { id: 7, method: "session/set_config_option", params: {} });
|
||||
created.onAcpMessage?.("outbound", { method: "session/cancel", params: {} });
|
||||
expect(journal.markDispatched).not.toHaveBeenCalled();
|
||||
created.onAcpMessage?.("outbound", { id: 8, method: "session/prompt", params: { sessionId: "backend-1" } });
|
||||
// Only the first prompt of the turn is journaled.
|
||||
created.onAcpMessage?.("outbound", { id: 9, method: "session/prompt", params: { sessionId: "backend-1" } });
|
||||
expect(order).toEqual(["received", "runtime.startTurn", "dispatched"]);
|
||||
pending.settle();
|
||||
await turn.result;
|
||||
} finally { await port.close({ reason: "fixture done" }); }
|
||||
});
|
||||
|
||||
it("runs a turn unjournaled when its start cannot be journaled", async () => {
|
||||
const runtime = fakeRuntime();
|
||||
let created!: AcpRuntimeOptions;
|
||||
const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(),
|
||||
createRuntime: value => { created = value; return runtime; } });
|
||||
const pending = pendingExtensionTurn("unjournaled-start");
|
||||
vi.mocked(runtime.startTurn).mockImplementation(() => pending.turn);
|
||||
const markDispatched = vi.fn();
|
||||
try {
|
||||
const turn = port.startTurn({ requestId: "unjournaled-start", text: "fixture",
|
||||
dispatchJournal: { markReceived: () => false, markDispatched } });
|
||||
created.onAcpMessage?.("outbound", { id: 1, method: "session/prompt", params: {} });
|
||||
expect(markDispatched).not.toHaveBeenCalled();
|
||||
pending.settle();
|
||||
await turn.result;
|
||||
} finally { await port.close({ reason: "fixture done" }); }
|
||||
});
|
||||
|
||||
it("aborts the prompt write when its dispatch cannot be journaled", async () => {
|
||||
const runtime = fakeRuntime();
|
||||
let created!: AcpRuntimeOptions;
|
||||
const port = await openCodexAcpxRuntime(openOptions(fakeCommand()), { createRegistry: () => registry(), createStore: () => store(),
|
||||
createRuntime: value => { created = value; return runtime; } });
|
||||
const pending = pendingExtensionTurn("unjournaled-turn");
|
||||
vi.mocked(runtime.startTurn).mockImplementation(() => pending.turn);
|
||||
try {
|
||||
const turn = port.startTurn({ requestId: "unjournaled-turn", text: "fixture", dispatchJournal: {
|
||||
markReceived: () => true,
|
||||
markDispatched: () => { throw new Error("ENOSPC: journal write failed"); },
|
||||
} });
|
||||
// ACPX calls this hook before it writes the bytes; a throw rejects that write.
|
||||
expect(() => created.onAcpMessage?.("outbound", { id: 1, method: "session/prompt", params: {} }))
|
||||
.toThrow("ENOSPC: journal write failed");
|
||||
pending.settle();
|
||||
await turn.result;
|
||||
} finally { await port.close({ reason: "fixture done" }); }
|
||||
});
|
||||
|
||||
it.each(["cancel", "closeStream"] as const)("retains the bound Grok usage response during %s until the prompt settles", async (stop) => {
|
||||
const runtime = fakeRuntime();
|
||||
const durableRecord = { acpxRecordId: "record-1", acpSessionId: "backend-1", agentSessionId: "agent-1", lastRequestId: "previous" };
|
||||
|
||||
@@ -45,6 +45,7 @@ import { ACPX_CAPABILITY_PROFILES } from "./capability-profiles.js";
|
||||
import { createCursorInstructionAdmission } from "./cursor-instructions.js";
|
||||
import { createAntigravityAdmission } from "./antigravity-admission.js";
|
||||
import { createAcpxModeBinding } from "./provider-mode.js";
|
||||
import { isAcpPromptRequest, type AcpxTurnDispatchJournal } from "./turn-dispatch-journal.js";
|
||||
import { assertCopilotPromptPolicy, createCopilotProtocolGuard } from "./copilot-policy.js";
|
||||
|
||||
const VERIFIED_COMMAND_SENTINEL = "paperclip-verified-acpx-command";
|
||||
@@ -122,6 +123,8 @@ interface AcpxRuntimeExtensionBoundary {
|
||||
active: AcpxRuntimeExtensionTurn | null;
|
||||
sessionIds: Set<string>;
|
||||
steering: AcpxRuntimeSteeringCapability | null;
|
||||
/** The started turn whose first session/prompt request is not yet written. */
|
||||
promptDispatch: { turn: AcpxRuntimeExtensionTurn; journal: AcpxTurnDispatchJournal } | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -326,7 +329,7 @@ export async function openQualifiedAcpxRuntime(
|
||||
const extensionNotifications = new Set(extensionProfile.extensionNotifications);
|
||||
const promptUsage = options.profile.agent === "grok" ? createGrokPromptUsageCollector() : undefined;
|
||||
const extensionBoundary: AcpxRuntimeExtensionBoundary = {
|
||||
active: null, sessionIds: new Set(), steering: null,
|
||||
active: null, sessionIds: new Set(), steering: null, promptDispatch: null,
|
||||
};
|
||||
const ownsExtensionTurn = (active: AcpxRuntimeExtensionTurn, params: Record<string, unknown>): boolean =>
|
||||
extensionBoundary.active === active && !active.signal.aborted
|
||||
@@ -508,6 +511,13 @@ export async function openQualifiedAcpxRuntime(
|
||||
onSessionNotification: acceptGoalNotification,
|
||||
onAcpMessage: (direction, message) => {
|
||||
const active = extensionBoundary.active;
|
||||
// ACPX calls this synchronously before it writes an outbound message to
|
||||
// the provider stream, so a thrown journal error aborts the prompt write.
|
||||
const dispatch = extensionBoundary.promptDispatch;
|
||||
if (direction === "outbound" && dispatch && dispatch.turn === active && isAcpPromptRequest(message)) {
|
||||
extensionBoundary.promptDispatch = null;
|
||||
dispatch.journal.markDispatched();
|
||||
}
|
||||
if (active && (direction === "inbound" || !active.signal.aborted)) promptUsage?.observe(direction, message);
|
||||
},
|
||||
spawnEnvironment: () => ({
|
||||
@@ -1552,6 +1562,8 @@ function runtimePort(
|
||||
if (providerProcessLost) throw new AcpxProviderProcessLostError();
|
||||
assertPromptPolicy?.(input.text);
|
||||
if (extensionBoundary.active) throw new Error("ACPX runtime already has an active turn");
|
||||
// Record the turn before any provider work can send its prompt.
|
||||
const dispatchJournal = input.dispatchJournal?.markReceived() ? input.dispatchJournal : null;
|
||||
const approval = new AbortController();
|
||||
const controller = new AbortController();
|
||||
const providerDeath = new AbortController();
|
||||
@@ -1563,6 +1575,7 @@ function runtimePort(
|
||||
onPlanProposal: input.onPlanProposal,
|
||||
};
|
||||
extensionBoundary.active = extensionTurn;
|
||||
extensionBoundary.promptDispatch = dispatchJournal ? { turn: extensionTurn, journal: dispatchJournal } : null;
|
||||
promptUsage?.begin(input.requestId, identity.backendSessionId);
|
||||
// A guardian can outlive the provider while ACP awaits a callback.
|
||||
// Native exit or a typed ACP agent disconnect retires this turn; losing
|
||||
@@ -1585,6 +1598,7 @@ function runtimePort(
|
||||
stopWatchingProviderExit();
|
||||
controller.abort(new Error("ACPX extension turn expired"));
|
||||
if (extensionBoundary.active === extensionTurn) extensionBoundary.active = null;
|
||||
if (extensionBoundary.promptDispatch?.turn === extensionTurn) extensionBoundary.promptDispatch = null;
|
||||
};
|
||||
permissionBoundary.hasAdmittedTurn = true;
|
||||
permissionBoundary.active = approval;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// Generated by scripts/generate-acpx-sidecar-contract.mjs. Do not edit.
|
||||
|
||||
export const GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION = 2 as const;
|
||||
export const GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE = "paperclip-turn-dispatch.jsonl";
|
||||
export const GENERATED_ACPX_TURN_DISPATCH_SCHEMA = "paperclip.acpx-turn-dispatch.v1";
|
||||
export const GENERATED_ACPX_SIDECAR_COMMANDS = [
|
||||
"initialize",
|
||||
"session.open",
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { retainAcpxCredentialRefresh } from "./credential-refresh.js";
|
||||
import type { AcpxTurnDispatchJournal } from "./turn-dispatch-journal.js";
|
||||
import { assertAcpxExecutionAdmission, parseAcpxCandidateStartupAdmission, type AcpxCandidateStartupAdmission } from "./candidate-admission.js";
|
||||
import { resolveGrokDisableWebSearch } from "./grok-web-search.js";
|
||||
import { recordAcpxAdmissionFailure, type ACPX_ADMISSION_CODES } from "./admission-diagnostics.js";
|
||||
@@ -143,6 +144,8 @@ export interface AcpxRuntimeTurnInput {
|
||||
onPlanProposal?: (proposal: AcpxPlanProposal) => void;
|
||||
/** Receives the typed AIR failure behind ACPX's generic terminal error. */
|
||||
onTerminalSessionFailure?: (failure: AcpxTerminalSessionFailure) => void;
|
||||
/** Records the turn start and the prompt dispatch durably (turn-dispatch-journal.ts). */
|
||||
dispatchJournal?: AcpxTurnDispatchJournal;
|
||||
}
|
||||
|
||||
export interface AcpxRuntimeTurn {
|
||||
@@ -933,6 +936,7 @@ export class AcpxRuntimeHost {
|
||||
...(input.onExtensionNotification ? { onExtensionNotification: input.onExtensionNotification } : {}),
|
||||
...(input.onPlanProposal ? { onPlanProposal: input.onPlanProposal } : {}),
|
||||
...(input.onTerminalSessionFailure ? { onTerminalSessionFailure: input.onTerminalSessionFailure } : {}),
|
||||
...(input.dispatchJournal ? { dispatchJournal: input.dispatchJournal } : {}),
|
||||
});
|
||||
this.#activeTurn = turn;
|
||||
const managed = withAcpxTurnCancellation(turn, reason => this.close({ reason }), ACPX_TURN_CANCELLATION_SHUTDOWN_BOUND_MS);
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { lstat, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createAcpRuntime, createAgentRegistry, createRuntimeStore } from "acpx/runtime";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE, GENERATED_ACPX_TURN_DISPATCH_SCHEMA } from "./generated-sidecar-contract.js";
|
||||
import { createAcpxTurnDispatchJournal, isAcpPromptRequest } from "./turn-dispatch-journal.js";
|
||||
|
||||
const directories: string[] = [];
|
||||
async function directory(): Promise<string> {
|
||||
const value = await mkdtemp(join(tmpdir(), "acpx-turn-dispatch-"));
|
||||
directories.push(value);
|
||||
return value;
|
||||
}
|
||||
afterEach(async () => {
|
||||
await Promise.all(directories.splice(0).map(value => rm(value, { recursive: true, force: true })));
|
||||
});
|
||||
|
||||
const lines = async (dir: string) => (await readFile(join(dir, GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE), "utf8"))
|
||||
.split("\n").filter(Boolean).map(line => JSON.parse(line) as Record<string, unknown>);
|
||||
|
||||
describe("ACPX turn dispatch journal", () => {
|
||||
it("keeps one record set per turn: received truncates, dispatched appends", async () => {
|
||||
const dir = await directory();
|
||||
const first = createAcpxTurnDispatchJournal(dir, "turn-1");
|
||||
expect(first.markReceived()).toBe(true);
|
||||
first.markDispatched();
|
||||
expect(await lines(dir)).toEqual([
|
||||
{ schema: GENERATED_ACPX_TURN_DISPATCH_SCHEMA, turnId: "turn-1", phase: "received" },
|
||||
{ schema: GENERATED_ACPX_TURN_DISPATCH_SCHEMA, turnId: "turn-1", phase: "dispatched" },
|
||||
]);
|
||||
createAcpxTurnDispatchJournal(dir, "turn-2").markReceived();
|
||||
expect(await lines(dir)).toEqual([{ schema: GENERATED_ACPX_TURN_DISPATCH_SCHEMA, turnId: "turn-2", phase: "received" }]);
|
||||
});
|
||||
|
||||
it("never records a dispatch without its turn's received record, and never follows a symlink", async () => {
|
||||
const dir = await directory();
|
||||
expect(() => createAcpxTurnDispatchJournal(dir, "turn-1").markDispatched()).toThrow(/ENOENT/);
|
||||
const target = join(dir, "elsewhere");
|
||||
await writeFile(target, "");
|
||||
await symlink(target, join(dir, GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE));
|
||||
// The turn runs unjournaled, and the planted link is removed, not followed.
|
||||
expect(createAcpxTurnDispatchJournal(dir, "turn-1").markReceived()).toBe(false);
|
||||
expect(await readFile(target, "utf8")).toBe("");
|
||||
await expect(lstat(join(dir, GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it("leaves no record when the start record cannot be written", async () => {
|
||||
const missing = join(await directory(), "missing");
|
||||
expect(createAcpxTurnDispatchJournal(missing, "turn-1").markReceived()).toBe(false);
|
||||
});
|
||||
|
||||
it("recognizes only the prompt request", () => {
|
||||
expect(isAcpPromptRequest({ jsonrpc: "2.0", id: 3, method: "session/prompt", params: {} })).toBe(true);
|
||||
expect(isAcpPromptRequest({ jsonrpc: "2.0", method: "session/prompt", params: {} })).toBe(false);
|
||||
expect(isAcpPromptRequest({ jsonrpc: "2.0", id: 3, method: "session/load", params: {} })).toBe(false);
|
||||
expect(isAcpPromptRequest({ jsonrpc: "2.0", id: 3, result: {} })).toBe(false);
|
||||
});
|
||||
|
||||
// The proof depends on ACPX calling onAcpMessage("outbound") before it writes
|
||||
// the prompt to the provider. A real ACPX runtime and a controlled ACP peer
|
||||
// check that order: the peer refuses a prompt it receives before the journal
|
||||
// holds its dispatch record.
|
||||
it("is written before a real ACPX runtime sends the prompt to the provider", async () => {
|
||||
const dir = await directory();
|
||||
const journalPath = join(dir, GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE);
|
||||
const peer = String.raw`
|
||||
const fs = require('node:fs');
|
||||
const send = x => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...x }) + '\n');
|
||||
require('node:readline').createInterface({ input: process.stdin }).on('line', line => {
|
||||
const m = JSON.parse(line);
|
||||
if (m.method === 'initialize') send({ id: m.id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true }, authMethods: [] } });
|
||||
else if (m.method === 'session/new') send({ id: m.id, result: { sessionId: 'journal-session' } });
|
||||
else if (m.method === 'session/prompt') {
|
||||
const journal = fs.existsSync(process.env.JOURNAL) ? fs.readFileSync(process.env.JOURNAL, 'utf8') : '';
|
||||
if (journal.includes('"phase":"dispatched"')) send({ id: m.id, result: { stopReason: 'end_turn' } });
|
||||
else send({ id: m.id, error: { code: -32603, message: 'prompt arrived before its dispatch record' } });
|
||||
}
|
||||
});`;
|
||||
const children: ChildProcess[] = [];
|
||||
const journal = createAcpxTurnDispatchJournal(dir, "turn-ordered");
|
||||
let pending: typeof journal | null = null;
|
||||
const runtime = createAcpRuntime({
|
||||
cwd: dir,
|
||||
agentRegistry: createAgentRegistry({ overrides: { claude: "fixture" } }),
|
||||
sessionStore: createRuntimeStore({ stateDir: join(dir, "state") }),
|
||||
permissionMode: "deny-all",
|
||||
onAcpMessage: (direction, value) => {
|
||||
if (direction === "outbound" && pending && isAcpPromptRequest(value)) {
|
||||
const current = pending;
|
||||
pending = null;
|
||||
current.markDispatched();
|
||||
}
|
||||
},
|
||||
spawnAgent: () => {
|
||||
const child = spawn(process.execPath, ["-e", peer], { cwd: dir, env: { ...process.env, JOURNAL: journalPath }, stdio: ["pipe", "pipe", "pipe"] });
|
||||
children.push(child);
|
||||
return child;
|
||||
},
|
||||
});
|
||||
try {
|
||||
const handle = await runtime.ensureSession({ sessionKey: "journal-ordering", agent: "claude", mode: "persistent", cwd: dir });
|
||||
journal.markReceived();
|
||||
pending = journal;
|
||||
const turn = runtime.startTurn({ handle, text: "fixture", mode: "prompt", requestId: "turn-ordered", timeoutMs: 5_000 });
|
||||
const drain = (async () => { for await (const _event of turn.events) { /* drain */ } })();
|
||||
expect(await turn.result).toMatchObject({ status: "completed" });
|
||||
await drain;
|
||||
expect((await lines(dir)).map(line => line.phase)).toEqual(["received", "dispatched"]);
|
||||
} finally {
|
||||
for (const child of children) if (child.exitCode === null) child.kill("SIGKILL");
|
||||
await runtime.close?.({ handle: undefined as never, reason: "fixture done" }).catch(() => undefined);
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
// A dispatch that cannot be journaled must never reach the provider, or a
|
||||
// lone `received` record would later prove a falsehood and duplicate it.
|
||||
it("keeps the prompt from a real ACPX provider when its dispatch record cannot be written", async () => {
|
||||
const dir = await directory();
|
||||
const seen = join(dir, "prompt-seen");
|
||||
const peer = String.raw`
|
||||
const fs = require('node:fs');
|
||||
const send = x => process.stdout.write(JSON.stringify({ jsonrpc: '2.0', ...x }) + '\n');
|
||||
require('node:readline').createInterface({ input: process.stdin }).on('line', line => {
|
||||
const m = JSON.parse(line);
|
||||
if (m.method === 'initialize') send({ id: m.id, result: { protocolVersion: 1, agentCapabilities: { loadSession: true }, authMethods: [] } });
|
||||
else if (m.method === 'session/new') send({ id: m.id, result: { sessionId: 'journal-session' } });
|
||||
else if (m.method === 'session/prompt') { fs.appendFileSync(process.env.SEEN, 'prompt\n'); send({ id: m.id, result: { stopReason: 'end_turn' } }); }
|
||||
});`;
|
||||
const children: ChildProcess[] = [];
|
||||
let armed = false;
|
||||
const runtime = createAcpRuntime({
|
||||
cwd: dir,
|
||||
agentRegistry: createAgentRegistry({ overrides: { claude: "fixture" } }),
|
||||
sessionStore: createRuntimeStore({ stateDir: join(dir, "state") }),
|
||||
permissionMode: "deny-all",
|
||||
onAcpMessage: (direction, value) => {
|
||||
if (armed && direction === "outbound" && isAcpPromptRequest(value)) throw new Error("ENOSPC: dispatch record not written");
|
||||
},
|
||||
spawnAgent: () => {
|
||||
const child = spawn(process.execPath, ["-e", peer], { cwd: dir, env: { ...process.env, SEEN: seen }, stdio: ["pipe", "pipe", "pipe"] });
|
||||
children.push(child);
|
||||
return child;
|
||||
},
|
||||
});
|
||||
try {
|
||||
const handle = await runtime.ensureSession({ sessionKey: "journal-refused", agent: "claude", mode: "persistent", cwd: dir });
|
||||
armed = true;
|
||||
const turn = runtime.startTurn({ handle, text: "fixture", mode: "prompt", requestId: "turn-refused", timeoutMs: 5_000 });
|
||||
const drain = (async () => { for await (const _event of turn.events) { /* drain */ } })().catch(() => undefined);
|
||||
const result = await turn.result.catch((error: unknown) => ({ status: "rejected", error }));
|
||||
await drain;
|
||||
expect(result.status).not.toBe("completed");
|
||||
// Give a stray write time to arrive before asserting it never did.
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
await expect(readFile(seen, "utf8")).rejects.toMatchObject({ code: "ENOENT" });
|
||||
} finally {
|
||||
for (const child of children) if (child.exitCode === null) child.kill("SIGKILL");
|
||||
await runtime.close?.({ handle: undefined as never, reason: "fixture done" }).catch(() => undefined);
|
||||
}
|
||||
}, 30_000);
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
import { closeSync, constants, fsyncSync, openSync, unlinkSync, writeSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE,
|
||||
GENERATED_ACPX_TURN_DISPATCH_SCHEMA,
|
||||
} from "./generated-sidecar-contract.js";
|
||||
|
||||
/**
|
||||
* Durable proof of whether a turn's prompt reached the provider.
|
||||
*
|
||||
* A turn start can be cut off (a timeout, a frozen or killed sidecar) after
|
||||
* the Runner asked for it and before it heard back. The Runner then cannot
|
||||
* tell whether the provider received the prompt: resending could duplicate it
|
||||
* and a continuation could lose it. The runtime port records two facts in the
|
||||
* session's private runtime directory:
|
||||
*
|
||||
* - `received`: the port started the turn. Written first, before any provider
|
||||
* work, truncating the previous turn's record. Not synced: losing it only
|
||||
* loses the proof.
|
||||
* - `dispatched`: appended and fsynced synchronously immediately before the
|
||||
* turn's first `session/prompt` request is written to the provider. A failed
|
||||
* write aborts the prompt write.
|
||||
*
|
||||
* The Runner reads the file only after it proves that the sidecar and the
|
||||
* provider are gone, so neither can still write. A lone `received` line then
|
||||
* proves that the prompt was never sent.
|
||||
*/
|
||||
export interface AcpxTurnDispatchJournal {
|
||||
/**
|
||||
* Returns false when the record could not be written. The turn then runs
|
||||
* unjournaled: without a `received` record no reader can form a proof.
|
||||
*/
|
||||
markReceived(): boolean;
|
||||
markDispatched(): void;
|
||||
}
|
||||
|
||||
function record(turnId: string, phase: "received" | "dispatched"): string {
|
||||
return `${JSON.stringify({ schema: GENERATED_ACPX_TURN_DISPATCH_SCHEMA, turnId, phase })}\n`;
|
||||
}
|
||||
|
||||
function writeAll(fd: number, line: string): void {
|
||||
const bytes = Buffer.from(line, "utf8");
|
||||
let offset = 0;
|
||||
while (offset < bytes.length) offset += writeSync(fd, bytes, offset, bytes.length - offset);
|
||||
}
|
||||
|
||||
export function createAcpxTurnDispatchJournal(
|
||||
runtimeDirectory: string,
|
||||
turnId: string,
|
||||
): AcpxTurnDispatchJournal {
|
||||
const path = join(runtimeDirectory, GENERATED_ACPX_TURN_DISPATCH_JOURNAL_FILE);
|
||||
return {
|
||||
markReceived() {
|
||||
try {
|
||||
const fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC | constants.O_NOFOLLOW, 0o600);
|
||||
try {
|
||||
writeAll(fd, record(turnId, "received"));
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
// A journal problem must never block the turn, but a `received`
|
||||
// record left behind without its dispatch would prove a falsehood.
|
||||
// Remove whatever was written; if even that fails, fail the start.
|
||||
try {
|
||||
unlinkSync(path);
|
||||
} catch (cleanup) {
|
||||
if ((cleanup as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
},
|
||||
markDispatched() {
|
||||
// O_APPEND without O_CREAT: a missing `received` line must not be
|
||||
// replaced by a lone `dispatched` record that a reader cannot bind.
|
||||
const fd = openSync(path, constants.O_WRONLY | constants.O_APPEND | constants.O_NOFOLLOW);
|
||||
try {
|
||||
writeAll(fd, record(turnId, "dispatched"));
|
||||
fsyncSync(fd);
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** True for the JSON-RPC request that hands a turn's prompt to the provider. */
|
||||
export function isAcpPromptRequest(message: unknown): boolean {
|
||||
return typeof message === "object" && message !== null && "id" in message
|
||||
&& (message as { method?: unknown }).method === "session/prompt";
|
||||
}
|
||||
@@ -20,7 +20,7 @@ import type {
|
||||
PersistedHarnessTurnTerminal,
|
||||
} from "../../contracts/harness-driver.js";
|
||||
import { NativeSessionProtocolIntegrityError, nativeRestartInterruptedTurnId } from "../../contracts/native-session-backend.js";
|
||||
import { HarnessReconciliationError, runnerRecoveryFailureClass } from "../../contracts/harness-driver.js";
|
||||
import { HarnessReconciliationError, PROVIDER_SIDE_EFFECT_PENDING, PROVIDER_STATE_INCOMPATIBLE, runnerRecoveryFailureClass } from "../../contracts/harness-driver.js";
|
||||
import {
|
||||
CODEX_CODEX_PROTOCOL_VERSION,
|
||||
CODEX_SKILLLESS_BASE_INSTRUCTIONS,
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
import {
|
||||
boundedCodexValue,
|
||||
codexThreadWorkingDirectory,
|
||||
remoteRunnerWorkingDirectoryMoved,
|
||||
validateCodexWorkingDirectory as validateWorkingDirectory,
|
||||
} from "./codex-boundaries.js";
|
||||
import {
|
||||
@@ -395,6 +396,40 @@ export class CodexAppServerDriver implements HarnessDriver {
|
||||
reason: "persisted session identity is incomplete",
|
||||
};
|
||||
}
|
||||
// A session saved under an abandoned remote workspace root cannot resume
|
||||
// in the newly assigned root. When it holds no in-flight turn or runtime
|
||||
// request (a follow-up's inherited checkpoint, for example), decline
|
||||
// before any Runner or provider process starts, so the runtime's recovery
|
||||
// policy decides: a replacement in the assigned workspace, or the
|
||||
// permanent named refusal when the checkpoint requires the same session.
|
||||
// Retrying cannot move the saved session, so this is incompatible state,
|
||||
// not a transient failure. A session with an in-flight turn or runtime
|
||||
// request may have an external effect nothing here can prove settled, so
|
||||
// it is never replaced: it stops by name for an operator to reconcile.
|
||||
if (
|
||||
snapshot.workingDirectory &&
|
||||
this.#options.workingDirectoryAuthority === "remote_runner" &&
|
||||
remoteRunnerWorkingDirectoryMoved(snapshot.workingDirectory, this.#options.environment)
|
||||
) {
|
||||
// A crash can save a turn's terminal record before clearing its active
|
||||
// marker; that turn finished and is not in flight.
|
||||
const activeTurnIsTerminal = (snapshot.terminalTurns ?? []).some(
|
||||
(terminal) => terminal.turnId === snapshot.activeTurnId,
|
||||
);
|
||||
const inFlight = (Boolean(snapshot.activeTurnId) && !activeTurnIsTerminal)
|
||||
|| Boolean(snapshot.pendingRuntimeRequests?.length);
|
||||
return inFlight
|
||||
? {
|
||||
recovered: false,
|
||||
reason: "persisted session working directory is not the assigned remote workspace, and a provider turn or runtime request was in flight",
|
||||
failureClass: PROVIDER_SIDE_EFFECT_PENDING,
|
||||
}
|
||||
: {
|
||||
recovered: false,
|
||||
reason: "persisted session working directory is not the assigned remote workspace",
|
||||
failureClass: PROVIDER_STATE_INCOMPATIBLE,
|
||||
};
|
||||
}
|
||||
const transport = this.#transport({
|
||||
workingDirectory: snapshot.workingDirectory
|
||||
? validateWorkingDirectory(snapshot.workingDirectory, this.#options.environment, this.#options.workingDirectoryAuthority)
|
||||
|
||||
+1
-1
@@ -550,7 +550,7 @@ describe("Codex app-server Codex driver", () => {
|
||||
await expect(driver.recoverSession?.(snapshot)).resolves.toEqual({
|
||||
recovered: false,
|
||||
reason: expect.stringContaining(
|
||||
"Codex working directory is outside the assigned workspace",
|
||||
"Agent working directory is outside the assigned workspace",
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -53,7 +53,7 @@ export function validateCodexWorkingDirectory(
|
||||
authority: CodexWorkingDirectoryAuthority = "local_filesystem",
|
||||
): string {
|
||||
if (workingDirectory.trim().length === 0) {
|
||||
throw new Error("Codex working directory is required");
|
||||
throw new Error("Agent working directory is required");
|
||||
}
|
||||
if (authority === "remote_runner") {
|
||||
return validateRemoteRunnerWorkingDirectory(workingDirectory, environment);
|
||||
@@ -66,24 +66,24 @@ export function validateCodexWorkingDirectory(
|
||||
try {
|
||||
resolved = realpathSync.native(requested);
|
||||
if (!statSync(resolved).isDirectory()) {
|
||||
throw new Error("Codex working directory must be a directory");
|
||||
throw new Error("Agent working directory must be a directory");
|
||||
}
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code === "ENOENT") {
|
||||
throw new Error(
|
||||
"Codex working directory must exist before provider admission",
|
||||
"Agent working directory must exist before provider admission",
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (resolved === parse(resolved).root) {
|
||||
throw new Error("Codex working directory cannot be a filesystem root");
|
||||
throw new Error("Agent working directory cannot be a filesystem root");
|
||||
}
|
||||
const configuredRoot = environment.PAPERCLIP_WORKSPACE_CWD;
|
||||
const hostHome = canonicalConfiguredPath(environment.HOME);
|
||||
if (hostHome && pathContains(resolved, hostHome)) {
|
||||
throw new Error("Codex working directory cannot contain the host HOME");
|
||||
throw new Error("Agent working directory cannot contain the host HOME");
|
||||
}
|
||||
if (
|
||||
hostHome &&
|
||||
@@ -92,7 +92,7 @@ export function validateCodexWorkingDirectory(
|
||||
)
|
||||
) {
|
||||
throw new Error(
|
||||
"Codex working directory cannot overlap sensitive host HOME state",
|
||||
"Agent working directory cannot overlap sensitive host HOME state",
|
||||
);
|
||||
}
|
||||
if (
|
||||
@@ -101,7 +101,7 @@ export function validateCodexWorkingDirectory(
|
||||
(configuredRoot === undefined || configuredRoot.trim().length === 0)
|
||||
) {
|
||||
throw new Error(
|
||||
"Codex working directory inside the host HOME requires an assigned workspace",
|
||||
"Agent working directory inside the host HOME requires an assigned workspace",
|
||||
);
|
||||
}
|
||||
const codexHome = canonicalConfiguredPath(environment.CODEX_HOME);
|
||||
@@ -110,7 +110,7 @@ export function validateCodexWorkingDirectory(
|
||||
pathContains(resolved, codexHome) ||
|
||||
pathContains(codexHome, resolved)
|
||||
) {
|
||||
throw new Error("Codex working directory cannot overlap host CODEX_HOME");
|
||||
throw new Error("Agent working directory cannot overlap host CODEX_HOME");
|
||||
}
|
||||
}
|
||||
if (configuredRoot !== undefined && configuredRoot.trim().length > 0) {
|
||||
@@ -122,7 +122,7 @@ export function validateCodexWorkingDirectory(
|
||||
isAbsolute(pathFromRoot)
|
||||
) {
|
||||
throw new Error(
|
||||
"Codex working directory is outside the assigned workspace",
|
||||
"Agent working directory is outside the assigned workspace",
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -154,7 +154,7 @@ export function validatePreparedLaunchWorkingDirectory(
|
||||
);
|
||||
}
|
||||
if (workingDirectory === posix.parse(workingDirectory).root) {
|
||||
throw new Error("Codex working directory cannot be a filesystem root");
|
||||
throw new Error("Agent working directory cannot be a filesystem root");
|
||||
}
|
||||
return workingDirectory;
|
||||
}
|
||||
@@ -170,10 +170,10 @@ export function codexThreadWorkingDirectory(
|
||||
authority: CodexWorkingDirectoryAuthority = "local_filesystem",
|
||||
): string {
|
||||
if (authority !== "runner_prepared_launch") {
|
||||
if (expected === null) throw new Error("Codex working directory is required");
|
||||
if (expected === null) throw new Error("Agent working directory is required");
|
||||
const returned = typeof reported === "string" ? reported : expected;
|
||||
if (resolve(returned) !== expected) {
|
||||
throw new Error("Codex thread response changed the assigned working directory");
|
||||
throw new Error("Provider thread response changed the assigned working directory");
|
||||
}
|
||||
return expected;
|
||||
}
|
||||
@@ -182,27 +182,51 @@ export function codexThreadWorkingDirectory(
|
||||
}
|
||||
const returned = validatePreparedLaunchWorkingDirectory(reported);
|
||||
if (expected !== null && returned !== expected) {
|
||||
throw new Error("Codex thread response changed the assigned working directory");
|
||||
throw new Error("Provider thread response changed the assigned working directory");
|
||||
}
|
||||
return returned;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a saved session names a remote workspace root other than the one
|
||||
* Core assigned to this run. A workspace epoch that was abandoned (for example
|
||||
* after a restart killed its preparation) is restored into a new sibling root,
|
||||
* so a session saved under the old root cannot resume here. That is an
|
||||
* ordinary resume failure, not an invalid admission: both paths are
|
||||
* well-formed and only differ. Malformed paths and a missing assignment are
|
||||
* still refused by validateCodexWorkingDirectory.
|
||||
*/
|
||||
export function remoteRunnerWorkingDirectoryMoved(
|
||||
savedWorkingDirectory: string,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
): boolean {
|
||||
const assigned = environment.PAPERCLIP_WORKSPACE_CWD?.trim();
|
||||
return Boolean(
|
||||
assigned &&
|
||||
isNormalizedRemotePath(assigned) &&
|
||||
assigned !== posix.parse(assigned).root &&
|
||||
isNormalizedRemotePath(savedWorkingDirectory) &&
|
||||
savedWorkingDirectory !== posix.parse(savedWorkingDirectory).root &&
|
||||
savedWorkingDirectory !== assigned,
|
||||
);
|
||||
}
|
||||
|
||||
function validateRemoteRunnerWorkingDirectory(
|
||||
workingDirectory: string,
|
||||
environment: NodeJS.ProcessEnv,
|
||||
): string {
|
||||
if (!isNormalizedRemotePath(workingDirectory)) {
|
||||
throw new Error(
|
||||
"Remote Codex working directory must be a normalized absolute path",
|
||||
"Remote agent working directory must be a normalized absolute path",
|
||||
);
|
||||
}
|
||||
if (workingDirectory === posix.parse(workingDirectory).root) {
|
||||
throw new Error("Codex working directory cannot be a filesystem root");
|
||||
throw new Error("Agent working directory cannot be a filesystem root");
|
||||
}
|
||||
const configuredRoot = environment.PAPERCLIP_WORKSPACE_CWD?.trim();
|
||||
if (!configuredRoot) {
|
||||
throw new Error(
|
||||
"Remote Codex working directory requires an assigned workspace",
|
||||
"Remote agent working directory requires an assigned workspace",
|
||||
);
|
||||
}
|
||||
if (
|
||||
@@ -218,7 +242,7 @@ function validateRemoteRunnerWorkingDirectory(
|
||||
// canonical identity inside the authoritative filesystem before launch.
|
||||
if (workingDirectory !== configuredRoot) {
|
||||
throw new Error(
|
||||
"Remote Codex working directory does not match the assigned workspace",
|
||||
"Remote agent working directory does not match the assigned workspace",
|
||||
);
|
||||
}
|
||||
return workingDirectory;
|
||||
|
||||
@@ -71,7 +71,7 @@ it("reproduces the controller-side remote cwd requirement for plugin-owned launc
|
||||
try {
|
||||
const { backend, prepareLaunch, launches } = await pluginBackend(root, root, "remote_runner");
|
||||
await expect(backend.openSession({ identity: sessionIdentity, workingDirectory: "/controller/workspace" }))
|
||||
.rejects.toThrow("Remote Codex working directory requires an assigned workspace");
|
||||
.rejects.toThrow("Remote agent working directory requires an assigned workspace");
|
||||
expect(prepareLaunch).not.toHaveBeenCalled();
|
||||
expect(launches).toEqual([]);
|
||||
} finally { await rm(root, { recursive: true, force: true }); }
|
||||
|
||||
@@ -294,3 +294,40 @@ it.skipIf(process.platform === "win32")("settles an ACPX read tail through ordin
|
||||
expect(await f.count("processStart")).toBe(3);
|
||||
} finally { await f.cleanup(); }
|
||||
}, 30_000);
|
||||
|
||||
// A turn start cut off in flight (here: the sidecar dies mid-start). The
|
||||
// sidecar's dispatch journal decides what the controller's next turn/start
|
||||
// may do: resend once when the prompt never left, refuse when it may have.
|
||||
it.skipIf(process.platform === "win32").each(["before", "after"] as const)("resends an ACPX turn whose start was cut off %s its prompt left, only when the journal proves it", async stage => {
|
||||
const f = await fixture("claude");
|
||||
try {
|
||||
const source = f.recover({ authorityRunId: f.identity.runId });
|
||||
expect((await source.transport.request("thread/read", {})).thread).toMatchObject(f.thread);
|
||||
await f.settle();
|
||||
await writeFile(f.fault, stage === "before" ? "hang-before-dispatch" : "hang-after-dispatch");
|
||||
const journal = join(f.root, "acpx", "paperclip-turn-dispatch.jsonl");
|
||||
const sidecar = (await f.calls()).filter(entry => entry.processStart).at(-1)!.processStart as number;
|
||||
const cut = source.transport.request("turn/start", { input: [{ type: "text", text: "Write the brief." }] })
|
||||
.then(() => null, (error: unknown) => error);
|
||||
await vi.waitFor(async () => {
|
||||
const phases = (await readFile(journal, "utf8")).trim().split("\n").map(line => JSON.parse(line).phase);
|
||||
expect(phases).toEqual(stage === "before" ? ["received"] : ["received", "dispatched"]);
|
||||
}, { timeout: 10_000 });
|
||||
kill(sidecar);
|
||||
expect(String(await cut)).toContain(stage === "before" ? "before its prompt reached the provider" : "failed closed");
|
||||
await writeFile(f.fault, "");
|
||||
const startsBefore = await f.count("turn.start");
|
||||
if (stage === "before") {
|
||||
await f.complete(source); await f.settle();
|
||||
expect(await f.count("turn.start")).toBe(startsBefore + 1);
|
||||
} else {
|
||||
await expect(source.transport.request("turn/start", { input: [{ type: "text", text: "Write the brief." }] }))
|
||||
.rejects.toThrow("ACPX session is not open");
|
||||
expect(await f.count("turn.start")).toBe(startsBefore);
|
||||
}
|
||||
} catch (error) {
|
||||
const diagnostics = (await readFile(join(f.root, "native.stderr"), "utf8").catch(() => ""))
|
||||
+ (await readFile(join(f.root, "diagnostics", "runnerd.stderr.log"), "utf8").catch(() => ""));
|
||||
throw new Error(`${String(error)}\n${diagnostics}`, { cause: error });
|
||||
} finally { await f.cleanup(); }
|
||||
}, 60_000);
|
||||
@@ -0,0 +1,160 @@
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { createCapabilityRunnerdCodexTransport, runnerdRecoveryInternals } from "./runnerd-codex-transport.js";
|
||||
import { defaultCapabilityRunnerdBinary, fakeCodex, fakeCodexArgs } from "../../test/support/runnerd-transport.js";
|
||||
|
||||
/**
|
||||
* A server freeze while the controller suspends a finished turn can stop the
|
||||
* runner inside `runner.suspend`: the runner journaled the command, its
|
||||
* outcome is not recorded, and the controller still lists it as pending. The
|
||||
* next same-run attempt starts a new runner. That runner settles the old
|
||||
* suspend from the welcome (as `execution_indeterminate`; it never runs it
|
||||
* again), records `suspended` and exits with code 0 before it accepts any of
|
||||
* this attempt's commands. The attempt restarts the runner in place once, and
|
||||
* the resume completes in the same attempt without another provider turn.
|
||||
*
|
||||
* `fenced` is the state a released build can leave: the controller already
|
||||
* recorded the suspend as failed and the runner kept its terminal fence. The
|
||||
* next runner reconciles that fence, keeps a provider cleanup fence and exits.
|
||||
* That runner would refuse new work, so the attempt is not restarted in place:
|
||||
* any exit without the exact proof keeps the earlier failure.
|
||||
*/
|
||||
it.each(["journaled", "fenced"] as const)("restarts in place only a runner that settled the previous attempt's suspend (%s)", async (mode) => {
|
||||
const root = await mkdtemp(join(tmpdir(), "runnerd-carried-suspend-"));
|
||||
const callsPath = join(root, "calls.log");
|
||||
const identity = {
|
||||
runnerInstanceId: "carried-suspend-runner",
|
||||
environmentLeaseId: "carried-suspend-lease",
|
||||
runId: "carried-suspend-run",
|
||||
normalizedSessionId: "carried-suspend-session",
|
||||
turnId: "carried-suspend-turn",
|
||||
itemId: "carried-suspend-item",
|
||||
};
|
||||
const options = {
|
||||
runnerBinary: defaultCapabilityRunnerdBinary(),
|
||||
codexCommand: fakeCodex,
|
||||
codexArgs: fakeCodexArgs(root, "--call-log", callsPath),
|
||||
stateDirectory: root,
|
||||
};
|
||||
const kill = (pid: number | null | undefined) => {
|
||||
if (!pid) return;
|
||||
try { process.kill(pid, "SIGKILL"); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; }
|
||||
};
|
||||
const first = createCapabilityRunnerdCodexTransport({ ...options, prpIdentity: identity });
|
||||
let resumed: ReturnType<typeof createCapabilityRunnerdCodexTransport> | undefined;
|
||||
try {
|
||||
const opened = await first.transport.request("thread/start", { cwd: tmpdir(), dynamicTools: [] });
|
||||
const openedThread = opened.thread as { id: string; sessionId: string };
|
||||
const thread = { id: openedThread.id, sessionId: openedThread.sessionId };
|
||||
await first.transport.close();
|
||||
|
||||
// Rewrite both journals to the moment of the freeze: the runner journaled
|
||||
// the suspend before its effect; the controller never saw its result.
|
||||
const controlPath = join(root, "control-plane", "control-plane-state.json");
|
||||
const control = JSON.parse(await readFile(controlPath, "utf8"));
|
||||
const suspend = control.commands.findLast((command: { type: string }) => command.type === "runner.suspend");
|
||||
expect(suspend).toMatchObject({ status: "completed" });
|
||||
expect(control.commands.at(-1).commandId).toBe(suspend.commandId);
|
||||
const indeterminate = { code: "execution_indeterminate", message: "runner recovered after journaling this command; it will not execute twice" };
|
||||
Object.assign(suspend, mode === "journaled" ? { status: "pending", result: null } : {
|
||||
status: "failed",
|
||||
result: { commandId: suspend.commandId, controllerSeq: suspend.controllerSeq, commandType: "runner.suspend",
|
||||
status: "failed", result: indeterminate },
|
||||
});
|
||||
await writeFile(controlPath, JSON.stringify(control));
|
||||
const runnerPath = join(root, "runner", "runner-state.json");
|
||||
const runner = JSON.parse(await readFile(runnerPath, "utf8"));
|
||||
expect(runner.lastControllerCommandSeq).toBe(suspend.controllerSeq);
|
||||
runner.processedCommands[suspend.commandId] = {
|
||||
...runner.processedCommands[suspend.commandId],
|
||||
...(mode === "journaled"
|
||||
? { status: "pending", result: { code: "execution_indeterminate", message: "command was journaled before its effect" } }
|
||||
: { status: "indeterminate", result: indeterminate }),
|
||||
};
|
||||
runner.lifecycle = mode === "journaled" ? "ready" : "suspended";
|
||||
runner.pendingTerminalDelivery = mode === "journaled" ? null : {
|
||||
commandId: suspend.commandId, controllerSeq: suspend.controllerSeq, commandType: "runner.suspend", lifecycle: "suspended",
|
||||
};
|
||||
await writeFile(runnerPath, JSON.stringify(runner));
|
||||
const callsBefore = (await readFile(callsPath, "utf8")).trim().split(/\r?\n/);
|
||||
|
||||
resumed = createCapabilityRunnerdCodexTransport({
|
||||
...options,
|
||||
prpIdentity: identity,
|
||||
resumeProviderSession: { driverSessionId: thread.id, providerSessionId: thread.sessionId },
|
||||
});
|
||||
if (mode === "fenced") {
|
||||
await expect(resumed.transport.request("thread/read", {})).rejects.toThrow(
|
||||
"runnerd exited unexpectedly with code 0",
|
||||
);
|
||||
expect(resumed.evidence().diagnostics).not.toContain(
|
||||
"runner settled a suspend left by an earlier attempt and exited; restarting it in place",
|
||||
);
|
||||
return;
|
||||
}
|
||||
expect((await resumed.transport.request("thread/read", {})).thread).toMatchObject(thread);
|
||||
expect(resumed.evidence().diagnostics).toContain(
|
||||
"runner settled a suspend left by an earlier attempt and exited; restarting it in place",
|
||||
);
|
||||
const recovered = JSON.parse(await readFile(controlPath, "utf8"));
|
||||
expect(recovered.commands.find((command: { commandId: string }) => command.commandId === suspend.commandId))
|
||||
.toMatchObject({ status: "failed", result: { result: { code: "execution_indeterminate" } } });
|
||||
const calls = (await readFile(callsPath, "utf8")).trim().split(/\r?\n/).slice(callsBefore.length);
|
||||
expect(calls.filter(call => call === "turn/start")).toHaveLength(0);
|
||||
} finally {
|
||||
await Promise.allSettled([first.transport.close(), resumed?.transport.close()]);
|
||||
for (const bundle of [first, resumed]) {
|
||||
const evidence = bundle?.evidence();
|
||||
kill(evidence?.runnerPid);
|
||||
kill(evidence?.providerPid);
|
||||
}
|
||||
await vi.waitFor(() => undefined);
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it("restarts only for the exact settled suspend left by an earlier attempt", () => {
|
||||
const prove = runnerdRecoveryInternals.carriedSuspendSettlementProven;
|
||||
const identity = {
|
||||
runnerInstanceId: "runner", environmentLeaseId: "lease", runId: "run",
|
||||
normalizedSessionId: "session", turnId: "turn", itemId: "item",
|
||||
};
|
||||
const runnerState = (overrides: Record<string, unknown> = {}) => ({
|
||||
schema: "paperclip.runner.durable.state.v1", ...identity, lifecycle: "suspended",
|
||||
pendingTerminalDelivery: null, pendingProviderCleanup: null, lastControllerCommandSeq: 3,
|
||||
processedCommands: { suspend: { commandId: "suspend", controllerSeq: 3, commandType: "runner.suspend", status: "indeterminate" } },
|
||||
...overrides,
|
||||
});
|
||||
const commands = (overrides: Record<string, unknown> = {}, later: Record<string, unknown>[] = []) => [
|
||||
{ commandId: "prepare", controllerSeq: 1, type: "run.prepare", status: "completed" },
|
||||
{ commandId: "turn", controllerSeq: 2, type: "turn.start", status: "completed" },
|
||||
{ commandId: "suspend", controllerSeq: 3, type: "runner.suspend", status: "failed", ...overrides },
|
||||
{ commandId: "probe", controllerSeq: 4, type: "runner.drain", status: "pending" },
|
||||
...later,
|
||||
] as { commandId: string; controllerSeq: number; type: string; status: string }[];
|
||||
const proven = (state = runnerState(), journal = commands(), carriedCommandCount = 3) =>
|
||||
prove({ runnerState: state, identity, commands: journal, carriedCommandCount });
|
||||
|
||||
expect(proven()).toBe(true);
|
||||
// This attempt queued the suspend, as a normal close does.
|
||||
expect(proven(runnerState(), commands(), 2)).toBe(false);
|
||||
// The controller has not settled it yet.
|
||||
expect(proven(runnerState(), commands({ status: "pending" }))).toBe(false);
|
||||
// The last command is not a suspend.
|
||||
expect(proven(runnerState(), commands({ type: "runner.shutdown" }))).toBe(false);
|
||||
// The runner went on to a command of this attempt.
|
||||
expect(proven(runnerState({ lastControllerCommandSeq: 4 }))).toBe(false);
|
||||
expect(proven(runnerState(), commands({}, []).map(command =>
|
||||
command.commandId === "probe" ? { ...command, status: "completed" } : command))).toBe(false);
|
||||
// The runner did not rest cleanly suspended.
|
||||
expect(proven(runnerState({ lifecycle: "ready" }))).toBe(false);
|
||||
expect(proven(runnerState({ pendingTerminalDelivery: { commandId: "suspend" } }))).toBe(false);
|
||||
expect(proven(runnerState({ pendingProviderCleanup: { commandId: "suspend" } }))).toBe(false);
|
||||
// The runner's receipt names another command or another authority.
|
||||
expect(proven(runnerState({ processedCommands: { suspend: { commandId: "suspend", controllerSeq: 3,
|
||||
commandType: "runner.shutdown", status: "completed" } } }))).toBe(false);
|
||||
expect(proven(runnerState({ processedCommands: {} }))).toBe(false);
|
||||
expect(proven(runnerState({ runId: "other-run" }))).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { createCapabilityRunnerdCodexTransport } from "./runnerd-codex-transport.js";
|
||||
import { defaultCapabilityRunnerdBinary, fakeCodex, fakeCodexArgs } from "../../test/support/runnerd-transport.js";
|
||||
|
||||
const signalGroup = (pid: number, signal: NodeJS.Signals) => {
|
||||
try { process.kill(-pid, signal); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; }
|
||||
};
|
||||
|
||||
// Chaos w-20261111T011704-s9107/t05: the control plane and its Runner tree were
|
||||
// stopped (SIGSTOP, a host-sleep stand-in) for 61 s while turn.start waited on its
|
||||
// 30 s deadline. On thaw the wall clock had passed the deadline before either
|
||||
// process could act, and the run reported "PRP command turn.start timed out".
|
||||
// This drives the real transport and Runner: it fails if turn start does not run
|
||||
// on the stopped-time clock, or if its waits do not read that clock.
|
||||
it("starts a turn whose Runner and control plane were stopped past the turn-start deadline", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "runnerd-turn-start-stall-"));
|
||||
const bundle = createCapabilityRunnerdCodexTransport({
|
||||
runnerBinary: defaultCapabilityRunnerdBinary(),
|
||||
codexCommand: fakeCodex,
|
||||
codexArgs: fakeCodexArgs(root),
|
||||
stateDirectory: root,
|
||||
turnStartTimeoutMs: 30_000,
|
||||
prpIdentity: {
|
||||
runnerInstanceId: "stall-runner", environmentLeaseId: "stall-lease", runId: "stall-run",
|
||||
normalizedSessionId: "stall-session", turnId: "stall-turn", itemId: "stall-item",
|
||||
},
|
||||
});
|
||||
const realNow = Date.now.bind(Date);
|
||||
let stoppedMs = 0;
|
||||
let runnerPid: number | null = null;
|
||||
try {
|
||||
await bundle.transport.request("thread/start", { cwd: tmpdir(), dynamicTools: [] });
|
||||
runnerPid = bundle.evidence().runnerPid;
|
||||
expect(runnerPid).toEqual(expect.any(Number));
|
||||
// Stop the Runner tree, then let this process "sleep" 40 s: the wall clock
|
||||
// jumps while no timer of this process runs.
|
||||
signalGroup(runnerPid!, "SIGSTOP");
|
||||
vi.spyOn(Date, "now").mockImplementation(() => realNow() + stoppedMs);
|
||||
const started = bundle.transport.request("turn/start", { input: [{ type: "text", text: "Continue after the freeze." }] });
|
||||
await new Promise(resolve => setTimeout(resolve, 300));
|
||||
stoppedMs = 40_000;
|
||||
await new Promise(resolve => setTimeout(resolve, 300));
|
||||
signalGroup(runnerPid!, "SIGCONT");
|
||||
await expect(started).resolves.toMatchObject({ turn: { status: "inProgress" } });
|
||||
} finally {
|
||||
vi.restoreAllMocks();
|
||||
if (runnerPid !== null) signalGroup(runnerPid, "SIGCONT");
|
||||
await bundle.transport.close().catch(() => undefined);
|
||||
if (runnerPid !== null) signalGroup(runnerPid, "SIGKILL");
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
}, 30_000);
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
runnerLaunchRequirementsDigest,
|
||||
type RunnerProviderLaunchRequirements,
|
||||
} from "./runner-provider-launch.js";
|
||||
import { coldAdmissionTimeoutMs, waitForRunnerCommand } from "./runnerd-codex-transport.js";
|
||||
import { coldAdmissionTimeoutMs, RUNNER_MAX_STOPPED_CREDIT_MS, RUNNER_POST_STOP_GRACE_MS, RunnerStallLedger, waitForRunnerCommand } from "./runnerd-codex-transport.js";
|
||||
import { configuredEnvironmentProjection } from "../configured-environment.js";
|
||||
import { chmod, cp, mkdir, mkdtemp, readFile, readdir, realpath, rename, rm, stat, truncate, writeFile } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
@@ -6703,6 +6703,129 @@ it("shares Pi's absolute cold deadline across recovery barriers and rejects a la
|
||||
} finally { vi.useRealTimers(); }
|
||||
});
|
||||
|
||||
// Chaos w-20261111T011704-s9107/t01: the control plane was stopped (SIGSTOP, as in
|
||||
// a host sleep) 1 s into the resume barrier, together with the Runner it waits on.
|
||||
// On thaw, the wall clock had passed the 30 s deadline before either process could
|
||||
// act, so recovery reported "runner.drain timed out" and spent a recovery attempt.
|
||||
describe("admission waits do not count time this process was stopped", () => {
|
||||
const pending = (clock: RunnerStallLedger | undefined, deadline: number, status: () => string, type = "runner.drain") =>
|
||||
waitForRunnerCommand({
|
||||
type, deadline, clock, abortOnClose: true, isClosed: () => false,
|
||||
throwIfFailed: () => undefined, command: () => ({ status: status() }),
|
||||
runnerHasExited: async () => false, failureCode: () => "runner_local_connect_failed",
|
||||
});
|
||||
|
||||
it("completes a resume barrier that the Runner answers after a 44 s freeze", async () => {
|
||||
vi.useFakeTimers();
|
||||
const clock = new RunnerStallLedger();
|
||||
const stop = clock.watch();
|
||||
try {
|
||||
let status = "pending";
|
||||
const drain = pending(clock, clock.now() + 30_000, () => status);
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
// Stopped for 44 s: the wall clock moves, but no timer of this process runs.
|
||||
vi.setSystemTime(Date.now() + 44_000);
|
||||
await vi.advanceTimersByTimeAsync(2_000);
|
||||
status = "completed";
|
||||
await vi.advanceTimersByTimeAsync(10);
|
||||
await expect(drain).resolves.toBeUndefined();
|
||||
} finally { stop(); vi.useRealTimers(); }
|
||||
});
|
||||
|
||||
it("keeps the wall-clock timeout for a wait outside an admission", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const drain = pending(undefined, Date.now() + 30_000, () => "pending");
|
||||
const rejection = expect(drain).rejects.toThrow("runner_local_connect_failed: PRP command runner.drain timed out");
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
vi.setSystemTime(Date.now() + 44_000);
|
||||
await vi.advanceTimersByTimeAsync(10);
|
||||
await rejection;
|
||||
} finally { vi.useRealTimers(); }
|
||||
});
|
||||
|
||||
it("still times out a barrier that the Runner never answers after a freeze", async () => {
|
||||
vi.useFakeTimers();
|
||||
const clock = new RunnerStallLedger();
|
||||
const stop = clock.watch();
|
||||
try {
|
||||
const drain = pending(clock, clock.now() + 30_000, () => "pending");
|
||||
const rejection = expect(drain).rejects.toThrow("runner_local_connect_failed: PRP command runner.drain timed out");
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
vi.setSystemTime(Date.now() + 44_000);
|
||||
// Running time reaches the deadline: 1 s before, then the rest of the
|
||||
// 30 s budget plus the 5 s post-stop grace.
|
||||
await vi.advanceTimersByTimeAsync(40_000);
|
||||
await rejection;
|
||||
} finally { stop(); vi.useRealTimers(); }
|
||||
});
|
||||
|
||||
it("leaves the Runner time to answer after a freeze in a wait's last half second", async () => {
|
||||
vi.useFakeTimers();
|
||||
const clock = new RunnerStallLedger();
|
||||
const stop = clock.watch();
|
||||
try {
|
||||
let status = "pending";
|
||||
const drain = pending(clock, clock.now() + 30_000, () => status);
|
||||
await vi.advanceTimersByTimeAsync(29_500);
|
||||
vi.setSystemTime(Date.now() + 60_000);
|
||||
await vi.advanceTimersByTimeAsync(2_000);
|
||||
status = "completed";
|
||||
await vi.advanceTimersByTimeAsync(10);
|
||||
await expect(drain).resolves.toBeUndefined();
|
||||
} finally { stop(); vi.useRealTimers(); }
|
||||
});
|
||||
|
||||
it("credits a freeze outside any poll loop to the next barrier on the same deadline", async () => {
|
||||
vi.useFakeTimers();
|
||||
const clock = new RunnerStallLedger();
|
||||
const stop = clock.watch();
|
||||
try {
|
||||
const deadline = clock.now() + coldAdmissionTimeoutMs("acpx", "pi", true);
|
||||
let status = "pending";
|
||||
const prepared = pending(clock, clock.now() + 30_000, () => status, "run.prepare");
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
status = "completed";
|
||||
await vi.advanceTimersByTimeAsync(10);
|
||||
await prepared;
|
||||
// Stopped for 70 s between barriers (a checkpoint flush, a spawn): only the ticker observes it.
|
||||
vi.setSystemTime(Date.now() + 70_000);
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
status = "pending";
|
||||
const opened = pending(clock, deadline, () => status, "session.open");
|
||||
await vi.advanceTimersByTimeAsync(20_000);
|
||||
status = "completed";
|
||||
await vi.advanceTimersByTimeAsync(10);
|
||||
await expect(opened).resolves.toBeUndefined();
|
||||
} finally { stop(); vi.useRealTimers(); }
|
||||
});
|
||||
|
||||
it("credits only stalls, so a slow but running process still reaches its deadline", () => {
|
||||
let wall = 0;
|
||||
const clock = new RunnerStallLedger(() => wall);
|
||||
const deadline = clock.now() + 30_000;
|
||||
// Every observation is 4.9 s apart on a loaded host: that is running time.
|
||||
while (clock.now() < deadline) wall += 4_900;
|
||||
expect(wall).toBeGreaterThanOrEqual(30_000);
|
||||
expect(wall).toBeLessThan(35_000);
|
||||
expect(clock.creditedMs).toBe(0);
|
||||
// A 6 s gap is a stop: credited in full plus the post-stop grace, and only once.
|
||||
wall += 6_000;
|
||||
clock.now();
|
||||
clock.now();
|
||||
expect(clock.creditedMs).toBe(6_000 + RUNNER_POST_STOP_GRACE_MS);
|
||||
// Total credit is capped, so a process that never runs normally still times out.
|
||||
wall += 2 * RUNNER_MAX_STOPPED_CREDIT_MS;
|
||||
clock.now();
|
||||
expect(clock.creditedMs).toBe(RUNNER_MAX_STOPPED_CREDIT_MS);
|
||||
// A wall-clock grace taken now moves onto the clock without the earlier
|
||||
// credit, so it keeps exactly its own running-time budget.
|
||||
const wallGrace = wall + 5_000;
|
||||
const onClock = wallGrace - clock.creditedMs;
|
||||
expect(onClock - clock.now()).toBe(5_000);
|
||||
});
|
||||
});
|
||||
|
||||
it("aborts startup promptly on close while allowing the owned cleanup command to drain", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
|
||||
@@ -119,6 +119,8 @@ const RUNNER_CLIENT_VERSION = "0.3.0";
|
||||
const RUNNER_BOOTSTRAP_TICKET_TTL_MS = 60_000;
|
||||
const RUNNER_RESTORE_STABLE_MS = 60_000;
|
||||
const MAX_UNSTABLE_RUNNER_RESTORES = 3;
|
||||
// Bounds the one in-place restart after a runner settles an earlier attempt's suspend.
|
||||
const CARRIED_SUSPEND_RESTART_GRACE_MS = 30_000;
|
||||
const RUNNERD_MAX_OUTBOX_BYTES = 16 * 1024 * 1024;
|
||||
const RUNNERD_P0_RESERVE_BYTES = 1024 * 1024;
|
||||
|
||||
@@ -4052,6 +4054,11 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
readonly #failureSignal: Promise<never>;
|
||||
#rejectFailureSignal!: (error: Error) => void;
|
||||
#runnerRecoveryInProgress = false;
|
||||
/** Controller commands journaled before this attempt queued any. */
|
||||
#carriedCommandCount: number | null = null;
|
||||
/** Each runner exit's carried-suspend classification, read once after exit. */
|
||||
readonly #carriedSuspendExits = new WeakMap<RunnerProcessHandle, Promise<boolean>>();
|
||||
#carriedSuspendRestartUsed = false;
|
||||
#lastRunnerRestoreAt: number | null = null;
|
||||
#unstableRunnerRestores = 0;
|
||||
#startupComplete = false;
|
||||
@@ -4064,6 +4071,8 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
#nextTraceDebugSequence = 1;
|
||||
#traceRehydrationSpoolOverflow = false;
|
||||
readonly #traceFrameIndex = new RunnerdTraceFrameIndex();
|
||||
/** Clock of the startup, recovery, or turn-start admission in progress, if any. */
|
||||
#admissionClock: RunnerStallLedger | null = null;
|
||||
#startupSteps: {
|
||||
begin(name: RunnerdStartupStep["name"]): void;
|
||||
/** Move on only from the named open step (later reconnects are not startup milestones). */
|
||||
@@ -5967,7 +5976,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
async #start(
|
||||
params: Record<string, unknown>,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const work = () => this.#withStartupSteps("bootstrap", () => this.#startWork(params));
|
||||
const work = () => this.#withAdmissionClock(() => this.#withStartupSteps("bootstrap", () => this.#startWork(params)));
|
||||
return this.options.measureOperation ? this.options.measureOperation("runner.transport.cold_start", work) : work();
|
||||
}
|
||||
|
||||
@@ -6079,6 +6088,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
connectionLeaseTtlMs: 60 * 60 * 1_000,
|
||||
});
|
||||
this.#core = core;
|
||||
this.#carriedCommandCount = core.store.state.commands.length;
|
||||
// Externally launched runners own their state directory (for example in a
|
||||
// Daytona sandbox). Do not create an empty controller-side placeholder:
|
||||
// prior-run authority checks must be able to distinguish absent remote
|
||||
@@ -6219,10 +6229,43 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
}
|
||||
|
||||
async #resume(): Promise<void> {
|
||||
const work = () => this.#withStartupSteps("resume", () => this.#resumeWork());
|
||||
const work = () => this.#withAdmissionClock(() => this.#withStartupSteps("resume", () => this.#resumeWork()));
|
||||
return this.options.measureOperation ? this.options.measureOperation("runner.transport.resume", work) : work();
|
||||
}
|
||||
|
||||
/**
|
||||
* One stopped-time clock per admission (startup, recovery, or a turn start);
|
||||
* a nested admission keeps the outer one. It covers the Runner command
|
||||
* barriers, the provider-identity wait, and turn.start with its start-event
|
||||
* and snapshot waits. The warm-transition and source-attachment reconnect
|
||||
* polls keep their own wall-clock grace deadlines.
|
||||
*/
|
||||
async #withAdmissionClock<T>(work: () => Promise<T>): Promise<T> {
|
||||
if (this.#admissionClock !== null) return work();
|
||||
const clock = new RunnerStallLedger();
|
||||
const stopWatching = clock.watch();
|
||||
this.#admissionClock = clock;
|
||||
try {
|
||||
return await work();
|
||||
} finally {
|
||||
stopWatching();
|
||||
if (this.#admissionClock === clock) this.#admissionClock = null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Wall time, or the admission clock while a startup, recovery, or turn start runs. */
|
||||
#waitNow(): number {
|
||||
return this.#admissionClock?.now() ?? Date.now();
|
||||
}
|
||||
|
||||
/** Moves a wall-clock deadline onto the admission clock, without the stops already credited. */
|
||||
#onWaitClock(wallDeadline: number): number {
|
||||
const clock = this.#admissionClock;
|
||||
if (clock === null) return wallDeadline;
|
||||
clock.now();
|
||||
return wallDeadline - clock.creditedMs;
|
||||
}
|
||||
|
||||
async #resumeWork(): Promise<void> {
|
||||
if (this.options.acpxCandidateAdmission?.agent === "antigravity") throw new Error("ACPX candidate durable runner recovery is not admitted");
|
||||
this.#startupSteps?.begin("runner.runtime.stage");
|
||||
@@ -6621,6 +6664,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
connectionLeaseTtlMs: 60 * 60 * 1_000,
|
||||
});
|
||||
this.#core = core;
|
||||
this.#carriedCommandCount = core.store.state.commands.length;
|
||||
// Reusing resources still requires current environment authorization. The
|
||||
// optional hook avoids re-preparation after controller storage is lost.
|
||||
// Existing consumers retain the preparation callback's authorization path.
|
||||
@@ -6943,7 +6987,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
this.#assertStartupOpen();
|
||||
const admissionDeadline = this.#sourceAttachmentDeadline === null
|
||||
? this.#coldAdmissionDeadline(adoptedRunner === undefined)
|
||||
: Math.min(Date.now() + 30_000, this.#sourceAttachmentDeadline);
|
||||
: Math.min(this.#waitNow() + 30_000, this.#onWaitClock(this.#sourceAttachmentDeadline));
|
||||
// An adopted runner is already live: no launch step (a launch span means a fresh process).
|
||||
if (adoptedRunner) this.#startupSteps?.end();
|
||||
else this.#startupSteps?.begin("runner.process.launch");
|
||||
@@ -7305,7 +7349,11 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
async #startTurn(
|
||||
params: Record<string, unknown>,
|
||||
): Promise<Record<string, unknown>> {
|
||||
return this.options.measureOperation ? this.options.measureOperation("runner.transport.turn_start", () => this.#startTurnWork(params), {inputBytes:Buffer.byteLength(JSON.stringify(params)), tokenDataAvailable:false}) : this.#startTurnWork(params);
|
||||
// turn.start and its start-event and snapshot waits share one deadline, so
|
||||
// they share one stopped-time clock (chaos t05: a 61 s freeze failed a
|
||||
// 30 s turn.start before the Runner or its sidecar could answer).
|
||||
const work = () => this.#withAdmissionClock(() => this.#startTurnWork(params));
|
||||
return this.options.measureOperation ? this.options.measureOperation("runner.transport.turn_start", work, {inputBytes:Buffer.byteLength(JSON.stringify(params)), tokenDataAvailable:false}) : work();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -7347,14 +7395,14 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
if (!Number.isSafeInteger(turnStartTimeoutMs) || turnStartTimeoutMs <= 0) {
|
||||
throw new Error("turnStartTimeoutMs must be a positive safe integer");
|
||||
}
|
||||
let commandDeadline = Date.now() + turnStartTimeoutMs;
|
||||
let commandDeadline = this.#waitNow() + turnStartTimeoutMs;
|
||||
const heldCalls = this.#core;
|
||||
if (typeof heldCalls?.semanticToolResultsSettled === "function" && !heldCalls.semanticToolResultsSettled()) {
|
||||
let recovering = true;
|
||||
void Promise.resolve(heldCalls.recoverPendingSemanticInputs())
|
||||
.catch(error => this.#failTransport(error instanceof Error ? error : new Error(String(error))))
|
||||
.finally(() => { recovering = false; });
|
||||
while (recovering && Date.now() < commandDeadline) {
|
||||
while (recovering && this.#waitNow() < commandDeadline) {
|
||||
this.#assertStartupOpen();
|
||||
this.#throwIfFailed();
|
||||
await new Promise<void>((resolveWait) => setTimeout(resolveWait, 10));
|
||||
@@ -7362,7 +7410,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
this.#assertStartupOpen();
|
||||
this.#throwIfFailed();
|
||||
if (recovering) throw new Error("native_turn_start_held_tool_calls_unresolved: recovering an earlier turn's held Paperclip tool calls did not finish before the turn-start deadline");
|
||||
commandDeadline = Date.now() + turnStartTimeoutMs;
|
||||
commandDeadline = this.#waitNow() + turnStartTimeoutMs;
|
||||
}
|
||||
const compactionTurn = params[COMPACTION_TURN] === true;
|
||||
const compactionPayload = compactionTurn ? runnerdCompactionTurnPayload(this.options.provider ?? "codex") : null;
|
||||
@@ -7464,7 +7512,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
// Codex and OpenCode return their provider-assigned identity.
|
||||
const deadline =
|
||||
this.options.turnStartTimeoutMs === undefined
|
||||
? Date.now() + 30_000
|
||||
? this.#waitNow() + 30_000
|
||||
: commandDeadline;
|
||||
const providerTurnStarted = () =>
|
||||
turnStartResponseReady({
|
||||
@@ -7477,7 +7525,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
// the start event early enough to read the runner's snapshot before it.
|
||||
const adoptionCheckAt = deadline - Math.min(
|
||||
TURN_START_ADOPTION_CHECK_RESERVE_MS,
|
||||
Math.floor(Math.max(0, deadline - Date.now()) / 4),
|
||||
Math.floor(Math.max(0, deadline - this.#waitNow()) / 4),
|
||||
);
|
||||
// The runner can end the accepted turn before it starts. Its terminal is
|
||||
// held for the pending start, so report that real cause at once.
|
||||
@@ -7492,7 +7540,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
throw new Error(`runnerd failed the provider turn before it started: ${failure}`);
|
||||
};
|
||||
const waitForStarted = async () => {
|
||||
while (!providerTurnStarted() && Date.now() < adoptionCheckAt) {
|
||||
while (!providerTurnStarted() && this.#waitNow() < adoptionCheckAt) {
|
||||
this.#throwIfFailed();
|
||||
this.#pumpEvents();
|
||||
if (providerTurnStarted()) break;
|
||||
@@ -7533,7 +7581,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
}
|
||||
// Not provably live: keep the original contract and wait for the
|
||||
// start event until the configured bound, then fail as before.
|
||||
while (!providerTurnStarted() && Date.now() < deadline) {
|
||||
while (!providerTurnStarted() && this.#waitNow() < deadline) {
|
||||
this.#throwIfFailed();
|
||||
this.#pumpEvents();
|
||||
if (providerTurnStarted()) break;
|
||||
@@ -7690,21 +7738,21 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
#coldAdmissionDeadline(coldProcess = true): number | undefined {
|
||||
const timeout = coldAdmissionTimeoutMs(this.options.provider, this.options.acpxAgent, coldProcess);
|
||||
// Preserve the existing independent waits for other providers and live adoption.
|
||||
return timeout === 60_000 ? Date.now() + timeout : undefined;
|
||||
return timeout === 60_000 ? this.#waitNow() + timeout : undefined;
|
||||
}
|
||||
|
||||
async #waitForProviderIdentity(
|
||||
expectedEventType?: "harness.ready" | "session.started" | "session.resumed",
|
||||
deadline = Date.now() + 30_000,
|
||||
deadline = this.#waitNow() + 30_000,
|
||||
): Promise<void> {
|
||||
return this.options.measureOperation ? this.options.measureOperation("runner.transport.provider_identity", () => this.#waitForProviderIdentityWork(expectedEventType, deadline)) : this.#waitForProviderIdentityWork(expectedEventType, deadline);
|
||||
}
|
||||
|
||||
async #waitForProviderIdentityWork(
|
||||
expectedEventType?: "harness.ready" | "session.started" | "session.resumed",
|
||||
deadline = Date.now() + 30_000,
|
||||
deadline = this.#waitNow() + 30_000,
|
||||
): Promise<void> {
|
||||
while (Date.now() < deadline) {
|
||||
while (this.#waitNow() < deadline) {
|
||||
this.#throwIfFailed();
|
||||
if (this.#closed) throw new Error("runnerd transport closed during provider startup");
|
||||
this.#pumpEvents();
|
||||
@@ -7728,7 +7776,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
async #waitCommand(
|
||||
type: string,
|
||||
commandId?: string,
|
||||
deadline = Date.now() + 30_000,
|
||||
deadline = this.#waitNow() + 30_000,
|
||||
abortOnClose = false,
|
||||
): Promise<void> {
|
||||
return this.options.measureOperation ? this.options.measureOperation("runner.transport.command_ack", () => this.#waitCommandWork(type, commandId, deadline, abortOnClose)) : this.#waitCommandWork(type, commandId, deadline, abortOnClose);
|
||||
@@ -7737,12 +7785,13 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
async #waitCommandWork(
|
||||
type: string,
|
||||
commandId?: string,
|
||||
deadline = Date.now() + 30_000,
|
||||
deadline = this.#waitNow() + 30_000,
|
||||
abortOnClose = false,
|
||||
): Promise<void> {
|
||||
await waitForRunnerCommand({
|
||||
type,
|
||||
deadline,
|
||||
clock: this.#admissionClock,
|
||||
abortOnClose,
|
||||
isClosed: () => this.#closed,
|
||||
throwIfFailed: () => this.#throwIfFailed(),
|
||||
@@ -8367,8 +8416,16 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
|
||||
async #runnerHasExited(): Promise<boolean> {
|
||||
// A runnerd killed by a signal reports exitCode null and its signalCode.
|
||||
if (this.#handle) return this.#handle.isExitConfirmed?.()
|
||||
?? (this.#handle.child.exitCode !== null || (this.#handle.child.signalCode ?? null) !== null);
|
||||
if (this.#handle) {
|
||||
const handle = this.#handle;
|
||||
const exited = handle.isExitConfirmed?.()
|
||||
?? (handle.child.exitCode !== null || (handle.child.signalCode ?? null) !== null);
|
||||
// A runner that only settled a suspend left by an earlier attempt is
|
||||
// being restarted in place; startup keeps waiting for its replacement.
|
||||
if (exited && !this.#startupComplete && await this.#carriedSuspendExits.get(handle))
|
||||
return this.#closed || this.#failure !== null;
|
||||
return exited;
|
||||
}
|
||||
const adoptedRunner = this.options.adoptExistingRunner;
|
||||
if (!adoptedRunner) return true;
|
||||
return !(await adoptedRunner.isAlive());
|
||||
@@ -8446,8 +8503,13 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
}
|
||||
|
||||
#watchRunner(handle: RunnerProcessHandle): void {
|
||||
const carriedSuspendExit = handle.completion.then(
|
||||
(result) => this.#settledOnlyCarriedSuspend(handle, result.code),
|
||||
() => false,
|
||||
);
|
||||
this.#carriedSuspendExits.set(handle, carriedSuspendExit);
|
||||
void handle.completion.then(
|
||||
(result) => {
|
||||
async (result) => {
|
||||
const exitConfirmed = handle.isExitConfirmed?.() ?? true;
|
||||
this.#evidence.runnerExited = exitConfirmed;
|
||||
this.#evidence.runnerExitCode = result.code;
|
||||
@@ -8463,6 +8525,14 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
this.#lostRunnerHandle = handle;
|
||||
if (this.#closed || this.#failure !== null || this.#handle !== handle || (this.#releaseEpisode && !this.#releaseEpisode.claimed))
|
||||
return;
|
||||
if (await carriedSuspendExit) {
|
||||
if (this.#closed || this.#failure !== null || this.#handle !== handle) return;
|
||||
this.#carriedSuspendRestartUsed = true;
|
||||
this.#diagnostic("runner settled a suspend left by an earlier attempt and exited; restarting it in place");
|
||||
void this.#recoverRunnerProcess(handle, detail, CARRIED_SUSPEND_RESTART_GRACE_MS);
|
||||
return;
|
||||
}
|
||||
if (this.#closed || this.#failure !== null || this.#handle !== handle) return;
|
||||
// A per-turn runner exits after its terminal suffix is durably ACKed.
|
||||
// Drain that suffix into the provider-facing queue before classifying
|
||||
// process completion; clean terminal exit is the expected lifecycle.
|
||||
@@ -8532,6 +8602,37 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A freeze or restart during `runner.suspend` leaves that command pending in
|
||||
* the controller journal. The next attempt's runner settles it from the
|
||||
* welcome and exits as suspended before it accepts this attempt's work. Only
|
||||
* that exit is restarted in place, once, and only when the durable runner
|
||||
* journal proves it: the runner's last command is exactly that earlier
|
||||
* suspend, settled by the controller, and the runner rests suspended with no
|
||||
* fence. It then executed nothing this attempt queued, so no turn started and
|
||||
* no provider work can repeat. The runner file is read only after an exit.
|
||||
*/
|
||||
async #settledOnlyCarriedSuspend(handle: RunnerProcessHandle, code: number | null): Promise<boolean> {
|
||||
const core = this.#core;
|
||||
const carried = this.#carriedCommandCount;
|
||||
if (code !== 0 || handle.isExitConfirmed?.() === false || !handle.restart || core === null || carried === null
|
||||
|| this.#carriedSuspendRestartUsed || this.#startupComplete || this.#closed || this.#failure !== null
|
||||
|| this.options.adoptExistingRunner || this.options.runnerProcessLauncher || this.options.readRunnerState
|
||||
|| this.options.runnerStateDirectory !== undefined) return false;
|
||||
let state: Record<string, unknown>;
|
||||
try {
|
||||
state = await this.#readDurableRunnerState();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return carriedSuspendSettlementProven({
|
||||
runnerState: state,
|
||||
identity: core.store.state.identity,
|
||||
commands: core.store.state.commands,
|
||||
carriedCommandCount: carried,
|
||||
});
|
||||
}
|
||||
|
||||
#recoverOrFailRunnerProcess(handle: RunnerProcessHandle, detail: string): void {
|
||||
this.#unstableRunnerRestores = unstableRunnerRestoreCount(
|
||||
this.#unstableRunnerRestores,
|
||||
@@ -8552,6 +8653,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
async #recoverRunnerProcess(
|
||||
failedHandle: RunnerProcessHandle,
|
||||
initialDetail: string,
|
||||
graceOverrideMs?: number,
|
||||
): Promise<void> {
|
||||
if (
|
||||
this.#runnerRecoveryInProgress ||
|
||||
@@ -8563,7 +8665,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
)
|
||||
return;
|
||||
this.#runnerRecoveryInProgress = true;
|
||||
const graceMs = this.options.runnerReconnectGraceMs ?? 0;
|
||||
const graceMs = graceOverrideMs ?? this.options.runnerReconnectGraceMs ?? 0;
|
||||
const deadline = Date.now() + graceMs;
|
||||
const delays = [250, 500, 1_000, 2_000, 5_000] as const;
|
||||
let attempt = 0;
|
||||
@@ -9083,7 +9185,33 @@ function unstableRunnerRestoreCount(previous: number, restoredAt: number | null,
|
||||
return restoredAt !== null && now - restoredAt < RUNNER_RESTORE_STABLE_MS ? previous + 1 : 0;
|
||||
}
|
||||
|
||||
/** The durable proof that a runner's clean exit only settled a suspend that an
|
||||
* earlier attempt journaled: its last command is exactly that suspend, which
|
||||
* the controller has settled; it rests suspended with no fence; and nothing
|
||||
* this attempt queued has a result, so no turn or provider work ran. */
|
||||
function carriedSuspendSettlementProven(input: {
|
||||
runnerState: Record<string, unknown>;
|
||||
identity: DurableRecoveryIdentity;
|
||||
commands: readonly { commandId: string; controllerSeq: number; type: string; status: string }[];
|
||||
carriedCommandCount: number;
|
||||
}): boolean {
|
||||
const { runnerState: state, commands, carriedCommandCount: carried } = input;
|
||||
const seq = state.lastControllerCommandSeq;
|
||||
if (state.schema !== "paperclip.runner.durable.state.v1"
|
||||
|| !recoveryIdentityMatches(state, input.identity)
|
||||
|| state.lifecycle !== "suspended" || state.pendingTerminalDelivery != null
|
||||
|| state.pendingProviderCleanup != null || state.warmTransition != null
|
||||
|| typeof seq !== "number" || !Number.isSafeInteger(seq) || seq < 1 || seq > carried) return false;
|
||||
const suspend = commands.find((command) => command.controllerSeq === seq);
|
||||
if (suspend?.type !== "runner.suspend" || suspend.status === "pending") return false;
|
||||
if (commands.some((command) => command.controllerSeq > carried && command.status !== "pending")) return false;
|
||||
const processed = record(record(state.processedCommands)[suspend.commandId]);
|
||||
return processed.commandId === suspend.commandId && processed.commandType === "runner.suspend"
|
||||
&& processed.controllerSeq === seq && processed.status !== "pending";
|
||||
}
|
||||
|
||||
export const runnerdRecoveryInternals = Object.freeze({
|
||||
carriedSuspendSettlementProven,
|
||||
unstableRunnerRestoreCount,
|
||||
projectCopilotRunGrant,
|
||||
completedMaintenanceTerminalReceipt,
|
||||
@@ -9165,10 +9293,70 @@ function closedAcpxRejection(message: unknown): string | null {
|
||||
? message : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A gap this long between two observations by a running process (its poll
|
||||
* loops sleep 10 ms, its ticker 1 s) means the process was not running:
|
||||
* SIGSTOP, host sleep, or a whole-process stall.
|
||||
*/
|
||||
export const RUNNER_STALL_THRESHOLD_MS = 5_000;
|
||||
const RUNNER_STALL_TICK_MS = 1_000;
|
||||
/** After a stop, the thawed Runner keeps at least this long to answer. */
|
||||
export const RUNNER_POST_STOP_GRACE_MS = 5_000;
|
||||
/** One admission never credits more stopped time than this in total. */
|
||||
export const RUNNER_MAX_STOPPED_CREDIT_MS = 15 * 60_000;
|
||||
|
||||
/**
|
||||
* The clock for one startup or recovery admission. Time this process spends
|
||||
* stopped is not waiting time: the Runner it waits on is usually stopped with
|
||||
* it (same host sleep or process tree), and could not answer. The wall clock
|
||||
* still passes the deadline, so a thaw used to report a timeout before either
|
||||
* process ran (chaos t01: "runner.drain timed out" 45 s into a 30 s wait that
|
||||
* held a 44 s freeze).
|
||||
*
|
||||
* `now()` is wall time minus the stopped time observed since the ledger
|
||||
* started. Poll loops and a 1 s ticker share one last-observation time, so a
|
||||
* stop is credited once, wherever the process was when it stopped (a poll
|
||||
* loop, a checkpoint flush, a spawn). A stop is credited in full plus a
|
||||
* grace, so a stop near a deadline still leaves the Runner time to answer
|
||||
* after the thaw. Gaps below the threshold are running time, and total credit
|
||||
* is capped, so a slow process still reaches its deadlines. Deadlines
|
||||
* compared with `now()` must be taken from `now()`.
|
||||
*/
|
||||
export class RunnerStallLedger {
|
||||
#creditedMs = 0;
|
||||
#last: number;
|
||||
constructor(private readonly wallNow: () => number = Date.now) {
|
||||
this.#last = wallNow();
|
||||
}
|
||||
|
||||
get creditedMs(): number {
|
||||
return this.#creditedMs;
|
||||
}
|
||||
|
||||
now(): number {
|
||||
const at = this.wallNow();
|
||||
if (at - this.#last > RUNNER_STALL_THRESHOLD_MS) {
|
||||
this.#creditedMs = Math.min(RUNNER_MAX_STOPPED_CREDIT_MS,
|
||||
this.#creditedMs + at - this.#last + RUNNER_POST_STOP_GRACE_MS);
|
||||
}
|
||||
this.#last = Math.max(this.#last, at);
|
||||
return at - this.#creditedMs;
|
||||
}
|
||||
|
||||
/** Observes stops between poll loops; runs only while its admission runs. */
|
||||
watch(): () => void {
|
||||
const ticker = setInterval(() => this.now(), RUNNER_STALL_TICK_MS);
|
||||
ticker.unref?.();
|
||||
return () => clearInterval(ticker);
|
||||
}
|
||||
}
|
||||
|
||||
/** Shared polling path keeps startup cancellation separate from owned cleanup commands. */
|
||||
export async function waitForRunnerCommand(input: {
|
||||
type: string;
|
||||
deadline: number;
|
||||
/** Startup or recovery admission clock; `deadline` was taken from it. */
|
||||
clock?: RunnerStallLedger | null;
|
||||
abortOnClose: boolean;
|
||||
isClosed: () => boolean;
|
||||
throwIfFailed: () => void;
|
||||
@@ -9176,7 +9364,8 @@ export async function waitForRunnerCommand(input: {
|
||||
runnerHasExited: () => Promise<boolean>;
|
||||
failureCode: () => string;
|
||||
}): Promise<void> {
|
||||
while (Date.now() < input.deadline) {
|
||||
const now = () => input.clock ? input.clock.now() : Date.now();
|
||||
while (now() < input.deadline) {
|
||||
input.throwIfFailed();
|
||||
if (input.abortOnClose && input.isClosed()) {
|
||||
throw new Error(`runnerd transport closed while waiting for ${input.type}`);
|
||||
|
||||
@@ -6664,6 +6664,67 @@ describe("executeNativeSession recovery", () => {
|
||||
}
|
||||
});
|
||||
|
||||
// A remote workspace epoch was abandoned, so the run was assigned a new
|
||||
// sibling root while its checkpoint still names the old one. A checkpoint
|
||||
// that requires the same session (an unfinished goal) ends with the
|
||||
// permanent named code, never a generic retryable failure; a checkpoint that
|
||||
// allows replacement continues in a fresh session in the assigned root.
|
||||
it.each([
|
||||
["same_session_only", false, false],
|
||||
["allow_replacement_after_governed_wait", false, false],
|
||||
["allow_replacement_after_resume_failure", true, false],
|
||||
// An in-flight turn may have an unsettled external effect: never replaced, under any policy.
|
||||
["same_session_only", false, true],
|
||||
["allow_replacement_after_resume_failure", false, true],
|
||||
] as const)("handles a %s checkpoint whose remote workspace root moved (replaces=%s, in flight=%s)", async (providerRecoveryPolicy, replaces, inFlight) => {
|
||||
const parent = "/home/daytona/paperclip-workspace/.paperclip-workspaces";
|
||||
const savedRoot = `${parent}/a5a34403-04fe-4e7e-97cf-d8f371a802a4-1-80214561-2151-4112-a43a-7d65f3071b56`;
|
||||
const assignedRoot = `${parent}/a5a34403-04fe-4e7e-97cf-d8f371a802a4-5-ef79592c-6784-438f-8a17-9800dd2fa2fc`;
|
||||
const checkpoint: PersistedNativeSession = {
|
||||
backendKind: "runner", sessionId: "thread-1", identity, providerSessionId: "provider-session-1",
|
||||
workingDirectory: savedRoot, providerRecoveryPolicy, cursor: "0", activeTurnId: inFlight ? "turn-in-flight" : null,
|
||||
terminalTurns: [], pendingRuntimeRequests: [], lineage: [],
|
||||
};
|
||||
const transportFactory = vi.fn(() => new FakeCodexTransport());
|
||||
const backend = createCodexNativeSessionBackend({ ...input, workspace: { ...input.workspace, cwd: assignedRoot } }, {
|
||||
runnerInstanceId: "runner-recovery", transportFactory,
|
||||
workingDirectoryAuthority: "remote_runner", environment: { PAPERCLIP_WORKSPACE_CWD: assignedRoot },
|
||||
});
|
||||
const replacementAttempted = new Error("replacement attempted");
|
||||
const openReplacementSession = vi.fn(async (sessionInput: { workingDirectory?: string }) => {
|
||||
expect(sessionInput.workingDirectory).toBe(assignedRoot);
|
||||
throw replacementAttempted;
|
||||
});
|
||||
const openRun = vi.fn(async () => undefined);
|
||||
const failure = await executeNativeSession({
|
||||
input: { ...input, workspace: { ...input.workspace, cwd: assignedRoot } },
|
||||
backend: { descriptor: () => backend.descriptor(), openSession: sessionInput => backend.openSession(sessionInput),
|
||||
openReplacementSession, recoverSession: (snapshot, options) => backend.recoverSession!(snapshot, options) },
|
||||
controlPlane: {
|
||||
openRun, appendEvent: vi.fn(), completeRun: vi.fn(),
|
||||
loadSessionCheckpoint: async () => structuredClone(checkpoint),
|
||||
replayEvents: async () => ({ events: [], highestContiguousSourceSeq: 0 }),
|
||||
},
|
||||
runnerInstanceId: "runner-recovery", controlPlaneInstanceId: "control-recovery",
|
||||
}).catch((error: unknown) => error);
|
||||
if (replaces) {
|
||||
expect(failure).toBe(replacementAttempted);
|
||||
expect(openReplacementSession).toHaveBeenCalledOnce();
|
||||
} else {
|
||||
if (inFlight) {
|
||||
expect(failure).toBeInstanceOf(NativeProviderSideEffectPendingError);
|
||||
expect((failure as NativeProviderSideEffectPendingError).code).toBe("native_provider_side_effect_pending");
|
||||
} else {
|
||||
expect(failure).toBeInstanceOf(NativeProviderStateIncompatibleError);
|
||||
expect((failure as NativeProviderStateIncompatibleError).code).toBe("native_provider_state_incompatible");
|
||||
}
|
||||
expect(openReplacementSession).not.toHaveBeenCalled();
|
||||
expect(openRun).not.toHaveBeenCalled();
|
||||
}
|
||||
// No Runner or provider process starts for a session that cannot resume here.
|
||||
expect(transportFactory).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("never replaces a session after a deterministic, non-destructive recovery refusal", async () => {
|
||||
const outcomes = [
|
||||
{ failureClass: PROVIDER_ATTACH_REFUSED, reason: "run.attach cannot change protected launch arguments",
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { createDb, startEmbeddedPostgresTestDatabase, type Db } from "../packages/db/src/index.js";
|
||||
import { registerGitHubTerminalResponseWork } from "../server/src/services/chat-channels/github/terminal-response-work.js";
|
||||
import { captureReviewWaitQueries, type CapturedReviewWaitQuery } from "../server/src/__tests__/helpers/github-review-wait.js";
|
||||
|
||||
// Measures the GitHub terminal-response discovery page against a synthetic
|
||||
// history: many agent runs with incompressible legacy contexts and a set of
|
||||
// acknowledged (processed, non-final) response comments.
|
||||
// pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-github-terminal-response-sweep.ts --baseline-ref=<pre-fix commit>
|
||||
const baselineRef = process.argv.find(arg => arg.startsWith("--baseline-ref="))?.slice(15);
|
||||
assert.ok(baselineRef, "Pass an explicit pre-fix --baseline-ref=<commit>");
|
||||
const number = (name: string, fallback: number) => Number(process.env[name] ?? fallback);
|
||||
const fixture = {
|
||||
issues: number("BENCH_ISSUES", 1_500),
|
||||
runsPerIssue: number("BENCH_RUNS_PER_ISSUE", 8),
|
||||
contextPadBytes: number("BENCH_CONTEXT_PAD_BYTES", 4_096),
|
||||
candidates: number("BENCH_CANDIDATES", 150),
|
||||
blockedEvery: 10,
|
||||
decoyCompanies: 1,
|
||||
};
|
||||
const baselineRevision = execFileSync("git", ["rev-parse", "--verify", `${baselineRef}^{commit}`], { encoding: "utf8" }).trim();
|
||||
const treatmentRevision = execFileSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).trim();
|
||||
const modulePath = "server/src/services/chat-channels/github/terminal-response-work.ts";
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
const keepAlive = setInterval(() => {}, 1_000);
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | undefined;
|
||||
let db: Db | undefined;
|
||||
let baselineDir: string | undefined;
|
||||
|
||||
async function seed(db: Db, companyIndex: number) {
|
||||
const sql = db.$client;
|
||||
const [{ company }] = await sql.unsafe(`insert into companies (name, issue_prefix) values ($1, $2) returning id as company`,
|
||||
[`Bench ${companyIndex}`, `BN${companyIndex}`]);
|
||||
const [{ agent }] = await sql.unsafe(`insert into agents (company_id, name) values ($1, 'GitHub agent') returning id as agent`, [company]);
|
||||
const [{ application }] = await sql.unsafe(`insert into tool_applications (company_id, application_key, name, type)
|
||||
values ($1, 'github', 'GitHub', 'chat') returning id as application`, [company]);
|
||||
const [{ connection }] = await sql.unsafe(`insert into tool_connections (company_id, application_id, name, uid, transport, connection_purpose)
|
||||
values ($1, $2, 'GitHub', $3, 'chat_sdk', 'channel') returning id as connection`, [company, application, `github-${companyIndex}`]);
|
||||
const [{ endpoint }] = await sql.unsafe(`insert into chat_endpoints (company_id, connection_id, provider, public_id, assigned_agent_id, status)
|
||||
values ($1, $2, 'github', $3, $4, 'active') returning id as endpoint`, [company, connection, `bench-${companyIndex}`, agent]);
|
||||
const [{ resource }] = await sql.unsafe(`insert into chat_endpoint_resources (company_id, endpoint_id, type, provider_resource_id, label, metadata)
|
||||
values ($1, $2, 'repository', 'R_1', 'paperclipai/paperclip', '{"providerRepositoryId":"R_1"}') returning id as resource`, [company, endpoint]);
|
||||
// Issue numbers are 1..N; every tenth issue is blocked.
|
||||
await sql.unsafe(`insert into issues (company_id, title, status)
|
||||
select $1, 'Issue ' || n, case when n % ${fixture.blockedEvery} = 0 then 'blocked' else 'in_progress' end
|
||||
from generate_series(1, ${fixture.issues}) n`, [company]);
|
||||
await sql.unsafe(`create unlogged table if not exists bench_issue (n int, id uuid, company uuid)`);
|
||||
await sql.unsafe(`delete from bench_issue`);
|
||||
await sql.unsafe(`insert into bench_issue select (regexp_replace(title, '\\D', '', 'g'))::int, id, company_id from issues where company_id = $1`, [company]);
|
||||
await sql.unsafe(`insert into chat_conversations (company_id, endpoint_id, issue_id, external_conversation_id, external_label,
|
||||
external_thread_id, resource_id)
|
||||
select $1, $2, i.id, 'github:paperclipai/paperclip:' || i.n, 'PR #' || i.n, 'github:paperclipai/paperclip:' || i.n, $3
|
||||
from bench_issue i`, [company, endpoint, resource]);
|
||||
await sql.unsafe(`insert into chat_deliveries (company_id, endpoint_id, provider_event_id, deduplication_key, event_kind,
|
||||
normalized_event, conversation_id, state)
|
||||
select $1, $2, 'event-' || i.n, 'dedupe-' || i.n, 'message', '{}', c.id, 'processed'
|
||||
from bench_issue i join chat_conversations c on c.issue_id = i.id`, [company, endpoint]);
|
||||
// One response comment per issue. The first N issues are acknowledged and
|
||||
// not final; the rest finished long ago with a final response.
|
||||
await sql.unsafe(`insert into chat_actions (company_id, endpoint_id, delivery_id, conversation_id, kind, provider_action_id, status, result)
|
||||
select $1, $2, d.id, c.id, 'github_response_comment', 'response-' || i.n, 'processed',
|
||||
case when i.n <= ${fixture.candidates} then jsonb_build_object('id', 'IC_' || i.n, 'final', false)
|
||||
else jsonb_build_object('id', 'IC_' || i.n, 'final', true) end
|
||||
from bench_issue i join chat_conversations c on c.issue_id = i.id join chat_deliveries d on d.conversation_id = c.id`, [company, endpoint]);
|
||||
await sql.unsafe(`insert into chat_message_links (company_id, endpoint_id, conversation_id, delivery_id, provider_message_id, direction)
|
||||
select $1, $2, c.id, d.id, 'IC_in_' || i.n, 'inbound'
|
||||
from bench_issue i join chat_conversations c on c.issue_id = i.id join chat_deliveries d on d.conversation_id = c.id`, [company, endpoint]);
|
||||
// Runs: odd issues are legacy (context_snapshot only), even issues are native.
|
||||
// Legacy contexts carry incompressible padding like real prompt context.
|
||||
await sql.unsafe(`insert into heartbeat_runs (company_id, agent_id, status, native_issue_id, context_snapshot, created_at)
|
||||
select $1, $2, case when r = ${fixture.runsPerIssue} and i.n % 3 = 0 then 'running' else 'succeeded' end,
|
||||
case when i.n % 2 = 0 then i.id end,
|
||||
jsonb_build_object('issueId', i.id::text, 'pad',
|
||||
(select string_agg(md5(random()::text || g::text || i.n::text || r::text), '') from generate_series(1, ${Math.ceil(fixture.contextPadBytes / 32)}) g)),
|
||||
timestamptz '2026-01-01' + (i.n * ${fixture.runsPerIssue} + r) * interval '1 second'
|
||||
from bench_issue i cross join generate_series(1, ${fixture.runsPerIssue}) r`, [company, agent]);
|
||||
// Precedence decoys: a newer active run natively bound to another issue whose
|
||||
// legacy context still names this issue. It must not count for this issue.
|
||||
await sql.unsafe(`insert into heartbeat_runs (company_id, agent_id, status, native_issue_id, context_snapshot, created_at)
|
||||
select $1, $2, 'running', gen_random_uuid(), jsonb_build_object('issueId', i.id::text),
|
||||
timestamptz '2026-01-01' + (i.n * ${fixture.runsPerIssue} + ${fixture.runsPerIssue} + 1) * interval '1 second'
|
||||
from bench_issue i where i.n % 7 = 0`, [company, agent]);
|
||||
// Ordering ties: an active run with the latest creation time of the issue's
|
||||
// other runs (native and legacy). The id decides which run is latest.
|
||||
await sql.unsafe(`insert into heartbeat_runs (company_id, agent_id, status, native_issue_id, context_snapshot, created_at)
|
||||
select $1, $2, 'running', case when i.n % 2 = 1 then i.id end, jsonb_build_object('issueId', i.id::text),
|
||||
timestamptz '2026-01-01' + (i.n * ${fixture.runsPerIssue} + ${fixture.runsPerIssue}) * interval '1 second'
|
||||
from bench_issue i where i.n % 11 = 0`, [company, agent]);
|
||||
// Another agent's newer active runs on the same issues.
|
||||
const [{ other }] = await sql.unsafe(`insert into agents (company_id, name) values ($1, 'Other agent') returning id as other`, [company]);
|
||||
await sql.unsafe(`insert into heartbeat_runs (company_id, agent_id, status, native_issue_id, context_snapshot, created_at)
|
||||
select $1, $2, 'running', case when i.n % 2 = 0 then i.id end, jsonb_build_object('issueId', i.id::text), timestamptz '2027-01-01'
|
||||
from bench_issue i where i.n % 5 = 0`, [company, other]);
|
||||
return { company, agent, endpoint };
|
||||
}
|
||||
|
||||
try {
|
||||
const oldSource = execFileSync("git", ["show", `${baselineRevision}:${modulePath}`], { encoding: "utf8" });
|
||||
const moduleUrl = new URL(`../${modulePath}`, import.meta.url);
|
||||
baselineDir = await fs.mkdtemp(path.join(root, "server/scripts/.terminal-response-baseline-"));
|
||||
const baselineFile = path.join(baselineDir, "terminal-response-work.ts");
|
||||
await fs.writeFile(baselineFile, oldSource.replace(/from "(\.{1,2}\/[^\"]+)"/g,
|
||||
(_match, specifier: string) => `from ${JSON.stringify(fileURLToPath(new URL(specifier, moduleUrl)))}`));
|
||||
const baseline = await import(pathToFileURL(baselineFile).href) as typeof import("../server/src/services/chat-channels/github/terminal-response-work.js");
|
||||
temporary = await startEmbeddedPostgresTestDatabase("github-terminal-response-benchmark-");
|
||||
db = createDb(temporary.connectionString);
|
||||
const seedStart = performance.now();
|
||||
const main = await seed(db, 0);
|
||||
for (let n = 1; n <= fixture.decoyCompanies; n++) await seed(db, n);
|
||||
await db.$client.unsafe("DROP TABLE bench_issue");
|
||||
await db.$client.unsafe("ANALYZE");
|
||||
const seedMs = performance.now() - seedStart;
|
||||
|
||||
const stop = new Error("captured");
|
||||
async function capture(register: typeof registerGitHubTerminalResponseWork) {
|
||||
const queries: CapturedReviewWaitQuery[] = [];
|
||||
const proxy = captureReviewWaitQueries(db!, queries);
|
||||
let task: { run(signal: AbortSignal): Promise<unknown> } | undefined;
|
||||
const coordinator = { register: (_queue: unknown, value: typeof task) => { task = value; return { wake() {}, stop: async () => {} }; } };
|
||||
register(new Proxy(proxy, { get(target, key) {
|
||||
const value = Reflect.get(target, key);
|
||||
if (key !== "select") return value;
|
||||
return (...args: unknown[]) => {
|
||||
if (queries.some(query => query.sql.includes("github-publication:"))) throw stop;
|
||||
return (value as (...args: unknown[]) => unknown)(...args);
|
||||
};
|
||||
} }), coordinator as never, async () => {}, () => true);
|
||||
await task!.run(new AbortController().signal).catch(() => {});
|
||||
const query = queries.find(query => query.sql.includes("github-publication:"));
|
||||
assert.ok(query, "Capture the real discovery page query");
|
||||
return query;
|
||||
}
|
||||
const queries = {
|
||||
baseline: await capture(baseline.registerGitHubTerminalResponseWork),
|
||||
treatment: await capture(registerGitHubTerminalResponseWork),
|
||||
};
|
||||
|
||||
// Compare every candidate, not only the first page: lift the page limit.
|
||||
async function rows(query: CapturedReviewWaitQuery) {
|
||||
assert.match(query.sql, /limit \$\d+$/);
|
||||
const params = [...query.params.slice(0, -1), 1_000_000];
|
||||
return (await db!.$client.unsafe(query.sql, params as never[]).values()).map(row => row.map(value =>
|
||||
value === null ? null : typeof value === "object" && !(value instanceof Date) ? JSON.stringify(value) : String(value)));
|
||||
}
|
||||
const before = await rows(queries.baseline), after = await rows(queries.treatment);
|
||||
assert.deepEqual(after, before, "Every returned column and row order must match");
|
||||
assert.ok(before.length > 0, "The fixture must return terminal candidates");
|
||||
|
||||
async function timed(query: CapturedReviewWaitQuery) {
|
||||
const start = performance.now();
|
||||
await db!.$client.unsafe(query.sql, query.params as never[]).values();
|
||||
return performance.now() - start;
|
||||
}
|
||||
const iterations = number("BENCH_ITERATIONS", 7);
|
||||
const samples = { baseline: [] as number[], treatment: [] as number[] };
|
||||
for (let n = 0; n < iterations + 2; n++) {
|
||||
const versions = n % 2 ? ["treatment", "baseline"] as const : ["baseline", "treatment"] as const;
|
||||
for (const version of versions) {
|
||||
const elapsed = await timed(queries[version]);
|
||||
if (n >= 2) samples[version].push(elapsed);
|
||||
}
|
||||
}
|
||||
const stats = (values: number[]) => {
|
||||
const sorted = [...values].sort((a, b) => a - b);
|
||||
return { samplesMs: values.map(value => Math.round(value * 10) / 10), medianMs: sorted[Math.floor(sorted.length / 2)],
|
||||
minMs: sorted[0], maxMs: sorted.at(-1) };
|
||||
};
|
||||
async function plan(query: CapturedReviewWaitQuery) {
|
||||
return (await db!.$client.unsafe(`EXPLAIN (ANALYZE, BUFFERS) ${query.sql}`, query.params as never[]).values()).map(row => row[0]);
|
||||
}
|
||||
const counts = (await db.$client.unsafe(`select (select count(*) from heartbeat_runs)::int runs,
|
||||
(select count(*) from chat_actions)::int actions, pg_size_pretty(pg_total_relation_size('heartbeat_runs')) runs_size`))[0];
|
||||
console.log(JSON.stringify({ baselineRevision, treatmentRevision,
|
||||
treatmentDiff: execFileSync("git", ["diff", "HEAD", "--", modulePath], { cwd: root, encoding: "utf8" }),
|
||||
postgresVersion: (await db.$client.unsafe("SELECT version()"))[0]!.version,
|
||||
fixture: { ...fixture, ...counts, seedMs: Math.round(seedMs), mainCompany: main.company, synthetic: true },
|
||||
correctness: { completeOutputEqual: true, rows: before.length },
|
||||
timings: { warmups: 2, samples: iterations, order: "alternating", baseline: stats(samples.baseline), treatment: stats(samples.treatment) },
|
||||
plans: { baseline: await plan(queries.baseline), treatment: await plan(queries.treatment) },
|
||||
generatedQueries: { baseline: queries.baseline, treatment: queries.treatment },
|
||||
}, null, 2));
|
||||
} finally {
|
||||
try {
|
||||
await db?.$client.end({ timeout: 0 });
|
||||
await temporary?.cleanup();
|
||||
if (baselineDir) await fs.rm(baselineDir, { recursive: true, force: true });
|
||||
} finally { clearInterval(keepAlive); }
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* Local proof for the run-event append lock and controller checkpoint saves.
|
||||
*
|
||||
* A native run appends every PRP event through `appendHeartbeatRunEvent`,
|
||||
* which locks the run row. The controller then saves its checkpoint: a new
|
||||
* `event:N` row plus the `cursor` row. The new row's foreign key check takes
|
||||
* FOR KEY SHARE on the same run row. This script replays that pattern with the
|
||||
* real append and the real checkpoint writer, on separate connections, and
|
||||
* times each checkpoint save. It compares a baseline append module (FOR UPDATE)
|
||||
* with the current one (FOR NO KEY UPDATE), in alternating order.
|
||||
*
|
||||
* Overlap is the normal controller order. The frame chain awaits each event's
|
||||
* append (onCommittedEvent) and local commit, but not its checkpoint save: the
|
||||
* ACK goes through #sendJson, which queues the save and does not block the
|
||||
* next frame. Only semantic inputs and command results await the save. So the
|
||||
* save for event N runs while event N+1 is appended. SERIAL=1 awaits every
|
||||
* save before the next append, as a control without overlap.
|
||||
*
|
||||
* HOLD_MS keeps each append transaction open that much longer. It stands in
|
||||
* for hosted round trips, which make the real append transaction last longer
|
||||
* than on loopback.
|
||||
*
|
||||
* git show <base>:server/src/services/heartbeat-run-events.ts \
|
||||
* > server/src/services/heartbeat-run-events.baseline.ts
|
||||
* pnpm --filter @paperclipai/server exec tsx ../scripts/benchmark-run-event-checkpoint-lock.ts
|
||||
*
|
||||
* Optional: EVENTS (default 400 per pass), PASSES (4), HOLD_MS (5), EVENT_KIB (2), SERIAL (0).
|
||||
* Delete the baseline copy afterwards.
|
||||
*/
|
||||
import assert from "node:assert/strict";
|
||||
import { randomBytes, randomUUID } from "node:crypto";
|
||||
import { existsSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { agents, companies, createDb, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations,
|
||||
nativeRunnerCheckpoints, startEmbeddedPostgresTestDatabase } from "../packages/db/src/index.js";
|
||||
import * as candidate from "../server/src/services/heartbeat-run-events.js";
|
||||
import { nativeRunnerCheckpointWriter } from "../server/src/services/native-runtime/native-runner-checkpoint.js";
|
||||
|
||||
const { eq, sql: drizzleSql } = createRequire(new URL("../server/package.json", import.meta.url))("drizzle-orm") as typeof import("drizzle-orm");
|
||||
|
||||
const baselinePath = fileURLToPath(new URL("../server/src/services/heartbeat-run-events.baseline.ts", import.meta.url));
|
||||
assert(existsSync(baselinePath), "Write the baseline module first (see the header)");
|
||||
const baseline = await import(baselinePath) as typeof candidate;
|
||||
const size = (name: string, fallback: number) => Number(process.env[name] ?? fallback);
|
||||
const EVENTS = size("EVENTS", 400), PASSES = size("PASSES", 4), HOLD_MS = size("HOLD_MS", 5), EVENT_KIB = size("EVENT_KIB", 2);
|
||||
const SERIAL = process.env.SERIAL === "1";
|
||||
process.env.PAPERCLIP_SECRETS_MASTER_KEY ??= randomBytes(32).toString("base64");
|
||||
|
||||
const keepAlive = setInterval(() => {}, 1_000);
|
||||
const temporary = await startEmbeddedPostgresTestDatabase("run-event-checkpoint-lock-");
|
||||
const appendDb = createDb(temporary.connectionString);
|
||||
const checkpointDb = createDb(temporary.connectionString);
|
||||
try {
|
||||
const [company] = await appendDb.insert(companies).values({ name: "Lock", issuePrefix: "LCK" }).returning();
|
||||
const [agent] = await appendDb.insert(agents).values({ companyId: company!.id, name: "Native" }).returning();
|
||||
const [issue] = await appendDb.insert(issues).values({ companyId: company!.id, title: "Streaming task" }).returning();
|
||||
const quantile = (values: number[], q: number) => [...values].sort((a, b) => a - b)[Math.min(values.length - 1, Math.floor(values.length * q))]!;
|
||||
const round = (value: number) => Number(value.toFixed(2));
|
||||
|
||||
async function pass(label: "baseline" | "candidate") {
|
||||
const append = (label === "baseline" ? baseline : candidate).appendHeartbeatRunEvent;
|
||||
const runId = randomUUID(), bootId = randomUUID(), leaseOwner = randomUUID();
|
||||
await appendDb.insert(heartbeatRuns).values({ id: runId, companyId: company!.id, agentId: agent!.id, status: "running",
|
||||
runtimeMode: "native", nativeIssueId: issue!.id, issueId: issue!.id,
|
||||
runnerProfileJson: { padding: randomBytes(3 * 1024).toString("base64") } });
|
||||
await appendDb.insert(nativeRunFinalizations).values({ runId, companyId: company!.id, issueId: issue!.id, phase: "observed",
|
||||
controllerBootId: bootId, controllerGeneration: 1, leaseOwner, leaseExpiresAt: new Date(Date.now() + 3_600_000) });
|
||||
const write = nativeRunnerCheckpointWriter(checkpointDb, { companyId: company!.id, issueId: issue!.id, runId,
|
||||
authorityRunId: runId, bootId, generation: 1, leaseOwner });
|
||||
const checkpoint = (records: Map<string, string>, changed: Map<string, string>, reset: boolean) => ({
|
||||
runId, records, changedRecords: changed, removedRecords: [], reset, workCommandIds: [], predecessor: null,
|
||||
runnerVersion: "bench", runnerDigest: `sha256:${"a".repeat(64)}`,
|
||||
recoveryEvidence: { runnerInstanceId: "bench", normalizedSessionId: "bench", authenticatedConnectionCount: 1, highestRecordedSourceSeq: 0 },
|
||||
restoreSessionDirectory() {},
|
||||
}) as unknown as Parameters<typeof write>[0];
|
||||
const records = new Map([["header", JSON.stringify({ padding: randomBytes(6 * 1024).toString("base64") })],
|
||||
["cursor", JSON.stringify({ ackedSourceSeq: 0 })]]);
|
||||
await write(checkpoint(records, new Map(records), true));
|
||||
const saves: number[] = [];
|
||||
let tail = Promise.resolve();
|
||||
const started = performance.now();
|
||||
for (let seq = 1; seq <= EVENTS; seq++) {
|
||||
const event = { sourceSeq: seq, eventType: "item.completed", text: randomBytes(EVENT_KIB * 768).toString("base64") };
|
||||
// The append commits before the controller ACKs, like onCommittedEvent.
|
||||
await appendDb.transaction(async tx => {
|
||||
await append(tx as unknown as typeof appendDb, { companyId: company!.id, agentId: agent!.id, runId,
|
||||
eventType: "item.completed", stream: "system", level: "info", payload: { prpEvent: event },
|
||||
nativeSource: { sourceInstanceId: "bench-runner", sourceEventId: `event-${seq}`, sourceSeq: seq,
|
||||
protocolSchemaVersion: 1, canonicalPayload: event } });
|
||||
if (HOLD_MS) await tx.execute(drizzleSql`select pg_sleep(${HOLD_MS / 1000})`);
|
||||
});
|
||||
const changed = new Map([[`event:${seq}`, JSON.stringify(event)], ["cursor", JSON.stringify({ ackedSourceSeq: seq })]]);
|
||||
for (const [key, value] of changed) records.set(key, value);
|
||||
// Checkpoint saves are serialized per controller and overlap the next append.
|
||||
tail = tail.then(async () => {
|
||||
const start = performance.now();
|
||||
await write(checkpoint(new Map(records), changed, false));
|
||||
saves.push(performance.now() - start);
|
||||
});
|
||||
if (SERIAL) await tail;
|
||||
}
|
||||
await tail;
|
||||
const elapsed = performance.now() - started;
|
||||
const [stored] = await checkpointDb.select({ count: drizzleSql<number>`count(*)::int` }).from(nativeRunnerCheckpoints)
|
||||
.where(eq(nativeRunnerCheckpoints.runId, runId));
|
||||
const events = await appendDb.select({ seq: heartbeatRunEvents.seq }).from(heartbeatRunEvents)
|
||||
.where(eq(heartbeatRunEvents.runId, runId)).orderBy(heartbeatRunEvents.seq);
|
||||
assert.equal(stored!.count, EVENTS + 2, "Every event row, the header and the cursor are stored");
|
||||
assert.deepEqual(events.map(row => row.seq), Array.from({ length: EVENTS }, (_, index) => index + 1));
|
||||
return { label, saves: saves.length, saveMedianMs: round(quantile(saves, 0.5)), saveP90Ms: round(quantile(saves, 0.9)),
|
||||
saveMaxMs: round(Math.max(...saves)), savesOver2Ms: saves.filter(value => value > 2).length,
|
||||
saveTotalMs: round(saves.reduce((sum, value) => sum + value, 0)), elapsedMs: round(elapsed) };
|
||||
}
|
||||
|
||||
await pass("candidate"); // Warm caches and the prepared-statement path once.
|
||||
const results = [];
|
||||
for (let index = 0; index < PASSES; index++) results.push(await pass(index % 2 === 0 ? "baseline" : "candidate"));
|
||||
console.log(JSON.stringify({ events: EVENTS, serial: SERIAL, holdMs: HOLD_MS, eventKiB: EVENT_KIB, results }, null, 2));
|
||||
} finally {
|
||||
clearInterval(keepAlive);
|
||||
await temporary.cleanup();
|
||||
}
|
||||
@@ -477,6 +477,74 @@ describeEmbeddedPostgres("cases routes", () => {
|
||||
expect(eventRows.filter((event) => event.runId === runId)).toHaveLength(eventRows.length);
|
||||
});
|
||||
|
||||
it("holds direct case status writes to the terminal handoff's primary-task authority", async () => {
|
||||
await enableCases();
|
||||
const company = await seedCompany("TRM");
|
||||
const owner = await seedAgent(company.id);
|
||||
const other = await seedAgent(company.id);
|
||||
const [primary] = await db.insert(issues).values({
|
||||
companyId: company.id,
|
||||
identifier: `${company.issuePrefix.toUpperCase()}-1`,
|
||||
title: "Primary case task",
|
||||
status: "done",
|
||||
assigneeAgentId: owner.id,
|
||||
}).returning();
|
||||
const [caseRow] = await db.insert(cases).values({
|
||||
companyId: company.id,
|
||||
caseNumber: 1,
|
||||
identifier: `${company.issuePrefix.toUpperCase()}-C1`,
|
||||
caseType: "customer",
|
||||
key: "accepted-fix",
|
||||
title: "Accepted fix",
|
||||
status: "in_review",
|
||||
workIssueId: primary!.id,
|
||||
}).returning();
|
||||
const agentActor = (agentId: string): Express.Request["actor"] => ({
|
||||
type: "agent",
|
||||
companyId: company.id,
|
||||
agentId,
|
||||
source: "agent_key",
|
||||
keyId: `key-${agentId}`,
|
||||
onBehalfOfUserId: null,
|
||||
onBehalfOfMemberships: [],
|
||||
});
|
||||
const otherHttp = request(app(agentActor(other.id)));
|
||||
const readCase = async () => (await db.select().from(cases).where(eq(cases.id, caseRow!.id)))[0]!;
|
||||
|
||||
for (const status of ["done", "cancelled"] as const) {
|
||||
const denied = await otherHttp.patch(`/api/cases/${caseRow!.id}`).send({ status }).expect(403);
|
||||
expect(denied.body.error).toBe(`Agents may complete only their own case work. ${owner.name} (agent ${owner.id}) owns primary task ${primary!.identifier} and records the terminal handoff. Ask that agent on ${primary!.identifier} to close the case.`);
|
||||
}
|
||||
const upsert = await otherHttp
|
||||
.post(`/api/companies/${company.id}/cases`)
|
||||
.send({ caseType: "customer", key: "accepted-fix", title: "Accepted fix", status: "done" })
|
||||
.expect(403);
|
||||
expect(upsert.body.error).toMatch(/^Agents may complete only their own case work\. /);
|
||||
expect(await readCase()).toMatchObject({ status: "in_review", completedAt: null });
|
||||
|
||||
// Fact edits and non-terminal status remain ordinary case writes.
|
||||
await otherHttp.patch(`/api/cases/${caseRow!.id}`).send({ title: "Accepted checkout fix" }).expect(200);
|
||||
await otherHttp.patch(`/api/cases/${caseRow!.id}`).send({ status: "in_progress" }).expect(200);
|
||||
|
||||
// The owner still closes through the terminal handoff, not a raw status write.
|
||||
const ownerHttp = request(app(agentActor(owner.id)));
|
||||
await ownerHttp.patch(`/api/cases/${caseRow!.id}`).send({ status: "done" }).expect(422);
|
||||
expect(await readCase()).toMatchObject({ status: "in_progress", completedAt: null });
|
||||
await ownerHttp.patch(`/api/cases/${caseRow!.id}`).send({ status: "cancelled" }).expect(200);
|
||||
const reopen = await otherHttp.patch(`/api/cases/${caseRow!.id}`).send({ status: "in_progress" }).expect(403);
|
||||
expect(reopen.body.error).toMatch(/^Agents may complete only their own case work\. /);
|
||||
|
||||
await request(app(boardActor)).patch(`/api/cases/${caseRow!.id}`).send({ status: "done" }).expect(200);
|
||||
expect(await readCase()).toMatchObject({ status: "done", completedAt: expect.any(Date) });
|
||||
|
||||
// An upsert without status keeps the locked row's status and completion.
|
||||
await otherHttp
|
||||
.post(`/api/companies/${company.id}/cases`)
|
||||
.send({ caseType: "customer", key: "accepted-fix", title: "Accepted checkout fix" })
|
||||
.expect(200);
|
||||
expect(await readCase()).toMatchObject({ status: "done", completedAt: expect.any(Date) });
|
||||
});
|
||||
|
||||
it("rejects cross-company agent access across the cases route surface", async () => {
|
||||
await enableCases();
|
||||
const ownCompany = await seedCompany("OWN");
|
||||
|
||||
@@ -4194,6 +4194,54 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => {
|
||||
} finally { await coordinator.stop(); vi.useRealTimers(); }
|
||||
});
|
||||
|
||||
it("finds terminal GitHub responses by native issue binding before legacy run context", async () => {
|
||||
const f = await toolReplyFixture();
|
||||
const issueId = f.conversation.issueId!;
|
||||
await db.update(heartbeatRuns).set({ status: "failed", updatedAt: new Date() }).where(eq(heartbeatRuns.id, f.run.id));
|
||||
// Newer runs of the same agent that do not bind this issue: one is natively
|
||||
// bound to another issue although its legacy context names this issue, and
|
||||
// one names another issue in its context. Neither may hide the stopped run.
|
||||
await db.insert(heartbeatRuns).values([
|
||||
{ companyId: f.companyId, agentId: f.assignedAgentId, status: "running", runtimeMode: "native",
|
||||
nativeIssueId: randomUUID(), contextSnapshot: { issueId }, createdAt: new Date(Date.now() + 60_000) },
|
||||
{ companyId: f.companyId, agentId: f.assignedAgentId, status: "running",
|
||||
contextSnapshot: { issueId: randomUUID() }, createdAt: new Date(Date.now() + 120_000) },
|
||||
]);
|
||||
const errors: unknown[] = [];
|
||||
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => errors.push(error) });
|
||||
try {
|
||||
await githubResponseCommentService(db, f.providerFetch).registerTerminalResponseWork(coordinator, () => true).ready;
|
||||
await expect.poll(() => [...f.responseComments.values()][0]?.body, { timeout: 5000 }).toContain("stopped before completing");
|
||||
await expect.poll(() => ({ next: coordinator.nextWakeAt(), active: idleWorkSnapshot().active }),
|
||||
{ timeout: 5000 }).toEqual({ next: null, active: 0 });
|
||||
expect(errors).toEqual([]);
|
||||
} finally { await coordinator.stop(); }
|
||||
});
|
||||
|
||||
it("keeps terminal GitHub responses waiting while a natively bound newer run is active", async () => {
|
||||
const f = await toolReplyFixture();
|
||||
const issueId = f.conversation.issueId!;
|
||||
await db.update(heartbeatRuns).set({ status: "failed", updatedAt: new Date() }).where(eq(heartbeatRuns.id, f.run.id));
|
||||
// The newer run binds this issue natively; its legacy context is ignored.
|
||||
await db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.assignedAgentId,
|
||||
status: "running", runtimeMode: "native", nativeIssueId: issueId, contextSnapshot: { issueId: randomUUID() },
|
||||
createdAt: new Date(Date.now() + 60_000) });
|
||||
const baseline = f.responseWrites.length;
|
||||
const errors: unknown[] = [];
|
||||
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError: error => errors.push(error) });
|
||||
try {
|
||||
await githubResponseCommentService(db, f.providerFetch).registerTerminalResponseWork(coordinator, () => true).ready;
|
||||
await expect.poll(() => ({ next: coordinator.nextWakeAt(), active: idleWorkSnapshot().active }),
|
||||
{ timeout: 5000 }).toEqual({ next: null, active: 0 });
|
||||
expect(f.responseWrites).toHaveLength(baseline);
|
||||
const [action] = await db.select().from(chatActions).where(and(eq(chatActions.endpointId, f.endpoint.id),
|
||||
eq(chatActions.kind, "github_response_comment")));
|
||||
expect(action).toMatchObject({ status: "processed" });
|
||||
expect(action.result?.final).not.toBe(true);
|
||||
expect(errors).toEqual([]);
|
||||
} finally { await coordinator.stop(); }
|
||||
});
|
||||
|
||||
it("settles a deleted Board-origin request without starving unrelated terminal GitHub replies", async () => {
|
||||
const invalid = await toolReplyFixture();
|
||||
const valid = await toolReplyFixture();
|
||||
|
||||
@@ -6,7 +6,41 @@ import { agents, chatActions, chatConversations, chatEndpointResources, chatEndp
|
||||
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { captureReviewWaitQueries, seedGitHubReviewWait, setGitHubReviewAssessment,
|
||||
type CapturedReviewWaitQuery } from "./helpers/github-review-wait.js";
|
||||
import { readInheritedGitHubReviewWait } from "../services/chat-channels/github/review-wait.js";
|
||||
import { readInheritedGitHubReviewWait, readInheritedGitHubReviewWaits } from "../services/chat-channels/github/review-wait.js";
|
||||
|
||||
const reviewWaitChanges = ["disabled", "inactive", "review_state", "review_agent", "repository", "repository_id",
|
||||
"thread", "publication", "identity", "endpoint_agent", "company"] as const;
|
||||
|
||||
async function applyReviewWaitChange(db: Db, f: Awaited<ReturnType<typeof seedGitHubReviewWait>>,
|
||||
change: typeof reviewWaitChanges[number]) {
|
||||
if (change === "disabled") await db.update(toolConnections).set({ enabled: false }).where(eq(toolConnections.id, f.connectionId));
|
||||
if (change === "inactive") await db.update(toolConnections).set({ status: "disabled" }).where(eq(toolConnections.id, f.connectionId));
|
||||
if (change === "review_state") await db.update(chatGitHubReviews).set({ state: "queued" }).where(eq(chatGitHubReviews.id, f.reviewId));
|
||||
if (change === "review_agent" || change === "endpoint_agent") {
|
||||
const [other] = await db.insert(agents).values({ companyId: f.companyId, name: "Other", adapterType: "process" }).returning();
|
||||
if (change === "review_agent") await db.update(heartbeatRuns).set({ agentId: other!.id }).where(eq(heartbeatRuns.id, f.reviewRunId));
|
||||
else await db.update(chatEndpoints).set({ assignedAgentId: other!.id }).where(eq(chatEndpoints.id, f.endpointId));
|
||||
}
|
||||
if (change === "repository") await db.update(chatEndpointResources).set({ providerResourceId: "other/repository" }).where(eq(chatEndpointResources.id, f.resourceId));
|
||||
if (change === "repository_id") await db.update(chatEndpointResources).set({ metadata: { providerRepositoryId: "43" } }).where(eq(chatEndpointResources.id, f.resourceId));
|
||||
if (change === "thread") await db.update(chatConversations).set({ externalThreadId: "github:synthetic/repository:8" }).where(eq(chatConversations.id, f.conversationId));
|
||||
if (change === "publication") await db.update(chatActions).set({ status: "received" }).where(eq(chatActions.id, f.publicationId));
|
||||
if (change === "identity") await db.update(runIdentityContexts).set({ status: "rejected" }).where(eq(runIdentityContexts.id, f.activeIdentityContextId!));
|
||||
if (change === "company") {
|
||||
const otherCompanyId = randomUUID();
|
||||
await db.insert(companies).values({ id: otherCompanyId, name: "Other", issuePrefix: otherCompanyId });
|
||||
f.run = { ...f.run, companyId: otherCompanyId };
|
||||
}
|
||||
}
|
||||
|
||||
/** Record the SQL text of every statement that the client sends. */
|
||||
async function withStatements<T>(db: Db, read: () => Promise<T>) {
|
||||
const client = db.$client as unknown as { unsafe: (query: string, ...rest: unknown[]) => unknown };
|
||||
const unsafe = client.unsafe;
|
||||
const sql: string[] = [];
|
||||
client.unsafe = (query: string, ...rest: unknown[]) => { sql.push(query); return unsafe.call(client, query, ...rest); };
|
||||
try { return { result: await read(), sql }; } finally { client.unsafe = unsafe; }
|
||||
}
|
||||
|
||||
describe("inherited GitHub review wait projection", () => {
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
@@ -54,32 +88,54 @@ describe("inherited GitHub review wait projection", () => {
|
||||
expect(await readInheritedGitHubReviewWait(db, f.run)).toEqual({ kind: "revoked" });
|
||||
});
|
||||
|
||||
it.each(["disabled", "inactive", "review_state", "review_agent", "repository", "repository_id", "thread", "publication", "identity", "endpoint_agent", "company"] as const)(
|
||||
it.each(reviewWaitChanges)(
|
||||
"continues to reject a changed %s binding", async change => {
|
||||
const f = await seedGitHubReviewWait(db);
|
||||
expect((await readInheritedGitHubReviewWait(db, f.run))?.kind).toBe("published");
|
||||
if (change === "disabled") await db.update(toolConnections).set({ enabled: false }).where(eq(toolConnections.id, f.connectionId));
|
||||
if (change === "inactive") await db.update(toolConnections).set({ status: "disabled" }).where(eq(toolConnections.id, f.connectionId));
|
||||
if (change === "review_state") await db.update(chatGitHubReviews).set({ state: "queued" }).where(eq(chatGitHubReviews.id, f.reviewId));
|
||||
if (change === "review_agent" || change === "endpoint_agent") {
|
||||
const [other] = await db.insert(agents).values({ companyId: f.companyId, name: "Other", adapterType: "process" }).returning();
|
||||
if (change === "review_agent") await db.update(heartbeatRuns).set({ agentId: other!.id }).where(eq(heartbeatRuns.id, f.reviewRunId));
|
||||
else await db.update(chatEndpoints).set({ assignedAgentId: other!.id }).where(eq(chatEndpoints.id, f.endpointId));
|
||||
}
|
||||
if (change === "repository") await db.update(chatEndpointResources).set({ providerResourceId: "other/repository" }).where(eq(chatEndpointResources.id, f.resourceId));
|
||||
if (change === "repository_id") await db.update(chatEndpointResources).set({ metadata: { providerRepositoryId: "43" } }).where(eq(chatEndpointResources.id, f.resourceId));
|
||||
if (change === "thread") await db.update(chatConversations).set({ externalThreadId: "github:synthetic/repository:8" }).where(eq(chatConversations.id, f.conversationId));
|
||||
if (change === "publication") await db.update(chatActions).set({ status: "received" }).where(eq(chatActions.id, f.publicationId));
|
||||
if (change === "identity") await db.update(runIdentityContexts).set({ status: "rejected" }).where(eq(runIdentityContexts.id, f.activeIdentityContextId!));
|
||||
if (change === "company") {
|
||||
const otherCompanyId = randomUUID();
|
||||
await db.insert(companies).values({ id: otherCompanyId, name: "Other", issuePrefix: otherCompanyId });
|
||||
f.run = { ...f.run, companyId: otherCompanyId };
|
||||
}
|
||||
await applyReviewWaitChange(db, f, change);
|
||||
expect((await readInheritedGitHubReviewWait(db, f.run))?.kind).not.toBe("published");
|
||||
expect((await readInheritedGitHubReviewWaits(db, [f.run]))[0]?.kind).not.toBe("published");
|
||||
},
|
||||
);
|
||||
|
||||
it("reads the waits of many runs with one review read and the same results", async () => {
|
||||
const [companyId, agentId] = [randomUUID(), randomUUID()];
|
||||
await db.insert(companies).values({ id: companyId, name: "Batch", issuePrefix: companyId });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", adapterType: "process" });
|
||||
const fixtures: Array<Awaited<ReturnType<typeof seedGitHubReviewWait>>> = [];
|
||||
for (const change of [null, ...reviewWaitChanges, "newer_head", "no_identity", "no_issue", null] as const) {
|
||||
const f = await seedGitHubReviewWait(db, change === "company" ? undefined : { companyId, agentId });
|
||||
if (change === "newer_head") {
|
||||
const [review] = await db.select().from(chatGitHubReviews).where(eq(chatGitHubReviews.id, f.reviewId));
|
||||
await db.insert(chatGitHubReviews).values({ ...review!, id: randomUUID(), deliveryId: randomUUID(),
|
||||
headSha: "2".repeat(40), state: "queued", createdAt: new Date(review!.createdAt.getTime() + 1_000) });
|
||||
} else if (change === "no_identity") f.run = { ...f.run, activeIdentityContextId: null };
|
||||
else if (change === "no_issue") f.run = { ...f.run, nativeIssueId: null };
|
||||
else if (change) await applyReviewWaitChange(db, f, change);
|
||||
fixtures.push(f);
|
||||
}
|
||||
// A run can be read twice in one pass.
|
||||
const [first] = fixtures;
|
||||
// The "company" wait moved its run to a third company; its own company
|
||||
// also has one published wait.
|
||||
const otherCompany = await seedGitHubReviewWait(db);
|
||||
const runs = [...fixtures.map(f => f.run), first!.run, otherCompany.run];
|
||||
const single = [];
|
||||
for (const run of runs) single.push(await readInheritedGitHubReviewWait(db, run));
|
||||
expect(single.filter(wait => wait?.kind === "published")).toHaveLength(4);
|
||||
// No identity, no task, and an endpoint of another agent have no inherited wait.
|
||||
expect(single.filter(wait => wait === null)).toHaveLength(3);
|
||||
expect(single.filter(wait => wait?.kind === "revoked")).toHaveLength(runs.length - 7);
|
||||
|
||||
const { result, sql } = await withStatements(db, () => readInheritedGitHubReviewWaits(db, runs));
|
||||
expect(result).toEqual(single);
|
||||
// One review read and one publication read for each company with a source
|
||||
// comment, not one of each for every run.
|
||||
expect(sql.filter(text => /join "chat_github_reviews"/i.test(text))).toHaveLength(2);
|
||||
expect(sql.filter(text => /from "chat_actions"/i.test(text))).toHaveLength(2);
|
||||
expect(await readInheritedGitHubReviewWaits(db, [])).toEqual([]);
|
||||
});
|
||||
|
||||
it("binds each call afresh while reusing the compiled query", async () => {
|
||||
const first = await seedGitHubReviewWait(db), second = await seedGitHubReviewWait(db);
|
||||
const queries: CapturedReviewWaitQuery[] = [];
|
||||
|
||||
@@ -384,6 +384,55 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut
|
||||
expect(reached).toHaveBeenCalled();
|
||||
}, 60_000);
|
||||
|
||||
// Daytona waves s9330 and s9331 (TM1): stalls of the same server outlived
|
||||
// the execution lease. Renewal found the lease lapsed and detached the
|
||||
// executor for "the next controller" with no shutdown handoff, and the
|
||||
// executor returned with the run still running. The next controller is this
|
||||
// same process; nothing may leave the run running with no recovery.
|
||||
it("recovers a run whose executor detached after its own lease lapsed, with no restart", async () => {
|
||||
const f = await seedRecoverableRun("SELF-DETACHED-LAPSED");
|
||||
let opened = 0;
|
||||
const reachedAgain = vi.fn();
|
||||
const backend = vi.fn((): NativeSessionBackend => {
|
||||
opened += 1;
|
||||
const first = opened === 1;
|
||||
const open = async () => {
|
||||
if (first) {
|
||||
// What the remote renewal's loss does: the lease lapsed during the
|
||||
// stall, and the executor is detached for the next controller.
|
||||
await f.db.update(nativeRunFinalizations).set({ leaseExpiresAt: new Date(Date.now() - 1_000) })
|
||||
.where(eq(nativeRunFinalizations.runId, f.runId));
|
||||
void detachNativeSessionsForRestart([f.runId]);
|
||||
throw new Error("runner stream lost while the controller was stopped");
|
||||
}
|
||||
reachedAgain();
|
||||
throw new Error("stop at provider dispatch");
|
||||
};
|
||||
return {
|
||||
async descriptor() {
|
||||
return { kind: "mock", name: "self-detached", version: "1", capabilities: {
|
||||
resume: true, typedEvents: true, steering: false, interruption: true, structuredResult: true },
|
||||
runtimeContextCapabilities: { instructions: "native", skills: "native", mcp: "native" } };
|
||||
},
|
||||
openSession: open,
|
||||
recoverSession: open,
|
||||
} as unknown as NativeSessionBackend;
|
||||
});
|
||||
const heartbeat = heartbeatService(f.db, { nativeSessionBackendFactory: backend });
|
||||
try {
|
||||
const { claims } = await heartbeat.recoverNativeRunsAfterRestart(new Date(), [f.runId]);
|
||||
expect(claims).toEqual([expect.objectContaining({ runId: f.runId })]);
|
||||
await heartbeat.drainActiveRunExecutions();
|
||||
// The same process takes the run back on its own, without a restart.
|
||||
await waitForCondition("the same process to take the run back", () => reachedAgain.mock.calls.length > 0, 15_000);
|
||||
} finally { await heartbeat.drainActiveRunExecutions(); }
|
||||
expect(reachedAgain).toHaveBeenCalled();
|
||||
const transitions = await f.db.select().from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.runId, f.runId),
|
||||
eq(heartbeatRunEvents.eventType, "native.recovery.transition")));
|
||||
expect(transitions.map(event => (event.payload as Record<string, unknown>).reason))
|
||||
.not.toContain("controller_still_alive");
|
||||
}, 60_000);
|
||||
|
||||
|
||||
async function shutdownDispositions(db: Awaited<ReturnType<typeof seedRecoverableRun>>["db"], runId: string) {
|
||||
const events = await db.select().from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.runId, runId),
|
||||
@@ -832,7 +881,9 @@ describeEmbeddedPostgres("heartbeat native recovery interrupted by graceful shut
|
||||
.where(eq(nativeRunFinalizations.runId, f.runId));
|
||||
const onClaim = vi.fn();
|
||||
expect(await claimNativeRestartRecoveries({ db: f.db, restartKind: "hard", runIds: [f.runId], onClaim }))
|
||||
.toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_still_alive" }]);
|
||||
.toEqual([{ kind: "awaiting_evidence", runId: f.runId, reason: "controller_still_alive",
|
||||
// This process's own live lease lapses by itself; recovery looks again then.
|
||||
retryAt: expect.any(Date) }]);
|
||||
expect(onClaim).not.toHaveBeenCalled();
|
||||
}, 60_000);
|
||||
|
||||
|
||||
@@ -3557,6 +3557,70 @@ describeEmbeddedPostgres("heartbeat orphaned process recovery", () => {
|
||||
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
["an assignment", {}],
|
||||
["a due monitor", { wakeReason: "issue_monitor_due" }],
|
||||
] as const)("retries %s run whose lease this process lost before adapter dispatch", async (_label, contextSnapshot) => {
|
||||
const { companyId, runId, issueId } = await seedRunFixture({
|
||||
adapterType: "paperclip_runner", agentStatus: "idle", runtimeMode: "legacy", contextSnapshot,
|
||||
});
|
||||
await db.update(heartbeatRuns).set({
|
||||
controllerBootId: controllerLeases.legacyControllerBootId,
|
||||
controllerProcess: currentControllerProcessStamp(),
|
||||
controllerLeaseExpiresAt: sql`clock_timestamp() - interval '1 second'`,
|
||||
executionStage: "preparing",
|
||||
runnerProfileJson: {
|
||||
adapterDispatch: { adapterType: "paperclip_runner" },
|
||||
remoteWorkspace: { schema: "paperclip.remote-workspace-run.v1", epoch: 6, state: "prepared",
|
||||
leaseId: randomUUID(), providerLeaseId: randomUUID(), workspaceId: randomUUID(),
|
||||
remoteCwd: "/home/daytona/paperclip-workspace", snapshotId: randomUUID() },
|
||||
},
|
||||
}).where(eq(heartbeatRuns.id, runId));
|
||||
|
||||
const heartbeat = heartbeatService(db);
|
||||
expect(await heartbeat.reapOrphanedRuns()).toEqual({ reaped: 1, runIds: [runId] });
|
||||
|
||||
const [reaped] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
||||
expect(reaped).toMatchObject({ status: "failed", errorCode: "process_lost",
|
||||
error: "Process lost -- server may have restarted; retrying once" });
|
||||
expect(reaped?.resultJson).toMatchObject({
|
||||
executionRecovery: { kind: "bootstrap", providerWorkStarted: false },
|
||||
processLossDiagnostic: { localCheck: "no_identifiers", retryEligible: true },
|
||||
});
|
||||
expect(await db.select().from(heartbeatRuns).where(and(
|
||||
eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId),
|
||||
))).toEqual([expect.objectContaining({ status: "scheduled_retry" })]);
|
||||
await heartbeat.reapOrphanedRuns();
|
||||
expect(await db.select().from(issueRecoveryActions)
|
||||
.where(eq(issueRecoveryActions.sourceIssueId, issueId))).toEqual([]);
|
||||
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a run this process dispatched held for reconciliation after its lease lapses", async () => {
|
||||
const { companyId, runId, issueId } = await seedRunFixture({
|
||||
adapterType: "paperclip_runner", agentStatus: "idle", runtimeMode: "legacy",
|
||||
});
|
||||
await db.update(heartbeatRuns).set({
|
||||
controllerBootId: controllerLeases.legacyControllerBootId,
|
||||
controllerProcess: currentControllerProcessStamp(),
|
||||
controllerLeaseExpiresAt: sql`clock_timestamp() - interval '1 second'`,
|
||||
executionStage: "dispatching",
|
||||
}).where(eq(heartbeatRuns.id, runId));
|
||||
|
||||
await heartbeatService(db).reapOrphanedRuns();
|
||||
|
||||
const [reaped] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
||||
expect(reaped).toMatchObject({ status: "failed", errorCode: "process_lost" });
|
||||
expect(reaped?.resultJson).not.toHaveProperty("executionRecovery");
|
||||
expect(await db.select().from(heartbeatRuns).where(and(
|
||||
eq(heartbeatRuns.companyId, companyId), eq(heartbeatRuns.retryOfRunId, runId),
|
||||
))).toEqual([]);
|
||||
expect(await db.select().from(issueRecoveryActions)
|
||||
.where(eq(issueRecoveryActions.sourceIssueId, issueId))).toEqual([
|
||||
expect.objectContaining({ cause: "legacy_execution_requires_reconciliation" }),
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps a lost preparation from an older build without a controller stamp in the charged lane", async () => {
|
||||
const { companyId, runId } = await seedRestartOrphanedLegacySetup("preparing");
|
||||
await db.update(heartbeatRuns).set({ runnerProfileJson: { adapterDispatch: { adapterType: "paperclip_runner" } } })
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
heartbeatRuns,
|
||||
externalAgentHolds,
|
||||
issues,
|
||||
issueThreadInteractions,
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
@@ -294,6 +295,62 @@ describeEmbeddedPostgres("heartbeat queued-run claim isolation", () => {
|
||||
expect(mockAdapterExecute).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
async function insertCardAnswerInterruptRun(fault?: "other-answer" | "other-resolver") {
|
||||
const { companyId, agentId } = await insertAgent();
|
||||
const userId = `card-owner-${randomUUID()}`;
|
||||
await db.insert(authUsers).values({ id: userId, name: "Card owner", email: `${userId}@paperclip.test`,
|
||||
createdAt: new Date(), updatedAt: new Date() });
|
||||
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: userId,
|
||||
status: "active", membershipRole: "owner" });
|
||||
const issueId = randomUUID();
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Website", status: "in_progress",
|
||||
assigneeAgentId: agentId, responsibleUserId: userId });
|
||||
const [interaction] = await db.insert(issueThreadInteractions).values({ companyId, issueId,
|
||||
kind: "request_confirmation", status: "accepted", payload: { version: 1, prompt: "Use the simpler layout?" },
|
||||
result: { version: 1, outcome: "accepted" }, createdByUserId: userId,
|
||||
resolvedByUserId: fault === "other-resolver" ? "another-user" : userId, resolvedAt: new Date() }).returning();
|
||||
const queueId = randomUUID();
|
||||
const { runId, wakeupRequestId } = await insertQueuedRun(companyId, agentId, {
|
||||
reason: "issue_commented",
|
||||
idempotencyKey: `queued-comment-interrupt:${queueId}`,
|
||||
requestedByActorType: "user",
|
||||
requestedByActorId: userId,
|
||||
payload: { issueId, interactionId: interaction!.id, explicitUserContinuation: { queuedCommentInterruptId: queueId } },
|
||||
}, new Date(Date.now() - 60_000));
|
||||
await db.insert(agentWakeupRequests).values({ id: queueId, companyId, agentId, source: "automation",
|
||||
triggerDetail: "system", reason: "issue_commented", status: "coalesced", runId,
|
||||
requestedByActorType: "user", requestedByActorId: userId,
|
||||
payload: { issueId, mutation: "interaction", interactionId: interaction!.id, interactionKind: "request_confirmation",
|
||||
interactionStatus: "accepted", queuedCommentInterrupt: { actorId: userId, requestedAt: new Date().toISOString() } } });
|
||||
await db.update(heartbeatRuns).set({ contextSnapshot: { issueId, taskId: issueId,
|
||||
interactionId: fault === "other-answer" ? randomUUID() : interaction!.id, interactionKind: "request_confirmation",
|
||||
interactionStatus: "accepted", queuedCommentSourceWakeIds: [queueId] } }).where(sql`${heartbeatRuns.id} = ${runId}`);
|
||||
return { runId, wakeupRequestId, userId };
|
||||
}
|
||||
|
||||
it("claims the successor of an interrupt that delivers a queued card answer", async () => {
|
||||
const { runId, userId } = await insertCardAnswerInterruptRun();
|
||||
|
||||
await expect(heartbeat.resumeQueuedRuns()).resolves.toBeUndefined();
|
||||
await heartbeat.drainActiveRunExecutions();
|
||||
|
||||
expect(await runStatus(runId)).toMatchObject({ status: "succeeded", errorCode: null });
|
||||
const [run] = await db.select({ responsibleUserId: heartbeatRuns.responsibleUserId }).from(heartbeatRuns)
|
||||
.where(sql`${heartbeatRuns.id} = ${runId}`);
|
||||
expect(run).toMatchObject({ responsibleUserId: userId });
|
||||
});
|
||||
|
||||
it.each(["other-answer", "other-resolver"] as const)(
|
||||
"rejects a card-answer interrupt whose %s does not match the receipt", async (fault) => {
|
||||
const { runId } = await insertCardAnswerInterruptRun(fault);
|
||||
|
||||
await expect(heartbeat.resumeQueuedRuns()).resolves.toBeUndefined();
|
||||
|
||||
expect(await runStatus(runId)).toMatchObject({ status: "cancelled", errorCode: "queued_run_claim_rejected" });
|
||||
expect(mockAdapterExecute).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps processing other agents' queued runs after one agent's run is rejected", async () => {
|
||||
const first = await insertAgent();
|
||||
const second = await insertAgent();
|
||||
|
||||
@@ -3,7 +3,7 @@ import { randomBytes } from "node:crypto";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { eq, inArray, sql } from "drizzle-orm";
|
||||
import { drizzle } from "drizzle-orm/postgres-js";
|
||||
import { agents, companies, createDb, heartbeatRunEvents, heartbeatRuns } from "@paperclipai/db";
|
||||
import { agents, companies, createDb, heartbeatRunEvents, heartbeatRuns, issues, nativeRunnerCheckpoints } from "@paperclipai/db";
|
||||
import { appendHeartbeatRunEvent } from "../services/heartbeat-run-events.js";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
|
||||
@@ -51,6 +51,7 @@ describeEmbeddedPostgres("atomic ordinary run events", () => {
|
||||
const fixtureCompanies = [companyId, otherCompanyId];
|
||||
await db.delete(heartbeatRunEvents).where(inArray(heartbeatRunEvents.companyId, fixtureCompanies));
|
||||
await db.delete(heartbeatRuns).where(inArray(heartbeatRuns.companyId, fixtureCompanies));
|
||||
await db.delete(issues).where(inArray(issues.companyId, fixtureCompanies));
|
||||
await db.delete(agents).where(inArray(agents.companyId, fixtureCompanies));
|
||||
await db.delete(companies).where(inArray(companies.id, fixtureCompanies));
|
||||
}
|
||||
@@ -145,7 +146,7 @@ describeEmbeddedPostgres("atomic ordinary run events", () => {
|
||||
expect((await readRun(runId)).nextEventSeq).toBe(2);
|
||||
expect(await readEvents(runId)).toEqual([committed.row]);
|
||||
const lockReads = statements.filter(query => query.startsWith("select ") &&
|
||||
query.includes('from "heartbeat_runs"') && query.endsWith("for update"));
|
||||
query.includes('from "heartbeat_runs"') && query.endsWith("for no key update"));
|
||||
expect(lockReads).toHaveLength(2);
|
||||
for (const query of lockReads) {
|
||||
expect(query).toMatch(/^select "company_id", "agent_id" from "heartbeat_runs" /);
|
||||
@@ -153,6 +154,53 @@ describeEmbeddedPostgres("atomic ordinary run events", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("serializes appenders without blocking child foreign key checks on the run", async () => {
|
||||
const runId = await makeRun();
|
||||
const [issue] = await db.insert(issues).values({ companyId, title: "Checkpointed task" }).returning();
|
||||
await db.update(heartbeatRuns).set({ nativeIssueId: issue!.id, runtimeMode: "native" })
|
||||
.where(eq(heartbeatRuns.id, runId));
|
||||
const native = (ordinal: number) => ({
|
||||
companyId, agentId, runId, eventType: "item.completed",
|
||||
nativeSource: { sourceInstanceId: "native-writer", sourceEventId: `held-${ordinal}`,
|
||||
sourceSeq: ordinal, protocolSchemaVersion: 1, canonicalPayload: { ordinal } },
|
||||
});
|
||||
let releaseHolder!: () => void;
|
||||
const held = new Promise<void>(resolve => { releaseHolder = resolve; });
|
||||
let holderLocked!: () => void;
|
||||
const locked = new Promise<void>(resolve => { holderLocked = resolve; });
|
||||
// An append whose transaction is still open holds the run lock, as an
|
||||
// event append does while its remaining statements run.
|
||||
const holder = otherDb.transaction(async tx => {
|
||||
await appendHeartbeatRunEvent(tx as unknown as typeof db, native(1));
|
||||
holderLocked();
|
||||
await held;
|
||||
});
|
||||
await locked;
|
||||
let secondSettled = false;
|
||||
const second = appendHeartbeatRunEvent(db, native(2)).finally(() => { secondSettled = true; });
|
||||
try {
|
||||
// A controller checkpoint row references the run row by foreign key.
|
||||
// Its insert must not wait for the open append.
|
||||
await db.transaction(async tx => {
|
||||
await tx.execute(sql`set local lock_timeout = '2s'`);
|
||||
await tx.insert(nativeRunnerCheckpoints).values({ companyId, issueId: issue!.id, runId,
|
||||
part: "event:1", material: { fixture: true } });
|
||||
});
|
||||
// Another appender still waits for the open append.
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
expect(secondSettled).toBe(false);
|
||||
} finally {
|
||||
releaseHolder();
|
||||
await holder;
|
||||
}
|
||||
expect((await second).row.seq).toBe(2);
|
||||
expect((await readEvents(runId)).map(row => [row.seq, row.sourceSeq])).toEqual([[1, 1], [2, 2]]);
|
||||
expect((await readRun(runId)).nextEventSeq).toBe(3);
|
||||
expect(await db.select({ part: nativeRunnerCheckpoints.part }).from(nativeRunnerCheckpoints)
|
||||
.where(eq(nativeRunnerCheckpoints.runId, runId))).toEqual([{ part: "event:1" }]);
|
||||
await db.delete(nativeRunnerCheckpoints).where(eq(nativeRunnerCheckpoints.runId, runId));
|
||||
});
|
||||
|
||||
it("rejects mismatched authority without changing either run", async () => {
|
||||
const runId = await makeRun();
|
||||
const otherRunId = "30000000-0000-4000-8000-000000000099";
|
||||
|
||||
@@ -5,14 +5,19 @@ import { agents, chatActions, chatConversations, chatDeliveries, chatEndpointRes
|
||||
runIdentityContexts, toolApplications, toolConnections, type Db } from "@paperclipai/db";
|
||||
import { defaultGitHubReviewPolicy } from "@paperclipai/shared";
|
||||
|
||||
export async function seedGitHubReviewWait(db: Db) {
|
||||
const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), runId = randomUUID();
|
||||
/** Seed one published inherited review wait. With `into`, the wait is added to
|
||||
* an existing company and agent. */
|
||||
export async function seedGitHubReviewWait(db: Db, into?: { companyId: string; agentId: string }) {
|
||||
const companyId = into?.companyId ?? randomUUID(), agentId = into?.agentId ?? randomUUID();
|
||||
const issueId = randomUUID(), runId = randomUUID();
|
||||
const reviewRunId = randomUUID(), reviewId = randomUUID(), endpointId = randomUUID(), resourceId = randomUUID();
|
||||
const conversationId = randomUUID(), commentId = randomUUID(), activeIdentityContextId = randomUUID();
|
||||
const applicationId = randomUUID(), connectionId = randomUUID(), publicationId = randomUUID();
|
||||
const headSha = "1".repeat(40), repository = "synthetic/repository", repositoryId = "42", pullNumber = 7;
|
||||
await db.insert(companies).values({ id: companyId, name: "Synthetic review", issuePrefix: companyId });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", adapterType: "process" });
|
||||
if (!into) {
|
||||
await db.insert(companies).values({ id: companyId, name: "Synthetic review", issuePrefix: companyId });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Reviewer", adapterType: "process" });
|
||||
}
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Review", assigneeAgentId: agentId });
|
||||
await db.insert(heartbeatRuns).values([
|
||||
{ id: runId, companyId, agentId, nativeIssueId: issueId, responsibleUserId: "operator", activeIdentityContextId },
|
||||
@@ -21,7 +26,7 @@ export async function seedGitHubReviewWait(db: Db) {
|
||||
await db.insert(issueComments).values({ id: commentId, companyId, issueId, authorUserId: "operator", body: "Review" });
|
||||
await db.insert(runIdentityContexts).values({ id: activeIdentityContextId, companyId, runId, revision: 1,
|
||||
responsibleUserId: "operator", messageId: commentId, cause: "test", correlationId: "test", status: "accepted" });
|
||||
await db.insert(toolApplications).values({ id: applicationId, companyId, name: "GitHub", type: "chat" });
|
||||
await db.insert(toolApplications).values({ id: applicationId, companyId, name: into ? `GitHub ${applicationId}` : "GitHub", type: "chat" });
|
||||
await db.insert(toolConnections).values({ id: connectionId, companyId, applicationId, name: "GitHub",
|
||||
uid: connectionId, transport: "chat_sdk", connectionPurpose: "channel", enabled: true, status: "active" });
|
||||
await db.insert(chatEndpoints).values({ id: endpointId, companyId, connectionId, provider: "github",
|
||||
|
||||
@@ -187,6 +187,62 @@ describe("runtime skill revision cache", () => {
|
||||
expect(await runtimeSkillCacheLockHolderExited(Buffer.from("not json"))).toBe(false);
|
||||
});
|
||||
|
||||
it("releases a lock whose holder ran in a deployment the platform replaced", async () => {
|
||||
// A Railway redeploy starts the server in a new process space, so a PID
|
||||
// proof never applies. The platform stopped the earlier deployment, which
|
||||
// held the same exclusive volume, before it started this one.
|
||||
const railway = { RAILWAY_PROJECT_ID: "project", RAILWAY_ENVIRONMENT_ID: "environment", RAILWAY_SERVICE_ID: "service",
|
||||
RAILWAY_DEPLOYMENT_ID: "deployment-new", RAILWAY_VOLUME_ID: "volume", RAILWAY_VOLUME_MOUNT_PATH: "/data" };
|
||||
for (const [key, value] of Object.entries(railway)) vi.stubEnv(key, value);
|
||||
try {
|
||||
const worker = { provider: "railway", projectId: "project", environmentId: "environment", serviceId: "service" };
|
||||
const holder = { bootId: randomUUID(), pid: 3, hostHash: "f".repeat(32), processStartedAt: null,
|
||||
deployment: { worker: { ...worker, deploymentId: "deployment-old" }, exclusiveVolume: true, volumeId: "volume" } };
|
||||
expect(await runtimeSkillCacheLockHolderExited(lockStamp(holder))).toBe(true);
|
||||
// Only a replaced deployment on the same exclusive volume is proof.
|
||||
const deployment = holder.deployment;
|
||||
for (const changed of [{ ...deployment, worker: { ...worker, deploymentId: "deployment-new" } },
|
||||
{ ...deployment, volumeId: "another-volume" }, { ...deployment, exclusiveVolume: false },
|
||||
{ ...deployment, worker: { ...worker, serviceId: "another-service", deploymentId: "deployment-old" } }]) {
|
||||
expect(await runtimeSkillCacheLockHolderExited(lockStamp({ ...holder, deployment: changed }))).toBe(false);
|
||||
}
|
||||
const { deployment: _omitted, ...withoutDeployment } = holder;
|
||||
expect(await runtimeSkillCacheLockHolderExited(lockStamp(withoutDeployment))).toBe(false);
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a lock held when the holder proof stalls or fails", async () => {
|
||||
// A distinct holder per case: a still-pending proof is joined by later waits on the same holder.
|
||||
const holder = () => ({ bootId: randomUUID(), pid: 3, hostHash: "f".repeat(32), processStartedAt: null });
|
||||
const startedAt = Date.now();
|
||||
expect(await runtimeSkillCacheLockHolderExited(lockStamp(holder()),
|
||||
{ timeoutMs: 50, prove: () => new Promise(() => {}) })).toBe(false);
|
||||
expect(Date.now() - startedAt).toBeLessThan(2_000);
|
||||
expect(await runtimeSkillCacheLockHolderExited(lockStamp(holder()),
|
||||
{ prove: async () => { throw new Error("database unavailable"); } })).toBe(false);
|
||||
expect(await runtimeSkillCacheLockHolderExited(lockStamp(holder()),
|
||||
{ prove: async () => ({ verdict: "gone", reason: "controller_stopped" }) })).toBe(true);
|
||||
});
|
||||
|
||||
it("joins a stalled holder proof instead of starting another read on every timeout", async () => {
|
||||
const holder = { bootId: randomUUID(), pid: 3, hostHash: "f".repeat(32), processStartedAt: null };
|
||||
let settle!: (proof: { verdict: "gone"; reason: "controller_stopped" }) => void;
|
||||
const prove = vi.fn(() => new Promise<{ verdict: "gone"; reason: "controller_stopped" }>(resolve => { settle = resolve; }));
|
||||
for (let attempt = 0; attempt < 5; attempt++) {
|
||||
expect(await runtimeSkillCacheLockHolderExited(lockStamp(holder), { timeoutMs: 10, prove })).toBe(false);
|
||||
}
|
||||
expect(prove).toHaveBeenCalledTimes(1);
|
||||
settle({ verdict: "gone", reason: "controller_stopped" });
|
||||
expect(await runtimeSkillCacheLockHolderExited(lockStamp(holder), { timeoutMs: 1_000, prove })).toBe(true);
|
||||
// A settled proof is not reused: the next wait asks again.
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
const fresh = vi.fn(async () => ({ verdict: "alive" as const, reason: "controller_lease_held" as const }));
|
||||
expect(await runtimeSkillCacheLockHolderExited(lockStamp(holder), { prove: fresh })).toBe(false);
|
||||
expect(fresh).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("fingerprints installed content and ownership, excluding cosmetic metadata", async () => {
|
||||
const spec = runtimeSkillCacheSpec(root, skill)!;
|
||||
expect(runtimeSkillCacheSpec(root, { ...skill, name: "Renamed", updatedAt: new Date(), metadata: { ...skill.metadata, starred: true, ref: "new-branch" } })!.fingerprint).toBe(spec.fingerprint);
|
||||
|
||||
@@ -159,6 +159,7 @@ const {
|
||||
registerIssueStateRecoveryWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve(),
|
||||
watchdogs: { reconciliationSnapshot: () => ({ revision: "startup-watchdogs:1", reconciled: true }), stop: vi.fn(async () => {}) } })),
|
||||
registerDeferredReceiptWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve() })),
|
||||
registerProviderLimitResumeWork: vi.fn((_coordinator: unknown, _canRun: () => boolean, _prepareChatRetry?: () => unknown) => ({ ready: Promise.resolve() })),
|
||||
registerRunDispatchWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve(),
|
||||
retries: { reconciliationSnapshot: () => ({ revision: "startup-retries:1", reconciled: true }), stop: vi.fn(async () => {}) } })),
|
||||
registerScheduledRetryCancellationWork: vi.fn((_coordinator: unknown, _canRun: () => boolean) => ({ ready: Promise.resolve() })),
|
||||
@@ -1048,7 +1049,14 @@ describe("startServer feedback export wiring", () => {
|
||||
expect(heartbeatServiceMock.registerActiveRunSilenceWork).toHaveBeenCalledTimes(enabled ? 1 : 0);
|
||||
expect(heartbeatServiceMock.registerRunDispatchWork).toHaveBeenCalledTimes(enabled ? 1 : 0);
|
||||
expect(heartbeatServiceMock.registerDeferredReceiptWork).toHaveBeenCalledTimes(enabled ? 1 : 0);
|
||||
expect(heartbeatServiceMock.registerProviderLimitResumeWork).toHaveBeenCalledTimes(enabled ? 1 : 0);
|
||||
expect(heartbeatServiceMock.resumeQueuedRuns).not.toHaveBeenCalled();
|
||||
if (enabled) {
|
||||
const [limitCoordinator, limitAdmitted, chatRetry] = heartbeatServiceMock.registerProviderLimitResumeWork.mock.calls[0];
|
||||
expect(limitCoordinator).toBe((await createAppMock.mock.results.at(-1)!.value).locals.deliveryWork);
|
||||
expect(limitAdmitted()).toBe(true);
|
||||
expect(typeof chatRetry).toBe("function");
|
||||
}
|
||||
if (enabled) {
|
||||
const [coordinator, admitted] = heartbeatServiceMock.registerRunDispatchWork.mock.calls[0];
|
||||
const app = await createAppMock.mock.results.at(-1)!.value;
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
classifyEventLoopStall,
|
||||
startEventLoopStallMonitor,
|
||||
type EventLoopStall,
|
||||
} from "./event-loop-stall-monitor.js";
|
||||
|
||||
const waitFor = async (predicate: () => boolean, timeoutMs = 5_000) => {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (!predicate()) {
|
||||
if (Date.now() > deadline) throw new Error("timed out waiting for the stall report");
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
};
|
||||
|
||||
const blockWithCpu = (ms: number) => {
|
||||
const until = Date.now() + ms;
|
||||
let spin = 0;
|
||||
while (Date.now() < until) spin += 1;
|
||||
return spin;
|
||||
};
|
||||
|
||||
// Blocks the main thread without using CPU, like a sync read on a stalled disk
|
||||
// or a sync child process.
|
||||
const blockOffCpu = (ms: number) => {
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
||||
};
|
||||
|
||||
describe("event-loop stall monitor", () => {
|
||||
const stops: Array<() => void> = [];
|
||||
afterEach(() => {
|
||||
while (stops.length > 0) stops.pop()!();
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
const start = (options: Parameters<typeof startEventLoopStallMonitor>[0]) => {
|
||||
const monitor = startEventLoopStallMonitor(options);
|
||||
stops.push(monitor.stop);
|
||||
return monitor;
|
||||
};
|
||||
|
||||
it("records a main-thread CPU block with its duration and CPU time", async () => {
|
||||
const stalls: EventLoopStall[] = [];
|
||||
const caused = () => stalls.filter((stall) => stall.stallMs >= 700);
|
||||
start({ log: (stall) => stalls.push(stall), intervalMs: 20, thresholdMs: 250, probes: { readCgroupThrottledUsec: async () => null } });
|
||||
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||
|
||||
blockWithCpu(800);
|
||||
await waitFor(() => caused().length > 0);
|
||||
|
||||
// A loaded runner can add unrelated pauses; check the one this test caused.
|
||||
const [stall] = caused();
|
||||
expect(stall!.cpuUserMs + stall!.cpuSystemMs).toBeGreaterThanOrEqual(400);
|
||||
expect(stall!.likelyCause).toBe("main_thread_cpu");
|
||||
expect(Date.parse(stall!.stallEndedAt) - Date.parse(stall!.stallStartedAt)).toBeGreaterThanOrEqual(700);
|
||||
});
|
||||
|
||||
it("records an off-CPU block, such as sync I/O, as blocked_off_cpu", async () => {
|
||||
const stalls: EventLoopStall[] = [];
|
||||
const caused = () => stalls.filter((stall) => stall.stallMs >= 700);
|
||||
start({ log: (stall) => stalls.push(stall), intervalMs: 20, thresholdMs: 250, probes: { readCgroupThrottledUsec: async () => null } });
|
||||
await new Promise((resolve) => setTimeout(resolve, 60));
|
||||
|
||||
blockOffCpu(800);
|
||||
await waitFor(() => caused().length > 0);
|
||||
|
||||
const [stall] = caused();
|
||||
expect(stall!.likelyCause).toBe("blocked_off_cpu");
|
||||
});
|
||||
|
||||
const fakeProbes = (state: { monotonic: number; throttledUsec: number | null; fsRead: number }) => ({
|
||||
monotonicNow: () => state.monotonic,
|
||||
wallNow: () => 1_794_298_792_000 + state.monotonic,
|
||||
cpuUsage: () => ({ user: 0, system: 0 }),
|
||||
resourceUsage: () => ({
|
||||
majorPageFault: 0, minorPageFault: 0, fsRead: state.fsRead, fsWrite: 0,
|
||||
voluntaryContextSwitches: 0, involuntaryContextSwitches: 0,
|
||||
}),
|
||||
readCgroupThrottledUsec: async () => state.throttledUsec,
|
||||
});
|
||||
|
||||
it("stays silent while the loop is responsive and after stop", async () => {
|
||||
vi.useFakeTimers();
|
||||
const state = { monotonic: 0, throttledUsec: null, fsRead: 0 };
|
||||
const log = vi.fn();
|
||||
const monitor = start({ log, intervalMs: 500, thresholdMs: 2_000, gcEntries: () => [], probes: fakeProbes(state) });
|
||||
for (let tick = 1; tick <= 10; tick++) {
|
||||
state.monotonic = tick * 500 + 100;
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
}
|
||||
expect(log).not.toHaveBeenCalled();
|
||||
|
||||
monitor.stop();
|
||||
state.monotonic += 60_000;
|
||||
await vi.advanceTimersByTimeAsync(5_000);
|
||||
expect(log).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the I/O deltas of the stall while the cgroup read is pending", async () => {
|
||||
vi.useFakeTimers();
|
||||
const state = { monotonic: 0, throttledUsec: 5_000_000 as number | null, fsRead: 10 };
|
||||
const stalls: EventLoopStall[] = [];
|
||||
start({ log: (stall) => stalls.push(stall), intervalMs: 500, thresholdMs: 2_000, gcEntries: () => [], probes: fakeProbes(state) });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
|
||||
state.monotonic = 100_500;
|
||||
state.fsRead = 4_010;
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
|
||||
expect(stalls).toHaveLength(1);
|
||||
expect(stalls[0]).toMatchObject({ fsReads: 4_000, cgroupThrottledMs: 0, likelyCause: "blocked_off_cpu" });
|
||||
});
|
||||
|
||||
it("reports cgroup throttling measured across the stall", async () => {
|
||||
vi.useFakeTimers();
|
||||
let monotonic = 0;
|
||||
let throttledUsec = 1_000_000;
|
||||
const stalls: EventLoopStall[] = [];
|
||||
start({
|
||||
log: (stall) => stalls.push(stall),
|
||||
intervalMs: 500,
|
||||
thresholdMs: 2_000,
|
||||
gcEntries: () => [],
|
||||
probes: {
|
||||
monotonicNow: () => monotonic,
|
||||
wallNow: () => 1_794_298_792_000 + monotonic,
|
||||
cpuUsage: () => ({ user: 0, system: 0 }),
|
||||
resourceUsage: () => ({
|
||||
majorPageFault: 0, minorPageFault: 0, fsRead: 0, fsWrite: 0,
|
||||
voluntaryContextSwitches: 0, involuntaryContextSwitches: 0,
|
||||
}),
|
||||
readCgroupThrottledUsec: async () => throttledUsec,
|
||||
},
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
|
||||
monotonic = 100_500;
|
||||
throttledUsec += 90_000_000;
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
|
||||
expect(stalls).toHaveLength(1);
|
||||
expect(stalls[0]).toMatchObject({
|
||||
stallMs: 100_000,
|
||||
stallStartedAt: "2026-11-10T08:19:52.000Z",
|
||||
stallEndedAt: "2026-11-10T08:21:32.500Z",
|
||||
cgroupThrottledMs: 90_000,
|
||||
likelyCause: "cpu_throttled",
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies each cause from the measured deltas", () => {
|
||||
const base = { stallMs: 100_000, monotonicElapsedMs: 100_500, wallElapsedMs: 100_500, cpuMs: 0, gcPauseMs: 0, majorPageFaults: 0, cgroupThrottledMs: null };
|
||||
expect(classifyEventLoopStall(base)).toBe("blocked_off_cpu");
|
||||
expect(classifyEventLoopStall({ ...base, cpuMs: 99_000 })).toBe("main_thread_cpu");
|
||||
expect(classifyEventLoopStall({ ...base, cpuMs: 99_000, gcPauseMs: 95_000 })).toBe("gc");
|
||||
expect(classifyEventLoopStall({ ...base, majorPageFaults: 50_000 })).toBe("memory_paging");
|
||||
expect(classifyEventLoopStall({ ...base, cgroupThrottledMs: 80_000 })).toBe("cpu_throttled");
|
||||
expect(classifyEventLoopStall({ ...base, monotonicElapsedMs: 500 })).toBe("host_suspended");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,288 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { PerformanceObserver, performance, type PerformanceEntry } from "node:perf_hooks";
|
||||
|
||||
// Records a long event-loop block as one local log line. Nothing leaves the
|
||||
// process: this is neither the Telemetry nor the Observability path.
|
||||
//
|
||||
// A timer that should fire every `intervalMs` measures how late it ran. When it
|
||||
// is late by `thresholdMs` or more, the line carries the process-level deltas
|
||||
// that tell the usual causes apart:
|
||||
// - main-thread CPU work (sync JSON, regex, hashing, compression): CPU ≈ stall
|
||||
// - garbage collection: GC pause time ≈ stall
|
||||
// - memory paging: many major page faults
|
||||
// - host suspend: wall clock advanced far more than the monotonic clock
|
||||
// - CPU throttling by the container: cgroup throttled time grows
|
||||
// - sync file I/O or a sync child process: little CPU, none of the above
|
||||
//
|
||||
// The timer reads only process counters (and, every ten seconds, the cgroup's
|
||||
// cpu.stat). It never queries the database or the network, so it does not keep
|
||||
// an idle instance or its database awake; it is unref'd and stopped on shutdown.
|
||||
export type EventLoopStallCause =
|
||||
| "gc"
|
||||
| "main_thread_cpu"
|
||||
| "memory_paging"
|
||||
| "host_suspended"
|
||||
| "cpu_throttled"
|
||||
| "blocked_off_cpu";
|
||||
|
||||
export type EventLoopStall = {
|
||||
stallMs: number;
|
||||
monotonicElapsedMs: number;
|
||||
wallElapsedMs: number;
|
||||
stallStartedAt: string;
|
||||
stallEndedAt: string;
|
||||
likelyCause: EventLoopStallCause;
|
||||
cpuUserMs: number;
|
||||
cpuSystemMs: number;
|
||||
gcPauseMs: number;
|
||||
gcCount: number;
|
||||
majorPageFaults: number;
|
||||
minorPageFaults: number;
|
||||
fsReads: number;
|
||||
fsWrites: number;
|
||||
voluntaryContextSwitches: number;
|
||||
involuntaryContextSwitches: number;
|
||||
cgroupThrottledMs: number | null;
|
||||
rssBytes: number;
|
||||
heapUsedBytes: number;
|
||||
heapTotalBytes: number;
|
||||
externalBytes: number;
|
||||
arrayBuffersBytes: number;
|
||||
processUptimeSec: number;
|
||||
};
|
||||
|
||||
type ResourceSample = Pick<
|
||||
NodeJS.ResourceUsage,
|
||||
| "majorPageFault"
|
||||
| "minorPageFault"
|
||||
| "fsRead"
|
||||
| "fsWrite"
|
||||
| "voluntaryContextSwitches"
|
||||
| "involuntaryContextSwitches"
|
||||
>;
|
||||
|
||||
export type EventLoopStallProbes = {
|
||||
monotonicNow: () => number;
|
||||
wallNow: () => number;
|
||||
cpuUsage: () => NodeJS.CpuUsage;
|
||||
resourceUsage: () => ResourceSample;
|
||||
memoryUsage: () => NodeJS.MemoryUsage;
|
||||
uptimeSec: () => number;
|
||||
// Total time this process's cgroup was CPU-throttled, in microseconds, or null.
|
||||
readCgroupThrottledUsec: () => Promise<number | null>;
|
||||
};
|
||||
|
||||
export type EventLoopStallMonitorOptions = {
|
||||
log: (stall: EventLoopStall) => void;
|
||||
intervalMs?: number;
|
||||
thresholdMs?: number;
|
||||
probes?: Partial<EventLoopStallProbes>;
|
||||
// GC pause entries can be supplied by a test; by default a GC observer is used.
|
||||
gcEntries?: () => readonly Pick<PerformanceEntry, "startTime" | "duration">[];
|
||||
};
|
||||
|
||||
export const EVENT_LOOP_STALL_INTERVAL_MS = 1_500;
|
||||
export const EVENT_LOOP_STALL_THRESHOLD_MS = 2_000;
|
||||
const CGROUP_SAMPLE_INTERVAL_MS = 10_000;
|
||||
const MAX_GC_ENTRIES = 512;
|
||||
const MAJOR_FAULTS_FOR_PAGING = 1_000;
|
||||
|
||||
async function readCgroupV2ThrottledUsec(): Promise<number | null> {
|
||||
if (process.platform !== "linux") return null;
|
||||
try {
|
||||
const stat = await readFile("/sys/fs/cgroup/cpu.stat", "utf8");
|
||||
const match = /^throttled_usec\s+(\d+)$/m.exec(stat);
|
||||
return match ? Number(match[1]) : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const defaultProbes: EventLoopStallProbes = {
|
||||
monotonicNow: () => performance.now(),
|
||||
wallNow: () => Date.now(),
|
||||
cpuUsage: () => process.cpuUsage(),
|
||||
resourceUsage: () => process.resourceUsage(),
|
||||
memoryUsage: () => process.memoryUsage(),
|
||||
uptimeSec: () => process.uptime(),
|
||||
readCgroupThrottledUsec: readCgroupV2ThrottledUsec,
|
||||
};
|
||||
|
||||
export function classifyEventLoopStall(input: {
|
||||
stallMs: number;
|
||||
monotonicElapsedMs: number;
|
||||
wallElapsedMs: number;
|
||||
cpuMs: number;
|
||||
gcPauseMs: number;
|
||||
majorPageFaults: number;
|
||||
cgroupThrottledMs: number | null;
|
||||
}): EventLoopStallCause {
|
||||
const half = input.stallMs / 2;
|
||||
if (input.wallElapsedMs - input.monotonicElapsedMs >= half) return "host_suspended";
|
||||
if (input.gcPauseMs >= half) return "gc";
|
||||
if (input.majorPageFaults >= MAJOR_FAULTS_FOR_PAGING) return "memory_paging";
|
||||
if (input.cgroupThrottledMs !== null && input.cgroupThrottledMs >= half) return "cpu_throttled";
|
||||
if (input.cpuMs >= half) return "main_thread_cpu";
|
||||
return "blocked_off_cpu";
|
||||
}
|
||||
|
||||
export function startEventLoopStallMonitor(options: EventLoopStallMonitorOptions): { stop: () => void } {
|
||||
const probes = { ...defaultProbes, ...options.probes };
|
||||
const intervalMs = options.intervalMs ?? EVENT_LOOP_STALL_INTERVAL_MS;
|
||||
const thresholdMs = options.thresholdMs ?? EVENT_LOOP_STALL_THRESHOLD_MS;
|
||||
|
||||
let gcObserver: PerformanceObserver | null = null;
|
||||
const observedGc: Pick<PerformanceEntry, "startTime" | "duration">[] = [];
|
||||
let gcEntries = options.gcEntries;
|
||||
if (!gcEntries) {
|
||||
try {
|
||||
gcObserver = new PerformanceObserver((list) => {
|
||||
for (const entry of list.getEntries()) {
|
||||
observedGc.push({ startTime: entry.startTime, duration: entry.duration });
|
||||
}
|
||||
if (observedGc.length > MAX_GC_ENTRIES) observedGc.splice(0, observedGc.length - MAX_GC_ENTRIES);
|
||||
});
|
||||
gcObserver.observe({ entryTypes: ["gc"] });
|
||||
} catch {
|
||||
gcObserver = null;
|
||||
}
|
||||
gcEntries = () => observedGc;
|
||||
}
|
||||
|
||||
let lastMonotonic = probes.monotonicNow();
|
||||
let lastWall = probes.wallNow();
|
||||
let lastCpu = probes.cpuUsage();
|
||||
let lastResources = probes.resourceUsage();
|
||||
let cgroupBaseline: number | null = null;
|
||||
let cgroupSampledAt = Number.NEGATIVE_INFINITY;
|
||||
let cgroupReading = false;
|
||||
let stopped = false;
|
||||
|
||||
const sampleCgroup = () => {
|
||||
if (cgroupReading || stopped) return;
|
||||
cgroupReading = true;
|
||||
void probes.readCgroupThrottledUsec()
|
||||
.then((value) => { cgroupBaseline = value; })
|
||||
.catch(() => { cgroupBaseline = null; })
|
||||
.finally(() => { cgroupReading = false; });
|
||||
};
|
||||
|
||||
const check = () => {
|
||||
const monotonic = probes.monotonicNow();
|
||||
const wall = probes.wallNow();
|
||||
const monotonicElapsedMs = monotonic - lastMonotonic;
|
||||
const wallElapsedMs = wall - lastWall;
|
||||
// A host suspend may stop the monotonic clock, so use the larger of the two.
|
||||
const stallMs = Math.max(monotonicElapsedMs, wallElapsedMs) - intervalMs;
|
||||
if (stallMs >= thresholdMs) {
|
||||
const cpu = probes.cpuUsage();
|
||||
const resources = probes.resourceUsage();
|
||||
const memory = probes.memoryUsage();
|
||||
const windowStart = lastMonotonic;
|
||||
let gcPauseMs = 0;
|
||||
let gcCount = 0;
|
||||
for (const entry of gcEntries!()) {
|
||||
if (entry.startTime + entry.duration < windowStart || entry.startTime > monotonic) continue;
|
||||
gcPauseMs += entry.duration;
|
||||
gcCount += 1;
|
||||
}
|
||||
const cpuUserMs = (cpu.user - lastCpu.user) / 1000;
|
||||
const cpuSystemMs = (cpu.system - lastCpu.system) / 1000;
|
||||
// Compute every delta now: the cgroup read below is asynchronous, and
|
||||
// later ticks replace the baselines before it settles.
|
||||
const previous = lastResources;
|
||||
const majorPageFaults = resources.majorPageFault - previous.majorPageFault;
|
||||
const minorPageFaults = resources.minorPageFault - previous.minorPageFault;
|
||||
const fsReads = resources.fsRead - previous.fsRead;
|
||||
const fsWrites = resources.fsWrite - previous.fsWrite;
|
||||
const voluntaryContextSwitches = resources.voluntaryContextSwitches - previous.voluntaryContextSwitches;
|
||||
const involuntaryContextSwitches = resources.involuntaryContextSwitches - previous.involuntaryContextSwitches;
|
||||
const uptimeSec = Math.round(probes.uptimeSec());
|
||||
const baseline = cgroupBaseline;
|
||||
const stallStartedAt = new Date(lastWall).toISOString();
|
||||
const stallEndedAt = new Date(wall).toISOString();
|
||||
const report = (cgroupThrottledMs: number | null) => {
|
||||
const rounded = Math.round(stallMs);
|
||||
options.log({
|
||||
stallMs: rounded,
|
||||
monotonicElapsedMs: Math.round(monotonicElapsedMs),
|
||||
wallElapsedMs: Math.round(wallElapsedMs),
|
||||
stallStartedAt,
|
||||
stallEndedAt,
|
||||
likelyCause: classifyEventLoopStall({
|
||||
stallMs: rounded,
|
||||
monotonicElapsedMs,
|
||||
wallElapsedMs,
|
||||
cpuMs: cpuUserMs + cpuSystemMs,
|
||||
gcPauseMs,
|
||||
majorPageFaults,
|
||||
cgroupThrottledMs,
|
||||
}),
|
||||
cpuUserMs: Math.round(cpuUserMs),
|
||||
cpuSystemMs: Math.round(cpuSystemMs),
|
||||
gcPauseMs: Math.round(gcPauseMs),
|
||||
gcCount,
|
||||
majorPageFaults,
|
||||
minorPageFaults,
|
||||
fsReads,
|
||||
fsWrites,
|
||||
voluntaryContextSwitches,
|
||||
involuntaryContextSwitches,
|
||||
cgroupThrottledMs,
|
||||
rssBytes: memory.rss,
|
||||
heapUsedBytes: memory.heapUsed,
|
||||
heapTotalBytes: memory.heapTotal,
|
||||
externalBytes: memory.external,
|
||||
arrayBuffersBytes: memory.arrayBuffers,
|
||||
processUptimeSec: uptimeSec,
|
||||
});
|
||||
};
|
||||
// Throttled time is read after the stall; the baseline is at most one
|
||||
// sampling interval older than the stall start, so the delta can include
|
||||
// a few seconds before it.
|
||||
if (baseline === null) {
|
||||
report(null);
|
||||
} else {
|
||||
void probes.readCgroupThrottledUsec()
|
||||
.then((after) => stopped ? undefined : report(after === null ? null : Math.round((after - baseline) / 1000)))
|
||||
.catch(() => report(null));
|
||||
}
|
||||
cgroupSampledAt = Number.NEGATIVE_INFINITY;
|
||||
lastCpu = cpu;
|
||||
lastResources = resources;
|
||||
} else {
|
||||
lastCpu = probes.cpuUsage();
|
||||
lastResources = probes.resourceUsage();
|
||||
}
|
||||
lastMonotonic = monotonic;
|
||||
lastWall = wall;
|
||||
if (monotonic - cgroupSampledAt >= CGROUP_SAMPLE_INTERVAL_MS) {
|
||||
cgroupSampledAt = monotonic;
|
||||
sampleCgroup();
|
||||
}
|
||||
};
|
||||
|
||||
// One pending unref'd timeout, re-armed after each check. Server startup
|
||||
// creates no interval timers, and this probe is not a work scan.
|
||||
let timer: NodeJS.Timeout | null = null;
|
||||
const arm = () => {
|
||||
if (stopped) return;
|
||||
timer = setTimeout(() => {
|
||||
timer = null;
|
||||
check();
|
||||
arm();
|
||||
}, intervalMs);
|
||||
(timer as Partial<NodeJS.Timeout>).unref?.();
|
||||
};
|
||||
arm();
|
||||
sampleCgroup();
|
||||
cgroupSampledAt = lastMonotonic;
|
||||
|
||||
return {
|
||||
stop: () => {
|
||||
stopped = true;
|
||||
if (timer) clearTimeout(timer);
|
||||
gcObserver?.disconnect();
|
||||
},
|
||||
};
|
||||
}
|
||||
+15
-1
@@ -132,6 +132,7 @@ import { drainHttpRequestWork } from "./middleware/idle-admission.js";
|
||||
import { initializeCloudRuntimeConfig } from "./services/cloud-runtime-config.js";
|
||||
import { loadCloudBootstrapConfig, loadConfig, type Config } from "./config.js";
|
||||
import { logger } from "./middleware/logger.js";
|
||||
import { startEventLoopStallMonitor } from "./event-loop-stall-monitor.js";
|
||||
import { setStartupRecoveryPhase } from "./startup-recovery-state.js";
|
||||
import {
|
||||
StartupRefusalError,
|
||||
@@ -951,7 +952,8 @@ async function startServerWithDatabaseTeardown(
|
||||
logger.warn({ scope: cloudQualification.scope, blockerCodes: cloudQualification.blockers.map((blocker) => blocker.code) }, "Cloud configuration and package qualification has blockers");
|
||||
}
|
||||
const idleDeadlineOwners: IdleDeadlineOwners = {};
|
||||
// createApp fills the chat Retry callback; the continuation worker reads it.
|
||||
// createApp fills the chat Retry callback; the continuation and
|
||||
// provider-limit Retry workers read it.
|
||||
const budgetResumeDelivery: BudgetResumeDelivery = {};
|
||||
const app = await createApp(db as any, {
|
||||
idleDeadlineOwners,
|
||||
@@ -1089,6 +1091,13 @@ async function startServerWithDatabaseTeardown(
|
||||
});
|
||||
});
|
||||
startupListenerBound = true;
|
||||
// A blocked event loop lapses every controller lease and freezes every
|
||||
// request, so record each long block with the deltas that name its class.
|
||||
const eventLoopStallMonitor = startEventLoopStallMonitor({
|
||||
log: (stall) => logger.warn({ eventLoopStall: stall }, `event loop blocked for ${stall.stallMs} ms (likely ${stall.likelyCause})`),
|
||||
});
|
||||
// A failed startup closes the listener without the ordered shutdown path.
|
||||
server.once("close", () => eventLoopStallMonitor.stop());
|
||||
// The factory publishes the verified numeric endpoint on listening. Native
|
||||
// recovery must never fall back to a configured/public URL if it is absent.
|
||||
resolveLocalRuntimeApiUrl();
|
||||
@@ -1771,6 +1780,10 @@ async function startServerWithDatabaseTeardown(
|
||||
}
|
||||
if (config.heartbeatSchedulerEnabled) await heartbeat.registerDeferredReceiptWork(deliveryWork,
|
||||
() => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped).ready;
|
||||
// A connected conversation's Retry needs the chat callback createApp registered.
|
||||
if (config.heartbeatSchedulerEnabled) await heartbeat.registerProviderLimitResumeWork(deliveryWork,
|
||||
() => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped,
|
||||
() => budgetResumeDelivery.prepareChatRetry).ready;
|
||||
if (config.heartbeatSchedulerEnabled) {
|
||||
const work = heartbeat.registerRunDispatchWork(deliveryWork,
|
||||
() => !isIdleTaskDrainActive() && !isWarmStandby() && !heartbeatSchedulerStopped);
|
||||
@@ -2057,6 +2070,7 @@ async function startServerWithDatabaseTeardown(
|
||||
) => {
|
||||
const shutdownStartedAt = Date.now();
|
||||
logger.info({ signal }, "shutdown signal received; starting ordered shutdown");
|
||||
eventLoopStallMonitor.stop();
|
||||
setStartupRecoveryPhase("draining");
|
||||
for (const client of liveEventsWebSocketServer.clients) client.close(1012, "Server restarting");
|
||||
liveEventsWebSocketServer.close();
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { and, eq, inArray, ne, sql, type SQL } from "drizzle-orm";
|
||||
import { agentWakeupRequests, chatMessageLinks, type Db } from "@paperclipai/db";
|
||||
import { isUuidLike } from "@paperclipai/shared";
|
||||
import { withQueuedCommentIdsInWakePayload } from "../../../services/issue-queued-comment-queue.js";
|
||||
|
||||
// A reviewed chat run attests exactly one conversation. A wake records its
|
||||
// conversation in `chatConversationId`, but a wake can also hold messages of
|
||||
// a conversation it does not record: the work-intent outbox saves unanswered
|
||||
// chat messages as a plain comment wake. These checks compare the
|
||||
// conversations of the messages themselves, so a batch never holds messages
|
||||
// of two conversations. Comments with no inbound chat link (board comments)
|
||||
// belong to no conversation and batch as before.
|
||||
|
||||
const DEFERRED_WAKE_CONTEXT_KEY = "_paperclipWakeContext";
|
||||
const CHAT_CONVERSATION_ID_KEY = "chatConversationId";
|
||||
|
||||
function record(value: unknown): Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
}
|
||||
const UUID_PATTERN = "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$";
|
||||
|
||||
/**
|
||||
* SQL predicate on a deferred `agent_wakeup_requests` row: none of its queued
|
||||
* messages is an inbound chat message of a conversation other than
|
||||
* `conversationId`.
|
||||
*/
|
||||
export function deferredWakeHoldsNoOtherConversation(companyId: string, conversationId: string): SQL {
|
||||
const ids = sql`${agentWakeupRequests.payload} -> ${DEFERRED_WAKE_CONTEXT_KEY}::text -> 'wakeCommentIds'`;
|
||||
return sql`not exists (
|
||||
select 1 from ${chatMessageLinks}
|
||||
where ${chatMessageLinks.companyId} = ${companyId}
|
||||
and ${chatMessageLinks.direction} = 'inbound'
|
||||
and ${chatMessageLinks.conversationId}::text <> ${conversationId}
|
||||
and ${chatMessageLinks.commentId} = any(array(
|
||||
select queued.id::uuid
|
||||
from jsonb_array_elements_text(case when jsonb_typeof(${ids}) = 'array' then ${ids} else '[]'::jsonb end) as queued(id)
|
||||
where queued.id ~ ${UUID_PATTERN}
|
||||
))
|
||||
)`;
|
||||
}
|
||||
|
||||
/** The ids among `commentIds` that are inbound chat messages of a conversation other than `conversationId`. */
|
||||
export async function otherConversationCommentIds(
|
||||
tx: Db,
|
||||
input: { companyId: string; conversationId: string; commentIds: string[] },
|
||||
): Promise<string[]> {
|
||||
const queryable = input.commentIds.filter((id) => isUuidLike(id));
|
||||
if (queryable.length === 0) return [];
|
||||
const rows = await tx
|
||||
.selectDistinct({ commentId: chatMessageLinks.commentId })
|
||||
.from(chatMessageLinks)
|
||||
.where(and(
|
||||
eq(chatMessageLinks.companyId, input.companyId),
|
||||
eq(chatMessageLinks.direction, "inbound"),
|
||||
inArray(chatMessageLinks.commentId, queryable),
|
||||
ne(sql`${chatMessageLinks.conversationId}::text`, input.conversationId),
|
||||
));
|
||||
const other = new Set(rows.map((row) => row.commentId));
|
||||
return input.commentIds.filter((id) => other.has(id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Upgrade repair for a deferred chat wake that older code merged across two
|
||||
* conversations. The messages of other conversations move to their own plain
|
||||
* saved wake (the shape the work-intent outbox writes), ordered just before
|
||||
* this wake so they keep their place. This wake keeps its id, its recorded
|
||||
* conversation and the rest of its messages. When no message of its own
|
||||
* conversation is left, the wake keeps its id and becomes a plain saved wake.
|
||||
* No message is dropped.
|
||||
* Returns true when the wake changed and must be read again.
|
||||
*/
|
||||
export async function splitOtherConversationMessages(
|
||||
tx: Db,
|
||||
row: typeof agentWakeupRequests.$inferSelect,
|
||||
input: { companyId: string; issueId: string; conversationId: string; queuedCommentIds: string[]; payload: Record<string, unknown> },
|
||||
): Promise<boolean> {
|
||||
const moved = await otherConversationCommentIds(tx, {
|
||||
companyId: input.companyId, conversationId: input.conversationId, commentIds: input.queuedCommentIds,
|
||||
});
|
||||
if (moved.length === 0) return false;
|
||||
const kept = input.queuedCommentIds.filter((id) => !moved.includes(id));
|
||||
const now = new Date();
|
||||
const deferred = and(eq(agentWakeupRequests.companyId, input.companyId), eq(agentWakeupRequests.id, row.id),
|
||||
eq(agentWakeupRequests.status, "deferred_issue_execution"));
|
||||
if (kept.length === 0) {
|
||||
// Every message belongs to another conversation. Keep the wake and its id
|
||||
// (an interrupt names the wake by id) and drop only its chat binding, so
|
||||
// it runs as plain saved messages.
|
||||
const { [CHAT_CONVERSATION_ID_KEY]: _dropped, ...context } = record(input.payload[DEFERRED_WAKE_CONTEXT_KEY]);
|
||||
await tx.update(agentWakeupRequests).set({ updatedAt: now,
|
||||
payload: withQueuedCommentIdsInWakePayload({ ...input.payload, mutation: "comment",
|
||||
[DEFERRED_WAKE_CONTEXT_KEY]: { ...context, source: "issue.comment", wakeReason: "issue_commented" } }, moved) })
|
||||
.where(deferred);
|
||||
return true;
|
||||
}
|
||||
const updated = await tx.update(agentWakeupRequests)
|
||||
.set({ payload: withQueuedCommentIdsInWakePayload(input.payload, kept), updatedAt: now })
|
||||
.where(deferred)
|
||||
.returning({ id: agentWakeupRequests.id });
|
||||
// Another writer already moved the wake on; its messages stay where they are.
|
||||
if (updated.length === 0) return true;
|
||||
const latest = moved.at(-1)!;
|
||||
await tx.insert(agentWakeupRequests).values({
|
||||
companyId: input.companyId, agentId: row.agentId, source: "automation", triggerDetail: "system",
|
||||
reason: "issue_commented", status: "deferred_issue_execution",
|
||||
requestedByActorType: row.requestedByActorType, requestedByActorId: row.requestedByActorId,
|
||||
requestedAt: new Date(row.requestedAt.getTime() - 1), updatedAt: now,
|
||||
payload: withQueuedCommentIdsInWakePayload({ issueId: input.issueId, mutation: "comment", commentId: latest,
|
||||
[DEFERRED_WAKE_CONTEXT_KEY]: { issueId: input.issueId, taskId: input.issueId, wakeReason: "issue_commented",
|
||||
source: "issue.comment", wakeCommentIds: moved, wakeCommentId: latest } }, moved),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { and, asc, eq, sql } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
||||
import { agentWakeupRequests, chatConversations, chatDeliveries, chatMessageLinks, createDb, heartbeatRuns,
|
||||
issueComments, issues, type Db } from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
|
||||
import { seedBoundChatAuthorization } from "../../../__tests__/helpers/bound-chat-authorization.js";
|
||||
import { authorizeChatConversationForBoundRun } from "../../../services/native-runtime/chat-attachment-reuse.js";
|
||||
import { mergeCoalescedContextSnapshot } from "../../../services/heartbeat/run-preparation.js";
|
||||
import { saveUndeliveredUserComments } from "../../../services/work-intent-outbox.js";
|
||||
import { queuedCommentIdsFromWakePayload } from "../../../services/issue-queued-comment-queue.js";
|
||||
import { createAdmitWakeBehindIssueExecution, createReleaseIssueExecution } from "../application/use-cases.js";
|
||||
import type { WakeAdmissionActiveExecutionRun } from "../application/ports.js";
|
||||
import { createAdmissionTransactionScope, createPostgresWakeQueueAdapter, createWakeAdmissionReader,
|
||||
createWakeAdmissionWriter } from "./postgres.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
const CONTEXT_KEY = "_paperclipWakeContext";
|
||||
|
||||
// PAP-4244 on staging. The work-intent outbox saved two unanswered GitHub
|
||||
// messages as a plain deferred wake: it records no chat conversation. A new
|
||||
// message from another conversation then merged into that saved wake, because
|
||||
// a wake with no recorded conversation matched every conversation. The
|
||||
// promoted run held messages of two conversations, and the reviewed chat
|
||||
// binding refused it: `reviewed_chat_execution_binding_not_authorized`
|
||||
// (`binding_denied`). Each conversation must get its own run, in order.
|
||||
describe.skipIf(!support.supported)("chat wake batches stay within one conversation", () => {
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let f: Awaited<ReturnType<typeof seedBoundChatAuthorization>>;
|
||||
let otherConversationId: string;
|
||||
let deferOnly = true;
|
||||
|
||||
const admit = createAdmitWakeBehindIssueExecution({
|
||||
reader: createWakeAdmissionReader(),
|
||||
writer: createWakeAdmissionWriter(),
|
||||
helpers: {
|
||||
filterZombieCoalesceTarget: (target) => target,
|
||||
mergeCoalescedContextSnapshot,
|
||||
shouldDeferFollowupWakeForSameIssue: () => deferOnly,
|
||||
shouldQueueFollowupForRunningIssueWake: () => false,
|
||||
},
|
||||
});
|
||||
|
||||
beforeAll(async () => {
|
||||
database = await startEmbeddedPostgresTestDatabase("wake-chat-conversation-batch-");
|
||||
db = createDb(database.connectionString);
|
||||
}, 60_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await db?.$client.end();
|
||||
await database?.cleanup();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
deferOnly = true;
|
||||
// The fixture uses fixed identifiers; move earlier cases' rows aside.
|
||||
await db.execute(sql`update companies set issue_prefix = 'X' || upper(left(replace(id::text, '-', ''), 6))`);
|
||||
await db.execute(sql`update issues set identifier = id::text`);
|
||||
f = await seedBoundChatAuthorization(db);
|
||||
otherConversationId = randomUUID();
|
||||
await db.insert(chatConversations).values({ id: otherConversationId, companyId: f.companyId, endpointId: f.endpointId,
|
||||
resourceId: f.resourceId, issueId: f.issueId, externalConversationId: "channel-1", externalThreadId: "thread-2",
|
||||
externalLabel: "Second review thread", state: "active" });
|
||||
// The fixture's own message is not part of these cases.
|
||||
await db.delete(chatMessageLinks).where(eq(chatMessageLinks.commentId, f.commentId));
|
||||
await db.delete(issueComments).where(eq(issueComments.id, f.commentId));
|
||||
await db.insert(heartbeatRuns).values({ id: f.runId, companyId: f.companyId, agentId: f.agentId, status: "running",
|
||||
invocationSource: "assignment", triggerDetail: "system", startedAt: new Date(),
|
||||
contextSnapshot: { issueId: f.issueId, taskId: f.issueId } });
|
||||
await db.update(issues).set({ executionRunId: f.runId, executionLockedAt: new Date() }).where(eq(issues.id, f.issueId));
|
||||
});
|
||||
|
||||
let messageClock = Date.now() - 600_000;
|
||||
async function message(conversationId: string | null): Promise<string> {
|
||||
messageClock += 1_000;
|
||||
const at = new Date(messageClock);
|
||||
const [comment] = await db.insert(issueComments).values({ companyId: f.companyId, issueId: f.issueId,
|
||||
authorType: "user", authorUserId: f.userId, body: `Message ${messageClock}`, createdAt: at, updatedAt: at }).returning();
|
||||
if (conversationId) {
|
||||
const deliveryId = randomUUID();
|
||||
await db.insert(chatDeliveries).values({ id: deliveryId, companyId: f.companyId, endpointId: f.endpointId,
|
||||
conversationId, principalId: f.principalId, providerEventId: deliveryId, deduplicationKey: deliveryId,
|
||||
eventKind: "message", normalizedEvent: {}, state: "processed", attempts: 1, processedAt: at });
|
||||
await db.insert(chatMessageLinks).values({ companyId: f.companyId, endpointId: f.endpointId, conversationId,
|
||||
deliveryId, commentId: comment!.id, providerMessageId: deliveryId, direction: "inbound" });
|
||||
}
|
||||
return comment!.id;
|
||||
}
|
||||
|
||||
function chatContext(conversationId: string, commentId: string) {
|
||||
return { issueId: f.issueId, taskId: f.issueId, source: "chat:slack", wakeReason: "External chat message received",
|
||||
wakeSource: "assignment", chatConversationId: conversationId, commentId, wakeCommentId: commentId,
|
||||
wakeCommentIds: [commentId] };
|
||||
}
|
||||
|
||||
function commentContext(commentId: string) {
|
||||
return { issueId: f.issueId, taskId: f.issueId, source: "issue.comment", wakeReason: "issue_commented",
|
||||
commentId, wakeCommentId: commentId, wakeCommentIds: [commentId] };
|
||||
}
|
||||
|
||||
async function admitWake(contextSnapshot: Record<string, unknown>, activeExecutionRun?: WakeAdmissionActiveExecutionRun) {
|
||||
const commentId = contextSnapshot.wakeCommentId as string;
|
||||
const chat = contextSnapshot.source === "chat:slack";
|
||||
return db.transaction(async (tx) => admit(createAdmissionTransactionScope(f.companyId, tx as unknown as Db), {
|
||||
companyId: f.companyId, issueId: f.issueId, agentId: f.agentId, agentNameKey: "chat runner",
|
||||
issueExecutionAgentNameKey: null,
|
||||
activeExecutionRun: activeExecutionRun ?? { id: f.runId, agentId: f.agentId, status: "running",
|
||||
contextSnapshot: { issueId: f.issueId, taskId: f.issueId }, wakeupRequestId: null },
|
||||
allowRunCoalescing: true, liveRunExecutions: new Set([f.runId]), wakeCommentId: commentId,
|
||||
forceFreshSession: false, contextSnapshot, source: "assignment", triggerDetail: "system",
|
||||
reason: chat ? "External chat message received" : "issue_commented",
|
||||
payload: { issueId: f.issueId, mutation: chat ? "chat_message_received" : "comment", wakeCommentId: commentId },
|
||||
requestedByActorType: "user", requestedByActorId: f.userId, idempotencyKey: null,
|
||||
}));
|
||||
}
|
||||
|
||||
async function deferredWakes() {
|
||||
const rows = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, f.companyId),
|
||||
eq(agentWakeupRequests.status, "deferred_issue_execution"))).orderBy(asc(agentWakeupRequests.requestedAt));
|
||||
return rows.map(row => ({ id: row.id, commentIds: queuedCommentIdsFromWakePayload(row.payload),
|
||||
context: (row.payload as Record<string, Record<string, unknown>>)[CONTEXT_KEY]! }));
|
||||
}
|
||||
|
||||
async function attest(context: Record<string, unknown>) {
|
||||
return authorizeChatConversationForBoundRun(db, { companyId: f.companyId, issueId: f.issueId, agentId: f.agentId,
|
||||
runId: f.runId }, { ...context, paperclipHarnessCheckedOut: true }, "read");
|
||||
}
|
||||
|
||||
async function saveUndelivered(commentIds: string[]) {
|
||||
const saved = await saveUndeliveredUserComments(db, { companyId: f.companyId, issueId: f.issueId, agentId: f.agentId,
|
||||
commentIds, allowedStatuses: ["in_review"] });
|
||||
expect(saved).toBeTruthy();
|
||||
return saved!;
|
||||
}
|
||||
|
||||
it("keeps a message out of a saved wake that holds another conversation's messages", async () => {
|
||||
const earlier = await message(otherConversationId);
|
||||
const saved = await saveUndelivered([earlier]);
|
||||
const reply = await message(f.conversationId);
|
||||
|
||||
expect(await admitWake(chatContext(f.conversationId, reply))).toEqual({ kind: "deferred" });
|
||||
|
||||
const wakes = await deferredWakes();
|
||||
// The saved messages run first, then the new conversation, each on its own.
|
||||
expect(wakes.map(wake => wake.commentIds)).toEqual([[earlier], [reply]]);
|
||||
expect(wakes[0]!.id).toBe(saved);
|
||||
expect(wakes[0]!.context.chatConversationId).toBeUndefined();
|
||||
expect(wakes[0]!.context.source).toBe("issue.comment");
|
||||
await expect(attest(wakes[1]!.context)).resolves.toMatchObject({ conversationId: f.conversationId });
|
||||
});
|
||||
|
||||
it("keeps two conversations apart when both arrive behind saved wakes", async () => {
|
||||
const first = await message(f.conversationId);
|
||||
const second = await message(otherConversationId);
|
||||
await saveUndelivered([first]);
|
||||
await saveUndelivered([second]);
|
||||
const replyToFirst = await message(f.conversationId);
|
||||
const replyToSecond = await message(otherConversationId);
|
||||
|
||||
await admitWake(chatContext(otherConversationId, replyToSecond));
|
||||
await admitWake(chatContext(f.conversationId, replyToFirst));
|
||||
|
||||
const wakes = await deferredWakes();
|
||||
expect(wakes.map(wake => wake.commentIds)).toEqual([[first, replyToFirst], [second, replyToSecond]]);
|
||||
expect(wakes.map(wake => wake.context.chatConversationId)).toEqual([f.conversationId, otherConversationId]);
|
||||
await expect(attest(wakes[0]!.context)).resolves.toMatchObject({ conversationId: f.conversationId });
|
||||
await expect(attest(wakes[1]!.context)).resolves.toMatchObject({ conversationId: otherConversationId });
|
||||
});
|
||||
|
||||
describe("batching that stays the same", () => {
|
||||
it("merges comment wakes that have no conversation", async () => {
|
||||
const one = await message(null);
|
||||
const two = await message(null);
|
||||
await admitWake(commentContext(one));
|
||||
await admitWake(commentContext(two));
|
||||
expect((await deferredWakes()).map(wake => wake.commentIds)).toEqual([[one, two]]);
|
||||
});
|
||||
|
||||
it("merges messages of one conversation", async () => {
|
||||
const one = await message(f.conversationId);
|
||||
const two = await message(f.conversationId);
|
||||
await admitWake(chatContext(f.conversationId, one));
|
||||
await admitWake(chatContext(f.conversationId, two));
|
||||
const wakes = await deferredWakes();
|
||||
expect(wakes.map(wake => wake.commentIds)).toEqual([[one, two]]);
|
||||
await expect(attest(wakes[0]!.context)).resolves.toMatchObject({ conversationId: f.conversationId });
|
||||
});
|
||||
|
||||
it("merges a saved wake of the same conversation's messages", async () => {
|
||||
const earlier = await message(f.conversationId);
|
||||
await saveUndelivered([earlier]);
|
||||
const reply = await message(f.conversationId);
|
||||
await admitWake(chatContext(f.conversationId, reply));
|
||||
const wakes = await deferredWakes();
|
||||
expect(wakes.map(wake => wake.commentIds)).toEqual([[earlier, reply]]);
|
||||
await expect(attest(wakes[0]!.context)).resolves.toMatchObject({ conversationId: f.conversationId });
|
||||
});
|
||||
|
||||
it("merges a chat message into a wake of plain comments, and a plain comment into a chat wake", async () => {
|
||||
const plain = await message(null);
|
||||
const chat = await message(f.conversationId);
|
||||
const laterPlain = await message(null);
|
||||
await admitWake(commentContext(plain));
|
||||
await admitWake(chatContext(f.conversationId, chat));
|
||||
await admitWake(commentContext(laterPlain));
|
||||
const wakes = await deferredWakes();
|
||||
expect(wakes.map(wake => wake.commentIds)).toEqual([[plain, chat, laterPlain]]);
|
||||
expect(wakes[0]!.context.chatConversationId).toBe(f.conversationId);
|
||||
});
|
||||
|
||||
it("keeps messages of two recorded conversations apart", async () => {
|
||||
const one = await message(f.conversationId);
|
||||
const two = await message(otherConversationId);
|
||||
await admitWake(chatContext(f.conversationId, one));
|
||||
await admitWake(chatContext(otherConversationId, two));
|
||||
expect((await deferredWakes()).map(wake => wake.commentIds)).toEqual([[one], [two]]);
|
||||
});
|
||||
});
|
||||
|
||||
it("does not fold a message into a queued run that holds another conversation's messages", async () => {
|
||||
deferOnly = false;
|
||||
const earlier = await message(otherConversationId);
|
||||
const savedId = await saveUndelivered([earlier]);
|
||||
// The saved wake was promoted: a queued run that the finished run left behind.
|
||||
const queuedRunId = randomUUID();
|
||||
const [savedWake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, savedId));
|
||||
const runContext = (savedWake!.payload as Record<string, Record<string, unknown>>)[CONTEXT_KEY]!;
|
||||
await db.insert(heartbeatRuns).values({ id: queuedRunId, companyId: f.companyId, agentId: f.agentId, status: "queued",
|
||||
invocationSource: "automation", triggerDetail: "system", wakeupRequestId: savedId, contextSnapshot: runContext });
|
||||
await db.update(agentWakeupRequests).set({ status: "queued", runId: queuedRunId }).where(eq(agentWakeupRequests.id, savedId));
|
||||
await db.update(issues).set({ executionRunId: queuedRunId }).where(eq(issues.id, f.issueId));
|
||||
const reply = await message(f.conversationId);
|
||||
|
||||
const result = await admitWake(chatContext(f.conversationId, reply), { id: queuedRunId, agentId: f.agentId,
|
||||
status: "queued", contextSnapshot: runContext, wakeupRequestId: savedId });
|
||||
|
||||
expect(result).toEqual({ kind: "deferred" });
|
||||
const [queuedRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, queuedRunId));
|
||||
expect(queuedRun!.contextSnapshot).toMatchObject({ wakeCommentIds: [earlier], source: "issue.comment" });
|
||||
expect((await deferredWakes()).map(wake => wake.commentIds)).toEqual([[reply]]);
|
||||
});
|
||||
|
||||
it("still folds a same-conversation message into a queued run", async () => {
|
||||
deferOnly = false;
|
||||
const earlier = await message(f.conversationId);
|
||||
const savedId = await saveUndelivered([earlier]);
|
||||
const queuedRunId = randomUUID();
|
||||
const [savedWake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, savedId));
|
||||
const runContext = (savedWake!.payload as Record<string, Record<string, unknown>>)[CONTEXT_KEY]!;
|
||||
await db.insert(heartbeatRuns).values({ id: queuedRunId, companyId: f.companyId, agentId: f.agentId, status: "queued",
|
||||
invocationSource: "automation", triggerDetail: "system", wakeupRequestId: savedId, contextSnapshot: runContext });
|
||||
await db.update(agentWakeupRequests).set({ status: "queued", runId: queuedRunId }).where(eq(agentWakeupRequests.id, savedId));
|
||||
await db.update(issues).set({ executionRunId: queuedRunId }).where(eq(issues.id, f.issueId));
|
||||
const reply = await message(f.conversationId);
|
||||
|
||||
const result = await admitWake(chatContext(f.conversationId, reply), { id: queuedRunId, agentId: f.agentId,
|
||||
status: "queued", contextSnapshot: runContext, wakeupRequestId: savedId });
|
||||
|
||||
expect(result.kind).toBe("coalesced");
|
||||
const [queuedRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, queuedRunId));
|
||||
expect(queuedRun!.contextSnapshot).toMatchObject({ wakeCommentIds: [earlier, reply], chatConversationId: f.conversationId });
|
||||
});
|
||||
|
||||
function releaseIssue() {
|
||||
return createReleaseIssueExecution({
|
||||
issueLock: createPostgresWakeQueueAdapter(db, {
|
||||
resolveResponsibleUserId: async () => f.userId,
|
||||
getRoutineEnv: async () => ({ routineId: null, env: null, responsibleUserId: null }),
|
||||
resolveSessionBeforeForWakeup: async () => null,
|
||||
} as never),
|
||||
recovery: { escalateStrandedAssignedIssue: async () => {}, escalateStrandedRecoveryIssueInPlace: async () => {} } as never,
|
||||
});
|
||||
}
|
||||
|
||||
// An older merged wake can be left with only the other conversation's
|
||||
// messages (its own message was discarded). An interrupt names the wake by
|
||||
// id, so the wake keeps its id and runs as plain saved messages.
|
||||
it("keeps an interrupted wake's id when all of its messages belong to another conversation", async () => {
|
||||
const earlier = await message(otherConversationId);
|
||||
const savedId = await saveUndelivered([earlier]);
|
||||
const [savedWake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, savedId));
|
||||
const payload = savedWake!.payload as Record<string, unknown>;
|
||||
await db.update(agentWakeupRequests).set({ payload: { ...payload, mutation: "chat_message_received",
|
||||
[CONTEXT_KEY]: { ...(payload[CONTEXT_KEY] as Record<string, unknown>), source: "chat:slack",
|
||||
wakeReason: "External chat message received", chatConversationId: f.conversationId } } })
|
||||
.where(eq(agentWakeupRequests.id, savedId));
|
||||
await db.update(heartbeatRuns).set({ status: "cancelled", finishedAt: new Date(),
|
||||
resultJson: { queuedCommentInterruptQueueId: savedId, executionCancellation: { state: "acknowledged" },
|
||||
conversationContinuation: "continue_conversation_v1" } })
|
||||
.where(eq(heartbeatRuns.id, f.runId));
|
||||
|
||||
const result = await releaseIssue()({ companyId: f.companyId, runId: f.runId, now: new Date() });
|
||||
|
||||
expect(result.outcome.kind).toBe("promoted");
|
||||
const promoted = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId),
|
||||
eq(heartbeatRuns.status, "queued")));
|
||||
expect(promoted).toHaveLength(1);
|
||||
expect(promoted[0]!.wakeupRequestId).toBe(savedId);
|
||||
expect(promoted[0]!.contextSnapshot).toMatchObject({ wakeCommentIds: [earlier], source: "issue.comment" });
|
||||
expect(promoted[0]!.contextSnapshot?.chatConversationId).toBeUndefined();
|
||||
expect(await deferredWakes()).toEqual([]);
|
||||
});
|
||||
|
||||
// A wake that older code already merged across two conversations. Release
|
||||
// splits it: the other conversation's messages run first as plain saved
|
||||
// messages, then the recorded conversation runs with its own messages.
|
||||
it("splits a saved wake that older code merged across two conversations", async () => {
|
||||
const earlier = await message(otherConversationId);
|
||||
const savedId = await saveUndelivered([earlier]);
|
||||
const reply = await message(f.conversationId);
|
||||
const [savedWake] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, savedId));
|
||||
const payload = savedWake!.payload as Record<string, unknown>;
|
||||
const merged = mergeCoalescedContextSnapshot(payload[CONTEXT_KEY], chatContext(f.conversationId, reply));
|
||||
await db.update(agentWakeupRequests).set({ payload: { ...payload, mutation: "chat_message_received",
|
||||
commentId: reply, wakeCommentId: reply, [CONTEXT_KEY]: merged } }).where(eq(agentWakeupRequests.id, savedId));
|
||||
expect(merged).toMatchObject({ wakeCommentIds: [earlier, reply], chatConversationId: f.conversationId });
|
||||
// This is the shape that failed on staging.
|
||||
await expect(attest(merged)).rejects.toThrow("paperclip_runner_chat_attachment_binding_denied");
|
||||
|
||||
const release = releaseIssue();
|
||||
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() }).where(eq(heartbeatRuns.id, f.runId));
|
||||
const first = await release({ companyId: f.companyId, runId: f.runId, now: new Date() });
|
||||
expect(first.outcome.kind).toBe("promoted");
|
||||
|
||||
const promoted = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId),
|
||||
eq(heartbeatRuns.status, "queued")));
|
||||
expect(promoted).toHaveLength(1);
|
||||
expect(promoted[0]!.contextSnapshot).toMatchObject({ wakeCommentIds: [earlier], source: "issue.comment" });
|
||||
expect(promoted[0]!.contextSnapshot?.chatConversationId).toBeUndefined();
|
||||
const waiting = await deferredWakes();
|
||||
expect(waiting).toEqual([expect.objectContaining({ id: savedId, commentIds: [reply] })]);
|
||||
await expect(attest(waiting[0]!.context)).resolves.toMatchObject({ conversationId: f.conversationId });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, agentWakeupRequests, companies, createDb, heartbeatRuns, issueComments, issues } from "@paperclipai/db";
|
||||
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "../../../__tests__/helpers/embedded-postgres.js";
|
||||
import { createReleaseIssueExecution } from "../application/use-cases.js";
|
||||
import { createPostgresWakeQueueAdapter } from "./postgres.js";
|
||||
import { resolveInboundWakeReceipt } from "../../../services/chat-inbound-wakeup-publications.js";
|
||||
import { createDurableChatWakeupRequest } from "../../../services/durable-chat-wakeup.js";
|
||||
|
||||
const support = await getEmbeddedPostgresTestSupport();
|
||||
|
||||
// A GitHub message arrives while the agent's run is active. The wake is saved
|
||||
// behind that run. The run reads the message (it is in its wake input) and
|
||||
// finishes. Before this fix the saved wake was still promoted, with its message
|
||||
// ids removed. A reviewed chat run with no message cannot be attested, so it
|
||||
// failed with `reviewed_chat_execution_binding_not_authorized` (context_mismatch)
|
||||
// and blocked the task.
|
||||
describe.skipIf(!support.supported)("release of a saved chat wake whose message was delivered", () => {
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let companyId: string;
|
||||
let agentId: string;
|
||||
|
||||
beforeAll(async () => {
|
||||
database = await startEmbeddedPostgresTestDatabase("wake-chat-delivered-");
|
||||
db = createDb(database.connectionString);
|
||||
const [company] = await db.insert(companies).values({ name: "Chat wake fixture", issuePrefix: "CWD" }).returning();
|
||||
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Reviewer", adapterType: "process" }).returning();
|
||||
companyId = company.id;
|
||||
agentId = agent.id;
|
||||
}, 60_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await db?.$client.end();
|
||||
await database?.cleanup();
|
||||
});
|
||||
|
||||
async function seed(delivered: boolean) {
|
||||
const [issue] = await db.insert(issues).values({ companyId, title: "Review a pull request", status: "in_review",
|
||||
assigneeAgentId: agentId }).returning();
|
||||
const [message] = await db.insert(issueComments).values({ companyId, issueId: issue.id, authorUserId: "chat-user",
|
||||
body: "GitHub review request.", createdAt: new Date(Date.now() - 60_000), updatedAt: new Date(Date.now() - 60_000) }).returning();
|
||||
// The finishing run started after the message and received it as wake input.
|
||||
const [run] = await db.insert(heartbeatRuns).values({ companyId, agentId, status: "succeeded",
|
||||
invocationSource: "assignment", triggerDetail: "system", startedAt: new Date(Date.now() - 30_000), finishedAt: new Date(),
|
||||
contextSnapshot: { issueId: issue.id, source: "chat:github", wakeReason: "External chat message received",
|
||||
chatConversationId: randomUUID(), ...(delivered ? { wakeCommentIds: [message.id] } : { wakeCommentIds: [randomUUID()] }) },
|
||||
}).returning();
|
||||
await db.update(issues).set({ executionRunId: run.id, executionLockedAt: new Date() }).where(eq(issues.id, issue.id));
|
||||
const context = { issueId: issue.id, taskId: issue.id, source: "chat:github", wakeReason: "External chat message received",
|
||||
wakeSource: "assignment", chatConversationId: randomUUID(), commentId: message.id, wakeCommentId: message.id,
|
||||
wakeCommentIds: [message.id] };
|
||||
const wakeId = randomUUID();
|
||||
const { idempotencyKey } = createDurableChatWakeupRequest({ id: wakeId, companyId, agentId, issueId: issue.id,
|
||||
commentId: message.id, requestedByActorType: "user", requestedByActorId: "chat-user", requestedAt: new Date(),
|
||||
authorize: async () => {} });
|
||||
const [wake] = await db.insert(agentWakeupRequests).values({ id: wakeId, idempotencyKey, companyId, agentId, source: "assignment",
|
||||
triggerDetail: "system", reason: "External chat message received", status: "deferred_issue_execution",
|
||||
requestedByActorType: "user", requestedByActorId: "chat-user",
|
||||
payload: { issueId: issue.id, mutation: "chat_message_received", wakeCommentId: message.id, _paperclipWakeContext: context },
|
||||
}).returning();
|
||||
return { issue, run, wake };
|
||||
}
|
||||
|
||||
function release(unexpected: () => never) {
|
||||
return createReleaseIssueExecution({
|
||||
issueLock: createPostgresWakeQueueAdapter(db, { resolveResponsibleUserId: unexpected, getRoutineEnv: unexpected,
|
||||
resolveSessionBeforeForWakeup: unexpected } as never),
|
||||
recovery: { escalateStrandedAssignedIssue: unexpected, escalateStrandedRecoveryIssueInPlace: unexpected } as never,
|
||||
});
|
||||
}
|
||||
|
||||
it("consumes the saved chat wake instead of starting a run with no message", async () => {
|
||||
const { run, wake } = await seed(true);
|
||||
const unexpected = vi.fn((): never => { throw new Error("Unexpected promotion of a consumed chat wake"); });
|
||||
const result = await release(unexpected)({ companyId, runId: run.id, now: new Date() });
|
||||
expect(result.outcome.kind).toBe("released");
|
||||
expect(unexpected).not.toHaveBeenCalled();
|
||||
const [saved] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake.id));
|
||||
expect(saved).toMatchObject({ status: "cancelled", runId: null, error: "Queued messages were already delivered to a completed run" });
|
||||
expect(await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, companyId)).then(rows =>
|
||||
rows.filter(row => row.contextSnapshot?.issueId === saved.payload?.issueId && row.id !== run.id))).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not report a delivered chat message as not started", async () => {
|
||||
const { wake } = await seed(true);
|
||||
const action = { id: wake.id, companyId, kind: "inbound_wakeup", conversationId: randomUUID(), deliveryId: randomUUID(),
|
||||
principalId: randomUUID(), createdAt: wake.requestedAt, status: "processed",
|
||||
payload: { version: 1, agentId, issueId: wake.payload?.issueId, commentId: wake.payload?.wakeCommentId,
|
||||
requestedByActorType: "user", requestedByActorId: "chat-user" } };
|
||||
const consumed = { ...wake, status: "cancelled", error: "Queued messages were already delivered to a completed run" };
|
||||
expect(resolveInboundWakeReceipt(action as never, consumed, consumed)).toBeNull();
|
||||
// Other declines keep their notice.
|
||||
const refused = { ...wake, status: "cancelled", error: "Deferred wake suppressed by active subtree pause hold" };
|
||||
expect(resolveInboundWakeReceipt(action as never, refused, refused)).toMatchObject({ state: "not_started" });
|
||||
});
|
||||
|
||||
it("still promotes a saved chat wake whose message no run has received", async () => {
|
||||
const { run, wake } = await seed(false);
|
||||
// Promotion reaches the host; the refusal proves the wake was not consumed.
|
||||
const unexpected = vi.fn((): never => { throw new Error("promotion reached the host"); });
|
||||
await expect(release(unexpected)({ companyId, runId: run.id, now: new Date() })).rejects.toThrow("promotion reached the host");
|
||||
expect(unexpected).toHaveBeenCalled();
|
||||
const [saved] = await db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, wake.id));
|
||||
expect(saved.status).not.toBe("cancelled");
|
||||
});
|
||||
});
|
||||
@@ -19,7 +19,7 @@ import { and, asc, eq, inArray, isNull, notInArray, or, sql } from "drizzle-orm"
|
||||
import { readReleaseRun, type ReleaseRun } from "./release-run-read.js";
|
||||
import { isGovernancePauseStop } from "../../../services/governance-pause-stop.js";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { deliveredQueuedCommentIds } from "../../../services/queued-comment-delivery.js";
|
||||
import { deliveredQueuedCommentIds, EXTERNAL_CHAT_MESSAGE_WAKE_MUTATION, EXTERNAL_CHAT_MESSAGE_WAKE_REASON } from "../../../services/queued-comment-delivery.js";
|
||||
import { extractIssueReferenceIdentifiers, isUuidLike } from "@paperclipai/shared";
|
||||
import {
|
||||
activityLog,
|
||||
@@ -55,7 +55,8 @@ import {
|
||||
queuedCommentIdsFromRunContext,
|
||||
withQueuedCommentIdsInWakePayload,
|
||||
} from "../../../services/issue-queued-comment-queue.js";
|
||||
import { CHAT_CONVERSATION_ID_KEY, extractWakeCommentIds } from "../../run-dispatch/index.js";
|
||||
import { CHAT_CONVERSATION_ID_KEY, extractWakeCommentIds, readWakeChatConversationId } from "../../run-dispatch/index.js";
|
||||
import { deferredWakeHoldsNoOtherConversation, otherConversationCommentIds, splitOtherConversationMessages } from "./chat-conversation-batch.js";
|
||||
import { hasInteractionContinuationWakeContext } from "../domain/context.js";
|
||||
import { decidePreDrain, type PreDrainFacts } from "../domain/policy.js";
|
||||
import {
|
||||
@@ -177,7 +178,11 @@ function toDeferredWakeCandidate(row: typeof agentWakeupRequests.$inferSelect):
|
||||
!queuedReason ||
|
||||
queuedReason === "issue_commented" ||
|
||||
queuedReason === "issue_reopened_via_comment" ||
|
||||
queuedReason === "issue_comment_mentioned";
|
||||
queuedReason === "issue_comment_mentioned" ||
|
||||
// An inbound chat message wake carries only its saved messages. When a
|
||||
// completed run already received them, nothing is left to start, and a
|
||||
// reviewed chat run with no message cannot be attested.
|
||||
(queuedReason === EXTERNAL_CHAT_MESSAGE_WAKE_REASON && payload.mutation === EXTERNAL_CHAT_MESSAGE_WAKE_MUTATION);
|
||||
const preservesIndependentContinuation =
|
||||
hasInteractionContinuationWakeContext(deferredContextSeed) ||
|
||||
deferredContextSeed.resumeIntent === true ||
|
||||
@@ -255,6 +260,12 @@ function buildTransaction(tx: Db, deps: WakeQueuePostgresAdapterDeps, db: Db, ru
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!row) return null;
|
||||
const candidate = toDeferredWakeCandidate(row);
|
||||
// Upgrade repair: older code could merge two conversations into one
|
||||
// saved chat wake. Split it and read the queue again.
|
||||
const conversationId = readWakeChatConversationId(candidate.deferredContextSeed);
|
||||
if (conversationId && candidate.queuedCommentIds.length > 0 && await splitOtherConversationMessages(tx, row, {
|
||||
companyId, issueId, conversationId, queuedCommentIds: candidate.queuedCommentIds, payload: candidate.payload,
|
||||
})) continue;
|
||||
try {
|
||||
const authorizedFailedChatRetry = await authorizeFailedChatRunRetryWake(
|
||||
db,
|
||||
@@ -956,6 +967,9 @@ export function createWakeAdmissionReader(): WakeAdmissionReader {
|
||||
...(chatConversationId
|
||||
? [
|
||||
sql`coalesce(${agentWakeupRequests.payload} -> ${DEFERRED_WAKE_CONTEXT_KEY}::text ->> ${CHAT_CONVERSATION_ID_KEY}::text, ${chatConversationId}) = ${chatConversationId}`,
|
||||
// A wake with no recorded conversation can still hold
|
||||
// another conversation's messages (an outbox-saved wake).
|
||||
deferredWakeHoldsNoOtherConversation(companyId, chatConversationId),
|
||||
]
|
||||
: []),
|
||||
...(durableActor
|
||||
@@ -1012,6 +1026,12 @@ export function createWakeAdmissionWriter(): WakeAdmissionWriter {
|
||||
)).for("update").limit(1);
|
||||
if (!current || current.status !== input.activeExecutionRunStatus || current.wakeupRequestId !== candidate.wakeupRequestId) return null;
|
||||
const commentIds = queuedCommentIdsFromRunContext(input.mergedContextSnapshot);
|
||||
// A reviewed chat run attests one conversation. Never fold a message
|
||||
// into a run that already holds another conversation's messages; the
|
||||
// wake is saved behind the run instead.
|
||||
const mergedConversationId = readWakeChatConversationId(input.mergedContextSnapshot);
|
||||
if (mergedConversationId && commentIds.length > 0 && (await otherConversationCommentIds(tx, {
|
||||
companyId: input.companyId, conversationId: mergedConversationId, commentIds })).length > 0) return null;
|
||||
const synchronizeBatch = current.status === "queued" && commentIds.length > 0
|
||||
&& primary?.status === "queued" && queuedCommentIdsFromWakePayload(primary.payload).length > 0;
|
||||
if (current.status === "queued" && commentIds.length && current.wakeupRequestId &&
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { readWakeChatConversationId } from "../../run-dispatch/index.js";
|
||||
import { enrichPromotedWakeContext, wakeMustNotJoinActiveRun } from "../domain/context.js";
|
||||
import { QUEUED_MESSAGES_DELIVERED_REASON } from "../domain/policy.js";
|
||||
import {
|
||||
decideQueuedCommentAction,
|
||||
decideReleaseRecovery,
|
||||
@@ -272,7 +273,7 @@ async function runReleaseDrain(
|
||||
reason: commentAction.selfAuthored
|
||||
? "Deferred wake contained only comments authored by the finishing run"
|
||||
: liveness.deliveredCommentIds?.length
|
||||
? "Queued messages were already delivered to a completed run"
|
||||
? QUEUED_MESSAGES_DELIVERED_REASON
|
||||
: "Queued messages were discarded before promotion",
|
||||
now: input.now,
|
||||
});
|
||||
|
||||
@@ -13,6 +13,9 @@
|
||||
// This file only branches on that facts object; it never queries a
|
||||
// database, reads the clock, or reads the wake context payload directly.
|
||||
|
||||
/** The error a saved wake records when a completed run already received all of its messages. */
|
||||
export const QUEUED_MESSAGES_DELIVERED_REASON = "Queued messages were already delivered to a completed run";
|
||||
|
||||
export type WakeAdmissionFacts = {
|
||||
/** True when the active execution run's agent and this wake's own agent share an execution-agent-name key. */
|
||||
isSameExecutionAgent: boolean;
|
||||
|
||||
@@ -29,6 +29,7 @@ export type {
|
||||
} from "./application/types.js";
|
||||
export { WakeQueueApplicationError } from "./application/types.js";
|
||||
export { hasRetainedExternalChatRetry } from "./domain/context.js";
|
||||
export { QUEUED_MESSAGES_DELIVERED_REASON } from "./domain/policy.js";
|
||||
export type {
|
||||
IssueSnapshot,
|
||||
RunSnapshot,
|
||||
|
||||
@@ -60,6 +60,7 @@ import { listIssueStatusBlockerAttention } from "../services/issue-status-presen
|
||||
import type { IssueBlockerAttention } from "@paperclipai/shared";
|
||||
import { listCaseTaskDocuments } from "../services/case-task-documents.js";
|
||||
import { authorizeCaseCreation, authorizeCaseMutation } from "../services/case-mutation-authorization.js";
|
||||
import { assertCaseStatusWriteAuthority } from "../services/case-handoffs.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { assertCompanyAccess, getActorInfo, hasCompanyAccess } from "./authz.js";
|
||||
|
||||
@@ -694,19 +695,21 @@ export function caseRoutes(db: Db, storage: StorageService) {
|
||||
.then((rows) => rows[0] ?? null);
|
||||
|
||||
if (existing) {
|
||||
await authorizeCaseMutation(tx as unknown as Db, req.actor, existing.id, companyId);
|
||||
const current = await authorizeCaseMutation(tx as unknown as Db, req.actor, existing.id, companyId);
|
||||
await assertCaseStatusWriteAuthority(tx as unknown as Db, req.actor, current, body.status);
|
||||
if (body.projectId) await retainCaseAccessSource(tx, {
|
||||
companyId, caseId: existing.id, sourceKind: "project", sourceId: body.projectId,
|
||||
});
|
||||
const status = body.status ?? existing.status;
|
||||
// Fall back to the locked row so a concurrent close or reopen is not undone.
|
||||
const status = body.status ?? current.status;
|
||||
const [updated] = await tx.update(cases).set({
|
||||
projectId: body.projectId ?? existing.projectId,
|
||||
projectId: body.projectId ?? current.projectId,
|
||||
title: body.title,
|
||||
summary: body.summary ?? existing.summary,
|
||||
summary: body.summary ?? current.summary,
|
||||
status,
|
||||
fields: body.fields ?? existing.fields,
|
||||
parentCaseId: body.parentCaseId ?? existing.parentCaseId,
|
||||
completedAt: completedAtForStatus(status, existing.completedAt),
|
||||
fields: body.fields ?? current.fields,
|
||||
parentCaseId: body.parentCaseId ?? current.parentCaseId,
|
||||
completedAt: completedAtForStatus(status, current.completedAt),
|
||||
updatedAt: now,
|
||||
}).where(eq(cases.id, existing.id)).returning();
|
||||
await insertCaseEvent(tx, {
|
||||
@@ -1592,6 +1595,7 @@ export function caseRoutes(db: Db, storage: StorageService) {
|
||||
const nextLabelIds = body.labelIds ?? body.labels;
|
||||
|
||||
const updated = await mutateCase(req, caseRow, async (tx, currentCase) => {
|
||||
await assertCaseStatusWriteAuthority(tx as unknown as Db, req.actor, currentCase, body.status);
|
||||
await assertProjectBelongsToCompany(tx, { companyId: caseRow.companyId, projectId: body.projectId ?? null });
|
||||
if (body.projectId) {
|
||||
if (!(await authorizationService(tx).decide({ actor: req.actor, action: "project:read", resource: {
|
||||
|
||||
@@ -51,6 +51,8 @@ export const experimentalApiDocs: Record<string, { summary: string; description:
|
||||
description: "Accepts a task UUID or identifier and returns each readable case linked to that task, as { id, role, case: { id, identifier, ... } }. The top-level id is the link; pass case.id to read_case or the case audit history." },
|
||||
"GET /api/cases/{id}": { summary: "Read a case and its current facts",
|
||||
description: "Returns the case identifier, title, status, current facts (fields) and primary task." },
|
||||
"PATCH /api/cases/{id}": { summary: "Update a case's facts, labels or status",
|
||||
description: "Updates title, summary, fields, labels, project, parent case or status. For a case with a primary task, agents do not close it here: the agent assigned to that task records a terminal handoff to done, and only that agent may cancel or reopen the case." },
|
||||
"GET /api/cases/{id}/events": { summary: "Read a case's audit history of fact changes, handoffs and links",
|
||||
description: "Newest first. Each event has its kind (such as fields_changed, status_changed, issue_linked), the actor and time. An agent actor has actorAgentId and actorAgentName; a person has actorType user and actorUserId, without a display name. A fields_changed event records who changed the facts and when; it does not retain the previous fact values. Document edits are in document revisions and handoffs in the case handoff history." },
|
||||
"GET /api/cases/{id}/documents/{key}/revisions": { summary: "Read a case document's revision history",
|
||||
|
||||
@@ -111,12 +111,39 @@ async function authorizeTerminalTask(tx: Db, actor: AuthorizationActor, issue: I
|
||||
parentIssueId: issue.parentId, assigneeAgentId: issue.assigneeAgentId, assigneeUserId: issue.assigneeUserId, status: issue.status };
|
||||
if (!(await access.decide({ actor, action: "issue:read", resource })).allowed) throw notFound("Task not found");
|
||||
if (actor.type === "agent" && (issue.assigneeAgentId !== actor.agentId || issue.assigneeUserId)) {
|
||||
throw forbidden("Agents may complete only their own case work");
|
||||
const task = issue.identifier ?? issue.id;
|
||||
const [owner] = issue.assigneeAgentId && !issue.assigneeUserId ? await tx.select({ name: agents.name }).from(agents)
|
||||
.where(and(eq(agents.id, issue.assigneeAgentId), eq(agents.companyId, issue.companyId))).limit(1) : [];
|
||||
throw forbidden(owner
|
||||
? `Agents may complete only their own case work. ${owner.name} (agent ${issue.assigneeAgentId}) owns primary task ${task} and records the terminal handoff. Ask that agent on ${task} to close the case.`
|
||||
: `Agents may complete only their own case work. Primary task ${task} has no assigned agent to close the case.`,
|
||||
{ primaryTaskId: issue.id, assigneeAgentId: issue.assigneeAgentId });
|
||||
}
|
||||
const mutation = await access.decide({ actor, action: "issue:mutate", resource });
|
||||
if (!mutation.allowed) throw forbidden(mutation.explanation, authorizationDeniedDetails(mutation));
|
||||
}
|
||||
|
||||
const TERMINAL_CASE_STATUSES = new Set(["done", "cancelled"]);
|
||||
|
||||
/**
|
||||
* Direct case writes must not close or reopen a case with a primary task past
|
||||
* the authority a terminal handoff requires. Agents need the same ownership of
|
||||
* the primary task, and `done` still goes through the handoff so primary-task
|
||||
* completion passes its normal gates.
|
||||
*/
|
||||
export async function assertCaseStatusWriteAuthority(tx: Db, actor: AuthorizationActor,
|
||||
current: { companyId: string; status: string; workIssueId: string | null }, nextStatus: string | undefined) {
|
||||
if (actor.type !== "agent" || nextStatus === undefined || nextStatus === current.status || !current.workIssueId) return;
|
||||
if (!TERMINAL_CASE_STATUSES.has(nextStatus) && !TERMINAL_CASE_STATUSES.has(current.status)) return;
|
||||
const [issue] = await tx.select().from(issues)
|
||||
.where(and(eq(issues.id, current.workIssueId), eq(issues.companyId, current.companyId))).limit(1);
|
||||
if (!issue) throw notFound("Task not found");
|
||||
await authorizeTerminalTask(tx, actor, issue);
|
||||
if (nextStatus === "done") {
|
||||
throw unprocessable("Close a case that has a primary task with a terminal handoff to done");
|
||||
}
|
||||
}
|
||||
|
||||
async function authorizeHandoffControl(tx: Db, actor: AuthorizationActor, row: CaseHandoffRow, issue: IssueRow, validateRecipient = true) {
|
||||
if (row.destinationKind === "done") return authorizeTerminalTask(tx, actor, issue);
|
||||
if (!row.toAgentId) throw conflict("Agent handoff has no recipient");
|
||||
|
||||
@@ -22,7 +22,7 @@ export async function hasPublishedGitHubReview(db: Db, binding: {
|
||||
eq(chatActions.companyId, binding.companyId),
|
||||
or(...reviews.map(review => and(
|
||||
eq(chatActions.endpointId, review.endpointId),
|
||||
eq(chatActions.providerActionId, `github_publication:${binding.issueId}:assessment:${createHash("sha256").update(JSON.stringify(review.id)).digest("hex")}`),
|
||||
eq(chatActions.providerActionId, publicationActionId(binding.issueId, review.id)),
|
||||
))),
|
||||
eq(chatActions.kind, "github_review_publication"),
|
||||
eq(chatActions.status, "processed"),
|
||||
@@ -33,20 +33,24 @@ export async function hasPublishedGitHubReview(db: Db, binding: {
|
||||
type WaitRun = Pick<typeof heartbeatRuns.$inferSelect,
|
||||
"id" | "companyId" | "agentId" | "responsibleUserId" | "activeIdentityContextId" | "nativeIssueId" | "issueId" | "contextSnapshot">;
|
||||
|
||||
/** The columns of one inherited review. The single read and the batch read
|
||||
* select the same columns. */
|
||||
const inheritedReviewFields = {
|
||||
id: chatGitHubReviews.id, endpointId: chatGitHubReviews.endpointId,
|
||||
state: chatGitHubReviews.state, repository: chatGitHubReviews.repository,
|
||||
repositoryId: chatGitHubReviews.repositoryId, headSha: chatGitHubReviews.headSha,
|
||||
reviewedCommit: sql<unknown>`${chatGitHubReviews.assessment}->'reviewedCommit'`, reviewRunId: chatGitHubReviews.runId,
|
||||
connectionEnabled: toolConnections.enabled, connectionStatus: toolConnections.status,
|
||||
reviewAgentId: heartbeatRuns.agentId, reviewCompanyId: heartbeatRuns.companyId,
|
||||
resourceRepository: chatEndpointResources.providerResourceId,
|
||||
resourceRepositoryId: sql<string | null>`${chatEndpointResources.metadata}->>'providerRepositoryId'`,
|
||||
pullNumber: chatGitHubReviews.pullNumber, thread: chatConversations.externalThreadId,
|
||||
};
|
||||
|
||||
const inheritedReviewQueries = new WeakMap<Db, ReturnType<typeof prepareInheritedReviewQuery>>();
|
||||
|
||||
function prepareInheritedReviewQuery(db: Db) {
|
||||
return db.select({
|
||||
id: chatGitHubReviews.id, endpointId: chatGitHubReviews.endpointId,
|
||||
state: chatGitHubReviews.state, repository: chatGitHubReviews.repository,
|
||||
repositoryId: chatGitHubReviews.repositoryId, headSha: chatGitHubReviews.headSha,
|
||||
reviewedCommit: sql<unknown>`${chatGitHubReviews.assessment}->'reviewedCommit'`, reviewRunId: chatGitHubReviews.runId,
|
||||
connectionEnabled: toolConnections.enabled, connectionStatus: toolConnections.status,
|
||||
reviewAgentId: heartbeatRuns.agentId, reviewCompanyId: heartbeatRuns.companyId,
|
||||
resourceRepository: chatEndpointResources.providerResourceId,
|
||||
resourceRepositoryId: sql<string | null>`${chatEndpointResources.metadata}->>'providerRepositoryId'`,
|
||||
pullNumber: chatGitHubReviews.pullNumber, thread: chatConversations.externalThreadId,
|
||||
}).from(chatMessageLinks)
|
||||
return db.select(inheritedReviewFields).from(chatMessageLinks)
|
||||
.innerJoin(chatConversations, and(eq(chatConversations.id, chatMessageLinks.conversationId),
|
||||
eq(chatConversations.companyId, sql.placeholder("companyId")), eq(chatConversations.issueId, sql.placeholder("issueId"))))
|
||||
.innerJoin(chatEndpoints, and(eq(chatEndpoints.id, chatConversations.endpointId),
|
||||
@@ -65,6 +69,8 @@ function prepareInheritedReviewQuery(db: Db) {
|
||||
.prepare("inherited_github_review_wait");
|
||||
}
|
||||
|
||||
type InheritedReviewRow = Awaited<ReturnType<ReturnType<typeof prepareInheritedReviewQuery>["execute"]>>[number];
|
||||
|
||||
function inheritedReviewQuery(db: Db) {
|
||||
let query = inheritedReviewQueries.get(db);
|
||||
if (!query) {
|
||||
@@ -74,35 +80,77 @@ function inheritedReviewQuery(db: Db) {
|
||||
return query;
|
||||
}
|
||||
|
||||
/** Passive review waits inherit the same accepted requester lineage as GitHub
|
||||
* tools. This is not a grant to publish, run a monitor, or reuse attachments. */
|
||||
export async function readInheritedGitHubReviewWait(db: Db, run: WaitRun) {
|
||||
type InheritedReviewKey = { commentId: string; issueId: string; agentId: string };
|
||||
|
||||
function inheritedReviewKey(key: InheritedReviewKey) {
|
||||
return `${key.commentId}:${key.issueId}:${key.agentId}`;
|
||||
}
|
||||
|
||||
/** The latest review for each (source comment, task, agent) key of one
|
||||
* company. For each key this is the row of the single prepared read: the same
|
||||
* joins and filters, and DISTINCT ON keeps the first row in the same order. */
|
||||
async function readInheritedReviewsForKeys(db: Db, companyId: string, keys: InheritedReviewKey[]) {
|
||||
const unique = (values: string[]) => [...new Set(values)];
|
||||
const rows = await db.selectDistinctOn([chatMessageLinks.commentId, chatConversations.issueId, chatEndpoints.assignedAgentId], {
|
||||
...inheritedReviewFields,
|
||||
keyCommentId: chatMessageLinks.commentId, keyIssueId: chatConversations.issueId, keyAgentId: chatEndpoints.assignedAgentId,
|
||||
}).from(chatMessageLinks)
|
||||
.innerJoin(chatConversations, and(eq(chatConversations.id, chatMessageLinks.conversationId),
|
||||
eq(chatConversations.companyId, companyId),
|
||||
sql`${chatConversations.issueId} = any(${sql.param(unique(keys.map(key => key.issueId)))}::uuid[])`))
|
||||
.innerJoin(chatEndpoints, and(eq(chatEndpoints.id, chatConversations.endpointId),
|
||||
eq(chatEndpoints.companyId, companyId), eq(chatEndpoints.provider, "github"),
|
||||
sql`${chatEndpoints.assignedAgentId} = any(${sql.param(unique(keys.map(key => key.agentId)))}::uuid[])`))
|
||||
.leftJoin(toolConnections, and(eq(toolConnections.id, chatEndpoints.connectionId),
|
||||
eq(toolConnections.companyId, companyId)))
|
||||
.innerJoin(chatEndpointResources, and(eq(chatEndpointResources.id, chatConversations.resourceId),
|
||||
eq(chatEndpointResources.companyId, companyId), eq(chatEndpointResources.endpointId, chatEndpoints.id)))
|
||||
.innerJoin(chatGitHubReviews, and(eq(chatGitHubReviews.endpointId, chatEndpoints.id),
|
||||
eq(chatGitHubReviews.companyId, companyId), eq(chatGitHubReviews.issueId, chatConversations.issueId)))
|
||||
.leftJoin(heartbeatRuns, eq(heartbeatRuns.id, chatGitHubReviews.runId))
|
||||
.where(and(eq(chatMessageLinks.companyId, companyId),
|
||||
sql`${chatMessageLinks.commentId} = any(${sql.param(unique(keys.map(key => key.commentId)))}::uuid[])`,
|
||||
eq(chatMessageLinks.direction, "inbound")))
|
||||
.orderBy(chatMessageLinks.commentId, chatConversations.issueId, chatEndpoints.assignedAgentId,
|
||||
desc(chatGitHubReviews.createdAt), desc(chatGitHubReviews.id));
|
||||
// The array filters can also match a mix of two keys. Only exact keys are read.
|
||||
const byKey = new Map<string, InheritedReviewRow>();
|
||||
for (const { keyCommentId, keyIssueId, keyAgentId, ...review } of rows) {
|
||||
if (keyCommentId && keyIssueId && keyAgentId) {
|
||||
byKey.set(inheritedReviewKey({ commentId: keyCommentId, issueId: keyIssueId, agentId: keyAgentId }), review);
|
||||
}
|
||||
}
|
||||
return byKey;
|
||||
}
|
||||
|
||||
function publicationActionId(issueId: string, reviewId: string) {
|
||||
return `github_publication:${issueId}:assessment:${createHash("sha256").update(JSON.stringify(reviewId)).digest("hex")}`;
|
||||
}
|
||||
|
||||
/** The accepted GitHub source comment of the run. A changed requester lineage
|
||||
* revokes the inherited wait. */
|
||||
async function inheritedSourceComment(db: Db, run: WaitRun): Promise<{ kind: "revoked" } | { commentId: string } | null> {
|
||||
if (!run.activeIdentityContextId || !run.nativeIssueId) return null;
|
||||
let commentId: string | null;
|
||||
try {
|
||||
commentId = await chatRunSourceMessageId(db, run, { provider: "github" });
|
||||
} catch (error) {
|
||||
if (error instanceof HttpError && error.status === 403) return { kind: "revoked" as const };
|
||||
if (error instanceof HttpError && error.status === 403) return { kind: "revoked" };
|
||||
throw error;
|
||||
}
|
||||
if (!commentId) return null;
|
||||
const [review] = await inheritedReviewQuery(db).execute({
|
||||
companyId: run.companyId, issueId: run.nativeIssueId, agentId: run.agentId, commentId,
|
||||
});
|
||||
// A newer unreviewed head cannot inherit the prior head's publication.
|
||||
if (!review) return null;
|
||||
if (!review.connectionEnabled || review.connectionStatus !== "active" || review.state !== "completed" ||
|
||||
review.reviewCompanyId !== run.companyId || review.reviewAgentId !== run.agentId ||
|
||||
review.reviewedCommit !== review.headSha ||
|
||||
review.resourceRepository.toLowerCase() !== review.repository.toLowerCase() ||
|
||||
review.resourceRepositoryId !== review.repositoryId ||
|
||||
review.thread.toLowerCase() !== `github:${review.repository}:${review.pullNumber}`.toLowerCase()) return { kind: "revoked" as const };
|
||||
const [publication] = await db.select({ id: chatActions.id }).from(chatActions).where(and(
|
||||
eq(chatActions.companyId, run.companyId), eq(chatActions.endpointId, review.endpointId),
|
||||
eq(chatActions.kind, "github_review_publication"), eq(chatActions.status, "processed"),
|
||||
eq(chatActions.providerActionId, `github_publication:${run.nativeIssueId}:assessment:${createHash("sha256").update(JSON.stringify(review.id)).digest("hex")}`),
|
||||
)).limit(1);
|
||||
if (!publication) return { kind: "revoked" as const };
|
||||
return commentId ? { commentId } : null;
|
||||
}
|
||||
|
||||
function inheritedReviewRevoked(run: WaitRun, review: InheritedReviewRow) {
|
||||
return !review.connectionEnabled || review.connectionStatus !== "active" || review.state !== "completed" ||
|
||||
review.reviewCompanyId !== run.companyId || review.reviewAgentId !== run.agentId ||
|
||||
review.reviewedCommit !== review.headSha ||
|
||||
review.resourceRepository.toLowerCase() !== review.repository.toLowerCase() ||
|
||||
review.resourceRepositoryId !== review.repositoryId ||
|
||||
review.thread.toLowerCase() !== `github:${review.repository}:${review.pullNumber}`.toLowerCase();
|
||||
}
|
||||
|
||||
function publishedInheritedWait(run: WaitRun, commentId: string, review: InheritedReviewRow) {
|
||||
// The caller must still verify live task ownership, destination and principal
|
||||
// policy. This normalized source is used only by the passive-wait boundary.
|
||||
return { kind: "published" as const, endpointId: review.endpointId, reviewId: review.id, reviewRunId: review.reviewRunId,
|
||||
@@ -113,3 +161,74 @@ export async function readInheritedGitHubReviewWait(db: Db, run: WaitRun) {
|
||||
issue: { id: run.nativeIssueId }, commentIds: [commentId] },
|
||||
} };
|
||||
}
|
||||
|
||||
export type InheritedGitHubReviewWait = { kind: "revoked" } | ReturnType<typeof publishedInheritedWait> | null;
|
||||
|
||||
/** Passive review waits inherit the same accepted requester lineage as GitHub
|
||||
* tools. This is not a grant to publish, run a monitor, or reuse attachments. */
|
||||
export async function readInheritedGitHubReviewWait(db: Db, run: WaitRun): Promise<InheritedGitHubReviewWait> {
|
||||
const source = await inheritedSourceComment(db, run);
|
||||
if (!source || !("commentId" in source)) return source;
|
||||
const { commentId } = source;
|
||||
const [review] = await inheritedReviewQuery(db).execute({
|
||||
companyId: run.companyId, issueId: run.nativeIssueId, agentId: run.agentId, commentId,
|
||||
});
|
||||
// A newer unreviewed head cannot inherit the prior head's publication.
|
||||
if (!review) return null;
|
||||
if (inheritedReviewRevoked(run, review)) return { kind: "revoked" };
|
||||
const [publication] = await db.select({ id: chatActions.id }).from(chatActions).where(and(
|
||||
eq(chatActions.companyId, run.companyId), eq(chatActions.endpointId, review.endpointId),
|
||||
eq(chatActions.kind, "github_review_publication"), eq(chatActions.status, "processed"),
|
||||
eq(chatActions.providerActionId, publicationActionId(run.nativeIssueId!, review.id)),
|
||||
)).limit(1);
|
||||
if (!publication) return { kind: "revoked" };
|
||||
return publishedInheritedWait(run, commentId, review);
|
||||
}
|
||||
|
||||
/** `readInheritedGitHubReviewWait` for the runs of one read-only pass, such
|
||||
* as the waits of an issue page. Each run gets the same result as a separate
|
||||
* call. The source lineage is still checked for each run. The reviews and the
|
||||
* publications of all the runs of one company are read with one statement
|
||||
* each, not with two statements for each run. */
|
||||
export async function readInheritedGitHubReviewWaits(db: Db, runs: WaitRun[]): Promise<InheritedGitHubReviewWait[]> {
|
||||
const sources = await Promise.all(runs.map(run => inheritedSourceComment(db, run)));
|
||||
const results: InheritedGitHubReviewWait[] = sources.map(source => source && !("commentId" in source) ? source : null);
|
||||
const byCompany = new Map<string, Array<{ index: number; run: WaitRun; commentId: string }>>();
|
||||
runs.forEach((run, index) => {
|
||||
const source = sources[index];
|
||||
if (!source || !("commentId" in source)) return;
|
||||
const entries = byCompany.get(run.companyId) ?? [];
|
||||
entries.push({ index, run, commentId: source.commentId });
|
||||
byCompany.set(run.companyId, entries);
|
||||
});
|
||||
for (const [companyId, entries] of byCompany) {
|
||||
const keyOf = ({ run, commentId }: { run: WaitRun; commentId: string }) =>
|
||||
({ commentId, issueId: run.nativeIssueId!, agentId: run.agentId });
|
||||
const reviews = await readInheritedReviewsForKeys(db, companyId, entries.map(keyOf));
|
||||
const reviewed: Array<{ index: number; run: WaitRun; commentId: string; review: InheritedReviewRow; actionId: string }> = [];
|
||||
for (const entry of entries) {
|
||||
const review = reviews.get(inheritedReviewKey(keyOf(entry)));
|
||||
// A newer unreviewed head cannot inherit the prior head's publication.
|
||||
if (!review) continue;
|
||||
if (inheritedReviewRevoked(entry.run, review)) {
|
||||
results[entry.index] = { kind: "revoked" };
|
||||
continue;
|
||||
}
|
||||
reviewed.push({ ...entry, review, actionId: publicationActionId(entry.run.nativeIssueId!, review.id) });
|
||||
}
|
||||
if (!reviewed.length) continue;
|
||||
const publications = await db.select({ endpointId: chatActions.endpointId, providerActionId: chatActions.providerActionId })
|
||||
.from(chatActions).where(and(
|
||||
eq(chatActions.companyId, companyId),
|
||||
sql`${chatActions.endpointId} = any(${sql.param([...new Set(reviewed.map(entry => entry.review.endpointId))])}::uuid[])`,
|
||||
eq(chatActions.kind, "github_review_publication"), eq(chatActions.status, "processed"),
|
||||
sql`${chatActions.providerActionId} = any(${sql.param([...new Set(reviewed.map(entry => entry.actionId))])}::text[])`,
|
||||
));
|
||||
const processed = new Set(publications.map(publication => `${publication.endpointId}:${publication.providerActionId}`));
|
||||
for (const { index, run, commentId, review, actionId } of reviewed) {
|
||||
results[index] = processed.has(`${review.endpointId}:${actionId}`)
|
||||
? publishedInheritedWait(run, commentId, review) : { kind: "revoked" };
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
@@ -21,6 +21,22 @@ export function registerGitHubTerminalResponseWork(
|
||||
const repositoryId = sql<string | null>`${chatEndpointResources.metadata}->>'providerRepositoryId'`;
|
||||
const number = sql<string | null>`substring(${chatConversations.externalThreadId}
|
||||
from '^github:[^:]+:(?:issue:)?([1-9][0-9]*)(?::rc:[1-9][0-9]*)?$')`;
|
||||
// Status of the assigned agent's latest run bound to the issue, where a run's
|
||||
// issue is coalesce(native_issue_id, context_snapshot->>'issueId'). The two
|
||||
// precedence branches are disjoint and each uses an issue index, so a
|
||||
// candidate does not walk (and detoast) the agent's whole run history.
|
||||
const latestIssueRunStatus = sql<string | null>`select latest.status from (
|
||||
(select r.status, r.created_at, r.id from ${heartbeatRuns} r
|
||||
where r.company_id = ${chatActions.companyId} and r.native_issue_id = ${chatConversations.issueId}
|
||||
and r.agent_id = ${chatEndpoints.assignedAgentId}
|
||||
order by r.created_at desc, r.id desc limit 1)
|
||||
union all
|
||||
(select r.status, r.created_at, r.id from ${heartbeatRuns} r
|
||||
where r.company_id = ${chatActions.companyId} and r.native_issue_id is null
|
||||
and r.context_snapshot->>'issueId' = ${chatConversations.issueId}::text
|
||||
and r.agent_id = ${chatEndpoints.assignedAgentId}
|
||||
order by r.created_at desc, r.id desc limit 1)
|
||||
) latest order by latest.created_at desc, latest.id desc limit 1`;
|
||||
async function page(scope?: Scope, cursor?: string, actionId?: string) {
|
||||
return db.select({
|
||||
id: chatActions.id, companyId: chatActions.companyId, endpointId: chatActions.endpointId,
|
||||
@@ -42,10 +58,7 @@ export function registerGitHubTerminalResponseWork(
|
||||
.where(and(eq(chatActions.kind, "github_response_comment"), eq(chatActions.status, "processed"),
|
||||
isNotNull(chatActions.deliveryId), isNotNull(chatEndpoints.assignedAgentId),
|
||||
sql`coalesce(${chatActions.result}->>'final', 'false') <> 'true'`,
|
||||
sql`(${issues.status} = 'blocked' or (select r.status from ${heartbeatRuns} r
|
||||
where r.company_id = ${chatActions.companyId} and r.agent_id = ${chatEndpoints.assignedAgentId}
|
||||
and coalesce(r.native_issue_id::text, r.context_snapshot->>'issueId') = ${chatConversations.issueId}::text
|
||||
order by r.created_at desc, r.id desc limit 1) in ('succeeded', 'failed', 'interrupted', 'timed_out', 'cancelled'))`,
|
||||
sql`(${issues.status} = 'blocked' or (${latestIssueRunStatus}) in ('succeeded', 'failed', 'interrupted', 'timed_out', 'cancelled'))`,
|
||||
scope ? eq(chatActions.companyId, scope.companyId) : undefined,
|
||||
scope?.issueId ? eq(issues.id, scope.issueId) : undefined,
|
||||
scope?.conversationId ? eq(chatActions.conversationId, scope.conversationId) : undefined,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EXTERNAL_CHAT_MESSAGE_WAKE_MUTATION, EXTERNAL_CHAT_MESSAGE_WAKE_REASON } from "../../queued-comment-delivery.js";
|
||||
import { notifyChatInboundWakeNotices } from "../../chat-inbound-wake-notice-notifications.js";
|
||||
import { DELIVERY_PROCESSING_STALE_MS } from "./delivery-ledger.js";
|
||||
import type { EndpointRow, DbOrTransaction } from "../runtime-types.js";
|
||||
@@ -367,8 +368,8 @@ export function createInboundWakeups(db: Db, options: WakeupOptions) {
|
||||
await queueIssueAssignmentWakeup({
|
||||
heartbeat: options.heartbeat,
|
||||
issue: context.issue,
|
||||
reason: "External chat message received",
|
||||
mutation: "chat_message_received",
|
||||
reason: EXTERNAL_CHAT_MESSAGE_WAKE_REASON,
|
||||
mutation: EXTERNAL_CHAT_MESSAGE_WAKE_MUTATION,
|
||||
contextSource: `chat:${context.endpoint.provider}`,
|
||||
requestedByActorType: request.requestedByActorType,
|
||||
requestedByActorId: request.requestedByActorId,
|
||||
@@ -471,7 +472,7 @@ export function createInboundWakeups(db: Db, options: WakeupOptions) {
|
||||
});
|
||||
assertDurableChatWakeupReceipt(request, receipt);
|
||||
await queueIssueAssignmentWakeup({ heartbeat: options.heartbeat, issue: context.issue,
|
||||
reason: "External chat message received", mutation: "chat_message_received",
|
||||
reason: EXTERNAL_CHAT_MESSAGE_WAKE_REASON, mutation: EXTERNAL_CHAT_MESSAGE_WAKE_MUTATION,
|
||||
contextSource: `chat:${context.endpoint.provider}`, taskKey: context.issue.identifier,
|
||||
requestedByActorType: request.requestedByActorType, requestedByActorId: request.requestedByActorId,
|
||||
wakeCommentId: request.commentId, chatConversationId: context.conversation.id,
|
||||
|
||||
@@ -92,6 +92,9 @@ export type ChatControlRecoveryStop =
|
||||
sourceRunId: string;
|
||||
};
|
||||
|
||||
/** Status-decision effects whose target is the native-status wake intent. */
|
||||
const NATIVE_STATUS_WAKE_EFFECT_KINDS = ["enqueue_continuation", "schedule_retry"];
|
||||
|
||||
/** A dispatched native continuation inherits only its committed decision's
|
||||
* source run. Arbitrary payload.nativeDecisionId / context.source is not proof. */
|
||||
export async function readChatControlNativeParent(
|
||||
@@ -137,7 +140,10 @@ export async function readChatControlNativeParent(
|
||||
eq(statusDecisionEffects.companyId, scope.companyId),
|
||||
eq(statusDecisionEffects.issueId, scope.issueId),
|
||||
eq(statusDecisionEffects.decisionId, statusDecisions.id),
|
||||
eq(statusDecisionEffects.effectKind, "enqueue_continuation"),
|
||||
// A committed continuation or failed-turn retry effect that targets
|
||||
// this intent is its proof. Refusing the retry stranded the task
|
||||
// with no queued work.
|
||||
inArray(statusDecisionEffects.effectKind, NATIVE_STATUS_WAKE_EFFECT_KINDS),
|
||||
eq(statusDecisionEffects.targetType, "agent_wakeup_request"),
|
||||
eq(statusDecisionEffects.targetId, intent.id),
|
||||
eq(statusDecisionEffects.deliveryState, "delivered"),
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
assertDurableChatWakeupReceipt,
|
||||
createDurableChatWakeupRequest,
|
||||
} from "./durable-chat-wakeup.js";
|
||||
import { QUEUED_MESSAGES_DELIVERED_REASON } from "../modules/wake-queue/index.js";
|
||||
|
||||
type Action = typeof chatActions.$inferSelect;
|
||||
type Receipt = typeof agentWakeupRequests.$inferSelect;
|
||||
@@ -125,6 +126,10 @@ export function resolveInboundWakeReceipt(
|
||||
const declined =
|
||||
["skipped", "cancelled", "failed"].includes(owner.status) ||
|
||||
["skipped", "cancelled", "failed"].includes(receipt.status);
|
||||
// A completed run already received this message and answered it. Saying
|
||||
// "not started" would be wrong; it keeps the same silence as a promotion.
|
||||
if (declined && owner.status === "cancelled" && owner.error === QUEUED_MESSAGES_DELIVERED_REASON)
|
||||
return null;
|
||||
if (declined)
|
||||
return owner.runId || receipt.runId
|
||||
? null
|
||||
|
||||
@@ -200,20 +200,6 @@ export function processStartsDefinitelyDiffer(
|
||||
return Number.isFinite(left) && Number.isFinite(right) && Math.abs(left - right) >= PROCESS_START_PRECISION_MS;
|
||||
}
|
||||
|
||||
/** True only with proof, in this process's own PID space, that the recorded
|
||||
* server process has exited. Another space, an unreadable space, this server,
|
||||
* or an ambiguous live PID returns false. */
|
||||
export async function controllerProcessExited(controller: ControllerProcess): Promise<boolean> {
|
||||
if (controller.bootId === bootId || hostHash === UNKNOWN_PROCESS_SPACE || controller.hostHash !== hostHash) return false;
|
||||
if (!processExists(controller.pid)) return true;
|
||||
// Without a recorded start time a live PID can never prove exit; skip the probe.
|
||||
if (!Number.isFinite(Date.parse(controller.processStartedAt ?? ""))) return false;
|
||||
// The PID now belongs to a live process, possibly this restarted server.
|
||||
// Only a definitely different start time proves the recorded process is gone.
|
||||
const observed = await observedProcessStartedAt(controller.pid);
|
||||
return observed !== null && processStartsDefinitelyDiffer(controller.processStartedAt, new Date(observed));
|
||||
}
|
||||
|
||||
/** This process's PID-space hash. An unreadable space is stored as
|
||||
* "unknown", which `sameProcessSpace` never accepts. */
|
||||
export function currentProcessSpaceHash(): string {
|
||||
|
||||
@@ -50,10 +50,8 @@ describe("controller process-space identity", () => {
|
||||
expect(state.sysctl).toHaveBeenCalledTimes(2);
|
||||
expect(JSON.stringify(first)).not.toContain(firstBoot);
|
||||
// Old weak/foreign receipts retain their original deadline: no local probe.
|
||||
const kill = vi.spyOn(process, "kill");
|
||||
expect(await owner.controllerProcessExited({ bootId: "old", pid: 2_000_000_001,
|
||||
hostHash: "old-rounded-clock-hash", processStartedAt: null })).toBe(false);
|
||||
expect(kill).not.toHaveBeenCalled();
|
||||
expect(owner.sameProcessSpace("old-rounded-clock-hash")).toBe(false);
|
||||
expect(owner.sameProcessSpace(first.hostHash)).toBe(true);
|
||||
});
|
||||
|
||||
it.each(["unreadable", "malformed", "unsupported"] as const)("fails closed without an owner PID probe for %s identity", async mode => {
|
||||
@@ -62,10 +60,7 @@ describe("controller process-space identity", () => {
|
||||
if (mode === "malformed") state.sysctl.mockReturnValue("not-a-kernel-uuid");
|
||||
const owner = await fresh();
|
||||
expect((await owner.currentControllerProcess()).hostHash).toBe("unknown");
|
||||
const kill = vi.spyOn(process, "kill");
|
||||
expect(await owner.controllerProcessExited({ bootId: "old", pid: 2_000_000_001,
|
||||
hostHash: "unknown", processStartedAt: null })).toBe(false);
|
||||
expect(kill).not.toHaveBeenCalled();
|
||||
expect(owner.sameProcessSpace("unknown")).toBe(false);
|
||||
if (mode === "unsupported") expect(state.sysctl).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -58,6 +58,7 @@ export const DELIVERY_QUEUES = {
|
||||
scheduledRetryCancellation: "scheduled-retry-cancellation",
|
||||
executionFinalization: "execution-finalization",
|
||||
workspaceRecovery: "workspace-recovery",
|
||||
providerLimitResume: "provider-limit-resume",
|
||||
executionReplacement: "execution-replacement",
|
||||
executionContinuation: "execution-continuation",
|
||||
executionStatus: "execution-status",
|
||||
|
||||
@@ -134,7 +134,11 @@ export async function appendHeartbeatRunEvent(
|
||||
...(projectsProgress ? { issueId: boundRunIssueIdSql() } : {}) })
|
||||
.from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.id, input.runId))
|
||||
.for("update")
|
||||
// Appenders, Stop, recovery and deletion still serialize on this row.
|
||||
// The append never changes key columns, so it must not block foreign
|
||||
// key checks (FOR KEY SHARE) of child rows, such as controller
|
||||
// checkpoints, that are written for the same run while events stream.
|
||||
.for("no key update")
|
||||
.limit(1)
|
||||
.then((rows) => rows[0] ?? null);
|
||||
if (!run || run.companyId !== input.companyId || run.agentId !== input.agentId) {
|
||||
|
||||
@@ -9,6 +9,7 @@ import { isContextCompactionRun } from "./context-compaction.js";
|
||||
import { isUnstartedTaskQuestionAnswer } from "./unstarted-task-question-answer.js";
|
||||
import { isVerifiedDependencyInteractionResponse } from "./queued-interaction-response.js";
|
||||
import { registerDeferredReceiptWork } from "./heartbeat/deferred-receipt-work.js";
|
||||
import { registerProviderLimitResumeWork, type PrepareChatRetry } from "./native-runtime/provider-limit-resume.js";
|
||||
import { reconcileTaskChatRetryReceipts } from "./task-retry.js";
|
||||
import { registerIssueRecoveryWork } from "./recovery/work.js";
|
||||
import { registerRunDispatchWork } from "./heartbeat/dispatch-work.js";
|
||||
@@ -54,7 +55,7 @@ import { prepareHeartbeatTaskContext } from "./heartbeat/task-context.js";
|
||||
import { selectHeartbeatEnvironment } from "./heartbeat/environment-selection.js";
|
||||
import { reconcileMuseNativeTerminalRun } from "./native-runtime/muse-terminal-reconciliation.js";
|
||||
import { prepareHeartbeatWorkspace } from "./heartbeat/workspace-preparation.js";
|
||||
import { nativeRecoveryClaimRelinquished, releaseLapsedNativeRestartClaim } from "./native-runtime/native-execution-lease.js";
|
||||
import { nativeRecoveryClaimRelinquished, ownNativeExecutionLeaseLapsed, releaseLapsedNativeRestartClaim } from "./native-runtime/native-execution-lease.js";
|
||||
import { executeHeartbeatRuntime, NativeSessionResumeScheduledError, NativeWorkspaceFinalizeScheduledError } from "./heartbeat/runtime-execution.js";
|
||||
import { preserveNativeFailedWorkspace } from "./native-runtime/native-failed-workspace-recovery.js";
|
||||
import { nativeRunHasNoWorkspaceAccess } from "./workspace-restore-recovery-state.js";
|
||||
@@ -2040,6 +2041,11 @@ export function heartbeatService(
|
||||
Parameters<typeof cleanupGitHubOperationLaunchers>[0] | null = null;
|
||||
let nativeSessionResumeScheduled = false;
|
||||
let restartClaimLapsed = false;
|
||||
// The executor detached for "the next controller" because its own lease
|
||||
// lapsed (for example after a stall), with no shutdown or hot-restart
|
||||
// handoff. The next controller is this process: recover the run here once
|
||||
// the executor has exited. A shutdown detach leaves it to the next server.
|
||||
let detachedWithoutHandoff = false;
|
||||
const shutdownHandedOff = watchShutdownHandoff(run.id);
|
||||
let nativeOwnershipHeld = false;
|
||||
let nativeStartupCleanupScheduled = false;
|
||||
@@ -3706,6 +3712,8 @@ export function heartbeatService(
|
||||
}
|
||||
if (err instanceof NativeControllerDetachedForRestartError) {
|
||||
nativeSessionResumeScheduled = true;
|
||||
detachedWithoutHandoff = !shutdownHandedOff() && await ownNativeExecutionLeaseLapsed(db, run)
|
||||
.catch(() => false);
|
||||
return;
|
||||
}
|
||||
if (err instanceof NativeRunnerOwnershipUnverifiedError) {
|
||||
@@ -4167,7 +4175,7 @@ export function heartbeatService(
|
||||
} finally {
|
||||
controllerLease.stop();
|
||||
activeRunExecutions.delete(run.id);
|
||||
if (restartClaimLapsed) scheduleNativeSessionResumeDispatch(run.id, new Date(), "restart");
|
||||
if (restartClaimLapsed || detachedWithoutHandoff) scheduleNativeSessionResumeDispatch(run.id, new Date(), "restart");
|
||||
// A failed owned Stop remains visible until this exact executor settles,
|
||||
// including a graceful exit result arriving after the cancellation error.
|
||||
// It is never retained beyond the active execution's cleanup.
|
||||
@@ -4522,6 +4530,13 @@ export function heartbeatService(
|
||||
},
|
||||
}, () => canRun() && readTaskDrain(new Date()) === null),
|
||||
readIdleWatchdogSchedule: taskWatchdogs.readIdleSchedule,
|
||||
registerProviderLimitResumeWork: (coordinator: Parameters<typeof registerProviderLimitResumeWork>[1], canRun: () => boolean,
|
||||
prepareChatRetry?: () => PrepareChatRetry | undefined) =>
|
||||
registerProviderLimitResumeWork(db, coordinator, {
|
||||
resume: (companyId, requestId) => runControl.resumeTaskRetry(companyId, requestId),
|
||||
schedulingSuppressed: async () => (await getSchedulingSuppression(true)).suppressed,
|
||||
prepareChatRetry,
|
||||
}, () => canRun() && readTaskDrain(new Date()) === null),
|
||||
registerIssueStateRecoveryWork: (coordinator: Parameters<typeof registerIssueRecoveryWork>[1], canRun: () => boolean) =>
|
||||
registerIssueRecoveryWork(db, coordinator, {
|
||||
stranded: scope => reconcileStrandedAssignedIssues({ ...scope, skipExternalConversationSettlement: true, skipRelatedRecovery: true }),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { QUEUED_MESSAGES_DELIVERED_REASON } from "../../modules/wake-queue/index.js";
|
||||
import { connectionIntentService } from "../connection-intents.js";
|
||||
import { verifyBlockerStallWake } from "../recovery/blocker-stall-wakeups.js";
|
||||
import { CONTEXT_COMPACTION_WAKE_REASON, ContextCompactionError, isContextCompactionRun, readContextCompactionRequest } from "../context-compaction.js";
|
||||
@@ -1920,7 +1921,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
const remaining = commentIds.filter(commentId => !delivered.has(commentId));
|
||||
const now = new Date();
|
||||
await db.update(agentWakeupRequests).set(remaining.length === 0
|
||||
? { status: "cancelled", finishedAt: now, updatedAt: now, error: "Queued messages were already delivered to a completed run" }
|
||||
? { status: "cancelled", finishedAt: now, updatedAt: now, error: QUEUED_MESSAGES_DELIVERED_REASON }
|
||||
: { payload: withQueuedCommentIdsInWakePayload(parseObject(receipt.payload), remaining), updatedAt: now })
|
||||
.where(and(eq(agentWakeupRequests.id, receipt.id), eq(agentWakeupRequests.status, "deferred_issue_execution")));
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { settleOwnableKind } from "../recovery/ownership-invariant-report.js";
|
||||
import { markRunHandedOffForShutdown } from "./shutdown-handoff.js";
|
||||
import { isRunHandedOffForShutdown, markRunHandedOffForShutdown } from "./shutdown-handoff.js";
|
||||
import { ORPHANED_RUN_LEASE_FAILURE_REASON } from "../environment-run-lease-settlement.js";
|
||||
import { ENVIRONMENT_LEASE_CONTROLLER_KEY } from "../environment-lease-controller.js";
|
||||
import { readNativeStartupCleanup, readNativeStartupContext } from "../native-runtime/native-startup-cleanup.js";
|
||||
@@ -1009,6 +1009,7 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
},
|
||||
db,
|
||||
liveRunExecutions: activeRunExecutions,
|
||||
handedOffForShutdown: isRunHandedOffForShutdown,
|
||||
runIds,
|
||||
restartKind,
|
||||
recoveryRequestId: intent?.recoveryRequestId ?? null,
|
||||
@@ -2660,8 +2661,8 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
continue;
|
||||
}
|
||||
// A legacy controller persists "dispatching" in the same lease renewal
|
||||
// that admits the adapter. An expired lease from another boot that is
|
||||
// still "preparing" proves a restart stopped setup before provider work.
|
||||
// that admits the adapter. An expired lease that is still "preparing"
|
||||
// proves setup stopped before provider work.
|
||||
// Use the state committed with the revocation, not the earlier snapshot:
|
||||
// the old controller may have dispatched before its lease expired.
|
||||
// The revocation matched the snapshot's boot ID before replacing it.
|
||||
@@ -2669,7 +2670,6 @@ export function createHeartbeatRecovery(db: Db, dependencies: HeartbeatRecoveryD
|
||||
run.runtimeMode === "legacy" &&
|
||||
revokedState.executionStage === "preparing" &&
|
||||
!!run.controllerBootId &&
|
||||
run.controllerBootId !== legacyControllerBootId &&
|
||||
!revokedState.processPid &&
|
||||
!revokedState.processGroupId;
|
||||
const shouldRetry =
|
||||
|
||||
@@ -19,8 +19,8 @@ function isReattachmentLoss(error: string | null): boolean {
|
||||
return error !== null && REATTACHMENT_LOST_ERRORS.some(code => error === code || error.startsWith(`${code}: `));
|
||||
}
|
||||
|
||||
const TURN_STARTED_EVENTS = ["turn.submitted", "turn.started", "turn.accepted"];
|
||||
const TURN_SETTLED_EVENTS = ["turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"];
|
||||
export const TURN_STARTED_EVENTS = ["turn.submitted", "turn.started", "turn.accepted"];
|
||||
export const TURN_SETTLED_EVENTS = ["turn.completed", "turn.failed", "turn.cancelled", "turn.interrupted"];
|
||||
|
||||
const asRecord = (value: unknown): Record<string, unknown> =>
|
||||
value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
|
||||
@@ -29,7 +29,7 @@ const asRecord = (value: unknown): Record<string, unknown> =>
|
||||
* A driver that lost its event stream records `providerTerminalObserved: false`
|
||||
* (on the event or its stored PRP source): the real outcome is unknown, and
|
||||
* another turn could repeat work that already happened. */
|
||||
function isProvenTurnSettlement(event: { eventType: string; payload: unknown }) {
|
||||
export function isProvenTurnSettlement(event: { eventType: string; payload: unknown }) {
|
||||
if (!TURN_SETTLED_EVENTS.includes(event.eventType)) return false;
|
||||
const payload = asRecord(event.payload);
|
||||
return payload.providerTerminalObserved !== false &&
|
||||
|
||||
@@ -33,7 +33,7 @@ import { PluginWorkerUnavailableError } from "../plugin-worker-unavailable-error
|
||||
import { ReviewedChatBindingDeniedError, ReviewedChatBindingNotReadyError } from "../reviewed-chat-binding-diagnostics.js";
|
||||
import { environmentTaskErrorCodeData, JsonRpcCallError, PluginEnvironmentTaskError, PluginWorkspaceOperationError, workspaceOperationErrorData } from "@paperclipai/plugin-sdk";
|
||||
import { RUNNER_REVISION_MISMATCH_RETRY } from "../runner-revision-mismatch.js";
|
||||
import { STORAGE_UNAVAILABLE_CODE, STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE, STORAGE_UNAVAILABLE_MESSAGE, STORAGE_UNAVAILABLE_RETRY } from "../../storage/storage-unavailable.js";
|
||||
import { STORAGE_CREDENTIALS_REJECTED_HELD_MESSAGE, STORAGE_UNAVAILABLE_CODE, STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE, STORAGE_UNAVAILABLE_HELD_MESSAGE, STORAGE_UNAVAILABLE_MESSAGE, STORAGE_UNAVAILABLE_RETRY } from "../../storage/storage-unavailable.js";
|
||||
import { withS3FailureDiagnostics } from "../../storage/s3-failure.js";
|
||||
import { workspaceProviderCallFailure } from "../workspace-provider-failure.js";
|
||||
import { logger } from "../../middleware/logger.js";
|
||||
@@ -857,6 +857,64 @@ describe.skipIf(!support.supported && !process.env.PAPERCLIP_TEST_DATABASE_URL)(
|
||||
error: STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE });
|
||||
});
|
||||
|
||||
// Staging incident shape: a server restart reattached a remote native runner whose turn was
|
||||
// still in flight. A storage outage then failed the reattachment, restart
|
||||
// recovery kept the workspace under a no-replay hold, and the run reported
|
||||
// "Paperclip will retry automatically when storage is back" with no storage
|
||||
// wait scheduled. The task sat blocked for 15 hours behind a false promise.
|
||||
it.each([
|
||||
["an outage", "ServiceUnavailable", 503, STORAGE_UNAVAILABLE_HELD_MESSAGE],
|
||||
["rejected credentials", "ExpiredToken", 403, STORAGE_CREDENTIALS_REJECTED_HELD_MESSAGE],
|
||||
] as const)("never promises a storage retry when native recovery holds the run after %s", async (_label, name, status, expected) => {
|
||||
const f = await fixture({ runtimeMode: "native" });
|
||||
const [issue] = await db.insert(issues).values({ companyId: f.run.companyId, title: "Daily staging review",
|
||||
assigneeAgentId: f.agent.id, status: "in_progress" }).returning();
|
||||
await db.update(agentWakeupRequests).set({ runId: f.run.id, reason: "issue_monitor_due", requestedByActorType: "system" })
|
||||
.where(eq(agentWakeupRequests.id, f.wake.id));
|
||||
const [run] = await db.update(heartbeatRuns).set({ nativeIssueId: issue.id,
|
||||
contextSnapshot: { issueId: issue.id, wakeReason: "issue_monitor_due", wakeSource: "automation" } })
|
||||
.where(eq(heartbeatRuns.id, f.run.id)).returning();
|
||||
await appendHeartbeatRunEvent(db, { companyId: run.companyId, runId: run.id, agentId: run.agentId,
|
||||
eventType: "turn.started", stream: "system", level: "info", message: "Provider turn started" });
|
||||
// Restart recovery's workspace preservation already settled the coordinator.
|
||||
await db.insert(nativeRunFinalizations).values({ companyId: run.companyId, issueId: issue.id, runId: run.id,
|
||||
phase: "terminal_failure", attempt: 1, controllerGeneration: 3, recoveryState: "blocked",
|
||||
failureCode: "native_continuation_requires_reconciliation" });
|
||||
const outage = await withS3FailureDiagnostics("put_object", async () => {
|
||||
throw Object.assign(new Error("Injected storage outage"), { name, $metadata: { httpStatusCode: status, attempts: 3 } });
|
||||
}).catch(error => error as Error);
|
||||
await f.completion.failRun({ ...f.failure(outage), run, issueId: issue.id, requiredWorkspaceRestoreEvidence: {}, legacyAdapterEntered: false });
|
||||
const failed = await read(run.id);
|
||||
expect(failed).toMatchObject({ status: "failed", errorCode: "native_continuation_requires_reconciliation", error: expected });
|
||||
expect(failed.error).not.toMatch(/retry automatically/i);
|
||||
expect(failed.error).toContain("Retry");
|
||||
// No storage wait is created for a run native recovery owns: it could only be refused.
|
||||
expect(f.deps.scheduleBoundedRetryForRun).not.toHaveBeenCalled();
|
||||
const events = await db.select().from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.runId, run.id),
|
||||
eq(heartbeatRunEvents.eventType, "error")));
|
||||
expect(events.map(event => event.message)).toEqual([expected]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["run", "not scheduled"], ["setup", "not scheduled"], ["run", "scheduling failed"], ["setup", "scheduling failed"],
|
||||
] as const)("withdraws the storage retry promise when no storage wait could be scheduled (%s, %s)", async (phase, mode) => {
|
||||
const f = await fixture();
|
||||
const outage = await withS3FailureDiagnostics("put_object", async () => {
|
||||
throw Object.assign(new Error("Injected storage outage"), { name: "ServiceUnavailable", $metadata: { httpStatusCode: 503 } });
|
||||
}).catch(error => error as Error);
|
||||
if (mode === "not scheduled") f.deps.scheduleBoundedRetryForRun.mockResolvedValueOnce({ outcome: "not_scheduled",
|
||||
reason: "Scheduled retry suppressed because the agent is not invokable", errorCode: "agent_not_invokable", issueId: null } as never);
|
||||
else f.deps.scheduleBoundedRetryForRun.mockRejectedValueOnce(new Error("retry write failed"));
|
||||
if (phase === "setup") await f.completion.failRunSetup(f.setup(outage));
|
||||
else await f.completion.failRun(f.failure(outage));
|
||||
expect(f.deps.scheduleBoundedRetryForRun).toHaveBeenCalledWith(expect.objectContaining({ id: f.run.id }), f.agent, STORAGE_UNAVAILABLE_RETRY);
|
||||
expect(await read(f.run.id)).toMatchObject({ status: "failed", errorCode: STORAGE_UNAVAILABLE_CODE,
|
||||
error: STORAGE_UNAVAILABLE_HELD_MESSAGE });
|
||||
const events = await db.select().from(heartbeatRunEvents).where(and(eq(heartbeatRunEvents.runId, f.run.id),
|
||||
eq(heartbeatRunEvents.eventType, "error")));
|
||||
expect(events.map(event => event.message)).toEqual([STORAGE_UNAVAILABLE_HELD_MESSAGE]);
|
||||
});
|
||||
|
||||
it.each(["execution", "setup"] as const)("names the nested cause of a generic %s failure and keeps SQL text off the board", async phase => {
|
||||
const f = await fixture();
|
||||
const logged = vi.spyOn(logger, "error");
|
||||
|
||||
@@ -24,7 +24,7 @@ import { ENVIRONMENT_PROVIDER_UNAVAILABLE_CODE, findEnvironmentProviderUnavailab
|
||||
import { REPOSITORY_CATALOG_UNAVAILABLE_CODE, findRepositoryCatalogUnavailableError } from "../repository-catalog-unavailable-error.js";
|
||||
import { findWorkspaceProviderFailure } from "../workspace-provider-failure.js";
|
||||
import { isRunnerRevisionMismatch, RUNNER_REVISION_MISMATCH_CODE, RUNNER_REVISION_MISMATCH_RETRY } from "../runner-revision-mismatch.js";
|
||||
import { isStorageUnavailableError, STORAGE_UNAVAILABLE_CODE, STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE, STORAGE_UNAVAILABLE_RETRY, storageUnavailableMessage } from "../../storage/storage-unavailable.js";
|
||||
import { isStorageUnavailableError, STORAGE_CREDENTIALS_REJECTED_MESSAGE, STORAGE_UNAVAILABLE_CODE, STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE, STORAGE_UNAVAILABLE_MESSAGE, STORAGE_UNAVAILABLE_RETRY, storageUnavailableHeldMessage, storageUnavailableMessage } from "../../storage/storage-unavailable.js";
|
||||
import { type RunSessionOutcome, resolveNextSessionState, normalizeUsageTotals, resolveCacheAdjustedCostUsd, resolveLedgerBiller, resolveLedgerCostStatus, normalizeLedgerBillingType } from "./run-state.js";
|
||||
import { readGitConnectionFailure } from "../git-connection-failure.js";
|
||||
import { CONFIGURATION_INCOMPLETE_FAILURE_CODE, ConfigurationIncompleteFailure } from "./run-preparation.js";
|
||||
@@ -38,8 +38,8 @@ import { accountRunCost } from "../run-cost-accounting.js";
|
||||
import { isConversation, settleConversationTurn } from "../agent-conversations.js";
|
||||
import { legacyExecutionNeedsReconciliationWithEvidence } from "../legacy-execution-recovery.js";
|
||||
import { isWorkspaceGitScanError } from "../workspace-git-operation-scheduler.js";
|
||||
import { and, eq, isNull, sql } from "drizzle-orm";
|
||||
import { heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults } from "@paperclipai/db";
|
||||
import { and, eq, inArray, isNull, sql } from "drizzle-orm";
|
||||
import { heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults } from "@paperclipai/db";
|
||||
import { HttpError } from "../../errors.js";
|
||||
import { logger } from "../../middleware/logger.js";
|
||||
import { normalizeResponsibleUserDenialCode } from "../responsible-user-denial-run-outcomes.js";
|
||||
@@ -1255,17 +1255,22 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC
|
||||
const interruptedExactResume = exactResumeCause
|
||||
? { ...exactResumeCause, originalMessage: redactFailureText(exactResumeCause.originalMessage) }
|
||||
: null;
|
||||
const message = interruptedExactResume
|
||||
? describeRefusedExactResume(interruptedExactResume, thrownMessage)
|
||||
: isStorageUnavailableError(err) ? storageUnavailableMessage(err) : thrownMessage;
|
||||
const storageUnavailable = isStorageUnavailableError(err);
|
||||
const failureErrorCode =
|
||||
workspaceValidationFailure?.code ??
|
||||
configurationIncompleteFailure?.code ??
|
||||
nonRetryablePreflightFailureCode(err) ??
|
||||
recordedResponsibleUserDenialCode ??
|
||||
nativeTerminalFailureCode ??
|
||||
(isStorageUnavailableError(err) ? STORAGE_UNAVAILABLE_CODE : null) ??
|
||||
(storageUnavailable ? STORAGE_UNAVAILABLE_CODE : null) ??
|
||||
"adapter_failed";
|
||||
// Only a `storage_unavailable` run gets a storage wait. Under any other code
|
||||
// (for example a native recovery hold that keeps the files without
|
||||
// replaying an unfinished turn) nothing retries it, so offer Retry instead.
|
||||
const message = interruptedExactResume
|
||||
? describeRefusedExactResume(interruptedExactResume, thrownMessage)
|
||||
: !storageUnavailable ? thrownMessage
|
||||
: failureErrorCode === STORAGE_UNAVAILABLE_CODE ? storageUnavailableMessage(err) : storageUnavailableHeldMessage(err);
|
||||
const failureCause = GENERIC_RUN_FAILURE_CODES.has(failureErrorCode) ? thrownFailureCause : null;
|
||||
logger.error({ err: identityRedactor.redact({ message: err instanceof Error ? err.message : String(err), stack: err instanceof Error ? err.stack : undefined }), runId,
|
||||
errorCode: failureErrorCode, failureCause: thrownFailureCause }, "heartbeat execution failed");
|
||||
@@ -1395,6 +1400,7 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC
|
||||
}
|
||||
await measureRunPhase("completion.summary", () => refreshContinuationSummaryForRun(livenessRun, agent));
|
||||
if (await pendingCaseHandoffForRun(db, livenessRun.id, livenessRun.companyId)) {
|
||||
await settleStorageWaitMessage(livenessRun, null, err);
|
||||
await releaseIssueExecutionAndPromote(livenessRun, { suppressImmediateRecovery: true });
|
||||
await settleAgent();
|
||||
return;
|
||||
@@ -1411,14 +1417,16 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC
|
||||
return null;
|
||||
})
|
||||
: null;
|
||||
if (storageWait?.outcome === "retry_exhausted") await markStorageWaitExhausted(livenessRun);
|
||||
const nativePreDispatchRetry = storageWait === null ? await scheduleNativePreDispatchRetry(livenessRun, agent) : null;
|
||||
let fallbackRetry: { outcome: string } | null | undefined = nativePreDispatchRetry;
|
||||
if (storageWait?.outcome !== "scheduled" && storageWait?.outcome !== "retry_exhausted" && nativePreDispatchRetry === null) {
|
||||
await scheduleInteractionContinuationInfrastructureRetryIfEligible(
|
||||
fallbackRetry = await scheduleInteractionContinuationInfrastructureRetryIfEligible(
|
||||
livenessRun,
|
||||
agent,
|
||||
);
|
||||
}
|
||||
// Another retry that took over after a failed storage wait keeps the promise.
|
||||
await settleStorageWaitMessage(livenessRun, fallbackRetry?.outcome === "scheduled" ? fallbackRetry : storageWait, err);
|
||||
await releaseIssueExecutionAndPromote(livenessRun, {
|
||||
// Native recovery owns the original heartbeat run through
|
||||
// exhaustion. Once its durable coordinator has classified a
|
||||
@@ -1480,10 +1488,26 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC
|
||||
}
|
||||
}
|
||||
|
||||
async function markStorageWaitExhausted(run: typeof heartbeatRuns.$inferSelect) {
|
||||
await db.update(heartbeatRuns).set({ error: STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE, updatedAt: new Date() })
|
||||
/**
|
||||
* A `storage_unavailable` failure first promises its storage wait. Keep that
|
||||
* promise only when the wait was scheduled. An exhausted wait says so; a wait
|
||||
* that was refused, could not be written, or was preempted by a case handoff
|
||||
* offers Retry instead, because nothing else will retry the run.
|
||||
*/
|
||||
async function settleStorageWaitMessage(run: typeof heartbeatRuns.$inferSelect,
|
||||
wait: { outcome: string } | null | undefined, cause: unknown) {
|
||||
if (run.errorCode !== STORAGE_UNAVAILABLE_CODE || wait?.outcome === "scheduled") return;
|
||||
const error = wait?.outcome === "retry_exhausted" ? STORAGE_UNAVAILABLE_EXHAUSTED_MESSAGE : storageUnavailableHeldMessage(cause);
|
||||
await db.update(heartbeatRuns).set({ error, updatedAt: new Date() })
|
||||
.where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.errorCode, STORAGE_UNAVAILABLE_CODE)))
|
||||
.catch((error: unknown) => logger.warn({ err: error, runId: run.id }, "failed to record an exhausted storage wait"));
|
||||
.catch((writeError: unknown) => logger.warn({ err: writeError, runId: run.id }, "failed to record why no storage wait follows"));
|
||||
// The failure's error event was written before the retry decision. Its
|
||||
// transcript text must not keep a promise that this run no longer makes.
|
||||
await db.update(heartbeatRunEvents).set({ message: error })
|
||||
.where(and(eq(heartbeatRunEvents.companyId, run.companyId), eq(heartbeatRunEvents.runId, run.id),
|
||||
eq(heartbeatRunEvents.eventType, "error"),
|
||||
inArray(heartbeatRunEvents.message, [STORAGE_UNAVAILABLE_MESSAGE, STORAGE_CREDENTIALS_REJECTED_MESSAGE])))
|
||||
.catch((writeError: unknown) => logger.warn({ err: writeError, runId: run.id }, "failed to correct the storage failure event"));
|
||||
}
|
||||
|
||||
async function failRunSetup(input: FailHeartbeatRunSetupInput) {
|
||||
@@ -1501,7 +1525,9 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC
|
||||
const storageUnavailable = isStorageUnavailableError(outerErr);
|
||||
// Bounded code from the error or its first three causes; never message text.
|
||||
const thrownFailureCause = failureCauseFromError(outerErr, providerFailure);
|
||||
const message = storageUnavailable ? storageUnavailableMessage(outerErr) : withoutSqlStatementText(redactCurrentUserText(
|
||||
// A lost controller lease takes the code below and its own retry, so only a
|
||||
// `storage_unavailable` failure carries the storage wait's text.
|
||||
const message = storageUnavailable && !controllerLeaseLost ? storageUnavailableMessage(outerErr) : withoutSqlStatementText(redactCurrentUserText(
|
||||
identityRedactor.redact(outerErr instanceof Error
|
||||
? outerErr.message
|
||||
: "Unknown setup failure"),
|
||||
@@ -1709,6 +1735,7 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC
|
||||
failedRun,
|
||||
).catch(() => failedRun);
|
||||
let storageWaitScheduled = false;
|
||||
let storageWait: { outcome: string } | null = null;
|
||||
let nativePreDispatchRetryScheduled = false;
|
||||
const setupFailureIssueId = readNonEmptyString(
|
||||
parseObject(livenessRun.contextSnapshot).issueId,
|
||||
@@ -1783,12 +1810,13 @@ export function createHeartbeatRunCompletion(db: Db, dependencies: HeartbeatRunC
|
||||
return null;
|
||||
});
|
||||
reviewedChatRetryScheduled = retry?.outcome === "scheduled";
|
||||
if (livenessRun.errorCode === STORAGE_UNAVAILABLE_CODE && retry?.outcome === "retry_exhausted") await markStorageWaitExhausted(livenessRun);
|
||||
storageWait = retry;
|
||||
storageWaitScheduled = livenessRun.errorCode === STORAGE_UNAVAILABLE_CODE
|
||||
&& (retry?.outcome === "scheduled" || retry?.outcome === "retry_exhausted");
|
||||
nativePreDispatchRetryScheduled = retry?.outcome === "scheduled" && isNativePreDispatchTransientFailure(livenessRun);
|
||||
}
|
||||
}
|
||||
await settleStorageWaitMessage(livenessRun, storageWait, outerErr);
|
||||
await releaseIssueExecutionAndPromote(livenessRun, {
|
||||
suppressImmediateRecovery: storageWaitScheduled || nativePreDispatchRetryScheduled ||
|
||||
readNonEmptyString(
|
||||
|
||||
@@ -11,7 +11,9 @@ import { getHeartbeatRunRuntimeStatus } from "../heartbeat-run-runtime-status.js
|
||||
import { createHeartbeatRunState } from "./run-state.js";
|
||||
import { heartbeatService } from "../heartbeat.js";
|
||||
import { createHeartbeatRunPreparation } from "./run-preparation.js";
|
||||
import { createHeartbeatLifecycle, persistHeartbeatRunProcessMetadata, type HeartbeatLifecycleDependencies } from "./run-lifecycle.js";
|
||||
import { createHeartbeatLifecycle, decorateHeartbeatRunRuntimeStatus, persistHeartbeatRunProcessMetadata, type HeartbeatLifecycleDependencies } from "./run-lifecycle.js";
|
||||
import { STORAGE_CREDENTIALS_REJECTED_HELD_MESSAGE, STORAGE_CREDENTIALS_REJECTED_MESSAGE, STORAGE_UNAVAILABLE_CODE,
|
||||
STORAGE_UNAVAILABLE_HELD_MESSAGE, STORAGE_UNAVAILABLE_MESSAGE } from "../../storage/storage-unavailable.js";
|
||||
import { DELIVERY_QUEUES, subscribeDeliveryWork } from "../delivery-work-notifications.js";
|
||||
|
||||
vi.mock("../live-events.js", () => ({ publishLiveEvent: vi.fn() }));
|
||||
@@ -52,6 +54,23 @@ describe("heartbeat lifecycle module boundary", () => {
|
||||
for (const callback of Object.values(deps)) if (vi.isMockFunction(callback)) expect(callback).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
// Rows saved by earlier releases can carry the storage retry promise
|
||||
// under a code that no storage wait owns. They read truthfully after deploy,
|
||||
// with no migration; a run a storage wait owns keeps its promise.
|
||||
it.each([
|
||||
["an outage", STORAGE_UNAVAILABLE_MESSAGE, STORAGE_UNAVAILABLE_HELD_MESSAGE],
|
||||
["rejected credentials", STORAGE_CREDENTIALS_REJECTED_MESSAGE, STORAGE_CREDENTIALS_REJECTED_HELD_MESSAGE],
|
||||
])("reads a previously saved storage retry promise under native recovery truthfully (%s)", (_label, saved, expected) => {
|
||||
const held = decorateHeartbeatRunRuntimeStatus({ id: "held-native-run", status: "failed",
|
||||
errorCode: "native_continuation_requires_reconciliation", error: saved });
|
||||
expect(held.error).toBe(expected);
|
||||
const waiting = decorateHeartbeatRunRuntimeStatus({ id: "run-with-storage-wait", status: "failed",
|
||||
errorCode: STORAGE_UNAVAILABLE_CODE, error: saved });
|
||||
expect(waiting.error).toBe(saved);
|
||||
const other = decorateHeartbeatRunRuntimeStatus({ id: "other", status: "failed", errorCode: "adapter_failed", error: "Adapter failed" });
|
||||
expect(other.error).toBe("Adapter failed");
|
||||
});
|
||||
|
||||
it("ignores absent wake requests without accessing the database", async () => {
|
||||
const database = guardedDatabase();
|
||||
const lifecycle = createHeartbeatLifecycle(database.db, callbacks(database.db));
|
||||
|
||||
@@ -208,6 +208,7 @@ import type { recoveryService } from "../recovery/index.js";
|
||||
import type { companySkillService } from "../company-skills.js";
|
||||
import type { budgetService, BudgetServiceHooks } from "../budgets.js";
|
||||
import type { issueTreeControlService } from "../issue-tree-control.js";
|
||||
import { presentStorageFailureMessage } from "../../storage/storage-unavailable.js";
|
||||
|
||||
type HeartbeatRun = typeof heartbeatRuns.$inferSelect;
|
||||
|
||||
@@ -369,6 +370,8 @@ export function decorateHeartbeatRunRuntimeStatus<
|
||||
|
||||
return {
|
||||
...run,
|
||||
// Saved runs from earlier releases may promise a storage retry no wait owns.
|
||||
...("error" in run ? { error: presentStorageFailureMessage(run as { error?: string | null; errorCode?: string | null }) } : {}),
|
||||
currentStatusMessage: currentStatus?.message ?? null,
|
||||
currentStatusUpdatedAt: currentStatus?.updatedAt ?? null,
|
||||
currentToolName: currentStatus?.currentToolName ?? null,
|
||||
|
||||
@@ -21,6 +21,7 @@ import * as legacy from "../heartbeat.js";
|
||||
import * as extracted from "./run-state.js";
|
||||
import { readRunCancellation } from "../run-cancellation.js";
|
||||
import { decideQueuedCommentQueueSteering } from "../issue-queued-comment-queue.js";
|
||||
import { STORAGE_UNAVAILABLE_CODE, STORAGE_UNAVAILABLE_HELD_MESSAGE, STORAGE_UNAVAILABLE_MESSAGE } from "../../storage/storage-unavailable.js";
|
||||
|
||||
// SQL_ASCII needs a separate database cluster. Inspect its selected SQL here;
|
||||
// the PostgreSQL tests below exercise the session queries and transactions.
|
||||
@@ -397,6 +398,19 @@ describePostgres("heartbeat run state database wiring", () => {
|
||||
expect(await state.listRuns(companyId, foreign.agent.id)).toEqual([]);
|
||||
});
|
||||
|
||||
it("lists a previously saved storage retry promise under native recovery truthfully", async () => {
|
||||
const { companyId, agent, state } = await fixture();
|
||||
const [held] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, status: "failed",
|
||||
errorCode: "native_continuation_requires_reconciliation", error: STORAGE_UNAVAILABLE_MESSAGE }).returning();
|
||||
const [waiting] = await db.insert(heartbeatRuns).values({ companyId, agentId: agent.id, status: "failed",
|
||||
errorCode: STORAGE_UNAVAILABLE_CODE, error: STORAGE_UNAVAILABLE_MESSAGE }).returning();
|
||||
for (const summary of [false, true]) {
|
||||
const rows = await state.listRuns(companyId, agent.id, 100, { summary });
|
||||
expect(rows.find(row => row.id === held.id)?.error).toBe(STORAGE_UNAVAILABLE_HELD_MESSAGE);
|
||||
expect(rows.find(row => row.id === waiting.id)?.error).toBe(STORAGE_UNAVAILABLE_MESSAGE);
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves legacy context text, native issue precedence and summary privacy", async () => {
|
||||
const { companyId, agent, issue, state } = await fixture();
|
||||
const contexts: unknown[] = [null, [], "legacy", 3, true, {}, {
|
||||
|
||||
@@ -57,6 +57,7 @@ import {
|
||||
import { isUuidLike } from "@paperclipai/shared";
|
||||
import { HEARTBEAT_RUN_LIST_DEFAULT_LIMIT, HEARTBEAT_RUN_LIST_MAX_LIMIT } from "@paperclipai/shared";
|
||||
import { isUnsafeSessionWorkspaceCwd } from "../session-workspace-cwd.js";
|
||||
import { presentStorageFailureMessage } from "../../storage/storage-unavailable.js";
|
||||
|
||||
export const EXECUTION_REVIEW_PARTICIPANT_RECOVERY_WAKE_REASON =
|
||||
"execution_review_participant_recovery";
|
||||
@@ -1868,6 +1869,8 @@ export function createHeartbeatRunState(db: Db) {
|
||||
|
||||
return {
|
||||
...rest,
|
||||
// Saved runs from earlier releases may promise a storage retry no wait owns.
|
||||
...("error" in rest ? { error: presentStorageFailureMessage(rest) ?? null } : {}),
|
||||
contextSnapshot: summarizeHeartbeatRunContextSnapshot({
|
||||
issueId: contextIssueId,
|
||||
taskId: contextTaskId,
|
||||
|
||||
@@ -11,3 +11,8 @@ export function watchShutdownHandoff(runId: string): () => boolean {
|
||||
return current !== undefined && current !== atStart;
|
||||
};
|
||||
}
|
||||
|
||||
/** This process handed the run to the next server (graceful drain or hot restart). */
|
||||
export function isRunHandedOffForShutdown(runId: string): boolean {
|
||||
return runsHandedOffForShutdown.has(runId);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { chatConversations, chatEndpoints, heartbeatRuns, issues, statusDecisions, type Db } from "@paperclipai/db";
|
||||
import { readInheritedGitHubReviewWait } from "../chat-channels/github/review-wait.js";
|
||||
import { readInheritedGitHubReviewWaits } from "../chat-channels/github/review-wait.js";
|
||||
import { authorizeChatConversationsForBoundRuns } from "./chat-attachment-reuse.js";
|
||||
import { EXTERNAL_CHAT_QUESTION_RESPONSE_KEY } from "./external-chat-question-response.js";
|
||||
|
||||
@@ -61,15 +61,19 @@ export async function listExternalReviewWaits(db: Db, companyId: string, issueId
|
||||
eq(chatEndpoints.status, "active"),
|
||||
))
|
||||
.where(and(eq(issues.companyId, companyId), inArray(issues.id, issueIds), eq(issues.status, "in_review")));
|
||||
const authorizable = (await Promise.all(candidates.map(async ({ runId, agentId, contextSnapshot, responsibleUserId, activeIdentityContextId, ...wait }) => {
|
||||
const inheritedWait = await readInheritedGitHubReviewWait(db, {
|
||||
id: runId, companyId, agentId, responsibleUserId, activeIdentityContextId,
|
||||
nativeIssueId: wait.issueId, issueId: wait.issueId, contextSnapshot,
|
||||
});
|
||||
if (inheritedWait?.kind === "revoked") return null;
|
||||
return { wait, binding: { companyId, issueId: wait.issueId, runId, agentId },
|
||||
contextSnapshot: inheritedWait?.context ?? contextSnapshot };
|
||||
}))).filter((candidate): candidate is NonNullable<typeof candidate> => candidate !== null);
|
||||
// One review read and one publication read for every wait of the page, not
|
||||
// two reads per wait. Each wait gets the same inherited result as before.
|
||||
const inheritedWaits = await readInheritedGitHubReviewWaits(db, candidates.map(candidate => ({
|
||||
id: candidate.runId, companyId, agentId: candidate.agentId, responsibleUserId: candidate.responsibleUserId,
|
||||
activeIdentityContextId: candidate.activeIdentityContextId, nativeIssueId: candidate.issueId,
|
||||
issueId: candidate.issueId, contextSnapshot: candidate.contextSnapshot,
|
||||
})));
|
||||
const authorizable = candidates.flatMap(({ runId, agentId, contextSnapshot, responsibleUserId: _user, activeIdentityContextId: _context, ...wait }, index) => {
|
||||
const inheritedWait = inheritedWaits[index];
|
||||
if (inheritedWait?.kind === "revoked") return [];
|
||||
return [{ wait, binding: { companyId, issueId: wait.issueId, runId, agentId },
|
||||
contextSnapshot: inheritedWait?.context ?? contextSnapshot }];
|
||||
});
|
||||
// One authorization read for every wait of the page, not one per wait: the
|
||||
// per-wait reads each held a pool connection at the same moment.
|
||||
const authorized = await authorizeChatConversationsForBoundRuns(db, companyId, authorizable);
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, companies, companyMemberships, completionContracts, createDb, heartbeatRuns, issues, nativeRunFinalizations } from "@paperclipai/db";
|
||||
import type { NativeExecutionInputV1 } from "@paperclipai/paperclip-runner";
|
||||
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
|
||||
|
||||
const provider = vi.hoisted(() => ({ execute: vi.fn() }));
|
||||
vi.mock("../../vendor/paperclip-runner/index.js", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("../../vendor/paperclip-runner/index.js")>()),
|
||||
executeNativeSession: provider.execute,
|
||||
}));
|
||||
|
||||
import { executePaperclipNativeSession, NATIVE_PROVIDER_SESSION_CLOSED } from "./native-session-executor.js";
|
||||
import { buildNativeCompletionContract } from "./completion-contracts.js";
|
||||
import { prepareNativeHeartbeatRun } from "./prepare-native-run.js";
|
||||
import { heartbeatService } from "../heartbeat.js";
|
||||
import { requestTaskRetry } from "../task-retry.js";
|
||||
import { taskInterruptionPresentation } from "../task-interruption-presentation.js";
|
||||
|
||||
// Chaos w-20261111T011704-s9107/t05 (claude, TM2): a cut-off ACPX turn start
|
||||
// left this run's session closed with the prompt possibly sent. Every same-run
|
||||
// resume got "ACPX session is not open"; the board offered Retry only after
|
||||
// three attempts (about 95 s). The Runner now classifies that refusal, and
|
||||
// Retry starts a new run with a fresh provider session.
|
||||
describe("native turn start refused on a closed provider session", () => {
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
const companyId = randomUUID();
|
||||
const agentId = randomUUID();
|
||||
|
||||
beforeAll(async () => {
|
||||
temporary = await startEmbeddedPostgresTestDatabase("native-closed-session-");
|
||||
db = createDb(temporary.connectionString);
|
||||
await db.insert(companies).values({ id: companyId, name: "Closed session", issuePrefix: "NCS" });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Claude agent", status: "active", adapterType: "paperclip_runner",
|
||||
adapterConfig: { provider: "acpx", agent: "claude", model: "claude-test" } });
|
||||
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "board-user", status: "active", membershipRole: "member" });
|
||||
});
|
||||
afterAll(async () => { await temporary?.cleanup(); });
|
||||
|
||||
const refusal = (result: Record<string, unknown>) => {
|
||||
const commandResult = { commandId: "command_lab_1", commandType: "turn.start", controllerSeq: 10, result, status: "failed" };
|
||||
return Object.defineProperty(new Error(`PRP command turn.start failed: ${JSON.stringify(commandResult)}`),
|
||||
"runnerCommandResult", { value: commandResult, enumerable: false });
|
||||
};
|
||||
|
||||
async function refuseTurnStart(failure: Error) {
|
||||
const issueId = randomUUID();
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Write the brief", status: "in_progress", workMode: "standard",
|
||||
assigneeAgentId: agentId, createdByUserId: "board-user", responsibleUserId: "board-user" });
|
||||
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
||||
const runId = randomUUID();
|
||||
const [run] = await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", runtimeMode: "native",
|
||||
nativeIssueId: issueId, responsibleUserId: "board-user", invocationSource: "automation", triggerDetail: "system",
|
||||
contextSnapshot: { issueId } }).returning();
|
||||
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
|
||||
const native = await prepareNativeHeartbeatRun({ db, run, issue, environmentLeaseId: randomUUID() });
|
||||
const [contract] = await db.select().from(completionContracts).where(eq(completionContracts.issueId, issueId));
|
||||
await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed" });
|
||||
const execution: NativeExecutionInputV1 = {
|
||||
schema: "paperclip.native-execution-input.v1",
|
||||
binding: { companyId, runId, issueId, agentId, executionWorkspaceId: runId },
|
||||
provider: { kind: "opencode", model: "openrouter/test-model" },
|
||||
task: { identifier: issueId, title: issue.title, description: null, prompt: "Write the brief.", workMode: "standard" },
|
||||
workspace: { cwd: "/tmp", repoUrl: null, repoRef: null, branchName: null },
|
||||
session: { normalizedSessionId: native.normalizedSessionId, driverKind: "opencode_server", protocolVersion: 1, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } },
|
||||
completionContract: { id: contract.id, sha256: contract.canonicalSha256, schemaVersion: "paperclip.completion-contract.v1",
|
||||
contract: buildNativeCompletionContract(issue, { revision: contract.revision }) },
|
||||
interactionResponses: [], credentialBindings: [],
|
||||
};
|
||||
// An established provider session: same-run resume is the ordinary recovery.
|
||||
await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution,
|
||||
sessionCheckpoint: { backendKind: "mock", providerSessionId: "claude-session" } } }).where(eq(heartbeatRuns.id, runId));
|
||||
provider.execute.mockReset().mockRejectedValue(failure);
|
||||
await executePaperclipNativeSession({ db, execution, runnerInstanceId: native.runnerInstanceId, backend: {
|
||||
descriptor: async () => { throw new Error("Unexpected provider call"); },
|
||||
openSession: async () => { throw new Error("Unexpected provider call"); },
|
||||
} }).catch(() => undefined);
|
||||
const [coordinator] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId));
|
||||
return { issueId, runId, coordinator };
|
||||
}
|
||||
|
||||
it("offers Retry on the first refusal, and Retry starts a new run", async () => {
|
||||
const { issueId, runId, coordinator } = await refuseTurnStart(refusal({ code: "command_execution_failed",
|
||||
message: "ACPX session is not open", classification: "provider_session_closed" }));
|
||||
expect(coordinator).toMatchObject({ phase: "terminal_failure", failureCode: NATIVE_PROVIDER_SESSION_CLOSED, nextAttemptAt: null });
|
||||
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
||||
await expect(taskInterruptionPresentation(db, issue)).resolves.toMatchObject({ state: "failed", canRetry: true });
|
||||
const receipt = await requestTaskRetry({ db, companyId, issueId, actorId: "board-user", actorSource: "session",
|
||||
idempotencyKey: randomUUID(), observedRunId: runId });
|
||||
expect(receipt).toMatchObject({ accepted: true, stale: false });
|
||||
const heartbeat = heartbeatService(db);
|
||||
await heartbeat.resumeTaskRetry(companyId, receipt.requestId!);
|
||||
const retried = (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId)))
|
||||
.filter(r => r.contextSnapshot?.issueId === issueId && r.contextSnapshot?.taskRetryRequestId === receipt.requestId);
|
||||
expect(retried).toHaveLength(1);
|
||||
await heartbeat.drainActiveRunExecutions();
|
||||
}, 120_000);
|
||||
|
||||
it("keeps a same-run retry when the Runner proved the prompt never left", async () => {
|
||||
const { coordinator } = await refuseTurnStart(refusal({ code: "command_execution_failed",
|
||||
message: "ACPX turn start failed before its prompt reached the provider: ACPX sidecar request timed out at turn.start" }));
|
||||
expect(coordinator).toMatchObject({ phase: "retryable_failure", failureCode: "native_session_interrupted" });
|
||||
}, 120_000);
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { agentWakeupRequests, heartbeatRuns, statusDecisions, statusDecisionEffe
|
||||
import { and, eq, inArray, isNull, ne, or, sql } from "drizzle-orm";
|
||||
import { alias } from "drizzle-orm/pg-core";
|
||||
import { boundRunIssueIdSql } from "../run-task-binding.js";
|
||||
import { NATIVE_RUN_FAILED_RETRY_CAUSE } from "./status-arbiter.js";
|
||||
|
||||
/** Recover conversation provenance from a committed continuation, never from
|
||||
* provider-supplied source IDs or the mere presence of a chat on the task. */
|
||||
@@ -34,18 +35,29 @@ export async function readNativeContinuationSource(
|
||||
))
|
||||
.innerJoin(statusDecisionEffects, and(
|
||||
eq(statusDecisionEffects.companyId, binding.companyId), eq(statusDecisionEffects.issueId, binding.issueId),
|
||||
eq(statusDecisionEffects.effectKind, "enqueue_continuation"),
|
||||
eq(statusDecisionEffects.targetType, "agent_wakeup_request"),
|
||||
sql`${statusDecisionEffects.targetId} = ${agentWakeupRequests.id}::text`,
|
||||
eq(statusDecisionEffects.deliveryState, "delivered"),
|
||||
sql`${statusDecisionEffects.payload}->>'continuationKind' = 'same_agent'`,
|
||||
sql`${agentWakeupRequests.payload}->>'continuationKind' = 'same_agent'`,
|
||||
or(and(
|
||||
eq(statusDecisionEffects.effectKind, "enqueue_continuation"),
|
||||
sql`${statusDecisionEffects.payload}->>'continuationKind' = 'same_agent'`,
|
||||
sql`${agentWakeupRequests.payload}->>'continuationKind' = 'same_agent'`,
|
||||
), and(
|
||||
// The one automatic retry after a failed turn answers the same chat.
|
||||
eq(statusDecisionEffects.effectKind, "schedule_retry"),
|
||||
sql`${agentWakeupRequests.payload}->>'retryCause' = ${NATIVE_RUN_FAILED_RETRY_CAUSE}`,
|
||||
)),
|
||||
))
|
||||
.innerJoin(statusDecisions, and(
|
||||
eq(statusDecisions.id, statusDecisionEffects.decisionId), eq(statusDecisions.companyId, binding.companyId),
|
||||
eq(statusDecisions.issueId, binding.issueId), eq(statusDecisions.applicationState, "applied"),
|
||||
eq(statusDecisions.reasonCode, "live_continuation_registered"),
|
||||
sql`${agentWakeupRequests.idempotencyKey} = 'native-status:' || ${statusDecisions.id}::text || ':continuation'`,
|
||||
or(and(
|
||||
eq(statusDecisions.reasonCode, "live_continuation_registered"),
|
||||
sql`${agentWakeupRequests.idempotencyKey} = 'native-status:' || ${statusDecisions.id}::text || ':continuation'`,
|
||||
), and(
|
||||
eq(statusDecisions.reasonCode, "run_failed_partial_evidence_preserved"),
|
||||
sql`${agentWakeupRequests.idempotencyKey} = 'native-status:' || ${statusDecisions.id}::text || ':retry'`,
|
||||
)),
|
||||
sql`${agentWakeupRequests.payload}->>'nativeDecisionId' = ${statusDecisions.id}::text`,
|
||||
))
|
||||
.innerJoin(source, and(
|
||||
|
||||
@@ -50,7 +50,18 @@ describe("interruptedExactResumeCause", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("finds the interruption behind the resume reconciler's claim entry for the same attempt", () => {
|
||||
const resumeClaim = { at: "2099-01-01T00:01:00.000Z", disposition: "same_run_resume", controllerBootId: "boot-1",
|
||||
providerAttempt: 1, evidence: { recoveryMode: "exact_checkpoint_resume" } };
|
||||
expect(interruptedExactResumeCause({ ...claimed, recoveryHistory: [interruption, resumeClaim] })).toEqual({
|
||||
originalFailureCode: "native_session_interrupted",
|
||||
originalMessage: "PRP command turn.start failed: classification=session_resume_required",
|
||||
interruptedAttempt: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a resume claim entry for a later provider attempt", { disposition: "same_run_resume", providerAttempt: 2 }],
|
||||
["a wait for a later provider attempt", { disposition: "blocked", reason: "held", providerAttempt: 2 }],
|
||||
["a later recovery entry that is not a wait", { disposition: "resume_dead_runner", reason: "restart", providerAttempt: 1 }],
|
||||
])("does not reach past %s", (_name, later) => {
|
||||
|
||||
@@ -16,7 +16,7 @@ const FAILURE_DETAIL_MAX_CHARS = 2_000;
|
||||
const REFUSAL_MAX_CHARS = 480;
|
||||
const REFUSAL_SEPARATOR = "; exact checkpoint resume refused: ";
|
||||
/** Restart-recovery waits that keep the interrupted provider attempt. */
|
||||
const RECOVERY_WAIT_DISPOSITIONS: ReadonlySet<unknown> = new Set(["blocked", "awaiting_evidence"]);
|
||||
const RECOVERY_WAIT_DISPOSITIONS: ReadonlySet<unknown> = new Set(["blocked", "awaiting_evidence", "same_run_resume"]);
|
||||
|
||||
/**
|
||||
* Cuts to at most `max` UTF-16 code units without splitting a surrogate pair.
|
||||
|
||||
@@ -220,6 +220,23 @@ export async function nativeRecoveryClaimRelinquished(input: {
|
||||
&& row.lastDisposition === "restart_suspended";
|
||||
}
|
||||
|
||||
/**
|
||||
* The run's controller is this process and its execution lease has lapsed
|
||||
* (or was released): the executor that held it detached because of that loss,
|
||||
* not because a shutdown or hot restart handed the run on.
|
||||
*/
|
||||
export async function ownNativeExecutionLeaseLapsed(db: Db, input: { companyId: string; id: string }): Promise<boolean> {
|
||||
const controller = await currentNativeControllerIdentity();
|
||||
const [row] = await db.select({ runId: nativeRunFinalizations.runId }).from(nativeRunFinalizations)
|
||||
.innerJoin(heartbeatRuns, eq(heartbeatRuns.id, nativeRunFinalizations.runId))
|
||||
.where(and(eq(nativeRunFinalizations.companyId, input.companyId), eq(nativeRunFinalizations.runId, input.id),
|
||||
eq(heartbeatRuns.status, "running"), isNull(nativeRunFinalizations.resultId),
|
||||
eq(nativeRunFinalizations.controllerBootId, controller.bootId), eq(nativeRunFinalizations.controllerPid, controller.pid),
|
||||
or(isNull(nativeRunFinalizations.leaseExpiresAt), sql`${nativeRunFinalizations.leaseExpiresAt} <= clock_timestamp()`)))
|
||||
.limit(1);
|
||||
return Boolean(row);
|
||||
}
|
||||
|
||||
export async function releaseLapsedNativeRestartClaim(input: {
|
||||
db: Db; companyId: string; runId: string; leaseOwner: string; controllerGeneration: number; providerAttempt: number;
|
||||
}): Promise<boolean> {
|
||||
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agents, agentWakeupRequests, companies, companyMemberships, completionContracts, createDb, heartbeatRuns, issues, nativeRunFinalizations, statusDecisions } from "@paperclipai/db";
|
||||
import type { ControlPlanePort, NativeExecutionInputV1, PrpEvent, PrpTerminalState } from "@paperclipai/paperclip-runner";
|
||||
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
|
||||
import { CONTROL_PLANE_CONFORMANCE_RESULT } from "../../vendor/paperclip-runner/testing.js";
|
||||
|
||||
const provider = vi.hoisted(() => ({ execute: vi.fn() }));
|
||||
vi.mock("../../vendor/paperclip-runner/index.js", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("../../vendor/paperclip-runner/index.js")>()),
|
||||
executeNativeSession: provider.execute,
|
||||
}));
|
||||
|
||||
import { executePaperclipNativeSession } from "./native-session-executor.js";
|
||||
import { buildNativeCompletionContract } from "./completion-contracts.js";
|
||||
import { prepareNativeHeartbeatRun } from "./prepare-native-run.js";
|
||||
import { finalizeNativeRun } from "./native-run-finalizer.js";
|
||||
import { readNativeContinuationSource } from "./native-continuation-delivery.js";
|
||||
import { NATIVE_RUN_FAILED_CONTINUATION_EXHAUSTED_ACTION } from "./status-arbiter.js";
|
||||
import { heartbeatService } from "../heartbeat.js";
|
||||
import { requestTaskRetry } from "../task-retry.js";
|
||||
|
||||
type FailureCode = "opencode_server_exited" | "opencode_empty_response";
|
||||
|
||||
// Seen on a staging deployment: an OpenCode turn
|
||||
// failed (its server was killed, or it ended without an answer). The accepted
|
||||
// result kept the task in_progress and the arbiter scheduled a retry, but the
|
||||
// dispatcher refused that wake (`chat_control_recovery_proof_unresolved`), so
|
||||
// the task sat for hours with no owner and no queued work.
|
||||
describe("native failed-turn continuation", () => {
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
const companyId = randomUUID();
|
||||
const agentId = randomUUID();
|
||||
|
||||
beforeAll(async () => {
|
||||
temporary = await startEmbeddedPostgresTestDatabase("native-failed-turn-");
|
||||
db = createDb(temporary.connectionString);
|
||||
await db.insert(companies).values({ id: companyId, name: "Native failed turn", issuePrefix: "NFT" });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "OpenCode agent", status: "active", adapterType: "paperclip_runner", adapterConfig: { provider: "opencode", model: "openrouter/test-model" } });
|
||||
await db.insert(companyMemberships).values({ companyId, principalType: "user", principalId: "board-user", status: "active", membershipRole: "member" });
|
||||
});
|
||||
afterAll(async () => { await temporary?.cleanup(); });
|
||||
|
||||
async function failTurn(issueId: string, code: FailureCode, context: Record<string, unknown> = {}, dispatchedFrom?: string) {
|
||||
const runId = randomUUID();
|
||||
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
|
||||
// A dispatched continuation carries the dispatcher's own receipt for its intent.
|
||||
const [receipt] = dispatchedFrom ? await db.insert(agentWakeupRequests).values({ companyId, agentId, source: "automation",
|
||||
triggerDetail: "system", reason: "issue_status_changed", status: "claimed", requestedByActorType: "system",
|
||||
requestedByActorId: `native-status-wake-dispatch:${dispatchedFrom}`, payload: { issueId } }).returning() : [];
|
||||
const [run] = await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, status: "running", runtimeMode: "native", nativeIssueId: issueId, responsibleUserId: "board-user", invocationSource: "automation", triggerDetail: "system", wakeupRequestId: receipt?.id ?? null, contextSnapshot: { issueId, ...context } }).returning();
|
||||
if (receipt) await db.update(agentWakeupRequests).set({ runId }).where(eq(agentWakeupRequests.id, receipt.id));
|
||||
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
|
||||
const native = await prepareNativeHeartbeatRun({ db, run, issue, environmentLeaseId: randomUUID() });
|
||||
const [contract] = await db.select().from(completionContracts).where(eq(completionContracts.issueId, issueId));
|
||||
const completionInput = buildNativeCompletionContract(issue, { revision: contract.revision });
|
||||
await db.insert(nativeRunFinalizations).values({ runId, companyId, issueId, phase: "observed" });
|
||||
const execution: NativeExecutionInputV1 = {
|
||||
schema: "paperclip.native-execution-input.v1",
|
||||
binding: { companyId, runId, issueId, agentId, executionWorkspaceId: runId },
|
||||
provider: { kind: "opencode", model: "openrouter/test-model" },
|
||||
task: { identifier: issueId, title: issue.title, description: null, prompt: "Review the PR.", workMode: "standard" },
|
||||
workspace: { cwd: "/tmp", repoUrl: null, repoRef: null, branchName: null },
|
||||
session: { normalizedSessionId: native.normalizedSessionId, driverKind: "opencode_server", protocolVersion: 1, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } },
|
||||
completionContract: { id: contract.id, sha256: contract.canonicalSha256, schemaVersion: "paperclip.completion-contract.v1", contract: completionInput },
|
||||
interactionResponses: [], credentialBindings: [],
|
||||
};
|
||||
await db.update(heartbeatRuns).set({ runnerProfileJson: { nativeExecutionInput: execution } }).where(eq(heartbeatRuns.id, runId));
|
||||
const event: PrpEvent = {
|
||||
schema: "paperclip.prp.event.v1", runId, normalizedSessionId: native.normalizedSessionId,
|
||||
turnId: native.turnId, sourceInstanceId: native.runnerInstanceId, sourceEventId: "turn-terminal", sourceSeq: 1,
|
||||
sourceKind: "runner", eventType: "turn.failed", schemaVersion: 1, priority: 0, emittedAt: new Date().toISOString(),
|
||||
payload: code === "opencode_server_exited"
|
||||
? { status: "failed", error: { code, message: "OpenCode stopped while the turn was running.", opencodeFailure: { kind: "server_exited", signal: "SIGKILL", connectionError: "ECONNREFUSED" } } }
|
||||
: { status: "failed", error: { code, message: "OpenCode ended without a final answer.", retryable: false } },
|
||||
};
|
||||
const terminal: PrpTerminalState = { schema: "paperclip.prp.terminal.v1", turnTerminalState: "failed", runTerminalState: "failed", reportedWorkDisposition: "needs_review" };
|
||||
const result = { ...CONTROL_PLANE_CONFORMANCE_RESULT, reportedWorkDisposition: "needs_review" as const,
|
||||
completionClaim: { ...CONTROL_PLANE_CONFORMANCE_RESULT.completionClaim, contractRevision: completionInput.revision } };
|
||||
const openInput = { identity: { companyId, issueId, runId, agentId, sessionId: native.normalizedSessionId }, backendKind: "mock" as const, sourceInstanceId: native.runnerInstanceId };
|
||||
provider.execute.mockReset().mockImplementation(async (options: { controlPlane: ControlPlanePort }) => {
|
||||
await options.controlPlane.openRun(openInput);
|
||||
await options.controlPlane.appendEvent(event);
|
||||
await options.controlPlane.completeRun({ result, terminal, turnId: native.turnId });
|
||||
return { result, terminal, turnId: native.turnId, normalizedSessionId: native.normalizedSessionId, providerSessionId: "fixture-provider-session", driverKind: execution.session.driverKind, driverVersion: "fixture", nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null };
|
||||
});
|
||||
await executePaperclipNativeSession({ db, execution, runnerInstanceId: native.runnerInstanceId, backend: {
|
||||
descriptor: async () => { throw new Error("Unexpected provider call"); },
|
||||
openSession: async () => { throw new Error("Unexpected provider call"); },
|
||||
} });
|
||||
await finalizeNativeRun({ db, runId, workspaceFinalizeStatus: "succeeded", projectRunStatus: true });
|
||||
const [failedRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
|
||||
expect(failedRun.status).toBe("failed");
|
||||
const [decision] = await db.select().from(statusDecisions).where(eq(statusDecisions.runId, runId));
|
||||
return { runId, decision };
|
||||
}
|
||||
|
||||
const issueWakes = async (issueId: string) => (await db.select().from(agentWakeupRequests)
|
||||
.where(eq(agentWakeupRequests.companyId, companyId))).filter(wake => wake.payload?.issueId === issueId);
|
||||
|
||||
it.each(["opencode_server_exited", "opencode_empty_response"] as const)("continues the task once after %s, then hands it to Retry", async (code) => {
|
||||
const issueId = randomUUID();
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Review a PR", status: "in_progress", workMode: "standard", assigneeAgentId: agentId, createdByUserId: "board-user", responsibleUserId: "board-user" });
|
||||
const first = await failTurn(issueId, code);
|
||||
expect(first.decision.reasonCode).toBe("run_failed_partial_evidence_preserved");
|
||||
|
||||
const heartbeat = heartbeatService(db);
|
||||
expect(await heartbeat.dispatchPendingNativeStatusWakeups({ companyId })).toMatchObject({ dispatched: 1 });
|
||||
const wakes = await issueWakes(issueId);
|
||||
expect(wakes.filter(wake => wake.status === "skipped")).toEqual([]);
|
||||
const intent = wakes.find(wake => wake.requestedByActorId === "native-status-committer")!;
|
||||
expect(intent.payload).toMatchObject({ retryCause: "native_run_failed" });
|
||||
const [continuation] = (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId)))
|
||||
.filter(r => r.id !== first.runId && r.contextSnapshot?.issueId === issueId);
|
||||
expect(continuation?.contextSnapshot?.nativeStatusWakeIntentId).toBe(intent.id);
|
||||
expect(["queued", "running"]).toContain(continuation.status);
|
||||
// The continuation keeps the failed run as its conversation source.
|
||||
expect(await readNativeContinuationSource(db, { companyId, issueId, runId: continuation.id })).toBe(first.runId);
|
||||
// The fixture cannot launch a real runner; let the dispatched run settle.
|
||||
await heartbeat.drainActiveRunExecutions();
|
||||
const [task] = await db.select().from(issues).where(eq(issues.id, issueId));
|
||||
expect(task.assigneeAgentId).toBe(agentId);
|
||||
|
||||
// The continuation's own turn fails the same way: no second automatic
|
||||
// wake, and a board blocker whose Retry restarts the work.
|
||||
await db.update(issues).set({ status: "in_progress", executionRunId: null, checkoutRunId: null }).where(eq(issues.id, issueId));
|
||||
const before = (await issueWakes(issueId)).length;
|
||||
const second = await failTurn(issueId, code, { nativeStatusWakeIntentId: intent.id }, intent.id);
|
||||
expect(second.decision).toMatchObject({ reasonCode: "native_run_failed_continuation_exhausted", toStatus: "blocked" });
|
||||
await heartbeat.dispatchPendingNativeStatusWakeups({ companyId });
|
||||
expect((await issueWakes(issueId)).length).toBe(before + 1); // only the fixture dispatch receipt
|
||||
const [blocked] = await db.select().from(issues).where(eq(issues.id, issueId));
|
||||
expect(blocked).toMatchObject({ status: "blocked", unblockDescriptor: { owner: "board", action: NATIVE_RUN_FAILED_CONTINUATION_EXHAUSTED_ACTION } });
|
||||
// The visible Retry is accepted and starts a new run of the task.
|
||||
const receipt = await requestTaskRetry({ db, companyId, issueId, actorId: "board-user", actorSource: "session",
|
||||
idempotencyKey: randomUUID(), observedRunId: second.runId });
|
||||
expect(receipt).toMatchObject({ accepted: true, stale: false });
|
||||
await heartbeat.resumeTaskRetry(companyId, receipt.requestId!);
|
||||
const retried = (await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.agentId, agentId)))
|
||||
.filter(r => r.contextSnapshot?.issueId === issueId && r.contextSnapshot?.taskRetryRequestId === receipt.requestId);
|
||||
expect(retried).toHaveLength(1);
|
||||
await heartbeat.drainActiveRunExecutions();
|
||||
}, 120_000);
|
||||
|
||||
it("does not treat a copied retry intent id as a used continuation", async () => {
|
||||
const issueId = randomUUID();
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Review another PR", status: "in_progress", workMode: "standard", assigneeAgentId: agentId, createdByUserId: "board-user", responsibleUserId: "board-user" });
|
||||
const first = await failTurn(issueId, "opencode_empty_response");
|
||||
expect(first.decision.reasonCode).toBe("run_failed_partial_evidence_preserved");
|
||||
const intent = (await issueWakes(issueId)).find(wake => wake.requestedByActorId === "native-status-committer")!;
|
||||
// A real intent id copied into a run that the dispatcher did not start.
|
||||
await db.update(issues).set({ status: "in_progress", executionRunId: null, checkoutRunId: null }).where(eq(issues.id, issueId));
|
||||
const copied = await failTurn(issueId, "opencode_empty_response", { nativeStatusWakeIntentId: intent.id });
|
||||
expect(copied.decision.reasonCode).toBe("run_failed_partial_evidence_preserved");
|
||||
}, 120_000);
|
||||
});
|
||||
@@ -0,0 +1,36 @@
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { agentWakeupRequests, type Db, type heartbeatRuns } from "@paperclipai/db";
|
||||
import { NATIVE_RUN_FAILED_RETRY_CAUSE } from "./status-arbiter.js";
|
||||
|
||||
/**
|
||||
* True when this run was dispatched from the committer's `schedule_retry` wake
|
||||
* for an earlier failed turn. The intent id is set by the native-status wake
|
||||
* dispatcher, and the intent row itself proves the retry cause, so provider
|
||||
* output or a copied context cannot claim or hide the used continuation.
|
||||
*/
|
||||
export async function isFailedTurnContinuationRun(
|
||||
db: Pick<Db, "select">,
|
||||
run: Pick<typeof heartbeatRuns.$inferSelect, "id" | "companyId" | "agentId" | "contextSnapshot" | "wakeupRequestId">,
|
||||
issueId: string,
|
||||
): Promise<boolean> {
|
||||
const intentId = run.contextSnapshot?.nativeStatusWakeIntentId;
|
||||
if (typeof intentId !== "string" || !/^[0-9a-f-]{36}$/i.test(intentId) || !run.wakeupRequestId) return false;
|
||||
// The run's own dispatch receipt must be the one the dispatcher created for
|
||||
// this intent, so a copied intent id on another run proves nothing.
|
||||
const [dispatch] = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and(
|
||||
eq(agentWakeupRequests.companyId, run.companyId),
|
||||
eq(agentWakeupRequests.id, run.wakeupRequestId),
|
||||
eq(agentWakeupRequests.runId, run.id),
|
||||
eq(agentWakeupRequests.requestedByActorId, `native-status-wake-dispatch:${intentId}`),
|
||||
)).limit(1);
|
||||
if (!dispatch) return false;
|
||||
const [intent] = await db.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(and(
|
||||
eq(agentWakeupRequests.companyId, run.companyId),
|
||||
eq(agentWakeupRequests.agentId, run.agentId),
|
||||
eq(agentWakeupRequests.id, intentId),
|
||||
eq(agentWakeupRequests.requestedByActorId, "native-status-committer"),
|
||||
sql`${agentWakeupRequests.payload}->>'issueId' = ${issueId}`,
|
||||
sql`${agentWakeupRequests.payload}->>'retryCause' = ${NATIVE_RUN_FAILED_RETRY_CAUSE}`,
|
||||
)).limit(1);
|
||||
return Boolean(intent);
|
||||
}
|
||||
@@ -87,7 +87,9 @@ const support = externalUrl ? { supported: true } : await getEmbeddedPostgresTes
|
||||
|
||||
expect(await claimNativeRestartRecoveries({ db, restartKind: "hard", runIds: [f.runId] })).toEqual([
|
||||
{ kind: kind === "owned" ? "awaiting_evidence" : "blocked", runId: f.runId,
|
||||
reason: kind === "owned" ? "controller_still_alive" : "provider_checkpoint_permanently_failed" },
|
||||
reason: kind === "owned" ? "controller_still_alive" : "provider_checkpoint_permanently_failed",
|
||||
// This process's own live lease lapses by itself; recovery looks again then.
|
||||
...(kind === "owned" ? { retryAt: expect.any(Date) } : {}) },
|
||||
]);
|
||||
const current = await readRun(f.runId);
|
||||
expect(current.status).toBe(kind === "owned" ? "running" : "failed");
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { sameRunResumeClaimEntry } from "./scheduled-resume-continuation.js";
|
||||
import { appendBoundedRecoveryHistory } from "./native-restart-recovery.js";
|
||||
import { notifyLiveRunRecovery } from "../live-run-recovery-notifications.js";
|
||||
import { currentControllerProcessStamp } from "../controller-process-identity.js";
|
||||
import { NATIVE_SESSION_RESUMPTION_ISSUE_STATUSES } from "./native-session-resumption-statuses.js";
|
||||
@@ -309,15 +311,16 @@ export async function claimNativeSessionResumptions(input: {
|
||||
|
||||
const leaseExpiresAt = new Date(now.getTime() + 20 * 60_000);
|
||||
await notifyLiveRunRecovery(tx, { companyId: row.run.companyId, runId: row.run.id, agentId: row.run.agentId });
|
||||
const stamp = currentControllerProcessStamp();
|
||||
const resumeClaim = sameRunResumeClaimEntry({ at: now, controllerBootId: stamp.bootId,
|
||||
providerAttempt: row.coordinator.attempt, failureDetail: row.coordinator.failureDetail });
|
||||
const updated = await tx.update(nativeRunFinalizations).set({
|
||||
phase: "observed",
|
||||
leaseOwner,
|
||||
leaseExpiresAt,
|
||||
...(() => {
|
||||
const stamp = currentControllerProcessStamp();
|
||||
return { controllerBootId: stamp.bootId, controllerPid: stamp.pid, controllerHostHash: stamp.hostHash,
|
||||
controllerProcessStartedAt: stamp.processStartedAt ? new Date(stamp.processStartedAt) : null };
|
||||
})(),
|
||||
controllerBootId: stamp.bootId, controllerPid: stamp.pid, controllerHostHash: stamp.hostHash,
|
||||
controllerProcessStartedAt: stamp.processStartedAt ? new Date(stamp.processStartedAt) : null,
|
||||
recoveryHistory: appendBoundedRecoveryHistory(resumeClaim),
|
||||
failureCode: null,
|
||||
failureDetail: null,
|
||||
nextAttemptAt: null,
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
agents,
|
||||
agentWakeupRequests,
|
||||
chatConversations,
|
||||
chatEndpoints,
|
||||
companies,
|
||||
completionContracts,
|
||||
createDb,
|
||||
@@ -11,6 +14,8 @@ import {
|
||||
issueRecoveryActions,
|
||||
issues,
|
||||
nativeRunFinalizations,
|
||||
toolApplications,
|
||||
toolConnections,
|
||||
} from "@paperclipai/db";
|
||||
import type {
|
||||
ControlPlanePort,
|
||||
@@ -31,6 +36,8 @@ import { executePaperclipNativeSession } from "./native-session-executor.js";
|
||||
import { buildNativeCompletionContract } from "./completion-contracts.js";
|
||||
import { PaperclipControlPlanePort } from "./paperclip-control-plane-port.js";
|
||||
import { prepareNativeHeartbeatRun } from "./prepare-native-run.js";
|
||||
import { PROVIDER_LIMIT_RESUME_KEY_PREFIX, registerProviderLimitResumeWork, requestProviderLimitResumeRetry } from "./provider-limit-resume.js";
|
||||
import { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js";
|
||||
|
||||
describe("native provider capacity failure persistence", () => {
|
||||
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
@@ -62,125 +69,211 @@ describe("native provider capacity failure persistence", () => {
|
||||
await temporary?.cleanup();
|
||||
});
|
||||
|
||||
/** Runs one native session whose provider ends its turn with `payload`. */
|
||||
async function failTurn(options: {
|
||||
payload: Record<string, unknown>;
|
||||
replayed?: boolean;
|
||||
responsibleUserId?: string | null;
|
||||
}) {
|
||||
const issueId = randomUUID();
|
||||
const runId = randomUUID();
|
||||
const [issue] = await db
|
||||
.insert(issues)
|
||||
.values({
|
||||
id: issueId,
|
||||
companyId,
|
||||
title: "Reply after a capacity failure",
|
||||
status: "in_progress",
|
||||
workMode: "standard",
|
||||
assigneeAgentId: agentId,
|
||||
})
|
||||
.returning();
|
||||
const [run] = await db
|
||||
.insert(heartbeatRuns)
|
||||
.values({
|
||||
id: runId,
|
||||
companyId,
|
||||
agentId,
|
||||
status: "running",
|
||||
runtimeMode: "native",
|
||||
nativeIssueId: issueId,
|
||||
invocationSource: "assignment",
|
||||
triggerDetail: "system",
|
||||
contextSnapshot: { issueId },
|
||||
responsibleUserId: options.responsibleUserId ?? null,
|
||||
})
|
||||
.returning();
|
||||
await db
|
||||
.update(issues)
|
||||
.set({ executionRunId: runId })
|
||||
.where(eq(issues.id, issueId));
|
||||
const native = await prepareNativeHeartbeatRun({
|
||||
db,
|
||||
run,
|
||||
issue,
|
||||
environmentLeaseId: randomUUID(),
|
||||
});
|
||||
const [contract] = await db
|
||||
.select()
|
||||
.from(completionContracts)
|
||||
.where(eq(completionContracts.issueId, issueId));
|
||||
const completionInput = buildNativeCompletionContract(issue, {
|
||||
revision: contract.revision,
|
||||
});
|
||||
expect(completionInput).toEqual(contract.contractJson);
|
||||
await db.insert(nativeRunFinalizations).values({
|
||||
runId,
|
||||
companyId,
|
||||
issueId,
|
||||
phase: "observed",
|
||||
});
|
||||
// A real terminal follows provider session establishment. Keep the
|
||||
// recovery evidence explicit; this must not be a bootstrap retry.
|
||||
await db
|
||||
.update(heartbeatRuns)
|
||||
.set({
|
||||
runnerProfileJson: {
|
||||
sessionCheckpoint: {
|
||||
providerSessionId: "capacity-test-provider-session",
|
||||
providerIdentity: { threadId: "capacity-test-thread" },
|
||||
},
|
||||
},
|
||||
})
|
||||
.where(eq(heartbeatRuns.id, runId));
|
||||
|
||||
const execution: NativeExecutionInputV1 = {
|
||||
schema: "paperclip.native-execution-input.v1",
|
||||
binding: {
|
||||
companyId,
|
||||
runId,
|
||||
issueId,
|
||||
agentId,
|
||||
executionWorkspaceId: runId,
|
||||
},
|
||||
provider: { kind: "codex", model: "gpt-5.6-luna" },
|
||||
task: {
|
||||
identifier: issueId,
|
||||
title: issue.title,
|
||||
description: null,
|
||||
prompt: "Reply to the current message.",
|
||||
workMode: "standard",
|
||||
},
|
||||
workspace: {
|
||||
cwd: "/tmp",
|
||||
repoUrl: null,
|
||||
repoRef: null,
|
||||
branchName: null,
|
||||
},
|
||||
session: {
|
||||
normalizedSessionId: native.normalizedSessionId,
|
||||
driverKind: "codex_app_server",
|
||||
protocolVersion: 1,
|
||||
lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
|
||||
},
|
||||
completionContract: {
|
||||
id: contract.id,
|
||||
sha256: contract.canonicalSha256,
|
||||
schemaVersion: "paperclip.completion-contract.v1",
|
||||
contract: completionInput,
|
||||
},
|
||||
interactionResponses: [],
|
||||
credentialBindings: [],
|
||||
};
|
||||
const event: PrpEvent = {
|
||||
schema: "paperclip.prp.event.v1",
|
||||
runId,
|
||||
normalizedSessionId: native.normalizedSessionId,
|
||||
turnId: native.turnId,
|
||||
sourceInstanceId: native.runnerInstanceId,
|
||||
sourceEventId: "capacity-terminal",
|
||||
sourceSeq: 1,
|
||||
sourceKind: "runner",
|
||||
eventType: "turn.failed",
|
||||
schemaVersion: 1,
|
||||
priority: 0,
|
||||
emittedAt: new Date().toISOString(),
|
||||
payload: options.payload,
|
||||
};
|
||||
const openInput = {
|
||||
identity: {
|
||||
companyId,
|
||||
issueId,
|
||||
runId,
|
||||
agentId,
|
||||
sessionId: native.normalizedSessionId,
|
||||
},
|
||||
backendKind: "mock" as const,
|
||||
sourceInstanceId: native.runnerInstanceId,
|
||||
};
|
||||
if (options.replayed) {
|
||||
// Model a controller crash after the event commit but before its
|
||||
// observational callback or failure coordinator could run.
|
||||
const priorPort = new PaperclipControlPlanePort(db, {
|
||||
companyId,
|
||||
issueId,
|
||||
runId,
|
||||
agentId,
|
||||
sessionId: native.normalizedSessionId,
|
||||
sourceInstanceId: native.runnerInstanceId,
|
||||
controlPlaneSourceInstanceId: "prior-controller",
|
||||
completionContractId: contract.id,
|
||||
completionContractSha256: contract.canonicalSha256,
|
||||
});
|
||||
await priorPort.openRun(openInput);
|
||||
expect((await priorPort.appendEvent(event)).disposition).toBe(
|
||||
"committed",
|
||||
);
|
||||
}
|
||||
provider.execute
|
||||
.mockReset()
|
||||
.mockImplementation(
|
||||
async (executeOptions: { controlPlane: ControlPlanePort }) => {
|
||||
await executeOptions.controlPlane.openRun(openInput);
|
||||
const appended = await executeOptions.controlPlane.appendEvent(event);
|
||||
expect(appended.disposition).toBe(
|
||||
options.replayed ? "duplicate" : "committed",
|
||||
);
|
||||
// Production reports the provider terminal through the event, not by
|
||||
// pattern-matching this exception's arbitrary message.
|
||||
throw new Error("provider turn stopped");
|
||||
},
|
||||
);
|
||||
await expect(
|
||||
executePaperclipNativeSession({
|
||||
db,
|
||||
execution,
|
||||
runnerInstanceId: native.runnerInstanceId,
|
||||
backend: {
|
||||
descriptor: async () => {
|
||||
throw new Error(
|
||||
"Unexpected provider descriptor call in capacity test",
|
||||
);
|
||||
},
|
||||
openSession: async () => {
|
||||
throw new Error(
|
||||
"Unexpected provider session call in capacity test",
|
||||
);
|
||||
},
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("provider turn stopped");
|
||||
expect(provider.execute).toHaveBeenCalledTimes(1);
|
||||
return { runId, issueId, sourceEventId: event.sourceEventId };
|
||||
}
|
||||
|
||||
async function holdFor(issueId: string) {
|
||||
const [recovery] = await db
|
||||
.select()
|
||||
.from(issueRecoveryActions)
|
||||
.where(eq(issueRecoveryActions.sourceIssueId, issueId));
|
||||
return recovery;
|
||||
}
|
||||
|
||||
it.each([false, true])(
|
||||
"stops automatic retries for a durable usage terminal (replayed=%s)",
|
||||
async (replayed) => {
|
||||
const issueId = randomUUID();
|
||||
const runId = randomUUID();
|
||||
const [issue] = await db
|
||||
.insert(issues)
|
||||
.values({
|
||||
id: issueId,
|
||||
companyId,
|
||||
title: "Reply after a capacity failure",
|
||||
status: "in_progress",
|
||||
workMode: "standard",
|
||||
assigneeAgentId: agentId,
|
||||
})
|
||||
.returning();
|
||||
const [run] = await db
|
||||
.insert(heartbeatRuns)
|
||||
.values({
|
||||
id: runId,
|
||||
companyId,
|
||||
agentId,
|
||||
status: "running",
|
||||
runtimeMode: "native",
|
||||
nativeIssueId: issueId,
|
||||
invocationSource: "assignment",
|
||||
triggerDetail: "system",
|
||||
contextSnapshot: { issueId },
|
||||
})
|
||||
.returning();
|
||||
await db
|
||||
.update(issues)
|
||||
.set({ executionRunId: runId })
|
||||
.where(eq(issues.id, issueId));
|
||||
const native = await prepareNativeHeartbeatRun({
|
||||
db,
|
||||
run,
|
||||
issue,
|
||||
environmentLeaseId: randomUUID(),
|
||||
});
|
||||
const [contract] = await db
|
||||
.select()
|
||||
.from(completionContracts)
|
||||
.where(eq(completionContracts.issueId, issueId));
|
||||
const completionInput = buildNativeCompletionContract(issue, {
|
||||
revision: contract.revision,
|
||||
});
|
||||
expect(completionInput).toEqual(contract.contractJson);
|
||||
await db.insert(nativeRunFinalizations).values({
|
||||
runId,
|
||||
companyId,
|
||||
issueId,
|
||||
phase: "observed",
|
||||
});
|
||||
// A real terminal follows provider session establishment. Keep the
|
||||
// recovery evidence explicit; this must not be a bootstrap retry.
|
||||
await db
|
||||
.update(heartbeatRuns)
|
||||
.set({
|
||||
runnerProfileJson: {
|
||||
sessionCheckpoint: {
|
||||
providerSessionId: "capacity-test-provider-session",
|
||||
providerIdentity: { threadId: "capacity-test-thread" },
|
||||
},
|
||||
},
|
||||
})
|
||||
.where(eq(heartbeatRuns.id, runId));
|
||||
|
||||
const execution: NativeExecutionInputV1 = {
|
||||
schema: "paperclip.native-execution-input.v1",
|
||||
binding: {
|
||||
companyId,
|
||||
runId,
|
||||
issueId,
|
||||
agentId,
|
||||
executionWorkspaceId: runId,
|
||||
},
|
||||
provider: { kind: "codex", model: "gpt-5.6-luna" },
|
||||
task: {
|
||||
identifier: issueId,
|
||||
title: issue.title,
|
||||
description: null,
|
||||
prompt: "Reply to the current message.",
|
||||
workMode: "standard",
|
||||
},
|
||||
workspace: {
|
||||
cwd: "/tmp",
|
||||
repoUrl: null,
|
||||
repoRef: null,
|
||||
branchName: null,
|
||||
},
|
||||
session: {
|
||||
normalizedSessionId: native.normalizedSessionId,
|
||||
driverKind: "codex_app_server",
|
||||
protocolVersion: 1,
|
||||
lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
|
||||
},
|
||||
completionContract: {
|
||||
id: contract.id,
|
||||
sha256: contract.canonicalSha256,
|
||||
schemaVersion: "paperclip.completion-contract.v1",
|
||||
contract: completionInput,
|
||||
},
|
||||
interactionResponses: [],
|
||||
credentialBindings: [],
|
||||
};
|
||||
const event: PrpEvent = {
|
||||
schema: "paperclip.prp.event.v1",
|
||||
runId,
|
||||
normalizedSessionId: native.normalizedSessionId,
|
||||
turnId: native.turnId,
|
||||
sourceInstanceId: native.runnerInstanceId,
|
||||
sourceEventId: "capacity-terminal",
|
||||
sourceSeq: 1,
|
||||
sourceKind: "runner",
|
||||
eventType: "turn.failed",
|
||||
schemaVersion: 1,
|
||||
priority: 0,
|
||||
emittedAt: new Date().toISOString(),
|
||||
const { runId, issueId, sourceEventId } = await failTurn({
|
||||
replayed,
|
||||
payload: {
|
||||
status: "failed",
|
||||
error: {
|
||||
@@ -188,72 +281,7 @@ describe("native provider capacity failure persistence", () => {
|
||||
message: "Private account metadata",
|
||||
},
|
||||
},
|
||||
};
|
||||
const openInput = {
|
||||
identity: {
|
||||
companyId,
|
||||
issueId,
|
||||
runId,
|
||||
agentId,
|
||||
sessionId: native.normalizedSessionId,
|
||||
},
|
||||
backendKind: "mock" as const,
|
||||
sourceInstanceId: native.runnerInstanceId,
|
||||
};
|
||||
if (replayed) {
|
||||
// Model a controller crash after the event commit but before its
|
||||
// observational callback or failure coordinator could run.
|
||||
const priorPort = new PaperclipControlPlanePort(db, {
|
||||
companyId,
|
||||
issueId,
|
||||
runId,
|
||||
agentId,
|
||||
sessionId: native.normalizedSessionId,
|
||||
sourceInstanceId: native.runnerInstanceId,
|
||||
controlPlaneSourceInstanceId: "prior-controller",
|
||||
completionContractId: contract.id,
|
||||
completionContractSha256: contract.canonicalSha256,
|
||||
});
|
||||
await priorPort.openRun(openInput);
|
||||
expect((await priorPort.appendEvent(event)).disposition).toBe(
|
||||
"committed",
|
||||
);
|
||||
}
|
||||
provider.execute
|
||||
.mockReset()
|
||||
.mockImplementation(
|
||||
async (options: { controlPlane: ControlPlanePort }) => {
|
||||
await options.controlPlane.openRun(openInput);
|
||||
const appended = await options.controlPlane.appendEvent(event);
|
||||
expect(appended.disposition).toBe(
|
||||
replayed ? "duplicate" : "committed",
|
||||
);
|
||||
// Production reports the provider terminal through the event, not by
|
||||
// pattern-matching this exception's arbitrary message.
|
||||
throw new Error("provider turn stopped");
|
||||
},
|
||||
);
|
||||
await expect(
|
||||
executePaperclipNativeSession({
|
||||
db,
|
||||
execution,
|
||||
runnerInstanceId: native.runnerInstanceId,
|
||||
backend: {
|
||||
descriptor: async () => {
|
||||
throw new Error(
|
||||
"Unexpected provider descriptor call in capacity test",
|
||||
);
|
||||
},
|
||||
openSession: async () => {
|
||||
throw new Error(
|
||||
"Unexpected provider session call in capacity test",
|
||||
);
|
||||
},
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("provider turn stopped");
|
||||
|
||||
expect(provider.execute).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
const [coordinator] = await db
|
||||
.select()
|
||||
.from(nativeRunFinalizations)
|
||||
@@ -271,10 +299,7 @@ describe("native provider capacity failure persistence", () => {
|
||||
.from(heartbeatRuns)
|
||||
.where(eq(heartbeatRuns.id, runId));
|
||||
expect(failedRun.errorCode).toBe("native_provider_usage_limit");
|
||||
const [recovery] = await db
|
||||
.select()
|
||||
.from(issueRecoveryActions)
|
||||
.where(eq(issueRecoveryActions.sourceIssueId, issueId));
|
||||
const recovery = await holdFor(issueId);
|
||||
expect(recovery).toMatchObject({
|
||||
ownerType: "board",
|
||||
cause: "native_provider_usage_limit",
|
||||
@@ -294,8 +319,269 @@ describe("native provider capacity failure persistence", () => {
|
||||
.from(heartbeatRunEvents)
|
||||
.where(eq(heartbeatRunEvents.runId, runId));
|
||||
expect(
|
||||
events.filter((row) => row.sourceEventId === event.sourceEventId),
|
||||
events.filter((row) => row.sourceEventId === sourceEventId),
|
||||
).toHaveLength(1);
|
||||
// No reset was reported, so nothing retries the task by itself.
|
||||
await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: recovery.id }))
|
||||
.resolves.toEqual({ requested: false, reason: "reset_unknown" });
|
||||
},
|
||||
);
|
||||
|
||||
/** The ACP harness's weekly-limit terminal, as staging recorded it (PAP-1057). */
|
||||
function weeklyLimit(resetAt: Date) {
|
||||
const month = resetAt.toLocaleString("en-US", { month: "short", timeZone: "UTC" });
|
||||
const hour = resetAt.getUTCHours();
|
||||
const clock = `${hour % 12 || 12}${hour < 12 ? "am" : "pm"}`;
|
||||
return {
|
||||
status: "failed",
|
||||
error: {
|
||||
code: "RUNTIME",
|
||||
message: "ACP agent reported a terminal limit failure.",
|
||||
providerFailure: {
|
||||
schema: "paperclip.provider-failure.v1",
|
||||
provider: "anthropic",
|
||||
phase: "turn",
|
||||
category: "quota_exhausted",
|
||||
retryability: "requires_action",
|
||||
message: `ACP agent reported a terminal limit failure.\nYou've hit your weekly limit · resets ${month} ${resetAt.getUTCDate()}, ${clock} (UTC)`,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
it("waits for a reported usage-limit reset and then requests the task's Retry once", async () => {
|
||||
const resetAt = new Date(Date.now() + 2 * 24 * 60 * 60_000);
|
||||
resetAt.setUTCMinutes(0, 0, 0);
|
||||
const userId = `user-${randomUUID()}`;
|
||||
const { runId, issueId } = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: userId });
|
||||
|
||||
const hold = await holdFor(issueId);
|
||||
expect(hold).toMatchObject({ cause: "native_provider_usage_limit",
|
||||
evidence: expect.objectContaining({ providerLimitResetAt: resetAt.toISOString() }) });
|
||||
// The hold says when work resumes, not that its session state is ambiguous.
|
||||
expect(hold.nextAction).toBe(`The provider usage limit resets at ${resetAt.toISOString()}. `
|
||||
+ "Paperclip will retry this task then; Retry starts it sooner if usage capacity is already restored.");
|
||||
|
||||
// A hold saved by the previous release names no reset and calls the state ambiguous.
|
||||
const { providerLimitResetAt: _reset, ...oldEvidence } = hold.evidence;
|
||||
await db.update(issueRecoveryActions).set({ evidence: oldEvidence, nextAction: "Inspect the original provider failure "
|
||||
+ "and explicitly resolve the ambiguous session state; do not open a replacement provider session." })
|
||||
.where(eq(issueRecoveryActions.id, hold.id));
|
||||
|
||||
// Before the reset nothing starts; the owner keeps the reset as its deadline
|
||||
// and tells the reader when work resumes.
|
||||
await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id }))
|
||||
.resolves.toEqual({ requested: false, waitUntil: resetAt });
|
||||
expect(await holdFor(issueId)).toMatchObject({ nextAction: hold.nextAction,
|
||||
evidence: expect.objectContaining({ providerLimitResetAt: resetAt.toISOString() }) });
|
||||
|
||||
// At the reset Paperclip asks for the same Retry the accountable user would.
|
||||
const afterReset = new Date(resetAt.getTime() + 1000);
|
||||
const outcome = await requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id }, afterReset);
|
||||
expect(outcome).toMatchObject({ requested: true });
|
||||
const [receipt] = await db.select().from(agentWakeupRequests).where(and(
|
||||
eq(agentWakeupRequests.companyId, companyId),
|
||||
eq(agentWakeupRequests.idempotencyKey, `task-retry:provider-limit-reset:${runId}`)));
|
||||
expect(receipt).toMatchObject({ reason: "task_retry", requestedByActorType: "user", requestedByActorId: userId,
|
||||
status: "deferred_issue_execution", payload: expect.objectContaining({ issueId,
|
||||
taskRetry: expect.objectContaining({ sourceRunId: runId, actorId: userId }) }) });
|
||||
expect((await holdFor(issueId)).evidence.providerLimitResume).toMatchObject({ state: "requested",
|
||||
requestId: receipt.id, resetAt: resetAt.toISOString() });
|
||||
|
||||
// A second pass never requests another Retry for the same hold.
|
||||
await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id }, afterReset))
|
||||
.resolves.toEqual({ requested: false, reason: "not_waiting" });
|
||||
const receipts = await db.select().from(agentWakeupRequests).where(and(
|
||||
eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.reason, "task_retry"),
|
||||
eq(agentWakeupRequests.agentId, agentId)));
|
||||
expect(receipts.filter(row => (row.payload as Record<string, unknown>).issueId === issueId)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("starts the Retry from the hold's own deadline after a restart rebuilds it", async () => {
|
||||
// A typed reset a few seconds out; the owner learns it only from durable rows.
|
||||
const resetAt = new Date(Date.now() + 3000);
|
||||
const payload = weeklyLimit(resetAt);
|
||||
(payload.error.providerFailure as Record<string, unknown>).retryAt = resetAt.toISOString();
|
||||
const userId = `user-${randomUUID()}`;
|
||||
const { issueId } = await failTurn({ payload, responsibleUserId: userId });
|
||||
const hold = await holdFor(issueId);
|
||||
const errors: unknown[] = [];
|
||||
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true,
|
||||
onError: error => { errors.push(error); } });
|
||||
const resume = vi.fn(async () => undefined);
|
||||
try {
|
||||
const worker = registerProviderLimitResumeWork(db, coordinator,
|
||||
{ resume, schedulingSuppressed: async () => false }, () => true);
|
||||
await worker.ready;
|
||||
// Nothing starts before the reset.
|
||||
expect(resume).not.toHaveBeenCalled();
|
||||
await vi.waitFor(() => expect(resume).toHaveBeenCalledTimes(1), { timeout: 20_000, interval: 200 });
|
||||
const [receipt] = await db.select().from(agentWakeupRequests).where(and(
|
||||
eq(agentWakeupRequests.companyId, companyId), eq(agentWakeupRequests.reason, "task_retry"),
|
||||
eq(agentWakeupRequests.requestedByActorId, userId)));
|
||||
expect(resume).toHaveBeenCalledWith(companyId, receipt.id);
|
||||
expect(Date.now()).toBeGreaterThanOrEqual(resetAt.getTime());
|
||||
expect((await holdFor(issueId)).evidence.providerLimitResume).toMatchObject({ state: "requested", requestId: receipt.id });
|
||||
expect(hold.id).toBe((await holdFor(issueId)).id);
|
||||
} finally {
|
||||
await coordinator.stop();
|
||||
}
|
||||
expect(errors).toEqual([]);
|
||||
}, 30_000);
|
||||
|
||||
it("leaves a visible Retry when no user is accountable for the run", async () => {
|
||||
const resetAt = new Date(Date.now() + 3 * 60 * 60_000);
|
||||
resetAt.setUTCMinutes(0, 0, 0);
|
||||
const { issueId } = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: null });
|
||||
const hold = await holdFor(issueId);
|
||||
expect(hold.nextAction).toBe(`The provider usage limit resets at ${resetAt.toISOString()}. `
|
||||
+ "Retry the task after that time, or sooner if usage capacity is restored.");
|
||||
const outcome = await requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id },
|
||||
new Date(resetAt.getTime() + 1000));
|
||||
expect(outcome).toEqual({ requested: false, reason: "no_accountable_user" });
|
||||
expect((await holdFor(issueId)).nextAction).toBe("Paperclip did not retry this task after the provider usage limit "
|
||||
+ "reset because no user is accountable for the run. Retry the task when usage capacity is available.");
|
||||
});
|
||||
|
||||
it("prepares a connected chat conversation's Retry through the chat service", async () => {
|
||||
const resetAt = new Date(Date.now() + 2 * 60 * 60_000);
|
||||
resetAt.setUTCMinutes(0, 0, 0);
|
||||
const userId = `user-${randomUUID()}`;
|
||||
const { runId, issueId } = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: userId });
|
||||
// The task belongs to a restricted external chat conversation.
|
||||
const [application] = await db.insert(toolApplications).values({ companyId, name: "Slack", type: "chat" }).returning();
|
||||
const connectionId = randomUUID();
|
||||
await db.insert(toolConnections).values({ id: connectionId, companyId, applicationId: application!.id, uid: connectionId,
|
||||
name: "Slack", transport: "chat_sdk", connectionPurpose: "channel" });
|
||||
const endpointId = randomUUID();
|
||||
await db.insert(chatEndpoints).values({ id: endpointId, companyId, connectionId, provider: "slack", publicId: endpointId,
|
||||
assignedAgentId: agentId, status: "active", externalExecutionPolicy: "restricted" });
|
||||
await db.insert(chatConversations).values({ companyId, endpointId, issueId, externalConversationId: "channel",
|
||||
externalThreadId: issueId, externalLabel: "#limits", state: "waiting" });
|
||||
const hold = await holdFor(issueId);
|
||||
const chatActionId = randomUUID();
|
||||
const prepareChatRetry = vi.fn(async () => ({ actionId: chatActionId }));
|
||||
const outcome = await requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id, prepareChatRetry },
|
||||
new Date(resetAt.getTime() + 1000));
|
||||
expect(outcome).toMatchObject({ requested: true });
|
||||
expect(prepareChatRetry).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
||||
companyId, issueId, agentId, failedRunId: runId, initiatedByUserId: userId }));
|
||||
const [receipt] = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, companyId),
|
||||
eq(agentWakeupRequests.idempotencyKey, `task-retry:${PROVIDER_LIMIT_RESUME_KEY_PREFIX}${runId}`)));
|
||||
expect(receipt.payload).toMatchObject({ taskRetry: expect.objectContaining({ chatActionId }) });
|
||||
});
|
||||
|
||||
it("replaces the retry promise on every give-up path", async () => {
|
||||
const resetAt = new Date(Date.now() + 2 * 60 * 60_000);
|
||||
resetAt.setUTCMinutes(0, 0, 0);
|
||||
const afterReset = new Date(resetAt.getTime() + 1000);
|
||||
// The failed run's terminal can no longer be read as a provider-observed reset.
|
||||
const unreadable = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: `user-${randomUUID()}` });
|
||||
await db.delete(heartbeatRunEvents).where(eq(heartbeatRunEvents.runId, unreadable.runId));
|
||||
const unreadableHold = await holdFor(unreadable.issueId);
|
||||
expect(unreadableHold.nextAction).toContain("Paperclip will retry this task then");
|
||||
await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: unreadableHold.id }, afterReset))
|
||||
.resolves.toEqual({ requested: false, reason: "reset_unknown" });
|
||||
expect((await holdFor(unreadable.issueId)).nextAction).toBe("Paperclip did not retry this task after the provider "
|
||||
+ "usage limit reset because the provider's reset could no longer be read. Retry the task when usage capacity is available.");
|
||||
// The hold's run no longer failed for the usage limit.
|
||||
const changed = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: `user-${randomUUID()}` });
|
||||
await db.update(heartbeatRuns).set({ errorCode: "adapter_failed" }).where(eq(heartbeatRuns.id, changed.runId));
|
||||
const changedHold = await holdFor(changed.issueId);
|
||||
await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: changedHold.id }, afterReset))
|
||||
.resolves.toEqual({ requested: false, reason: "source_run_mismatch" });
|
||||
expect((await holdFor(changed.issueId)).nextAction).toBe("Paperclip did not retry this task after the provider "
|
||||
+ "usage limit reset because the failed run no longer matches this hold. Retry the task when usage capacity is available.");
|
||||
});
|
||||
|
||||
it("stops after three automatic Retries in a row and counts again after a successful run", async () => {
|
||||
const resetAt = new Date(Date.now() + 2 * 60 * 60_000);
|
||||
resetAt.setUTCMinutes(0, 0, 0);
|
||||
const afterReset = new Date(resetAt.getTime() + 1000);
|
||||
const userId = `user-${randomUUID()}`;
|
||||
const { issueId } = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: userId });
|
||||
const hold = await holdFor(issueId);
|
||||
// Earlier usage-limit Retries on this task, none followed by a success.
|
||||
const earlierRetry = (task: string) => ({ companyId, agentId, source: "on_demand", triggerDetail: "manual",
|
||||
reason: "task_retry", status: "completed", idempotencyKey: `task-retry:${PROVIDER_LIMIT_RESUME_KEY_PREFIX}${randomUUID()}`,
|
||||
requestedByActorType: "user", requestedByActorId: userId, payload: { issueId: task },
|
||||
requestedAt: new Date(Date.now() - 60_000) });
|
||||
// Two in a row still leave this one.
|
||||
await db.insert(agentWakeupRequests).values([earlierRetry(issueId), earlierRetry(issueId)]);
|
||||
const [third] = await db.insert(agentWakeupRequests).values(earlierRetry(issueId)).returning();
|
||||
await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id }, afterReset))
|
||||
.resolves.toEqual({ requested: false, reason: "automatic_retry_budget_used" });
|
||||
expect((await holdFor(issueId)).nextAction).toBe("Paperclip did not retry this task after the provider usage limit "
|
||||
+ "reset because three automatic Retries in a row did not restore usage. Retry the task when usage capacity is available.");
|
||||
expect(third.id).toBeTruthy();
|
||||
|
||||
// A successful run on the task after earlier Retries restores the budget.
|
||||
const second = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: userId });
|
||||
await db.insert(agentWakeupRequests).values([earlierRetry(second.issueId), earlierRetry(second.issueId),
|
||||
earlierRetry(second.issueId)]);
|
||||
await db.insert(heartbeatRuns).values({ companyId, agentId, status: "succeeded", runtimeMode: "native",
|
||||
nativeIssueId: second.issueId, invocationSource: "assignment", triggerDetail: "system",
|
||||
contextSnapshot: { issueId: second.issueId }, finishedAt: new Date(Date.now() - 1000),
|
||||
createdAt: new Date(Date.now() - 10 * 60_000) });
|
||||
const secondHold = await holdFor(second.issueId);
|
||||
await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: secondHold.id }, afterReset))
|
||||
.resolves.toMatchObject({ requested: true });
|
||||
});
|
||||
|
||||
it("rebuilds every waiting hold after a restart, past one page", async () => {
|
||||
const resetAt = new Date(Date.now() + 2 * 60 * 60_000);
|
||||
resetAt.setUTCMinutes(0, 0, 0);
|
||||
const { issueId } = await failTurn({ payload: weeklyLimit(resetAt), responsibleUserId: `user-${randomUUID()}` });
|
||||
const hold = await holdFor(issueId);
|
||||
// A hold saved before holds named their reset; it sorts after 600 others.
|
||||
const { providerLimitResetAt: _reset, ...oldEvidence } = hold.evidence;
|
||||
await db.delete(issueRecoveryActions).where(eq(issueRecoveryActions.id, hold.id));
|
||||
const otherCompanyId = randomUUID();
|
||||
await db.insert(companies).values({ id: otherCompanyId, name: "Other holds", issuePrefix: "OTH" });
|
||||
const otherIssues = Array.from({ length: 600 }, () => randomUUID());
|
||||
await db.insert(issues).values(otherIssues.map(id => ({ id, companyId: otherCompanyId, title: "Other", status: "in_progress" })));
|
||||
const { id: _id, companyId: _company, sourceIssueId: _issue, createdAt: _c, updatedAt: _u, ...template } = hold;
|
||||
for (let page = 0; page < 6; page++) {
|
||||
await db.insert(issueRecoveryActions).values(Array.from({ length: 100 }, (_, index) => ({ ...template,
|
||||
companyId: otherCompanyId, sourceIssueId: otherIssues[page * 100 + index]!,
|
||||
id: `00000000-0000-4000-8000-${String(page * 100 + index).padStart(12, "0")}`,
|
||||
evidence: { ...oldEvidence, runId: randomUUID() } })));
|
||||
}
|
||||
await db.insert(issueRecoveryActions).values({ ...hold, id: `ffffffff-ffff-4fff-bfff-${randomUUID().slice(-12)}`,
|
||||
evidence: oldEvidence });
|
||||
const errors: unknown[] = [];
|
||||
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true,
|
||||
onError: error => { errors.push(error); } });
|
||||
try {
|
||||
const worker = registerProviderLimitResumeWork(db, coordinator,
|
||||
{ resume: vi.fn(async () => undefined), schedulingSuppressed: async () => false }, () => true);
|
||||
await worker.ready;
|
||||
// The hold past the first page reads its reset and records it.
|
||||
await vi.waitFor(async () => expect((await holdFor(issueId)).evidence.providerLimitResetAt).toBe(resetAt.toISOString()),
|
||||
{ timeout: 25_000, interval: 250 });
|
||||
} finally {
|
||||
await coordinator.stop();
|
||||
}
|
||||
expect(errors).toEqual([]);
|
||||
}, 40_000);
|
||||
|
||||
it("reports a reset beyond the automatic wait without retrying by itself", async () => {
|
||||
// A monthly limit, typed by the provider, three weeks out.
|
||||
const resetAt = new Date(Date.now() + 21 * 24 * 60 * 60_000);
|
||||
resetAt.setUTCMinutes(0, 0, 0);
|
||||
const payload = weeklyLimit(resetAt);
|
||||
(payload.error.providerFailure as Record<string, unknown>).retryAt = resetAt.toISOString();
|
||||
const userId = `user-${randomUUID()}`;
|
||||
const { issueId } = await failTurn({ payload, responsibleUserId: userId });
|
||||
const hold = await holdFor(issueId);
|
||||
expect(hold.nextAction).toBe(`The provider usage limit resets at ${resetAt.toISOString()}. `
|
||||
+ "Retry the task after that time, or sooner if usage capacity is restored.");
|
||||
expect(hold.evidence).toMatchObject({ providerLimitResetAt: resetAt.toISOString() });
|
||||
await expect(requestProviderLimitResumeRetry(db, { companyId, actionId: hold.id },
|
||||
new Date(resetAt.getTime() + 1000))).resolves.toEqual({ requested: false, reason: "reset_beyond_wait" });
|
||||
expect((await holdFor(issueId)).nextAction).toBe(hold.nextAction);
|
||||
const receipts = await db.select().from(agentWakeupRequests).where(and(eq(agentWakeupRequests.companyId, companyId),
|
||||
eq(agentWakeupRequests.requestedByActorId, userId)));
|
||||
expect(receipts).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -226,6 +226,37 @@ describe("provider pack admission PostgreSQL fencing", () => {
|
||||
} finally { release(); await owner; }
|
||||
await expect(recordNativeProviderPackAdmission(db, f)).resolves.toBe(true);
|
||||
});
|
||||
it.each([false, true])("waits for a concurrent run-event append's run-row lock instead of losing the admission (waitForClaim: %s)", async waitForClaim => {
|
||||
// Staging failure: a run-event append locks the run row
|
||||
// (FOR NO KEY UPDATE, as appendHeartbeatRunEvent does) for milliseconds. A
|
||||
// NOWAIT admission write failed, left the state pending, and artifact
|
||||
// retention then failed the run as native_provider_artifacts_admission_unverified.
|
||||
const f = await fixture();
|
||||
let release!: () => void, acquired!: () => void;
|
||||
const holding = new Promise<void>(resolve => { acquired = resolve; });
|
||||
const gate = new Promise<void>(resolve => { release = resolve; });
|
||||
const append = db.transaction(async tx => {
|
||||
await tx.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(eq(heartbeatRuns.id, f.identity.runId)).for("no key update");
|
||||
acquired(); await gate;
|
||||
});
|
||||
await holding;
|
||||
let settled = false;
|
||||
const recording = recordNativeProviderPackAdmission(db, { ...f, waitForClaim } as Parameters<typeof recordNativeProviderPackAdmission>[1])
|
||||
.then(value => { settled = true; return { value }; }, error => { settled = true; return { error }; });
|
||||
try {
|
||||
// Release only after the admission is proven to wait on the run row, so
|
||||
// the old NOWAIT code cannot pass by running after the append commits.
|
||||
await vi.waitFor(async () => {
|
||||
const [row] = await db.execute<{ waiting: boolean }>(sql`select exists(select 1 from pg_stat_activity
|
||||
where datname = current_database() and wait_event_type = 'Lock' and state = 'active'
|
||||
and query like '%heartbeat_runs%') as waiting`);
|
||||
expect(settled || row.waiting).toBe(true);
|
||||
}, { timeout: 800 });
|
||||
} finally { release(); await append; }
|
||||
expect(await recording).toEqual({ value: true });
|
||||
expect((await read(f.identity.runId)).runnerProfileJson?.nativeProviderPackAdmissionState)
|
||||
.toEqual({ ...f.profile.nativeProviderPackAdmissionState, state: "verified" });
|
||||
});
|
||||
it.each([false, true])("waits within the durable-capture bound and rechecks the claim after its lock (revoked: %s)", async revoked => {
|
||||
const f = await fixture();
|
||||
let release!: () => void, acquired!: () => void;
|
||||
|
||||
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user