codingest 0.2.28

codingest — standalone extraction of KGLite's code-tree component: parse polyglot codebases into kglite knowledge graphs (tree-sitter parsers, call/type/route edges, docs pass, multi-rev merge)
Documentation
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
//! codingest Cypher query/traversal benchmark + query-parity harness.
//!
//! KGLite deleted its in-tree `code_tree` builder on 2026-07-16, so the old
//! cross-builder comparison (in-tree vs standalone) is gone. This harness now
//! builds the SAME target directory TWICE with `codingest::builder::run_with_options`
//! (two independent builds A and B), then runs an identical Cypher workload
//! against BOTH through kglite's canonical read path
//! (`kglite::api::session::{execute_read, ExecuteOptions}` — the exact pipeline
//! an MCP / CLI user hits).
//!
//! For each query we alternate timed iterations A/B/A/B… (warm cache) and report
//! median + min per side. Before timing, each query's result is compared across
//! the two builds (row count + a canonicalized, order-insensitive value digest);
//! a MISMATCH is reported and that query is NOT timed. Because the builder is
//! deterministic, two independent builds must return identical results — so a
//! MISMATCH is a query-result determinism regression, and the A/B delta is
//! run-to-run timing variance. The release gate fails on any MISMATCH.
//!
//! # The corpus is defined by the harness, not by the working directory
//!
//! A benchmark number is comparable to another only if both were measured on
//! the same input. The builder walks whatever is on disk: it skips dot-dirs,
//! `target/`, `node_modules/`, `venv/` and `__pycache__/` by name, but it has
//! no notion of `.gitignore`, so a repository's *untracked* working state
//! (scratch folders, local notes, generated markdown) is ingested — notably
//! through the docs pass. Benchmarking a working tree therefore measures a
//! corpus nobody else can reconstruct. Measured on this workspace: a clean
//! `git worktree` of a commit scored 1,115 nodes / 3,692 edges while the
//! working tree at that same commit scored 1,170 / 3,759 — a ~5% swing with no
//! builder or engine involvement, which silently invalidated published numbers.
//!
//! So this harness defines its own corpus. By default it materializes the
//! target's **git-tracked** files into a temporary directory and builds that:
//! the input is then a function of the committed content plus any uncommitted
//! edits to tracked files, reproducible on any machine at the same revision.
//! Every run prints `corpus_sha256`, so two numbers can be *checked* for
//! comparability rather than assumed comparable. `--include-untracked` restores
//! the old build-the-directory-as-is behaviour for a one-off measurement of a
//! non-git tree, and prints a NOT-REPRODUCIBLE banner.
//!
//! Usage:
//!   cargo run -p codingest --bin codingest_bench --release -- <path>
//!   cargo run -p codingest --bin codingest_bench --release -- <path> --json
//!   cargo run -p codingest --bin codingest_bench --release -- <path> --include-untracked
//!   cargo run -p codingest --bin codingest_bench --release -- <path> --no-docs

use kglite::api::session::{execute_read, ExecuteOptions, ExecuteOutcome};
use kglite::api::{DirGraph, GraphRead, Value};
use sha2::{Digest, Sha256};
use std::collections::hash_map::DefaultHasher;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::Instant;

const WARMUP: usize = 3;
const ITERS: usize = 20;

struct Query {
    name: &'static str,
    cypher: String,
}

/// Run one read-only query through the canonical session path.
fn run_query(graph: &DirGraph, query: &str) -> ExecuteOutcome {
    let params: HashMap<String, Value> = HashMap::new();
    let opts = ExecuteOptions::eager(&params);
    execute_read(graph, query, &opts)
        .unwrap_or_else(|e| panic!("query failed:\n  {query}\n  error: {e:?}"))
}

/// (row_count, order-insensitive value digest) for parity comparison.
/// Rows are canonicalized (`{:?}` per cell — stable for `Value`), sorted, and
/// hashed with the fixed-key `DefaultHasher`, so ordering nondeterminism between
/// the two graphs cannot produce a false MISMATCH — only a genuine difference in
/// the row multiset can.
fn digest(outcome: &ExecuteOutcome) -> (usize, u64) {
    let r = &outcome.result;
    let mut rows: Vec<String> = r
        .rows
        .iter()
        .map(|row| {
            row.iter()
                .map(|v| format!("{v:?}"))
                .collect::<Vec<_>>()
                .join("\u{1}")
        })
        .collect();
    rows.sort();
    let mut h = DefaultHasher::new();
    rows.len().hash(&mut h);
    for s in &rows {
        s.hash(&mut h);
    }
    (r.rows.len(), h.finish())
}

/// Extract the string in the first cell of the first row, if any.
fn first_string(outcome: &ExecuteOutcome) -> Option<String> {
    outcome
        .result
        .rows
        .first()
        .and_then(|row| row.first())
        .and_then(|v| match v {
            Value::String(s) => Some(s.clone()),
            _ => None,
        })
}

fn median(mut v: Vec<f64>) -> f64 {
    v.sort_by(|a, b| a.partial_cmp(b).unwrap());
    v[v.len() / 2]
}

fn min(v: &[f64]) -> f64 {
    v.iter().cloned().fold(f64::INFINITY, f64::min)
}

// ── corpus selection ─────────────────────────────────────────────────────

/// How the benchmark input was assembled. See the module docs.
#[derive(Clone, Copy, PartialEq, Eq)]
enum CorpusMode {
    /// Git-tracked files of the target, copied into a tempdir. Reproducible.
    TrackedOnly,
    /// The target directory exactly as it sits on disk. Not reproducible if
    /// the tree carries untracked or git-ignored content.
    WorkingTree,
}

impl CorpusMode {
    fn as_str(self) -> &'static str {
        match self {
            CorpusMode::TrackedOnly => "tracked-only",
            CorpusMode::WorkingTree => "working-tree",
        }
    }
}

/// The resolved benchmark input: the directory to build, plus the identity of
/// the content in it.
struct Corpus {
    build_dir: PathBuf,
    mode: CorpusMode,
    /// Why we ended up in `mode` — printed so the choice is never silent.
    reason: String,
    files: usize,
    bytes: u64,
    /// `None` in `WorkingTree` mode: the ingested set is not enumerable
    /// without duplicating the builder's walk, and an approximate identity is
    /// worse than an explicit absence.
    sha256: Option<String>,
    /// Owns the tempdir for the process lifetime; dropping it deletes the copy.
    _tmp: Option<tempfile::TempDir>,
}

fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}

/// Git-tracked paths under `target`, relative to it. `None` when `target` is
/// not inside a git work tree (or git is unavailable).
fn git_tracked_files(target: &Path) -> Option<Vec<String>> {
    let out = Command::new("git")
        .arg("-C")
        .arg(target)
        .args(["ls-files", "-z", "--cached"])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let stdout = String::from_utf8(out.stdout).ok()?;
    Some(
        stdout
            .split('\0')
            .filter(|s| !s.is_empty())
            .map(str::to_string)
            .collect(),
    )
}

/// Copy `rels` (relative to `target`) into a fresh tempdir and return the
/// corpus, including a content digest over the sorted `(path, sha256(bytes))`
/// pairs. Two runs with the same digest measured the same input.
fn materialize_tracked(target: &Path, mut rels: Vec<String>) -> std::io::Result<Corpus> {
    rels.sort();
    let tmp = tempfile::Builder::new()
        .prefix("codingest-bench-corpus-")
        .tempdir()?;
    let root = tmp.path().to_path_buf();

    let mut manifest = Sha256::new();
    let mut files = 0usize;
    let mut bytes = 0u64;

    for rel in &rels {
        let src = target.join(rel);
        // `ls-files` lists index entries; a tracked-but-deleted file, or a
        // gitlink (submodule) directory, has nothing to copy.
        let Ok(data) = std::fs::read(&src) else {
            continue;
        };
        let dst = root.join(rel);
        if let Some(parent) = dst.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(&dst, &data)?;

        let mut file_hash = Sha256::new();
        file_hash.update(&data);
        manifest.update(rel.as_bytes());
        manifest.update(b"\0");
        manifest.update(hex(&file_hash.finalize()).as_bytes());
        manifest.update(b"\n");

        files += 1;
        bytes += data.len() as u64;
    }

    Ok(Corpus {
        build_dir: root,
        mode: CorpusMode::TrackedOnly,
        reason: format!("git-tracked content of {}", target.display()),
        files,
        bytes,
        sha256: Some(hex(&manifest.finalize())),
        _tmp: Some(tmp),
    })
}

/// Resolve the benchmark input for `target`.
///
/// Default is `TrackedOnly`; it degrades to `WorkingTree` only when the target
/// is not in a git work tree, and says so. `--include-untracked` forces
/// `WorkingTree`.
fn resolve_corpus(target: &Path, include_untracked: bool) -> Corpus {
    let working_tree = |reason: String| Corpus {
        build_dir: target.to_path_buf(),
        mode: CorpusMode::WorkingTree,
        reason,
        files: 0,
        bytes: 0,
        sha256: None,
        _tmp: None,
    };

    if include_untracked {
        return working_tree("--include-untracked requested".to_string());
    }
    let Some(rels) = git_tracked_files(target) else {
        return working_tree(format!("{} is not in a git work tree", target.display()));
    };
    if rels.is_empty() {
        return working_tree(format!("git tracks no files under {}", target.display()));
    }
    match materialize_tracked(target, rels) {
        Ok(corpus) => corpus,
        Err(e) => {
            eprintln!("warning: could not materialize the tracked-only corpus: {e}");
            working_tree(format!("tracked-only materialization failed: {e}"))
        }
    }
}

// ── command line ─────────────────────────────────────────────────────────

const USAGE: &str = "usage: codingest_bench <path> [--json] [--include-untracked] [--no-docs]";

/// Everything the command line can say after `<path>`, parsed once so the
/// configuration a run was taken under is a value that can be echoed and
/// tested rather than a scatter of `any(|a| a == …)` predicates — the shape
/// `codingest_stats` already uses.
#[derive(Debug, PartialEq, Eq)]
struct Options {
    json: bool,
    include_untracked: bool,
    /// DECISION (2026-08-10): this default points the OPPOSITE way to
    /// `codingest_stats`' `--include-docs`, deliberately.
    ///
    /// Both binaries obey the same rule — a binary's default must reproduce
    /// that binary's own historical rows, or old and new numbers silently stop
    /// being comparable — and they have mirror-image histories. Every
    /// `codingest_stats` row predating its flag was captured docs-OFF, so it
    /// defaults off and opts in. This harness hardcoded docs-ON from the day it
    /// was written, so every bench row ever filed (`BENCHMARKS.md`, the ad-hoc
    /// results log) is a docs-ON measurement: it keeps docs-ON as the default
    /// and gains an explicit `--no-docs` opt-OUT.
    ///
    /// The asymmetry is therefore not an inconsistency to be tidied away; it is
    /// what keeps each binary's own series continuous. Neither default is
    /// self-describing, which is why the effective value is echoed in the JSON
    /// (`include_docs`) and in the human header either way — no row can be
    /// filed without stating the mode it was taken under.
    include_docs: bool,
}

impl Default for Options {
    fn default() -> Self {
        Self {
            json: false,
            include_untracked: false,
            include_docs: true,
        }
    }
}

/// Parse the arguments after `<path>`.
///
/// Rejects anything unrecognised rather than silently ignoring it: a typo'd
/// `--include-untraked` or `--nodocs` would otherwise change nothing and the
/// run would be reported as a measurement taken under a mode it never ran in.
/// That includes `--include-docs`: it is `codingest_stats`' spelling, it is not
/// this binary's, and accepting it as a no-op would teach the wrong muscle
/// memory for the one flag whose two binaries disagree.
fn parse_options(args: &[String]) -> Result<Options, String> {
    let mut out = Options::default();
    for arg in args {
        match arg.as_str() {
            "--json" => out.json = true,
            "--include-untracked" => out.include_untracked = true,
            "--no-docs" => out.include_docs = false,
            other => return Err(format!("unknown argument `{other}`")),
        }
    }
    Ok(out)
}

struct QueryResult {
    name: String,
    rows: usize,
    parity: bool,
    a_median_ms: f64,
    a_min_ms: f64,
    b_median_ms: f64,
    b_min_ms: f64,
    delta_pct: f64,
}

fn main() {
    let mut args = std::env::args().skip(1);
    let path = match args.next() {
        Some(p) => p,
        None => {
            eprintln!("{USAGE}");
            std::process::exit(2);
        }
    };
    let rest: Vec<String> = args.collect();
    let Options {
        json,
        include_untracked,
        include_docs,
    } = parse_options(&rest).unwrap_or_else(|e| {
        eprintln!("{e}");
        eprintln!("{USAGE}");
        std::process::exit(2);
    });
    let target = Path::new(&path);

    // Resolve the corpus BEFORE any timing: by default this copies the
    // target's git-tracked files into a tempdir so the measured input is
    // reproducible from the revision alone (see the module docs).
    let corpus = resolve_corpus(target, include_untracked);
    let build_dir = corpus.build_dir.as_path();

    // Two independent codingest builds with identical arguments: verbose=false,
    // include_tests=false, save_to=None, max_loc=None, docs=`include_docs`
    // (ON unless `--no-docs`). Both sides MUST take the same value — the A/B
    // comparison is a determinism check, so a configuration difference between
    // them would surface as a MISMATCH and be read as a builder regression.
    let t = Instant::now();
    let graph_a =
        codingest::builder::run_with_options(build_dir, false, false, None, None, include_docs)
            .unwrap_or_else(|e| {
                eprintln!("build A failed: {e}");
                std::process::exit(1);
            });
    let build_a_secs = t.elapsed().as_secs_f64();

    let t = Instant::now();
    let graph_b =
        codingest::builder::run_with_options(build_dir, false, false, None, None, include_docs)
            .unwrap_or_else(|e| {
                eprintln!("build B failed: {e}");
                std::process::exit(1);
            });
    let build_b_secs = t.elapsed().as_secs_f64();

    let a: &DirGraph = &graph_a;
    let b: &DirGraph = &graph_b;

    let nodes = a.graph.node_count();
    let edges = a.graph.edge_count();

    // Anchors discovered at runtime on graph A (graph B is equivalent, so the
    // same node exists there): the CALLS in-degree and out-degree hubs.
    let hot_in = first_string(&run_query(
        a,
        "MATCH (:Function)-[:CALLS]->(f:Function) \
         RETURN f.qualified_name AS q, count(*) AS c ORDER BY c DESC, q ASC LIMIT 1",
    ))
    .unwrap_or_default();
    let hot_out = first_string(&run_query(
        a,
        "MATCH (f:Function)-[:CALLS]->(:Function) \
         RETURN f.qualified_name AS q, count(*) AS c ORDER BY c DESC, q ASC LIMIT 1",
    ))
    .unwrap_or_default();

    let queries = vec![
        Query {
            name: "count_functions (full-label scan + count)",
            cypher: "MATCH (f:Function) RETURN count(f)".to_string(),
        },
        Query {
            name: "eq_filter_pub (equality property filter)",
            cypher: "MATCH (f:Function) WHERE f.visibility = 'pub' RETURN count(f)".to_string(),
        },
        Query {
            name: "contains_new (CONTAINS string filter)",
            cypher: "MATCH (f:Function) WHERE f.qualified_name CONTAINS 'new' RETURN count(f)"
                .to_string(),
        },
        Query {
            name: "top20_by_branch_count (ORDER BY + LIMIT)",
            cypher: "MATCH (f:Function) RETURN f.qualified_name, f.branch_count \
                     ORDER BY f.branch_count DESC, f.qualified_name ASC LIMIT 20"
                .to_string(),
        },
        Query {
            name: "defs_per_file (grouped aggregation)",
            cypher: "MATCH (file:File)-[:DEFINES]->(f:Function) \
                     RETURN file.path, count(f) AS c ORDER BY c DESC, file.path ASC LIMIT 20"
                .to_string(),
        },
        Query {
            name: "calls_edge_scan (1-hop edge scan + count)",
            cypher: "MATCH (:Function)-[:CALLS]->(:Function) RETURN count(*)".to_string(),
        },
        Query {
            name: "anchored_callers (anchored 1-hop, in-hub)",
            cypher: format!(
                "MATCH (caller:Function)-[:CALLS]->(f:Function {{qualified_name: '{hot_in}'}}) \
                 RETURN caller.qualified_name ORDER BY caller.qualified_name ASC"
            ),
        },
        Query {
            name: "two_hop_into_hot (2-hop traversal + count)",
            cypher: format!(
                "MATCH (a:Function)-[:CALLS]->(b:Function)-[:CALLS]->\
                 (f:Function {{qualified_name: '{hot_in}'}}) RETURN count(*)"
            ),
        },
        Query {
            name: "varlen_callers_1_3 ([:CALLS*1..3] + count DISTINCT)",
            cypher: format!(
                "MATCH (f:Function {{qualified_name: '{hot_in}'}})<-[:CALLS*1..3]-(caller:Function) \
                 RETURN count(DISTINCT caller)"
            ),
        },
        Query {
            name: "reverse_callees_of_hub (reverse-direction 1-hop)",
            cypher: format!(
                "MATCH (callee:Function)<-[:CALLS]-(f:Function {{qualified_name: '{hot_out}'}}) \
                 RETURN callee.qualified_name ORDER BY callee.qualified_name ASC"
            ),
        },
        Query {
            name: "method_calls_mix (Struct-HAS_METHOD->Fn-CALLS->Fn)",
            cypher: "MATCH (s:Struct)-[:HAS_METHOD]->(m:Function)-[:CALLS]->(f:Function) \
                     RETURN count(*)"
                .to_string(),
        },
    ];

    let mut results: Vec<QueryResult> = Vec::new();

    for q in &queries {
        // Parity first: run once on each graph, compare row-count + digest.
        let out_a = run_query(a, &q.cypher);
        let out_b = run_query(b, &q.cypher);
        let (rows_a, dig_a) = digest(&out_a);
        let (rows_b, dig_b) = digest(&out_b);
        let parity = rows_a == rows_b && dig_a == dig_b;

        if !parity {
            eprintln!(
                "MISMATCH on `{}`: build A rows={rows_a} digest={dig_a:016x} | \
                 build B rows={rows_b} digest={dig_b:016x}\n  query: {}",
                q.name, q.cypher
            );
            results.push(QueryResult {
                name: q.name.to_string(),
                rows: rows_a,
                parity: false,
                a_median_ms: f64::NAN,
                a_min_ms: f64::NAN,
                b_median_ms: f64::NAN,
                b_min_ms: f64::NAN,
                delta_pct: f64::NAN,
            });
            continue;
        }

        // Warmup both sides.
        for _ in 0..WARMUP {
            let _ = run_query(a, &q.cypher);
            let _ = run_query(b, &q.cypher);
        }
        // Timed, alternating A/B.
        let mut ta = Vec::with_capacity(ITERS);
        let mut tb = Vec::with_capacity(ITERS);
        for _ in 0..ITERS {
            let s = Instant::now();
            let _ = run_query(a, &q.cypher);
            ta.push(s.elapsed().as_secs_f64() * 1000.0);
            let s = Instant::now();
            let _ = run_query(b, &q.cypher);
            tb.push(s.elapsed().as_secs_f64() * 1000.0);
        }
        let a_min_ms = min(&ta);
        let b_min_ms = min(&tb);
        let a_median_ms = median(ta);
        let b_median_ms = median(tb);
        let delta_pct = if a_median_ms > 0.0 {
            (b_median_ms - a_median_ms) / a_median_ms * 100.0
        } else {
            0.0
        };

        results.push(QueryResult {
            name: q.name.to_string(),
            rows: rows_a,
            parity: true,
            a_median_ms,
            a_min_ms,
            b_median_ms,
            b_min_ms,
            delta_pct,
        });
    }

    if json {
        let out = serde_json::json!({
            "path": path,
            "corpus_mode": corpus.mode.as_str(),
            "corpus_reason": corpus.reason,
            "corpus_files": corpus.sha256.as_ref().map(|_| corpus.files),
            "corpus_bytes": corpus.sha256.as_ref().map(|_| corpus.bytes),
            "corpus_sha256": corpus.sha256,
            // Build configuration, echoed so a recorded row states it rather
            // than inheriting it from whoever reads the row. `include_docs` is
            // the EFFECTIVE value, not the default: docs are ON unless
            // `--no-docs` was passed, and when they are on the docs pass is in
            // these build times and node counts. Every historical bench row was
            // taken docs-ON — see `Options::include_docs` for why that is this
            // binary's default and the opposite of codingest_stats'.
            "include_tests": false,
            "include_docs": include_docs,
            "nodes": nodes,
            "edges": edges,
            "build_a_secs": (build_a_secs * 1000.0).round() / 1000.0,
            "build_b_secs": (build_b_secs * 1000.0).round() / 1000.0,
            "anchor_hot_in": hot_in,
            "anchor_hot_out": hot_out,
            "warmup": WARMUP,
            "iters": ITERS,
            "queries": results.iter().map(|r| serde_json::json!({
                "name": r.name,
                "rows": r.rows,
                "parity": r.parity,
                "a_median_ms": (r.a_median_ms * 1000.0).round() / 1000.0,
                "a_min_ms": (r.a_min_ms * 1000.0).round() / 1000.0,
                "b_median_ms": (r.b_median_ms * 1000.0).round() / 1000.0,
                "b_min_ms": (r.b_min_ms * 1000.0).round() / 1000.0,
                "delta_pct": (r.delta_pct * 100.0).round() / 100.0,
            })).collect::<Vec<_>>(),
        });
        println!("{}", serde_json::to_string_pretty(&out).unwrap());
        return;
    }

    println!("codingest Cypher benchmark — query-parity across two independent builds");
    println!("target : {path}");
    match &corpus.sha256 {
        Some(digest) => println!(
            "corpus : {} — {} files, {} bytes, sha256 {}\n         ({})",
            corpus.mode.as_str(),
            corpus.files,
            corpus.bytes,
            digest,
            corpus.reason,
        ),
        None => println!(
            "corpus : {} — NOT REPRODUCIBLE: untracked and git-ignored content \
             is ingested\n         ({})",
            corpus.mode.as_str(),
            corpus.reason,
        ),
    }
    // The effective build configuration, printed for the same reason the JSON
    // echoes it: a pasted bench table must carry the mode it was taken under.
    println!("config : include_tests=false include_docs={include_docs}");
    println!("graph  : {nodes} nodes / {edges} edges  (identical across both builds)");
    println!("build  : A {build_a_secs:.3}s | B {build_b_secs:.3}s  (one-off, context)");
    println!("anchor : in-hub  = {hot_in}");
    println!("         out-hub = {hot_out}");
    println!("timing : {WARMUP} warmup + {ITERS} timed iters, alternating A/B, warm cache\n");

    println!(
        "{:<52} {:>7} {:>12} {:>12} {:>9}  parity",
        "query", "rows", "build A(ms)", "build B(ms)", "delta"
    );
    println!("{}", "-".repeat(110));
    for r in &results {
        if r.parity {
            println!(
                "{:<52} {:>7} {:>12} {:>12} {:>8.1}%  OK",
                r.name,
                r.rows,
                format!("{:.3} (min {:.3})", r.a_median_ms, r.a_min_ms),
                format!("{:.3} (min {:.3})", r.b_median_ms, r.b_min_ms),
                r.delta_pct,
            );
        } else {
            println!(
                "{:<52} {:>7} {:>12} {:>12} {:>9}  MISMATCH",
                r.name, r.rows, "-", "-", "-",
            );
        }
    }
    let mismatches = results.iter().filter(|r| !r.parity).count();
    println!(
        "\n{} queries, {} OK, {} MISMATCH",
        results.len(),
        results.len() - mismatches,
        mismatches
    );
}

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

    fn opts(args: &[&str]) -> Result<Options, String> {
        parse_options(&args.iter().map(|a| a.to_string()).collect::<Vec<_>>())
    }

    #[test]
    fn parse_options_defaults_to_the_historical_docs_on_configuration() {
        // Every bench row ever filed was measured docs-ON, because this harness
        // hardcoded docs-ON before the flag existed. The default must stay that
        // way or old and new rows silently stop being comparable. This is the
        // MIRROR of codingest_stats' equivalent test, which asserts docs-OFF —
        // same rule, opposite history. See `Options::include_docs`.
        let parsed = opts(&[]).expect("empty argv parses");
        assert_eq!(parsed, Options::default());
        assert!(parsed.include_docs, "bench must default to docs-ON");
        assert!(!parsed.json);
        assert!(!parsed.include_untracked);
    }

    #[test]
    fn parse_options_reads_every_flag() {
        let parsed =
            opts(&["--json", "--include-untracked", "--no-docs"]).expect("all flags parse");
        assert!(parsed.json);
        assert!(parsed.include_untracked);
        assert!(!parsed.include_docs);
    }

    #[test]
    fn no_docs_turns_docs_off_on_its_own() {
        // The one flag whose absence is not the interesting case: assert it
        // flips the value rather than merely parsing.
        assert!(!opts(&["--no-docs"]).expect("parses").include_docs);
        assert!(opts(&["--json"]).expect("parses").include_docs);
    }

    #[test]
    fn parse_options_rejects_an_unknown_flag() {
        // A silently-ignored typo would report a measurement taken under a mode
        // the run never used — the reason this parser is strict at all.
        let err = opts(&["--include-untraked"]).expect_err("typo must not parse");
        assert!(err.contains("--include-untraked"), "unhelpful error: {err}");
        assert!(opts(&["--nodocs"]).is_err(), "`--nodocs` must not parse");
    }

    #[test]
    fn parse_options_rejects_the_stats_spelling_of_the_docs_flag() {
        // `--include-docs` is codingest_stats' flag. Accepting it here as a
        // harmless no-op (docs are already on) would teach that the two
        // binaries share a spelling for the one flag on which they disagree —
        // and would then silently accept `--include-docs` from a user who meant
        // to CHANGE the mode. Rejecting it is what makes the asymmetry visible
        // at the moment it matters.
        assert!(opts(&["--include-docs"]).is_err());
    }
}