mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 14:35:17 +01:00
Merge current master while preserving Photon sleep handoff
This commit is contained in:
commit
02c754159b
53 files changed
+1024
-3151
No files matched your search
@@ -22,11 +22,12 @@ replaying tasks, changing credentials, or deploying instrumentation.
|
||||
| What is a page's real-user load time or SLO on a hosted instance? | Browser `page.load` spans in [browser performance tracing](../../../doc/browser-performance-tracing.md) |
|
||||
| Which CI jobs or test files delay the whole suite? | [CI profiling](references/ci.md) |
|
||||
| How should a trace be organized so a person can understand it? | Human-readable waterfall guidance below and [trace design](references/trace-design.md) |
|
||||
| Where should a new span go? | Instrumentation guidance below and [Observability contract](../../../doc/observability.md) |
|
||||
| Where should a new span go? | Instrumentation guidance below and the code that opens the nearest existing span |
|
||||
|
||||
Repository-relative paths and commands assume the checkout root. The maintained
|
||||
contracts are `doc/observability.md` and `doc/ci-profiling.md`; recheck them and
|
||||
the owning code when a deployed version differs.
|
||||
Repository-relative paths and commands assume the checkout root. Span names and
|
||||
attributes are defined in the code that opens each span; `doc/observability.md`
|
||||
covers only operator setup and Sentry. `doc/ci-profiling.md` covers CI traces.
|
||||
Recheck the owning code when a deployed version differs.
|
||||
|
||||
Keep the repository's three paths distinct:
|
||||
|
||||
@@ -178,7 +179,7 @@ explain one slow scan.
|
||||
Observability must not retry the operation, replace its return/error, change
|
||||
authorization/locks, or break execution when the tracer fails. Preserve root
|
||||
sampling and the explicit endpoint gate even if another library registers an
|
||||
OTel provider. Update `doc/observability.md` when the trace contract changes.
|
||||
OTel provider. Update `doc/observability.md` only when operator setup changes.
|
||||
Run focused tests for endpoint-off behavior, parentage/concurrent-run isolation,
|
||||
failure handling, and the changed seam. Use real exported evidence to claim that
|
||||
new spans appear in Honeycomb; a unit-test tracer alone does not prove ingestion.
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
Read this when adding, reorganizing, or reviewing a waterfall's hierarchy.
|
||||
The goal is to understand the work at a glance, then expand the slow phase to
|
||||
find its cause. Follow the current
|
||||
[Observability contract](../../../../doc/observability.md) for exact names,
|
||||
roots, lifecycle boundaries, sampling, and allowed attributes.
|
||||
find its cause. Follow the code that
|
||||
opens the nearest existing span for exact names, roots, lifecycle boundaries,
|
||||
sampling, and allowed attributes.
|
||||
|
||||
## Organize by the work being done
|
||||
|
||||
|
||||
+1
-1
@@ -122,7 +122,7 @@ and coverage requirements.
|
||||
|
||||
This repo has three separate data paths: Telemetry, Observability, and the run log. See [`rules/data-paths.mdc`](rules/data-paths.mdc) for the full definitions and the review level each path needs.
|
||||
|
||||
If your change adds, removes, or modifies emitted telemetry events, update the [Telemetry Data Contract](packages/shared/src/telemetry/README.md) in the same PR. Keep clients emitting raw dimension values and avoid documenting or relying on private delivery details. If your change adds, removes, or modifies an OpenTelemetry span or span attribute, keep the change inside the closed span-attribute allowlist in `packages/adapter-utils/src/acpx-engine/startup-timing.ts`. If your change adds or modifies a run-log event, update `doc/run-log-events.md` in the same PR.
|
||||
If your change adds, removes, or modifies emitted telemetry events, update the [Telemetry Data Contract](packages/shared/src/telemetry/README.md) in the same PR. Keep clients emitting raw dimension values and avoid documenting or relying on private delivery details. If your change adds, removes, or modifies an OpenTelemetry span or span attribute, keep the change inside the closed span-attribute allowlist in `packages/adapter-utils/src/acpx-engine/startup-timing.ts`. Define a new or changed run-log event where it is written; do not list it in a doc.
|
||||
|
||||
### Paperclip Gates Must Pass
|
||||
|
||||
|
||||
+36
-1716
File diff suppressed because it is too large.
Load diff
+17
-1256
File diff suppressed because it is too large.
Load diff
@@ -343,7 +343,7 @@ idempotent redaction projection. Repeated projection preserves the original
|
||||
payload digest. Provider recovery uses the same projection to compare saved
|
||||
completion results with provider history. Changed private bodies still conflict.
|
||||
Restart preparation preserves the run's admitted REST credential scope, even
|
||||
when the task mode changes. See [the run-log guide](run-log-events.md) for stored fields.
|
||||
when the task mode changes. The stored fields are defined where the run-log event is written.
|
||||
|
||||
The server-issued REST credential for the bound run is never returned to the model.
|
||||
Streaming, WebSocket, MCP and authentication
|
||||
|
||||
@@ -79,7 +79,7 @@ receipt and inline response policy as newly created webhook secrets.
|
||||
Task image access requires the company boundary and the task permission;
|
||||
skill-test and low-trust agents do not need company-wide browsing authority.
|
||||
Completion replay applies the same idempotent projection to stored and expected
|
||||
payloads; [the run-log guide](../../doc/run-log-events.md) describes its fields.
|
||||
payloads; its fields are defined where the [run-log event](../../doc/run-log-events.md) is written.
|
||||
|
||||
Sources: [API client](../../server/src/services/native-runtime/runner-api-client.ts),
|
||||
[catalog](../../server/src/services/native-runtime/runner-api-catalog.ts),
|
||||
|
||||
@@ -287,7 +287,8 @@ The native first-text span ends after text is committed for the existing run-eve
|
||||
reader, including reasoning and completed responses. It exports only the bounded
|
||||
text kind and timing, with no text content or new agent access.
|
||||
This adds no agent API, credential access, run-log write, or recovery authority.
|
||||
See [the tracing contract](../../doc/observability.md#controller-preparation-phases).
|
||||
See the spans in
|
||||
[`execution-preparation-timing.ts`](../../server/src/services/execution-preparation-timing.ts).
|
||||
Live latency verification remains separate from the existing access baseline.
|
||||
|
||||
API: `present` — representative operation IDs:
|
||||
|
||||
@@ -110,7 +110,8 @@ Eyes should appear after authorized task/comment persistence, independently of
|
||||
file preparation, subscription and agent startup. Duplicate delivery must keep
|
||||
one receipt; the final reply must remove only its source message's eyes. Record
|
||||
live mention-to-reaction timing separately from the PostgreSQL fixture tests and
|
||||
the `chat.slack.receipt` transport span described in [Observability](../../doc/observability.md).
|
||||
the `chat.slack.receipt` transport span in
|
||||
[`receipt-timing.ts`](../../server/src/services/chat-channels/slack/receipt-timing.ts).
|
||||
|
||||
During a top-level DM run, verify that the bot adds eyes to the source message
|
||||
and removes them when the final reply arrives. The pinned Slack SDK encodes a
|
||||
|
||||
@@ -44,7 +44,8 @@ For latency diagnosis with an operator OTLP endpoint, search the hashed run ID
|
||||
without restricting the root span name. Compare workspace preparation with its
|
||||
`workspace_<step>` intervals. Measure controller readiness separately through
|
||||
`controller.startup.<phase>`. A recovery pause or deployment drain is not model
|
||||
execution time. See the [tracing contract](../../doc/observability.md#controller-preparation-phases).
|
||||
execution time. See the spans in
|
||||
[`execution-preparation-timing.ts`](../../server/src/services/execution-preparation-timing.ts).
|
||||
These source-level diagnostics do not establish a live response-time budget.
|
||||
`task.time_to_first_token` measures accepted ingress through the first committed
|
||||
text that the task transcript can show, including thinking and completed
|
||||
|
||||
@@ -132,9 +132,8 @@ export const HTTP2_BRIDGE_SERVER_OPTIONS: http2.ServerOptions = {
|
||||
* total, so no combination of concurrent streams, across every route, can
|
||||
* retain more than this many bytes at once. This value keeps the accepted
|
||||
* process ceiling at 1,073,741,824 bytes (1 GiB) — the same ceiling
|
||||
* `doc/observability.md` already accepted before the per-body limit rose to
|
||||
* 10 MiB — now enforced by this reservation instead of left as an unenforced
|
||||
* document note. See the per-route budget comment above for the full
|
||||
* the project already accepted before the per-body limit rose to 10 MiB —
|
||||
* now enforced by this reservation instead of left as an unenforced note. See the per-route budget comment above for the full
|
||||
* accounting.
|
||||
*/
|
||||
export const HTTP2_BRIDGE_MAX_PROCESS_BODY_BYTES = 1024 * 1024 * 1024;
|
||||
|
||||
@@ -39,12 +39,14 @@ test("distribution build admits network settings without provider keys or Node i
|
||||
test("setup cancellation physically stops an in-flight owned child", { timeout: 5_000 }, async t => {
|
||||
const { root } = await fixture(t), pidFile = join(root, "pid");
|
||||
const controller = new AbortController();
|
||||
const result = runKimiBuildCommand(process.execPath, ["-e", "require('node:fs').writeFileSync(process.argv[1],String(process.pid));setInterval(()=>{},1000)", pidFile], { env: {}, timeout: 3_000 }, undefined, controller.signal).then(() => null, error => error);
|
||||
let pid;
|
||||
const result = runKimiBuildCommand(process.execPath, ["-e", "const f=require('node:fs');f.writeFileSync(process.argv[1]+'.tmp',String(process.pid));f.renameSync(process.argv[1]+'.tmp',process.argv[1]);setInterval(()=>{},1000)", pidFile], { env: {}, timeout: 3_000 }, undefined, controller.signal).then(() => null, error => error);
|
||||
let pid, settled = false;
|
||||
void result.then(() => { settled = true; });
|
||||
try {
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
try { pid = Number(await readFile(pidFile, "utf8")); break; }
|
||||
catch (error) { if (error.code !== "ENOENT") throw error; await delay(10); }
|
||||
while (!settled && !(Number.isSafeInteger(pid) && pid > 0)) {
|
||||
try { pid = Number(await readFile(pidFile, "utf8")); }
|
||||
catch (error) { if (error.code !== "ENOENT") throw error; }
|
||||
await delay(10);
|
||||
}
|
||||
assert.ok(Number.isSafeInteger(pid) && pid > 0, "The real child did not start");
|
||||
controller.abort();
|
||||
|
||||
@@ -54,7 +54,7 @@ test("installed Kimi setup is self-contained, rejects corrupt assets and cancels
|
||||
let stderr = ""; cancelled.stderr.on("data", chunk => { stderr = (stderr + chunk).slice(-4096); });
|
||||
const kill = setTimeout(() => cancelled.kill("SIGKILL"), 5_000);
|
||||
try {
|
||||
for (let attempt = 0; attempt < 100; attempt++) {
|
||||
while (cancelled.exitCode === null && cancelled.signalCode === null) {
|
||||
try { if (await readFile(ready, "utf8") === "ready") break; }
|
||||
catch (error) { if (error.code !== "ENOENT") throw error; }
|
||||
await delay(10);
|
||||
|
||||
@@ -86,8 +86,8 @@ test("release metadata rejects incompatible native, harness and protocol contrac
|
||||
|
||||
async function withOwnedChildren(root, action) {
|
||||
const owned = [];
|
||||
const start = (command, args) => {
|
||||
const child = spawn(command, args, { env: { PATH: "/usr/bin:/bin" }, stdio: "ignore" });
|
||||
const start = (command, args, argv0) => {
|
||||
const child = spawn(command, args, { argv0, env: { PATH: "/usr/bin:/bin" }, stdio: "ignore" });
|
||||
// close follows both exit and spawn error. A failed second spawn must not
|
||||
// interrupt retirement of the first still-running executable.
|
||||
const closed = new Promise(resolve => child.once("close", resolve));
|
||||
@@ -115,7 +115,7 @@ test("atomically publishes while the previous executable is running", { skip: pr
|
||||
await withOwnedChildren(root, async start => {
|
||||
await stageRunnerBinary("/bin/sleep", destination);
|
||||
const previous = await stat(destination);
|
||||
const old = start(destination, ["30"]);
|
||||
const old = start(destination, ["30"], "sleep");
|
||||
await old.spawned;
|
||||
await stageRunnerBinary("/bin/sleep", destination);
|
||||
const published = await stat(destination);
|
||||
@@ -124,7 +124,7 @@ test("atomically publishes while the previous executable is running", { skip: pr
|
||||
assert.equal(old.child.exitCode, null);
|
||||
assert.equal(old.child.signalCode, null);
|
||||
assert.deepEqual(await readdir(root), ["paperclip-runnerd"]);
|
||||
const next = start(destination, ["0"]);
|
||||
const next = start(destination, ["0"], "sleep");
|
||||
await next.spawned; await next.closed;
|
||||
assert.equal(next.child.exitCode, 0);
|
||||
});
|
||||
@@ -150,7 +150,7 @@ test("a source rebuild selects fresh dev bytes while preserving release binaries
|
||||
await mkdir(path.dirname(source), { recursive: true });
|
||||
await writeFile(source, "fn main() {}\n");
|
||||
await mkdir(path.dirname(built), { recursive: true });
|
||||
await copyHostFixture("/bin/echo", built);
|
||||
await copyHostFixture("/bin/sh", built);
|
||||
const previousBuild = path.join(root, "previous-build");
|
||||
await copyHostFixture("/bin/sleep", previousBuild);
|
||||
await stageRunnerBinary(previousBuild, hostTarget);
|
||||
@@ -178,7 +178,7 @@ test("a source rebuild selects fresh dev bytes while preserving release binaries
|
||||
const manifestPath = path.join(binaryRoot, "release-manifest.json");
|
||||
const manifest = JSON.stringify({ schema: "paperclip.runner.release-binaries.v1", sourceRevision: "a".repeat(40), platforms });
|
||||
await writeFile(manifestPath, manifest);
|
||||
const old = start(hostTarget, ["30"]);
|
||||
const old = start(hostTarget, ["30"], "sleep");
|
||||
await old.spawned;
|
||||
const requirement = { repoRoot: root, nativeRunnerRequired: true };
|
||||
assert.equal(paperclipRunnerBinaryNeedsBuild(requirement), true);
|
||||
@@ -198,7 +198,7 @@ test("a source rebuild selects fresh dev bytes while preserving release binaries
|
||||
assert.equal(paperclipRunnerBinaryNeedsBuild(requirement), false);
|
||||
assert.equal(old.child.exitCode, null);
|
||||
assert.equal(old.child.signalCode, null);
|
||||
const next = start(selected.binary, ["rebuilt"]);
|
||||
const next = start(selected.binary, ["-c", "exit 0"]);
|
||||
await next.spawned; await next.closed;
|
||||
assert.equal(next.child.exitCode, 0);
|
||||
});
|
||||
|
||||
@@ -293,6 +293,12 @@ export class SemanticToolNotDispatchedError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export class SemanticToolHandedOffError extends Error {
|
||||
constructor() {
|
||||
super("semantic_tool_handed_off");
|
||||
}
|
||||
}
|
||||
|
||||
export interface DurablePrpControlPlaneOptions {
|
||||
stateDirectory: string;
|
||||
identity: DurableRecoveryIdentity;
|
||||
@@ -4798,6 +4804,7 @@ export class DurablePrpControlPlane {
|
||||
queueResult(outcome.result, outcome.isError === true),
|
||||
)
|
||||
.catch((error: unknown) => {
|
||||
if (error instanceof SemanticToolHandedOffError) return;
|
||||
if (error instanceof SemanticToolNotDispatchedError) {
|
||||
queueResult({ error: {
|
||||
code: "semantic_tool_not_dispatched",
|
||||
|
||||
+82
-7
@@ -3,7 +3,8 @@ import { createServer } from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { DurablePrpControlPlane } from "../control-plane/durable-prp-control-plane.js";
|
||||
import * as durableControlPlane from "../control-plane/durable-prp-control-plane.js";
|
||||
import type { DurablePrpControlPlane } from "../control-plane/durable-prp-control-plane.js";
|
||||
import { recoverToolCallback, TOOL_CALLBACK_INTERRUPTED_CODE } from "../control-plane/orphaned-tool-callback.js";
|
||||
import { createCapabilityRunnerdCodexTransport } from "./runnerd-codex-transport.js";
|
||||
import { defaultCapabilityRunnerdBinary, fakeCodex, fakeCodexArgs } from "../../test/support/runnerd-transport.js";
|
||||
@@ -12,7 +13,7 @@ const taskTool = { name: "get_task_context", description: "Read current task", i
|
||||
|
||||
type SavedCommand = { commandId: string; type: string; status: string; payload: Record<string, unknown> };
|
||||
|
||||
it("settles an earlier generation's in-flight tool call at attach even when that attach never finishes startup", async () => {
|
||||
it.each(["dispatched to its handler", "still before dispatch"] as const)("settles an earlier generation's in-flight tool call at attach even when that attach never finishes startup (%s at detach)", async stage => {
|
||||
const stateDirectory = await mkdtemp(join(tmpdir(), "runnerd-orphaned-tool-at-attach-"));
|
||||
const controlPlaneStatePath = join(stateDirectory, "control-plane", "control-plane-state.json");
|
||||
const server = createServer();
|
||||
@@ -55,8 +56,28 @@ it("settles an earlier generation's in-flight tool call at attach even when that
|
||||
const recovered = vi.fn(async (call: { operationId: string; callId: string; input: unknown; admission?: "this_controller" | "earlier_controller" }) =>
|
||||
recoverToolCallback({ runId: identity.runId, call: { tool: call.operationId, callId: call.callId, arguments: call.input },
|
||||
admission: call.admission, recover: async () => null }));
|
||||
let reached!: () => void;
|
||||
const callReached = new Promise<void>(resolveReached => { reached = resolveReached; });
|
||||
let releaseDispatch!: () => void;
|
||||
const dispatchGate = new Promise<void>(resolveGate => { releaseDispatch = resolveGate; });
|
||||
let gatedOutcome: Promise<unknown> | null = null;
|
||||
const OriginalCore = durableControlPlane.DurablePrpControlPlane;
|
||||
const coreSpy = vi.spyOn(durableControlPlane, "DurablePrpControlPlane").mockImplementation(function (coreOptions) {
|
||||
const dispatch = coreOptions.onSemanticToolInput;
|
||||
if (stage === "still before dispatch" && dispatch && !gatedOutcome) {
|
||||
coreOptions = { ...coreOptions, onSemanticToolInput: call => {
|
||||
reached();
|
||||
gatedOutcome = dispatchGate.then(() => dispatch(call));
|
||||
return gatedOutcome as ReturnType<typeof dispatch>;
|
||||
} };
|
||||
}
|
||||
return new OriginalCore(coreOptions);
|
||||
});
|
||||
const first = createCapabilityRunnerdCodexTransport(options);
|
||||
first.transport.setServerRequestHandler(() => new Promise<Record<string, unknown>>(() => undefined));
|
||||
first.transport.setServerRequestHandler(() => {
|
||||
reached();
|
||||
return new Promise<Record<string, unknown>>(() => undefined);
|
||||
});
|
||||
const generations: Array<ReturnType<typeof createCapabilityRunnerdCodexTransport>> = [];
|
||||
let runnerPid: number | null = null;
|
||||
const savedToolResults = async () => (JSON.parse(await readFile(controlPlaneStatePath, "utf8")) as { commands: SavedCommand[] })
|
||||
@@ -66,11 +87,11 @@ it("settles an earlier generation's in-flight tool call at attach even when that
|
||||
runnerPid = first.evidence().runnerPid;
|
||||
const runnerStartedAt = first.transport.processInfo!().startedAt;
|
||||
await first.transport.request("turn/start", { input: [{ type: "text", text: "Read current task" }] });
|
||||
await vi.waitFor(async () => {
|
||||
const saved = JSON.parse(await readFile(controlPlaneStatePath, "utf8")) as { committedEvents: Array<{ eventType: string }> };
|
||||
expect(saved.committedEvents.some(event => event.eventType === "semantic_tool.input")).toBe(true);
|
||||
}, { timeout: 10_000 });
|
||||
await callReached;
|
||||
await first.detachControllerForRestart();
|
||||
releaseDispatch();
|
||||
await (gatedOutcome as Promise<unknown> | null)?.catch(() => undefined);
|
||||
await new Promise<void>(resolveTurn => setImmediate(resolveTurn));
|
||||
expect(await savedToolResults()).toEqual([]);
|
||||
|
||||
const adopt = (graceMs?: number) => {
|
||||
@@ -110,6 +131,8 @@ it("settles an earlier generation's in-flight tool call at attach even when that
|
||||
}, { timeout: 10_000 });
|
||||
expect(recovered).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
releaseDispatch();
|
||||
coreSpy.mockRestore();
|
||||
for (const generation of generations.reverse()) await generation.transport.close().catch(() => undefined);
|
||||
await first.transport.close().catch(() => undefined);
|
||||
if (runnerPid) {
|
||||
@@ -120,3 +143,55 @@ it("settles an earlier generation's in-flight tool call at attach even when that
|
||||
await rm(stateDirectory, { recursive: true, force: true });
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
it("still settles a call stopped before dispatch as not dispatched when the controller closes without a restart", async () => {
|
||||
const stateDirectory = await mkdtemp(join(tmpdir(), "runnerd-not-dispatched-at-close-"));
|
||||
const controlPlaneStatePath = join(stateDirectory, "control-plane", "control-plane-state.json");
|
||||
let reached!: () => void;
|
||||
const callReached = new Promise<void>(resolveReached => { reached = resolveReached; });
|
||||
let releaseDispatch!: () => void;
|
||||
const dispatchGate = new Promise<void>(resolveGate => { releaseDispatch = resolveGate; });
|
||||
let gatedOutcome: Promise<unknown> | null = null;
|
||||
const OriginalCore = durableControlPlane.DurablePrpControlPlane;
|
||||
const coreSpy = vi.spyOn(durableControlPlane, "DurablePrpControlPlane").mockImplementation(function (coreOptions) {
|
||||
const dispatch = coreOptions.onSemanticToolInput;
|
||||
if (dispatch && !gatedOutcome) {
|
||||
coreOptions = { ...coreOptions, onSemanticToolInput: call => {
|
||||
reached();
|
||||
gatedOutcome = dispatchGate.then(() => dispatch(call));
|
||||
return gatedOutcome as ReturnType<typeof dispatch>;
|
||||
} };
|
||||
}
|
||||
return new OriginalCore(coreOptions);
|
||||
});
|
||||
const bundle = createCapabilityRunnerdCodexTransport({
|
||||
runnerBinary: defaultCapabilityRunnerdBinary(),
|
||||
codexCommand: fakeCodex,
|
||||
codexArgs: fakeCodexArgs(stateDirectory, "--emit-tool-call"),
|
||||
stateDirectory,
|
||||
});
|
||||
bundle.transport.setServerRequestHandler(() => new Promise<Record<string, unknown>>(() => undefined));
|
||||
let runnerPid: number | null = null;
|
||||
try {
|
||||
await bundle.transport.request("thread/start", { cwd: tmpdir(), dynamicTools: [taskTool] });
|
||||
runnerPid = bundle.evidence().runnerPid;
|
||||
await bundle.transport.request("turn/start", { input: [{ type: "text", text: "Read current task" }] });
|
||||
await callReached;
|
||||
const closing = bundle.transport.close().catch(() => undefined);
|
||||
releaseDispatch();
|
||||
await (gatedOutcome as Promise<unknown> | null)?.catch(() => undefined);
|
||||
await closing;
|
||||
const results = (JSON.parse(await readFile(controlPlaneStatePath, "utf8")) as { commands: SavedCommand[] })
|
||||
.commands.filter(command => command.type === "semantic_tool.result");
|
||||
expect(results).toHaveLength(1);
|
||||
expect(JSON.stringify(results[0]!.payload)).toContain("semantic_tool_not_dispatched");
|
||||
} finally {
|
||||
releaseDispatch();
|
||||
coreSpy.mockRestore();
|
||||
await bundle.transport.close().catch(() => undefined);
|
||||
if (runnerPid) {
|
||||
try { process.kill(-runnerPid, "SIGKILL"); } catch { runnerPid = null; }
|
||||
}
|
||||
await rm(stateDirectory, { recursive: true, force: true });
|
||||
}
|
||||
}, 120_000);
|
||||
@@ -76,6 +76,7 @@ import { NativeRunnerResumeStateUnavailableError, NativeRunnerSourceReconciliati
|
||||
import {
|
||||
DurablePrpControlPlane,
|
||||
inspectStagedRunAttachment,
|
||||
SemanticToolHandedOffError,
|
||||
SemanticToolNotDispatchedError,
|
||||
durableRecoveryInternals,
|
||||
inspectWarmRunTransition,
|
||||
@@ -6518,7 +6519,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
onAuthenticatedConnection: () => this.#startupSteps?.advance("runner.process.launch", "provider.session.load"),
|
||||
get authorityRunId() { return authorityRunId(); },
|
||||
semanticInputMode: this.#retainsSourceInputs() || this.options.recoveryPurpose === "stop_cleanup" ? "retain_only" : "dispatch",
|
||||
onSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : (call) => this.#handleSemanticToolInput(call),
|
||||
onSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : (call) => this.#dispatchSemanticToolInput(call),
|
||||
recoverSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : call => this.#recoverSemanticToolInput(call),
|
||||
onCommittedEvent: async (event) => {
|
||||
const source = this.#sourceAccountingIdentity();
|
||||
@@ -7079,7 +7080,7 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
onAuthenticatedConnection: () => this.#startupSteps?.advance("runner.process.launch", "provider.session.load"),
|
||||
get authorityRunId() { return authorityRunId(); },
|
||||
semanticInputMode: this.#retainsSourceInputs() || this.options.recoveryPurpose === "stop_cleanup" ? "retain_only" : "dispatch",
|
||||
onSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : (call) => this.#handleSemanticToolInput(call),
|
||||
onSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : (call) => this.#dispatchSemanticToolInput(call),
|
||||
recoverSemanticToolInput: this.options.recoveryPurpose === "stop_cleanup" ? undefined : call => this.#recoverSemanticToolInput(call),
|
||||
onCommittedEvent: async (event) => {
|
||||
const source = this.#sourceAccountingIdentity();
|
||||
@@ -7680,6 +7681,15 @@ class DurablePrpCodexTransport implements CodexAppServerTransport {
|
||||
return outcome ? this.#bindSemanticToolOutcome(call, outcome) : null;
|
||||
}
|
||||
|
||||
async #dispatchSemanticToolInput(call: Parameters<NonNullable<DurablePrpControlPlaneOptions["onSemanticToolInput"]>>[0]) {
|
||||
try {
|
||||
return await this.#handleSemanticToolInput(call);
|
||||
} catch (error) {
|
||||
if (error instanceof SemanticToolNotDispatchedError && this.#controllerDetachedForRestart) throw new SemanticToolHandedOffError();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async #handleSemanticToolInput(
|
||||
call: Parameters<
|
||||
NonNullable<DurablePrpControlPlaneOptions["onSemanticToolInput"]>
|
||||
|
||||
@@ -126,9 +126,8 @@ This document covers Paperclip Telemetry only. The generated Telemetry
|
||||
contract covers neither the Observability path nor the run-log path. Two other
|
||||
data paths document their own contract in their own file:
|
||||
|
||||
- [Observability](../../../../doc/observability.md) — the OpenTelemetry trace
|
||||
path, the sandbox startup trace spans, and the sandbox duplex transport
|
||||
instrumentation.
|
||||
- [Observability](../../../../doc/observability.md) — the operator-enabled
|
||||
OpenTelemetry trace path and Sentry error monitoring.
|
||||
- [Run-Log Events](../../../../doc/run-log-events.md) — events written to the
|
||||
local `heartbeat_run_events` table.
|
||||
|
||||
|
||||
@@ -49,10 +49,10 @@ Apply a review level that matches the path:
|
||||
- **Observability change (lighter review).** The operator endpoint gate stays in
|
||||
place. The no-operation behaviour stays when no endpoint is set. A privacy
|
||||
review is not necessary while the change stays inside the closed
|
||||
span-attribute allowlist.
|
||||
span-attribute allowlist defined in the code that opens the span.
|
||||
- **Run-log change (no extra review).** A run-log change needs neither review
|
||||
level above, because the data stays in the instance database. Update
|
||||
`doc/run-log-events.md` when an event is added or changed.
|
||||
level above, because the data stays in the instance database. Define the
|
||||
event and its payload where it is written; do not list it in a doc.
|
||||
|
||||
## Exclusion
|
||||
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import { appendFileSync } from "node:fs";
|
||||
import { createServer } from "node:http";
|
||||
import { setImmediate as immediate } from "node:timers/promises";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { agents, heartbeatRunEvents, heartbeatRuns, issueComments, issues } from "@paperclipai/db";
|
||||
import { trimWorkSignalStack, workSignalDebug } from "@paperclipai/db/work-signal-debug";
|
||||
import { issueService } from "../services/issues.js";
|
||||
import { describeIssueRecovery, issueRecoveryFixture } from "./issue-recovery.test-fixture.js";
|
||||
import { seedRecoveryPopulation } from "./helpers/recovery-population.js";
|
||||
|
||||
vi.hoisted(() => { process.env.PAPERCLIP_DEBUG_WORK_SIGNALS = "stranded-assignments:1,assigned-work-invariant:1"; });
|
||||
|
||||
const MINUTE = 60_000;
|
||||
const measuring = Boolean(process.env.RECOVERY_ACTIVITY_REPORT);
|
||||
const report = (label: string, summary: unknown) => {
|
||||
if (process.env.RECOVERY_ACTIVITY_REPORT) appendFileSync(process.env.RECOVERY_ACTIVITY_REPORT, `${label} ${JSON.stringify(summary, null, 1)}\n`);
|
||||
};
|
||||
const TASK_QUEUES = new Set(["stranded-assignments", "assigned-work-invariant", "resolved-dependencies", "stale-issue-locks"]);
|
||||
type Recorded = { at: number; topic: string; name: string; fields: Record<string, unknown> };
|
||||
|
||||
describeIssueRecovery("recovery checks while runs are active in a staging-shaped company", () => {
|
||||
const state = issueRecoveryFixture({ meter: true });
|
||||
|
||||
async function advance(ms: number) {
|
||||
const until = Date.now() + ms;
|
||||
while (Date.now() < until) {
|
||||
await vi.advanceTimersByTimeAsync(Math.min(1000, until - Date.now()));
|
||||
await Promise.allSettled([...state.passes]); await immediate();
|
||||
}
|
||||
}
|
||||
|
||||
function record() {
|
||||
const events: Recorded[] = [];
|
||||
vi.spyOn(workSignalDebug, "event").mockImplementation((topic, name, fields = {}) => {
|
||||
if (name === "check") events.push({ at: Date.now(), topic, name, fields });
|
||||
});
|
||||
vi.spyOn(workSignalDebug, "signal").mockImplementation((topic, hint) => {
|
||||
if (!TASK_QUEUES.has(topic)) return;
|
||||
const holder: { stack?: string } = {};
|
||||
const limit = Error.stackTraceLimit;
|
||||
Error.stackTraceLimit = 40;
|
||||
Error.captureStackTrace(holder);
|
||||
Error.stackTraceLimit = limit;
|
||||
const frames = trimWorkSignalStack(holder.stack, 30).filter(line => !/issue-recovery-notifications|run-dispatch-notifications|external-conversation-settlement-notifications|native-status-reassessment-notifications|execution-control-notifications|issue-review-state-notifications|mockImplementation|spy|vitest/.test(line));
|
||||
const short = (line: string) => line.replace(/^at (async )?/, "").replace(/\(?\/.*\/server\/src\//, "(").replace(/:\d+\)?$/, ")");
|
||||
const app = frames.filter(line => /services|modules|routes/.test(line));
|
||||
const caller = app.length ? app.slice(0, process.env.RECOVERY_ACTIVITY_FRAMES ? Number(process.env.RECOVERY_ACTIVITY_FRAMES) : 1).map(short).join(" < ")
|
||||
: short(frames[0] ?? "unknown");
|
||||
const kind = hint === undefined || hint === "*" ? "all" : (() => {
|
||||
const scope = JSON.parse(hint) as Record<string, unknown>;
|
||||
return scope.issueId ? "task" : scope.graphRunId || scope.graphIssueId ? "graph" : scope.backstop ? "backstop" : "company";
|
||||
})();
|
||||
events.push({ at: Date.now(), topic, name: "signal", fields: { kind, caller } });
|
||||
});
|
||||
return events;
|
||||
}
|
||||
|
||||
function summarize(events: Recorded[], seconds: number) {
|
||||
const checks: Record<string, Record<string, number>> = {}, signals: Record<string, number> = {}, scoped: Record<string, number> = {};
|
||||
for (const event of events) {
|
||||
if (event.name === "check") {
|
||||
const byQueue = checks[event.topic] ??= {};
|
||||
byQueue[String(event.fields.wake)] = (byQueue[String(event.fields.wake)] ?? 0) + 1;
|
||||
} else if (event.topic === "stranded-assignments" && (event.fields.kind === "task" || event.fields.kind === "graph")) {
|
||||
const key = `${event.fields.kind} ${event.fields.caller}`;
|
||||
scoped[key] = (scoped[key] ?? 0) + 1;
|
||||
} else if (event.fields.kind !== "task" && event.fields.kind !== "graph") {
|
||||
const key = `${event.topic} ${event.fields.kind} ${event.fields.caller}`;
|
||||
signals[key] = (signals[key] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
const perSecond = Object.fromEntries(Object.entries(checks).map(([queue, byReason]) => [queue, Object.fromEntries(
|
||||
Object.entries(byReason).map(([reason, count]) => [reason, Number((count / seconds).toFixed(2))]))]));
|
||||
const total = (queue: string) => Object.values(checks[queue] ?? {}).reduce((sum, count) => sum + count, 0);
|
||||
return { checks, perSecond, signals, scoped, stranded: total("stranded-assignments"), assigned: total("assigned-work-invariant") };
|
||||
}
|
||||
|
||||
async function provider(companyId: string, workerIds: string[]) {
|
||||
const failures: unknown[] = [];
|
||||
const listener = createServer(async (request, response) => {
|
||||
try {
|
||||
let body = "";
|
||||
for await (const chunk of request) body += chunk;
|
||||
const { runId } = JSON.parse(body) as { runId: string };
|
||||
const [run] = await state.db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.id, runId), eq(heartbeatRuns.companyId, companyId)));
|
||||
if (!run!.contextSnapshot?.issueId) { response.end("ok"); return; }
|
||||
const issueId = String(run!.contextSnapshot?.issueId);
|
||||
const deadlocked = (error: unknown): boolean => typeof error === "object" && error !== null
|
||||
&& ((error as { code?: string }).code === "40P01" || deadlocked((error as { cause?: unknown }).cause));
|
||||
const retryDeadlock = async (write: () => Promise<unknown>) => {
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
try { return await write(); } catch (error) { if (attempt >= 3 || !deadlocked(error)) throw error; }
|
||||
}
|
||||
};
|
||||
await retryDeadlock(() => issueService(state.db).addComment(issueId, "Progress: done with this step", { agentId: run!.agentId, runId }));
|
||||
await retryDeadlock(() => issueService(state.db).update(issueId, { status: "in_review" }));
|
||||
response.end("ok");
|
||||
} catch (error) { failures.push(error); response.statusCode = 500; response.end("failed"); }
|
||||
});
|
||||
await new Promise<void>(resolve => listener.listen(0, "127.0.0.1", resolve));
|
||||
const port = (listener.address() as { port: number }).port;
|
||||
const script = `fetch("http://127.0.0.1:${port}/progress",{method:"POST",body:JSON.stringify({runId:process.env.PAPERCLIP_RUN_ID})}).then(r=>{if(!r.ok)process.exitCode=1;console.log("ok")})`;
|
||||
await state.db.update(agents).set({ adapterConfig: { command: process.execPath, args: ["-e", script], cwd: process.cwd() } })
|
||||
.where(inArray(agents.id, workerIds));
|
||||
return { failures, close: async () => { listener.closeAllConnections(); await new Promise<void>(resolve => listener.close(() => resolve())); } };
|
||||
}
|
||||
|
||||
async function measure(runsPerMinute: number, minutes: number, timerRunsPerMinute = 0) {
|
||||
const f = await state.fixture();
|
||||
const population = await seedRecoveryPopulation(state.db, f.companyId, { agents: 50, inReview: 780, inProgress: 40, todo: 30,
|
||||
recoveryActions: 12, terminated: 3 });
|
||||
const workers = population.agentIds.slice(7, 7 + 41);
|
||||
const fake = await provider(f.companyId, workers);
|
||||
const events = record();
|
||||
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
|
||||
await state.start({});
|
||||
await advance(10 * MINUTE);
|
||||
events.length = 0;
|
||||
const counts = async () => {
|
||||
const [runs] = await state.db.select({ finished: sql<number>`count(*) filter (where ${heartbeatRuns.status} = 'succeeded')::int`,
|
||||
failed: sql<number>`count(*) filter (where ${heartbeatRuns.status} = 'failed')::int`, all: sql<number>`count(*)::int` })
|
||||
.from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, f.companyId), eq(heartbeatRuns.runtimeMode, "legacy")));
|
||||
const [events] = await state.db.select({ n: sql<number>`count(*)::int` }).from(heartbeatRunEvents)
|
||||
.where(eq(heartbeatRunEvents.companyId, f.companyId));
|
||||
const [comments] = await state.db.select({ n: sql<number>`count(*)::int` }).from(issueComments)
|
||||
.where(and(eq(issueComments.companyId, f.companyId), sql`${issueComments.authorAgentId} is not null`));
|
||||
return { ...runs!, events: events!.n, agentComments: comments!.n };
|
||||
};
|
||||
const workBefore = await counts();
|
||||
const before = state.meter.read();
|
||||
const startedAt = Date.now();
|
||||
const byCheck: Record<string, number> = {}, settingsCallers: Record<string, number> = {};
|
||||
const tally = (log: ReturnType<typeof state.meter.stopLog>) => {
|
||||
for (const entry of log) {
|
||||
const stack = entry.stack ?? "";
|
||||
const owner = stack.includes("reconcileStrandedAssignedIssues") ? "stranded-assignments"
|
||||
: /assigned-work-sweep|checkIssue/.test(stack) ? "assigned-work-invariant"
|
||||
: stack.includes("sweepStaleIssueLocks") ? "stale-issue-locks" : stack.includes("recovery/work.ts") ? "recovery-loads" : "other";
|
||||
byCheck[owner] = (byCheck[owner] ?? 0) + 1;
|
||||
if (/from "instance_settings"/.test(entry.sql)) {
|
||||
const frame = stack.split("\n").map(line => line.trim()).find(line => /server\/src\/services\//.test(line) && !/instance-settings/.test(line)) ?? "unknown";
|
||||
const key = `${owner} ${frame.replace(/^at (async )?/, "").replace(/\(?\/.*\/server\/src\//, "(").replace(/:\d+\)?$/, ")")}`;
|
||||
settingsCallers[key] = (settingsCallers[key] ?? 0) + 1;
|
||||
}
|
||||
}
|
||||
};
|
||||
if (measuring) state.meter.startLog({ stacks: true });
|
||||
let next = 12;
|
||||
for (let minute = 0; minute < minutes; minute++) {
|
||||
const minuteEnds = startedAt + (minute + 1) * MINUTE;
|
||||
for (let started = 0; started < runsPerMinute; started++) {
|
||||
const issueId = population.inReview[next++ % population.inReview.length]!;
|
||||
const comment = await issueService(state.db).addComment(issueId, "Please take another pass", { userId: "recovery-user" });
|
||||
const [task] = await state.db.select({ assigneeAgentId: issues.assigneeAgentId }).from(issues).where(eq(issues.id, issueId));
|
||||
await state.heartbeat.wakeup(task!.assigneeAgentId!, { source: "automation", triggerDetail: "system", reason: "issue_commented",
|
||||
payload: { issueId, commentId: comment.id, mutation: "comment" }, requestedByActorType: "user", requestedByActorId: "recovery-user",
|
||||
contextSnapshot: { issueId, taskId: issueId, commentId: comment.id, wakeCommentId: comment.id, source: "issue.comment",
|
||||
wakeReason: "issue_commented" } });
|
||||
await vi.advanceTimersByTimeAsync(Math.floor(MINUTE / runsPerMinute / 4));
|
||||
}
|
||||
for (let timer = 0; timer < timerRunsPerMinute; timer++) {
|
||||
await state.heartbeat.wakeup(workers[(minute * timerRunsPerMinute + timer) % workers.length]!, { source: "on_demand", triggerDetail: "manual",
|
||||
reason: "manual", requestedByActorType: "user", requestedByActorId: "recovery-user",
|
||||
contextSnapshot: { source: "scheduler", reason: "interval_elapsed", now: new Date().toISOString() } });
|
||||
}
|
||||
await advance(minuteEnds - Date.now());
|
||||
await state.heartbeat.drainActiveRunExecutions();
|
||||
if (measuring) tally(state.meter.stopLog());
|
||||
if (measuring) state.meter.startLog({ stacks: true });
|
||||
}
|
||||
const seconds = (Date.now() - startedAt) / 1000;
|
||||
const after = state.meter.read();
|
||||
if (measuring) tally(state.meter.stopLog());
|
||||
const workAfter = await counts();
|
||||
const work = { started: workAfter.all - workBefore.all, finished: workAfter.finished - workBefore.finished,
|
||||
failed: workAfter.failed - workBefore.failed, events: workAfter.events - workBefore.events,
|
||||
agentComments: workAfter.agentComments - workBefore.agentComments };
|
||||
const summary = { ...summarize(events, seconds), seconds, work,
|
||||
statementsPerSecond: Number(((after.statements - before.statements) / seconds).toFixed(1)),
|
||||
agentWriteFailures: fake.failures.length,
|
||||
statementsPerSecondBy: Object.fromEntries(Object.entries(byCheck).map(([owner, count]) => [owner, Number((count / seconds).toFixed(1))])),
|
||||
instanceSettingsReads: settingsCallers };
|
||||
await fake.close();
|
||||
return summary;
|
||||
}
|
||||
|
||||
function expectWorkload(summary: Awaited<ReturnType<typeof measure>>, taskRuns: number, tasklessRuns: number) {
|
||||
expect(summary.agentWriteFailures).toBe(0);
|
||||
expect(summary.work.started).toBeGreaterThanOrEqual(taskRuns + tasklessRuns);
|
||||
expect(summary.work.finished).toBeGreaterThanOrEqual(taskRuns + tasklessRuns);
|
||||
expect(summary.work.failed).toBeLessThanOrEqual(Math.ceil(0.1 * summary.work.started));
|
||||
expect(summary.work.agentComments).toBeGreaterThanOrEqual(taskRuns);
|
||||
expect(summary.work.events).toBeGreaterThan(summary.work.finished);
|
||||
}
|
||||
|
||||
it("re-checks only the tasks seven runs a minute touch, among 850 open tasks", async () => {
|
||||
const minutes = measuring ? 10 : 4;
|
||||
const summary = await measure(7, minutes, 1);
|
||||
report("7 runs/min", summary);
|
||||
expectWorkload(summary, 7 * minutes, minutes);
|
||||
expect(summary.checks["stranded-assignments"]?.company ?? 0).toBe(0);
|
||||
expect(summary.signals).toEqual({});
|
||||
expect(summary.stranded / summary.seconds).toBeLessThan(2);
|
||||
}, 1_800_000);
|
||||
|
||||
it.runIf(measuring)("re-checks only the tasks fifty runs a minute touch, among 850 open tasks", async () => {
|
||||
const summary = await measure(50, 6, 5);
|
||||
report("50 runs/min", summary);
|
||||
expectWorkload(summary, 300, 30);
|
||||
expect(summary.checks["stranded-assignments"]?.company ?? 0).toBe(0);
|
||||
expect(summary.signals).toEqual({});
|
||||
expect(summary.stranded / summary.seconds).toBeLessThan(3);
|
||||
}, 1_800_000);
|
||||
});
|
||||
@@ -8,12 +8,15 @@ import { heartbeatService } from "../services/heartbeat.js";
|
||||
import { issueService } from "../services/issues.js";
|
||||
import { issueRecoveryActionService } from "../services/issue-recovery-actions.js";
|
||||
import { registerIssueRecoveryWork } from "../services/recovery/work.js";
|
||||
import { changedTaskCondition } from "../services/recovery/changed-tasks.js";
|
||||
import { recoveryService } from "../services/recovery/service.js";
|
||||
import { ISSUE_RECOVERY_BACKSTOP_MS, ISSUE_RECOVERY_MAX_ISSUE_IDS, notifyIssueRecovery, resolveIssueGraph }
|
||||
from "../services/issue-recovery-notifications.js";
|
||||
import { notifyNativeStatusReassessment } from "../services/native-status-reassessment-notifications.js";
|
||||
import { notifyExecutionRunWork } from "../services/execution-control-notifications.js";
|
||||
import { notifyRunDispatch } from "../services/run-dispatch-notifications.js";
|
||||
import { notifyExternalConversationSettlement } from "../services/external-conversation-settlement-notifications.js";
|
||||
import { notifyChatInboundWakeNotices } from "../services/chat-inbound-wake-notice-notifications.js";
|
||||
import { promoteDeferredWorkIntents } from "../services/work-intent-outbox.js";
|
||||
import { taskWatchdogService } from "../services/task-watchdogs.js";
|
||||
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
|
||||
@@ -246,6 +249,68 @@ describeIssueRecovery("issue recovery production producers and deadlines", () =>
|
||||
await graph.backlog(4000);
|
||||
expect(await lifecycleEvent(finished())).toBe(first);
|
||||
});
|
||||
it("re-checks a run's own tasks for its settlement, lease and dispatch writers, and nothing for a run without a task", async () => {
|
||||
const f = await fixture();
|
||||
const graph = await runGraph(f.companyId, f.agentId);
|
||||
await graph.backlog(300);
|
||||
const [taskless] = await state.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "succeeded",
|
||||
finishedAt: new Date(), contextSnapshot: { source: "scheduler" } }).returning({ id: heartbeatRuns.id });
|
||||
const checked: string[] = [];
|
||||
const assigned: string[] = [];
|
||||
await recordedRecovery({
|
||||
stranded: async scope => { checked.push(scope.issueId); },
|
||||
assignedWork: {
|
||||
listSuspects: (scope, cursor, limit) => recoveryService(state.db, { enqueueWakeup: async () => null })
|
||||
.assignedWork.listSuspects(scope, cursor, limit),
|
||||
checkIssue: async scope => { assigned.push(scope.issueId); },
|
||||
},
|
||||
}, { backstopMs: 60 * 60_000 });
|
||||
await settleWork({ backstopPending: true });
|
||||
const writers = (runId: string): Array<(tx: object) => Promise<unknown>> => [
|
||||
tx => notifyRunDispatch(tx, { companyId: f.companyId, runId }),
|
||||
tx => notifyExecutionRunWork(tx, { companyId: f.companyId, runId }),
|
||||
tx => notifyExternalConversationSettlement(tx, { companyId: f.companyId, runId }),
|
||||
tx => notifyChatInboundWakeNotices(tx, { companyId: f.companyId, runId }),
|
||||
tx => promoteDeferredWorkIntents(tx, { companyId: f.companyId, trigger: "lock_released", issueId: null, runId }),
|
||||
];
|
||||
for (const [runId, expected] of [[graph.runId, graph.affected], [taskless.id, []]] as Array<[string, string[]]>) {
|
||||
for (const writer of writers(runId)) {
|
||||
checked.length = 0; assigned.length = 0;
|
||||
await state.db.transaction(tx => writer(tx));
|
||||
await settleWork({ backstopPending: true });
|
||||
expect([...new Set(checked)].sort()).toEqual(expected);
|
||||
expect(assigned.every(id => expected.includes(id))).toBe(true);
|
||||
await vi.advanceTimersByTimeAsync(31_000);
|
||||
}
|
||||
}
|
||||
checked.length = 0; assigned.length = 0;
|
||||
await issueService(state.db).addComment(graph.siblingId, "A note on the next task", { userId: "recovery-user" });
|
||||
await settleWork({ backstopPending: true });
|
||||
expect(checked).toEqual([graph.siblingId]);
|
||||
expect(assigned.every(id => id === graph.siblingId)).toBe(true);
|
||||
});
|
||||
it("counts an agent's own run heartbeat as no change to its other tasks, and a resume as a change", async () => {
|
||||
const f = await fixture();
|
||||
const old = new Date(Date.now() - 60 * 60_000);
|
||||
const tasks = await state.db.insert(issues).values(Array.from({ length: 5 }, (_, index) => ({ companyId: f.companyId,
|
||||
title: `Waiting ${index}`, status: "todo", assigneeAgentId: f.agentId, createdAt: old, updatedAt: old }))).returning({ id: issues.id });
|
||||
const since = new Date(Date.now() - 5 * 60_000);
|
||||
const changed = async () => (await state.db.select({ id: issues.id }).from(issues)
|
||||
.where(and(eq(issues.companyId, f.companyId), changedTaskCondition(since)))).map(row => row.id).sort();
|
||||
const heartbeatAt = new Date();
|
||||
await state.db.update(agents).set({ status: "idle", lastHeartbeatAt: heartbeatAt, updatedAt: heartbeatAt }).where(eq(agents.id, f.agentId));
|
||||
expect(await changed()).toEqual([]);
|
||||
await state.db.update(agents).set({ status: "idle", updatedAt: new Date(heartbeatAt.getTime() + 1000) }).where(eq(agents.id, f.agentId));
|
||||
expect(await changed()).toEqual(tasks.map(row => row.id).sort());
|
||||
});
|
||||
it("resolves a run without a task to no tasks and a missing task to the whole company", async () => {
|
||||
const f = await fixture();
|
||||
const [taskless] = await state.db.insert(heartbeatRuns).values({ companyId: f.companyId, agentId: f.agentId, status: "running",
|
||||
contextSnapshot: { source: "scheduler" } }).returning({ id: heartbeatRuns.id });
|
||||
expect(await resolveIssueGraph(state.db, { companyId: f.companyId, runId: taskless.id })).toEqual([]);
|
||||
expect(await resolveIssueGraph(state.db, { companyId: f.companyId, runId: randomUUID() })).toEqual([]);
|
||||
expect(await resolveIssueGraph(state.db, { companyId: f.companyId, issueId: randomUUID() })).toBeNull();
|
||||
});
|
||||
it("resolves a run's task graph through index lookups, not the backlog", async () => {
|
||||
const f = await fixture();
|
||||
const graph = await runGraph(f.companyId, f.agentId);
|
||||
|
||||
@@ -2,7 +2,8 @@ import { notifyExternalConversationSettlement } from "./external-conversation-se
|
||||
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
|
||||
import type { InboundWakeNoticeScope } from "./chat-channels/inbound/wakeup-notices.js";
|
||||
|
||||
export async function notifyChatInboundWakeNotices(tx: object, scope: InboundWakeNoticeScope, options: { notifySettlement?: boolean } = {}) {
|
||||
export async function notifyChatInboundWakeNotices(tx: object, scope: InboundWakeNoticeScope & { runId?: string },
|
||||
options: { notifySettlement?: boolean } = {}) {
|
||||
if (options.notifySettlement !== false) await notifyExternalConversationSettlement(tx, scope);
|
||||
const hint = JSON.stringify({ companyId: scope.companyId, issueId: scope.issueId });
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.chatInboundWakeNotices, hint);
|
||||
|
||||
@@ -1778,7 +1778,7 @@ export function environmentService(db: Db) {
|
||||
(options?.cleanupStatus !== undefined && previous.cleanupStatus !== options.cleanupStatus) ||
|
||||
(status !== "retained" && !previous.releasedAt))) {
|
||||
await notifyChatInboundWakeNotices(tx, {
|
||||
companyId: previous.companyId, issueId: previous.issueId ?? undefined,
|
||||
companyId: previous.companyId, issueId: previous.issueId ?? undefined, runId: previous.heartbeatRunId,
|
||||
});
|
||||
}
|
||||
if (previous.heartbeatRunId && ["active", "pending_cleanup"].includes(previous.status)
|
||||
@@ -1789,7 +1789,8 @@ export function environmentService(db: Db) {
|
||||
// Messages saved behind a finished run wait for its cleanup to
|
||||
// settle. Reconsider them through normal deferred admission.
|
||||
await notifyDeferredExecutionWork(tx, { companyId: previous.companyId });
|
||||
await promoteDeferredWorkIntents(tx, { companyId: previous.companyId, trigger: "lock_released", issueId: previous.issueId });
|
||||
await promoteDeferredWorkIntents(tx, { companyId: previous.companyId, trigger: "lock_released", issueId: previous.issueId,
|
||||
runId: previous.heartbeatRunId });
|
||||
}
|
||||
if (previous.creationOperationId && previous.status === "pending_cleanup" && options?.cleanupStatus === "success" && status !== "pending_cleanup") {
|
||||
await tx.update(sandboxCreationOperations).set({ state: "resolved", updatedAt: now })
|
||||
@@ -1932,7 +1933,7 @@ export function environmentService(db: Db) {
|
||||
await notifyRetainedNativeSessionCleanup(tx, { companyId: run.companyId, runId: heartbeatRunId });
|
||||
await notifyDeferredExecutionWork(tx, { companyId: run.companyId });
|
||||
await promoteDeferredWorkIntents(tx, { companyId: run.companyId, trigger: "lock_released",
|
||||
issueId: run.issueId && /^[0-9a-f-]{36}$/i.test(run.issueId) ? run.issueId : null });
|
||||
issueId: run.issueId && /^[0-9a-f-]{36}$/i.test(run.issueId) ? run.issueId : null, runId: heartbeatRunId });
|
||||
}
|
||||
return tx.update(environmentLeases)
|
||||
.set({
|
||||
|
||||
@@ -267,7 +267,7 @@ export async function reconcileAbandonedExecutionControl(
|
||||
await notifyNativeEnvironmentSettlement(tx, { companyId: run.companyId, runId: run.id });
|
||||
await notifyCancelledWorkspacePreservation(tx, { companyId: run.companyId, runId: run.id });
|
||||
await notifyUnsafeWorkspaceExportRunChange(tx, run);
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id });
|
||||
const [updatedRun] = await tx
|
||||
.update(heartbeatRuns)
|
||||
.set({
|
||||
|
||||
@@ -827,7 +827,7 @@ export async function settleUnrecoverableExecutions(
|
||||
companyId: run.companyId, issueId: task.id, runId: run.id,
|
||||
}).limit(1).for("update") : [];
|
||||
if (!hold) return void await continueNativeInterruption(tx as unknown as Db, { action, run, coordinator, now });
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id });
|
||||
const note = "Exact session recovery stopped. The recorded workspace recovery holds this execution without replaying its actions.";
|
||||
await tx.update(issueRecoveryActions).set({ status: "cancelled", outcome: "cancelled",
|
||||
resolvedAt: now, updatedAt: now, wakePolicy: null, monitorPolicy: null,
|
||||
@@ -962,7 +962,7 @@ export async function settleUnrecoverableExecutions(
|
||||
replay: "not_authorized",
|
||||
},
|
||||
});
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id });
|
||||
await tx
|
||||
.update(heartbeatRuns)
|
||||
.set({ executionStatusDeliveryId: randomUUID() })
|
||||
|
||||
@@ -10,7 +10,7 @@ import { refreshRunStartYieldIfStale } from "../run-start-handover.js";
|
||||
import { deliveredQueuedCommentIds } from "../queued-comment-delivery.js";
|
||||
import { hasAutomaticInteractionDeliveryHold, INTERACTION_DELIVERY_DENIED, recheckQueuedRunInteractions, withInteractionDeliveryOrigin } from "../agent-interaction-delivery.js";
|
||||
import { deferredWorkIntentWait } from "../work-intent-outbox.js";
|
||||
import { notifyIssueRecovery } from "../issue-recovery-notifications.js";
|
||||
import { notifyIssueGraphRecovery } from "../issue-recovery-notifications.js";
|
||||
import { createHeartbeatTimerPolicy } from "./timer-policy.js";
|
||||
import { QUEUED_RUN_AGING_MS, RECOVERY_WAKE_REASONS, createQueuedRunDispatcher, hasQueuedRunAged, queuedRunDispatchClass } from "./queued-run-dispatch-order.js";
|
||||
import { reserveAutomaticRunStart } from "../recovery/automatic-run-brake.js";
|
||||
@@ -587,7 +587,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
const receipts = await tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests).where(owned).for("update");
|
||||
if (!receipts.length) return;
|
||||
// Register the recovery signal before the write it announces.
|
||||
await notifyIssueRecovery(tx, { companyId: run.companyId });
|
||||
await notifyIssueGraphRecovery(tx, { companyId: run.companyId, runId: run.id });
|
||||
await tx.update(agentWakeupRequests).set({
|
||||
idempotencyKey: null,
|
||||
payload: sql`coalesce(${agentWakeupRequests.payload}, '{}'::jsonb)
|
||||
@@ -5392,8 +5392,10 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
return mergedRun;
|
||||
}
|
||||
|
||||
const queuedRunId = randomUUID();
|
||||
const queueOutcome = await db.transaction(async (tx) => {
|
||||
await notifyRunDispatch(tx, { companyId: agent.companyId, issueId: readNonEmptyString(enrichedContextSnapshot.issueId) });
|
||||
await notifyRunDispatch(tx, { companyId: agent.companyId, issueId: readNonEmptyString(enrichedContextSnapshot.issueId),
|
||||
runId: readNonEmptyString(enrichedContextSnapshot.issueId) ? undefined : queuedRunId });
|
||||
await tx.execute(
|
||||
sql`select id from agents where id = ${agentId} and company_id = ${agent.companyId} for update`,
|
||||
);
|
||||
@@ -5463,6 +5465,7 @@ export function createHeartbeatQueue(db: Db, dependencies: HeartbeatQueueDepende
|
||||
const newRun = await tx
|
||||
.insert(heartbeatRuns)
|
||||
.values({
|
||||
id: queuedRunId,
|
||||
companyId: agent.companyId,
|
||||
agentId,
|
||||
scopeKind: readNonEmptyString(enrichedContextSnapshot.issueId) ? "issue" : "company",
|
||||
|
||||
@@ -20,11 +20,8 @@ const TASK_QUEUES: DeliveryQueue[] = [DELIVERY_QUEUES.strandedAssignments, DELIV
|
||||
export async function notifyIssueRecovery(transaction: object, scope?: IssueRecoveryScope) {
|
||||
const companyHint = scope ? JSON.stringify({ companyId: scope.companyId }) : "*";
|
||||
const issueHint = scope ? JSON.stringify({ companyId: scope.companyId, issueId: scope.issueId }) : "*";
|
||||
for (const queue of [DELIVERY_QUEUES.orphanBlockers, DELIVERY_QUEUES.activeRecoveryActions, DELIVERY_QUEUES.strandedAssignments, DELIVERY_QUEUES.assignedWorkInvariant, DELIVERY_QUEUES.resolvedDependencies,
|
||||
DELIVERY_QUEUES.taskWatchdogs, DELIVERY_QUEUES.staleIssueLocks]) {
|
||||
await notifyDeliveryWork(transaction, queue,
|
||||
queue === DELIVERY_QUEUES.strandedAssignments || queue === DELIVERY_QUEUES.staleIssueLocks ? issueHint : companyHint);
|
||||
}
|
||||
for (const queue of COMPANY_QUEUES) await notifyDeliveryWork(transaction, queue, companyHint);
|
||||
for (const queue of TASK_QUEUES) await notifyDeliveryWork(transaction, queue, issueHint);
|
||||
}
|
||||
|
||||
export function issueRecoveryBackstopHint(companyId: string) {
|
||||
@@ -71,5 +68,6 @@ export async function resolveIssueGraph(db: Db, scope: { companyId: string; runI
|
||||
and issue_id in (select id from seed) limit ${ISSUE_RECOVERY_MAX_ISSUE_IDS + 1})
|
||||
) select id::text as id from affected limit ${ISSUE_RECOVERY_MAX_ISSUE_IDS + 1}`);
|
||||
const issueIds = rows.map(row => row.id).sort();
|
||||
return issueIds.length && issueIds.length <= ISSUE_RECOVERY_MAX_ISSUE_IDS ? issueIds : null;
|
||||
if (issueIds.length === 0) return scope.issueId ? null : [];
|
||||
return issueIds.length <= ISSUE_RECOVERY_MAX_ISSUE_IDS ? issueIds : null;
|
||||
}
|
||||
@@ -8,14 +8,15 @@ import { createHash, randomUUID } from "node:crypto";
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { agentTaskSessions, agents, companies, controllerInstances, createDb, environmentLeases, environments, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults, nativeRunnerCheckpoints } from "@paperclipai/db";
|
||||
import { DurablePrpControlPlane, parseNativeExecutionInput, type PersistedNativeSession } from "../../vendor/paperclip-runner/index.js";
|
||||
import { startRecoveryPostgres, recoveryPostgresSupport } from "../../__tests__/helpers/recovery-postgres.js";
|
||||
import { createIsolatedTestHome } from "../../__tests__/helpers/isolated-test-home.js";
|
||||
import { prepareNativeHeartbeatRun } from "./prepare-native-run.js";
|
||||
import { nativeRunnerCheckpointWriter } from "./native-runner-checkpoint.js";
|
||||
import { assertNativeRunnerCheckpointOwner, loadNativeRunnerCheckpoint, nativeRunnerCheckpointWriter } from "./native-runner-checkpoint.js";
|
||||
import { assertNativeHarnessBackupOwner, nativeHarnessBackupOwner } from "./native-harness-backup-storage.js";
|
||||
import { assertNativeRetainedSandboxBinding, createNativeControllerRecovery, deferNativeControllerRecovery, deferNativeRunForBusyAgentDirectory, NATIVE_AGENT_DIRECTORY_BUSY_WAIT, importNativeControllerRecovery, NativeControllerRecoveryWaitingError, NATIVE_RETAINED_OWNER_WAIT, resolveNativeControllerRecovery } from "./native-controller-recovery.js";
|
||||
import { claimNativeSessionResumptions } from "./native-finalization-reconciler.js";
|
||||
import { claimNativeRestartRecoveries, currentNativeControllerIdentity } from "./native-restart-recovery.js";
|
||||
@@ -27,6 +28,7 @@ import { inspectRemoteWarmSessionRecovery, waitForLiveWarmSessionOwner } from ".
|
||||
import { currentProcessSpaceHash } from "../controller-process-identity.js";
|
||||
import { registerControllerInstanceDb, resetControllerInstanceLeaseForTests } from "../controller-instance-lease.js";
|
||||
import { readProcessStartedAt } from "../hot-restart.js";
|
||||
import { PROCESS_START_REQUESTED } from "../native-process-start-events.js";
|
||||
|
||||
describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable discovery and import", () => {
|
||||
let database: Awaited<ReturnType<typeof startRecoveryPostgres>>;
|
||||
@@ -610,17 +612,20 @@ describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable d
|
||||
await new Promise(resolve => oldServer.once("spawn", resolve));
|
||||
const startedAt = await readProcessStartedAt(oldServer.pid!);
|
||||
expect(startedAt).toBeTruthy();
|
||||
const { inspect, recordOwner, runId, current } = await seedWarmFollowUpOnOldServer();
|
||||
await recordOwner({ controllerBootId: randomUUID(), controllerPid: oldServer.pid!, controllerHostHash: currentProcessSpaceHash(),
|
||||
const { inspect, recordOwner, runId, current, fixture } = await seedWarmFollowUpOnOldServer();
|
||||
const outgoingBoot = randomUUID();
|
||||
await recordOwner({ controllerBootId: outgoingBoot, controllerPid: oldServer.pid!, controllerHostHash: currentProcessSpaceHash(),
|
||||
controllerProcessStartedAt: new Date(startedAt!), leaseOwner: null, leaseExpiresAt: null });
|
||||
const before = Date.now();
|
||||
const waiting = await inspect().catch(error => error);
|
||||
expect(waiting).toBeInstanceOf(NativeControllerRecoveryWaitingError);
|
||||
expect(waiting.owner).toEqual({ runId: fixture.scope.runId, controllerBootId: outgoingBoot });
|
||||
expect(waiting.retryAt.getTime()).toBeGreaterThan(before);
|
||||
expect(waiting.retryAt.getTime()).toBeLessThanOrEqual(Date.now() + 10_000);
|
||||
await deferNativeControllerRecovery(db, { ...current.binding, retryAt: waiting.retryAt });
|
||||
await deferNativeControllerRecovery(db, { ...current.binding, retryAt: waiting.retryAt, waitingForOwner: waiting.owner });
|
||||
expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)))[0])
|
||||
.toMatchObject({ phase: "retryable_failure", attempt: 0, failureCode: NATIVE_RETAINED_OWNER_WAIT, resultId: null });
|
||||
.toMatchObject({ phase: "retryable_failure", attempt: 0, failureCode: NATIVE_RETAINED_OWNER_WAIT, resultId: null,
|
||||
failureDetail: expect.objectContaining({ waitingForOwner: { runId: fixture.scope.runId, controllerBootId: outgoingBoot } }) });
|
||||
const [task] = await db.select().from(issues).where(eq(issues.executionRunId, runId));
|
||||
expect(task?.status).toBe("in_progress");
|
||||
|
||||
@@ -685,6 +690,129 @@ describe.skipIf(!recoveryPostgresSupport.supported)("native controller durable d
|
||||
} finally { resetControllerInstanceLeaseForTests(); }
|
||||
});
|
||||
|
||||
async function parkFollowUpBehindOutgoingServer(waitingFor?: (owner: { runId: string; controllerBootId: string }) => { runId: string; controllerBootId: string }) {
|
||||
const seeded = await seedWarmFollowUpOnOldServer();
|
||||
const { fixture, current, identity, recordOwner, runId } = seeded;
|
||||
const outgoingBoot = fixture.owner.bootId;
|
||||
await recordOwner({ controllerBootId: outgoingBoot, controllerPid: 7, controllerHostHash: "outgoing-container",
|
||||
controllerProcessStartedAt: new Date(Date.now() - 600_000), leaseOwner: null, leaseExpiresAt: null });
|
||||
await db.insert(controllerInstances).values({ bootId: outgoingBoot, processSpace: "outgoing-container", pid: 7,
|
||||
leaseExpiresAt: new Date(Date.now() + 90_000) });
|
||||
await db.update(nativeRunFinalizations).set({ controllerBootId: randomUUID() }).where(eq(nativeRunFinalizations.runId, runId));
|
||||
const wait = (checkpointedAt: Date | null) => waitForLiveWarmSessionOwner({ db, execution: current,
|
||||
priorRunId: fixture.scope.runId, checkpointedAt: async () => checkpointedAt });
|
||||
const waiting = await wait(null).catch(error => error);
|
||||
expect(waiting).toBeInstanceOf(NativeControllerRecoveryWaitingError);
|
||||
expect(waiting.owner).toEqual({ runId: fixture.scope.runId, controllerBootId: outgoingBoot });
|
||||
const parkedAt = Date.now();
|
||||
await deferNativeControllerRecovery(db, { ...current.binding, retryAt: waiting.retryAt,
|
||||
waitingForOwner: waitingFor ? waitingFor(waiting.owner) : waiting.owner });
|
||||
const outgoingRoot = join(root, `${fixture.scope.runId}-outgoing`);
|
||||
(await loadNativeRunnerCheckpoint(db, { companyId, issueId: fixture.scope.issueId, runId: fixture.scope.runId }))!
|
||||
.restoreSessionDirectory(outgoingRoot);
|
||||
const outgoing = new DurablePrpControlPlane({ stateDirectory: join(outgoingRoot, "control-plane"), identity,
|
||||
expectedRunnerVersion: "discovery-fixture", expectedRunnerDigest: `sha256:${"a".repeat(64)}` });
|
||||
outgoing.setCheckpointPersistence(nativeRunnerCheckpointWriter(db, fixture.owner));
|
||||
const fenceHarnessBackup = async () => assertNativeHarnessBackupOwner(db, await nativeHarnessBackupOwner(db, {
|
||||
companyId, issueId: fixture.scope.issueId, runId: fixture.scope.runId, bootId: outgoingBoot }));
|
||||
const saveSuspend = async () => {
|
||||
outgoing.queueCommand("runner.suspend", {}, `idle-close-${randomUUID()}`);
|
||||
await outgoing.flushCheckpoint();
|
||||
};
|
||||
const closeIdleSession = async () => {
|
||||
await fenceHarnessBackup();
|
||||
await saveSuspend();
|
||||
return new Date();
|
||||
};
|
||||
return { ...seeded, wait, waiting: waiting as NativeControllerRecoveryWaitingError, parkedAt, outgoing,
|
||||
fenceHarnessBackup, saveSuspend, closeIdleSession };
|
||||
}
|
||||
|
||||
it("the outgoing server checkpoints and closes its idle warm session while the incoming server's follow-up waits for it, and the follow-up resumes within one recheck", async () => {
|
||||
registerControllerInstanceDb(db);
|
||||
const parked = await parkFollowUpBehindOutgoingServer();
|
||||
try {
|
||||
const { fixture, runId, wait, waiting, parkedAt, outgoing, closeIdleSession } = parked;
|
||||
expect((await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId)))[0])
|
||||
.toMatchObject({ phase: "retryable_failure", attempt: 0, leaseOwner: null, failureCode: NATIVE_RETAINED_OWNER_WAIT,
|
||||
failureDetail: expect.objectContaining({ waitingForOwner: waiting.owner }) });
|
||||
const [prior] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, fixture.scope.runId));
|
||||
const ownerExitDeadline = prior!.finishedAt!.getTime() + 600_000 + 120_000;
|
||||
|
||||
const checkpointedAt = await closeIdleSession();
|
||||
const saved = await loadNativeRunnerCheckpoint(db, { companyId, issueId: fixture.scope.issueId, runId: fixture.scope.runId });
|
||||
const restoredRoot = join(root, `${runId}-idle-close`);
|
||||
saved!.restoreSessionDirectory(restoredRoot);
|
||||
const restored = JSON.parse(await readFile(join(restoredRoot, "control-plane", "control-plane-state.json"), "utf8"));
|
||||
expect(restored.commands).toContainEqual(expect.objectContaining({ type: "runner.suspend" }));
|
||||
await outgoing.stop();
|
||||
|
||||
expect(await claimNativeSessionResumptions({ db, runnerInstanceId: "incoming", runIds: [runId] })).toEqual([]);
|
||||
const claims = await claimNativeSessionResumptions({ db, runnerInstanceId: "incoming", runIds: [runId], now: waiting.retryAt });
|
||||
expect(claims).toHaveLength(1);
|
||||
await expect(wait(checkpointedAt)).resolves.toBeUndefined();
|
||||
const waitedMs = Math.max(waiting.retryAt.getTime(), checkpointedAt.getTime()) - parkedAt;
|
||||
expect(waitedMs).toBeLessThanOrEqual(5_000);
|
||||
expect(ownerExitDeadline - parkedAt).toBeGreaterThan(600_000);
|
||||
} finally {
|
||||
await parked.outgoing.stop();
|
||||
resetControllerInstanceLeaseForTests();
|
||||
}
|
||||
});
|
||||
|
||||
it("holds a resumption claim of the parked follow-up until the outgoing server's save commits", async () => {
|
||||
registerControllerInstanceDb(db);
|
||||
const parked = await parkFollowUpBehindOutgoingServer();
|
||||
try {
|
||||
const { fixture, runId, waiting } = parked;
|
||||
let claim!: Promise<Awaited<ReturnType<typeof claimNativeSessionResumptions>>>;
|
||||
let claimSettled = false;
|
||||
await db.transaction(async tx => {
|
||||
await assertNativeRunnerCheckpointOwner(tx, fixture.owner, false);
|
||||
claim = claimNativeSessionResumptions({ db, runnerInstanceId: "incoming", runIds: [runId], now: waiting.retryAt });
|
||||
void claim.finally(() => { claimSettled = true; });
|
||||
await vi.waitFor(async () => {
|
||||
const [blocked] = await db.execute<{ count: number }>(sql`select count(*)::int as count from pg_stat_activity
|
||||
where datname = current_database() and wait_event_type = 'Lock' and query ilike '%native_run_finalizations%'`);
|
||||
expect(blocked.count).toBeGreaterThan(0);
|
||||
}, { timeout: 1_500, interval: 20 });
|
||||
expect(claimSettled).toBe(false);
|
||||
});
|
||||
expect(await claim).toHaveLength(1);
|
||||
await expect(parked.saveSuspend()).rejects.toThrow("native_runner_checkpoint_owner_lost");
|
||||
} finally {
|
||||
await parked.outgoing.stop();
|
||||
resetControllerInstanceLeaseForTests();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["own-process", "own-process-event", "own-checkpoint", "claimed", "other-owner-boot", "other-owner-run"] as const)(
|
||||
"refuses the outgoing server's idle checkpoint when the parked follow-up is no longer waiting on it: %s", async scenario => {
|
||||
registerControllerInstanceDb(db);
|
||||
const parked = await parkFollowUpBehindOutgoingServer(owner => scenario === "other-owner-boot"
|
||||
? { ...owner, controllerBootId: randomUUID() } : scenario === "other-owner-run" ? { ...owner, runId: randomUUID() } : owner);
|
||||
try {
|
||||
const { fixture, runId, waiting, fenceHarnessBackup, saveSuspend } = parked;
|
||||
if (scenario === "own-process") {
|
||||
await db.update(heartbeatRuns).set({ processPid: 4242, processGroupId: 4242, processStartedAt: new Date() }).where(eq(heartbeatRuns.id, runId));
|
||||
} else if (scenario === "own-process-event") {
|
||||
await db.insert(heartbeatRunEvents).values({ companyId, runId, agentId, seq: 1, eventType: PROCESS_START_REQUESTED });
|
||||
} else if (scenario === "own-checkpoint") {
|
||||
await db.insert(nativeRunnerCheckpoints).values({ companyId, issueId: fixture.scope.issueId, runId, part: "header", material: {} });
|
||||
} else if (scenario === "claimed") {
|
||||
expect(await claimNativeSessionResumptions({ db, runnerInstanceId: "incoming", runIds: [runId], now: waiting.retryAt })).toHaveLength(1);
|
||||
}
|
||||
const before = await loadNativeRunnerCheckpoint(db, { companyId, issueId: fixture.scope.issueId, runId: fixture.scope.runId });
|
||||
await expect(fenceHarnessBackup()).rejects.toThrow("native_runner_checkpoint_owner_lost");
|
||||
await expect(saveSuspend()).rejects.toThrow("native_runner_checkpoint_owner_lost");
|
||||
expect((await loadNativeRunnerCheckpoint(db, { companyId, issueId: fixture.scope.issueId, runId: fixture.scope.runId }))?.records)
|
||||
.toEqual(before?.records);
|
||||
} finally {
|
||||
await parked.outgoing.stop();
|
||||
resetControllerInstanceLeaseForTests();
|
||||
}
|
||||
});
|
||||
|
||||
it("sends a re-wake after a crash restart to a fresh sandbox when the parked predecessor's warm Runner cannot be adopted", async () => {
|
||||
const fixture = await seed(), runId = randomUUID(), environmentId = randomUUID(), leaseId = randomUUID();
|
||||
const previous = parseNativeExecutionInput({
|
||||
|
||||
@@ -70,8 +70,10 @@ export type NativeControllerRecoveryOutcome =
|
||||
|
||||
export const NATIVE_RETAINED_OWNER_WAIT = "native_controller_recovery_waiting_for_owner";
|
||||
|
||||
export type NativeRetainedOwnerWait = { runId: string; controllerBootId: string };
|
||||
|
||||
export class NativeControllerRecoveryWaitingError extends Error {
|
||||
constructor(readonly retryAt: Date) {
|
||||
constructor(readonly retryAt: Date, readonly owner?: NativeRetainedOwnerWait) {
|
||||
super(NATIVE_RETAINED_OWNER_WAIT);
|
||||
this.name = "NativeControllerRecoveryWaitingError";
|
||||
}
|
||||
@@ -83,7 +85,7 @@ export class NativeControllerRecoveryWaitingError extends Error {
|
||||
* permissions and task ownership when this deadline arrives. */
|
||||
export async function deferNativeControllerRecovery(db: Db, input: {
|
||||
companyId: string; agentId: string; issueId: string; runId: string;
|
||||
leaseOwner?: string; retryAt: Date;
|
||||
leaseOwner?: string; retryAt: Date; waitingForOwner?: NativeRetainedOwnerWait;
|
||||
}): Promise<void> {
|
||||
await db.transaction(async tx => {
|
||||
const [task] = await tx.select({ executionRunId: issues.executionRunId }).from(issues)
|
||||
@@ -128,7 +130,9 @@ export async function deferNativeControllerRecovery(db: Db, input: {
|
||||
failureDetail: { originalFailureCode: NATIVE_RETAINED_OWNER_WAIT,
|
||||
message: "Waiting for the retained native controller owner to release its lease.",
|
||||
recoveryMode: record(run.runnerProfileJson).sessionCheckpoint ? "same_session_resume" : "bootstrap_retry",
|
||||
providerSessionEstablished: false, providerEventsExist: false },
|
||||
providerSessionEstablished: false, providerEventsExist: false,
|
||||
...(input.waitingForOwner ? { waitingForOwner: { runId: input.waitingForOwner.runId,
|
||||
controllerBootId: input.waitingForOwner.controllerBootId } } : {}) },
|
||||
updatedAt: new Date(),
|
||||
}).where(eq(nativeRunFinalizations.runId, input.runId));
|
||||
});
|
||||
|
||||
@@ -161,7 +161,7 @@ export async function preserveNativeFailedWorkspace(db: Db, selected: Pick<typeo
|
||||
let retained = !retainFiles || alreadyRetained ? run : await recordRequiredWorkspaceRestoreFailure(tx as unknown as Db, run, { workspaceRestoreFailure: "restore_failed" }, source);
|
||||
if (!retained || retainFiles && !hasRequiredWorkspaceRecovery(retained.resultJson)) return;
|
||||
if (options.allowPreterminal && coordinator.phase === "observed") {
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id });
|
||||
const [settled] = await tx.update(nativeRunFinalizations).set({ phase: "terminal_failure",
|
||||
leaseOwner: null, leaseExpiresAt: null, controlDeadlineAt: null, nextAttemptAt: null,
|
||||
recoveryState: "blocked", failureCode: coordinator.failureCode ?? "native_continuation_requires_reconciliation", updatedAt: new Date(),
|
||||
|
||||
@@ -27,7 +27,7 @@ export async function settleFailedNativeRecoveryPreparation(db: Db, input: {
|
||||
if (run?.status !== "failed") return false;
|
||||
// Register the work before the writes it announces. A spare wake when no
|
||||
// coordinator matches below is harmless.
|
||||
await notifyExecutionRunWork(tx as unknown as Db, { companyId: input.companyId });
|
||||
await notifyExecutionRunWork(tx as unknown as Db, { companyId: input.companyId, runId: input.runId });
|
||||
const now = new Date();
|
||||
const [settled] = await tx.update(nativeRunFinalizations).set({
|
||||
phase: "terminal_failure", leaseOwner: null, leaseExpiresAt: null, nextAttemptAt: null, controlDeadlineAt: null,
|
||||
|
||||
@@ -1030,7 +1030,7 @@ async function endNamespaceUnverifiedRun(tx: Db, row: {
|
||||
run: typeof heartbeatRuns.$inferSelect; coordinator: typeof nativeRunFinalizations.$inferSelect;
|
||||
issueAssigneeAgentId: string | null; issueStatus: string;
|
||||
}, now: Date, reason: string, event: ReturnType<typeof historyEntry>, recoveryRequestId: string | null) {
|
||||
await notifyExecutionRunWork(tx, { companyId: row.run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: row.run.companyId, runId: row.run.id });
|
||||
await tx.update(nativeRunFinalizations).set({ phase: "terminal_failure", leaseOwner: null, leaseExpiresAt: null,
|
||||
nextAttemptAt: null, failureCode: "native_restart_recovery_blocked",
|
||||
failureDetail: { ...row.coordinator.failureDetail, reason, executorStopEvidence: "unverified" },
|
||||
@@ -1932,7 +1932,7 @@ export async function claimNativeRestartRecoveries(input: {
|
||||
recycledProviderPids: providerProcesses.recycledPids,
|
||||
stderrTail: row.run.stderrExcerpt,
|
||||
});
|
||||
await notifyExecutionRunWork(tx, { companyId: row.run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: row.run.companyId, runId: row.run.id });
|
||||
await tx
|
||||
.update(nativeRunFinalizations)
|
||||
.set({
|
||||
|
||||
@@ -405,7 +405,7 @@ export async function endSupersededNativeFinalizationRuns(db: Db, runIds?: reado
|
||||
: accepted === "succeeded" ? "succeeded" as const : accepted === "cancelled" ? "cancelled" as const : "failed" as const;
|
||||
await notifyNativeFinalizationWork(tx, { companyId: run.companyId, runId: run.id });
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.accounting, run.companyId);
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id });
|
||||
await notifyChatRunMilestones(tx, { companyId: run.companyId, issueId: coordinator.issueId });
|
||||
await notifyInstructionCollection(tx, { companyId: run.companyId, runId: run.id });
|
||||
await notifyCancelledWorkspacePreservation(tx, { companyId: run.companyId, runId: run.id });
|
||||
@@ -626,7 +626,7 @@ async function recordRetryableFailure(input: {
|
||||
if (phase === "terminal_failure" && failureCode === "native_workspace_sync_out_unsafe_archive") {
|
||||
await notifyUnsafeWorkspaceExportRecovery(tx, { companyId: input.run.companyId, issueId: input.coordinator.issueId });
|
||||
}
|
||||
await notifyExecutionRunWork(tx, { companyId: input.run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: input.run.companyId, runId: input.run.id });
|
||||
await notifyChatRunMilestones(tx, { companyId: input.run.companyId, issueId: input.coordinator.issueId });
|
||||
await tx
|
||||
.update(nativeRunFinalizations)
|
||||
@@ -2077,7 +2077,7 @@ export async function finalizeNativeRun(input: {
|
||||
if (input.projectRunStatus) await notifyCancelledWorkspacePreservation(tx, { companyId: run.companyId, runId: run.id });
|
||||
if (input.projectRunStatus) await notifyUnsafeWorkspaceExportRunChange(tx, run);
|
||||
if (input.projectRunStatus) await notifyDeliveryWork(tx, DELIVERY_QUEUES.accounting, run.companyId);
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id });
|
||||
await notifyChatRunMilestones(tx, { companyId: run.companyId, issueId: coordinator.issueId });
|
||||
const [after] = await projectRun(tx);
|
||||
if (after && input.projectRunStatus) await settleNativeTerminalWake(tx, after);
|
||||
|
||||
@@ -51,7 +51,7 @@ export async function settleNativeTerminalWake(tx: Db, run: Pick<typeof heartbea
|
||||
const [current] = await tx.select({ id: agentWakeupRequests.id }).from(agentWakeupRequests)
|
||||
.where(claim).for("update").limit(1);
|
||||
if (!current) return;
|
||||
await notifyExternalConversationSettlement(tx, { companyId: run.companyId });
|
||||
await notifyExternalConversationSettlement(tx, { companyId: run.companyId, runId: run.id });
|
||||
await notifyStrandedAgentStatus(tx, { companyId: run.companyId, agentId: run.agentId });
|
||||
await tx.update(agentWakeupRequests).set({
|
||||
status: run.status === "succeeded" ? "completed" : run.status,
|
||||
@@ -174,7 +174,7 @@ export async function projectCommittedRun(input: {
|
||||
await notifyCancelledWorkspacePreservation(tx, { companyId: input.run.companyId, runId: input.run.id });
|
||||
await notifyUnsafeWorkspaceExportRunChange(tx, input.run);
|
||||
await notifyDeliveryWork(tx, DELIVERY_QUEUES.accounting, input.run.companyId);
|
||||
await notifyExecutionRunWork(tx, { companyId: input.run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: input.run.companyId, runId: input.run.id });
|
||||
await notifyChatRunMilestones(tx, { companyId: input.run.companyId, issueId: input.coordinator.issueId });
|
||||
const [after] = await tx
|
||||
.update(heartbeatRuns)
|
||||
|
||||
@@ -69,6 +69,18 @@ function createRecordingTraceContext(): {
|
||||
}
|
||||
|
||||
describe("native runner performance trace", () => {
|
||||
it("records the named check of a failed measurement on its run event", async () => {
|
||||
const {traceContext}=createRecordingTraceContext();
|
||||
const events: Array<Record<string, unknown>> = [];
|
||||
const trace=createNativeRunTrace({runId:"provider-pack-check",startedAtMs:1000,traceContext,
|
||||
onEvent:async event=>{events.push(event.payload as Record<string, unknown>);}});
|
||||
const rejected=Object.assign(new Error("runner_remote_provider_artifact_incompatible: incompatible"),{failureCheck:"contract_digest"});
|
||||
await expect(trace.measure("provider_pack.compatibility",async()=>{throw rejected;},{attributes:{target:"image"}})).rejects.toBe(rejected);
|
||||
await expect(trace.measure("provider_pack.verify",async()=>{throw Object.assign(new Error("x"),{failureCheck:"has space"});})).rejects.toThrow("x");
|
||||
await trace.finish("ok");
|
||||
expect(events.find(event=>event.span==="provider_pack.compatibility")).toMatchObject({outcome:"failed",target:"image",check:"contract_digest"});
|
||||
expect(events.find(event=>event.span==="provider_pack.verify")).not.toHaveProperty("check");
|
||||
});
|
||||
it("projects a full durable diagnostic batch without waiting on duplicate run-log writes", async () => {
|
||||
const {traceContext, spans}=createRecordingTraceContext();
|
||||
let release!: () => void;
|
||||
|
||||
@@ -210,6 +210,7 @@ const SAFE_NATIVE_RUN_SPAN_ATTRIBUTE_KEYS = new Set([
|
||||
"adapter",
|
||||
"anchor",
|
||||
"bytesTransferred",
|
||||
"check",
|
||||
"inputBytes", "toolSchemaBytes", "toolCount", "contextReused", "tokenDataAvailable",
|
||||
"connectionOwner",
|
||||
"driver",
|
||||
@@ -229,6 +230,11 @@ const SAFE_NATIVE_RUN_SPAN_ATTRIBUTE_KEYS = new Set([
|
||||
"target",
|
||||
]);
|
||||
|
||||
export function nativeRunFailureCheck(error: unknown): string | undefined {
|
||||
const check = (error as { failureCheck?: unknown } | null)?.failureCheck;
|
||||
return typeof check === "string" && /^[A-Za-z0-9_.:,@/-]{1,120}$/.test(check) ? check : undefined;
|
||||
}
|
||||
|
||||
function finiteMs(value: number): number {
|
||||
return Number.isFinite(value) ? Math.max(0, value) : 0;
|
||||
}
|
||||
@@ -630,6 +636,8 @@ export function createNativeRunTrace(input: {
|
||||
return await run(scope, fn);
|
||||
} catch (error) {
|
||||
outcome = "failed";
|
||||
const check = nativeRunFailureCheck(error);
|
||||
if (check) annotate(scope, { check });
|
||||
throw error;
|
||||
} finally {
|
||||
await end(scope, { outcome });
|
||||
|
||||
@@ -3,12 +3,14 @@ import { NATIVE_PREPARATION_FENCING_VERSION } from "./native-active-runs.js";
|
||||
import { notifyLiveRunRecovery } from "../live-run-recovery-notifications.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import { and, eq, exists, gt, isNull, lte, inArray, notExists, or, sql, type SQL } from "drizzle-orm";
|
||||
import { checkpointDb, heartbeatRuns, issues, nativeRunFinalizations, nativeRunnerCheckpoints, primeDatabaseWorkTransactionId, type Db } from "@paperclipai/db";
|
||||
import { checkpointDb, heartbeatRunEvents, heartbeatRuns, issues, nativeRunFinalizations, nativeRunnerCheckpoints, primeDatabaseWorkTransactionId, type Db } from "@paperclipai/db";
|
||||
import { inspectDurablePrpCheckpointHeader, inspectUnauthenticatedBootstrapCheckpoint, inspectUnclaimedBootstrapCheckpoint, decodeDurablePrpCheckpoint, type DurablePrpCheckpoint, type DurablePrpControlPlane, type DurableRecoveryIdentity } from "../../vendor/paperclip-runner/index.js";
|
||||
import { createLocalEncryptedCipher, deriveLocalEncryptedInstanceSecret } from "../../secrets/local-encrypted-provider.js";
|
||||
import { legacyControllerBootId } from "../legacy-controller-lease.js";
|
||||
import { assertNativeSourceCheckpointConsumer, lockSourceRecoveryCoordinators } from "./native-source-recovery-ownership.js";
|
||||
import { runnerdStateHasNoProviderTurn, runnerdStateIsIncompleteBootstrap } from "./native-bootstrap-proof.js";
|
||||
import { NATIVE_RETAINED_OWNER_WAIT } from "./native-controller-recovery.js";
|
||||
import { OWN_PROCESS_START_EVENT_TYPES } from "../native-process-start-events.js";
|
||||
|
||||
type Binding = { companyId: string; issueId: string; runId: string };
|
||||
export const NATIVE_CHECKPOINT_HEADER_INSPECTION_MAX_BYTES = 1024 * 1024;
|
||||
@@ -116,13 +118,37 @@ export async function validateNativeRunnerCheckpointOwner(
|
||||
eq(heartbeatRuns.issueId, owner.issueId), inArray(heartbeatRuns.status, ["queued", "scheduled_retry"]),
|
||||
notExists(tx.select({ runId: nativeRunFinalizations.runId }).from(nativeRunFinalizations)
|
||||
.where(eq(nativeRunFinalizations.runId, heartbeatRuns.id))))) : [];
|
||||
const [parkedSuccessor] = !successor && !preparingSuccessor && !waitingSuccessor && task?.executionRunId && task.executionRunId !== owner.runId
|
||||
? await parkedSuccessorWaitingForOwner(tx, owner, task.executionRunId) : [];
|
||||
if (!current.resultId || newWork || !task
|
||||
|| (task.executionRunId && task.executionRunId !== owner.runId && !successor && !preparingSuccessor && !waitingSuccessor)) {
|
||||
|| (task.executionRunId && task.executionRunId !== owner.runId && !successor && !preparingSuccessor && !waitingSuccessor && !parkedSuccessor)) {
|
||||
throw new Error("native_runner_checkpoint_owner_lost");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function parkedSuccessorWaitingForOwner(tx: CheckpointTransaction, owner: NativeRunnerCheckpointFenceOwner, successorRunId: string) {
|
||||
return tx.select({ runId: nativeRunFinalizations.runId }).from(nativeRunFinalizations)
|
||||
.innerJoin(heartbeatRuns, eq(heartbeatRuns.id, nativeRunFinalizations.runId)).where(and(
|
||||
eq(nativeRunFinalizations.runId, successorRunId), eq(nativeRunFinalizations.companyId, owner.companyId),
|
||||
eq(nativeRunFinalizations.issueId, owner.issueId), eq(nativeRunFinalizations.phase, "retryable_failure"),
|
||||
eq(nativeRunFinalizations.failureCode, NATIVE_RETAINED_OWNER_WAIT), eq(nativeRunFinalizations.attempt, 0),
|
||||
isNull(nativeRunFinalizations.resultId), isNull(nativeRunFinalizations.leaseOwner),
|
||||
sql`${nativeRunFinalizations.failureDetail}->'waitingForOwner'->>'runId' = ${owner.runId}`,
|
||||
sql`${nativeRunFinalizations.failureDetail}->'waitingForOwner'->>'controllerBootId' = ${owner.bootId}`,
|
||||
eq(heartbeatRuns.companyId, owner.companyId), eq(heartbeatRuns.nativeIssueId, owner.issueId),
|
||||
eq(heartbeatRuns.runtimeMode, "native"), eq(heartbeatRuns.status, "running"),
|
||||
isNull(heartbeatRuns.processPid), isNull(heartbeatRuns.processGroupId), isNull(heartbeatRuns.processStartedAt),
|
||||
sql`${heartbeatRuns.nativeSessionId} = (select source.native_session_id from heartbeat_runs source
|
||||
where source.id = ${owner.runId} and source.company_id = ${owner.companyId})`,
|
||||
notExists(tx.select({ runId: nativeRunnerCheckpoints.runId }).from(nativeRunnerCheckpoints).where(and(
|
||||
eq(nativeRunnerCheckpoints.companyId, owner.companyId), eq(nativeRunnerCheckpoints.runId, successorRunId)))),
|
||||
notExists(tx.select({ id: heartbeatRunEvents.id }).from(heartbeatRunEvents).where(and(
|
||||
eq(heartbeatRunEvents.companyId, owner.companyId), eq(heartbeatRunEvents.runId, successorRunId),
|
||||
isNull(heartbeatRunEvents.sourceEventId), inArray(heartbeatRunEvents.eventType, [...OWN_PROCESS_START_EVENT_TYPES])))),
|
||||
)).for("share", { of: nativeRunFinalizations });
|
||||
}
|
||||
|
||||
export async function assertNativeRunnerCheckpointOwner(tx: CheckpointTransaction, owner: NativeRunnerCheckpointOwner, newWork: boolean) {
|
||||
const locked = await lockNativeRunnerCheckpointOwner(tx, owner);
|
||||
await validateNativeRunnerCheckpointOwner(tx, owner, locked, newWork);
|
||||
|
||||
@@ -610,7 +610,7 @@ export async function reconcileSafeNativeReplacements(
|
||||
(ownershipBound && !await ownershipProofExpired(tx, run))
|
||||
)
|
||||
return;
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: run.companyId, runId: run.id });
|
||||
await tx
|
||||
.update(nativeRunFinalizations)
|
||||
.set({
|
||||
|
||||
@@ -434,6 +434,8 @@ import {
|
||||
nativeSessionWorkspaceScope,
|
||||
reserveWarmNativeInstructionDirectory,
|
||||
closeIdleWarmNativeSessionsForRestart,
|
||||
WARM_IDLE_CLOSE_MAX_RETRIES,
|
||||
WARM_IDLE_CLOSE_RETRY_MS,
|
||||
readNativeSessionIdleWork,
|
||||
createGovernedWaitEventObservation,
|
||||
createRemoteRunnerProcessLauncher,
|
||||
@@ -11614,10 +11616,12 @@ describe("native warm session supervision", () => {
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ lease: "pending_cleanup", forgotten: true },
|
||||
{ lease: "released", forgotten: true },
|
||||
{ lease: "stopped-receipt", forgotten: true },
|
||||
{ lease: "destroyed-receipt", forgotten: true },
|
||||
{ lease: "pending_cleanup", forgotten: false },
|
||||
{ lease: "released", forgotten: false },
|
||||
{ lease: "retained", forgotten: false },
|
||||
])("forgets a warm owner whose idle close failed only once the host gave up its sandbox: $lease", async ({ lease, forgotten }) => {
|
||||
])("forgets a warm owner whose idle close failed only once its sandbox has a stop or destroy receipt: $lease", async ({ lease, forgotten }) => {
|
||||
const identity = `warm-idle-close-sandbox-${lease}`;
|
||||
const warmExecution = { ...execution, binding: { ...execution.binding, runId: identity, executionWorkspaceId: `${identity}-workspace` },
|
||||
session: { ...execution.session, normalizedSessionId: identity, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 50 } },
|
||||
@@ -11632,7 +11636,7 @@ describe("native warm session supervision", () => {
|
||||
});
|
||||
const copy = (runId: string) => ({ runId, root: `/tmp/${identity}`, preparationKey: "same", hasChanges: async () => false,
|
||||
collectStopped: async () => undefined, retirementFailed: async () => undefined });
|
||||
let leaseRows: Array<{ status: string }> = [];
|
||||
let leaseRows: Array<Record<string, unknown>> = [];
|
||||
const base = leaseDb(warmExecution);
|
||||
const db = { ...base, select: (fields?: unknown) => ({ from: (table: unknown) => table === environmentLeases
|
||||
? { where: async () => leaseRows } : base.select(fields as never).from(table as never) }) } as unknown as Db;
|
||||
@@ -11641,7 +11645,14 @@ describe("native warm session supervision", () => {
|
||||
runnerExecutionTarget: { kind: "remote", transport: "sandbox", environmentId: identity, remoteCwd: `/tmp/${identity}`,
|
||||
sandboxLeaseAcquisition: { providerLeaseId: `${identity}-sandbox` } } as never,
|
||||
instructionWorkingCopy: copy(identity) });
|
||||
leaseRows = [{ status: lease }];
|
||||
const receipt = lease.endsWith("-receipt") ? lease.slice(0, -"-receipt".length) : null;
|
||||
leaseRows = [{ id: `${identity}-lease`, companyId: warmExecution.binding.companyId, environmentId: identity,
|
||||
heartbeatRunId: identity, provider: "daytona", providerLeaseId: `${identity}-sandbox`,
|
||||
status: receipt ? "released" : lease, releasedAt: lease === "retained" ? null : new Date(),
|
||||
cleanupStatus: receipt || lease === "released" ? "success" : "failed", leasePolicy: "reuse_by_environment",
|
||||
metadata: receipt ? { remoteExecutionTermination: { schema: "paperclip.remote-termination.v1",
|
||||
companyId: warmExecution.binding.companyId, runId: identity, leaseId: `${identity}-lease`, provider: "daytona",
|
||||
providerLeaseId: `${identity}-sandbox`, state: receipt, confirmedAt: new Date().toISOString() } } : {} }];
|
||||
await vi.waitFor(() => expect(session.close).toHaveBeenCalledTimes(1));
|
||||
const followUpRunId = `${identity}-follow-up`;
|
||||
const adopt = vi.fn(async () => null);
|
||||
@@ -12197,6 +12208,79 @@ describe("native warm session supervision", () => {
|
||||
expect(collectStopped).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("an idle warm session whose close fails with runner_remote_process_identity_unavailable and whose Runner is proven gone is released at controller restart", async () => {
|
||||
const name = "warm-close-runner-gone";
|
||||
const current = { ...execution,
|
||||
binding: { ...execution.binding, runId: name, executionWorkspaceId: name },
|
||||
session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } },
|
||||
} as NativeExecutionInputV1;
|
||||
const close = vi.fn<() => Promise<void>>(async () => {
|
||||
throw new RemoteRunnerRecoveryError({ stage: "process_verification", reason: "process_not_running" });
|
||||
});
|
||||
state.execute.mockReset().mockImplementationOnce(async options => {
|
||||
await options.onSession?.({ close });
|
||||
return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" },
|
||||
turnId: name, normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1",
|
||||
nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null };
|
||||
});
|
||||
await expect(executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name }))
|
||||
.resolves.toMatchObject({ exitCode: 0 });
|
||||
expect(close).not.toHaveBeenCalled();
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toEqual({ closed: 1, busy: 0, failed: 0, failures: [] });
|
||||
expect(close).toHaveBeenCalledOnce();
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toEqual({ closed: 0, busy: 0, failed: 0, failures: [] });
|
||||
});
|
||||
|
||||
it("names the Runner check in a warm close failure and keeps an unproven owner registered at controller restart", async () => {
|
||||
const name = "warm-close-marker-missing";
|
||||
const current = { ...execution,
|
||||
binding: { ...execution.binding, runId: name, executionWorkspaceId: name },
|
||||
session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 60_000 } },
|
||||
} as NativeExecutionInputV1;
|
||||
const close = vi.fn<() => Promise<void>>(async () => {
|
||||
throw new RemoteRunnerRecoveryError({ stage: "process_verification", reason: "marker_missing" });
|
||||
});
|
||||
state.execute.mockReset().mockImplementationOnce(async options => {
|
||||
await options.onSession?.({ close });
|
||||
return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" },
|
||||
turnId: name, normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1",
|
||||
nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null };
|
||||
});
|
||||
await executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name });
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 0, failed: 1, failures: [{ runId: name,
|
||||
reason: "close failed: runner_remote_process_identity_unavailable: runner_remote_process_identity_unavailable [process_verification/marker_missing]" }] });
|
||||
close.mockResolvedValue(undefined);
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 1, failed: 0 });
|
||||
});
|
||||
|
||||
it("retries a failed idle warm close a bounded number of times", async () => {
|
||||
const name = "warm-idle-close-retry";
|
||||
const current = { ...execution,
|
||||
binding: { ...execution.binding, runId: name, executionWorkspaceId: name },
|
||||
session: { ...execution.session, normalizedSessionId: name, lifecyclePolicy: { mode: "warm" as const, idleTimeoutMs: 20 } },
|
||||
} as NativeExecutionInputV1;
|
||||
const close = vi.fn<() => Promise<void>>(async () => { throw new Error("native_runner_checkpoint_owner_lost"); });
|
||||
state.execute.mockReset().mockImplementationOnce(async options => {
|
||||
await options.onSession?.({ close });
|
||||
return { result: { summary: "completed" }, terminal: { runTerminalState: "succeeded" },
|
||||
turnId: name, normalizedSessionId: name, providerSessionId: name, driverKind: "test", driverVersion: "1",
|
||||
nativeEventCount: 1, highestContiguousSourceSeq: 1, usage: null };
|
||||
});
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
||||
try {
|
||||
await executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: name });
|
||||
await vi.advanceTimersByTimeAsync(20);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
await vi.advanceTimersByTimeAsync(WARM_IDLE_CLOSE_RETRY_MS);
|
||||
expect(close).toHaveBeenCalledTimes(2);
|
||||
await vi.advanceTimersByTimeAsync(WARM_IDLE_CLOSE_RETRY_MS * 10);
|
||||
expect(close).toHaveBeenCalledTimes(1 + WARM_IDLE_CLOSE_MAX_RETRIES);
|
||||
expect(readNativeSessionIdleWork()).toBe("present");
|
||||
} finally { vi.useRealTimers(); }
|
||||
close.mockResolvedValue(undefined);
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed: 1, failed: 0 });
|
||||
});
|
||||
|
||||
it.each(["failed", "cancelled"] as const)("retires a %s session even if its warm checkpoint rejects", async (runTerminalState) => {
|
||||
const name = `warm-checkpoint-rejects-${runTerminalState}`;
|
||||
const current = { ...execution,
|
||||
@@ -13245,6 +13329,48 @@ describe("native warm session supervision", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ lease: "released-stop-receipt", closed: 1 },
|
||||
{ lease: "pending_cleanup", closed: 0 },
|
||||
{ lease: "released-without-receipt", closed: 0 },
|
||||
{ lease: "stop-receipt-for-another-run", closed: 0 },
|
||||
] as const)("reads the warm owner's own lease rows at controller restart: $lease", async ({ lease: kind, closed }) => {
|
||||
const { base } = fixture(`restart-lease-${kind}`);
|
||||
const environmentId = `restart-lease-env-${kind}`, providerLeaseId = `restart-lease-sandbox-${kind}`;
|
||||
const close = vi.fn(async (): Promise<void> => { throw new Error("owned close not yet confirmed"); });
|
||||
state.execute.mockReset().mockImplementationOnce(async options => {
|
||||
await options.onSession?.({ close }); return result;
|
||||
});
|
||||
const leaseRunId = kind === "stop-receipt-for-another-run" ? "earlier-run" : base.binding.runId;
|
||||
const terminal = kind !== "pending_cleanup";
|
||||
const row = { id: `lease-${kind}`, companyId: base.binding.companyId, environmentId, heartbeatRunId: leaseRunId,
|
||||
provider: "daytona", providerLeaseId, status: terminal ? "released" : "pending_cleanup", releasedAt: new Date(),
|
||||
cleanupStatus: terminal ? "success" : "failed", leasePolicy: "reuse_by_environment",
|
||||
metadata: kind === "released-stop-receipt" || kind === "stop-receipt-for-another-run"
|
||||
? { remoteExecutionTermination: { schema: "paperclip.remote-termination.v1", companyId: base.binding.companyId,
|
||||
runId: leaseRunId, leaseId: `lease-${kind}`, provider: "daytona", providerLeaseId, state: "stopped",
|
||||
confirmedAt: new Date().toISOString() } }
|
||||
: { failureReason: "sandbox_stop_pending" } };
|
||||
let leaseRows: unknown[] = [];
|
||||
const ownerDb = leaseDb(base), select = ownerDb.select.bind(ownerDb);
|
||||
ownerDb.select = ((fields?: Record<string, unknown>) => ({ from: (table: unknown) => {
|
||||
if (table !== environmentLeases) return select(fields as never).from(table as never);
|
||||
const query = { then: (...args: Parameters<Promise<unknown[]>["then"]>) => Promise.resolve(leaseRows).then(...args),
|
||||
where: () => query, limit: () => query };
|
||||
return query;
|
||||
} })) as unknown as Db["select"];
|
||||
try {
|
||||
await executePaperclipNativeSession({ db: ownerDb, execution: base, runnerInstanceId: "runner",
|
||||
runnerExecutionTarget: { kind: "remote", transport: "sandbox", environmentId, remoteCwd: `/tmp/${environmentId}`,
|
||||
sandboxLeaseAcquisition: { outcome: "created", providerLeaseId } } });
|
||||
leaseRows = [row];
|
||||
expect(await closeIdleWarmNativeSessionsForRestart()).toMatchObject({ closed, failed: 1 - closed });
|
||||
} finally {
|
||||
close.mockResolvedValue(undefined);
|
||||
await closeIdleWarmNativeSessionsForRestart();
|
||||
}
|
||||
});
|
||||
|
||||
it("retains failed retirement for retry and never launches over an uncontained owner", async () => {
|
||||
const { base, next, run } = fixture("identity-close-failure");
|
||||
const close = vi.fn().mockRejectedValueOnce(new Error("containment unavailable")).mockResolvedValue(undefined);
|
||||
|
||||
@@ -50,7 +50,7 @@ import { notifyCancelledWorkspacePreservation } from "../cancelled-workspace-pre
|
||||
import { notifyInstructionCollection } from "../instruction-collection-notifications.js";
|
||||
import { providerPackWorkspaceId, recordAdmittedRemoteProviderPack, resolveRemoteProviderPackAuthority } from "./remote-provider-pack-authority.js";
|
||||
import { nativeProviderPackAdmissionFailureCode, prepareNativeProviderPackAdmission, rememberAdmittedNativeProviderPack, rememberRecoveredNativeProviderPack, recordNativeProviderPackAdmission, type NativeProviderPackAdmissionSource } from "./native-provider-pack-admission.js";
|
||||
import { type ProviderPackInstallation, verifyRemoteProviderPack as verifyRemoteProviderPackIdentity } from "./remote-provider-pack-verification.js";
|
||||
import { type ProviderPackInstallation, providerPackIncompatible, verifyRemoteProviderPack as verifyRemoteProviderPackIdentity } from "./remote-provider-pack-verification.js";
|
||||
import { writeEnvironmentCleanup } from "../environment-cleanup-notifications.js";
|
||||
import { NATIVE_SESSION_EXECUTION_LEASE_TTL_MS, lockNativeExecutionLeaseForReacquire, nativeExecutionLeaseHeldCondition, releaseUnstartedNativeExecutionClaim, startNativeSessionExecutionLeaseRenewal, type NativeExecutionLeaseRenewal } from "./native-execution-lease.js";
|
||||
export { renewNativeSessionExecutionLease } from "./native-execution-lease.js";
|
||||
@@ -743,12 +743,15 @@ type WarmNativeSession = {
|
||||
controllerDetachedForRestart?: boolean;
|
||||
finishRelease?: () => Promise<void>;
|
||||
closeOnReleaseReason?: string;
|
||||
idleCloseRetries?: number;
|
||||
idleTimer: ReturnType<typeof setTimeout> | null;
|
||||
lastActivityAt: string;
|
||||
};
|
||||
|
||||
const WARM_CLOSE_FAILURE_DETAIL_MAX = 2_000;
|
||||
const WARM_NATIVE_SESSION_CLOSE_CONCURRENCY = 4;
|
||||
export const WARM_IDLE_CLOSE_RETRY_MS = 5_000;
|
||||
export const WARM_IDLE_CLOSE_MAX_RETRIES = 3;
|
||||
|
||||
export function describeWarmCloseFailure(error: unknown): string {
|
||||
const describe = (value: unknown): string => {
|
||||
@@ -757,8 +760,10 @@ export function describeWarmCloseFailure(error: unknown): string {
|
||||
const code = "code" in value && typeof value.code === "string" ? `${value.code}: ` : "";
|
||||
const settlement = value instanceof NativeSessionCloseUnrecoverableError && value.settlement
|
||||
? ` ${JSON.stringify(value.settlement)}` : "";
|
||||
const remote = readRemoteRunnerRecoveryError(value);
|
||||
const recovery = remote ? ` [${remote.stage}/${remote.reason}${remote.runnerLifecycle ? `/${remote.runnerLifecycle}` : ""}]` : "";
|
||||
const cause = value.cause === undefined ? "" : ` (cause: ${describe(value.cause)})`;
|
||||
return `${code}${value.message}${settlement}${cause}`;
|
||||
return `${code}${value.message}${recovery}${settlement}${cause}`;
|
||||
};
|
||||
const text = describe(error).replaceAll(/[\r\n]+/g, " ");
|
||||
return text.length > WARM_CLOSE_FAILURE_DETAIL_MAX ? `${text.slice(0, WARM_CLOSE_FAILURE_DETAIL_MAX)}…` : text;
|
||||
@@ -1107,17 +1112,7 @@ export async function closeWarmNativeSessionsForEnvironment(input: {
|
||||
return closeIdleWarmNativeSessions(input);
|
||||
}
|
||||
|
||||
async function warmSandboxGivenUpByHost(entry: WarmNativeSession): Promise<boolean> {
|
||||
if (!entry.sandboxLeaseDb || !entry.providerLeaseId || !entry.environmentId) return false;
|
||||
const leases = await entry.sandboxLeaseDb.select({ status: environmentLeases.status }).from(environmentLeases).where(and(
|
||||
eq(environmentLeases.companyId, entry.companyId),
|
||||
eq(environmentLeases.environmentId, entry.environmentId),
|
||||
eq(environmentLeases.providerLeaseId, entry.providerLeaseId),
|
||||
));
|
||||
return leases.length > 0 && leases.every(lease => lease.status !== "active" && lease.status !== "retained");
|
||||
}
|
||||
|
||||
async function warmSandboxDestroyed(db: Db, entry: WarmNativeSession): Promise<boolean> {
|
||||
async function warmSandboxTerminated(db: Db, entry: WarmNativeSession): Promise<boolean> {
|
||||
if (!entry.providerLeaseId || !entry.environmentId) return false;
|
||||
const leases = await db.select().from(environmentLeases).where(and(
|
||||
eq(environmentLeases.companyId, entry.companyId),
|
||||
@@ -1125,8 +1120,23 @@ async function warmSandboxDestroyed(db: Db, entry: WarmNativeSession): Promise<b
|
||||
eq(environmentLeases.providerLeaseId, entry.providerLeaseId),
|
||||
));
|
||||
const resolved = await Promise.all(leases.map(lease => resolveRemoteTerminationLease(db, lease)));
|
||||
return resolved.some(lease => hasRemoteTerminationReceipt(lease)
|
||||
&& (lease.metadata?.remoteExecutionTermination as { state?: unknown } | undefined)?.state === "destroyed");
|
||||
return resolved.some(lease => {
|
||||
if (!hasRemoteTerminationReceipt(lease)) return false;
|
||||
const state = (lease.metadata?.remoteExecutionTermination as { state?: unknown } | undefined)?.state;
|
||||
return state === "destroyed" || (state === "stopped" && lease.heartbeatRunId === entry.runId);
|
||||
});
|
||||
}
|
||||
|
||||
/** A failed close is complete when its Runner is proven gone, its sandbox is destroyed, or the run's own sandbox lease has a stop receipt. */
|
||||
async function warmCloseFailureProvesOwnerGone(entry: WarmNativeSession, error: unknown, db = entry.sandboxLeaseDb): Promise<boolean> {
|
||||
const diagnostic = readRemoteRunnerRecoveryError(error);
|
||||
if (diagnostic?.stage === "process_verification" && diagnostic.reason === "process_not_running") return true;
|
||||
try {
|
||||
return db ? await warmSandboxTerminated(db, entry) : false;
|
||||
} catch (proofError) {
|
||||
logger.warn({ err: proofError, runId: entry.runId }, "could not read the warm session's sandbox lease");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Detach released owners and checkpoint unreleased owners before a controller
|
||||
@@ -1195,16 +1205,10 @@ async function closeIdleWarmNativeSessions(input: {
|
||||
busy += 1;
|
||||
return;
|
||||
}
|
||||
const destroyed = !detach && input.forceStopUnsettled && input.db
|
||||
? await warmSandboxDestroyed(input.db, entry).catch(proofError => {
|
||||
logger.warn({ err: proofError, runId: entry.runId }, "could not read the warm session's sandbox lease");
|
||||
return false;
|
||||
})
|
||||
: false;
|
||||
if (destroyed) {
|
||||
if (!detach && await warmCloseFailureProvesOwnerGone(entry, error, input.db ?? entry.sandboxLeaseDb)) {
|
||||
logger.warn({ runId: entry.runId, issueId: entry.issueId, environmentId: entry.environmentId,
|
||||
providerLeaseId: entry.providerLeaseId ?? null, reason: input.reason, closeFailure: describeWarmCloseFailure(error) },
|
||||
"warm native session's sandbox was already destroyed; released its owner");
|
||||
"warm native session's Runner or sandbox is gone; released its owner");
|
||||
forgetWarmNativeSession(sessionId, entry);
|
||||
closed += 1;
|
||||
return;
|
||||
@@ -8860,17 +8864,21 @@ function armWarmNativeSessionIdleTimer(
|
||||
return;
|
||||
}
|
||||
logger.warn({ runId: current.runId, issueId: current.issueId, environmentId: current.environmentId,
|
||||
providerLeaseId: current.providerLeaseId ?? null, closeFailure: describeWarmCloseFailure(error) },
|
||||
providerLeaseId: current.providerLeaseId ?? null, closeFailure: describeWarmCloseFailure(error),
|
||||
closeAttempt: (current.idleCloseRetries ?? 0) + 1 },
|
||||
released ? "idle warm native session detach failed" : "idle warm native session close failed");
|
||||
if (released) return;
|
||||
return warmSandboxGivenUpByHost(current).then(givenUp => {
|
||||
if (!givenUp) return;
|
||||
logger.warn({ runId: current.runId, issueId: current.issueId, environmentId: current.environmentId,
|
||||
providerLeaseId: current.providerLeaseId ?? null },
|
||||
"warm native session's sandbox was stopped by the host; released its owner");
|
||||
forgetWarmNativeSession(sessionId, current);
|
||||
}, proofError => {
|
||||
logger.warn({ err: proofError, runId: current.runId }, "could not read the warm session's sandbox lease");
|
||||
return warmCloseFailureProvesOwnerGone(current, error).then(gone => {
|
||||
if (gone) {
|
||||
logger.warn({ runId: current.runId, issueId: current.issueId, environmentId: current.environmentId,
|
||||
providerLeaseId: current.providerLeaseId ?? null },
|
||||
"warm native session's Runner or sandbox is gone; released its owner");
|
||||
forgetWarmNativeSession(sessionId, current);
|
||||
return;
|
||||
}
|
||||
if ((current.idleCloseRetries ?? 0) >= WARM_IDLE_CLOSE_MAX_RETRIES) return;
|
||||
current.idleCloseRetries = (current.idleCloseRetries ?? 0) + 1;
|
||||
armWarmNativeSessionIdleTimer(sessionId, current, WARM_IDLE_CLOSE_RETRY_MS);
|
||||
});
|
||||
})
|
||||
.finally(() => {
|
||||
@@ -10727,7 +10735,7 @@ export async function executePaperclipNativeSession(input: {
|
||||
executionFailure = error;
|
||||
if (error instanceof NativeControllerRecoveryWaitingError) {
|
||||
await deferNativeControllerRecovery(input.db, { ...input.execution.binding,
|
||||
leaseOwner: input.leaseOwner, retryAt: error.retryAt });
|
||||
leaseOwner: input.leaseOwner, retryAt: error.retryAt, waitingForOwner: error.owner });
|
||||
}
|
||||
if (!(error instanceof NativeRunnerOwnershipUnverifiedError) && !(error instanceof NativeStartupCleanupPendingError) && startup.stopRequested && startup.executionContext?.signal.reason instanceof Error &&
|
||||
startup.executionContext.signal.reason.message === "native_session_cancelled") {
|
||||
@@ -13027,7 +13035,7 @@ async function executePaperclipNativeSessionAttempt(
|
||||
eq(nativeRunFinalizations.runId, input.execution.binding.runId),
|
||||
eq(nativeRunFinalizations.leaseOwner, leaseOwner),
|
||||
),
|
||||
), { companyId: input.execution.binding.companyId });
|
||||
), { companyId: input.execution.binding.companyId, runId: input.execution.binding.runId });
|
||||
|
||||
const failedAtMs = Date.now();
|
||||
const executionFailureMessage = redactOutputText(
|
||||
@@ -13092,7 +13100,7 @@ async function executePaperclipNativeSessionAttempt(
|
||||
eq(nativeRunFinalizations.leaseOwner, leaseOwner),
|
||||
eq(nativeRunFinalizations.attempt, attempt),
|
||||
isNull(nativeRunFinalizations.resultId),
|
||||
)).returning({ runId: nativeRunFinalizations.runId }), { companyId: input.execution.binding.companyId });
|
||||
)).returning({ runId: nativeRunFinalizations.runId }), { companyId: input.execution.binding.companyId, runId: input.execution.binding.runId });
|
||||
if (settled) {
|
||||
await stoppedLeaseRenewal;
|
||||
if (warmSessionId !== null && lifecyclePolicy.mode === "warm") {
|
||||
@@ -13281,7 +13289,7 @@ async function executePaperclipNativeSessionAttempt(
|
||||
// Issue → coordinator → run, as below. A lease that lapsed untouched
|
||||
// (host sleep) is still this owner's to settle; see the held condition.
|
||||
await lockNativeExecutionLeaseForReacquire(tx, { ...input.execution.binding, leaseOwner, preResultOnly: true });
|
||||
await notifyExecutionRunWork(tx, { companyId: input.execution.binding.companyId });
|
||||
await notifyExecutionRunWork(tx, { companyId: input.execution.binding.companyId, runId: input.execution.binding.runId });
|
||||
await notifyNativeFinalizationWork(tx, input.execution.binding);
|
||||
const updated = await tx
|
||||
.update(nativeRunFinalizations)
|
||||
@@ -14698,7 +14706,8 @@ export async function prepareRemoteProviderPackOnTarget(input: {
|
||||
"provider_pack.verify",
|
||||
() => verifyRemoteProviderPack(stagedRemoteProviderPackRoot),
|
||||
),
|
||||
usePreinstalled: async () => useVerifiedPreinstalledRemoteProviderPack({
|
||||
usePreinstalled: async (onRejected) => useVerifiedPreinstalledRemoteProviderPack({
|
||||
onRejected,
|
||||
candidates: preinstalledProviderPackRoots = await measureNativeRunnerSpan(input.trace, "provider_pack.discover", discoverPreinstalledProviderPack),
|
||||
verifyAndLink: async (preinstalledProviderPack) => {
|
||||
await measureNativeRunnerSpan(
|
||||
@@ -14728,9 +14737,7 @@ export async function prepareRemoteProviderPackOnTarget(input: {
|
||||
timeoutMs: 10_000,
|
||||
}));
|
||||
if (linked.exitCode !== 0 || linked.timedOut) {
|
||||
throw new Error(
|
||||
"runner_remote_provider_artifact_incompatible: preinstalled provider pack could not be linked",
|
||||
);
|
||||
throw providerPackIncompatible("link_failed", "preinstalled provider pack could not be linked");
|
||||
}
|
||||
activeRemoteProviderPackRoot = stagedRemoteProviderPackRoot;
|
||||
await input.onLog?.(
|
||||
@@ -17143,7 +17150,7 @@ async function createRunnerdBackendWithinSessionClaim(
|
||||
requireExactIdentity: retainProviderPack || explicitProviderPackSelection,
|
||||
requireCurrentOpenCodeProxy: !retainProviderPack
|
||||
&& runnerEnvironment?.PAPERCLIP_OPENCODE_PERFORMANCE_DIAGNOSTICS === "1",
|
||||
}));
|
||||
}), { attributes: { target: installation.root === stagedRemoteProviderPackRoot ? "workspace" : "image" } });
|
||||
if (!retainProviderPack) providerPackAuthority!.select(manifest);
|
||||
expectedProviderPackManifest = manifest;
|
||||
activeRemoteProviderPackRoot = installation.root;
|
||||
|
||||
@@ -39,7 +39,7 @@ export async function retireSupersededNativeRetry(db: Db, input: {
|
||||
)).limit(1);
|
||||
if (!source) return false;
|
||||
|
||||
await notifyExecutionRunWork(db, { companyId: run.companyId });
|
||||
await notifyExecutionRunWork(db, { companyId: run.companyId, runId: run.id });
|
||||
await db.update(nativeRunFinalizations).set({ phase: "terminal_failure", nextAttemptAt: null,
|
||||
leaseExpiresAt: null, controlDeadlineAt: null, recoveryState: "blocked",
|
||||
failureCode: "native_retry_superseded", failureDetail: { ...coordinator.failureDetail,
|
||||
|
||||
@@ -51,8 +51,20 @@ describe("installed provider pack compatibility", () => {
|
||||
try {
|
||||
// Exercise the old complete-manifest comparison in a real Node process.
|
||||
// Only provenance changed; provider bytes and interface are identical.
|
||||
await expect(verifyRemoteProviderPack(input)).rejects.toThrow("manifest mismatch");
|
||||
await expect(verifyRemoteProviderPack(input)).rejects.toMatchObject({
|
||||
message: expect.stringContaining("manifest mismatch"), failureCheck: "manifest_mismatch:runnerSourceRevision" });
|
||||
expect(execute).toHaveBeenCalledOnce();
|
||||
await expect(verifyRemoteProviderPack({ ...input, manifest: installed })).rejects.toMatchObject({
|
||||
message: expect.stringContaining("nodeCommand digest mismatch"), failureCheck: "artifact_digest:nodeCommand" });
|
||||
await rm(join(root, "provider-pack.json"));
|
||||
await expect(verifyRemoteProviderPack(input)).rejects.toMatchObject({ failureCheck: "manifest_unreadable" });
|
||||
const combined = vi.fn(async (request: Parameters<CommandManagedRuntimeRunner["execute"]>[0]) => {
|
||||
const result = await execute(request);
|
||||
return { ...result, stdout: `${result.stdout}${result.stderr}`, stderr: "" };
|
||||
});
|
||||
await expect(verifyRemoteProviderPack({ ...input, runner: { execute: combined } }))
|
||||
.rejects.toMatchObject({ failureCheck: "manifest_unreadable" });
|
||||
await writeFile(join(root, "provider-pack.json"), JSON.stringify(installed));
|
||||
execute.mockClear();
|
||||
const selected = await verifyRemoteProviderPack({ ...input,
|
||||
installation: { root, manifest: installed, immutable: true }, provider: { kind: "opencode" } });
|
||||
@@ -70,6 +82,31 @@ describe("installed provider pack compatibility", () => {
|
||||
provider: { kind: "opencode" }, requireExactIdentity: options.requireExactIdentity,
|
||||
requireCurrentOpenCodeProxy: options.requireCurrentOpenCodeProxy });
|
||||
};
|
||||
it.each([
|
||||
["interface", "compatibility_revision"], ["contracts", "contract_digest"], ["platform", "target"], ["schema", "schema"],
|
||||
["artifact_path", "artifact:nodeCommand"], ["digest", "manifest_digest"], ["legacy", "compatibility_revision"],
|
||||
["legacy_contracts", "contract_digest_missing"],
|
||||
])("names the failed check for an incompatible %s", async (field, failureCheck) => {
|
||||
let pack = manifest("a");
|
||||
if (field === "interface") pack.payload.compatibility!.opencode += 1;
|
||||
if (field === "contracts") pack.payload.contractDigest = sha("other-contracts");
|
||||
if (field === "legacy") delete pack.payload.compatibility;
|
||||
if (field === "legacy_contracts") delete pack.payload.contractDigest;
|
||||
if (field === "platform") pack.payload.target.architecture = "arm64";
|
||||
if (field === "schema") pack.schema = "unknown";
|
||||
if (field === "artifact_path") pack.payload.artifacts.nodeCommand.path = "../node";
|
||||
pack = reseal(pack);
|
||||
if (field === "digest") pack.digest = sha("corrupt");
|
||||
await expect(check(pack)).rejects.toMatchObject({ failureCheck });
|
||||
});
|
||||
it("names unprotected, exact-identity and proxy rejections", async () => {
|
||||
await expect(check(manifest("b"), { immutable: false })).rejects.toMatchObject({ failureCheck: "installation_unprotected" });
|
||||
await expect(check(manifest("a"), { requireExactIdentity: true })).rejects.toMatchObject({ failureCheck: "exact_identity" });
|
||||
await expect(check(manifest("a"), { requireCurrentOpenCodeProxy: true })).rejects.toMatchObject({ failureCheck: "opencode_proxy" });
|
||||
const unpinned = manifest("b");
|
||||
(unpinned.payload.pins as Record<string, unknown>).opencode = null;
|
||||
await expect(check(reseal(unpinned))).rejects.toMatchObject({ failureCheck: "opencode_pin_missing" });
|
||||
});
|
||||
it.each(["interface", "contracts", "platform", "schema", "artifact_path", "digest", "legacy", "legacy_contracts"])("rejects an incompatible %s", async field => {
|
||||
let pack = manifest("a");
|
||||
if (field === "interface") pack.payload.compatibility!.opencode += 1;
|
||||
|
||||
@@ -28,6 +28,22 @@ export type ProviderPackIdentity = {
|
||||
};
|
||||
};
|
||||
|
||||
export function providerPackIncompatible(check: string, detail: string): Error & { failureCheck: string } {
|
||||
return Object.assign(new Error(`runner_remote_provider_artifact_incompatible: ${detail}`), { failureCheck: check });
|
||||
}
|
||||
|
||||
async function withProviderPackCheck<T>(step: "pack" | "opencode", verify: () => Promise<T>): Promise<T> {
|
||||
try {
|
||||
return await verify();
|
||||
} catch (error) {
|
||||
if (!(error instanceof Error) || error.name === "AbortError") throw error;
|
||||
const reported = /paperclip-pack-check=([A-Za-z0-9_.:,@/-]{1,100})/.exec(error.message)?.[1];
|
||||
const check = reported ?? (error.message.startsWith("runner_remote_provider_verification_unavailable")
|
||||
? `${step}_verifier_unavailable` : `${step}_verifier_failed`);
|
||||
throw Object.assign(error, { failureCheck: check });
|
||||
}
|
||||
}
|
||||
|
||||
export type ProviderPackInstallation = { root: string; manifest: unknown; immutable: boolean };
|
||||
export type PackProvider = { kind: "opencode" } | { kind: "acpx"; agent: string };
|
||||
|
||||
@@ -45,28 +61,33 @@ function compatibleInstallation<T extends ProviderPackIdentity>(
|
||||
const actual = installation.manifest as T | null;
|
||||
const payload = actual?.payload;
|
||||
const contract = expected.payload.compatibility?.[provider.kind];
|
||||
if (!installation.immutable || installation.root !== packRoot || !payload
|
||||
|| actual.schema !== expected.schema
|
||||
|| actual.digest !== `sha256:${createHash("sha256").update(canonicalProviderPackJson(payload)).digest("hex")}`
|
||||
|| canonicalProviderPackJson(payload.target) !== canonicalProviderPackJson(expected.payload.target)
|
||||
|| (requireExactIdentity ? actual.digest !== expected.digest
|
||||
: !Number.isSafeInteger(contract) || contract! < 1 || payload.compatibility?.[provider.kind] !== contract
|
||||
|| !/^sha256:[a-f0-9]{64}$/.test(expected.payload.contractDigest ?? "")
|
||||
|| payload.contractDigest !== expected.payload.contractDigest)
|
||||
|| typeof payload.pins?.opencode !== "string") {
|
||||
throw new Error("runner_remote_provider_artifact_incompatible: installed provider pack interface or installation is incompatible");
|
||||
const failed = !installation.immutable ? "installation_unprotected"
|
||||
: installation.root !== packRoot ? "installation_root"
|
||||
: !payload ? "manifest_missing"
|
||||
: actual.schema !== expected.schema ? "schema"
|
||||
: actual.digest !== `sha256:${createHash("sha256").update(canonicalProviderPackJson(payload)).digest("hex")}` ? "manifest_digest"
|
||||
: canonicalProviderPackJson(payload.target) !== canonicalProviderPackJson(expected.payload.target) ? "target"
|
||||
: requireExactIdentity ? (actual.digest !== expected.digest ? "exact_identity" : null)
|
||||
: !Number.isSafeInteger(contract) || contract! < 1 ? "expected_compatibility_missing"
|
||||
: payload.compatibility?.[provider.kind] !== contract ? "compatibility_revision"
|
||||
: !/^sha256:[a-f0-9]{64}$/.test(expected.payload.contractDigest ?? "") ? "expected_contract_digest_missing"
|
||||
: payload.contractDigest === undefined ? "contract_digest_missing"
|
||||
: payload.contractDigest !== expected.payload.contractDigest ? "contract_digest"
|
||||
: null;
|
||||
if (failed || !actual || !payload || typeof payload.pins?.opencode !== "string") {
|
||||
throw providerPackIncompatible(failed ?? "opencode_pin_missing", "installed provider pack interface or installation is incompatible");
|
||||
}
|
||||
// Launch profiles and recovery receipts bind the selected installation's own
|
||||
// bytes, never the current controller's artifact hashes.
|
||||
for (const [name, expectedArtifact] of Object.entries(expected.payload.artifacts)) {
|
||||
const artifact = payload.artifacts?.[name];
|
||||
if (artifact?.path !== expectedArtifact.path || !/^sha256:[a-f0-9]{64}$/.test(artifact.sha256)) {
|
||||
throw new Error("runner_remote_provider_artifact_incompatible: installed provider pack artifact identity is invalid");
|
||||
throw providerPackIncompatible(`artifact:${name}`, "installed provider pack artifact identity is invalid");
|
||||
}
|
||||
}
|
||||
if (provider.kind === "opencode" && requireCurrentOpenCodeProxy
|
||||
&& payload.artifacts.opencodeProxy?.sha256 !== expected.payload.artifacts.opencodeProxy?.sha256) {
|
||||
throw new Error("runner_remote_provider_artifact_incompatible: installed proxy does not match the requested OpenCode diagnostics");
|
||||
throw providerPackIncompatible("opencode_proxy", "installed proxy does not match the requested OpenCode diagnostics");
|
||||
}
|
||||
if (provider.kind === "acpx") {
|
||||
const agent = provider.agent;
|
||||
@@ -78,7 +99,7 @@ function compatibleInstallation<T extends ProviderPackIdentity>(
|
||||
if (currentProfile ? payload.acpxProfileDigests?.[agent] !== currentProfile
|
||||
: !selected || !installed || ["version", "profileDigest", "closureDigest", "qualification", "path"].some(key =>
|
||||
(installed as Record<string, unknown>)[key] !== (selected as Record<string, unknown>)[key])) {
|
||||
throw new Error("runner_remote_provider_artifact_incompatible: selected ACPX provider profile is incompatible");
|
||||
throw providerPackIncompatible("acpx_profile", "selected ACPX provider profile is incompatible");
|
||||
}
|
||||
}
|
||||
return structuredClone(actual);
|
||||
@@ -112,47 +133,48 @@ export async function verifyRemoteProviderPack<T extends ProviderPackIdentity>({
|
||||
"const path=require('node:path')",
|
||||
"const root=process.argv[1]",
|
||||
"const expected=Buffer.from(process.argv[2],'base64').toString('utf8')",
|
||||
"const actual=fs.readFileSync(path.join(root,'provider-pack.json'),'utf8').trim()",
|
||||
"const fail=(check,detail)=>{fs.writeSync(2,detail+'\\n');fs.writeSync(1,'\\npaperclip-pack-check='+check+'\\n');process.exit(3)}",
|
||||
"let actual;try{actual=fs.readFileSync(path.join(root,'provider-pack.json'),'utf8').trim()}catch{fail('manifest_unreadable','provider pack manifest unreadable')}",
|
||||
"const canonical=(v)=>Array.isArray(v)?'['+v.map(canonical).join(',')+']':v&&typeof v==='object'?'{'+Object.keys(v).sort().map(k=>JSON.stringify(k)+':'+canonical(v[k])).join(',')+'}':JSON.stringify(v)",
|
||||
"const manifest=JSON.parse(actual)",
|
||||
"if(canonical(manifest)!==expected)throw new Error('manifest mismatch')",
|
||||
"const hash=(p)=>'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(path.join(root,p))).digest('hex')",
|
||||
"const tree=(treeRoot)=>{const digest=crypto.createHash('sha256');const visit=(directory,prefix='')=>{for(const entry of fs.readdirSync(directory,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))){const relative=prefix?prefix+'/'+entry.name:entry.name;const absolute=path.join(directory,entry.name);if(entry.isDirectory()){digest.update('directory\\0'+relative+'\\n');visit(absolute,relative)}else if(entry.isFile()){digest.update('file\\0'+relative+'\\0'+'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(absolute)).digest('hex')+'\\n')}else if(entry.isSymbolicLink()){digest.update('symlink\\0'+relative+'\\0'+fs.readlinkSync(absolute)+'\\n')}else throw new Error('unsupported dist entry '+relative)}};visit(treeRoot);return 'sha256:'+digest.digest('hex')}",
|
||||
"for(const name of ['nodeCommand','productionLock','opencodeCommand','opencodeExecutable','opencodeProxy','acpxSidecar','grokLauncher']){const artifact=manifest.payload.artifacts[name];if(hash(artifact.path)!==artifact.sha256)throw new Error(name+' digest mismatch')}",
|
||||
"if(tree(path.join(root,'dist'))!==manifest.payload.distDigest)throw new Error('dist tree digest mismatch')",
|
||||
"for(const candidate of Object.values({...manifest.payload.providers,...manifest.payload.candidateProviders})){if(tree(path.join(root,candidate.path))!==candidate.sha256)throw new Error('candidate asset tree digest mismatch')}",
|
||||
"let manifest;try{manifest=JSON.parse(actual)}catch{fail('manifest_invalid','provider pack manifest invalid')}",
|
||||
"const differing=(a,b)=>[...new Set([...Object.keys(a||{}),...Object.keys(b||{})])].sort().filter(k=>canonical((a||{})[k])!==canonical((b||{})[k]))",
|
||||
"if(canonical(manifest)!==expected){const wanted=JSON.parse(expected);const keys=differing(manifest,wanted).flatMap(k=>k==='payload'?differing(manifest.payload,wanted.payload):k==='digest'?[]:[k]);fail('manifest_mismatch:'+keys.join(',').slice(0,90),'manifest mismatch')}",
|
||||
"const hash=(p)=>{try{return 'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(path.join(root,p))).digest('hex')}catch{return 'unreadable'}}",
|
||||
"const walk=(treeRoot)=>{const digest=crypto.createHash('sha256');const visit=(directory,prefix='')=>{for(const entry of fs.readdirSync(directory,{withFileTypes:true}).sort((a,b)=>a.name.localeCompare(b.name))){const relative=prefix?prefix+'/'+entry.name:entry.name;const absolute=path.join(directory,entry.name);if(entry.isDirectory()){digest.update('directory\\0'+relative+'\\n');visit(absolute,relative)}else if(entry.isFile()){digest.update('file\\0'+relative+'\\0'+'sha256:'+crypto.createHash('sha256').update(fs.readFileSync(absolute)).digest('hex')+'\\n')}else if(entry.isSymbolicLink()){digest.update('symlink\\0'+relative+'\\0'+fs.readlinkSync(absolute)+'\\n')}else throw new Error('unsupported dist entry '+relative)}};visit(treeRoot);return 'sha256:'+digest.digest('hex')}",
|
||||
"const tree=(treeRoot)=>{try{return walk(treeRoot)}catch{return 'unreadable'}}",
|
||||
"for(const name of ['nodeCommand','productionLock','opencodeCommand','opencodeExecutable','opencodeProxy','acpxSidecar','grokLauncher']){const artifact=manifest.payload.artifacts[name];if(hash(artifact.path)!==artifact.sha256)fail('artifact_digest:'+name,name+' digest mismatch')}",
|
||||
"if(tree(path.join(root,'dist'))!==manifest.payload.distDigest)fail('dist_digest','dist tree digest mismatch')",
|
||||
"for(const candidate of Object.values({...manifest.payload.providers,...manifest.payload.candidateProviders})){if(tree(path.join(root,candidate.path))!==candidate.sha256)fail('candidate_digest','candidate asset tree digest mismatch')}",
|
||||
"const version=process.versions.node.split('.').map(Number)",
|
||||
"const minimum=manifest.payload.pins.nodeMinimum.split('.').map(Number)",
|
||||
"if(version[0]<minimum[0]||(version[0]===minimum[0]&&(version[1]<minimum[1]||(version[1]===minimum[1]&&version[2]<minimum[2]))))throw new Error('Node version incompatible')",
|
||||
"if(process.platform!==manifest.payload.target.platform||process.arch!==manifest.payload.target.architecture)throw new Error('provider pack target mismatch')",
|
||||
"const packageVersion=(pkg)=>JSON.parse(fs.readFileSync(path.join(root,'node_modules',...pkg.split('/'),'package.json'),'utf8')).version",
|
||||
"if(version[0]<minimum[0]||(version[0]===minimum[0]&&(version[1]<minimum[1]||(version[1]===minimum[1]&&version[2]<minimum[2]))))fail('node_version','Node version incompatible')",
|
||||
"if(process.platform!==manifest.payload.target.platform||process.arch!==manifest.payload.target.architecture)fail('target','provider pack target mismatch')",
|
||||
"const packageVersion=(pkg)=>{try{return JSON.parse(fs.readFileSync(path.join(root,'node_modules',...pkg.split('/'),'package.json'),'utf8')).version}catch{return null}}",
|
||||
"const expectedPackages={acpx:manifest.payload.pins.acpx,'@agentclientprotocol/claude-agent-acp':manifest.payload.pins.claudeAcp,'@agentclientprotocol/codex-acp':manifest.payload.pins.codexAcp,'opencode-ai':manifest.payload.pins.opencode}",
|
||||
"for(const [pkg,version] of Object.entries(expectedPackages))if(packageVersion(pkg)!==version)throw new Error(pkg+' version mismatch')",
|
||||
"for(const [pkg,version] of Object.entries(expectedPackages))if(packageVersion(pkg)!==version)fail('package_version:'+pkg,pkg+' version mismatch')",
|
||||
].join(";");
|
||||
await runRemoteProviderVerification(() => runner.execute({
|
||||
await withProviderPackCheck("pack", () => runRemoteProviderVerification(() => runner.execute({
|
||||
command: providerNodeCommand,
|
||||
args: ["-e", verifyScript, packRoot, expected],
|
||||
cwd: cwd,
|
||||
bypassSession: true,
|
||||
timeoutMs: 30_000,
|
||||
}), "provider pack verification");
|
||||
}), "provider pack verification"));
|
||||
const opencodeCommand = posix.join(
|
||||
packRoot,
|
||||
manifest.payload.artifacts.opencodeCommand.path,
|
||||
);
|
||||
const opencodeVersion = await runRemoteProviderVerification(() => runner.execute({
|
||||
const opencodeVersion = await withProviderPackCheck("opencode", () => runRemoteProviderVerification(() => runner.execute({
|
||||
command: opencodeCommand,
|
||||
args: ["--version"],
|
||||
cwd: cwd,
|
||||
bypassSession: true,
|
||||
timeoutMs: 30_000,
|
||||
}), "OpenCode version verification");
|
||||
}), "OpenCode version verification"));
|
||||
if (
|
||||
opencodeVersion.stdout.trim() !== manifest.payload.pins.opencode
|
||||
) {
|
||||
throw new Error(
|
||||
"runner_remote_provider_artifact_incompatible: OpenCode version mismatch",
|
||||
);
|
||||
throw providerPackIncompatible("opencode_version", "OpenCode version mismatch");
|
||||
}
|
||||
return structuredClone(manifest);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { createNativeRunTrace } from "./native-run-trace.js";
|
||||
import { prepareVerifiedRemoteProviderPack, useVerifiedPreinstalledRemoteProviderPack, runRemoteProviderVerification, shouldUseBundledAcpxImageAssets } from "./remote-provider-pack.js";
|
||||
|
||||
describe("remote provider verification", () => {
|
||||
@@ -96,6 +97,30 @@ describe("remote provider pack reuse", () => {
|
||||
stageAndVerify.mockResolvedValue(undefined);
|
||||
await expect(prepareVerifiedRemoteProviderPack(input)).resolves.toBe("uploaded");
|
||||
});
|
||||
|
||||
it("records on the selection span why the image pack was not reused", async () => {
|
||||
const trace = createNativeRunTrace({ runId: "provider-pack-select-run", startedAtMs: Date.now() });
|
||||
const annotate = vi.spyOn(trace, "annotate");
|
||||
const rejected = Object.assign(new Error("runner_remote_provider_artifact_incompatible: provider pack verification failed"),
|
||||
{ failureCheck: "manifest_mismatch:runnerSourceRevision" });
|
||||
await expect(prepareVerifiedRemoteProviderPack({
|
||||
trace,
|
||||
verifyStaged: async () => { throw new Error("missing"); },
|
||||
usePreinstalled: onRejected => useVerifiedPreinstalledRemoteProviderPack({
|
||||
candidates: ["/opt/paperclip-runner/provider-pack", "/home/operator/.local/share/paperclip-runner/provider-pack"], onRejected,
|
||||
verifyAndLink: async root => {
|
||||
throw root.startsWith("/opt/") ? rejected : Object.assign(new Error("missing"), { failureCheck: "manifest_unreadable" });
|
||||
},
|
||||
}),
|
||||
stageAndVerify: async () => {},
|
||||
})).resolves.toBe("uploaded");
|
||||
expect(annotate).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
||||
stateSource: "uploaded", reason: "cached_packs_unverified", check: "manifest_mismatch:runnerSourceRevision" }));
|
||||
annotate.mockClear();
|
||||
await prepareVerifiedRemoteProviderPack({ trace, verifyStaged: async () => { throw new Error("missing"); },
|
||||
usePreinstalled: async () => false, stageAndVerify: async () => {} });
|
||||
expect(annotate).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ check: "no_preinstalled_pack" }));
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { redactSensitiveText } from "../../redaction.js";
|
||||
import type { NativeRunTrace } from "./native-run-trace.js";
|
||||
import { nativeRunFailureCheck, type NativeRunTrace } from "./native-run-trace.js";
|
||||
import type { NativeExecutionInput } from "../../vendor/paperclip-runner/index.js";
|
||||
|
||||
/** Qualified ACPX releases carry their Linux image manifest and daemon. */
|
||||
@@ -55,24 +55,27 @@ export async function runRemoteProviderVerification(
|
||||
export async function prepareVerifiedRemoteProviderPack(input: {
|
||||
trace?: NativeRunTrace;
|
||||
verifyStaged: () => Promise<void>;
|
||||
usePreinstalled: () => Promise<boolean>;
|
||||
usePreinstalled: (onRejected: (check: string) => void) => Promise<boolean>;
|
||||
stageAndVerify: () => Promise<void>;
|
||||
}): Promise<"staged" | "preinstalled" | "uploaded"> {
|
||||
const scope = input.trace?.start("provider_pack.select");
|
||||
let failed = false;
|
||||
let preinstalledCheck = "no_preinstalled_pack";
|
||||
const select = async () => {
|
||||
try {
|
||||
await input.verifyStaged();
|
||||
return "staged" as const;
|
||||
} catch {}
|
||||
if (await input.usePreinstalled()) return "preinstalled" as const;
|
||||
let rejected = false;
|
||||
if (await input.usePreinstalled(check => { if (!rejected) preinstalledCheck = check; rejected = true; })) return "preinstalled" as const;
|
||||
await input.stageAndVerify();
|
||||
return "uploaded" as const;
|
||||
};
|
||||
try {
|
||||
const source = scope ? await input.trace!.run(scope, select) : await select();
|
||||
if (scope) input.trace!.annotate(scope, { stateSource: source,
|
||||
reason: source === "uploaded" ? "cached_packs_unverified" : "verified_pack_reused" });
|
||||
reason: source === "uploaded" ? "cached_packs_unverified" : "verified_pack_reused",
|
||||
...(source === "uploaded" ? { check: preinstalledCheck } : {}) });
|
||||
return source;
|
||||
} catch (error) {
|
||||
failed = true;
|
||||
@@ -85,12 +88,14 @@ export async function prepareVerifiedRemoteProviderPack(input: {
|
||||
export async function useVerifiedPreinstalledRemoteProviderPack(input: {
|
||||
candidates: readonly string[];
|
||||
verifyAndLink: (root: string) => Promise<void>;
|
||||
onRejected?: (check: string) => void;
|
||||
}): Promise<boolean> {
|
||||
for (const candidate of input.candidates) {
|
||||
try {
|
||||
await input.verifyAndLink(candidate);
|
||||
return true;
|
||||
} catch {
|
||||
} catch (error) {
|
||||
input.onRejected?.(nativeRunFailureCheck(error) ?? "verification_failed");
|
||||
}
|
||||
}
|
||||
return false;
|
||||
|
||||
@@ -53,10 +53,10 @@ export async function waitForLiveWarmSessionOwner(input: {
|
||||
const finishedAt = prior?.finishedAt ?? null;
|
||||
const retryAt = await liveWarmSessionOwnerRetryAt({ owner, finishedAt,
|
||||
idleTimeoutMs: input.execution.session.lifecyclePolicy.idleTimeoutMs ?? null });
|
||||
if (!retryAt) return;
|
||||
if (!retryAt || !owner.controllerBootId) return;
|
||||
const checkpointedAt = await input.checkpointedAt();
|
||||
if (checkpointedAt && finishedAt && checkpointedAt >= finishedAt) return;
|
||||
throw new NativeControllerRecoveryWaitingError(retryAt);
|
||||
throw new NativeControllerRecoveryWaitingError(retryAt, { runId: input.priorRunId, controllerBootId: owner.controllerBootId });
|
||||
}
|
||||
|
||||
export type RemoteWarmSessionRecovery = {
|
||||
@@ -228,7 +228,9 @@ export async function inspectRemoteWarmSessionRecovery(input: {
|
||||
if (prior.owner.phase !== "committed" || prior.owner.leaseOwner) return deny("owner_unsettled");
|
||||
const liveOwnerRetryAt = await liveWarmSessionOwnerRetryAt({ owner: prior.owner, finishedAt: prior.run.finishedAt,
|
||||
idleTimeoutMs: previous.session?.lifecyclePolicy?.idleTimeoutMs ?? null });
|
||||
if (liveOwnerRetryAt) throw new NativeControllerRecoveryWaitingError(liveOwnerRetryAt);
|
||||
if (liveOwnerRetryAt) {
|
||||
throw new NativeControllerRecoveryWaitingError(liveOwnerRetryAt, { runId: identity.runId, controllerBootId: prior.owner.controllerBootId });
|
||||
}
|
||||
if (sourceProviderLeaseId === providerLeaseId) settledPredecessor = { runId: identity.runId, providerLeaseId };
|
||||
const checkpoint = input.loadCheckpoint(previous);
|
||||
if (!checkpoint || checkpoint.identity.runId !== identity.runId ||
|
||||
|
||||
@@ -177,7 +177,8 @@ if sys.argv[1] != "completion":
|
||||
const read = await executeWorkspaceTool(directory, "workspace_run", { program: "/bin/cat", args: [secret] }, authorize);
|
||||
expect(read).toMatchObject({ exitCode: 1 }); expect(String((read as any).output)).not.toContain("PRIVATE");
|
||||
const write = await executeWorkspaceTool(directory, "workspace_run", { program: "/bin/sh", args: ["-c", 'printf stolen > "$1"', "sh", secret] }, authorize);
|
||||
expect(write).toMatchObject({ exitCode: 1 }); expect(await readFile(secret, "utf8")).toBe("PRIVATE");
|
||||
expect(await readFile(secret, "utf8")).toBe("PRIVATE");
|
||||
expect(write).toMatchObject({ stopped: null, exitCode: expect.any(Number) }); expect((write as { exitCode: number }).exitCode).not.toBe(0);
|
||||
});
|
||||
it.skipIf(!workspaceCommandSandboxAvailable())("stops its owned process on authority loss and bounds output", async () => {
|
||||
const directory = await root(); let calls = 0;
|
||||
|
||||
@@ -14,5 +14,6 @@ export function changedTaskCondition(since: Date) {
|
||||
and t.issue_id = ${issues.id} and t.updated_at >= ${at})
|
||||
or exists (select 1 from issue_comments c where c.company_id = ${issues.companyId}
|
||||
and c.issue_id = ${issues.id} and c.created_at >= ${at})
|
||||
or exists (select 1 from agents ag where ag.id = ${issues.assigneeAgentId} and ag.updated_at >= ${at}))`;
|
||||
or exists (select 1 from agents ag where ag.id = ${issues.assigneeAgentId} and ag.updated_at >= ${at}
|
||||
and (ag.last_heartbeat_at is null or ag.last_heartbeat_at < ag.updated_at)))`;
|
||||
}
|
||||
@@ -64,7 +64,7 @@ export async function settleClaimedWakeRequest(db: Db, record: InProgressRecord,
|
||||
.where(claim).for("update");
|
||||
if (!current) return { settled: false, reason: "claim_no_longer_held" };
|
||||
// Work intents before the write they announce (sleep-aware background work).
|
||||
await notifyExternalConversationSettlement(tx, { companyId: run.companyId });
|
||||
await notifyExternalConversationSettlement(tx, { companyId: run.companyId, runId: run.id });
|
||||
await notifyStrandedAgentStatus(tx, { companyId: run.companyId, agentId: current.agentId });
|
||||
const updated = await tx.update(agentWakeupRequests).set({
|
||||
status: wakeStatusFor(run.status),
|
||||
|
||||
@@ -76,6 +76,8 @@ export function registerIssueRecoveryWork(
|
||||
const scopeKey = (scope: IssueRecoveryScope | undefined) => scope
|
||||
? JSON.stringify([scope.companyId, scope.issueId, scope.graphRunId, scope.graphIssueId, scope.backstop]) : "*";
|
||||
const isGraph = (scope: IssueRecoveryScope | undefined) => Boolean(scope?.graphRunId || scope?.graphIssueId);
|
||||
const loadOrigin = (scope: IssueRecoveryScope | undefined) => !workSignalDebug.enabled ? undefined : !scope ? "reload" as const
|
||||
: scope.backstop ? "backstop" as const : scope.issueId || isGraph(scope) ? "hint" as const : "company" as const;
|
||||
const graphs = new Map<string, { at: number; ids: Promise<string[] | null> }>();
|
||||
async function resolveGraph(scope: IssueRecoveryScope | undefined) {
|
||||
if (!scope || !isGraph(scope)) return;
|
||||
@@ -115,6 +117,7 @@ export function registerIssueRecoveryWork(
|
||||
if (workSignalDebug.enabled) workSignalDebug.event(queue, "load", { scope: key });
|
||||
if (!enabled) { cursors.delete(key); return []; }
|
||||
if (await toCompany(scope, worker)) return { rows: null, complete: true };
|
||||
if (scope?.issueIds?.length === 0) return { rows: [], complete: true };
|
||||
const cursor = cursors.get(key);
|
||||
const changedSince = passes.changedSince(scope, key, !cursor);
|
||||
const rows = await db.select({ id: issues.id, companyId: issues.companyId }).from(issues).where(and(
|
||||
@@ -133,8 +136,7 @@ export function registerIssueRecoveryWork(
|
||||
if (complete) cursors.delete(key); else cursors.set(key, rows.at(-1)!.id);
|
||||
passes.loaded(scope, key, complete);
|
||||
const keepUnseen = changedSince ? { keepUnseen: true as const } : {};
|
||||
const origin = !workSignalDebug.enabled ? undefined : !scope ? "reload" as const : scope.backstop ? "backstop" as const
|
||||
: scope.issueId || isGraph(scope) ? "hint" as const : "company" as const;
|
||||
const origin = loadOrigin(scope);
|
||||
return { rows: rows.map(row => ({ ...row, dueAt: Date.now(), ...(origin ? { origin } : {}) })), complete, ...keepUnseen };
|
||||
},
|
||||
check: async entry => {
|
||||
@@ -172,22 +174,28 @@ export function registerIssueRecoveryWork(
|
||||
const key = scopeKey(scope);
|
||||
if (!enabled) { cursors.delete(key); return []; }
|
||||
if (await toCompany(scope, worker)) return { rows: null, complete: true };
|
||||
if (scope?.issueIds?.length === 0) return { rows: [], complete: true };
|
||||
const changedSince = passes.changedSince(scope, key, !cursors.has(key));
|
||||
const rows = await sweep.listSuspects(scope ? { companyId: scope.companyId, issueId: scope.issueId,
|
||||
issueIds: scope.issueIds, ...(changedSince ? { changedSince } : {}) } : {}, cursors.get(key) ?? null, PAGE_SIZE);
|
||||
const complete = rows.length < PAGE_SIZE;
|
||||
if (complete) cursors.delete(key); else cursors.set(key, rows.at(-1)!.id);
|
||||
passes.loaded(scope, key, complete);
|
||||
const origin = loadOrigin(scope);
|
||||
return { rows: rows.map(row => ({ id: row.id, companyId: row.companyId, updatedAt: row.updatedAt.getTime(), dueAt: Date.now(),
|
||||
...(scope?.backstop ? { fromBackstop: true as const } : {}) })), complete, ...(changedSince ? { keepUnseen: true as const } : {}) };
|
||||
...(scope?.backstop ? { fromBackstop: true as const } : {}), ...(origin ? { origin } : {}) })), complete,
|
||||
...(changedSince ? { keepUnseen: true as const } : {}) };
|
||||
},
|
||||
check: async entry => {
|
||||
if (!enabled) return null;
|
||||
if (workSignalDebug.enabled) workSignalDebug.event(DELIVERY_QUEUES.assignedWorkInvariant, "check", { issueId: entry.id,
|
||||
companyId: entry.companyId, wake: entry.fromDeadline ? "deadline" : entry.origin ?? "load", dueAt: entry.dueAt });
|
||||
let next: number | null = null, unchanged = false;
|
||||
await sweep.checkIssue({ companyId: entry.companyId, issueId: entry.id,
|
||||
onDeferredDeadline: (at, detail) => { next = next === null ? at : Math.min(next, at); unchanged ||= detail?.unchanged === true; } });
|
||||
const { unchanged: _previous, fromBackstop: _source, ...rest } = entry;
|
||||
return next === null ? null : { ...rest, dueAt: next, ...(unchanged ? { unchanged: true as const } : {}) };
|
||||
return next === null ? null : { ...rest, dueAt: next, ...(unchanged ? { unchanged: true as const } : {}),
|
||||
...(workSignalDebug.enabled ? { fromDeadline: true as const } : {}) };
|
||||
},
|
||||
}, canRun);
|
||||
return worker;
|
||||
|
||||
@@ -71,6 +71,7 @@ export async function promoteDeferredWorkIntents(tx: object, input: {
|
||||
.select({ id: budgetPolicies.id }).from(budgetPolicies).where(and(eq(budgetPolicies.companyId, input.companyId),
|
||||
eq(budgetPolicies.isActive, true), eq(budgetPolicies.hardStopEnabled, true))).limit(1)).length > 0 : true;
|
||||
const scope = input.trigger === "lock_released" && input.issueId ? { companyId: input.companyId, issueId: input.issueId }
|
||||
: input.trigger === "lock_released" && input.runId ? { companyId: input.companyId, runId: input.runId }
|
||||
: input.trigger === "accounting_settled" && input.runId && !hardStop ? { companyId: input.companyId, runId: input.runId } : null;
|
||||
// Register the work signals before the write they announce.
|
||||
await notifyRunDispatch(tx, scope ?? { companyId: input.companyId });
|
||||
|
||||
@@ -1861,7 +1861,7 @@ Results can include a `startupReuse` entry for each run. The dashboard shows
|
||||
receipt-derived warmth, the environment/lease, workspace, Runner, provider
|
||||
process and session decisions, and observed provider launches. Private attempt
|
||||
evidence includes `snapshots/startup-reuse.json`. See the
|
||||
[run-log contract](../../doc/run-log-events.md#startup-reuse-evidence) for the
|
||||
[startup reuse receipt](../../packages/adapter-utils/src/startup-reuse.ts) for the
|
||||
closed states and reasons. Historical runs without receipts show unknown
|
||||
values. Provider-session continuity does not establish physical process reuse.
|
||||
|
||||
|
||||
@@ -351,7 +351,7 @@
|
||||
"packages/shared/src/slack-tools.ts": "c53a75cd3099c6d8dcd1475e755aae589d4c88f6",
|
||||
"packages/shared/src/subscriptions.ts": "ef70e63395ca967bbc30776b71560e96eb354a75",
|
||||
"packages/shared/src/summary-slot.test.ts": "5f8e222dea425f0d5bff0adb5c683087bd7cf7fb",
|
||||
"packages/shared/src/telemetry/README.md": "e792827b9f1e629ccdb66eecaad014cd02e532e8",
|
||||
"packages/shared/src/telemetry/README.md": "28125b5ab542abc46c4bb6c044636a093f13584f",
|
||||
"packages/shared/src/telemetry/client-types.test.ts": "3b630edda4972b929ba4decd7457f226eb9cfc5b",
|
||||
"packages/shared/src/telemetry/client.test.ts": "3ba900cdab5a1ac1dcc1dcea382bb790af32d895",
|
||||
"packages/shared/src/telemetry/client.ts": "03a10a5550b542487543fbfd4a417e6eb316e11e",
|
||||
|
||||
Reference in new issue
Block a user