| 1 | use super::*; |
| 2 | use codewhale_engine::llm_client::mock::MockLlmClient; |
| 3 | use codewhale_engine::runtime_threads::job_operations::{ |
| 4 | MEMBER_RESERVED, MemberOperation, MemberOperationRecord, |
| 5 | }; |
| 6 | |
| 7 | struct AbortOnDrop(tokio::task::AbortHandle); |
| 8 | impl Drop for AbortOnDrop { |
| 9 | fn drop(&mut self) { |
| 10 | self.0.abort(); |
| 11 | } |
| 12 | } |
| 13 | |
| 14 | fn fleet() -> Value { |
| 15 | json!({ |
| 16 | "schema": "fleet", |
| 17 | "schema_revision": 2, |
| 18 | "name": "Review team", |
| 19 | "members": [ |
| 20 | { "id": "reviewer", "role": "reviewer", "provider": "deepseek", "model": "deepseek-v4-pro" } |
| 21 | ] |
| 22 | }) |
| 23 | } |
| 24 | |
| 25 | fn start_body(key: &str, prompt: &str) -> Value { |
| 26 | json!({ |
| 27 | "operation_key": key, |
| 28 | "member_id": "reviewer", |
| 29 | "display_name": "Reviewer", |
| 30 | "prompt": prompt, |
| 31 | "fleet": fleet(), |
| 32 | }) |
| 33 | } |
| 34 | |
| 35 | fn reserve( |
| 36 | threads: &SharedRuntimeThreadManager, |
| 37 | thread_id: &str, |
| 38 | key: &str, |
| 39 | generation: &str, |
| 40 | ) -> Result<()> { |
| 41 | threads |
| 42 | .job_operation_store() |
| 43 | .with_job_operations(|transaction| { |
| 44 | let now = chrono::Utc::now().timestamp_millis(); |
| 45 | transaction.save_member(&MemberOperationRecord { |
| 46 | schema_version: 1, |
| 47 | operation: MemberOperation { |
| 48 | id: transaction.member_operation_id(thread_id, key)?, |
| 49 | store_id: threads.job_operation_store_id().to_string(), |
| 50 | thread_id: thread_id.to_string(), |
| 51 | member_id: "reviewer".to_string(), |
| 52 | operation_key: key.to_string(), |
| 53 | agent_id: "agent_reservedfixture".to_string(), |
| 54 | state: MEMBER_RESERVED.to_string(), |
| 55 | created_at_ms: now, |
| 56 | updated_at_ms: now, |
| 57 | }, |
| 58 | request_fingerprint: "a".repeat(64), |
| 59 | owner_generation: generation.to_string(), |
| 60 | }) |
| 61 | }) |
| 62 | } |
| 63 | |
| 64 | #[tokio::test] |
| 65 | async fn member_starts_are_durable_replayable_and_refuse_foreign_or_mismatched_replay() -> Result<()> |
| 66 | { |
| 67 | let _env = lock_test_env(); |
| 68 | let temporary = tempfile::tempdir()?; |
| 69 | let root = temporary.path().canonicalize()?; |
| 70 | let _home = EnvVarGuard::set("CODEWHALE_HOME", root.join("home")); |
| 71 | let workspace = root.join("workspace"); |
| 72 | fs::create_dir_all(&workspace)?; |
| 73 | let config = Config::default().with_legacy_root( |
| 74 | Some("member-fixture-key".into()), |
| 75 | Some("http://127.0.0.1:1/v1".into()), |
| 76 | ); |
| 77 | let (addr, threads, server) = spawn_test_server_with_root_token_mobile_workspace_and_overrides( |
| 78 | root.clone(), |
| 79 | root.join("sessions"), |
| 80 | None, |
| 81 | false, |
| 82 | workspace.clone(), |
| 83 | TestServerOverrides { |
| 84 | config: Some(config), |
| 85 | ..TestServerOverrides::default() |
| 86 | }, |
| 87 | ) |
| 88 | .await? |
| 89 | .context("the member fixture needs a loopback listener")?; |
| 90 | let _server = AbortOnDrop(server.abort_handle()); |
| 91 | threads.set_test_model_client(Arc::new(MockLlmClient::new(Vec::new()))); |
| 92 | let client = codewhale_release::tls::reqwest_client(); |
| 93 | let url = |path: &str| format!("http://{addr}{path}"); |
| 94 | let create_thread = || async { |
| 95 | let created: Value = client |
| 96 | .post(url("/v1/threads")) |
| 97 | .json(&json!({ "model": "deepseek-v4-pro", "mode": "agent", "workspace": workspace })) |
| 98 | .send() |
| 99 | .await? |
| 100 | .error_for_status()? |
| 101 | .json() |
| 102 | .await?; |
| 103 | anyhow::Ok(created["id"].as_str().context("thread id")?.to_string()) |
| 104 | }; |
| 105 | let thread = create_thread().await?; |
| 106 | let other = create_thread().await?; |
| 107 | let info: Value = client |
| 108 | .get(url("/v1/runtime/info")) |
| 109 | .send() |
| 110 | .await? |
| 111 | .json() |
| 112 | .await?; |
| 113 | assert_eq!( |
| 114 | info["capabilities"]["thread_fleet_member_durable_operations_v1"], |
| 115 | true |
| 116 | ); |
| 117 | let store_id = threads.job_operation_store_id().to_string(); |
| 118 | let members = url(&format!("/v1/threads/{thread}/members")); |
| 119 | |
| 120 | let first = client |
| 121 | .post(&members) |
| 122 | .json(&start_body("team-start-1", "Review the diff")) |
| 123 | .send() |
| 124 | .await?; |
| 125 | let status = first.status(); |
| 126 | let receipt: Value = first.json().await?; |
| 127 | assert_eq!(status, StatusCode::OK, "{receipt}"); |
| 128 | assert_eq!(receipt["state"], "accepted"); |
| 129 | assert_eq!(receipt["runtime_store_id"], store_id.as_str()); |
| 130 | assert_eq!(receipt["operation_key"], "team-start-1"); |
| 131 | let agent_id = receipt["agent_id"] |
| 132 | .as_str() |
| 133 | .context("agent id")? |
| 134 | .to_string(); |
| 135 | let runs = member_runs(&client, addr, &thread).await?; |
| 136 | assert_eq!(runs.len(), 1, "{runs:?}"); |
| 137 | assert_eq!( |
| 138 | runs[0]["spec"]["worker_id"], |
| 139 | agent_id.as_str(), |
| 140 | "the receipt names the worker it started" |
| 141 | ); |
| 142 | |
| 143 | let replayed: Value = client |
| 144 | .post(&members) |
| 145 | .json(&start_body("team-start-1", "Review the diff")) |
| 146 | .send() |
| 147 | .await? |
| 148 | .error_for_status()? |
| 149 | .json() |
| 150 | .await?; |
| 151 | assert_eq!( |
| 152 | replayed, receipt, |
| 153 | "exact replay returns the original receipt" |
| 154 | ); |
| 155 | let read: Value = client |
| 156 | .get(url(&format!( |
| 157 | "/v1/threads/{thread}/members/operations/team-start-1" |
| 158 | ))) |
| 159 | .send() |
| 160 | .await? |
| 161 | .error_for_status()? |
| 162 | .json() |
| 163 | .await?; |
| 164 | assert_eq!(read, receipt); |
| 165 | |
| 166 | let mismatched = client |
| 167 | .post(&members) |
| 168 | .json(&start_body("team-start-1", "Review something else")) |
| 169 | .send() |
| 170 | .await?; |
| 171 | assert_eq!(mismatched.status(), StatusCode::CONFLICT); |
| 172 | let body: Value = mismatched.json().await?; |
| 173 | assert_eq!(body["error"]["code"], "member_operation_mismatch"); |
| 174 | |
| 175 | let foreign = client |
| 176 | .get(url(&format!( |
| 177 | "/v1/threads/{other}/members/operations/team-start-1" |
| 178 | ))) |
| 179 | .send() |
| 180 | .await?; |
| 181 | assert_eq!( |
| 182 | foreign.status(), |
| 183 | StatusCode::NOT_FOUND, |
| 184 | "a key never crosses threads" |
| 185 | ); |
| 186 | |
| 187 | let mut ghost = start_body("team-ghost", "Review the diff"); |
| 188 | ghost["member_id"] = json!("ghost"); |
| 189 | let refused = client.post(&members).json(&ghost).send().await?; |
| 190 | assert_eq!(refused.status(), StatusCode::CONFLICT); |
| 191 | let withdrawn = client |
| 192 | .get(url(&format!( |
| 193 | "/v1/threads/{thread}/members/operations/team-ghost" |
| 194 | ))) |
| 195 | .send() |
| 196 | .await?; |
| 197 | assert_eq!( |
| 198 | withdrawn.status(), |
| 199 | StatusCode::NOT_FOUND, |
| 200 | "a start the Engine refused withdraws its reservation" |
| 201 | ); |
| 202 | |
| 203 | let mut stale = start_body("team-start-2", "Review the diff"); |
| 204 | stale["expected_store_id"] = json!("another-store"); |
| 205 | let stale = client.post(&members).json(&stale).send().await?; |
| 206 | assert_eq!(stale.status(), StatusCode::CONFLICT); |
| 207 | let body: Value = stale.json().await?; |
| 208 | assert_eq!(body["error"]["code"], "member_operation_store_changed"); |
| 209 | |
| 210 | let mut forged = start_body("team-start-3", "Review the diff"); |
| 211 | forged["request_fingerprint"] = json!("b".repeat(64)); |
| 212 | let forged = client.post(&members).json(&forged).send().await?; |
| 213 | assert_eq!(forged.status(), StatusCode::BAD_REQUEST); |
| 214 | |
| 215 | let generation = threads.job_operation_generation()?; |
| 216 | reserve(&threads, &other, "in-flight", &generation)?; |
| 217 | let deleted = threads.delete_thread(&other).await; |
| 218 | assert!( |
| 219 | deleted |
| 220 | .as_ref() |
| 221 | .is_err_and(|error| error.to_string().contains("pending member operation")), |
| 222 | "a thread with a start in flight is not deleted: {deleted:?}" |
| 223 | ); |
| 224 | |
| 225 | reserve( |
| 226 | &threads, |
| 227 | &other, |
| 228 | "before-restart", |
| 229 | &Uuid::new_v4().to_string(), |
| 230 | )?; |
| 231 | let abandoned: Value = client |
| 232 | .get(url(&format!( |
| 233 | "/v1/threads/{other}/members/operations/before-restart" |
| 234 | ))) |
| 235 | .send() |
| 236 | .await? |
| 237 | .error_for_status()? |
| 238 | .json() |
| 239 | .await?; |
| 240 | assert_eq!( |
| 241 | abandoned["state"], "abandoned", |
| 242 | "a reservation an earlier Engine never started is settled, not left unknown" |
| 243 | ); |
| 244 | |
| 245 | let cancelled = client |
| 246 | .post(url(&format!("/v1/agent-runs/{agent_id}/cancel"))) |
| 247 | .send() |
| 248 | .await?; |
| 249 | assert!(cancelled.status().is_success(), "{}", cancelled.status()); |
| 250 | let after_cancel: Value = client |
| 251 | .post(&members) |
| 252 | .json(&start_body("team-start-1", "Review the diff")) |
| 253 | .send() |
| 254 | .await? |
| 255 | .error_for_status()? |
| 256 | .json() |
| 257 | .await?; |
| 258 | assert_eq!( |
| 259 | after_cancel["agent_id"], agent_id, |
| 260 | "owner cancellation never makes a replay start a second worker" |
| 261 | ); |
| 262 | assert_eq!(member_runs(&client, addr, &thread).await?.len(), 1); |
| 263 | Ok(()) |
| 264 | } |
| 265 | |
| 266 | async fn member_runs( |
| 267 | client: &reqwest::Client, |
| 268 | addr: SocketAddr, |
| 269 | thread: &str, |
| 270 | ) -> Result<Vec<Value>> { |
| 271 | let listed: Value = client |
| 272 | .get(format!("http://{addr}/v1/agent-runs")) |
| 273 | .send() |
| 274 | .await? |
| 275 | .error_for_status()? |
| 276 | .json() |
| 277 | .await?; |
| 278 | Ok(listed["runs"] |
| 279 | .as_array() |
| 280 | .context("runs")? |
| 281 | .iter() |
| 282 | .filter(|run| run["owner_session_id"] == thread) |
| 283 | .cloned() |
| 284 | .collect()) |
| 285 | } |
| 286 |