nornir 0.4.31

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
//! Static extractor for the **fn → warehouse-table access fact**.
//!
//! This is the ONE wiring edge no call graph yields: *which function
//! reads/writes which warehouse table*. It is grounded in the
//! layer-boundary-discoverability LAW — warehouse access goes through
//! **canonical accessors** (`query_<table>` / `append_<table>` / a few
//! bespoke writers + the generic `scan_preview`), so the access sites are
//! enumerable by name.
//!
//! Approach (mirrors [`crate::knowledge::symbols`]): walk every `.rs` under
//! `src/ tests/ benches/ examples/` of each crate, parse with `syn`, and for
//! every `fn` body collect call expressions (`Expr::Call` /
//! `Expr::MethodCall`). When the callee identifier matches a known accessor we
//! emit an [`AccessEdge`] `caller_fn → (table, read|write)`.
//!
//! What is statically knowable:
//!   - The **named per-table accessors** (`query_test_results` → `test_results`
//!     read, `append_release_events` → `release_events` write, …) — a closed
//!     map keyed by callee identifier. One accessor may touch several tables
//!     (a knowledge scan writes `symbol_facts` + `call_edges` +
//!     `feature_gate_facts` in one call) → one edge per table.
//!   - The generic `scan_preview(table, limit)` / `table_names()` browsers,
//!     when the table argument is a **string/const literal** we can read off the
//!     call site (e.g. `scan_preview("mcp_requests", …)`). When the table is a
//!     runtime variable we record the access against the sentinel table
//!     `<dynamic>` so the fact still says "this fn does a generic scan" without
//!     fabricating a table name.
//!
//! What is NOT statically knowable (documented limits):
//!   - A `scan_preview(var, …)` where `var` is computed at runtime → table is
//!     `<dynamic>` (the viz Warehouse browser + MCP `scan_preview` RPC iterate
//!     `table_names()`, so the concrete table is a runtime value).
//!   - Re-exports / aliased imports that rename an accessor (we match on the
//!     final path segment, so `use …::query_test_results as qtr; qtr(..)` is
//!     matched, but `let f = query_test_results; f(..)` indirection is not).
//!   - Cross-crate inlining / trait dispatch (`TestSink::append`) — we match the
//!     concrete free-fn / method *name* only, not resolved trait impls.

use std::path::Path;

use anyhow::{Context, Result};
use syn::visit::Visit;
use syn::{Expr, ImplItem, Item, ItemImpl, Lit};
use syn::spanned::Spanned;
use walkdir::WalkDir;

/// `read` or `write` — the direction of a warehouse-table access.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
pub enum Access {
    Read,
    Write,
}

impl Access {
    pub fn as_str(self) -> &'static str {
        match self {
            Access::Read => "read",
            Access::Write => "write",
        }
    }
}

/// Sentinel table name recorded when a generic `scan_preview`/`table_names`
/// access targets a runtime (non-literal) table — the table is not statically
/// knowable, but the *access site* is a real, persisted fact.
pub const DYNAMIC_TABLE: &str = "<dynamic>";

/// One extracted fact: `caller_fn` (in `crate`) does a `access` on `table` at
/// `file:line`.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub struct AccessEdge {
    pub caller_fn: String,
    pub crate_name: String,
    pub table: String,
    pub access: Access,
    pub file: String,
    pub line: u32,
}

impl AccessEdge {
    /// Sort/dedup key (stable order independent of walk order).
    pub fn key(&self) -> (String, String, String, &'static str, u32) {
        (
            self.caller_fn.clone(),
            self.crate_name.clone(),
            self.table.clone(),
            self.access.as_str(),
            self.line,
        )
    }
}

/// The accessor → (table, access) map. One callee identifier may produce
/// several `(table, access)` pairs (a multi-table writer like a knowledge
/// scan). `None` table means "the table is the first string-literal argument"
/// (the generic `scan_preview` / `table_names` browser).
///
/// Resolution of the callee identifier is on the **final path segment**:
/// `crate::warehouse::test_results::query_test_results` and a `use … as` alias
/// both resolve to `query_test_results`.
fn accessor_table_access(callee: &str) -> Option<Vec<(Option<&'static str>, Access)>> {
    use Access::*;
    let v: Vec<(Option<&'static str>, Access)> = match callee {
        // ── named per-table readers ───────────────────────────────────────
        "query_test_results" => vec![(Some("test_results"), Read)],
        "query_release_events" => vec![(Some("release_events"), Read)],
        "query_agent_model_runs" => vec![(Some("agent_model_runs"), Read)],
        "query_dep_graph_snapshots" => vec![(Some("dep_graph_edges"), Read)],
        "query_bench_runs" | "query_bench_runs_async" => vec![(Some("bench_runs"), Read)],
        "query_bench_telemetry" | "query_bench_telemetry_async" => {
            vec![(Some("bench_telemetry"), Read)]
        }
        "query_mcp_stats" | "query_mcp_stats_async" => vec![(Some("mcp_requests"), Read)],
        "query_sbom_components" | "query_sbom_components_async" => {
            vec![(Some("sbom_components"), Read)]
        }
        "query_vuln_findings" | "query_vuln_findings_async" => {
            vec![(Some("vuln_findings"), Read)]
        }
        "query_viz_actions" | "query_viz_actions_blocking" => vec![(Some("viz_actions"), Read)],
        "load_all_events" => vec![(Some("funnel_events"), Read)],
        "knowledge_scan_exists" => vec![(Some("knowledge_scans"), Read)],
        "load_latest" => vec![
            (Some("symbol_facts"), Read),
            (Some("call_edges"), Read),
            (Some("feature_gate_facts"), Read),
            (Some("git_heat_facts"), Read),
        ],

        // ── named per-table writers ───────────────────────────────────────
        "append_test_results" => vec![(Some("test_results"), Write)],
        "append_release_events" => vec![(Some("release_events"), Write)],
        "append_agent_model_runs" => vec![(Some("agent_model_runs"), Write)],
        "record_dep_graph" => vec![(Some("dep_graph_edges"), Write)],
        "append_bench_run" | "append_bench_run_async" => vec![
            (Some("bench_runs"), Write),
            (Some("bench_results"), Write),
            (Some("test_outcomes"), Write),
        ],
        "append_mcp_calls" | "append_mcp_calls_async" => vec![(Some("mcp_requests"), Write)],
        "append_sbom_components" | "append_sbom_components_async" => {
            vec![(Some("sbom_components"), Write)]
        }
        "append_vuln_findings" | "append_vuln_findings_async" => {
            vec![(Some("vuln_findings"), Write)]
        }
        "append_viz_actions" | "append_viz_actions_blocking" => {
            vec![(Some("viz_actions"), Write)]
        }
        "append_event" => vec![(Some("funnel_events"), Write)],
        "persist_lineage" => vec![(Some("release_lineage"), Write)],
        // A knowledge scan writes the three syn-derived tables in one batch.
        "append_symbol_scan" | "append_symbol_scan_async" => vec![
            (Some("symbol_facts"), Write),
            (Some("call_edges"), Write),
            (Some("feature_gate_facts"), Write),
        ],
        "append_git_heat_scan" | "append_git_heat_scan_async" => {
            vec![(Some("git_heat_facts"), Write)]
        }
        "record_knowledge_scan" | "record_knowledge_scan_async" => {
            vec![(Some("knowledge_scans"), Write)]
        }

        // ── generic browser: table is the first literal argument ──────────
        "scan_preview" | "scan_preview_async" => vec![(None, Read)],
        "table_names" | "table_names_async" => vec![(None, Read)],

        _ => return None,
    };
    Some(v)
}

/// All caller-fn → (table, access) edges found in the crates under `root`.
/// `root` is a repo root (we discover crates by `Cargo.toml`, like the
/// knowledge symbol scan). Returns edges sorted + deduped.
pub fn scan_repo(root: &Path) -> Result<Vec<AccessEdge>> {
    let mut out: Vec<AccessEdge> = Vec::new();
    for entry in WalkDir::new(root)
        .into_iter()
        .filter_entry(|e| !is_skipped_dir(&e.file_name().to_string_lossy()))
    {
        let entry = entry.context("walkdir")?;
        if entry.file_name() == "Cargo.toml" {
            scan_one_crate(root, entry.path(), &mut out);
        }
    }
    dedup_sorted(&mut out);
    Ok(out)
}

/// Extract edges from a single `.rs` file's source text (the unit the tests
/// drive). `crate_name` labels the edges; `rel_file` is the file path recorded.
pub fn scan_source(crate_name: &str, rel_file: &str, src: &str) -> Vec<AccessEdge> {
    let mut out = Vec::new();
    if let Ok(syntax) = syn::parse_file(src) {
        let mut w = Walker {
            crate_name: crate_name.to_string(),
            file: rel_file.to_string(),
            out: &mut out,
        };
        w.walk_items(&syntax.items);
    }
    dedup_sorted(&mut out);
    out
}

fn dedup_sorted(out: &mut Vec<AccessEdge>) {
    out.sort_by(|a, b| a.key().cmp(&b.key()));
    out.dedup_by(|a, b| a.key() == b.key());
}

fn is_skipped_dir(name: &str) -> bool {
    matches!(name, "target" | ".git" | "node_modules" | ".nornir")
}

fn scan_one_crate(repo_root: &Path, cargo_toml: &Path, out: &mut Vec<AccessEdge>) {
    let Ok(text) = std::fs::read_to_string(cargo_toml) else { return };
    let Ok(doc) = text.parse::<toml::Value>() else { return };
    let Some(crate_name) = doc
        .get("package")
        .and_then(|p| p.get("name"))
        .and_then(|n| n.as_str())
    else { return };
    let Some(crate_dir) = cargo_toml.parent() else { return };

    for sub in &["src", "tests", "benches", "examples"] {
        let dir = crate_dir.join(sub);
        if !dir.is_dir() { continue; }
        for entry in WalkDir::new(&dir)
            .into_iter()
            .filter_entry(|e| !is_skipped_dir(&e.file_name().to_string_lossy()))
        {
            let Ok(entry) = entry else { continue };
            if entry.file_type().is_file()
                && entry.path().extension().and_then(|e| e.to_str()) == Some("rs")
            {
                let Ok(text) = std::fs::read_to_string(entry.path()) else { continue };
                let Ok(syntax) = syn::parse_file(&text) else { continue };
                let rel = entry
                    .path()
                    .strip_prefix(repo_root)
                    .unwrap_or(entry.path())
                    .to_string_lossy()
                    .to_string();
                let mut w = Walker {
                    crate_name: crate_name.to_string(),
                    file: rel,
                    out,
                };
                w.walk_items(&syntax.items);
            }
        }
    }
}

struct Walker<'a> {
    crate_name: String,
    file: String,
    out: &'a mut Vec<AccessEdge>,
}

impl<'a> Walker<'a> {
    fn walk_items(&mut self, items: &[Item]) {
        for item in items {
            self.walk_item(item, "");
        }
    }

    fn walk_item(&mut self, item: &Item, module_prefix: &str) {
        match item {
            Item::Fn(f) => self.walk_fn(&qualify(module_prefix, &f.sig.ident.to_string()), &f.block),
            Item::Impl(i) => self.walk_impl(i, module_prefix),
            Item::Mod(m) => {
                if let Some((_, sub)) = &m.content {
                    let nested = qualify(module_prefix, &m.ident.to_string());
                    for it in sub {
                        self.walk_item(it, &nested);
                    }
                }
            }
            _ => {}
        }
    }

    fn walk_impl(&mut self, i: &ItemImpl, module_prefix: &str) {
        let self_ty = type_ident(&i.self_ty);
        let scope = qualify(module_prefix, &self_ty);
        for it in &i.items {
            if let ImplItem::Fn(f) = it {
                self.walk_fn(&qualify(&scope, &f.sig.ident.to_string()), &f.block);
            }
        }
    }

    fn walk_fn(&mut self, caller: &str, block: &syn::Block) {
        let mut cc = CallCollector {
            caller: format!("{}::{}", self.crate_name, caller),
            crate_name: self.crate_name.clone(),
            file: self.file.clone(),
            out: self.out,
        };
        cc.visit_block(block);
    }
}

struct CallCollector<'a> {
    caller: String,
    crate_name: String,
    file: String,
    out: &'a mut Vec<AccessEdge>,
}

impl<'a> CallCollector<'a> {
    fn record(
        &mut self,
        callee: &str,
        args: &syn::punctuated::Punctuated<Expr, syn::Token![,]>,
        line: u32,
    ) {
        let Some(pairs) = accessor_table_access(callee) else { return };
        for (table_opt, access) in pairs {
            let table = match table_opt {
                Some(t) => t.to_string(),
                // generic browser: the table is the first string-literal arg.
                None => first_str_lit(args).unwrap_or_else(|| DYNAMIC_TABLE.to_string()),
            };
            self.out.push(AccessEdge {
                caller_fn: self.caller.clone(),
                crate_name: self.crate_name.clone(),
                table,
                access,
                file: self.file.clone(),
                line,
            });
        }
    }
}

impl<'ast, 'a> Visit<'ast> for CallCollector<'a> {
    fn visit_expr(&mut self, e: &'ast Expr) {
        match e {
            Expr::Call(c) => {
                if let Expr::Path(p) = &*c.func {
                    let callee = last_seg(&p.path);
                    self.record(&callee, &c.args, c.func.span().start().line as u32);
                }
            }
            Expr::MethodCall(m) => {
                let callee = m.method.to_string();
                self.record(&callee, &m.args, m.method.span().start().line as u32);
            }
            _ => {}
        }
        syn::visit::visit_expr(self, e);
    }
}

fn qualify(prefix: &str, name: &str) -> String {
    if prefix.is_empty() {
        name.to_string()
    } else {
        format!("{prefix}::{name}")
    }
}

fn last_seg(p: &syn::Path) -> String {
    p.segments
        .last()
        .map(|s| s.ident.to_string())
        .unwrap_or_default()
}

fn type_ident(ty: &syn::Type) -> String {
    if let syn::Type::Path(tp) = ty {
        last_seg(&tp.path)
    } else {
        "_".to_string()
    }
}

/// The first string-literal argument of a call, if any (the table name in
/// `scan_preview("mcp_requests", 50_000)`).
fn first_str_lit(args: &syn::punctuated::Punctuated<Expr, syn::Token![,]>) -> Option<String> {
    for a in args {
        if let Expr::Lit(l) = a {
            if let Lit::Str(s) = &l.lit {
                return Some(s.value());
            }
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn extracts_named_read_and_write_edges() {
        // The LAW-1 fixture from the task: a `query_test_results` call in `foo`
        // and an `append_release_events` call in `bar`. Assert the extracted
        // edges are exactly {foo→test_results:read, bar→release_events:write}.
        let src = r#"
            async fn foo(wh: &Wh) {
                let rows = query_test_results(wh, &sel).await.unwrap();
                let _ = rows;
            }
            async fn bar(wh: &Wh) {
                append_release_events(wh, &events).await.unwrap();
            }
        "#;
        let edges = scan_source("demo", "src/lib.rs", src);

        assert_eq!(edges.len(), 2, "exactly two edges: {edges:?}");

        let foo = edges
            .iter()
            .find(|e| e.caller_fn == "demo::foo")
            .expect("foo edge present");
        assert_eq!(foo.table, "test_results");
        assert_eq!(foo.access, Access::Read);
        assert_eq!(foo.file, "src/lib.rs");
        assert_eq!(foo.crate_name, "demo");
        assert!(foo.line > 0, "real source line");

        let bar = edges
            .iter()
            .find(|e| e.caller_fn == "demo::bar")
            .expect("bar edge present");
        assert_eq!(bar.table, "release_events");
        assert_eq!(bar.access, Access::Write);
    }

    #[test]
    fn multi_table_writer_emits_one_edge_per_table() {
        // A knowledge scan writes symbol_facts + call_edges + feature_gate_facts
        // in one call → three write edges from the same caller.
        let src = r#"
            fn scan_and_store(wh: &Wh) {
                append_symbol_scan(wh, &scan).unwrap();
            }
        "#;
        let edges = scan_source("nornir", "src/mimir.rs", src);
        let tables: Vec<&str> = edges.iter().map(|e| e.table.as_str()).collect();
        assert!(tables.contains(&"symbol_facts"), "{tables:?}");
        assert!(tables.contains(&"call_edges"));
        assert!(tables.contains(&"feature_gate_facts"));
        assert!(edges.iter().all(|e| e.access == Access::Write));
        assert!(edges.iter().all(|e| e.caller_fn == "nornir::scan_and_store"));
    }

    #[test]
    fn generic_scan_preview_reads_literal_table_arg() {
        // `scan_preview("mcp_requests", 50_000)` — the table is the string
        // literal, statically knowable. A method call form is also matched.
        let src = r#"
            fn mcp_load(wh: &Wh) {
                let _ = wh.scan_preview("mcp_requests", 50_000);
            }
            fn dyn_load(wh: &Wh, t: &str) {
                let _ = wh.scan_preview(t, 500);
            }
        "#;
        let edges = scan_source("nornir", "src/viz/mcp_tab.rs", src);

        let mcp = edges.iter().find(|e| e.caller_fn == "nornir::mcp_load").unwrap();
        assert_eq!(mcp.table, "mcp_requests");
        assert_eq!(mcp.access, Access::Read);

        // The runtime-variable table is recorded as the <dynamic> sentinel —
        // the access site is real, the table is not statically knowable.
        let dynamic = edges.iter().find(|e| e.caller_fn == "nornir::dyn_load").unwrap();
        assert_eq!(dynamic.table, DYNAMIC_TABLE);
        assert_eq!(dynamic.access, Access::Read);
    }

    #[test]
    fn impl_methods_get_qualified_caller_names() {
        // A method on an impl block carries the type in its caller path, and a
        // method-call accessor (`.query_release_events()` style) is matched.
        let src = r#"
            struct Loader;
            impl Loader {
                async fn hydrate(&self, wh: &Wh) {
                    let _ = query_release_events(wh, &sel).await;
                }
            }
        "#;
        let edges = scan_source("nornir", "src/viz/live.rs", src);
        assert_eq!(edges.len(), 1);
        assert_eq!(edges[0].caller_fn, "nornir::Loader::hydrate");
        assert_eq!(edges[0].table, "release_events");
        assert_eq!(edges[0].access, Access::Read);
    }

    #[test]
    fn non_accessor_calls_are_ignored() {
        let src = r#"
            fn unrelated() {
                println!("hello");
                let _ = format!("{}", 1);
                helper();
            }
        "#;
        let edges = scan_source("demo", "src/lib.rs", src);
        assert!(edges.is_empty(), "no accessor calls → no edges: {edges:?}");
    }
}