failpoint 与 go test 如何集成?
解读
在国内 TiDB 技术面试中,failpoint 是必考点。PingCAP 自研的 failpoint 本质是一种“编译期可注入、运行时可触发”的故障模拟框架,与 go test 集成后,可以让单测在本地或 CI 里低成本地覆盖“网络抖动、磁盘 hang、leader 掉线、TiKV 重启”等分布式故障路径。面试官问“如何集成”,核心想确认三件事:
- 你是否知道 failpoint 代码只能在开启 failpoint build tag 的测试二进制里生效;
- 你是否能把“写 failpoint → 编译 → 运行 → 关闭”做成一条可回滚的自动化链路;
- 你是否理解 failpoint 对性能、并发安全、CI 缓存的影响,并给出工程化方案。
回答时切忌只贴命令,要把“Makefile 封装、并发安全、CI 缓存、性能回退”讲透,才能体现资深水平。
知识点
- failpoint 语法:
failpoint.Inject("fpName", func(val failpoint.Value) { … })
编译期被改写为if val, ok := failpoint.Eval("fpName"); ok { … },无注入时开销接近零。 - build tag:
代码文件顶部//go:build failpoint或// +build failpoint,只有带该 tag 的测试二进制才会把 failpoint 编译进去。 - 启用/禁用:
- 启用:
go test -tags=failpoint ./… - 禁用:默认无 tag,二进制干净,零性能回退。
- 启用:
- 运行时激活:
通过环境变量GO_FAILPOINTS='pkg/path=fpName->return(1)'或http://:2379/failpoints接口动态注入。 - 并发安全:
同一进程内多个测试并发跑时,failpoint 状态是全局 map,需用t.Parallel()谨慎隔离,或借助TestMain做串行化。 - 工程化:
Makefile 里统一封装make failpoint-test目标,自动:- 生成
_failpoint.go文件(failpoint-ctl enable) - 跑测试
- 生成覆盖率
- 回滚
_failpoint.go(failpoint-ctl disable)
保证开发者无感、CI 缓存 key 不变、不会误提交污染代码。
- 生成
- 性能基线:
线上二进制禁止带 failpoint tag,CI 里单独跑failpoint-testjob,与常规单测并行,防止回归。
答案
step 1 在需要注入故障的包内写 failpoint
// store/tikv/region_cache.go
import "github.com/pingcap/failpoint"
func (c *RegionCache) dropRegionOnSendFail(bo *Backoffer, region *Region) error {
failpoint.Inject("tikvRegionCacheDrop", func(val failpoint.Value) {
if val.(bool) {
bo.ctx = context.WithValue(bo.ctx, "drop", true)
}
})
...
}
step 2 给测试文件加 build tag
// store/tikv/region_cache_failpoint_test.go
//go:build failpoint
// +build failpoint
package tikv
import "testing"
func TestRegionCacheDrop(t *testing.T) {
// 激活 failpoint
require.NoError(t, failpoint.Enable("tikvRegionCacheDrop", "return(true)"))
defer failpoint.Disable("tikvRegionCacheDrop")
// 构造请求,断言 region 被 drop 后重试次数增加
...
}
step 3 Makefile 统一封装
.PHONY: failpoint-test
failpoint-test:
@failpoint-ctl enable # 生成 *_failpoint.go
go test -tags=failpoint -race -coverprofile=coverage-failpoint.out ./...
@failpoint-ctl disable # 回滚
step 4 CI 并行跑
# .github/workflows/ci.yml
- name: unit-test
run: make test
- name: failpoint-test
run: make failpoint-test
step 5 性能兜底
线上构建命令始终不带 failpoint tag,确保二进制零开销;CI 里 failpoint-test 失败即阻断合并。
拓展思考
- 多版本并发测试:
在 CI matrix 里同时跑failpoint=on + go1.18与failpoint=on + go1.21,提前发现 runtime 变更导致的死锁。 - 混沌与单测联动:
把 failpoint 触发事件通过 etcd 推送给 Chaos-Mesh,实现“单测里触发 region drop → Chaos-Mesh 立即杀 TiKV pod”,验证端到端自愈时间。 - 静态分析兜底:
写 linter 扫描*_failpoint.go是否被误提交,若发现则 PR 直接 -2,防止线上二进制被污染。 - 性能回归门禁:
在failpoint-testjob 里同步跑 sysbench 短压测,若 QPS 下降 >3%,自动 comment “failpoint 引入性能回退”,倒逼开发者优化注入粒度。