nornir 0.5.3

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
//! **Semantic blast radius** from the warehouse SCIP call-graph (EPIC item 7).
//!
//! The crate-level blast radius in [`super::doctor::blast_radius`] answers *who
//! DEPENDS on* a changed crate — reachability over the Cargo.toml dep graph. That
//! is the pessimistic set: every dependent repo *might* break. This module answers
//! the sharper question — *what ACTUALLY breaks* — by cross-referencing a version
//! bump against the SCIP call-graph the warehouse already holds (`deep_scan` →
//! `symbol_facts` + `call_edges`, read via [`crate::knowledge::query`]):
//!
//! ```text
//!   target crate C  (a version bump)
//!     → its changed / removed exported symbols
//!       → REVERSE call_edges (`KnowledgeView::callers_of`) into every dependent
//!         → the exact call sites that invoke those symbols
//!           → ranked by API-surface delta (which changed symbols are hit, how often)
//! ```
//!
//! So "facett → 7 repos might break" becomes "these 12 call sites in 3 crates call
//! the 2 symbols that changed." The ranked list feeds the doctor report (the
//! [`SemanticBlast`] field alongside the crate-level `blast`) and the release gate.
//!
//! **Reading SCIP** — the real query path is used: [`crate::knowledge::query::
//! load_preferred_merged`] loads the resolved SCIP call-graph (or falls back to the
//! syn `call_edges`) for a set of member repos and merges them into one
//! [`KnowledgeView`]. Reverse lookup is the memoized inverted index behind
//! [`KnowledgeView::callers_of`]. Nothing here is stubbed: if the warehouse has no
//! rows for the dependents, [`compute`] returns an empty (source-tagged) result.

use std::collections::BTreeSet;

use anyhow::Result;
use serde::{Deserialize, Serialize};

use crate::knowledge::query::{load_preferred_merged, KnowledgeView};
use crate::release::doctor::{blast_radius, RepoGraph};
use crate::warehouse::iceberg::IcebergWarehouse;

/// How a symbol of the target crate changed across the version bump. Ordered so a
/// higher discriminant = a harder break (used as the rank tie-breaker).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChangeKind {
    /// The symbol's signature/behaviour changed but the name still resolves — a
    /// call site keeps compiling but may behave differently.
    Changed,
    /// The symbol was removed / renamed — every call site is a hard break.
    Removed,
}

impl ChangeKind {
    /// Short marker for the text report.
    fn glyph(self) -> &'static str {
        match self {
            ChangeKind::Changed => "~",
            ChangeKind::Removed => "",
        }
    }
}

/// One exported symbol of the target crate that the bump touched. `name` is the
/// bare identifier (last path segment, e.g. `open` for `Warehouse::open`) — the
/// key [`KnowledgeView::callers_of`] matches against, so both `open` and
/// `Warehouse::open` call sites resolve.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ChangedSymbol {
    pub name: String,
    pub change: ChangeKind,
}

impl ChangedSymbol {
    pub fn removed(name: impl Into<String>) -> Self {
        ChangedSymbol { name: name.into(), change: ChangeKind::Removed }
    }
    pub fn changed(name: impl Into<String>) -> Self {
        ChangedSymbol { name: name.into(), change: ChangeKind::Changed }
    }
}

/// One concrete call site in a dependent that invokes a changed symbol — the atom
/// of the semantic blast radius. Mapped straight from a reverse `call_edges` hit.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CallSite {
    /// The crate the call is made FROM (the dependent). Best-effort: the edge's
    /// `crate_name` when the syn scan set it, else the first segment of the caller
    /// path (the SCIP moniker carries no crate column).
    pub crate_name: String,
    /// The calling function (`caller_path`, e.g. `nornir::TestTab::fetch`).
    pub caller: String,
    /// The invoked identifier as written at the call site (`callee_ident`).
    pub callee: String,
    /// `call`, `method`, `assoc`, … from the SCIP/syn extractor.
    pub call_kind: String,
    pub file: String,
    pub line: u32,
}

/// The impact of ONE changed symbol: the call sites that hit it, most-called first.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SymbolImpact {
    pub symbol: String,
    pub change: ChangeKind,
    pub call_sites: Vec<CallSite>,
}

/// The semantic blast radius of a version bump to `target_repo`: the ranked, exact
/// call sites in its dependents that touch the changed API surface.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SemanticBlast {
    /// The bumped repo whose crates changed.
    pub target_repo: String,
    /// The crate names `target_repo` produces (the API surface owners).
    pub target_crates: Vec<String>,
    /// Which index answered — `"resolved/scip"`, `"syn"`, or `""` (no rows).
    pub source: String,
    /// Per changed symbol → its call sites, sorted most-impacted first. Symbols
    /// with ZERO dependent call sites are dropped (they are not part of the
    /// *actual* blast) and listed in `unused_changes` instead.
    pub impacts: Vec<SymbolImpact>,
    /// Changed symbols that NO dependent call site invokes — the delta that is
    /// internal-only, so the bump is safe w.r.t. them.
    pub unused_changes: Vec<ChangedSymbol>,
    /// Total call sites across all impacts (the headline number).
    pub total_call_sites: usize,
    /// The distinct dependent crates that contain at least one call site.
    pub affected_crates: Vec<String>,
}

impl SemanticBlast {
    /// True when the bump touches nothing any dependent actually calls — the
    /// crate-level blast said "might break", the semantic blast says "no call
    /// site does."
    pub fn is_empty(&self) -> bool {
        self.impacts.is_empty()
    }

    /// The **LINK ERRORS**: impacts of a symbol that was *removed* (or otherwise no
    /// longer resolves) yet a dependent still calls. A removed symbol with a live
    /// call site is a pre-release link error — once the bump ships, the dependent
    /// fails to compile/link on that exact symbol, precisely as a linker fails on an
    /// undefined reference. A [`ChangeKind::Changed`] impact still resolves (the call
    /// keeps compiling), so it is a WARNING, not a link error.
    pub fn link_errors(&self) -> Vec<&SymbolImpact> {
        self.impacts
            .iter()
            .filter(|i| i.change == ChangeKind::Removed && !i.call_sites.is_empty())
            .collect()
    }

    /// True when at least one removed symbol has a live cross-crate call site — the
    /// release must FAIL (see [`crate::release::gate::semantic_link_gate`]).
    pub fn has_link_error(&self) -> bool {
        self.impacts
            .iter()
            .any(|i| i.change == ChangeKind::Removed && !i.call_sites.is_empty())
    }

    /// Total live call sites across all link errors (the headline "N broken calls").
    pub fn link_error_sites(&self) -> usize {
        self.link_errors().iter().map(|i| i.call_sites.len()).sum()
    }
}

/// Compute the **API-surface delta** between a crate's OLD and NEW exported-symbol
/// sets — the seam that turns a version bump into the `changed`/`removed` symbol set
/// [`rank`] / [`compute`] consume. Read the two snapshots from the warehouse
/// `symbol_facts` table (before/after the bump, or last-published-tag vs HEAD); this
/// pure function diffs them:
///
/// - a `pub` symbol present in `old` but **gone** from `new` → [`ChangeKind::Removed`]
///   (a hard break: every call site is a link error),
/// - a `pub` symbol in **both** whose `signature` changed → [`ChangeKind::Changed`]
///   (still resolves, but may behave differently),
/// - a symbol only in `new` (a pure ADDITION) is *not* part of the blast — adding API
///   breaks no existing call site.
///
/// Non-`pub` symbols are ignored (they were never part of the crate's callable
/// surface). Keyed by the bare `item_name`, the same key [`KnowledgeView::callers_of`]
/// matches, so the delta feeds straight into the reverse call-graph lookup.
pub fn diff_exported_symbols(
    old: &[crate::knowledge::symbols::SymbolRow],
    new: &[crate::knowledge::symbols::SymbolRow],
) -> Vec<ChangedSymbol> {
    use std::collections::BTreeMap;
    // Only a FULLY public (`pub`) symbol is cross-crate callable; `pub(crate)`
    // and narrower are never part of the callable surface a dependent could break on.
    let is_pub = |v: &str| v == "pub";
    // name → signature (last wins; a crate rarely exports the same bare name twice
    // with different signatures, and if it does either is a fair break signal).
    let index = |rows: &[crate::knowledge::symbols::SymbolRow]| -> BTreeMap<String, Option<String>> {
        rows.iter()
            .filter(|r| is_pub(&r.visibility))
            .map(|r| (r.item_name.clone(), r.signature.clone()))
            .collect()
    };
    let old_idx = index(old);
    let new_idx = index(new);
    let mut out: Vec<ChangedSymbol> = Vec::new();
    for (name, old_sig) in &old_idx {
        match new_idx.get(name) {
            None => out.push(ChangedSymbol::removed(name.clone())),
            Some(new_sig) => {
                // Only flag a signature change when BOTH sides recorded one (a
                // missing signature on either side is unknown, not a change).
                if old_sig.is_some() && new_sig.is_some() && old_sig != new_sig {
                    out.push(ChangedSymbol::changed(name.clone()));
                }
            }
        }
    }
    out.sort_by(|a, b| a.name.cmp(&b.name));
    out
}

/// Best-effort crate name for a reverse `call_edges` hit: the edge's `crate_name`
/// if the syn scan recorded one, else the first `::`-segment of the caller path
/// (a resolved SCIP moniker has no crate column).
fn caller_crate(crate_name: &str, caller_path: &str) -> String {
    if !crate_name.is_empty() {
        return crate_name.to_string();
    }
    match caller_path.split_once("::") {
        Some((head, _)) if !head.is_empty() => head.to_string(),
        _ => caller_path.to_string(),
    }
}

/// **The pure core** — rank the changed symbols by their real call-site impact over
/// an already-loaded call-graph `view`, excluding call sites made from the target
/// repo's OWN crates (`own_crates`) so only genuine cross-crate breakage counts.
///
/// This is what the unit tests drive with a synthetic [`KnowledgeView`] fixture; the
/// warehouse read is factored out into [`compute`].
pub fn rank(
    view: &KnowledgeView,
    target_repo: &str,
    target_crates: &BTreeSet<String>,
    own_crates: &BTreeSet<String>,
    changed: &[ChangedSymbol],
) -> SemanticBlast {
    let mut impacts: Vec<SymbolImpact> = Vec::new();
    let mut unused_changes: Vec<ChangedSymbol> = Vec::new();
    let mut affected: BTreeSet<String> = BTreeSet::new();

    for cs in changed {
        // Reverse call_edges: every edge whose callee resolves to this symbol.
        let mut sites: Vec<CallSite> = view
            .callers_of(&cs.name)
            .into_iter()
            .filter(|e| !own_crates.contains(&caller_crate(&e.crate_name, &e.caller_path)))
            .map(|e| CallSite {
                crate_name: caller_crate(&e.crate_name, &e.caller_path),
                caller: e.caller_path.clone(),
                callee: e.callee_ident.clone(),
                call_kind: e.call_kind.clone(),
                file: e.file.clone(),
                line: e.line,
            })
            .collect();

        if sites.is_empty() {
            unused_changes.push(cs.clone());
            continue;
        }

        // Stable, deterministic order inside a symbol: by crate, then file, line.
        sites.sort_by(|a, b| {
            (&a.crate_name, &a.file, a.line).cmp(&(&b.crate_name, &b.file, b.line))
        });
        for s in &sites {
            affected.insert(s.crate_name.clone());
        }
        impacts.push(SymbolImpact { symbol: cs.name.clone(), change: cs.change, call_sites: sites });
    }

    // Rank by API-surface delta: most-called symbol first, then the harder break
    // (Removed > Changed), then name for a stable order.
    impacts.sort_by(|a, b| {
        b.call_sites
            .len()
            .cmp(&a.call_sites.len())
            .then(b.change.cmp(&a.change))
            .then(a.symbol.cmp(&b.symbol))
    });

    let total_call_sites = impacts.iter().map(|i| i.call_sites.len()).sum();
    SemanticBlast {
        target_repo: target_repo.to_string(),
        target_crates: target_crates.iter().cloned().collect(),
        source: String::new(),
        impacts,
        unused_changes,
        total_call_sites,
        affected_crates: affected.into_iter().collect(),
    }
}

/// **The warehouse orchestrator** — read the SCIP call-graph for `target_repo`'s
/// dependents and compute the semantic blast of `changed` over it.
///
/// Flow: crate-level [`blast_radius`] gives the dependent repos; those are the only
/// places a call site to `target_repo`'s API can live, so we load exactly their
/// call-graphs (merged, resolved-preferred) and reverse-lookup the changed symbols.
/// The `graphs` are the same [`RepoGraph`]s the doctor already gathered, so no
/// extra Cargo parsing.
pub fn compute(
    wh: &IcebergWarehouse,
    graphs: &[RepoGraph],
    target_repo: &str,
    changed: &[ChangedSymbol],
) -> Result<SemanticBlast> {
    let own_crates: BTreeSet<String> = graphs
        .iter()
        .find(|g| g.repo == target_repo)
        .map(|g| g.produces.clone())
        .unwrap_or_default();

    // The dependents are the only crates that can hold a call site to C's API.
    let dependents = blast_radius(graphs, target_repo);
    if dependents.is_empty() {
        let mut sb = SemanticBlast {
            target_repo: target_repo.to_string(),
            target_crates: own_crates.iter().cloned().collect(),
            ..Default::default()
        };
        sb.unused_changes = changed.to_vec();
        return Ok(sb);
    }

    let (view, source) = load_preferred_merged(wh, &dependents)?;
    let mut sb = rank(&view, target_repo, &own_crates, &own_crates, changed);
    sb.source = source.to_string();
    Ok(sb)
}

/// Convenience over [`compute`] for the common case where the doctor wants the
/// semantic blast for EVERY dirty repo whose changed symbols are supplied. Returns
/// only the non-empty results (a dirty repo whose bump touches no dependent call
/// site is not surfaced). `changed_by_repo` maps repo → its changed symbol set.
pub fn compute_for_dirty<'a>(
    wh: &IcebergWarehouse,
    graphs: &[RepoGraph],
    changed_by_repo: impl IntoIterator<Item = (&'a str, &'a [ChangedSymbol])>,
) -> Result<std::collections::BTreeMap<String, SemanticBlast>> {
    let mut out = std::collections::BTreeMap::new();
    for (repo, changed) in changed_by_repo {
        let sb = compute(wh, graphs, repo, changed)?;
        if !sb.is_empty() {
            out.insert(repo.to_string(), sb);
        }
    }
    Ok(out)
}

/// Render a semantic blast as a text block for the doctor report, mirroring the
/// crate-level "Blast radius" section's style.
pub fn format_semantic_blast(sb: &SemanticBlast) -> String {
    let mut s = String::new();
    if sb.is_empty() {
        return s;
    }
    s.push_str(&format!(
        "  {} bump touches {} call site(s) in {} crate(s) [{}]:\n",
        sb.target_repo,
        sb.total_call_sites,
        sb.affected_crates.len(),
        if sb.source.is_empty() { "no-index" } else { &sb.source },
    ));
    for imp in &sb.impacts {
        s.push_str(&format!(
            "    {} {} ({} call site(s)):\n",
            imp.change.glyph(),
            imp.symbol,
            imp.call_sites.len(),
        ));
        for site in &imp.call_sites {
            s.push_str(&format!(
                "        {}::{}{}:{}\n",
                site.crate_name, site.caller, site.file, site.line,
            ));
        }
    }
    if !sb.unused_changes.is_empty() {
        let names: Vec<&str> = sb.unused_changes.iter().map(|c| c.name.as_str()).collect();
        s.push_str(&format!("    (no dependent call sites: {})\n", names.join(", ")));
    }
    s
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::knowledge::symbols::{CallEdgeRow, SymbolRow};

    /// A synthetic SCIP call-graph: `facett` exports `render` + `open` + `secret`;
    /// three dependent crates call into it, plus one intra-`facett` self-call that
    /// must NOT count as blast.
    fn fixture() -> KnowledgeView {
        let sym = |cr: &str, name: &str| SymbolRow {
            crate_name: cr.into(),
            module_path: format!("{cr}::api"),
            item_kind: "fn".into(),
            item_name: name.into(),
            visibility: "pub".into(),
            file: format!("{cr}/src/api.rs"),
            line: 1,
            doc_lines: 0,
            signature: None,
        };
        let call = |cr: &str, caller: &str, callee: &str, file: &str, line: u32| CallEdgeRow {
            crate_name: cr.into(),
            caller_path: caller.into(),
            callee_ident: callee.into(),
            call_kind: "call".into(),
            file: file.into(),
            line,
        };
        let symbols = vec![
            sym("facett", "render"),
            sym("facett", "open"),
            sym("facett", "secret"),
        ];
        let calls = vec![
            // `render` is hot: three call sites across two crates.
            call("korp", "korp::view::draw", "facett::render", "korp/src/view.rs", 40),
            call("korp", "korp::view::redraw", "render", "korp/src/view.rs", 88),
            call("knut", "knut::ui::paint", "facett::render", "knut/src/ui.rs", 12),
            // `open` is called once, from a third crate.
            call("nornir", "nornir::boot::run", "facett::open", "nornir/src/boot.rs", 7),
            // A self-call inside facett — must be EXCLUDED (not cross-crate blast).
            call("facett", "facett::api::render", "open", "facett/src/api.rs", 3),
            // Noise: a call to an unrelated symbol.
            call("korp", "korp::view::draw", "std::mem::swap", "korp/src/view.rs", 41),
        ];
        KnowledgeView::new(symbols, calls)
    }

    fn own() -> BTreeSet<String> {
        BTreeSet::from(["facett".to_string()])
    }

    #[test]
    fn ranks_changed_symbols_by_real_call_site_count() {
        let view = fixture();
        let changed = [
            ChangedSymbol::removed("render"),
            ChangedSymbol::changed("open"),
            ChangedSymbol::removed("secret"), // exported but never called → unused
        ];
        let sb = rank(&view, "facett", &own(), &own(), &changed);

        // `render` (3 sites) ranks above `open` (1 site); `secret` drops to unused.
        let ranked: Vec<&str> = sb.impacts.iter().map(|i| i.symbol.as_str()).collect();
        let correct_rank = ranked == ["render", "open"];
        let render = &sb.impacts[0];
        // The intra-facett self-call is excluded → exactly 3 cross-crate sites.
        let self_call_excluded = render.call_sites.len() == 3
            && render.call_sites.iter().all(|s| s.crate_name != "facett");
        let secret_unused = sb.unused_changes.iter().any(|c| c.name == "secret")
            && sb.impacts.iter().all(|i| i.symbol != "secret");
        let totals = sb.total_call_sites == 4
            && sb.affected_crates == vec!["knut".to_string(), "korp".to_string(), "nornir".to_string()];

        nornir_testmatrix::functional_status(
            "semantic-blast",
            "ranks_by_real_call_site_count",
            correct_rank && self_call_excluded && secret_unused && totals,
            &format!(
                "rank={ranked:?} render_sites={} affected={:?} total={} unused={:?}",
                render.call_sites.len(),
                sb.affected_crates,
                sb.total_call_sites,
                sb.unused_changes.iter().map(|c| &c.name).collect::<Vec<_>>(),
            ),
        );

        assert!(correct_rank, "render (3 sites) must outrank open (1 site): {ranked:?}");
        assert!(self_call_excluded, "the intra-facett self-call must be excluded from blast");
        assert!(secret_unused, "an exported-but-uncalled changed symbol is `unused`, not an impact");
        assert!(totals, "4 cross-crate call sites across knut/korp/nornir");
    }

    #[test]
    fn suffix_and_bare_callees_both_resolve() {
        // Both `facett::render` (path-qualified) and bare `render` call sites hit.
        let view = fixture();
        let sb = rank(&view, "facett", &own(), &own(), &[ChangedSymbol::removed("render")]);
        let render = &sb.impacts[0];
        let has_qualified = render.call_sites.iter().any(|s| s.callee == "facett::render");
        let has_bare = render.call_sites.iter().any(|s| s.callee == "render");

        nornir_testmatrix::functional_status(
            "semantic-blast",
            "suffix_and_bare_callees_resolve",
            has_qualified && has_bare,
            &format!("callees={:?}", render.call_sites.iter().map(|s| &s.callee).collect::<Vec<_>>()),
        );
        assert!(has_qualified && has_bare, "reverse lookup matches both `facett::render` and bare `render`");
    }

    #[test]
    fn no_call_sites_yields_empty_blast() {
        let view = fixture();
        let sb = rank(&view, "facett", &own(), &own(), &[ChangedSymbol::changed("nonexistent")]);
        nornir_testmatrix::functional_status(
            "semantic-blast",
            "no_sites_is_empty",
            sb.is_empty() && sb.total_call_sites == 0 && sb.unused_changes.len() == 1,
            &format!("empty={} total={}", sb.is_empty(), sb.total_call_sites),
        );
        assert!(sb.is_empty(), "a symbol nobody calls produces an empty semantic blast");
    }

    /// The rendered report names the bumped repo, the headline call-site/crate
    /// counts, the changed-symbol lines (with the removed glyph), and each concrete
    /// call site. An empty blast renders to the empty string.
    #[test]
    fn format_renders_headline_symbols_and_sites() {
        let view = fixture();
        let mut sb = rank(&view, "facett", &own(), &own(), &[ChangedSymbol::removed("render")]);
        sb.source = "resolved/scip".to_string();
        let text = format_semantic_blast(&sb);
        assert!(text.contains("facett bump touches 3 call site(s) in 2 crate(s)"), "headline: {text}");
        assert!(text.contains("[resolved/scip]"), "source tag surfaced");
        assert!(text.contains("✗ render (3 call site(s))"), "removed glyph + count: {text}");
        assert!(text.contains("korp/src/view.rs:40"), "a concrete call site is listed");
        // An empty blast produces no text at all.
        let empty = rank(&view, "facett", &own(), &own(), &[ChangedSymbol::changed("nope")]);
        assert!(format_semantic_blast(&empty).is_empty(), "empty blast renders nothing");
    }

    /// `own_crates` filtering is what excludes internal callers: widen `own` to also
    /// cover `korp` and every korp call site drops out of `render`'s impact, leaving
    /// only the genuinely-external `knut` site.
    #[test]
    fn own_crates_filter_excludes_internal_callers() {
        let view = fixture();
        let own = BTreeSet::from(["facett".to_string(), "korp".to_string()]);
        let sb = rank(&view, "facett", &BTreeSet::from(["facett".to_string()]), &own, &[ChangedSymbol::removed("render")]);
        let render = &sb.impacts[0];
        assert!(render.call_sites.iter().all(|s| s.crate_name != "korp"), "korp calls filtered out");
        assert_eq!(render.call_sites.len(), 1, "only knut's cross-crate site survives");
        assert_eq!(render.call_sites[0].crate_name, "knut");
    }

    /// LINK ERROR: a REMOVED symbol that a dependent still calls is a link error;
    /// a CHANGED symbol that still resolves is only a warning (not a link error).
    #[test]
    fn link_errors_flags_removed_with_live_call_sites_only() {
        let view = fixture();
        // `render` removed (3 live sites) → link error; `open` merely changed → warn.
        let sb = rank(
            &view,
            "facett",
            &own(),
            &own(),
            &[ChangedSymbol::removed("render"), ChangedSymbol::changed("open")],
        );
        let errs = sb.link_errors();
        let one_link_error = errs.len() == 1 && errs[0].symbol == "render";
        let counts = sb.has_link_error() && sb.link_error_sites() == 3;
        // The `open` change is present as an impact but NOT a link error.
        let changed_not_error = sb.impacts.iter().any(|i| i.symbol == "open")
            && errs.iter().all(|i| i.symbol != "open");

        nornir_testmatrix::functional_status(
            "semantic-blast",
            "link_errors_only_removed",
            one_link_error && counts && changed_not_error,
            &format!(
                "errors={:?} sites={} has={}",
                errs.iter().map(|i| &i.symbol).collect::<Vec<_>>(),
                sb.link_error_sites(),
                sb.has_link_error(),
            ),
        );
        assert!(one_link_error, "only the removed `render` is a link error: {errs:?}");
        assert!(counts, "3 broken call sites, has_link_error=true");
        assert!(changed_not_error, "a still-resolving Changed symbol is not a link error");
    }

    /// The API-surface DELTA seam: a `pub` symbol dropped between snapshots is
    /// `removed`, a `pub` symbol whose signature changed is `changed`, a pure addition
    /// is not part of the blast, a non-`pub` (pub(crate)) symbol is ignored entirely,
    /// and an unchanged symbol is absent.
    #[test]
    fn diff_exported_symbols_detects_removed_changed_ignores_additions_and_private() {
        use crate::knowledge::symbols::SymbolRow;
        let s = |name: &str, vis: &str, sig: Option<&str>| SymbolRow {
            crate_name: "facett".into(),
            module_path: "facett::api".into(),
            item_kind: "fn".into(),
            item_name: name.into(),
            visibility: vis.into(),
            file: "facett/src/api.rs".into(),
            line: 1,
            doc_lines: 0,
            signature: sig.map(|x| x.into()),
        };
        let old = vec![
            s("render", "pub", Some("fn render(&self)")),
            s("open", "pub", Some("fn open() -> Self")),
            s("secret", "pub", Some("fn secret()")),
            s("internal", "pub(crate)", Some("fn internal()")),
        ];
        let new = vec![
            // render removed
            s("open", "pub", Some("fn open(path: &str) -> Self")), // signature changed
            s("secret", "pub", Some("fn secret()")),               // unchanged
            s("added", "pub", Some("fn added()")),                 // addition (ignored)
            s("internal", "pub(crate)", Some("fn internal(x: u32)")), // not `pub` → ignored
        ];
        let delta = diff_exported_symbols(&old, &new);
        let by = |n: &str| delta.iter().find(|c| c.name == n).map(|c| c.change);
        // render → removed, open → changed, secret unchanged → absent, added → absent,
        // internal is pub(crate) → never part of the cross-crate surface → absent.
        let ok = by("render") == Some(ChangeKind::Removed)
            && by("open") == Some(ChangeKind::Changed)
            && by("secret").is_none()
            && by("added").is_none()
            && by("internal").is_none();

        nornir_testmatrix::functional_status(
            "semantic-blast",
            "diff_exported_symbols",
            ok,
            &format!("delta={:?}", delta.iter().map(|c| (&c.name, c.change)).collect::<Vec<_>>()),
        );
        assert_eq!(by("render"), Some(ChangeKind::Removed), "dropped pub symbol is removed");
        assert_eq!(by("open"), Some(ChangeKind::Changed), "signature change is changed");
        assert!(by("secret").is_none(), "unchanged symbol is not in the delta");
        assert!(by("added").is_none(), "a pure addition breaks nobody → not in the delta");
        assert!(by("internal").is_none(), "a pub(crate) symbol is not cross-crate surface");
    }
}

/// WAREHOUSE-BACKED integration tests for the two warehouse-reading wrappers —
/// [`compute`] and [`compute_for_dirty`] — that Wave-1 deferred. Where the pure
/// [`rank`] tests above drive a synthetic in-RAM [`KnowledgeView`], these seed a
/// REAL temporary [`IcebergWarehouse`] with a small syn call-graph (one
/// [`crate::knowledge::symbols::SymbolScan`] per dependent repo) so the full
/// `blast_radius → load_preferred_merged → callers_of` read path executes
/// end-to-end against persisted iceberg rows.
#[cfg(test)]
mod warehouse_tests {
    use super::*;
    use crate::knowledge::symbols::{CallEdgeRow, SymbolRow, SymbolScan};
    use crate::warehouse::iceberg::IcebergWarehouse;
    use std::collections::BTreeSet;

    fn sym(cr: &str, name: &str) -> SymbolRow {
        SymbolRow {
            crate_name: cr.into(),
            module_path: format!("{cr}::api"),
            item_kind: "fn".into(),
            item_name: name.into(),
            visibility: "pub".into(),
            file: format!("{cr}/src/api.rs"),
            line: 1,
            doc_lines: 0,
            signature: None,
        }
    }
    fn call(cr: &str, caller: &str, callee: &str, file: &str, line: u32) -> CallEdgeRow {
        CallEdgeRow {
            crate_name: cr.into(),
            caller_path: caller.into(),
            callee_ident: callee.into(),
            call_kind: "call".into(),
            file: file.into(),
            line,
        }
    }

    /// Append one syn scan for `repo`. A dependent's snapshot must carry at least
    /// one `symbol_facts` row or [`crate::knowledge::query::load_latest`] can't
    /// discover its latest snapshot (and would read back zero call edges), so we
    /// always seed a marker symbol alongside the call edges.
    fn seed(wh: &IcebergWarehouse, repo: &str, calls: Vec<CallEdgeRow>) {
        let scan = SymbolScan {
            snapshot_id: uuid::Uuid::new_v4(),
            ts: chrono::Utc::now(),
            repo: repo.to_string(),
            symbols: vec![sym(repo, "marker")],
            calls,
            features: vec![],
            tests: vec![],
        };
        wh.append_symbol_scan(&scan).unwrap();
    }

    /// The doctor's cross-repo graph: `facett` exports the API; `korp`, `knut` and
    /// `nornir` each depend on it (a `path=` dep on the `facett` crate), so
    /// [`blast_radius`] returns exactly those three as the places a call site can
    /// live.
    fn graphs() -> Vec<RepoGraph> {
        let g = |repo: &str, produces: &str, deps: &[&str]| RepoGraph {
            repo: repo.into(),
            produces: BTreeSet::from([produces.to_string()]),
            deps: deps.iter().map(|s| s.to_string()).collect(),
            ..Default::default()
        };
        vec![
            g("facett", "facett", &[]),
            g("korp", "korp", &["facett"]),
            g("knut", "knut", &["facett"]),
            g("nornir", "nornir", &["facett"]),
        ]
    }

    /// Seed a warehouse whose dependents call into `facett`: `render` is hot (three
    /// cross-crate sites over korp+knut), `open` is called once (nornir), `secret`
    /// is exported but called by nobody. A self-call inside facett is also seeded to
    /// prove the own-crate filter excludes it even over the real read path.
    fn seeded_wh(dir: &std::path::Path) -> IcebergWarehouse {
        let wh = IcebergWarehouse::open(dir).unwrap();
        seed(&wh, "korp", vec![
            call("korp", "korp::view::draw", "facett::render", "korp/src/view.rs", 40),
            call("korp", "korp::view::redraw", "render", "korp/src/view.rs", 88),
            call("korp", "korp::view::draw", "std::mem::swap", "korp/src/view.rs", 41),
        ]);
        seed(&wh, "knut", vec![
            call("knut", "knut::ui::paint", "facett::render", "knut/src/ui.rs", 12),
        ]);
        seed(&wh, "nornir", vec![
            call("nornir", "nornir::boot::run", "facett::open", "nornir/src/boot.rs", 7),
        ]);
        // The target repo's OWN self-call — a dependent scan is never loaded for
        // facett (it isn't in the blast radius), so this must never appear as blast.
        seed(&wh, "facett", vec![
            call("facett", "facett::api::render", "open", "facett/src/api.rs", 3),
        ]);
        wh
    }

    /// END-TO-END: `compute` reads the persisted call-graph of `facett`'s
    /// dependents and attaches the EXACT impacted call sites — `render` (3 sites in
    /// korp+knut) ranks above `open` (1 in nornir), `secret` drops to `unused`, the
    /// facett self-call is excluded, and the source is tagged `syn`.
    #[test]
    fn compute_attaches_exact_call_sites_from_warehouse() {
        let dir = tempfile::tempdir().unwrap();
        let wh = seeded_wh(dir.path());
        let graphs = graphs();
        let changed = [
            ChangedSymbol::removed("render"),
            ChangedSymbol::changed("open"),
            ChangedSymbol::removed("secret"),
        ];
        let sb = compute(&wh, &graphs, "facett", &changed).unwrap();

        assert_eq!(sb.source, "syn", "the syn read path answered the call-graph query");
        assert_eq!(sb.target_repo, "facett");
        assert_eq!(sb.target_crates, vec!["facett".to_string()]);

        let ranked: Vec<&str> = sb.impacts.iter().map(|i| i.symbol.as_str()).collect();
        assert_eq!(ranked, ["render", "open"], "render (3 sites) outranks open (1): {ranked:?}");

        let render = &sb.impacts[0];
        assert_eq!(render.call_sites.len(), 3, "3 cross-crate render sites (korp×2, knut×1)");
        assert!(render.call_sites.iter().all(|s| s.crate_name != "facett"), "self-call excluded");
        // The concrete site coordinates survive the warehouse round-trip.
        assert!(render.call_sites.iter().any(|s|
            s.crate_name == "knut" && s.file == "knut/src/ui.rs" && s.line == 12));
        assert!(render.call_sites.iter().any(|s|
            s.crate_name == "korp" && s.file == "korp/src/view.rs" && s.line == 40));

        assert_eq!(sb.total_call_sites, 4);
        assert_eq!(
            sb.affected_crates,
            vec!["knut".to_string(), "korp".to_string(), "nornir".to_string()],
        );
        assert!(sb.unused_changes.iter().any(|c| c.name == "secret"), "secret is unused");
    }

    /// An INTERNAL-ONLY change — a symbol no dependent invokes — yields an EMPTY
    /// semantic blast over the real warehouse (the crate-level blast said "might
    /// break"; the call-graph says "no call site does").
    #[test]
    fn compute_is_empty_for_internal_only_change() {
        let dir = tempfile::tempdir().unwrap();
        let wh = seeded_wh(dir.path());
        let sb = compute(&wh, &graphs(), "facett", &[ChangedSymbol::changed("secret")]).unwrap();
        assert!(sb.is_empty(), "no dependent calls `secret` → empty blast");
        assert_eq!(sb.total_call_sites, 0);
        assert_eq!(sb.unused_changes.len(), 1);
        assert_eq!(sb.unused_changes[0].name, "secret");
    }

    /// `compute_for_dirty` runs `compute` per dirty repo and surfaces ONLY the
    /// non-empty results: `facett`'s `render` bump lands in the map; a bump that
    /// touches only the internal `secret` is dropped.
    #[test]
    fn compute_for_dirty_keeps_only_impacted_repos() {
        let dir = tempfile::tempdir().unwrap();
        let wh = seeded_wh(dir.path());
        let graphs = graphs();

        let render_change = [ChangedSymbol::removed("render")];
        let secret_change = [ChangedSymbol::changed("secret")];
        let changed_by_repo: Vec<(&str, &[ChangedSymbol])> = vec![
            ("facett", &render_change),
            ("korp", &secret_change), // korp has no dependents that call `secret` → dropped
        ];
        let map = compute_for_dirty(&wh, &graphs, changed_by_repo).unwrap();

        assert!(map.contains_key("facett"), "facett's render bump is surfaced");
        assert!(!map.contains_key("korp"), "an internal-only bump is not surfaced");
        assert_eq!(map["facett"].total_call_sites, 3);
    }

    /// A bump to a repo with NO dependents (nothing in the blast radius) short-
    /// circuits to an empty, source-tagged result whose changed symbols are all
    /// `unused` — the read path is never even entered.
    #[test]
    fn compute_no_dependents_is_empty_with_unused_changes() {
        let dir = tempfile::tempdir().unwrap();
        let wh = seeded_wh(dir.path());
        // `nornir` is a leaf here (nobody depends on it), so blast_radius is empty.
        let sb = compute(&wh, &graphs(), "nornir", &[ChangedSymbol::removed("boot")]).unwrap();
        assert!(sb.is_empty());
        assert_eq!(sb.unused_changes.len(), 1);
        assert_eq!(sb.unused_changes[0].name, "boot");
    }
}