perf(runner): save ACPX provider state once per poll instead of once per output (#22840)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - ACPX chat turns (Claude, Codex, and the other ACP agents) run
through runnerd. runnerd reads the ACPX sidecar output in order and
keeps the run's provider state in a durable file
> - For each sidecar output that it read, runnerd rewrote the full
provider state file. Each save did a JSON rewrite, a file `fsync`, a
rename, and a directory `fsync`
> - runnerd reads the sidecar again only after the controller
acknowledges the events that it sent. Streamed text collects in the
sidecar pipe during that round trip, so one poll usually reads several
outputs
> - #20217 made the Codex provider save once per poll. ACPX still saved
once per output
> - This pull request makes the ACPX executor save the outputs of one
poll once, before anything that depends on them leaves the executor
> - The benefit is fewer full state rewrites and `fsync` pairs during a
streamed turn, on any disk. In a replay of a real Claude stream, runnerd
made 49% fewer ACPX state saves

## Linked Issues or Issue Description

Refs #20217 (the same change for the Codex provider)
Related: #22829 (the same change for runnerd's own state file)
Related: #16817 (a broader change. It also merges text deltas into fewer
events, changes the sidecar contract, and records expired tool results.
This pull request changes only when the ACPX executor saves, and does
not change the event stream or the contract.)

**What existing behavior does this improve?**

The number of durable ACPX provider state saves during a streamed turn.

**Subsystem affected**

Runner (`paperclip-runner-core`, ACPX provider backend).

**Current behavior**

`poll_provider_events` calls `save_state` after each sidecar output that
returns events. One ACP update, for example one streamed text chunk,
becomes one sidecar output. Each save rewrites the full
`acpx-provider-state.json` file and does two `fsync` calls.

**Proposed behavior**

The executor keeps the effects of ordinary outputs in memory and saves
them once at the end of the poll. Outputs that drive an effect outside
the stream save at once, as before.

**Reason and benefit**

The save count during a streamed turn no longer grows with the number of
chunks in a poll. This removes disk writes and `fsync` calls on every
platform.

**Breaking changes**

None. The state file format does not change.

## What Changed

- The ACPX executor marks state as unsaved after an ordinary sidecar
output. It saves once when the poll ends, also when the poll stops with
an error. A poll returns events only after that save, so no event,
command result, or reply to the sidecar leaves before the state that it
depends on is on disk.
- Each unsaved output still applies the state transition that a save
applies (`leave_finished_provider_turn_wait`). The order of the events
does not change.
- These outputs still save at once: a turn terminal, a tool call, a lost
provider turn, and a provider transport failure. The goal read at a
terminal keeps its own save.
- The session holds a tool rejection that it sends to the sidecar inside
`poll_output` (the "too many tool calls in flight" case). The executor
saves the outputs read before the rejection, then sends it.
- The event acknowledgement (`acknowledge_events`) still saves at once.
Recovery reads an empty queue on disk as fully delivered, so that save
must not wait.
- The transport-failure handling moves into one helper,
`fail_polled_provider`. The poll loop and the held-rejection path both
use it.
- `runner/DURABLE_TRANSPORT.md` now describes when the ACPX executor
saves.

## Verification

Measurement (macOS, APFS, debug runnerd). I recorded the arrival times
of one real Claude ACP turn from `claude-agent-acp` (323 updates in 15.4
s, median gap 33 ms). A temporary build of the fake sidecar replayed
that timing in `runnerd-acpx-source-reconciliation.test.ts` ("claude"
case, two turns). That test runs a real runnerd against the in-process
controller. Temporary counters in the backend recorded the outputs per
poll and each state save. These counters are not in this pull request.

| | Polls with output | Outputs per poll (mean) | ACPX state saves |
Time in saves |
| --- | --- | --- | --- | --- |
| Before | 84 | 7.7 | 749 | 8.1 s |
| After | 182 | 3.6 | 379 | 4.3 s |

- One save took about 10 ms (median) in both runs.
- Before the change, 642 of 650 outputs came in polls with more than one
output.
- After the change, the remaining saves are about one per poll plus one
per acknowledgement. Polls come more often because each cycle spends
less time in saves.

Tests:

- New lib tests in `src/tests/acpx_poll_state_saves.rs`:
- 48 outputs in one poll need one state write. The file on disk then
equals the state in memory.
- Polled outputs survive a restart once: a new executor retains exactly
the unacknowledged suffix, with no duplicate event ids.
  - An output that ends the turn, or calls a tool, is saved at once.
- The sidecar receives a held tool rejection only after the outputs read
before it are on disk.
- With the old per-output save restored, the tests fail with 48, 26, and
21 writes. Without the hold, the rejection test fails.
- `cargo test -p paperclip-runner-core --lib acpx` (122 passed) and
`--lib durable` (162 passed).
- `cargo test -p paperclip-runner-core --test acpx_park_preparation
--test acpx_park_readiness --test acpx_warm_attachment --test
durable_recovery` (47, 8, 7, 4 passed).
- `cargo test -p paperclip-runner-core --test acpx_provider_session
--test acpx_provider_turns --test acpx_quiet_turn_continuation --test
acpx_provider_resolutions` (13, 31, 14, 12 passed).
- With a freshly built runnerd: `vitest run
src/live/runnerd-acpx-source-reconciliation.test.ts` (17 passed).
- `cargo fmt --check` is clean. `cargo clippy` shows no new warnings in
the changed files.
- I did not run `pnpm verify` or the full Rust suite locally. CI
supplies that coverage.

## Risks

- Crash window: if runnerd stops before the end-of-poll save, it loses
the unsaved outputs of that poll. Nothing derived from them has left the
executor, so recovery is the same as a stop before runnerd read them.
Turn terminals, tool calls, lost provider turns, and failures keep their
immediate save.
- The executor adds no save to `retained_events`, `execute`,
`host_park_ready`, or `prepare_for_park`. Unsaved state does not outlive
one poll call. If the end-of-poll save fails, the existing persistence
latch blocks all later work.
- A held tool rejection reaches the sidecar after one more state save.
Its order relative to other sidecar requests does not change.
- Low risk overall. The state file format and the acknowledgement path
do not change.

> 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, through Claude Code
with tool use (shell, file edits, local builds and tests).

## 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:16:32 -08:00
1 parent a0d5f275af
commit 0175300a48
4 files changed
+551 -35

No files matched your search

@@ -82,6 +82,14 @@ 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
@@ -1049,8 +1049,13 @@ pub struct AcpxCommandExecutor {
restore_checked: bool,
restore_error: Option<DurableRunnerError>,
persistence_error: Option<DurableRunnerError>,
/// Provider outputs read in the current poll changed the in-memory state
/// after its last save. The poll saves them once before it returns.
polled_state_unsaved: bool,
#[cfg(test)]
fail_after_state_rename: bool,
#[cfg(test)]
state_writes: std::cell::Cell<usize>,
launch_profile: Option<AcpxLaunchProfile>,
recovery_pending_effects: Option<usize>,
parked_relaunch: bool,
@@ -1104,8 +1109,11 @@ impl AcpxCommandExecutor {
turn_accepts_provider_turns: false,
restore_error: None,
persistence_error: None,
polled_state_unsaved: false,
#[cfg(test)]
fail_after_state_rename: false,
#[cfg(test)]
state_writes: std::cell::Cell::new(0),
launch_profile: config.acpx_launch_profile.clone(),
}
}
@@ -1693,7 +1701,28 @@ impl AcpxCommandExecutor {
.as_ref()
.ok_or_else(|| DurableRunnerError::invalid("ACPX provider state is unavailable"))
.and_then(|state| self.write_state(state));
self.record_state_write(result)
self.record_state_write(result)?;
self.polled_state_unsaved = false;
Ok(())
}
/// Keeps the effects of one provider output in memory until the poll
/// saves. It applies the same state transition as `save_state`, so the
/// event order does not depend on when the save occurs.
fn stage_polled_state(&mut self) -> Result<(), DurableRunnerError> {
self.ensure_persistence_healthy()?;
if let Some(state) = self.state.as_mut() {
state.leave_finished_provider_turn_wait()?;
}
self.polled_state_unsaved = true;
Ok(())
}
fn save_polled_state(&mut self) -> Result<(), DurableRunnerError> {
if self.polled_state_unsaved {
self.save_state()?;
}
Ok(())
}
fn commit_staged_state(&mut self, state: AcpxDurableState) -> Result<(), DurableRunnerError> {
@@ -1741,6 +1770,8 @@ impl AcpxCommandExecutor {
fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).map_err(|error| {
DurableRunnerError::invalid(format!("failed to protect ACPX provider state: {error}"))
})?;
#[cfg(test)]
self.state_writes.set(self.state_writes.get() + 1);
Ok(())
}
@@ -2969,10 +3000,78 @@ impl AcpxCommandExecutor {
}
}
/// Reads up to `count` provider outputs and saves their state once, before
/// any event derived from them can leave this 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. A tool rejection that the session sends
/// to the provider waits until the outputs read before it are saved.
fn poll_provider_events(
&mut self,
count: usize,
disconnected: bool,
) -> Result<(), DurableRunnerError> {
if let Some(session) = self.session.as_mut() {
session.hold_tool_rejections();
}
let polled = self.poll_provider_outputs(count, disconnected);
let saved = self.save_polled_state();
let released = if saved.is_ok() {
self.release_tool_rejections(false).map(|_| ())
} else {
Ok(())
};
polled?;
saved?;
released
}
/// Sends held provider tool rejections. Returns `true` when the provider
/// failed and the poll must stop.
fn release_tool_rejections(&mut self, keep_holding: bool) -> Result<bool, DurableRunnerError> {
let Some(session) = self.session.as_mut() else {
return Ok(false);
};
match session.release_tool_rejections(keep_holding) {
Ok(()) => Ok(false),
Err(error) => {
self.fail_polled_provider(&error)?;
Ok(true)
}
}
}
fn fail_polled_provider(
&mut self,
error: &crate::local_runner::LocalRunnerError,
) -> Result<(), DurableRunnerError> {
let state = self
.state
.as_mut()
.expect("ACPX failed provider has durable state");
state.expire_runtime_requests("provider_process_lost", false)?;
let failed_turn = state.active_turn_id.take();
state.lifecycle = "closed".to_owned();
state.provider_exit_unconfirmed = true;
if let Some(turn_id) = failed_turn {
let message = crate::durable::redact_text(&error.to_string());
state.push(NormalizedProviderEvent { event_type: "turn.failed".to_owned(), priority: EventPriority::P0,
payload: json!({"provider":"acpx","providerTurnId":turn_id,"status":"failed","providerTerminalObserved":false,
"code":"acpx_provider_transport_failed","message":message,
"error":{"code":"acpx_provider_transport_failed","message":message,"recoverable":false}}) })?;
state.push(NormalizedProviderEvent { event_type: "run.terminal".to_owned(), priority: EventPriority::P0,
payload: json!({"schema":"paperclip.prp.terminal.v1","status":"failed","turnTerminalState":"failed","runTerminalState":"failed","reportedWorkDisposition":"needs_review","provider":"acpx"}) })?;
}
self.context.provider_turn_id = None;
// A failed transport cannot attest escaped provider cleanup.
// Drop the closed process owner; later cleanup must prove the lifetime fence.
self.session = None;
self.save_state()
}
fn poll_provider_outputs(
&mut self,
count: usize,
disconnected: bool,
) -> Result<(), DurableRunnerError> {
for _ in 0..count {
let events = self
@@ -2992,28 +3091,7 @@ impl AcpxCommandExecutor {
let events = match events {
Ok(events) => events,
Err(error) => {
let state = self
.state
.as_mut()
.expect("ACPX failed provider has durable state");
state.expire_runtime_requests("provider_process_lost", false)?;
let failed_turn = state.active_turn_id.take();
state.lifecycle = "closed".to_owned();
state.provider_exit_unconfirmed = true;
if let Some(turn_id) = failed_turn {
let message = crate::durable::redact_text(&error.to_string());
state.push(NormalizedProviderEvent { event_type: "turn.failed".to_owned(), priority: EventPriority::P0,
payload: json!({"provider":"acpx","providerTurnId":turn_id,"status":"failed","providerTerminalObserved":false,
"code":"acpx_provider_transport_failed","message":message,
"error":{"code":"acpx_provider_transport_failed","message":message,"recoverable":false}}) })?;
state.push(NormalizedProviderEvent { event_type: "run.terminal".to_owned(), priority: EventPriority::P0,
payload: json!({"schema":"paperclip.prp.terminal.v1","status":"failed","turnTerminalState":"failed","runTerminalState":"failed","reportedWorkDisposition":"needs_review","provider":"acpx"}) })?;
}
self.context.provider_turn_id = None;
// A failed transport cannot attest escaped provider cleanup.
// Drop the closed process owner; later cleanup must prove the lifetime fence.
self.session = None;
self.save_state()?;
self.fail_polled_provider(&error)?;
return Ok(());
}
};
@@ -3021,7 +3099,12 @@ impl AcpxCommandExecutor {
break;
};
let mut provider_turn_settled = false;
let mut gates_effect = false;
for event in events {
gates_effect |= matches!(
&event,
crate::acpx_provider_state::AcpxProviderStateEvent::ToolCall { .. }
);
if let crate::acpx_provider_state::AcpxProviderStateEvent::ProviderTurnStarted {
turn_id,
} = &event
@@ -3110,6 +3193,7 @@ impl AcpxCommandExecutor {
accepted.push(event);
}
let turn_ended = terminal.is_some();
gates_effect |= turn_ended || provider_lost;
let mut run_terminal = None;
if let Some(event_type) = terminal {
state.active_turn_id = None;
@@ -3171,7 +3255,18 @@ impl AcpxCommandExecutor {
if provider_turn_settled {
self.context.provider_turn_id = None;
}
self.save_state()?;
let session_holds_rejections = self
.session
.as_ref()
.is_some_and(AcpxProviderSession::has_held_tool_rejections);
if gates_effect || session_holds_rejections {
self.save_state()?;
if self.release_tool_rejections(true)? {
return Ok(());
}
} else {
self.stage_polled_state()?;
}
}
Ok(())
}
@@ -3591,12 +3686,16 @@ pub(crate) fn secure_directory(path: &Path, label: &str) -> Result<(), DurableRu
#[path = "tests/acpx_park_relaunch.rs"]
pub(crate) mod park_relaunch_tests;
#[cfg(all(test, unix))]
#[path = "tests/acpx_poll_state_saves.rs"]
mod poll_state_save_tests;
#[cfg(test)]
mod tests {
use super::*;
use std::time::{SystemTime, UNIX_EPOCH};
fn temporary_directory(label: &str) -> PathBuf {
pub(super) fn temporary_directory(label: &str) -> PathBuf {
let nonce = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
@@ -3628,7 +3727,7 @@ mod tests {
}
}
fn test_config(
pub(super) fn test_config(
state_dir: &Path,
launch_profile: Option<AcpxLaunchProfile>,
) -> DurableRunnerConfig {
@@ -372,6 +372,9 @@ pub struct AcpxProviderSession {
generation_has_run_turn: bool,
restarted_after_turn_from: Option<u32>,
prepared_generation: Option<String>,
/// Provider tool rejections held while the backend holds the outputs read
/// before them in memory: `(call_id, turn_id, message)`.
held_tool_rejections: Option<Vec<(String, String, String)>>,
}
pub(crate) fn goal_is_dormant(projection: &Value) -> bool {
@@ -438,6 +441,7 @@ impl AcpxProviderSession {
run_result_reported: None,
generation_has_run_turn: false,
restarted_after_turn_from: None,
held_tool_rejections: None,
prepared_generation: None,
})
}
@@ -1142,15 +1146,11 @@ impl AcpxProviderSession {
.flatten()
{
for (call_id, message) in retryable_rejections {
let response = self
.transport
.request_tool_resolve(json!({
"callId": call_id,
"turnId": turn_id,
"error": {"message": message},
}))
.map_err(|(error, _)| self.fail_closed(error))?;
self.verify_resolution(&response, "tool")?;
if let Some(held) = self.held_tool_rejections.as_mut() {
held.push((call_id, turn_id.clone(), message));
} else {
self.reject_tool_call(&call_id, &turn_id, &message)?;
}
}
}
if let Some(turn_id) = terminal_turn {
@@ -1159,6 +1159,56 @@ impl AcpxProviderSession {
Ok(Some((reconciled_events, terminal_goal)))
}
fn reject_tool_call(
&mut self,
call_id: &str,
turn_id: &str,
message: &str,
) -> Result<(), LocalRunnerError> {
let response = self
.transport
.request_tool_resolve(json!({
"callId": call_id,
"turnId": turn_id,
"error": {"message": message},
}))
.map_err(|(error, _)| self.fail_closed(error))?;
self.verify_resolution(&response, "tool")
}
/// Holds provider tool rejections from `poll_output` until
/// `release_tool_rejections`. The backend can then save the outputs that
/// it read before a rejection, before the provider sees that rejection.
pub(crate) fn hold_tool_rejections(&mut self) {
self.held_tool_rejections.get_or_insert_with(Vec::new);
}
pub(crate) fn has_held_tool_rejections(&self) -> bool {
self.held_tool_rejections
.as_ref()
.is_some_and(|held| !held.is_empty())
}
/// Sends the held tool rejections in their polled order. With
/// `keep_holding`, later rejections are held again.
pub(crate) fn release_tool_rejections(
&mut self,
keep_holding: bool,
) -> Result<(), LocalRunnerError> {
let held = if keep_holding {
self.held_tool_rejections
.as_mut()
.map(std::mem::take)
.unwrap_or_default()
} else {
self.held_tool_rejections.take().unwrap_or_default()
};
for (call_id, turn_id, message) in held {
self.reject_tool_call(&call_id, &turn_id, &message)?;
}
Ok(())
}
pub fn deliver_tool_result(&mut self, result: &ToolResult) -> Result<(), LocalRunnerError> {
self.ensure_open()?;
let mut next_state = self.state.clone();
@@ -2047,6 +2097,55 @@ fn with_cleanup_error(
}
}
#[cfg(all(test, unix))]
impl AcpxProviderSession {
/// A session with `turn_id` active whose sidecar is the shell script at
/// `script`.
pub(crate) fn scripted_turn_for_test(
mut config: AcpxProviderSessionConfig,
identity: AcpxProviderSessionIdentity,
script: &Path,
turn_id: &str,
) -> Self {
config.transport.command = PathBuf::from("/bin/sh");
config.transport.args = vec![script.to_string_lossy().into_owned()];
config.transport.verified_launch = None;
let transport =
AcpxSidecarTransport::start_for_agent(&config.transport, &config.agent).unwrap();
let mut state = AcpxProviderState::new(&config.run_id).unwrap();
state.begin_turn(turn_id).unwrap();
let mut tool_bridge = ProviderToolBridge::default();
tool_bridge.prepare(config.tool_set.clone()).unwrap();
AcpxProviderSession {
transport,
state,
identity,
tool_bridge,
reserved_tool_bridge: reserved_terminal_tool_bridge().unwrap(),
turn_controls: AcpxTurnControlCapabilities::default(),
catalog_revision: config.catalog_revision,
working_directory: config.working_directory.clone(),
config,
closed: false,
failure: None,
transport_terminated: false,
rejected_start_resumable: false,
runtime_retired: false,
cancelled_turn_id: None,
completed_turn_observed: false,
quiet_turn_observed: false,
continues_in_process: false,
turn_start_replaced_provider: false,
provider_turn_offer: None,
run_result_reported: None,
generation_has_run_turn: false,
restarted_after_turn_from: None,
prepared_generation: None,
held_tool_rejections: None,
}
}
}
#[cfg(test)]
mod tests {
#[test]
@@ -2398,6 +2497,7 @@ mod mode_tests {
run_result_reported: None,
generation_has_run_turn: false,
restarted_after_turn_from: None,
held_tool_rejections: None,
prepared_generation: None,
}
}
@@ -0,0 +1,309 @@
use super::tests::{artifact, descriptor, temporary_directory, test_config, write_artifact};
use super::*;
use crate::generated_acpx_sidecar_contract::GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION;
use crate::provider_bridge::AuthorizedTool;
const TOOL: &str = "issues.read";
fn tool_set() -> AuthorizedToolSet {
let operations = vec![AuthorizedTool {
operation_id: TOOL.to_owned(),
version: 1,
description: "Read an issue.".to_owned(),
input_schema: json!({"type": "object"}),
response_schema: json!({"type": "object"}),
}];
AuthorizedToolSet {
schema: TOOL_SET_SCHEMA.to_owned(),
schema_version: 1,
catalog_digest: authorized_tool_catalog_digest(&operations).unwrap(),
operations,
}
}
fn frame(sequence: u64, event_type: &str, payload: Value) -> Value {
json!({
"protocolVersion": GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION,
"sequence": sequence,
"eventType": event_type,
"runId": "run-1",
"turnId": "turn-1",
"payload": payload,
})
}
fn text(sequence: u64) -> Value {
frame(
sequence,
"runtime.event",
json!({"type": "text_delta", "text": "x"}),
)
}
struct StreamedTurn {
directory: PathBuf,
config: DurableRunnerConfig,
executor: AcpxCommandExecutor,
}
impl Drop for StreamedTurn {
fn drop(&mut self) {
// Dropping the session stops the sidecar without a close request.
drop(self.executor.session.take());
let _ = fs::remove_dir_all(&self.directory);
}
}
/// An active turn whose sidecar has written every frame before the first
/// poll. The sidecar answers the requests that follow with `replies`.
fn streamed_turn(frames: &[Value], replies: &[Value]) -> StreamedTurn {
let directory = temporary_directory("poll-state-saves");
let command = directory.join("sidecar");
write_artifact(&command, b"#!/bin/sh\nexit 1\n", true);
let launch_profile = AcpxLaunchProfile {
candidate_admission: None,
authority_digest: format!("sha256:{}", "d".repeat(64)),
command: command.clone(),
args: Vec::new(),
artifacts: vec![artifact(&command)],
};
let runtime = directory.join("runtime");
let workspace = directory.join("workspace");
for private in [&runtime, &workspace] {
fs::create_dir_all(private).unwrap();
fs::set_permissions(private, fs::Permissions::from_mode(0o700)).unwrap();
}
let mut value = descriptor("codex");
value["runtimeDirectory"] = json!(runtime);
value["cwd"] = json!(workspace);
value["sidecarCommand"] = json!(command);
value["sidecarArgs"] = json!([]);
let descriptor: AcpxProviderDescriptor = serde_json::from_value(value).unwrap();
let identity = AcpxProviderSessionIdentity {
kind: "acpx".into(),
normalized_session_id: "session-1".into(),
acpx_record_id: "record-1".into(),
backend_session_id: "backend-1".into(),
agent_session_id: "agent-1".into(),
profile_digest: descriptor.command_digest.clone(),
workspace_digest: format!("sha256:{}", "a".repeat(64)),
requested_model: descriptor.model.clone(),
effective_model: descriptor.model.clone(),
permission_mode: Some(descriptor.permission_mode),
mode: descriptor.mode.clone(),
pi_thinking_level: descriptor.pi_thinking_level,
claude_effort: descriptor.claude_effort.clone(),
grok_effort: descriptor.grok_effort.clone(),
grok_disable_web_search: descriptor.grok_disable_web_search,
provider_lifetime_fence_candidates: [60_001, 60_002, 60_003],
};
let session_config = descriptor
.session_config(tool_set(), Some(identity.clone()), Some(&launch_profile))
.unwrap();
let mut state = AcpxDurableState::new(
descriptor,
tool_set(),
launch_profile.canonical_digest().unwrap(),
);
state.identity = Some(identity.clone());
state.lifecycle = "turn_active".into();
state.active_turn_id = Some("turn-1".into());
let config = test_config(&directory, Some(launch_profile));
let mut executor = AcpxCommandExecutor::with_runner_config(&directory, &config);
executor.restore_checked = true;
executor.context.provider_turn_id = Some("turn-1".into());
executor.state = Some(state);
executor.save_state().unwrap();
let streamed = directory.join("streamed");
let print = |value: &Value| {
format!(
"printf '%s\\n' '{}'\n",
value.to_string().replace('\'', "'\"'\"'")
)
};
let mut script: String = frames.iter().map(print).collect();
script.push_str(&format!("touch '{}'\n", streamed.display()));
for (index, reply) in replies.iter().enumerate() {
// Record the saved state that the provider could rely on when it
// received this request.
script.push_str(&format!(
"IFS= read -r request_line\ncp '{}' '{}'\n",
executor.state_path().display(),
directory
.join(format!("state-at-request-{}", index + 1))
.display(),
));
script.push_str(&print(reply));
}
script.push_str("while IFS= read -r request_line; do :; done\n");
let script_path = directory.join("streamed-sidecar.sh");
write_artifact(&script_path, script.as_bytes(), false);
executor.session = Some(AcpxProviderSession::scripted_turn_for_test(
session_config,
identity,
&script_path,
"turn-1",
));
let deadline = Instant::now() + Duration::from_secs(10);
while !streamed.exists() {
assert!(
Instant::now() < deadline,
"sidecar did not stream its frames"
);
std::thread::sleep(Duration::from_millis(5));
}
StreamedTurn {
directory,
config,
executor,
}
}
fn saved_state(executor: &AcpxCommandExecutor) -> AcpxDurableState {
serde_json::from_slice(&fs::read(executor.state_path()).unwrap()).unwrap()
}
/// Polls once and returns the retained events and the number of state writes.
fn poll_once(executor: &mut AcpxCommandExecutor) -> (Vec<PolledEvent>, usize) {
let before = executor.state_writes.get();
let events = executor.poll_events().unwrap();
(events, executor.state_writes.get() - before)
}
#[test]
fn outputs_read_in_one_poll_share_one_state_write() {
let frames: Vec<_> = (1..=48).map(text).collect();
let mut turn = streamed_turn(&frames, &[]);
let (events, writes) = poll_once(&mut turn.executor);
assert_eq!(writes, 1, "48 outputs in one poll need one state write");
assert!(events.len() >= 48, "every streamed output is retained");
// Nothing leaves the executor before the poll's state is on disk.
assert_eq!(
&saved_state(&turn.executor),
turn.executor.state.as_ref().unwrap()
);
let (more, writes) = poll_once(&mut turn.executor);
assert_eq!(writes, 0, "a poll that reads no output writes nothing");
assert_eq!(more, events);
}
#[test]
fn polled_outputs_survive_a_restart_once() {
let frames: Vec<_> = (1..=48).map(text).collect();
let mut turn = streamed_turn(&frames, &[]);
let (events, _) = poll_once(&mut turn.executor);
let acknowledged = events.len() / 2;
turn.executor.acknowledge_events(acknowledged).unwrap();
let saved = saved_state(&turn.executor);
let mut recovered = AcpxCommandExecutor::with_runner_config(&turn.directory, &turn.config);
recovered.restore_checked = true;
recovered.state = Some(saved);
let retained = recovered.retained_events().unwrap();
assert_eq!(retained, events[acknowledged..]);
let mut ids = HashSet::new();
assert!(retained
.iter()
.all(|event| ids.insert(event.executor_event_id.clone())));
assert!(events[..acknowledged]
.iter()
.all(|event| !ids.contains(&event.executor_event_id)));
}
#[test]
fn an_output_that_ends_the_turn_is_saved_at_once() {
let mut frames: Vec<_> = (1..=24).map(text).collect();
frames.push(frame(
25,
"runtime.turn_terminal",
json!({"status": "completed"}),
));
let goal = json!({
"protocolVersion": GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION,
"id": 1,
"ok": true,
"result": {
"schema": "paperclip.session_goal.snapshot.v1",
"providerRevision": 1,
"goal": null,
"workingNow": false,
},
});
let mut turn = streamed_turn(&frames, &[goal]);
let (events, writes) = poll_once(&mut turn.executor);
// The goal read at the terminal and the terminal itself each save, as
// before. The 24 streamed outputs ahead of them add no write.
assert_eq!(writes, 2);
assert_eq!(events.last().unwrap().event_type, "run.terminal");
assert_eq!(
&saved_state(&turn.executor),
turn.executor.state.as_ref().unwrap()
);
}
#[test]
fn an_output_that_calls_a_tool_is_saved_at_once() {
let mut frames: Vec<_> = (1..=10).map(text).collect();
frames.push(frame(
11,
"runtime.tool_called",
json!({"callId": "call-1", "operationId": TOOL, "input": {}}),
));
frames.extend((12..=21).map(text));
let mut turn = streamed_turn(&frames, &[]);
let (events, writes) = poll_once(&mut turn.executor);
// One write for the tool call, which carries the outputs before it, and
// one at the end of the poll for the outputs after it.
assert_eq!(writes, 2);
assert!(events
.iter()
.any(|event| event.payload.to_string().contains("call-1")));
assert_eq!(
&saved_state(&turn.executor),
turn.executor.state.as_ref().unwrap()
);
}
fn tool_call(sequence: u64, index: usize) -> Value {
frame(
sequence,
"runtime.tool_called",
json!({"callId": format!("call-{index}"), "operationId": TOOL, "input": {"id": format!("issue-{index}")}}),
)
}
#[test]
fn a_tool_rejection_reaches_the_provider_after_the_outputs_before_it_are_saved() {
// The result reserve admits ten calls in flight. The provider rejects the
// eleventh in the session; the ordinary output between them is in memory.
let mut frames: Vec<_> = (0..10)
.map(|index| tool_call(index as u64 + 1, index))
.collect();
frames.extend((11..=15).map(text));
frames.push(tool_call(16, 10));
frames.extend((17..=19).map(text));
let resolved = json!({
"protocolVersion": GENERATED_ACPX_SIDECAR_PROTOCOL_VERSION,
"id": 1,
"ok": true,
"result": {"resolved": true},
});
let mut turn = streamed_turn(&frames, &[resolved]);
let (_, writes) = poll_once(&mut turn.executor);
// Ten admitted calls, the rejected call, and the end of the poll.
assert_eq!(writes, 12);
let at_rejection: AcpxDurableState =
serde_json::from_slice(&fs::read(turn.directory.join("state-at-request-1")).unwrap())
.unwrap();
let saved = saved_state(&turn.executor);
// The provider saw the rejection only after every output read before it
// was on disk. The three outputs after it were not read yet.
let trailing = saved.next_event_sequence - at_rejection.next_event_sequence;
assert_eq!(trailing, 3);
assert!(saved
.pending_events
.iter()
.take(at_rejection.pending_events.len())
.eq(at_rejection.pending_events.iter()));
}