Skip to content

Commit 0b32f24

Browse files
authored
Merge pull request #560 from OpenCoven/test/534-remaining-flakes
test: make the remaining #534 tests robust on a loaded host
2 parents 3938dff + b66ef61 commit 0b32f24

4 files changed

Lines changed: 259 additions & 135 deletions

File tree

‎src-rust/crates/api/src/providers/claude_cli.rs‎

Lines changed: 104 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1458,45 +1458,83 @@ mod tests {
14581458
if message.contains("printed nothing for"))
14591459
}
14601460

1461+
/// The pid a stand-in CLI wrote to `dir`, if it got that far. The
1462+
/// provider kills the CLI at its 1 s quiet limit, and a stand-in that a
1463+
/// busy host keeps off the CPU until then is killed before it writes:
1464+
/// the file then never appears, so waiting for it cannot help.
1465+
#[cfg(unix)]
1466+
fn recorded_pid(dir: &std::path::Path) -> Option<String> {
1467+
let pid = std::fs::read_to_string(dir.join("pid")).ok()?;
1468+
let pid = pid.trim();
1469+
pid.parse::<u32>().is_ok().then(|| pid.to_string())
1470+
}
1471+
1472+
/// Runs of a pid-recording scenario before giving up. A run whose
1473+
/// stand-in was killed before it wrote its pid shows nothing about
1474+
/// whether a killed CLI is left running, so the scenario runs again.
1475+
#[cfg(unix)]
1476+
const PID_ATTEMPTS: usize = 3;
1477+
1478+
#[cfg(unix)]
1479+
fn no_pid_recorded() -> ! {
1480+
panic!(
1481+
"in {PID_ATTEMPTS} runs the stand-in CLI had not written its pid when the turn \
1482+
ended at the 1 s quiet limit; the host is likely too busy to run this test"
1483+
)
1484+
}
1485+
1486+
/// Checks that the stand-in CLI in `dir` is no longer running, and
1487+
/// removes `dir`. Returns false, having checked nothing, when the
1488+
/// stand-in wrote no pid.
1489+
#[cfg(unix)]
1490+
async fn assert_recorded_cli_stopped(dir: std::path::PathBuf) -> bool {
1491+
let Some(pid) = recorded_pid(&dir) else {
1492+
let _ = std::fs::remove_dir_all(dir);
1493+
return false;
1494+
};
1495+
let running = still_running_after_a_wait(&pid).await;
1496+
let _ = std::fs::remove_dir_all(dir);
1497+
assert!(!running, "the hung CLI (pid {pid}) is still running");
1498+
true
1499+
}
1500+
14611501
/// The keepalive tells the query loop a silent CLI is busy for as long as
14621502
/// its process lives. A CLI that has hung is alive too, so without a
14631503
/// limit of the provider's own the turn would wait on it for ever.
14641504
#[cfg(unix)]
14651505
#[tokio::test]
14661506
async fn a_running_cli_silent_past_the_limit_ends_the_turn_with_an_error() {
1467-
// The CLI records its pid, then hangs: one process, alive and silent.
1468-
let (dir, items, took) = run_with_quiet_limit(
1469-
"echo $$ > \"$(dirname \"$0\")/pid\"\nexec sleep 60\n",
1470-
Some(std::time::Duration::from_secs(1)),
1471-
)
1472-
.await;
1473-
let pid = std::fs::read_to_string(dir.join("pid")).unwrap();
1507+
for _ in 0..PID_ATTEMPTS {
1508+
// The CLI records its pid, then hangs: one process, alive and silent.
1509+
let (dir, items, took) = run_with_quiet_limit(
1510+
"echo $$ > \"$(dirname \"$0\")/pid\"\nexec sleep 60\n",
1511+
Some(std::time::Duration::from_secs(1)),
1512+
)
1513+
.await;
14741514

1475-
// It was kept alive up to the limit, then failed once, and the stream
1476-
// ended there instead of waiting out the minute.
1477-
assert!(
1478-
took >= std::time::Duration::from_secs(1),
1479-
"ended after {took:?}"
1480-
);
1481-
assert!(
1482-
took < std::time::Duration::from_secs(30),
1483-
"ended after {took:?}"
1484-
);
1485-
let (last, before) = items.split_last().unwrap();
1486-
assert!(is_quiet_limit_error(last), "last item was {last:?}");
1487-
assert!(before.iter().all(Result::is_ok));
1488-
assert!(before
1489-
.iter()
1490-
.any(|item| matches!(item, Ok(StreamEvent::Ping))));
1515+
// It was kept alive up to the limit, then failed once, and the
1516+
// stream ended there instead of waiting out the minute.
1517+
assert!(
1518+
took >= std::time::Duration::from_secs(1),
1519+
"ended after {took:?}"
1520+
);
1521+
assert!(
1522+
took < std::time::Duration::from_secs(30),
1523+
"ended after {took:?}"
1524+
);
1525+
let (last, before) = items.split_last().unwrap();
1526+
assert!(is_quiet_limit_error(last), "last item was {last:?}");
1527+
assert!(before.iter().all(Result::is_ok));
1528+
assert!(before
1529+
.iter()
1530+
.any(|item| matches!(item, Ok(StreamEvent::Ping))));
14911531

1492-
// Ending the stream stopped the CLI: nothing is left running.
1493-
let running = still_running_after_a_wait(pid.trim()).await;
1494-
let _ = std::fs::remove_dir_all(dir);
1495-
assert!(
1496-
!running,
1497-
"the hung CLI (pid {}) is still running",
1498-
pid.trim()
1499-
);
1532+
// Ending the stream stopped the CLI: nothing is left running.
1533+
if assert_recorded_cli_stopped(dir).await {
1534+
return;
1535+
}
1536+
}
1537+
no_pid_recorded();
15001538
}
15011539

15021540
/// A CLI can hang before it prints anything. No stream exists yet at
@@ -1505,44 +1543,42 @@ mod tests {
15051543
#[cfg(unix)]
15061544
#[tokio::test]
15071545
async fn a_cli_silent_from_the_start_fails_the_turn_at_the_limit() {
1508-
let dir = std::env::temp_dir().join(format!("mute-claude-{}", uuid::Uuid::new_v4()));
1509-
std::fs::create_dir(&dir).unwrap();
1510-
let script =
1511-
"#!/bin/sh\necho $$ > \"$(dirname \"$0\")/pid\"\ncat >/dev/null\nexec sleep 60\n";
1512-
let binary = fixture_binary(&dir, script);
1513-
let provider = ClaudeCliProvider {
1514-
id: ProviderId::new(ProviderId::ANTHROPIC),
1515-
binary: Some(binary),
1516-
heartbeat: std::time::Duration::from_millis(50),
1517-
quiet_limit: Some(std::time::Duration::from_secs(1)),
1518-
goal_authority: None,
1519-
};
1520-
let request = request_with(vec![Message::user("fixture prompt")]);
1521-
let started = std::time::Instant::now();
1522-
let error = match provider.create_message_stream(request).await {
1523-
Ok(_) => panic!("a CLI that printed nothing produced a stream"),
1524-
Err(error) => error,
1525-
};
1526-
let took = started.elapsed();
1527-
let error_result = Err(error);
1528-
assert!(is_quiet_limit_error(&error_result), "{error_result:?}");
1529-
let pid = std::fs::read_to_string(dir.join("pid")).unwrap();
1546+
for _ in 0..PID_ATTEMPTS {
1547+
let dir = std::env::temp_dir().join(format!("mute-claude-{}", uuid::Uuid::new_v4()));
1548+
std::fs::create_dir(&dir).unwrap();
1549+
let script =
1550+
"#!/bin/sh\necho $$ > \"$(dirname \"$0\")/pid\"\ncat >/dev/null\nexec sleep 60\n";
1551+
let binary = fixture_binary(&dir, script);
1552+
let provider = ClaudeCliProvider {
1553+
id: ProviderId::new(ProviderId::ANTHROPIC),
1554+
binary: Some(binary),
1555+
heartbeat: std::time::Duration::from_millis(50),
1556+
quiet_limit: Some(std::time::Duration::from_secs(1)),
1557+
goal_authority: None,
1558+
};
1559+
let request = request_with(vec![Message::user("fixture prompt")]);
1560+
let started = std::time::Instant::now();
1561+
let error = match provider.create_message_stream(request).await {
1562+
Ok(_) => panic!("a CLI that printed nothing produced a stream"),
1563+
Err(error) => error,
1564+
};
1565+
let took = started.elapsed();
1566+
let error_result = Err(error);
1567+
assert!(is_quiet_limit_error(&error_result), "{error_result:?}");
1568+
assert!(
1569+
took >= std::time::Duration::from_secs(1),
1570+
"failed after {took:?}"
1571+
);
1572+
assert!(
1573+
took < std::time::Duration::from_secs(30),
1574+
"failed after {took:?}"
1575+
);
15301576

1531-
assert!(
1532-
took >= std::time::Duration::from_secs(1),
1533-
"failed after {took:?}"
1534-
);
1535-
assert!(
1536-
took < std::time::Duration::from_secs(30),
1537-
"failed after {took:?}"
1538-
);
1539-
let running = still_running_after_a_wait(pid.trim()).await;
1540-
let _ = std::fs::remove_dir_all(dir);
1541-
assert!(
1542-
!running,
1543-
"the hung CLI (pid {}) is still running",
1544-
pid.trim()
1545-
);
1577+
if assert_recorded_cli_stopped(dir).await {
1578+
return;
1579+
}
1580+
}
1581+
no_pid_recorded();
15461582
}
15471583

15481584
/// The limit is on unbroken silence, not on the length of the turn: each

‎src-rust/crates/mcp/src/oauth.rs‎

Lines changed: 87 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -2322,53 +2322,75 @@ mod tests {
23222322
#[tokio::test]
23232323
async fn valid_callback_exchanges_once_persists_and_cannot_replay() {
23242324
let _home = TokenHomeGuard::new();
2325-
let token_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
2326-
let token_endpoint = format!("http://{}/token", token_listener.local_addr().unwrap());
2327-
let callback_port = oauth_port_alloc().unwrap();
2328-
let callback_address: std::net::SocketAddr =
2329-
format!("127.0.0.1:{callback_port}").parse().unwrap();
2330-
let redirect_uri = format!("http://{callback_address}/callback");
2331-
let state = "fixture-state".to_string();
2332-
let session = McpAuthSession {
2333-
plugin: None,
2334-
caller: None,
2335-
server_name: "callback-exchange-fixture".into(),
2336-
server_url: "https://mcp.example/fixture".into(),
2337-
auth_url: "https://auth.example/unused".into(),
2338-
redirect_uri: redirect_uri.clone(),
2339-
verifier: "fixture-verifier".into(),
2340-
state: state.clone(),
2341-
metadata: McpOAuthMetadata {
2342-
authorization_endpoint: "https://auth.example/unused".into(),
2343-
token_endpoint: token_endpoint.clone(),
2344-
},
2345-
};
2346-
let token_server = tokio::spawn(async move {
2347-
let (mut socket, _) = token_listener.accept().await.unwrap();
2348-
let mut request = [0_u8; 4096];
2349-
let read = socket.read(&mut request).await.unwrap();
2350-
let request = String::from_utf8_lossy(&request[..read]);
2351-
assert!(request.starts_with("POST /token HTTP/1.1"));
2352-
let body = r#"{"access_token":"fixture-access","refresh_token":"fixture-refresh","expires_in":3600}"#;
2353-
let response = format!(
2354-
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
2355-
body.len()
2356-
);
2357-
socket.write_all(response.as_bytes()).await.unwrap();
2358-
});
2359-
let callback_request = callback_request(
2360-
&callback_address.to_string(),
2361-
&format!("/callback?code=fixture-code&state={state}"),
2362-
);
2363-
let flow = tokio::spawn(run_mcp_auth_session_with(session, move |_| {
2364-
tokio::spawn(async move {
2365-
let response = send_callback(callback_address, &callback_request).await;
2366-
assert!(response.starts_with("HTTP/1.1 200"), "{response}");
2325+
// `oauth_port_alloc` frees its port before the flow binds it, so on a
2326+
// busy host another test can take it in between. The flow then fails
2327+
// to bind before it opens the browser, and the scenario runs again on
2328+
// a fresh port.
2329+
let mut attempts = 0;
2330+
let (result, token_server, callback_address) = loop {
2331+
attempts += 1;
2332+
let token_listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
2333+
let token_endpoint = format!("http://{}/token", token_listener.local_addr().unwrap());
2334+
let callback_port = oauth_port_alloc().unwrap();
2335+
let callback_address: std::net::SocketAddr =
2336+
format!("127.0.0.1:{callback_port}").parse().unwrap();
2337+
let redirect_uri = format!("http://{callback_address}/callback");
2338+
let state = "fixture-state".to_string();
2339+
let session = McpAuthSession {
2340+
plugin: None,
2341+
caller: None,
2342+
server_name: "callback-exchange-fixture".into(),
2343+
server_url: "https://mcp.example/fixture".into(),
2344+
auth_url: "https://auth.example/unused".into(),
2345+
redirect_uri: redirect_uri.clone(),
2346+
verifier: "fixture-verifier".into(),
2347+
state: state.clone(),
2348+
metadata: McpOAuthMetadata {
2349+
authorization_endpoint: "https://auth.example/unused".into(),
2350+
token_endpoint: token_endpoint.clone(),
2351+
},
2352+
};
2353+
let token_server = tokio::spawn(async move {
2354+
let (mut socket, _) = token_listener.accept().await.unwrap();
2355+
let mut request = [0_u8; 4096];
2356+
let read = socket.read(&mut request).await.unwrap();
2357+
let request = String::from_utf8_lossy(&request[..read]);
2358+
assert!(request.starts_with("POST /token HTTP/1.1"));
2359+
let body = r#"{"access_token":"fixture-access","refresh_token":"fixture-refresh","expires_in":3600}"#;
2360+
let response = format!(
2361+
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
2362+
body.len()
2363+
);
2364+
socket.write_all(response.as_bytes()).await.unwrap();
23672365
});
2368-
Ok(())
2369-
}));
2370-
2371-
let result = flow.await.unwrap().unwrap();
2366+
let callback_request = callback_request(
2367+
&callback_address.to_string(),
2368+
&format!("/callback?code=fixture-code&state={state}"),
2369+
);
2370+
let flow = tokio::spawn(run_mcp_auth_session_with(session, move |_| {
2371+
tokio::spawn(async move {
2372+
let response = send_callback(callback_address, &callback_request).await;
2373+
assert!(response.starts_with("HTTP/1.1 200"), "{response}");
2374+
});
2375+
Ok(())
2376+
}));
2377+
match flow.await.unwrap() {
2378+
Err(error)
2379+
if attempts < 3
2380+
&& error
2381+
.to_string()
2382+
.starts_with("Failed to bind OAuth callback listener") =>
2383+
{
2384+
token_server.abort();
2385+
}
2386+
result => {
2387+
let result = result.unwrap_or_else(|error| {
2388+
panic!("callback flow failed on attempt {attempts} of 3: {error:#}")
2389+
});
2390+
break (result, token_server, callback_address);
2391+
}
2392+
}
2393+
};
23722394
token_server.await.unwrap();
23732395
assert_eq!(result.server_name, "callback-exchange-fixture");
23742396
assert_eq!(
@@ -2377,7 +2399,25 @@ mod tests {
23772399
.access_token,
23782400
"fixture-access"
23792401
);
2380-
assert!(TcpStream::connect(callback_address).await.is_err());
2402+
// The flow's listener is gone once the callback address can be bound
2403+
// again; a listener the flow kept would hold it for good. The port is
2404+
// free once the flow ends, so another test in this process may bind
2405+
// it first and hold it for a while: retry until that test lets go. A
2406+
// connect proves nothing either way: it can reach another test's
2407+
// listener, and on macOS a kept listener that never accepts was seen
2408+
// to refuse once its backlog filled.
2409+
let deadline = std::time::Instant::now() + Duration::from_secs(10);
2410+
loop {
2411+
let rebound = TcpListener::bind(callback_address).await;
2412+
if rebound.is_ok() {
2413+
break;
2414+
}
2415+
assert!(
2416+
std::time::Instant::now() < deadline,
2417+
"the callback address is still in use 10s after the flow returned: {rebound:?}"
2418+
);
2419+
tokio::time::sleep(Duration::from_millis(20)).await;
2420+
}
23812421
}
23822422

23832423
#[tokio::test]

‎src-rust/crates/mcp/src/rmcp_http_privacy_tests.rs‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,16 +53,24 @@ fn assert_private(error: &anyhow::Error, category: &str) {
5353
rendered.contains("http-privacy-fixture"),
5454
"missing fixture name"
5555
);
56-
assert!(rendered.contains(category), "missing failure category");
56+
assert!(
57+
rendered.contains(category),
58+
"missing failure category {category:?} in {rendered:?}"
59+
);
5760
}
5861
}
5962

6063
#[tokio::test]
6164
async fn http_refused_initialization_does_not_expose_endpoint() {
6265
for owned in [true, false] {
63-
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
64-
let address = listener.local_addr().unwrap();
65-
drop(listener);
66+
// This assumes nothing listens on port 1, and no test is given it:
67+
// binding port 0 picks from the ephemeral range, far above it. A port
68+
// freed by dropping a listener is open to any other test, whose
69+
// server answers instead of refusing; that reproduces the "missing
70+
// failure category" seen under load. The category message prints the
71+
// error, should a failure have another cause. (A bound socket that
72+
// never listens does not refuse on macOS: the connect hangs.)
73+
let address = "127.0.0.1:1";
6674
let error = initialization_error(
6775
format!("http://{address}/messages?key={SECRET}#{SECRET}"),
6876
owned,

0 commit comments

Comments
 (0)