mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-03 01:27:09 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Operators use run logs and restricted provider traces to inspect agent work. > - Local log and trace files depend on the web server's persistent volume. > - That dependency prevents overlapping volume-backed Railway deployments. > - This PR reuses the instance S3 store for batched log and trace payloads with conditional publication. > - Existing Postgres rows retain their contracts; native export recovery reuses events already committed before Runner acknowledgement. > - S3-configured servers automatically copy and verify retained history before a later deployment cutover. ## Linked Issues or Issue Description **Subsystem affected** Server run logs, restricted provider traces, storage providers, and migration tooling. **Problem or motivation** Replacing the web server and its disk must preserve committed log output and retained traces. The current S3 mirror can repeatedly upload a growing file. Moving those payloads into Postgres would add database writes, WAL, replication, and backup work. **Proposed solution** Reuse the existing instance storage configuration, S3-compatible provider and credential chain. Store new run logs under run-logs/ and opted-in raw traces under provider-traces/, below the existing prefix. Cloud keeps its existing bucket and bucket-scoped credentials per stack. Add no new configuration switches. Store immutable payload segments and bounded binary range indexes directly in S3. Publish each batch with an ETag-conditional head. Keep existing database ownership and lifecycle records. Recover canonical native exports from their existing validated control event source, checkpointing export progress in S3. Add no new payload writes to Postgres. Preserve local defaults and migrate settled history with verified byte counts and digests. **Alternatives considered** Postgres payload chunks add control-plane load. Repeated whole-file mirrors amplify transfer work. The first index prototype left superseded index nodes; the final binary index keeps all normally published nodes reachable. **Roadmap alignment** This is a storage prerequisite for replacing the main web/API server. It does not enable deployment overlap, detach a volume, or change native Runner protocol acknowledgements. The maintainer approved this implementation scope. ROADMAP.md has no duplicate implementation item. Related PR: #16770 improves the existing in-flight mirror. This PR preserves that legacy backend and uses the existing instance S3 profile for new journals. ## What Changed - Automatically select S3 segments for new logs and opted-in traces when instance file storage uses S3. Reuse bucket, endpoint, region, prefix, path style and credentials. Remove separate backend switches. Keep local-disk instances local. - Share the existing storage configuration resolver with product files. Preserve config-file settings, environment precedence and the existing root prefix. Keep pre-existing run-log mirror settings for legacy history. - Add bounded buffering, conditional ownership fencing, immutable range reads, stable byte offsets, and completion hashing. - Dispatch all existing log consumers through the recorded backend. Coalesce output progress writes and publish live log messages after storage receipts. - Recover interrupted canonical native exports from their existing durable source. Exclude separate credential, cleanup, and reprojection records. Replay missing callback ranges and deduplicate late delivery. Repair settled archives after controller lease expiry. Bound shared repair work and stop it when all readers cancel. Serve the published prefix when best-effort repair fails. - Add encrypted optional trace channels, replacement reads, durable deletion tombstones, and deadline-driven local/external expiry cleanup independently of heartbeat scheduling. Stream historical source and remote verification. Propagate worker cancellation through trace open, conditional-write probing, upload, restore and reads. Fence deletion even before the first object head exists; abort and drain owned captures. - Retry transient storage errors, distinguish 409 from failed preconditions, and backpressure bounded log admission. Track interrupted trace imports explicitly so ordinary local deletion stays independent of S3. - Automatically migrate retained history through the existing delivery coordinator. Process one log and one trace per batch. Retry unresolved history with backoff and stop scans after completion. Keep the inventory/import command as optional diagnosis and repair. Verify source and remote bytes before switching references. Verify finalized native size and digest before setting its export cursor. Require ordered source coverage when completeness metadata is missing. Preserve original trace expiry. Block active, missing, corrupt, and unproven sources. - Preserve identity and run-secret redaction in live and recovered native logs. Register runtime log redaction secrets once through the existing encrypted registry. Keep agent private keys in their existing owner. - Add storage, migration, retention, UTF-8, and route-privacy coverage, plus operating documentation and qualification tooling. - Add no schema, payload table, per-record SQL, production dependency, or lockfile change. ## Verification - Final fixes at `b3a44c898e` passed all 116 selected startup, retention, attribution and cancellation controls. The disabled-scheduler cleanup and concurrent-repair defects reproduced red before the fixes. A timed-out repair still prevents later storage reads. - The merged source passed 124 storage and real-Postgres Cloud configuration tests. These include automatic history migration, existing environment/file vault keys, source-directory removal, five real-SDK stalled-request cancellation cases, shared capability-probe cancellation and multi-chunk trace ordering. Saved Cloud S3 settings work after the legacy config file is gone. - Workspace typecheck and full build passed at the merged parent `19f702d780`. Server typecheck and build passed again at `b3a44c898e`. - Actual app acceptance: finish a process-agent run through the normal API, stage its retained local-file input, then restart. Automatic migration reports one migrated item and zero blockers. Remove the original web home and restart at `b3a44c898e` with an empty home, the existing S3 profile and the existing vault key file. The normal log API preserves all five producer lines and exactly 788 bytes, with SHA-256 `74d9ae469da28bfe89b9b50a0e132aec24fe9e6d686496ed5e4ffa6167151036`. No log-specific storage settings are present. - Actual expiry acceptance: with heartbeat scheduling disabled, a trace remains unexpired after startup and later reaches its fixture deadline. The worker marks the row deleted and tombstones both S3 channel heads. The retained run log stays byte-identical. The process fixture emits no provider protocol frames, so nonempty encrypted payloads are qualified separately through the real SDK round trips. - Isolation tests use identical run identities in two stack buckets. Cleanup in one existing prefix leaves another prefix, another company and product files intact. Read-only Cloud source inspection confirms a bucket and bucket-scoped credentials per stack. Four existing Cloud storage environment-contract tests passed. No Cloud provisioning changed and no new live vendor permission probe was performed. - Earlier qualification passed 1,014 affected storage/native tests and 27 privacy-route tests with isolated Docker Postgres. An abrupt process test commits 1,000 records, receives receipts, dies by SIGKILL and loses its directory; another process reads every byte and continues. The real Rust Runner experiment acknowledges 32 records while the export cursor is zero, then continues the same Runner PID after controller loss. All 64 records export once with exactly 64 existing control rows. Repeated snapshot/Stop commands completed in 162/81 ms. - Emulator workload: 1,000 burst records used two batch PUTs. Eight steady streams produced 240 records with 104 conditional PUTs and 72 GETs over 6.9 seconds. These are synthetic operation counts, not fleet sizing or provider prices. - Failure evidence is retained. Compact native events over 64 KiB, missing file-key support, disabled-scheduler retention and repair failure handling all reproduced before their fixes. Fixture repairs addressed cold module setup, localhost/IPC permissions, the S3 bucket-name limit and a mode-0700 crash-test directory. Full local `pnpm test:run` was stopped after host PostgreSQL semaphore exhaustion; affected suites used isolated Docker databases instead. Native package library symlinks were restored with the package's standard hydration helper. - The `19f702d780` browser session-recovery case timed out while saving a task title. All eight browser shards passed on `b3a44c898e`, including that case, with no UI behavior or assertion change. Fresh-head CI passed at `b3a44c898e`: 55 successful checks, three skipped checks and one neutral check. The branch is conflict-free. - Map and module-boundary checks passed. Current-head Greptile is 5/5 with zero unresolved review threads. Reproduce the opt-in storage suites with `PAPERCLIP_LOG_TEST_S3_ENDPOINT` and a dedicated `PAPERCLIP_RUN_EVIDENCE_MIGRATION_DATABASE_URL` ending in `_test`. See `doc/run-evidence-storage.md` for operating limits, automatic migration, optional diagnostics and rollout qualification. ## Risks - Keep the existing per-stack bucket, prefix and vault key stable across replacements. Relocating that storage is a separate whole-instance operation. - This release automatically changes new log storage for existing S3-configured instances. Local-disk instances remain local. Canonical native source replay is qualified with a deterministic real Runner; actual remote execution and production-provider qualification remain rollout gates. Generic server-only diagnostics and optional raw trace tails without a surviving source can be incomplete after a crash. This does not establish full zero-downtime deployment. - Before deploying this release, qualify the actual S3 provider. It must enforce conditional writes and pass read, version, deletion, workload, and latency qualification. A capability probe rejects providers which ignore preconditions. Moto is emulator evidence only. - Dirty output is bounded and unconfirmed until S3 publication. Storage failure leaves persistence incomplete while task results and usage can settle. - Trace expiry is not yet represented by Cloud's external wake contract. Outstanding trace deadlines conservatively block sleep. - Automatic history copying requires the original source volume. Keep it until all retained resources pass verified import and clean-filesystem reads. Stop old binaries from creating new local-file runs. Missing or corrupt history remains blocked and visible in server logs. Rollback requires a compatible reader against the same external state. Ordinary object deletion does not erase retained historical object versions or backups. ## Model Used OpenAI Codex, `gpt-6.1-sol`, with reasoning, tool use, code execution, and browser verification. The runtime did not expose a 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>
475 lines
18 KiB
TypeScript
475 lines
18 KiB
TypeScript
import { randomUUID, createHash, generateKeyPairSync } from "node:crypto";
|
|
import { eq, sql } from "drizzle-orm";
|
|
import {
|
|
createDb,
|
|
heartbeatRunEvents,
|
|
heartbeatRuns,
|
|
agentIdentityKeys,
|
|
type Db,
|
|
} from "@paperclipai/db";
|
|
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
|
import {
|
|
S3Client,
|
|
CreateBucketCommand,
|
|
DeleteBucketCommand,
|
|
DeleteObjectsCommand,
|
|
ListObjectsV2Command,
|
|
} from "@aws-sdk/client-s3";
|
|
import { createS3StorageProvider } from "../../storage/s3-provider.js";
|
|
import { createObjectRunLogStore } from "../object-run-log-store.js";
|
|
import { createNativeRunLogExporter, formatNativeRunLogEvent } from "./native-run-log-export.js";
|
|
import { recoverSettledNativeRunLog, readRecoverableRunLog } from "./native-run-log-recovery.js";
|
|
import { PaperclipControlPlanePort } from "./paperclip-control-plane-port.js";
|
|
import { resolveExternalTestDatabaseUrl } from "../../__tests__/helpers/external-test-database.js";
|
|
import { createNativeRunLogTestTables } from "../../__tests__/helpers/native-run-log-database.js";
|
|
import type { PrpEvent } from "../../vendor/paperclip-runner/index.js";
|
|
import type { StorageProvider } from "../../storage/types.js";
|
|
import { appendNativeCredentialUpdate } from "./native-credential-updates.js";
|
|
import { appendRetainedNativeCleanupEvent } from "./native-session-executor.js";
|
|
import { idleWorkSnapshot } from "../task-admission.js";
|
|
import { appendHeartbeatRunEvent } from "../heartbeat-run-events.js";
|
|
import { localEncryptedProvider } from "../../secrets/local-encrypted-provider.js";
|
|
import { createHeartbeatRunOutput } from "../heartbeat/run-output.js";
|
|
import { createAgentIdentityRedactor } from "../agent-identity-redaction.js";
|
|
import { ObjectJournalConflictError } from "../object-byte-journal.js";
|
|
|
|
const url = resolveExternalTestDatabaseUrl("PAPERCLIP_RUN_EVIDENCE_MIGRATION_DATABASE_URL");
|
|
const endpoint = process.env.PAPERCLIP_LOG_TEST_S3_ENDPOINT;
|
|
describe.skipIf(!url || !endpoint)("native run log source recovery", () => {
|
|
const schema = `native_log_${randomUUID().replaceAll("-", "")}`,
|
|
bucket = `pc-native-log-${randomUUID()}`;
|
|
let db: Db,
|
|
client: S3Client,
|
|
bucketCreated = false;
|
|
beforeAll(async () => {
|
|
db = createDb(url!, { maxConnections: 1, idleTimeoutSeconds: 0 });
|
|
await db.execute(sql.raw(`create schema ${schema}`));
|
|
await db.execute(sql.raw(`set search_path=${schema}`));
|
|
await createNativeRunLogTestTables(db);
|
|
client = new S3Client({ endpoint, region: "us-east-1", forcePathStyle: true });
|
|
await client.send(new CreateBucketCommand({ Bucket: bucket }));
|
|
bucketCreated = true;
|
|
});
|
|
afterEach(() => vi.unstubAllEnvs());
|
|
afterAll(async () => {
|
|
if (client && bucketCreated) {
|
|
for (;;) {
|
|
const page = await client.send(new ListObjectsV2Command({ Bucket: bucket }));
|
|
if (!page.Contents?.length) break;
|
|
await client.send(
|
|
new DeleteObjectsCommand({
|
|
Bucket: bucket,
|
|
Delete: { Objects: page.Contents.map((item) => ({ Key: item.Key! })) },
|
|
}),
|
|
);
|
|
}
|
|
await client.send(new DeleteBucketCommand({ Bucket: bucket }));
|
|
client.destroy();
|
|
}
|
|
if (db) {
|
|
await db.execute(sql.raw(`drop schema ${schema} cascade`));
|
|
await db.$client.end();
|
|
}
|
|
});
|
|
async function fixture() {
|
|
const binding = {
|
|
companyId: randomUUID(),
|
|
runId: randomUUID(),
|
|
agentId: randomUUID(),
|
|
sessionId: randomUUID(),
|
|
issueId: randomUUID(),
|
|
sourceInstanceId: randomUUID(),
|
|
controlPlaneSourceInstanceId: randomUUID(),
|
|
completionContractId: randomUUID(),
|
|
completionContractSha256: "test",
|
|
};
|
|
await db.execute(
|
|
sql`insert into heartbeat_runs(id,company_id,agent_id,status) values(${binding.runId},${binding.companyId},${binding.agentId},'running')`,
|
|
);
|
|
const provider = createS3StorageProvider({
|
|
endpoint,
|
|
bucket,
|
|
region: "us-east-1",
|
|
forcePathStyle: true,
|
|
});
|
|
const store = (storage: StorageProvider = provider) =>
|
|
createObjectRunLogStore({
|
|
provider: storage,
|
|
keyPrefix: "logs",
|
|
flushMs: 30_000,
|
|
assertWriterAuthority: async (input) => {
|
|
await input.assertWriterAuthority?.();
|
|
},
|
|
});
|
|
const begin = { companyId: binding.companyId, agentId: binding.agentId, runId: binding.runId };
|
|
const port = new PaperclipControlPlanePort(db, binding);
|
|
const event = (seq: number): PrpEvent => ({
|
|
schema: "paperclip.prp.event.v1",
|
|
schemaVersion: 1,
|
|
sourceInstanceId: binding.sourceInstanceId,
|
|
sourceEventId: `${binding.sourceInstanceId}:${seq}`,
|
|
sourceSeq: seq,
|
|
sourceKind: "runner",
|
|
runId: binding.runId,
|
|
normalizedSessionId: binding.sessionId,
|
|
eventType: "item.delta",
|
|
priority: 2,
|
|
emittedAt: new Date().toISOString(),
|
|
payload: { text: `step ${seq} 再開` },
|
|
});
|
|
return { binding, store, begin, port, event, provider };
|
|
}
|
|
it("replays acknowledged native records into a new writer, repairs gaps, and ignores late duplicates", async () => {
|
|
const f = await fixture(),
|
|
a = f.store(),
|
|
h = await a.begin(f.begin);
|
|
await db.execute(
|
|
sql`update heartbeat_runs set log_store='s3_segments', log_ref=${h.logRef} where id=${f.binding.runId}`,
|
|
);
|
|
const events = [f.event(1), f.event(2), f.event(3)];
|
|
const cursors = await Promise.all(events.slice(0, 2).map((event) => f.port.appendEvent(event)));
|
|
const receipt = await a.enqueue!(h, {
|
|
stream: "stdout",
|
|
chunk: formatNativeRunLogEvent(events[0]!),
|
|
ts: "then",
|
|
seq: 1,
|
|
sourceCursor: cursors[0]!.cursor,
|
|
});
|
|
await a.flush!(h);
|
|
await receipt.committed;
|
|
const b = f.store(),
|
|
successor = await b.begin(f.begin);
|
|
let seq = successor.initialSequence!;
|
|
const exporter = createNativeRunLogExporter({
|
|
db,
|
|
companyId: f.binding.companyId,
|
|
runId: f.binding.runId,
|
|
afterCursor: successor.initialSourceCursor!,
|
|
enqueue: async (sourceCursor, chunk) => {
|
|
const queued = await b.enqueue!(successor, {
|
|
stream: "stdout",
|
|
chunk,
|
|
ts: "now",
|
|
seq: ++seq,
|
|
sourceCursor,
|
|
});
|
|
void queued.committed.catch(() => undefined);
|
|
},
|
|
flush: () => b.flush!(successor),
|
|
});
|
|
const third = await f.port.appendEvent(events[2]!);
|
|
await exporter.record(third.cursor, formatNativeRunLogEvent(events[2]!));
|
|
await exporter.record(cursors[0]!.cursor, formatNativeRunLogEvent(events[0]!));
|
|
await b.finalize(successor);
|
|
const entries = (await b.read(successor)).content
|
|
.trim()
|
|
.split("\n")
|
|
.map((line) => JSON.parse(JSON.parse(line).chunk).event);
|
|
expect(entries.map((event) => event.sourceSeq)).toEqual([1, 2, 3]);
|
|
expect(
|
|
await db
|
|
.select()
|
|
.from(heartbeatRunEvents)
|
|
.where(eq(heartbeatRunEvents.runId, f.binding.runId)),
|
|
).toHaveLength(3);
|
|
});
|
|
it("repairs a settled run on demand after its controller lease expires, without extending source retention", async () => {
|
|
const f = await fixture(),
|
|
a = f.store(),
|
|
h = await a.begin(f.begin);
|
|
await f.port.appendEvent(f.event(1));
|
|
await db.execute(
|
|
sql`update heartbeat_runs set status='succeeded', log_store='s3_segments', log_ref=${h.logRef} where id=${f.binding.runId}`,
|
|
);
|
|
await db.execute(
|
|
sql`insert into native_run_finalizations values(${f.binding.runId},${f.binding.companyId},now()+interval '1 minute')`,
|
|
);
|
|
const b = f.store();
|
|
await recoverSettledNativeRunLog(db, b, h.logRef, async () => ({ enabled: false }));
|
|
expect((await b.read(h)).content).toBe("");
|
|
await db.execute(
|
|
sql`update native_run_finalizations set lease_expires_at=now()-interval '1 second' where run_id=${f.binding.runId}`,
|
|
);
|
|
await Promise.all(
|
|
[1, 2].map(() =>
|
|
recoverSettledNativeRunLog(db, b, h.logRef, async () => ({ enabled: false })),
|
|
),
|
|
);
|
|
expect((await b.read(h)).content.trim().split("\n")).toHaveLength(1);
|
|
const [run] = await db
|
|
.select({ bytes: heartbeatRuns.logBytes })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, f.binding.runId));
|
|
expect(run!.bytes).toBeGreaterThan(0);
|
|
});
|
|
it.each(["hash", "payload", "identity"])(
|
|
"rejects a corrupt canonical source %s without marking the partial archive complete",
|
|
async (kind) => {
|
|
const f = await fixture(),
|
|
a = f.store(),
|
|
h = await a.begin(f.begin);
|
|
await f.port.appendEvent(f.event(1));
|
|
if (kind === "hash")
|
|
await db.execute(
|
|
sql`update heartbeat_run_events set source_payload_sha256='wrong' where run_id=${f.binding.runId}`,
|
|
);
|
|
else if (kind === "payload")
|
|
await db.execute(
|
|
sql`update heartbeat_run_events set payload='{}'::jsonb where run_id=${f.binding.runId}`,
|
|
);
|
|
else
|
|
await db.execute(
|
|
sql`update heartbeat_run_events set source_instance_id='wrong' where run_id=${f.binding.runId}`,
|
|
);
|
|
await db.execute(
|
|
sql`update heartbeat_runs set status='succeeded', log_store='s3_segments', log_ref=${h.logRef} where id=${f.binding.runId}`,
|
|
);
|
|
await expect(
|
|
recoverSettledNativeRunLog(db, f.store(), h.logRef, async () => ({ enabled: false })),
|
|
).rejects.toThrow("integrity");
|
|
const [run] = await db
|
|
.select({ bytes: heartbeatRuns.logBytes })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, f.binding.runId));
|
|
expect(run!.bytes).toBeNull();
|
|
},
|
|
);
|
|
it("ignores credential and retained cleanup projections when replaying canonical log sources", async () => {
|
|
const f = await fixture(),
|
|
a = f.store(),
|
|
h = await a.begin(f.begin);
|
|
await f.port.appendEvent(f.event(1));
|
|
const credential = (sourceSeq: number): PrpEvent => ({
|
|
...f.event(sourceSeq),
|
|
schema: "paperclip.prp.event.v3",
|
|
schemaVersion: 3,
|
|
priority: 0,
|
|
eventType: "auth.credentials.updated",
|
|
payload: {
|
|
schema: "paperclip.auth.credentials.updated.v1",
|
|
provider: "codex",
|
|
bindingId: "test-auth",
|
|
revision: 1,
|
|
detection: "credential_store",
|
|
},
|
|
});
|
|
await f.port.appendEvent(credential(2));
|
|
await db.execute(sql`update heartbeat_runs set status='succeeded', log_store='s3_segments', log_ref=${h.logRef},
|
|
native_session_id=${f.binding.sessionId}, runner_instance_id=${f.binding.sourceInstanceId} where id=${f.binding.runId}`);
|
|
await appendNativeCredentialUpdate(db, {
|
|
companyId: f.binding.companyId,
|
|
agentId: f.binding.agentId,
|
|
normalizedSessionId: f.binding.sessionId,
|
|
runnerInstanceId: f.binding.sourceInstanceId,
|
|
event: credential(20),
|
|
});
|
|
await appendRetainedNativeCleanupEvent(db, {
|
|
companyId: f.binding.companyId,
|
|
agentId: f.binding.agentId,
|
|
runId: f.binding.runId,
|
|
nativeSessionId: f.binding.sessionId,
|
|
runnerInstanceId: f.binding.sourceInstanceId,
|
|
requestId: "test-cleanup",
|
|
event: f.event(21),
|
|
});
|
|
await appendHeartbeatRunEvent(db, {
|
|
companyId: f.binding.companyId,
|
|
agentId: f.binding.agentId,
|
|
runId: f.binding.runId,
|
|
eventType: "workspace.diff.recorded",
|
|
payload: { complete: true },
|
|
nativeSource: {
|
|
sourceInstanceId: "provider-trace-reproject:test",
|
|
sourceEventId: "provider-trace-reproject:test:change",
|
|
sourceSeq: 1,
|
|
protocolSchemaVersion: 1,
|
|
canonicalPayload: { complete: true },
|
|
},
|
|
});
|
|
const b = f.store();
|
|
await recoverSettledNativeRunLog(db, b, h.logRef, async () => ({ enabled: false }));
|
|
const entries = (await b.read(h)).content.trim().split("\n");
|
|
expect(entries).toHaveLength(2);
|
|
expect(JSON.parse(JSON.parse(entries[0]!).chunk).event.sourceSeq).toBe(1);
|
|
expect(JSON.parse(JSON.parse(entries[1]!).chunk).event.eventType).toBe(
|
|
"auth.credentials.updated",
|
|
);
|
|
const [run] = await db
|
|
.select({ bytes: heartbeatRuns.logBytes })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, f.binding.runId));
|
|
expect(run!.bytes).toBeGreaterThan(0);
|
|
});
|
|
it("aborts in-flight archive writes when its last reader cancels, then resumes without loss", async () => {
|
|
const f = await fixture(),
|
|
a = f.store(),
|
|
h = await a.begin(f.begin),
|
|
baseline = idleWorkSnapshot().active;
|
|
await f.port.appendEvent(f.event(1));
|
|
await db.execute(
|
|
sql`update heartbeat_runs set status='succeeded', log_store='s3_segments', log_ref=${h.logRef} where id=${f.binding.runId}`,
|
|
);
|
|
let entered = false,
|
|
aborted = false;
|
|
const blocked: StorageProvider = {
|
|
...f.provider,
|
|
async putObjectConditional(input) {
|
|
if (input.objectKey.includes("/objects/")) {
|
|
entered = true;
|
|
await new Promise<void>((_resolve, reject) =>
|
|
input.signal!.addEventListener(
|
|
"abort",
|
|
() => {
|
|
aborted = true;
|
|
reject(input.signal!.reason);
|
|
},
|
|
{ once: true },
|
|
),
|
|
);
|
|
}
|
|
return f.provider.putObjectConditional!(input);
|
|
},
|
|
};
|
|
const controller = new AbortController();
|
|
const repairing = recoverSettledNativeRunLog(
|
|
db,
|
|
f.store(blocked),
|
|
h.logRef,
|
|
async () => ({ enabled: false }),
|
|
controller.signal,
|
|
);
|
|
const rejected = expect(repairing).rejects.toThrow("reader cancelled");
|
|
const lastReader = new AbortController();
|
|
const joined = recoverSettledNativeRunLog(
|
|
db,
|
|
f.store(blocked),
|
|
h.logRef,
|
|
async () => ({ enabled: false }),
|
|
lastReader.signal,
|
|
);
|
|
const joinedRejected = expect(joined).rejects.toThrow("last reader cancelled");
|
|
await vi.waitFor(() => expect(entered).toBe(true));
|
|
controller.abort(new Error("reader cancelled"));
|
|
await rejected;
|
|
expect(aborted).toBe(false);
|
|
lastReader.abort(new Error("last reader cancelled"));
|
|
await joinedRejected;
|
|
await vi.waitFor(() => {
|
|
expect(aborted).toBe(true);
|
|
expect(idleWorkSnapshot().active).toBe(baseline);
|
|
});
|
|
const b = f.store();
|
|
await vi.waitFor(async () => {
|
|
await recoverSettledNativeRunLog(db, b, h.logRef, async () => ({ enabled: false }));
|
|
});
|
|
expect((await b.read(h)).content.trim().split("\n")).toHaveLength(1);
|
|
});
|
|
it("redacts the existing agent identity and registered secrets before publishing recovered native output", async () => {
|
|
vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY", "e".repeat(64));
|
|
const f = await fixture();
|
|
const keys = generateKeyPairSync("ed25519"),
|
|
privateKeyPem = keys.privateKey.export({ type: "pkcs8", format: "pem" }).toString();
|
|
const publicKeyPem = keys.publicKey.export({ type: "spki", format: "pem" }).toString();
|
|
const keyId = `sha256:${createHash("sha256")
|
|
.update(keys.publicKey.export({ type: "spki", format: "der" }))
|
|
.digest("base64url")}`;
|
|
const encrypted = await localEncryptedProvider.createSecret({ value: privateKeyPem });
|
|
await db.insert(agentIdentityKeys).values({
|
|
agentId: f.binding.agentId,
|
|
companyId: f.binding.companyId,
|
|
algorithm: "Ed25519",
|
|
keyId,
|
|
publicKeyPem,
|
|
privateKeyMaterial: encrypted.material,
|
|
});
|
|
const secret = "registered-native-fixture-secret";
|
|
const redactor = createAgentIdentityRedactor(privateKeyPem);
|
|
redactor.values.push(secret);
|
|
const run = {
|
|
id: f.binding.runId,
|
|
companyId: f.binding.companyId,
|
|
agentId: f.binding.agentId,
|
|
status: "running",
|
|
runtimeMode: "native",
|
|
logStore: null,
|
|
logRef: null,
|
|
logBytes: null,
|
|
lastOutputSeq: 0,
|
|
lastOutputAt: null,
|
|
} as typeof heartbeatRuns.$inferSelect;
|
|
const output = createHeartbeatRunOutput(db, {
|
|
run,
|
|
runId: run.id,
|
|
issueId: null,
|
|
runLogStore: f.store(),
|
|
identityRedactor: redactor,
|
|
secretKeys: new Set(),
|
|
runtimeLogSecretValues: [secret],
|
|
appendRunEvent: async () => undefined,
|
|
getCurrentUserRedactionOptions: async () => ({ enabled: false }),
|
|
});
|
|
await output.begin(run);
|
|
const h = output.handle!;
|
|
await f.port.appendEvent({ ...f.event(1), payload: { text: `${privateKeyPem}\n${secret}` } });
|
|
await db.execute(
|
|
sql`update heartbeat_runs set status='succeeded', log_store='s3_segments',log_ref=${h.logRef} where id=${f.binding.runId}`,
|
|
);
|
|
const b = f.store();
|
|
await recoverSettledNativeRunLog(db, b, h.logRef, async () => ({ enabled: false }));
|
|
const content = (await b.read(h)).content;
|
|
expect(content).not.toContain(privateKeyPem.split("\n")[1]!);
|
|
expect(content).not.toContain(secret);
|
|
expect(content).toContain("REDACTED");
|
|
const [snapshot] = await db
|
|
.select({ context: heartbeatRuns.contextSnapshot })
|
|
.from(heartbeatRuns)
|
|
.where(eq(heartbeatRuns.id, f.binding.runId));
|
|
expect(JSON.stringify(snapshot!.context)).not.toContain(privateKeyPem.split("\n")[1]!);
|
|
});
|
|
it("serves the published snapshot when another writer wins a repair claim", async () => {
|
|
const f = await fixture(),
|
|
a = f.store(),
|
|
h = await a.begin(f.begin);
|
|
const event = f.event(1),
|
|
receipt = await f.port.appendEvent(event);
|
|
const queued = await a.enqueue!(h, {
|
|
stream: "stdout",
|
|
chunk: formatNativeRunLogEvent(event),
|
|
ts: "then",
|
|
seq: 1,
|
|
sourceCursor: receipt.cursor,
|
|
});
|
|
await a.flush!(h);
|
|
await queued.committed;
|
|
await f.port.appendEvent(f.event(2));
|
|
await db.execute(
|
|
sql`update heartbeat_runs set status='succeeded',log_store='s3_segments',log_ref=${h.logRef} where id=${f.binding.runId}`,
|
|
);
|
|
let enter!: () => void, release!: () => void;
|
|
const entered = new Promise<void>((resolve) => {
|
|
enter = resolve;
|
|
}),
|
|
blocked = new Promise<void>((resolve) => {
|
|
release = resolve;
|
|
});
|
|
const store = {
|
|
...f.store(),
|
|
async begin() {
|
|
enter();
|
|
await blocked;
|
|
throw new ObjectJournalConflictError();
|
|
},
|
|
};
|
|
const repairing = recoverSettledNativeRunLog(db, store, h.logRef, async () => ({
|
|
enabled: false,
|
|
}));
|
|
const rejected = expect(repairing).rejects.toBeInstanceOf(ObjectJournalConflictError);
|
|
await entered;
|
|
const read = readRecoverableRunLog(db, store, h);
|
|
release();
|
|
await rejected;
|
|
expect((await read).content.trim().split("\n")).toHaveLength(1);
|
|
await a.finalize(h);
|
|
});
|
|
});
|