如何验证混合结果一致性?

解读

“混合结果”在国内项目里通常指同一业务链路里同时存在“新/旧实现”“Python/Java 服务”“本地/远程接口”“CPU/GPU 版本”等多套输出,需要保证它们在逻辑上“等价”。面试官问的不是“断言相等”这么简单,而是考察你能否用 Pytest 体系把“一致性”做成可持续、可回归、可量化的质量门禁。核心痛点有三:

  1. 结果格式差异(浮点精度、字段顺序、嵌套结构、时间戳、随机种子)。
  2. 数据量级大(几十万条推理结果或千万级表数据),全量比对性能差。
  3. 需要嵌入现有 CI(GitLab-CI、Jenkins、阿里 Yunxiao),失败时要能一键定位差异。

因此,回答必须覆盖:采样策略、归一化清洗、差异模型、报告可视化、失败重试与 flaky 治理,并给出可直接落地的 Pytest 代码骨架。

知识点

  1. pytest-approx:内置的 approx 支持相对/绝对误差,避免浮点误杀。
  2. pytest-datadir / pytest-cache:把“黄金结果”序列化后随仓库或缓存管理,实现“快照比对”。
  3. fixture 的 params + ids:一套测试逻辑多“混合源”复用,自动生成矩阵报告。
  4. pytest-html / allure-pytest:差异结果高亮,支持附件 diff 图、csv,方便 QA 二次确认。
  5. pytest-xdist + pytest-order:并行跑多套实现,但保证全局顺序一致性,节省 CI 时间。
  6. 自定义 hook(pytest_assertrepr_compare、pytest_runtest_makereport):把差异写入 Redis,供 BI 大屏实时统计“一致性分数”。
  7. flaky 标记与重试:对非确定性算法(带随机采样、并发竞争)允许重跑 3 次,降低误报。
  8. 数据合规:若涉及用户敏感信息,需脱敏后再落盘,符合《个人信息保护法》要求。

答案

下面给出一套可直接落地的“混合结果一致性”测试方案,覆盖接口级、文件级、数据库级三种常见场景。假设我们要验证“新版推荐服务”与“旧版推荐服务”的 top50 商品列表在核心指标上一致。

  1. 目录结构
    project/tests/consistency/
    ├── conftest.py # 全局 fixture
    ├── test_recommend.py # 推荐接口一致性
    ├── test_model_output.py # 离线模型结果一致性
    └── assets/
    └── golden/ # 黄金结果,git-lfs 管理

  2. conftest.py 核心片段

import json, os, pytest, redis, hashlib
from pathlib import Path

# 用 redis 缓存差异,方便报表
r = redis.Redis(host='localhost', port=6379, decode_responses=True)

def pytest_configure(config):
    # 创建本次构建的唯一标识
    config.build_id = os.environ.get("CI_BUILD_ID", "local")

def pytest_assertrepr_compare(op, left, right):
    # 把失败差异写 redis,key=build_id+nodeid
    if op == "==" and isinstance(left, dict) and isinstance(right, dict):
        diff = {k: (left.get(k), right.get(k)) for k in left.keys() | right.keys()
                if left.get(k) != right.get(k)}
        r.hset(pytest.config.build_id, pytest.config.nodeid, json.dumps(diff, ensure_ascii=False))
    return None  # 使用默认断言输出

@pytest.fixture(scope="session", params=["new", "old"], ids=lambda x: f"api_{x}")
def api_client(request):
    """返回两套服务的封装 client"""
    from myapi import NewClient, OldClient
    return NewClient() if request.param == "new" else OldClient()

@pytest.fixture(scope="session")
def golden_path():
    return Path(__file__).with_name("assets") / "golden"
  1. 测试用例 test_recommend.py
import json, pytest
from deepdiff import DeepDiff

class TestRecommendConsistency:
    @pytest.mark.parametrize("uid", ["u123", "u456", "u789"])  # 可放 csv 采样
    def test_top50_consistency(self, uid, api_client, golden_path, request):
        # 1. 调用接口
        resp = api_client.recommend(uid=uid, size=50)
        # 2. 归一化:排序、截断浮点、去掉时间戳
        normalized = [{k: round(v, 6) if isinstance(v, float) else v
                       for k, v in item.items() if k != "ts"} 
                      for item in sorted(resp, key=lambda x: x["score"], reverse=True)]
        # 3. 快照比对
        golden_file = golden_path / f"{uid}.json"
        if golden_file.exists():  # 回归模式
            golden = json.loads(golden_file.read_text())
            # 4. 差异模型:允许 5% 商品不同,但分数 RMSE<0.01
            item_diff = DeepDiff(normalized, golden, ignore_order=True, report_repetition=True)
            if item_diff:
                # 解析差异
                missing = len(item_diff.get("iterable_item_removed", {}))
                added   = len(item_diff.get("iterable_item_added", {}))
                assert (missing + added) / len(golden) <= 0.05, f"商品差异超 5%: {item_diff}"
                # 分数 RMSE
                score_map = {g["id"]: g["score"] for g in golden}
                rmse = (sum((item["score"] - score_map[item["id"]])**2
                           for item in normalized if item["id"] in score_map) / len(score_map)) ** 0.5
                assert rmse < 0.01, f"RMSE 超阈值: {rmse}"
        else:  # 首次运行,生成基线
            golden_file.write_text(json.dumps(normalized, ensure_ascii=False, indent=2))
            pytest.skip("golden 文件不存在,已自动生成基线")
  1. 数据库级一致性(离线场景)
@pytest.mark.order(1)  # 先跑,生成结果表
def test_etl_pipeline():
    run_spark_job()  # 写 tmp_consistency.new 分区

@pytest.mark.order(2)
def test_db_consistency(golden_path):
    from sqlalchemy import create_engine
    engine = create_engine("mysql+pymysql://user:pwd@db:3306/olap")
    sql = """
      SELECT item_id, SUM(score) AS total
      FROM tmp_consistency.new
      GROUP BY item_id
      ORDER BY total DESC
      LIMIT 1000
    """
    df_new = pd.read_sql(sql, engine)
    df_old = pd.read_sql(sql.replace("new", "old"), engine)
    # 使用 pandas-testing
    pd.testing.assert_frame_equal(
        df_new.reset_index(drop=True),
        df_old.reset_index(drop=True),
        check_dtype=False,
        check_less_precise=2  # 精度 1e-2
    )
  1. CI 集成(GitLab-CI 片段)
consistency:
  stage: test
  image: python:3.11
  services:
    - redis:7
  script:
    - pip install -r requirements-test.txt
    - pytest tests/consistency -n auto --html=report.html --self-contained-html
    - python scripts/consistency_score.py  # 读取 redis 生成 0~100 分
  artifacts:
    when: always
    paths:
      - report.html
    expire_in: 7 days
  only:
    - merge_requests
    - schedules  # 每日定时全量
  1. 失败治理
  • 对随机算法使用 @pytest.mark.flaky(reruns=3, reruns_delay=2)
  • 对已知抖动字段(trace_id、request_id)在归一化阶段 pop 掉
  • 对超过阈值的差异,自动创建飞书告警卡片,附 html 报告链接,@代码 owner

拓展思考

  1. 大模型时代的一致性:如果“混合结果”一边是传统召回,一边是 LLM 生成,如何定义“等价”?可以引入 BLEU、ROUGE、BERTScore 等语义指标,把阈值做成可配置 fixture,支持离线回归。
  2. 流量回放与一致性结合:用 GoReplay 把线上流量录下来,在 pytest 里用 parametrize 回放,保证新旧系统输出一致,实现“无侵入”回归。
  3. 数据合规脱敏:对手机号、身份证做掩码,使用 faker 生成假数据,但保持分布一致,避免“脱敏后不一致”导致的误报。
  4. 性能一致性:不仅结果要对,P99 延迟差异也要 <5%,可在同一用例里用 pytest-benchmark 采样,把性能退化也挡在 MR 阶段。
  5. 多云混合:若“混合”跨越阿里云/华为云,需考虑跨云网络抖动,建议在 pytest 里用 tenacity 重试,并对超时异常单独标记,避免把网络问题误判为业务不一致。