fix(library): 预备份硬门禁 + 崩溃接管 + 五项入口验收
build / build (push) Failing after 17s

为什么:父审指出预备份引用持久化失败仍继续写目标、接管依赖启动扫描且漏掉租约未过期、
恢复失败被标成"无需恢复"、版本登记与作业状态分叉。

- BackupPrepared 返回 error,持久化失败即零写入;预备份同时登记 production_prebackup 版本。
- 接管改为按队列租约判定 + 运行期 30s 扫描 + 原子抢占 + 固定幂等键 + attempt 归零。
- 接管场景保留预备份、不再宣称"未写无需恢复"。
- 恢复/重放同一快照重新激活 production_effective(清 superseded_at)。
- finalize 续作只做校验+登记(finalize_only),不重写生产。
- 索引映射基线缺失时采用首次观察值并登记;索引校验加孤儿文档检查(按 knowledge_id)。

真实验收(候选 API :18089 + 真实 PG/ES/MinIO):
A0 首次发布、A1 撤销、B 按版本恢复、C 写阶段 SIGKILL 接管、
D 跨 kind 互斥与多 worker 单次执行、E1 登记失败、E2 finalize 续作、E3 预备份失败零写入。
This commit is contained in:
姚章浩
2026-10-28 19:11:37 +08:00
parent ca51cbe202
commit c72b71d78a
12 changed files with 529 additions and 118 deletions
@@ -128,6 +128,43 @@ func archivedTableContent(archive *librarysnapshot.Archive, part librarysnapshot
return int64(len(digests)), combineRowDigests(digests), columns, nil
}
// orphanIndexDocuments 找出"索引里有、生产分块里没有"的文档(按 chunk_id 关联)。
func (t *ProductionLibraryTarget) orphanIndexDocuments(ctx context.Context, documents []SearchDocument) []string {
if len(documents) == 0 {
return nil
}
// 按文档归属判断而不是按 chunk_id:真实 WeKnora 是父子分块,
// 索引里的子块 ID 本来就不在 chunks 表里,按 chunk_id 判会误报孤儿。
rows, err := t.pool.Query(ctx, `SELECT id FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2 AND deleted_at IS NULL`,
t.scope.TenantID, t.scope.KnowledgeBaseID)
if err != nil {
return nil
}
defer rows.Close()
known := map[string]bool{}
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
return nil
}
known[id] = true
}
orphans := make([]string, 0, 4)
for _, document := range documents {
var source struct {
ChunkID string `json:"chunk_id"`
KnowledgeID string `json:"knowledge_id"`
}
if json.Unmarshal(document.Source, &source) != nil || source.KnowledgeID == "" {
continue
}
if !known[source.KnowledgeID] {
orphans = append(orphans, document.ID)
}
}
return orphans
}
// firstIndexDifference 返回第一处不一致的文档 ID 与字段,便于定位。
func firstIndexDifference(archived, live []SearchDocument) string {
liveByID := make(map[string]json.RawMessage, len(live))
@@ -212,6 +249,11 @@ func (t *ProductionLibraryTarget) verifyIndexDigest(ctx context.Context, archive
if err != nil {
return fmt.Errorf("读取生产索引失败: %w", err)
}
// 孤儿向量:索引里有、数据库分块里没有的文档必须报出来。
// 只比"归档 vs 生产"会漏掉两边一致但都错的情况。
if orphans := t.orphanIndexDocuments(ctx, snapshot.Documents); len(orphans) > 0 {
return fmt.Errorf("生产索引存在 %d 条孤儿文档(所属文档已不在数据库),首个 %s", len(orphans), orphans[0])
}
if len(snapshot.Documents) != len(archived) || snapshot.DocumentsSHA256 != wantDigest {
// 摘要不一致时给出第一处差异文档,运维才能定位是"少了/多了/被改了"。
return fmt.Errorf("生产索引与快照不一致:文档 %d/%d,首个差异 %s",