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
//! nornir's OWN linked bencher registrations (Task #39 — bench-move).
//!
//! The `register_bench!` calls MUST compile INTO the `nornir` library so that
//! `inventory` links them into every binary/test that uses the lib — crucially
//! the release completeness-gate binary. The bencher-discovery seam the coverage
//! gate sweeps, [`nornir_bench::api::registered_bench_ids`], reports exactly the
//! benchers linked into the CURRENT unit; when nornir's benchers lived only in
//! `examples/nornir-bench.rs` (an example is NOT linked into the lib) that seam
//! saw ZERO benchers at gate time and every hot-path fell back to a seeded
//! allowlist excuse — the gate had nothing real to check.
//!
//! With the registrations here, a gate run sees `nornir.dep_graph_build` /
//! `nornir.dep_graph_build_ext`, so the `nornir.dep_graph` hot-path is verified
//! for real (its allowlist entry is deleted). `examples/nornir-bench.rs` stays
//! the RUNNER: it links this lib, so `run_main_json()` iterates these same
//! `inventory` registrations — no bencher is defined in the example any more.
//!
//! ## Benches
//!
//! - `nornir.dep_graph_build` / `nornir.dep_graph_build_ext` — the B-bucket
//!   dependency-Mímir workload, cloned from `tests/scenarios.rs::l3/l4`.
//!   Generates a layered-DAG synthetic workspace of 50 real cargo crates, times
//!   [`WorkspaceGraph::build`](crate::warehouse::dep_graph::WorkspaceGraph::build)
//!   (which runs `cargo metadata` per repo), then times the warm
//!   transitive-closure queries the Mímir answers (`dependents_transitive` /
//!   `deps_transitive`) over every repo. The `_ext` variant additionally pins 300
//!   locked "external" crates so the build also resolves external-dependency edges.
//!
//! The synthetic-workspace generator is the same one the scenario tests use,
//! `#[path]`-included exactly like `scenarios.rs` does. It is kept private here so
//! moving it into the lib adds NO public API surface — only the `inventory`
//! registrations become visible, via the discovery seam.
#![allow(dead_code)]

use anyhow::Result;

use crate::bench::api::Bencher;
use crate::bench::BenchResult;
use crate::warehouse::dep_graph::WorkspaceGraph;
use crate::workspace::WorkspaceDescriptor;

#[path = "../tests/support/genworkspace.rs"]
mod genworkspace;
use genworkspace::{gen_workspace, GenSpec, Shape};

/// B-bucket: build a `WorkspaceGraph` over a synthetic layered DAG, then run
/// warm transitive-closure queries over every repo — the dependency-Mímir's
/// hot path.
///
/// This is a **latency / IO microbench, NOT a parallel-compute arm** (bencher
/// O1): the build phase is one `cargo metadata` subprocess per repo (I/O +
/// process bound) and the query phase is a warm in-memory closure battery. The
/// **authoritative metric is `queries_per_sec`** (~600K, run-to-run flat);
/// `build_ms` is host-contention wall-time that swings ~10× and must NOT be read
/// as a compute regression or the arm treated as multi-threaded. The
/// core-saturation LAW therefore exempts it (see
/// [`crate::release::gate::is_latency_microbench`]); the genuinely parallel
/// nornir headline arms are `knowledge_scan` / `warehouse_query`.
struct DepGraphBuild {
    id: &'static str,
    repos: usize,
    ext_crates: usize,
}

impl Bencher for DepGraphBuild {
    fn id(&self) -> &'static str {
        self.id
    }

    fn run(&self) -> Result<BenchResult> {
        // Build the synthetic workspace on disk (real cargo crates + descriptor).
        let mut spec = GenSpec::new(Shape::LayeredDag, self.repos).seed(42);
        if self.ext_crates > 0 {
            spec = spec.ext_crates(self.ext_crates);
        }
        let ws = gen_workspace(&spec);

        // ── Time the graph build (one `cargo metadata` per repo). ──
        let desc = WorkspaceDescriptor::load(&ws.descriptor_path)?;
        let t0 = std::time::Instant::now();
        let g = WorkspaceGraph::build(&desc)?;
        let build = t0.elapsed();

        // ── Time the warm closure queries (the Mímir's hot answers). ──
        // Two closures per repo, exactly the L3/L4 query battery.
        let t1 = std::time::Instant::now();
        let mut answered = 0u64;
        for name in &ws.repo_names {
            let _ = g.dependents_transitive(name);
            let _ = g.deps_transitive(name);
            answered += 2;
        }
        let queries = t1.elapsed();

        let crates = ws.repo_names.len() as u64;
        let queries_per_sec = if queries.as_secs_f64() > 0.0 {
            answered as f64 / queries.as_secs_f64()
        } else {
            0.0
        };

        let mut metrics = serde_json::Map::new();
        metrics.insert("build_ms".into(), serde_json::json!(build.as_secs_f64() * 1000.0));
        metrics.insert("crates".into(), serde_json::json!(crates));
        metrics.insert("queries".into(), serde_json::json!(answered));
        metrics.insert("queries_per_sec".into(), serde_json::json!(queries_per_sec));
        metrics.insert("ext_crates".into(), serde_json::json!(self.ext_crates));
        metrics.insert(
            "elapsed_ms".into(),
            serde_json::json!((build + queries).as_secs_f64() * 1000.0),
        );

        Ok(BenchResult { name: self.id.into(), metrics , ..Default::default() })
    }
}

// `nornir.dep_graph_build`     — 50 repos, no externals (mirrors L3).
crate::register_bench!(DepGraphBuild {
    id: "nornir.dep_graph_build",
    repos: 50,
    ext_crates: 0,
});

/// The **introspection DELTA** bench (design doc `P0.1`): in an N-file crate,
/// change ONE file, then measure the time to an updated warehouse via the
/// file-level delta rescan vs a full from-scratch rebuild. This is the number
/// that has to beat JetBrains on re-index latency — the whole point of
/// [`crate::knowledge::delta`].
struct DeltaRescan {
    id: &'static str,
    files: usize,
}

impl Bencher for DeltaRescan {
    fn id(&self) -> &'static str {
        self.id
    }

    fn run(&self) -> Result<BenchResult> {
        use crate::knowledge::delta::SymbolDelta;

        // A synthetic single-crate workspace of `files` one-fn modules on disk.
        let dir = tempfile::tempdir()?;
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nname = \"deltabench\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
        )?;
        let src = dir.path().join("src");
        std::fs::create_dir_all(&src)?;
        let mut lib = String::new();
        for i in 0..self.files {
            std::fs::write(
                src.join(format!("m{i}.rs")),
                format!("pub fn f{i}() {{ let _ = {i}; }}\npub struct S{i};\n"),
            )?;
            lib.push_str(&format!("pub mod m{i};\n"));
        }
        std::fs::write(src.join("lib.rs"), lib)?;

        let now = chrono::Utc::now();

        // ── Cold: one full build (parse EVERY file) + its manifest. ──
        let t0 = std::time::Instant::now();
        let mut wh = SymbolDelta::full_build(dir.path(), "deltabench", uuid::Uuid::new_v4(), now)?;
        let full_build = t0.elapsed();
        let baseline_syms = wh.scan.symbols.len();

        // Edit ONE file (mid-tree). Bump mtime so the cheap gate can't miss it.
        let target = src.join(format!("m{}.rs", self.files / 2));
        std::thread::sleep(std::time::Duration::from_millis(12));
        std::fs::write(&target, "pub fn edited() {}\npub struct Edited;\npub struct Extra;\n")?;

        // ── Delta: re-parse ONLY the changed file, merge. ──
        let t1 = std::time::Instant::now();
        let plan = wh.rescan(dir.path(), uuid::Uuid::new_v4(), now)?;
        let delta = t1.elapsed();

        // ── Reference: a full from-scratch rebuild of the mutated tree. ──
        let t2 = std::time::Instant::now();
        let _fresh =
            SymbolDelta::full_build(dir.path(), "deltabench", uuid::Uuid::new_v4(), now)?;
        let full_rebuild = t2.elapsed();

        let speedup = if delta.as_secs_f64() > 0.0 {
            full_rebuild.as_secs_f64() / delta.as_secs_f64()
        } else {
            0.0
        };

        let mut metrics = serde_json::Map::new();
        metrics.insert("files".into(), serde_json::json!(self.files));
        metrics.insert("full_build_ms".into(), serde_json::json!(full_build.as_secs_f64() * 1000.0));
        metrics.insert("delta_rescan_ms".into(), serde_json::json!(delta.as_secs_f64() * 1000.0));
        metrics.insert("full_rebuild_ms".into(), serde_json::json!(full_rebuild.as_secs_f64() * 1000.0));
        metrics.insert("speedup_vs_full".into(), serde_json::json!(speedup));
        metrics.insert("files_touched".into(), serde_json::json!(plan.touched()));
        metrics.insert("baseline_symbols".into(), serde_json::json!(baseline_syms));
        metrics.insert("elapsed_ms".into(), serde_json::json!((full_build + delta + full_rebuild).as_secs_f64() * 1000.0));

        Ok(BenchResult { name: self.id.into(), metrics, ..Default::default() })
    }
}

// `nornir.delta_rescan` — 1-file edit in a 400-file crate → updated warehouse.
crate::register_bench!(DeltaRescan {
    id: "nornir.delta_rescan",
    files: 400,
});

// `nornir.dep_graph_build_ext` — 50 repos + 300 locked externals (mirrors L4).
crate::register_bench!(DepGraphBuild {
    id: "nornir.dep_graph_build_ext",
    repos: 50,
    ext_crates: 300,
});

/// The **knowledge-scan** hot path (`BENCH_HOT_PATHS[nornir.knowledge_scan]`): a
/// from-scratch symbol + call-edge scan of a whole crate. Builds a synthetic
/// N-file crate on disk (each module a fn that CALLS its sibling, so the scan
/// resolves real call-edges too), then times
/// [`crate::knowledge::symbols::scan_repo`] — the parallel `syn` parse that
/// produces the `symbol_facts` / `call_edges` index the introspection warehouse
/// is built from. This is the raw index-build number the delta rescan is
/// measured against.
struct KnowledgeScan {
    id: &'static str,
    files: usize,
}

impl Bencher for KnowledgeScan {
    fn id(&self) -> &'static str {
        self.id
    }

    fn run(&self) -> Result<BenchResult> {
        use crate::knowledge::symbols::scan_repo;

        // A synthetic single-crate workspace of `files` modules, each a fn that
        // calls the next module's fn (so the scan produces real call-edges) plus
        // a struct (so there are type symbols to collect).
        let dir = tempfile::tempdir()?;
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nname = \"scanbench\"\nversion = \"0.0.0\"\nedition = \"2021\"\n",
        )?;
        let src = dir.path().join("src");
        std::fs::create_dir_all(&src)?;
        let mut lib = String::new();
        for i in 0..self.files {
            let next = (i + 1) % self.files;
            std::fs::write(
                src.join(format!("m{i}.rs")),
                format!(
                    "pub fn f{i}() {{ let _ = crate::m{next}::g{next}(); }}\n\
                     pub fn g{i}() -> u32 {{ {i} }}\n\
                     pub struct S{i} {{ pub v: u32 }}\n"
                ),
            )?;
            lib.push_str(&format!("pub mod m{i};\n"));
        }
        std::fs::write(src.join("lib.rs"), lib)?;

        let now = chrono::Utc::now();

        // ── Time the full from-scratch scan (parse EVERY file across all cores). ──
        let t0 = std::time::Instant::now();
        let scan = scan_repo(dir.path(), "scanbench", uuid::Uuid::new_v4(), now)?;
        let elapsed = t0.elapsed();

        let symbols = scan.symbols.len() as u64;
        let calls = scan.calls.len() as u64;
        let symbols_per_sec = if elapsed.as_secs_f64() > 0.0 {
            symbols as f64 / elapsed.as_secs_f64()
        } else {
            0.0
        };

        let mut metrics = serde_json::Map::new();
        metrics.insert("files".into(), serde_json::json!(self.files));
        metrics.insert("symbols".into(), serde_json::json!(symbols));
        metrics.insert("call_edges".into(), serde_json::json!(calls));
        metrics.insert("symbols_per_sec".into(), serde_json::json!(symbols_per_sec));
        metrics.insert(
            "elapsed_ms".into(),
            serde_json::json!(elapsed.as_secs_f64() * 1000.0),
        );

        Ok(BenchResult { name: self.id.into(), metrics, ..Default::default() })
    }
}

// `nornir.knowledge_scan` — from-scratch symbol + call-edge scan of a 300-file crate.
crate::register_bench!(KnowledgeScan {
    id: "nornir.knowledge_scan",
    files: 300,
});

/// The **vector-search** hot path (`BENCH_HOT_PATHS[nornir.vector_search]`): the
/// embedding similarity query the semantic-search index answers. Fills a real
/// [`crate::vector::VectorIndex`] with `rows` deterministic `dim`-D vectors
/// (over [`crate::vector::I8_SCAN_THRESHOLD`], so `search_auto` dispatches the
/// same int8/VNNI kernel `store::search` uses in production), then times a
/// battery of top-k nearest-neighbour queries — the exact cosine-similarity
/// scan the `vector_search` MCP tool / CLI runs per query.
#[cfg(feature = "vector")]
struct VectorSearch {
    id: &'static str,
    rows: usize,
    dim: usize,
    queries: usize,
    k: usize,
}

#[cfg(feature = "vector")]
impl Bencher for VectorSearch {
    fn id(&self) -> &'static str {
        self.id
    }

    fn run(&self) -> Result<BenchResult> {
        use crate::vector::VectorIndex;

        // Deterministic pseudo-embedding: a smooth per-(row,dim) function so every
        // vector is distinct and non-degenerate (no external model needed — we are
        // benching the SEARCH kernel, not the embedder).
        let mk = |seed: u64, dim: usize| -> Vec<f32> {
            (0..dim)
                .map(|d| {
                    let x = (seed.wrapping_mul(2_654_435_761).wrapping_add(d as u64)) as f32;
                    (x * 0.000_1).sin() + 0.001 * (d as f32 + 1.0)
                })
                .collect()
        };

        // ── Build the index (excluded from the query timing). ──
        let mut idx = VectorIndex::new(self.dim)?;
        let mut flat = Vec::with_capacity(self.rows * self.dim);
        let mut ids = Vec::with_capacity(self.rows);
        for r in 0..self.rows as u64 {
            flat.extend(mk(r, self.dim));
            ids.push(r * 7 + 3);
        }
        idx.add(&flat, &ids)?;

        // ── Time the top-k query battery (the real similarity search). ──
        let t0 = std::time::Instant::now();
        let mut hits = 0u64;
        for q in 0..self.queries as u64 {
            let query = mk(q.wrapping_mul(31).wrapping_add(1_000), self.dim);
            hits += idx.search_auto(&query, self.k).len() as u64;
        }
        let elapsed = t0.elapsed();

        let queries_per_sec = if elapsed.as_secs_f64() > 0.0 {
            self.queries as f64 / elapsed.as_secs_f64()
        } else {
            0.0
        };

        let mut metrics = serde_json::Map::new();
        metrics.insert("rows".into(), serde_json::json!(self.rows));
        metrics.insert("dim".into(), serde_json::json!(self.dim));
        metrics.insert("queries".into(), serde_json::json!(self.queries));
        metrics.insert("k".into(), serde_json::json!(self.k));
        metrics.insert("hits".into(), serde_json::json!(hits));
        metrics.insert("queries_per_sec".into(), serde_json::json!(queries_per_sec));
        metrics.insert(
            "elapsed_ms".into(),
            serde_json::json!(elapsed.as_secs_f64() * 1000.0),
        );

        Ok(BenchResult { name: self.id.into(), metrics, ..Default::default() })
    }
}

// `nornir.vector_search` — 8192×128-D index, 256 top-10 similarity queries.
#[cfg(feature = "vector")]
crate::register_bench!(VectorSearch {
    id: "nornir.vector_search",
    rows: 8192,
    dim: 128,
    queries: 256,
    k: 10,
});

/// The **warehouse-query** hot path (`BENCH_HOT_PATHS[nornir.warehouse_query]`):
/// a representative columnar read out of the local Iceberg warehouse. Writes one
/// coverage snapshot of `files` files (via the real `rows_for` + `append_report`
/// writer) into a temp-dir warehouse, then times
/// [`crate::warehouse::coverage::query_coverage`] — the Arrow `RecordBatch` scan
/// + decode + per-repo filter + sort that the Test-pane coverage panel and the
/// docs `nornir:gen:coverage` table read through. Fully offline (no network).
struct WarehouseQuery {
    id: &'static str,
    files: usize,
}

impl Bencher for WarehouseQuery {
    fn id(&self) -> &'static str {
        self.id
    }

    fn run(&self) -> Result<BenchResult> {
        use crate::coverage::{summarise, Boundary, FileCoverage, FnCoverage};
        use crate::warehouse::coverage::{append_report, query_coverage, rows_for};
        use crate::warehouse::iceberg::IcebergWarehouse;

        // A synthetic coverage report over `files` files (each with one fn), rolled
        // up by the real `summarise`, so the row shapes match a live `nornir
        // coverage` run exactly.
        let file_cov: Vec<FileCoverage> = (0..self.files)
            .map(|i| {
                let file = format!("src/gen/m{i}.rs");
                FileCoverage {
                    file: file.clone(),
                    krate: "nornir".into(),
                    lines: 20,
                    lines_covered: (i as u64 % 21),
                    regions: 12,
                    regions_covered: (i as u64 % 13),
                    functions: vec![FnCoverage {
                        name: format!("nornir::gen::m{i}::f{i}"),
                        file,
                        lines: 20,
                        lines_covered: (i as u64 % 21),
                        regions: 12,
                        regions_covered: (i as u64 % 13),
                        boundary: Boundary::Core,
                    }],
                }
            })
            .collect();
        let report = summarise("nornir", file_cov)?;
        let (rows, fn_rows) = rows_for(&report, "bench-run", "nornir", 1_000);

        let dir = tempfile::tempdir()?;
        let wh = IcebergWarehouse::open(dir.path())?;

        // ── Write one snapshot (excluded from the read timing). ──
        wh.block_on(append_report(&wh, &rows, &fn_rows))?;

        // ── Time the representative read query. ──
        let t0 = std::time::Instant::now();
        let back = wh.block_on(query_coverage(&wh, "nornir"))?;
        let elapsed = t0.elapsed();

        let read = back.len() as u64;
        let rows_per_sec = if elapsed.as_secs_f64() > 0.0 {
            read as f64 / elapsed.as_secs_f64()
        } else {
            0.0
        };

        let mut metrics = serde_json::Map::new();
        metrics.insert("files".into(), serde_json::json!(self.files));
        metrics.insert("rows_written".into(), serde_json::json!(rows.len()));
        metrics.insert("rows_read".into(), serde_json::json!(read));
        metrics.insert("rows_per_sec".into(), serde_json::json!(rows_per_sec));
        metrics.insert(
            "elapsed_ms".into(),
            serde_json::json!(elapsed.as_secs_f64() * 1000.0),
        );

        Ok(BenchResult { name: self.id.into(), metrics, ..Default::default() })
    }
}

// `nornir.warehouse_query` — read back a 500-file coverage snapshot from Iceberg.
crate::register_bench!(WarehouseQuery {
    id: "nornir.warehouse_query",
    files: 500,
});

/// The **funnel Plan-DAG assembly** hot path: build a synthetic funnel whose one
/// idea decomposes into an `n`-node dependency chain, then time
/// [`funnel_core::plan_dag::PlanDag::from_funnel`] — the projection + edge
/// assembly the `nornir viz` Plan-DAG panel runs whenever the plan selection
/// changes. Pure/offline (no warehouse), so it's a clean scaling number for the
/// DAG-over-N-nodes path.
struct PlanDagAssemble {
    id: &'static str,
    nodes: usize,
}

impl Bencher for PlanDagAssemble {
    fn id(&self) -> &'static str {
        self.id
    }

    fn run(&self) -> Result<BenchResult> {
        use funnel_core::event::{Event, ItemKind, PlanStatus};
        use funnel_core::ids::{IdeaId, NodeId, PlanId};
        use funnel_core::plan_dag::PlanDag;
        use funnel_core::state::Funnel;

        // Build the funnel: one idea → one Active plan → an n-node chain a→b→c→…
        let mut f = Funnel::default();
        let now = chrono::Utc::now();
        let idea = IdeaId::seq(1);
        let plan = PlanId::seq(1);
        f.apply(&Event::IdeaSubmitted {
            id: idea.clone(),
            source: "bench".into(),
            text: "assemble".into(),
            refs: vec![],
            item_kind: ItemKind::Idea,
            ts: now,
        })?;
        f.apply(&Event::PlanCreated {
            id: plan.clone(),
            idea_id: idea,
            summary: "chain".into(),
            planner: "bench".into(),
            ts: now,
        })?;
        f.apply(&Event::PlanStatusChanged { plan_id: plan.clone(), status: PlanStatus::Active, why: None, ts: now })?;
        for i in 1..=self.nodes as u64 {
            f.apply(&Event::NodeAdded {
                plan_id: plan.clone(),
                node_id: NodeId::seq(i),
                kind: "code:write".into(),
                params: Default::default(),
                targets: vec![],
                prompt_excerpt: Some(format!("task {i}")),
                ts: now,
            })?;
            if i > 1 {
                f.apply(&Event::EdgeAdded {
                    plan_id: plan.clone(),
                    from_node: NodeId::seq(i - 1),
                    to_node: NodeId::seq(i),
                    ts: now,
                })?;
            }
        }

        // ── Time the assembly (the hot path). ──
        let iters = 200u64;
        let t0 = std::time::Instant::now();
        let mut last_nodes = 0usize;
        for _ in 0..iters {
            let dag = PlanDag::from_funnel(&f, None);
            last_nodes = dag.node_count();
        }
        let elapsed = t0.elapsed();
        let per = elapsed.as_secs_f64() * 1000.0 / iters as f64;

        let mut metrics = serde_json::Map::new();
        metrics.insert("nodes".into(), serde_json::json!(last_nodes));
        metrics.insert("assemble_ms".into(), serde_json::json!(per));
        metrics.insert("elapsed_ms".into(), serde_json::json!(elapsed.as_secs_f64() * 1000.0));
        metrics.insert(
            "assemblies_per_sec".into(),
            serde_json::json!(if elapsed.as_secs_f64() > 0.0 { iters as f64 / elapsed.as_secs_f64() } else { 0.0 }),
        );

        Ok(BenchResult { name: self.id.into(), metrics, ..Default::default() })
    }
}

// `nornir.plan_dag_assemble` — assemble the funnel Plan-DAG over a 200-node chain.
crate::register_bench!(PlanDagAssemble {
    id: "nornir.plan_dag_assemble",
    nodes: 200,
});

#[cfg(test)]
mod tests {
    /// The whole point of moving the registrations into the lib (Task #39): the
    /// discovery seam MUST be non-empty in a build that links this crate, and MUST
    /// carry the `nornir.dep_graph` benchers — so the completeness gate verifies
    /// that hot-path for real instead of excusing it via an allowlist entry.
    #[test]
    fn dep_graph_benchers_are_linked_and_discoverable() {
        let ids = crate::bench::api::registered_bench_ids();
        assert!(!ids.is_empty(), "linked build must register at least one bencher: {ids:?}");
        assert!(
            ids.iter().any(|id| id == "nornir.dep_graph_build"),
            "nornir.dep_graph_build must be linked + discoverable: {ids:?}"
        );
        assert!(
            ids.iter().any(|id| id == "nornir.dep_graph_build_ext"),
            "nornir.dep_graph_build_ext must be linked + discoverable: {ids:?}"
        );
    }

    /// The bencher ids satisfy the `nornir.dep_graph` hot-path per the gate's
    /// matching rule (`id == key` or `<key>_`/`<key>.` prefix), so the gate row
    /// resolves covered from the LIVE registry — no allowlist excuse needed.
    #[test]
    fn dep_graph_hot_path_is_covered_by_registry() {
        let registered = crate::bench::api::registered_bench_ids();
        let rows = crate::autonom::bench_rows(&["nornir.dep_graph"], &registered);
        let dg = rows.iter().find(|r| r.module == "nornir.dep_graph").unwrap();
        assert!(dg.has_bencher, "dep_graph must be covered by the linked registry: {registered:?}");
    }

    /// The three formerly-sentinelled hot-paths — `knowledge_scan`,
    /// `warehouse_query`, and (under `vector`) `vector_search` — are now benched
    /// by LINKED registrations whose ids equal the hot-path key, so the
    /// completeness gate resolves them covered from the live registry and their
    /// `autonom-allow.toml` sentinels are deleted (a stale excuse would red the
    /// gate). Mirrors `dep_graph_hot_path_is_covered_by_registry`.
    #[test]
    fn wired_hot_paths_are_covered_by_registry() {
        let registered = crate::bench::api::registered_bench_ids();

        let mut keys = vec!["nornir.knowledge_scan", "nornir.warehouse_query"];
        #[cfg(feature = "vector")]
        keys.push("nornir.vector_search");

        let rows = crate::autonom::bench_rows(&keys, &registered);
        for key in &keys {
            let row = rows.iter().find(|r| &r.module == key).unwrap();
            assert!(
                row.has_bencher,
                "{key} must be covered by the linked registry: {registered:?}"
            );
        }
    }
}