perf(runner): commit each provider batch with one durable save (#22829)

## 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>
This commit is contained in:
Nicky LeachandClaude Opus 5.5 authored and GitHub committed 2026-11-25 09:17:12 -08:00
1 parent 0175300a48
commit 9f570837cb
4 files changed
+146 -31

No files matched your search

@@ -72,10 +72,12 @@ 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. Batches commit one event at a time, so a later oversized event or
capacity failure cannot roll back the accepted prefix or discard the
unacknowledged suffix. Each retained executor event has a stable identity that
runnerd derives into its PRP `sourceEventId`. If the process stops after the
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
@@ -2365,40 +2365,50 @@ fn commit_executor_events<E: CommandExecutor>(
) -> Result<(), DurableRunnerError> {
let mut events = events.into_iter().peekable();
while events.peek().is_some() {
let mut durable_prefix = 0;
let committed = (|| -> Result<(), DurableRunnerError> {
// Keep each PRP event's durable save. Only coalesce provider queue
// acknowledgements, bounded below the retained receipt window so
// a crash before the prefix ACK can replay every event exactly.
for event in events.by_ref().take(128) {
if !state.has_executor_event_receipt(
&event.executor_event_id,
&event.event_type,
event.priority,
&event.payload,
)? {
state.enqueue_executor_event(
// Group commit: enqueue a bounded batch, then make all of it durable
// with one save before the provider may release any of it. The batch
// stays below the retained receipt window, so a crash between this
// save and the provider acknowledgement replays every event exactly.
let mut accepted = 0;
let mut enqueued = false;
let mut rejected = Ok(());
for event in events.by_ref().take(128) {
let committed = match state.has_executor_event_receipt(
&event.executor_event_id,
&event.event_type,
event.priority,
&event.payload,
) {
Ok(true) => Ok(()),
Ok(false) => state
.enqueue_executor_event(
config,
event.executor_event_id,
event.event_type,
event.priority,
event.payload,
)?;
store.save(state)?;
}
durable_prefix += 1;
)
.map(|_| enqueued = true),
Err(error) => Err(error),
};
if let Err(error) = committed {
rejected = Err(error);
break;
}
Ok(())
})();
// Even when a later save/validation fails, remove only the already
// durable prefix. A failed provider ACK leaves that prefix replayable;
// it must not hide the original commit/identity error, if any.
let acknowledged = if durable_prefix > 0 {
executor.acknowledge_events(durable_prefix)
} else {
Ok(())
accepted += 1;
}
// A rejected event still leaves the accepted prefix durable and
// releasable. A failed save releases nothing: the provider keeps the
// whole batch for replay.
let saved = if enqueued { store.save(state) } else { Ok(()) };
let acknowledged = match (&saved, accepted) {
(Ok(()), 1..) => executor.acknowledge_events(accepted),
_ => Ok(()),
};
committed?;
// A failed provider ACK leaves that prefix replayable; it must not
// hide the original commit/identity error, if any.
saved?;
rejected?;
acknowledged?;
}
Ok(())
@@ -2675,6 +2685,8 @@ mod tests {
use super::*;
include!("tests/batched_saves.rs");
struct CountingExecutor {
calls: usize,
}
@@ -2,6 +2,10 @@ use std::collections::{BTreeMap, HashSet};
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
#[cfg(test)]
use std::sync::atomic::{AtomicUsize, Ordering};
#[cfg(test)]
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
#[cfg(unix)]
@@ -1110,6 +1114,8 @@ fn canonical_json(value: &Value) -> String {
#[derive(Clone, Debug)]
pub struct DurableStateStore {
path: PathBuf,
#[cfg(test)]
saves: Arc<AtomicUsize>,
}
impl DurableStateStore {
@@ -1142,9 +1148,16 @@ impl DurableStateStore {
verify_private_directory(state_dir)?;
Ok(Self {
path: state_dir.join(STATE_FILE),
#[cfg(test)]
saves: Arc::default(),
})
}
#[cfg(test)]
pub(crate) fn save_count(&self) -> usize {
self.saves.load(Ordering::Acquire)
}
pub fn path(&self) -> &Path {
&self.path
}
@@ -1246,6 +1259,9 @@ impl DurableStateStore {
})();
if result.is_err() {
let _ = fs::remove_file(&temporary);
} else {
#[cfg(test)]
self.saves.fetch_add(1, Ordering::AcqRel);
}
result
}
@@ -0,0 +1,85 @@
// Saves per provider batch. Shares the helpers of
// `durable::runner::tests`.
#[test]
fn provider_batch_commits_with_one_durable_save() {
for size in [8_usize, 48] {
let directory = std::env::temp_dir().join(format!(
"paperclip-runner-group-commit-{size}-{}",
uuid::Uuid::new_v4()
));
let mut config = config(directory.clone());
config.max_outbox_bytes = 1024 * 1024;
let store = DurableStateStore::new(&directory).unwrap();
let (mut state, _) = store.load_or_create(&config).unwrap();
let mut executor = RetainingEventExecutor {
events: (1..=size)
.map(|index| PolledEvent {
executor_event_id: format!("provider-event-{index}"),
event_type: "item.delta".to_owned(),
priority: EventPriority::P2,
payload: json!({"index": index}),
})
.collect(),
fail_acknowledgement: false,
acknowledgements: Vec::new(),
};
let saves = store.save_count();
poll_executor_events(&mut state, &store, &config, &mut executor).unwrap();
assert_eq!(
store.save_count() - saves,
1,
"a batch of {size} events must commit with one save"
);
assert_eq!(executor.acknowledgements, vec![size]);
let (reloaded, _) = store.load_or_create(&config).unwrap();
assert_eq!(reloaded.outbox, state.outbox);
assert_eq!(reloaded.highest_source_seq(), size as u64);
fs::remove_dir_all(directory).unwrap();
}
}
#[test]
fn a_streamed_round_saves_its_batch_once_and_its_emptying_ack_once() {
// Each round polls one batch, then the controller ACKs every event in it.
for batch in [1_u64, 8] {
let directory = std::env::temp_dir().join(format!(
"paperclip-runner-streamed-rounds-{batch}-{}",
uuid::Uuid::new_v4()
));
let mut config = config(directory.clone());
config.max_outbox_bytes = 1024 * 1024;
let store = DurableStateStore::new(&directory).unwrap();
let (mut state, _) = store.load_or_create(&config).unwrap();
let mut executor = RetainingEventExecutor {
events: VecDeque::new(),
fail_acknowledgement: false,
acknowledgements: Vec::new(),
};
let mut persistence = CumulativeAckPersistence::default();
let saves = store.save_count();
let mut acked = 0;
for round in 0..10 {
for index in 0..batch {
executor.events.push_back(PolledEvent {
executor_event_id: format!("streamed-{round}-{index}"),
event_type: "item.delta".to_owned(),
priority: EventPriority::P2,
payload: json!({"round": round, "index": index}),
});
}
poll_executor_events(&mut state, &store, &config, &mut executor).unwrap();
for _ in 0..batch {
acked += 1;
persistence.apply(&mut state, &store, acked, 2).unwrap();
}
}
assert_eq!(store.save_count() - saves, 20, "batch of {batch}");
let (reloaded, _) = store.load_or_create(&config).unwrap();
assert_eq!(reloaded.acked_source_seq, 10 * batch);
assert!(reloaded.outbox.is_empty());
fs::remove_dir_all(directory).unwrap();
}
}