mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-30 17:14:54 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - During a release swap, the outgoing server stops and the incoming server takes over the live runs on remote Runners > - The incoming server reached those runs late: it waited up to 60 s for the outgoing server's controller lease to lapse, re-verified each run's whole log from object storage, and deferred a reattach when the agent directory was busy. Queued starts competed with the reattaches for the same resources. > - On hosted staging, the later a live run was reached, the more likely it was to fail. Runs reached in under 150 s never failed; runs reached after 420 s almost always failed. > - This pull request hands live runs over at the start of shutdown, makes a reattach skip work that the same run already did, and holds queued starts while handed-over runs are being reached, with a 180 s cap. > - The benefit is that live runs are reached within seconds of a swap instead of minutes, so they continue instead of failing. ## Linked Issues or Issue Description **What happened?** Hosted staging, release swaps on 2026-11-13 (06:05Z to 09:45Z). For each run that crossed a swap we measured the gap from the last Runner output to the moment the new server recorded the Runner's process identity: - gap under 150 s: 0 of 9 runs failed - gap over 420 s: 14 of 15 runs failed - median gap: 180 s for runs that resumed, 470 s for runs that failed In one traced run the incoming server waited on `remote_controller_lease_live` three times (09:14:21, 09:15:18, 09:16:17), claimed at 09:16:59, and spent 85 s in `task.prepare`. Of that, `heartbeat.prepare.run_output` took 58.7 s, because it re-read the run's whole log from object storage. A control run spent 23 s in `task.prepare`. Queued starts used the same preparation path, the same 8 object-I/O slots and the same database pool, and nothing gave a reattach priority. The first-attempt failures were `PRP command session.snapshot timed out` and `codex_history_read_failed`. The retry then failed with `runner_harness_state_mismatch: resumed_not_suspended`, `runner_remote_process_identity_unavailable` or `provider_turn_lost_on_restore`. **Expected behavior** Every live run is reached within about 30 s of the swap. Queued work starts after that, or after a bounded wait. **Steps to reproduce** 1. Run a two-server release swap with live remote runs and queued runs. 2. Observe `native.recovery.transition` "waiting" events with `remote_controller_lease_live`, then the claim, then a long `heartbeat.prepare.run_output` span. 3. The new tests in `reattach-phase.test.ts` and `heartbeat-native-early-hand-off.test.ts` model this. **Paperclip version or commit** `master` at426e8a35dc. ## What Changed - Early hand-off at shutdown (`heartbeat/recovery.ts`, `server/src/index.ts`): in deploy-overlap mode, the outgoing server releases the remote controller lease of its live runs at SIGTERM (`recoveryState` `awaiting_runner_reattach`). A run another server already took over is left alone. The incoming server no longer waits for the lease to lapse. - Reattach fast path: - `heartbeat/run-output.ts`, `native-runtime/native-run-log-export.ts`: a reattach starts without waiting for the existing log to be re-verified. - `heartbeat/agent-directory-busy.ts`, `heartbeat.ts`: a reattach that meets a busy agent directory waits in process (at most 30 s) instead of being deferred to a full re-preparation. An ordinary start is still deferred at once, with no added wait. - Reattach phase lifecycle (`heartbeat/reattach-phase.ts`): the watch is a worker on the shared delivery coordinator, queue `reattach-phase`. - Trigger: one startup listing of a previous server's live runs; then the hand-over notification (`notifyReattachHandOver`, sent in the hand-over transaction); the earliest lease deadline it watches (a killed owner); and a 2 s re-check only while handed-over runs are still pending, which ends with the phase (cap 180 s). The bounded re-check exists because a run can also end on another path that sends no notification to this queue. - Source of truth: `native_run_finalizations` and `heartbeat_runs` rows. - Quiet condition: nothing pending and no watched lease, so no deadline and no SQL. It stops with the coordinator at shutdown. - Reached hook for every driver (`native-session-executor.ts`): a reattached run counts as reached when the native session runtime hands the executor its recovered or opened session (`onSession`). Every driver reaches that point only after the Runner answered this server's attach and recovery commands, including an adopted `RunnerdExternalDriver` Runner, which records no new process identity. The identity hook stays as an earlier signal. - Claim wake: when the reattach-phase worker finds runs that just became claimable (hand-over notification or a killed owner's lease deadline), it starts this server's restart-recovery claim for them at once. A validation cell showed the claim otherwise waited about 21.5 s after the hand-over. - `recovery/assigned-work-sweep.ts`: the `deferred_reattach_phase` return now sits before every action path of `act()`, except starting an overdue saved-work recovery (it resumes an existing run). - The in-transaction admission re-check of a queued claim (`confirmRunAdmissionStillOpen`) also honours the reattach phase. A phase that begins during a claim returns the run to the queue through the existing rollback. - A reattach whose log re-verification runs in the background awaits it before the log is finalized (`settleDeferredLogRecovery`, both finalization sites in `run-completion.ts`). - Reattach phase (`heartbeat/reattach-phase.ts`, `heartbeat/run-admission.ts`): `isReattachPhaseActive()` is true while runs that a previous controller handed over (lease released or observed expired, or claimed by this server's restart recovery) are claimable but not yet reached. A run is reached when its process identity is recorded. Authentication is logged as a mark. The cap (180 s, `PAPERCLIP_REATTACH_PHASE_CAP_MS`) counts from the moment the runs became claimable. Later batches join or re-arm the phase. Runs reached after 150 s are counted and logged. - Gates on the phase: - `claimQueuedRun`, start-next, resume-queued and dispatch in `heartbeat/queue.ts`, `run-lifecycle.ts` and `native-runner-execution-driver.ts` leave queued runs queued. - `execution-recovery-resolution.ts`: one line, the first line of `deliverReconciledExecutions`. - `recovery/assigned-work-sweep.ts`: one line, outcome `deferred_reattach_phase`. - `heartbeat/recovery.ts`: a one-line claim hook (`noteReattachRunsClaimed`) after restart recovery claims runs. - The owner of those three files agreed to these one-line gates. - `tests/restart-chaos/daytona-image.ts`: `PAPERCLIP_CHAOS_TEST_ACCEPT_IMAGE_CONTENT_ID` lets a local wave run a controller-only branch against an existing Daytona image. It accepts a content-ID mismatch only for the exact content ID of the named image, and it prints a TEST OVERRIDE warning. This is harness-only. ## Verification Red on master, green on this branch: - `heartbeat/reattach-phase.test.ts` (27 tests). Five of the six two-server scenarios were red on the earlier phase timing: - `does not hold queued starts while the previous owner is alive and not handing over` - `closes the gate when the previous owner hands its runs over, and counts reach latency from the hand-over` - `runs the cap from the hand-over, so a wedged run ends the phase without the overlap eating it` - `begins when a killed owner's lease is observed expired, without any hand-over` - `re-arms for a later batch, including runs the previous owner started after discovery` - `closes the gate at once when this server claims a run between two lease reads, dated from the hand-over` - plus `claimQueuedRun leaves a queued run queued and unstarted, in the admission gate's shape`, `is the same gate the assigned-work sweep and reconciled continuation delivery read`, `ends at the cap, counted from when the runs became claimable, so one wedged Runner cannot hold run starts` - `heartbeat-native-early-hand-off.test.ts`: `releases the remote controller lease of %i live runs at once` (1, 20, 40 runs; 40 runs in 56 ms), `leaves a run another server already took over alone`, `holds the incoming server's queued starts only from the hand-over, not while the outgoing server still drives its runs` - `heartbeat/run-output.test.ts`: `lets a reattach start before its existing log is re-verified` - `heartbeat/agent-directory-busy.test.ts`: `defers an ordinary start at once, with no wait added to the run-start path`, `lets a reattach wait its turn in process instead of a deferred full re-preparation`, `still defers a reattach once its bounded wait runs out` - `tests/restart-chaos/daytona-image.test.ts`: `accepts a mismatch only for the exact image content ID named by the test override` - Review fixes (red before the fix, green after): `reattach-phase.test.ts` `starts the claim of handed-over runs within a second of the hand-over notification`; `assigned-work-invariant.test.ts` `takes no action while handed-over live runs are being reached, and acts once the phase ends`; `heartbeat-native-early-hand-off.test.ts` `never lets the outgoing server claim back a run it handed off, while the incoming server may take it over`; `reattach-phase.test.ts` `retries a failed first listing instead of going quiet, and still finds the previous owner's runs`, `keeps a hand-over notification whose listing failed until a listing succeeds`, `moves the cap earlier when a claimed run turns out to have been handed over before its claim`; `queue.test.ts` `returns the claim to the queue when a reattach phase begins while the claim is being checked`; `run-completion.test.ts` `finalizes the run log in completeRun|failRun only after a reattach's deferred log recovery settles`. `native-session-executor.test.ts` `ends the reattach phase once a reattached %s session is driven by this server again, without the cap or manual settling` over codex_app_server, opencode_server, acpx_runtime, muse_external, grok_bot_mcp and openai_dot_mcp (6 of 6 red without the hook; the test drives the executor with a mocked session runtime, not each real driver). Lifecycle tests for the new worker: `does no database work and keeps no deadline on an instance with nothing to reattach`, `waits for the hand-over notification or the lease deadline instead of polling while the previous owner drives its runs`, `begins at a killed owner's lease deadline, without any hand-over or notification`, `stops with the delivery coordinator at shutdown and ignores a later hand-over`. Local runs on this branch: `tsc --noEmit` is clean for `server`. Passing on this branch: `reattach-phase.test.ts`, `heartbeat-native-early-hand-off.test.ts`, `run-output.test.ts` (53 tests together), `agent-directory-busy.test.ts`, `heartbeat-native-restart-suspension.test.ts` (115 of 115, alone), the new cases in `queue.test.ts` and `run-completion.test.ts`. Under load 30 to 96 on this shared machine, the full `queue.test.ts` and `recovery-wake-herd.test.ts` runs stalled in their embedded-Postgres setup; CI supplies them. Daytona results that exist (local servers with Daytona sandboxes, release-swap cells). They ran on a combined branch with this PR, #21462, #21442 and #21362 (merged), so they cannot be credited to this PR alone: - G5 baseline (masterd1d71a7755): SIGTERM to PRP authentication 21.5 to 38 s at swap 1. - G5c (combined branch 588c6ba267): SIGTERM to authentication 6.2 to 7.7 s at swap 1. All runs that crossed swap 2 were adopted on the same Runner process. The staging chain (`provider recovery timed out after 900000ms`, then `resumed_not_suspended`) did not recur. - Caveat: G5c ran before the phase timing fix in this PR. In G5c the phase opened at process start, its 180 s cap ran out during the overlap, and swap 2 ended `cap_reached` with 0 runs reached, 1 s before the lease claims. The timing fix (the phase begins when the runs become claimable) has not run on Daytona. - G6c (12 live runs and 20 queued, two graceful swaps, no injection, combined branch 588c6ba267): 0 failed runs at either swap; 11 of 11 survivors at both. - Swap 1: hand-off of 11 runs in 291 ms; claims 0.3 to 2.9 s after hand-off; authentication 7.6 to 12.5 s and identity 8.3 to 13.3 s after SIGTERM. The 30 s target was met. - Swap 2: hand-off took 8,562 ms and `hot_restart_prepare` timed out at 19 s, so the outgoing server drained gracefully. The incoming server did not claim on the hand-over; it claimed only when the outgoing server exited, 33 s after SIGTERM. Authentication was 46 to 54 s and identity 47 to 57 s after SIGTERM. The target was missed. Why the claims waited for the exit is not explained. - The host load was 49 to 70 from other work. 7 of 32 tasks timed out in the queue or budget after the swaps; we suspect the overload. ## Risks - Product trade-off: while handed-over live runs are being reached, queued starts wait, up to the 180 s cap. On an instance with no handed-over runs, nothing waits. - Not proven: two-server behavior with the phase timing fix and the notification-driven watch (no cell has run them); warm standby becoming active; runs that the outgoing server starts after discovery. - Early hand-off at SIGTERM orphans a server-side exec tool that is in flight. With #21442 the next controller settles it as interrupted with an unknown outcome; it is never run again. - Swap 2 in G6c: the incoming server claimed only at the outgoing server's exit. That is unexplained. - Cross-session ownership: the gates in `execution-recovery-resolution.ts` and `recovery/assigned-work-sweep.ts`, and the claim hook in `heartbeat/recovery.ts`, are in files that the restart-recovery work owns. They are one-line gates agreed with that owner. That owner said the gate did not need to be inside the claim transaction; that was before the phase could begin during a claim. After review, the in-transaction re-check in `heartbeat/queue.ts` also reads the phase, through the existing rollback. #21427 (open) also edits `execution-recovery-resolution.ts`, `heartbeat/queue.ts` and `recovery/assigned-work-sweep.ts`; whichever merges second needs a rebase. `native-runtime/native-restart-recovery.ts` (claim logic, owned by the restart-recovery work): a 3-line guard in `claimNativeRestartRecoveries` returns a run this process handed off at shutdown as `blocked` / `handed_off_to_next_controller` before takeover is evaluated, so the outgoing server never claims back a run it handed off. #21478 (merged) added a sweep path that starts an overdue saved-work recovery; it is deliberately not gated by the reattach phase, because it resumes an existing run (reattach-like work), which the phase makes room for rather than competes with. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, with tool use and code execution in Claude Code. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
525 lines
25 KiB
TypeScript
525 lines
25 KiB
TypeScript
import { NativeSessionDiagnostics } from "../native-runtime/native-session-diagnostics.js";
|
|
import { withS3FailureDiagnostics } from "../../storage/s3-failure.js";
|
|
import { objectLogFixture } from "./__tests__/object-log-fixture.js";
|
|
import { promises as fs } from "node:fs";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { Readable } from "node:stream";
|
|
import type { Db, heartbeatRuns } from "@paperclipai/db";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { createDurableRunLogStore } from "../run-log-store.js";
|
|
import type { StorageProvider } from "../../storage/types.js";
|
|
import { createHeartbeatRunOutput, isNewRunLog } from "./run-output.js";
|
|
import { createAgentIdentityRedactor, secretEnvironmentValues } from "../agent-identity-redaction.js";
|
|
import { formatNativeRunLogEvent } from "../native-runtime/native-run-log-export.js";
|
|
import { generateKeyPairSync } from "node:crypto";
|
|
import { reportStorageOutageWaitsTo, runInOwnStorageScope } from "../../storage/storage-unavailable.js";
|
|
import { clearAllHeartbeatRunRuntimeStatuses, getHeartbeatRunRuntimeStatus } from "../heartbeat-run-runtime-status.js";
|
|
import { createStorageWaitNotice, STORAGE_WAIT_PHASE } from "./storage-wait-notice.js";
|
|
|
|
vi.mock("../live-events.js", () => ({ publishLiveEvent: vi.fn() }));
|
|
|
|
type Run = typeof heartbeatRuns.$inferSelect;
|
|
|
|
function createMemoryProvider() {
|
|
const objects = new Map<string, Buffer>();
|
|
const calls = { head: 0, get: 0 };
|
|
const provider: StorageProvider = {
|
|
id: "s3",
|
|
async putObject(input) {
|
|
const chunks: Buffer[] = [];
|
|
for await (const chunk of Readable.from(input.body)) chunks.push(Buffer.from(chunk));
|
|
objects.set(input.objectKey, Buffer.concat(chunks));
|
|
},
|
|
async getObject(input) {
|
|
calls.get++;
|
|
const buf = objects.get(input.objectKey)!;
|
|
return { stream: Readable.from(buf), contentLength: buf.length };
|
|
},
|
|
async headObject(input) {
|
|
calls.head++;
|
|
const buf = objects.get(input.objectKey);
|
|
return buf ? { exists: true, contentLength: buf.length } : { exists: false };
|
|
},
|
|
async deleteObject(input) {
|
|
objects.delete(input.objectKey);
|
|
},
|
|
};
|
|
return { provider, objects, calls };
|
|
}
|
|
|
|
// The recorder persists the handle with update().set().where(); capture it the
|
|
// way the run row would carry it into a later attempt.
|
|
function createRunRowDb(row: Partial<Run>) {
|
|
return {
|
|
async transaction<T>(write: (tx: Db) => Promise<T>): Promise<T> { return write(this as unknown as Db); },
|
|
update: () => ({
|
|
set: (values: Partial<Run>) => ({
|
|
where: async () => {
|
|
Object.assign(row, values);
|
|
},
|
|
}),
|
|
}),
|
|
} as unknown as Db;
|
|
}
|
|
|
|
const newRunRow = {
|
|
id: "run-1",
|
|
companyId: "company-1",
|
|
agentId: "agent-1",
|
|
status: "running",
|
|
logStore: null,
|
|
logRef: null,
|
|
logBytes: null,
|
|
lastOutputSeq: 0,
|
|
lastOutputAt: null,
|
|
} as Partial<Run>;
|
|
|
|
describe("claiming the run log during a storage outage (storage chaos ST1)", () => {
|
|
const outage = () => withS3FailureDiagnostics("put_object", async () => {
|
|
throw Object.assign(new Error("Injected storage outage"), { name: "ServiceUnavailable", $metadata: { httpStatusCode: 503 } });
|
|
});
|
|
const output = (begin: () => Promise<never | { store: "s3_segments"; logRef: string }>, signal?: AbortSignal) =>
|
|
createHeartbeatRunOutput(createRunRowDb({ ...newRunRow }), { run: newRunRow as Run, runId: "run-1", issueId: null,
|
|
runLogStore: { begin, append: async () => 0, enqueue: async () => ({ committed: Promise.resolve(0) }), flush: async () => undefined },
|
|
identityRedactor: { chunk: (_stream, chunk) => chunk, redact: value => value }, secretKeys: new Set(),
|
|
appendRunEvent: vi.fn(), getCurrentUserRedactionOptions: async () => ({ enabled: false }), signal });
|
|
|
|
it("claims the log once the store is back instead of failing the run", async () => {
|
|
let calls = 0;
|
|
const begin = vi.fn(async () => (++calls < 2 ? outage() : { store: "s3_segments" as const, logRef: "company/agent/run" }));
|
|
await output(begin).begin({ ...newRunRow } as Run);
|
|
expect(begin).toHaveBeenCalledTimes(2);
|
|
}, 30_000);
|
|
|
|
it("shows the wait as live status and writes nothing to the run while its log claim waits", async () => {
|
|
clearAllHeartbeatRunRuntimeStatuses();
|
|
const row = { ...newRunRow, contextSnapshot: { issueId: "issue-1" } } as Partial<Run>;
|
|
const writes: Partial<Run>[] = [];
|
|
const db = createRunRowDb(row);
|
|
const update = db.update.bind(db);
|
|
(db as { update: unknown }).update = (table: unknown) => {
|
|
const pending = (update as (t: unknown) => { set: (v: Partial<Run>) => unknown })(table);
|
|
return { set: (values: Partial<Run>) => { writes.push(values); return pending.set(values); } };
|
|
};
|
|
const appendRunEvent = vi.fn(async (_run: unknown, _event: { payload?: { reason?: string } }) => undefined);
|
|
const authority = vi.fn(async () => undefined);
|
|
const seen: Array<{ writes: number; events: number; phase: string | undefined; message: string | undefined }> = [];
|
|
let calls = 0;
|
|
const begin = vi.fn(async (input: { assertWriterAuthority?: () => Promise<void> }) => {
|
|
const status = getHeartbeatRunRuntimeStatus("run-1", { companyId: "company-1", agentId: "agent-1" });
|
|
seen.push({ writes: writes.length, events: appendRunEvent.mock.calls.length, phase: status?.phase, message: status?.message });
|
|
if (++calls < 3) return outage();
|
|
await input.assertWriterAuthority?.();
|
|
return { store: "s3_segments" as const, logRef: "company/agent/run" };
|
|
});
|
|
const recorder = createHeartbeatRunOutput(db, { run: row as Run, runId: "run-1", issueId: "issue-1",
|
|
runLogStore: { begin, append: async () => 0, enqueue: async () => ({ committed: Promise.resolve(0) }), flush: async () => undefined },
|
|
identityRedactor: { chunk: (_stream, chunk) => chunk, redact: value => value }, secretKeys: new Set(),
|
|
appendRunEvent: appendRunEvent as never, getCurrentUserRedactionOptions: async () => ({ enabled: false }),
|
|
assertWriterAuthority: authority });
|
|
await runInOwnStorageScope(async () => {
|
|
reportStorageOutageWaitsTo(createStorageWaitNotice({ run: row as Run, appendRunEvent: appendRunEvent as never }));
|
|
await recorder.begin(row as Run);
|
|
});
|
|
await new Promise(resolve => setImmediate(resolve));
|
|
expect(begin).toHaveBeenCalledTimes(3);
|
|
expect(authority).toHaveBeenCalledTimes(1);
|
|
expect(seen.slice(1)).toEqual([
|
|
expect.objectContaining({ writes: 0, events: 0, phase: STORAGE_WAIT_PHASE, message: expect.stringContaining("before starting the run log") }),
|
|
expect.objectContaining({ writes: 0, events: 0, phase: STORAGE_WAIT_PHASE }),
|
|
]);
|
|
expect(writes).toEqual([expect.objectContaining({ logStore: "s3_segments", logRef: "company/agent/run" })]);
|
|
expect(appendRunEvent).toHaveBeenCalledTimes(1);
|
|
expect(appendRunEvent).toHaveBeenCalledWith(row, expect.objectContaining({ eventType: "lifecycle",
|
|
message: expect.stringMatching(/^Waited \d+s for file storage before starting the run log\.$/),
|
|
payload: expect.objectContaining({ reason: "storage_outage_wait", recovered: true }) }));
|
|
expect(getHeartbeatRunRuntimeStatus("run-1", { companyId: "company-1", agentId: "agent-1" })?.phase).toBe("run_activity");
|
|
}, 30_000);
|
|
|
|
it("stops waiting as soon as the run is stopped", async () => {
|
|
const stop = new AbortController();
|
|
const begin = vi.fn(async () => outage());
|
|
setTimeout(() => stop.abort(new Error("Stopped by a board operator")), 100);
|
|
const startedAt = Date.now();
|
|
await expect(output(begin, stop.signal).begin({ ...newRunRow } as Run)).rejects.toBeTruthy();
|
|
expect(Date.now() - startedAt).toBeLessThan(1_500);
|
|
}, 30_000);
|
|
});
|
|
|
|
async function beginAttempt(store: ReturnType<typeof createDurableRunLogStore>, row: Partial<Run>) {
|
|
const output = createHeartbeatRunOutput(createRunRowDb(row), {
|
|
run: row as Run,
|
|
runId: row.id!,
|
|
issueId: null,
|
|
runLogStore: store,
|
|
identityRedactor: { chunk: (_stream, chunk) => chunk, redact: (value) => value },
|
|
secretKeys: new Set(),
|
|
appendRunEvent: vi.fn(),
|
|
getCurrentUserRedactionOptions: async () => ({ enabled: false }),
|
|
});
|
|
const { onLog } = await output.begin({ ...row } as Run);
|
|
return { output, onLog };
|
|
}
|
|
|
|
let baseDir: string;
|
|
beforeEach(async () => {
|
|
baseDir = await fs.mkdtemp(path.join(os.tmpdir(), "run-output-test-"));
|
|
});
|
|
afterEach(async () => {
|
|
await fs.rm(baseDir, { recursive: true, force: true });
|
|
});
|
|
|
|
describe("heartbeat run output log recovery", () => {
|
|
it("keeps active diagnostic identity and current-user redaction while idle retention stays content-free", async () => {
|
|
const row = { ...newRunRow }, store = objectLogFixture(), idle = vi.fn();
|
|
const owner = { companyId: row.companyId!, runId: row.id!, sessionScope: "synthetic-session" };
|
|
const events = vi.fn(async () => undefined);
|
|
const output = createHeartbeatRunOutput(createRunRowDb(row), { run: row as Run, runId: row.id!, issueId: null,
|
|
runLogStore: store, identityRedactor: createAgentIdentityRedactor("SYNTHETIC_PRIVATE_KEY"), secretKeys: new Set(), appendRunEvent: events,
|
|
getCurrentUserRedactionOptions: async () => ({ enabled: true, userNames: ["synthetic-user"], homeDirs: ["/home/synthetic-user"] }) });
|
|
const handlers = await output.begin(row as Run);
|
|
const channel = new NativeSessionDiagnostics(owner, owner, idle, vi.fn());
|
|
const lease = channel.activate(owner, handlers.onLog);
|
|
const text = "diagnostic SYNTHETIC_PRIVATE_KEY /home/synthetic-user/data synthetic-user\n";
|
|
channel.record(text);
|
|
lease.retire();
|
|
const summary = await store.finalize(output.handle!);
|
|
const before = await store.read(output.handle!, { limitBytes: 65536 });
|
|
expect(summary.bytes).toBe(Buffer.byteLength(before.content));
|
|
expect(before.content).toContain("diagnostic");
|
|
for (const value of ["SYNTHETIC_PRIVATE_KEY", "synthetic-user"]) expect(before.content).not.toContain(value);
|
|
channel.record(text);
|
|
expect(idle).toHaveBeenCalledWith(owner, "session_diagnostic");
|
|
expect(JSON.stringify(idle.mock.calls)).not.toContain("synthetic-user");
|
|
expect(JSON.stringify(idle.mock.calls)).not.toContain("SYNTHETIC_PRIVATE_KEY");
|
|
expect((await store.read(output.handle!, { limitBytes: 65536 })).content).toBe(before.content);
|
|
expect(events).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it.each(["enqueue", "progress", "export"] as const)("still warns for a genuine %s failure", async phase => {
|
|
const row = { ...newRunRow }, events = vi.fn(async () => undefined);
|
|
const base = createRunRowDb(row);
|
|
const db = { ...base,
|
|
select: () => { throw new Error("synthetic canonical-source read failure"); },
|
|
update: () => ({ set: (values: Partial<Run>) => ({ where: async () => {
|
|
if (phase === "progress" && values.lastOutputSeq !== undefined) throw new Error("synthetic progress write failure");
|
|
Object.assign(row, values);
|
|
} }) }),
|
|
} as unknown as Db;
|
|
const output = createHeartbeatRunOutput(db, { run: row as Run, runId: row.id!, issueId: null,
|
|
runLogStore: { begin: async () => ({ store: "s3_segments", logRef: "synthetic-company/agent/run" }),
|
|
append: async () => 10, enqueue: async () => {
|
|
if (phase === "enqueue") throw new Error("synthetic object admission failure");
|
|
return { committed: Promise.resolve(10) };
|
|
}, flush: async () => undefined },
|
|
identityRedactor: { chunk: (_stream, chunk) => chunk, redact: value => value }, secretKeys: new Set(),
|
|
appendRunEvent: events, getCurrentUserRedactionOptions: async () => ({ enabled: false }) });
|
|
const handlers = await output.begin(row as Run);
|
|
if (phase === "export") await handlers.onPersistedNativeLog!(1, "synthetic canonical source");
|
|
else {
|
|
const owner = { companyId: row.companyId!, runId: row.id!, sessionScope: "synthetic-session" };
|
|
const channel = new NativeSessionDiagnostics(owner, owner, vi.fn(), vi.fn());
|
|
const lease = channel.activate(owner, handlers.onLog);
|
|
channel.record("accepted active diagnostic");
|
|
lease.retire();
|
|
}
|
|
await vi.waitFor(() => expect(events).toHaveBeenCalledWith(expect.objectContaining({ id: row.id, companyId: row.companyId }),
|
|
expect.objectContaining({ level: "warn", payload: { reason: "object_log_persistence_failed" } })));
|
|
});
|
|
|
|
it("treats only a run row with no recorded log or output as new", () => {
|
|
expect(isNewRunLog({ logStore: null, logRef: null, logBytes: null, lastOutputSeq: 0 })).toBe(
|
|
true,
|
|
);
|
|
expect(
|
|
isNewRunLog({
|
|
logStore: "local_file",
|
|
logRef: "c/a/r.ndjson",
|
|
logBytes: null,
|
|
lastOutputSeq: 0,
|
|
}),
|
|
).toBe(false);
|
|
expect(
|
|
isNewRunLog({ logStore: null, logRef: "c/a/r.ndjson", logBytes: null, lastOutputSeq: 0 }),
|
|
).toBe(false);
|
|
expect(isNewRunLog({ logStore: null, logRef: null, logBytes: null, lastOutputSeq: 3 })).toBe(
|
|
false,
|
|
);
|
|
expect(isNewRunLog({ logStore: null, logRef: null, logBytes: 120, lastOutputSeq: 0 })).toBe(
|
|
false,
|
|
);
|
|
});
|
|
|
|
it("makes no remote log recovery request for a new run", async () => {
|
|
const { provider, calls } = createMemoryProvider();
|
|
const store = createDurableRunLogStore({ basePath: baseDir, s3: { provider } });
|
|
const row = { ...newRunRow };
|
|
const { onLog } = await beginAttempt(store, row);
|
|
await onLog("stdout", "hello\n");
|
|
expect(calls).toEqual({ head: 0, get: 0 });
|
|
expect(row.logRef).toBe(path.join("company-1", "agent-1", "run-1.ndjson"));
|
|
});
|
|
|
|
it("restores an existing attempt's durable log after local state is lost", async () => {
|
|
const { provider, objects, calls } = createMemoryProvider();
|
|
const row = { ...newRunRow };
|
|
const firstStore = createDurableRunLogStore({ basePath: baseDir, s3: { provider } });
|
|
const first = await beginAttempt(firstStore, row);
|
|
await first.onLog("stdout", "attempt one\n");
|
|
await firstStore.finalize(first.output.handle!);
|
|
expect(calls).toEqual({ head: 0, get: 0 });
|
|
|
|
// Process restart on a new pod: local logs and in-memory state are gone,
|
|
// but the run row still records the earlier attempt's log.
|
|
await fs.rm(baseDir, { recursive: true, force: true });
|
|
const restartedStore = createDurableRunLogStore({ basePath: baseDir, s3: { provider } });
|
|
const second = await beginAttempt(restartedStore, row);
|
|
expect(calls).toEqual({ head: 1, get: 1 });
|
|
await second.onLog("stdout", "attempt two\n");
|
|
await restartedStore.finalize(second.output.handle!);
|
|
|
|
const lines = objects
|
|
.get(row.logRef!)!
|
|
.toString()
|
|
.trim()
|
|
.split("\n")
|
|
.map((line) => JSON.parse(line));
|
|
expect(lines.map((line) => line.chunk)).toEqual(["attempt one\n", "attempt two\n"]);
|
|
expect(lines.map((line) => line.seq)).toEqual([1, 2]);
|
|
});
|
|
});
|
|
|
|
describe("object-backed diagnostic recording", () => {
|
|
it.each(["legacy", "native"])("applies identity redaction before S3 admission when output begins in %s mode", async (runtimeMode) => {
|
|
const privateKeyPem = generateKeyPairSync("ed25519")
|
|
.privateKey.export({ type: "pkcs8", format: "pem" })
|
|
.toString();
|
|
const row = { ...newRunRow, runtimeMode } as Run;
|
|
const db = createRunRowDb(row) as Db & { select: () => unknown };
|
|
db.select = (() => ({
|
|
from: () => ({ where: () => ({ orderBy: () => ({ limit: async () => [] }) }) }),
|
|
})) as typeof db.select;
|
|
const chunks: string[] = [];
|
|
const output = createHeartbeatRunOutput(db, {
|
|
run: row,
|
|
runId: row.id,
|
|
issueId: null,
|
|
secretKeys: new Set(),
|
|
identityRedactor: createAgentIdentityRedactor(privateKeyPem),
|
|
runLogStore: {
|
|
begin: async () => ({
|
|
store: "s3_segments",
|
|
logRef: "company/agent/run",
|
|
initialSourceCursor: 0,
|
|
}),
|
|
append: async () => 0,
|
|
enqueue: async (_handle, event) => {
|
|
chunks.push(event.chunk);
|
|
return { committed: Promise.resolve(100) };
|
|
},
|
|
flush: async () => undefined,
|
|
},
|
|
appendRunEvent: vi.fn(),
|
|
getCurrentUserRedactionOptions: async () => ({ enabled: false }),
|
|
});
|
|
const handlers = await output.begin(row);
|
|
await handlers.onPersistedNativeLog!(
|
|
1,
|
|
formatNativeRunLogEvent({
|
|
schema: "paperclip.prp.event.v1",
|
|
schemaVersion: 1,
|
|
runId: row.id,
|
|
sourceEventId: "source:1",
|
|
sourceInstanceId: "source",
|
|
sourceKind: "runner",
|
|
sourceSeq: 1,
|
|
normalizedSessionId: "session",
|
|
eventType: "harness.diagnostic",
|
|
priority: 1,
|
|
emittedAt: new Date().toISOString(),
|
|
payload: { text: privateKeyPem },
|
|
}),
|
|
);
|
|
expect(chunks).toHaveLength(1);
|
|
expect(chunks[0]).not.toContain(privateKeyPem.split("\n")[1]!);
|
|
expect(chunks[0]).toContain("REDACTED");
|
|
});
|
|
it("admits a burst without serial network waits, publishes after receipts, and coalesces progress", async () => {
|
|
const { publishLiveEvent } = await import("../live-events.js");
|
|
vi.mocked(publishLiveEvent).mockClear();
|
|
const row = { ...newRunRow };
|
|
const writes: Array<Partial<Run>> = [];
|
|
const db = {
|
|
async transaction<T>(write: (tx: Db) => Promise<T>): Promise<T> { return write(this as unknown as Db); },
|
|
update: () => ({
|
|
set: (values: Partial<Run>) => ({
|
|
where: async () => {
|
|
writes.push(values);
|
|
Object.assign(row, values);
|
|
},
|
|
}),
|
|
}),
|
|
} as unknown as Db;
|
|
const commit: Array<() => void> = [];
|
|
const recorder = createHeartbeatRunOutput(db, {
|
|
run: row as Run,
|
|
runId: row.id!,
|
|
issueId: null,
|
|
runLogStore: {
|
|
begin: async () => ({
|
|
store: "s3_segments",
|
|
logRef: "company/agent/run",
|
|
initialBytes: 0,
|
|
initialSequence: 10,
|
|
}),
|
|
append: () => new Promise<number>((resolve) => commit.push(() => resolve(100))),
|
|
},
|
|
identityRedactor: { chunk: (_stream, chunk) => chunk, redact: (value) => value },
|
|
secretKeys: new Set(),
|
|
appendRunEvent: vi.fn(),
|
|
getCurrentUserRedactionOptions: async () => ({ enabled: false }),
|
|
});
|
|
const { onLog } = await recorder.begin(row as Run);
|
|
for (let i = 0; i < 100; i++) await onLog("stdout", `line ${i}\n`);
|
|
expect(commit).toHaveLength(100);
|
|
expect(publishLiveEvent).not.toHaveBeenCalled();
|
|
for (const resolve of commit) resolve();
|
|
await vi.waitFor(() =>
|
|
expect(
|
|
vi
|
|
.mocked(publishLiveEvent)
|
|
.mock.calls.filter(([event]) => event.type === "heartbeat.run.log"),
|
|
).toHaveLength(100),
|
|
);
|
|
await recorder.flushOutputProgress({ force: true });
|
|
expect(row.lastOutputSeq).toBe(110);
|
|
expect(row.lastOutputBytes).toBe(10000);
|
|
expect(writes.filter((write) => write.lastOutputSeq !== undefined)).toHaveLength(2);
|
|
});
|
|
|
|
it.each(["succeeds", "fails"] as const)("holds the log's finalization until a reattach's deferred re-verification %s", async (outcome) => {
|
|
const row = { ...newRunRow, runtimeMode: "native", logStore: "s3_segments", logRef: "company/agent/run", lastOutputSeq: 4 } as Run;
|
|
const db = createRunRowDb(row);
|
|
let releaseRead!: () => void;
|
|
const read = vi.fn(async () => {
|
|
await new Promise<void>(resolve => { releaseRead = resolve; });
|
|
if (outcome === "fails") throw new Error("object store read failed");
|
|
return { content: "", nextOffset: 0, eof: true };
|
|
});
|
|
const appendRunEvent = vi.fn(async (_run: unknown, _event: { payload?: { reason?: string } }) => undefined);
|
|
const output = createHeartbeatRunOutput(db, {
|
|
run: row, runId: row.id, issueId: null, secretKeys: new Set(),
|
|
identityRedactor: { chunk: (_stream, chunk) => chunk, redact: value => value },
|
|
runLogStore: {
|
|
begin: async () => ({ store: "s3_segments", logRef: "company/agent/run", initialBytes: 4_000_000, initialSequence: 4,
|
|
initialSourceCursor: 900 }),
|
|
append: async () => 0, enqueue: async () => ({ committed: Promise.resolve(0) }), flush: async () => undefined,
|
|
read: read as never,
|
|
},
|
|
appendRunEvent: appendRunEvent as never, getCurrentUserRedactionOptions: async () => ({ enabled: false }),
|
|
deferNativeLogRecovery: true,
|
|
});
|
|
await output.begin(row);
|
|
await vi.waitFor(() => expect(read).toHaveBeenCalled());
|
|
let settled = false;
|
|
const settling = output.settleDeferredLogRecovery().then(() => { settled = true; });
|
|
await new Promise(resolve => setTimeout(resolve, 20));
|
|
expect(settled).toBe(false);
|
|
releaseRead();
|
|
await settling;
|
|
expect(settled).toBe(true);
|
|
if (outcome === "fails") expect(appendRunEvent.mock.calls.some(([, event]) => event.payload?.reason === "object_log_persistence_failed")).toBe(true);
|
|
});
|
|
|
|
it("settles at once when no log re-verification was deferred", async () => {
|
|
const row = { ...newRunRow } as Run;
|
|
const output = createHeartbeatRunOutput(createRunRowDb(row), {
|
|
run: row, runId: row.id, issueId: null, secretKeys: new Set(),
|
|
identityRedactor: { chunk: (_stream, chunk) => chunk, redact: value => value },
|
|
runLogStore: { begin: async () => ({ store: "local_file", logRef: "run.ndjson" }), append: async () => 0 } as never,
|
|
appendRunEvent: vi.fn(async () => undefined) as never, getCurrentUserRedactionOptions: async () => ({ enabled: false }),
|
|
});
|
|
await expect(output.settleDeferredLogRecovery()).resolves.toBeUndefined();
|
|
});
|
|
|
|
it.each([false, true])("lets a reattach start before its existing log is re-verified (deferred %s)", async (deferNativeLogRecovery) => {
|
|
const row = { ...newRunRow, runtimeMode: "native", logStore: "s3_segments", logRef: "company/agent/run", lastOutputSeq: 4 } as Run;
|
|
const db = createRunRowDb(row);
|
|
let releaseRead!: () => void;
|
|
const readStarted = vi.fn();
|
|
const read = vi.fn(async () => {
|
|
readStarted();
|
|
await new Promise<void>(resolve => { releaseRead = resolve; });
|
|
return { content: "", nextOffset: 0, eof: true };
|
|
});
|
|
const output = createHeartbeatRunOutput(db, {
|
|
run: row, runId: row.id, issueId: null, secretKeys: new Set(),
|
|
identityRedactor: { chunk: (_stream, chunk) => chunk, redact: value => value },
|
|
runLogStore: {
|
|
begin: async () => ({ store: "s3_segments", logRef: "company/agent/run", initialBytes: 4_000_000, initialSequence: 4,
|
|
initialSourceCursor: 900 }),
|
|
append: async () => 0, enqueue: async () => ({ committed: Promise.resolve(0) }), flush: async () => undefined,
|
|
read: read as never,
|
|
},
|
|
appendRunEvent: vi.fn(async () => undefined) as never, getCurrentUserRedactionOptions: async () => ({ enabled: false }),
|
|
deferNativeLogRecovery,
|
|
});
|
|
let begun = false;
|
|
const beginning = output.begin(row).then(() => { begun = true; });
|
|
await vi.waitFor(() => expect(readStarted).toHaveBeenCalled());
|
|
await new Promise(resolve => setTimeout(resolve, 20));
|
|
expect(begun).toBe(deferNativeLogRecovery);
|
|
releaseRead();
|
|
await beginning.catch(() => undefined);
|
|
});
|
|
});
|
|
|
|
describe("secret-bound environment values in local run output", () => {
|
|
it("masks resolved secret values in the stored log, excerpt, live event, and adapter events", async () => {
|
|
const { publishLiveEvent } = await import("../live-events.js");
|
|
vi.mocked(publishLiveEvent).mockClear();
|
|
const secret = "sk_test_synthetic_local_0123456789";
|
|
const shortSecret = "pin42";
|
|
const plain = "https://plain.example.test/api";
|
|
const env = { STRIPE_KEY: secret, SHORT_PIN: shortSecret, PLAIN_URL: plain };
|
|
const secretKeys = new Set(["STRIPE_KEY", "SHORT_PIN"]);
|
|
const row = { ...newRunRow };
|
|
const chunks: string[] = [];
|
|
const events = vi.fn(async (_run: unknown, _event: { payload?: Record<string, unknown> }) => undefined);
|
|
const output = createHeartbeatRunOutput(createRunRowDb(row), {
|
|
run: row as Run,
|
|
runId: row.id!,
|
|
issueId: null,
|
|
runLogStore: {
|
|
begin: async () => ({ store: "local_file", logRef: "company/agent/run.ndjson" }),
|
|
append: async (_handle, event) => {
|
|
chunks.push(event.chunk);
|
|
return Buffer.byteLength(event.chunk);
|
|
},
|
|
enqueue: undefined,
|
|
flush: async () => undefined,
|
|
},
|
|
identityRedactor: createAgentIdentityRedactor(undefined, secretEnvironmentValues(env, secretKeys)),
|
|
secretKeys,
|
|
appendRunEvent: events as never,
|
|
getCurrentUserRedactionOptions: async () => ({ enabled: false }),
|
|
});
|
|
const handlers = await output.begin(row as Run);
|
|
await handlers.onLog("stdout", `STRIPE_KEY=${secret.slice(0, 12)}`);
|
|
await handlers.onLog("stdout", `${secret.slice(12)}\nSHORT_PIN=${shortSecret}\nPLAIN_URL=${plain}\n`);
|
|
await handlers.onAdapterEvent({ eventType: "tool.output", stream: "stdout", level: "info", message: `echo ${secret}`,
|
|
payload: { output: `${secret}\n` } });
|
|
await handlers.onAdapterMeta({ adapterType: "process", command: "synthetic", commandArgs: ["--token", secret],
|
|
env: { ...env } } as never);
|
|
const stored = chunks.join("");
|
|
expect(stored).toBe(`STRIPE_KEY=***REDACTED***\nSHORT_PIN=${shortSecret}\nPLAIN_URL=${plain}\n`);
|
|
expect(output.stdoutExcerpt).not.toContain(secret.slice(12));
|
|
expect(JSON.stringify(vi.mocked(publishLiveEvent).mock.calls)).not.toContain(secret.slice(12));
|
|
const persistedEvents = JSON.stringify(events.mock.calls.map(([, event]) => event));
|
|
expect(persistedEvents).not.toContain(secret);
|
|
expect(persistedEvents).toContain("***REDACTED***");
|
|
expect(persistedEvents).toContain(plain);
|
|
});
|
|
});
|