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
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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: MIT

//! CalNexus 求值编排层:parse → canonicalize → cache → route → domain::evaluate。
//! 本模块不受 feature gate,CLI、REPL、batch 与 HTTP/MCP server 共用。

use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use crate::core::{
    AstCanonicalizer, AstNode, CacheManager, CalcError, CanonicalForm, DomainRouter, EvalContext,
    EvalResult, MAX_PRECISION, parse,
};
use crate::domains::{build_default_router, build_precision_domain};

/// 全链路求值:parse → canonicalize → cache → route → evaluate。
///
/// `cache` 允许调用方注入预填充缓存(测试用),生产代码传空缓存。
pub fn evaluate(
    expr: &str,
    ctx: &EvalContext,
    precision: Option<usize>,
    cache: &CacheManager,
) -> Result<(EvalResult, String, bool, Option<usize>), CalcError> {
    evaluate_with_router(expr, ctx, precision, cache, build_default_router())
}

/// 路由器可注入求值:与 [`evaluate`] 语义一致,路由器由调用方提供。
///
/// # 示例
///
/// ```
/// use calnexus::{evaluate_with_router, CacheManager, CalculationDomain, DomainRouter, EvalContext};
///
/// let router = DomainRouter::new(); // 空路由器(无内置域)
/// let cache = CacheManager::new();
/// let ctx = EvalContext::new();
/// // 空路由器下任何表达式都返回路由错误,证明路由器确实被注入消费
/// let err = evaluate_with_router("1+1", &ctx, None, &cache, &router).unwrap_err();
/// assert!(err.message.contains("no registered domain") || err.message.contains("route"));
/// ```
pub fn evaluate_with_router(
    expr: &str,
    ctx: &EvalContext,
    precision: Option<usize>,
    cache: &CacheManager,
    router: &DomainRouter,
) -> Result<(EvalResult, String, bool, Option<usize>), CalcError> {
    let start = Instant::now();
    // 阶段 1: 输入校验(timeout=0 + precision 上界)
    validate_inputs(ctx, precision)?;

    // 阶段 2: parse + canonicalize + 超时检查
    let ast = parse(expr)?;
    check_elapsed(start, ctx.timeout)?;
    let (canonical_ast, cf) = AstCanonicalizer::canonicalize(&ast)?;
    check_elapsed(start, ctx.timeout)?;
    let cache_cf = build_cache_key(&cf, ctx, precision);

    // 阶段 3: 按 precision 模式分发
    if precision.is_some() {
        eval_precision_mode(&canonical_ast, ctx, cache, &cache_cf, precision, start)
    } else {
        eval_regular_mode(&canonical_ast, ctx, cache, &cache_cf, start, router)
    }
}

/// 输入校验:timeout=0 立即超时 + precision 参数上界检查。
///
/// evaluate 是公共入口,不经 server validate(),须拦截超大 precision 防 DoS。
fn validate_inputs(ctx: &EvalContext, precision: Option<usize>) -> Result<(), CalcError> {
    if ctx.timeout.is_zero() {
        return Err(CalcError::timeout());
    }
    if let Some(p) = precision
        && p > MAX_PRECISION
    {
        return Err(
            CalcError::domain(format!("precision {} exceeds limit {}", p, MAX_PRECISION))
                .with_i18n(
                    "msg.core.precision_exceeds_limit",
                    vec![
                        ("precision".to_string(), p.to_string()),
                        ("max".to_string(), MAX_PRECISION.to_string()),
                    ],
                ),
        );
    }
    Ok(())
}

/// 缓存键 = CanonicalForm + precision + vars 哈希 + timeout;不混 vars 会导致 REPL 换值仍命中旧缓存。
fn build_cache_key(
    cf: &CanonicalForm,
    ctx: &EvalContext,
    precision: Option<usize>,
) -> CanonicalForm {
    let base = if precision.is_some() {
        format!("precision:{}", cf.as_str())
    } else {
        cf.as_str().to_string()
    };

    // 混入 vars 哈希
    let mut vars_input: Vec<u8> = Vec::new();
    let mut sorted_vars: Vec<_> = ctx.vars.iter().collect();
    sorted_vars.sort_by_key(|(k, _)| *k);
    for (k, v) in sorted_vars {
        vars_input.extend_from_slice(k.as_bytes());
        vars_input.push(0); // key/value 分隔符,防止边界混淆
        // to_bits 区分 -0.0 与 0.0(to_string 二者同为 "0",换用会误命中缓存)
        vars_input.extend_from_slice(&v.to_bits().to_le_bytes());
        vars_input.push(0); // 项分隔符,防止相邻项边界混淆
    }
    let vars_hash_hex = blake3::hash(&vars_input).to_hex();

    // 混入 timeout:已知 DoS 向量由常量约束,elapsed 检查捕获未知累积慢操作(第二道防线)
    let timeout_nanos = ctx.timeout.as_nanos();

    CanonicalForm::new(format!(
        "{}|vars={}|timeout={}",
        base, vars_hash_hex, timeout_nanos
    ))
}

/// precision 模式:直接用 PrecisionDomain 绕过路由器,`get_or_compute` 保证并发同键仅求值一次。
fn eval_precision_mode(
    canonical_ast: &AstNode,
    ctx: &EvalContext,
    cache: &CacheManager,
    cache_cf: &CanonicalForm,
    precision: Option<usize>,
    start: Instant,
) -> Result<(EvalResult, String, bool, Option<usize>), CalcError> {
    let computed = AtomicBool::new(false);
    let result = cache.get_or_compute(cache_cf, || {
        computed.store(true, Ordering::Relaxed);
        let domain = build_precision_domain();
        check_elapsed(start, ctx.timeout)?;
        let r = domain.evaluate(canonical_ast, ctx)?;
        check_elapsed(start, ctx.timeout)?;
        Ok(r)
    })?;
    Ok((
        result,
        "precision".to_string(),
        !computed.load(Ordering::Relaxed),
        precision,
    ))
}

/// 常规模式:路由器分发 + 缓存查询 + 格式化精度提取。
///
/// 非确定性表达式(now()/today()/fx() 等)同时跳过缓存读写,避免时间/汇率结果被污染。
fn eval_regular_mode(
    canonical_ast: &AstNode,
    ctx: &EvalContext,
    cache: &CacheManager,
    cache_cf: &CanonicalForm,
    start: Instant,
    router: &DomainRouter,
) -> Result<(EvalResult, String, bool, Option<usize>), CalcError> {
    // 非确定性函数旁路缓存:跳过 cache.get 与 cache.insert
    if router.is_nondeterministic(canonical_ast) {
        let domain = router.route(canonical_ast)?;
        check_elapsed(start, ctx.timeout)?;
        let result = domain.evaluate(canonical_ast, ctx)?;
        check_elapsed(start, ctx.timeout)?;
        let fmt_prec = extract_format_precision(canonical_ast);
        return Ok((result, domain.domain_name().to_string(), false, fmt_prec));
    }

    // 缓存查询或计算(single-flight):miss 时闭包内路由 + 求值 + 超时检查;
    // hit 时(含 single-flight follower)跳过闭包,domain 名与格式化精度照常提取。
    let computed = AtomicBool::new(false);
    let result = cache.get_or_compute(cache_cf, || {
        computed.store(true, Ordering::Relaxed);
        let domain = router.route(canonical_ast)?;
        check_elapsed(start, ctx.timeout)?;
        let r = domain.evaluate(canonical_ast, ctx)?;
        check_elapsed(start, ctx.timeout)?;
        Ok(r)
    })?;
    let domain = router.route(canonical_ast)?;
    let fmt_prec = extract_format_precision(canonical_ast);
    let cache_hit = !computed.load(Ordering::Relaxed);
    Ok((
        result,
        domain.domain_name().to_string(),
        cache_hit,
        fmt_prec,
    ))
}

/// 检查是否已超时,超时则返回 `CalcError::timeout()`。
///
/// 避免在 `evaluate` 中重复超时判断模板;`elapsed()` 开销约 20ns,可逐节点检查。
fn check_elapsed(start: Instant, timeout: Duration) -> Result<(), CalcError> {
    if start.elapsed() > timeout {
        return Err(CalcError::timeout());
    }
    Ok(())
}

/// 从 AST 顶层提取 precision(N, expr) 调用中的 N,用于输出格式化。
///
/// 安全约束:N > MAX_PRECISION 时返回 `None`(降级为分数格式化),防 format 循环 DoS。
fn extract_format_precision(ast: &AstNode) -> Option<usize> {
    if let AstNode::FunctionCall(name, args) = ast
        && name == "precision"
        && args.len() == 2
        && let AstNode::Number(n) = &args[0]
        && n.fract() == 0.0
        && *n > 0.0
    {
        let n_usize = *n as usize;
        // 纵深防御:拒绝超大精度值,防止 format_decimal 循环 DoS
        if n_usize <= MAX_PRECISION {
            return Some(n_usize);
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{BinaryOp, ErrorKind, EvalContext};

    /// evaluate_with_router 注入自定义路由器:空路由器下任意表达式路由失败。
    #[test]
    fn test_evaluate_with_router_injection() {
        let router = DomainRouter::new();
        let cache = CacheManager::new();
        let ctx = EvalContext::new();
        let r = evaluate_with_router("1+1", &ctx, None, &cache, &router);
        assert!(r.is_err(), "空路由器应无法路由 1+1");
    }

    // N 为 Number 但非正整数(浮点数)时,内层 if 不成立,返回 None。
    #[test]
    fn test_extract_format_precision_float_n() {
        let ast = AstNode::FunctionCall(
            "precision".to_string(),
            vec![
                AstNode::Number(2.5),
                AstNode::BinaryOp(
                    BinaryOp::Div,
                    Box::new(AstNode::Number(1.0)),
                    Box::new(AstNode::Number(3.0)),
                ),
            ],
        );
        assert_eq!(extract_format_precision(&ast), None);
    }

    // N 非 Number(如 Variable)时,if let 不匹配,返回 None。
    #[test]
    fn test_extract_format_precision_non_number_n() {
        let ast = AstNode::FunctionCall(
            "precision".to_string(),
            vec![AstNode::Variable("x".to_string()), AstNode::Number(1.0)],
        );
        assert_eq!(extract_format_precision(&ast), None);
    }

    // N 为 BigNumber 时,if let Number 不匹配,返回 None。
    #[test]
    fn test_extract_format_precision_bignumber_n() {
        let ast = AstNode::FunctionCall(
            "precision".to_string(),
            vec![AstNode::BigNumber("5".to_string()), AstNode::Number(1.0)],
        );
        assert_eq!(extract_format_precision(&ast), None);
    }

    // 正常路径:precision(5, expr) → Some(5)
    #[test]
    fn test_extract_format_precision_valid() {
        let ast = AstNode::FunctionCall(
            "precision".to_string(),
            vec![AstNode::Number(5.0), AstNode::Number(1.0)],
        );
        assert_eq!(extract_format_precision(&ast), Some(5));
    }

    // 非 precision 函数调用 → None
    #[test]
    fn test_extract_format_precision_non_precision_call() {
        let ast = AstNode::FunctionCall("sin".to_string(), vec![AstNode::Number(1.0)]);
        assert_eq!(extract_format_precision(&ast), None);
    }

    // 非函数调用节点 → None
    #[test]
    fn test_extract_format_precision_non_function() {
        let ast = AstNode::Number(42.0);
        assert_eq!(extract_format_precision(&ast), None);
    }

    // precision 模式 miss→hit 缓存路径,`precision:` 前缀键与常规模式隔离。
    #[test]
    fn test_evaluate_precision_mode_cache_hit() {
        let cache = CacheManager::new();
        let ctx = EvalContext::new();

        // 首次调用:miss → 计算并缓存到 precision: 前缀键
        let (result1, domain1, cache_hit1, fmt_prec1) =
            evaluate("2+3", &ctx, Some(5), &cache).unwrap();
        assert_eq!(result1, EvalResult::BigInt(num_bigint::BigInt::from(5)));
        assert_eq!(domain1, "precision");
        assert!(!cache_hit1);
        assert_eq!(fmt_prec1, Some(5));

        // 第二次调用:hit → 返回缓存值
        let (result2, domain2, cache_hit2, fmt_prec2) =
            evaluate("2+3", &ctx, Some(5), &cache).unwrap();
        assert_eq!(result2, result1);
        assert_eq!(domain2, "precision");
        assert!(cache_hit2);
        assert_eq!(fmt_prec2, Some(5));
    }

    // 缓存键隔离:常规模式预填 Scalar 后,precision 模式不得命中该缓存。
    #[test]
    fn test_evaluate_precision_mode_does_not_pollute_regular_cache() {
        let cache = CacheManager::new();
        let ast = parse("2+3").unwrap();
        let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();

        // 常规模式预填充 Scalar(5.0)
        cache.insert(&cf, &Ok(EvalResult::Scalar(5.0)));

        let ctx = EvalContext::new();
        // precision 模式不应命中常规模式缓存,应重新计算返回 BigRational/BigInt
        let (result, domain, cache_hit, fmt_prec) = evaluate("2+3", &ctx, Some(5), &cache).unwrap();
        assert_ne!(result, EvalResult::Scalar(5.0));
        assert_eq!(result, EvalResult::BigInt(num_bigint::BigInt::from(5)));
        assert_eq!(domain, "precision");
        assert!(!cache_hit);
        assert_eq!(fmt_prec, Some(5));
    }

    // N 超过 MAX_PRECISION 时,extract_format_precision 降级且求值被拒。
    #[test]
    fn test_evaluate_precision_bypass_dos_rejected() {
        let cache = CacheManager::new();
        let ctx = EvalContext::new();
        // N = MAX_PRECISION + 1,应被 extract_precision_value 拒绝
        let huge_n = MAX_PRECISION + 1;
        let expr = format!("precision({}, 1/3)", huge_n);
        let result = evaluate(&expr, &ctx, None, &cache);
        assert!(
            result.is_err(),
            "precision N > MAX_PRECISION must be rejected"
        );
    }

    // precision 参数本身 DoS 防护:入口处须拦截 precision > MAX_PRECISION。
    #[test]
    fn test_evaluate_precision_param_exceeds_limit_rejected() {
        let cache = CacheManager::new();
        let ctx = EvalContext::new();
        let result = evaluate("1/3", &ctx, Some(MAX_PRECISION + 1), &cache);
        assert!(
            result.is_err(),
            "precision param > MAX_PRECISION must be rejected"
        );
    }

    // 常规模式缓存命中:预填充键须经 build_cache_key 混入 vars 与 timeout 构造。
    #[test]
    fn test_evaluate_regular_mode_cache_hit() {
        let cache = CacheManager::new();
        let ast = parse("2+3").unwrap();
        let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();

        let ctx = EvalContext::new();
        let cache_cf = build_cache_key(&cf, &ctx, None);
        cache.insert(&cache_cf, &Ok(EvalResult::Scalar(5.0)));

        let (result, domain, cache_hit, fmt_prec) = evaluate("2+3", &ctx, None, &cache).unwrap();

        assert_eq!(result, EvalResult::Scalar(5.0));
        assert_eq!(domain, "arithmetic");
        assert!(cache_hit);
        assert_eq!(fmt_prec, None);
    }

    // 域 CLI 单元测试
    #[test]
    fn test_v08_cli_number_theory_gcd() {
        let cache = CacheManager::new();
        let ctx = EvalContext::new();
        let (result, domain, cache_hit, _) = evaluate("gcd(12,18)", &ctx, None, &cache).unwrap();
        assert_eq!(result, EvalResult::Scalar(6.0));
        assert_eq!(domain, "number_theory");
        assert!(!cache_hit);
    }

    #[test]
    fn test_v08_cli_combinatorics_C() {
        let cache = CacheManager::new();
        let ctx = EvalContext::new();
        let (result, domain, cache_hit, _) = evaluate("C(10,3)", &ctx, None, &cache).unwrap();
        assert_eq!(result, EvalResult::Scalar(120.0));
        assert_eq!(domain, "combinatorics");
        assert!(!cache_hit);
    }

    #[test]
    fn test_v08_cli_vector_dot() {
        let cache = CacheManager::new();
        let ctx = EvalContext::new();
        let (result, domain, _, _) = evaluate("dot([1,2,3],[4,5,6])", &ctx, None, &cache).unwrap();
        assert_eq!(result, EvalResult::Scalar(32.0));
        let _ = domain;
    }

    #[test]
    fn test_v08_cli_polynomial_add() {
        let cache = CacheManager::new();
        let ctx = EvalContext::new();
        let (result, domain, _, _) = evaluate("poly_add(x+1,x+2)", &ctx, None, &cache).unwrap();
        assert!(matches!(result, EvalResult::Polynomial(_)));
        assert_eq!(domain, "polynomial");
    }

    #[test]
    fn test_v08_cli_cache_hit_number_theory() {
        let cache = CacheManager::new();
        let ast = parse("gcd(12,18)").unwrap();
        let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();

        let ctx = EvalContext::new();
        // 缓存键需经 build_cache_key 混入 ctx.vars 哈希与 timeout
        let cache_cf = build_cache_key(&cf, &ctx, None);
        cache.insert(&cache_cf, &Ok(EvalResult::Scalar(6.0)));

        let (result, domain, cache_hit, _) = evaluate("gcd(12,18)", &ctx, None, &cache).unwrap();
        assert_eq!(result, EvalResult::Scalar(6.0));
        assert_eq!(domain, "number_theory");
        assert!(cache_hit);
    }

    #[test]
    fn test_v08_cli_cache_hit_combinatorics() {
        let cache = CacheManager::new();
        let ast = parse("C(10,3)").unwrap();
        let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();

        let ctx = EvalContext::new();
        // 缓存键需经 build_cache_key 混入 ctx.vars 哈希与 timeout
        let cache_cf = build_cache_key(&cf, &ctx, None);
        cache.insert(&cache_cf, &Ok(EvalResult::Scalar(120.0)));

        let (result, domain, cache_hit, _) = evaluate("C(10,3)", &ctx, None, &cache).unwrap();
        assert_eq!(result, EvalResult::Scalar(120.0));
        assert_eq!(domain, "combinatorics");
        assert!(cache_hit);
    }

    // ===== timeout elapsed 追踪测试 =====

    /// timeout=0 应立即超时(回归测试)。
    #[test]
    fn test_evaluate_timeout_zero_immediate() {
        let cache = CacheManager::new();
        let mut ctx = EvalContext::new();
        ctx.timeout = Duration::ZERO;
        let result = evaluate("1+1", &ctx, None, &cache);
        assert!(
            matches!(result, Err(ref e) if e.kind == ErrorKind::Timeout),
            "timeout=0 should trigger immediate timeout, got {:?}",
            result
        );
    }

    /// timeout elapsed 追踪:极小 timeout(非零)应在关键节点触发超时。
    #[test]
    fn test_evaluate_timeout_elapsed_triggers() {
        let cache = CacheManager::new();
        let mut ctx = EvalContext::new();
        ctx.timeout = Duration::from_nanos(1);
        // 确保时间过期(1ms >> 1ns)
        std::thread::sleep(Duration::from_millis(1));
        let result = evaluate("1+1", &ctx, None, &cache);
        assert!(
            matches!(result, Err(ref e) if e.kind == ErrorKind::Timeout),
            "should timeout (elapsed > 1ns), got {:?}",
            result
        );
    }

    /// 正常 timeout 不应误触发:默认 5s 超时下,简单表达式应成功。
    #[test]
    fn test_evaluate_timeout_normal_succeeds() {
        let cache = CacheManager::new();
        let ctx = EvalContext::new(); // 默认 timeout=5s
        let result = evaluate("1+1", &ctx, None, &cache);
        assert!(
            result.is_ok(),
            "normal eval should succeed, got {:?}",
            result
        );
    }

    /// precision 模式下的 timeout elapsed 追踪:同样受 elapsed 检查保护。
    #[test]
    fn test_evaluate_timeout_elapsed_precision_mode() {
        let cache = CacheManager::new();
        let mut ctx = EvalContext::new();
        ctx.timeout = Duration::from_nanos(1);
        std::thread::sleep(Duration::from_millis(1));
        let result = evaluate("1+1", &ctx, Some(5), &cache);
        assert!(
            matches!(result, Err(ref e) if e.kind == ErrorKind::Timeout),
            "precision mode should also timeout, got {:?}",
            result
        );
    }

    /// `check_elapsed` 辅助函数单元测试:未超时返回 Ok。
    #[test]
    fn test_check_elapsed_ok_when_not_expired() {
        let start = Instant::now();
        let timeout = Duration::from_secs(60);
        assert!(check_elapsed(start, timeout).is_ok());
    }

    /// `check_elapsed` 辅助函数单元测试:已超时返回 Timeout 错误。
    #[test]
    fn test_check_elapsed_err_when_expired() {
        let start = Instant::now();
        let timeout = Duration::from_nanos(1);
        std::thread::sleep(Duration::from_millis(1));
        let result = check_elapsed(start, timeout);
        assert!(
            matches!(result, Err(ref e) if e.kind == ErrorKind::Timeout),
            "expired should return Timeout error, got {:?}",
            result
        );
    }

    // ===== evaluate 三阶段分发回归测试:重构前后行为不变 =====
    #[test]
    fn test_evaluate_three_phases() {
        // ----- 阶段 1: 输入校验(timeout=0 / precision 越界 / parse 错误)-----
        {
            let cache = CacheManager::new();
            let mut ctx = EvalContext::new();
            ctx.timeout = Duration::ZERO;
            let r = evaluate("1+1", &ctx, None, &cache);
            assert!(matches!(r, Err(ref e) if e.kind == ErrorKind::Timeout));
        }
        // 1b. precision > MAX_PRECISION → 拒绝
        {
            let cache = CacheManager::new();
            let ctx = EvalContext::new();
            let r = evaluate("1/3", &ctx, Some(MAX_PRECISION + 1), &cache);
            assert!(r.is_err());
        }
        // 1c. parse 错误传播
        {
            let cache = CacheManager::new();
            let ctx = EvalContext::new();
            let r = evaluate("(1+2", &ctx, None, &cache);
            assert!(r.is_err());
        }

        // ----- 阶段 2: 执行分发(precision/常规模式 miss+hit、多域路由)-----
        {
            let cache = CacheManager::new();
            let ctx = EvalContext::new();
            let (r, domain, hit, fmt) = evaluate("2+3", &ctx, Some(5), &cache).unwrap();
            assert_eq!(r, EvalResult::BigInt(num_bigint::BigInt::from(5)));
            assert_eq!(domain, "precision");
            assert!(!hit);
            assert_eq!(fmt, Some(5));
        }
        // 2b. precision 模式 hit → 返回缓存
        {
            let cache = CacheManager::new();
            let ctx = EvalContext::new();
            let _ = evaluate("2+3", &ctx, Some(5), &cache).unwrap();
            let (r, domain, hit, fmt) = evaluate("2+3", &ctx, Some(5), &cache).unwrap();
            assert_eq!(r, EvalResult::BigInt(num_bigint::BigInt::from(5)));
            assert_eq!(domain, "precision");
            assert!(hit);
            assert_eq!(fmt, Some(5));
        }
        // 2c. 常规模式 miss → 路由到 arithmetic
        {
            let cache = CacheManager::new();
            let ctx = EvalContext::new();
            let (r, domain, hit, fmt) = evaluate("2+3", &ctx, None, &cache).unwrap();
            assert_eq!(r, EvalResult::Scalar(5.0));
            assert_eq!(domain, "arithmetic");
            assert!(!hit);
            assert_eq!(fmt, None);
        }
        // 2d. 常规模式 hit → 返回缓存
        {
            let cache = CacheManager::new();
            let ctx = EvalContext::new();
            let _ = evaluate("2+3", &ctx, None, &cache).unwrap();
            let (r, domain, hit, fmt) = evaluate("2+3", &ctx, None, &cache).unwrap();
            assert_eq!(r, EvalResult::Scalar(5.0));
            assert_eq!(domain, "arithmetic");
            assert!(hit);
            assert_eq!(fmt, None);
        }
        // 2e. 多域路由:number_theory
        {
            let cache = CacheManager::new();
            let ctx = EvalContext::new();
            let (r, domain, _, _) = evaluate("gcd(12,18)", &ctx, None, &cache).unwrap();
            assert_eq!(r, EvalResult::Scalar(6.0));
            assert_eq!(domain, "number_theory");
        }
        // 2f. 多域路由:combinatorics
        {
            let cache = CacheManager::new();
            let ctx = EvalContext::new();
            let (r, domain, _, _) = evaluate("C(10,3)", &ctx, None, &cache).unwrap();
            assert_eq!(r, EvalResult::Scalar(120.0));
            assert_eq!(domain, "combinatorics");
        }

        // ----- 阶段 3: 输出格式化 -----
        // 3a. precision(N, expr) → fmt_prec = Some(N)
        {
            let cache = CacheManager::new();
            let ctx = EvalContext::new();
            let (r, domain, _, fmt) = evaluate("precision(5, 1/3)", &ctx, None, &cache).unwrap();
            let _ = r;
            let _ = domain;
            assert_eq!(fmt, Some(5));
        }
        // 3b. 常规表达式 → fmt_prec = None
        {
            let cache = CacheManager::new();
            let ctx = EvalContext::new();
            let (_, _, _, fmt) = evaluate("sin(0)", &ctx, None, &cache).unwrap();
            assert_eq!(fmt, None);
        }
        // 3c. 缓存写入验证:miss 后第二次应 hit
        {
            let cache = CacheManager::new();
            let ctx = EvalContext::new();
            let (_, _, hit1, _) = evaluate("6*7", &ctx, None, &cache).unwrap();
            assert!(!hit1);
            let (_, _, hit2, _) = evaluate("6*7", &ctx, None, &cache).unwrap();
            assert!(hit2);
        }
    }

    // ===== 回归测试:cache 键必须包含 vars 与 timeout =====
    #[test]
    fn test_cache_key_includes_vars_different_values_do_not_collide() {
        let cache = CacheManager::new();
        let ctx1 = EvalContext::new().with_var("x", 1.0);
        let ctx2 = EvalContext::new().with_var("x", 2.0);

        // 第一次:x=1 → 计算 1.0,未命中
        let (r1, _, hit1, _) = evaluate("x", &ctx1, None, &cache).unwrap();
        assert_eq!(r1, EvalResult::Scalar(1.0));
        assert!(!hit1, "first call must miss");

        // 第二次:x=2 → 必须重新计算 2.0,不应误命中 x=1 的缓存
        let (r2, _, hit2, _) = evaluate("x", &ctx2, None, &cache).unwrap();
        assert_eq!(
            r2,
            EvalResult::Scalar(2.0),
            "different vars must not return cached value from other vars"
        );
        assert!(!hit2, "different vars must not hit cache");
    }

    // 测试 2:相同表达式、相同 vars、不同 timeout 必须产生不同 cache 键。
    #[test]
    fn test_cache_key_includes_timeout_different_values_do_not_collide() {
        let cf = CanonicalForm::new("(+ 2 3)");
        let ctx1 = EvalContext::new();
        let mut ctx2 = EvalContext::new();
        ctx2.timeout = Duration::from_secs(10);

        let key1 = build_cache_key(&cf, &ctx1, None);
        let key2 = build_cache_key(&cf, &ctx2, None);
        assert_ne!(
            key1, key2,
            "different timeout must produce different cache key"
        );
    }

    // 测试 3:相同表达式、不同 vars 必须产生不同 cache 键(直接测试 build_cache_key)。
    #[test]
    fn test_build_cache_key_includes_vars() {
        let cf = CanonicalForm::new("(+ 2 3)");
        let ctx_empty = EvalContext::new();
        let ctx_x1 = EvalContext::new().with_var("x", 1.0);
        let ctx_x2 = EvalContext::new().with_var("x", 2.0);
        let ctx_y = EvalContext::new().with_var("y", 1.0);

        let key_empty = build_cache_key(&cf, &ctx_empty, None);
        let key_x1 = build_cache_key(&cf, &ctx_x1, None);
        let key_x2 = build_cache_key(&cf, &ctx_x2, None);
        let key_y = build_cache_key(&cf, &ctx_y, None);

        // 任意两个不同 vars 状态必须产生不同 cache 键
        assert_ne!(key_empty, key_x1, "empty vars vs vars=x:1 must differ");
        assert_ne!(key_x1, key_x2, "vars x:1 vs x:2 must differ");
        assert_ne!(key_x1, key_y, "vars x:1 vs y:1 must differ");

        // 相同 ctx 应产生相同 cache 键(确定性)
        let key_x1_again = build_cache_key(&cf, &ctx_x1, None);
        assert_eq!(key_x1, key_x1_again, "same ctx must produce same key");
    }

    // 测试 4:precision 模式前缀仍然生效(与 cache 键修复共存)。
    #[test]
    fn test_build_cache_key_precision_prefix_preserved() {
        let cf = CanonicalForm::new("(+ 2 3)");
        let ctx = EvalContext::new();
        let key_reg = build_cache_key(&cf, &ctx, None);
        let key_prec = build_cache_key(&cf, &ctx, Some(5));
        assert_ne!(
            key_reg, key_prec,
            "precision mode key must differ from regular mode"
        );
        assert!(
            key_prec.as_str().contains("precision:"),
            "precision mode key must contain precision: prefix, got {}",
            key_prec
        );
    }

    // ===== 回归测试:precision(N, 1/3) 必须返回 N 位精确的 1/3 =====
    // transform_function 对 precision 的 args[1] 跳过常量折叠,保留 BinaryOp 交由域内求值。
    #[cfg(any(feature = "cli", feature = "http", feature = "mcp"))]
    #[test]
    fn test_precision_function_preserves_exact_rational() {
        let cache = CacheManager::new();
        let ctx = EvalContext::new();
        let (result, domain, _, fmt_prec) =
            evaluate("precision(20, 1/3)", &ctx, None, &cache).unwrap();

        // 必须路由到 precision 域
        assert_eq!(domain, "precision");
        // 顶层 precision(20, expr) 提取 N=20 用于格式化
        assert_eq!(fmt_prec, Some(20));

        // 结果必须是 BigRational(1/3),不是 f64 近似的 BigRational
        let r = match result {
            EvalResult::BigRational(r) => r,
            other => panic!("expected BigRational(1/3), got {:?}", other),
        };
        let one = num_bigint::BigInt::from(1);
        let three = num_bigint::BigInt::from(3);
        let expected = num_rational::BigRational::new(one, three);
        assert_eq!(
            r, expected,
            "precision(20, 1/3) must be exact 1/3, got {}",
            r
        );

        // 格式化验证:20 位精确 1/3 应为 0.33333333333333333333
        let formatted = crate::domains::format_bigrational(&r, Some(20));
        assert_eq!(
            formatted, "0.33333333333333333333",
            "20-digit 1/3 must be exact, got {}",
            formatted
        );
    }

    // precision 函数嵌套调用时仍需保留精确分数语义:precision(10, 1/6) → BigRational(1/6)。
    #[cfg(any(feature = "cli", feature = "http", feature = "mcp"))]
    #[test]
    fn test_precision_function_preserves_exact_rational_other_fraction() {
        let cache = CacheManager::new();
        let ctx = EvalContext::new();
        let (result, _, _, fmt_prec) = evaluate("precision(10, 1/6)", &ctx, None, &cache).unwrap();
        assert_eq!(fmt_prec, Some(10));

        let r = result.as_bigrational().expect("expected BigRational");
        let one = num_bigint::BigInt::from(1);
        let six = num_bigint::BigInt::from(6);
        let expected = num_rational::BigRational::new(one, six);
        assert_eq!(
            *r, expected,
            "precision(10, 1/6) must be exact 1/6, got {}",
            r
        );

        let formatted = crate::domains::format_bigrational(r, Some(10));
        // 1/6 = 0.16666666666...,10 位小数四舍五入为 0.1666666667
        assert_eq!(formatted, "0.1666666667", "got {}", formatted);
    }
}