CI / UI Checks (pull_request) Successful in 11s
CI / Rust Checks (pull_request) Successful in 12m45s
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
Community Release / release (push) Successful in 40m35s
Tool Draft фиксирует synchronous/background/adaptive, deadline и fallback; runtime применяет единый снимок политики (concurrency, очередь, approval, deadline) до внешнего действия. Насыщение отклоняется typed overload с retry guidance, mandatory safety store fail closed, background/adaptive используют опубликованный synchronous/unsupported fallback. Refs: #29
742 lines
23 KiB
Rust
742 lines
23 KiB
Rust
//! Unit oracles of the Story 3.19 signal seam: the catalog projection, the bounded filter, the exact
|
|
//! wire frames of both approved revisions and the bounded legacy stream ownership.
|
|
|
|
use std::{
|
|
collections::BTreeMap,
|
|
io,
|
|
sync::{Arc, Mutex},
|
|
time::{Duration, Instant},
|
|
};
|
|
|
|
use crank_core::ids::{PromptId, ResourceId};
|
|
use crank_core::{
|
|
ExecutionConfig, HttpMethod, Operation, OperationId, OperationSecurityLevel, OperationStatus,
|
|
Protocol, RestTarget, Target, ToolAccessMode, ToolDescription, ToolGroup, ToolSearchSettings,
|
|
ToolSelectionPolicy, WorkspaceId,
|
|
};
|
|
use crank_mapping::MappingSet;
|
|
use crank_registry::PublishedAgentCatalog;
|
|
use crank_registry::model::{AgentPromptBinding, AgentResourceBinding, PublishedAgentTool};
|
|
use crank_schema::{Schema, SchemaKind};
|
|
use serde_json::{Value, json};
|
|
use time::OffsetDateTime;
|
|
use tokio::sync::mpsc;
|
|
|
|
use super::{
|
|
CatalogFingerprint, FilterOutcome, INVALID_LISTEN_FILTER, ListenFilter, MAX_FILTER_URIS,
|
|
MAX_SUBSCRIPTION_ID_BYTES, PROMPT_LIST_CHANGED, RESOURCE_LIST_CHANGED, ReadError, Reader,
|
|
SIGNAL_QUEUE_CAPACITY, SUBSCRIPTION_ID_KEY, SUBSCRIPTIONS_ACKNOWLEDGED, Signals,
|
|
StreamRegistry, TOOL_LIST_CHANGED, Watch, Wire, acknowledged_frame, run, subscription_id,
|
|
};
|
|
|
|
fn catalog(
|
|
resources: &[(&str, u32)],
|
|
prompts: &[(&str, u32)],
|
|
catalog_revision: &str,
|
|
) -> PublishedAgentCatalog {
|
|
catalog_with(
|
|
ToolSelectionPolicy::default(),
|
|
Vec::new(),
|
|
resources,
|
|
prompts,
|
|
catalog_revision,
|
|
)
|
|
}
|
|
|
|
fn catalog_with(
|
|
tool_selection_policy: ToolSelectionPolicy,
|
|
tools: Vec<PublishedAgentTool>,
|
|
resources: &[(&str, u32)],
|
|
prompts: &[(&str, u32)],
|
|
catalog_revision: &str,
|
|
) -> PublishedAgentCatalog {
|
|
PublishedAgentCatalog {
|
|
agent_version: 1,
|
|
catalog_revision: catalog_revision.to_owned(),
|
|
tool_selection_policy,
|
|
tools,
|
|
resources: resources
|
|
.iter()
|
|
.map(|(id, version)| AgentResourceBinding {
|
|
resource_id: ResourceId::new(*id),
|
|
resource_version: *version,
|
|
})
|
|
.collect(),
|
|
prompts: prompts
|
|
.iter()
|
|
.map(|(id, version)| AgentPromptBinding {
|
|
prompt_id: PromptId::new(*id),
|
|
prompt_version: *version,
|
|
})
|
|
.collect(),
|
|
}
|
|
}
|
|
|
|
fn search_policy(tool_names: &[&str]) -> ToolSelectionPolicy {
|
|
ToolSelectionPolicy {
|
|
mode: ToolAccessMode::Search,
|
|
groups: vec![ToolGroup {
|
|
id: "crm".to_owned(),
|
|
name: "CRM".to_owned(),
|
|
description: "CRM operations".to_owned(),
|
|
tool_names: tool_names.iter().map(|name| (*name).to_owned()).collect(),
|
|
}],
|
|
search: ToolSearchSettings::default(),
|
|
}
|
|
}
|
|
|
|
fn empty_object_schema() -> Schema {
|
|
Schema {
|
|
kind: SchemaKind::Object,
|
|
format: None,
|
|
description: None,
|
|
required: false,
|
|
nullable: false,
|
|
default_value: None,
|
|
fields: BTreeMap::new(),
|
|
items: None,
|
|
enum_values: Vec::new(),
|
|
variants: Vec::new(),
|
|
}
|
|
}
|
|
|
|
/// One published Tool binding whose served definition is exactly `title`/`description`.
|
|
fn published_tool(name: &str, title: &str, description: &str, version: u32) -> PublishedAgentTool {
|
|
PublishedAgentTool {
|
|
workspace_id: WorkspaceId::new("ws_test"),
|
|
workspace_slug: "ws-test".to_owned(),
|
|
agent_id: "agent_test".into(),
|
|
agent_slug: "agent".to_owned(),
|
|
operation: Operation {
|
|
id: OperationId::new(format!("op_{name}")),
|
|
name: name.to_owned(),
|
|
display_name: title.to_owned(),
|
|
category: "test".to_owned(),
|
|
protocol: Protocol::Rest,
|
|
security_level: OperationSecurityLevel::Standard,
|
|
status: OperationStatus::Published,
|
|
version,
|
|
target: Target::Rest(RestTarget {
|
|
base_url: "https://example.test".to_owned(),
|
|
method: HttpMethod::Get,
|
|
path_template: "/leads".to_owned(),
|
|
static_headers: BTreeMap::new(),
|
|
request_contract: None,
|
|
response_contract: Vec::new(),
|
|
multipart_field_mime_types: BTreeMap::new(),
|
|
}),
|
|
input_schema: empty_object_schema(),
|
|
output_schema: empty_object_schema(),
|
|
input_mapping: MappingSet { rules: Vec::new() },
|
|
output_mapping: MappingSet { rules: Vec::new() },
|
|
execution_config: ExecutionConfig {
|
|
timeout_ms: 10_000,
|
|
retry_policy: None,
|
|
response_cache: None,
|
|
idempotency: None,
|
|
safety: None,
|
|
approval_policy: None,
|
|
execution_policy: None,
|
|
auth_profile_ref: None,
|
|
headers: BTreeMap::new(),
|
|
},
|
|
tool_description: ToolDescription {
|
|
title: title.to_owned(),
|
|
description: description.to_owned(),
|
|
tags: Vec::new(),
|
|
examples: Vec::new(),
|
|
},
|
|
samples: None,
|
|
generated_draft: None,
|
|
config_export: None,
|
|
wizard_state: None,
|
|
created_at: OffsetDateTime::UNIX_EPOCH,
|
|
updated_at: OffsetDateTime::UNIX_EPOCH,
|
|
published_at: None,
|
|
},
|
|
tool_name: name.to_owned(),
|
|
tool_title: title.to_owned(),
|
|
tool_description: description.to_owned(),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn a_committed_resource_binding_is_a_resource_change_only() {
|
|
let before = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-1"));
|
|
let after = CatalogFingerprint::of(&catalog(
|
|
&[("res_a", 1), ("res_b", 1)],
|
|
&[("prm_a", 1)],
|
|
"rev-2",
|
|
));
|
|
|
|
assert_eq!(
|
|
after.changes_since(&before),
|
|
Signals {
|
|
resources: true,
|
|
prompts: false,
|
|
tools: false
|
|
}
|
|
);
|
|
assert!(!before.changes_since(&after).prompts);
|
|
assert_eq!(
|
|
before.changes_since(&after),
|
|
Signals {
|
|
resources: true,
|
|
prompts: false,
|
|
tools: false
|
|
}
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_committed_prompt_binding_is_a_prompt_change_only() {
|
|
let before = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1)], "rev-1"));
|
|
let after = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1), ("prm_b", 2)], "rev-2"));
|
|
|
|
assert_eq!(
|
|
after.changes_since(&before),
|
|
Signals {
|
|
resources: false,
|
|
prompts: true,
|
|
tools: false
|
|
}
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_pinned_version_bump_is_a_change_even_when_the_binding_names_are_stable() {
|
|
let before = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-1"));
|
|
let after = CatalogFingerprint::of(&catalog(&[("res_a", 2)], &[("prm_a", 1)], "rev-1"));
|
|
|
|
assert_eq!(
|
|
after.changes_since(&before),
|
|
Signals {
|
|
resources: true,
|
|
prompts: false,
|
|
tools: false
|
|
}
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_committed_tool_definition_change_is_a_tool_change_only() {
|
|
let lead = || published_tool("crm_create_lead", "Create Lead", "Creates a lead", 1);
|
|
let before = CatalogFingerprint::of(&catalog_with(
|
|
ToolSelectionPolicy::default(),
|
|
vec![lead()],
|
|
&[("res_a", 1)],
|
|
&[("prm_a", 1)],
|
|
"rev-1",
|
|
));
|
|
let added = CatalogFingerprint::of(&catalog_with(
|
|
ToolSelectionPolicy::default(),
|
|
vec![
|
|
lead(),
|
|
published_tool(
|
|
"crm_create_second",
|
|
"Create Second",
|
|
"Creates a second lead",
|
|
1,
|
|
),
|
|
],
|
|
&[("res_a", 1)],
|
|
&[("prm_a", 1)],
|
|
"rev-2",
|
|
));
|
|
let retitled = CatalogFingerprint::of(&catalog_with(
|
|
ToolSelectionPolicy::default(),
|
|
vec![published_tool(
|
|
"crm_create_lead",
|
|
"Create a lead",
|
|
"Creates a lead",
|
|
1,
|
|
)],
|
|
&[("res_a", 1)],
|
|
&[("prm_a", 1)],
|
|
"rev-2",
|
|
));
|
|
|
|
let tools_only = Signals {
|
|
resources: false,
|
|
prompts: false,
|
|
tools: true,
|
|
};
|
|
assert_eq!(added.changes_since(&before), tools_only);
|
|
assert_eq!(
|
|
retitled.changes_since(&before),
|
|
tools_only,
|
|
"a retitled binding changes the visible Tool projection without a new Operation version"
|
|
);
|
|
// The reverse direction is a Tool change as well: a removed binding is a real change.
|
|
assert!(before.changes_since(&added).tools);
|
|
}
|
|
|
|
#[test]
|
|
fn a_republished_operation_version_with_an_identical_definition_is_silent() {
|
|
// `tools/list` serves the definition, not the Operation version: a version bump that leaves the
|
|
// served definition unchanged is not a client-visible Tool catalog change.
|
|
let before = CatalogFingerprint::of(&catalog_with(
|
|
ToolSelectionPolicy::default(),
|
|
vec![published_tool(
|
|
"crm_create_lead",
|
|
"Create Lead",
|
|
"Creates a lead",
|
|
1,
|
|
)],
|
|
&[("res_a", 1)],
|
|
&[("prm_a", 1)],
|
|
"rev-1",
|
|
));
|
|
let after = CatalogFingerprint::of(&catalog_with(
|
|
ToolSelectionPolicy::default(),
|
|
vec![published_tool(
|
|
"crm_create_lead",
|
|
"Create Lead",
|
|
"Creates a lead",
|
|
2,
|
|
)],
|
|
&[("res_a", 1)],
|
|
&[("prm_a", 1)],
|
|
"rev-2",
|
|
));
|
|
|
|
assert!(!after.changes_since(&before).any());
|
|
}
|
|
|
|
#[test]
|
|
fn a_policy_only_commit_that_changes_tools_list_is_a_tool_change_only() {
|
|
// The Tool selection policy is part of the served `tools/list` projection: switching the same
|
|
// bindings from direct to search mode replaces the served tools with `search_tools`/`call_tool`.
|
|
let tool = published_tool("crm_create_lead", "Create Lead", "Creates a lead", 1);
|
|
let direct = CatalogFingerprint::of(&catalog_with(
|
|
ToolSelectionPolicy::default(),
|
|
vec![tool.clone()],
|
|
&[("res_a", 1)],
|
|
&[("prm_a", 1)],
|
|
"rev-1",
|
|
));
|
|
let search = CatalogFingerprint::of(&catalog_with(
|
|
search_policy(&["crm_create_lead"]),
|
|
vec![tool],
|
|
&[("res_a", 1)],
|
|
&[("prm_a", 1)],
|
|
"rev-2",
|
|
));
|
|
|
|
let tools_only = Signals {
|
|
resources: false,
|
|
prompts: false,
|
|
tools: true,
|
|
};
|
|
assert_eq!(search.changes_since(&direct), tools_only);
|
|
assert_eq!(direct.changes_since(&search), tools_only);
|
|
}
|
|
|
|
#[test]
|
|
fn a_policy_field_invisible_to_tools_list_is_silent() {
|
|
// `search.max_results` is only served inside the search-mode definitions: in direct mode it
|
|
// changes nothing the client receives.
|
|
let tool = || published_tool("crm_create_lead", "Create Lead", "Creates a lead", 1);
|
|
let before = CatalogFingerprint::of(&catalog_with(
|
|
ToolSelectionPolicy::default(),
|
|
vec![tool()],
|
|
&[],
|
|
&[],
|
|
"rev-1",
|
|
));
|
|
let after = CatalogFingerprint::of(&catalog_with(
|
|
ToolSelectionPolicy {
|
|
search: ToolSearchSettings { max_results: 5 },
|
|
..ToolSelectionPolicy::default()
|
|
},
|
|
vec![tool()],
|
|
&[],
|
|
&[],
|
|
"rev-2",
|
|
));
|
|
|
|
assert!(!after.changes_since(&before).any());
|
|
}
|
|
|
|
#[test]
|
|
fn a_search_mode_binding_change_is_silent_when_tools_list_is_unchanged() {
|
|
// In search mode the served list is `search_tools`/`call_tool`; the bindings behind it are not
|
|
// part of `tools/list`, so a binding-only commit must not claim a visible Tool change.
|
|
let policy = search_policy(&["crm_create_lead"]);
|
|
let before = CatalogFingerprint::of(&catalog_with(
|
|
policy.clone(),
|
|
vec![published_tool(
|
|
"crm_create_lead",
|
|
"Create Lead",
|
|
"Creates a lead",
|
|
1,
|
|
)],
|
|
&[],
|
|
&[],
|
|
"rev-1",
|
|
));
|
|
let after = CatalogFingerprint::of(&catalog_with(
|
|
policy,
|
|
vec![
|
|
published_tool("crm_create_lead", "Create Lead", "Creates a lead", 1),
|
|
published_tool(
|
|
"crm_create_second",
|
|
"Create Second",
|
|
"Creates a second lead",
|
|
1,
|
|
),
|
|
],
|
|
&[],
|
|
&[],
|
|
"rev-2",
|
|
));
|
|
|
|
assert!(!after.changes_since(&before).any());
|
|
}
|
|
|
|
#[test]
|
|
fn a_resource_or_prompt_change_is_not_a_tool_change() {
|
|
let tool = || published_tool("crm_create_lead", "Create Lead", "Creates a lead", 1);
|
|
let before = CatalogFingerprint::of(&catalog_with(
|
|
ToolSelectionPolicy::default(),
|
|
vec![tool()],
|
|
&[("res_a", 1)],
|
|
&[("prm_a", 1)],
|
|
"rev-1",
|
|
));
|
|
let changed = CatalogFingerprint::of(&catalog_with(
|
|
ToolSelectionPolicy::default(),
|
|
vec![tool()],
|
|
&[("res_a", 2)],
|
|
&[("prm_a", 1), ("prm_b", 1)],
|
|
"rev-1",
|
|
));
|
|
|
|
assert_eq!(
|
|
changed.changes_since(&before),
|
|
Signals {
|
|
resources: true,
|
|
prompts: true,
|
|
tools: false
|
|
}
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_catalog_revision_bump_without_a_visible_change_is_silent() {
|
|
// `catalog_revision` moved, but no visible Resource/Prompt/Tool projection did: no signal.
|
|
let before = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-1"));
|
|
let after = CatalogFingerprint::of(&catalog(&[("res_a", 1)], &[("prm_a", 1)], "rev-2"));
|
|
|
|
assert!(!after.changes_since(&before).any());
|
|
}
|
|
|
|
#[test]
|
|
fn the_projection_is_order_independent_and_has_no_duplicate_growth() {
|
|
let forward = CatalogFingerprint::of(&catalog(
|
|
&[("res_a", 1), ("res_b", 2)],
|
|
&[("prm_a", 1), ("prm_b", 2)],
|
|
"rev-1",
|
|
));
|
|
let reversed = CatalogFingerprint::of(&catalog(
|
|
&[("res_b", 2), ("res_a", 1)],
|
|
&[("prm_b", 2), ("prm_a", 1)],
|
|
"rev-1",
|
|
));
|
|
|
|
assert!(!reversed.changes_since(&forward).any());
|
|
}
|
|
|
|
#[test]
|
|
fn the_legacy_frames_carry_a_closed_method_name_and_no_parameters() {
|
|
let frames = Wire::Legacy.signal_frames(Signals::ALL);
|
|
|
|
assert_eq!(
|
|
frames,
|
|
vec![
|
|
json!({"jsonrpc": "2.0", "method": RESOURCE_LIST_CHANGED}).to_string(),
|
|
json!({"jsonrpc": "2.0", "method": PROMPT_LIST_CHANGED}).to_string(),
|
|
json!({"jsonrpc": "2.0", "method": TOOL_LIST_CHANGED}).to_string(),
|
|
]
|
|
);
|
|
// No URI, name or payload of a changed object is part of a list-change notification.
|
|
assert!(frames.iter().all(|frame| !frame.contains("uri")));
|
|
}
|
|
|
|
#[test]
|
|
fn the_modern_frames_carry_the_subscription_id_of_their_listen_request() {
|
|
let id = json!(41);
|
|
let frames = Wire::Modern(id.clone()).signal_frames(Signals::ALL);
|
|
|
|
assert_eq!(
|
|
frames,
|
|
vec![
|
|
json!({
|
|
"jsonrpc": "2.0",
|
|
"method": RESOURCE_LIST_CHANGED,
|
|
"params": { "_meta": { SUBSCRIPTION_ID_KEY: 41 } }
|
|
})
|
|
.to_string(),
|
|
json!({
|
|
"jsonrpc": "2.0",
|
|
"method": PROMPT_LIST_CHANGED,
|
|
"params": { "_meta": { SUBSCRIPTION_ID_KEY: 41 } }
|
|
})
|
|
.to_string(),
|
|
json!({
|
|
"jsonrpc": "2.0",
|
|
"method": TOOL_LIST_CHANGED,
|
|
"params": { "_meta": { SUBSCRIPTION_ID_KEY: 41 } }
|
|
})
|
|
.to_string(),
|
|
]
|
|
);
|
|
assert_eq!(
|
|
serde_json::from_str::<Value>(&frames[0]).unwrap()["params"]["_meta"][SUBSCRIPTION_ID_KEY],
|
|
id
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn only_the_requested_and_honoured_types_are_encoded() {
|
|
let frames = Wire::Modern(json!(1)).signal_frames(Signals {
|
|
resources: false,
|
|
prompts: true,
|
|
tools: false,
|
|
});
|
|
|
|
assert_eq!(frames.len(), 1);
|
|
assert!(frames[0].contains(PROMPT_LIST_CHANGED));
|
|
}
|
|
|
|
#[test]
|
|
fn the_acknowledgment_reports_exactly_the_honoured_subset() {
|
|
let frame: Value = serde_json::from_str(&acknowledged_frame(
|
|
&json!(7),
|
|
Signals {
|
|
resources: true,
|
|
prompts: false,
|
|
tools: true,
|
|
},
|
|
))
|
|
.unwrap();
|
|
|
|
assert_eq!(frame["method"], SUBSCRIPTIONS_ACKNOWLEDGED);
|
|
assert_eq!(frame["params"]["_meta"][SUBSCRIPTION_ID_KEY], json!(7));
|
|
assert_eq!(
|
|
frame["params"]["notifications"],
|
|
json!({ "resourcesListChanged": true, "toolsListChanged": true })
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn an_empty_honoured_subset_is_an_empty_filter_object() {
|
|
let frame: Value =
|
|
serde_json::from_str(&acknowledged_frame(&json!("sub-1"), Signals::default())).unwrap();
|
|
|
|
assert_eq!(frame["params"]["notifications"], json!({}));
|
|
}
|
|
|
|
#[test]
|
|
fn the_filter_keeps_only_the_implemented_list_change_types() {
|
|
let filter: ListenFilter = serde_json::from_value(json!({
|
|
"toolsListChanged": true,
|
|
"promptsListChanged": true,
|
|
"resourcesListChanged": false,
|
|
"resourceSubscriptions": ["file:///project/config.json"]
|
|
}))
|
|
.unwrap();
|
|
|
|
match filter.accepted() {
|
|
FilterOutcome::Accepted(signals) => assert_eq!(
|
|
signals,
|
|
Signals {
|
|
resources: false,
|
|
prompts: true,
|
|
tools: true
|
|
},
|
|
"the honoured set is the requested list-change subset: {signals:?}"
|
|
),
|
|
FilterOutcome::Invalid(detail) => panic!("a bounded filter must be accepted: {detail}"),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn an_absent_filter_field_means_not_subscribed() {
|
|
let filter: ListenFilter = serde_json::from_value(json!({})).unwrap();
|
|
|
|
match filter.accepted() {
|
|
FilterOutcome::Accepted(signals) => assert!(!signals.any()),
|
|
FilterOutcome::Invalid(detail) => panic!("an empty filter must be accepted: {detail}"),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn an_oversized_uri_filter_is_refused_without_echoing_it() {
|
|
let filter: ListenFilter = serde_json::from_value(json!({
|
|
"resourceSubscriptions": (0..=MAX_FILTER_URIS)
|
|
.map(|index| format!("file:///resource-{index}"))
|
|
.collect::<Vec<_>>()
|
|
}))
|
|
.unwrap();
|
|
|
|
match filter.accepted() {
|
|
FilterOutcome::Invalid(detail) => assert_eq!(detail, INVALID_LISTEN_FILTER),
|
|
FilterOutcome::Accepted(_) => panic!("an oversized filter must be refused"),
|
|
}
|
|
|
|
let oversized: ListenFilter = serde_json::from_value(json!({
|
|
"resourceSubscriptions": ["u".repeat(super::MAX_FILTER_URI_BYTES + 1)]
|
|
}))
|
|
.unwrap();
|
|
assert!(matches!(
|
|
oversized.accepted(),
|
|
FilterOutcome::Invalid(INVALID_LISTEN_FILTER)
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn a_non_object_filter_is_a_deserialization_error() {
|
|
assert!(serde_json::from_value::<ListenFilter>(json!(["toolsListChanged"])).is_err());
|
|
assert!(serde_json::from_value::<ListenFilter>(json!({"promptsListChanged": "yes"})).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn the_subscription_id_is_bound_by_its_encoded_size() {
|
|
assert_eq!(subscription_id(&json!(1)), Some(json!(1)));
|
|
assert_eq!(subscription_id(&json!("sub-1")), Some(json!("sub-1")));
|
|
assert_eq!(
|
|
subscription_id(&json!("x".repeat(MAX_SUBSCRIPTION_ID_BYTES))),
|
|
None,
|
|
"an id longer than the frame bound must not be used as a subscription id"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn a_newer_legacy_stream_supersedes_the_previous_one() {
|
|
let streams = StreamRegistry::new();
|
|
let first = streams.admit("session-1").unwrap();
|
|
let second = streams.admit("session-1").unwrap();
|
|
|
|
assert!(!streams.is_current("session-1", first));
|
|
assert!(streams.is_current("session-1", second));
|
|
// Another session is unaffected.
|
|
let other = streams.admit("session-2").unwrap();
|
|
assert!(streams.is_current("session-2", other));
|
|
|
|
streams.retire("session-1");
|
|
assert!(!streams.is_current("session-1", second));
|
|
assert!(streams.is_current("session-2", other));
|
|
}
|
|
|
|
#[derive(Clone, Default)]
|
|
struct SharedLogWriter {
|
|
buffer: Arc<Mutex<Vec<u8>>>,
|
|
}
|
|
|
|
impl SharedLogWriter {
|
|
fn output(&self) -> String {
|
|
String::from_utf8(self.buffer.lock().unwrap().clone()).unwrap()
|
|
}
|
|
}
|
|
|
|
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for SharedLogWriter {
|
|
type Writer = SharedLogGuard;
|
|
|
|
fn make_writer(&'a self) -> Self::Writer {
|
|
SharedLogGuard {
|
|
buffer: Arc::clone(&self.buffer),
|
|
}
|
|
}
|
|
}
|
|
|
|
struct SharedLogGuard {
|
|
buffer: Arc<Mutex<Vec<u8>>>,
|
|
}
|
|
|
|
impl io::Write for SharedLogGuard {
|
|
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
|
self.buffer.lock().unwrap().extend_from_slice(bytes);
|
|
Ok(bytes.len())
|
|
}
|
|
|
|
fn flush(&mut self) -> io::Result<()> {
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
/// AC-2: a failed committed-catalog read is observable and loses nothing — the tick is skipped (no
|
|
/// fabricated signal, no write path that could roll the catalog back) while the baseline survives, so
|
|
/// the next successful read still reports the change of the committed catalog.
|
|
#[tokio::test]
|
|
async fn a_failed_catalog_read_is_observable_and_loses_no_committed_change() {
|
|
let writer = SharedLogWriter::default();
|
|
let subscriber = crank_observability::build_subscriber(
|
|
crank_observability::ObservabilityConfig::new(
|
|
crank_observability::ServiceIdentity::try_new("mcp-server", "test", "test").unwrap(),
|
|
"info",
|
|
crank_observability::RedactionLimits::default(),
|
|
),
|
|
writer.clone(),
|
|
)
|
|
.unwrap();
|
|
let dispatch = tracing::Dispatch::new(subscriber);
|
|
let _guard = tracing::dispatcher::set_default(&dispatch);
|
|
|
|
let baseline = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1)], "rev-1"));
|
|
let committed = CatalogFingerprint::of(&catalog(&[], &[("prm_a", 1), ("prm_b", 1)], "rev-2"));
|
|
let script = Arc::new(Mutex::new(
|
|
vec![Ok(baseline), Err(ReadError::Retry), Ok(committed)].into_iter(),
|
|
));
|
|
let reader: Reader = Box::new(move || {
|
|
let next = script
|
|
.lock()
|
|
.unwrap()
|
|
.next()
|
|
.unwrap_or(Err(ReadError::Retry));
|
|
Box::pin(async move { next })
|
|
});
|
|
|
|
let (sender, mut receiver) = mpsc::channel(SIGNAL_QUEUE_CAPACITY);
|
|
tokio::spawn(run(
|
|
Watch {
|
|
workspace_slug: "workspace-canary".to_owned(),
|
|
agent_slug: "agent-canary".to_owned(),
|
|
signals: Signals::ALL,
|
|
wire: Wire::Legacy,
|
|
legacy_stream: None,
|
|
deadline: Some(Instant::now() + Duration::from_millis(2_100)),
|
|
},
|
|
sender,
|
|
reader,
|
|
));
|
|
|
|
let mut frames = Vec::new();
|
|
while let Some(frame) = receiver.recv().await {
|
|
frames.push(frame);
|
|
}
|
|
|
|
// The failed tick produced no frame; the committed change of the next successful read did.
|
|
assert_eq!(
|
|
frames,
|
|
vec![json!({"jsonrpc": "2.0", "method": PROMPT_LIST_CHANGED}).to_string()]
|
|
);
|
|
|
|
let output = writer.output();
|
|
let failures: Vec<Value> = output
|
|
.lines()
|
|
.filter_map(|line| serde_json::from_str::<Value>(line).ok())
|
|
.filter(|event| event["event"] == "mcp.signals.read_failed")
|
|
.collect();
|
|
assert!(
|
|
!failures.is_empty(),
|
|
"a skipped tick must be observable: {output}"
|
|
);
|
|
for event in &failures {
|
|
assert_eq!(event["fields"]["error_category"], "catalog");
|
|
}
|
|
// Closed vocabulary: no workspace, Agent, URI or raw database text is read into the event.
|
|
assert!(!output.contains("workspace-canary"));
|
|
assert!(!output.contains("agent-canary"));
|
|
}
|