Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,112 @@ mod tests {
assert_ne!(reqs[1].json()["requestId"], reqs[2].json()["requestId"], "b is its own request");
}

/// A burst that spans turns is paid per REQUEST, not per attempt: turn A is
/// refused twice and lands on its third try under ONE id, then turn B lands on
/// its first try under a new one. The transcript holds `a` once — the repeats
/// are the same request — and then `b`.
///
/// MUTATION: mint a `requestId` per try, and A is stored three times.
#[tokio::test]
async fn a_burst_over_two_turns_names_each_turn_once() {
let mock = MockCloud::start_refusing(&[true, true, false]).await;
let client = SessionClient::new(&mock.base_url(), "T").unwrap();

client.event("sess_1", Kind::Log, json!({"line":"a"})).await.expect("a lands on its third try");
client.event("sess_1", Kind::Log, json!({"line":"b"})).await.expect("b lands on its first");

let reqs = mock.requests();
let lines: Vec<String> = reqs.iter().map(|r| r.json()["payload"]["line"].as_str().unwrap_or_default().to_string()).collect();
assert_eq!(lines, ["a", "a", "a", "b"], "a is tried until it lands, then b");
let named = |i: usize| reqs[i].json()["requestId"].as_str().unwrap_or_default().to_string();
assert_eq!(named(0), named(1), "a's second try is a");
assert_eq!(named(1), named(2), "a's third try is a");
assert_ne!(named(2), named(3), "b is its own request");
}

/// A burst that falls between turns still lands every turn exactly once: each
/// turn's repeats share their own id, and no two turns share one.
///
/// MUTATION: reuse the id across turns, and the platform collapses them into
/// one turn; drop it, and the refused tries are lost.
#[tokio::test]
async fn interleaved_refusals_land_each_turn_once() {
let mock = MockCloud::start_refusing(&[true, false, true, true, false, true]).await;
let client = SessionClient::new(&mock.base_url(), "T").unwrap();
for line in ["a", "b", "c"] {
client.event("sess_1", Kind::Log, json!({ "line": line })).await.unwrap();
}

let reqs = mock.requests();
let lines: Vec<String> = reqs.iter().map(|r| r.json()["payload"]["line"].as_str().unwrap_or_default().to_string()).collect();
assert_eq!(lines, ["a", "a", "b", "b", "b", "c", "c"], "each turn is tried until it lands");
let mut ids: Vec<String> = Vec::new();
for (i, line) in lines.iter().enumerate() {
let idx = ["a", "b", "c"].iter().position(|l| l == line).unwrap();
let id = reqs[i].json()["requestId"].as_str().unwrap_or_default().to_string();
if idx == ids.len() {
assert!(!id.is_empty(), "turn {line} was sent unnamed");
assert!(!ids.contains(&id), "turn {line} shares an id with an earlier turn");
ids.push(id);
} else {
assert_eq!(id, ids[idx], "turn {line}'s repeat is a different request");
}
}
assert_eq!(ids.len(), 3);
}

/// A cloud that comes back is named again, and nothing it was sent twice went
/// under two names. Turn A is refused once then served; the next two turns are
/// lost (every try refused, then one unnamed try); the turn that follows lands
/// unnamed — the one-try policy — and the turn after that is named again.
///
/// MUTATION: clear `lost` before the landing turn can prove it, and D is named
/// (a fresh retry budget on a cloud just proven down); never clear it, and E
/// stays unnamed after a turn has landed.
#[tokio::test]
async fn a_cloud_that_comes_back_names_turns_again_without_two_names_for_one() {
// A: refuse, serve. B: refuse all 4 tries. C: refuse the unnamed try.
// D: serve the unnamed try. E: serve, named.
let mock = MockCloud::start_refusing(&[true, false, true, true, true, true, true, false, false]).await;
let client = SessionClient::new(&mock.base_url(), "T").unwrap();
let turn = |line: &'static str| client.event("sess_1", Kind::Log, json!({ "line": line }));

turn("a").await.expect("a's repeat lands");
assert!(turn("b").await.is_err(), "b is refused every try");
assert!(turn("c").await.is_err(), "c is refused its single try");
turn("d").await.expect("the cloud is back");
turn("e").await.expect("and stays up");

let reqs = mock.requests();
assert_eq!(reqs.len(), 9, "2 for a, 4 for b, 1 each for c, d and e");
let line = |i: usize| reqs[i].json()["payload"]["line"].as_str().unwrap_or_default().to_string();
let named = |i: usize| reqs[i].json()["requestId"].as_str().unwrap_or_default().to_string();

assert_eq!(named(0), named(1), "a's repeat is a");
for i in 2..6 {
assert_eq!(line(i), "b");
assert_eq!(named(i), named(2), "b's tries are all b");
}
assert_ne!(named(1), named(2), "b is not a");
assert!(named(6).is_empty(), "c is tried once, unnamed, after a lost turn");
assert_eq!(line(6), "c");
assert!(named(7).is_empty(), "d lands under the same one-try policy");
assert_eq!(line(7), "d");
assert!(!named(8).is_empty(), "e is named: a turn has landed");
assert_ne!(named(8), named(0), "e is not a");
assert_ne!(named(8), named(2), "e is not b");

// No payload was ever sent twice under two DIFFERENT names: the platform
// would store such a pair as two turns.
for i in 0..reqs.len() {
for j in (i + 1)..reqs.len() {
if line(i) == line(j) {
assert_eq!(named(i), named(j), "{} was sent under two request ids", line(i));
}
}
}
}

/// Two turns are two requests: the id names one append, never the session.
#[tokio::test]
async fn each_event_names_itself_apart() {
Expand Down
28 changes: 22 additions & 6 deletions src/testmock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,10 @@ struct Config {
refuse_claims: bool,
/// Optional server-side long-poll hold on `/claim` before answering.
claim_hold: std::time::Duration,
/// Answer 503 to the first this-many requests, then serve normally.
refuse_first: usize,
/// Answer 503 to the requests whose position is `true`, then serve normally
/// past the end: a cloud that is ready except for the moments named here.
refuse_schedule: Vec<bool>,
/// The position of the next request in the schedule, shared across connections.
refused: Arc<std::sync::atomic::AtomicUsize>,
/// The folders every target answer carries as granted; a test changes them
/// with [`MockCloud::grant`].
Expand Down Expand Up @@ -112,7 +114,7 @@ impl Default for Config {
reject_first_key: false,
refuse_claims: false,
claim_hold: std::time::Duration::ZERO,
refuse_first: 0,
refuse_schedule: Vec::new(),
refused: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
folders: Arc::new(Mutex::new(Vec::new())),
}
Expand Down Expand Up @@ -148,9 +150,16 @@ impl MockCloud {
}

/// A mock that answers 503 to its first `n` requests and then serves normally:
/// a cloud that is briefly not ready.
/// a cloud that is briefly not ready. Exactly the schedule of `n` refusals.
pub async fn start_refusing_first(n: usize) -> MockCloud {
Self::with(Config { refuse_first: n, ..Config::default() }).await
Self::start_refusing(&vec![true; n]).await
}

/// A mock that answers 503 at each position that is `true` and serves every
/// other request — and everything past the end of the schedule. Bursts can be
/// placed on the turns a test means them for, instead of only at the start.
pub async fn start_refusing(schedule: &[bool]) -> MockCloud {
Self::with(Config { refuse_schedule: schedule.to_vec(), ..Config::default() }).await
}

/// A mock that fails GET on a session id with `code` while register still
Expand Down Expand Up @@ -369,7 +378,14 @@ fn respond(cfg: &Config, method: &str, path: &str, bearer: bool, claim_key: Opti
if let Some(code) = cfg.force_status {
return (format!("{code} Error"), r#"{"error":"forced"}"#.to_string());
}
if cfg.refused.fetch_add(1, std::sync::atomic::Ordering::SeqCst) < cfg.refuse_first {
// Past the end of the schedule, a position is served normally: a short
// schedule names a burst, not a cloud that never recovers.
if cfg
.refuse_schedule
.get(cfg.refused.fetch_add(1, std::sync::atomic::Ordering::SeqCst))
.copied()
.unwrap_or(false)
{
return ("503 Service Unavailable".into(), r#"{"error":"not ready"}"#.to_string());
}
// The org's kit, as the caller reads it.
Expand Down
129 changes: 118 additions & 11 deletions tests/signals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ use std::net::TcpListener;
use std::os::unix::process::{CommandExt, ExitStatusExt};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// A session's world: `bin/` with the stand-ins, `home/`, and the agent's log.
Expand All @@ -25,6 +27,15 @@ impl World {
std::fs::create_dir(w.at(d)).unwrap();
}
let log = w.at("log");
// The one turn the agent says, as pi's `--mode json` prints it: it is what
// the run forwards to the cloud, and what a refused cloud retries.
let say = w.at("say");
std::fs::write(
&say,
r#"{"type":"message_end","message":{"role":"assistant","content":[{"type":"text","text":"working"}]}}
"#,
)
.unwrap();
w.program(
"pi",
&format!(
Expand All @@ -35,10 +46,12 @@ trap 'echo HUP >> {log}; exit 129' HUP
echo $$ > {log}.pid
echo start >> {log}
[ -n "$QUICK" ] && exit 0
cat {say}
i=0; while [ $i -lt 200 ]; do sleep 0.05; i=$((i+1)); done
echo end >> {log}
"#,
log = log.display()
log = log.display(),
say = say.display()
),
);
w.program(
Expand Down Expand Up @@ -182,10 +195,11 @@ fn a_signal_once_the_agent_has_ended_ends_gen() {
let w = World::new(&profile);
let log = w.at("log");
let (stalled, stall) = mpsc::channel();
let state = Arc::new(Cloud { stall_when_reaped: true, ..Cloud::default() });
std::thread::spawn(move || {
for conn in cloud.incoming().flatten() {
let (log, stalled) = (log.clone(), stalled.clone());
std::thread::spawn(move || answer(conn, &log, &stalled));
let (log, stalled, state) = (log.clone(), stalled.clone(), state.clone());
std::thread::spawn(move || answer(conn, &log, &stalled, &state));
}
});
let mut gen = w.gen(&["--backend", "pi", "--link", "--no-mcp", "x"], None, true);
Expand All @@ -198,9 +212,89 @@ fn a_signal_once_the_agent_has_ended_ends_gen() {
assert!(sent.elapsed() < Duration::from_secs(3), "{:?}", sent.elapsed());
}

/// A transcript turn refused mid-run is still ONE request when SIGINT ends the
/// run: every recorded `/events` body with the same payload carries the SAME
/// `requestId`, so the platform stores the turn once. A fresh name on each try
/// would store the turn twice — exactly the duplicate a burst is named to prevent
/// — and the agent heard INT rather than reaching its own end.
#[test]
fn a_signal_inside_a_retry_window_keeps_a_turn_named_once() {
let stand = TcpListener::bind("127.0.0.1:0").unwrap();
let port = stand.local_addr().unwrap().port();
let profile = format!(
r#"{{"api": "http://127.0.0.1:{port}", "local": true, "org": null, "provider": "hanzo", "identities": [["test", "one"]], "link": true, "theme": "auto"}}"#
);
let w = World::new(&profile);
let log = w.at("log");
// Serve the run's opening status, then refuse every turn: the agent's first
// message is inside the wire's retry window when the signal arrives.
let state = Arc::new(Cloud { refuse_after: Some(1), ..Cloud::default() });
let (stalled, _stall) = mpsc::channel();
{
let (log, stalled, state) = (log.clone(), stalled.clone(), state.clone());
std::thread::spawn(move || {
for conn in stand.incoming().flatten() {
let (log, stalled, state) = (log.clone(), stalled.clone(), state.clone());
std::thread::spawn(move || answer(conn, &log, &stalled, &state));
}
});
}
let mut gen = w.gen(&["--backend", "pi", "--link", "--no-mcp", "x"], None, false);
// The opening status is one event; the refused turn's first try is the next.
let by = Instant::now() + Duration::from_secs(20);
while state.events.lock().unwrap().len() < 2 {
assert!(Instant::now() < by, "the turn never reached the cloud: {:?}", w.heard());
assert!(gen.try_wait().unwrap().is_none(), "gen ended before its turn was refused");
std::thread::sleep(Duration::from_millis(20));
}
kill(&gen, libc::SIGINT);
let status = ended(&mut gen, Duration::from_secs(20)).expect("gen outlived SIGINT");
let heard = w.heard();
assert!(!status.success(), "a run cut short by SIGINT said it succeeded");
assert!(heard.lines().any(|l| l == "INT"), "the agent never heard SIGINT: {heard:?}");
assert!(!heard.contains("end"), "the agent ran to its end through SIGINT: {heard:?}");

// Group the recorded bodies by what they say; the id must be the group's,
// not the attempt's.
let bodies = state.events.lock().unwrap().clone();
let mut groups: Vec<(serde_json::Value, Vec<String>)> = Vec::new();
for b in &bodies {
let key = serde_json::json!({ "kind": b["kind"], "payload": b["payload"] });
let id = b["requestId"].as_str().unwrap_or_default().to_string();
match groups.iter_mut().find(|(k, _)| *k == key) {
Some((_, ids)) => ids.push(id),
None => groups.push((key, vec![id])),
}
}
let retried = groups.iter().find(|(_, ids)| ids.len() > 1).unwrap_or_else(|| {
panic!("no turn was tried twice before the signal: {bodies:?}")
});
assert!(!retried.1[0].is_empty(), "the retried turn was sent unnamed: {bodies:?}");
for (key, ids) in &groups {
assert!(
ids.iter().all(|id| *id == ids[0]),
"{key} was sent under two request ids {ids:?}"
);
}
}

/// What the stand-in cloud remembers across connections: every `/events` body it
/// was sent, and how many it has refused.
#[derive(Default)]
struct Cloud {
events: Mutex<Vec<serde_json::Value>>,
refused: AtomicUsize,
/// Serve this many event POSTs, then answer 503 to the rest. `None` serves
/// every one — a cloud with no burst in it.
refuse_after: Option<usize>,
/// Go silent once the agent that wrote `log` has been reaped: a cloud that
/// stopped answering mid-close-out.
stall_when_reaped: bool,
}

/// One connection to the stand-in cloud: every request is answered until gen has
/// reaped its agent, and from then on none is, as a cloud that has stalled.
fn answer(conn: std::net::TcpStream, log: &Path, stalled: &mpsc::Sender<()>) {
fn answer(conn: std::net::TcpStream, log: &Path, stalled: &mpsc::Sender<()>, cloud: &Cloud) {
let mut out = conn.try_clone().unwrap();
let mut r = BufReader::new(conn);
loop {
Expand All @@ -219,20 +313,33 @@ fn answer(conn: std::net::TcpStream, log: &Path, stalled: &mpsc::Sender<()>) {
.unwrap_or(0);
let mut body = vec![0; len];
r.read_exact(&mut body).unwrap();
if reaped(log) {
let first = head.lines().next().unwrap_or_default();
if cloud.stall_when_reaped && reaped(log) {
let _ = stalled.send(());
std::thread::sleep(Duration::from_secs(60));
return;
}
let first = head.lines().next().unwrap_or_default();
let reply = if first.starts_with("POST /v1/agents/sessions ") {
r#"{"id":"sess_t"}"#
let is_event = first
.strip_prefix("POST /v1/agents/sessions/")
.and_then(|rest| rest.split_whitespace().next())
.is_some_and(|p| p.ends_with("/events"));
let refused = if is_event {
cloud.events.lock().unwrap().push(serde_json::from_slice(&body).unwrap_or_default());
let n = cloud.refused.fetch_add(1, Ordering::SeqCst);
cloud.refuse_after.is_some_and(|after| n >= after)
} else {
false
};
let (status, reply) = if refused {
("503 Service Unavailable", r#"{"error":"not ready"}"#)
} else if first.starts_with("POST /v1/agents/sessions ") {
("200 OK", r#"{"id":"sess_t"}"#)
} else if first.contains("/control") {
r#"{"commands":[],"cursor":0}"#
("200 OK", r#"{"commands":[],"cursor":0}"#)
} else {
"{}"
("200 OK", "{}")
};
let _ = write!(out, "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{reply}", reply.len());
let _ = write!(out, "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\n\r\n{reply}", reply.len());
}
}

Expand Down