fix(library): 修复封存终态回写并增加精确核对
build / build (push) Successful in 2m9s

修复 varchar 状态参数在 AdvanceLibraryJob 的 42P08;worker 开始/终态写入失败
不再吞掉。新增管理员核对路由,仅在 completed capture queue、export succeeded、
精确 test_sealed 版本、来源身份和归档复核一致时,以条件更新修复仍为
pending/running 的同一作业;已有不同快照或并发失败/取消行拒绝覆盖。保留
第一因与历史记录,不重新封存、不产生快照、不写源或目标知识。

验证:真实 varchar DDL PG 路径、handler 负例/幂等、worker 注入、web 组件;
umask022 与真实隔离 kg_library_test_* 下 Go 全量与 make verify 17 项通过。
This commit is contained in:
姚章浩
2026-11-06 10:04:19 +08:00
parent 77bbc3ac6b
commit 146ac832a2
18 changed files with 1082 additions and 39 deletions
+5
View File
@@ -148,6 +148,11 @@ func classifyRole(method, path string) string {
if strings.HasPrefix(path, "/api/v1/backup-schedule") && method != http.MethodGet {
return roleAdmin
}
// 核对封存结果会把一个 pending 业务作业修成 succeeded;只允许管理员,
// 且 handler 仍要求 completed queue、精确版本和归档复核。
if strings.HasPrefix(path, "/api/v1/library/jobs/") && strings.HasSuffix(path, "/reconcile-capture") {
return roleAdmin
}
// 版本记录的同步会拉起一次对远端仓库的抓取(消耗网络与数据库写入),
// 与"谁能改生产绑定"同级:读任何角色可看,同步只能管理员。
if strings.HasPrefix(path, "/api/v1/version-history") && method != http.MethodGet {
@@ -0,0 +1,213 @@
package httpapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"strings"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
"knowledge-governance/internal/librarysnapshot"
)
// libraryCaptureReconciler is deliberately narrow: it repairs one business
// seal job only after the completed capture queue, the successful export stage,
// the exact test-sealed version and the archived bytes all agree. It never
// captures, freezes writers, creates snapshots, writes source/target content or
// changes historical failure evidence.
type libraryCaptureReconciler interface {
LibraryJob(ctx context.Context, id string) (governance.LibraryJob, error)
LibraryCaptureExportEvidence(ctx context.Context, jobID string) (string, string, error)
LibraryTestSealedVersionForJob(ctx context.Context, scope, jobID string) (governance.LibraryVersion, bool, error)
EnsureLibraryOperation(ctx context.Context, op governance.LibraryOperation) (governance.LibraryOperation, bool, error)
ReconcileLibraryCaptureTerminal(ctx context.Context, jobID, scope, queueJobID, snapshotID string, now time.Time) (bool, error)
}
type libraryCaptureQueueReader interface {
QueueJob(ctx context.Context, id string) (jobs.Job, bool, error)
}
func libraryCaptureReconcile(w http.ResponseWriter, r *http.Request, config Config) {
if r.Method != http.MethodPost {
writeJSON(w, http.StatusMethodNotAllowed, map[string]string{"error": "method not allowed"})
return
}
store, ok := config.Store.(libraryCaptureReconciler)
if !ok {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
"reason": "封存作业核对存储不可用"})
return
}
queueStore, ok := config.Store.(libraryCaptureQueueReader)
if !ok {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
"reason": "队列精确读取不可用"})
return
}
jobID := strings.TrimSpace(r.PathValue("id"))
if jobID == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "job id required"})
return
}
job, err := store.LibraryJob(r.Context(), jobID)
if err != nil {
writeJSON(w, http.StatusNotFound, map[string]any{"available": false, "reason": "作业不存在"})
return
}
if job.Kind != governance.LibraryJobSeal {
conflict(w, "只有封存作业可以核对封存结果")
return
}
if job.State != governance.LibraryJobPending && job.State != governance.LibraryJobRunning && job.State != governance.LibraryJobSucceeded {
conflict(w, "作业已是失败/取消终态,不能改写成成功")
return
}
if job.QueueJobID == "" {
conflict(w, "作业没有关联队列号,不能证明封存完成")
return
}
captureJob := strings.TrimPrefix(job.ID, "libseal-")
if captureJob == "" || captureJob == job.ID {
conflict(w, "作业号不是封存作业身份")
return
}
queue, found, err := queueStore.QueueJob(r.Context(), job.QueueJobID)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read capture queue"})
return
}
if !found {
conflict(w, "队列作业不存在,不能证明封存完成")
return
}
if queue.Type != libraryCaptureJobType || queue.State != jobs.StateCompleted {
conflict(w, "队列作业不是 completed 的 library.capture")
return
}
var payload struct {
Scope string `json:"scope"`
CaptureJob string `json:"capture_job"`
}
if err := json.Unmarshal(queue.Payload, &payload); err != nil ||
payload.Scope != job.Scope || payload.CaptureJob != captureJob ||
queue.IdempotencyKey != "library.capture:"+captureJob {
conflict(w, "队列作业的 scope/capture_job/幂等键与业务作业不一致")
return
}
stageState, _, err := store.LibraryCaptureExportEvidence(r.Context(), job.ID)
if err != nil || stageState != "succeeded" {
conflict(w, "导出阶段没有成功证据,不能修复终态")
return
}
version, found, err := store.LibraryTestSealedVersionForJob(r.Context(), job.Scope, job.ID)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot read exact test-sealed version"})
return
}
if !found || version.Kind != governance.LibraryVersionTestSealed ||
version.Scope != job.Scope || version.SourceJobID != job.ID || version.SnapshotID == "" {
conflict(w, "没有与作业/scope 精确绑定的测试封存版本")
return
}
source := configuredLibrarySource(config, job.Scope)
sourceID, err := source.ID()
if err != nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
"reason": "来源身份配置不完整,无法核对封存来源"})
return
}
evidenceSource, _ := version.Evidence["source_id"].(string)
evidenceCapture, _ := version.Evidence["capture_job"].(string)
if evidenceSource != sourceID || evidenceCapture != captureJob {
conflict(w, "版本来源或 capture_job 与当前作业不一致")
return
}
if config.LibraryArchiveRoot == "" {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
"reason": "未接线归档根,无法复核归档完整性"})
return
}
archive, err := librarysnapshot.Open(config.LibraryArchiveRoot, 256*1024*1024)
if err != nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"available": false,
"reason": "归档不可读,不能确认封存完整"})
return
}
defer archive.Close()
manifest, err := archive.Load(version.SnapshotID)
if err != nil {
conflict(w, "归档字节复核失败,不能修复作业")
return
}
if manifest.Scope != source.Scope || manifest.TenantID != source.TenantID ||
manifest.KnowledgeBaseID != source.KnowledgeBaseID {
conflict(w, "归档清单来源身份与当前来源不一致")
return
}
if job.SnapshotID != "" && job.SnapshotID != version.SnapshotID {
conflict(w, "作业已有不同快照,不能覆盖")
return
}
if job.State == governance.LibraryJobSucceeded {
if job.SnapshotID != version.SnapshotID {
conflict(w, "作业已成功但快照与精确版本不一致")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"repaired": false, "already_succeeded": true, "job_id": job.ID,
"snapshot_id": version.SnapshotID, "queue_job_id": queue.ID,
"version_id": version.ID,
})
return
}
actor := ""
if identity, ok := sessionFrom(r.Context()); ok {
actor = identity.Username
}
now := time.Now().UTC()
digest, err := governance.LibraryRequestDigest(job.Scope, governance.LibraryJobRecover, map[string]any{
"kind": "capture_reconcile", "job_id": job.ID, "queue_job_id": queue.ID,
"snapshot_id": version.SnapshotID, "capture_job": captureJob, "stage": "export",
})
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot build reconcile audit digest"})
return
}
opID := "libop-capture-reconcile-" + digest[:16]
op, _, err := store.EnsureLibraryOperation(r.Context(), governance.LibraryOperation{
ID: opID, Scope: job.Scope, Kind: governance.LibraryJobRecover,
TargetSnapshotID: version.SnapshotID, RequestDigest: digest,
OperationKey: "capture-reconcile:" + job.ID, Actor: actor, CreatedAt: now,
})
if errors.Is(err, governance.ErrLibraryOperationConflict) {
conflict(w, "同一核对键对应了不同证据,拒绝修复")
return
}
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot record reconcile audit"})
return
}
updated, err := store.ReconcileLibraryCaptureTerminal(r.Context(), job.ID, job.Scope, job.QueueJobID, version.SnapshotID, now)
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]any{
"error": "cannot persist reconciled job terminal", "audit_operation_id": op.ID,
})
return
}
if !updated {
conflict(w, "作业状态/身份在核对期间变化,拒绝覆盖")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"repaired": true, "already_succeeded": false, "job_id": job.ID,
"snapshot_id": version.SnapshotID, "queue_job_id": queue.ID,
"stage": "export", "version_id": version.ID, "audit_operation_id": op.ID,
})
}
func conflict(w http.ResponseWriter, reason string) {
writeJSON(w, http.StatusConflict, map[string]any{"available": false, "repaired": false, "reason": reason})
}
@@ -0,0 +1,273 @@
package httpapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
"knowledge-governance/internal/librarysnapshot"
)
func (f *fakeLibraryStore) QueueJob(_ context.Context, id string) (jobs.Job, bool, error) {
if f.queue == nil || f.queue.ID != id {
return jobs.Job{}, false, nil
}
return *f.queue, true, nil
}
func (f *fakeLibraryStore) LibraryCaptureExportEvidence(_ context.Context, _ string) (string, string, error) {
return f.stageState, "", f.stageErr
}
func (f *fakeLibraryStore) LibraryJobStage(_ context.Context, _, stage string) (string, string, error) {
if f.stageErr != nil {
return "", "", f.stageErr
}
if stage != "export" {
return "", "", errors.New("unexpected stage")
}
return f.stageState, "", nil
}
func (f *fakeLibraryStore) LibraryTestSealedVersionForJob(_ context.Context, scope, jobID string) (governance.LibraryVersion, bool, error) {
if f.versionErr != nil {
return governance.LibraryVersion{}, false, f.versionErr
}
if f.sealedVersion == nil || f.sealedVersion.Scope != scope || f.sealedVersion.SourceJobID != jobID {
return governance.LibraryVersion{}, false, nil
}
return *f.sealedVersion, true, nil
}
func reconcileFixture(t *testing.T) (*fakeLibraryStore, Config, governance.LibraryJob, []byte) {
t.Helper()
root := libraryFixtureRoot(t)
snapshotID := sealSharedVersions(t, root, 1, 4)[0]
archive, err := librarysnapshot.Open(root, 256*1024*1024)
if err != nil {
t.Fatal(err)
}
manifest, err := archive.Load(snapshotID)
archive.Close()
if err != nil {
t.Fatal(err)
}
config := Config{LibraryArchiveRoot: root,
LibrarySourceProject: "fixture-project", LibrarySourceApp: "fixture-app",
LibrarySourceTenantID: manifest.TenantID, LibrarySourceInternalKB: manifest.KnowledgeBaseID}
source := configuredLibrarySource(config, "internal")
sourceID, err := source.ID()
if err != nil {
t.Fatal(err)
}
job := governance.LibraryJob{ID: "libseal-cap-1", Scope: "internal", Kind: governance.LibraryJobSeal,
State: governance.LibraryJobPending, QueueJobID: "libcap-1"}
payload, _ := json.Marshal(map[string]string{"scope": "internal", "capture_job": "cap-1"})
store := &fakeLibraryStore{
jobs: []governance.LibraryJob{job},
stageState: "succeeded",
queue: &jobs.Job{ID: "libcap-1", Type: libraryCaptureJobType, State: jobs.StateCompleted,
Payload: payload, IdempotencyKey: "library.capture:cap-1"},
sealedVersion: &governance.LibraryVersion{ID: "libver-1", Scope: "internal",
Kind: governance.LibraryVersionTestSealed, SnapshotID: snapshotID, SourceJobID: job.ID,
Evidence: map[string]any{"source_id": sourceID, "capture_job": "cap-1"}},
}
config.Store = store
return store, config, job, payload
}
func (f *fakeLibraryStore) ReconcileLibraryCaptureTerminal(_ context.Context, jobID, scope, queueJobID, snapshotID string, _ time.Time) (bool, error) {
if f.reconcileDenied {
return false, nil
}
for index := range f.jobs {
if f.jobs[index].ID != jobID || f.jobs[index].Scope != scope || f.jobs[index].Kind != governance.LibraryJobSeal ||
f.jobs[index].QueueJobID != queueJobID || (f.jobs[index].State != governance.LibraryJobPending && f.jobs[index].State != governance.LibraryJobRunning) ||
(f.jobs[index].SnapshotID != "" && f.jobs[index].SnapshotID != snapshotID) {
return false, nil
}
f.jobs[index].State = governance.LibraryJobSucceeded
f.jobs[index].SnapshotID = snapshotID
f.lastState = governance.LibraryJobSucceeded
return true, nil
}
return false, nil
}
func runReconcile(t *testing.T, config Config, jobID string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/"+jobID+"/reconcile-capture", nil)
req.SetPathValue("id", jobID)
rec := httptest.NewRecorder()
libraryCaptureReconcile(rec, req, config)
return rec
}
func TestLibraryCaptureReconcileRepairsExactCompletedCapture(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusOK {
t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String())
}
var body map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body["repaired"] != true || body["snapshot_id"] == "" || body["audit_operation_id"] == "" {
t.Fatalf("body=%v", body)
}
if store.lastState != governance.LibraryJobSucceeded {
t.Fatalf("advanced state=%s", store.lastState)
}
if len(store.operations) != 1 {
t.Fatalf("audit operations=%v", store.operations)
}
}
func TestLibraryCaptureReconcileAlreadySucceededIsReadOnly(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
job.State = governance.LibraryJobSucceeded
job.SnapshotID = store.sealedVersion.SnapshotID
store.jobs[0] = job
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusOK {
t.Fatalf("code=%d body=%s", rec.Code, rec.Body.String())
}
var body map[string]any
_ = json.Unmarshal(rec.Body.Bytes(), &body)
if body["already_succeeded"] != true || body["repaired"] != false || store.lastState != "" {
t.Fatalf("body=%v advanced=%q", body, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsQueueNotCompleted(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.queue.State = jobs.StateRunning
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
}
}
func TestLibraryCaptureReconcileRejectsStageNotSucceeded(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.stageState = "failed"
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsWrongVersionSource(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.sealedVersion.Evidence["source_id"] = "other-source"
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsWrongCaptureJob(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.sealedVersion.Evidence["capture_job"] = "other-capture"
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsBadArchive(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.sealedVersion.SnapshotID = "missing-snapshot"
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
}
}
func TestLibraryCaptureReconcileRejectsFailedJob(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
job.State = governance.LibraryJobFailed
store.jobs[0] = job
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileIsIdempotent(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
first := runReconcile(t, config, job.ID)
if first.Code != http.StatusOK {
t.Fatalf("first code=%d body=%s", first.Code, first.Body.String())
}
second := runReconcile(t, config, job.ID)
if second.Code != http.StatusOK {
t.Fatalf("second code=%d body=%s", second.Code, second.Body.String())
}
var body map[string]any
_ = json.Unmarshal(second.Body.Bytes(), &body)
if body["already_succeeded"] != true || len(store.operations) != 1 {
t.Fatalf("body=%v ops=%v", body, store.operations)
}
}
func TestLibraryCaptureReconcileRejectsMissingQueue(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.queue = nil
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsQueueScope(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.queue.Payload, _ = json.Marshal(map[string]string{"scope": "external", "capture_job": "cap-1"})
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsMissingVersion(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.sealedVersion = nil
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsWrongScopeVersion(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.sealedVersion.Scope = "external"
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q", rec.Code, store.lastState)
}
}
func TestLibraryCaptureReconcileRejectsDifferentExistingSnapshot(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
job.SnapshotID = "other-snapshot"
store.jobs[0] = job
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
}
}
func TestLibraryCaptureReconcileConditionalWriteRejectsConcurrentState(t *testing.T) {
store, config, job, _ := reconcileFixture(t)
store.reconcileDenied = true
rec := runReconcile(t, config, job.ID)
if rec.Code != http.StatusConflict || store.lastState != "" {
t.Fatalf("code=%d advanced=%q body=%s", rec.Code, store.lastState, rec.Body.String())
}
}
+17 -1
View File
@@ -11,6 +11,7 @@ import (
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
)
// 生产闸口与整库状态契约的针对性测试:不做数据库集成,只验证
@@ -37,6 +38,13 @@ type fakeLibraryStore struct {
resumeOK bool
resumeErr error
resumeCalls []string
// capture reconciliation fixtures
queue *jobs.Job
stageState string
stageErr error
sealedVersion *governance.LibraryVersion
versionErr error
reconcileDenied bool
}
func (f *fakeLibraryStore) CreateLibraryJob(_ context.Context, job governance.LibraryJob, _ []string, _ time.Time) (governance.LibraryJob, bool, error) {
@@ -127,8 +135,16 @@ func (f *fakeLibraryStore) UpdateLibraryStage(_ context.Context, _, _, _ string,
return nil
}
func (f *fakeLibraryStore) AdvanceLibraryJob(_ context.Context, _ string, state governance.LibraryJobState, _, _, _, _, _ string, _ time.Time) error {
func (f *fakeLibraryStore) AdvanceLibraryJob(_ context.Context, jobID string, state governance.LibraryJobState, _, _, _, snapshotID, _ string, _ time.Time) error {
f.lastState = state
for index := range f.jobs {
if f.jobs[index].ID == jobID {
f.jobs[index].State = state
if snapshotID != "" {
f.jobs[index].SnapshotID = snapshotID
}
}
}
return nil
}
+4
View File
@@ -559,6 +559,10 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("POST /api/v1/library/jobs/{id}/resume", func(w http.ResponseWriter, r *http.Request) {
libraryJobResume(w, r, config)
})
// 封存完成但终态回写失败时,只按已完成队列+精确版本+归档复核修复该作业。
mux.HandleFunc("POST /api/v1/library/jobs/{id}/reconcile-capture", func(w http.ResponseWriter, r *http.Request) {
libraryCaptureReconcile(w, r, config)
})
// 生产同步唯一入口:闸口未齐不建作业,返回缺项而不是假 Accepted。
mux.HandleFunc("POST /api/v1/library/syncs", func(w http.ResponseWriter, r *http.Request) {
librarySyncEnqueue(w, r, config)