Files
PaperClipAI/doc/run-evidence-storage.md
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

17 KiB

Run log and provider trace object storage

Instances configured for S3-compatible file storage automatically use the s3_segments backend for new run logs and opted-in provider traces. Postgres retains the existing run/trace references and lifecycle rows. It adds no payload table, per-record SQL, or database-to-object compactor. Structured heartbeat_run_events retain their existing database path. Native events already committed there before a Runner ACK also provide the recovery source for an interrupted canonical native log export. No additional event copy or payload write is introduced. When native object logging uses runtime observability credentials, their log redaction values are registered once in the existing encrypted run-secret registry. This is bounded redaction metadata, not a transcript copy or a per-event write. Agent identity private material stays in its existing key store.

Configuration

No additional storage configuration is required. The existing instance storage.provider setting, or PAPERCLIP_STORAGE_PROVIDER, selects storage. The same config-file S3 fields and PAPERCLIP_STORAGE_S3_* overrides select the bucket, endpoint, region, prefix, and path style used by product files. Credentials use the same AWS SDK chain. Local-disk instances keep local_file logs and traces.

The instance's existing S3 prefix is preserved. The folders underneath it are:

<existing-prefix>/run-logs/segments-v1/<company>/<agent>/<run>/
<existing-prefix>/provider-traces/segments-v1/<company>/<run>/<trace>/<channel>/
<existing-prefix>/<company>/...    existing product files

Cloud's existing provisioning supplies a separate bucket and bucket-scoped credentials for each stack, plus the stack's encryption key. The app reuses that boundary rather than selecting a global customer bucket. Within a stack, journal keys remain company/run scoped. Cleanup lists only the resource's own prefix; it cannot sweep other companies, other stacks' prefixes, or product files. Folders are organization, not a substitute for bucket permissions or API access checks. Shared-bucket self-hosted deployments must retain their existing distinct instance prefixes and appropriate storage credentials.

Legacy run rows retain their recorded backend until verified migration. Their pre-existing RUN_LOG_S3_* mirror settings and key paths remain supported for legacy reads and writes. They do not override instance storage for new journals. Use stable bucket/prefix settings across replacements and releases. As with existing product files, changing the instance bucket or prefix is a separate storage move and requires copying the complete namespace and preserving its keys before changing configuration. Switching to local storage does not move existing S3 evidence. Readers reject an unavailable external store; they never substitute an empty local log. Restore the original stack's storage profile to read its history. This upgrade migrates legacy local evidence into the existing stack store; it does not introduce bucket relocation or reverse migration.

Raw capture still requires its existing explicit capture request. Its encryption uses the existing vault key, from PAPERCLIP_SECRETS_MASTER_KEY or the existing configured key file. Cloud already supplies the environment key. No separate trace key is introduced, and a missing vault key fails rather than creating a replacement. Disposable deployments must preserve the existing vault key along with their other secrets. Raw payload and index objects use AES-GCM with a key derived for the particular company/run/trace/channel. The bounded head holds only ownership, range, digest, and publication metadata. Existing capture opt-in, redaction, instance-admin access, task/company access, reveal/download auditing, and the 24-hour capture expiry remain in effect.

The provider must enforce If-None-Match: * and ETag If-Match, return ETags, and support prefix-scoped paginated listing. Claiming the first journal performs a conditional-write capability probe. A backend which ignores preconditions is rejected. Before deploying this release to an S3-configured production instance, qualify the provider's conditional writes, range/read consistency, encryption, object versions, and cleanup. AWS API compatibility alone is insufficient evidence.

Publication and operating limits

Each batch uploads immutable payload segments and merges equal-height index roots into immutable binary nodes, then conditionally publishes one head object. The head carries at most 53 ordered roots. Every normally published payload and index node remains reachable; appends do not leave superseded index copies. Interrupted or fenced uploads can leave unpublished objects, which remain inside the resource prefix for scoped deletion. The head is the commit boundary. A stale writer can upload an orphan but cannot replace the current owner's published history. An uncertain response is reconciled against the exact head before returning a durability receipt. Committed reads use immutable roots, so publication cannot change the bytes behind an already selected snapshot.

An individual store append resolves only after publication. Heartbeat's onLog diagnostic callback waits for bounded admission without serially waiting for each network batch. At capacity it waits for space; admission beyond the bounded waiting allowance is rejected without poisoning accepted batches. Transient network, 409, 429 and server errors receive bounded retries. A 412 or a changed head fences the stale writer; a 409 alone does not prove ownership loss or conditional-write support. Live log messages and progress are published after storage confirmation. Finalization drains admitted writes before closing and hashing the stream. Logging failure reports incomplete persistence and leaves the final size/digest unknown rather than claiming a complete snapshot. The original progress projection remains coarsely throttled; concurrent batch completions share a single progress write.

Defaults and fixed safeguards:

Limit Value
Dirty batch deadline 1 second, configurable from 1 ms to 30 seconds
Segment target 1 MiB
Pending bytes per writer 8 MiB
Pending run-log bytes per process 64 MiB
Additional waiting admission 8 MiB / 32 calls per process
Concurrent run-log flushes 4
Concurrent journal object operations 8, with 32 queued operations
Object operation/batch cancellation deadline 15 seconds
Current index fanout / maximum roots 2 children / 53 roots
Journal head read bound 64 KiB
Trace encoded payload bound per sidecar 192 MiB, in addition to the existing raw capture limit

A configured but empty log store sends no periodic request. Dirty buffers, capture file-change events, and actual retention/retry obligations drive work. Use request/transfer counts, byte volume, steady versus bursty producers, concurrent runs, and control/API latency to size a deployment. The local S3 qualification is a synthetic workload, not a production cost forecast.

Finalization streams the committed bytes once to compute the existing complete file SHA-256. It does not re-upload the entire log. Range indexes avoid loading all segment descriptors to read a tail. Historical consumers, UTF-8/NDJSON record alignment, issue previews, feedback, and customer-success inspection dispatch through the persisted backend. Logical reads retain the existing authorization. On-demand native repair closes its verified committed range with an exact byte count and leaves an unavailable full-file SHA-256 null. It does not make a log page request re-download the entire archive to compute that optional digest.

Durability boundary

Committed log receipts and captured object prefixes survive web disk loss. Output still buffered only by the current web process has no durable receipt. The live log path waits for publication before showing that output. Raw sidecar capture remains optional; a crash can leave an incomplete uncommitted tail, and only durably closed channels plus valid terminal markers qualify as complete.

Native PRP events have a surviving source: the control port already commits validated, redacted events before acknowledging them. The S3 head checkpoints the highest exported database event cursor with the batch's bytes. A replacement replays later native source rows in bounded 16-row pages, checks their identity and canonical hash, and exports the same paperclip.prp.event representation through normal log redaction/compaction. Late callbacks and duplicate delivery cannot append the same source record again. This is a canonical native export; generic stdout, stderr, and raw provider traces are not reconstructed from event rows. The control ACK and sparse checkpoint formats remain unchanged.

Recovery runs before native execution reconnects. If the run settled before its archive finished, the normal log API, issue preview, or feedback reader can repair it after the native controller lease expires. Concurrent requests share recovery; final metadata is saved only when no later native source remains. Read-only customer-success inspection reads the currently published prefix. A failed repair leaves final size/digest unknown and preserves the existing source. Retained native events are not deleted by Runner cleanup. Recovery adds bounded reads and one final metadata update, with no new per-record SQL on the normal contiguous output path. Raw optional capture can still be incomplete after a crash. Credential-update, retained-cleanup, and trace-reprojection records have separate source namespaces and do not enter this log export. Corrupt canonical records fail integrity validation. Shared on-demand repair has a 30-second lifetime; cancellation removes a waiting reader and aborts storage work when no readers remain. It preserves already published cursors so a later request can resume. Live export and recovery both redact the existing agent identity and known run secrets before publication. Recovery reads existing identity material without provisioning a key. If best-effort repair loses ownership or fails, ordinary log reads serve the published prefix and leave completion metadata unknown; request cancellation still propagates.

The remote continuity protocol and the parent deployment's other filesystem and HTTP handoff requirements still apply.

Trace deletion, expiry, and sleep

Deletion/expiry denies reads through a database tombstone before payload cleanup. Object journal tombstones prevent further publication. If an active writer may have an in-flight upload, cleanup waits at least 30 seconds and remains a durable retry obligation. A successful manual DELETE requires payload cleanup; an unsettled cleanup returns a retryable failure, and the shared retention worker retries it. Tombstones remain after object removal. Historical backups and object-version retention need a separate operator policy; an ordinary DELETE must not be mistaken for erasure of historical versions.

The shared coordinator restores expiry/cleanup work on startup and registers actual deadlines for local and external captures. New local inserts also wake it; expired backlogs drain in bounded pages. No completed-history polling is added. Trace expiry is not yet part of Cloud's durable wake contract, so outstanding trace deadlines conservatively block instance sleep. Removing that blocker requires qualification of the corresponding external wake, not a longer polling interval.

Trace expiry and failed-deletion recovery remain registered when HEARTBEAT_SCHEDULER_ENABLED=false. Disabling agent scheduling does not disable retained-data cleanup. The worker still respects warm standby, admission drain, actual deadlines, and shutdown.

History migration and rollback

S3-configured servers automatically migrate retained local history in the background. No command or extra configuration is required. The existing delivery coordinator starts the upgrade outside request handling, independently of the heartbeat scheduler toggle. Each batch processes at most one log and one trace, then yields for one second. Existing references are the durable work inventory. Restarting reconstructs unfinished work from those references; already migrated rows are excluded. No new payload or job table is added.

Active writers, missing files, corrupt data, and storage failures leave history unresolved. Other pages continue. The server logs each blocked resource and a pass summary. Unresolved passes retry after five minutes, with backoff up to 30 minutes. Transport failures retry through the shared coordinator. After all retained history is migrated, the worker stops querying and contacting storage. Trace source hashing and remote verification stream bounded chunks instead of loading a complete capture into server memory. The worker cancellation signal reaches file reads, trace opening, conditional probing, uploads and verification. Local-disk instances do not register this worker. Outstanding migration conservatively blocks instance sleep, and shutdown aborts the batch and waits for owned work.

Deploy compatible readers and stop old binaries from starting new local runs. The upgrade waits for existing writers to settle and their leases to expire. Keep the source volume attached until migration completes and clean-filesystem reads pass. Automatic copying cannot recover a file after its only copy is lost.

server/scripts/migrate-run-evidence.ts remains an optional diagnostic and repair tool. Its default is a read-only inventory; --apply runs the same verified importer used by the automatic worker. --company, --after-run, --after-trace and --limit allow scoped investigation against an explicitly selected DATABASE_URL. Normal upgrades do not require this tool. It does not stop agents, select a production target, delete source files, or certify volume removal.

For logs, migration verifies exact local bytes or a mirror with proven length and digest, compares any previously uploaded prefix, verifies remote SHA-256, then conditionally changes the run's backend/reference. Unknown-completeness mirrors, missing/corrupt payloads, and active writers block publication. Existing trace bytes, download ordering, integrity state and original expiry are retained. Neither path fabricates missing historical data or extends trace retention. For finalized native logs, matching the recorded size and SHA-256 proves the complete legacy file, including display chunks truncated by the existing 64 KiB formatter. Migration preserves those exact bytes and records the settled source cursor. If either completeness field is absent, a bounded NDJSON scan must prove ordered coverage of the existing canonical source records. Missing ranges or chunks whose identities cannot be verified block publication as native_log_source_coverage_unproven. A database's latest event cursor alone does not establish completeness. Publication checks that the original reference, completeness metadata, and source cursor have not changed. Keep the original volume and resolve blocked inventory before cutover. An interrupted trace import keeps an s3-import-v1: reference: reads still use the original local sidecars, while deletion and expiry retain responsibility for the staged object prefix. The automatic worker resumes the verified switch after restart or retry. Ordinary local traces have no S3 cleanup dependency.

Keep the volume until every retained item has been verified from a clean web filesystem. Rollback must use a compatible reader against the same remote state. An older binary or stale local volume is not a valid rollback target after new external writes. Enforce that floor in the owning deployment procedure.

Qualification

Run the storage, recorder, migration, privacy and retention tests. The opt-in S3/Postgres integration fixtures use PAPERCLIP_LOG_TEST_S3_ENDPOINT and a dedicated PAPERCLIP_RUN_EVIDENCE_MIGRATION_DATABASE_URL ending in _test. They create unique test buckets and schemas, and remove only those resources. The privacy route suite also accepts PAPERCLIP_RUN_LOG_PRIVACY_TEST_DATABASE_URL for a dedicated, fully migrated database ending in _test; it clears its fixtures.

server/scripts/qualify-object-run-logs.ts exercises the actual AWS SDK against a loopback test backend, confirms exact replacement reads and stale-writer rejection, and reports requests/bytes/timing. It uses synthetic credentials and refuses a non-loopback target. This proves its tested transport and workload; production-provider qualification and actual Railway deployment remain separate.

server/scripts/qualify-native-log-recovery.ts uses the real Rust recovery-fixture example, real Postgres, the control port, production recorder, and S3 backend. It kills the controller after Runner ACKs but before the S3 cursor catches up, deletes that controller's directory, and restores sparse control state into a fresh controller. It checks exact source order, no duplicate records, the same surviving Runner PID, and control/Stop responsiveness. Build the example with cargo build --locked --manifest-path packages/paperclip-runner/runner/Cargo.toml -p paperclip-runner-core --example recovery-fixture. It accepts the same two explicit loopback test endpoints and creates a private schema and bucket. This deterministic protocol experiment does not qualify a live provider, remote execution environment, or production S3 vendor.