CI / UI Checks (pull_request) Successful in 10s
CI / Rust Checks (pull_request) Successful in 24m38s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
438 lines
16 KiB
Rust
438 lines
16 KiB
Rust
//! #107 result serialization: wire controls run independently of the structural SDK oracle.
|
|
use super::*;
|
|
use axum::{
|
|
Json,
|
|
body::Body,
|
|
extract::State,
|
|
http::StatusCode,
|
|
response::{IntoResponse, Response},
|
|
};
|
|
use futures_util::{StreamExt, stream};
|
|
|
|
const ERROR_EMAIL: &str = "upstream-error@example.test";
|
|
const REQUEST_ID: &str = "sdk-result-wire";
|
|
const TRACE_ID: &str = "11111111111111111111111111111111";
|
|
|
|
pub(super) async fn upstream(state: State<Arc<AtomicUsize>>, payload: Json<Value>) -> Response {
|
|
if payload.0["email"] == ERROR_EMAIL {
|
|
state.0.fetch_add(1, Ordering::SeqCst);
|
|
return (
|
|
StatusCode::UNPROCESSABLE_ENTITY,
|
|
Json(json!({"error":"fixture rejection"})),
|
|
)
|
|
.into_response();
|
|
}
|
|
create_lead(state, payload).await.into_response()
|
|
}
|
|
|
|
// The HTTP body is polled after next.run returns. Carry only the test observer, not a new lifecycle.
|
|
pub(super) fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
|
|
let (parts, body) = response.into_parts();
|
|
let body = stream::unfold(
|
|
(body.into_data_stream(), counters),
|
|
|(mut body, counters)| async move {
|
|
observe(counters.clone(), body.next())
|
|
.await
|
|
.map(|chunk| (chunk, (body, counters)))
|
|
},
|
|
);
|
|
Response::from_parts(parts, Body::from_stream(body))
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn rmcp_result_http_pagination_both_revisions() {
|
|
let h = Endpoint::started().await;
|
|
let mut operation = test_operation(&h._upstream.1);
|
|
operation.id = crank_core::OperationId::new("op_second_lead");
|
|
operation.name = "second_lead".to_owned();
|
|
h.registry
|
|
.create_operation(&workspace_id(), &operation, Some("alice"))
|
|
.await
|
|
.unwrap();
|
|
h.registry
|
|
.publish_operation(PublishRequest {
|
|
workspace_id: &workspace_id(),
|
|
operation_id: &operation.id,
|
|
version: 1,
|
|
published_at: &test_time(),
|
|
published_by: Some("alice"),
|
|
})
|
|
.await
|
|
.unwrap();
|
|
let now = time::OffsetDateTime::now_utc();
|
|
h.registry
|
|
.create_agent_draft_version(CreateAgentDraftVersionRequest {
|
|
workspace_id: &workspace_id(),
|
|
agent_id: &agent_id(),
|
|
version: &AgentVersion {
|
|
agent_id: agent_id(),
|
|
version: 2,
|
|
status: AgentStatus::Draft,
|
|
instructions: json!({}),
|
|
tool_selection_policy: ToolSelectionPolicy::default(),
|
|
created_at: now,
|
|
},
|
|
bindings: &[
|
|
AgentOperationBinding {
|
|
operation_id: crank_core::OperationId::new("op_create_lead"),
|
|
operation_version: 1,
|
|
tool_name: TOOL_NAME.into(),
|
|
tool_title: "Create Lead".into(),
|
|
tool_description_override: None,
|
|
enabled: true,
|
|
},
|
|
AgentOperationBinding {
|
|
operation_id: operation.id,
|
|
operation_version: 1,
|
|
tool_name: "second_lead".into(),
|
|
tool_title: "Second Lead".into(),
|
|
tool_description_override: None,
|
|
enabled: true,
|
|
},
|
|
],
|
|
updated_at: &now,
|
|
})
|
|
.await
|
|
.unwrap();
|
|
h.registry
|
|
.publish_agent(PublishAgentRequest {
|
|
workspace_id: &workspace_id(),
|
|
agent_id: &agent_id(),
|
|
version: 2,
|
|
published_at: &now,
|
|
published_by: Some("alice"),
|
|
expected_state: None,
|
|
})
|
|
.await
|
|
.unwrap();
|
|
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
|
let session = h.session(revision).await;
|
|
let mut names = Vec::new();
|
|
for (cursor, expected_next, expected_len) in [
|
|
(None, Some("1"), 1),
|
|
(Some("1"), None, 1),
|
|
(Some("2"), None, 0),
|
|
] {
|
|
let id = json!(format!("page-{cursor:?}"));
|
|
let mut request =
|
|
json!({"jsonrpc":"2.0","id":id,"method":"tools/list","params":{"limit":1}});
|
|
if let Some(cursor) = cursor {
|
|
request["params"]["cursor"] = json!(cursor);
|
|
}
|
|
if revision == MODERN_REVISION {
|
|
request["params"]["_meta"] = modern_meta();
|
|
}
|
|
let before = h.counters.sdk_tools_list_result();
|
|
let body = wire_body(
|
|
h.post(revision, session.as_deref(), &request).await,
|
|
&id,
|
|
false,
|
|
)
|
|
.await;
|
|
assert_era(&body["result"], revision, true);
|
|
assert_eq!(
|
|
body["result"].get("nextCursor"),
|
|
expected_next.map(|s| json!(s)).as_ref()
|
|
);
|
|
let tools = body["result"]["tools"].as_array().unwrap();
|
|
assert_eq!(tools.len(), expected_len);
|
|
names.extend(
|
|
tools
|
|
.iter()
|
|
.map(|tool| tool["name"].as_str().unwrap().to_owned()),
|
|
);
|
|
assert_eq!(h.counters.sdk_tools_list_result() - before, 1);
|
|
}
|
|
names.sort();
|
|
let mut expected = vec![TOOL_NAME.to_owned(), "second_lead".to_owned()];
|
|
expected.sort();
|
|
assert_eq!(names, expected);
|
|
}
|
|
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
|
|
}
|
|
|
|
fn assert_era(result: &Value, revision: &str, list: bool) {
|
|
if revision == MODERN_REVISION {
|
|
assert_eq!(result["resultType"], "complete", "{result}");
|
|
if list {
|
|
assert_eq!(result["ttlMs"], 0);
|
|
assert_eq!(result["cacheScope"], "private");
|
|
}
|
|
} else {
|
|
assert!(result.get("resultType").is_none(), "{result}");
|
|
assert!(result.get("ttlMs").is_none(), "{result}");
|
|
assert!(result.get("cacheScope").is_none(), "{result}");
|
|
}
|
|
assert!(result.get("_meta").is_none(), "{result}");
|
|
}
|
|
|
|
async fn wire_body(response: reqwest::Response, id: &Value, sse: bool) -> Value {
|
|
assert_eq!(response.status(), 200);
|
|
assert_eq!(response.headers()["x-request-id"], REQUEST_ID);
|
|
assert_eq!(response.headers()["x-trace-id"], TRACE_ID);
|
|
let content_type = response.headers()["content-type"]
|
|
.to_str()
|
|
.unwrap()
|
|
.to_owned();
|
|
let text = tokio::time::timeout(Duration::from_secs(5), response.text())
|
|
.await
|
|
.unwrap()
|
|
.unwrap();
|
|
let body: Value = if sse {
|
|
assert!(
|
|
content_type.starts_with("text/event-stream"),
|
|
"{content_type}"
|
|
);
|
|
let frames: Vec<Value> = text
|
|
.lines()
|
|
.filter_map(|line| {
|
|
line.strip_prefix("data:")
|
|
.map(|data| serde_json::from_str(data.trim()).unwrap())
|
|
})
|
|
.collect();
|
|
let terminal: Vec<_> = frames
|
|
.iter()
|
|
.filter(|frame| frame.get("id") == Some(id))
|
|
.collect();
|
|
assert_eq!(terminal.len(), 1, "{frames:?}");
|
|
assert_eq!(frames.last(), Some(terminal[0]), "terminal must be last");
|
|
assert!(
|
|
frames
|
|
.iter()
|
|
.any(|frame| frame["method"] == "notifications/progress"
|
|
&& frame["params"]["progressToken"] == "result-progress"),
|
|
"{frames:?}"
|
|
);
|
|
terminal[0].clone()
|
|
} else {
|
|
assert!(
|
|
content_type.starts_with("application/json"),
|
|
"{content_type}"
|
|
);
|
|
serde_json::from_str(&text).unwrap()
|
|
};
|
|
assert_eq!(body["jsonrpc"], "2.0");
|
|
assert_eq!(&body["id"], id);
|
|
body
|
|
}
|
|
|
|
fn assert_call_result(body: &Value, revision: &str, email: &str) {
|
|
assert!(body.get("error").is_none(), "{body}");
|
|
let result = &body["result"];
|
|
assert_era(result, revision, false);
|
|
let (output, text, is_error) = if email == ERROR_EMAIL {
|
|
let contract = crate::tool_error::tool_error_contract_from_runtime(
|
|
&crank_runtime::RuntimeError::ProtocolAdapter(
|
|
crank_core::ProtocolAdapterError::UnexpectedStatus {
|
|
status: 422,
|
|
dispatch: crank_core::DispatchEvidence::MayHaveDispatched,
|
|
},
|
|
),
|
|
REQUEST_ID,
|
|
TRACE_ID,
|
|
crank_core::ExecutionLocale::En,
|
|
);
|
|
(
|
|
json!({"error":crate::tool_error::tool_error_value(&contract)}),
|
|
crate::tool_error::tool_error_text(&contract),
|
|
true,
|
|
)
|
|
} else {
|
|
let output = json!({"id":format!("lead_for_{email}")});
|
|
let text = serde_json::to_string_pretty(&output).unwrap();
|
|
(output, text, false)
|
|
};
|
|
assert_eq!(result["structuredContent"], output, "{body}");
|
|
assert_eq!(result["content"], json!([{"type":"text", "text":text}]));
|
|
assert_eq!(result["isError"], is_error);
|
|
assert_eq!(
|
|
result.as_object().unwrap().len(),
|
|
if revision == MODERN_REVISION { 4 } else { 3 },
|
|
"no unexpected optional fields: {result}"
|
|
);
|
|
}
|
|
|
|
async fn result_control(revision: &str) -> Vec<usize> {
|
|
let h = Endpoint::started().await;
|
|
let session = h.session(revision).await;
|
|
let session = session.as_deref();
|
|
let mut counts = Vec::new();
|
|
// Actual published descriptor and schema, then the empty page at the catalog boundary.
|
|
for (cursor, expected_tools, id) in [
|
|
(
|
|
None,
|
|
json!([{"name":TOOL_NAME,"title":"Create Lead","description":"Creates a CRM lead","inputSchema":{"type":"object","properties":{"email":{"type":"string"}},"required":["email"]}}]),
|
|
json!("list-string-id"),
|
|
),
|
|
(Some("1"), json!([]), json!(9007199254740993_u64)),
|
|
] {
|
|
let mut request =
|
|
json!({"jsonrpc":"2.0","id":id,"method":"tools/list","params":{"limit":1}});
|
|
if revision == MODERN_REVISION {
|
|
request["params"]["_meta"] = modern_meta();
|
|
}
|
|
if let Some(cursor) = cursor {
|
|
request["params"]["cursor"] = json!(cursor);
|
|
}
|
|
let before = h.counters.sdk_tools_list_result();
|
|
let before_call = h.counters.sdk_tools_call_result();
|
|
let before_dispatch = h.counters.sdk_tools_dispatch();
|
|
let body = wire_body(h.post(revision, session, &request).await, &id, false).await;
|
|
assert!(body.get("error").is_none(), "{body}");
|
|
assert_eq!(body["result"]["tools"], expected_tools);
|
|
assert!(body["result"].get("nextCursor").is_none(), "{body}");
|
|
assert_era(&body["result"], revision, true);
|
|
assert_eq!(h.counters.sdk_tools_call_result(), before_call);
|
|
assert_eq!(h.counters.sdk_tools_dispatch() - before_dispatch, 1);
|
|
counts.push(h.counters.sdk_tools_list_result() - before);
|
|
}
|
|
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
|
|
for (email, id, sse) in [
|
|
(
|
|
"result-success@example.test",
|
|
json!(9007199254740993_u64),
|
|
false,
|
|
),
|
|
(ERROR_EMAIL, json!("tool-error-string-id"), false),
|
|
("result-sse@example.test", json!("sse-string-id"), true),
|
|
(ERROR_EMAIL, json!(92), true),
|
|
] {
|
|
if sse && revision != MODERN_REVISION {
|
|
continue;
|
|
}
|
|
let mut request = if revision == MODERN_REVISION {
|
|
modern_tool_call(90, email)
|
|
} else {
|
|
legacy_tool_call(90, email)
|
|
};
|
|
request["id"] = id.clone();
|
|
if sse {
|
|
request["params"]["_meta"]["progressToken"] = json!("result-progress");
|
|
}
|
|
let before = h.counters.sdk_tools_call_result();
|
|
let before_list = h.counters.sdk_tools_list_result();
|
|
let before_dispatch = h.counters.sdk_tools_dispatch();
|
|
let arrivals = h.calls.load(Ordering::SeqCst);
|
|
let response = h
|
|
.post_accept(
|
|
revision,
|
|
session,
|
|
&request,
|
|
if sse {
|
|
"application/json, text/event-stream"
|
|
} else {
|
|
"application/json"
|
|
},
|
|
)
|
|
.await;
|
|
let body = wire_body(response, &id, sse).await;
|
|
assert_call_result(&body, revision, email);
|
|
assert_eq!(h.calls.load(Ordering::SeqCst) - arrivals, 1);
|
|
assert_eq!(h.counters.sdk_tools_list_result(), before_list);
|
|
assert_eq!(h.counters.sdk_tools_dispatch() - before_dispatch, 1);
|
|
counts.push(h.counters.sdk_tools_call_result() - before);
|
|
}
|
|
// Unknown tool is a command InvalidParams, not an execution tool-error result.
|
|
let mut invalid = if revision == MODERN_REVISION {
|
|
modern_tool_call(93, "unused@example.test")
|
|
} else {
|
|
legacy_tool_call(93, "unused@example.test")
|
|
};
|
|
invalid["params"]["name"] = json!("missing_tool");
|
|
invalid["id"] = json!("invalid-params-id");
|
|
let before = h.counters.sdk_tools_call_result();
|
|
let arrivals = h.calls.load(Ordering::SeqCst);
|
|
let body = wire_body(
|
|
h.post(revision, session, &invalid).await,
|
|
&invalid["id"],
|
|
false,
|
|
)
|
|
.await;
|
|
assert_eq!(body["error"]["code"], -32602, "{body}");
|
|
assert!(body.get("result").is_none(), "{body}");
|
|
assert_eq!(body["error"]["data"]["request_id"], REQUEST_ID);
|
|
assert_eq!(body["error"]["data"]["trace_id"], TRACE_ID);
|
|
assert_eq!(h.counters.sdk_tools_call_result(), before);
|
|
assert_eq!(h.calls.load(Ordering::SeqCst), arrivals);
|
|
eprintln!(
|
|
"existing GREEN result wire {revision}: published list/schema + empty page, exact success/error JSON{}; InvalidParams/no result/no marker/no outbound; SDK result deltas={counts:?}",
|
|
if revision == MODERN_REVISION {
|
|
" + success/error terminal SSE"
|
|
} else {
|
|
" (legacy JSON-only)"
|
|
}
|
|
);
|
|
counts
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn rmcp_result_wire_modern() {
|
|
result_control(MODERN_REVISION).await;
|
|
}
|
|
#[tokio::test]
|
|
async fn rmcp_result_wire_legacy() {
|
|
result_control(LEGACY_REVISION).await;
|
|
}
|
|
#[tokio::test]
|
|
async fn rmcp_result_sdk_serialization_modern() {
|
|
assert_eq!(
|
|
result_control(MODERN_REVISION).await,
|
|
vec![1; 6],
|
|
"structural oracle: SDK list/final-empty/success/error/SSE-success/SSE-error must each serialize once after successful real HTTP wire controls"
|
|
);
|
|
}
|
|
#[tokio::test]
|
|
async fn rmcp_result_sdk_serialization_legacy() {
|
|
assert_eq!(
|
|
result_control(LEGACY_REVISION).await,
|
|
vec![1; 4],
|
|
"structural oracle: SDK list/final-empty/success/error must each serialize once after successful real HTTP wire controls"
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn rmcp_result_observer_scope_control() {
|
|
use crate::app::dispatch_observer::{
|
|
sdk_tools_call_result_serialized, sdk_tools_list_result_serialized,
|
|
};
|
|
let a = Arc::new(CounterSet::default());
|
|
let b = Arc::new(CounterSet::default());
|
|
sdk_tools_list_result_serialized();
|
|
sdk_tools_call_result_serialized();
|
|
assert_eq!(
|
|
(a.sdk_tools_list_result(), a.sdk_tools_call_result()),
|
|
(0, 0)
|
|
);
|
|
observe(a.clone(), async {
|
|
sdk_tools_list_result_serialized();
|
|
sdk_tools_call_result_serialized();
|
|
})
|
|
.await;
|
|
// A different request cannot alter a's result counters.
|
|
observe(b.clone(), async {
|
|
sdk_tools_list_result_serialized();
|
|
})
|
|
.await;
|
|
assert_eq!(
|
|
(a.sdk_tools_list_result(), a.sdk_tools_call_result()),
|
|
(1, 1)
|
|
);
|
|
assert_eq!(
|
|
(b.sdk_tools_list_result(), b.sdk_tools_call_result()),
|
|
(1, 0)
|
|
);
|
|
// Prove the stream-body scope actually records deferred work after the header scope ended.
|
|
let stream_counters = b.clone();
|
|
let body = Body::from_stream(stream::once(async move {
|
|
sdk_tools_call_result_serialized();
|
|
Ok::<_, std::convert::Infallible>("terminal")
|
|
}));
|
|
let response = observe_body(Response::new(body), stream_counters);
|
|
let bytes = axum::body::to_bytes(response.into_body(), 100)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(&bytes[..], b"terminal");
|
|
assert_eq!(b.sdk_tools_call_result(), 1);
|
|
assert_eq!(a.sdk_tools_call_result(), 1);
|
|
}
|