fix(library): 续作在事务内校验阶段并原子入队
build / build (push) Successful in 1m29s

This commit is contained in:
姚章浩
2026-11-01 22:05:02 +08:00
parent e292b6f674
commit a98828dc4a
6 changed files with 363 additions and 43 deletions
+26
View File
@@ -33,6 +33,10 @@ type fakeLibraryStore struct {
// operations/lastOperation 记录"意图身份":重放与换键的差别在这里表达(F01)。
operations map[string]governance.LibraryOperation
lastOperation governance.LibraryOperation
// 续作:resumeOK/resumeErr 驱动存储层结果,resumeCalls 记录每次调用(断言不重复投递)。
resumeOK bool
resumeErr error
resumeCalls []string
}
func (f *fakeLibraryStore) CreateLibraryJob(_ context.Context, job governance.LibraryJob, _ []string, _ time.Time) (governance.LibraryJob, bool, error) {
@@ -59,6 +63,11 @@ func (f *fakeLibraryStore) EnsureLibraryOperation(_ context.Context, op governan
}
func (f *fakeLibraryStore) LibraryJob(_ context.Context, id string) (governance.LibraryJob, error) {
for _, job := range f.jobs {
if job.ID == id {
return job, nil
}
}
return governance.LibraryJob{ID: id}, nil
}
@@ -178,6 +187,23 @@ func (f *fakeLibraryStore) ResetQueueJobForResume(_ context.Context, _ string, _
return nil
}
// ResumeLibraryJob 模拟存储层事务语义:结果由 resumeResult 驱动,调用次数可断言"重复请求不重复投递"。
func (f *fakeLibraryStore) ResumeLibraryJob(_ context.Context, jobID, queueType string, _ time.Time) (governance.LibraryJob, bool, error) {
f.resumeCalls = append(f.resumeCalls, jobID+"/"+queueType)
if f.resumeErr != nil {
return governance.LibraryJob{}, false, f.resumeErr
}
if !f.resumeOK {
return governance.LibraryJob{}, false, nil
}
for _, job := range f.jobs {
if job.ID == jobID {
return job, true, nil
}
}
return governance.LibraryJob{}, false, nil
}
func TestLibrarySyncGateRequiresEveryPieceOfEvidence(t *testing.T) {
known := libraryKnownView{State: "known", Version: &libraryVersionView{ID: "v1"}}
cases := []struct {
+26 -24
View File
@@ -271,41 +271,31 @@ func libraryJobResume(w http.ResponseWriter, r *http.Request, config Config) {
// id 落盘。另建 `-resume` 作业只能继承 operation,其它所有者仍指向旧作业:
// AcquireInstanceMaintenance 会拒绝它、journal 与预备份也查不到——那样"续作"只是
// 一个漂亮的新行,接不上原窗口。原作业 + 新 attempt 才是批准协议的形状。
// 已回滚并持有维护窗口的作业不能续作:继续跑等于丢开原 before-image 重来一遍,
// 正确出口是维护恢复(/library/maintenance/recover),它绑定原 window_job_id。
if source.Stage == "rollback" {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_resume_requires_recover",
"error": "作业已在回滚阶段失败并保留维护窗口,请走维护恢复而不是续作"})
return
}
// 写入已完成、只差登记版本的情况:续作只做幂等收尾,不重写生产。
body := map[string]any{"library_job_id": sourceID, "scope": source.Scope,
"target_snapshot_id": source.TargetSnapshotID}
if source.Stage == "finalize" && source.SnapshotID != "" {
body["finalize_only"] = true
}
payload, _ := json.Marshal(body)
queueID := governance.QueueJobIDFor(sourceID)
// 状态变更与队列 upsert 必须在同一事务里:否则入队失败会把作业留在 pending 却没有队列行。
// 阶段/状态/执行权与载荷全部在存储层的事务里校验并构造:handler 手里的 source 只用于
// 授权与闸口判断,不参与续作决策,避免用过期快照复活一个已经变化的作业。
resumer, ok := config.Store.(interface {
ResumeLibraryJob(ctx context.Context, jobID, queueID, queueType string, payload []byte, now time.Time) (governance.LibraryJob, bool, error)
ResumeLibraryJob(ctx context.Context, jobID, queueType string, now time.Time) (governance.LibraryJob, bool, error)
})
if !ok {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"error": "作业存储不支持续作"})
return
}
prepared, resumed, err := resumer.ResumeLibraryJob(r.Context(), sourceID, queueID, queueType, payload, now)
if errors.Is(err, postgres.ErrLibraryResumeBusy) {
prepared, resumed, err := resumer.ResumeLibraryJob(r.Context(), sourceID, queueType, now)
switch {
case errors.Is(err, postgres.ErrLibraryResumeBusy):
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_resume_busy",
"error": "该作业已有执行在跑(租约仍有效),等它结束再续作"})
return
}
if err != nil {
case errors.Is(err, postgres.ErrLibraryResumeRequiresRecover):
// 窗口是否仍被持有由维护记录决定:已释放的回滚作业说"窗口已释放",不能一律宣称仍持有。
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_resume_requires_recover",
"error": "作业停在回滚阶段,请走维护恢复而不是续作",
"maintenance_held": maintenanceHeldFor(r.Context(), config, source)})
return
case err != nil:
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot resume job"})
return
}
if !resumed {
// 状态在检查之后被别的执行者推进(已接管/已完成):不许再塞一次。
case !resumed:
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_resume_state_changed",
"error": "作业已不在可续作状态(可能已被接管或完成)"})
return
@@ -313,3 +303,15 @@ func libraryJobResume(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, http.StatusAccepted, map[string]any{"job": prepared, "resumed_from": sourceID,
"resumed": true, "next_attempt_epoch": prepared.AttemptEpoch + 1})
}
// maintenanceHeldFor 只回答"这个作业现在是否仍持有维护窗口",用于给回滚作业的拒绝文案定性。
func maintenanceHeldFor(ctx context.Context, config Config, job governance.LibraryJob) bool {
reader, ok := config.Store.(interface {
LibraryMaintenanceOf(ctx context.Context, scope string) (*postgres.LibraryMaintenance, error)
})
if !ok {
return false
}
m, err := reader.LibraryMaintenanceOf(ctx, job.Scope)
return err == nil && m != nil && m.OwnerJobID == job.ID && m.ReleasedAt == nil
}
+118
View File
@@ -0,0 +1,118 @@
package httpapi
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/platform/postgres"
)
func resumeRequest(id string) *http.Request {
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/"+id+"/resume", nil)
request.SetPathValue("id", id)
return request.WithContext(context.WithValue(request.Context(), sessionKey{},
sessionIdentity{Username: "admin", Role: roleAdmin}))
}
func resumableStore(job governance.LibraryJob) *fakeLibraryStore {
now := time.Now().UTC()
digest, _ := librarySyncParamsDigest(job.Scope, job.TargetSnapshotID)
if job.Kind == governance.LibraryJobRestore {
digest, _ = libraryRestoreParamsDigest(job.Scope, job.TargetSnapshotID)
}
store := &fakeLibraryStore{
jobs: []governance.LibraryJob{job},
grant: &governance.LibraryReleaseAuthorization{ID: "a", Scope: job.Scope,
SnapshotID: job.TargetSnapshotID, ParamsDigest: digest, ExpiresAt: now.Add(time.Hour), CreatedAt: now},
}
store.resumeOK = true
return store
}
func resumeConfig(store *fakeLibraryStore) Config {
return Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true}
}
// 合法续作:202,并且只投递一次。
func TestR26ResumeAcceptedDeliversOnce(t *testing.T) {
job := governance.LibraryJob{ID: "job-ok", Scope: "internal", Kind: governance.LibraryJobSync,
State: governance.LibraryJobFailed, Stage: "resources", TargetSnapshotID: "snap-1"}
store := resumableStore(job)
recorder := httptest.NewRecorder()
libraryJobResume(recorder, resumeRequest("job-ok"), resumeConfig(store))
if recorder.Code != http.StatusAccepted {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
if len(store.resumeCalls) != 1 || store.resumeCalls[0] != "job-ok/library.sync" {
t.Fatalf("resume calls=%v", store.resumeCalls)
}
}
// 回滚阶段的作业:409,且文案不能一律宣称"仍持有维护窗口"(窗口可能已释放)。
func TestR26ResumeRollbackStageRequiresRecover(t *testing.T) {
job := governance.LibraryJob{ID: "job-rb", Scope: "internal", Kind: governance.LibraryJobRestore,
State: governance.LibraryJobFailed, Stage: "rollback", TargetSnapshotID: "snap-1"}
store := resumableStore(job)
store.resumeErr = postgres.ErrLibraryResumeRequiresRecover
recorder := httptest.NewRecorder()
libraryJobResume(recorder, resumeRequest("job-rb"), resumeConfig(store))
if recorder.Code != http.StatusConflict || !strings.Contains(recorder.Body.String(), "library_resume_requires_recover") {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
if strings.Contains(recorder.Body.String(), "保留维护窗口") {
t.Fatalf("must not always claim the window is held: %s", recorder.Body.String())
}
}
// 租约仍有效:409 busy,不是 500。
func TestR26ResumeBusyIsConflict(t *testing.T) {
job := governance.LibraryJob{ID: "job-busy", Scope: "internal", Kind: governance.LibraryJobSync,
State: governance.LibraryJobFailed, Stage: "resources", TargetSnapshotID: "snap-1"}
store := resumableStore(job)
store.resumeErr = postgres.ErrLibraryResumeBusy
recorder := httptest.NewRecorder()
libraryJobResume(recorder, resumeRequest("job-busy"), resumeConfig(store))
if recorder.Code != http.StatusConflict || !strings.Contains(recorder.Body.String(), "library_resume_busy") {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
}
// 入队失败(存储层事务回滚):500,且不得把作业当成已续作。
func TestR26ResumeEnqueueFailureIsServerError(t *testing.T) {
job := governance.LibraryJob{ID: "job-fail", Scope: "internal", Kind: governance.LibraryJobRestore,
State: governance.LibraryJobFailed, Stage: "resources", TargetSnapshotID: "snap-1"}
store := resumableStore(job)
store.resumeErr = errors.New("enqueue resumed job: injected")
recorder := httptest.NewRecorder()
libraryJobResume(recorder, resumeRequest("job-fail"), resumeConfig(store))
if recorder.Code != http.StatusInternalServerError {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
if strings.Contains(recorder.Body.String(), "resumed") {
t.Fatalf("failed enqueue must not claim success: %s", recorder.Body.String())
}
}
// 重复请求:第二次被存储层拒绝(状态已推进),不会重复投递。
func TestR26ResumeDuplicateRequestDoesNotRedeliver(t *testing.T) {
job := governance.LibraryJob{ID: "job-dup", Scope: "internal", Kind: governance.LibraryJobSync,
State: governance.LibraryJobFailed, Stage: "resources", TargetSnapshotID: "snap-1"}
store := resumableStore(job)
first := httptest.NewRecorder()
libraryJobResume(first, resumeRequest("job-dup"), resumeConfig(store))
store.resumeOK = false // 第二次:业务作业已不是 failed
second := httptest.NewRecorder()
libraryJobResume(second, resumeRequest("job-dup"), resumeConfig(store))
if first.Code != http.StatusAccepted || second.Code != http.StatusConflict {
t.Fatalf("first=%d second=%d body=%s", first.Code, second.Code, second.Body.String())
}
if len(store.resumeCalls) != 2 {
t.Fatalf("expected 2 store calls, got %v", store.resumeCalls)
}
}