Skip to main content

code_system_graph_core/
event_graph.rs

1use std::collections::{BTreeMap, BTreeSet};
2
3use code_system_graph_model::{
4    Edge, EdgeId, EdgeKind, EpistemicStatus, Evidence, EvidenceId, Node, NodeId, NodeKind, Provenance, RepoId, stable_id
5};
6
7use crate::{EventBroker, EventDocument, EventObservation, EventRole};
8
9const EVENT_DELIVERY_EVIDENCE_LIMIT: usize = 16;
10
11#[derive(Clone)]
12struct EventObservationAggregate {
13    status: EpistemicStatus,
14    confidence: f32,
15    evidence: BTreeSet<EvidenceId>,
16    evidence_truncated: bool,
17}
18
19type EventObservationsByChannel = BTreeMap<NodeId, BTreeMap<RepoId, EventObservationAggregate>>;
20
21/// Graph facts assembled from workspace-wide event declarations and source observations.
22#[derive(Debug, Clone, Default)]
23pub struct EventGraphFacts {
24    /// Event channels, schemas, source artifacts, and repository nodes.
25    pub nodes: Vec<Node>,
26    /// Publish, subscribe, delivery, schema, and dead-letter relationships.
27    pub edges: Vec<Edge>,
28    /// Direct contract and source-call evidence.
29    pub evidence: Vec<Evidence>,
30}
31
32/// Canonical repository-to-repository delivery inferred from observed publisher and subscriber
33/// edges that share one exact event-channel identity.
34#[derive(Debug, Clone, PartialEq)]
35pub struct EventDeliveryProjection {
36    /// Shared event channel.
37    pub channel_id: NodeId,
38    /// Human-readable channel label.
39    pub channel_label: String,
40    /// Whether broker namespace/cluster identity was observed for the channel.
41    pub namespace_known: bool,
42    /// Unambiguous repository that publishes the event.
43    pub publisher_repository: RepoId,
44    /// Unambiguous repository that subscribes to the event.
45    pub subscriber_repository: RepoId,
46    /// Most conservative epistemic status among the contributing observations.
47    pub status: EpistemicStatus,
48    /// Lowest confidence among the contributing observations.
49    pub confidence: f32,
50    /// Union of evidence supporting the contributing observations.
51    pub evidence: Vec<EvidenceId>,
52    /// Whether additional supporting evidence was omitted by the projection bound.
53    pub evidence_truncated: bool,
54}
55
56/// Bounded result of projecting repository-to-repository event deliveries.
57#[derive(Debug, Clone, PartialEq)]
58pub struct EventDeliveryProjectionReport {
59    /// Canonical deliveries retained within the caller's limit.
60    pub deliveries: Vec<EventDeliveryProjection>,
61    /// Exact number of repository/channel pairs available before the limit.
62    pub total: usize,
63    /// Whether complete deliveries were omitted by the caller's limit.
64    pub truncated: bool,
65    /// Whether cooperative cancellation stopped projection early.
66    pub cancelled: bool,
67}
68
69/// Projects canonical event deliveries from exact publish/subscribe channel joins.
70///
71/// Nodes without a unique repository owner are intentionally excluded. Multiple observations for
72/// the same repository pair and channel are merged, retaining conservative status and all evidence.
73#[must_use]
74pub fn project_event_deliveries<'a>(
75    nodes: impl IntoIterator<Item = &'a Node>,
76    edges: &[Edge],
77    owners: &BTreeMap<NodeId, RepoId>,
78) -> Vec<EventDeliveryProjection> {
79    project_event_deliveries_bounded(nodes, edges, owners, usize::MAX, || false).deliveries
80}
81
82/// Projects event deliveries after first collapsing duplicate observations per repository.
83///
84/// Aggregating before joining changes the adversarial work from observation-level `P × S` to
85/// repository-level pairs. `limit` bounds retained pairs and `cancelled` permits callers with a
86/// request deadline to stop long scans without returning unmarked partial data.
87#[must_use]
88pub fn project_event_deliveries_bounded<'a>(
89    nodes: impl IntoIterator<Item = &'a Node>,
90    edges: &[Edge],
91    owners: &BTreeMap<NodeId, RepoId>,
92    limit: usize,
93    mut cancelled: impl FnMut() -> bool,
94) -> EventDeliveryProjectionReport {
95    let channels = nodes
96        .into_iter()
97        .filter(|node| node.kind == NodeKind::EventChannel)
98        .map(|node| {
99            (
100                node.id.clone(),
101                (node.label.clone(), event_channel_has_namespace(node)),
102            )
103        })
104        .collect::<BTreeMap<_, _>>();
105    let Some((publishers, subscribers)) =
106        aggregate_event_observations(edges, owners, &channels, &mut cancelled)
107    else {
108        return EventDeliveryProjectionReport {
109            deliveries: Vec::new(),
110            total: 0,
111            truncated: false,
112            cancelled: true,
113        };
114    };
115    join_event_observations(publishers, &subscribers, &channels, limit, &mut cancelled)
116}
117
118fn aggregate_event_observations(
119    edges: &[Edge],
120    owners: &BTreeMap<NodeId, RepoId>,
121    channels: &BTreeMap<NodeId, (String, bool)>,
122    cancelled: &mut impl FnMut() -> bool,
123) -> Option<(EventObservationsByChannel, EventObservationsByChannel)> {
124    let mut publishers = EventObservationsByChannel::new();
125    let mut subscribers = EventObservationsByChannel::new();
126    for edge in edges {
127        if cancelled() {
128            return None;
129        }
130        let Some(repository) = owners.get(&edge.source) else {
131            continue;
132        };
133        let observations = match edge.kind {
134            EdgeKind::Publishes if channels.contains_key(&edge.target) => &mut publishers,
135            EdgeKind::Subscribes if channels.contains_key(&edge.target) => &mut subscribers,
136            _ => continue,
137        };
138        let aggregate = observations
139            .entry(edge.target.clone())
140            .or_default()
141            .entry(repository.clone())
142            .or_insert_with(|| EventObservationAggregate {
143                status: edge.status,
144                confidence: edge.confidence,
145                evidence: BTreeSet::new(),
146                evidence_truncated: false,
147            });
148        aggregate.status = conservative_status(aggregate.status, edge.status);
149        aggregate.confidence = aggregate.confidence.min(edge.confidence);
150        for evidence in &edge.evidence {
151            aggregate.evidence.insert(evidence.clone());
152            if aggregate.evidence.len() > EVENT_DELIVERY_EVIDENCE_LIMIT {
153                aggregate.evidence_truncated = true;
154                let _ = aggregate.evidence.pop_last();
155            }
156        }
157    }
158    Some((publishers, subscribers))
159}
160
161fn join_event_observations(
162    publishers: EventObservationsByChannel,
163    subscribers: &EventObservationsByChannel,
164    channels: &BTreeMap<NodeId, (String, bool)>,
165    limit: usize,
166    cancelled: &mut impl FnMut() -> bool,
167) -> EventDeliveryProjectionReport {
168    let total = publishers
169        .iter()
170        .filter_map(|(channel_id, publisher_repositories)| {
171            subscribers.get(channel_id).map(|subscriber_repositories| {
172                publisher_repositories
173                    .len()
174                    .saturating_mul(subscriber_repositories.len())
175            })
176        })
177        .fold(0_usize, usize::saturating_add);
178    let mut deliveries = Vec::with_capacity(total.min(limit));
179    for (channel_id, publisher_repositories) in publishers {
180        let Some(subscriber_repositories) = subscribers.get(&channel_id) else {
181            continue;
182        };
183        for (publisher_repository, publisher) in publisher_repositories {
184            for (subscriber_repository, subscriber) in subscriber_repositories {
185                if cancelled() {
186                    return EventDeliveryProjectionReport {
187                        deliveries,
188                        total,
189                        truncated: true,
190                        cancelled: true,
191                    };
192                }
193                if deliveries.len() == limit {
194                    return EventDeliveryProjectionReport {
195                        deliveries,
196                        total,
197                        truncated: true,
198                        cancelled: false,
199                    };
200                }
201                let (channel_label, has_namespace) =
202                    channels.get(&channel_id).cloned().unwrap_or_default();
203                let mut evidence = publisher
204                    .evidence
205                    .union(&subscriber.evidence)
206                    .take(EVENT_DELIVERY_EVIDENCE_LIMIT + 1)
207                    .cloned()
208                    .collect::<Vec<_>>();
209                let evidence_truncated = publisher.evidence_truncated
210                    || subscriber.evidence_truncated
211                    || evidence.len() > EVENT_DELIVERY_EVIDENCE_LIMIT;
212                evidence.truncate(EVENT_DELIVERY_EVIDENCE_LIMIT);
213                let observed_status = conservative_status(publisher.status, subscriber.status);
214                deliveries.push(EventDeliveryProjection {
215                    channel_label,
216                    channel_id: channel_id.clone(),
217                    namespace_known: has_namespace,
218                    publisher_repository: publisher_repository.clone(),
219                    subscriber_repository: subscriber_repository.clone(),
220                    status: if has_namespace {
221                        observed_status
222                    } else {
223                        conservative_status(observed_status, EpistemicStatus::Ambiguous)
224                    },
225                    confidence: if has_namespace {
226                        publisher.confidence.min(subscriber.confidence)
227                    } else {
228                        publisher.confidence.min(subscriber.confidence).min(0.5)
229                    },
230                    evidence,
231                    evidence_truncated,
232                });
233            }
234        }
235    }
236    EventDeliveryProjectionReport {
237        truncated: deliveries.len() < total,
238        deliveries,
239        total,
240        cancelled: false,
241    }
242}
243
244fn event_channel_has_namespace(node: &Node) -> bool {
245    node.stable_key
246        .strip_prefix("event:")
247        .and_then(|identity| identity.split_once(':'))
248        .and_then(|(_, identity)| identity.split_once(':'))
249        .is_some_and(|(namespace, _)| !namespace.is_empty())
250}
251
252fn conservative_status(left: EpistemicStatus, right: EpistemicStatus) -> EpistemicStatus {
253    const fn severity(status: EpistemicStatus) -> u8 {
254        match status {
255            EpistemicStatus::Confirmed => 0,
256            EpistemicStatus::Inferred => 1,
257            EpistemicStatus::Ambiguous => 2,
258            EpistemicStatus::Stale => 3,
259            EpistemicStatus::Incomplete => 4,
260        }
261    }
262    if severity(left) >= severity(right) {
263        left
264    } else {
265        right
266    }
267}
268
269struct EventEndpoint {
270    repo_id: RepoId,
271    source_path: String,
272    observation: EventObservation,
273    evidence: Evidence,
274}
275
276/// Converts event documents into deterministic, ambiguity-safe graph facts.
277///
278/// Source observations without a namespace link to a declared broker/channel only when exactly
279/// one namespace candidate exists. Generic source APIs link to a broker-specific declaration only
280/// when the channel has one unambiguous declaration across the workspace.
281#[must_use]
282pub fn event_documents_to_graph(
283    inputs: &[(&RepoId, &str, &str, &EventDocument)],
284) -> EventGraphFacts {
285    let mut result = EventGraphFacts::default();
286    let mut declarations = Vec::new();
287    let mut endpoints = Vec::new();
288    for (repo_id, source_path, content_hash, document) in inputs {
289        let repository = repository_node(repo_id);
290        let artifact = artifact_node(repo_id, source_path);
291        let artifact_evidence =
292            event_evidence(repo_id, source_path, content_hash, None, "event artifact");
293        result.edges.push(edge(
294            &repository.id,
295            &artifact.id,
296            EdgeKind::Contains,
297            vec![artifact_evidence.id.clone()],
298        ));
299        result.nodes.extend([repository, artifact]);
300        result.evidence.push(artifact_evidence);
301        for observation in &document.observations {
302            if observation.channel.is_none() || observation.incomplete {
303                continue;
304            }
305            let evidence = event_evidence(
306                repo_id,
307                source_path,
308                content_hash,
309                Some(observation),
310                "event boundary",
311            );
312            let endpoint = EventEndpoint {
313                repo_id: (*repo_id).clone(),
314                source_path: (*source_path).to_owned(),
315                observation: observation.clone(),
316                evidence,
317            };
318            if observation.language.is_none() || observation.role == EventRole::Declaration {
319                declarations.push(endpoint);
320            } else {
321                endpoints.push(endpoint);
322            }
323        }
324    }
325    append_declarations(&declarations, &mut result);
326    append_endpoints(&declarations, &endpoints, &mut result);
327    finish(&mut result);
328    result
329}
330
331fn append_declarations(declarations: &[EventEndpoint], result: &mut EventGraphFacts) {
332    for declaration in declarations {
333        let channel = channel_node(&declaration.observation);
334        let artifact = artifact_node(&declaration.repo_id, &declaration.source_path);
335        result.edges.push(edge(
336            &artifact.id,
337            &channel.id,
338            match declaration.observation.role {
339                EventRole::Publisher => EdgeKind::Publishes,
340                EventRole::Subscriber => EdgeKind::Subscribes,
341                EventRole::Declaration => EdgeKind::Contains,
342            },
343            vec![declaration.evidence.id.clone()],
344        ));
345        append_schema(declaration, &channel, result);
346        append_dead_letter(declaration, &channel, result);
347        result.nodes.push(channel);
348        result.evidence.push(declaration.evidence.clone());
349    }
350}
351
352fn append_endpoints(
353    declarations: &[EventEndpoint],
354    endpoints: &[EventEndpoint],
355    result: &mut EventGraphFacts,
356) {
357    for endpoint in endpoints {
358        let channel = resolve_channel(declarations, endpoint).map_or_else(
359            || channel_node(&endpoint.observation),
360            |declaration| channel_node(&declaration.observation),
361        );
362        let source = source_node(endpoint);
363        match endpoint.observation.role {
364            EventRole::Publisher => result.edges.push(edge(
365                &source.id,
366                &channel.id,
367                EdgeKind::Publishes,
368                vec![endpoint.evidence.id.clone()],
369            )),
370            EventRole::Subscriber => {
371                result.edges.push(edge(
372                    &source.id,
373                    &channel.id,
374                    EdgeKind::Subscribes,
375                    vec![endpoint.evidence.id.clone()],
376                ));
377                result.edges.push(edge(
378                    &channel.id,
379                    &source.id,
380                    EdgeKind::DeliversTo,
381                    vec![endpoint.evidence.id.clone()],
382                ));
383            }
384            EventRole::Declaration => {}
385        }
386        result.nodes.extend([source, channel]);
387        result.evidence.push(endpoint.evidence.clone());
388    }
389}
390
391fn resolve_channel<'a>(
392    declarations: &'a [EventEndpoint],
393    endpoint: &EventEndpoint,
394) -> Option<&'a EventEndpoint> {
395    let channel = endpoint.observation.channel.as_deref()?;
396    let candidates = declarations
397        .iter()
398        .filter(|declaration| {
399            declaration.observation.channel.as_deref() == Some(channel)
400                && (endpoint.observation.broker == EventBroker::Generic
401                    || declaration.observation.broker == endpoint.observation.broker)
402                && endpoint
403                    .observation
404                    .namespace
405                    .as_ref()
406                    .is_none_or(|namespace| {
407                        declaration.observation.namespace.as_ref() == Some(namespace)
408                    })
409        })
410        .collect::<Vec<_>>();
411    let first = candidates.first().copied()?;
412    let identity = channel_node(&first.observation).id;
413    candidates
414        .iter()
415        .all(|candidate| channel_node(&candidate.observation).id == identity)
416        .then_some(first)
417}
418
419fn append_schema(declaration: &EventEndpoint, channel: &Node, result: &mut EventGraphFacts) {
420    let Some(schema) = &declaration.observation.schema else {
421        return;
422    };
423    let Some(name) = schema
424        .name
425        .as_deref()
426        .or(declaration.observation.event_type.as_deref())
427    else {
428        return;
429    };
430    let stable_key = format!(
431        "event-schema:{:?}:{name}:{}",
432        declaration.observation.broker,
433        schema.version.as_deref().unwrap_or("")
434    );
435    let node = Node {
436        id: NodeId::new(stable_id("node", &stable_key)),
437        kind: NodeKind::EventSchema,
438        repo_id: Some(declaration.repo_id.clone()),
439        stable_key,
440        label: name.to_owned(),
441    };
442    result.edges.push(edge(
443        &channel.id,
444        &node.id,
445        EdgeKind::Contains,
446        vec![declaration.evidence.id.clone()],
447    ));
448    result.nodes.push(node);
449}
450
451fn append_dead_letter(declaration: &EventEndpoint, channel: &Node, result: &mut EventGraphFacts) {
452    let Some(dead_letter) = &declaration.observation.dead_letter_channel else {
453        return;
454    };
455    let mut observation = declaration.observation.clone();
456    observation.channel = Some(dead_letter.clone());
457    let target = channel_node(&observation);
458    result.edges.push(edge(
459        &channel.id,
460        &target.id,
461        EdgeKind::CallsRemote,
462        vec![declaration.evidence.id.clone()],
463    ));
464    result.nodes.push(target);
465}
466
467fn source_node(endpoint: &EventEndpoint) -> Node {
468    let channel = endpoint.observation.channel.as_deref().unwrap_or("dynamic");
469    let stable_key = format!(
470        "event-source:{}:{}:{:?}:{channel}:{:?}",
471        endpoint.repo_id.as_str(),
472        endpoint.source_path,
473        endpoint.observation.role,
474        endpoint.observation.broker
475    );
476    Node {
477        id: NodeId::new(stable_id("node", &stable_key)),
478        kind: NodeKind::SymbolRef,
479        repo_id: Some(endpoint.repo_id.clone()),
480        stable_key,
481        label: format!("{} {channel}", endpoint.source_path),
482    }
483}
484
485fn channel_node(observation: &EventObservation) -> Node {
486    let channel = observation.channel.as_deref().unwrap_or("dynamic");
487    let stable_key = format!(
488        "event:{:?}:{}:{channel}",
489        observation.broker,
490        observation.namespace.as_deref().unwrap_or("")
491    );
492    Node {
493        id: NodeId::new(stable_id("node", &stable_key)),
494        kind: NodeKind::EventChannel,
495        repo_id: None,
496        stable_key,
497        label: channel.to_owned(),
498    }
499}
500
501fn artifact_node(repo_id: &RepoId, source_path: &str) -> Node {
502    let stable_key = format!("event-artifact:{}:{source_path}", repo_id.as_str());
503    Node {
504        id: NodeId::new(stable_id("node", &stable_key)),
505        kind: NodeKind::Artifact,
506        repo_id: Some(repo_id.clone()),
507        stable_key,
508        label: source_path.to_owned(),
509    }
510}
511
512fn repository_node(repo_id: &RepoId) -> Node {
513    let stable_key = format!("repository:{}", repo_id.as_str());
514    Node {
515        id: NodeId::new(stable_id("node", &stable_key)),
516        kind: NodeKind::Repository,
517        repo_id: Some(repo_id.clone()),
518        stable_key,
519        label: repo_id.as_str().to_owned(),
520    }
521}
522
523fn event_evidence(
524    repo_id: &RepoId,
525    source_path: &str,
526    content_hash: &str,
527    observation: Option<&EventObservation>,
528    note: &str,
529) -> Evidence {
530    let line = observation
531        .and_then(|observation| observation.evidence.first())
532        .map_or(1, |evidence| evidence.line);
533    let key = format!(
534        "{}:{source_path}:{line}:{note}:{content_hash}",
535        repo_id.as_str()
536    );
537    Evidence {
538        id: EvidenceId::new(stable_id("evidence", &key)),
539        repo_id: Some(repo_id.clone()),
540        file_path: Some(source_path.to_owned()),
541        start_line: Some(line),
542        end_line: Some(line),
543        extractor: "code-system-graph.events".to_owned(),
544        extractor_version: "1.0.0".to_owned(),
545        provenance: Provenance::Extracted,
546        confidence: observation.map_or(1.0, |observation| observation.confidence),
547        observed_at_commit: None,
548        content_hash: Some(content_hash.to_owned()),
549        note: Some(note.to_owned()),
550    }
551}
552
553fn edge(source: &NodeId, target: &NodeId, kind: EdgeKind, evidence: Vec<EvidenceId>) -> Edge {
554    let key = format!("{}:{kind:?}:{}", source.as_str(), target.as_str());
555    Edge {
556        id: EdgeId::new(stable_id("edge", &key)),
557        source: source.clone(),
558        target: target.clone(),
559        kind,
560        confidence: 1.0,
561        status: EpistemicStatus::Confirmed,
562        evidence,
563    }
564}
565
566fn finish(result: &mut EventGraphFacts) {
567    result.nodes.sort_by(|left, right| left.id.cmp(&right.id));
568    result.nodes.dedup_by(|left, right| left.id == right.id);
569    result.edges.sort_by(|left, right| left.id.cmp(&right.id));
570    result.edges.dedup_by(|left, right| left.id == right.id);
571    result
572        .evidence
573        .sort_by(|left, right| left.id.cmp(&right.id));
574    result.evidence.dedup_by(|left, right| left.id == right.id);
575}
576
577#[cfg(test)]
578mod tests {
579    use std::collections::BTreeMap;
580
581    use code_system_graph_model::{
582        Edge, EdgeId, EdgeKind, EpistemicStatus, EvidenceId, Node, NodeId, NodeKind, RepoId
583    };
584
585    use super::{
586        event_documents_to_graph, project_event_deliveries, project_event_deliveries_bounded
587    };
588    use crate::{SourceLanguage, extract_asyncapi, parse_event_source};
589
590    #[test]
591    fn event_graph_should_trace_publisher_through_channel_to_subscriber() {
592        let declaration = extract_asyncapi(
593            "asyncapi.yaml",
594            r"
595asyncapi: 2.6.0
596info: { title: events, version: 1.0.0 }
597servers:
598  kafka: { url: kafka:9092, protocol: kafka }
599channels:
600  orders.created:
601    publish: { message: { name: OrderCreated } }
602",
603        );
604        let publisher = parse_event_source(
605            SourceLanguage::Rust,
606            r#"kafka_producer.send("orders.created", payload);"#,
607        );
608        let subscriber = parse_event_source(
609            SourceLanguage::Python,
610            r#"kafka_consumer.subscribe("orders.created")"#,
611        );
612        let api = RepoId::new("repo:api");
613        let worker = RepoId::new("repo:worker");
614        let facts = declaration.as_ref().ok().map(|declaration| {
615            event_documents_to_graph(&[
616                (&api, "asyncapi.yaml", "contract", declaration),
617                (&api, "src/lib.rs", "publisher", &publisher),
618                (&worker, "worker.py", "subscriber", &subscriber),
619            ])
620        });
621
622        assert!(matches!(
623            facts,
624            Some(facts)
625                if [EdgeKind::Publishes, EdgeKind::Subscribes, EdgeKind::DeliversTo]
626                    .into_iter()
627                    .all(|kind| facts.edges.iter().any(|edge| edge.kind == kind))
628        ));
629    }
630
631    #[test]
632    fn event_delivery_projection_merges_duplicate_observations_conservatively() {
633        let channel = Node {
634            id: NodeId::new("channel"),
635            kind: NodeKind::EventChannel,
636            repo_id: None,
637            stable_key: "event:Kafka:cluster-a:orders".to_owned(),
638            label: "orders.created".to_owned(),
639        };
640        let owners = BTreeMap::from([
641            (NodeId::new("publisher"), RepoId::new("repo:api")),
642            (NodeId::new("subscriber"), RepoId::new("repo:worker")),
643        ]);
644        let event_edge = |id: &str,
645                          source: &str,
646                          kind: EdgeKind,
647                          status: EpistemicStatus,
648                          confidence: f32,
649                          evidence: &str| Edge {
650            id: EdgeId::new(id),
651            source: NodeId::new(source),
652            target: NodeId::new("channel"),
653            kind,
654            confidence,
655            status,
656            evidence: vec![EvidenceId::new(evidence)],
657        };
658        let edges = vec![
659            event_edge(
660                "publish-a",
661                "publisher",
662                EdgeKind::Publishes,
663                EpistemicStatus::Confirmed,
664                0.9,
665                "evidence:a",
666            ),
667            event_edge(
668                "publish-b",
669                "publisher",
670                EdgeKind::Publishes,
671                EpistemicStatus::Inferred,
672                0.7,
673                "evidence:b",
674            ),
675            event_edge(
676                "subscribe",
677                "subscriber",
678                EdgeKind::Subscribes,
679                EpistemicStatus::Confirmed,
680                0.8,
681                "evidence:c",
682            ),
683        ];
684
685        let projections = project_event_deliveries(&[channel], &edges, &owners);
686
687        assert_eq!(projections.len(), 1);
688        assert_eq!(projections[0].status, EpistemicStatus::Inferred);
689        assert!((projections[0].confidence - 0.7).abs() < f32::EPSILON);
690        assert_eq!(projections[0].evidence.len(), 3);
691    }
692
693    #[test]
694    fn event_delivery_projection_aggregates_before_a_bounded_repository_join() {
695        let channel = Node {
696            id: NodeId::new("channel"),
697            kind: NodeKind::EventChannel,
698            repo_id: None,
699            stable_key: "event:Kafka:cluster-a:shared".to_owned(),
700            label: "shared.event".to_owned(),
701        };
702        let mut owners = BTreeMap::new();
703        let mut edges = Vec::new();
704        for index in 0..100 {
705            for (role, kind) in [
706                ("publisher", EdgeKind::Publishes),
707                ("subscriber", EdgeKind::Subscribes),
708            ] {
709                let source = format!("{role}:{index}");
710                owners.insert(
711                    NodeId::new(&source),
712                    RepoId::new(format!("repo:{role}:{index}")),
713                );
714                edges.push(Edge {
715                    id: EdgeId::new(format!("edge:{role}:{index}")),
716                    source: NodeId::new(source),
717                    target: NodeId::new("channel"),
718                    kind,
719                    confidence: 1.0,
720                    status: EpistemicStatus::Confirmed,
721                    evidence: Vec::new(),
722                });
723            }
724        }
725
726        let mut cancellation_checks = 0_usize;
727        let report = project_event_deliveries_bounded(&[channel], &edges, &owners, 32, || {
728            cancellation_checks += 1;
729            false
730        });
731
732        assert_eq!(report.total, 10_000);
733        assert_eq!(report.deliveries.len(), 32);
734        assert!(report.truncated);
735        assert!(!report.cancelled);
736        assert!(cancellation_checks <= edges.len() + report.deliveries.len() + 1);
737    }
738
739    #[test]
740    fn event_delivery_without_namespace_is_ambiguous_and_evidence_is_bounded() {
741        let channel = Node {
742            id: NodeId::new("channel"),
743            kind: NodeKind::EventChannel,
744            repo_id: None,
745            stable_key: "event:Kafka::orders".to_owned(),
746            label: "orders".to_owned(),
747        };
748        let owners = BTreeMap::from([
749            (NodeId::new("publisher"), RepoId::new("repo:api")),
750            (NodeId::new("subscriber"), RepoId::new("repo:worker")),
751        ]);
752        let evidence = (0..100)
753            .map(|index| EvidenceId::new(format!("evidence:{index:03}")))
754            .collect::<Vec<_>>();
755        let edges = vec![
756            Edge {
757                id: EdgeId::new("publish"),
758                source: NodeId::new("publisher"),
759                target: NodeId::new("channel"),
760                kind: EdgeKind::Publishes,
761                confidence: 1.0,
762                status: EpistemicStatus::Confirmed,
763                evidence: evidence.clone(),
764            },
765            Edge {
766                id: EdgeId::new("subscribe"),
767                source: NodeId::new("subscriber"),
768                target: NodeId::new("channel"),
769                kind: EdgeKind::Subscribes,
770                confidence: 1.0,
771                status: EpistemicStatus::Confirmed,
772                evidence,
773            },
774        ];
775
776        let deliveries = project_event_deliveries(&[channel], &edges, &owners);
777
778        assert_eq!(deliveries.len(), 1);
779        assert_eq!(deliveries[0].status, EpistemicStatus::Ambiguous);
780        assert!((deliveries[0].confidence - 0.5).abs() < f32::EPSILON);
781        assert_eq!(
782            deliveries[0].evidence.len(),
783            super::EVENT_DELIVERY_EVIDENCE_LIMIT
784        );
785        assert!(deliveries[0].evidence_truncated);
786    }
787}