fix(library): 对齐真实 WeKnora Schema + 入口级真实服务验收
build / build (push) Successful in 1m21s

为什么:候选环境改用真实 WeKnora 表结构后,暴露出多处"按猜的列名/形状"的假设,
以及若干 varchar 长度、对象定位符、空索引基线问题,导致真实链路跑不通。

- knowledge_tag_relations 无 tenant_id/KB 列 → 归属走父表;resources 作用域=绑定+chunk 引用。
- 写入顺序按真实外键;无代理键表用内容摘要核对。
- 队列作业 ID / 版本记录 ID 改固定长度摘要(列宽 varchar(36)/varchar(64))。
- 对象定位符拆 storage://<backend>/oss://<bucket>/<key>;provider 可配置。
- 空索引基线全链路一致(Current/Export/Backup/Archive),非空仍严格比对映射。
- finalize 阶段:版本登记失败不报成功;崩溃接管复用已持久化预备份。
- 迁移 000069:同一目标的 sync/restore 跨 kind 互斥。
This commit is contained in:
姚章浩
2026-10-28 17:53:43 +08:00
parent 8a68ea2da2
commit ac3b395102
28 changed files with 878 additions and 104 deletions
+71 -6
View File
@@ -5,10 +5,13 @@ import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"strings"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
"knowledge-governance/internal/librarydiff"
@@ -42,6 +45,35 @@ type libraryKnownView struct {
State string `json:"state"` // known | unknown
Version *libraryVersionView `json:"version,omitempty"`
Reason string `json:"reason,omitempty"`
// EmptyBaseline 表示"没有生效版本记录,但生产目标可读且确实是空的":
// 这是首次发布的合法起点,和"生产非空却没有权威版本"必须区分。
EmptyBaseline bool `json:"empty_baseline,omitempty"`
}
// productionScopeEmpty 只读探测生产目标:真正连库数一遍,不用缓存或推断。
func productionScopeEmpty(ctx context.Context, config Config, scope string) (bool, error) {
if strings.TrimSpace(config.LibraryProductionDatabaseURL) == "" {
return false, errors.New("生产整库目标未配置")
}
kb := config.LibraryProductionInternalKB
if scope == "external" {
kb = config.LibraryProductionExternalKB
}
if kb == "" {
return false, errors.New("生产知识库未配置")
}
pool, err := pgxpool.New(ctx, config.LibraryProductionDatabaseURL)
if err != nil {
return false, err
}
defer pool.Close()
var count int64
err = pool.QueryRow(ctx, `SELECT count(*) FROM knowledges WHERE tenant_id=$1 AND knowledge_base_id=$2 AND deleted_at IS NULL`,
config.LibraryProductionTenantID, kb).Scan(&count)
if err != nil {
return false, err
}
return count == 0, nil
}
type libraryDiffView struct {
@@ -302,6 +334,13 @@ func libraryVersionViewOf(item governance.LibraryVersion) libraryVersionView {
// librarySyncGate 只依据真实存在的证据判断能不能写生产:闸口、生产端点、
// 生产权威版本、目标快照的预备份。任何一项缺失都给出具体原因,不默认放行。
func errString(err error) string {
if err == nil {
return ""
}
return err.Error()
}
func librarySyncGate(config Config, production libraryKnownView, prebackup libraryKnownView, target string) libraryGateView {
return librarySyncGateWithGrant(config, production, prebackup, target, false)
}
@@ -319,17 +358,23 @@ func librarySyncGateWithGrant(config Config, production libraryKnownView, prebac
if !config.ProductionBackupRestoreVerified {
gate.Reasons = append(gate.Reasons, "没有已核验的生产恢复演练证据(PRODUCTION_BACKUP_RESTORE_VERIFIED=false)")
}
if strings.TrimSpace(config.ProductionWeKnoraBaseURL) == "" {
gate.Reasons = append(gate.Reasons, "生产端点未配置,无法核验生产当前版本")
// 生产端点以"整库目标是否配置"为准:整库同步直接写 PG/ES/对象,
// 不依赖 WeKnora 的 HTTP 端,所以不能拿它是否配置当门禁。
if strings.TrimSpace(config.LibraryProductionDatabaseURL) == "" {
gate.Reasons = append(gate.Reasons, "生产整库目标未配置(LIBRARY_PRODUCTION_DATABASE_URL),无法核验生产当前状态")
}
if production.State != "known" {
// 首次发布:生产还没有"生效版本"记录,但只要生产目标可读且是空的,
// 这就是一个合法的"空基线",不应该被永久挡住。非空但无权威版本仍然阻断。
if production.State != "known" && !production.EmptyBaseline {
gate.Reasons = append(gate.Reasons, "生产当前权威版本未知,不能启动写入")
}
if target == "" {
gate.Reasons = append(gate.Reasons, "还没有可同步的测试封存版本")
}
if prebackup.State != "known" {
gate.Reasons = append(gate.Reasons, "本次目标快照还没有生产预备份")
// 预备份是作业内第一步生成的:启动前要求它已存在会造成死循环。
// 这里只在作业已经被判定失败或回滚失败时提示,不作为启动前的硬门禁。
if prebackup.State == "failed" {
gate.Reasons = append(gate.Reasons, "上一次预备份失败,先处理后才能重试")
}
if config.LibraryCapacityBudgetBytes <= 0 {
gate.Reasons = append(gate.Reasons, "容量预算未设置(LIBRARY_CAPACITY_BUDGET_BYTES),无法证明装得下")
@@ -507,6 +552,10 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
}
overview.Production = libraryKnownView{State: "unknown"}
overview.Prebackup = libraryKnownView{State: "unknown"}
if empty, probeErr := productionScopeEmpty(r.Context(), config, request.Scope); probeErr == nil && empty {
overview.Production = libraryKnownView{State: "unknown", EmptyBaseline: true,
Reason: "生产目标可读且为空:本次是首次发布,写入前仍会生成完整预备份"}
}
for index := range versions {
item := versions[index]
if item.Kind == governance.LibraryVersionProductionEffective && item.SupersededAt == nil {
@@ -559,6 +608,21 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot create library sync job"})
return
}
// 上一次同参数请求失败/被取消后,幂等键不能再把新请求塞回那个死作业里:
// 换一个"重试代次"键重新建作业,旧作业保留为审计记录。
if reused && (job.State == governance.LibraryJobFailed || job.State == governance.LibraryJobCancelled) {
job, reused, err = store.CreateLibraryJob(r.Context(), governance.LibraryJob{
ID: fmt.Sprintf("libsync-%s-%d", request.Scope, now.UnixNano()), Scope: request.Scope,
Kind: governance.LibraryJobSync,
IdempotencyKey: "library.sync:" + request.Scope + ":" + request.Target + ":retry:" + now.Format("20060102T150405.000000000"),
RequestDigest: digest, TargetSnapshotID: request.Target, Actor: actor,
}, governance.SyncStages(), now)
if err != nil || reused {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_sync_retry_conflict",
"error": "无法为重试创建新作业", "detail": errString(err)})
return
}
}
if reused {
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": true})
return
@@ -572,10 +636,11 @@ func librarySyncEnqueue(w http.ResponseWriter, r *http.Request, config Config) {
return
}
queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
ID: job.ID + "-queue", Type: librarySyncJobType, Payload: payload, AvailableAt: now,
ID: governance.QueueJobIDFor(job.ID), Type: librarySyncJobType, Payload: payload, AvailableAt: now,
MaxAttempts: 1, IdempotencyKey: "library.sync.queue:" + job.ID,
}, now)
if err != nil || queueJob == nil {
log.Printf("library sync enqueue failed job=%s: %v", job.ID, err)
_ = store.CancelLibraryJob(r.Context(), job.ID, "队列投递失败,未开始同步", now)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue sync job"})
return
+47 -11
View File
@@ -128,7 +128,7 @@ func TestLibrarySyncGateRequiresEveryPieceOfEvidence(t *testing.T) {
{
name: "flags on but restore evidence missing",
config: Config{ProductionReleaseRequestsEnabled: true,
ProductionWeKnoraBaseURL: "http://prod.invalid"},
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int"},
production: known,
prebackup: known,
target: "snap-1",
@@ -138,7 +138,7 @@ func TestLibrarySyncGateRequiresEveryPieceOfEvidence(t *testing.T) {
{
name: "capacity budget missing blocks even when everything else is present",
config: Config{ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
ProductionWeKnoraBaseURL: "http://prod.invalid"},
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int"},
production: known,
prebackup: known,
target: "snap-1",
@@ -148,7 +148,7 @@ func TestLibrarySyncGateRequiresEveryPieceOfEvidence(t *testing.T) {
{
name: "everything present",
config: Config{ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
ProductionWeKnoraBaseURL: "http://prod.invalid", LibraryCapacityBudgetBytes: 1 << 40},
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int", LibraryCapacityBudgetBytes: 1 << 40},
production: known,
prebackup: known,
target: "snap-1",
@@ -198,26 +198,62 @@ func TestLibrarySyncEnqueueRefusesWithoutCreatingJob(t *testing.T) {
}
}
// 即使闸口打开,缺少与目标快照绑定的预备份也必须拒绝。
// 预备份是作业内第一步生成的,不能拿"启动前还没有预备份"当门禁:
// 否则预备份只能由作业生成、作业又要求预备份,永远启动不了。
// 但"上一次预备份失败"必须阻断重试。
func TestLibrarySyncEnqueueDoesNotRequirePrebackupBeforeStart(t *testing.T) {
store := &fakeLibraryStore{}
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int",
LibraryCapacityBudgetBytes: 1 << 40}
gate := librarySyncGateWithGrant(config, libraryKnownView{State: "known"}, libraryKnownView{State: "unknown"}, "snap-1", true)
if !gate.SyncAllowed {
t.Fatalf("missing prebackup must not block the start: %v", gate.Reasons)
}
failed := librarySyncGateWithGrant(config, libraryKnownView{State: "known"},
libraryKnownView{State: "failed"}, "snap-1", true)
if failed.SyncAllowed || !strings.Contains(strings.Join(failed.Reasons, "|"), "预备份失败") {
t.Fatalf("failed prebackup must block: %v", failed.Reasons)
}
}
// 首次发布:生产没有生效版本,但目标为空 = 合法空基线。
func TestLibrarySyncGateAllowsFirstPublishOnEmptyBaseline(t *testing.T) {
config := Config{ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int",
LibraryCapacityBudgetBytes: 1 << 40}
empty := libraryKnownView{State: "unknown", EmptyBaseline: true}
if gate := librarySyncGateWithGrant(config, empty, libraryKnownView{State: "unknown"}, "snap-1", true); !gate.SyncAllowed {
t.Fatalf("empty production must be a legal first-publish baseline: %v", gate.Reasons)
}
// 非空但没有权威版本:仍然阻断。
if gate := librarySyncGateWithGrant(config, libraryKnownView{State: "unknown"}, libraryKnownView{State: "unknown"}, "snap-1", true); gate.SyncAllowed {
t.Fatal("unknown non-empty production must block")
}
}
// 上一次预备份失败时必须阻断重试(预备份本身是作业内生成的,不能当启动前门禁)。
func TestLibrarySyncEnqueueRequiresPrebackupForTarget(t *testing.T) {
store := &fakeLibraryStore{versions: []governance.LibraryVersion{{
ID: "ver-prod-1", Scope: "internal", Kind: governance.LibraryVersionProductionEffective,
SnapshotID: "prod-snap", VersionLabel: "prod-2026.10", CreatedAt: time.Now().UTC(),
}, {
ID: "ver-backup-1", Scope: "internal", Kind: governance.LibraryVersionProductionPrebackup,
SnapshotID: "snap-1", CreatedAt: time.Now().UTC(),
}}}
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
ProductionWeKnoraBaseURL: "http://prod.invalid"}
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int",
LibraryCapacityBudgetBytes: 1 << 40}
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/syncs",
strings.NewReader(`{"scope":"internal","target_snapshot_id":"snap-1"}`))
recorder := httptest.NewRecorder()
librarySyncEnqueue(recorder, request, config)
// 没有授权仍然 503,但原因里不能再出现"还没有生产预备份"这种死循环门禁。
if recorder.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503", recorder.Code)
}
if !strings.Contains(recorder.Body.String(), "预备份") {
t.Fatalf("refusal must name the missing prebackup: %s", recorder.Body.String())
}
if store.createN != 0 {
t.Fatalf("created %d jobs without a prebackup", store.createN)
if strings.Contains(recorder.Body.String(), "还没有生产预备份") {
t.Fatalf("start gate must not require a prebackup that only the job can create: %s", recorder.Body.String())
}
}
@@ -236,7 +272,7 @@ func TestLibrarySyncEnqueueCreatesJobOnlyWithGrant(t *testing.T) {
}}
store.enqueueEchoRequestedID = true
config := Config{Store: store, ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: true,
ProductionWeKnoraBaseURL: "http://prod.invalid", LibraryCapacityBudgetBytes: 1 << 40}
LibraryProductionDatabaseURL: "postgres://prod.invalid/db", LibraryProductionInternalKB: "kb-int", LibraryCapacityBudgetBytes: 1 << 40}
body := `{"scope":"internal","target_snapshot_id":"` + target + `"}`
// 先没有授权
+67 -10
View File
@@ -100,6 +100,17 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot create restore job"})
return
}
if reused && (job.State == governance.LibraryJobFailed || job.State == governance.LibraryJobCancelled) {
job, reused, err = store.CreateLibraryJob(r.Context(), governance.LibraryJob{
ID: jobID + "-retry", Scope: request.Scope, Kind: governance.LibraryJobRestore,
IdempotencyKey: "library.restore:" + request.Scope + ":" + request.SnapshotID + ":retry:" + now.Format("20060102T150405.000000000"),
RequestDigest: digest, TargetSnapshotID: request.SnapshotID, Actor: identity.Username,
}, governance.SyncStages(), now)
if err != nil || reused {
writeJSON(w, http.StatusConflict, map[string]any{"code": "library_restore_retry_conflict", "error": "无法为重试创建新作业"})
return
}
}
if reused {
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "reused": true})
return
@@ -112,7 +123,7 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config
return
}
queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
ID: job.ID + "-queue", Type: libraryRestoreJobType, Payload: payload, AvailableAt: now,
ID: governance.QueueJobIDFor(job.ID), Type: libraryRestoreJobType, Payload: payload, AvailableAt: now,
MaxAttempts: 1, IdempotencyKey: "library.restore.queue:" + job.ID,
}, now)
if err != nil || queueJob == nil {
@@ -130,8 +141,9 @@ func libraryRestoreEnqueue(w http.ResponseWriter, r *http.Request, config Config
// 崩溃续作:失败作业可以按原参数重新排队,生成新作业(旧作业保留为审计记录)。
func libraryJobResume(w http.ResponseWriter, r *http.Request, config Config) {
identity, ok := sessionFrom(r.Context())
if !ok || roleRank(identity.Role) < roleRank(roleEngineer) {
writeJSON(w, http.StatusForbidden, map[string]any{"error": "续作需要知识工程师及以上权限"})
// 续作会重新写生产,权限与恢复一致:只有管理员能触发。
if !ok || roleRank(identity.Role) < roleRank(roleAdmin) {
writeJSON(w, http.StatusForbidden, map[string]any{"error": "续作需要管理员权限"})
return
}
store, ok := libraryStore(config)
@@ -149,8 +161,41 @@ func libraryJobResume(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, http.StatusConflict, map[string]any{"error": "只有失败或已取消的作业可以续作"})
return
}
// 与同步/恢复一致:闸口、恢复演练证据与授权都要在 API 侧 fail-closed,
// 不能让前台接受一个 worker 必然拒绝的请求。
reasons := make([]string, 0, 3)
if !config.ProductionReleaseRequestsEnabled {
reasons = append(reasons, "生产写入闸口关闭")
}
if !config.ProductionBackupRestoreVerified {
reasons = append(reasons, "没有已核验的生产恢复演练证据")
}
var digest string
switch source.Kind {
case governance.LibraryJobSync:
digest, _ = librarySyncParamsDigest(source.Scope, source.TargetSnapshotID)
case governance.LibraryJobRestore:
digest, _ = libraryRestoreParamsDigest(source.Scope, source.TargetSnapshotID)
}
authorizationOK := false
if storeWithAuth, ok := config.Store.(interface {
ActiveLibraryAuthorization(ctx context.Context, scope, snapshotID, digest string, now time.Time) (governance.LibraryReleaseAuthorization, bool, error)
}); ok && digest != "" {
_, found, authErr := storeWithAuth.ActiveLibraryAuthorization(r.Context(), source.Scope,
source.TargetSnapshotID, digest, time.Now().UTC())
authorizationOK = authErr == nil && found
}
if !authorizationOK {
reasons = append(reasons, "没有针对该快照的有效授权")
}
if len(reasons) > 0 {
writeJSON(w, http.StatusServiceUnavailable, map[string]any{"code": "library_resume_blocked", "reasons": reasons})
return
}
now := time.Now().UTC()
jobID := sourceID + "-r" + now.Format("150405")
// 幂等键按源作业固定:重复点击返回同一个续作作业,而不是每次新建。
jobID := sourceID + "-resume"
var kind governance.LibraryJobKind
queueType := ""
switch source.Kind {
@@ -162,24 +207,31 @@ func libraryJobResume(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, http.StatusConflict, map[string]any{"error": "封存作业由封存入口重发,不走续作"})
return
}
digest := source.RequestDigest
job, _, err := store.CreateLibraryJob(r.Context(), governance.LibraryJob{
job, reused, err := store.CreateLibraryJob(r.Context(), governance.LibraryJob{
ID: jobID, Scope: source.Scope, Kind: kind,
IdempotencyKey: "library.resume:" + sourceID + ":" + now.Format("150405"),
IdempotencyKey: "library.resume:" + sourceID,
RequestDigest: digest, TargetSnapshotID: source.TargetSnapshotID, Actor: identity.Username,
}, governance.SyncStages(), now)
if errors.Is(err, governance.ErrLibraryJobActive) {
writeJSON(w, http.StatusConflict, map[string]any{"error": "该目标已有在飞作业"})
return
}
if errors.Is(err, governance.ErrLibraryJobIdempotencyConflict) {
writeJSON(w, http.StatusConflict, map[string]any{"error": "同一续作请求参数不一致"})
return
}
if err != nil {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot create resumed job"})
return
}
if reused {
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})
queueJob, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{
ID: job.ID + "-queue", Type: queueType, Payload: payload, AvailableAt: now,
ID: governance.QueueJobIDFor(job.ID), Type: queueType, Payload: payload, AvailableAt: now,
MaxAttempts: 1, IdempotencyKey: "library.resume.queue:" + job.ID,
}, now)
if err != nil || queueJob == nil {
@@ -187,6 +239,11 @@ func libraryJobResume(w http.ResponseWriter, r *http.Request, config Config) {
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot enqueue resumed job"})
return
}
_ = store.AttachLibraryQueueJob(r.Context(), job.ID, queueJob.ID, now)
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "resumed_from": sourceID})
// 附不上队列号就等于作业没人跑:必须显式失败并取消,不能静默返回 202。
if attachErr := store.AttachLibraryQueueJob(r.Context(), job.ID, queueJob.ID, now); attachErr != nil {
_ = store.CancelLibraryJob(r.Context(), job.ID, "队列归属写入失败", now)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "cannot attach resumed job"})
return
}
writeJSON(w, http.StatusAccepted, map[string]any{"job": job, "resumed_from": sourceID, "reused": false})
}
+1 -1
View File
@@ -78,7 +78,7 @@ func TestLibraryJobResumeRejectsNonFailedJobs(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "/api/v1/library/jobs/job-1/resume", nil)
request.SetPathValue("id", "job-1")
request = request.WithContext(context.WithValue(request.Context(), sessionKey{},
sessionIdentity{Username: "eng", Role: roleEngineer}))
sessionIdentity{Username: "admin", Role: roleAdmin}))
recorder := httptest.NewRecorder()
libraryJobResume(recorder, request, Config{Store: store})
if recorder.Code != http.StatusConflict {
+5
View File
@@ -135,6 +135,11 @@ type Config struct {
LibraryAgentSocket string
// LibraryCapacityBudgetBytes 是整库归档容量预算;0 = 未设置(容量门禁不放行)。
LibraryCapacityBudgetBytes int64
// 整库生产目标的只读探测配置:首次发布要能证明"生产可读且为空"。
LibraryProductionDatabaseURL string
LibraryProductionInternalKB string
LibraryProductionExternalKB string
LibraryProductionTenantID uint64
// LibraryRetentionVersions/Days 是保留策略;都为 0 = 未设置(不生成清理候选)。
LibraryRetentionVersions int
LibraryRetentionDays int