Files
PaperClipAI/server/src/services/object-byte-journal.test.ts
T
DottaandPaperclip dbff3747b8 feat(server): persist run logs and provider traces in S3 (#18327)
## 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>
2026-10-30 15:17:35 -05:00

327 lines
14 KiB
TypeScript

import { createHash } from "node:crypto";
import { Readable } from "node:stream";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { StorageProvider } from "../storage/types.js";
import { createObjectByteJournal, ObjectJournalConflictError } from "./object-byte-journal.js";
async function readBody(body: AsyncIterable<Uint8Array>) {
const chunks: Buffer[] = [];
for await (const bytes of body) chunks.push(Buffer.from(bytes));
return Buffer.concat(chunks);
}
function storage() {
const objects = new Map<string, Buffer>();
const calls = { get: 0, put: 0, maxPut: 0 };
let loseHeadResponse = false;
const etag = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex");
const missing = () => Object.assign(new Error("missing"), { name: "NoSuchKey" });
const conflict = () => Object.assign(new Error("conflict"), { name: "PreconditionFailed" });
const provider: StorageProvider = {
id: "s3",
async getObject({ objectKey, signal }) {
signal?.throwIfAborted();
calls.get++;
const bytes = objects.get(objectKey);
if (!bytes) throw missing();
return { stream: Readable.from([bytes]), etag: etag(bytes), contentLength: bytes.length };
},
async putObject() {
throw new Error("unconditional PUT forbidden");
},
async putObjectConditional(input) {
const old = objects.get(input.objectKey);
if (input.ifNoneMatch ? old : !old || etag(old) !== input.ifMatch) throw conflict();
const bytes = Buffer.isBuffer(input.body) ? input.body : await readBody(input.body);
objects.set(input.objectKey, Buffer.from(bytes));
calls.put++;
calls.maxPut = Math.max(calls.maxPut, bytes.length);
if (loseHeadResponse && input.objectKey.endsWith("/head.json")) {
loseHeadResponse = false;
throw new Error("response lost after PUT");
}
return { etag: etag(bytes) };
},
async headObject({ objectKey }) {
return { exists: objects.has(objectKey) };
},
async deleteObject({ objectKey }) {
objects.delete(objectKey);
},
async listObjects({ prefix }) {
return { keys: [...objects.keys()].filter((k) => k.startsWith(prefix)) };
},
};
return {
provider,
objects,
calls,
loseResponse: () => {
loseHeadResponse = true;
},
};
}
const authority = async () => undefined;
afterEach(() => vi.useRealTimers());
describe("object byte journal", () => {
it("keeps a shared capability probe alive for another writer when one claim cancels", async () => {
const s = storage();
const put = s.provider.putObjectConditional!;
let release!: () => void, started!: () => void, admitted!: () => void;
let probeSignal: AbortSignal | undefined;
const probing = new Promise<void>((resolve) => {
started = resolve;
});
const joined = new Promise<void>((resolve) => {
admitted = resolve;
});
s.provider.putObjectConditional = async (input) => {
if (input.objectKey.includes("conditional-probe-") && !probeSignal) {
probeSignal = input.signal;
await new Promise<void>((resolve, reject) => {
release = resolve;
input.signal!.addEventListener("abort", () => reject(input.signal!.reason), {
once: true,
});
started();
});
}
return put(input);
};
const controller = new AbortController();
const a = createObjectByteJournal({ provider: s.provider, prefix: "company/a/log" });
const first = a.claim({
expectedOwner: null,
assertAuthority: authority,
signal: controller.signal,
});
void first.catch(() => undefined);
await probing;
const b = createObjectByteJournal({ provider: s.provider, prefix: "company/b/log" });
const second = b.claim({
expectedOwner: null,
assertAuthority: async () => {
admitted();
},
});
await joined;
await Promise.resolve();
controller.abort();
await expect(first).rejects.toMatchObject({ name: "AbortError" });
expect(probeSignal!.aborted).toBe(false);
release();
const writer = await second;
expect((await b.head())!.head.owner).toBe(writer.head.owner);
});
it("recovers committed bytes and stable ranges with no local filesystem", async () => {
const s = storage(),
a = createObjectByteJournal({ provider: s.provider, prefix: "company/run/log" });
let writer = await a.claim({ expectedOwner: null, assertAuthority: authority });
const expected = Buffer.from("first\n再開\n".repeat(20));
writer = await a.append(writer, expected.subarray(0, 17));
writer = await a.append(writer, expected.subarray(17));
const b = createObjectByteJournal({ provider: s.provider, prefix: "company/run/log" });
const snapshot = (await b.head())!;
expect(await b.readRange(snapshot.head, 0, expected.length)).toEqual(expected);
expect(await b.readRange(snapshot.head, 7, 23)).toEqual(expected.subarray(7, 30));
expect(await b.readRange(snapshot.head, expected.length, 100)).toEqual(Buffer.alloc(0));
});
it("fences stale appends/finalization and preserves a pinned reader snapshot", async () => {
const s = storage(),
a = createObjectByteJournal({ provider: s.provider, prefix: "c/r/log" });
let old = await a.claim({ expectedOwner: null, assertAuthority: authority });
old = await a.append(old, Buffer.from("before"));
const snapshot = old.head;
let next = await a.claim({ expectedOwner: old.head.owner, assertAuthority: authority });
next = await a.append(next, Buffer.from("after"));
await expect(a.append(old, Buffer.from("lost"))).rejects.toBeInstanceOf(
ObjectJournalConflictError,
);
await expect(a.close(old)).rejects.toBeInstanceOf(ObjectJournalConflictError);
expect(await a.readRange(snapshot, 0, 100)).toEqual(Buffer.from("before"));
expect(await a.readRange(next.head, 0, 100)).toEqual(Buffer.from("beforeafter"));
});
it("reconciles an uncertain manifest commit without duplicating output", async () => {
const s = storage(),
a = createObjectByteJournal({ provider: s.provider, prefix: "c/r/log" });
let writer = await a.claim({ expectedOwner: null, assertAuthority: authority });
s.loseResponse();
writer = await a.append(writer, Buffer.from("once"));
expect(writer.head.end).toBe(4);
expect(await a.readRange((await a.head())!.head, 0, 100)).toEqual(Buffer.from("once"));
});
it("keeps index objects bounded over multiple tree levels", async () => {
const s = storage(),
a = createObjectByteJournal({ provider: s.provider, prefix: "c/r/log" });
let writer = await a.claim({ expectedOwner: null, assertAuthority: authority });
for (let i = 0; i < 180; i++)
writer = await a.append(writer, Buffer.from(String(i).padStart(4, "0")));
expect(await a.readRange(writer.head, 252, 16)).toEqual(Buffer.from("0063006400650066"));
expect(await a.readRange(writer.head, 700, 20)).toEqual(Buffer.from("01750176017701780179"));
expect(s.calls.maxPut).toBeLessThan(20_000);
expect(s.calls.put).toBeLessThan(180 * 5);
const reachable = new Set<string>();
function visit(ref: { key: string }, level: number) {
reachable.add(ref.key);
if (level === 0) return;
const node = JSON.parse(s.objects.get(ref.key)!.toString());
for (const child of node.children) visit(child, level - 1);
}
for (const root of writer.head.roots!) visit(root, root.level);
expect([...reachable].sort()).toEqual(
[...s.objects.keys()].filter((key) => key.includes("/objects/")).sort(),
);
});
it("retries a transient head conflict without fencing its current writer", async () => {
const s = storage(),
journal = createObjectByteJournal({ provider: s.provider, prefix: "c/r/log" });
let writer = await journal.claim({ expectedOwner: null, assertAuthority: authority });
const original = s.provider.putObjectConditional!;
let conflicts = 0;
s.provider.putObjectConditional = async (input) => {
if (input.objectKey.endsWith("/head.json") && conflicts++ === 0)
throw Object.assign(new Error("in-flight conflict"), {
name: "ConditionalRequestConflict",
$metadata: { httpStatusCode: 409 },
});
return original(input);
};
writer = await journal.append(writer, Buffer.from("once"));
expect(await journal.readRange(writer.head, 0, 100)).toEqual(Buffer.from("once"));
expect(conflicts).toBe(2);
});
it("does not accept a provider's 409 response as proof of conditional enforcement", async () => {
const s = storage(),
original = s.provider.putObjectConditional!;
s.provider.putObjectConditional = async (input) => {
if (s.objects.has(input.objectKey))
throw Object.assign(new Error("conflict"), { $metadata: { httpStatusCode: 409 } });
return original(input);
};
const journal = createObjectByteJournal({ provider: s.provider, prefix: "c/r/log" });
await expect(
journal.claim({ expectedOwner: null, assertAuthority: authority }),
).rejects.toThrow("conflict");
expect(s.objects.size).toBe(0);
});
it("retries transient segment failures and acknowledges exactly one batch", async () => {
const s = storage(),
journal = createObjectByteJournal({ provider: s.provider, prefix: "c/r/log" });
let writer = await journal.claim({ expectedOwner: null, assertAuthority: authority });
const original = s.provider.putObjectConditional!;
let failures = 2;
s.provider.putObjectConditional = async (input) => {
if (input.objectKey.includes("/objects/") && failures-- > 0)
throw Object.assign(new Error("temporary outage"), { $metadata: { httpStatusCode: 503 } });
return original(input);
};
writer = await journal.append(writer, Buffer.from("one batch"));
expect(await journal.readRange(writer.head, 0, 100)).toEqual(Buffer.from("one batch"));
});
it("rejects corrupt published data and cancelled reads", async () => {
const s = storage(),
a = createObjectByteJournal({ provider: s.provider, prefix: "c/r/log" });
let writer = await a.claim({ expectedOwner: null, assertAuthority: authority });
writer = await a.append(writer, Buffer.from("data"));
const data = [...s.objects].find(([, bytes]) => bytes.toString() === "data")!;
s.objects.set(data[0], Buffer.from("oops"));
await expect(a.readRange(writer.head, 0, 4)).rejects.toThrow("integrity");
await expect(a.readRange(writer.head, 0, 4, AbortSignal.abort())).rejects.toThrow();
});
it("retains a deletion tombstone and denies a subsequent claim", async () => {
const s = storage(),
a = createObjectByteJournal({ provider: s.provider, prefix: "c/r/log" });
let writer = await a.claim({ expectedOwner: null, assertAuthority: authority });
writer = await a.append(writer, Buffer.from("private"));
await a.close(writer);
await a.remove();
expect([...s.objects.keys()]).toEqual(["c/r/log/head.json"]);
expect((await a.head())!.head.deleted).toBe(true);
await expect(
a.claim({ expectedOwner: writer.head.owner, assertAuthority: authority }),
).rejects.toThrow();
});
it("does not claim ownership when execution authority rejects", async () => {
const s = storage(),
a = createObjectByteJournal({ provider: s.provider, prefix: "c/r/log" });
await expect(
a.claim({
expectedOwner: null,
assertAuthority: async () => {
throw new Error("revoked");
},
}),
).rejects.toThrow("revoked");
expect(s.calls.put).toBe(0);
});
it("fences a pending first claim when deletion wins before journal creation", async () => {
const s = storage(),
journal = createObjectByteJournal({ provider: s.provider, prefix: "c/r/log" });
let enter!: () => void, release!: () => void;
const entered = new Promise<void>((resolve) => {
enter = resolve;
});
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
const pending = journal.claim({
expectedOwner: null,
assertAuthority: async () => {
enter();
await blocked;
},
});
await entered;
await journal.remove();
release();
await expect(pending).rejects.toBeInstanceOf(ObjectJournalConflictError);
expect((await journal.head())!.head.deleted).toBe(true);
expect([...s.objects.keys()]).toEqual(["c/r/log/head.json"]);
});
it("rejects a compatible provider which silently ignores conditional writes", async () => {
const s = storage();
s.provider.putObjectConditional = async (input) => {
const bytes = Buffer.from(input.body as Buffer);
s.objects.set(input.objectKey, bytes);
return { etag: "ignored-condition" };
};
const journal = createObjectByteJournal({ provider: s.provider, prefix: "c/r/log" });
await expect(
journal.claim({ expectedOwner: null, assertAuthority: authority }),
).rejects.toThrow("does not enforce conditional");
expect(s.objects.size).toBe(0);
});
it("fences an active writer before cleanup and preserves the retry obligation", async () => {
vi.useFakeTimers({ toFake: ["Date"] });
const s = storage(),
journal = createObjectByteJournal({ provider: s.provider, prefix: "c/r/log" });
let writer = await journal.claim({ expectedOwner: null, assertAuthority: authority });
writer = await journal.append(writer, Buffer.from("private"));
await expect(journal.remove()).rejects.toThrow("cleanup_pending");
expect((await journal.head())!.head.deleted).toBe(true);
await expect(journal.append(writer, Buffer.from("late"))).rejects.toBeInstanceOf(
ObjectJournalConflictError,
);
vi.setSystemTime(Date.now() + 30_001);
await journal.remove();
expect([...s.objects.keys()]).toEqual(["c/r/log/head.json"]);
});
it("does not publish a partial batch when a later segment fails", async () => {
const s = storage(),
journal = createObjectByteJournal({ provider: s.provider, prefix: "c/r/log" });
const writer = await journal.claim({ expectedOwner: null, assertAuthority: authority });
const original = s.provider.putObjectConditional!;
const failed = Buffer.alloc(1024 * 1024, 2);
const key = createHash("sha256").update(failed).digest("hex");
s.provider.putObjectConditional = (input) => {
if (input.objectKey.endsWith(key)) throw Error("second segment failed");
return original(input);
};
await expect(
journal.append(writer, Buffer.concat([Buffer.alloc(1024 * 1024, 1), failed])),
).rejects.toThrow("second segment failed");
expect((await journal.head())!.head.end).toBe(0);
});
});