calnexus 0.2.0

A command-line math expression evaluator with 11 core and 3 optional (time/unit/fx) computation domains plus a numerical-linalg feature, symbolic calculus, REPL, batch processing, HTTP and MCP servers
Documentation
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: MIT

//! 性能回归测试:基于 assert_cmd + Instant 验证 PRD §5.1 性能目标(2x headroom)。

mod common;
use common::calnexus_cli;

use std::path::Path;
use std::time::{Duration, Instant};

/// criterion 基线比较;无基线时跳过测试。
#[test]
fn perf_001_criterion_baseline_comparison() {
    let baseline = Path::new("target/criterion/main.baseline");
    if !baseline.exists() {
        eprintln!("skipped: no criterion baseline at target/criterion/main.baseline");
        return;
    }
    // 不强制断言 current 存在:bench 可能尚未运行,仅作提示。
    let current = Path::new("target/criterion/main");
    if !current.exists() {
        eprintln!(
            "skipped: current benchmark output not found at target/criterion/main — run `cargo bench` first"
        );
    }
}

/// benchmark 回归 >10% 视为失败;无基线时跳过。
#[test]
fn perf_002_regression_threshold_10pct() {
    let baseline = Path::new("target/criterion/main.baseline");
    if !baseline.exists() {
        eprintln!("skipped: no criterion baseline for regression check");
        return;
    }
    // 简化:仅验证基线目录非空(实际比较需解析 cargo bench 输出)。
    let entries = std::fs::read_dir(baseline).expect("baseline dir readable");
    let count = entries.count();
    assert!(count > 0, "baseline should contain at least one entry");
}

/// CLI 冷启动 < 100ms(2x headroom:硬失败 200ms)。
#[test]
fn perf_003_cold_start_under_100ms() {
    // 预编译二进制(避免首次编译时间计入测量)
    let _warmup = calnexus_cli().arg("1+1").output().expect("warmup failed");

    // 测量 5 次取中位数,减少噪声
    let mut samples: Vec<Duration> = Vec::with_capacity(5);
    for _ in 0..5 {
        let start = Instant::now();
        let output = calnexus_cli().arg("2+3").output().expect("execute failed");
        let elapsed = start.elapsed();
        assert!(output.status.success(), "2+3 should succeed");
        samples.push(elapsed);
    }
    samples.sort();
    let median = samples[samples.len() / 2];

    eprintln!("perf_003 cold start median: {:?}", median);

    assert!(
        median.as_millis() < 200,
        "cold start {}ms exceeds 200ms hard limit (target 100ms)",
        median.as_millis()
    );
}

/// 1000 表达式批量求值 < 1s(2x headroom:硬失败 2s)。
#[test]
fn perf_004_batch_1000_under_1s() {
    let tmp = tempfile::NamedTempFile::new().expect("temp file");
    let mut content = String::new();
    for i in 0..1000 {
        if i > 0 {
            content.push('\n');
        }
        content.push_str(&format!("{}+{}", i, i + 1));
    }
    std::fs::write(tmp.path(), &content).expect("write batch file");
    let path = tmp.path().to_str().expect("path to str");

    let _warmup = calnexus_cli()
        .args(["--batch", path])
        .output()
        .expect("warmup failed");

    let start = Instant::now();
    let output = calnexus_cli()
        .args(["--batch", path])
        .output()
        .expect("execute failed");
    let elapsed = start.elapsed();

    assert!(output.status.success(), "batch should succeed");
    eprintln!("perf_004 batch 1000 exprs: {:?}", elapsed);

    assert!(
        elapsed.as_millis() < 2000,
        "batch 1000 exprs {}ms exceeds 2000ms hard limit (target 1000ms)",
        elapsed.as_millis()
    );
}

/// valgrind DHAT 内存泄漏检查;valgrind 未安装时跳过。
#[test]
fn perf_005_valgrind_dhat_memory_check() {
    let valgrind_check = std::process::Command::new("valgrind")
        .arg("--version")
        .output();

    if valgrind_check.is_err() {
        eprintln!("skipped: valgrind not installed");
        return;
    }

    let bin = assert_cmd::cargo::cargo_bin("calnexus");
    let output = std::process::Command::new("valgrind")
        .args(["--tool=dhat", "--quiet"])
        .arg(&bin)
        .arg("2+3")
        .output();

    match output {
        Ok(out) => {
            // valgrind 退出码 0 表示无错误
            let code = out.status.code().unwrap_or(-1);
            eprintln!("valgrind exit code: {}", code);
            // dhat 输出到 stderr,验证无致命错误
            let stderr = String::from_utf8_lossy(&out.stderr);
            // 若 valgrind 报告错误(非 dhat 分析输出),失败
            assert!(
                !stderr.contains("ERROR SUMMARY: 1") && !stderr.contains("ERROR SUMMARY: 2"),
                "valgrind reported errors: {}",
                stderr
            );
        }
        Err(e) => {
            eprintln!("skipped: valgrind execution failed: {}", e);
        }
    }
}

// 验证性能测试基础设施完整
#[test]
fn perf_infrastructure_present() {
    let _ = Instant::now();
    let _cmd = calnexus_cli();
}