mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-08 21:01:54 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work.
> - An ephemeral web server needs provider history in shared object
storage.
> - Offline enrollment must preserve old backups before it can detach a
volume.
> - A large copied dataset still exceeded the maintenance deadline with
parallel transfers.
> - Most of its bytes belong to successful turns with released runtime
authority.
> - This pull request pre-copies that history while unrelated executions
continue.
> - The final offline migration still verifies every source and grants
enrollment authority.
## Linked Issues or Issue Description
Refs #19108, #19038, #18943.
**What happened?**
A copied instance has 1,953 local harness backups and 54.8 GB of
declared source bytes. A resumed parallel migration still reached its
25-minute deadline. It cannot safely enroll by moving all history during
maintenance.
**Expected behavior**
Copy eligible completed history while the server remains online. Defer
active, failed or changed sources. Keep all existing data and final
enrollment checks.
**Steps to reproduce**
1. Retain many local native harness backups on a volume-backed instance.
2. Attempt a full offline conversion within the maintenance deadline.
3. Observe that most time moves historical bytes rather than current
execution state.
## What Changed
- Add finite `native-harness-prestage.mjs` preparation from a normal
runtime build. Require explicit opt-in and shared object storage.
Process one source at a time with a 90-minute deadline.
- Use the recorded released runtime owner of each successful, finished
turn. Do not assert that all writers stopped.
- Recheck checkout, related queued/running work, successful result
ownership, session, Runner, exact lease stamp and unchanged backup at
database publication fences.
- Defer source changes, malformed source JSON and unsafe backup roots.
Log each such source and its reason. Keep database failures and
cancellation fatal. Keep completed objects valid for retry. Never return
an enrollment-ready receipt.
- Reuse the bounded migration source walker. Keep offline admission and
final verification unchanged.
- Keep private lifecycle state, task ownership and provider policies
unchanged. Document the operator path and its limits.
## Verification
- A zero-source scan now checks the existing database obligation query.
A known mismatch blocks with a source-missing receipt; empty
fresh/already-durable scans and nonempty deferred scans remain valid
advisory results. The prior command fails the mismatch regression. All
16 command and runtime-bundle tests pass for this follow-up.
- At head `7ba3dbc7aa`, 87 focused command, database-timeout, storage,
archive, publication and runtime-bundle tests passed with real
PostgreSQL and filesystem restoration.
- The current follow-up passes all 68 backup and archive tests. A source
renamed after preparation fails the new regression on the previous head,
then defers and permits the next backup with this fix. An archive output
ENOENT remains fatal. Existing database-error and cancellation tests
pass.
- New race tests fail against the previous storage owner: a changed
backup, queued turn or revoked lease otherwise publishes.
- Tests prove unrelated executions stay running, same-task work defers,
failed history stays deferred, retry verifies existing objects, and
private bytes restore after deleting the old home.
- Command review fixes require the configured existing vault key, retain
it for the process, set database lock/statement/idle bounds, close
clients on cancellation, and cap shutdown at ten seconds. Abort
immediately sets failure status and prints one blocked receipt. A real
child with real shortened timers reproduces the old missing-receipt exit
and verifies the fix. Tests also use a real PostgreSQL lock.
- Malformed manifest or runner JSON and symlink replacement fail the new
preparation and publication-fence regressions on the previous code. The
fixed command defers each damaged source and copies the next eligible
backup. Separate tests keep database SyntaxError and cancellation fatal.
Offline migration still rejects damaged sources.
- The bundle test runs the emitted preparation entry with plain Node
without starting the app.
- A prior copied-data experiment completed with 1,738 new publications,
nine verified current objects and 206 deferred sources. Later checks
found different database and filesystem capture times: 43 source runs
were absent from the older database snapshot, and one required
historical manifest was absent from the retained filesystem archive.
This experiment does not prove a consistent restore or enrollment
readiness.
- Full current-head CI at ce63517d0c
passed: 54 successful checks, two skipped and one neutral, with no
failed or pending statuses. Typecheck, tests and build pass. CI:
https://github.com/paperclipai/paperclip/actions/runs/41970370960. The
earlier superseded run lost a spot runner after a shutdown signal; that
infrastructure cancellation is retained and is not counted as a passing
run.
- Greptile and Ponytail both rate this exact head 5/5; all actionable
review threads are resolved. Comment-only cleanup removes newly added
prose comments under CONTRIBUTING.md. TypeScript output with
removeComments:true is byte-identical for all seven changed TypeScript
files; 20 existing command, runtime and bundle tests pass after cleanup.
- Serving enrollment, full normal-image migration, empty-home
restoration and active-agent release handoffs remain separate acceptance
gates.
## Risks
- Preparation still consumes CPU, disk and storage requests. It uses one
transfer and at most two database connections. Check memory headroom for
a separate operator process.
- A task can gain work during upload. The final fence rejects that
publication and retains the previous current object.
- Deferred sources remain migration obligations. Preparation never
permits detaching the volume.
- Ordinary backup callers do not opt into the new preparation constraint
and keep their existing behavior.
## Model Used
OpenAI GPT-6.1 Codex, exact model ID `gpt-6.1-sol`. Used for reasoning,
code editing, shell tools and test execution. The runtime does not
expose its context-window size.
## 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>
221 lines
14 KiB
TypeScript
221 lines
14 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import { readdir } from "node:fs/promises";
|
|
import { join } from "node:path";
|
|
import { and, eq, inArray, or, sql } from "drizzle-orm";
|
|
import { environmentLeases, heartbeatRuns, issues, nativeHarnessBackups, nativeRunFinalizations, type Db } from "@paperclipai/db";
|
|
import type { StorageService } from "../../storage/types.js";
|
|
import { nativeHarnessStateBase, readNativeHarnessBackupStamp, verifyNativeHarnessBackupStampAsync } from "./native-harness-backup-stamp.js";
|
|
import { nativeHarnessBackupOwner, persistNativeHarnessBackup, verifyDurableNativeHarnessBackup } from "./native-harness-backup-storage.js";
|
|
import { MAX_NATIVE_HARNESS_BYTES, MAX_NATIVE_HARNESS_OBJECT_BYTES, nativeHarnessArchiveSizeLimit } from "./native-harness-backup-archive.js";
|
|
import { offlineMigrationExecutionWhere } from "../offline-migration-execution.js";
|
|
import { NativeHarnessBackupSourceError, readNativeHarnessBackupSource } from "./native-harness-backup-source.js";
|
|
|
|
export async function hasLocalNativeHarnessObligations(db: Db): Promise<boolean> {
|
|
const rows = await db.execute(sql`select 1 from agent_task_sessions s
|
|
join heartbeat_runs r on r.id = s.last_run_id and r.company_id = s.company_id and r.agent_id = s.agent_id
|
|
join environment_leases e on e.company_id = r.company_id and e.issue_id = r.native_issue_id
|
|
and e.metadata->'nativeHarnessBackup'->>'normalizedSessionId' = r.native_session_id::text
|
|
where s.adapter_type = 'paperclip_runner'
|
|
and e.metadata->'nativeHarnessBackup'->>'schema' = 'paperclip.native-harness-backup-stamp.v2'
|
|
and not exists (select 1 from native_harness_backups b where b.company_id = r.company_id
|
|
and b.scope_digest = e.metadata->'nativeHarnessBackup'->>'sessionScopeSha256' and b.status = 'current')
|
|
limit 1`);
|
|
return rows.length > 0;
|
|
}
|
|
|
|
const MAX_PARALLEL_BACKUPS = 4;
|
|
// An archive and its encrypted copy coexist. Keep the same worst-case scratch
|
|
// bound as one maximum-size serial transfer, including tar header overhead.
|
|
const MAX_SCRATCH_BYTES = 2 * MAX_NATIVE_HARNESS_OBJECT_BYTES;
|
|
|
|
async function prepareSource(base: string, scopeDigest: string) {
|
|
const root = join(base, scopeDigest, "failover-backups", "current");
|
|
const files = await readNativeHarnessBackupSource(root);
|
|
if (!files) return null;
|
|
const { manifestBytes, manifest, state } = files;
|
|
if (state.lifecycle !== "suspended" || typeof state.runId !== "string"
|
|
|| manifest.schema !== "paperclip.native-harness-backup.v1") throw new Error("native_harness_migration_source_unsettled");
|
|
const names = new Set<string>();
|
|
let bytes = manifestBytes.length, closed = Array.isArray(manifest.directories) && manifest.directories.length > 0;
|
|
for (const value of Array.isArray(manifest.directories) ? manifest.directories : []) {
|
|
const entry = value as { name?: unknown; bytes?: unknown } | null;
|
|
if (!entry || typeof entry.name !== "string" || !/^[A-Za-z0-9._-]+$/.test(entry.name)
|
|
|| [".", ".."].includes(entry.name) || !Number.isSafeInteger(entry.bytes) || Number(entry.bytes) < 0) { closed = false; break; }
|
|
names.add(entry.name); bytes += Number(entry.bytes);
|
|
}
|
|
const entries = await readdir(root, { withFileTypes: true });
|
|
closed &&= entries.length === names.size + 1 && entries.every(entry => entry.name === "manifest.json"
|
|
? entry.isFile() : names.has(entry.name) && entry.isDirectory() && !entry.isSymbolicLink());
|
|
// Unknown extra files are preserved with an exclusive full-size reservation.
|
|
const archiveLimit = closed && Number.isSafeInteger(bytes) && bytes <= MAX_NATIVE_HARNESS_BYTES
|
|
? nativeHarnessArchiveSizeLimit(bytes)
|
|
: MAX_NATIVE_HARNESS_OBJECT_BYTES;
|
|
return { root, scopeDigest, runId: state.runId as string, archiveLimit,
|
|
sessionId: manifest.normalizedSessionId, runnerId: manifest.runnerInstanceId,
|
|
manifestSha256: `sha256:${createHash("sha256").update(manifestBytes).digest("hex")}` };
|
|
}
|
|
|
|
type Source = NonNullable<Awaited<ReturnType<typeof prepareSource>>>;
|
|
|
|
async function sourceRun(db: Db, source: Source) {
|
|
const [run] = await db.select({ companyId: heartbeatRuns.companyId, issueId: heartbeatRuns.nativeIssueId,
|
|
sessionId: heartbeatRuns.nativeSessionId, runnerId: heartbeatRuns.runnerInstanceId,
|
|
status: heartbeatRuns.status, finishedAt: heartbeatRuns.finishedAt }).from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, source.runId));
|
|
if (!run) return null;
|
|
if (!run.issueId || !run.sessionId || !run.runnerId || run.sessionId !== source.sessionId || run.runnerId !== source.runnerId) {
|
|
throw new Error("native_harness_migration_binding_mismatch");
|
|
}
|
|
return { ...run, issueId: run.issueId, sessionId: run.sessionId, runnerId: run.runnerId };
|
|
}
|
|
|
|
async function verifiedSourceLease(db: Db, source: Source, run: NonNullable<Awaited<ReturnType<typeof sourceRun>>>, signal: AbortSignal) {
|
|
const leases = await db.select({ stamp: sql<unknown>`${environmentLeases.metadata}->'nativeHarnessBackup'`,
|
|
providerLeaseId: environmentLeases.providerLeaseId }).from(environmentLeases).where(and(
|
|
eq(environmentLeases.companyId, run.companyId), eq(environmentLeases.issueId, run.issueId),
|
|
sql`${environmentLeases.metadata}->'nativeHarnessBackup'->>'manifestSha256' = ${source.manifestSha256}`));
|
|
for (const lease of leases) {
|
|
const stamp = readNativeHarnessBackupStamp(lease.stamp, lease.providerLeaseId ?? "");
|
|
if (stamp?.sessionScopeSha256 === source.scopeDigest && await verifyNativeHarnessBackupStampAsync(stamp, lease.providerLeaseId!, signal)) return lease.providerLeaseId!;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
async function migrateSource(db: Db, input: { storage: StorageService; signal: AbortSignal }, source: Source) {
|
|
input.signal.throwIfAborted();
|
|
const { root, scopeDigest, manifestSha256 } = source, run = await sourceRun(db, source);
|
|
if (!run) return 0;
|
|
const [current] = await db.select().from(nativeHarnessBackups).where(and(eq(nativeHarnessBackups.companyId, run.companyId),
|
|
eq(nativeHarnessBackups.scopeDigest, scopeDigest), eq(nativeHarnessBackups.status, "current")));
|
|
if (current) {
|
|
if (current.manifestSha256 !== manifestSha256) throw new Error("native_harness_migration_durable_source_conflict");
|
|
await verifyDurableNativeHarnessBackup({ db, storage: input.storage, companyId: run.companyId,
|
|
scopeDigest, manifestSha256: current.manifestSha256, signal: input.signal });
|
|
return 1;
|
|
}
|
|
if (!await verifiedSourceLease(db, source, run, input.signal)) throw new Error("native_harness_migration_backup_unverified");
|
|
await persistNativeHarnessBackup({ db, storage: input.storage, root, scopeDigest, signal: input.signal,
|
|
maxArchiveBytes: source.archiveLimit,
|
|
owner: { kind: "offline_migration", writersStopped: true, companyId: run.companyId, issueId: run.issueId, runId: source.runId } });
|
|
return 1;
|
|
}
|
|
|
|
async function mapSources<T>(input: { signal: AbortSignal; concurrency?: number;
|
|
unavailableSource?: (error: unknown, scopeDigest: string) => T | undefined }, visit: (source: Source, signal: AbortSignal) => Promise<T>) {
|
|
const base = nativeHarnessStateBase();
|
|
const directories = await readdir(base).catch((error: NodeJS.ErrnoException) => {
|
|
if (error.code === "ENOENT") return [] as string[]; throw error;
|
|
});
|
|
let reserved = 0, wave: Source[] = [];
|
|
const results: T[] = [];
|
|
const flush = async () => {
|
|
const cancellation = new AbortController();
|
|
const signal = AbortSignal.any([input.signal, cancellation.signal]);
|
|
const settled = await Promise.allSettled(wave.map(async source => {
|
|
try { return await visit(source, signal); }
|
|
catch (error) { cancellation.abort(error); throw error; }
|
|
}));
|
|
// Never return failure while a peer can still upload or publish. Partial
|
|
// completed transfers remain valid for the next offline attempt.
|
|
if (cancellation.signal.aborted) throw cancellation.signal.reason;
|
|
for (const result of settled) {
|
|
if (result.status === "rejected") throw result.reason;
|
|
results.push(result.value);
|
|
}
|
|
wave = []; reserved = 0;
|
|
};
|
|
for (const scopeDigest of directories.filter(name => /^[a-f0-9]{64}$/.test(name)).sort()) {
|
|
input.signal.throwIfAborted();
|
|
let source;
|
|
try { source = await prepareSource(base, scopeDigest); }
|
|
catch (error) {
|
|
input.signal.throwIfAborted();
|
|
const deferred = input.unavailableSource?.(error, scopeDigest);
|
|
if (deferred === undefined) throw error;
|
|
results.push(deferred); continue;
|
|
}
|
|
if (!source) continue;
|
|
const reservation = 2 * source.archiveLimit;
|
|
if (wave.length && (wave.length === (input.concurrency ?? MAX_PARALLEL_BACKUPS) || reserved + reservation > MAX_SCRATCH_BYTES)) await flush();
|
|
wave.push(source); reserved += reservation;
|
|
}
|
|
if (wave.length) await flush();
|
|
return results;
|
|
}
|
|
|
|
export async function migrateNativeHarnessBackups(db: Db, input: {
|
|
storage: StorageService; writersStopped: true; signal: AbortSignal;
|
|
}): Promise<number> {
|
|
if (!input.writersStopped) throw new Error("native_harness_migration_requires_offline_writers");
|
|
const [active] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(offlineMigrationExecutionWhere()).limit(1);
|
|
if (active) throw new Error("native_harness_migration_requires_offline_writers");
|
|
const counts = await mapSources(input, (source, signal) => migrateSource(db, { storage: input.storage, signal }, source));
|
|
return counts.reduce<number>((total, count) => total + count, 0);
|
|
}
|
|
|
|
export async function prestageNativeHarnessBackups(db: Db, input: { storage: StorageService; signal: AbortSignal }) {
|
|
const deferSource = (scopeDigest: string, reason: string, outcome: string) => {
|
|
console.warn(JSON.stringify({ schema: "paperclip.native-harness-prestage-source.v1", scopeDigest, reason }));
|
|
return outcome;
|
|
};
|
|
const outcomes = await mapSources({ ...input, concurrency: 1, unavailableSource: (error, scopeDigest) => {
|
|
if (error instanceof NativeHarnessBackupSourceError || error instanceof Error && error.message === "native_harness_migration_source_unsettled") {
|
|
return deferSource(scopeDigest, error.message, "source_unavailable");
|
|
}
|
|
if (["ENOENT", "ENOTDIR", "EISDIR", "ELOOP", "EACCES", "EPERM"].includes((error as NodeJS.ErrnoException)?.code ?? "")) {
|
|
return deferSource(scopeDigest, "native_harness_migration_source_unavailable", "source_unavailable");
|
|
}
|
|
return undefined;
|
|
} }, async (source, signal) => {
|
|
signal.throwIfAborted();
|
|
const run = await sourceRun(db, source).catch(error => {
|
|
if (error instanceof Error && error.message === "native_harness_migration_binding_mismatch") return null;
|
|
throw error;
|
|
});
|
|
if (!run) return "missing_run";
|
|
const [current] = await db.select().from(nativeHarnessBackups).where(and(eq(nativeHarnessBackups.companyId, run.companyId),
|
|
eq(nativeHarnessBackups.scopeDigest, source.scopeDigest), eq(nativeHarnessBackups.status, "current")));
|
|
if (current) {
|
|
if (current.manifestSha256 !== source.manifestSha256) return "durable_source_changed";
|
|
await verifyDurableNativeHarnessBackup({ db, storage: input.storage, companyId: run.companyId,
|
|
scopeDigest: source.scopeDigest, manifestSha256: source.manifestSha256, signal });
|
|
return "current";
|
|
}
|
|
if (run.status !== "succeeded" || !run.finishedAt) return "source_not_successful";
|
|
const [coordinator] = await db.select().from(nativeRunFinalizations).where(and(
|
|
eq(nativeRunFinalizations.companyId, run.companyId), eq(nativeRunFinalizations.issueId, run.issueId),
|
|
eq(nativeRunFinalizations.runId, source.runId)));
|
|
if (coordinator?.phase !== "committed" || coordinator.leaseOwner || !coordinator.resultId || !coordinator.controllerBootId) return "owner_not_released";
|
|
const [task] = await db.select({ executionRunId: issues.executionRunId, checkoutRunId: issues.checkoutRunId }).from(issues)
|
|
.where(and(eq(issues.companyId, run.companyId), eq(issues.id, run.issueId)));
|
|
const [active] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns).where(and(
|
|
eq(heartbeatRuns.companyId, run.companyId), inArray(heartbeatRuns.status, ["queued", "running"]),
|
|
or(eq(heartbeatRuns.nativeIssueId, run.issueId), eq(heartbeatRuns.issueId, run.issueId), eq(heartbeatRuns.nativeSessionId, run.sessionId)))).limit(1);
|
|
if (!task || task.executionRunId || task.checkoutRunId || active) return "source_active";
|
|
const providerLeaseId = await verifiedSourceLease(db, source, run, signal);
|
|
if (!providerLeaseId) return "source_unverified";
|
|
try {
|
|
const owner = await nativeHarnessBackupOwner(db, { companyId: run.companyId, issueId: run.issueId,
|
|
runId: source.runId, bootId: coordinator.controllerBootId });
|
|
await persistNativeHarnessBackup({ db, storage: input.storage, root: source.root, scopeDigest: source.scopeDigest,
|
|
owner, signal, maxArchiveBytes: source.archiveLimit,
|
|
inactiveSource: { normalizedSessionId: run.sessionId, runnerInstanceId: run.runnerId, providerLeaseId } });
|
|
return "published";
|
|
} catch (error) {
|
|
signal.throwIfAborted();
|
|
if (error instanceof NativeHarnessBackupSourceError || error instanceof Error && ["native_runner_checkpoint_owner_lost", "native_harness_storage_owner_missing",
|
|
"native_harness_storage_prestage_source_active", "native_harness_storage_prestage_source_changed",
|
|
"native_harness_storage_owner_superseded", "native_harness_archive_invalid"].includes(error.message)) {
|
|
return deferSource(source.scopeDigest, error.message, "source_changed");
|
|
}
|
|
throw error;
|
|
}
|
|
});
|
|
const counts = { inspected: outcomes.length, published: 0, current: 0, deferred: {} as Record<string, number> };
|
|
for (const outcome of outcomes) {
|
|
if (outcome === "published" || outcome === "current") counts[outcome]++;
|
|
else counts.deferred[outcome] = (counts.deferred[outcome] ?? 0) + 1;
|
|
}
|
|
return counts;
|
|
}
|