Files
crank/apps/mcp-server/tests/integration/era_isolation/harness.rs
T
bsodfather 54ce770682
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
2026-10-25 09:08:22 +00:00

646 lines
22 KiB
Rust

//! Instrumented harness of `era_isolation`: counted session store, arrival barriers, held upstream,
//! test-server lifecycle and cleanup, plus the fixture constants the scenarios share.
//!
//! Moved verbatim out of `era_isolation.rs` (Story 3.6, kanban t_987bf309). Expectations, timeouts,
//! the Drop/cleanup order and every counter are unchanged; the scenario module reaches these items
//! through `super::harness`.
use super::super::common::*;
use async_trait::async_trait;
use axum::{Json, Router, extract::State, http::header, routing::post};
use crank_community_mcp::session::{
InMemorySessionStore, SessionState, SessionStoreError, SharedSessionStore,
TransportSessionStore,
};
use crank_core::PlatformApiKeyScope;
use crank_registry::{PostgresRegistry, PublishRequest};
use serde_json::{Value, json};
use std::sync::{
Arc, Mutex,
atomic::{AtomicBool, AtomicU64, Ordering},
};
use std::time::Duration;
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
use tokio::net::TcpListener;
use tokio::sync::Notify;
use tokio::task::JoinHandle;
pub(super) const MODERN_REVISION: &str = "2026-07-28";
pub(super) const LEGACY_REVISION: &str = "2025-11-25";
pub(super) const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
pub(super) const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
pub(super) const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
/// Bound on waiting for one in-processing arrival marker. The held handler itself has no bound: the
/// test bounds the wait and is responsible for releasing the gate on every path.
const MARKER_TIMEOUT: Duration = Duration::from_secs(5);
/// Bound on joining a request task after the gates were released, and on reading a response body.
pub(super) const REAP_TIMEOUT: Duration = Duration::from_secs(5);
/// The two sides are different Agents with different catalogs and different canary payloads, so a
/// crossed result cannot pass on a shared fixed id.
pub(super) const LEGACY_TOOL: &str = "crm_create_lead";
pub(super) const MODERN_TOOL: &str = "crm_create_lead_modern";
pub(super) const LEGACY_CANARY: &str = "legacy-canary@example.com";
pub(super) const MODERN_CANARY: &str = "modern-canary@example.com";
pub(super) fn canary_id(canary: &str) -> String {
format!("lead::{canary}")
}
/// A bounded wait that expired before the named in-processing marker arrived.
#[derive(Debug)]
pub(super) struct MarkerTimeout {
marker: &'static str,
deadline: Duration,
}
impl MarkerTimeout {
pub(super) fn describe(&self) -> String {
format!(
"bounded {:?} wait expired: {} never arrived",
self.deadline, self.marker
)
}
}
async fn await_notification(
notified: &Notify,
marker: &'static str,
deadline: Duration,
) -> Result<(), MarkerTimeout> {
if tokio::time::timeout(deadline, notified.notified())
.await
.is_ok()
{
Ok(())
} else {
Err(MarkerTimeout { marker, deadline })
}
}
// ---------------------------------------------------------------------------------------------
// Instrumented session store: counts store *operations* and can hold one session's `get`.
// ---------------------------------------------------------------------------------------------
#[derive(Default)]
pub(super) struct StoreCounters {
creates: AtomicU64,
gets: AtomicU64,
marks: AtomicU64,
}
impl StoreCounters {
pub(super) fn snapshot(&self) -> (u64, u64, u64) {
(
self.creates.load(Ordering::SeqCst),
self.gets.load(Ordering::SeqCst),
self.marks.load(Ordering::SeqCst),
)
}
}
pub(super) struct InstrumentedSessionStore {
inner: InMemorySessionStore,
counters: Arc<StoreCounters>,
holding: AtomicBool,
hold_session: Mutex<Option<String>>,
gets_for_held_session: AtomicU64,
/// Index of the `get` call for the held session that acts as the in-processing arrival marker.
/// `2` is deliberate: `mcp_post_response` performs its own session lookup for any request that
/// carries a session header **before** era resolution (`app.rs:866-895`), while the legacy
/// handler's `require_initialized_session` lookup happens **after** admission and inside the
/// legacy branch - only the latter proves that the legacy handler is in processing.
hold_on_get_number: AtomicU64,
/// Handlers currently parked inside the held `get`: proves that the legacy side really is held.
parked_waiters: AtomicU64,
arrived: Arc<Notify>,
released: Arc<Notify>,
}
impl InstrumentedSessionStore {
fn new() -> (Arc<Self>, Arc<StoreCounters>) {
let counters = Arc::new(StoreCounters::default());
let store = Arc::new(Self {
inner: InMemorySessionStore::default(),
counters: Arc::clone(&counters),
holding: AtomicBool::new(false),
hold_session: Mutex::new(None),
gets_for_held_session: AtomicU64::new(0),
hold_on_get_number: AtomicU64::new(2),
parked_waiters: AtomicU64::new(0),
arrived: Arc::new(Notify::new()),
released: Arc::new(Notify::new()),
});
(store, counters)
}
pub(super) fn hold(&self, session_id: &str) {
*self.hold_session.lock().unwrap() = Some(session_id.to_owned());
self.gets_for_held_session.store(0, Ordering::SeqCst);
self.holding.store(true, Ordering::SeqCst);
}
pub(super) fn release(&self) {
self.holding.store(false, Ordering::SeqCst);
// Leave a permit for a waiter that has not parked yet, then wake the parked ones. The gate
// flag (not the permit) is the source of truth, so a leftover permit cannot keep a handler
// inside the gate and cannot fake a later overlap.
self.released.notify_one();
self.released.notify_waiters();
}
pub(super) fn is_holding(&self) -> bool {
self.holding.load(Ordering::SeqCst)
}
pub(super) fn parked_waiters(&self) -> u64 {
self.parked_waiters.load(Ordering::SeqCst)
}
pub(super) async fn await_arrival(
&self,
marker: &'static str,
deadline: Duration,
) -> Result<(), MarkerTimeout> {
await_notification(&self.arrived, marker, deadline).await
}
async fn hold_if_needed(&self, session_id: &str) {
if !self.holding.load(Ordering::SeqCst) {
return;
}
let is_held = self.hold_session.lock().unwrap().as_deref() == Some(session_id);
if !is_held {
return;
}
let call_number = self.gets_for_held_session.fetch_add(1, Ordering::SeqCst) + 1;
if call_number != self.hold_on_get_number.load(Ordering::SeqCst) {
return;
}
self.parked_waiters.fetch_add(1, Ordering::SeqCst);
self.arrived.notify_one();
// Hold until the explicit coordinated release. There is deliberately no internal deadline:
// an internal timeout-and-continue could let this era proceed while the other era has not
// arrived yet, which is exactly the false overlap the barrier must not allow.
while self.holding.load(Ordering::SeqCst) {
self.released.notified().await;
}
self.parked_waiters.fetch_sub(1, Ordering::SeqCst);
}
}
#[async_trait]
impl TransportSessionStore for InstrumentedSessionStore {
async fn create(
&self,
protocol_version: &str,
workspace_slug: &str,
agent_slug: &str,
supports_elicitation: bool,
now: OffsetDateTime,
expires_at: Option<OffsetDateTime>,
) -> Result<String, SessionStoreError> {
self.counters.creates.fetch_add(1, Ordering::SeqCst);
self.inner
.create(
protocol_version,
workspace_slug,
agent_slug,
supports_elicitation,
now,
expires_at,
)
.await
}
async fn get(&self, session_id: &str) -> Result<Option<SessionState>, SessionStoreError> {
self.counters.gets.fetch_add(1, Ordering::SeqCst);
self.hold_if_needed(session_id).await;
self.inner.get(session_id).await
}
async fn mark_initialized(
&self,
session_id: &str,
now: OffsetDateTime,
) -> Result<bool, SessionStoreError> {
self.counters.marks.fetch_add(1, Ordering::SeqCst);
self.inner.mark_initialized(session_id, now).await
}
async fn delete(&self, session_id: &str) -> Result<bool, SessionStoreError> {
self.inner.delete(session_id).await
}
async fn cleanup_expired(&self, now: OffsetDateTime) -> Result<u64, SessionStoreError> {
self.inner.cleanup_expired(now).await
}
async fn active_count(&self, now: OffsetDateTime) -> Result<u64, SessionStoreError> {
self.inner.active_count(now).await
}
}
// ---------------------------------------------------------------------------------------------
// Held, counted loopback upstream: signals that a tool-execution request physically arrived and
// echoes a per-side canary back into the tool result.
// ---------------------------------------------------------------------------------------------
#[derive(Clone)]
pub(super) struct HeldUpstream {
arrivals: Arc<AtomicU64>,
holding: Arc<AtomicBool>,
parked_waiters: Arc<AtomicU64>,
arrived: Arc<Notify>,
released: Arc<Notify>,
}
impl HeldUpstream {
fn new() -> Self {
Self {
arrivals: Arc::new(AtomicU64::new(0)),
holding: Arc::new(AtomicBool::new(false)),
parked_waiters: Arc::new(AtomicU64::new(0)),
arrived: Arc::new(Notify::new()),
released: Arc::new(Notify::new()),
}
}
pub(super) fn hold(&self) {
self.holding.store(true, Ordering::SeqCst);
}
pub(super) fn release(&self) {
self.holding.store(false, Ordering::SeqCst);
self.released.notify_one();
self.released.notify_waiters();
}
pub(super) fn is_holding(&self) -> bool {
self.holding.load(Ordering::SeqCst)
}
pub(super) fn parked_waiters(&self) -> u64 {
self.parked_waiters.load(Ordering::SeqCst)
}
pub(super) async fn await_arrival(
&self,
marker: &'static str,
deadline: Duration,
) -> Result<(), MarkerTimeout> {
await_notification(&self.arrived, marker, deadline).await
}
pub(super) fn arrivals(&self) -> u64 {
self.arrivals.load(Ordering::SeqCst)
}
}
async fn held_create_lead(
State(upstream): State<HeldUpstream>,
Json(payload): Json<Value>,
) -> Json<Value> {
upstream.arrivals.fetch_add(1, Ordering::SeqCst);
upstream.parked_waiters.fetch_add(1, Ordering::SeqCst);
upstream.arrived.notify_one();
// Same discipline as the session-store gate: wait for the explicit release, never continue on an
// internal timeout (that would let this side finish before the other side's marker arrives).
while upstream.holding.load(Ordering::SeqCst) {
upstream.released.notified().await;
}
upstream.parked_waiters.fetch_sub(1, Ordering::SeqCst);
// Per-side scoped output: the canary the caller sent comes back inside the tool result, so a
// swapped or crossed result is visible in the response instead of hiding behind a fixed id.
let email = payload["email"].as_str().unwrap_or("unknown-canary");
Json(json!({ "id": canary_id(email), "email": email }))
}
async fn spawn_held_upstream(upstream: HeldUpstream) -> (String, JoinHandle<()>) {
let app = Router::new()
.route("/crm/leads", post(held_create_lead))
.with_state(upstream);
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let handle = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
(format!("http://{}", address), handle)
}
/// The module keeps the MCP server task handle for its own bounded cleanup (abort on the failure
/// path and when the harness is dropped), so it does not use the fire-and-forget helper.
async fn spawn_mcp_server_task(app: Router) -> (String, JoinHandle<()>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let handle = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
(format!("http://{}", address), handle)
}
// ---------------------------------------------------------------------------------------------
// Harness
// ---------------------------------------------------------------------------------------------
#[derive(Clone)]
pub(super) struct ClientSide {
pub(super) mcp_url: String,
pub(super) api_key: String,
pub(super) tool_name: String,
}
pub(super) struct Harness {
pub(super) client: reqwest::Client,
pub(super) mcp_url: String,
pub(super) api_key: String,
pub(super) tool_name: String,
/// A second Agent with its own catalog, used by the mixed-era overlap test to also cover the
/// agreed Agent/catalog scope.
alternate: Option<ClientSide>,
pub(super) store: Arc<InstrumentedSessionStore>,
pub(super) counters: Arc<StoreCounters>,
pub(super) upstream: HeldUpstream,
mcp_server: JoinHandle<()>,
upstream_server: JoinHandle<()>,
}
impl Harness {
pub(super) fn primary(&self) -> ClientSide {
ClientSide {
mcp_url: self.mcp_url.clone(),
api_key: self.api_key.clone(),
tool_name: self.tool_name.clone(),
}
}
pub(super) fn alternate(&self) -> ClientSide {
self.alternate
.clone()
.expect("this harness runs two Agents; the overlap test is the only caller")
}
}
impl Drop for Harness {
fn drop(&mut self) {
// Stop only this test's own servers.
self.mcp_server.abort();
self.upstream_server.abort();
}
}
pub(super) async fn harness(agent_slug: &str) -> Harness {
harness_with_sides(agent_slug, None).await
}
pub(super) async fn harness_with_two_agents(legacy_slug: &str, modern_slug: &str) -> Harness {
harness_with_sides(legacy_slug, Some(modern_slug)).await
}
async fn harness_with_sides(agent_slug: &str, modern_agent_slug: Option<&str>) -> Harness {
let registry = test_registry().await;
let upstream = HeldUpstream::new();
let (upstream_base_url, upstream_server) = spawn_held_upstream(upstream.clone()).await;
let operation = test_operation(&upstream_base_url, LEGACY_TOOL);
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.unwrap();
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &operation.id,
version: 1,
published_at: &OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &operation, agent_slug).await;
let api_key = create_platform_api_key(
&registry,
agent_slug,
"mcp-era-isolation",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
// Optional second Agent: its own catalog (its own tool), its own key, its own canary.
let alternate = match modern_agent_slug {
None => None,
Some(modern_slug) => {
let modern_operation = test_operation(&upstream_base_url, MODERN_TOOL);
registry
.create_operation(&test_workspace_id(), &modern_operation, Some("alice"))
.await
.unwrap();
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &modern_operation.id,
version: 1,
published_at: &OffsetDateTime::parse("2026-03-26T10:00:00Z", &Rfc3339).unwrap(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent_for_operation(&registry, &modern_operation, modern_slug).await;
let modern_api_key = create_platform_api_key(
&registry,
modern_slug,
"mcp-era-isolation-modern",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
Some(ClientSide {
mcp_url: String::new(),
api_key: modern_api_key,
tool_name: MODERN_TOOL.to_owned(),
})
}
};
let (store, counters) = InstrumentedSessionStore::new();
let sessions: SharedSessionStore = store.clone();
let (base_url, mcp_server) = spawn_mcp_server_task(build_test_app_with_sessions(
registry,
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
sessions,
))
.await;
let alternate = alternate.map(|mut side| {
side.mcp_url = agent_mcp_url(&base_url, modern_agent_slug.expect("a modern agent slug"));
side
});
Harness {
client: reqwest::Client::new(),
mcp_url: agent_mcp_url(&base_url, agent_slug),
api_key,
tool_name: LEGACY_TOOL.to_owned(),
alternate,
store,
counters,
upstream,
mcp_server,
upstream_server,
}
}
pub(super) fn header_refs<'a>(
headers: &'a [(&'static str, String)],
) -> Vec<(&'static str, &'a str)> {
headers
.iter()
.map(|(name, value)| (*name, value.as_str()))
.collect()
}
// ---------------------------------------------------------------------------------------------
// Bounded overlap run: owns the request tasks and the failure-path cleanup.
// ---------------------------------------------------------------------------------------------
pub(super) struct OverlapRun<'a> {
harness: &'a Harness,
pub(super) deadline: Duration,
tasks: Vec<Option<JoinHandle<reqwest::Response>>>,
pub(super) joined: usize,
pub(super) cancelled: usize,
}
impl<'a> OverlapRun<'a> {
pub(super) fn new(harness: &'a Harness) -> Self {
Self {
harness,
deadline: MARKER_TIMEOUT,
tasks: Vec::new(),
joined: 0,
cancelled: 0,
}
}
pub(super) fn with_deadline(harness: &'a Harness, deadline: Duration) -> Self {
Self {
harness,
deadline,
tasks: Vec::new(),
joined: 0,
cancelled: 0,
}
}
pub(super) fn spawn(
&mut self,
side: &ClientSide,
headers: Vec<(&'static str, String)>,
payload: Value,
) -> usize {
let client = self.harness.client.clone();
let url = side.mcp_url.clone();
let key = side.api_key.clone();
self.tasks.push(Some(tokio::spawn(async move {
post_jsonrpc_with_headers(&client, &url, &key, &header_refs(&headers), payload).await
})));
self.tasks.len() - 1
}
pub(super) fn is_finished(&self, index: usize) -> bool {
self.tasks
.get(index)
.and_then(|task| task.as_ref())
.is_none_or(|task| task.is_finished())
}
/// Bounded join of one request task. Any failure runs the full cleanup and then fails.
pub(super) async fn join_bounded(
&mut self,
index: usize,
what: &'static str,
) -> reqwest::Response {
let mut task = self.tasks[index]
.take()
.unwrap_or_else(|| panic!("the {what} request task was already joined"));
match tokio::time::timeout(REAP_TIMEOUT, &mut task).await {
Ok(Ok(response)) => {
self.joined += 1;
response
}
Ok(Err(join_error)) => {
self.cancelled += 1;
self.cleanup().await;
panic!("the {what} request task failed: {join_error}");
}
Err(_elapsed) => {
self.cancelled += 1;
task.abort();
let _ = task.await;
self.cleanup().await;
panic!(
"the {what} request task did not finish within {REAP_TIMEOUT:?} after the barrier \
was released"
);
}
}
}
/// Failure path required by R1: release both gates FIRST, then bounded-join or cancel every task
/// this run started, then abort the test's own servers - and only afterwards fail.
pub(super) async fn fail(&mut self, timeout: MarkerTimeout) -> ! {
self.cleanup().await;
panic!("{}", timeout.describe());
}
pub(super) async fn cleanup(&mut self) -> Vec<reqwest::Response> {
self.harness.store.release();
self.harness.upstream.release();
let mut responses = Vec::new();
for slot in self.tasks.iter_mut() {
let Some(mut task) = slot.take() else {
continue;
};
match tokio::time::timeout(REAP_TIMEOUT, &mut task).await {
Ok(Ok(response)) => {
self.joined += 1;
responses.push(response);
}
Ok(Err(_join_error)) => {
self.cancelled += 1;
}
Err(_elapsed) => {
self.cancelled += 1;
task.abort();
let _ = task.await;
}
}
}
self.harness.mcp_server.abort();
self.harness.upstream_server.abort();
responses
}
}
impl Drop for OverlapRun<'_> {
fn drop(&mut self) {
// Never leave a parked handler or a live request task behind, even when an assertion above
// panicked before the coordinated release.
self.harness.store.release();
self.harness.upstream.release();
for slot in self.tasks.iter_mut() {
if let Some(task) = slot.take() {
task.abort();
}
}
}
}