CI / UI Checks (pull_request) Successful in 12s
CI / Rust Checks (pull_request) Successful in 36m53s
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
346 lines
12 KiB
Rust
346 lines
12 KiB
Rust
//! #107 Completion: real build_app HTTP wire controls and a separate SDK-path 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_completion_test_support.rs"]
|
|
mod fixtures;
|
|
use fixtures::{BOUNDED_URI, Endpoint, LARGE_URI, URI};
|
|
|
|
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, c)| async move {
|
|
observe(c.clone(), body.next())
|
|
.await
|
|
.map(|chunk| (chunk, (body, c)))
|
|
},
|
|
);
|
|
Response::from_parts(parts, Body::from_stream(body))
|
|
}
|
|
fn counts(c: &CounterSet) -> [usize; 2] {
|
|
[c.sdk_completion_dispatch(), c.sdk_completion_result()]
|
|
}
|
|
fn params(reference: Value, name: &str, value: &str) -> Value {
|
|
json!({"ref":reference,"argument":{"name":name,"value":value}})
|
|
}
|
|
fn prompt(name: &str) -> Value {
|
|
json!({"type":"ref/prompt","name":name})
|
|
}
|
|
fn resource(uri: &str) -> Value {
|
|
json!({"type":"ref/resource","uri":uri})
|
|
}
|
|
fn request(revision: &str, mut params: Value) -> Value {
|
|
if revision == MODERN_REVISION {
|
|
params["_meta"] = modern_meta();
|
|
}
|
|
json!({"jsonrpc":"2.0","id":9007199254740993_u64,"method":"completion/complete","params":params})
|
|
}
|
|
async fn wire(response: reqwest::Response, sse: bool) -> Value {
|
|
assert_eq!(response.status(), 200);
|
|
assert_eq!(response.headers()["x-request-id"], "sdk-completion-wire");
|
|
assert_eq!(
|
|
response.headers()["x-trace-id"],
|
|
"11111111111111111111111111111111"
|
|
);
|
|
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}: {text}"
|
|
);
|
|
let frames: Vec<Value> = text
|
|
.lines()
|
|
.filter_map(|line| {
|
|
line.strip_prefix("data:")
|
|
.map(|s| serde_json::from_str(s.trim()).unwrap())
|
|
})
|
|
.collect();
|
|
let terminal: Vec<_> = frames
|
|
.iter()
|
|
.filter(|f| f.get("id") == Some(&json!(9007199254740993_u64)))
|
|
.collect();
|
|
assert_eq!(terminal.len(), 1, "{frames:?}");
|
|
assert_eq!(frames.last(), Some(terminal[0]), "terminal must be last");
|
|
terminal[0].clone()
|
|
} else {
|
|
assert!(
|
|
content_type.starts_with("application/json"),
|
|
"{content_type}: {text}"
|
|
);
|
|
serde_json::from_str(&text).unwrap()
|
|
};
|
|
assert_eq!(body["jsonrpc"], "2.0");
|
|
assert_eq!(body["id"], json!(9007199254740993_u64));
|
|
body
|
|
}
|
|
async fn success(
|
|
h: &Endpoint,
|
|
revision: &str,
|
|
session: Option<&str>,
|
|
p: Value,
|
|
sse: bool,
|
|
) -> (Value, [usize; 2]) {
|
|
let before = counts(&h.counters);
|
|
let body = wire(
|
|
h.post(revision, session, &request(revision, p), sse).await,
|
|
sse,
|
|
)
|
|
.await;
|
|
assert!(body.get("error").is_none(), "{body}");
|
|
let result = &body["result"];
|
|
if revision == MODERN_REVISION {
|
|
assert_eq!(result["resultType"], "complete", "{body}");
|
|
} else {
|
|
assert!(result.get("resultType").is_none(), "{body}");
|
|
}
|
|
for key in ["ttlMs", "cacheScope", "_meta"] {
|
|
assert!(result.get(key).is_none(), "{body}");
|
|
}
|
|
let after = counts(&h.counters);
|
|
(
|
|
result["completion"].clone(),
|
|
std::array::from_fn(|i| after[i] - before[i]),
|
|
)
|
|
}
|
|
async fn control(revision: &str) -> Vec<[usize; 2]> {
|
|
let h = Endpoint::started().await;
|
|
let session = h.session(revision).await;
|
|
let session = session.as_deref();
|
|
let modes: &[bool] = if revision == MODERN_REVISION {
|
|
&[false, true]
|
|
} else {
|
|
&[false]
|
|
};
|
|
let mut deltas = Vec::new();
|
|
for &sse in modes {
|
|
for (p, expected) in [
|
|
(
|
|
params(prompt("greeting"), "tone", ""),
|
|
json!({"values":["warm","dry"],"total":2}),
|
|
),
|
|
(
|
|
params(prompt("archived-prompt"), "tone", "W"),
|
|
json!({"values":["warm"],"total":1}),
|
|
),
|
|
(
|
|
params(prompt("greeting"), "name", "A"),
|
|
json!({"values":[],"total":0}),
|
|
),
|
|
(
|
|
params(resource(URI), "region", ""),
|
|
json!({"values":["eu","us","apac"],"total":3}),
|
|
),
|
|
(
|
|
params(resource(URI), "region", "A"),
|
|
json!({"values":["apac"],"total":1}),
|
|
),
|
|
(
|
|
params(resource(URI), "region", "zzz"),
|
|
json!({"values":[],"total":0}),
|
|
),
|
|
] {
|
|
let (completion, delta) = success(&h, revision, session, p, sse).await;
|
|
assert_eq!(completion, expected);
|
|
deltas.push(delta);
|
|
}
|
|
for (uri, total) in [(BOUNDED_URI, Some(150)), (LARGE_URI, None)] {
|
|
let (completion, delta) = success(
|
|
&h,
|
|
revision,
|
|
session,
|
|
params(resource(uri), "region", "item"),
|
|
sse,
|
|
)
|
|
.await;
|
|
assert_eq!(
|
|
completion["values"],
|
|
json!((0..100).map(|i| format!("item{i:04}")).collect::<Vec<_>>())
|
|
);
|
|
assert_eq!(completion["hasMore"], true);
|
|
if let Some(total) = total {
|
|
assert_eq!(completion["total"], total);
|
|
} else {
|
|
assert!(
|
|
completion.get("total").is_none(),
|
|
"partial scan: {completion}"
|
|
);
|
|
}
|
|
deltas.push(delta);
|
|
}
|
|
let mut with_context = params(prompt("greeting"), "tone", "w");
|
|
with_context["context"] = json!({"arguments":{"name":"Ada","tone":"dry"}});
|
|
let (completion, delta) = success(&h, revision, session, with_context, sse).await;
|
|
assert_eq!(completion, json!({"values":["warm"],"total":1}));
|
|
deltas.push(delta);
|
|
let mut unavailable = None;
|
|
for p in [
|
|
params(prompt("draft-prompt"), "tone", ""),
|
|
params(prompt("unbound-prompt"), "tone", ""),
|
|
params(prompt("other-agent-prompt"), "tone", ""),
|
|
params(prompt("never-existed"), "tone", ""),
|
|
params(prompt("changed-draft"), "tone", ""),
|
|
params(prompt("greeting"), "unknown-argument", ""),
|
|
params(resource("crank://foreign/{region}"), "region", ""),
|
|
params(resource(URI), "unknown-parameter", ""),
|
|
] {
|
|
let body = wire(
|
|
h.post(revision, session, &request(revision, p), sse).await,
|
|
sse,
|
|
)
|
|
.await;
|
|
assert_eq!(body["error"]["code"], -32602, "{body}");
|
|
assert_eq!(
|
|
body["error"]["message"],
|
|
"the completion reference is not available"
|
|
);
|
|
assert!(body.get("result").is_none());
|
|
if let Some(ref previous) = unavailable {
|
|
assert_eq!(&body, previous);
|
|
}
|
|
unavailable = Some(body);
|
|
}
|
|
let mut invalid = vec![
|
|
json!({"argument":{"name":"tone","value":""}}),
|
|
params(json!({"type":"ref/tool","name":"greeting"}), "tone", ""),
|
|
params(prompt("greeting"), "tone", &"s".repeat(1025)),
|
|
params(prompt("greeting"), &"n".repeat(129), ""),
|
|
];
|
|
// Preserve domain validation on arbitrary JSON, never drop or stringify context values for SDK.
|
|
for value in [
|
|
json!(7),
|
|
json!(true),
|
|
json!(null),
|
|
json!(["eu"]),
|
|
json!({"region":"eu"}),
|
|
json!("s".repeat(1025)),
|
|
] {
|
|
let mut p = params(prompt("greeting"), "tone", "");
|
|
p["context"] = json!({"arguments":{"secret-context":value}});
|
|
invalid.push(p);
|
|
}
|
|
let mut p = params(prompt("greeting"), "tone", "");
|
|
p["context"] = json!({"arguments":(0..33).map(|i| (format!("arg{i}"), json!("eu"))).collect::<serde_json::Map<_,_>>()});
|
|
invalid.push(p);
|
|
for p in invalid {
|
|
let body = wire(
|
|
h.post(revision, session, &request(revision, p), sse).await,
|
|
sse,
|
|
)
|
|
.await;
|
|
assert_eq!(body["error"]["code"], -32602, "{body}");
|
|
assert_eq!(
|
|
body["error"]["message"],
|
|
"invalid completion/complete parameters"
|
|
);
|
|
assert!(body.get("result").is_none());
|
|
for leaked in ["secret-context", &"s".repeat(1025), &"n".repeat(129)] {
|
|
assert!(!body.to_string().contains(leaked), "{body}");
|
|
}
|
|
}
|
|
}
|
|
h.registry
|
|
.revoke_platform_api_key(
|
|
&workspace_id(),
|
|
&crank_core::PlatformApiKeyId::new("pk_dispatch_observer"),
|
|
&time::OffsetDateTime::now_utc(),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
let before = h.counters.snapshot();
|
|
let sdk_before = counts(&h.counters);
|
|
let response = h
|
|
.post(
|
|
revision,
|
|
session,
|
|
&request(revision, params(prompt("greeting"), "tone", "")),
|
|
false,
|
|
)
|
|
.await;
|
|
assert_eq!(response.status(), 401);
|
|
let _ = response.bytes().await.unwrap();
|
|
assert_eq!(
|
|
counts(&h.counters),
|
|
sdk_before,
|
|
"revoked key must not dispatch to SDK"
|
|
);
|
|
let after = h.counters.snapshot();
|
|
assert_eq!(after.era_modern, before.era_modern);
|
|
assert_eq!(after.era_legacy, before.era_legacy);
|
|
assert_eq!(after.tools_service, before.tools_service);
|
|
eprintln!(
|
|
"existing GREEN Completion HTTP {revision}: Prompt+Resource refs, exact bound v1/archive, prefix/empty/bounded/truncated, JSON/context/errors/correlation/auth; SDK actual={deltas:?}, expected=[1,1] per success"
|
|
);
|
|
deltas
|
|
}
|
|
#[tokio::test]
|
|
async fn rmcp_completion_wire_legacy() {
|
|
control(LEGACY_REVISION).await;
|
|
}
|
|
#[tokio::test]
|
|
async fn rmcp_completion_wire_modern() {
|
|
control(MODERN_REVISION).await;
|
|
}
|
|
#[tokio::test]
|
|
async fn rmcp_completion_sdk_legacy() {
|
|
let deltas = control(LEGACY_REVISION).await;
|
|
assert!(
|
|
deltas.iter().all(|d| *d == [1, 1]),
|
|
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
|
);
|
|
}
|
|
#[tokio::test]
|
|
async fn rmcp_completion_sdk_modern() {
|
|
let deltas = control(MODERN_REVISION).await;
|
|
assert!(
|
|
deltas.iter().all(|d| *d == [1, 1]),
|
|
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
|
);
|
|
}
|
|
#[tokio::test]
|
|
async fn rmcp_completion_observer_scope_control() {
|
|
use super::{sdk_completion_dispatch_enter, sdk_completion_result_serialized};
|
|
let a = Arc::new(CounterSet::default());
|
|
let b = Arc::new(CounterSet::default());
|
|
sdk_completion_dispatch_enter();
|
|
sdk_completion_result_serialized();
|
|
assert_eq!(counts(&a), [0; 2]);
|
|
let snapshot = a.snapshot();
|
|
tokio::join!(
|
|
observe(a.clone(), async {
|
|
sdk_completion_dispatch_enter();
|
|
tokio::task::yield_now().await;
|
|
sdk_completion_result_serialized();
|
|
}),
|
|
observe(b.clone(), async {
|
|
sdk_completion_result_serialized();
|
|
})
|
|
);
|
|
assert_eq!(counts(&a), [1, 1]);
|
|
assert_eq!(counts(&b), [0, 1]);
|
|
assert_eq!(a.snapshot(), snapshot);
|
|
let body = Body::from_stream(stream::once(async {
|
|
sdk_completion_result_serialized();
|
|
Ok::<_, std::convert::Infallible>("data: terminal\n\n")
|
|
}));
|
|
let response = observe_body(Response::new(body), b.clone());
|
|
assert_eq!(counts(&b), [0, 1], "body must be deferred");
|
|
assert_eq!(
|
|
&axum::body::to_bytes(response.into_body(), 100)
|
|
.await
|
|
.unwrap()[..],
|
|
b"data: terminal\n\n"
|
|
);
|
|
assert_eq!(counts(&b), [0, 2]);
|
|
assert_eq!(counts(&a), [1, 1]);
|
|
}
|