diff --git a/doc/run-evidence-storage.md b/doc/run-evidence-storage.md index a6a6c5c7622..2ff50e61112 100644 --- a/doc/run-evidence-storage.md +++ b/doc/run-evidence-storage.md @@ -290,6 +290,19 @@ background worker and online preparation may delegate a settled native source with unproven coverage to the guarded read-only archive path. Rollbacks after enrollment require readers that support `s3_archive`. +A finalized local log can grow after its size and SHA-256 were recorded, for +example when a later attempt of the same run appended to the file. When the +recorded size and SHA-256 match a prefix of the current file, both the online +and offline paths archive every current byte as a read-only `s3_archive` log, +update the run's size and SHA-256 to the archived bytes, and record the original +prefix proof and the archived proof in a `run.historical_log_archived` activity +entry in the same transaction. When the recorded proof matches no prefix of the +file, the log stays on the volume and is reported as +`legacy_recorded_log_not_a_prefix`. The longer bytes must come from the local file; +a longer mirror copy stays blocked as `mirror_completeness_unproven`. While the +run still has a pending or leased attempt, the log stays blocked as +`legacy_writer_retry_pending`, and the publication rechecks this condition. + An interrupted trace import keeps an `s3-import-v1:` reference: reads still use the original local sidecars, while deletion and expiry retain responsibility for the staged object prefix. The automatic worker resumes the verified switch after restart or retry. diff --git a/server/src/services/run-evidence-migration-appended.test.ts b/server/src/services/run-evidence-migration-appended.test.ts new file mode 100644 index 00000000000..ebb0cf73284 --- /dev/null +++ b/server/src/services/run-evidence-migration-appended.test.ts @@ -0,0 +1,173 @@ +import { createHash } from "node:crypto"; +import { promises as fs } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { and, eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { activityLog, agents, companies, createDb, heartbeatRuns, issues, nativeRunFinalizations } from "@paperclipai/db"; +import type { StorageProvider } from "../storage/types.js"; +import { + EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, +} from "../__tests__/helpers/embedded-postgres.js"; + +const objects = vi.hoisted(() => new Map()); +const mirrors = vi.hoisted(() => new Map()); +const etag = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex"); +const provider = vi.hoisted((): StorageProvider => { + const digest = async (bytes: Buffer) => (await import("node:crypto")).createHash("sha256").update(bytes).digest("hex"); + return { + id: "s3", + async putObject() { throw new Error("unexpected unconditional write"); }, + async putObjectConditional(input) { + const old = objects.get(input.objectKey); + if (input.ifNoneMatch ? old : !old || await digest(old) !== input.ifMatch) + throw Object.assign(new Error("conflict"), { name: "PreconditionFailed" }); + const chunks: Buffer[] = []; + if (Buffer.isBuffer(input.body)) chunks.push(input.body); + else for await (const chunk of input.body as AsyncIterable) chunks.push(Buffer.from(chunk)); + const bytes = Buffer.concat(chunks); + objects.set(input.objectKey, bytes); + return { etag: await digest(bytes) }; + }, + async getObject(input) { + const bytes = objects.get(input.objectKey); + if (!bytes) throw Object.assign(new Error("missing"), { name: "NoSuchKey" }); + const { Readable: ReadableStream } = await import("node:stream"); + return { stream: ReadableStream.from([bytes]), etag: await digest(bytes), contentLength: bytes.length }; + }, + async headObject(input) { return { exists: objects.has(input.objectKey) }; }, + async deleteObject(input) { objects.delete(input.objectKey); }, + async listObjects(input) { return { keys: [...objects.keys()].filter(key => key.startsWith(input.prefix)) }; }, + }; +}); +vi.mock("./run-evidence-storage.js", () => ({ + resolveRunEvidenceStorage: () => ({ provider, keyPrefix: "run-logs", tracePrefix: "provider-traces" }), +})); +vi.mock("./run-log-store.js", async importOriginal => { + const actual = await importOriginal(); + const { Readable } = await import("node:stream"); + return { + ...actual, + openLegacyRunLogForMigration: async (logRef: string, options?: { requireCanonicalLocalFile?: boolean }) => { + const mirror = mirrors.get(logRef); + if (!mirror) return actual.openLegacyRunLogForMigration(logRef, options); + return { stream: Readable.from([mirror]), bytes: mirror.length, source: "mirror" as const }; + }, + }; +}); + +const { migrateRunEvidence } = await import("./run-evidence-migration.js"); +const { migrateRunEvidencePage } = await import("./run-evidence-migration-page.js"); +const { createObjectRunLogStore } = await import("./object-run-log-store.js"); +const support = await getEmbeddedPostgresTestSupport(); + +describe.skipIf(!support.supported)("run log migration after a retry appended to a finalized log", () => { + let db!: ReturnType; + let tempDb: Awaited> | null = null; + let directory = ""; + beforeAll(async () => { + tempDb = await startEmbeddedPostgresTestDatabase("paperclip-run-log-appended-"); + db = createDb(tempDb.connectionString); + directory = await fs.mkdtemp(path.join(os.tmpdir(), "run-log-appended-")); + vi.stubEnv("RUN_LOG_BASE_PATH", directory); + }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); + afterAll(async () => { + vi.unstubAllEnvs(); + await db?.$client.end(); + await tempDb?.cleanup(); + if (directory) await fs.rm(directory, { recursive: true, force: true }); + }); + + async function seed(prefix: string, file: string, recordedSha256 = etag(Buffer.from(prefix)), runtimeMode = "legacy") { + const [company] = await db.insert(companies).values({ name: "Logs", issuePrefix: `L${Math.random().toString(36).slice(2, 6).toUpperCase()}` }).returning(); + const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Worker" }).returning(); + const [run] = await db.insert(heartbeatRuns).values({ companyId: company!.id, agentId: agent!.id, status: "failed", runtimeMode }).returning(); + const logRef = `${company!.id}/${agent!.id}/${run!.id}.ndjson`; + await fs.mkdir(path.dirname(path.join(directory, logRef)), { recursive: true }); + await fs.writeFile(path.join(directory, logRef), file); + await db.update(heartbeatRuns).set({ logStore: "local_file", logRef, logBytes: Buffer.byteLength(prefix), logSha256: recordedSha256 }) + .where(eq(heartbeatRuns.id, run!.id)); + return { companyId: company!.id, agentId: agent!.id, runId: run!.id, logRef }; + } + + it.each([ + ["online", "legacy", (_companyId: string, runId: string) => migrateRunEvidencePage(db, { kinds: ["log"], limit: 100 }) + .then(page => ({ items: page.items.filter(item => item.id === runId) }))], + ["offline", "native", (companyId: string) => { + vi.stubEnv("PAPERCLIP_EPHEMERAL_MIGRATION", "true"); + return migrateRunEvidence(db, { apply: true, companyId, kinds: ["log"], preserveHistoricalFiles: true }) + .finally(() => vi.stubEnv("PAPERCLIP_EPHEMERAL_MIGRATION", "false")); + }], + ] as const)("archives every current byte when the recorded log is a prefix, keeping both proofs (%s)", async (_path, runtimeMode, migrate) => { + const first = '{"seq":1,"stream":"stdout","chunk":"first attempt"}\n'; + const retry = '{"seq":2,"stream":"stdout","chunk":"retry 再開"}\n'; + const f = await seed(first, first + retry, undefined, runtimeMode); + const result = await migrate(f.companyId, f.runId); + const full = Buffer.from(first + retry); + expect(result.items).toEqual([expect.objectContaining({ id: f.runId, state: "migrated", historicalArchive: true, + bytes: full.length, sha256: etag(full) })]); + const [row] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + expect(row).toMatchObject({ logStore: "s3_archive", logRef: `${f.companyId}/${f.agentId}/${f.runId}.archive`, + logBytes: full.length, logSha256: etag(full) }); + await fs.rm(path.join(directory, f.logRef)); + const store = createObjectRunLogStore({ provider, keyPrefix: "run-logs", assertWriterAuthority: async () => undefined }); + expect((await store.read({ store: "s3_archive", logRef: row!.logRef! })).content).toBe(first + retry); + const entries = await db.select({ action: activityLog.action, details: activityLog.details }).from(activityLog) + .where(and(eq(activityLog.companyId, f.companyId), eq(activityLog.entityId, f.runId))); + expect(entries).toEqual([{ action: "run.historical_log_archived", details: { + reason: "output_appended_after_finalize", + recorded: { bytes: Buffer.byteLength(first), sha256: etag(Buffer.from(first)) }, + bytes: full.length, sha256: etag(full), + } }]); + }); + + it("keeps an extended log on the volume while the same run still has an attempt pending", async () => { + const first = "first attempt\n"; + const f = await seed(first, `${first}retry output\n`, undefined, "native"); + const [issue] = await db.insert(issues).values({ companyId: f.companyId, title: "Retrying" }).returning(); + await db.update(heartbeatRuns).set({ nativeIssueId: issue!.id }).where(eq(heartbeatRuns.id, f.runId)); + await db.insert(nativeRunFinalizations).values({ runId: f.runId, companyId: f.companyId, issueId: issue!.id, + phase: "retryable_failure", nextAttemptAt: new Date(Date.now() + 60_000) }); + const online = await migrateRunEvidencePage(db, { kinds: ["log"], limit: 100 }); + expect(online.items.filter(item => item.id === f.runId)).toEqual([expect.objectContaining({ state: "blocked", reason: "legacy_writer_retry_pending" })]); + vi.stubEnv("PAPERCLIP_EPHEMERAL_MIGRATION", "true"); + const offline = await migrateRunEvidence(db, { apply: true, companyId: f.companyId, kinds: ["log"], preserveHistoricalFiles: true }) + .finally(() => vi.stubEnv("PAPERCLIP_EPHEMERAL_MIGRATION", "false")); + expect(offline.items).toEqual([expect.objectContaining({ id: f.runId, state: "blocked", reason: "legacy_writer_retry_pending" })]); + const [row] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + expect(row).toMatchObject({ logStore: "local_file", logRef: f.logRef, logBytes: Buffer.byteLength(first) }); + expect(await db.select().from(activityLog).where(eq(activityLog.companyId, f.companyId))).toEqual([]); + }); + + it("does not treat a longer mirror copy as the complete log", async () => { + const first = "first attempt\n"; + const f = await seed(first, first); + await fs.rm(path.join(directory, f.logRef)); + mirrors.set(f.logRef, Buffer.from(`${first}partial retry`)); + try { + const result = await migrateRunEvidence(db, { apply: true, companyId: f.companyId, kinds: ["log"] }); + expect(result.items).toEqual([expect.objectContaining({ id: f.runId, state: "blocked", reason: "mirror_completeness_unproven" })]); + const [row] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + expect(row).toMatchObject({ logStore: "local_file", logRef: f.logRef }); + } finally { + mirrors.delete(f.logRef); + } + }); + + it("keeps a log blocked under its own name when the recorded digest is not a prefix of the file", async () => { + const longer = await seed("original output\n", "different output\nand more\n"); + const shorter = await seed("original output that was longer\n", "original output\n"); + const same = await seed("original output\n", "originaX output\n"); + for (const f of [longer, shorter, same]) { + const online = await migrateRunEvidencePage(db, { kinds: ["log"], limit: 100 }); + expect(online.items.filter(item => item.id === f.runId)).toEqual([expect.objectContaining({ state: "blocked", reason: "legacy_recorded_log_not_a_prefix" })]); + vi.stubEnv("PAPERCLIP_EPHEMERAL_MIGRATION", "true"); + const offline = await migrateRunEvidence(db, { apply: true, companyId: f.companyId, kinds: ["log"], preserveHistoricalFiles: true }); + vi.stubEnv("PAPERCLIP_EPHEMERAL_MIGRATION", "false"); + expect(offline.items).toEqual([expect.objectContaining({ id: f.runId, state: "blocked", reason: "legacy_recorded_log_not_a_prefix" })]); + const [row] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, f.runId)); + expect(row).toMatchObject({ logStore: "local_file", logRef: f.logRef }); + expect(await db.select().from(activityLog).where(eq(activityLog.companyId, f.companyId))).toEqual([]); + } + }); +}); diff --git a/server/src/services/run-evidence-migration.ts b/server/src/services/run-evidence-migration.ts index 1b7c530f18d..0b31df5b2e1 100644 --- a/server/src/services/run-evidence-migration.ts +++ b/server/src/services/run-evidence-migration.ts @@ -1,7 +1,7 @@ import { createHash } from "node:crypto"; import { createReadStream, promises as fs } from "node:fs"; import path from "node:path"; -import { and, asc, desc, eq, gt, inArray, isNull, lte, or, sql } from "drizzle-orm"; +import { and, asc, desc, eq, gt, inArray, isNotNull, isNull, lte, notInArray, or, sql } from "drizzle-orm"; import { heartbeatRuns, heartbeatRunEvents, @@ -28,6 +28,28 @@ import { logActivity, publishActivity, type ActivityPublication } from "./activi import { logger } from "../middleware/logger.js"; const SETTLED = ["succeeded", "failed", "cancelled", "timed_out", "interrupted"]; +const NOT_A_PREFIX = "legacy_recorded_log_not_a_prefix"; + +async function recordedPrefixOfLongerLog(logRef: string, bytes: number, sha256: string, signal?: AbortSignal) { + const source = await openLegacyRunLogForMigration(logRef); + try { + if (source.bytes === undefined || source.bytes <= bytes) return false; + if (source.source !== "local") throw new Error("mirror_completeness_unproven"); + const hash = createHash("sha256"); + let remaining = bytes; + for await (const chunk of source.stream) { + signal?.throwIfAborted(); + if (remaining <= 0) break; + const part = Buffer.from(chunk).subarray(0, remaining); + hash.update(part); + remaining -= part.length; + } + if (remaining > 0 || hash.digest("hex") !== sha256) throw new Error(NOT_A_PREFIX); + return true; + } finally { + source.stream.destroy(); + } +} export interface RunEvidenceMigrationItem { kind: "log" | "trace"; id: string; @@ -95,6 +117,17 @@ export async function migrateRunEvidence( )})`, ); } + function noPendingAttempt() { + return sql`not exists (select 1 from ${nativeRunFinalizations} where ${and( + eq(nativeRunFinalizations.runId, heartbeatRuns.id), + eq(nativeRunFinalizations.companyId, heartbeatRuns.companyId), + or( + isNotNull(nativeRunFinalizations.nextAttemptAt), + isNotNull(nativeRunFinalizations.leaseOwner), + notInArray(nativeRunFinalizations.phase, ["committed", "terminal_failure"]), + ), + )})`; + } async function assertDrained(runId: string, companyId: string) { const [run] = await db .select({ id: heartbeatRuns.id }) @@ -144,9 +177,18 @@ export async function migrateRunEvidence( if (!run.logRef) throw new Error("legacy_reference_missing"); const originalLogRef = run.logRef; await assertDrained(run.id, run.companyId); - const historicalArchive = (preserveHistoricalFiles || preserveSettledNativeFiles) && run.runtimeMode === "native" && + const recorded = run.bytes !== null && run.sha256 ? { bytes: run.bytes, sha256: run.sha256 } : null; + const nativeHistory = (preserveHistoricalFiles || preserveSettledNativeFiles) && run.runtimeMode === "native" && (run.bytes === null || run.sha256 === null); - const scopedArchive = historicalArchive && preserveSettledNativeFiles; + const appended = recorded !== null + && await recordedPrefixOfLongerLog(run.logRef, recorded.bytes, recorded.sha256, options.signal); + const historicalArchive = nativeHistory || appended; + const scopedArchive = nativeHistory && preserveSettledNativeFiles; + if (appended) { + const [settled] = await db.select({ id: heartbeatRuns.id }).from(heartbeatRuns) + .where(and(eq(heartbeatRuns.id, run.id), eq(heartbeatRuns.companyId, run.companyId), noPendingAttempt())); + if (!settled) throw new Error("legacy_writer_retry_pending"); + } const sourceFence = scopedArchive ? options.apply ? await withNativeLogArchiveSource(db, run, undefined, async (_tx, fence) => fence) : await inspectNativeLogArchiveSource(db, run) : undefined; @@ -189,6 +231,7 @@ export async function migrateRunEvidence( throw new Error("mirror_completeness_unproven"); } const hash = createHash("sha256"); + const prefixHash = appended ? createHash("sha256") : undefined; const nativeCoverage = !historicalArchive && run.runtimeMode === "native" && (run.bytes === null || run.sha256 === null) ? createNativeRunLogCoverageVerifier(db, run.companyId, run.id) @@ -201,6 +244,8 @@ export async function migrateRunEvidence( options.signal?.throwIfAborted(); const bytes = Buffer.from(chunk); hash.update(bytes); + if (prefixHash && recorded && offset < recorded.bytes) + prefixHash.update(bytes.subarray(0, recorded.bytes - offset)); await nativeCoverage?.write(bytes); tail = Buffer.concat([tail, bytes]).subarray(-262144); if (writer) { @@ -222,12 +267,13 @@ export async function migrateRunEvidence( } const digest = hash.digest("hex"); if (source.source === "local") await source.assertUnchanged(); - if ( - (source.bytes !== undefined && source.bytes !== offset) || - (run.bytes !== null && run.bytes !== offset) || - (run.sha256 && run.sha256 !== digest) - ) + if (source.bytes !== undefined && source.bytes !== offset) throw new Error("legacy_length_or_digest_mismatch"); + if (appended) { + if (source.source !== "local") throw new Error("mirror_completeness_unproven"); + if (offset <= recorded!.bytes || prefixHash!.digest("hex") !== recorded!.sha256) throw new Error(NOT_A_PREFIX); + } else if ((run.bytes !== null && run.bytes !== offset) || (run.sha256 && run.sha256 !== digest)) + throw new Error(recorded ? NOT_A_PREFIX : "legacy_length_or_digest_mismatch"); for (const line of tail.toString("utf8").split("\n")) { try { const entry = JSON.parse(line); @@ -265,7 +311,8 @@ export async function migrateRunEvidence( if (source.source === "local") await source.assertUnchanged(); const publish = (database: Db) => database .update(heartbeatRuns) - .set({ logStore: historicalArchive ? "s3_archive" : "s3_segments", logRef: ref }) + .set({ logStore: historicalArchive ? "s3_archive" : "s3_segments", logRef: ref, + ...(appended ? { logBytes: offset, logSha256: digest } : {}) }) .where( and( eq(heartbeatRuns.id, run.id), @@ -279,6 +326,7 @@ export async function migrateRunEvidence( ? isNull(heartbeatRuns.logSha256) : eq(heartbeatRuns.logSha256, run.sha256), drainedWriter(), + appended ? noPendingAttempt() : undefined, run.runtimeMode === "native" && !historicalArchive ? sql`not exists (select 1 from ${heartbeatRunEvents} where ${and( nativeRunLogSourceWhere(run.companyId, run.id), @@ -289,18 +337,25 @@ export async function migrateRunEvidence( ) .returning({ id: heartbeatRuns.id }); const publications: ActivityPublication[] = []; + const publishArchive = async (tx: Db) => { + const result = await publish(tx); + if (!result.length) throw new Error("migration_publication_conflict"); + await logActivity(tx, { companyId: run.companyId, actorType: "system", actorId: "run-evidence-migration", + action: "run.historical_log_archived", entityType: "heartbeat_run", entityId: run.id, + agentId: run.agentId, runId: run.id, details: { ...(appended ? { reason: "output_appended_after_finalize", + recorded: { bytes: recorded!.bytes, sha256: recorded!.sha256 } } : {}), + bytes: offset, sha256: digest, ...(sourceFence ? { sourceFence } : {}) } }, publications); + return result; + }; const [updated] = scopedArchive ? await withNativeLogArchiveSource(db, run, sourceFence, async tx => { if (source.source !== "local") throw new Error("native_log_archive_local_source_required"); await source.assertUnchanged(); - const result = await publish(tx); - if (!result.length) throw new Error("migration_publication_conflict"); - await logActivity(tx, { companyId: run.companyId, actorType: "system", actorId: "run-evidence-migration", - action: "run.historical_log_archived", entityType: "heartbeat_run", entityId: run.id, - agentId: run.agentId, runId: run.id, details: { bytes: offset, sha256: digest, sourceFence } }, publications); - return result; + return publishArchive(tx); }) - : await publish(db); + : appended + ? await db.transaction(transaction => publishArchive(transaction as unknown as Db)) + : await publish(db); if (!updated) throw new Error("migration_publication_conflict"); item.state = "migrated"; for (const publication of publications) {