fix(library): 搬运复用前复验字节、回传游标分页与发布队列事务交接
父独立审查退回的四个 finding,逐项修在本包内,不改架构。 1 复用路径没复验字节:remoteEvidence 只读清单+摘要就宣布可用。现在新增 libraryctl snapshot-verify(整版逐部件重算)并在复用前调用;blob 缺失/篡改必须 在入发布队列之前失败。新增真实 local 跨进程用例:清单不动、删 blob / 改 blob 后 再 Push 必须拒绝。 2 回传枚举被固定 LIMIT 50 截断:LibraryJobSnapshots 只取成功作业且按摘要字典序。 改为 LibrarySnapshotCandidates:合并 library_versions、library_jobs.snapshot_id、 library_jobs.target_snapshot_id 三处引用,按 (created_at, snapshot_id) 游标分页; 回传循环翻页到不足一页为止。失败/待恢复作业留下的预备份、第 51 条以后、历史恢复 输入快照都能被枚举。另修"本地只有清单、blob 已损坏就永远跳过":改用整版 Load 判定, 并给 Unpack 增加显式 RepairCorruptBlobs(只在权威云端读回时开启)。 3 身份映射错误:搬运拿目标 tenant/KB 去核对封存快照,而封存清单写的是**源**身份 (云测试验收目标 a8e9c8ad/2e980686 与源 KB 必然不同)。现在 expectedSnapshotIdentity 按版本台账判定:test_sealed → 用部署注入的源绑定(LIBRARY_SOURCE_TENANT_ID / LIBRARY_SOURCE_KB_*);预备份/生效/恢复版本 → 用目标绑定;没有登记或两类冲突一律拒绝。 身份永远来自独立绑定与台账,不接受包自证。 4 两步入队有竞态:Enqueue 成功后云执行器可能立刻领取并开始维护,Attach 失败却把作业 标失败并声称"未维护"。改为 EnqueueAndAttachLibraryJob 单事务(锁行 + 插入 + 关联 + 状态守卫),要么都成功要么都不发生;重复执行幂等,已关联别的队列作业则拒绝。 另修终态重放:AdvanceLibraryJob 无状态守卫,迟到的失败出口会把已成功作业改写; 新增 AdvanceLibraryJobIfActive(仅 pending/running 可推进),拿不到就明确记录"未覆盖"。 测试:libraryhandoff 用例覆盖跨租户/错误 scope/清单在而字节坏/本地损坏自愈; 隔离 fixture 库覆盖"校验通过才入队、失败不入队"、>50 条分页与失败作业预备份、 幂等重放不重复投递、迟到失败不改写终态。 未部署、未推送、未构建镜像;真实跨主机 SSH 链路仍未验证。
This commit is contained in:
@@ -114,6 +114,8 @@ func main() {
|
||||
runErr = runSnapshotPush(opts)
|
||||
case "snapshot-fetch":
|
||||
runErr = runSnapshotFetch(opts)
|
||||
case "snapshot-verify":
|
||||
runErr = runSnapshotVerify(opts)
|
||||
default:
|
||||
usage()
|
||||
os.Exit(2)
|
||||
@@ -140,6 +142,7 @@ func usage() {
|
||||
version manifest is the commit point; repeated import is idempotent)
|
||||
snapshot-push send one sealed snapshot to the cloud release executor (verify on both sides)
|
||||
snapshot-fetch bring a cloud-held snapshot back into this archive (verified)
|
||||
snapshot-verify re-hash every part of one snapshot (used before reusing a remote copy)
|
||||
|
||||
Flags (defaults target the local WKNFull test stack):
|
||||
-source-app WKNFull-app container whose env describes the source
|
||||
@@ -1269,3 +1272,25 @@ func openHandoff(opts options) (*libraryhandoff.Handoff, error) {
|
||||
}
|
||||
return libraryhandoff.New(config, nil)
|
||||
}
|
||||
|
||||
// runSnapshotVerify 对一份快照做整版校验(逐部件重算字节),用于"复用前先证明字节还在"。
|
||||
func runSnapshotVerify(opts options) error {
|
||||
if opts.snapshot == "" {
|
||||
return errors.New("snapshot-verify 需要 -snapshot <id>")
|
||||
}
|
||||
archive, err := openArchive(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer archive.Close()
|
||||
manifest, err := archive.Load(opts.snapshot)
|
||||
if err != nil {
|
||||
return fmt.Errorf("快照校验失败:%w", err)
|
||||
}
|
||||
printJSON(map[string]any{
|
||||
"verified": true, "snapshot": opts.snapshot, "scope": manifest.Scope,
|
||||
"tenant_id": manifest.TenantID, "knowledge_base_id": manifest.KnowledgeBaseID,
|
||||
"parts": len(manifest.Parts),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
+109
-32
@@ -20,6 +20,13 @@ import (
|
||||
// release-executor 永不注册它——云端没有源归档,也没有回本机的通道。
|
||||
const libraryHandoffJobType = "library.snapshot.handoff"
|
||||
|
||||
// 回传分页:每次 100 条、最多 20 页(单轮最多核对 2000 份引用),
|
||||
// 游标按 (created_at, snapshot_id) 推进,下一轮从最新处重新开始。
|
||||
const (
|
||||
pullPageSize = 100
|
||||
pullMaxPages = 20
|
||||
)
|
||||
|
||||
// libraryHandoffStage 是搬运在作业阶段表里的名字(页面能看出卡在搬运还是发布)。
|
||||
const libraryHandoffStage = "handoff"
|
||||
|
||||
@@ -76,15 +83,12 @@ func runLibraryHandoff(ctx context.Context, store *postgresstore.Store, config a
|
||||
return failLibraryHandoff(ctx, store, payload, "业务作业已终态,不再搬运")
|
||||
}
|
||||
|
||||
knowledgeBase := config.LibraryProductionInternalKB
|
||||
if payload.Scope == "external" {
|
||||
knowledgeBase = config.LibraryProductionExternalKB
|
||||
// 期望身份来自**独立注入的绑定** + 版本台账的登记类型,绝不来自快照自报:
|
||||
// 封存快照的清单写的是源 tenant/KB,目标知识库本来就不是它(云测试验收用专用 KB)。
|
||||
want, identityErr := expectedSnapshotIdentity(ctx, store, config, payload.Scope, payload.TargetSnapshotID)
|
||||
if identityErr != nil {
|
||||
return failLibraryHandoff(ctx, store, payload, "无法确定快照的可信归属,拒绝搬运:"+identityErr.Error())
|
||||
}
|
||||
if config.LibraryProductionTenantID == 0 || knowledgeBase == "" {
|
||||
return failLibraryHandoff(ctx, store, payload, "目标身份未配置(租户/知识库),无法核对快照归属")
|
||||
}
|
||||
want := libraryhandoff.Identity{SnapshotID: payload.TargetSnapshotID, Scope: payload.Scope,
|
||||
TenantID: config.LibraryProductionTenantID, KnowledgeBaseID: knowledgeBase}
|
||||
|
||||
_ = store.UpdateLibraryStage(ctx, payload.LibraryJobID, libraryHandoffStage, "running", nil, nil, nil, nil,
|
||||
"正在把快照送到发布执行器并校验", now)
|
||||
@@ -105,16 +109,19 @@ func runLibraryHandoff(ctx context.Context, store *postgresstore.Store, config a
|
||||
if marshalErr != nil {
|
||||
return failLibraryHandoff(ctx, store, payload, "无法构造发布作业载荷")
|
||||
}
|
||||
queueJob, enqueueErr := store.Enqueue(ctx, jobs.EnqueueRequest{
|
||||
// 投递与关联必须在同一事务里:分两步时云执行器可能已领取并开始维护,
|
||||
// 而第二步失败会让我们把作业标失败并声称"未维护"——那是说假话。
|
||||
queueJob, enqueueErr := store.EnqueueAndAttachLibraryJob(ctx, jobs.EnqueueRequest{
|
||||
ID: governance.QueueJobIDFor(payload.LibraryJobID), Type: payload.NextType, Payload: payloadRaw,
|
||||
AvailableAt: time.Now().UTC(), MaxAttempts: 1,
|
||||
IdempotencyKey: payload.NextType + ".queue:" + payload.LibraryJobID,
|
||||
}, time.Now().UTC())
|
||||
if enqueueErr != nil || queueJob == nil {
|
||||
return failLibraryHandoff(ctx, store, payload, "快照已在执行器就绪,但发布作业投递失败")
|
||||
}, payload.LibraryJobID, time.Now().UTC())
|
||||
if enqueueErr != nil {
|
||||
return failLibraryHandoff(ctx, store, payload, "发布作业投递或关联失败(两者同一事务,未产生半完成状态):"+enqueueErr.Error())
|
||||
}
|
||||
if attachErr := store.AttachLibraryQueueJob(ctx, payload.LibraryJobID, queueJob.ID, time.Now().UTC()); attachErr != nil {
|
||||
return failLibraryHandoff(ctx, store, payload, "发布作业已投递但无法关联业务作业")
|
||||
if queueJob == nil {
|
||||
// 幂等重放:业务作业已关联同一个队列作业,不重复投递、不改写状态。
|
||||
log.Printf("library handoff replay: release job already attached job=%s", payload.LibraryJobID)
|
||||
}
|
||||
detail := fmt.Sprintf("快照已在校验后送达执行器(parts=%d bytes=%d reused=%t)", evidence.Parts, evidence.Bytes, evidence.Reused)
|
||||
_ = store.UpdateLibraryStage(ctx, payload.LibraryJobID, libraryHandoffStage, "succeeded", nil, nil, nil, nil, detail, time.Now().UTC())
|
||||
@@ -125,8 +132,14 @@ func runLibraryHandoff(ctx context.Context, store *postgresstore.Store, config a
|
||||
|
||||
func failLibraryHandoff(ctx context.Context, store *postgresstore.Store, payload libraryHandoffPayload, message string) error {
|
||||
_ = store.UpdateLibraryStage(ctx, payload.LibraryJobID, libraryHandoffStage, "failed", nil, nil, nil, nil, message, time.Now().UTC())
|
||||
_ = store.AdvanceLibraryJob(ctx, payload.LibraryJobID, governance.LibraryJobFailed, libraryHandoffStage, message,
|
||||
"未进入维护窗口、未写任何知识;修正后重试", "", "", time.Now().UTC())
|
||||
// 只在业务作业仍处于非终态时写失败:重放一次失败出口不得把已经成功的作业改写成失败。
|
||||
changed, err := store.AdvanceLibraryJobIfActive(ctx, payload.LibraryJobID, governance.LibraryJobFailed,
|
||||
libraryHandoffStage, message, "未进入维护窗口、未写任何知识;修正后重试", "", "", time.Now().UTC())
|
||||
if err != nil {
|
||||
log.Printf("library handoff fail-advance error job=%s: %v", payload.LibraryJobID, err)
|
||||
} else if !changed {
|
||||
log.Printf("library handoff fail-advance skipped job=%s: 作业已是终态,不覆盖既有状态", payload.LibraryJobID)
|
||||
}
|
||||
return fmt.Errorf("%s", message)
|
||||
}
|
||||
|
||||
@@ -150,25 +163,41 @@ func runLibraryArchivePullLoop(ctx context.Context, store *postgresstore.Store,
|
||||
}
|
||||
defer archive.Close()
|
||||
for _, scope := range []string{"internal", "external"} {
|
||||
ids, listErr := store.LibraryJobSnapshots(ctx, scope, 50)
|
||||
if listErr != nil {
|
||||
report(fmt.Errorf("读不到 %s 的已完成作业快照:%w", scope, listErr))
|
||||
continue
|
||||
}
|
||||
for _, id := range ids {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return
|
||||
// 游标分页(不是"取最近 N 条"):第 51 条以后的预备份、失败作业留下的
|
||||
// 恢复基线同样必须能被枚举到,否则它们在本机永远读不回来。
|
||||
var afterCreated time.Time
|
||||
afterID := ""
|
||||
for page := 0; page < pullMaxPages; page++ {
|
||||
items, listErr := store.LibrarySnapshotCandidates(ctx, scope, afterCreated, afterID, pullPageSize)
|
||||
if listErr != nil {
|
||||
report(fmt.Errorf("读不到 %s 的快照引用:%w", scope, listErr))
|
||||
break
|
||||
}
|
||||
if _, loadErr := archive.LoadManifest(id); loadErr == nil {
|
||||
continue
|
||||
if len(items) == 0 {
|
||||
break
|
||||
}
|
||||
evidence, fetchErr := handoff.Fetch(ctx, id)
|
||||
if fetchErr != nil {
|
||||
report(fmt.Errorf("回传快照 %s 失败:%w", id, fetchErr))
|
||||
continue
|
||||
for _, item := range items {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return
|
||||
}
|
||||
// 用整版校验(不是只看清单):本地"只有清单、blob 已损坏"的版本必须被
|
||||
// 重新取回,否则它会永远停在不可读状态,而页面无法把它与"真的没有"区分。
|
||||
if _, loadErr := archive.Load(item.SnapshotID); loadErr == nil {
|
||||
continue
|
||||
}
|
||||
evidence, fetchErr := handoff.Fetch(ctx, item.SnapshotID)
|
||||
if fetchErr != nil {
|
||||
report(fmt.Errorf("回传快照 %s 失败:%w", item.SnapshotID, fetchErr))
|
||||
continue
|
||||
}
|
||||
log.Printf("library archive pull snapshot=%s scope=%s parts=%d bytes=%d reused=%t",
|
||||
evidence.Snapshot, evidence.Scope, evidence.Parts, evidence.Bytes, evidence.Reused)
|
||||
}
|
||||
last := items[len(items)-1]
|
||||
afterCreated, afterID = last.CreatedAt, last.SnapshotID
|
||||
if len(items) < pullPageSize {
|
||||
break
|
||||
}
|
||||
log.Printf("library archive pull snapshot=%s scope=%s parts=%d bytes=%d reused=%t",
|
||||
evidence.Snapshot, evidence.Scope, evidence.Parts, evidence.Bytes, evidence.Reused)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -184,3 +213,51 @@ func runLibraryArchivePullLoop(ctx context.Context, store *postgresstore.Store,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// expectedSnapshotIdentity 决定"这份快照的清单身份应该等于谁"。
|
||||
//
|
||||
// 两类快照的身份来源不同,混用会把合法的跨 KB 发布判成非法(或反过来放行错数据):
|
||||
// - 封存版本(test_sealed):清单里是**源**的 tenant/KB → 用部署注入的源绑定核对;
|
||||
// - 目标状态版本(预备份/生效/恢复):清单里是**目标**的 tenant/KB → 用目标绑定核对。
|
||||
//
|
||||
// 没有登记过版本、或两类同时出现,一律拒绝:来源不明的快照不允许进入发布链路。
|
||||
func expectedSnapshotIdentity(ctx context.Context, store *postgresstore.Store, config appconfig.Config,
|
||||
scope, snapshotID string) (libraryhandoff.Identity, error) {
|
||||
kinds, err := store.LibrarySnapshotKinds(ctx, scope, snapshotID)
|
||||
if err != nil {
|
||||
return libraryhandoff.Identity{}, err
|
||||
}
|
||||
if len(kinds) == 0 {
|
||||
return libraryhandoff.Identity{}, fmt.Errorf("快照 %s 在该 scope 下没有登记过任何版本", snapshotID)
|
||||
}
|
||||
sealedState, targetState := false, false
|
||||
for _, kind := range kinds {
|
||||
switch kind {
|
||||
case string(governance.LibraryVersionTestSealed):
|
||||
sealedState = true
|
||||
case string(governance.LibraryVersionProductionPrebackup), string(governance.LibraryVersionProductionEffective),
|
||||
string(governance.LibraryVersionRecoveryVerified):
|
||||
targetState = true
|
||||
}
|
||||
}
|
||||
if sealedState && targetState {
|
||||
return libraryhandoff.Identity{}, fmt.Errorf("快照 %s 同时登记为封存版本与目标状态版本:身份不一致", snapshotID)
|
||||
}
|
||||
tenant, knowledgeBase := config.LibrarySourceTenantID, config.LibrarySourceInternalKB
|
||||
label := "源绑定"
|
||||
if !sealedState {
|
||||
tenant, knowledgeBase = config.LibraryProductionTenantID, config.LibraryProductionInternalKB
|
||||
label = "目标绑定"
|
||||
}
|
||||
if scope == "external" {
|
||||
if sealedState {
|
||||
knowledgeBase = config.LibrarySourceExternalKB
|
||||
} else {
|
||||
knowledgeBase = config.LibraryProductionExternalKB
|
||||
}
|
||||
}
|
||||
if tenant == 0 || knowledgeBase == "" {
|
||||
return libraryhandoff.Identity{}, fmt.Errorf("未配置%s(tenant/知识库),无法核对快照身份", label)
|
||||
}
|
||||
return libraryhandoff.Identity{SnapshotID: snapshotID, Scope: scope, TenantID: tenant, KnowledgeBaseID: knowledgeBase}, nil
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/libraryhandoff"
|
||||
"knowledge-governance/internal/librarysnapshot"
|
||||
@@ -38,17 +37,12 @@ func TestHandoffChainGatesReleaseJobOnVerifiedTransfer(t *testing.T) {
|
||||
t.Fatalf("migrate fixture db: %v", err)
|
||||
}
|
||||
store := postgresstore.NewStore(pool)
|
||||
// 隔离 fixture 库会被反复使用:先把上一次运行残留的在飞 fixture 作业收掉,
|
||||
// 否则 (scope,kind) 的唯一索引会把本次新建当成冲突。只动 handoff fixture 的行。
|
||||
if _, err := pool.Exec(ctx, `UPDATE library_jobs SET state='failed', finished_at=now(), updated_at=now()
|
||||
WHERE id LIKE 'libsync-handoff-%' AND state IN ('pending','running')`); err != nil {
|
||||
t.Fatalf("reset fixture jobs: %v", err)
|
||||
}
|
||||
resetFixtureJobs(t, pool)
|
||||
fixture := newHandoffFixture(t)
|
||||
config := appconfig.Config{LibraryProductionTenantID: fixture.tenant,
|
||||
LibraryProductionInternalKB: fixture.kb, LibraryProductionExternalKB: fixture.kb}
|
||||
config := appconfigFixture(fixture)
|
||||
|
||||
snapshot := fixture.seal(t)
|
||||
recordSealedVersion(t, store, snapshot, "internal")
|
||||
job := createFixtureJob(t, store, "internal", snapshot)
|
||||
payload := libraryHandoffPayload{LibraryJobID: job.ID, Scope: "internal",
|
||||
TargetSnapshotID: snapshot, NextType: librarySyncJobType}
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/governance"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
)
|
||||
|
||||
func fixturePool(t *testing.T) (*pgxpool.Pool, *postgresstore.Store) {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("KG_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("KG_TEST_DSN 未设置:跳过隔离 fixture 库测试")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
if err := postgresstore.ApplyMigrations(ctx, pool); err != nil {
|
||||
t.Fatalf("migrate fixture db: %v", err)
|
||||
}
|
||||
return pool, postgresstore.NewStore(pool)
|
||||
}
|
||||
|
||||
// appconfigFixture 让**源绑定与目标绑定不同**:封存快照的身份是源 KB,发布目标是专用验收 KB。
|
||||
// 这正是云测试方案 A 的真实形状(源 WKNFull,目标 a8e9c8ad/2e980686 专用 KB)。
|
||||
func appconfigFixture(f handoffFixture) appconfig.Config {
|
||||
return appconfig.Config{
|
||||
LibrarySourceTenantID: f.tenant, LibrarySourceInternalKB: f.kb, LibrarySourceExternalKB: f.kb,
|
||||
LibraryProductionTenantID: f.tenant, LibraryProductionInternalKB: "kb-target-acceptance",
|
||||
LibraryProductionExternalKB: "kb-target-acceptance",
|
||||
}
|
||||
}
|
||||
|
||||
// recordSealedVersion 登记"这份快照是一次封存的产物",搬运据此判定它应按源绑定核对。
|
||||
func recordSealedVersion(t *testing.T, store *postgresstore.Store, snapshot, scope string) {
|
||||
t.Helper()
|
||||
if err := store.RecordLibraryVersion(context.Background(), governance.LibraryVersion{
|
||||
ID: governance.LibraryVersionID(governance.LibraryVersionTestSealed, scope, snapshot),
|
||||
Scope: scope, Kind: governance.LibraryVersionTestSealed, SnapshotID: snapshot,
|
||||
SourceJobID: "fixture-capture", CreatedAt: time.Now().UTC(),
|
||||
}); err != nil {
|
||||
t.Fatalf("record sealed version: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// resetFixtureJobs 收掉上一个用例留下的在飞 fixture 作业:隔离库会被反复使用,
|
||||
// (scope,kind) 的唯一索引会把新建当成冲突。只动 handoff fixture 的行。
|
||||
func resetFixtureJobs(t *testing.T, pool *pgxpool.Pool) {
|
||||
t.Helper()
|
||||
if _, err := pool.Exec(context.Background(),
|
||||
`UPDATE library_jobs SET state='failed', finished_at=now(), updated_at=now()
|
||||
WHERE id LIKE 'libsync-handoff-%' AND state IN ('pending','running')`); err != nil {
|
||||
t.Fatalf("reset fixture jobs: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func digestOf(label string) string {
|
||||
sum := sha256.Sum256([]byte(label))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// 回传枚举必须覆盖"第 51 条以后"和"失败作业留下的预备份",不能用固定 LIMIT 50 截断。
|
||||
func TestSnapshotCandidatesPaginateBeyondFiftyAndIncludeRecoveryBackups(t *testing.T) {
|
||||
pool, store := fixturePool(t)
|
||||
ctx := context.Background()
|
||||
scope := "internal"
|
||||
if _, err := pool.Exec(ctx, `DELETE FROM library_jobs WHERE id LIKE 'pagination-%'`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
base := time.Now().UTC().Add(-time.Hour)
|
||||
want := map[string]bool{}
|
||||
for index := 0; index < 55; index++ {
|
||||
id := "pagination-ok-" + digestOf(string(rune('a'+index%26)) + time.Duration(index).String())[:10] + string(rune('a'+index%26)) + string(rune('a'+index/26))
|
||||
snapshot := digestOf("snapshot-" + id)
|
||||
want[snapshot] = true
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO library_jobs (id, scope, kind, state, snapshot_id, created_at, updated_at, request_digest, operation_id, attempt_epoch, idempotency_key)
|
||||
VALUES ($1,$2,'sync','succeeded',$3,$4,$4,'d','op',1,$1)
|
||||
ON CONFLICT (id) DO UPDATE SET snapshot_id=EXCLUDED.snapshot_id, state='succeeded'`,
|
||||
id, scope, snapshot, base.Add(time.Duration(index)*time.Second)); err != nil {
|
||||
t.Fatalf("insert fixture job %d: %v", index, err)
|
||||
}
|
||||
// 最新的 50 条之外还有恢复基线:一个失败作业留下的预备份。
|
||||
}
|
||||
failedSnapshot := digestOf("failed-prebackup")
|
||||
want[failedSnapshot] = true
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO library_jobs (id, scope, kind, state, snapshot_id, recovery, created_at, updated_at, request_digest, operation_id, attempt_epoch, idempotency_key)
|
||||
VALUES ('pagination-failed',$1,'sync','failed',$2,'按预备份恢复',$3,$3,'d','op',1,'pagination-failed')
|
||||
ON CONFLICT (id) DO UPDATE SET snapshot_id=EXCLUDED.snapshot_id, state='failed'`,
|
||||
scope, failedSnapshot, base.Add(2*time.Hour)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
seen := map[string]bool{}
|
||||
var afterCreated time.Time
|
||||
afterID := ""
|
||||
for page := 0; page < 20; page++ {
|
||||
items, err := store.LibrarySnapshotCandidates(ctx, scope, afterCreated, afterID, 7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(items) == 0 {
|
||||
break
|
||||
}
|
||||
for _, item := range items {
|
||||
if seen[item.SnapshotID] {
|
||||
t.Fatalf("pagination repeated snapshot %s", item.SnapshotID)
|
||||
}
|
||||
seen[item.SnapshotID] = true
|
||||
}
|
||||
last := items[len(items)-1]
|
||||
afterCreated, afterID = last.CreatedAt, last.SnapshotID
|
||||
if len(items) < 7 {
|
||||
break
|
||||
}
|
||||
}
|
||||
for snapshot := range want {
|
||||
if !seen[snapshot] {
|
||||
t.Fatalf("pagination missed snapshot %s(第51条之后或失败作业的预备份被截断)", snapshot)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 重放:已成功的作业不允许被一次迟到的搬运失败改写成 failed;重复搬运不重复投递。
|
||||
func TestHandoffReplayDoesNotOverwriteTerminalStateOrDuplicateReleaseJob(t *testing.T) {
|
||||
pool, store := fixturePool(t)
|
||||
ctx := context.Background()
|
||||
resetFixtureJobs(t, pool)
|
||||
fixture := newHandoffFixture(t)
|
||||
config := appconfigFixture(fixture)
|
||||
snapshot := fixture.seal(t)
|
||||
recordSealedVersion(t, store, snapshot, "internal")
|
||||
job := createFixtureJob(t, store, "internal", snapshot)
|
||||
payload := libraryHandoffPayload{LibraryJobID: job.ID, Scope: "internal",
|
||||
TargetSnapshotID: snapshot, NextType: librarySyncJobType}
|
||||
if err := runLibraryHandoff(ctx, store, config, fixture.handoff, payload); err != nil {
|
||||
t.Fatalf("first handoff: %v", err)
|
||||
}
|
||||
// 幂等重放:不得产生第二个队列作业,也不得改状态。
|
||||
if err := runLibraryHandoff(ctx, store, config, fixture.handoff, payload); err != nil {
|
||||
t.Fatalf("replayed handoff: %v", err)
|
||||
}
|
||||
var queued int
|
||||
if err := pool.QueryRow(ctx, `SELECT count(*) FROM jobs WHERE id LIKE $1`,
|
||||
governance.QueueJobIDFor(job.ID)+"%").Scan(&queued); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if queued != 1 {
|
||||
t.Fatalf("replay produced %d release queue jobs", queued)
|
||||
}
|
||||
// 迟到的失败重放:作业已成功,不允许被改写。
|
||||
if _, err := pool.Exec(ctx, `UPDATE library_jobs SET state='succeeded', error='', recovery='' WHERE id=$1`, job.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bad := libraryHandoffPayload{LibraryJobID: job.ID, Scope: "internal",
|
||||
TargetSnapshotID: fixture.unknownSnapshotID(), NextType: librarySyncJobType}
|
||||
_ = runLibraryHandoff(ctx, store, config, fixture.handoff, bad)
|
||||
after, err := store.LibraryJob(ctx, job.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after.State != governance.LibraryJobSucceeded {
|
||||
t.Fatalf("a late failure replay overwrote state to %s", after.State)
|
||||
}
|
||||
}
|
||||
@@ -108,7 +108,13 @@ type Config struct {
|
||||
LibrarySourceProject string
|
||||
// LibrarySourceApp 是封存源容器名(agent -source-app)。project 可能同名而源接线
|
||||
// 不同,所以配了就一起绑定进"期望执行器身份"。
|
||||
LibrarySourceApp string
|
||||
LibrarySourceApp string
|
||||
// 源绑定的知识库身份:封存快照的清单里写的是**源**的 tenant/KB,和目标知识库
|
||||
// 本来就不是同一个(云测试验收用专用 KB)。搬运必须拿这份独立注入的源绑定去核对,
|
||||
// 不能拿目标绑定去对,更不能信快照自报。
|
||||
LibrarySourceTenantID uint64
|
||||
LibrarySourceInternalKB string
|
||||
LibrarySourceExternalKB string
|
||||
LibraryTargetProject string
|
||||
LibraryTargetWriters []string
|
||||
LibraryTargetNonWriters map[string]string
|
||||
@@ -153,6 +159,11 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
return Config{}, errors.New("LIBRARY_PRODUCTION_TENANT_ID must be a positive integer")
|
||||
}
|
||||
tenantID := uint64(tenantID64)
|
||||
sourceTenant64, err := positiveInt64OrDefault(strings.TrimSpace(getenv("LIBRARY_SOURCE_TENANT_ID")), 0)
|
||||
if err != nil {
|
||||
return Config{}, errors.New("LIBRARY_SOURCE_TENANT_ID must be a positive integer")
|
||||
}
|
||||
sourceTenantID := uint64(sourceTenant64)
|
||||
embeddingDimension64, err := positiveInt64OrDefault(strings.TrimSpace(getenv("LIBRARY_EMBEDDING_DIMENSION")), 1024)
|
||||
if err != nil {
|
||||
return Config{}, errors.New("LIBRARY_EMBEDDING_DIMENSION must be a positive integer")
|
||||
@@ -217,6 +228,9 @@ func Load(getenv func(string) string) (Config, error) {
|
||||
LibrarySourceInstance: strings.TrimSpace(getenv("LIBRARY_SOURCE_INSTANCE")),
|
||||
LibrarySourceProject: strings.TrimSpace(getenv("LIBRARY_SOURCE_PROJECT")),
|
||||
LibrarySourceApp: strings.TrimSpace(getenv("LIBRARY_SOURCE_APP")),
|
||||
LibrarySourceTenantID: uint64(sourceTenantID),
|
||||
LibrarySourceInternalKB: strings.TrimSpace(getenv("LIBRARY_SOURCE_KB_INTERNAL")),
|
||||
LibrarySourceExternalKB: strings.TrimSpace(getenv("LIBRARY_SOURCE_KB_EXTERNAL")),
|
||||
LibraryTargetProject: strings.TrimSpace(getenv("LIBRARY_TARGET_PROJECT")),
|
||||
LibraryTargetWriters: splitList(getenv("LIBRARY_TARGET_WRITERS")),
|
||||
LibraryTargetNonWriters: splitDeclarations(getenv("LIBRARY_TARGET_NON_WRITERS")),
|
||||
|
||||
@@ -127,6 +127,9 @@ type Remote interface {
|
||||
RemoveBundle(ctx context.Context, name string) error
|
||||
RunLibraryctl(ctx context.Context, args ...string) ([]byte, error)
|
||||
ReadVersionManifest(ctx context.Context, id string) ([]byte, error)
|
||||
// VerifySnapshot 要求远端对这份快照做**整版**校验(逐部件重算字节),
|
||||
// 复用一份已有清单前必须通过它:清单存在不等于字节还在。
|
||||
VerifySnapshot(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
// Handoff 是搬运的执行者(一套实现,两个方向)。
|
||||
@@ -320,7 +323,8 @@ func (h *Handoff) Fetch(ctx context.Context, id string) (Evidence, error) {
|
||||
if written > h.config.MaxBundleBytes {
|
||||
return Evidence{}, errors.New("回传 bundle 超过上限,拒绝导入")
|
||||
}
|
||||
manifest, err := archive.Unpack(localBundle, id)
|
||||
// 读回的是权威云端副本:本地同名 blob 字节不符按损坏修复(普通导入仍默认拒绝)。
|
||||
manifest, err := archive.UnpackWithOptions(localBundle, id, librarysnapshot.UnpackOptions{RepairCorruptBlobs: true})
|
||||
if err != nil {
|
||||
return Evidence{}, fmt.Errorf("回传快照校验失败(截断/篡改/缺部件):%w", err)
|
||||
}
|
||||
@@ -349,6 +353,11 @@ func (h *Handoff) remoteEvidence(ctx context.Context, want Identity) (Evidence,
|
||||
if err := matchesIdentity(manifest, want); err != nil {
|
||||
return Evidence{}, false, err
|
||||
}
|
||||
// 关键:清单存在只证明"这个名字有主",不证明 blob 还在、还对。
|
||||
// 复用前让远端整版重算一遍,缺失/篡改必须在这里就失败(尚未入发布队列)。
|
||||
if err := h.remote.VerifySnapshot(ctx, want.SnapshotID); err != nil {
|
||||
return Evidence{}, false, fmt.Errorf("执行器侧已有清单但字节校验失败,拒绝复用:%w", err)
|
||||
}
|
||||
return Evidence{Snapshot: want.SnapshotID, Scope: manifest.Scope, TenantID: manifest.TenantID,
|
||||
KnowledgeBase: manifest.KnowledgeBaseID, Parts: len(manifest.Parts),
|
||||
Bytes: manifestBytes(manifest), Reused: true, VerifiedAt: h.now().UTC()}, true, nil
|
||||
@@ -520,6 +529,11 @@ func (r *sshRemote) RunLibraryctl(ctx context.Context, args ...string) ([]byte,
|
||||
return []byte(out.String()), nil
|
||||
}
|
||||
|
||||
func (r *sshRemote) VerifySnapshot(ctx context.Context, id string) error {
|
||||
_, err := r.RunLibraryctl(ctx, "snapshot-verify", "-archive", r.config.RemoteArchive, "-snapshot", id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *sshRemote) ReadVersionManifest(ctx context.Context, id string) ([]byte, error) {
|
||||
path := filepath.Join(r.config.RemoteArchive, "versions", id+".json")
|
||||
var out strings.Builder
|
||||
@@ -622,6 +636,11 @@ func (r *localRemote) RunLibraryctl(ctx context.Context, args ...string) ([]byte
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (r *localRemote) VerifySnapshot(ctx context.Context, id string) error {
|
||||
_, err := r.RunLibraryctl(ctx, "snapshot-verify", "-archive", r.config.RemoteArchive, "-snapshot", id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *localRemote) ReadVersionManifest(ctx context.Context, id string) ([]byte, error) {
|
||||
path := filepath.Join(r.config.RemoteArchive, "versions", id+".json")
|
||||
raw, err := os.ReadFile(path)
|
||||
|
||||
@@ -351,6 +351,109 @@ func (errorRemote) RemoveBundle(context.Context, string) error { return errors.N
|
||||
func (errorRemote) RunLibraryctl(context.Context, ...string) ([]byte, error) {
|
||||
return nil, errors.New("network down")
|
||||
}
|
||||
func (errorRemote) VerifySnapshot(context.Context, string) error { return errors.New("network down") }
|
||||
func (errorRemote) ReadVersionManifest(context.Context, string) ([]byte, error) {
|
||||
return nil, errors.New("network down")
|
||||
}
|
||||
|
||||
// 已有清单但字节坏了:Push 的复用路径必须整版校验,不能只看清单摘要就宣布可用。
|
||||
func TestPushRefusesToReuseWhenRemoteBytesAreGoneOrTampered(t *testing.T) {
|
||||
sourceRoot, source := newArchive(t)
|
||||
id := seal(t, source)
|
||||
up := newFixture(t, sourceRoot)
|
||||
pusher, err := New(up.cfg, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := Identity{SnapshotID: id, Scope: "internal", TenantID: fixtureTenant, KnowledgeBaseID: fixtureKB}
|
||||
if _, err := pusher.Push(context.Background(), want); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
blobs, err := os.ReadDir(filepath.Join(up.remoteA, "blobs"))
|
||||
if err != nil || len(blobs) == 0 {
|
||||
t.Fatalf("remote blobs = %v %v", blobs, err)
|
||||
}
|
||||
// 清单不动、只把 blob 偷走:清单摘要仍然自证,但字节已经不在。
|
||||
remoteBlob := filepath.Join(up.remoteA, "blobs", blobs[0].Name())
|
||||
original, err := os.ReadFile(remoteBlob)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Remove(remoteBlob); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pusher.Push(context.Background(), want); err == nil {
|
||||
t.Fatal("Push() reused a remote copy whose blobs are missing")
|
||||
}
|
||||
// 同名不同内容同样必须被拒绝。
|
||||
if err := os.WriteFile(remoteBlob, append(original, 'x'), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pusher.Push(context.Background(), want); err == nil {
|
||||
t.Fatal("Push() reused a remote copy with tampered bytes")
|
||||
}
|
||||
}
|
||||
|
||||
// 跨租户 / 错误 scope:期望身份与清单不一致一律拒绝(身份只能来自可信绑定)。
|
||||
func TestPushRejectsCrossTenantAndWrongScope(t *testing.T) {
|
||||
sourceRoot, source := newArchive(t)
|
||||
id := seal(t, source)
|
||||
up := newFixture(t, sourceRoot)
|
||||
pusher, err := New(up.cfg, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
crossTenant := Identity{SnapshotID: id, Scope: "internal", TenantID: fixtureTenant + 1, KnowledgeBaseID: fixtureKB}
|
||||
if _, err := pusher.Push(context.Background(), crossTenant); err == nil {
|
||||
t.Fatal("Push() accepted a snapshot from another tenant")
|
||||
}
|
||||
wrongScope := Identity{SnapshotID: id, Scope: "external", TenantID: fixtureTenant, KnowledgeBaseID: fixtureKB}
|
||||
if _, err := pusher.Push(context.Background(), wrongScope); err == nil {
|
||||
t.Fatal("Push() accepted a snapshot sealed for another scope")
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(up.remoteA, "versions", id+".json")); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatal("rejected pushes left a version on the executor")
|
||||
}
|
||||
}
|
||||
|
||||
// 本地副本损坏(清单在、blob 坏):Fetch 必须能修复,而不是永远报"已存在不同字节"。
|
||||
func TestFetchRepairsCorruptLocalCopy(t *testing.T) {
|
||||
sourceRoot, source := newArchive(t)
|
||||
id := seal(t, source)
|
||||
up := newFixture(t, sourceRoot)
|
||||
pusher, err := New(up.cfg, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := pusher.Push(context.Background(), Identity{SnapshotID: id, Scope: "internal",
|
||||
TenantID: fixtureTenant, KnowledgeBaseID: fixtureKB}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
localRoot, _ := newArchive(t)
|
||||
fetcher, err := New(withLocalArchive(t, up, localRoot), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := fetcher.Fetch(context.Background(), id); err != nil {
|
||||
t.Fatalf("first fetch: %v", err)
|
||||
}
|
||||
blobs, err := os.ReadDir(filepath.Join(localRoot, "blobs"))
|
||||
if err != nil || len(blobs) == 0 {
|
||||
t.Fatalf("local blobs = %v %v", blobs, err)
|
||||
}
|
||||
victim := filepath.Join(localRoot, "blobs", blobs[0].Name())
|
||||
if err := os.WriteFile(victim, []byte("corrupt"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := fetcher.Fetch(context.Background(), id); err != nil {
|
||||
t.Fatalf("Fetch() could not repair a corrupt local copy: %v", err)
|
||||
}
|
||||
archive, err := librarysnapshot.Open(localRoot, 1024*1024)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer archive.Close()
|
||||
if _, err := archive.Load(id); err != nil {
|
||||
t.Fatalf("repaired snapshot still does not verify: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -136,7 +136,19 @@ func (a *Archive) Pack(id, outPath string) (BundleInfo, error) {
|
||||
// 不会留下"看起来存在但缺字节"的版本。
|
||||
//
|
||||
// 幂等:同一份包重复导入成功;名字相同内容不同的 blob 或清单直接拒绝。
|
||||
// UnpackOptions 控制"本地已有同名 blob 但字节不符"时的行为。
|
||||
//
|
||||
// 默认拒绝(同 ID 异内容一律当身份冲突处理)。只有"从权威云端副本读回"这一条路径
|
||||
// 显式打开修复:那时同名 blob 字节不符只能是本地损坏,拒绝会让这份版本永远不可读。
|
||||
type UnpackOptions struct {
|
||||
RepairCorruptBlobs bool
|
||||
}
|
||||
|
||||
func (a *Archive) Unpack(bundlePath, expectID string) (Manifest, error) {
|
||||
return a.UnpackWithOptions(bundlePath, expectID, UnpackOptions{})
|
||||
}
|
||||
|
||||
func (a *Archive) UnpackWithOptions(bundlePath, expectID string, options UnpackOptions) (Manifest, error) {
|
||||
if expectID != "" && !validDigest(expectID) {
|
||||
return Manifest{}, errors.New("invalid expected snapshot ID")
|
||||
}
|
||||
@@ -217,7 +229,7 @@ func (a *Archive) Unpack(bundlePath, expectID string) (Manifest, error) {
|
||||
if received[name] {
|
||||
return Manifest{}, fmt.Errorf("bundle repeats blob %s", name)
|
||||
}
|
||||
if err := a.installBlob(reader, part); err != nil {
|
||||
if err := a.installBlob(reader, part, options); err != nil {
|
||||
return Manifest{}, err
|
||||
}
|
||||
received[name] = true
|
||||
@@ -251,14 +263,21 @@ func (a *Archive) Unpack(bundlePath, expectID string) (Manifest, error) {
|
||||
|
||||
// installBlob 把一个 blob 从包里写到 blobs/<sha256>。
|
||||
// 已存在时必须字节一致,否则拒绝——同名不同内容是身份冲突,不是"覆盖一下"。
|
||||
func (a *Archive) installBlob(body io.Reader, part Part) error {
|
||||
func (a *Archive) installBlob(body io.Reader, part Part, options UnpackOptions) error {
|
||||
if _, err := a.blobs.Lstat(part.SHA256); err == nil {
|
||||
if err := a.verify(part); err != nil {
|
||||
if verifyErr := a.verify(part); verifyErr == nil {
|
||||
// 已有且一致:仍然读完包里的字节,否则 tar 流会错位。
|
||||
_, err := io.CopyN(io.Discard, body, part.Bytes)
|
||||
return err
|
||||
}
|
||||
if !options.RepairCorruptBlobs {
|
||||
return fmt.Errorf("archive already holds different bytes for blob %s", part.SHA256)
|
||||
}
|
||||
// 已有且一致:仍然读完包里的字节,否则 tar 流会错位。
|
||||
_, err := io.CopyN(io.Discard, body, part.Bytes)
|
||||
return err
|
||||
// 名字就是内容摘要:同名而字节不符只可能是**本地损坏**。显式修复时删掉坏文件,
|
||||
// 按包内字节原子重建;否则"本地坏块"永远无法自愈,页面会一直读成不可用。
|
||||
if removeErr := a.blobs.Remove(part.SHA256); removeErr != nil && !errors.Is(removeErr, os.ErrNotExist) {
|
||||
return fmt.Errorf("repair corrupt blob %s: %w", part.SHA256, removeErr)
|
||||
}
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return errors.New("archive blob lookup failed")
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
"knowledge-governance/internal/jobs"
|
||||
)
|
||||
|
||||
// 整库作业与版本:队列(jobs)负责租约重试,本文件负责业务身份、阶段与结果。
|
||||
@@ -793,30 +794,166 @@ FROM library_release_authorizations WHERE scope=$1 ORDER BY created_at DESC, id
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
// LibraryJobSnapshots 返回该 scope 最近完成作业引用过的快照 ID(预备份/目标快照)。
|
||||
// LibrarySnapshotKinds 返回这份快照在该 scope 下登记过的版本类型。
|
||||
//
|
||||
// 只用于"云端产生的版本回传到本机"这一件事:本机缺哪些、要不要取,按这些 ID 逐个核对。
|
||||
// 只读、按作业终态过滤,不推断内容是否可用——是否可用由归档自身的 Load 决定。
|
||||
func (s *Store) LibraryJobSnapshots(ctx context.Context, scope string, limit int) ([]string, error) {
|
||||
if scope == "" || limit <= 0 || limit > 500 {
|
||||
return nil, errors.New("library job snapshots requires scope and a bounded limit")
|
||||
// 用途是判定"这份快照的清单身份应该等于谁":封存版本(test_sealed)的清单写的是
|
||||
// **源**的 tenant/KB;预备份/生效/恢复版本写的是**目标**的 tenant/KB。没有登记过
|
||||
// 就说明来源不明,调用方必须拒绝搬运(不能信快照自报)。
|
||||
func (s *Store) LibrarySnapshotKinds(ctx context.Context, scope, snapshotID string) ([]string, error) {
|
||||
if scope == "" || snapshotID == "" {
|
||||
return nil, errors.New("snapshot kinds requires scope and snapshot")
|
||||
}
|
||||
rows, err := s.db.Query(ctx, `
|
||||
SELECT DISTINCT snapshot_id FROM library_jobs
|
||||
WHERE scope=$1 AND state='succeeded' AND snapshot_id <> ''
|
||||
ORDER BY snapshot_id
|
||||
LIMIT $2`, scope, limit)
|
||||
rows, err := s.db.Query(ctx, `SELECT DISTINCT kind FROM library_versions WHERE scope=$1 AND snapshot_id=$2`, scope, snapshotID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list library job snapshots: %w", err)
|
||||
return nil, fmt.Errorf("read snapshot provenance: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
ids := make([]string, 0, limit)
|
||||
kinds := make([]string, 0, 4)
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
var kind string
|
||||
if err := rows.Scan(&kind); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
kinds = append(kinds, kind)
|
||||
}
|
||||
return ids, rows.Err()
|
||||
return kinds, rows.Err()
|
||||
}
|
||||
|
||||
// SnapshotCandidate 是一份"本机可能需要有"的快照,以及它最近一次被引用的时间。
|
||||
// CreatedAt 同时充当分页游标:按 (created_at, snapshot_id) 倒序,跨页不重不漏。
|
||||
type SnapshotCandidate struct {
|
||||
SnapshotID string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// LibrarySnapshotCandidates 枚举该 scope 下**被引用过**的快照(分页,游标不是 OFFSET)。
|
||||
//
|
||||
// 为什么不能"只取最近 N 条成功作业的 snapshot_id":那会把回传永久卡在最早的 50 条上,
|
||||
// 第 51 条以后的预备份、以及失败/待恢复作业留下的**恢复所需**预备份再也读不回来。
|
||||
// 所以这里合并三处权威引用:
|
||||
// - library_versions.snapshot_id(版本台账,含封存/预备份/生效/恢复);
|
||||
// - library_jobs.snapshot_id(作业自己留下的预备份,含失败与 needs_restore);
|
||||
// - library_jobs.target_snapshot_id(发布/恢复的输入快照,历史恢复要靠它寻址)。
|
||||
//
|
||||
// 游标语义:afterCreated/afterID 为空表示第一页;返回值不足 limit 即到底。
|
||||
func (s *Store) LibrarySnapshotCandidates(ctx context.Context, scope string, afterCreated time.Time,
|
||||
afterID string, limit int) ([]SnapshotCandidate, error) {
|
||||
if scope == "" || limit <= 0 || limit > 500 {
|
||||
return nil, errors.New("snapshot candidates requires scope and a bounded limit")
|
||||
}
|
||||
var cursor any
|
||||
if !afterCreated.IsZero() {
|
||||
cursor = afterCreated.UTC()
|
||||
}
|
||||
rows, err := s.db.Query(ctx, `
|
||||
WITH referenced AS (
|
||||
SELECT snapshot_id, created_at FROM library_versions WHERE scope=$1 AND snapshot_id <> ''
|
||||
UNION ALL
|
||||
SELECT snapshot_id, created_at FROM library_jobs WHERE scope=$1 AND snapshot_id <> ''
|
||||
UNION ALL
|
||||
SELECT target_snapshot_id, created_at FROM library_jobs WHERE scope=$1 AND target_snapshot_id <> ''
|
||||
), grouped AS (
|
||||
SELECT snapshot_id, MAX(created_at) AS created_at FROM referenced GROUP BY snapshot_id
|
||||
)
|
||||
SELECT snapshot_id, created_at FROM grouped
|
||||
WHERE $2::timestamptz IS NULL
|
||||
OR created_at < $2::timestamptz
|
||||
OR (created_at = $2::timestamptz AND snapshot_id < $3)
|
||||
ORDER BY created_at DESC, snapshot_id DESC
|
||||
LIMIT $4`, scope, cursor, afterID, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list snapshot candidates: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
items := make([]SnapshotCandidate, 0, limit)
|
||||
for rows.Next() {
|
||||
var item SnapshotCandidate
|
||||
if err := rows.Scan(&item.SnapshotID, &item.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return items, rows.Err()
|
||||
}
|
||||
|
||||
// EnqueueAndAttachLibraryJob 在**一个事务**里完成"投递发布队列作业 + 关联到业务作业"。
|
||||
//
|
||||
// 为什么要事务:分两步时,第一步成功后云执行器可能立刻领取并开始维护,第二步失败却把
|
||||
// 业务作业标失败并声称"未进入维护窗口"——那就是对页面和审计说谎。这里要么两者都成功,
|
||||
// 要么都不发生。并发/重放时:业务作业已关联同一队列作业 ⇒ 幂等成功;关联到别的队列作业
|
||||
// ⇒ 拒绝;业务作业已终态 ⇒ 拒绝(不许把已成功的作业改写)。
|
||||
func (s *Store) EnqueueAndAttachLibraryJob(ctx context.Context, request jobs.EnqueueRequest,
|
||||
libraryJobID string, now time.Time) (*jobs.Job, error) {
|
||||
if libraryJobID == "" || request.ID == "" || request.Type == "" {
|
||||
return nil, errors.New("enqueue and attach requires library job, queue id and type")
|
||||
}
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
var state string
|
||||
var attached *string
|
||||
if err := tx.QueryRow(ctx, `SELECT state, queue_job_id FROM library_jobs WHERE id=$1 FOR UPDATE`,
|
||||
libraryJobID).Scan(&state, &attached); err != nil {
|
||||
return nil, fmt.Errorf("lock library job for enqueue: %w", err)
|
||||
}
|
||||
if state != "pending" && state != "running" {
|
||||
return nil, fmt.Errorf("业务作业已是终态(%s):拒绝投递发布队列作业", state)
|
||||
}
|
||||
if attached != nil && *attached != "" {
|
||||
if *attached == request.ID {
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, nil // 幂等:同一个队列作业已经关联好了
|
||||
}
|
||||
return nil, fmt.Errorf("业务作业已关联另一个队列作业(%s):拒绝替换", *attached)
|
||||
}
|
||||
job, err := scanJob(tx.QueryRow(ctx, enqueueJobSQL, request.ID, request.Type, request.Payload,
|
||||
request.Priority, request.AvailableAt, request.MaxAttempts, request.IdempotencyKey, now))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("enqueue release job: %w", err)
|
||||
}
|
||||
tag, err := tx.Exec(ctx, `UPDATE library_jobs SET queue_job_id=$2, updated_at=$3
|
||||
WHERE id=$1 AND state IN ('pending','running')`, libraryJobID, request.ID, now.UTC())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("attach library queue job: %w", err)
|
||||
}
|
||||
if tag.RowsAffected() != 1 {
|
||||
return nil, errors.New("attach library queue job: 业务作业状态已变化,回滚本次投递")
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return job, nil
|
||||
}
|
||||
|
||||
// AdvanceLibraryJobIfActive 只在业务作业仍处于非终态时推进状态。
|
||||
//
|
||||
// 为什么需要:`AdvanceLibraryJob` 没有状态守卫,重放一次失败出口会把已经 succeeded/running
|
||||
// 的作业改写成 failed——页面上"已成功"的发布会突然变红,且恢复责任文案是错的。
|
||||
// 返回 changed=false 表示"没有改写",调用方必须据此说清"没有覆盖既存状态"。
|
||||
func (s *Store) AdvanceLibraryJobIfActive(ctx context.Context, jobID string, state governance.LibraryJobState,
|
||||
stage, message, recovery, snapshotID, targetSnapshotID string, now time.Time) (bool, error) {
|
||||
finished := any(nil)
|
||||
if state == governance.LibraryJobSucceeded || state == governance.LibraryJobFailed || state == governance.LibraryJobCancelled {
|
||||
finished = now.UTC()
|
||||
}
|
||||
tag, err := s.db.Exec(ctx, `
|
||||
UPDATE library_jobs SET
|
||||
state=$2,
|
||||
stage = CASE WHEN $3='' THEN stage ELSE $3 END,
|
||||
error = CASE WHEN $4='' THEN error ELSE $4 END,
|
||||
recovery = CASE WHEN $5='' THEN recovery ELSE $5 END,
|
||||
snapshot_id = CASE WHEN $6='' THEN snapshot_id ELSE $6 END,
|
||||
target_snapshot_id = CASE WHEN $7='' THEN target_snapshot_id ELSE $7 END,
|
||||
updated_at=$8,
|
||||
finished_at=COALESCE($9, finished_at)
|
||||
WHERE id=$1 AND state IN ('pending','running')`,
|
||||
jobID, string(state), stage, message, recovery, snapshotID, targetSnapshotID, now.UTC(), finished)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("advance library job: %w", err)
|
||||
}
|
||||
return tag.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
@@ -272,6 +272,16 @@
|
||||
"package": "knowledge-governance/cmd/worker",
|
||||
"test": "TestHandoffChainGatesReleaseJobOnVerifiedTransfer",
|
||||
"reason": "需要隔离的 fixture PostgreSQL(KG_TEST_DSN)与真实 libraryctl 二进制(KG_TEST_LIBRARYCTL);CI 不注入测试库。本机已用独立测试库容器实跑通过,未运行不等于通过"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/cmd/worker",
|
||||
"test": "TestSnapshotCandidatesPaginateBeyondFiftyAndIncludeRecoveryBackups",
|
||||
"reason": "需要隔离的 fixture PostgreSQL(KG_TEST_DSN)才能验证 >50 条分页与失败作业预备份的枚举;CI 不注入测试库。本机已用独立测试库容器实跑通过(go test ./cmd/worker -run 'TestHandoff|TestSnapshotCandidates' → ok),未运行不等于通过"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/cmd/worker",
|
||||
"test": "TestHandoffReplayDoesNotOverwriteTerminalStateOrDuplicateReleaseJob",
|
||||
"reason": "需要隔离的 fixture PostgreSQL 与真实 libraryctl 二进制,验证幂等重放不重复投递、迟到失败不改写终态;CI 不注入测试库。本机已实跑通过,未运行不等于通过"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user