1use std::collections::BTreeMap;
2
3use code_system_graph_model::{
4 Edge, EdgeId, EdgeKind, EpistemicStatus, Evidence, EvidenceId, Node, NodeId, NodeKind, Provenance, RepoId, stable_id
5};
6
7use crate::linker::{http_link_ambiguity, sort_http_ambiguities};
8use crate::{
9 BoundaryRole, ContractImplementationConfig, HttpBoundary, HttpLinkResolution, IntegrationTestConfig, LinkError, normalize_http_path
10};
11
12#[derive(Debug, Clone, PartialEq)]
14pub struct DeclaredTestCase {
15 pub node: Node,
17 pub method: String,
19 pub path: String,
21 pub evidence: Evidence,
23}
24
25#[derive(Debug, Clone, PartialEq)]
27pub struct DeclaredImplementation {
28 pub node: Node,
30 pub method: String,
32 pub path: String,
34 pub evidence: Evidence,
36}
37
38#[must_use]
40pub fn declared_test_case(
41 repo_id: RepoId,
42 config: &IntegrationTestConfig,
43 content_hash: Option<String>,
44) -> DeclaredTestCase {
45 let method = config.validates.method.trim().to_ascii_uppercase();
46 let path = normalize_http_path(&config.validates.path);
47 let stable_key = format!(
48 "test:{}:{}:{}:{}:{}",
49 repo_id.as_str(),
50 config.language.trim().to_ascii_lowercase(),
51 config.framework.trim().to_ascii_lowercase(),
52 config.path,
53 config.name
54 );
55 let evidence_key = format!("{stable_key}:{method}:{path}");
56 DeclaredTestCase {
57 node: Node {
58 id: NodeId::new(stable_id("node", &stable_key)),
59 kind: NodeKind::TestCase,
60 repo_id: Some(repo_id.clone()),
61 stable_key,
62 label: format!("{}/{}::{}", config.language, config.framework, config.name),
63 },
64 method,
65 path,
66 evidence: Evidence {
67 id: EvidenceId::new(stable_id("evidence", &evidence_key)),
68 repo_id: Some(repo_id),
69 file_path: Some(config.path.clone()),
70 start_line: None,
71 end_line: None,
72 extractor: "code-system-graph.tests.declared".to_owned(),
73 extractor_version: env!("CARGO_PKG_VERSION").to_owned(),
74 provenance: Provenance::Declared,
75 confidence: 1.0,
76 observed_at_commit: None,
77 content_hash,
78 note: Some(format!(
79 "{} test declared with {}",
80 config.language, config.framework
81 )),
82 },
83 }
84}
85
86#[must_use]
88pub fn declared_implementation(
89 repo_id: RepoId,
90 config: &ContractImplementationConfig,
91 content_hash: Option<String>,
92) -> DeclaredImplementation {
93 let method = config.implements.method.trim().to_ascii_uppercase();
94 let path = normalize_http_path(&config.implements.path);
95 let identity = crate::SourceSymbolIdentity::new(
96 repo_id.clone(),
97 &config.language,
98 &config.path,
99 &config.symbol,
100 );
101 let stable_key = identity.stable_key();
102 let evidence_key = format!("{stable_key}:{method}:{path}");
103 DeclaredImplementation {
104 node: identity.node(format!("{}::{}", config.language, config.symbol)),
105 method,
106 path,
107 evidence: Evidence {
108 id: EvidenceId::new(stable_id("evidence", &evidence_key)),
109 repo_id: Some(repo_id),
110 file_path: Some(config.path.clone()),
111 start_line: None,
112 end_line: None,
113 extractor: "code-system-graph.implementations.declared".to_owned(),
114 extractor_version: env!("CARGO_PKG_VERSION").to_owned(),
115 provenance: Provenance::Declared,
116 confidence: 1.0,
117 observed_at_commit: None,
118 content_hash,
119 note: Some(format!(
120 "{} symbol declared as contract implementation",
121 config.language
122 )),
123 },
124 }
125}
126
127pub fn link_declared_tests(
139 tests: &[DeclaredTestCase],
140 boundaries: &[HttpBoundary],
141) -> Result<Vec<Edge>, LinkError> {
142 link_declared_tests_with_ambiguities(tests, boundaries).into_legacy_result()
143}
144
145#[must_use]
147pub fn link_declared_tests_with_ambiguities(
148 tests: &[DeclaredTestCase],
149 boundaries: &[HttpBoundary],
150) -> HttpLinkResolution {
151 let mut providers: BTreeMap<(&str, &str), Vec<&HttpBoundary>> = BTreeMap::new();
152 for provider in boundaries
153 .iter()
154 .filter(|boundary| boundary.role == BoundaryRole::Provider)
155 {
156 let candidates = providers
157 .entry((&provider.method, &provider.path))
158 .or_default();
159 if let Some(existing) = candidates
160 .iter()
161 .position(|candidate| candidate.node.id == provider.node.id)
162 {
163 if provider.evidence.confidence > candidates[existing].evidence.confidence {
164 candidates[existing] = provider;
165 }
166 } else {
167 candidates.push(provider);
168 }
169 }
170 let mut edges = Vec::new();
171 let mut ambiguities = Vec::new();
172 for test in tests {
173 let Some(candidates) = providers.get(&(test.method.as_str(), test.path.as_str())) else {
174 continue;
175 };
176 if candidates.len() > 1 {
177 ambiguities.push(http_link_ambiguity(
178 &test.method,
179 &test.path,
180 candidates.iter().map(|candidate| &candidate.node.id),
181 ));
182 continue;
183 }
184 let provider = candidates[0];
185 let edge_key = format!(
186 "{}:validates:{}",
187 test.node.id.as_str(),
188 provider.node.id.as_str()
189 );
190 edges.push(Edge {
191 id: EdgeId::new(stable_id("edge", &edge_key)),
192 source: test.node.id.clone(),
193 target: provider.node.id.clone(),
194 kind: EdgeKind::Validates,
195 confidence: test.evidence.confidence.min(provider.evidence.confidence),
196 status: consensus_status(test.evidence.confidence.min(provider.evidence.confidence)),
197 evidence: vec![test.evidence.id.clone(), provider.evidence.id.clone()],
198 });
199 }
200 edges.sort_by(|left, right| left.id.cmp(&right.id));
201 sort_http_ambiguities(&mut ambiguities);
202 HttpLinkResolution { edges, ambiguities }
203}
204
205pub fn link_declared_implementations(
215 implementations: &[DeclaredImplementation],
216 boundaries: &[HttpBoundary],
217) -> Result<Vec<Edge>, LinkError> {
218 link_declared_implementations_with_ambiguities(implementations, boundaries).into_legacy_result()
219}
220
221#[must_use]
223pub fn link_declared_implementations_with_ambiguities(
224 implementations: &[DeclaredImplementation],
225 boundaries: &[HttpBoundary],
226) -> HttpLinkResolution {
227 let mut edges = BTreeMap::<EdgeId, Edge>::new();
228 let mut ambiguities = Vec::new();
229 for implementation in implementations {
230 let candidates = boundaries
231 .iter()
232 .filter(|boundary| {
233 boundary.role == BoundaryRole::Provider
234 && boundary.node.repo_id == implementation.node.repo_id
235 && boundary.method == implementation.method
236 && boundary.path == implementation.path
237 })
238 .fold(
239 BTreeMap::<NodeId, &HttpBoundary>::new(),
240 |mut candidates, boundary| {
241 candidates
242 .entry(boundary.node.id.clone())
243 .and_modify(|existing| {
244 if boundary.evidence.confidence > existing.evidence.confidence {
245 *existing = boundary;
246 }
247 })
248 .or_insert(boundary);
249 candidates
250 },
251 )
252 .into_values()
253 .collect::<Vec<_>>();
254 if candidates.len() > 1 {
255 ambiguities.push(http_link_ambiguity(
256 &implementation.method,
257 &implementation.path,
258 candidates.iter().map(|candidate| &candidate.node.id),
259 ));
260 continue;
261 }
262 let Some(provider) = candidates.first() else {
263 continue;
264 };
265 let edge_key = format!(
266 "{}:implemented_by:{}",
267 provider.node.id.as_str(),
268 implementation.node.id.as_str()
269 );
270 let confidence = provider
271 .evidence
272 .confidence
273 .min(implementation.evidence.confidence);
274 let edge = Edge {
275 id: EdgeId::new(stable_id("edge", &edge_key)),
276 source: provider.node.id.clone(),
277 target: implementation.node.id.clone(),
278 kind: EdgeKind::ImplementedBy,
279 confidence,
280 status: consensus_status(confidence),
281 evidence: vec![
282 provider.evidence.id.clone(),
283 implementation.evidence.id.clone(),
284 ],
285 };
286 edges
287 .entry(edge.id.clone())
288 .and_modify(|existing| merge_equivalent_implementation_edge(existing, &edge))
289 .or_insert(edge);
290 }
291 sort_http_ambiguities(&mut ambiguities);
292 HttpLinkResolution {
293 edges: edges.into_values().collect(),
294 ambiguities,
295 }
296}
297
298fn merge_equivalent_implementation_edge(existing: &mut Edge, candidate: &Edge) {
299 existing.confidence = existing.confidence.max(candidate.confidence);
300 existing.status = consensus_status(existing.confidence);
301 existing.evidence.extend(candidate.evidence.iter().cloned());
302 existing.evidence.sort();
303 existing.evidence.dedup();
304}
305
306fn consensus_status(confidence: f32) -> EpistemicStatus {
307 if confidence >= 1.0 {
308 EpistemicStatus::Confirmed
309 } else {
310 EpistemicStatus::Inferred
311 }
312}
313
314#[cfg(test)]
315mod tests {
316 use code_system_graph_model::{EdgeKind, EpistemicStatus, RepoId};
317
318 use super::{declared_test_case, link_declared_implementations, link_declared_tests};
319 use crate::{
320 HttpContractConfig, IntegrationTestConfig, extract_openapi, parse_rust_source, source_observations_to_graph
321 };
322
323 #[test]
324 fn declared_python_test_should_validate_rust_provider_with_bilateral_evidence() {
325 let test = declared_test_case(
326 RepoId::new("repo:tests"),
327 &IntegrationTestConfig {
328 name: "test_create_order".to_owned(),
329 path: "tests/test_orders.py".to_owned(),
330 framework: "pytest".to_owned(),
331 language: "python".to_owned(),
332 validates: HttpContractConfig {
333 method: "POST".to_owned(),
334 path: "/api/orders".to_owned(),
335 },
336 },
337 Some("content:test".to_owned()),
338 );
339 let providers = extract_openapi(
340 &RepoId::new("repo:rust-api"),
341 "openapi.yaml",
342 "openapi: 3.1.0\npaths:\n /api/orders:\n post: {}\n",
343 );
344 let result = providers
345 .map_err(|error| error.to_string())
346 .and_then(|providers| {
347 link_declared_tests(&[test], &providers).map_err(|error| error.to_string())
348 });
349
350 assert!(matches!(
351 result,
352 Ok(edges)
353 if edges.len() == 1
354 && edges[0].kind == EdgeKind::Validates
355 && edges[0].evidence.len() == 2
356 ));
357 }
358
359 #[test]
360 fn executable_route_should_outweigh_divergent_utoipa_advisory() {
361 let repo = RepoId::new("repo:rust-api");
362 let observations = parse_rust_source(
363 r#"
364use actix_web::get;
365
366#[utoipa::path(get, path = "/documented")]
367#[get("/runtime")]
368async fn handler() {}
369"#,
370 );
371 let facts =
372 source_observations_to_graph(&repo, "src/routes.rs", "content:routes", &observations);
373 let edges = link_declared_implementations(&facts.implementations, &facts.boundaries)
374 .expect("both exact declarations should remain linkable");
375 let mut consensus = edges
376 .iter()
377 .filter_map(|edge| {
378 let path = facts
379 .boundaries
380 .iter()
381 .find(|boundary| boundary.node.id == edge.source)?
382 .path
383 .clone();
384 Some((path, edge.confidence, edge.status))
385 })
386 .collect::<Vec<_>>();
387 consensus.sort_by(|left, right| left.0.cmp(&right.0));
388
389 assert_eq!(
390 consensus,
391 vec![
392 ("/documented".to_owned(), 0.75, EpistemicStatus::Inferred),
393 ("/runtime".to_owned(), 1.0, EpistemicStatus::Confirmed),
394 ]
395 );
396 }
397
398 #[test]
399 fn executable_route_should_merge_matching_utoipa_advisory() {
400 let repo = RepoId::new("repo:rust-api");
401 let observations = parse_rust_source(
402 r#"
403use actix_web::get;
404
405#[utoipa::path(get, path = "/payments")]
406#[get("/payments")]
407async fn handler() {}
408"#,
409 );
410 let facts =
411 source_observations_to_graph(&repo, "src/routes.rs", "content:routes", &observations);
412 let edges = link_declared_implementations(&facts.implementations, &facts.boundaries)
413 .expect("matching declarations should merge into one implementation edge");
414
415 assert!(matches!(
416 edges.as_slice(),
417 [edge]
418 if edge.kind == EdgeKind::ImplementedBy
419 && (edge.confidence - 1.0).abs() < f32::EPSILON
420 && edge.status == EpistemicStatus::Confirmed
421 && edge.evidence.len() == 3
422 ));
423 }
424}