Files
PaperClipAI/server/src/services/object-run-log-store.test.ts
T
DottaandPaperclip 3910352c92 feat(runner): add experimental Cursor Cloud provider (#18068)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Runner gives each provider durable execution, tool, and completion
contracts.
> - Cursor Cloud currently has a direct adapter outside that native
contract.
> - Cloud work needs exact ownership across HTTP, SSE, Stop, and
recovery.
> - This PR adds a qualified Cloud API driver and verified proxy to
Runner.
> - Product setup and hosted placement remain separate dependent
changes.

## Linked Issues or Issue Description

Refs #5664, #11803, #17299, and #17471. Product integration is #18069.
Managed-only API placement is #18310. The related direct-adapter
model/transcript work is not replaced. No duplicate native Cursor Cloud
integration was found.

## What Changed

- Add native `cursor_cloud` / `cursor_cloud_api` with explicit
model/repository validation, bounded HTTP/SSE, durable per-turn
checkpoints and a qualified Node proxy launched through the Rust facade.
- Commit terminal custody before publication/release; coalesce
consumers, preserve ambiguous create/Stop/recovery fences, reject late
tools, and distinguish definitely-unsent oversized requests from
ambiguous responses.
- Support scoped cold attachment, current authority, reconnect and
verified artifact staging. Keep unsupported warm/external and Windows
paths closed.
- Preserve early source cursors and verify immutable legacy prefixes
before suffix replay, including supported compaction/masking. Optional
proof publication failure falls back to complete cold verification.
- Preserve canonical records at the durable native producer with
JSON-safe privacy and the existing 8MiB bound; drain admitted successor
flushes. Reconcile upstream semantic/pack/schema/lifecycle changes and
retain S3 and legacy CLI checks.

## Verification

Core head `37c442ec8dd4`: all 66 check contexts are terminal
successful/neutral/skipped, including required `ci / verify` and `ci /
e2e`; fresh exact-head Greptile is 5/5 with zero unresolved threads.
Dependent Product `81e828d20a77` and Top `dd2959689627` include the
later client handoff correction and are running their own fresh gates.

Core: 47/47 Rust, 4/4 compiled-native retirement, 19/19 settlement and
normal Runner build passed. Runtime Top `9af1a5de42a2`: build and
recursive typecheck passed. Earlier source-scoped evidence includes 398
focused tests, five relay tests and token/type gates. The 251-assertion,
7/8-suite run failed physical PostgreSQL teardown; the unchanged stable
WSP suite passed 128 through the documented wrapper.

The downstream fixture corrections passed 7/7 browser and 121/121
startup tests without timeout/oracle relaxation; a broken-unsubscribe
control fails. Hosted runtime `9af1a5de42a2` has a passing normal build
and recursive typecheck. Latest dependent heads additionally contain a
pure client fix for stale live/history overlap, with 48 focused tests,
UI typecheck and token gates passing. Its new client is not deployed in
the frozen hosted image; server/native/API/provider source is unchanged
by these four downstream files.

Fresh hosted Linux admission on `9af1a5de42a2` retired its owned
runner/proxy/socket with zero prompts. The saved configuration survived
reopening, and Test authenticated the bound key/catalog/selected model
without a prompt. Artifact with `claude-sonnet-4-5` completed,
downloaded the exact 27 bytes, matched 121 canonical identities against
complete logs and independently reached FINISHED. The active Stop retry
was clicked within its immutable boundary, produced one canonical
interrupted turn and acknowledged run-only cancellation, retained a
valid 35.076s quiet window (maximum gap 4.584s), and independently
remained CANCELLED/artifact-absent beyond the original 180-second
command deadline. All provider-observer credential callbacks, DB clients
and loaders closed; accounting is settled and explicitly unpriced. The
first fresh Stop retains its failed 10.373s sampling gap and every
sample.

On the upgraded9af server, the historical F226 artifact was reopened and
downloaded with its exact original hash after its provider agent had
been deleted/GET404 earlier today. Historical F226 full Artifact/Stop
cleanup, Question, corrected Plan and reconnect retain their original
identities. Deleting the three newly created disposable provider agents
and the new-case post-delete grade remain blocked on explicit user
approval after automatic review rejected expanding the two original
approved IDs. No new-case cleanup or complete fresh matrix pass is
claimed; this is separate from the directly observed task/Stop behavior
and retained exact cleanup proof.

Retained failures: stale fixture 132/133; E8 48/135 with 87 reset-hook
failures; Mac 17 SQL failures/skips; earlier startup-title, title-save,
custody/Stop and deletion failures with unknown causes and bounded
recoveries. `dea023` Artifact passed 17 checks but Stop failed its false
warning and 50 duplicate log identities. Pre-repair ACK failure and
original Core CI failure remain recorded; retry alone establishes no
cause or full local-suite pass. Provider dollar cost stays UNKNOWN.

## Risks

Experimental: Cursor independently acknowledges neither the effective
model nor instruction digest before the first prompt. The caller’s
explicit values are submitted and behavior checked live. Unpriced
provider dollar cost stays UNKNOWN.

Only qualified per-turn controllers are admitted. Uncertain work and
incomplete cleanup stay fenced. Existing damaged/duplicate archives
remain failed evidence. Prefix proof adds bounded object-store I/O; the
8MiB producer bound does not guarantee future providers’ output fits.

## Model Used

OpenAI Codex, GPT-6 family, assisted with reasoning, repository tools,
code execution, browser verification, and delegated code review. The
serving model’s exact API ID and context window are not exposed. No
value is inferred from the model catalog.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used and the limits of available model
metadata
- [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 linked public issues or described the issue in this PR
- [x] I have not referenced internal or instance-local Paperclip issues
or links
- [x] My branch describes the change and contains no internal ticket ID
- [x] I have run the scoped local tests reported above; pending gates
are stated separately
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation
- [x] I have considered and documented the risks
- [x] All required CI gates pass on the current head
- [x] Fresh Greptile is 5/5 with no unresolved findings on the current
head
- [x] I will address all reviewer comments before requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-03 08:38:57 -06:00

399 lines
18 KiB
TypeScript

import { createHash } from "node:crypto";
import { Readable } from "node:stream";
import { describe, expect, it, vi } from "vitest";
import type { StorageProvider } from "../storage/types.js";
import { createObjectRunLogStore } from "./object-run-log-store.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 memory() {
const objects = new Map<string, Buffer>();
let puts = 0,
unavailable = false;
const etag = (b: Buffer) => createHash("sha256").update(b).digest("hex");
const provider: StorageProvider = {
id: "s3",
async putObject() {
throw Error("unconditional");
},
async putObjectConditional(i) {
if (unavailable) throw Error("storage offline");
const old = objects.get(i.objectKey);
if (i.ifNoneMatch ? old : !old || etag(old) !== i.ifMatch)
throw Object.assign(Error("conflict"), { name: "PreconditionFailed" });
const b = Buffer.isBuffer(i.body) ? i.body : await readBody(i.body);
objects.set(i.objectKey, Buffer.from(b));
puts++;
return { etag: etag(b) };
},
async getObject(i) {
const b = objects.get(i.objectKey);
if (!b) throw Object.assign(Error("missing"), { name: "NoSuchKey" });
return { stream: Readable.from([b]), etag: etag(b) };
},
async headObject(i) {
return { exists: objects.has(i.objectKey) };
},
async deleteObject(i) {
objects.delete(i.objectKey);
},
async listObjects(i) {
return { keys: [...objects.keys()].filter((k) => k.startsWith(i.prefix)) };
},
};
return {
provider,
objects,
puts: () => puts,
offline: (value: boolean) => {
unavailable = value;
},
};
}
const input = { companyId: "company", agentId: "agent", runId: "run" };
const event = (seq: number) => ({
stream: "stdout" as const,
chunk: "再開",
ts: "2026-10-30T00:00:00Z",
seq,
});
describe("S3 run log store", () => {
it("awaits a successor flush started by another drain waiter before finalizing", async () => {
const m = memory(), store = createObjectRunLogStore({ provider: m.provider, keyPrefix: "logs", flushMs: 1000,
segmentBytes: 1024, assertWriterAuthority: async () => undefined });
const handle = await store.begin(input), put = m.provider.putObjectConditional!.bind(m.provider);
let firstEntered!: () => void, secondEntered!: () => void, releaseFirst!: () => void, releaseSecond!: () => void;
const firstStarted = new Promise<void>(resolve => { firstEntered = resolve; });
const secondStarted = new Promise<void>(resolve => { secondEntered = resolve; });
const firstGate = new Promise<void>(resolve => { releaseFirst = resolve; });
const secondGate = new Promise<void>(resolve => { releaseSecond = resolve; });
let publications = 0;
m.provider.putObjectConditional = async value => {
if (value.objectKey.endsWith("/head.json") && Buffer.isBuffer(value.body)) {
const head = JSON.parse(value.body.toString());
if (!head.closed && head.end > 0) {
publications++;
if (publications === 1) { firstEntered(); await firstGate; }
else if (publications === 2) { secondEntered(); await secondGate; }
}
}
return put(value);
};
const first = await store.enqueue!(handle, { ...event(1), chunk: "first ".repeat(200) });
const firstCommitted = first.committed.catch(error => error);
await firstStarted;
const second = await store.enqueue!(handle, { ...event(2), chunk: "second" });
const secondCommitted = second.committed.catch(error => error);
let finalized = false;
const finalizing = store.finalize(handle).then(result => { finalized = true; return result; });
releaseFirst();
await secondStarted;
await new Promise<void>(resolve => setImmediate(resolve));
const finalizedBeforeSecondCommit = finalized;
releaseSecond();
const summary = await finalizing;
const committed = await Promise.all([firstCommitted, secondCommitted]);
const content = (await store.read(handle)).content;
expect(finalizedBeforeSecondCommit).toBe(false);
expect(committed.every(value => typeof value === "number")).toBe(true);
expect(summary.bytes).toBe(Buffer.byteLength(content));
expect(content.trim().split("\n").map(line => JSON.parse(line).seq)).toEqual([1, 2]);
});
it("rejects outer records exceeding 8MiB without losing later bounded appends", async () => {
const m = memory(), store = createObjectRunLogStore({ provider: m.provider, keyPrefix: "logs", flushMs: 1,
assertWriterAuthority: async () => undefined });
const handle = await store.begin(input);
await expect(store.append(handle, { ...event(1), chunk: "x".repeat(8 * 1024 * 1024) }))
.rejects.toThrow("Object run log record exceeds pending-byte limit");
await store.append(handle, event(1));
const content = (await store.read(handle)).content;
expect(content.trim().split("\n")).toHaveLength(1);
expect((await store.finalize(handle)).bytes).toBe(Buffer.byteLength(content));
});
it("keeps live byte appends deliverable after a proof-only outage and requires cold prefix verification", async () => {
const m = memory(), options = { provider: m.provider, keyPrefix: "logs", flushMs: 1,
assertWriterAuthority: async () => undefined };
const put = m.provider.putObjectConditional!.bind(m.provider);
let proofUnavailable = false, proofFailures = 0;
m.provider.putObjectConditional = async value => {
if (proofUnavailable && value.objectKey.includes("/objects/source-prefix-proof-v1-")) {
proofFailures++;
throw Object.assign(new Error("proof storage unavailable"), { $metadata: { httpStatusCode: 503 } });
}
return put(value);
};
const store = createObjectRunLogStore(options), handle = await store.begin(input);
await store.recordVerifiedSourcePrefix!(handle, 0);
proofUnavailable = true;
const first = await store.append(handle, { ...event(1), sourceCursor: 2, preservesSourceCoverage: true })
.catch(error => error);
// The existing byte/index/head publication succeeded despite the proof PUT failure.
expect((await store.read(handle)).content.trim().split("\n")).toHaveLength(1);
proofUnavailable = false;
const second = await store.append(handle, { ...event(2), sourceCursor: 5, preservesSourceCoverage: true })
.catch(error => error);
const summary = await store.finalize(handle);
const cold = createObjectRunLogStore(options), resumed = await cold.begin(input);
const content = (await cold.read(resumed)).content;
expect(resumed.initialSourceCursor).toBe(5);
// Absence selects the maintained consumer's mandatory full source-prefix scan.
expect(resumed.initialSourcePrefixVerified).toBe(false);
proofUnavailable = true;
// A complete legacy proof can advance the old max cursor before its optional
// proof PUT fails. The public recorder must retain that known committed head.
await cold.recordVerifiedSourcePrefix!(resumed, 8);
expect(resumed.initialSourcePrefixVerified).toBe(false);
proofUnavailable = false;
const third = await cold.append(resumed, { ...event(3), sourceCursor: 11, preservesSourceCoverage: true });
await cold.finalize(resumed);
const final = await store.begin(input);
const finalContent = (await store.read(final)).content;
await store.finalize(final);
expect(proofFailures).toBeGreaterThan(0);
expect(first).toBeTypeOf("number");
expect(second).toBeTypeOf("number");
expect(third).toBeTypeOf("number");
expect(summary.bytes).toBe(Buffer.byteLength(content));
expect(finalContent.trim().split("\n").map(line => JSON.parse(line).seq)).toEqual([1, 2, 3]);
expect(final.initialSourceCursor).toBe(11);
expect(final.initialSourcePrefixVerified).toBe(false);
});
it.each(["internal-deadline", "caller-abort"] as const)("distinguishes proof %s after the byte head committed", async kind => {
const m = memory(), caller = new AbortController();
const options = { provider: m.provider, keyPrefix: "logs", flushMs: 1,
assertWriterAuthority: async () => undefined };
const store = createObjectRunLogStore(options), handle = await store.begin({ ...input, signal: caller.signal });
await store.recordVerifiedSourcePrefix!(handle, 0);
const put = m.provider.putObjectConditional!.bind(m.provider);
const deadline = new AbortController();
let entered!: () => void;
const proofStarted = new Promise<void>(resolve => { entered = resolve; });
m.provider.putObjectConditional = async value => {
if (!value.objectKey.includes("/objects/source-prefix-proof-v1-")) return put(value);
entered();
return new Promise((_resolve, reject) => {
if (value.signal!.aborted) reject(value.signal!.reason);
else value.signal!.addEventListener("abort", () => reject(value.signal!.reason), { once: true });
});
};
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(deadline.signal);
let first: unknown;
const callerReason = new Error("caller revoked writer");
try {
const pending = store.append(handle, { ...event(1), sourceCursor: 2, preservesSourceCoverage: true })
.catch(error => error);
await proofStarted;
if (kind === "internal-deadline") deadline.abort(new DOMException("proof deadline", "TimeoutError"));
else caller.abort(callerReason);
first = await pending;
} finally { timeout.mockRestore(); m.provider.putObjectConditional = put; }
const second = await store.append(handle, { ...event(2), sourceCursor: 5, preservesSourceCoverage: true })
.catch(error => error);
const summary = await store.finalize(handle);
const cold = createObjectRunLogStore(options), resumed = await cold.begin(input);
await cold.finalize(resumed);
expect(resumed.initialSourcePrefixVerified).toBe(false);
if (kind === "internal-deadline") {
expect(first).toBeTypeOf("number");
expect(second).toBeTypeOf("number");
expect(summary.bytes).not.toBeNull();
expect(resumed.initialSourceCursor).toBe(5);
} else {
expect(first).toBe(callerReason);
expect(second).toBe(callerReason);
expect(summary.bytes).toBeNull();
expect(resumed.initialSourceCursor).toBe(2);
}
});
it("keeps an unknown head publication failure fatal", async () => {
const m = memory(), store = createObjectRunLogStore({ provider: m.provider, keyPrefix: "logs", flushMs: 1,
assertWriterAuthority: async () => undefined });
const handle = await store.begin(input);
await store.recordVerifiedSourcePrefix!(handle, 0);
const put = m.provider.putObjectConditional!.bind(m.provider);
m.provider.putObjectConditional = async value => {
if (value.objectKey.endsWith("/head.json")) throw new Error("unknown head publication failure");
return put(value);
};
await expect(store.append(handle, { ...event(1), sourceCursor: 2, preservesSourceCoverage: true }))
.rejects.toThrow("unknown head publication failure");
await expect(store.append(handle, { ...event(2), sourceCursor: 5, preservesSourceCoverage: true }))
.rejects.toThrow("unknown head publication failure");
expect((await store.read(handle)).content).toBe("");
await store.finalize(handle);
});
it("binds source proof to exact immutable bytes and invalidates it on ordinary appends", async () => {
const m = memory(), options = { provider: m.provider, keyPrefix: "logs", flushMs: 1,
assertWriterAuthority: async () => undefined };
const store = createObjectRunLogStore(options), handle = await store.begin(input);
expect(handle.initialSourcePrefixVerified).toBe(false);
await store.recordVerifiedSourcePrefix!(handle, 0);
await store.append(handle, { ...event(1), sourceCursor: 2, preservesSourceCoverage: true });
await store.finalize(handle);
const replacement = createObjectRunLogStore(options), verified = await replacement.begin(input);
expect(verified.initialSourceCursor).toBe(2);
expect(verified.initialSourcePrefixVerified).toBe(true);
const head = JSON.parse([...m.objects].find(([key]) => key.endsWith("/head.json"))![1].toString());
expect(Object.keys(head).sort()).toEqual([
"cleanupAfter", "closed", "deleted", "end", "generation", "owner", "root", "roots", "sequence", "sourceCursor", "v",
]);
// An older/generic caller cannot carry the attestation across new bytes,
// even when it reuses the old max cursor or calls its payload a diagnostic.
await replacement.append(verified, { ...event(2), sourceCursor: 2,
chunk: '{"type":"paperclip.prp.event","event":{"duplicate":true}}' });
await replacement.finalize(verified);
const legacy = await store.begin(input);
expect(legacy.initialSourceCursor).toBe(2);
expect(legacy.initialSourcePrefixVerified).toBe(false);
await store.finalize(legacy);
});
it("fails closed when an existing exact-prefix proof is malformed or changed", async () => {
const m = memory(), options = { provider: m.provider, keyPrefix: "logs", flushMs: 1,
assertWriterAuthority: async () => undefined };
const store = createObjectRunLogStore(options), handle = await store.begin(input);
await store.recordVerifiedSourcePrefix!(handle, 0);
await store.append(handle, { ...event(1), sourceCursor: 2, preservesSourceCoverage: true });
await store.finalize(handle);
const proofs = [...m.objects.keys()].filter(key => key.includes("/objects/source-prefix-proof-v1-"));
expect(proofs.length).toBeGreaterThan(0);
for (const key of proofs) m.objects.set(key, Buffer.from('{"schema":"changed-proof"}'));
await expect(createObjectRunLogStore(options).begin(input))
.rejects.toThrow("object_journal_source_prefix_proof_invalid");
});
it("batches concurrent appends, confirms durability, and resumes offsets/sequence on a replacement", async () => {
const m = memory(),
options = {
provider: m.provider,
keyPrefix: "logs",
flushMs: 10,
assertWriterAuthority: async () => undefined,
};
const a = createObjectRunLogStore(options),
handle = await a.begin(input),
before = m.puts();
const sizes = await Promise.all(
Array.from({ length: 100 }, (_, i) => a.append(handle, event(i + 1))),
);
expect(m.puts() - before).toBe(2);
const b = createObjectRunLogStore(options);
const read = await b.read(handle);
expect(read.content.trim().split("\n")).toHaveLength(100);
const successor = await b.begin(input);
expect(successor.initialSequence).toBe(100);
expect(successor.initialBytes).toBe(sizes.reduce((sum, size) => sum + size, 0));
await b.append(successor, event(101));
const summary = await b.finalize(successor);
expect(summary.bytes).toBeGreaterThan(successor.initialBytes!);
expect(summary.sha256).toBe(
createHash("sha256")
.update((await b.read(successor)).content)
.digest("hex"),
);
await expect(a.append(handle, event(102))).rejects.toThrow("another writer");
});
it("finalization flushes already accepted writes and rejects later append admission", async () => {
const m = memory(),
store = createObjectRunLogStore({
provider: m.provider,
keyPrefix: "logs",
flushMs: 1000,
assertWriterAuthority: async () => undefined,
});
const h = await store.begin(input),
pending = store.append(h, event(1));
const finalizing = store.finalize(h);
await expect(store.append(h, event(2))).rejects.toThrow("closed");
const [size, result] = await Promise.all([pending, finalizing]);
expect(result.bytes).toBe(size);
});
it("does not acknowledge a batch when storage fails", async () => {
const m = memory(),
store = createObjectRunLogStore({
provider: m.provider,
keyPrefix: "logs",
flushMs: 1,
assertWriterAuthority: async () => undefined,
});
const h = await store.begin(input);
m.offline(true);
await expect(store.append(h, event(1))).rejects.toThrow("storage offline");
m.offline(false);
expect((await store.read(h)).content).toBe("");
});
it("preserves UTF-8 and byte offsets across tiny pages and aligned tails", async () => {
const m = memory(),
store = createObjectRunLogStore({
provider: m.provider,
keyPrefix: "logs",
flushMs: 1,
assertWriterAuthority: async () => undefined,
});
const h = await store.begin(input);
await store.append(h, { ...event(1), chunk: "再開😀" });
await store.append(h, event(2));
const full = Buffer.from((await store.read(h)).content);
let offset = 0,
text = "";
for (;;) {
const page = await store.read(h, { offset, limitBytes: 7 });
text += page.content;
if (page.nextOffset === undefined) break;
expect(page.nextOffset).toBeGreaterThan(offset);
offset = page.nextOffset;
}
expect(Buffer.from(text)).toEqual(full);
const start = full.indexOf(Buffer.from("再")) + 1;
const tail = await store.read(h, { offset: start, limitBytes: 1000, alignStartToRecord: true });
expect(Buffer.from(tail.content)).toEqual(full);
});
it("backpressures admission at capacity without poisoning the writer or losing accepted output", async () => {
const m = memory(),
original = m.provider.putObjectConditional!;
let release!: () => void,
entered = false;
const blocked = new Promise<void>((resolve) => {
release = resolve;
});
m.provider.putObjectConditional = async (input) => {
if (input.objectKey.includes("/objects/") && !entered) {
entered = true;
await blocked;
}
return original(input);
};
const store = createObjectRunLogStore({
provider: m.provider,
keyPrefix: "logs",
assertWriterAuthority: async () => undefined,
});
const h = await store.begin(input);
const first = await store.enqueue!(h, { ...event(1), chunk: "a".repeat(7 * 1024 * 1024) });
await vi.waitFor(() => expect(entered).toBe(true));
let admitted = false;
const second = store.enqueue!(h, { ...event(2), chunk: "b".repeat(2 * 1024 * 1024) }).then(
(receipt) => {
admitted = true;
return receipt.committed;
},
);
await Promise.resolve();
expect(admitted).toBe(false);
release();
await Promise.all([first.committed, second]);
await store.append(h, event(3));
expect((await store.finalize(h)).bytes).toBeGreaterThan(9 * 1024 * 1024);
});
});