fix(run-logs): archive a finalized log that a later attempt extended (#22709)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted stacks move from a volume to volume-free storage, and the
durable-data migration must move every run log first
> - Some finalized run logs grew after their size and SHA-256 were
recorded, because a later attempt of the same run appended to the same
local file
> - Both the online and offline migration refused these logs as
`legacy_length_or_digest_mismatch`, so the stack could never leave its
volume
> - This pull request archives such a log when the recorded proof
matches a prefix of the file, and names the real corruption case
distinctly
> - The benefit is that these stacks can move without deleting or hiding
any bytes, and real corruption still blocks the move

## Linked Issues or Issue Description

**What happened?**
Durable-data migration blocks a run log with
`legacy_length_or_digest_mismatch` when the local file is longer than
the size and SHA-256 recorded at finalize. The run log store never
truncates, so a later attempt that shares the run id appends to the
finalized file. The stack then cannot move to volume-free storage.

**Steps to reproduce**
1. Finalize a run log so that the run records its size and SHA-256.
2. Append more output to the same local file.
3. Run the online or offline durable-data migration.
4. See the log blocked as `legacy_length_or_digest_mismatch`.

**Expected behavior**
When the recorded size and SHA-256 match a prefix of the file, the
migration keeps every current byte, records both proofs, and lets the
stack move. When the recorded proof matches no prefix, the log stays
blocked under a distinct name.

## What Changed

- `server/src/services/run-evidence-migration.ts`: before it claims the
object journal, the migration checks if the recorded size and SHA-256
match a prefix of a longer file. If yes, it archives every current byte
as a read-only `s3_archive` log in the `<run>.archive` journal.
- The publish sets the run's size and SHA-256 to the archived bytes. In
the same transaction it writes a `run.historical_log_archived` activity
entry with the original prefix proof (`recorded`) and the new size and
SHA-256.
- A log whose recorded size and SHA-256 match no prefix (a different
longer file, a shorter file, or a same-size file with different bytes)
stays blocked as `legacy_recorded_log_not_a_prefix`. Nothing is uploaded
or published for a longer file that fails the prefix check.
- The extended log must come from the local file. A longer mirror copy
stays blocked as `mirror_completeness_unproven`, because a matching
prefix does not prove that the mirror holds the whole file.
- While the run still has a pending or leased attempt (a native
finalization with `next_attempt_at`, a lease owner, or a phase other
than `committed` or `terminal_failure`), the log stays blocked as
`legacy_writer_retry_pending`. The publish `WHERE` rechecks this
condition, so a later attempt of the same run never finds a read-only
archive.
- Both archive publications (settled native history and extended logs)
share one helper that publishes and writes the activity entry in one
transaction.
- `legacy_length_or_digest_mismatch` stays for the other cases: a source
that changed while it was read, and a run that recorded only one of size
or SHA-256.
- The online path (`migrateRunEvidencePage`) and the offline path
(`preserveHistoricalFiles`) use the same code, so the rule is the same
for both.
- `doc/run-evidence-storage.md` describes the new rule.

## Verification

- New test `server/src/services/run-evidence-migration-appended.test.ts`
uses embedded PostgreSQL, real local files and an in-memory object
store:
- online and offline: a log with appended output is archived, the run
row has the new size and SHA-256, the archive reads back every byte
after the local file is deleted, and one activity entry holds both
proofs.
- online and offline: a longer file, a shorter file and a same-size file
whose bytes differ stay blocked as `legacy_recorded_log_not_a_prefix`,
keep their local reference, and write no activity.
- online and offline: an extended log whose run has a pending attempt
stays blocked as `legacy_writer_retry_pending`, unchanged and with no
activity.
- a longer mirror copy (local file missing) stays blocked as
`mirror_completeness_unproven`.
- Red: the first 3 tests fail on master
(`legacy_length_or_digest_mismatch`). The pending-attempt and mirror
tests fail on the first commit. Green: all 5 pass with this change.
- `npx vitest run src/services/run-evidence-migration-appended.test.ts
src/services/run-evidence-migration-page.test.ts
src/services/online-durable-data-migration.test.ts`: 40 passed.
- `npx tsc --noEmit -p server`: clean.
- I did not run the opt-in S3 integration suite
(`run-evidence-migration.integration.test.ts`), because it needs an
external S3 endpoint. Its `wrong-digest` case records only a SHA-256, so
it keeps `legacy_length_or_digest_mismatch`.

## Risks

- An archived log is read-only. This is the same as the existing
historical archives. The publish requires a settled run with no writer
lease, so no attempt can still be writing.
- The prefix check reads the recorded prefix (not the whole file) one
more time before the copy. This happens only when the file is longer
than the recorded size. It lets a non-prefix file fail before anything
is uploaded.
- Low risk otherwise: logs whose bytes match their recorded proof follow
the same path as before.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, in Claude Code with
tool use and code execution.

## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

Related: #22697 (archived workspaces whose files are gone) and #22698
(skills whose remote source is gone) settle the other two cases that
block the same move.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-23 18:32:00 -06:00
1 parent 2e229c311f
commit 506211b917
3 files changed
+257 -16

No files matched your search

+13
View File
@@ -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.
@@ -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<string, Buffer>());
const mirrors = vi.hoisted(() => new Map<string, Buffer>());
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<Uint8Array>) 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<typeof import("./run-log-store.js")>();
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<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | 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([]);
}
});
});
+71 -16
View File
@@ -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) {