feat(epic3): progress и безопасная отмена Tool calls (Story 3.4, FR-14)
- request-scoped lifecycle одного tools/call: валидированный `_meta.progressToken` (строковый/числовой, 1..=128 байт) и bounded очередь реальных этапов (tool_resolved → authorization_resolved → execution_dispatched) в собственный SSE-stream запроса; без token или без stream-carrier результат не меняется; - сериализация `notifications/progress` по pinned схеме обеих revisions (progressToken/progress/message, total не изобретается); - отмена по revision: 2025-11-25 — `notifications/cancelled` через bounded in-flight таблицу (владение = session + platform credential, не progress token); 2026-07-28 — закрытие response stream; в обоих случаях drop будущего вызова = кооперативная остановка, terminal-сообщение не отправляется; - streamed ответ сохраняет проекцию Story 3.18: closed `notifications/message` перед финальным кадром (перенос logging-scope в тело стрима); - ATDD: 12 end-to-end тестов на реальном endpoint/каталоге/counted upstream (обе revisions, malformed/oversized/reused token, owner/foreign/late cancel, disconnect, ambiguous outbound, representative client smoke) + 7 unit-тестов границ lifecycle; entry в scripts/ci-story-checks.sh.
This commit is contained in:
1 parent
49c8af24ed
commit
862cde8559
18 files changed
+2207
-112
No files matched your search
@@ -0,0 +1,170 @@
|
||||
//! Story 3.4 bounds that do not need the HTTP surface: token validation, the monotonic bounded
|
||||
//! progress queue, the pinned frame shape and the ownership of the in-flight cancellation table.
|
||||
|
||||
use super::*;
|
||||
|
||||
fn token(value: Value) -> Option<ProgressToken> {
|
||||
progress_token(&json!({ "_meta": { "progressToken": value } }))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pinned_progress_token_is_a_bounded_string_or_a_number() {
|
||||
assert_eq!(
|
||||
token(json!("tok-1")),
|
||||
Some(ProgressToken::Text("tok-1".to_owned()))
|
||||
);
|
||||
assert!(matches!(token(json!(7)), Some(ProgressToken::Number(_))));
|
||||
assert!(matches!(token(json!(1.5)), Some(ProgressToken::Number(_))));
|
||||
|
||||
// Malformed and out-of-bound tokens disable progress instead of failing the call.
|
||||
assert_eq!(token(json!("")), None);
|
||||
assert_eq!(token(json!("x".repeat(MAX_PROGRESS_TOKEN_LEN + 1))), None);
|
||||
assert_eq!(token(json!("line\nbreak")), None);
|
||||
assert_eq!(token(json!(null)), None);
|
||||
assert_eq!(token(json!(true)), None);
|
||||
assert_eq!(token(json!({ "nested": 1 })), None);
|
||||
assert_eq!(token(json!([1, 2])), None);
|
||||
// A token at the bound is still accepted.
|
||||
assert!(token(json!("x".repeat(MAX_PROGRESS_TOKEN_LEN))).is_some());
|
||||
// Absent `_meta`, absent token and a non-object `_meta` are all "no progress".
|
||||
assert_eq!(progress_token(&json!({})), None);
|
||||
assert_eq!(progress_token(&json!({ "_meta": { "other": 1 } })), None);
|
||||
assert_eq!(progress_token(&json!({ "_meta": "not-an-object" })), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn real_steps_produce_strictly_increasing_bounded_progress_events() {
|
||||
let (lifecycle, events) = ToolCallLifecycle::new(token(json!("tok-monotonic")));
|
||||
let mut events = events.expect("a validated token opens the progress queue");
|
||||
for phase in [Phase::Resolved, Phase::Authorized, Phase::Dispatching] {
|
||||
lifecycle.advance(phase);
|
||||
}
|
||||
drop(lifecycle);
|
||||
|
||||
let mut observed = Vec::new();
|
||||
while let Some(event) = events.recv().await {
|
||||
observed.push((event.progress, event.message));
|
||||
}
|
||||
assert_eq!(
|
||||
observed,
|
||||
vec![
|
||||
(1, "tool_resolved"),
|
||||
(2, "authorization_resolved"),
|
||||
(3, "execution_dispatched"),
|
||||
]
|
||||
);
|
||||
assert!(
|
||||
observed.windows(2).all(|pair| pair[0].0 < pair[1].0),
|
||||
"progress must increase monotonically, got {observed:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_full_progress_queue_drops_events_instead_of_blocking_the_call() {
|
||||
let (lifecycle, events) = ToolCallLifecycle::new(token(json!(9)));
|
||||
let mut events = events.expect("a validated token opens the progress queue");
|
||||
// Many more steps than the queue holds: the call must never wait for the reader.
|
||||
for _ in 0..(PROGRESS_CAPACITY * 4) {
|
||||
lifecycle.advance(Phase::Resolved);
|
||||
}
|
||||
let mut delivered = 0;
|
||||
while events.try_recv().is_ok() {
|
||||
delivered += 1;
|
||||
}
|
||||
assert_eq!(delivered, PROGRESS_CAPACITY);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn without_a_token_no_progress_is_produced_at_all() {
|
||||
let (lifecycle, events) = ToolCallLifecycle::new(None);
|
||||
assert!(events.is_none());
|
||||
lifecycle.advance(Phase::Resolved);
|
||||
lifecycle.advance(Phase::Dispatching);
|
||||
}
|
||||
|
||||
/// The pinned `notifications/progress` frame (schema `ProgressNotification`, both supported
|
||||
/// revisions): `progressToken` echoed verbatim, `progress` increasing, `message` optional and
|
||||
/// `total` absent because this server never invents one.
|
||||
#[test]
|
||||
fn the_progress_frame_matches_the_pinned_notification_shape() {
|
||||
let event = ProgressEvent {
|
||||
progress: 2,
|
||||
message: Phase::Authorized.message(),
|
||||
};
|
||||
assert_eq!(
|
||||
progress_frame(&ProgressToken::Text("tok-2".to_owned()), &event),
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"method": "notifications/progress",
|
||||
"params": {
|
||||
"progressToken": "tok-2",
|
||||
"progress": 2,
|
||||
"message": "authorization_resolved"
|
||||
}
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
progress_frame(&ProgressToken::Number(7.into()), &event)["params"]["progressToken"],
|
||||
json!(7)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_cancellation_only_reaches_the_call_of_the_same_session_and_credential() {
|
||||
let registry = Arc::new(InFlightCalls::new(MAX_IN_FLIGHT_CALLS));
|
||||
let scope = InFlightScope {
|
||||
session_id: "sess-1".to_owned(),
|
||||
owner: "pk_a".to_owned(),
|
||||
};
|
||||
let entry = registry
|
||||
.register(&scope, &json!(42))
|
||||
.expect("the table has room");
|
||||
let mut signal = entry.cancel_signal();
|
||||
|
||||
// A foreign credential, a foreign session and a different request id cancel nothing.
|
||||
for foreign in [
|
||||
InFlightScope {
|
||||
session_id: "sess-1".to_owned(),
|
||||
owner: "pk_b".to_owned(),
|
||||
},
|
||||
InFlightScope {
|
||||
session_id: "sess-2".to_owned(),
|
||||
owner: "pk_a".to_owned(),
|
||||
},
|
||||
] {
|
||||
assert!(!registry.cancel(&foreign, &json!(42)));
|
||||
}
|
||||
assert!(!registry.cancel(&scope, &json!(43)));
|
||||
assert!(
|
||||
tokio::time::timeout(std::time::Duration::from_millis(50), signal.cancelled())
|
||||
.await
|
||||
.is_err(),
|
||||
"a foreign cancellation must not fire the signal"
|
||||
);
|
||||
|
||||
assert!(registry.cancel(&scope, &json!(42)));
|
||||
tokio::time::timeout(std::time::Duration::from_millis(50), signal.cancelled())
|
||||
.await
|
||||
.expect("the owner's cancellation fires the signal");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_released_call_releases_its_slot_and_the_table_is_bounded() {
|
||||
let registry = Arc::new(InFlightCalls::new(1));
|
||||
let scope = InFlightScope {
|
||||
session_id: "sess-1".to_owned(),
|
||||
owner: "pk_a".to_owned(),
|
||||
};
|
||||
let entry = registry.register(&scope, &json!(1)).expect("first slot");
|
||||
assert!(
|
||||
registry.register(&scope, &json!(2)).is_none(),
|
||||
"the table refuses a call beyond its bound instead of evicting the live one"
|
||||
);
|
||||
assert!(registry.cancel(&scope, &json!(1)));
|
||||
drop(entry);
|
||||
assert!(
|
||||
!registry.cancel(&scope, &json!(1)),
|
||||
"a terminal call is no longer cancellable"
|
||||
);
|
||||
assert!(registry.register(&scope, &json!(2)).is_some());
|
||||
}
|
||||
Reference in new issue
Block a user