如何利用 `inspection-testing` 验证融合成功?

解读

在国内 Haskell 岗位面试中,性能与正确性同等重要。inspection-testing 是 GHC 8.0+ 提供的编译期断言库,能把“两个表达式是否被编译成同一 Core”变成可执行的测试用例,从而用类型系统级别的证据证明融合(fusion)真正发生,而不是靠肉眼读 -ddump-simpl 的“玄学”。面试官想确认:

  1. 你熟悉 GHC 的重写规则(rewrite rules)与列表/向量融合机制;
  2. 你能把“性能优化”转化为可回归的测试,避免“优化一次,后续改代码又回退”;
  3. 你理解惰性求值+规则触发条件,能解释为什么有时规则不生效。

知识点

  • 重写规则({-# RULES #-}):GHC 在简化期用模式匹配把高阶函数管道替换成高效循环。
  • Core 语言:GHC 的中间语言,所有语法糖被脱糖后的形态;inspection-testing 比较的是 Core。
  • Inspection testing 三步曲:
    1. 在测试模块导入 Test.Inspection;
    2. 用 inspect $ 'lhs === 'rhs 生成断言;
    3. 在 cabal test 或 stack test 里跑,编译失败即证明未融合,成功则静默通过。
  • 触发条件:规则必须满足参数可见性(arity)、类型实例一致、构造函数可见(INLINE/CONLIKE),否则 GHC 会“礼貌地”跳过。
  • 国内工程实践:金融高频簿记、区块链 UTXO 扫描等场景,用 inspection-testing 把“零拷贝融合”写进 CI,防止后续维护者意外引入中间列表。

答案

  1. 在 .cabal 里加测试套件
    test-suite inspection
    type: exitcode-stdio-1.0
    hs-source-dirs: test
    main-is: Spec.hs
    build-depends: base, mylib, inspection-testing >= 0.5

  2. 在业务库中暴露被测规则

    module Stream where
    import qualified Data.Vector.Fusion.Stream.Monadic as S
    
    sumS :: S.Stream Int -> Int
    sumS = S.foldl' (+) 0
    
    {-# RULES
    "sumS/filterS"  forall f s. sumS (S.filter f s) = sumSFilter f s
      #-}
    sumSFilter f = S.foldl' (+) 0 . S.filter f
    
  3. 在 test/Spec.hs 写断言

    {-# LANGUAGE TemplateHaskell #-}
    module Main where
    import Test.Inspection
    import Stream
    
    lhs, rhs :: S.Stream Int -> Int
    lhs s  = sumS (S.filter even s)
    rhs s  = sumSFilter even s
    
    inspect $ 'lhs === 'rhs
    
    main :: IO ()
    main = putStrLn "Inspection passed!"
    
  4. 运行
    stack test --test-arguments="+RTS -A32m"
    若融合失败,GHC 会在编译期报错并打印两条不同的 Core,CI 直接红灯;成功则测试通过,零运行时开销。

  5. 面试加分句
    “我把 inspection-testing 做成黄金 Master 测试,只要后续有人调整 filter 实现导致规则失效,CI 立刻失败,用类型系统守护性能回归。”

拓展思考

  • 多阶段融合:对 vector + streaming + fusion-plugin 的三阶段管道,可以写多个 === 断言,验证阶段间是否全部熔合;若中间出现 stream/unstream 对,则 Core 会多出一层 Vector 构造,可被 inspection-testing 捕获。
  • 跨模块边界:国内大型代码库常把 RULES 写在 .hs-boot 或 INLINEABLE 模板中,需确保跨模块的 unfolding 可见,否则 inspection-testing 会误报失败;此时可用 -fexpose-all-unfoldings 做 CI 专用标志。
  • 与 Liquid Haskell 结合:先用 Liquid Haskell 证明融合前后语义等价(如 sumS (filter f s) ≡ sumSFilter f s),再用 inspection-testing 证明性能等价(同一 Core),形成**“语义+性能”双保险**,在高频交易撮合引擎中落地。