//! #107: real HTTP wire controls first; SDK participation is an independent migration oracle. use super::{CounterSet, observe, support::*}; use axum::{body::Body, response::Response}; use futures_util::{StreamExt, stream}; use serde_json::{Value, json}; use std::{sync::Arc, time::Duration}; #[path = "rmcp_progress_cancel_http_support.rs"] pub(super) mod fixtures; use fixtures::Endpoint; fn observe_body(response: Response, counters: Arc) -> Response { let (parts, body) = response.into_parts(); let body = stream::unfold( (body.into_data_stream(), counters), |(mut body, c)| async move { observe(c.clone(), body.next()) .await .map(|chunk| (chunk, (body, c))) }, ); Response::from_parts(parts, Body::from_stream(body)) } async fn frames(response: reqwest::Response) -> Vec { assert_eq!(response.status(), 200); let sse = response.headers()["content-type"] .to_str() .unwrap() .starts_with("text/event-stream"); let raw = tokio::time::timeout(Duration::from_secs(5), response.text()) .await .unwrap() .unwrap(); if sse { raw.lines() .filter_map(|line| { line.strip_prefix("data:") .map(|data| serde_json::from_str(data.trim()).unwrap()) }) .collect() } else if raw.is_empty() { vec![] } else { vec![serde_json::from_str(&raw).unwrap()] } } fn terminal(frames: &[Value], revision: &str, id: Value) -> Value { let last = frames.last().expect("terminal result"); assert_eq!(last["jsonrpc"], "2.0"); assert_eq!(last["id"], id); assert!(last.get("method").is_none()); assert!(last.get("error").is_none()); assert_eq!(last["result"]["isError"], false); assert_eq!( last["result"]["structuredContent"], json!({"id":"lead_progress"}) ); if revision == MODERN_REVISION { assert_eq!(last["result"]["resultType"], "complete"); } last["result"].clone() } async fn progress_control(revision: &str) -> usize { let h = Endpoint::started().await; let session = h.session(revision).await; // Establish the unchanged successful execution independently of any notification/marker. h.gate.add_permits(1); let plain = frames( h.call( revision, session.as_deref(), json!(51), None, "application/json", ) .send() .await .unwrap(), ) .await; assert_eq!(plain.len(), 1); let expected = terminal(&plain, revision, json!(51)); assert_eq!(h.counters.sdk_progress_notification(), 0); let mut sdk_positive = usize::MAX; for token in [ json!("opaque-token"), json!(-7), json!(1.5), json!(1.0), json!(-0.0), json!(u64::MAX), ] { let before = h.counters.sdk_progress_notification(); h.gate.add_permits(1); let reply = h .call( revision, session.as_deref(), json!(51), Some(token.clone()), "application/json, text/event-stream", ) .send() .await .unwrap(); assert!( reply.headers()["content-type"] .to_str() .unwrap() .starts_with("text/event-stream") ); let reply = frames(reply).await; assert_eq!(reply.len(), 4, "three bounded real steps and one terminal"); for (index, message) in [ "tool_resolved", "authorization_resolved", "execution_dispatched", ] .iter() .enumerate() { let expected_frame = json!({"jsonrpc":"2.0","method":"notifications/progress","params":{ "progressToken":token,"progress":index+1,"message":message}}); // Stringify too: float-form tokens must not silently become integers/strings. assert_eq!(reply[index].to_string(), expected_frame.to_string()); assert!(reply[index]["params"]["progress"].as_u64().is_some()); } assert_eq!(terminal(&reply, revision, json!(51)), expected); sdk_positive = sdk_positive.min(h.counters.sdk_progress_notification() - before); } for token in [ None, Some(json!(null)), Some(json!(true)), Some(json!({})), Some(json!([])), Some(json!("")), Some(json!("bad\ntoken")), Some(json!("x".repeat(129))), ] { h.gate.add_permits(1); let before = h.counters.sdk_progress_notification(); let reply = frames( h.call( revision, session.as_deref(), json!(51), token, "text/event-stream", ) .send() .await .unwrap(), ) .await; assert_eq!(reply.len(), 1, "invalid/absent token is silent"); assert_eq!(terminal(&reply, revision, json!(51)), expected); assert_eq!(h.counters.sdk_progress_notification(), before); } h.gate.add_permits(1); let before = h.counters.sdk_progress_notification(); let reply = frames( h.call( revision, session.as_deref(), json!(51), Some(json!(u64::MAX)), "application/json", ) .send() .await .unwrap(), ) .await; assert_eq!(reply.len(), 1, "no SSE means no progress"); assert_eq!(terminal(&reply, revision, json!(51)), expected); assert_eq!(h.counters.sdk_progress_notification(), before); eprintln!( "existing GREEN progress HTTP {revision}: exact token forms, bounded integer steps, unchanged result and silent negatives; minimum per-token SDK delta={sdk_positive}" ); sdk_positive } async fn cancel_control(with_meta: bool) -> usize { let h = Endpoint::started().await; let session = h.session(LEGACY_REVISION).await.unwrap(); let foreign = h.session(LEGACY_REVISION).await.unwrap(); let request = h .call( LEGACY_REVISION, Some(&session), json!(u64::MAX), Some(json!("cancel-token")), "text/event-stream", ) .header("x-request-id", "progress-cancel-owner"); let mut call = tokio::spawn(async move { frames(request.send().await.unwrap()).await }); h.wait_started(1).await; // All no-ops target this active call while its upstream response is held, not a completed call. for params in [ json!({"requestId":u64::MAX.to_string()}), json!({"requestId":999}), json!({}), json!({"requestId":null}), json!({"requestId":true}), json!({"requestId":[]}), json!({"requestId":{}}), ] { h.cancel(&h.key, &session, params).await; } eprintln!("cancel diagnostic: malformed/unknown/lookalike controls passed"); h.cancel(&h.other_key, &session, json!({"requestId":u64::MAX})) .await; h.cancel(&h.key, &foreign, json!({"requestId":u64::MAX})) .await; eprintln!("cancel diagnostic: foreign ownership controls passed"); assert!( tokio::time::timeout(Duration::from_millis(100), &mut call) .await .is_err(), "no-op targets must leave the owned call running" ); // Now let exactly that call finish: this proves no-op, rather than just delayed cancellation. h.gate.add_permits(1); let reply = call.await.unwrap(); terminal(&reply, LEGACY_REVISION, json!(u64::MAX)); let history = h.history("progress-cancel-owner").await; assert_eq!(history.len(), 1); assert_eq!(history[0].status, crank_core::InvocationStatus::Ok); h.cancel(&h.key, &session, json!({"requestId":u64::MAX})) .await; assert_eq!( h.history("progress-cancel-owner").await.len(), 1, "late cancel adds no outcome" ); let request = h .call( LEGACY_REVISION, Some(&session), json!(u64::MAX), Some(json!("cancel-token")), "text/event-stream", ) .header("x-request-id", "progress-cancel-stop"); let call = tokio::spawn(async move { frames(request.send().await.unwrap()).await }); h.wait_started(2).await; let before = h.counters.sdk_cancelled_params(); let mut params = json!({"requestId":u64::MAX,"reason":42,"unknown":{"nested":true}}); if with_meta { params["_meta"] = json!({}); } h.cancel(&h.key, &session, params).await; let delta = h.counters.sdk_cancelled_params() - before; let reply = tokio::time::timeout(Duration::from_secs(1), call) .await .expect("cancel releases call while upstream is still held") .unwrap(); assert_eq!(reply.len(), 3); assert!( reply .iter() .all(|f| f["method"] == "notifications/progress"), "no false terminal result" ); assert!(h.history("progress-cancel-stop").await.is_empty()); // Releasing an abandoned upstream cannot turn the cancelled execution into completed history. h.gate.add_permits(2); let reply = frames( h.call( LEGACY_REVISION, Some(&session), json!(u64::MAX), None, "application/json", ) .send() .await .unwrap(), ) .await; terminal(&reply, LEGACY_REVISION, json!(u64::MAX)); assert!(h.history("progress-cancel-stop").await.is_empty()); assert_eq!( h.started.load(std::sync::atomic::Ordering::SeqCst), 3, "no automatic write retry" ); eprintln!( "existing GREEN cancel HTTP legacy: active no-ops, numeric owner stop with ignored fields, released/reused id and no false history; SDK delta={delta}" ); delta } #[tokio::test] async fn rmcp_progress_cancel_wire_legacy() { progress_control(LEGACY_REVISION).await; } #[tokio::test] async fn rmcp_progress_cancel_wire_modern() { progress_control(MODERN_REVISION).await; } #[tokio::test] async fn rmcp_progress_cancel_wire_cancellation() { cancel_control(false).await; } #[tokio::test] async fn rmcp_progress_cancel_sdk_legacy() { assert!( progress_control(LEGACY_REVISION).await > 0, "missing SDK progress serialization after successful HTTP controls" ); } #[tokio::test] async fn rmcp_progress_cancel_sdk_modern() { assert!( progress_control(MODERN_REVISION).await > 0, "missing SDK progress serialization after successful HTTP controls" ); } #[tokio::test] async fn rmcp_progress_cancel_sdk_cancellation() { assert!( cancel_control(false).await > 0, "missing SDK cancelled params decode after successful HTTP stop controls" ); } #[tokio::test] async fn rmcp_progress_cancel_wire_modern_stream_close() { let h = Endpoint::started().await; let response = h .call( MODERN_REVISION, None, json!(52), Some(json!("disconnect")), "text/event-stream", ) .header("x-request-id", "progress-modern-stop") .send() .await .unwrap(); assert_eq!(response.status(), 200); h.wait_started(1).await; drop(response); tokio::time::sleep(Duration::from_millis(250)).await; // Match the existing lifecycle grace; an un-stopped future would complete after gate release. h.gate.add_permits(2); tokio::time::sleep(Duration::from_millis(2500)).await; assert!( h.history("progress-modern-stop").await.is_empty(), "closed stream must not reach completed history" ); let reply = frames( h.call(MODERN_REVISION, None, json!(52), None, "application/json") .send() .await .unwrap(), ) .await; terminal(&reply, MODERN_REVISION, json!(52)); assert_eq!( h.started.load(std::sync::atomic::Ordering::SeqCst), 2, "no retry after disconnect" ); assert!(h.history("progress-modern-stop").await.is_empty()); } #[tokio::test] async fn rmcp_progress_cancel_admitted_meta_cancellation() { assert!(cancel_control(true).await > 0); } #[tokio::test] async fn rmcp_progress_cancel_malformed_meta_rejected_before_decode() { let h = Endpoint::started().await; let session = h.session(LEGACY_REVISION).await.unwrap(); let request = h .call( LEGACY_REVISION, Some(&session), json!(u64::MAX), Some(json!("meta-boundary")), "text/event-stream", ) .header("x-request-id", "progress-meta-rejected"); let mut call = tokio::spawn(async move { frames(request.send().await.unwrap()).await }); h.wait_started(1).await; let before = h.counters.sdk_cancelled_params(); let response = h .request( LEGACY_REVISION, Some(&session), &h.key, "application/json", json!({"jsonrpc":"2.0","method":"notifications/cancelled","params":{ "requestId":u64::MAX,"reason":42,"_meta":[],"unknown":{"nested":true}}}), ) .send() .await .unwrap(); assert_eq!(response.status(), 400); let error = json_body(response).await; assert_eq!(error["error"]["code"], -32020); assert_eq!(error["error"]["message"], "protocol identity mismatch"); assert_eq!( error["error"]["data"]["details"], "request _meta must be an object" ); assert_eq!(h.counters.sdk_cancelled_params(), before); assert!( tokio::time::timeout(Duration::from_millis(100), &mut call) .await .is_err() ); h.gate.add_permits(1); let reply = call.await.unwrap(); terminal(&reply, LEGACY_REVISION, json!(u64::MAX)); let history = h.history("progress-meta-rejected").await; assert_eq!(history.len(), 1); assert_eq!(history[0].status, crank_core::InvocationStatus::Ok); assert_eq!(h.started.load(std::sync::atomic::Ordering::SeqCst), 1); assert_eq!(h.counters.sdk_cancelled_params(), before); } #[tokio::test] async fn rmcp_progress_cancel_observer_scope_control() { use super::{sdk_cancelled_params_decoded, sdk_progress_notification_serialized}; let a = Arc::new(CounterSet::default()); let b = Arc::new(CounterSet::default()); sdk_cancelled_params_decoded(); sdk_progress_notification_serialized(); assert_eq!(a.sdk_cancelled_params(), 0); tokio::join!( observe(a.clone(), async { sdk_cancelled_params_decoded(); }), observe(b.clone(), async { sdk_progress_notification_serialized(); }) ); assert_eq!( [a.sdk_cancelled_params(), a.sdk_progress_notification()], [1, 0] ); assert_eq!( [b.sdk_cancelled_params(), b.sdk_progress_notification()], [0, 1] ); let body = Body::from_stream(stream::once(async { sdk_progress_notification_serialized(); Ok::<_, std::convert::Infallible>("data: terminal\n\n") })); let response = observe_body(Response::new(body), a.clone()); assert_eq!(a.sdk_progress_notification(), 0); axum::body::to_bytes(response.into_body(), 100) .await .unwrap(); assert_eq!(a.sdk_progress_notification(), 1); assert_eq!(b.sdk_progress_notification(), 1); }