mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 03:36:57 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Native recovery must keep admitted provider state and useful workspace files. > - OpenCode binds its saved session to exact executable paths and hashes. > - A replacement image can remove those files even when session data is saved. > - Retaining a manifest alone cannot restore the missing launch files. > - This pull request saves the qualified files before provider work and restores the same owned paths. > - The benefit is cold continuity without relaxing the Runner guard or replaying a prior turn. ## Linked Issues or Issue Description Refs #19558. That fix retains the selected pack for ordinary continuation. This change adds durable file retention for a cold allocation. Related #19487 adjusts the admission budget; it does not retain launch files. A search of open and closed OpenCode cold/durable artifact PRs found no duplicate. **What happened?** A saved OpenCode session could outlive the image that supplied its Node executable, proxy, and native executable. A new image supplied different bytes. The Runner then correctly refused the changed launch profile. The saved harness did not contain the old files. **Expected behavior** Core must save qualified launch files before the first turn. It must restore those exact files under the same owned account and absolute paths. Unknown ownership, missing files, and changed hashes must still stop recovery. **Steps to reproduce** Start an admitted remote OpenCode session. Save its workspace, encrypted checkpoint, and harness data. Destroy the original allocation and controller files. Restore into a new allocation with an image whose qualified proxy has different bytes. Resume the same session. The new opt-in local qualification command automates this path with actual OpenCode and a local synthetic model. ## What Changed - Store company-bound, encrypted launch objects and canonical run/backup references. Generate migration 0438 through the normal database workflow. - Stage qualified Node, proxy, and native OpenCode files under a private content-addressed OS-account home. Record the account UID and exact launch paths. Preserve the Rust profile guard. - Gate first provider work on durable capture under the current native claim. Bound Stop/deadline waits while the actual late transfer keeps its worker and scratch ownership until settlement. Restore cold caches with verified staging and atomic rename. Keep live reattachment and historical image-rooted sessions on their existing paths. - Reuse bounded canonical expiration owners. Atomically fence old checkpoint authority with a strict company/run-scoped retirement marker before external deletion. Keep its indexed cleanup anchor across failed deletes and restart. Preserve earlier resume handles and reject later header or source-consumer writes. Add no idle scan or network call inside a transaction. - Add storage, race, executor, filesystem, and actual Rust resume regressions. Add the opt-in local Linux qualification command and operating limits in `doc/opencode-cold-recovery.md`. ## Verification - RED before repair: real PostgreSQL/AES cold restore lacked the launch files; normal executor preparation chose the new image pack. Separate regressions exposed lost upload receipts, missing cache repair, last-owner retirement, an account-UID mismatch, and a resume-handle race during external deletion. Each expected failure was captured before its repair. - Local qualification before the final master integration: 1,169 executor tests, 233 storage/archive/admission/expiration tests, all seven server typecheck layers, migration safety, and the actual Rust cold-resume test passed. - The maintained Linux command passed with two cached immutable Paperclip images whose proxy hashes differ. It removed the original account/controller trees, restored the production published cwd under a new lease, resumed the same actual OpenCode session, kept a useful file and prior model context, and made one new synthetic model request. No external model call or network was available in either container. - The object-store fixture uses real encrypted StorageService streams with an independent owned local directory. It is not hosted S3 acceptance or a complete task HTTP/actor workflow. Historical tasks still require normal effects reconciliation and recovery after deployment. - Review regressions reproduced partial-cache publication, resume-versus-deletion, fresh-writer and source-consumer resurrection, and unbounded Stop/deadline waits before each repair. They now pass through real filesystem, encrypted storage, PostgreSQL, and SDK boundaries. File validation is split from database ownership (384/831 source lines). - Clean runtime head `aadab7acc69ff959678030db46ffe2dcfbefe28f`: the maintained actual OpenCode cold qualification passed with `dirty:false`. It preserved the provider session and recorded launch paths, restored useful workspace content and prior model context, and made exactly one resumed synthetic model request. The 314,560,000-byte launch capture took 23.118 seconds; the later harness was 833,536 bytes. Subsequent repairs change backup-reference retirement and governed continuity-cache classification; capture, restore, launch, and published-workspace inputs are unchanged, so that runtime receipt remains scoped to those paths. The continuity-break consumer is verified separately. - Retention repair `c14d386cecf7123257918ba6a8d47307df2da397`: 68/68 affected real PostgreSQL/AES storage tests and 15/15 focused executor authority/admission cases pass. All seven server typecheck layers pass (source layers and unchanged test shards, with the final 590-file test layer repeated after fixture edits). All review threads have evidence-backed resolutions. Its subsequent CI caught the separate lifecycle-classification gap described below. The refreshed Paperclip review reported paused work, not a completed new review. - Final head `4d1cd3e3309e328b11abc85adc6d78c6d0c7f55d`: all 19 focused root-entry/executor cases and all three source declaration layers pass. [Greptile reviewed this exact head at 5/5](https://github.com/paperclipai/paperclip/pull/19622#issuecomment-6695984874). Final-head [CI verification](https://github.com/paperclipai/paperclip/actions/runs/42308908167/job/128214100339) passes: 60 successful checks, five conditional skips, and the explicitly neutral paused Paperclip review. No check is pending or failing. - CI also caught the launch cache missing from the session-root lifecycle contract. Both the writer scan and a real governed-replacement consumer failed locally before repair: old launch bytes remained in the active root. The cache now archives with the prior session state; the consumer verifies exact bytes are preserved in the archive and absent from the active root. - The latest review found that backup retirement could delete an independent run pin while a selected session retained the checkpoint. A real PostgreSQL/AES regression failed before the repair. Backup-only ownership now uses a NULL-safe exact backup predicate; the run pin belongs to fenced checkpoint expiration. The regression verifies checkpoint decryption and launch-file restoration after pending-backup cleanup, followed by deletion only after removing the final resume handle. - An executor first-session case checks new-session durable capture through the real capture helper and receipt propagation into the actual harness manifest at the backup boundary. Real storage cases verify the run-profile receipt and canonical backup/run pins. - Sequential closure reuse and simultaneous first admission are different scopes. A deterministic two-uploader test measures both independent uploads, one verified ready winner, loser-only deletion, and usable restoration for both runs. Each capture is bounded to 512 MiB and five minutes; up to three pending receipts per run are retained. There is no claim of global single-flight capture or a company-wide egress bound. - Earlier optional warm-ownership verification encountered missing local binaries. After exact-source setup, all nine ownership assertions passed; two other suites encountered local PostgreSQL setup/teardown contention, so those interrupted attempts are not passes. Required current-head CI supplies the broad final coverage. No deployment or hosted historical recovery is claimed. ## Risks - This adds two tables and a forward migration. The file object is bounded to 512 MiB. Capture adds one initial transfer; later harness archives exclude those large files. Company-scoped ready objects are shared and retained until the last canonical owner retires. Concurrent initial admissions can duplicate bounded transfers; each keeps independent ownership and cancellation rather than waiting on another controller. A continuity break retains the controller cache with its prior state until normal session-root cleanup, adding up to one bounded launch closure per retired state. - Cold continuity requires the same qualified Linux platform, supported runtime dependencies, owned account UID/home, and published absolute cwd. A mismatch fails closed. No alias or Rust guard change is included. - Existing image-rooted profiles have no retained file object. This change cannot backfill missing historical binaries. A fresh governed session must reconcile prior effects first. - Live reattachment does not read artifact objects. Storage or provenance failures before a new turn hold admission. They do not grant new execution, model, tool, or replay authority. ## Model Used OpenAI Codex, GPT-6 family, with reasoning, repository tools, code execution, and local browser tools. The exact served model ID and context window are not exposed in this session. No claim is made for unavailable model metadata. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
952 lines
45 KiB
TypeScript
952 lines
45 KiB
TypeScript
import { readNativeCheckpointRetirement, nativeCheckpointRetirement, MAX_NATIVE_CHECKPOINT_RETIREMENT_RUNS } from "./native-runner-checkpoint-retirement.js";
|
|
import { notifyExternalConversationSettlement } from "../external-conversation-settlement-notifications.js";
|
|
import { randomUUID } from "node:crypto";
|
|
import { promises as fs } from "node:fs";
|
|
import path from "node:path";
|
|
import { and, asc, eq, gt, gte, inArray, isNull, lt, or, sql } from "drizzle-orm";
|
|
import {
|
|
agentTaskSessions,
|
|
environmentLeases,
|
|
heartbeatRuns,
|
|
issues,
|
|
nativeRunFinalizations,
|
|
nativeRunnerCheckpoints,
|
|
nativeHarnessBackups,
|
|
nativeProviderArtifactReferences,
|
|
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";
|
|
import type { createDeliveryWorkCoordinator } from "../delivery-work-coordinator.js";
|
|
import { DELIVERY_QUEUES } from "../delivery-work-notifications.js";
|
|
import type { NativeHarnessBackupExpirationScope } from "../native-harness-backup-expiration-notifications.js";
|
|
import { deleteRetiredNativeHarnessBackup, durableNativeHarnessStorage } from "./native-harness-backup-storage.js";
|
|
import { retireObsoleteNativeHarnessBackup } from "./native-harness-backup-retention.js";
|
|
import type { StorageService } from "../../storage/types.js";
|
|
import { releaseExpiredNativeProviderArtifactRun } from "./native-provider-artifacts.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;
|
|
export const NATIVE_RUNNER_EVIDENCE_RETENTION_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 CONTINUITY_ARCHIVE_PATTERN = /^(\d{1,15})-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
const QUARANTINE_PATTERN =
|
|
/^([0-9a-f]{64})\.(?:identity_indeterminate|identity_mismatch)\.(\d{1,15})\.\d{1,10}\.[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
const QUARANTINE_CLEANUP_PATTERN = /^[0-9a-f]{64}\.identity_indeterminate\.cleanup\./;
|
|
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;
|
|
const CHECKPOINT_EXPIRATION_MAX_FAILED_PASSES = 3;
|
|
|
|
export type NativeHarnessBackupExpirationOptions = {
|
|
duty?: "backups" | "evidence";
|
|
closedForDays?: number;
|
|
evidenceRetentionDays?: number;
|
|
dryRun?: boolean;
|
|
maxEntries?: number;
|
|
maxRemovals?: number;
|
|
now?: Date;
|
|
stateBase?: string;
|
|
shouldContinue?: () => boolean;
|
|
isSessionBusy?: (scopeDigest: string) => boolean;
|
|
storage?: StorageService;
|
|
};
|
|
|
|
export type NativeHarnessBackupExpirationResult = {
|
|
checked: number;
|
|
candidates: number;
|
|
candidateBytes: number;
|
|
expired: number;
|
|
reclaimedBytes: number;
|
|
clearedTaskSessions: number;
|
|
evidenceCandidates: number;
|
|
evidenceCandidateBytes: number;
|
|
evidenceRemoved: number;
|
|
evidenceReclaimedBytes: number;
|
|
expiredCheckpoints: number;
|
|
checkpointCandidates: number;
|
|
failed: number;
|
|
truncated: boolean;
|
|
skipped: Record<string, number>;
|
|
};
|
|
|
|
type EvidenceContext = {
|
|
dryRun: boolean;
|
|
isSessionBusy: (scopeDigest: string) => boolean;
|
|
now: number;
|
|
retentionMs: number;
|
|
retainedBefore: number;
|
|
canInspect: () => boolean;
|
|
dueAt: (at: number) => void;
|
|
retry: () => void;
|
|
};
|
|
|
|
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,
|
|
evidenceCandidates: 0,
|
|
evidenceCandidateBytes: 0,
|
|
evidenceRemoved: 0,
|
|
evidenceReclaimedBytes: 0,
|
|
expiredCheckpoints: 0,
|
|
checkpointCandidates: 0,
|
|
failed: 0,
|
|
truncated: false,
|
|
skipped: {},
|
|
};
|
|
}
|
|
|
|
function missingPath(error: NodeJS.ErrnoException) {
|
|
if (error.code === "ENOENT") return null;
|
|
throw error;
|
|
}
|
|
|
|
async function isRealDirectory(target: string): Promise<boolean> {
|
|
const stat = await fs.lstat(target).catch(missingPath);
|
|
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> };
|
|
if (!state || typeof state !== "object" || Array.isArray(state)) return null;
|
|
const identity = state.identity ?? {};
|
|
if (!identity || typeof identity !== "object" || Array.isArray(identity)) return null;
|
|
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 (error) {
|
|
if (error instanceof SyntaxError || ["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) return null;
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export type NativeHarnessBackupDependencies = {
|
|
companyId: string; agentId: string; sessionId: string; runIds: string[]; issueIds: string[]; leaseIds: string[];
|
|
};
|
|
|
|
type Tx = Parameters<Parameters<Db["transaction"]>[0]>[0];
|
|
|
|
async function sessionRetentionBlocker(
|
|
tx: Tx,
|
|
input: { scopeDigest: string | null; identity: SessionIdentity; closedBefore: Date; checkpoint?: boolean; lock?: boolean },
|
|
): Promise<{ reason: string } | { companyId: string; agentId: string; runIds: string[]; issueIds: string[]; closedAt: number }> {
|
|
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,
|
|
incompleteRecovery: sql<boolean>`(${heartbeatRuns.runnerProfileJson}->'nativeControllerRecovery'->>'schema' = 'paperclip.native-controller-recovery.v1'
|
|
and ${heartbeatRuns.runnerProfileJson}->'nativeControllerRecovery'->'checkpoint' = 'null'::jsonb) is true`,
|
|
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" };
|
|
}
|
|
if (runs.some(run => run.incompleteRecovery)) return { reason: "native_recovery_incomplete" };
|
|
if (input.checkpoint && runs.some(run => run.finishedAt! >= input.closedBefore)) return { reason: "recent_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 issueQuery = tx
|
|
.select({
|
|
id: issues.id,
|
|
status: issues.status,
|
|
executionRunId: issues.executionRunId,
|
|
closedAt: sql<Date | null>`coalesce(${issues.completedAt}, ${issues.cancelledAt})`,
|
|
})
|
|
.from(issues)
|
|
.where(and(eq(issues.companyId, owner.companyId), inArray(issues.id, issueIds)));
|
|
const issueRows = await (input.lock === false ? issueQuery : issueQuery.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" };
|
|
if (input.checkpoint && issue.executionRunId) return { reason: "live_run" };
|
|
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 finalizationQuery = tx
|
|
.select({ phase: nativeRunFinalizations.phase, recoveryState: nativeRunFinalizations.recoveryState,
|
|
leaseOwner: nativeRunFinalizations.leaseOwner })
|
|
.from(nativeRunFinalizations)
|
|
.where(inArray(nativeRunFinalizations.runId, runIds))
|
|
.orderBy(asc(nativeRunFinalizations.runId));
|
|
const finalizations = await (input.checkpoint ? finalizationQuery.for("update") : finalizationQuery);
|
|
if ((input.checkpoint && finalizations.length !== runIds.length)
|
|
|| finalizations.some(row => !SETTLED_FINALIZATION_PHASES.includes(row.phase) || row.leaseOwner)) {
|
|
return { reason: "pending_finalization" };
|
|
}
|
|
const leaseReferences = [
|
|
inArray(environmentLeases.heartbeatRunId, runIds),
|
|
];
|
|
if (input.scopeDigest) leaseReferences.push(
|
|
sql`${environmentLeases.metadata}->'nativeHarnessBackup'->>'sessionScopeSha256' = ${input.scopeDigest}`,
|
|
);
|
|
if (input.checkpoint) leaseReferences.push(
|
|
inArray(environmentLeases.issueId, issueIds),
|
|
and(eq(environmentLeases.companyId, owner.companyId),
|
|
sql`${environmentLeases.metadata}->'nativeHarnessBackup'->>'normalizedSessionId' = ${input.identity.normalizedSessionId}`)!,
|
|
);
|
|
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, runIds, issueIds, closedAt: issueRows.reduce((latest, issue) => Math.max(latest, new Date(issue.closedAt!).getTime()), Number.NEGATIVE_INFINITY) };
|
|
}
|
|
|
|
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 = {},
|
|
) {
|
|
const includeBackups = defaults.duty !== "evidence";
|
|
const includeEvidence = defaults.duty !== "backups";
|
|
let cursor: string | null = null;
|
|
let resume: { scope: string; archive: string } | null = null;
|
|
let quarantineCursor: string | null = null;
|
|
let phase: "sessions" | "quarantine" = "sessions";
|
|
let passActive = false;
|
|
let evidencePass = false;
|
|
let evidenceDueAt = 0;
|
|
let passDueAt = Number.POSITIVE_INFINITY;
|
|
let checkpointCursor: string | null = null;
|
|
let durableBackupCursor: string | null = null;
|
|
let checkpointsEnumerated = false;
|
|
|
|
async function expireDurableBackups(options: {
|
|
closedBefore: Date; dryRun: boolean; maxEntries: number; maxRemovals: number; shouldContinue: () => boolean;
|
|
}, result: NativeHarnessBackupExpirationResult) {
|
|
const storage = defaults.storage ?? durableNativeHarnessStorage();
|
|
if (!storage) return;
|
|
const candidates = await db.select({ id: nativeHarnessBackups.id, scopeDigest: nativeHarnessBackups.scopeDigest,
|
|
companyId: nativeHarnessBackups.companyId, runId: nativeHarnessBackups.runId, survivingRunId: heartbeatRuns.id,
|
|
sessionId: heartbeatRuns.nativeSessionId, status: nativeHarnessBackups.status })
|
|
.from(nativeHarnessBackups).leftJoin(heartbeatRuns, eq(heartbeatRuns.id, nativeHarnessBackups.runId))
|
|
.where(and(durableBackupCursor ? gt(nativeHarnessBackups.id, durableBackupCursor) : undefined,
|
|
or(eq(nativeHarnessBackups.status, "retired"), lt(nativeHarnessBackups.createdAt, options.closedBefore))))
|
|
.orderBy(asc(nativeHarnessBackups.id)).limit(options.maxEntries + 1);
|
|
let processed = 0;
|
|
for (const candidate of candidates) {
|
|
if (!options.shouldContinue() || processed++ >= options.maxEntries || result.expired >= options.maxRemovals) {
|
|
result.truncated = true; return;
|
|
}
|
|
durableBackupCursor = candidate.id;
|
|
if (candidate.survivingRunId && !candidate.sessionId) continue;
|
|
try {
|
|
const retired = candidate.status === "retired" || await db.transaction(async tx => {
|
|
if (["pending", "superseded"].includes(candidate.status)) {
|
|
const obsolete = await retireObsoleteNativeHarnessBackup(tx, { ...candidate,
|
|
closedBefore: options.closedBefore, dryRun: options.dryRun });
|
|
if (obsolete) result.candidates++;
|
|
return obsolete && !options.dryRun;
|
|
}
|
|
if (!candidate.survivingRunId) {
|
|
result.candidates++;
|
|
if (options.dryRun) return false;
|
|
await tx.update(nativeHarnessBackups).set({ status: "retired", updatedAt: new Date() })
|
|
.where(eq(nativeHarnessBackups.id, candidate.id));
|
|
return true;
|
|
}
|
|
const blocker = await sessionRetentionBlocker(tx, { scopeDigest: candidate.scopeDigest, checkpoint: true,
|
|
closedBefore: options.closedBefore,
|
|
identity: { runId: candidate.runId, normalizedSessionId: candidate.sessionId!, environmentLeaseId: null } });
|
|
if ("reason" in blocker) return false;
|
|
const [recent] = await tx.select({ id: nativeHarnessBackups.id }).from(nativeHarnessBackups).where(and(
|
|
eq(nativeHarnessBackups.companyId, blocker.companyId), eq(nativeHarnessBackups.scopeDigest, candidate.scopeDigest),
|
|
gte(nativeHarnessBackups.createdAt, options.closedBefore))).limit(1);
|
|
if (recent) return false;
|
|
result.candidates++;
|
|
if (options.dryRun) return false;
|
|
await notifyExternalConversationSettlement(tx, { companyId: blocker.companyId });
|
|
await tx.update(nativeRunFinalizations).set({ controllerGeneration: sql`${nativeRunFinalizations.controllerGeneration} + 1` })
|
|
.where(inArray(nativeRunFinalizations.runId, blocker.runIds));
|
|
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`${blocker.companyId}:${candidate.scopeDigest}`}, 0))`);
|
|
const cleared = await tx.delete(agentTaskSessions).where(and(eq(agentTaskSessions.companyId, blocker.companyId),
|
|
eq(agentTaskSessions.agentId, blocker.agentId), or(inArray(agentTaskSessions.lastRunId, blocker.runIds),
|
|
sql`${agentTaskSessions.sessionParamsJson}->>'sessionId' = ${candidate.sessionId}`))).returning({ id: agentTaskSessions.id });
|
|
result.clearedTaskSessions += cleared.length;
|
|
await tx.update(nativeHarnessBackups).set({ status: "retired", updatedAt: new Date() }).where(and(
|
|
eq(nativeHarnessBackups.companyId, blocker.companyId), eq(nativeHarnessBackups.scopeDigest, candidate.scopeDigest)));
|
|
return true;
|
|
});
|
|
if (retired && !options.dryRun && await deleteRetiredNativeHarnessBackup(db, storage, candidate.id, AbortSignal.timeout(60_000))) result.expired++;
|
|
} catch (err) {
|
|
result.failed++;
|
|
logger.warn({ err, backupId: candidate.id }, "durable native harness backup expiration skipped an object");
|
|
}
|
|
}
|
|
durableBackupCursor = null;
|
|
}
|
|
|
|
async function expireCheckpoints(options: {
|
|
closedBefore: Date; dryRun: boolean; maxEntries: number; maxRemovals: number; shouldContinue: () => boolean;
|
|
}, result: NativeHarnessBackupExpirationResult) {
|
|
// The partial header index enumerates retained checkpoints without reading
|
|
// event payloads or scanning runs that have no checkpoint left to expire.
|
|
const candidates = await db.select({ runId: heartbeatRuns.id, companyId: heartbeatRuns.companyId, sessionId: heartbeatRuns.nativeSessionId,
|
|
retirement: sql<Record<string, unknown> | null>`case when ${nativeRunnerCheckpoints.material}->>'schema' like 'paperclip.native-runner-checkpoint-retirement.%' then ${nativeRunnerCheckpoints.material} else null end` })
|
|
.from(nativeRunnerCheckpoints)
|
|
.innerJoin(nativeRunFinalizations, eq(nativeRunFinalizations.runId, nativeRunnerCheckpoints.runId))
|
|
.innerJoin(heartbeatRuns, eq(heartbeatRuns.id, nativeRunFinalizations.runId))
|
|
.where(and(
|
|
sql`${nativeRunnerCheckpoints.part} = 'header'`,
|
|
checkpointCursor ? gt(nativeRunnerCheckpoints.runId, checkpointCursor) : undefined,
|
|
lt(heartbeatRuns.finishedAt, options.closedBefore),
|
|
inArray(nativeRunFinalizations.phase, SETTLED_FINALIZATION_PHASES),
|
|
isNull(nativeRunFinalizations.leaseOwner), isNull(nativeRunFinalizations.recoveryState),
|
|
))
|
|
.orderBy(asc(nativeRunnerCheckpoints.runId)).limit(options.maxEntries + 1);
|
|
let processed = 0;
|
|
let removed = 0;
|
|
for (const candidate of candidates) {
|
|
if (!options.shouldContinue() || processed >= options.maxEntries || removed >= options.maxRemovals) {
|
|
result.truncated = true;
|
|
return;
|
|
}
|
|
processed++;
|
|
checkpointCursor = candidate.runId;
|
|
if (!candidate.sessionId) continue; // Unknown identity is never expiration evidence.
|
|
try {
|
|
const previousRetirement = readNativeCheckpointRetirement(candidate.retirement, candidate);
|
|
if (previousRetirement && previousRetirement.sessionId !== candidate.sessionId) throw new Error("native_runner_checkpoint_retirement_invalid");
|
|
const retirement = previousRetirement ?? await db.transaction(async tx => {
|
|
const blocker = await sessionRetentionBlocker(tx, {
|
|
scopeDigest: null, checkpoint: true, closedBefore: options.closedBefore,
|
|
identity: { runId: candidate.runId, normalizedSessionId: candidate.sessionId!, environmentLeaseId: null },
|
|
});
|
|
if ("reason" in blocker || blocker.runIds.length > MAX_NATIVE_CHECKPOINT_RETIREMENT_RUNS) return false;
|
|
const [resume] = await tx.select({ id: agentTaskSessions.id }).from(agentTaskSessions).where(and(
|
|
eq(agentTaskSessions.companyId, blocker.companyId), eq(agentTaskSessions.agentId, blocker.agentId),
|
|
or(inArray(agentTaskSessions.lastRunId, blocker.runIds),
|
|
sql`${agentTaskSessions.sessionParamsJson}->>'sessionId' = ${candidate.sessionId}`),
|
|
)).limit(1);
|
|
if (resume) return false;
|
|
result.checkpointCandidates++;
|
|
if (options.dryRun) return false;
|
|
// Serialize with checkpoint writers and retire every old authority for
|
|
// this session, including a predecessor authorized for warm handoff.
|
|
await tx.update(nativeRunFinalizations).set({
|
|
controllerGeneration: sql`${nativeRunFinalizations.controllerGeneration} + 1`,
|
|
}).where(inArray(nativeRunFinalizations.runId, blocker.runIds));
|
|
const retired = nativeCheckpointRetirement({ companyId: blocker.companyId, agentId: blocker.agentId,
|
|
sessionId: candidate.sessionId!, runIds: blocker.runIds });
|
|
await tx.update(nativeRunnerCheckpoints).set({ material: retired, updatedAt: new Date() }).where(and(
|
|
eq(nativeRunnerCheckpoints.companyId, blocker.companyId), inArray(nativeRunnerCheckpoints.runId, blocker.runIds),
|
|
eq(nativeRunnerCheckpoints.part, "header")));
|
|
return retired;
|
|
});
|
|
let expired = false;
|
|
if (retirement && !options.dryRun) {
|
|
const storage = defaults.storage ?? durableNativeHarnessStorage();
|
|
if (!storage) {
|
|
const [pending] = await db.select({ id: nativeProviderArtifactReferences.id }).from(nativeProviderArtifactReferences).where(and(
|
|
eq(nativeProviderArtifactReferences.companyId, retirement.companyId), inArray(nativeProviderArtifactReferences.runId, retirement.runIds),
|
|
isNull(nativeProviderArtifactReferences.backupId))).limit(1);
|
|
if (pending) throw new Error("native_provider_artifacts_storage_unavailable");
|
|
}
|
|
if (storage) for (const runId of retirement.runIds) await releaseExpiredNativeProviderArtifactRun({ db, storage,
|
|
companyId: retirement.companyId, runId, signal: AbortSignal.timeout(60_000) });
|
|
expired = !options.dryRun && await db.transaction(async tx => {
|
|
const [header] = await tx.select().from(nativeRunnerCheckpoints).where(and(
|
|
eq(nativeRunnerCheckpoints.companyId, retirement.companyId), eq(nativeRunnerCheckpoints.runId, candidate.runId),
|
|
eq(nativeRunnerCheckpoints.part, "header"))).for("update");
|
|
const current = header && readNativeCheckpointRetirement(header.material, candidate);
|
|
if (!current || current.retiredAt !== retirement.retiredAt || current.agentId !== retirement.agentId
|
|
|| current.sessionId !== retirement.sessionId || current.runIds.join(",") !== retirement.runIds.join(",")) return false;
|
|
const rows = await tx.delete(nativeRunnerCheckpoints).where(and(eq(nativeRunnerCheckpoints.companyId, retirement.companyId),
|
|
eq(nativeRunnerCheckpoints.runId, candidate.runId))).returning({ part: nativeRunnerCheckpoints.part });
|
|
return rows.length > 0;
|
|
});
|
|
}
|
|
if (expired) { removed++; result.expiredCheckpoints++; }
|
|
} catch (err) {
|
|
result.failed++;
|
|
logger.warn({ err, runId: candidate.runId }, "native runner checkpoint expiration skipped a run");
|
|
}
|
|
}
|
|
checkpointCursor = null;
|
|
}
|
|
|
|
async function settleLeftovers(backupRoot: string) {
|
|
const current = path.join(backupRoot, "current");
|
|
for (const name of (await fs.readdir(backupRoot).catch(missingPath)) ?? []) {
|
|
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 bytes = await allocatedBytes(current);
|
|
const id = randomUUID();
|
|
const retiring = path.join(backupRoot, `${RETIRING_PREFIX}${id}`);
|
|
const trash = path.join(backupRoot, `${EXPIRED_PREFIX}${id}`);
|
|
let retired = false;
|
|
let decision: { reason: string } | { cleared: number; bytes: number };
|
|
try {
|
|
decision = await db.transaction(async (tx) => {
|
|
const blocker = await sessionRetentionBlocker(tx, {
|
|
scopeDigest, identity, closedBefore: options.closedBefore,
|
|
});
|
|
if ("reason" in blocker) return blocker;
|
|
if ((await fs.stat(current)).mtime >= options.closedBefore) return { reason: "recent_backup" };
|
|
if (options.dryRun) return { cleared: 0, bytes };
|
|
if (options.isSessionBusy(scopeDigest)) return { reason: "session_active" };
|
|
await notifyExternalConversationSettlement(tx, { companyId: blocker.companyId });
|
|
await fs.rename(current, retiring);
|
|
retired = true;
|
|
if (await hasLiveRun(tx as unknown as Db, blocker, identity.normalizedSessionId)) {
|
|
await fs.rename(retiring, current);
|
|
retired = false;
|
|
return { reason: "live_run" };
|
|
}
|
|
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 { cleared: cleared.length, bytes };
|
|
});
|
|
} catch (error) {
|
|
if (retired) await fs.rename(retiring, current);
|
|
throw error;
|
|
}
|
|
if ("reason" in decision) return skip(decision.reason);
|
|
result.candidates++;
|
|
result.candidateBytes += decision.bytes;
|
|
if (options.dryRun) return;
|
|
result.clearedTaskSessions += decision.cleared;
|
|
await fs.rename(retiring, trash);
|
|
await removeBackupTree(trash);
|
|
result.expired++;
|
|
result.reclaimedBytes += decision.bytes;
|
|
}
|
|
|
|
async function removeExpiredLeftovers(parent: string, context: EvidenceContext, result: NativeHarnessBackupExpirationResult) {
|
|
for (const name of await fs.readdir(parent).catch((error: NodeJS.ErrnoException) => {
|
|
if (error.code === "ENOENT") return [] as string[];
|
|
throw error;
|
|
})) {
|
|
if (!name.startsWith(EXPIRED_PREFIX) || !UUID_PATTERN.test(name.slice(EXPIRED_PREFIX.length))) continue;
|
|
if (!context.canInspect()) {
|
|
context.dueAt(context.now);
|
|
return;
|
|
}
|
|
result.checked++;
|
|
await removeBackupTree(path.join(parent, name));
|
|
}
|
|
}
|
|
|
|
async function retireEvidence(
|
|
parent: string,
|
|
name: string,
|
|
scopeDigest: string,
|
|
stampedAt: number,
|
|
context: EvidenceContext,
|
|
result: NativeHarnessBackupExpirationResult,
|
|
) {
|
|
const skip = (reason: string) => {
|
|
result.skipped[reason] = (result.skipped[reason] ?? 0) + 1;
|
|
};
|
|
const target = path.join(parent, name);
|
|
const stat = await fs.lstat(target).catch(missingPath);
|
|
if (path.dirname(target) !== parent || !stat?.isDirectory()) {
|
|
return skip("unsafe_path");
|
|
}
|
|
const createdAt = stampedAt > 0 && stampedAt <= context.now ? stampedAt : stat.mtimeMs;
|
|
if (createdAt >= context.retainedBefore) {
|
|
context.dueAt(createdAt + context.retentionMs + 1);
|
|
return skip("recent_evidence");
|
|
}
|
|
if (context.isSessionBusy(scopeDigest)) {
|
|
context.retry();
|
|
return skip("session_active");
|
|
}
|
|
const bytes = await allocatedBytes(target);
|
|
result.evidenceCandidates++;
|
|
result.evidenceCandidateBytes += bytes;
|
|
if (context.dryRun) return;
|
|
if (context.isSessionBusy(scopeDigest)) {
|
|
context.retry();
|
|
return skip("session_active");
|
|
}
|
|
const trash = path.join(parent, `${EXPIRED_PREFIX}${randomUUID()}`);
|
|
await fs.rename(target, trash);
|
|
await removeBackupTree(trash);
|
|
result.evidenceRemoved++;
|
|
result.evidenceReclaimedBytes += bytes;
|
|
}
|
|
|
|
async function retireContinuityBreaks(
|
|
root: string,
|
|
scopeDigest: string,
|
|
resumeAfter: string | null,
|
|
context: EvidenceContext,
|
|
result: NativeHarnessBackupExpirationResult,
|
|
): Promise<string | null> {
|
|
const parent = path.join(root, "continuity-breaks");
|
|
const stat = await fs.lstat(parent).catch(missingPath);
|
|
if (!stat) return null;
|
|
if (!stat.isDirectory()) {
|
|
result.skipped.unsafe_path = (result.skipped.unsafe_path ?? 0) + 1;
|
|
return null;
|
|
}
|
|
if (!context.dryRun) await removeExpiredLeftovers(parent, context, result);
|
|
let last = resumeAfter ?? "";
|
|
const names = (await fs.readdir(parent)).filter((name) => name > last).sort();
|
|
for (const name of names) {
|
|
const match = CONTINUITY_ARCHIVE_PATTERN.exec(name);
|
|
if (!match) continue;
|
|
if (!context.canInspect()) return last;
|
|
result.checked++;
|
|
last = name;
|
|
try {
|
|
await retireEvidence(parent, name, scopeDigest, Number(match[1]), context, result);
|
|
} catch (err) {
|
|
result.failed++;
|
|
context.retry();
|
|
logger.warn({ err, scope: scopeDigest }, "native runner evidence retention skipped a continuity archive");
|
|
}
|
|
}
|
|
if (!context.dryRun) await fs.rmdir(parent).catch(() => undefined);
|
|
return null;
|
|
}
|
|
|
|
async function retireQuarantine(
|
|
base: string,
|
|
context: EvidenceContext,
|
|
result: NativeHarnessBackupExpirationResult,
|
|
): Promise<boolean> {
|
|
const parent = path.join(base, "quarantine");
|
|
const stat = await fs.lstat(parent).catch(missingPath);
|
|
if (!stat) return true;
|
|
if (!stat.isDirectory()) {
|
|
result.skipped.unsafe_path = (result.skipped.unsafe_path ?? 0) + 1;
|
|
return true;
|
|
}
|
|
if (!context.dryRun && quarantineCursor === null) await removeExpiredLeftovers(parent, context, result);
|
|
const names = (await fs.readdir(parent)).sort();
|
|
const pending = quarantineCursor ? names.filter((name) => name > quarantineCursor!) : names;
|
|
for (const name of pending) {
|
|
const match = QUARANTINE_PATTERN.exec(name);
|
|
const cleanupArchive = QUARANTINE_CLEANUP_PATTERN.test(name);
|
|
if (!match && !cleanupArchive) continue;
|
|
if (!context.canInspect()) return false;
|
|
result.checked++;
|
|
quarantineCursor = name;
|
|
if (!match) {
|
|
result.skipped.cleanup_archive = (result.skipped.cleanup_archive ?? 0) + 1;
|
|
continue;
|
|
}
|
|
try {
|
|
await retireEvidence(parent, name, match[1]!, Number(match[2]), context, result);
|
|
} catch (err) {
|
|
result.failed++;
|
|
context.retry();
|
|
logger.warn({ err, scope: match[1] }, "native runner evidence retention skipped a quarantine entry");
|
|
}
|
|
}
|
|
quarantineCursor = null;
|
|
return true;
|
|
}
|
|
|
|
function noteEvidence(writtenAt: number) {
|
|
evidenceDueAt = Math.min(evidenceDueAt, writtenAt + evidenceRetentionMs() + (defaults.duty === "evidence" ? 1 : 0));
|
|
}
|
|
|
|
function evidenceRetentionMs(options: NativeHarnessBackupExpirationOptions = {}) {
|
|
return Math.max(
|
|
1,
|
|
options.evidenceRetentionDays ?? defaults.evidenceRetentionDays ?? NATIVE_RUNNER_EVIDENCE_RETENTION_DEFAULT_DAYS,
|
|
) * DAY_MS;
|
|
}
|
|
|
|
async function tick(options: NativeHarnessBackupExpirationOptions = {}) {
|
|
const closedForDays = Math.max(
|
|
1,
|
|
options.closedForDays ?? defaults.closedForDays ?? NATIVE_HARNESS_BACKUP_EXPIRATION_DEFAULT_DAYS,
|
|
);
|
|
const retentionMs = evidenceRetentionMs(options);
|
|
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 now = (options.now ?? defaults.now ?? new Date()).getTime();
|
|
const closedBefore = new Date(now - closedForDays * DAY_MS);
|
|
const result = emptyResult();
|
|
const hasBudget = () => shouldContinue() && result.candidates + result.evidenceCandidates < maxRemovals;
|
|
if (!passActive && !includeBackups && evidenceDueAt > now) return result;
|
|
if (!passActive) {
|
|
passActive = true;
|
|
evidencePass = includeEvidence && evidenceDueAt <= now;
|
|
if (evidencePass) {
|
|
evidenceDueAt = Number.POSITIVE_INFINITY;
|
|
passDueAt = Number.POSITIVE_INFINITY;
|
|
}
|
|
}
|
|
const context: EvidenceContext = {
|
|
dryRun,
|
|
isSessionBusy,
|
|
now,
|
|
retentionMs,
|
|
retainedBefore: now - retentionMs,
|
|
canInspect: () => hasBudget() && result.checked < maxEntries,
|
|
dueAt: (at) => {
|
|
passDueAt = Math.min(passDueAt, at);
|
|
},
|
|
retry: () => {
|
|
passDueAt = Math.min(passDueAt, now + (defaults.duty === "evidence" ? 60 * 60_000 : 0));
|
|
},
|
|
};
|
|
|
|
if (phase === "sessions") {
|
|
const names = (await fs.readdir(base).catch((error: NodeJS.ErrnoException) => {
|
|
if (error.code === "ENOENT") return [] as string[];
|
|
throw error;
|
|
}))
|
|
.filter((name) => SCOPE_PATTERN.test(name))
|
|
.sort();
|
|
const pending = cursor ? names.filter((name) => name > cursor!) : names;
|
|
for (const name of pending) {
|
|
if (!hasBudget() || result.checked >= maxEntries) {
|
|
result.truncated = true;
|
|
break;
|
|
}
|
|
const resumeAfter = resume?.scope === name ? resume.archive : null;
|
|
if (resume && name >= resume.scope) resume = null;
|
|
if (resumeAfter === null) result.checked++;
|
|
const previous = cursor;
|
|
cursor = name;
|
|
const root = path.join(base, name);
|
|
try {
|
|
if (path.dirname(root) !== base || !(await isRealDirectory(root))) {
|
|
result.skipped.unsafe_path = (result.skipped.unsafe_path ?? 0) + 1;
|
|
continue;
|
|
}
|
|
} catch (err) {
|
|
result.failed++;
|
|
context.retry();
|
|
logger.warn({ err, scope: name }, "native runner retention could not inspect a session root");
|
|
continue;
|
|
}
|
|
if (resumeAfter === null && includeBackups) {
|
|
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 (!evidencePass) continue;
|
|
let stoppedAt: string | null = null;
|
|
try {
|
|
stoppedAt = await retireContinuityBreaks(root, name, resumeAfter, context, result);
|
|
} catch (err) {
|
|
result.failed++;
|
|
context.retry();
|
|
logger.warn({ err, scope: name }, "native runner evidence retention skipped a session");
|
|
}
|
|
if (stoppedAt !== null) {
|
|
resume = { scope: name, archive: stoppedAt };
|
|
cursor = previous;
|
|
result.truncated = true;
|
|
break;
|
|
}
|
|
}
|
|
if (result.truncated) return result;
|
|
cursor = null;
|
|
if (!evidencePass) {
|
|
passActive = false;
|
|
return result;
|
|
}
|
|
phase = "quarantine";
|
|
}
|
|
try {
|
|
if (!(await retireQuarantine(base, context, result))) {
|
|
result.truncated = true;
|
|
return result;
|
|
}
|
|
} catch (err) {
|
|
result.failed++;
|
|
context.retry();
|
|
quarantineCursor = null;
|
|
logger.warn({ err }, "native runner evidence retention skipped quarantine");
|
|
}
|
|
phase = "sessions";
|
|
passActive = false;
|
|
evidencePass = false;
|
|
evidenceDueAt = Math.min(evidenceDueAt, passDueAt);
|
|
return result;
|
|
}
|
|
|
|
function nextEvidenceAt() {
|
|
if (passActive) return Date.now();
|
|
return Number.isFinite(evidenceDueAt) ? evidenceDueAt : null;
|
|
}
|
|
|
|
async function tickCheckpoints(options: NativeHarnessBackupExpirationOptions = {}) {
|
|
const closedForDays = Math.max(1, options.closedForDays ?? defaults.closedForDays ?? NATIVE_HARNESS_BACKUP_EXPIRATION_DEFAULT_DAYS);
|
|
const result = emptyResult();
|
|
const shouldContinue = options.shouldContinue ?? defaults.shouldContinue ?? (() => true);
|
|
if (!shouldContinue()) return { ...result, truncated: true };
|
|
const pass = {
|
|
closedBefore: new Date((options.now ?? defaults.now ?? new Date()).getTime() - closedForDays * DAY_MS),
|
|
dryRun: options.dryRun ?? defaults.dryRun ?? false,
|
|
maxEntries: Math.max(1, options.maxEntries ?? defaults.maxEntries ?? 200),
|
|
maxRemovals: Math.max(1, options.maxRemovals ?? defaults.maxRemovals ?? 50),
|
|
shouldContinue,
|
|
};
|
|
if (!checkpointsEnumerated) {
|
|
await expireCheckpoints(pass, result);
|
|
if (result.truncated) return result;
|
|
checkpointsEnumerated = true;
|
|
}
|
|
await expireDurableBackups(pass, result);
|
|
if (!result.truncated) checkpointsEnumerated = false;
|
|
return result;
|
|
}
|
|
|
|
function registerCheckpointExpiration(coordinator: ReturnType<typeof createDeliveryWorkCoordinator>) {
|
|
// Opportunistic startup retention, not a recurring expiry obligation. A
|
|
// protected/recent checkpoint is reconsidered on the next server startup.
|
|
// Persisted rows remain safe; seven days is a minimum age, not a deadline.
|
|
let pending = true;
|
|
let retryFailedPage = false;
|
|
let failedPasses = 0;
|
|
const failedPass = (err?: unknown) => {
|
|
pending = ++failedPasses < CHECKPOINT_EXPIRATION_MAX_FAILED_PASSES;
|
|
logger.warn({ err, failedPasses }, pending
|
|
? "startup checkpoint expiration will retry a failed pass"
|
|
: "startup checkpoint expiration retries exhausted; retained checkpoints deferred to next startup");
|
|
};
|
|
return coordinator.register(DELIVERY_QUEUES.nativeCheckpointExpiration, {
|
|
retryMs: 1000,
|
|
pausePassiveMaintenance: true,
|
|
run: async () => {
|
|
if (!pending) return;
|
|
try {
|
|
const result = await tickCheckpoints();
|
|
retryFailedPage ||= result.failed > 0;
|
|
pending = result.truncated || retryFailedPage;
|
|
if (!result.truncated) {
|
|
if (retryFailedPage) failedPass();
|
|
retryFailedPage = false;
|
|
}
|
|
if (result.checkpointCandidates || result.failed) logger.info(result, "startup native checkpoint expiration");
|
|
} catch (err) {
|
|
// Candidate-query failures need the same finite startup budget as
|
|
// per-row failures; the shared coordinator otherwise retries forever.
|
|
failedPass(err);
|
|
}
|
|
},
|
|
hasPending: async () => pending,
|
|
});
|
|
}
|
|
|
|
async function backupDependencies(scopeDigest: string, identity: SessionIdentity): Promise<NativeHarnessBackupDependencies | null> {
|
|
const [owner] = await db.select({ companyId: heartbeatRuns.companyId, agentId: heartbeatRuns.agentId,
|
|
issueId: sql<string | null>`coalesce(${heartbeatRuns.nativeIssueId}, ${heartbeatRuns.issueId})`,
|
|
}).from(heartbeatRuns).where(eq(heartbeatRuns.id, identity.runId));
|
|
if (!owner) return null;
|
|
const runs = await db.select({ id: heartbeatRuns.id,
|
|
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, identity.normalizedSessionId)));
|
|
const runIds = [...new Set([identity.runId, ...runs.map(run => run.id)])];
|
|
const issueIds = [...new Set([owner.issueId, ...runs.map(run => run.issueId)].filter((id): id is string => Boolean(id)))];
|
|
const leases = await db.select({ id: environmentLeases.id }).from(environmentLeases).where(and(
|
|
eq(environmentLeases.companyId, owner.companyId), or(inArray(environmentLeases.heartbeatRunId, runIds),
|
|
sql`${environmentLeases.metadata}->'nativeHarnessBackup'->>'sessionScopeSha256' = ${scopeDigest}`,
|
|
identity.environmentLeaseId ? eq(environmentLeases.id, identity.environmentLeaseId) : undefined)));
|
|
return { companyId: owner.companyId, agentId: owner.agentId, sessionId: identity.normalizedSessionId,
|
|
runIds, issueIds, leaseIds: leases.map(lease => lease.id) };
|
|
}
|
|
|
|
async function resolveBackupScope(scope: NativeHarnessBackupExpirationScope) {
|
|
let runId = scope.runId;
|
|
let issueId = scope.issueId;
|
|
let scopeDigest = scope.scopeDigest;
|
|
if (scope.leaseId) {
|
|
const [lease] = await db.select({ runId: environmentLeases.heartbeatRunId, issueId: environmentLeases.issueId,
|
|
scopeDigest: sql<string | null>`${environmentLeases.metadata}->'nativeHarnessBackup'->>'sessionScopeSha256'`,
|
|
}).from(environmentLeases).where(and(eq(environmentLeases.companyId, scope.companyId), eq(environmentLeases.id, scope.leaseId)));
|
|
runId = lease?.runId ?? runId; issueId = lease?.issueId ?? issueId;
|
|
scopeDigest = lease?.scopeDigest && SCOPE_PATTERN.test(lease.scopeDigest) ? lease.scopeDigest : scopeDigest;
|
|
}
|
|
const [run] = runId ? await db.select({ agentId: heartbeatRuns.agentId, sessionId: heartbeatRuns.nativeSessionId,
|
|
issueId: sql<string | null>`coalesce(${heartbeatRuns.nativeIssueId}, ${heartbeatRuns.issueId})`,
|
|
}).from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, scope.companyId), eq(heartbeatRuns.id, runId))) : [];
|
|
return { runId, issueId: run?.issueId ?? issueId, agentId: run?.agentId ?? scope.agentId,
|
|
sessionId: run?.sessionId ?? scope.sessionId, scopeDigest };
|
|
}
|
|
|
|
async function reconcileBackup(scopeDigest: string) {
|
|
const base = path.resolve(defaults.stateBase ?? nativeHarnessStateBase());
|
|
const root = path.join(base, scopeDigest);
|
|
if (!SCOPE_PATTERN.test(scopeDigest) || !(await isRealDirectory(root))) return null;
|
|
const backupRoot = path.join(root, "failover-backups");
|
|
if (!(await isRealDirectory(backupRoot))) return null;
|
|
if (!defaults.dryRun) await settleLeftovers(backupRoot);
|
|
const current = path.join(backupRoot, "current");
|
|
const stat = await fs.lstat(current).catch(missingPath);
|
|
if (!stat?.isDirectory() || stat.isSymbolicLink()) return null;
|
|
const identity = await readSessionIdentity(root);
|
|
if (!identity) return null;
|
|
const dependencies = await backupDependencies(scopeDigest, identity);
|
|
if (!dependencies) return null;
|
|
const source = { id: scopeDigest, companyId: dependencies.companyId, agentId: dependencies.agentId, dependencies };
|
|
if (await fs.lstat(path.join(root, "cleanup-activation.json")).then(() => true, () => false)) {
|
|
return { ...source, dueAt: null };
|
|
}
|
|
const blocker = await db.transaction(tx => sessionRetentionBlocker(tx, {
|
|
scopeDigest, identity, closedBefore: new Date(8_000_000_000_000_000), lock: false,
|
|
}));
|
|
if ("reason" in blocker) return { ...source, dueAt: null };
|
|
const retentionMs = Math.max(1, defaults.closedForDays ?? NATIVE_HARNESS_BACKUP_EXPIRATION_DEFAULT_DAYS) * DAY_MS;
|
|
return { ...source, dueAt: Math.max(stat!.mtime.getTime(), blocker.closedAt) + retentionMs + 1 };
|
|
}
|
|
|
|
async function backupScopes(after?: string, limit = 100) {
|
|
const base = path.resolve(defaults.stateBase ?? nativeHarnessStateBase());
|
|
const names = (await fs.readdir(base).catch((error: NodeJS.ErrnoException) => {
|
|
if (error.code === "ENOENT") return [] as string[];
|
|
throw error;
|
|
})).filter(name => SCOPE_PATTERN.test(name) && (!after || name > after)).sort();
|
|
return { names: names.slice(0, limit), complete: names.length <= limit };
|
|
}
|
|
|
|
async function expireBackup(scopeDigest: string) {
|
|
if (!SCOPE_PATTERN.test(scopeDigest)) throw new Error("Invalid native harness backup scope");
|
|
const result = emptyResult();
|
|
const root = path.join(path.resolve(defaults.stateBase ?? nativeHarnessStateBase()), scopeDigest);
|
|
const dryRun = defaults.dryRun ?? false;
|
|
await expireSession(root, scopeDigest, {
|
|
dryRun,
|
|
isSessionBusy: defaults.isSessionBusy ?? nativeSessionScopeDigestIsBusy,
|
|
closedBefore: new Date(Date.now() - Math.max(1, defaults.closedForDays ?? NATIVE_HARNESS_BACKUP_EXPIRATION_DEFAULT_DAYS) * DAY_MS),
|
|
}, result);
|
|
return result;
|
|
}
|
|
|
|
return { tick, noteEvidence, nextEvidenceAt, tickCheckpoints, registerCheckpointExpiration,
|
|
reconcileBackup, backupScopes, expireBackup, resolveBackupScope };
|
|
}
|