为什么:父审指出预备份引用持久化失败仍继续写目标、接管依赖启动扫描且漏掉租约未过期、 恢复失败被标成"无需恢复"、版本登记与作业状态分叉。 - 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:
@@ -13,8 +13,11 @@ import (
|
||||
// 生产发布授权:管理员把"目标 + 快照 + 参数摘要 + 有效期"钉死。
|
||||
// 换快照、换目标或改参数都会得到不同摘要,旧授权自然失效;到期或被撤销也不能用。
|
||||
type libraryAuthorizationRequest struct {
|
||||
Scope string `json:"scope"`
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
Scope string `json:"scope"`
|
||||
SnapshotID string `json:"snapshot_id"`
|
||||
// Action 决定授权的动作:sync(默认)或 restore。两者摘要不同,
|
||||
// 同步授权不能当恢复授权用,反之亦然。
|
||||
Action string `json:"action"`
|
||||
ExpiresInMinutes int `json:"expires_in_minutes"`
|
||||
}
|
||||
|
||||
@@ -69,14 +72,28 @@ func libraryAuthorizationCreate(w http.ResponseWriter, r *http.Request, config C
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "expires_in_minutes must be between 5 and 1440"})
|
||||
return
|
||||
}
|
||||
digest, err := librarySyncParamsDigest(request.Scope, request.SnapshotID)
|
||||
action := strings.TrimSpace(request.Action)
|
||||
if action == "" {
|
||||
action = "sync"
|
||||
}
|
||||
var digest string
|
||||
var err error
|
||||
switch action {
|
||||
case "sync":
|
||||
digest, err = librarySyncParamsDigest(request.Scope, request.SnapshotID)
|
||||
case "restore":
|
||||
digest, err = libraryRestoreParamsDigest(request.Scope, request.SnapshotID)
|
||||
default:
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "action must be sync or restore"})
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot digest params"})
|
||||
return
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
item := governance.LibraryReleaseAuthorization{
|
||||
ID: "libauth-" + request.Scope + "-" + now.Format("20060102T150405.000000"),
|
||||
ID: "libauth-" + action + "-" + request.Scope + "-" + now.Format("20060102T150405.000000000"),
|
||||
Scope: request.Scope,
|
||||
SnapshotID: request.SnapshotID,
|
||||
ParamsDigest: digest,
|
||||
|
||||
@@ -597,7 +597,8 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
TargetSnapshotID: request.Target, Actor: actor,
|
||||
}, governance.SyncStages(), now)
|
||||
if errors.Is(err, governance.ErrLibraryJobActive) {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_sync_active", "error": "该目标已有在飞的同步作业"})
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_sync_active",
|
||||
"error": "该目标已有在飞的生产写作业(同步与恢复互斥)"})
|
||||
return
|
||||
}
|
||||
if errors.Is(err, governance.ErrLibraryJobIdempotencyConflict) {
|
||||
|
||||
@@ -228,8 +228,13 @@ func libraryJobResume(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "resumed_from": sourceID, "reused": true})
|
||||
return
|
||||
}
|
||||
payload, _ := json.Marshal(map[string]string{"library_job_id": job.ID, "scope": source.Scope,
|
||||
"target_snapshot_id": source.TargetSnapshotID})
|
||||
// 写入已完成、只差登记版本的情况:续作只做幂等收尾,不重写生产。
|
||||
body := map[string]any{"library_job_id": job.ID, "scope": source.Scope,
|
||||
"target_snapshot_id": source.TargetSnapshotID}
|
||||
if source.Stage == "finalize" && source.SnapshotID != "" {
|
||||
body["finalize_only"] = true
|
||||
}
|
||||
payload, _ := json.Marshal(body)
|
||||
queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
|
||||
ID: governance.QueueJobIDFor(job.ID), Type: queueType, Payload: payload, AvailableAt: now,
|
||||
MaxAttempts: 1, IdempotencyKey: "library.resume.queue:" + job.ID,
|
||||
|
||||
@@ -93,7 +93,9 @@ type Recorder interface {
|
||||
// BackupObserver 让调用方在预备份完成时立刻持久化快照身份:
|
||||
// worker 被杀后重启必须能接管这份预备份,而不是重新备份覆盖它。
|
||||
type BackupObserver interface {
|
||||
BackupPrepared(ctx context.Context, backup BackupRef)
|
||||
// 必须返回错误:预备份引用没能持久化时,worker 被杀就没有恢复基线,
|
||||
// 这种情况下一个字节都不许写目标。调用方据此直接失败。
|
||||
BackupPrepared(ctx context.Context, backup BackupRef) error
|
||||
}
|
||||
|
||||
// FinalizeStages 是"写入完成之后的收尾":先登记权威版本,再把作业标成功。
|
||||
@@ -117,6 +119,7 @@ type Outcome struct {
|
||||
FailedAt Stage `json:"failed_at,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Rollback string `json:"rollback,omitempty"`
|
||||
Recovery string `json:"recovery,omitempty"`
|
||||
Finished time.Time `json:"finished"`
|
||||
}
|
||||
|
||||
@@ -178,7 +181,14 @@ func Run(ctx context.Context, request Request, target Target, backups BackupStor
|
||||
}
|
||||
outcome.Backup = backup
|
||||
if observer, ok := recorder.(BackupObserver); ok {
|
||||
observer.BackupPrepared(ctx, backup)
|
||||
if err := observer.BackupPrepared(ctx, backup); err != nil {
|
||||
// 硬门禁:持久化失败 = 没有可恢复基线 = 绝不写目标。
|
||||
outcome.State = "failed"
|
||||
outcome.Error = "预备份已生成但引用无法持久化,未对生产执行任何写入:" + err.Error()
|
||||
outcome.Recovery = "预备份 " + backup.SnapshotID + " 已落盘,先修复治理库再重试"
|
||||
recorder.Stage(ctx, "prebackup", "failed", outcome.Error)
|
||||
return outcome
|
||||
}
|
||||
}
|
||||
recorder.Stage(ctx, "prebackup", "succeeded", "预备份 "+backup.ID)
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
package libraryrelease
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// failingObserver 模拟"预备份引用无法持久化":真实场景是治理库写入失败。
|
||||
type failingObserver struct{ stageLog }
|
||||
|
||||
func (f *failingObserver) BackupPrepared(context.Context, BackupRef) error {
|
||||
return errors.New("persist backup ref failed")
|
||||
}
|
||||
|
||||
// 预备份引用持久化失败时必须零写入:没有可恢复基线就不许碰目标。
|
||||
func TestRunRefusesToWriteWhenBackupReferenceCannotBePersisted(t *testing.T) {
|
||||
target := &fakeTarget{}
|
||||
backups := &fakeBackups{}
|
||||
recorder := &failingObserver{}
|
||||
outcome := Run(context.Background(), request(time.Now()), target, backups, recorder)
|
||||
if outcome.State == "succeeded" {
|
||||
t.Fatalf("state = %s, must not succeed without a recoverable backup", outcome.State)
|
||||
}
|
||||
if len(target.applied) != 0 {
|
||||
t.Fatalf("applied stages = %v, must be zero when the backup reference is lost", target.applied)
|
||||
}
|
||||
if target.restored != 0 {
|
||||
t.Fatalf("restore must not run when nothing was written (restored=%d)", target.restored)
|
||||
}
|
||||
if !recorder.has("prebackup:failed") {
|
||||
t.Fatalf("stage log = %v, want prebackup:failed", recorder.entries)
|
||||
}
|
||||
if outcome.Recovery == "" {
|
||||
t.Fatal("failed outcome must explain how to recover")
|
||||
}
|
||||
}
|
||||
@@ -239,7 +239,13 @@ WHERE scope=$1 AND kind='production_effective' AND superseded_at IS NULL`, versi
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO library_versions (id, scope, kind, snapshot_id, version_label, source_job_id, evidence, created_by, created_at)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)
|
||||
ON CONFLICT (id) DO NOTHING`,
|
||||
ON CONFLICT (id) DO UPDATE SET
|
||||
-- 恢复/重放同一个快照时必须把它重新"激活":否则它还是被 supersede 的旧行,
|
||||
-- 页面会显示"生产当前版本未知",而实际生产已经恢复到这个快照。
|
||||
superseded_at = NULL,
|
||||
source_job_id = EXCLUDED.source_job_id,
|
||||
evidence = EXCLUDED.evidence,
|
||||
created_at = EXCLUDED.created_at`,
|
||||
version.ID, version.Scope, string(version.Kind), version.SnapshotID, version.VersionLabel,
|
||||
version.SourceJobID, evidence, version.CreatedBy, version.CreatedAt.UTC()); err != nil {
|
||||
return fmt.Errorf("record library version: %w", err)
|
||||
@@ -250,10 +256,19 @@ ON CONFLICT (id) DO NOTHING`,
|
||||
// InterruptedLibraryJobs 找出"业务作业 running、但队列里已没有活跃作业"的作业:
|
||||
// worker 被杀/重启后它们需要被接管,而不是被当成失败丢掉已完成的预备份。
|
||||
func (s *Store) InterruptedLibraryJobs(ctx context.Context) ([]governance.LibraryJob, error) {
|
||||
// lease 过期才算中断:worker 刚被杀但 lease 未到期时,队列里还是 running,
|
||||
// 直接判"没中断"会让作业永远悬着;所以这里按 lease_until 判断。
|
||||
rows, err := s.db.Query(ctx, `
|
||||
SELECT id FROM library_jobs lj
|
||||
WHERE lj.state='running' AND lj.kind IN ('sync','restore')
|
||||
AND NOT EXISTS (SELECT 1 FROM jobs j WHERE j.id=lj.queue_job_id AND j.state IN ('pending','running','retry'))
|
||||
SELECT lj.id FROM library_jobs lj
|
||||
LEFT JOIN jobs j ON j.id=lj.queue_job_id
|
||||
WHERE lj.kind IN ('sync','restore')
|
||||
AND (
|
||||
-- 业务作业在跑、队列已经没了/停了/租约过期
|
||||
(lj.state='running' AND (j.id IS NULL OR j.state IN ('failed','completed','cancelled','dead')
|
||||
OR (j.state IN ('pending','running','retry') AND j.lease_until IS NOT NULL AND j.lease_until < now())))
|
||||
-- 业务作业已被前一轮接管置为 pending,但队列作业的租约也没了(worker 又死了)
|
||||
OR (lj.state='pending' AND j.state='running' AND j.lease_until IS NOT NULL AND j.lease_until < now())
|
||||
)
|
||||
ORDER BY lj.created_at`)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list interrupted library jobs: %w", err)
|
||||
@@ -281,6 +296,28 @@ ORDER BY lj.created_at`)
|
||||
return jobs, nil
|
||||
}
|
||||
|
||||
// ResetQueueJobForResume 把中断/失败过的队列作业重新排队:attempt 必须归零,
|
||||
// 否则 attempt<max_attempts 永远不成立,作业再也不会被任何 worker 领取。
|
||||
func (s *Store) ResetQueueJobForResume(ctx context.Context, queueJobID string, now time.Time) error {
|
||||
if _, err := s.db.Exec(ctx, `UPDATE jobs
|
||||
SET state='pending', attempt=0, lease_owner=NULL, lease_until=NULL, available_at=$2, updated_at=$2
|
||||
WHERE id=$1 AND state IN ('running','retry','failed','pending')`, queueJobID, now); err != nil {
|
||||
return fmt.Errorf("reset queue job for resume: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClaimLibraryJobForResume 用一次条件更新把中断作业抢过来:只有把 running 改成 pending
|
||||
// 的那一个 worker 拿到 true,多个 worker 同时重启也只会有一个执行(fencing)。
|
||||
func (s *Store) ClaimLibraryJobForResume(ctx context.Context, jobID string, now time.Time) (bool, error) {
|
||||
tag, err := s.db.Exec(ctx, `UPDATE library_jobs SET state='pending', updated_at=$2
|
||||
WHERE id=$1 AND state IN ('running','pending')`, jobID, now)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("claim interrupted library job: %w", err)
|
||||
}
|
||||
return tag.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
// ReconcileLibraryJobs 收拾"业务作业还在飞、队列里已经没有对应作业"的孤儿:
|
||||
// 它们会永久占用 (scope,kind) 唯一索引,让同一目标再也发不出作业。
|
||||
// 只标失败并写明恢复责任,不猜结果、不重放。
|
||||
|
||||
@@ -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",
|
||||
|
||||
Reference in New Issue
Block a user