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 = Vec::new();
204                for item in publisher
205                    .evidence
206                    .first()
207                    .into_iter()
208                    .chain(subscriber.evidence.first())
209                    .chain(publisher.evidence.union(&subscriber.evidence))
210                {
211                    if !evidence.contains(item) {
212                        evidence.push(item.clone());
213                    }
214                    if evidence.len() > EVENT_DELIVERY_EVIDENCE_LIMIT {
215                        break;
216                    }
217                }
218                let evidence_truncated = publisher.evidence_truncated
219                    || subscriber.evidence_truncated
220                    || evidence.len() > EVENT_DELIVERY_EVIDENCE_LIMIT;
221                evidence.truncate(EVENT_DELIVERY_EVIDENCE_LIMIT);
222                let observed_status = conservative_status(publisher.status, subscriber.status);
223                deliveries.push(EventDeliveryProjection {
224                    channel_label,
225                    channel_id: channel_id.clone(),
226                    namespace_known: has_namespace,
227                    publisher_repository: publisher_repository.clone(),
228                    subscriber_repository: subscriber_repository.clone(),
229                    status: if has_namespace {
230                        observed_status
231                    } else {
232                        conservative_status(observed_status, EpistemicStatus::Ambiguous)
233                    },
234                    confidence: if has_namespace {
235                        publisher.confidence.min(subscriber.confidence)
236                    } else {
237                        publisher.confidence.min(subscriber.confidence).min(0.5)
238                    },
239                    evidence,
240                    evidence_truncated,
241                });
242            }
243        }
244    }
245    EventDeliveryProjectionReport {
246        truncated: deliveries.len() < total,
247        deliveries,
248        total,
249        cancelled: false,
250    }
251}
252
253fn event_channel_has_namespace(node: &Node) -> bool {
254    node.stable_key
255        .strip_prefix("event:")
256        .and_then(|identity| identity.split_once(':'))
257        .and_then(|(_, identity)| identity.split_once(':'))
258        .is_some_and(|(namespace, _)| !namespace.is_empty())
259}
260
261fn conservative_status(left: EpistemicStatus, right: EpistemicStatus) -> EpistemicStatus {
262    const fn severity(status: EpistemicStatus) -> u8 {
263        match status {
264            EpistemicStatus::Confirmed => 0,
265            EpistemicStatus::Inferred => 1,
266            EpistemicStatus::Ambiguous => 2,
267            EpistemicStatus::Stale => 3,
268            EpistemicStatus::Incomplete => 4,
269        }
270    }
271    if severity(left) >= severity(right) {
272        left
273    } else {
274        right
275    }
276}
277
278struct EventEndpoint {
279    repo_id: RepoId,
280    source_path: String,
281    observation: EventObservation,
282    evidence: Evidence,
283}
284
285/// Converts event documents into deterministic, ambiguity-safe graph facts.
286///
287/// Source observations without a namespace link to a declared broker/channel only when exactly
288/// one namespace candidate exists. Generic source APIs link to a broker-specific declaration only
289/// when the channel has one unambiguous declaration across the workspace.
290#[must_use]
291pub fn event_documents_to_graph(
292    inputs: &[(&RepoId, &str, &str, &EventDocument)],
293) -> EventGraphFacts {
294    let mut result = EventGraphFacts::default();
295    let mut declarations = Vec::new();
296    let mut endpoints = Vec::new();
297    for (repo_id, source_path, content_hash, document) in inputs {
298        let repository = repository_node(repo_id);
299        let artifact = artifact_node(repo_id, source_path);
300        let artifact_evidence =
301            event_evidence(repo_id, source_path, content_hash, None, "event artifact");
302        result.edges.push(edge(
303            &repository.id,
304            &artifact.id,
305            EdgeKind::Contains,
306            vec![artifact_evidence.id.clone()],
307        ));
308        result.nodes.extend([repository, artifact]);
309        result.evidence.push(artifact_evidence);
310        for observation in &document.observations {
311            if observation.channel.is_none() || observation.incomplete {
312                continue;
313            }
314            let evidence = event_evidence(
315                repo_id,
316                source_path,
317                content_hash,
318                Some(observation),
319                "event boundary",
320            );
321            let endpoint = EventEndpoint {
322                repo_id: (*repo_id).clone(),
323                source_path: (*source_path).to_owned(),
324                observation: observation.clone(),
325                evidence,
326            };
327            if observation.language.is_none() || observation.role == EventRole::Declaration {
328                declarations.push(endpoint);
329            } else {
330                endpoints.push(endpoint);
331            }
332        }
333    }
334    append_declarations(&declarations, &mut result);
335    append_endpoints(&declarations, &endpoints, &mut result);
336    finish(&mut result);
337    result
338}
339
340fn append_declarations(declarations: &[EventEndpoint], result: &mut EventGraphFacts) {
341    for declaration in declarations {
342        let channel = channel_node(&declaration.observation);
343        let artifact = artifact_node(&declaration.repo_id, &declaration.source_path);
344        result.edges.push(edge(
345            &artifact.id,
346            &channel.id,
347            match declaration.observation.role {
348                EventRole::Publisher => EdgeKind::Publishes,
349                EventRole::Subscriber => EdgeKind::Subscribes,
350                EventRole::Declaration => EdgeKind::Contains,
351            },
352            vec![declaration.evidence.id.clone()],
353        ));
354        append_schema(declaration, &channel, result);
355        append_dead_letter(declaration, &channel, result);
356        result.nodes.push(channel);
357        result.evidence.push(declaration.evidence.clone());
358    }
359}
360
361fn append_endpoints(
362    declarations: &[EventEndpoint],
363    endpoints: &[EventEndpoint],
364    result: &mut EventGraphFacts,
365) {
366    for endpoint in endpoints {
367        let channel = resolve_channel(declarations, endpoint).map_or_else(
368            || channel_node(&endpoint.observation),
369            |declaration| channel_node(&declaration.observation),
370        );
371        let source = source_node(endpoint);
372        match endpoint.observation.role {
373            EventRole::Publisher => result.edges.push(edge(
374                &source.id,
375                &channel.id,
376                EdgeKind::Publishes,
377                vec![endpoint.evidence.id.clone()],
378            )),
379            EventRole::Subscriber => {
380                result.edges.push(edge(
381                    &source.id,
382                    &channel.id,
383                    EdgeKind::Subscribes,
384                    vec![endpoint.evidence.id.clone()],
385                ));
386                result.edges.push(edge(
387                    &channel.id,
388                    &source.id,
389                    EdgeKind::DeliversTo,
390                    vec![endpoint.evidence.id.clone()],
391                ));
392            }
393            EventRole::Declaration => {}
394        }
395        result.nodes.extend([source, channel]);
396        result.evidence.push(endpoint.evidence.clone());
397    }
398}
399
400fn resolve_channel<'a>(
401    declarations: &'a [EventEndpoint],
402    endpoint: &EventEndpoint,
403) -> Option<&'a EventEndpoint> {
404    let channel = endpoint.observation.channel.as_deref()?;
405    let candidates = declarations
406        .iter()
407        .filter(|declaration| {
408            declaration.observation.channel.as_deref() == Some(channel)
409                && (endpoint.observation.broker == EventBroker::Generic
410                    || declaration.observation.broker == endpoint.observation.broker)
411                && endpoint
412                    .observation
413                    .namespace
414                    .as_ref()
415                    .is_none_or(|namespace| {
416                        declaration.observation.namespace.as_ref() == Some(namespace)
417                    })
418        })
419        .collect::<Vec<_>>();
420    let first = candidates.first().copied()?;
421    let identity = channel_node(&first.observation).id;
422    candidates
423        .iter()
424        .all(|candidate| channel_node(&candidate.observation).id == identity)
425        .then_some(first)
426}
427
428fn append_schema(declaration: &EventEndpoint, channel: &Node, result: &mut EventGraphFacts) {
429    let Some(schema) = &declaration.observation.schema else {
430        return;
431    };
432    let Some(name) = schema
433        .name
434        .as_deref()
435        .or(declaration.observation.event_type.as_deref())
436    else {
437        return;
438    };
439    let stable_key = format!(
440        "event-schema:{:?}:{name}:{}",
441        declaration.observation.broker,
442        schema.version.as_deref().unwrap_or("")
443    );
444    let node = Node {
445        id: NodeId::new(stable_id("node", &stable_key)),
446        kind: NodeKind::EventSchema,
447        repo_id: Some(declaration.repo_id.clone()),
448        stable_key,
449        label: name.to_owned(),
450    };
451    result.edges.push(edge(
452        &channel.id,
453        &node.id,
454        EdgeKind::Contains,
455        vec![declaration.evidence.id.clone()],
456    ));
457    result.nodes.push(node);
458}
459
460fn append_dead_letter(declaration: &EventEndpoint, channel: &Node, result: &mut EventGraphFacts) {
461    let Some(dead_letter) = &declaration.observation.dead_letter_channel else {
462        return;
463    };
464    let mut observation = declaration.observation.clone();
465    observation.channel = Some(dead_letter.clone());
466    let target = channel_node(&observation);
467    result.edges.push(edge(
468        &channel.id,
469        &target.id,
470        EdgeKind::CallsRemote,
471        vec![declaration.evidence.id.clone()],
472    ));
473    result.nodes.push(target);
474}
475
476fn source_node(endpoint: &EventEndpoint) -> Node {
477    let channel = endpoint.observation.channel.as_deref().unwrap_or("dynamic");
478    let stable_key = format!(
479        "event-source:{}:{}:{:?}:{channel}:{:?}",
480        endpoint.repo_id.as_str(),
481        endpoint.source_path,
482        endpoint.observation.role,
483        endpoint.observation.broker
484    );
485    Node {
486        id: NodeId::new(stable_id("node", &stable_key)),
487        kind: NodeKind::SymbolRef,
488        repo_id: Some(endpoint.repo_id.clone()),
489        stable_key,
490        label: format!("{} {channel}", endpoint.source_path),
491    }
492}
493
494fn channel_node(observation: &EventObservation) -> Node {
495    let channel = observation.channel.as_deref().unwrap_or("dynamic");
496    let stable_key = format!(
497        "event:{:?}:{}:{channel}",
498        observation.broker,
499        observation.namespace.as_deref().unwrap_or("")
500    );
501    Node {
502        id: NodeId::new(stable_id("node", &stable_key)),
503        kind: NodeKind::EventChannel,
504        repo_id: None,
505        stable_key,
506        label: channel.to_owned(),
507    }
508}
509
510fn artifact_node(repo_id: &RepoId, source_path: &str) -> Node {
511    let stable_key = format!("event-artifact:{}:{source_path}", repo_id.as_str());
512    Node {
513        id: NodeId::new(stable_id("node", &stable_key)),
514        kind: NodeKind::Artifact,
515        repo_id: Some(repo_id.clone()),
516        stable_key,
517        label: source_path.to_owned(),
518    }
519}
520
521fn repository_node(repo_id: &RepoId) -> Node {
522    let stable_key = format!("repository:{}", repo_id.as_str());
523    Node {
524        id: NodeId::new(stable_id("node", &stable_key)),
525        kind: NodeKind::Repository,
526        repo_id: Some(repo_id.clone()),
527        stable_key,
528        label: repo_id.as_str().to_owned(),
529    }
530}
531
532fn event_evidence(
533    repo_id: &RepoId,
534    source_path: &str,
535    content_hash: &str,
536    observation: Option<&EventObservation>,
537    note: &str,
538) -> Evidence {
539    let line = observation
540        .and_then(|observation| observation.evidence.first())
541        .map_or(1, |evidence| evidence.line);
542    let key = format!(
543        "{}:{source_path}:{line}:{note}:{content_hash}",
544        repo_id.as_str()
545    );
546    Evidence {
547        id: EvidenceId::new(stable_id("evidence", &key)),
548        repo_id: Some(repo_id.clone()),
549        file_path: Some(source_path.to_owned()),
550        start_line: Some(line),
551        end_line: Some(line),
552        extractor: "code-system-graph.events".to_owned(),
553        extractor_version: "1.0.0".to_owned(),
554        provenance: Provenance::Extracted,
555        confidence: observation.map_or(1.0, |observation| observation.confidence),
556        observed_at_commit: None,
557        content_hash: Some(content_hash.to_owned()),
558        note: Some(note.to_owned()),
559    }
560}
561
562fn edge(source: &NodeId, target: &NodeId, kind: EdgeKind, evidence: Vec<EvidenceId>) -> Edge {
563    let key = format!("{}:{kind:?}:{}", source.as_str(), target.as_str());
564    Edge {
565        id: EdgeId::new(stable_id("edge", &key)),
566        source: source.clone(),
567        target: target.clone(),
568        kind,
569        confidence: 1.0,
570        status: EpistemicStatus::Confirmed,
571        evidence,
572    }
573}
574
575fn finish(result: &mut EventGraphFacts) {
576    result.nodes.sort_by(|left, right| left.id.cmp(&right.id));
577    result.nodes.dedup_by(|left, right| left.id == right.id);
578    result.edges.sort_by(|left, right| left.id.cmp(&right.id));
579    result.edges.dedup_by(|left, right| left.id == right.id);
580    result
581        .evidence
582        .sort_by(|left, right| left.id.cmp(&right.id));
583    result.evidence.dedup_by(|left, right| left.id == right.id);
584}
585
586#[cfg(test)]
587mod tests {
588    use std::collections::BTreeMap;
589
590    use code_system_graph_model::{
591        Edge, EdgeId, EdgeKind, EpistemicStatus, EvidenceId, Node, NodeId, NodeKind, RepoId
592    };
593
594    use super::{
595        event_documents_to_graph, project_event_deliveries, project_event_deliveries_bounded
596    };
597    use crate::{SourceLanguage, extract_asyncapi, parse_event_source};
598
599    #[test]
600    fn event_graph_should_trace_publisher_through_channel_to_subscriber() {
601        let declaration = extract_asyncapi(
602            "asyncapi.yaml",
603            r"
604asyncapi: 2.6.0
605info: { title: events, version: 1.0.0 }
606servers:
607  kafka: { url: kafka:9092, protocol: kafka }
608channels:
609  orders.created:
610    publish: { message: { name: OrderCreated } }
611",
612        );
613        let publisher = parse_event_source(
614            SourceLanguage::Rust,
615            r#"kafka_producer.send("orders.created", payload);"#,
616        );
617        let subscriber = parse_event_source(
618            SourceLanguage::Python,
619            r#"kafka_consumer.subscribe("orders.created")"#,
620        );
621        let api = RepoId::new("repo:api");
622        let worker = RepoId::new("repo:worker");
623        let facts = declaration.as_ref().ok().map(|declaration| {
624            event_documents_to_graph(&[
625                (&api, "asyncapi.yaml", "contract", declaration),
626                (&api, "src/lib.rs", "publisher", &publisher),
627                (&worker, "worker.py", "subscriber", &subscriber),
628            ])
629        });
630
631        assert!(matches!(
632            facts,
633            Some(facts)
634                if [EdgeKind::Publishes, EdgeKind::Subscribes, EdgeKind::DeliversTo]
635                    .into_iter()
636                    .all(|kind| facts.edges.iter().any(|edge| edge.kind == kind))
637        ));
638    }
639
640    #[test]
641    fn event_delivery_projection_merges_duplicate_observations_conservatively() {
642        let channel = Node {
643            id: NodeId::new("channel"),
644            kind: NodeKind::EventChannel,
645            repo_id: None,
646            stable_key: "event:Kafka:cluster-a:orders".to_owned(),
647            label: "orders.created".to_owned(),
648        };
649        let owners = BTreeMap::from([
650            (NodeId::new("publisher"), RepoId::new("repo:api")),
651            (NodeId::new("subscriber"), RepoId::new("repo:worker")),
652        ]);
653        let event_edge = |id: &str,
654                          source: &str,
655                          kind: EdgeKind,
656                          status: EpistemicStatus,
657                          confidence: f32,
658                          evidence: &str| Edge {
659            id: EdgeId::new(id),
660            source: NodeId::new(source),
661            target: NodeId::new("channel"),
662            kind,
663            confidence,
664            status,
665            evidence: vec![EvidenceId::new(evidence)],
666        };
667        let edges = vec![
668            event_edge(
669                "publish-a",
670                "publisher",
671                EdgeKind::Publishes,
672                EpistemicStatus::Confirmed,
673                0.9,
674                "evidence:a",
675            ),
676            event_edge(
677                "publish-b",
678                "publisher",
679                EdgeKind::Publishes,
680                EpistemicStatus::Inferred,
681                0.7,
682                "evidence:b",
683            ),
684            event_edge(
685                "subscribe",
686                "subscriber",
687                EdgeKind::Subscribes,
688                EpistemicStatus::Confirmed,
689                0.8,
690                "evidence:c",
691            ),
692        ];
693
694        let projections = project_event_deliveries(&[channel], &edges, &owners);
695
696        assert_eq!(projections.len(), 1);
697        assert_eq!(projections[0].status, EpistemicStatus::Inferred);
698        assert!((projections[0].confidence - 0.7).abs() < f32::EPSILON);
699        assert_eq!(projections[0].evidence.len(), 3);
700    }
701
702    #[test]
703    fn event_delivery_projection_aggregates_before_a_bounded_repository_join() {
704        let channel = Node {
705            id: NodeId::new("channel"),
706            kind: NodeKind::EventChannel,
707            repo_id: None,
708            stable_key: "event:Kafka:cluster-a:shared".to_owned(),
709            label: "shared.event".to_owned(),
710        };
711        let mut owners = BTreeMap::new();
712        let mut edges = Vec::new();
713        for index in 0..100 {
714            for (role, kind) in [
715                ("publisher", EdgeKind::Publishes),
716                ("subscriber", EdgeKind::Subscribes),
717            ] {
718                let source = format!("{role}:{index}");
719                owners.insert(
720                    NodeId::new(&source),
721                    RepoId::new(format!("repo:{role}:{index}")),
722                );
723                edges.push(Edge {
724                    id: EdgeId::new(format!("edge:{role}:{index}")),
725                    source: NodeId::new(source),
726                    target: NodeId::new("channel"),
727                    kind,
728                    confidence: 1.0,
729                    status: EpistemicStatus::Confirmed,
730                    evidence: Vec::new(),
731                });
732            }
733        }
734
735        let mut cancellation_checks = 0_usize;
736        let report = project_event_deliveries_bounded(&[channel], &edges, &owners, 32, || {
737            cancellation_checks += 1;
738            false
739        });
740
741        assert_eq!(report.total, 10_000);
742        assert_eq!(report.deliveries.len(), 32);
743        assert!(report.truncated);
744        assert!(!report.cancelled);
745        assert!(cancellation_checks <= edges.len() + report.deliveries.len() + 1);
746    }
747
748    #[test]
749    fn event_delivery_without_namespace_is_ambiguous_and_evidence_is_bounded() {
750        let channel = Node {
751            id: NodeId::new("channel"),
752            kind: NodeKind::EventChannel,
753            repo_id: None,
754            stable_key: "event:Kafka::orders".to_owned(),
755            label: "orders".to_owned(),
756        };
757        let owners = BTreeMap::from([
758            (NodeId::new("publisher"), RepoId::new("repo:api")),
759            (NodeId::new("subscriber"), RepoId::new("repo:worker")),
760        ]);
761        let evidence = (0..100)
762            .map(|index| EvidenceId::new(format!("evidence:{index:03}")))
763            .collect::<Vec<_>>();
764        let edges = vec![
765            Edge {
766                id: EdgeId::new("publish"),
767                source: NodeId::new("publisher"),
768                target: NodeId::new("channel"),
769                kind: EdgeKind::Publishes,
770                confidence: 1.0,
771                status: EpistemicStatus::Confirmed,
772                evidence,
773            },
774            Edge {
775                id: EdgeId::new("subscribe"),
776                source: NodeId::new("subscriber"),
777                target: NodeId::new("channel"),
778                kind: EdgeKind::Subscribes,
779                confidence: 1.0,
780                status: EpistemicStatus::Confirmed,
781                evidence: vec![EvidenceId::new("evidence:zz-subscriber")],
782            },
783        ];
784
785        let deliveries = project_event_deliveries(&[channel], &edges, &owners);
786
787        assert_eq!(deliveries.len(), 1);
788        assert_eq!(deliveries[0].status, EpistemicStatus::Ambiguous);
789        assert!((deliveries[0].confidence - 0.5).abs() < f32::EPSILON);
790        assert_eq!(
791            deliveries[0].evidence.len(),
792            super::EVENT_DELIVERY_EVIDENCE_LIMIT
793        );
794        assert!(deliveries[0].evidence_truncated);
795        assert!(
796            deliveries[0]
797                .evidence
798                .contains(&EvidenceId::new("evidence:000"))
799        );
800        assert!(
801            deliveries[0]
802                .evidence
803                .contains(&EvidenceId::new("evidence:zz-subscriber"))
804        );
805    }
806}