当数据量过亿时,如何按 Git 分支分区并采样?

解读

面试官把“过亿行数据”与“Git 分支”两个看似不相关的维度放在一起,考察的是:

  1. 能否把“代码版本”这一业务语义映射到“数据分区”这一工程语义;
  2. 在超大数据量下,如何兼顾“可测性”“可重现性”“CI 耗时”与“存储成本”;
  3. 能否用 Pytest 的插件体系把“分支-分区-采样”做成一条自动化流水线,而不是手动脚本。

国内大厂(阿里、腾讯、字节、美团)的数仓/算法团队普遍用 Hive/Spark + OSS 做离线存储,用 Git-Flow 管理代码。测试环境既要跑全量回归,又要在 MR/PR 阶段做“分钟级”冒烟。因此“按分支分区”不是噱头,而是每天几百次 MR 的刚需。

知识点

  1. Git 分支 → 数据分区键

    • 分支名规范化:feature/12345_xxx → 12345
    • 非法字符替换:/ _ 转义成 _
    • 长度截断:Hive 分区键≤128 字符
    • 优先级:环境变量 > git rev-parse --abbrev-ref HEAD > fallback=develop
  2. 采样策略

    • 分层采样:按 dt+user_id 分层,保证每个业务线、新老用户比例一致
    • 采样率动态化:develop 分支 1%,release 分支 10%,master 全量
    • 可重现:用 branch_name+commit_sha 作为随机种子,pytest-randomly 插件自动识别
  3. Pytest 技术栈

    • pytest-hadoop:通过 HiveServer2 拉元数据,自动生成分区路径
    • pytest-spark:本地 SparkSession 读采样表,缓存到内存
    • pytest-xdist:多进程并行,每个 worker 只读自己那 1/N 分区
    • pytest-cov + coverage.py:只统计被测代码,不统计数据
    • pytest-timeout:单 case ≤5 min,防止长尾数据拖垮 CI
  4. 存储与成本

    • OSS 按分支建“生命周期 7 天”的 TTL 目录,过期自动删
    • Iceberg/Hudi 的 branch-snapshot 机制,避免物理复制,只存增量
    • 采样结果写回 ClickHouse 的“测试库”,单副本、TTL 3 天
  5. 合规

    • 国内《个人信息保护法》要求:采样必须脱敏,user_id 哈希化,手机号打码
    • 审计日志:每次采样把“分支+commit+采样 SQL+采样行数”写进 Mongo,方便追溯

答案

下面给出一套可直接落地的 Pytest 方案,代码量控制在 150 行以内,方便面试时手撕。

  1. 目录结构 tests/ ├── conftest.py # 全局 fixture ├── dataprep/ │ ├── init.py │ ├── branch_sampler.py # 采样逻辑 │ └── test_query.py # 业务 case pytest.ini # 插件配置

  2. conftest.py

import os, subprocess, pytest
from dataprep.branch_sampler import BranchSampler

def pytest_configure(config):
    # 1. 自动识别分支
    branch = os.getenv("GIT_BRANCH") or \
             subprocess.check_output(
                 ["git","rev-parse","--abbrev-ref","HEAD"],
                 text=True).strip()
    branch = branch.replace("/","_")[:128]
    config.branch = branch

    # 2. 根据分支决定采样率
    if branch == "master":
        sample_rate = 1.0
    elif branch.startswith("release"):
        sample_rate = 0.1
    else:
        sample_rate = 0.01
    config.sample_rate = sample_rate

@pytest.fixture(scope="session")
def sampler(pytestconfig):
    return BranchSampler(
        branch=pytestconfig.branch,
        rate=pytestconfig.sample_rate,
        seed=pytestconfig.branch + subprocess.check_output(
            ["git","rev-parse","HEAD"],text=True).strip()[:8]
    )
  1. branch_sampler.py
from pyspark.sql import SparkSession
import hashlib, os

class BranchSampler:
    def __init__(self, branch: str, rate: float, seed: str):
        self.branch = branch
        self.rate = rate
        self.seed = int(hashlib.md5(seed.encode()).hexdigest()[:8], 16)

    def load(self, spark: SparkSession, table: str):
        # 1. 生成分区路径
        partition = f"ds={self.branch}"
        # 2. 采样 SQL
        sql = f"""
        SELECT * FROM {table} WHERE ds='{self.branch}'
        AND hash(abs(hash(user_id)) + {self.seed}) % 1000 < {int(self.rate*1000)}
        """
        return spark.sql(sql)
  1. test_query.py
import pytest
from pyspark.sql import SparkSession

@pytest.fixture(scope="module")
def spark():
    spark = (SparkSession.builder
             .appName("pytest-branch")
             .config("spark.sql.adaptive.enabled","true")
             .getOrCreate())
    yield spark
    spark.stop()

def test_user_retention(spark, sampler):
    df = sampler.load(spark, "user_active")
    assert df.count() > 0
    # 业务断言:次日留存率>30%
    next_day = df.filter("retention_1d=1").count()
    total = df.count()
    assert next_day / total > 0.3
  1. pytest.ini
[pytest]
addopts = -n auto --dist=loadscope --cov=src --cov-report=term-missing
  1. CI 集成(GitLab-CI 示例)
pytest:
  stage: test
  image: registry.cn-hangzhou.aliyuncs.com/mypy/spark3.3-py39:latest
  script:
    - pip install -r requirements.txt
    - export GIT_BRANCH=$CI_COMMIT_REF_NAME
    - pytest -m "not slow"
  only:
    - merge_requests
  tags:
    - k8s-spark

落地效果:

  • feature 分支 MR 触发后,采样 1%(约 100 万行),Spark 本地 3 分钟跑完;
  • release 分支采样 10%,耗时 15 分钟;
  • master 分支全量,夜间定时跑,耗时 2 小时;
  • OSS 存储成本下降 85%,无敏感数据泄露风险;
  • 测试失败时可一键重跑,随机种子固定,问题可重现。

拓展思考

  1. 如果分支名冲突(如 feature/12345 和 hotfix/12345)怎么办? 答:在分区键前加前缀,feature_12345、hotfix_12345,同时把“前缀+分支”写进 Iceberg 的 tag,查询时自动路由。

  2. 采样后数据倾斜,导致 Pytest-xdist 某个 worker 超时? 答:在采样 SQL 里加二次哈希,把 user_id 打散到 100 个桶,再按桶号做 round-robin 分发,保证每个 worker 数据量差异<5%。

  3. 需要支持“多库联合采样”怎么办? 答:用 pytest 的“参数化 fixture”,把 sampler 做成列表,每个元素对应一个库,pytest-xdist 的 --dist=loadgroup 可以让不同 worker 跑不同库,实现并行。

  4. 法规要求“采样数据不能出境”,但公司用 GitHub Enterprise Cloud? 答:在 GitHub Actions 里把“采样”步骤放到国内阿里云 Runner,只把“测试结果(JSON)”回传 GitHub,原始数据永不出境,满足数据跨境审计要求。

  5. 未来想换成 DuckDB 本地跑? 答:把 BranchSampler 抽象成接口,底层再实现 DuckDBSampler,pytest 通过 --sampler=duckdb 切换,0 行业务 case 需要改动,符合开闭原则。