Files
PaperClipAI/server/src/services/object-run-log-store.test.ts
T
DottaandClaude Opus 5.5 d1b5cfe038 feat(connections): let users delete data read through a connection (#22010)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Agents call connected apps, such as Google Workspace, through
Paperclip's tool gateway
> - Paperclip saves part of each tool result, approval previews, app
views and the full run transcripts that contain tool output
> - No user action deleted this data. Removing the connection left it in
place
> - Google's restricted-scope review requires that users can delete the
data an app obtained, and that the privacy policy says how
> - This pull request adds "Delete data read through this connection"
for any connection, on the connection's page and as an option when you
remove it
> - The benefit is that the picker text ("They stay there until you
delete them") is now true, and the privacy policy can link to a help
page

## Linked Issues or Issue Description

**Subsystem affected**

Connections (tool gateway audit tables, run logs, run events) and the
Connectors UI.

**Problem or motivation**

Paperclip stores content from a connection's tool calls in several
places and gives users no way to delete it:

- `tool_invocations.arguments_summary/result_summary` and
`tool_call_events.arguments_summary/request_summary/result_summary` keep
the first ~4,000 characters of each redacted value
(`summarizeToolValue`, `tool-access-policy.ts` `redactArguments`). No
retention limit.
- `tool_action_requests` keeps `canonical_arguments_summary`,
`preview_markdown` and `signed_arguments`. The linked approval card
(`issue_thread_interactions`) keeps copies in `payload.detailsMarkdown`,
`payload.toolAction.previewMarkdown`,
`payload.toolAction.argumentsSummaryJson` and
`result.toolAction.resultSummary`.
- `tool_mcp_app_views` keeps `tool_input` and `tool_result` for MCP app
views.
- Run transcripts hold full tool output: the run log (`local_file` with
an optional S3 mirror, or `s3_segments`/`s3_archive` object journals),
`heartbeat_run_events.message/payload`, and
`heartbeat_runs.stdout_excerpt/stderr_excerpt`. Neither run-log store
had a delete path.
- Connection removal (`removal.ts`) archives the connection and revokes
credentials. It deletes no content.

**Proposed solution**

A durable, resumable, company-scoped deletion request per connection.
See "Design" below.

**Alternatives considered**

- Delete synchronously in the request. Rejected: an interrupted request
leaves partial state that needs a person to retry it.
- Delete only the run events that mention the connection. Rejected: tool
output also reaches the model's later messages, so the safe unit is the
whole run transcript.
- Delete the audit rows. Rejected: counts, outcomes and hashes feed the
activity history and usage counts.

## Design

**Rule.** The job never drops a reference to content it has not
confirmed deleted. It is marked complete, and writes the
`tool_connection.content_deleted` activity entry, only after every step
succeeded. A step that cannot confirm its work throws. The request then
stays pending, the UI says "Paperclip keeps trying until it finishes",
and the worker retries it.

**Store inventory.** Every place that stores tool arguments, results or
previews. I found them from `summarizeToolValue`, `redactArguments`,
`writeAudit`, and every column or JSON field named like summary,
preview, arguments, result, toolInput or toolResult.

| Store | Content | Cleared by this PR | Proof |
| --- | --- | --- | --- |
| `tool_invocations.arguments_summary`, `result_summary`, `progress` |
Redacted request/result preview, provider progress | Yes: `summary`
becomes `""` with `contentDeletedAt`; `progress` null; size and sha256
kept | content-deletion test 1 |
| `tool_call_events.arguments_summary`, `request_summary`,
`result_summary` | Same previews | Yes, same | test 1 |
| `tool_access_audit_events.details.argumentsSummary` (`writeAudit`) |
Argument preview | Yes, same; decision, ids, size, hash kept | test 1 |
| `tool_action_requests.canonical_arguments_summary`,
`preview_markdown`, `signed_arguments` | Approval preview and arguments
| Yes, for settled requests | test 1, card retry test |
| Approval card in `issue_thread_interactions`:
`payload.detailsMarkdown`, `payload.toolAction.previewMarkdown`,
`payload.toolAction.argumentsSummaryJson`,
`result.toolAction.resultSummary` | Approval preview, arguments,
executed result | Yes. Cards are found from every settled request of a
batch, in the same transaction | test 1, card retry test |
| `heartbeat_runs.context_snapshot` and `agent_wakeup_requests.payload`
(`toolAction(s)[].resultSummary`,
`paperclipAgentMessage.untrustedToolResults[].resultSummary`) | Approved
action result delivered to the agent | Yes, for settled runs and settled
wakes | test 1 |
| `tool_mcp_app_views.tool_input`, `tool_result`, `model_context` | App
view input, result, shared context | Yes: rows deleted | test 1 |
| Run log: object journal, archive journal, original `local_file` log
and its legacy S3 mirror | Full transcript | Yes, every copy, for each
settled run that called the connection or received an approved result |
run-log-store tests, test 1 |
| `heartbeat_run_events.message`, `payload` | Transcript events | Yes,
except structural events (lifecycle, terminal, presentation, usage,
compaction, session/turn start, `native.*`) | test 1 |
| `heartbeat_runs.stdout_excerpt`, `stderr_excerpt`, and every string
`summary`, `result`, `message`, `text`, `output`, `content` or `body` at
any depth of `result_json` (including `nativeResult`, `acceptedResult`,
`semanticResult` and their `continuation`) | Output excerpts and final
answer | Yes; schema and control fields kept | test 1, canary |
| `approvals.payload` (formal board approval) | Tool name, risk and
hashes only | Not needed: no content | — |
| `tool_mcp_tasks` | Request hash and sealed provider task id; no result
| Not needed: no content | — |
| `tool_mcp_elicitations.questions` and their question cards | Questions
the provider asked a person | No. These are provider prompts, not tool
results, and the answered question stays in the task. Follow-up if
wanted | — |
| `tool_mcp_skills`, `tool_mcp_skill_files`, `tool_catalog_entries` |
Skills and tool descriptions the provider publishes | No. These are
provider definitions, not data read through tool calls | — |
| Transcripts of later runs that read an app view's `model_context` |
Shared app context | No. Nothing records which runs read it. The help
page says so. Follow-up | — |
| `issue_comments.body`, issue documents (including continuation
summaries), files, chat messages | Task content written by agents or
Paperclip | No, by design. The user removes it by editing or deleting it
or the task. The confirmation says in bold that anything agents wrote
into tasks is not removed, and so does the help page. The canary
excludes `issue_comments.body` by name for this reason | canary asserts
it is kept |
| Raw provider traces | Full provider traffic | No. Admin opt-in,
encrypted, expire within 24 hours | — |
| Feedback exports already sent | Run logs the user chose to share | No.
Already outside Paperclip | — |
| Content of runs of a deleted task or company | Same stores | No.
Follow-up | — |

**Durable request (schema change).** I added one table,
`tool_connection_content_deletions`, and migration `0490`. I followed
`doc/DATABASE.md`: edited the schema, exported it from
`packages/db/src/schema/index.ts`, ran `pnpm db:generate`, and ran the
migration drift and compatibility tests. The classifier marks it
`online_compatible` (a new table and its indexes only). No existing
table can hold a durable per-connection request with a cutoff time,
cursor, counts and retry state. Without it, an interrupted deletion
could resume only when a person pressed the button again.

**Resume after restart.** The worker uses the shared
`registerDeadlineWork` lifecycle on a new
`tool-connection-content-deletion` queue. The request insert signals the
queue in the same transaction. At server start the worker runs once,
`next()` finds any pending row, and processing continues from the saved
phase and cursor. Nobody presses anything. `next()` returns a deadline
only while a pending row exists, so an idle instance sends no recurring
query. A failure records `attempts` and `last_error` and retries after
30 seconds.

**One run selection.** `runsWithStoredContentSql` selects the runs whose
transcripts are deleted: runs that made a tool call or tool-call event
through the connection, and runs whose context lists one of the
connection's approved action requests, limited to runs that still hold a
log, an excerpt, result text or a content event. The dialog count, its
in-progress warning and the job's `runs` phase all use this one
function.

**Phases.** `invocations`, `events`, `auditEvents`, `appViews`,
`deliveredResults` (50 action requests per page; matching runs and wakes
are locked with `FOR UPDATE` before their documents are rewritten),
`runs` (the shared selection, 50 run ids per page, then one run at a
time), `done`.

**Canary test.** `tool-connection-content-deletion-canary.test.ts` puts
a unique marker in a tool call's arguments and result, an approved
action with a preview, a result delivered to a later run and its wake, a
native run that quotes the marker in its answer and events, a run log
migrated from a local file with an S3 mirror to an object journal, an
MCP App view and the audit tables. It checks that the marker is first
present in the database, the object store, the legacy mirror and the log
files. After the deletion it scans every `text`, `varchar`, `json` and
`jsonb` column of every table found through `information_schema` (no
hand-written table list), every object in both stores and every file
under the log directory. Any hit fails with the table and column or the
key. It runs three times: a complete deletion, a deletion interrupted
twice by storage failures and resumed, and two deletions for different
connections on one task at the same time. The only exclusion is
`issue_comments.body`, named with its reason.

**Batching and time budget.** Tool rows are read in pages of 200 with
keyset pagination on the existing `(company_id, created_at)` indexes,
bounded by the request time. Each page's writes and the saved progress
commit in one transaction. Counts are therefore exact, and a crash
repeats at most one page, idempotently. Runs advance one at a time from
the shared selection. Each 1,000-event page is its own step. Log removal
is its own step and runs before its progress transaction, so object
storage calls never run inside a database transaction. The 10-second
budget is checked after every step. Nothing changes on the agent boot or
tool-call path.

**In-flight work.** A run counts as settled only when its status is
terminal, `finished_at` is set, cost accounting is done, and no native
finalization is open. Calls, approvals, events, app views, delivered
results and transcripts tied to other runs or wakes are skipped and
counted. The confirmation says "N runs are still working and will be
skipped. Delete again after they finish."

**Permissions.** Board users with configure access (connection manager
or creator) can delete, like `DELETE /tool-connections/:id`. Agents,
viewers and other companies are refused. The activity entries
`tool_connection.content_deletion_requested` and
`tool_connection.content_deleted` hold counts only.

**UI reads.** The dialog loads counts once when it opens. While a
deletion runs, it polls `GET
/tool-connections/:id/stored-content/deletion`, a single indexed row
read, every 2 seconds. Polling stops when the job completes or the
dialog closes. The Delete button is not gated on counts.

## What Changed

- `packages/db`: new `tool_connection_content_deletions` table and
migration `0490` (online compatible: new table and its indexes only).
- `packages/shared`: `ToolConnectionStoredContent`,
`ToolConnectionContentDeletion` and counts types; optional
`contentDeletedAt` on `ToolRedactedValueSummary`.
- `server`: `RunLogStore.remove`, which deletes every copy of a run's
log (`composeRunLogStore`); `content-deletion.ts` service; deadline
worker wired into startup and pre-drain; `GET
/tool-connections/:id/stored-content`, `POST` and `GET
/tool-connections/:id/stored-content/deletion`, and `DELETE
/tool-connections/:id?deleteStoredContent=true`; OpenAPI entries.
- `ui`: "Delete data" row on the connection's Permissions tab with a
confirmation that shows counts, skipped runs, and "This cannot be
undone"; "Also delete data read through this connection" checkbox in the
Connectors removal dialog.
- Docs: user help
`docs/guides/board-operator/deleting-connection-data.md` (for the
privacy policy link) and an API note in
`doc/connections/CONNECTOR-PLAYBOOK.md`.
- `tests/runner-e2e/source-sdk-public-inputs.json` refreshed for the
shared type change.

`server/src/routes/tool-access.ts` (3,010 lines) and
`ui/src/pages/apps/Browse.tsx` (1,722 lines) grow by about 40 and 20
lines. The routes reuse that file's connection access checks; the dialog
reuses the existing removal confirmation. The new logic lives in its own
files.

## Verification

- `server/src/__tests__/tool-connection-content-deletion.test.ts`
(embedded PostgreSQL): content is gone from every "Yes" store in the
inventory; rows, hashes and sizes stay; another connection and another
company are untouched; a running run is skipped and is deleted after it
settles; a storage failure leaves the request pending with `retrying`,
and the next pass completes it; an approval-card update that fails once
is cleared on the retry; an unrecognised log backend keeps the pointer,
keeps the job pending and writes no completion entry; a zero time budget
yields after every step and still finishes; a repeat request returns the
pending one; agents and outsiders are refused; removal with
`deleteStoredContent=true` queues the deletion.
- `run-log-store.test.ts` and `object-run-log-store.test.ts`: `remove`
deletes local and mirrored logs and object journals, removes a migrated
run's original local file and mirror with its journal, refuses an object
log when object storage is not configured, and is idempotent.
- `ui/.../StoredContentDeletion.test.tsx`: confirmation text, counts,
skipped-run warning, and the request.
- Red: these tests fail on `master` because `remove`, the service and
the routes do not exist. Green on this branch.
- Ran: the tests above, `openapi-routes`,
`server-startup-feedback-export`, `tool-connection-removal`,
`packages/db` migration drift and compatibility tests, all
`ui/src/pages/apps` tests (950), `pnpm check:token-gates`, server and UI
`tsc --noEmit`. `pnpm verify` exits 2 (global CI input changed), so
required CI supplies broad coverage.

## Risks

- Deleting is permanent by design. The confirmation says so.
- A `local_file` log written on another replica's local disk stays on
that pod's disk until the pod is replaced; its S3 mirror is deleted. New
logs on S3-configured instances use object journals, which are deleted.
- On versioned buckets, earlier object versions remain until the
bucket's lifecycle policy removes them (the existing journal delete path
does not remove versions).
- Not in this PR (follow-ups): the "No" rows of the inventory (except
agent-written task content, which is out of scope by design), mainly the
same deletion when a task or a company is deleted, and later runs that
read an app view's shared context.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via 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

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 08:55:35 -06:00

686 lines
34 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 { S3_CLIENT_MAX_SOCKETS } from "../storage/s3-client-limits.js";
import { OBJECT_JOURNAL_IO_CEILING, OBJECT_JOURNAL_READ_IO_RESERVE, OBJECT_JOURNAL_UPLOAD_SLOTS, ObjectJournalBusyError,
objectJournalIOSlots, objectJournalUploadActivity, objectJournalUploadSlots } from "./object-byte-journal.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("removes every object of a finalized log and stays removable", async () => {
const m = memory(), store = createObjectRunLogStore({ provider: m.provider, keyPrefix: "logs",
assertWriterAuthority: async () => undefined });
const handle = await store.begin(input);
await store.append(handle, { ...event(1), chunk: "tool result content" });
await store.finalize(handle);
expect([...m.objects.keys()].some((key) => key.includes(handle.logRef))).toBe(true);
await store.remove!(handle);
await store.remove!(handle);
expect([...m.objects.keys()].filter((key) => key.includes(handle.logRef) && !key.endsWith("/head.json"))).toEqual([]);
await expect(store.read(handle)).rejects.toThrow("Run log not found");
});
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("begins a new run log with one head read and no source proof read", async () => {
const m = memory(), options = { provider: m.provider, keyPrefix: "logs", flushMs: 1,
assertWriterAuthority: async () => undefined };
const get = m.provider.getObject.bind(m.provider), reads: string[] = [];
m.provider.getObject = async value => { reads.push(value.objectKey); return get(value); };
const headReads = () => reads.filter(key => key.endsWith("/head.json")).length;
const proofReads = () => reads.filter(key => key.includes("/objects/source-prefix-proof-v1-")).length;
const handle = await createObjectRunLogStore(options).begin(input);
expect(handle.initialSourcePrefixVerified).toBe(false);
expect({ head: headReads(), proof: proofReads() }).toEqual({ head: 1, proof: 0 });
reads.length = 0;
const resumed = await createObjectRunLogStore(options).begin(input);
expect(resumed.initialSourcePrefixVerified).toBe(false);
expect({ head: headReads(), proof: proofReads() }).toEqual({ head: 1, proof: 1 });
});
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("resumes a run log through the prefix read and proof while the store still hides the head it just published", async () => {
const m = memory(),
options = { provider: m.provider, keyPrefix: "logs", flushMs: 10, assertWriterAuthority: async () => undefined };
const lagged = { ...input, runId: "lagged-run" };
const a = createObjectRunLogStore(options),
handle = await a.begin(lagged);
await Promise.all([1, 2, 3].map((seq) => a.append(handle, event(seq))));
const b = createObjectRunLogStore(options),
successor = await b.begin(lagged);
const original = m.provider.getObject;
let hiddenHeadReads = 0;
m.provider.getObject = async (i) => {
if (i.objectKey === "logs/segments-v1/company/agent/lagged-run/head.json") {
hiddenHeadReads++;
throw Object.assign(Error("not yet visible"), { name: "NoSuchKey", $metadata: { httpStatusCode: 404 } });
}
return original(i);
};
const read = await b.read(successor, { limitBytes: successor.initialBytes });
expect(read.content.trim().split("\n").map((line) => JSON.parse(line).seq)).toEqual([1, 2, 3]);
await b.recordVerifiedSourcePrefix!(successor, 0);
expect(successor.initialSourcePrefixVerified).toBe(false);
expect(hiddenHeadReads).toBeGreaterThanOrEqual(2);
m.provider.getObject = original;
await b.append(successor, event(4));
const resumed = await b.read(successor);
expect(resumed.content.trim().split("\n").map((line) => JSON.parse(line).seq)).toEqual([1, 2, 3, 4]);
});
it("fails a read of a run log that was never written", async () => {
const m = memory(),
store = createObjectRunLogStore({ provider: m.provider, keyPrefix: "logs", assertWriterAuthority: async () => undefined });
await expect(store.read({ store: "s3_segments", logRef: "company/agent/never-written", attemptId: "attempt" }))
.rejects.toMatchObject({ status: 404, message: "Run log not found" });
});
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.each(["commit", "storage failure", "Stop"] as const)("settles pre-close bounded admission through %s and fences new producers", async mode => {
const m = memory(), original = m.provider.putObjectConditional!;
let release!: () => void, entered = false;
const gate = new Promise<void>(resolve => { release = resolve; });
const cancellation = new AbortController();
m.provider.putObjectConditional = async value => {
if (value.objectKey.includes("/objects/") && !entered) {
entered = true;
await gate;
value.signal?.throwIfAborted();
if (mode === "storage failure") throw new Error("controlled upload failure");
}
return original(value);
};
const store = createObjectRunLogStore({ provider: m.provider, keyPrefix: "logs", assertWriterAuthority: async () => undefined });
const handle = await store.begin({ ...input, signal: cancellation.signal });
const first = await store.enqueue!(handle, { ...event(1), chunk: "a".repeat(7 * 1024 * 1024) });
const committed = first.committed.catch(error => error);
await vi.waitFor(() => expect(entered).toBe(true));
let admitted = false;
const waiting = store.enqueue!(handle, { ...event(2), chunk: "b".repeat(2 * 1024 * 1024) })
.then(receipt => { admitted = true; return receipt.committed; }).catch(error => error);
let finalized = false;
const finalizing = store.finalize(handle).then(value => { finalized = true; return value; });
try {
await expect(store.enqueue!(handle, event(3))).rejects.toThrow("closed");
const peer = await store.begin({ ...input, runId: "peer" });
await store.append(peer, { ...event(1), chunk: "peer output" });
expect((await store.finalize(peer)).bytes).toBeGreaterThan(0);
expect(admitted).toBe(false);
expect(finalized).toBe(false);
if (mode === "Stop") cancellation.abort(new Error("controlled Stop"));
} finally { release(); }
const [firstResult, secondResult, summary] = await Promise.all([committed, waiting, finalizing]);
if (mode === "commit") {
expect(admitted).toBe(true);
expect(summary.bytes).toBe(Number(firstResult) + Number(secondResult));
const hash = createHash("sha256");
let offset = 0, chunks = 0;
for (;;) {
const page = await store.read(handle, { offset, limitBytes: 1024 * 1024 });
hash.update(page.content);
chunks += (page.content.match(/"chunk":/g) ?? []).length;
if (page.nextOffset === undefined) break;
offset = page.nextOffset;
}
expect(chunks).toBe(2);
expect(summary.sha256).toBe(hash.digest("hex"));
} else {
expect(firstResult).toBeInstanceOf(Error);
expect(secondResult).toBeInstanceOf(Error);
expect(admitted).toBe(false);
expect(summary).toMatchObject({ bytes: null, sha256: null });
}
});
it("drains an admission waiting on global capacity while other writers flush", async () => {
const m = memory(), original = m.provider.putObjectConditional!;
let release!: () => void, uploads = 0;
const gate = new Promise<void>(resolve => { release = resolve; });
m.provider.putObjectConditional = async value => {
if (value.objectKey.includes("/objects/")) { uploads++; await gate; }
return original(value);
};
const store = createObjectRunLogStore({ provider: m.provider, keyPrefix: "logs", assertWriterAuthority: async () => undefined });
const handles = [], committed = [];
for (let index = 0; index < 9; index++) {
const handle = await store.begin({ ...input, runId: `full-${index}` });
handles.push(handle);
committed.push((await store.enqueue!(handle, { ...event(1), chunk: "x".repeat(7 * 1024 * 1024) })).committed);
}
await vi.waitFor(() => expect(uploads).toBe(4));
const target = await store.begin({ ...input, runId: "waiting" });
let admitted = false, finalized = false;
const waiting = store.enqueue!(target, { ...event(1), chunk: "y".repeat(2 * 1024 * 1024) })
.then(receipt => { admitted = true; return receipt.committed; });
const finalizing = store.finalize(target).then(value => { finalized = true; return value; });
try {
await expect(store.enqueue!(target, event(2))).rejects.toThrow("closed");
expect(admitted).toBe(false);
expect(finalized).toBe(false);
} finally { release(); }
const [bytes, summary] = await Promise.all([waiting, finalizing]);
expect(admitted).toBe(true);
expect(summary.bytes).toBe(bytes);
await Promise.all(committed);
await Promise.all(handles.map(handle => store.finalize(handle)));
});
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);
});
it("bounds ordinary reads while explicit internal reads keep queuing", async () => {
const m = memory(),
store = createObjectRunLogStore({
provider: m.provider,
keyPrefix: "logs",
assertWriterAuthority: async () => undefined,
});
const handle = await store.begin(input);
await store.append(handle, event(1));
await store.finalize(handle);
const get = m.provider.getObject;
let open!: () => void;
const gate = new Promise<void>((resolve) => {
open = resolve;
});
m.provider.getObject = async (i) => {
await gate;
return get(i);
};
const polls = Array.from({ length: 40 }, () => store.read(handle));
const excess = store.read(handle);
let rejected: unknown;
void excess.catch((error) => { rejected = error; });
let internal: ReturnType<typeof store.read> | undefined;
try {
await vi.waitFor(() => expect(rejected).toBeInstanceOf(ObjectJournalBusyError));
internal = store.read(handle, { priority: "background" });
open();
for (const poll of await Promise.allSettled(polls))
if (poll.status === "rejected") expect(poll.reason).toBeInstanceOf(ObjectJournalBusyError);
expect((await internal).content.trim().split("\n")).toHaveLength(1);
} finally {
open();
await Promise.allSettled([...polls, excess, ...(internal ? [internal] : [])]);
}
});
it("keeps the object storage sockets the journal may use within the storage client's budget", () => {
expect(OBJECT_JOURNAL_UPLOAD_SLOTS.ceiling + OBJECT_JOURNAL_READ_IO_RESERVE).toBeLessThanOrEqual(OBJECT_JOURNAL_IO_CEILING);
expect(OBJECT_JOURNAL_IO_CEILING).toBeLessThanOrEqual(S3_CLIENT_MAX_SOCKETS / 2);
});
async function uploadsInFlightWithOpenRuns(runs: number) {
const m = memory(),
store = createObjectRunLogStore({ provider: m.provider, keyPrefix: "logs", flushMs: 30_000,
assertWriterAuthority: async () => undefined });
const slotsBefore = objectJournalUploadSlots();
const handles = [];
for (let run = 0; run < runs; run++) handles.push(await store.begin({ ...input, runId: `run-${run}` }));
const put = m.provider.putObjectConditional!.bind(m.provider);
let open!: () => void;
const gate = new Promise<void>(resolve => { open = resolve; });
let inFlight = 0, peak = 0;
m.provider.putObjectConditional = async value => {
inFlight++;
peak = Math.max(peak, inFlight);
try {
await gate;
return await put(value);
} finally {
inFlight--;
}
};
const appended = await Promise.all(handles.map(handle => store.enqueue!(handle, event(1))));
const flushes = handles.map(handle => store.flush!(handle));
await vi.waitFor(() => expect(inFlight).toBe(Math.min(runs, objectJournalUploadSlots())));
await new Promise<void>(resolve => setImmediate(resolve));
const waiting = { slotsBefore, slots: objectJournalUploadSlots(), ioSlots: objectJournalIOSlots() };
open();
await Promise.all(flushes);
await Promise.all(appended.map(entry => entry.committed));
await Promise.all(handles.map(handle => store.finalize(handle, { computeDigest: false })));
return { ...waiting, peak, slotsAfterFinalize: objectJournalUploadSlots() };
}
it("gives a log upload slot to each ten open runs, so 200 runs upload at least twenty logs at once", async () => {
const result = await uploadsInFlightWithOpenRuns(200);
expect(result.slotsBefore).toBe(OBJECT_JOURNAL_UPLOAD_SLOTS.floor);
expect(result.peak).toBeGreaterThanOrEqual(20);
expect(result.peak).toBeLessThanOrEqual(result.ioSlots);
});
it("caps log uploads at the storage budget with 1,000 open runs and finishes every run's upload", async () => {
const result = await uploadsInFlightWithOpenRuns(1_000);
expect(result.slots).toBe(OBJECT_JOURNAL_UPLOAD_SLOTS.ceiling);
expect(result.peak).toBeLessThanOrEqual(result.ioSlots);
expect(result.ioSlots).toBeLessThanOrEqual(S3_CLIENT_MAX_SOCKETS / 2);
expect(result.slotsAfterFinalize).toBeLessThan(result.slots);
});
it("starts waiting uploads when runs open and starts no new upload after runs close until the count is under the limit", async () => {
const options = { keyPrefix: "logs", flushMs: 30_000, assertWriterAuthority: async () => undefined };
const busy = memory(), idle = memory();
const busyStore = createObjectRunLogStore({ ...options, provider: busy.provider });
const idleStore = createObjectRunLogStore({ ...options, provider: idle.provider });
const busyHandles = [];
for (let run = 0; run < 40; run++) busyHandles.push(await busyStore.begin({ ...input, runId: `busy-${run}` }));
const slotsBefore = objectJournalUploadSlots();
const put = busy.provider.putObjectConditional!.bind(busy.provider);
const held: Array<() => void> = [];
busy.provider.putObjectConditional = async value => {
await new Promise<void>(resolve => held.push(resolve));
return put(value);
};
const appended = await Promise.all(busyHandles.map(handle => busyStore.enqueue!(handle, event(1))));
const flushes = busyHandles.map(handle => busyStore.flush!(handle));
await vi.waitFor(() => expect(objectJournalUploadActivity().active).toBe(slotsBefore));
expect(objectJournalUploadActivity().waiting).toBe(40 - slotsBefore);
const idleHandles = [];
for (let run = 0; run < 160; run++) idleHandles.push(await idleStore.begin({ ...input, runId: `idle-${run}` }));
const grown = objectJournalUploadSlots();
expect(grown).toBeGreaterThanOrEqual(slotsBefore + 16);
expect(objectJournalUploadActivity().active).toBe(grown);
await vi.waitFor(() => expect(held).toHaveLength(grown));
const closing = Promise.all(idleHandles.map(handle => idleStore.finalize(handle, { computeDigest: false })));
let previous = grown, shrankWhileBusy = false;
while (held.length || objectJournalUploadActivity().waiting || objectJournalUploadSlots() > slotsBefore) {
held.shift()?.();
await new Promise<void>(resolve => setImmediate(resolve));
await new Promise<void>(resolve => setImmediate(resolve));
const { active } = objectJournalUploadActivity(), limit = objectJournalUploadSlots();
expect(active).toBeLessThanOrEqual(Math.max(previous, limit));
if (active > limit && limit === slotsBefore) shrankWhileBusy = true;
previous = active;
}
await closing;
busy.provider.putObjectConditional = put;
await Promise.all(flushes);
await Promise.all(appended.map(entry => entry.committed));
await Promise.all(busyHandles.map(handle => busyStore.finalize(handle, { computeDigest: false })));
expect(shrankWhileBusy).toBe(true);
expect(objectJournalUploadActivity()).toEqual({ active: 0, waiting: 0 });
});
});