Files
knowledge-governance/internal/releaseadapter/v071/library_index_known_recovery_test.go
T
姚章浩 066dc45a25
build / build (push) Successful in 1m34s
fix(release): 删除型索引恢复不再用 ES 统计计数放行
- ES `_stats` 写计数是分片生命周期统计(官方文档:分片迁到另一节点时该分片统计清零),
  索引 uuid 不变不绑定统计生命周期,清零后重新累计到同一数值(ABA)无法排除。
  撤销 r36 的"写计数器栅栏"授权:既不落盘也不读取,统计仅作诊断。
- 删除型恢复(独占 `_create`)只有在本次尝试开始时不存在任何恢复意图、且文档确实缺失时
  才可重做;既存 restore-mark-intent 配缺失文档一律 held、零写入。
- 保留可证明路径:marker 仍在且世代一致的 clean 收尾重试;文档仍是 applied 结果、
  世代一致的 DELETE 补偿重试。
- 新增 ABA 反例(传输层 stats 故障模拟、真实 ES 文档写删、未重启共享 ES);
  B19 / clean / delete 安全正例全回归。

验证(真实 PG/ES/MinIO 隔离夹具):
- ABA 反例:旧代码 RED(restoration must be held, not rebuilt),新代码 PASS
- 索引/恢复回归 13 项 PASS
- 回滚回归 2 项 PASS
- make verify 16 项 success(identity 仅 CI 可核)
未部署、未写生产/云、未重启共享 ES。
2026-11-02 01:19:00 +08:00

184 lines
7.7 KiB
Go

package v071
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"io"
"net/http"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"knowledge-governance/internal/libraryrelease"
)
// restoreMarkerWire 只旁路计数:真正派发到真实 ES 的"恢复标记写入"次数。
//
// 为什么要有它:本用例要证明第一次失败发生在**派发之前**(控制流在边界上拒绝),
// 不是断线、也不是响应丢失。只靠错误文本分不出这两者,次数能分:边界拒绝 = 0 次派发,
// 断线 = 1 次派发且结果未知。它不改写请求与响应,ES 仍是唯一权威。
type restoreMarkerWire struct {
inner http.RoundTripper
dispatch int
}
func (w *restoreMarkerWire) RoundTrip(r *http.Request) (*http.Response, error) {
if r.Body != nil {
raw, err := io.ReadAll(r.Body)
if err != nil {
return nil, err
}
r.Body = io.NopCloser(bytes.NewReader(raw))
if r.Method == http.MethodPut && bytes.Contains(raw, []byte(indexRestoreClaimPrefix)) {
w.dispatch++
}
}
return w.inner.RoundTrip(r)
}
func indexChangeOf(t *testing.T, plan *libraryrelease.WriteSet, id string) libraryrelease.IndexWrite {
t.Helper()
if plan == nil {
t.Fatal("write set missing: recovery would have no bound plan")
}
for _, change := range plan.Index {
if change.ID == id {
return change
}
}
t.Fatalf("index plan lacks %s", id)
return libraryrelease.IndexWrite{}
}
// indexEffectFile 与生产代码的落盘路径同构(sha256(index\x00id)),用于直接读证据文件。
func indexEffectFile(fx *writeSetFixture, plan *libraryrelease.WriteSet, change libraryrelease.IndexWrite, phase string) string {
sum := sha256.Sum256([]byte(change.Index + "\x00" + change.ID))
return filepath.Join(fx.archiveRoot, "effects", plan.Digest, "index", hex.EncodeToString(sum[:]), phase+".json")
}
func requireIndexEffect(t *testing.T, fx *writeSetFixture, plan *libraryrelease.WriteSet, change libraryrelease.IndexWrite, phase string, want bool) string {
t.Helper()
path := indexEffectFile(fx, plan, change, phase)
info, err := os.Stat(path)
if want && err != nil {
t.Fatalf("index effect %s/%s not durable: %v", change.ID, phase, err)
}
if !want && err == nil {
t.Fatalf("index effect %s/%s exists unexpectedly: %s", change.ID, phase, info.Name())
}
return path
}
// r37:删除型恢复(Before 非空、After 为空,恢复写入是独占 `_create`)在持久意图
// 落盘之后、派发之前"确定失败"。撤掉故障后**不能**自动重做:文档缺失与"从未写过"
// 在索引里完全同形,服务端没有可持久、不可重用的"没写进去"证据。测试侧的派发次数
// 是内存观测,不是可复核的持久证据;ES `_stats` 写计数器是分片生命周期统计(分片
// 迁移/节点替换会清零,见官方 `_stats` 文档),索引 uuid 不变不绑定统计生命周期,
// 清零后重新累计到同一数值(ABA)无法排除。因此本状态必须 held(B19 不放宽)。
//
// 故障边界(target.restoreMarkerFault):在恢复标记的持久意图落盘之后、网络派发之前
// 返回错误——真实 ES 一个字节都没收到(用例用派发次数 0 证明),但"证明"只存在于
// 测试进程里,不能变成生产可用的授权。
func TestContractRestoreMarkerAfterBoundaryFaultIsHeldIsolated(t *testing.T) {
fx := openWriteSetFixture(t)
seedTargetData(t, fx)
snapshot := sealSourceSnapshot(t, fx, nil)
target := fx.target(t)
backups := fx.backups(t, target)
client := *target.search.client
inner := client.Transport
if inner == nil {
inner = http.DefaultTransport
}
wire := &restoreMarkerWire{inner: inner}
client.Transport = wire
target.search.client = &client
var faulted []string
target.restoreMarkerFault = func(c libraryrelease.IndexWrite) error {
if c.ID != "chunk-target" {
return nil
}
faulted = append(faulted, c.ID)
return errors.New("injected restore boundary fault: dispatch refused before any index write")
}
outcome := libraryrelease.Run(fx.ctx, requestFor(snapshot), contractFailWikiTarget{target}, backups, nil)
if outcome.State != "rollback_failed" {
t.Fatalf("state = %q (rollback=%q error=%q), want rollback_failed: a failed index restoration must be held, never admitted",
outcome.State, outcome.Rollback, outcome.Error)
}
if outcome.FailedAt != libraryrelease.StageWiki {
t.Fatalf("failed_at = %q, want wiki (the injected apply failure)", outcome.FailedAt)
}
if !strings.Contains(outcome.Rollback, "injected restore boundary fault") {
t.Fatalf("rollback failure does not name the injected index boundary fault: %q", outcome.Rollback)
}
if len(faulted) != 1 || faulted[0] != "chunk-target" {
t.Fatalf("fault fired %v, want exactly one chunk-target restore attempt", faulted)
}
if wire.dispatch != 0 {
t.Fatalf("boundary fault dispatched %d restore marker writes; a control-flow refusal must send nothing", wire.dispatch)
}
// 应用期的真实逐 ID 回执必须已在故障之前落盘:恢复读的是证据,不是目标现状。
plan := outcome.Backup.WriteSet
if plan == nil || plan.JobID != requestFor(snapshot).JobID {
t.Fatalf("backup is not bound to the original job: %+v", plan)
}
applied, err := filepath.Glob(filepath.Join(fx.archiveRoot, "effects", plan.Digest, "index", "*", "applied.json"))
if err != nil || len(applied) != 2 {
t.Fatalf("applied index receipts = %d (%v), want 2 durable per-ID receipts", len(applied), err)
}
change := indexChangeOf(t, plan, "chunk-target")
if len(change.Before) == 0 {
t.Fatal("fixture lost the chunk-target before-image")
}
requireIndexEffect(t, fx, plan, change, "apply-intent", true)
requireIndexEffect(t, fx, plan, change, "applied", true)
// 恢复意图已落盘,但恢复标记在测试进程里从未派发。这条"没派发"只存在于
// 内存计数里,不是生产可复核的持久证据。
requireIndexEffect(t, fx, plan, change, "restore-mark-intent", true)
requireIndexEffect(t, fx, plan, change, "restore-claimed", false)
requireIndexEffect(t, fx, plan, change, "restored", false)
// held 期间业务存储不许被"顺手恢复一半再报成功":索引仍是应用后的样子。
heldIndex := recoveryIndexReadback(t, fx)
heldPG := universeDump(t, fx.pool)
heldObjects := objectVersionSet(t, fx)
if _, ok := heldIndex["chunk-src"]; ok {
t.Fatal("index still carries the applied chunk-src after a failed index restoration")
}
if _, ok := heldIndex["chunk-target"]; ok {
t.Fatal("chunk-target came back without the restoration marker ever being dispatched")
}
// 撤掉故障。删除型恢复写入是独占 `_create`,文档缺失与"从未写过"同形;服务端
// 没有可持久、不可重用的未发送证据(ES 统计随分片迁移清零,不能当证据),
// 所以必须 held,不能凭测试侧"派发 0 次"放行写入。
target.restoreMarkerFault = nil
beforeDispatch := wire.dispatch
if err := target.Restore(fx.ctx, outcome.Backup); err == nil {
t.Fatal("delete-type restoration without a durable not-dispatched proof must stay held")
} else if !strings.Contains(err.Error(), "held") {
t.Fatalf("held error must say held, got: %v", err)
}
if wire.dispatch != beforeDispatch {
t.Fatalf("held restoration dispatched %d restore marker writes", wire.dispatch-beforeDispatch)
}
if diff := diffUniverse(heldPG, universeDump(t, fx.pool)); diff != "" {
t.Fatalf("held restoration changed PG: %s", diff)
}
if after := recoveryIndexReadback(t, fx); !reflect.DeepEqual(heldIndex, after) {
t.Fatal("held restoration changed the index")
}
if after := objectVersionSet(t, fx); !reflect.DeepEqual(heldObjects, after) {
t.Fatalf("held restoration changed object versions:\n before=%v\n after=%v", heldObjects, after)
}
}