## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - `paperclip-runnerd` delivers provider output to the controller through a durable outbox in `runner-state.json` > - Each save rewrites the whole state, then syncs the file and its directory > - runnerd saved once for every provider event in a poll, so a burst of k events paid k saves before any of them could leave > - #20217 made the provider state save once per poll. runnerd's own outbox still saved once per event > - This pull request commits each polled batch with one save > - The benefit is fewer syncs and full-state rewrites whenever events arrive together, on every disk, with no change to what recovery can replay ## Linked Issues or Issue Description Refs #20217 (the same change for the provider state file) Related: #17514 (closed; the same per-event rewrite on the controller side) **What existing behavior does this improve?** runnerd's commit of provider events into its durable outbox. **Subsystem affected** Paperclip Runner (`packages/paperclip-runner/runner/crates/runner-core/src/durable`). **Current behavior** `commit_executor_events` saves the full durable state once for each new event in a poll. A poll that returns k events costs k saves before the provider can release them. Each save writes the full state and calls `fsync` twice. **Proposed behavior** runnerd adds a polled batch (up to 128 events) to the outbox in memory. Then it saves once, and then it acknowledges the batch to the provider. A poll that returns k events costs one save. **Reason and benefit** Every save is a full rewrite and two syncs, so the save count sets the cost of durable delivery. On a local macOS APFS disk, one save takes about 10 ms. With 8 events per round, the cost drops from about 10.7 ms to about 2.4 ms per event. The change helps on any storage. It does not change what recovery can replay. **Breaking changes** None. The state file format does not change. Older and newer Runners read the same file. ## What Changed - `commit_executor_events` (group commit): - It adds each polled batch to the outbox and saves once. Only then does it acknowledge the batch to the provider. - The batch stays at 128 events, below the 256-receipt window. A crash between the save and the provider acknowledgement still replays every retained event exactly. - If an event is rejected (oversized, or over capacity), runnerd still saves and acknowledges the events before it. The provider keeps the rejected event and everything after it, as before. - If the save fails, runnerd acknowledges nothing. The provider keeps the whole batch. - Cumulative ACK persistence does not change. runnerd saves when an ACK empties the outbox, and after every 16 advances. - `DurableStateStore` counts saves in test builds only. - `DURABLE_TRANSPORT.md` describes the batch commit. An earlier revision of this pull request also let an outbox-emptying ACK wait for the next save. It was removed. Recovery treats an empty outbox on disk as fully delivered. `runnerd-acpx-source-reconciliation.test.ts` showed that a Runner stopped shortly after a completed run then started its provider once more on recovery. ## Verification - `cargo test -p paperclip-runner-core --lib durable::`: 136 pass, including 2 new tests in `src/durable/tests/batched_saves.rs`: - `provider_batch_commits_with_one_durable_save`: batches of 8 and 48 events each need one save. The reloaded file holds every event. - `a_streamed_round_saves_its_batch_once_and_its_emptying_ack_once`: 10 rounds of 1 or 8 events need 20 saves either way. The reloaded file has an empty outbox. - Existing tests that cover the accepted prefix, a failed save, backpressure, and receipts pass unchanged: - `event_batch_acknowledges_only_bounded_durable_prefixes` - `event_batch_never_acknowledges_a_failed_durable_save` - `disconnected_ingestion_keeps_durable_prefix_and_resumes_after_backpressure_ack` - `receipt_survives_outbox_ack_and_prevents_duplicate_delivery` - `cargo test -p paperclip-runner-core --test durable_recovery --test acpx_park_preparation --test acpx_park_readiness --test acpx_provider_suspend --test acpx_warm_attachment`: all pass. - With a freshly built runnerd: `vitest run src/live/runnerd-acpx-source-reconciliation.test.ts` (17 pass) and `vitest run src/live/runnerd-codex-transport.test.ts -t "replaces an owned v1 runner with fresh v2 authorization"` (pass). - `cargo fmt --all -- --check`: clean. - Local measurement: a release build on macOS APFS, 200 events of `item.delta`, not committed. | Events per round | Saves before | Saves after | Time before | Time after | | --- | --- | --- | --- | --- | | 1 | 400 | 400 | 3.9 s | 3.8 s | | 8 | 225 | 50 | 2.1 s | 0.49 s | ## Risks - Low risk. The file holds the same data after each batch as before. Only the number of intermediate saves changes. - A failed save inside a batch leaves the in-memory state ahead of the file, as a failed per-event save did before. The error stops the loop, as before. - The provider state file (ACPX, Codex and others) keeps its own save policy. This change touches only runnerd's state file. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, through Claude Code with tool use (shell, file editing, test 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 - [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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
23 KiB
Durable PRP transport
Core uses durable PRP v1 for a selected, flag-enabled paperclip_runner
agent or recovery of its persisted run. On a fresh launch or restart,
paperclip-runnerd selects durable mode from its connection arguments.
- With
--connect-url <url>, the Runner dials Core. - With
--listen-address 0.0.0.0 --listen-path /api/runner/v1/connect/<run-id>, the Runner listens for Core.--listen-portdefaults to43127.
A dialing Runner waits --reconnect-delay-ms (default 250) between
connection attempts and backs off after a failed one. A listening Runner
checks for an incoming connection every 10 ms (or sooner, when that delay is
smaller). It never redials, so a connection does not wait out the reconnect
delay after a disconnect or an authority rotation.
A listening Runner accepts one controller at a time. Core pings the Runner every 20 seconds. When the current controller sends no frame, ping included, for 90 seconds, the Runner closes that connection and accepts the next one within its reconnect grace. A path that broke without a close therefore cannot block a replacement controller.
In both modes, Runner enables TCP_NODELAY before the WebSocket handshake
when the connected peer is on loopback.
Choose one form. Both require PAPERCLIP_RUNNER_BOOTSTRAP_TICKET.
Recovery uses the same entry point. The Runner rejects --source-reconcile.
Trust boundary
- For outbound
ws://, every resolved address must be loopback. The Runner resolves the destination once and reuses the pinned addresses on reconnect. - A bootstrap ticket is read from
PAPERCLIP_RUNNER_BOOTSTRAP_TICKET, removed from the environment immediately, and never sent over the socket. Both peers prove possession through HMAC-SHA-256. - A successful bootstrap exchanges the one-use ticket for a connection-bound, expiring lease held only in memory. Once authentication starts, a failed bootstrap attempt is not replayed automatically.
- Post-authentication frames use AES-256-GCM with direction-specific keys, monotonically increasing counters, and session-bound associated data. Plaintext, replayed, out-of-order, oversized, or incorrectly bound frames fail closed.
- Cross-language authentication primitives use the UTF-8 domain bytes followed by a NUL byte, then each input as an unsigned 64-bit big-endian byte length and its raw bytes. Challenge proofs cover the lexicographically key-sorted, compact JSON challenge payload. The server-to-runner integration test is the parity gate for these TypeScript and Rust encodings.
- The durable state directory is private, symlinks are rejected, and updates use a private temporary file, file sync, atomic rename, and directory sync. Credentials and lease tokens are never written to this state.
Recovery contract
Events enter the outbox before delivery. A cumulative ACK may advance only to a source sequence the runner has produced; acknowledged prefixes are removed atomically from durable state. After disconnect, every remaining event is sent again with the same identity and source sequence.
After disconnect, runnerd tries Core when reconnect is due. Between attempts,
live Codex and ACPX processes can drain local output into the outbox. Work that
needs a provider request waits for Core, including managed-provider history
reads and unanswered tools or approvals. An ACPX sidecar can include a fresh
goalAtTerminal snapshot in runtime.turn_terminal to settle the turn offline.
A missing or stale snapshot waits for a connected goal read. Runnerd suspends
intake during terminal delivery or an authority transition.
If Codex hits its tool-receipt limit during reconnect, runnerd stops its local process group at the original deadline. It reads the remaining stdout in short intervals, then replays the frames in order across as many batches as needed. Only confirmed EOF with no terminal permits a missing-terminal result. If stdout stays open or the buffer lacks room for one maximum-size frame, runnerd reports uncertainty and keeps the events already committed to disk.
Executors retain polled events until runnerd acknowledges each event after its
outbox commit. Runnerd commits each polled batch of up to 128 events with one
save, and only then acknowledges the batch to the executor. If an event is
oversized or exceeds capacity, runnerd still saves and acknowledges the events
before it, and the executor keeps the rejected event and everything after it.
If the save fails, the executor keeps the whole batch. Each retained executor
event has a stable identity that runnerd derives into its PRP sourceEventId. If the process stops after the
outbox commit but before the executor acknowledgement, a bounded durable
receipt journal recognizes and byte-validates the retained copy without
appending a second event. Receipts outlive transport ACK removal; because the
provider queue is ordered and bounded, a possibly retained front event cannot
be evicted while later events advance the journal.
The ACPX executor saves its provider state once for all the sidecar outputs that one poll reads, not once for each output. The save comes before an event, a command result, or a reply to the sidecar that depends on those outputs leaves the executor. An output that ends a turn, calls a tool, or reports a lost provider turn is saved at once, as is a provider failure. If the process stops before the save, nothing derived from the unsaved outputs has left the executor, so recovery is the same as a stop before runnerd read them.
Commands require a contiguous controller sequence. The runner journals a pending command before invoking its executor and persists its result afterward. An exact duplicate returns the stored result without repeating the effect. If the process dies inside the effect window, recovery records an indeterminate result and refuses to execute that command again. Recent results are bounded; commands older than the compacted controller cursor fail closed.
A controller can die after it sends turn.start but before it checkpoints the
accepted turn. The provider keeps running that turn. On reattach, the host
driver adopts the single active turn only when the latest completed
turn.start result for this run accepted that exact turn id, and no run
attachment came after it. The driver then emits the missing turn.accepted
and waits for that turn instead of starting another. Any other active turn
still fails closed as an unexpected turn.
State written before complete-command fingerprints existed is migrated by compacting its legacy command journal through the last recorded controller sequence. The runner can recover, but it rejects redelivery of those older commands instead of guessing an identity or repeating an uncertain effect.
The outbox has separate hard and reserved limits. P1/P2 events cannot consume the P0 reserve. When the soft limit is reached, the runner enters backpressure and rejects the new non-P0 event rather than silently losing it. Exhausting the P0 reserve is an explicit unrecoverable condition.
While disconnected, soft-limit backpressure retains the rejected event and its suffix at the provider owner until replay ACKs free outbox space. Oversized events or exhausted hard limits stop the owned provider and preserve the accepted durable prefix. The ACPX sidecar separately caps queued stdout at 4 MiB; exceeding that bound requests owned provider shutdown and records a failure rather than allowing unbounded process memory while the Runner cannot read.
Event generations and stale events
Every runner event payload carries generation: the runner process generation
that emitted it. A runner process that recovers existing durable state starts
the next generation. The counter is saved with the next state write, so
recovery adds no write before the first turn. Events that are still in the
outbox keep the generation that emitted them. State saved before this field
existed loads as generation 0.
Consumers apply one rule to provider events. An event that names a turn which
is not the active turn, and which an earlier generation accepted or this
generation already settled, is history. The consumer records it and it never
fails the current turn. This covers late usage, items, workspace changes, and
terminals for a turn lost on restore. An event for a turn the consumer never
saw is not history and still fails closed. A terminal that contradicts a turn
the same generation settled is still a conflict. The ACPX provider state and
the Codex driver (which Runnerd also uses for OpenCode) apply this rule, and a
pending turn.start ignores a held failure that names another turn.
Recovering Codex between turns
Suppose run A finishes a turn, its Runner exits, and run B wants to continue
the conversation. Core uses ordinary recovery for A, then attaches B with
authenticated run.attach. If the original process is alive, its owner can
verify and adopt it instead.
Is A idle? Before launch, the host driver (codexSourceRecoveryVersion: 1)
checks that A’s process stopped and its saved session was idle. After launch,
the Runner (recoveryIntegrityVersion: 1) verifies that Codex restored an idle
session when no command effect is uncertain. It reads the goal, then the
thread. An unexpected turn or active goal blocks recovery, even if the goal
changes during the thread read. Accepted updates stay queued for delivery.
Active runs use same-run recovery. Indeterminate commands follow the replay rules above. A prepared session can continue normally, but this handoff requires a completed turn. Reads and cleanup leave a prepared provider unopened.
Who owns the session? Core matches A’s Runner instance, environment lease,
run, normalized session, turn and item. History reads require A’s thread. A
resume request returns saved state without asking Codex to resume twice. Retained events and usage
belong to A. The authenticated authorityRunId identifies the current owner
(A for same-run recovery). Losing that owner blocks new commands and dispatch.
Only a transport that starts under a later owner sends A's events to recovery
accounting, and only while its event identity is still A. After recovery moves
the transport to B, a later warm attachment treats B like any live owner. A
live warm run.attach also moves authorityRunId to B before
the Runner flushes A's outbox. Those events use ordinary accounting, which
drains A's usage under B.
If Core loses its cached preparation, the preparer uses A’s frozen
recoveryLaunch.requirements, exact identity and authenticated owner. It
leaves A’s configuration in place and the cache empty. B inherits A’s recorded
launch policy on later attachments. Explicit settings must agree after
provider defaults are applied. Authenticated context and instruction grants
keep their usual precedence and compatibility checks.
When can B start work? After authenticated attachment, Core persists B’s fresh snapshot and checkpoint and runs any recovery callback. B can then start work. If a write or callback fails, Core can retry the handoff. Cancellation cleanup only settles retained work.
What if the Runner starts as B? Core can rotate the session to B before
launch: it archives A's Runner state and starts a Runner under B's identity.
That Runner starts with fresh durable state over A's saved Codex session. It
does not restore Codex under A's settings. Until run.attach, it refuses
commands that start work; snapshots and shutdown commands still work. The
Runner saves the wait in the Codex state before it creates its durable state,
so a restart before attachment keeps it.
run.attach then starts Codex once with B's settings. ACPX follows the same
rule.
Live qualification still needs to verify that restoring a provider starts no work, deployed storage honors fsync, and the old process has exited.
Recovering ACPX between turns
paperclip-runnerd --build-metadata prints acpxRecoveryIntegrityVersion: 1
when the Runner implements these ACPX checks. The hosted ROM build copies
that field into its manifest. The host driver advertises a separate
acpxSourceRecoveryVersion: 1 and checks whether this run qualifies.
The Runner compares the restored session identity, pending requests, turn and goal with A’s saved idle state. After reading the goal, it checks updates that arrive during the final status read and keeps them queued for delivery. As with Codex, a prepared session can continue or be cleaned up. This handoff requires a completed turn. Suspended sessions use their usual recovery path.
Before B attaches, Runner saves the events it already received from A's sidecar. The readiness snapshot stays blocked until Core acknowledges those events. Another turn within A also keeps its buffered events without waiting for an ACK. ACPX still replaces the sidecar at the next turn or run attachment. The saved provider identity continues through that replacement.
Host park eligibility
CommandExecutor::host_park_ready defaults to false. Native Codex opts in only
for the existing process that completed the current turn. An eligibility check
never selects or restores a provider. A restored process must complete its own
authoritative turn before it can be eligible. Reconstructing an accepted finish
during recovery preserves result delivery but does not qualify that process.
Active turns, goals, startup attempts, tool calls, pending credentials, and
unsettled events block parking. Known helper threads also block it: their
diagnostic lineage does not prove that their work finished. The bounded
completed-turn tail drain retains late accounting and goal changes for durable
state and normal event delivery.
Claude and Codex through ACPX also need a successful turn in the live sidecar. Runner checks its qualified profile, session identity and source run A. It gives that sidecar 100 ms to report its goal and session state. If the sidecar is slow or declines, Runner stays attached. Runner keeps at most one unanswered read and recognizes its late reply. Events received during that read still belong to A and are delivered before B attaches. The existing policy still replaces the sidecar at park and run attachment; the saved provider identity continues.
Between turns of the same run, Runner keeps a Claude sidecar only when the turn
completed normally, its terminal reported backgroundTasks: {"live": 0}, and
every condition of the turn-end restart holds. Before the next turn it reads
session.snapshot again and requires the same report. A missing, live or
malformed report, a failed, cancelled or interrupted turn, any other agent, a
full settled-turn ledger or a full tool replay ledger replaces the sidecar as
before. A kept sidecar keeps its tool call-ID tombstones and settled turn
identities. The report's shape is $defs.backgroundTasks in
protocol/provider-schemas/acpx-sidecar.schema.json; both readers are
generated from it and tested against
protocol/fixtures/provider-boundary/acpx-background-tasks.json.
The Claude sidecar reports {"live": N} with N above zero only while N shell
tasks are running and nothing has made the count unknown; finished tasks do
not count. It reports {"live": 0} only while its provider process has never
had a background task and Claude has not acted between prompts. Every other
case is unknown and the field is omitted: once a background task has finished
or a provider-started cycle has run and no shell is running, and permanently
after a dropped, declined, failed or cancelled cycle, a task that is not a
shell, a malformed task update, a scheduling tool, a full ledger, or idle
activity that was not adopted. The ACP stream does not say which task a Claude
cycle reports on, so the sidecar does not guess: after a provider-started turn,
Runner keeps waiting only while a background command is still running, and a
command that finishes while Claude is already reporting on an earlier one gets
no turn of its own. An origin-tagged usage update that directly follows the
previous one with the same context size and cost and zero usage is an empty
result, not a cycle, and is ignored.
A controller opts in per turn with providerStartedTurns: true on
turn.start. Only then, when that completed Claude turn reported no accepted
paperclip_finish or paperclip_block result for the run, its terminal reports
backgroundTasks: {"live": N} with N above zero, and the same restart
conditions hold, Runner sends the sidecar session.provider_turn with
armed: true for that terminal. Only if the sidecar replies armed: true does
Runner keep it and await a provider-started turn: the PRP turn.completed
carries awaitingProviderTurn: true and no run.terminal follows. Without the
opt-in, with a result, or when arming is refused, every event and the turn-end
restart are exactly as before.
The sidecar adopts Claude's own cycle only while armed. A cycle that starts
after the terminal and before the arming command is held, with nothing lost,
for at most 5 s; arming adopts it and anything else drops it. When armed, the
sidecar emits runtime.turn_started with {"origin": "provider"} and a
sidecar-minted turn id. Runner admits it only while awaiting and only for
Claude, with the same settled-identity and receipt rules as a controller turn,
and publishes PRP turn.started with origin: "provider". Any other
provider-started turn fails the session closed. A controller turn.start while
awaiting disarms and replaces the sidecar first. If the provider exits while armed, the
sidecar reports runtime.diagnostic with code ACPX_PROVIDER_PROCESS_LOST; that,
or a failed sidecar transport, ends the wait and Runner publishes the
run.terminal it held back for the completed turn. Park is refused while awaiting.
Runner waits at most 5 s for the sidecar to answer an arm or a disarm. No answer
is handled as a lost sidecar, and Runner still publishes the held run.terminal.
When a run.attach from a different run succeeds, the wait ends and Runner
discards the held run.terminal. If that attach fails, the wait and its held
run.terminal stay with the old run. A run.attach from the same run publishes
the held run.terminal.
Runner saves the wait with its held run.terminal in the provider state; a
Runner restart during the wait publishes that run.terminal once and resumes
in a fresh process.
The check also inspects the live provider after that drain, so a late active-goal notification cannot be hidden by the older executor journal. This hook does not detach a controller, stop a process, or advertise hosted parking support. The host-control consumer must separately validate the exact Runner identity and acknowledged sequence cut.
Hosted park and reclaim loop
On Unix builds, paperclip-runnerd --build-metadata reports
privateHostControlVersion: 1 for the existing private fd 4 protocol below.
Other builds omit this field. A consumer must verify the selected executable's
identity and require the exact supported version before using this channel;
an absent or unknown version does not establish support. Recovery and warm-task
versions do not establish it either. Ordinary artifact admission can ignore this
optional field.
This field describes protocol support only. It does not mean a provider is ready
to park or that a host implements the public releaseResumeVersion contract.
Runner readiness checks and host sleep/wake qualification are still required.
A trusted Launcher may pass a connected Unix stream at fd 4 and start durable
listener mode with --host-control-fd 4. The descriptor is close-on-exec before
provider startup. The private channel accepts the park, claim, and retire
requests defined in the host-control codec; it cannot execute PRP commands.
park requires the exact six-field authority, acknowledged command/event cut,
no unfinished transition or cleanup, and the provider eligibility proof above.
The Runner drops its controller connection and credentials, retains its provider
and journals, and blocks on host control without provider polling. Ordinary
reconnect grace does not expire a parked Runner. The configured process lifetime
still applies. Mount ownership stays with Launcher.
claim names the accepted park request and supplies a fresh bootstrap ticket.
It resumes authenticated PRP under the retained authority; ordinary run.attach
must still establish the next authority before new work. Pending reconnect and
live commands both reject execution before that attachment; snapshots, drain,
and cleanup remain available. Replaying the same claim returns its acknowledgement without consuming another ticket. A parked
retirement names the park request. Cancelling a claim additionally requires its
claim ID, the unchanged authority and sequence cut, and provider quiescence.
Retirement, parked host-channel loss, or process-lifetime expiry uses the existing
suspended lifecycle and provider shutdown path. There is no new checkpoint state.
When a trusted host relaunches an absent Runner from a verified ACPX park, it can
pass --acpx-park-relaunch with the private host-control descriptor. For
park-eligible ACPX providers, Runner validates the settled checkpoint and keeps
the claim fence without starting the provider. The authenticated run.attach
opens the provider with the incoming run's bindings and checks live session
identity and dormancy before committing the attachment. An existing warm
transition receipt follows the ordinary replay path.
This native loop does not advertise hosted parking support: Launcher retention, Core orchestration, provider-specific qualification, and live VM sleep/wake verification are required before rollout. Providers without an eligibility implementation remain ineligible.
Optional controller release and resume
An explicit session release() returns a copy of A's confirmed six-field source
identity. It returns false when support is absent or work is still active.
Those refusals leave active work and its controller route in place. Release and
released-source adoption require a registration checkpoint hook that owns process
cleanup. Without it, release returns false and adoption fails before claim.
For an eligible release, the controller first makes its existing route quiet, then waits for the host acknowledgement before it closes that route. A failed request can have taken effect. Its retry keeps the same source identity; a resume retry also keeps the exact bootstrap ticket. The route stays quiet while the result is uncertain. Resume's pinned ticket deadline bounds claim reconciliation. A late reply cannot grant authentication or work permission.
A resumed result permits authentication under A. Ordinary run.attach must
still establish B before B can start work. An unavailable result reports known
absence of the retained Runner; it does not prove that descendants have stopped
or release their cleanup ownership. This optional contract adds no automatic
release policy or capability advertisement.