|
| 1 | +#![cfg(unix)] |
| 2 | +use claurst_api::{ |
| 3 | + provider::LlmProvider, provider_error::ProviderError, provider_types::ProviderRequest, |
| 4 | + providers::ClaudeCliProvider, |
| 5 | +}; |
| 6 | +use claurst_core::types::{ContentBlock, Message}; |
| 7 | +use std::{ |
| 8 | + fs, |
| 9 | + os::unix::{fs::PermissionsExt, process::CommandExt}, |
| 10 | + path::{Path, PathBuf}, |
| 11 | + process::{Child, Command, Stdio}, |
| 12 | + time::{Duration, Instant}, |
| 13 | +}; |
| 14 | + |
| 15 | +const FAKE: &str = r#" |
| 16 | +import json, os, pathlib, sys, time |
| 17 | +root = pathlib.Path(os.environ['STDERR_FIXTURE_ROOT']) |
| 18 | +case = os.environ['STDERR_FIXTURE_CASE'] |
| 19 | +(root / 'pid.tmp').write_text(str(os.getpid())) |
| 20 | +os.replace(root / 'pid.tmp', root / 'pid') |
| 21 | +value = json.loads(sys.stdin.read()) |
| 22 | +assert value['message']['content'][0]['text'] == 'fixture prompt' |
| 23 | +if case == 'diagnostic': |
| 24 | + sys.stderr.write(' fixture startup diagnostic\n') |
| 25 | + sys.stderr.flush() |
| 26 | + sys.exit(1) |
| 27 | +if case == 'success': |
| 28 | + print(json.dumps({'type':'assistant','message':{'content':[{'type':'text','text':'fixture response'}]}}), flush=True) |
| 29 | + print(json.dumps({'type':'result'}), flush=True) |
| 30 | + sys.exit(0) |
| 31 | +child = os.fork() |
| 32 | +if child == 0: |
| 33 | + os.close(0) |
| 34 | + os.close(1) |
| 35 | + (root / 'descendant.tmp').write_text(str(os.getpid())) |
| 36 | + os.replace(root / 'descendant.tmp', root / 'descendant') |
| 37 | + while not (root / 'release').exists(): |
| 38 | + time.sleep(0.01) |
| 39 | + os.set_blocking(2, False) |
| 40 | + while True: |
| 41 | + try: |
| 42 | + os.write(2, b'fixture stderr pressure\n' * 128) |
| 43 | + except BrokenPipeError: |
| 44 | + (root / 'broken-pipe.tmp').write_text('closed') |
| 45 | + os.replace(root / 'broken-pipe.tmp', root / 'broken-pipe') |
| 46 | + os._exit(0) |
| 47 | + except BlockingIOError: |
| 48 | + pass |
| 49 | + time.sleep(0.01) |
| 50 | +while not (root / 'descendant').exists(): |
| 51 | + time.sleep(0.01) |
| 52 | +if case == 'early-error': |
| 53 | + sys.exit(1) |
| 54 | +if case == 'stream-drop': |
| 55 | + print(json.dumps({'type':'system','session_id':'fixture','model':'fixture'}), flush=True) |
| 56 | +time.sleep(60) |
| 57 | +"#; |
| 58 | + |
| 59 | +struct OwnedCase { |
| 60 | + root: PathBuf, |
| 61 | + child: Option<Child>, |
| 62 | + python: PathBuf, |
| 63 | +} |
| 64 | +impl OwnedCase { |
| 65 | + fn cleanup(&mut self) -> std::io::Result<()> { |
| 66 | + let Some(mut child) = self.child.take() else { |
| 67 | + return Ok(()); |
| 68 | + }; |
| 69 | + // Never signal the group after reaping its leader. |
| 70 | + let result = Command::new(&self.python).args(["-c", "import os,signal,sys\ntry: os.killpg(int(sys.argv[1]),signal.SIGKILL)\nexcept ProcessLookupError: pass", &child.id().to_string()]).status(); |
| 71 | + let group_killed = result.as_ref().is_ok_and(|status| status.success()); |
| 72 | + if !group_killed { |
| 73 | + child.kill()?; |
| 74 | + } |
| 75 | + child.wait()?; |
| 76 | + fs::remove_dir_all(&self.root)?; |
| 77 | + if group_killed { |
| 78 | + Ok(()) |
| 79 | + } else { |
| 80 | + Err(std::io::Error::other(format!( |
| 81 | + "owned group cleanup failed: {result:?}" |
| 82 | + ))) |
| 83 | + } |
| 84 | + } |
| 85 | +} |
| 86 | +impl Drop for OwnedCase { |
| 87 | + fn drop(&mut self) { |
| 88 | + if let Err(error) = self.cleanup() { |
| 89 | + eprintln!("fixture cleanup failed: {error}"); |
| 90 | + } |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +fn run_case(case: &str) { |
| 95 | + let python = ["/opt/homebrew/bin/python3", "/usr/bin/python3"] |
| 96 | + .into_iter() |
| 97 | + .map(PathBuf::from) |
| 98 | + .find(|path| path.is_file()) |
| 99 | + .expect("fixture requires Python 3"); |
| 100 | + let stamp = std::time::SystemTime::now() |
| 101 | + .duration_since(std::time::UNIX_EPOCH) |
| 102 | + .unwrap() |
| 103 | + .as_nanos(); |
| 104 | + let root = std::env::temp_dir().join(format!( |
| 105 | + "coven-cli-stderr-{}-{case}-{stamp}", |
| 106 | + std::process::id() |
| 107 | + )); |
| 108 | + fs::create_dir(&root).unwrap(); |
| 109 | + fs::write(root.join("fake.py"), FAKE).unwrap(); |
| 110 | + let launcher = root.join("claude"); |
| 111 | + fs::write( |
| 112 | + &launcher, |
| 113 | + "#!/bin/sh\nexec \"$STDERR_FIXTURE_PYTHON\" \"$STDERR_FIXTURE_ROOT/fake.py\" \"$@\"\n", |
| 114 | + ) |
| 115 | + .unwrap(); |
| 116 | + fs::set_permissions(&launcher, fs::Permissions::from_mode(0o700)).unwrap(); |
| 117 | + let log = fs::File::create(root.join("worker.log")).unwrap(); |
| 118 | + let child = Command::new(std::env::current_exe().unwrap()) |
| 119 | + .args([ |
| 120 | + "--exact", |
| 121 | + "stderr_fixture_worker", |
| 122 | + "--ignored", |
| 123 | + "--nocapture", |
| 124 | + ]) |
| 125 | + .env_clear() |
| 126 | + .env("HOME", &root) |
| 127 | + .env("USERPROFILE", &root) |
| 128 | + .env("COVEN_CODE_HOME", &root) |
| 129 | + .env("PATH", &root) |
| 130 | + .env("COVEN_CODE_CLAUDE_BIN", &launcher) |
| 131 | + .env("STDERR_FIXTURE_ROOT", &root) |
| 132 | + .env("STDERR_FIXTURE_CASE", case) |
| 133 | + .env("STDERR_FIXTURE_PYTHON", &python) |
| 134 | + .current_dir(&root) |
| 135 | + .stdin(Stdio::null()) |
| 136 | + .stdout(log.try_clone().unwrap()) |
| 137 | + .stderr(log) |
| 138 | + .process_group(0) |
| 139 | + .spawn() |
| 140 | + .unwrap(); |
| 141 | + assert!(child.id() >= 2); |
| 142 | + let mut owned = OwnedCase { |
| 143 | + root, |
| 144 | + child: Some(child), |
| 145 | + python, |
| 146 | + }; |
| 147 | + let deadline = Instant::now() + Duration::from_secs(20); |
| 148 | + while !owned.root.join("complete").exists() |
| 149 | + && !owned.root.join("failed").exists() |
| 150 | + && Instant::now() < deadline |
| 151 | + { |
| 152 | + std::thread::sleep(Duration::from_millis(20)); |
| 153 | + } |
| 154 | + let complete = fs::read_to_string(owned.root.join("complete")).ok(); |
| 155 | + let started = owned.root.join("pid").exists(); |
| 156 | + let log = fs::read_to_string(owned.root.join("worker.log")).unwrap(); |
| 157 | + owned.cleanup().expect("owned process-group cleanup failed"); |
| 158 | + assert_eq!(complete.as_deref(), Some("complete"), "{case}: {log}"); |
| 159 | + assert!(started, "fake executable was not reached"); |
| 160 | +} |
| 161 | + |
| 162 | +#[test] |
| 163 | +fn startup_drop_closes_stderr_reader() { |
| 164 | + run_case("startup-drop"); |
| 165 | +} |
| 166 | +#[test] |
| 167 | +fn unpolled_stream_drop_closes_stderr_reader() { |
| 168 | + run_case("stream-drop"); |
| 169 | +} |
| 170 | +#[test] |
| 171 | +fn returned_startup_error_closes_stderr_reader() { |
| 172 | + run_case("early-error"); |
| 173 | +} |
| 174 | +#[test] |
| 175 | +fn startup_diagnostic_is_preserved() { |
| 176 | + run_case("diagnostic"); |
| 177 | +} |
| 178 | +#[test] |
| 179 | +fn normal_response_is_preserved() { |
| 180 | + run_case("success"); |
| 181 | +} |
| 182 | + |
| 183 | +async fn wait_for_pid(root: &Path) { |
| 184 | + tokio::time::timeout(Duration::from_secs(3), async { |
| 185 | + while fs::read_to_string(root.join("pid")) |
| 186 | + .ok() |
| 187 | + .and_then(|value| value.parse::<u32>().ok()) |
| 188 | + .is_none() |
| 189 | + { |
| 190 | + tokio::time::sleep(Duration::from_millis(10)).await; |
| 191 | + } |
| 192 | + }) |
| 193 | + .await |
| 194 | + .unwrap(); |
| 195 | +} |
| 196 | + |
| 197 | +async fn assert_child_gone(root: &Path) { |
| 198 | + let pid = fs::read_to_string(root.join("pid")).unwrap(); |
| 199 | + assert!(pid.parse::<u32>().unwrap() >= 2); |
| 200 | + let python = std::env::var_os("STDERR_FIXTURE_PYTHON").unwrap(); |
| 201 | + tokio::time::timeout(Duration::from_secs(3), async { |
| 202 | + loop { |
| 203 | + let status = tokio::process::Command::new(&python).args(["-c", "import os,sys\ntry: os.kill(int(sys.argv[1]),0)\nexcept ProcessLookupError: sys.exit(0)\nsys.exit(1)", &pid]).status().await.unwrap(); |
| 204 | + if status.success() { break; } |
| 205 | + tokio::time::sleep(Duration::from_millis(20)).await; |
| 206 | + } |
| 207 | + }).await.expect("provider child survived drop before group cleanup"); |
| 208 | +} |
| 209 | + |
| 210 | +async fn wait_for_file(root: &Path, name: &str) { |
| 211 | + tokio::time::timeout(Duration::from_secs(3), async { |
| 212 | + while !root.join(name).exists() { |
| 213 | + tokio::time::sleep(Duration::from_millis(10)).await; |
| 214 | + } |
| 215 | + }) |
| 216 | + .await |
| 217 | + .unwrap_or_else(|_| panic!("missing fixture marker: {name}")); |
| 218 | +} |
| 219 | + |
| 220 | +#[test] |
| 221 | +#[ignore = "invoked by isolated parent drivers"] |
| 222 | +fn stderr_fixture_worker() { |
| 223 | + let root = PathBuf::from(std::env::var_os("STDERR_FIXTURE_ROOT").unwrap()); |
| 224 | + let case = std::env::var("STDERR_FIXTURE_CASE").unwrap(); |
| 225 | + let runtime = tokio::runtime::Builder::new_multi_thread() |
| 226 | + .worker_threads(2) |
| 227 | + .enable_all() |
| 228 | + .build() |
| 229 | + .unwrap(); |
| 230 | + let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 231 | + runtime.block_on(async { |
| 232 | + let provider = ClaudeCliProvider::new(); |
| 233 | + let request = ProviderRequest { |
| 234 | + model: "fixture".into(), messages: vec![Message::user("fixture prompt")], |
| 235 | + system_prompt: None, tools: Vec::new(), max_tokens: 16, |
| 236 | + temperature: None, top_p: None, top_k: None, stop_sequences: Vec::new(), |
| 237 | + thinking: None, provider_options: serde_json::json!({}), |
| 238 | + }; |
| 239 | + if case == "startup-drop" { |
| 240 | + { |
| 241 | + let startup = provider.create_message_stream(request); |
| 242 | + tokio::pin!(startup); |
| 243 | + tokio::select! { |
| 244 | + _ = &mut startup => panic!("startup unexpectedly completed"), |
| 245 | + _ = wait_for_file(&root, "descendant") => {} |
| 246 | + } |
| 247 | + } |
| 248 | + } else if case == "stream-drop" { |
| 249 | + let stream = tokio::time::timeout(Duration::from_secs(3), provider.create_message_stream(request)).await.unwrap().unwrap(); |
| 250 | + drop(stream); |
| 251 | + } else if case == "success" { |
| 252 | + let response = tokio::time::timeout(Duration::from_secs(3), provider.create_message(request)).await.unwrap().unwrap(); |
| 253 | + assert!(matches!(response.content.as_slice(), [ContentBlock::Text { text }] if text == "fixture response")); |
| 254 | + } else { |
| 255 | + let result = tokio::time::timeout(Duration::from_secs(3), provider.create_message_stream(request)).await.unwrap(); |
| 256 | + let error = match result { Ok(_) => panic!("expected startup failure"), Err(error) => error }; |
| 257 | + let expected = if case == "diagnostic" { "claude CLI exited without producing output: fixture startup diagnostic" } else { "claude CLI exited without producing output" }; |
| 258 | + assert!(matches!(error, ProviderError::Other { message, .. } if message == expected)); |
| 259 | + } |
| 260 | + wait_for_pid(&root).await; |
| 261 | + if case != "success" && case != "diagnostic" { |
| 262 | + wait_for_file(&root, "descendant").await; |
| 263 | + let descendant = fs::read_to_string(root.join("descendant")).unwrap().parse::<u32>().unwrap(); |
| 264 | + assert!(descendant >= 2); |
| 265 | + assert_child_gone(&root).await; |
| 266 | + fs::write(root.join("release"), "release").unwrap(); |
| 267 | + wait_for_file(&root, "broken-pipe").await; |
| 268 | + assert_eq!(fs::read_to_string(root.join("broken-pipe")).unwrap(), "closed"); |
| 269 | + } |
| 270 | + }) |
| 271 | + })); |
| 272 | + let marker = if outcome.is_ok() { |
| 273 | + "complete" |
| 274 | + } else { |
| 275 | + "failed" |
| 276 | + }; |
| 277 | + let pending = root.join("outcome.pending"); |
| 278 | + if let Err(error) = |
| 279 | + fs::write(&pending, marker).and_then(|()| fs::rename(&pending, root.join(marker))) |
| 280 | + { |
| 281 | + eprintln!("fixture outcome publication failed: {error}"); |
| 282 | + } |
| 283 | + std::thread::sleep(Duration::from_secs(60)); |
| 284 | +} |
0 commit comments