#![allow(dead_code, unused_imports)] //! Story 3.1 ATDD (AT-04/06/07/10/11): mixed-era isolation, honest bounded counters and causal //! capture. //! //! What this module observes, and what it deliberately does NOT observe: //! //! * **session-store operations** - a test-only `TransportSessionStore` counts `get`/`create`/ //! `mark_initialized` calls. These are *store* operations, not service/dispatch entries: a request //! can enter the Tools/approval path and finish (approval refusal, invalid params, catalog refusal, //! pagination) **before** any outbound call, so no counter here is renamed into a "service entry" //! or "dispatch" counter. //! * **upstream outbound calls** - a held, counted loopback upstream signals the moment a //! tool-execution request actually arrives; it is an *outbound* counter for the same reason. //! * **in-processing arrival markers** - the barrier is released only after (a) the legacy handler has //! called the session store from `require_initialized_session` (i.e. after admission and era //! selection) and (b) the modern handler's tool-execution request has physically reached the //! upstream. A client-side "request sent" signal is a precondition only and never releases the //! barrier; there is no sleep-only overlap and no stress profile. //! //! Barrier discipline (TL ATDD round-1 R1): //! //! * a held handler waits **until the explicit coordinated release** - there is no internal //! `timeout`-and-continue branch that could let one era leave the gate before the other arrives, //! and no stored permit can turn a later phase into a false overlap (the release flag itself is //! re-checked, so a stale permit simply exits the loop); //! * the *test* owns the bound: `tokio::time::timeout` wraps the arrival wait, and the timeout is an //! error, not a continuation of a success path; //! * on any error the failure path releases both gates first, then bounded-joins or cancels the //! request tasks, aborts the test's own server tasks, and only then fails naming the marker that //! never arrived (`OverlapRun::cleanup`); the same cleanup also runs from `Drop`, so an assertion //! failure cannot leak a parked handler or a live test server; //! * `parked_waiters()` proves that both handlers really were held at the same time *before* the //! release, and returns to zero afterwards. //! //! Scoped output (TL ATDD round-1 R3): each side is a **distinct Agent with its own catalog and its //! own canary email**, and the counted upstream echoes the canary into the tool result. A swapped //! legacy/modern result - or a crossed Agent/catalog scope - therefore fails the exact response //! assertions instead of passing on a shared fixed id. //! //! Statements that the available seams genuinely cannot prove - "the rejected request did not enter //! any other handler" (AT-06) and "no residual state is left on the short rejection branches" //! (AT-11) - stay **NOT-PROVEN** here: they need the BUILD-only semantic era-adapter/service-entry //! markers inside `crates/crank-community-mcp`. This module never weakens an assertion to satisfy the //! current code, and never claims those two statements. use super::common::*; use axum::{Json, Router, extract::State, http::header, routing::post}; use serde_json::{Value, json}; use std::collections::BTreeMap; use std::time::Duration; use self::harness::{ LEGACY_CANARY, LEGACY_REVISION, LEGACY_TOOL, META_CLIENT_CAPABILITIES, META_CLIENT_INFO, META_PROTOCOL_VERSION, MODERN_CANARY, MODERN_REVISION, MODERN_TOOL, OverlapRun, REAP_TIMEOUT, canary_id, harness, harness_with_two_agents, header_refs, }; mod harness; fn modern_meta(revision: &str) -> Value { json!({ META_PROTOCOL_VERSION: revision, META_CLIENT_CAPABILITIES: {}, META_CLIENT_INFO: { "name": "crank-atdd-era-client", "version": "0.1.0" } }) } fn legacy_tool_call(id: u64, tool_name: &str, email: &str) -> Value { json!({ "jsonrpc": "2.0", "id": id, "method": "tools/call", "params": { "name": tool_name, "arguments": { "email": email } } }) } fn modern_tool_call(id: u64, tool_name: &str, email: &str) -> Value { json!({ "jsonrpc": "2.0", "id": id, "method": "tools/call", "params": { "_meta": modern_meta(MODERN_REVISION), "name": tool_name, "arguments": { "email": email } } }) } fn legacy_headers(session_id: &str) -> Vec<(&'static str, String)> { vec![ ("MCP-Protocol-Version", LEGACY_REVISION.to_owned()), ("MCP-Session-Id", session_id.to_owned()), ] } fn modern_headers(tool_name: &str) -> Vec<(&'static str, String)> { vec![ ("MCP-Protocol-Version", MODERN_REVISION.to_owned()), ("Mcp-Method", "tools/call".to_owned()), ("Mcp-Name", tool_name.to_owned()), ] } /// Bounded response read: the overlap test must not be able to hang inside a body read. async fn bounded_json_body(response: reqwest::Response) -> (Value, String) { let status = response.status(); let body = match tokio::time::timeout(REAP_TIMEOUT, response.text()).await { Ok(Ok(body)) => body, Ok(Err(error)) => panic!("reading the response body failed (status {status}): {error}"), Err(_elapsed) => { panic!("bounded {REAP_TIMEOUT:?} response-body read expired (status {status})") } }; let parsed = serde_json::from_str(&body).unwrap_or_else(|error| { panic!("expected a JSON-RPC body, got status {status} body {body:?}: {error}") }); (parsed, body) } // --------------------------------------------------------------------------------------------- // AT-04: the modern stateless era performs no session-store operation at all. // --------------------------------------------------------------------------------------------- #[tokio::test] async fn era_isolation_modern_requests_never_touch_the_session_store() { let harness = harness("era-modern-only").await; let side = harness.primary(); assert_eq!( harness.counters.snapshot(), (0, 0, 0), "no session store operation may happen before any legacy request" ); // `server/discover` is mandatory for the modern era; `tools/list` and `tools/call` follow on // separate, independent stateless requests (no priming, no session). let discover = post_jsonrpc_with_headers( &harness.client, &harness.mcp_url, &harness.api_key, &header_refs(&[ ("MCP-Protocol-Version", MODERN_REVISION.to_owned()), ("Mcp-Method", "server/discover".to_owned()), ]), json!({ "jsonrpc": "2.0", "id": 11, "method": "server/discover", "params": { "_meta": modern_meta(MODERN_REVISION) } }), ) .await; assert_eq!(discover.status().as_u16(), 200); assert!(discover.headers().get("MCP-Session-Id").is_none()); let listed = post_jsonrpc_with_headers( &harness.client, &harness.mcp_url, &harness.api_key, &header_refs(&[ ("MCP-Protocol-Version", MODERN_REVISION.to_owned()), ("Mcp-Method", "tools/list".to_owned()), ]), json!({ "jsonrpc": "2.0", "id": 12, "method": "tools/list", "params": { "_meta": modern_meta(MODERN_REVISION) } }), ) .await; assert_eq!(listed.status().as_u16(), 200); let called = post_jsonrpc_with_headers( &harness.client, &harness.mcp_url, &harness.api_key, &header_refs(&modern_headers(&side.tool_name)), modern_tool_call(13, &side.tool_name, MODERN_CANARY), ) .await; assert_eq!(called.status().as_u16(), 200); let (called_body, _) = bounded_json_body(called).await; assert!( called_body["error"].is_null(), "a valid modern tools/call must succeed, got {called_body}" ); assert_eq!( called_body["result"]["structuredContent"]["id"], canary_id(MODERN_CANARY), "the modern response must carry the canary this side sent" ); assert_eq!( harness.counters.snapshot(), (0, 0, 0), "the modern stateless path must not create, read or initialize any session; store operations \ are not service/dispatch counters, but on this path zero is the honest expected value" ); assert_eq!( harness.upstream.arrivals(), 1, "exactly one outbound tool execution" ); } // --------------------------------------------------------------------------------------------- // AT-07 / AT-06: overlapping legacy and modern tool calls stay scoped, released only by real // in-processing arrival markers. // --------------------------------------------------------------------------------------------- #[tokio::test] async fn era_isolation_overlapping_legacy_and_modern_calls_stay_scoped() { // Two Agents: the legacy side and the modern side have different catalogs, so the Agent/catalog // scope is part of what this test checks. let harness = harness_with_two_agents("era-overlap", "era-overlap-modern").await; let legacy_side = harness.primary(); let modern_side = harness.alternate(); let session = initialize_session(&harness.client, &harness.mcp_url, &harness.api_key).await; let baseline = harness.counters.snapshot(); let arrivals_baseline = harness.upstream.arrivals(); harness.store.hold(&session); harness.upstream.hold(); let mut run = OverlapRun::new(&harness); // Precondition only: the legacy request is *sent*. This never releases the barrier. run.spawn( &legacy_side, legacy_headers(&session), legacy_tool_call(21, &legacy_side.tool_name, LEGACY_CANARY), ); // In-processing marker (legacy era): the handler reached `require_initialized_session`. if let Err(timeout) = harness .store .await_arrival( "the legacy handler's post-admission session-store lookup", run.deadline, ) .await { run.fail(timeout).await; } run.spawn( &modern_side, modern_headers(&modern_side.tool_name), modern_tool_call(22, &modern_side.tool_name, MODERN_CANARY), ); // In-processing marker (both eras): the modern handler's tool execution reached the upstream. if let Err(timeout) = harness .upstream .await_arrival( "the modern tool-execution request reaching the counted upstream", run.deadline, ) .await { run.fail(timeout).await; } // Both markers observed: prove the REAL simultaneous hold *before* releasing the gates. A false // overlap (one side already past the gate) would show up as a zero parked count or a finished // request. assert_eq!( harness.store.parked_waiters(), 1, "the legacy handler must still be parked inside its post-admission store lookup" ); assert_eq!( harness.upstream.parked_waiters(), 1, "the modern tool execution must still be parked at the counted upstream" ); assert!( !run.is_finished(0) && !run.is_finished(1), "both requests must still be in processing when the barrier is released" ); // Both arrivals observed: release the gates, join, then collect the results. harness.store.release(); harness.upstream.release(); assert_eq!( (harness.store.is_holding(), harness.upstream.is_holding()), (false, false), "the coordinated release must open both gates" ); let legacy_response = run.join_bounded(0, "legacy").await; let modern_response = run.join_bounded(1, "modern").await; assert_eq!( ( harness.store.parked_waiters(), harness.upstream.parked_waiters() ), (0, 0), "no handler may stay parked after the release" ); assert_eq!(legacy_response.status().as_u16(), 200); assert_eq!(modern_response.status().as_u16(), 200); let (legacy_body, legacy_raw) = bounded_json_body(legacy_response).await; let (modern_body, modern_raw) = bounded_json_body(modern_response).await; assert_eq!(legacy_body["jsonrpc"], "2.0"); assert_eq!(modern_body["jsonrpc"], "2.0"); assert_eq!( legacy_body["id"], 21, "legacy correlation must not cross eras" ); assert_eq!( modern_body["id"], 22, "modern correlation must not cross eras" ); assert!( legacy_body["error"].is_null(), "legacy call must succeed, got {legacy_body}" ); assert!( modern_body["error"].is_null(), "modern call must succeed, got {modern_body}" ); // Scoped output: each era's response carries the canary of ITS OWN Agent/catalog call and never // the other side's. A swapped result would satisfy the id/resultType checks but fail here. assert_eq!( legacy_body["result"]["structuredContent"]["id"], canary_id(LEGACY_CANARY), "the legacy response must carry the legacy side's scoped canary, got {legacy_body}" ); assert_eq!( modern_body["result"]["structuredContent"]["id"], canary_id(MODERN_CANARY), "the modern response must carry the modern side's scoped canary, got {modern_body}" ); assert!( !legacy_raw.contains(MODERN_CANARY), "the legacy response must not contain the modern side's canary: {legacy_raw}" ); assert!( !modern_raw.contains(LEGACY_CANARY), "the modern response must not contain the legacy side's canary: {modern_raw}" ); assert!( legacy_body["result"].get("resultType").is_none(), "the legacy era must not receive modern-only result members, got {legacy_body}" ); assert_eq!( modern_body["result"]["resultType"], "complete", "the modern era keeps its own result projection, got {modern_body}" ); // Store/upstream observables must be measured BEFORE the Agent/catalog scope probes below, which // add their own (legacy) store lookups. let after = harness.counters.snapshot(); assert_eq!( (after.0, after.2), (baseline.0, baseline.2), "only the legacy request may consult the store, and it must not create or initialize a session" ); assert_eq!( after.1 - baseline.1, 2, "one legacy tools/call performs exactly the two store lookups (carrier lookup before era \ resolution plus require_initialized_session); the modern request performs none" ); assert_eq!( harness.upstream.arrivals() - arrivals_baseline, 2, "each era performs exactly one outbound tool execution" ); // Agent/catalog scope: each Agent advertises exactly its own tool and never the other side's. let legacy_tools = post_jsonrpc_with_headers( &harness.client, &legacy_side.mcp_url, &legacy_side.api_key, &header_refs(&legacy_headers(&session)), json!({ "jsonrpc": "2.0", "id": 23, "method": "tools/list", "params": {} }), ) .await; assert_eq!(legacy_tools.status().as_u16(), 200); let (legacy_tools_body, _legacy_tools_raw) = bounded_json_body(legacy_tools).await; let legacy_names: Vec = legacy_tools_body["result"]["tools"] .as_array() .expect("tools/list returns an array") .iter() .map(|tool| tool["name"].as_str().unwrap_or_default().to_owned()) .collect(); assert_eq!( legacy_names, vec![LEGACY_TOOL.to_owned()], "the legacy Agent's catalog must be exactly its own tool, got {legacy_tools_body}" ); let modern_tools = post_jsonrpc_with_headers( &harness.client, &modern_side.mcp_url, &modern_side.api_key, &header_refs(&[ ("MCP-Protocol-Version", MODERN_REVISION.to_owned()), ("Mcp-Method", "tools/list".to_owned()), ]), json!({ "jsonrpc": "2.0", "id": 24, "method": "tools/list", "params": { "_meta": modern_meta(MODERN_REVISION) } }), ) .await; assert_eq!(modern_tools.status().as_u16(), 200); let (modern_tools_body, _modern_tools_raw) = bounded_json_body(modern_tools).await; let modern_names: Vec = modern_tools_body["result"]["tools"] .as_array() .expect("tools/list returns an array") .iter() .map(|tool| tool["name"].as_str().unwrap_or_default().to_owned()) .collect(); assert_eq!( modern_names, vec![MODERN_TOOL.to_owned()], "the modern Agent's catalog must be exactly its own tool, got {modern_tools_body}" ); } // --------------------------------------------------------------------------------------------- // R1 failure path: a missing in-processing marker must release the gates, cancel the run's own // tasks and fail naming the marker - bounded, deterministic and without sleep-only waits. // --------------------------------------------------------------------------------------------- #[tokio::test] async fn era_isolation_marker_timeout_path_releases_the_gates_and_cancels_its_own_tasks() { let harness = harness("era-timeout-path").await; let side = harness.primary(); let session = initialize_session(&harness.client, &harness.mcp_url, &harness.api_key).await; // The store gate is armed for a session id that no request will ever present, so the legacy // in-processing marker cannot arrive; the upstream gate is armed normally, so the request really // is held in processing while the bounded wait expires. harness.store.hold("session-that-no-request-uses"); harness.upstream.hold(); let mut run = OverlapRun::with_deadline(&harness, Duration::from_millis(250)); run.spawn( &side, legacy_headers(&session), legacy_tool_call(51, &side.tool_name, LEGACY_CANARY), ); let timeout = harness .store .await_arrival("the marker that never arrives", run.deadline) .await .expect_err("the marker cannot arrive for a session id no request uses"); assert!( timeout.describe().contains("the marker that never arrives"), "the failure must name the missing marker: {}", timeout.describe() ); assert!( harness.upstream.parked_waiters() >= 1, "the request must be held in processing" ); assert_eq!( harness.store.parked_waiters(), 0, "the gate armed for an unused session id must not have parked any handler" ); // The failure path releases both gates first, then bounded-joins/cancels every task it started. let responses = run.cleanup().await; assert_eq!( (harness.store.is_holding(), harness.upstream.is_holding()), (false, false), "the failure path must release both gates" ); assert_eq!( ( harness.store.parked_waiters(), harness.upstream.parked_waiters() ), (0, 0), "no handler may stay parked after the failure-path cleanup" ); assert_eq!( (run.joined, run.cancelled), (1, 0), "the started request must be joined in bounded time (no leak, no unbounded join)" ); let (body, raw) = bounded_json_body(responses.into_iter().next().expect("one joined response")).await; assert!( body["error"].is_null(), "releasing the gate must let the held request finish normally, got {body}" ); assert_eq!( body["result"]["structuredContent"]["id"], canary_id(LEGACY_CANARY) ); assert!(!raw.contains(MODERN_CANARY)); } // --------------------------------------------------------------------------------------------- // AT-11: positive control -> one-factor mutation -> valid follow-up on the same session. // --------------------------------------------------------------------------------------------- #[tokio::test] async fn era_isolation_reject_then_valid_follow_up_keeps_the_legacy_session() { let harness = harness("era-reject-follow-up").await; let side = harness.primary(); let session = initialize_session(&harness.client, &harness.mcp_url, &harness.api_key).await; // 1. Positive control of EXACTLY the shape the mutation uses: a stateless modern tools/call with // no session carrier. It must succeed on the real endpoint (existing GREEN). let control = post_jsonrpc_with_headers( &harness.client, &harness.mcp_url, &harness.api_key, &header_refs(&modern_headers(&side.tool_name)), modern_tool_call(31, &side.tool_name, MODERN_CANARY), ) .await; assert_eq!( control.status().as_u16(), 200, "the positive control must pass" ); let (control_body, _) = bounded_json_body(control).await; assert!(control_body["error"].is_null(), "got {control_body}"); assert_eq!(control_body["jsonrpc"], "2.0"); assert_eq!(control_body["id"], 31); assert_eq!( control_body["result"]["structuredContent"]["id"], canary_id(MODERN_CANARY), "the control must return the canary this side sent, got {control_body}" ); let baseline = harness.counters.snapshot(); let arrivals_baseline = harness.upstream.arrivals(); // 2. One-factor mutation: the SAME modern request (same body, same identity headers, same id, // same email) with exactly one factor added - the legacy session carrier. let mut mutated_headers = modern_headers(&side.tool_name); mutated_headers.push(("MCP-Session-Id", session.clone())); let mutated = post_jsonrpc_with_headers( &harness.client, &harness.mcp_url, &harness.api_key, &header_refs(&mutated_headers), modern_tool_call(31, &side.tool_name, MODERN_CANARY), ) .await; assert_eq!( mutated.status().as_u16(), 400, "a modern identity carrying a session carrier is an era-correct rejection" ); let (mutated_body, _) = bounded_json_body(mutated).await; assert_eq!(mutated_body["jsonrpc"], "2.0"); assert_eq!( mutated_body["id"], 31, "the rejection must keep the request correlation" ); assert_eq!( mutated_body["error"]["code"], -32020, "the modern carrier conflict keeps its era-correct code, got {mutated_body}" ); assert!( mutated_body.get("result").is_none(), "a rejected request must not return a result, got {mutated_body}" ); // The conflict is decided before any session lookup, any rate-limit accounting and any dispatch. // NOT-PROVEN (AT-06/AT-11): that the rejected request "did not enter any other handler" and left // "no residual state" cannot be proven with the seams available here; that needs the BUILD-only // semantic era-adapter/service-entry markers. Only store/outbound observables are asserted. assert_eq!( harness.counters.snapshot(), baseline, "a pre-admission rejection must not perform any session-store operation" ); assert_eq!( harness.upstream.arrivals(), arrivals_baseline, "a pre-admission rejection must not reach the upstream" ); // 3. Valid follow-ups: the SAME legacy session is still served, and the stateless modern request // of the positive-control shape still succeeds. Each carries its own scoped canary. let follow_up = post_jsonrpc_with_headers( &harness.client, &harness.mcp_url, &harness.api_key, &header_refs(&legacy_headers(&session)), legacy_tool_call(33, &side.tool_name, LEGACY_CANARY), ) .await; assert_eq!( follow_up.status().as_u16(), 200, "the same legacy session must still be served" ); let (follow_up_body, follow_up_raw) = bounded_json_body(follow_up).await; assert!(follow_up_body["error"].is_null(), "got {follow_up_body}"); assert_eq!(follow_up_body["jsonrpc"], "2.0"); assert_eq!(follow_up_body["id"], 33); assert_eq!( follow_up_body["result"]["structuredContent"]["id"], canary_id(LEGACY_CANARY), "the legacy follow-up must return the legacy side's canary, got {follow_up_body}" ); assert!(!follow_up_raw.contains(MODERN_CANARY)); let modern_follow_up = post_jsonrpc_with_headers( &harness.client, &harness.mcp_url, &harness.api_key, &header_refs(&modern_headers(&side.tool_name)), modern_tool_call(34, &side.tool_name, MODERN_CANARY), ) .await; assert_eq!(modern_follow_up.status().as_u16(), 200); let (modern_body, modern_raw) = bounded_json_body(modern_follow_up).await; assert!(modern_body["error"].is_null(), "got {modern_body}"); assert_eq!(modern_body["id"], 34); assert_eq!( modern_body["result"]["structuredContent"]["id"], canary_id(MODERN_CANARY), "the modern follow-up must return the modern side's canary, got {modern_body}" ); assert!(!modern_raw.contains(LEGACY_CANARY)); assert_eq!(modern_body["result"]["resultType"], "complete"); let after = harness.counters.snapshot(); assert_eq!( after.0 - baseline.0, 0, "the follow-ups must not mint a new session" ); assert_eq!( after.1 - baseline.1, 2, "only the legacy follow-up consults the store (twice); the independent modern request does not" ); assert_eq!(after.2 - baseline.2, 0); assert_eq!( harness.upstream.arrivals() - arrivals_baseline, 2, "exactly one outbound call per follow-up" ); } // --------------------------------------------------------------------------------------------- // AT-10: causal capture - a minimal legacy client receives no undeclared server->client message. // --------------------------------------------------------------------------------------------- #[tokio::test] async fn era_isolation_minimal_client_receives_no_undeclared_server_to_client_message() { let harness = harness("era-minimal-client").await; let session = initialize_session(&harness.client, &harness.mcp_url, &harness.api_key).await; // Capture happens strictly after the response future completes (no sleep, no polling); the // minimal client advertises no capabilities at all. let response = post_jsonrpc_with_headers( &harness.client, &harness.mcp_url, &harness.api_key, &header_refs(&legacy_headers(&session)), json!({ "jsonrpc": "2.0", "id": 41, "method": "tools/list", "params": {} }), ) .await; assert_eq!(response.status().as_u16(), 200); let content_type = response .headers() .get(header::CONTENT_TYPE) .and_then(|value| value.to_str().ok()) .unwrap_or_default() .to_owned(); let captured_headers: BTreeMap = response .headers() .iter() .map(|(name, value)| { ( name.as_str().to_ascii_lowercase(), value.to_str().unwrap_or_default().to_owned(), ) }) .collect(); let (body, _raw) = bounded_json_body(response).await; // A single JSON-RPC answer, not a stream, and no extra server->client notification/method. assert!( content_type.starts_with("application/json"), "a minimal client asked for JSON and must receive JSON, got {content_type:?}" ); assert!( body.get("method").is_none(), "no server->client method may be emitted: {body}" ); assert!(body.get("id").is_some() && body.get("jsonrpc").is_some()); assert!( body["error"].is_null(), "the minimal client's tools/list must succeed, got {body}" ); assert_eq!(body["result"]["tools"][0]["name"], harness.tool_name); // Current pagination only: no new opaque cursor contract is introduced here (that stays 3.2). assert!( body["result"].get("nextCursor").is_none(), "a single-page catalog must not invent a cursor, got {body}" ); assert!( !captured_headers.contains_key("mcp-session-id"), "only initialize mints a session header; the captured headers were {captured_headers:?}" ); // A legacy request that never asks for Tools does not reach the upstream either. assert_eq!( harness.upstream.arrivals(), 0, "tools/list performs no outbound tool execution" ); }