Integrate bounded warm retirement recovery

Co-Authored-By: Paperclip <noreply@paperclip.ing>

* commit '84a50124a997f4256932eab15fe79dd9ce875940':
  fix(runner): bound instruction collection and preserve pending retirement
This commit is contained in:
DottaandPaperclip committed 2026-09-30 05:29:03 -05:00
commit 3518902733
5 files changed
+99 -13

No files matched your search

+6 -1
View File
@@ -138,7 +138,12 @@ Edits, additions, removals or changed configuration retire the owner before
collection and fresh preparation. A configuration or copy change found at the
final dispatch fence fails that run after retirement; it does not replay the
request automatically. Idle expiry, restart and abandoned preparation also retire
before collection. The whole-directory contract closes the provider process,
before collection. Immediate collection retries have a fixed call budget and must
advance; a deferred ownership state ends the callback without inventing attempts.
A failed close leaves an unstopped pending receipt through generic run cleanup.
Later owner retirement or independent current-run stop proof can still collect it;
a prior run's stop proof cannot authorize collection. The whole-directory contract
closes the provider process,
including child processes, to establish this safe collection boundary. It
preserves the provider's resumable conversation. Only the loaded instruction entry
participates in the new runtime instruction digest; adding or editing another file does not change
@@ -192,7 +192,7 @@ describe("persistent agent directories", () => {
expect((await copies.get(companyId, first.runId))?.receipt?.retainedByRunId).toBeUndefined();
await copies.collectStopped({ companyId, runId: first.runId });
});
it("durably preserves an adopted directory after retirement failure", async () => {
it.each(["owner-close", "restart-proof"])("durably preserves an adopted directory after retirement failure and final cleanup: %s", async recovery => {
const first = await run();
expect(await copies.hasChanges({ companyId, runId: first.runId })).toBe(false);
const secondId = await nextRun();
@@ -201,13 +201,33 @@ describe("persistent agent directories", () => {
expect(await copies.reportRetirementUnconfirmed(companyId, secondId)).toMatchObject({
state: "pending_collection", errorCode: "INSTRUCTION_STOP_UNCONFIRMED", processStoppedAt: null,
});
await fs.writeFile(path.join(first.localRoot, "unsaved-memory.txt"), "Keep failed retirement edits");
// Mirror heartbeat's final cleanup after preparation throws. Neither the
// current pending owner nor the prior alias may become terminal loss.
await copies.reportUnavailable(companyId, secondId);
await copies.reportUnavailable(companyId, first.runId);
expect(await copies.get(companyId, secondId)).toMatchObject({ state: "pending_collection", errorCode: "INSTRUCTION_STOP_UNCONFIRMED", processStoppedAt: null });
await copies.reportRetirementUnconfirmed(companyId, first.runId);
await copies.release(companyId, first.runId);
await copies.release(companyId, secondId);
await copies.recoverStopped(); // A terminal run with no stop receipt grants no collection authority.
expect((await copies.get(companyId, secondId))?.processStoppedAt).toBeNull();
expect(await fs.readFile(path.join(first.localRoot, entryFile), "utf8")).toBe(initial);
await copies.collectStopped({ companyId, runId: secondId }); // Explicit test owner retirement.
if (recovery === "owner-close") await copies.collectStopped({ companyId, runId: secondId }); // Explicit test owner retirement.
else {
const { appendHeartbeatRunEvent } = await import("../services/heartbeat-run-events.js");
const stop = (runId: string) => appendHeartbeatRunEvent(db, { companyId, runId, agentId,
eventType: "native.local_process_stopped", stream: "system", level: "info", message: "Test-owned process retirement proof", payload: {} });
await stop(first.runId);
copies = agentInstructionWorkingCopyService(db); // No in-memory owner or transport survives.
await copies.recoverStopped();
expect((await copies.get(companyId, secondId))?.processStoppedAt).toBeNull();
await stop(secondId);
await copies.recoverStopped();
}
expect(await copies.get(companyId, secondId)).toMatchObject({ state: "saved", receipt: { cleanupPending: false } });
expect(await fs.readFile(path.join(root, "unsaved-memory.txt"), "utf8")).toBe("Keep failed retirement edits");
await expect(fs.stat(first.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
});
it("declines reuse after canonical instruction changes", async () => {
const first = await run();
@@ -32,6 +32,19 @@ const MAX_COLLECTION_ATTEMPTS = 3;
const liveTargets = new Map<string, AdapterExecutionTarget>();
const targetKey = (companyId: string, runId: string) => `${companyId}:${runId}`;
/** Finish only bounded immediate collection work; deferred ownership remains pending. */
export async function collectStoppedInstructionCopyWithRetries<T extends Pick<Copy, "state" | "attempts" | "nextAttemptAt">>(collect: () => Promise<T | null>): Promise<T | null> {
let saved: T | null = null;
let previousAttempts = -1;
for (let calls = 0; calls < MAX_COLLECTION_ATTEMPTS; calls++) {
saved = await collect();
if (!saved || saved.state !== "pending_collection" || saved.nextAttemptAt === null
|| saved.attempts >= MAX_COLLECTION_ATTEMPTS || saved.attempts <= previousAttempts) break;
previousAttempts = saved.attempts;
}
return saved;
}
export function instructionWorkingCopyGuidance(copy: Pick<Copy, "executionRoot" | "entryFile" | "receipt">) {
if (isAgentDirectoryCopy(copy)) return `Your persistent agent directory is ${copy.executionRoot} (AGENT_HOME). Your instruction entry is ${copy.executionRoot}/${copy.entryFile}. Read and write your own files and subfolders there. This directory belongs to this agent across tasks and sessions; task files belong in the task working directory. Paperclip restores this directory before execution and saves changes after the provider stops. Regular files, including binary files, persist; symlinks and special files are unsupported. Check the agent-files save receipt before claiming persistence; Only files you change or delete are synchronized. If another run changes the same file, the last completed synchronization wins. Temporary copies are removed after synchronization; there is no per-run file history. Storage allows 256 MiB per file, 2 GiB total, and 100,000 entries; the instruction entry must remain UTF-8 and at most 1 MiB. Reaching a storage limit never prevents this or future tasks from running. Remove or shrink files to free space; changes that exceed the limits will not be saved.${typeof copy.receipt?.storageWarning === "string" ? `\n\n${copy.receipt.storageWarning}` : ""}`;
return `Your editable agent instruction file is ${copy.executionRoot}/${copy.entryFile}. Edit this registered private copy normally. After this run stops, Paperclip saves changed content as a persistent revision if your responsible user still has permission and the baseline has not changed. Check the run's instruction-save receipt before claiming persistence. Use read_agent_instructions, update_agent_instructions, get_agent_instruction_history, and restore_agent_instructions for immediate saves and history. Read first and pin the returned revision. Preserve conflicts; never silently retry against a newer head. Repository instructions, skills, and the loaded prompt are separate and are not collected.`;
@@ -346,7 +359,10 @@ export function agentInstructionWorkingCopyService(db: Db, options: { environmen
async function reportUnavailable(companyId: string, runId: string) {
const row = await get(companyId, runId);
if (!row || completed.has(row.state) || row.state === "unchanged_turn" || row.candidateBase64 !== null || (isAgentDirectoryCopy(row) && row.candidateHash !== null) || row.state === "conflict") return row;
if (isAgentDirectoryCopy(row) && row.state === "unavailable") return row;
// A failed close or deferred lease observation grants no stop proof. Keep
// that row recoverable through generic heartbeat cleanup.
if (isAgentDirectoryCopy(row) && (row.state === "unavailable"
|| row.state === "pending_collection" && !row.processStoppedAt)) return row;
return patch(row, { state: "unavailable", errorCode: "INSTRUCTION_COLLECTION_UNAVAILABLE",
errorMessage: "The registered instruction copy could not be retrieved safely before environment release. No instruction save is claimed.", nextAttemptAt: null });
}
+4 -7
View File
@@ -71,7 +71,7 @@ import {
startAdapterExecutionTargetPaperclipBridge,
} from "@paperclipai/adapter-utils/execution-target";
import { agentService } from "./agents.js";
import { agentInstructionWorkingCopyService, instructionWorkingCopyGuidance } from "./agent-instruction-working-copies.js";
import { agentInstructionWorkingCopyService, collectStoppedInstructionCopyWithRetries, instructionWorkingCopyGuidance } from "./agent-instruction-working-copies.js";
import { normalizeLegacyRunnerProvider } from "@paperclipai/adapter-utils";
import fs from "node:fs/promises";
import path from "node:path";
@@ -22431,12 +22431,9 @@ export function heartbeatService(
})).digest("hex");
const collectStoppedInstructions = async () => {
if (!instructionCopy) return;
let saved = await instructionCopies.collectStopped({ companyId: agent.companyId, runId: run.id, target: executionTarget });
// Capture before disposal. Exhausted bounded collection leaves a durable
// explicit loss report, never a claim that missing bytes were saved.
while (saved?.state === "pending_collection" && saved.attempts < 3) {
saved = await instructionCopies.collectStopped({ companyId: agent.companyId, runId: run.id, target: executionTarget });
}
const saved = await collectStoppedInstructionCopyWithRetries(() => instructionCopies.collectStopped({
companyId: agent.companyId, runId: run.id, target: executionTarget,
}));
if (!saved) return;
const receipt = parseObject(saved.receipt);
const storageWarning = readNonEmptyString(receipt.storageWarning);
@@ -5979,8 +5979,36 @@ describe("native session same-turn steering", () => {
});
});
describe("bounded stopped instruction collection", () => {
it.each([
{ scenario: "deferred", attempts: [0], nextAttemptAt: null, expectedCalls: 1 },
{ scenario: "no progress", attempts: [0, 0], nextAttemptAt: new Date(0), expectedCalls: 2 },
{ scenario: "regressed counter", attempts: [1, 0], nextAttemptAt: new Date(0), expectedCalls: 2 },
{ scenario: "progressing counter", attempts: [0, 1, 2], nextAttemptAt: new Date(0), expectedCalls: 3 },
{ scenario: "exhausted", attempts: [3], nextAttemptAt: new Date(0), expectedCalls: 1 },
])("finishes pending collection without inventing attempts: $scenario", async ({ attempts, nextAttemptAt, expectedCalls }) => {
const { collectStoppedInstructionCopyWithRetries } = await import("../agent-instruction-working-copies.js");
const collect = vi.fn(async () => {
const index = collect.mock.calls.length - 1;
if (index >= attempts.length) throw new Error("collector invoked beyond bounded progress");
return { state: "pending_collection", attempts: attempts[index]!, nextAttemptAt };
});
expect(await collectStoppedInstructionCopyWithRetries(collect)).toEqual({ state: "pending_collection", attempts: attempts.at(-1), nextAttemptAt });
expect(collect).toHaveBeenCalledTimes(expectedCalls);
});
it("returns completed or absent copies and propagates collection errors", async () => {
const { collectStoppedInstructionCopyWithRetries } = await import("../agent-instruction-working-copies.js");
const result = { state: "saved", attempts: 1, nextAttemptAt: null };
const saved = vi.fn(async () => result), absent = vi.fn(async () => null);
expect(await collectStoppedInstructionCopyWithRetries(saved)).toBe(result);
expect(await collectStoppedInstructionCopyWithRetries(absent)).toBeNull();
expect(saved).toHaveBeenCalledOnce(); expect(absent).toHaveBeenCalledOnce();
await expect(collectStoppedInstructionCopyWithRetries(async () => { throw new Error("collection failed"); })).rejects.toThrow("collection failed");
});
});
describe("native warm session supervision", () => {
it.each(["collect", "stopped", "destroyed", "missing-lease", "foreign-run", "foreign-environment", "deleted-environment", "claim-edit", "claim-add", "claim-remove", "claim-remove-entry", "claim-canonical", "claim-config", "claim-uncertain"])("composes remote warm ownership with real DB successor leases and current-run collection: %s", async ending => {
it.each(["collect", "close-failure", "stopped", "destroyed", "missing-lease", "foreign-run", "foreign-environment", "deleted-environment", "claim-edit", "claim-add", "claim-remove", "claim-remove-entry", "claim-canonical", "claim-config", "claim-uncertain"])("composes remote warm ownership with real DB successor leases and current-run collection: %s", async ending => {
const tables = await import("@paperclipai/db");
const { eq } = await import("drizzle-orm");
const { randomUUID } = await import("node:crypto");
@@ -6075,7 +6103,10 @@ describe("native warm session supervision", () => {
const preparationKey = turn === 1 && ending === "claim-config" ? "changed-config" : "same-config";
let retiredReceipt: Record<string, unknown> | null = null;
const capability = () => ({ runId, preparationKey, hasChanges: () => copies.hasChanges({ companyId, runId, target }),
collectStopped: async () => { expect(closed).toBe(true); retiredReceipt = (await copies.get(companyId, runId))?.receipt ?? null; await copies.collectStopped({ companyId, runId, target }); } });
collectStopped: async () => { expect(closed).toBe(true); retiredReceipt = (await copies.get(companyId, runId))?.receipt ?? null;
const { collectStoppedInstructionCopyWithRetries } = await import("../agent-instruction-working-copies.js");
await collectStoppedInstructionCopyWithRetries(() => copies.collectStopped({ companyId, runId, target }));
}, retirementFailed: async () => { await copies.reportRetirementUnconfirmed(companyId, runId); } });
let release: (() => Promise<void>) | null = null;
if (prior) {
// Same environment is insufficient: reject a different physical allocation.
@@ -6167,6 +6198,23 @@ describe("native warm session supervision", () => {
expect(await readFile(join(originalRoot, "late-memory.txt"), "utf8")).toBe("Latest owner's remote bytes");
return;
}
if (ending === "close-failure") {
session.close.mockImplementationOnce(async () => { throw new Error("owned close not yet confirmed"); });
const before = commands.length;
expect(await closeWarmNativeSessionsForEnvironment({ environmentId, reason: "first retirement" })).toMatchObject({ failed: 1 });
await copies.reportUnavailable(companyId, prior!.binding.runId);
await copies.reportUnavailable(companyId, materializationRunId);
await copies.release(companyId, prior!.binding.runId);
await copies.release(companyId, materializationRunId);
expect(await copies.get(companyId, prior!.binding.runId)).toMatchObject({ state: "pending_collection", errorCode: "INSTRUCTION_STOP_UNCONFIRMED", processStoppedAt: null });
expect(commands).toHaveLength(before);
expect(await readFile(join(originalRoot, "late-memory.txt"), "utf8")).toBe("Latest owner's remote bytes");
expect(await closeWarmNativeSessionsForEnvironment({ environmentId, reason: "verified later retirement" })).toMatchObject({ closed: 1, failed: 0 });
expect(await copies.get(companyId, prior!.binding.runId)).toMatchObject({ state: "saved", receipt: { cleanupPending: false } });
expect(await readFile(join(canonical, "late-memory.txt"), "utf8")).toBe("Latest owner's remote bytes");
await expect(access(originalRoot)).rejects.toMatchObject({ code: "ENOENT" });
return;
}
if (ending !== "collect") {
const { remoteTerminationReceipt } = await import("../remote-execution-termination.js");
const [lease] = await db.select().from(tables.environmentLeases).where(eq(tables.environmentLeases.id, currentLease));