Skip to content

The open-source app everyone uses to manage agents at work

fix: expire native session failover backups after their issues close (#16866)

Devin Foley1f3695ac6716
diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md
index 7576805d19..c83b2e211c 100644
--- a/doc/DEVELOPING.md
+++ b/doc/DEVELOPING.md
@@ -2434,6 +2434,12 @@ Environment overrides:
- `PAPERCLIP_SKILL_VERSION_RETENTION_GRACE_MINUTES=<minutes>` sets how long a
materialized skill version stays after its last use. The default is `60`. A
negative, empty, or non-numeric value falls back to the default.
+- `PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DAYS=<days>` sets how long an issue
+ stays closed before the failover backups of its native sessions expire (see
+ `doc/recoverable-disk-cleanup.md`). The default is `7` and the minimum is `1`. A
+ negative, empty, or non-numeric value falls back to the default.
+ `PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_ENABLED=false` turns expiry off, and
+ `PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DRY_RUN=true` only reports candidates.
Without `PAPERCLIP_DB_BACKUP_ALERT_FILE`, health checks look for
`db-backup-to-s3.failure` in the backup directory, beside the backup directory,
diff --git a/doc/recoverable-disk-cleanup.md b/doc/recoverable-disk-cleanup.md
index f27de547ac..81c3e6cb53 100644
--- a/doc/recoverable-disk-cleanup.md
+++ b/doc/recoverable-disk-cleanup.md
@@ -45,3 +45,45 @@ does not start the legacy observation period.
Roll out with dry run enabled, inspect candidates/skips, then enable removal.
Recovery archives and runner backups have separate ownership and retention;
this worker never scans or removes them.
+
+## Native session failover backups
+
+After each remote turn, the server copies the sandbox's harness state (runner
+state plus the provider's session home, such as `codex-home`) to
+`<instance>/runtime/paperclip-runner/durable-sessions/<scope>/failover-backups/current`.
+A replacement sandbox restores the session from this copy. Each session keeps one
+copy, and a single copy can reach several gigabytes.
+
+An hourly background sweep expires the copy once the session can only resume by
+reopening closed work. It checks at most 200 sessions and expires at most 50 per
+batch, starting two minutes after readiness. A copy expires when all of these hold:
+
+- every issue the session ran on is `done` or `cancelled`, and closed before the window;
+- the copy itself was written before the window;
+- no run of the session is queued, running, or unfinished;
+- every native run finalization of the session is settled, with no recovery in progress;
+- no active, released, retained, or pending-cleanup environment lease references the copy;
+- the session is not executing, initializing, warm, or closing in this process, and
+ no cleanup activation is pending in its directory.
+
+A session whose control-plane state is missing, unreadable, or larger than 4 MB
+keeps its copy, because the sweep cannot identify its runs.
+
+The sweep checks and locks these rows in one transaction, and removes the agent task
+session that points at the session there. A reopened issue therefore starts a fresh
+native session instead of resuming the expired one. The copy is atomically renamed to
+`failover-backups/.retiring-<UUID>`, and a final check looks for a run of the session.
+If one appeared, or the check fails, the rename is undone. Only a confirmed copy is
+renamed to `.expired-<UUID>` and deleted asynchronously. A later sweep restores an
+unconfirmed `.retiring-*` copy when `current` is missing, drops it when a newer
+`current` exists, and finishes an interrupted deletion.
+The rest of the session directory, including its control-plane state, is kept.
+
+| Environment variable | Default | Effect |
+| --- | --- | --- |
+| `PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_ENABLED` | `true` | Set `false` to stop expiring copies |
+| `PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DRY_RUN` | `false` | Set `true` to report candidates without deleting copies or task sessions |
+| `PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DAYS` | `7` | Days an issue must be closed before its sessions' copies expire (minimum `1`) |
+
+Each batch that finds candidates logs them with candidate and reclaimed allocated
+bytes, cleared task sessions, and skip reasons.
diff --git a/server/src/__tests__/native-harness-backup-expiration-config.test.ts b/server/src/__tests__/native-harness-backup-expiration-config.test.ts
new file mode 100644
index 0000000000..81967a9bda
--- /dev/null
+++ b/server/src/__tests__/native-harness-backup-expiration-config.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { loadConfig } from "../config.ts";
+
+describe("native harness backup expiration config parsing", () => {
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it("is enabled for issues closed seven days by default", () => {
+ vi.stubEnv("PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_ENABLED", undefined);
+ vi.stubEnv("PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DRY_RUN", undefined);
+ vi.stubEnv("PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DAYS", undefined);
+ expect(loadConfig()).toMatchObject({
+ nativeHarnessBackupExpirationEnabled: true,
+ nativeHarnessBackupExpirationDryRun: false,
+ nativeHarnessBackupExpirationDays: 7,
+ });
+ });
+
+ it("accepts explicit controls", () => {
+ vi.stubEnv("PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_ENABLED", "false");
+ vi.stubEnv("PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DRY_RUN", "true");
+ vi.stubEnv("PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DAYS", "3");
+ expect(loadConfig()).toMatchObject({
+ nativeHarnessBackupExpirationEnabled: false,
+ nativeHarnessBackupExpirationDryRun: true,
+ nativeHarnessBackupExpirationDays: 3,
+ });
+ });
+
+ it.each(["", "-1", "many"])("falls back to seven days for %j", (value) => {
+ vi.stubEnv("PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DAYS", value);
+ expect(loadConfig()).toMatchObject({ nativeHarnessBackupExpirationDays: 7 });
+ });
+
+ it("never expires sooner than one day", () => {
+ vi.stubEnv("PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DAYS", "0");
+ expect(loadConfig()).toMatchObject({ nativeHarnessBackupExpirationDays: 1 });
+ });
+});
diff --git a/server/src/__tests__/native-harness-backup-expiration.test.ts b/server/src/__tests__/native-harness-backup-expiration.test.ts
new file mode 100644
index 0000000000..1efb58a615
--- /dev/null
+++ b/server/src/__tests__/native-harness-backup-expiration.test.ts
@@ -0,0 +1,293 @@
+import { createHash, randomUUID } from "node:crypto";
+import os from "node:os";
+import path from "node:path";
+import { promises as fs } from "node:fs";
+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+import { eq } from "drizzle-orm";
+import {
+ agents,
+ agentTaskSessions,
+ companies,
+ createDb,
+ environmentLeases,
+ heartbeatRuns,
+ issues,
+ nativeRunFinalizations,
+} from "@paperclipai/db";
+import {
+ getEmbeddedPostgresTestSupport,
+ startEmbeddedPostgresTestDatabase,
+} from "./helpers/embedded-postgres.js";
+import { nativeHarnessBackupExpirationService } from "../services/native-runtime/native-harness-backup-expiration.ts";
+
+const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
+const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
+
+if (!embeddedPostgresSupport.supported) {
+ console.warn(
+ `Skipping embedded Postgres native harness backup expiration tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
+ );
+}
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+async function exists(target: string) {
+ return fs.lstat(target).then(() => true, () => false);
+}
+
+describeEmbeddedPostgres("native harness backup expiration", () => {
+ let db!: ReturnType<typeof createDb>;
+ let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
+ let stateBase = "";
+ const now = new Date();
+
+ beforeAll(async () => {
+ tempDb = await startEmbeddedPostgresTestDatabase("paperclip-native-backup-expiration-");
+ db = createDb(tempDb.connectionString);
+ }, 20_000);
+
+ afterEach(async () => {
+ await db.delete(agentTaskSessions);
+ await db.delete(nativeRunFinalizations);
+ await db.delete(environmentLeases);
+ await db.delete(heartbeatRuns);
+ await db.delete(issues);
+ await db.delete(agents);
+ await db.delete(companies);
+ if (stateBase) await fs.rm(stateBase, { recursive: true, force: true });
+ stateBase = "";
+ });
+
+ afterAll(async () => {
+ await tempDb?.cleanup();
+ });
+
+ async function seedSession(input: {
+ issueStatus?: string;
+ closedDaysAgo?: number;
+ runStatus?: string;
+ finalization?: { phase: string; recoveryState?: string | null };
+ leaseStatus?: string;
+ backupAgeDays?: number;
+ cleanupActive?: boolean;
+ } = {}) {
+ if (!stateBase) stateBase = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-durable-sessions-"));
+ const companyId = randomUUID();
+ await db.insert(companies).values({ id: companyId, name: "Backups", issuePrefix: `B${companyId.slice(0, 6)}` });
+ const [agent] = await db.insert(agents).values({ companyId, name: "Coder" }).returning();
+ const issueStatus = input.issueStatus ?? "done";
+ const closedAt = new Date(now.getTime() - (input.closedDaysAgo ?? 10) * DAY_MS);
+ const [issue] = await db.insert(issues).values({
+ companyId,
+ title: "Closed work",
+ status: issueStatus,
+ completedAt: issueStatus === "done" ? closedAt : null,
+ cancelledAt: issueStatus === "cancelled" ? closedAt : null,
+ }).returning();
+ const sessionId = randomUUID();
+ const runStatus = input.runStatus ?? "succeeded";
+ const [run] = await db.insert(heartbeatRuns).values({
+ companyId,
+ agentId: agent!.id,
+ status: runStatus,
+ issueId: issue!.id,
+ nativeIssueId: issue!.id,
+ nativeSessionId: sessionId,
+ finishedAt: ["queued", "running"].includes(runStatus) ? null : closedAt,
+ }).returning();
+ await db.insert(agentTaskSessions).values({
+ companyId,
+ agentId: agent!.id,
+ adapterType: "paperclip_runner",
+ taskKey: issue!.id,
+ sessionParamsJson: { sessionId },
+ lastRunId: run!.id,
+ });
+ if (input.finalization) {
+ await db.insert(nativeRunFinalizations).values({
+ runId: run!.id,
+ companyId,
+ issueId: issue!.id,
+ phase: input.finalization.phase,
+ recoveryState: input.finalization.recoveryState ?? null,
+ });
+ }
+ const scope = createHash("sha256").update(randomUUID()).digest("hex");
+ const root = path.join(stateBase, scope);
+ const current = path.join(root, "failover-backups", "current");
+ await fs.mkdir(path.join(root, "control-plane"), { recursive: true });
+ await fs.writeFile(
+ path.join(root, "control-plane", "control-plane-state.json"),
+ JSON.stringify({ identity: { runId: run!.id, normalizedSessionId: sessionId } }),
+ );
+ await fs.mkdir(path.join(current, "codex-home"), { recursive: true });
+ await fs.writeFile(path.join(current, "codex-home", "history.jsonl"), "x".repeat(64 * 1024));
+ await fs.writeFile(path.join(current, "manifest.json"), "{}");
+ const backupAt = new Date(now.getTime() - (input.backupAgeDays ?? 9) * DAY_MS);
+ await fs.utimes(current, backupAt, backupAt);
+ if (input.cleanupActive) await fs.writeFile(path.join(root, "cleanup-activation.json"), "{}");
+ if (input.leaseStatus) {
+ await db.insert(environmentLeases).values({
+ companyId,
+ status: input.leaseStatus,
+ metadata: { nativeHarnessBackup: { sessionScopeSha256: scope } },
+ });
+ }
+ return { companyId, agentId: agent!.id, issueId: issue!.id, sessionId, scope, root, current };
+ }
+
+ function service() {
+ return nativeHarnessBackupExpirationService(db, {
+ stateBase,
+ closedForDays: 7,
+ now,
+ isSessionBusy: () => false,
+ });
+ }
+
+ async function taskSessionCount(agentId: string) {
+ return (await db.select().from(agentTaskSessions).where(eq(agentTaskSessions.agentId, agentId))).length;
+ }
+
+ it("expires the backup of a session whose issue closed before the window and clears its resume pointer", async () => {
+ const session = await seedSession();
+ const result = await service().tick();
+
+ expect(result).toMatchObject({ checked: 1, candidates: 1, expired: 1, clearedTaskSessions: 1, failed: 0 });
+ expect(result.reclaimedBytes).toBeGreaterThan(0);
+ expect(await exists(session.current)).toBe(false);
+ expect(await exists(path.join(session.root, "control-plane", "control-plane-state.json"))).toBe(true);
+ expect(await fs.readdir(path.join(session.root, "failover-backups"))).toEqual([]);
+ expect(await taskSessionCount(session.agentId)).toBe(0);
+ });
+
+ it("expires sessions of cancelled issues", async () => {
+ const session = await seedSession({ issueStatus: "cancelled" });
+ expect(await service().tick()).toMatchObject({ expired: 1 });
+ expect(await exists(session.current)).toBe(false);
+ });
+
+ it.each([
+ ["issue_open", { issueStatus: "in_progress" }],
+ ["recently_closed", { closedDaysAgo: 2 }],
+ ["live_run", { runStatus: "running" }],
+ ["pending_finalization", { finalization: { phase: "settling" } }],
+ ["pending_finalization", { finalization: { phase: "committed", recoveryState: "resuming_session" } }],
+ ["live_lease", { leaseStatus: "released" }],
+ ["recent_backup", { backupAgeDays: 1 }],
+ ["cleanup_active", { cleanupActive: true }],
+ ] as const)("keeps the backup when %s", async (reason, input) => {
+ const session = await seedSession(input);
+ const result = await service().tick();
+
+ expect(result).toMatchObject({ checked: 1, candidates: 0, expired: 0, failed: 0 });
+ expect(result.skipped[reason]).toBe(1);
+ expect(await exists(session.current)).toBe(true);
+ expect(await taskSessionCount(session.agentId)).toBe(1);
+ });
+
+ it("keeps the backup when the session's control-plane state is too large to read", async () => {
+ const session = await seedSession();
+ const statePath = path.join(session.root, "control-plane", "control-plane-state.json");
+ await fs.writeFile(statePath, `${await fs.readFile(statePath, "utf8")}${" ".repeat(5 * 1024 * 1024)}`);
+
+ const result = await service().tick();
+
+ expect(result.skipped.identity_unknown).toBe(1);
+ expect(await exists(session.current)).toBe(true);
+ expect(await taskSessionCount(session.agentId)).toBe(1);
+ });
+
+ it("keeps the backup of a session that is executing in this process", async () => {
+ const session = await seedSession();
+ const result = await nativeHarnessBackupExpirationService(db, {
+ stateBase,
+ now,
+ isSessionBusy: (scope) => scope === session.scope,
+ }).tick();
+
+ expect(result.skipped.session_active).toBe(1);
+ expect(await exists(session.current)).toBe(true);
+ expect(await taskSessionCount(session.agentId)).toBe(1);
+ });
+
+ it("settled finalizations and expired leases do not block expiry", async () => {
+ const session = await seedSession({ finalization: { phase: "committed" }, leaseStatus: "expired" });
+ expect(await service().tick()).toMatchObject({ expired: 1 });
+ expect(await exists(session.current)).toBe(false);
+ });
+
+ it("reports candidates without deleting anything in dry run", async () => {
+ const session = await seedSession();
+ const result = await nativeHarnessBackupExpirationService(db, {
+ stateBase,
+ now,
+ dryRun: true,
+ isSessionBusy: () => false,
+ }).tick();
+
+ expect(result).toMatchObject({ candidates: 1, expired: 0, clearedTaskSessions: 0 });
+ expect(result.candidateBytes).toBeGreaterThan(0);
+ expect(await exists(session.current)).toBe(true);
+ expect(await taskSessionCount(session.agentId)).toBe(1);
+ });
+
+ it("continues across ticks when a batch is bounded", async () => {
+ const sessions = [await seedSession(), await seedSession(), await seedSession()];
+ const expiration = nativeHarnessBackupExpirationService(db, {
+ stateBase,
+ now,
+ maxEntries: 2,
+ isSessionBusy: () => false,
+ });
+
+ expect(await expiration.tick()).toMatchObject({ checked: 2, expired: 2, truncated: true });
+ expect(await expiration.tick()).toMatchObject({ checked: 1, expired: 1, truncated: false });
+ for (const session of sessions) expect(await exists(session.current)).toBe(false);
+ });
+
+ it("uses the configured clock for the closed window", async () => {
+ const session = await seedSession({ closedDaysAgo: 8, backupAgeDays: 20 });
+ const early = nativeHarnessBackupExpirationService(db, {
+ stateBase,
+ now: new Date(now.getTime() - 2 * DAY_MS),
+ isSessionBusy: () => false,
+ });
+ expect((await early.tick()).skipped.recently_closed).toBe(1);
+ expect(await exists(session.current)).toBe(true);
+ expect(await service().tick()).toMatchObject({ expired: 1 });
+ });
+
+ it("restores a backup whose expiry stopped before its final check", async () => {
+ const session = await seedSession({ issueStatus: "in_progress" });
+ const retiring = path.join(session.root, "failover-backups", `.retiring-${randomUUID()}`);
+ await fs.rename(session.current, retiring);
+
+ await service().tick();
+
+ expect(await exists(retiring)).toBe(false);
+ expect(await exists(path.join(session.current, "manifest.json"))).toBe(true);
+ });
+
+ it("drops an unconfirmed retired backup once a newer backup exists", async () => {
+ const session = await seedSession({ issueStatus: "in_progress" });
+ const retiring = path.join(session.root, "failover-backups", `.retiring-${randomUUID()}`);
+ await fs.mkdir(path.join(retiring, "codex-home"), { recursive: true });
+
+ await service().tick();
+
+ expect(await exists(retiring)).toBe(false);
+ expect(await exists(path.join(session.current, "manifest.json"))).toBe(true);
+ });
+
+ it("finishes removing a backup left over from an interrupted expiry", async () => {
+ const session = await seedSession({ issueStatus: "in_progress" });
+ const leftover = path.join(session.root, "failover-backups", `.expired-${randomUUID()}`);
+ await fs.mkdir(path.join(leftover, "codex-home"), { recursive: true });
+
+ await service().tick();
+
+ expect(await exists(leftover)).toBe(false);
+ expect(await exists(session.current)).toBe(true);
+ });
+});
diff --git a/server/src/config.ts b/server/src/config.ts
index 4d752fbdb0..62c40bbbcf 100644
--- a/server/src/config.ts
+++ b/server/src/config.ts
@@ -88,6 +88,9 @@ export interface Config {
skillVersionRetentionDryRun: boolean;
skillVersionRetentionKeepNewest: number;
skillVersionRetentionGraceMinutes: number;
+ nativeHarnessBackupExpirationEnabled: boolean;
+ nativeHarnessBackupExpirationDryRun: boolean;
+ nativeHarnessBackupExpirationDays: number;
serveUi: boolean;
uiDevMiddleware: boolean;
secretsProvider: SecretProvider;
@@ -333,6 +336,7 @@ export function loadConfig(): Config {
};
const skillVersionRetentionKeepNewest = nonNegativeIntegerEnv("PAPERCLIP_SKILL_VERSION_RETENTION_KEEP", 0);
const skillVersionRetentionGraceMinutes = nonNegativeIntegerEnv("PAPERCLIP_SKILL_VERSION_RETENTION_GRACE_MINUTES", 60);
+ const nativeHarnessBackupExpirationDays = Math.max(1, nonNegativeIntegerEnv("PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DAYS", 7));
const bindValidationErrors = validateConfiguredBindMode({
deploymentMode,
deploymentExposure,
@@ -387,6 +391,9 @@ export function loadConfig(): Config {
skillVersionRetentionDryRun: process.env.PAPERCLIP_SKILL_VERSION_RETENTION_DRY_RUN === "true",
skillVersionRetentionKeepNewest,
skillVersionRetentionGraceMinutes,
+ nativeHarnessBackupExpirationEnabled: process.env.PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_ENABLED !== "false",
+ nativeHarnessBackupExpirationDryRun: process.env.PAPERCLIP_NATIVE_HARNESS_BACKUP_EXPIRATION_DRY_RUN === "true",
+ nativeHarnessBackupExpirationDays,
serveUi:
process.env.SERVE_UI !== undefined
? process.env.SERVE_UI === "true"
diff --git a/server/src/index.ts b/server/src/index.ts
index 674deb4962..a302db1b25 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -5,6 +5,11 @@ import {
SKILL_VERSION_RETENTION_STARTUP_DELAY_MS,
skillVersionRetentionService,
} from "./services/skill-version-retention.js";
+import {
+ NATIVE_HARNESS_BACKUP_EXPIRATION_INTERVAL_MS,
+ NATIVE_HARNESS_BACKUP_EXPIRATION_STARTUP_DELAY_MS,
+ nativeHarnessBackupExpirationService,
+} from "./services/native-runtime/native-harness-backup-expiration.js";
import { subscribeAllCompanyLiveEvents } from "./services/live-events.js";
import { DELIVERY_QUEUES } from "./services/delivery-work-notifications.js";
import { registerScheduledWork } from "./services/scheduled-work.js";
@@ -1270,6 +1275,35 @@ async function startServerWithDatabaseTeardown(
skillVersionRetentionInterval.unref?.();
const skillVersionRetentionStartup = setTimeout(sweepSkillVersionSnapshots, SKILL_VERSION_RETENTION_STARTUP_DELAY_MS);
skillVersionRetentionStartup.unref?.();
+ const nativeHarnessBackupExpiration = nativeHarnessBackupExpirationService(db as any, {
+ dryRun: config.nativeHarnessBackupExpirationDryRun,
+ closedForDays: config.nativeHarnessBackupExpirationDays,
+ shouldContinue: () => !heartbeatSchedulerStopped && !isIdleTaskDrainActive() && !isWarmStandby(),
+ });
+ let nativeHarnessBackupExpirationInFlight = false;
+ let nativeHarnessBackupExpirationContinuation: ReturnType<typeof setTimeout> | undefined;
+ const sweepNativeHarnessBackups = () => {
+ if (!config.nativeHarnessBackupExpirationEnabled || nativeHarnessBackupExpirationInFlight || isIdleTaskDrainActive() || heartbeatSchedulerStopped || isWarmStandby()) return;
+ nativeHarnessBackupExpirationInFlight = true;
+ trackHeartbeatSchedulerWork(nativeHarnessBackupExpiration.tick()
+ .then((result) => {
+ if (result.candidates > 0 || result.failed > 0) {
+ logger.info({ ...result, dryRun: config.nativeHarnessBackupExpirationDryRun }, "native harness backup expiration");
+ }
+ if (result.truncated && !heartbeatSchedulerStopped) {
+ nativeHarnessBackupExpirationContinuation = setTimeout(sweepNativeHarnessBackups, 1000);
+ nativeHarnessBackupExpirationContinuation.unref?.();
+ }
+ })
+ .catch((err) => {
+ logger.error({ err }, "native harness backup expiration failed");
+ })
+ .finally(() => { nativeHarnessBackupExpirationInFlight = false; }));
+ };
+ const nativeHarnessBackupExpirationInterval = setInterval(sweepNativeHarnessBackups, NATIVE_HARNESS_BACKUP_EXPIRATION_INTERVAL_MS);
+ nativeHarnessBackupExpirationInterval.unref?.();
+ const nativeHarnessBackupExpirationStartup = setTimeout(sweepNativeHarnessBackups, NATIVE_HARNESS_BACKUP_EXPIRATION_STARTUP_DELAY_MS);
+ nativeHarnessBackupExpirationStartup.unref?.();
const externalObjects = externalObjectService(db as any, {
pluginWorkerManager,
enabled: async () => (await instanceSettingsService(db).getExperimental()).enableExternalObjects === true,
@@ -2050,6 +2084,9 @@ async function startServerWithDatabaseTeardown(
clearInterval(skillVersionRetentionInterval);
clearTimeout(skillVersionRetentionStartup);
clearTimeout(skillVersionRetentionContinuation);
+ clearInterval(nativeHarnessBackupExpirationInterval);
+ clearTimeout(nativeHarnessBackupExpirationStartup);
+ clearTimeout(nativeHarnessBackupExpirationContinuation);
await skillVersionRetention.dispose();
await skillSourceSync.stop();
unsubscribeChatCompletions();
diff --git a/server/src/services/native-runtime/native-harness-backup-expiration.ts b/server/src/services/native-runtime/native-harness-backup-expiration.ts
new file mode 100644
index 0000000000..d87789f047
--- /dev/null
+++ b/server/src/services/native-runtime/native-harness-backup-expiration.ts
@@ -0,0 +1,356 @@
+import { randomUUID } from "node:crypto";
+import { promises as fs } from "node:fs";
+import path from "node:path";
+import { and, eq, inArray, isNull, notInArray, or, sql } from "drizzle-orm";
+import {
+ agentTaskSessions,
+ environmentLeases,
+ heartbeatRuns,
+ issues,
+ nativeRunFinalizations,
+ type Db,
+} from "@paperclipai/db";
+import { logger } from "../../middleware/logger.js";
+import { nativeHarnessStateBase } from "./native-harness-backup-stamp.js";
+import { nativeSessionScopeDigestIsBusy } from "./native-session-executor.js";
+
+export const NATIVE_HARNESS_BACKUP_EXPIRATION_INTERVAL_MS = 60 * 60 * 1000;
+export const NATIVE_HARNESS_BACKUP_EXPIRATION_STARTUP_DELAY_MS = 2 * 60 * 1000;
+export const NATIVE_HARNESS_BACKUP_EXPIRATION_DEFAULT_DAYS = 7;
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+const SCOPE_PATTERN = /^[0-9a-f]{64}$/;
+const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const EXPIRED_PREFIX = ".expired-";
+const RETIRING_PREFIX = ".retiring-";
+const LIVE_RUN_STATUSES = ["queued", "scheduled_retry", "running"];
+const SETTLED_FINALIZATION_PHASES = ["committed", "terminal_failure"];
+const LIVE_LEASE_STATUSES = ["active", "released", "retained", "pending_cleanup"];
+const CLOSED_ISSUE_STATUSES = ["done", "cancelled"];
+const MAX_CONTROL_PLANE_STATE_BYTES = 4 * 1024 * 1024;
+
+export type NativeHarnessBackupExpirationOptions = {
+ closedForDays?: number;
+ dryRun?: boolean;
+ maxEntries?: number;
+ maxRemovals?: number;
+ now?: Date;
+ stateBase?: string;
+ shouldContinue?: () => boolean;
+ isSessionBusy?: (scopeDigest: string) => boolean;
+};
+
+export type NativeHarnessBackupExpirationResult = {
+ checked: number;
+ candidates: number;
+ candidateBytes: number;
+ expired: number;
+ reclaimedBytes: number;
+ clearedTaskSessions: number;
+ failed: number;
+ truncated: boolean;
+ skipped: Record<string, number>;
+};
+
+type SessionIdentity = {
+ runId: string;
+ normalizedSessionId: string;
+ environmentLeaseId: string | null;
+};
+
+function emptyResult(): NativeHarnessBackupExpirationResult {
+ return {
+ checked: 0,
+ candidates: 0,
+ candidateBytes: 0,
+ expired: 0,
+ reclaimedBytes: 0,
+ clearedTaskSessions: 0,
+ failed: 0,
+ truncated: false,
+ skipped: {},
+ };
+}
+
+async function isRealDirectory(target: string): Promise<boolean> {
+ const stat = await fs.lstat(target).catch(() => null);
+ return Boolean(stat?.isDirectory() && !stat.isSymbolicLink());
+}
+
+async function removeBackupTree(target: string): Promise<void> {
+ const prepare = async (current: string): Promise<void> => {
+ const stat = await fs.lstat(current).catch(() => null);
+ if (!stat?.isDirectory()) return;
+ await fs.chmod(current, (stat.mode & 0o777) | 0o700);
+ for (const name of await fs.readdir(current)) await prepare(path.join(current, name));
+ };
+ await prepare(target);
+ await fs.rm(target, { recursive: true, force: true });
+}
+
+async function allocatedBytes(target: string): Promise<number> {
+ const stat = await fs.lstat(target).catch(() => null);
+ if (!stat) return 0;
+ let bytes = stat.blocks * 512;
+ if (stat.isDirectory() && !stat.isSymbolicLink()) {
+ for (const entry of await fs.readdir(target).catch(() => [] as string[])) {
+ bytes += await allocatedBytes(path.join(target, entry));
+ }
+ }
+ return bytes;
+}
+
+async function readSessionIdentity(root: string): Promise<SessionIdentity | null> {
+ try {
+ const statePath = path.join(root, "control-plane", "control-plane-state.json");
+ const stat = await fs.lstat(statePath);
+ if (!stat.isFile() || stat.size > MAX_CONTROL_PLANE_STATE_BYTES) return null;
+ const state = JSON.parse(await fs.readFile(statePath, "utf8")) as { identity?: Record<string, unknown> };
+ const identity = state.identity ?? {};
+ const runId = identity.runId;
+ const normalizedSessionId = identity.normalizedSessionId;
+ const environmentLeaseId = identity.environmentLeaseId;
+ if (typeof runId !== "string" || !UUID_PATTERN.test(runId)) return null;
+ if (typeof normalizedSessionId !== "string" || !UUID_PATTERN.test(normalizedSessionId)) return null;
+ return {
+ runId,
+ normalizedSessionId,
+ environmentLeaseId:
+ typeof environmentLeaseId === "string" && UUID_PATTERN.test(environmentLeaseId)
+ ? environmentLeaseId
+ : null,
+ };
+ } catch {
+ return null;
+ }
+}
+
+type Tx = Parameters<Parameters<Db["transaction"]>[0]>[0];
+
+async function sessionRetentionBlocker(
+ tx: Tx,
+ input: { scopeDigest: string; identity: SessionIdentity; closedBefore: Date },
+): Promise<{ reason: string } | { companyId: string; agentId: string }> {
+ const [owner] = await tx
+ .select({ companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId })
+ .from(heartbeatRuns)
+ .where(eq(heartbeatRuns.id, input.identity.runId));
+ if (!owner) return { reason: "run_missing" };
+ const runs = await tx
+ .select({
+ id: heartbeatRuns.id,
+ status: heartbeatRuns.status,
+ finishedAt: heartbeatRuns.finishedAt,
+ issueId: sql<string | null>`coalesce(${heartbeatRuns.nativeIssueId}, ${heartbeatRuns.issueId})`,
+ })
+ .from(heartbeatRuns)
+ .where(
+ and(
+ eq(heartbeatRuns.companyId, owner.companyId),
+ eq(heartbeatRuns.agentId, owner.agentId),
+ eq(heartbeatRuns.nativeSessionId, input.identity.normalizedSessionId),
+ ),
+ );
+ if (runs.some((run) => LIVE_RUN_STATUSES.includes(run.status) || !run.finishedAt)) {
+ return { reason: "live_run" };
+ }
+ const issueIds = [...new Set(runs.map((run) => run.issueId).filter((id): id is string => Boolean(id)))];
+ if (issueIds.length === 0) return { reason: "issue_unknown" };
+ const issueRows = await tx
+ .select({
+ id: issues.id,
+ status: issues.status,
+ closedAt: sql<Date | null>`coalesce(${issues.completedAt}, ${issues.cancelledAt})`,
+ })
+ .from(issues)
+ .where(and(eq(issues.companyId, owner.companyId), inArray(issues.id, issueIds)))
+ .for("share");
+ if (issueRows.length !== issueIds.length) return { reason: "issue_unknown" };
+ for (const issue of issueRows) {
+ if (!CLOSED_ISSUE_STATUSES.includes(issue.status)) return { reason: "issue_open" };
+ const closedAt = issue.closedAt ? new Date(issue.closedAt) : null;
+ if (!closedAt || closedAt >= input.closedBefore) return { reason: "recently_closed" };
+ }
+ const runIds = runs.map((run) => run.id);
+ const [pending] = await tx
+ .select({ runId: nativeRunFinalizations.runId })
+ .from(nativeRunFinalizations)
+ .where(
+ and(
+ inArray(nativeRunFinalizations.runId, runIds),
+ or(
+ notInArray(nativeRunFinalizations.phase, SETTLED_FINALIZATION_PHASES),
+ sql`${nativeRunFinalizations.recoveryState} is not null`,
+ sql`${nativeRunFinalizations.leaseOwner} is not null`,
+ ),
+ ),
+ )
+ .limit(1);
+ if (pending) return { reason: "pending_finalization" };
+ const leaseReferences = [
+ sql`${environmentLeases.metadata}->'nativeHarnessBackup'->>'sessionScopeSha256' = ${input.scopeDigest}`,
+ inArray(environmentLeases.heartbeatRunId, runIds),
+ ];
+ if (input.identity.environmentLeaseId) {
+ leaseReferences.push(eq(environmentLeases.id, input.identity.environmentLeaseId));
+ }
+ const [lease] = await tx
+ .select({ id: environmentLeases.id })
+ .from(environmentLeases)
+ .where(and(inArray(environmentLeases.status, LIVE_LEASE_STATUSES), or(...leaseReferences)))
+ .limit(1);
+ if (lease) return { reason: "live_lease" };
+ return owner;
+}
+
+async function hasLiveRun(db: Db, owner: { companyId: string; agentId: string }, sessionId: string) {
+ const [run] = await db
+ .select({ id: heartbeatRuns.id })
+ .from(heartbeatRuns)
+ .where(
+ and(
+ eq(heartbeatRuns.companyId, owner.companyId),
+ eq(heartbeatRuns.agentId, owner.agentId),
+ eq(heartbeatRuns.nativeSessionId, sessionId),
+ or(inArray(heartbeatRuns.status, LIVE_RUN_STATUSES), isNull(heartbeatRuns.finishedAt)),
+ ),
+ )
+ .limit(1);
+ return Boolean(run);
+}
+
+export function nativeHarnessBackupExpirationService(
+ db: Db,
+ defaults: NativeHarnessBackupExpirationOptions = {},
+) {
+ let cursor: string | null = null;
+
+ async function settleLeftovers(backupRoot: string) {
+ const current = path.join(backupRoot, "current");
+ for (const name of await fs.readdir(backupRoot).catch(() => [] as string[])) {
+ const target = path.join(backupRoot, name);
+ if (name.startsWith(RETIRING_PREFIX) && UUID_PATTERN.test(name.slice(RETIRING_PREFIX.length))) {
+ if (!(await isRealDirectory(current))) await fs.rename(target, current);
+ else await removeBackupTree(target);
+ } else if (name.startsWith(EXPIRED_PREFIX) && UUID_PATTERN.test(name.slice(EXPIRED_PREFIX.length))) {
+ await removeBackupTree(target);
+ }
+ }
+ }
+
+ async function expireSession(
+ root: string,
+ scopeDigest: string,
+ options: Required<Pick<NativeHarnessBackupExpirationOptions, "dryRun" | "isSessionBusy">> & {
+ closedBefore: Date;
+ },
+ result: NativeHarnessBackupExpirationResult,
+ ) {
+ const skip = (reason: string) => {
+ result.skipped[reason] = (result.skipped[reason] ?? 0) + 1;
+ };
+ const backupRoot = path.join(root, "failover-backups");
+ const current = path.join(backupRoot, "current");
+ if (!options.dryRun) await settleLeftovers(backupRoot);
+ if (!(await isRealDirectory(current))) return skip("no_backup");
+ if (await fs.lstat(path.join(root, "cleanup-activation.json")).then(() => true, () => false)) {
+ return skip("cleanup_active");
+ }
+ if (options.isSessionBusy(scopeDigest)) return skip("session_active");
+ const backupStat = await fs.stat(current);
+ if (backupStat.mtime >= options.closedBefore) return skip("recent_backup");
+ const identity = await readSessionIdentity(root);
+ if (!identity) return skip("identity_unknown");
+
+ const decision = await db.transaction(async (tx) => {
+ const blocker = await sessionRetentionBlocker(tx, {
+ scopeDigest,
+ identity,
+ closedBefore: options.closedBefore,
+ });
+ if ("reason" in blocker) return blocker;
+ if (options.dryRun) return { owner: blocker, cleared: 0 };
+ const cleared = await tx
+ .delete(agentTaskSessions)
+ .where(
+ and(
+ eq(agentTaskSessions.companyId, blocker.companyId),
+ eq(agentTaskSessions.agentId, blocker.agentId),
+ sql`${agentTaskSessions.sessionParamsJson}->>'sessionId' = ${identity.normalizedSessionId}`,
+ ),
+ )
+ .returning({ id: agentTaskSessions.id });
+ return { owner: blocker, cleared: cleared.length };
+ });
+ if ("reason" in decision) return skip(decision.reason);
+
+ const bytes = await allocatedBytes(current);
+ result.candidates++;
+ result.candidateBytes += bytes;
+ if (options.dryRun) return;
+ result.clearedTaskSessions += decision.cleared;
+ if (options.isSessionBusy(scopeDigest)) return skip("session_active");
+ const id = randomUUID();
+ const retiring = path.join(backupRoot, `${RETIRING_PREFIX}${id}`);
+ const trash = path.join(backupRoot, `${EXPIRED_PREFIX}${id}`);
+ await fs.rename(current, retiring);
+ let liveRun: boolean;
+ try {
+ liveRun = await hasLiveRun(db, decision.owner, identity.normalizedSessionId);
+ } catch (err) {
+ await fs.rename(retiring, current);
+ throw err;
+ }
+ if (liveRun) {
+ await fs.rename(retiring, current);
+ return skip("live_run");
+ }
+ await fs.rename(retiring, trash);
+ await removeBackupTree(trash);
+ result.expired++;
+ result.reclaimedBytes += bytes;
+ }
+
+ async function tick(options: NativeHarnessBackupExpirationOptions = {}) {
+ const closedForDays = Math.max(
+ 1,
+ options.closedForDays ?? defaults.closedForDays ?? NATIVE_HARNESS_BACKUP_EXPIRATION_DEFAULT_DAYS,
+ );
+ const dryRun = options.dryRun ?? defaults.dryRun ?? false;
+ const maxEntries = Math.max(1, options.maxEntries ?? defaults.maxEntries ?? 200);
+ const maxRemovals = Math.max(1, options.maxRemovals ?? defaults.maxRemovals ?? 50);
+ const shouldContinue = options.shouldContinue ?? defaults.shouldContinue ?? (() => true);
+ const isSessionBusy = options.isSessionBusy ?? defaults.isSessionBusy ?? nativeSessionScopeDigestIsBusy;
+ const base = path.resolve(options.stateBase ?? defaults.stateBase ?? nativeHarnessStateBase());
+ const closedBefore = new Date((options.now ?? defaults.now ?? new Date()).getTime() - closedForDays * DAY_MS);
+ const result = emptyResult();
+
+ const names = (await fs.readdir(base).catch(() => [] as string[]))
+ .filter((name) => SCOPE_PATTERN.test(name))
+ .sort();
+ const pending = cursor ? names.filter((name) => name > cursor!) : names;
+ for (const name of pending) {
+ if (!shouldContinue() || result.checked >= maxEntries || result.candidates >= maxRemovals) {
+ result.truncated = true;
+ break;
+ }
+ result.checked++;
+ cursor = name;
+ const root = path.join(base, name);
+ if (path.dirname(root) !== base || !(await isRealDirectory(root))) {
+ result.skipped.unsafe_path = (result.skipped.unsafe_path ?? 0) + 1;
+ continue;
+ }
+ try {
+ await expireSession(root, name, { dryRun, isSessionBusy, closedBefore }, result);
+ } catch (err) {
+ result.failed++;
+ logger.warn({ err, scope: name }, "native harness backup expiration skipped a session");
+ }
+ }
+ if (!result.truncated) cursor = null;
+ return result;
+ }
+
+ return { tick };
+}
diff --git a/server/src/services/native-runtime/native-harness-backup-stamp.ts b/server/src/services/native-runtime/native-harness-backup-stamp.ts
index 202bf8a9cf..865a2b853c 100644
--- a/server/src/services/native-runtime/native-harness-backup-stamp.ts
+++ b/server/src/services/native-runtime/native-harness-backup-stamp.ts
@@ -14,7 +14,7 @@ export interface NativeHarnessBackupStamp {
completedAt: string;
}
-function stateBase(): string {
+export function nativeHarnessStateBase(): string {
return resolve(
process.env.PAPERCLIP_RUNNER_STATE_DIR ??
resolve(
@@ -28,7 +28,7 @@ function stateBase(): string {
function stateRootFromDigest(digest: string): string | null {
if (!/^[0-9a-f]{64}$/.test(digest)) return null;
- const base = stateBase();
+ const base = nativeHarnessStateBase();
const root = resolve(base, digest);
return dirname(root) === base ? root : null;
}
diff --git a/server/src/services/native-runtime/native-session-executor.ts b/server/src/services/native-runtime/native-session-executor.ts
index 53222f06fc..53b972d77c 100644
--- a/server/src/services/native-runtime/native-session-executor.ts
+++ b/server/src/services/native-runtime/native-session-executor.ts
@@ -1665,6 +1665,18 @@ const initializingSessionToolAuthorities = new Set<string>();
const executingRunnerdSessionScopes = new Map<string, string>();
const executingNativeOwnerScopes = new Map<string, symbol>();
+export function nativeSessionScopeDigestIsBusy(digest: string): boolean {
+ const scopes = [
+ ...executingRunnerdSessionScopes.keys(),
+ ...initializingSessionToolAuthorities,
+ ...warmNativeSessions.keys(),
+ ...closingWarmNativeSessions.keys(),
+ ];
+ return scopes.some(
+ (scope) => createHash("sha256").update(scope).digest("hex") === digest,
+ );
+}
+
async function assertExternalNativeRunAuthority(db: Db, execution: NativeExecutionInput, authorityDatabase: Db = db): Promise<void> {
if (execution.schema === "paperclip.native-execution-input.v6") return dotRunnerBroker(db).assertRunAuthority(execution);
if (execution.schema === "paperclip.native-execution-input.v8") return museRunnerBroker(db).assertRunAuthority(execution, authorityDatabase);