fix(library): 按目标身份隔离版本授权与执行历史
build / build (push) Successful in 1m47s

This commit is contained in:
姚章浩
2026-10-31 02:15:15 +08:00
parent 323f9ae502
commit 7ab2eb1ccf
15 changed files with 473 additions and 72 deletions
+11
View File
@@ -1,5 +1,16 @@
# Changelog
## 开发快照(发布目标历史隔离)
### Fixed
- 切换发布目标后,不再把旧实例的当前生效版本、预备份、恢复候选和授权当成新实例事实;当前指针按目标与对内/对外范围独立保存,旧作业不可被新目标接管。
- 本机隧道与云端直连共用逻辑目标身份,源封存保持可见;历史记录及证据保留,不自动归属新目标。
### Changed
- **破坏性**:治理库迁移 077 增加目标身份,须停旧消费者后升级;已有目标绑定证据时禁止直接降级。[升级与回退边界](docs/library-target-identity.md)。
## 开发快照(云端归档清单读回)
### Fixed
+2 -1
View File
@@ -176,6 +176,7 @@ func run(ctx context.Context, getenv func(string) string) error {
if handoffErr != nil {
return fmt.Errorf("快照搬运接线无效: %w", handoffErr)
}
log.Printf("library target evidence identity=%s", config.LibraryTargetIdentity())
handler, err := httpapi.NewHandler(httpapi.Config{
LibraryHandoffEnabled: handoffConfigured,
QAAI: qaopsai.NewFromEnvironment(pool, getenv, config.DatabaseURL),
@@ -189,7 +190,7 @@ func run(ctx context.Context, getenv func(string) string) error {
QAOpsTenantKey: qaSettings.TenantKey,
QAOpsEnabled: qaSettings.Enabled,
QAOpsProblem: qaSettings.Problem,
Store: postgresstore.NewStore(pool),
Store: postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity()),
Monitor: monitorProvider,
InternalRoutingKnowledgeBaseID: config.InternalRoutingKnowledgeBaseID,
ExternalRoutingKnowledgeBaseID: config.ExternalRoutingKnowledgeBaseID,
@@ -0,0 +1,41 @@
package main
import (
"context"
"encoding/json"
"strings"
"testing"
"time"
"knowledge-governance/internal/appconfig"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
)
func TestLibraryReleaseRejectsAnotherTargetBeforeMaintenance(t *testing.T) {
legacy, pool := openLedgerStore(t)
config := appconfig.Config{LibraryTargetInstance: "new-cloud-target"}
current := legacy.WithLibraryTarget(config.LibraryTargetIdentity())
ctx := context.Background()
now := time.Now()
job, _, err := legacy.CreateLibraryJob(ctx, governance.LibraryJob{ID: "old-target-job", Scope: "internal", Kind: governance.LibraryJobSync, IdempotencyKey: "old-target-job", RequestDigest: "digest", QueueJobID: "queue-old", TargetSnapshotID: "snapshot"}, governance.SyncStages(), now)
if err != nil {
t.Fatal(err)
}
payload, _ := json.Marshal(libraryReleasePayload{LibraryJobID: job.ID, Scope: "internal", TargetSnapshotID: "snapshot"})
err = runLibraryRelease(ctx, current, config, jobs.Job{ID: "queue-old", Payload: payload}, governance.LibraryJobSync)
if err == nil || !strings.Contains(err.Error(), "拒绝在任何维护动作前继续") {
t.Fatalf("must reject at admission, not after opening a target: %v", err)
}
var attempts, locks int
if err := pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM library_attempts), (SELECT count(*) FROM library_instance_maintenance)`).Scan(&attempts, &locks); err != nil {
t.Fatal(err)
}
if attempts != 0 || locks != 0 {
t.Fatalf("foreign request caused side effects: attempts=%d locks=%d", attempts, locks)
}
got, err := legacy.LibraryJob(ctx, job.ID)
if err != nil || got.State != governance.LibraryJobPending {
t.Fatalf("old job was modified: %+v %v", got, err)
}
}
+2 -1
View File
@@ -142,7 +142,8 @@ func run(ctx context.Context, getenv func(string) string) error {
} else if len(pending) > 0 {
return fmt.Errorf("治理库 schema 落后(待应用迁移 %v):本角色不拥有 DDL,先由控制面进程完成迁移", pending)
}
store := postgresstore.NewStore(pool)
store := postgresstore.NewStore(pool).WithLibraryTarget(config.LibraryTargetIdentity())
log.Printf("library target evidence identity=%s", config.LibraryTargetIdentity())
// 启动先接管被中断的写作业(复用已持久化的预备份),再把剩下的孤儿判失败:
// 顺序反了会把可接管的作业先标失败,丢掉已完成的备份。
//
+31
View File
@@ -0,0 +1,31 @@
# 发布目标身份隔离与迁移 077
## 身份与可见性
API 与 worker 使用同一 `appconfig.Config.LibraryTargetIdentity`:实例、Compose 项目、数据库名、租户、对内/对外 KB、索引、对象存储 provider/endpoint/bucket 的 SHA-256。凭据、数据库连接的主机/端口、Docker socket、归档目录不参与,避免本机 SSH 转发与云端直连生成不同身份。
实例/项目是部署身份,不得把相同名字重新指给另一物理部署;执行器现有实时身份/拓扑准入仍必须通过。本变更不是跨环境凭据授权边界,也不代替目标健康与维护验证。
- 当前版本按 `(scope, target_id)` 保存;某目标的新版本不顶替另一目标的 current 或 superseded 元数据。
- 预备份、历史生效、恢复候选、复用来源和回传引用都只取当前目标证据。
- 作业、授权、意图持久绑定目标。切换目标后旧作业不可被新执行器准入、续作或自动接管;旧授权不生效。
- `test_sealed` 和 `seal` 是源侧事实,保持可见;切换发布目标不删除或冒充源封存。
- 原有事件/作业/授权/意图保留,新增列为空表示“目标归属未证明”,不推断回填。它们不成为任何新目标的运行证据;归档保护仍跨全部历史,避免清理器误删旧恢复材料。
- 目标绑定是部署级(包含两个 KB);修改其中任一 KB 会建立新的证据上下文。旧记录保存在治理库,不在新目标的发布列表中混显。需要恢复旧目标时必须确认真实配置及证据归属,禁止把空身份批量改成当前身份。
## 升级顺序
1. 保持写门关闭,检查无在飞发布/恢复/封存、维护锁和未结束执行代次;不能仅凭一次空队列采样。
2. 备份治理库并在隔离库实际恢复,保留旧运行镜像、Compose 配置链与版本证据摘要。
3. 停止旧 API/worker/云发布消费者后迁移,防止旧的 `ON CONFLICT(scope)` 与新主键并行使用。**只迁移治理库,不修改 WeKnora schema。**
4. 先启动新 API 完成迁移 077,再启动使用同一配置身份的新 worker;读回版本、schema、身份配置、健康与禁写门。
5. 页面应显示目标尚无权威版本,不能沿用旧本机演练的“已生效/0 变化”。真实空基线仍由目标逐表只读探测回答。
6. 在独立目标备份/恢复和正式授权条件满足后执行实际发布及恢复,再确认新 target_id 下的 current。
## 回退边界
077 的 down 只允许没有任何非空目标绑定记录时执行,避免把已分离的历史合并回一个 scope。产生新记录后不要直接降级;使用经过恢复验证的控制面备份,先核对目标内容与在飞窗口,不能只回旧镜像。源封存、历史事件和快照均不得为了通过验收而清空。
## 验证范围
真实 PostgreSQL 用例覆盖旧无归属 current、新目标 A/B current 相互独立、外目标预备份/授权/作业/意图不可复用、跨目标事件 ID 冲突拒绝、源封存可共享,以及真实 worker 入口在维护前拒绝旧目标作业。默认 CI 无测试库时显式跳过这部分;本机必须另行实跑。单测通过不代表真实发布/恢复或页面验收已完成。
+41
View File
@@ -0,0 +1,41 @@
package appconfig
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"github.com/jackc/pgx/v5/pgxpool"
)
// LibraryTargetIdentity binds control-plane evidence to the logical deployment
// and data scope, not credentials or the caller's transport. API may use an SSH
// forward while the executor uses the private DB address. Instance/project are
// deployment identities, verified independently by executor admission; reusing
// them for another physical deployment is not a supported target switch.
func (c Config) LibraryTargetIdentity() string {
database := "unconfigured"
if c.LibraryProductionDatabaseURL != "" {
if parsed, err := pgxpool.ParseConfig(c.LibraryProductionDatabaseURL); err == nil {
database = parsed.ConnConfig.Database
} else {
database = "invalid"
}
}
raw, _ := json.Marshal(struct {
Instance string
Project string
Database string
Tenant uint64
InternalKB string
ExternalKB string
Index string
Provider string
ObjectEndpoint string
Bucket string
}{c.LibraryTargetInstance, c.LibraryTargetProject, database, c.LibraryProductionTenantID,
c.LibraryProductionInternalKB, c.LibraryProductionExternalKB, c.LibraryProductionIndex,
c.LibraryProductionS3Provider, c.LibraryProductionS3Endpoint, c.LibraryProductionS3Bucket})
sum := sha256.Sum256(raw)
return hex.EncodeToString(sum[:])
}
+48
View File
@@ -0,0 +1,48 @@
package appconfig
import "testing"
func identityForTest(c Config) string {
return c.LibraryTargetIdentity()
}
func TestLibraryTargetIdentityIgnoresTransportButBindsData(t *testing.T) {
a := Config{LibraryTargetInstance: "cloud-test", LibraryTargetProject: "weknora-test",
LibraryProductionDatabaseURL: "postgres://local@127.0.0.1:5433/target_db", LibraryProductionTenantID: 10000,
LibraryProductionInternalKB: "internal-a", LibraryProductionExternalKB: "external-a",
LibraryProductionIndex: "index-a", LibraryProductionS3Bucket: "bucket-a", LibraryProductionS3Provider: "s3", LibraryProductionS3Endpoint: "https://objects.example"}
want := identityForTest(a)
if want == "" {
t.Fatal("live services must never bind the empty legacy namespace")
}
transport := a
transport.LibraryProductionDatabaseURL = "postgres://remote@database:5432/target_db"
transport.LibraryTargetDockerSocket = "/other/docker.sock"
transport.LibraryArchiveRoot = "/other/archive"
if got := identityForTest(transport); got != want {
t.Fatal("SSH routing must not change logical identity")
}
cases := map[string]func(*Config){
"instance": func(c *Config) { c.LibraryTargetInstance = "other" },
"project": func(c *Config) { c.LibraryTargetProject = "other" },
"database": func(c *Config) { c.LibraryProductionDatabaseURL = "postgres://local@127.0.0.1:5433/other_db" },
"tenant": func(c *Config) { c.LibraryProductionTenantID = 20000 },
"internal": func(c *Config) { c.LibraryProductionInternalKB = "other" },
"external": func(c *Config) { c.LibraryProductionExternalKB = "other" },
"index": func(c *Config) { c.LibraryProductionIndex = "other" },
"bucket": func(c *Config) { c.LibraryProductionS3Bucket = "other" },
"object_endpoint": func(c *Config) { c.LibraryProductionS3Endpoint = "https://other.example" },
}
for name, change := range cases {
t.Run(name, func(t *testing.T) {
c := a
change(&c)
if identityForTest(c) == want {
t.Fatal("changed data target reused old identity")
}
})
}
if identityForTest(Config{}) == "" {
t.Fatal("unconfigured service must not adopt unbound historical evidence")
}
}
+69 -52
View File
@@ -30,12 +30,12 @@ func (s *Store) CreateLibraryJob(ctx context.Context, job governance.LibraryJob,
var id string
err = s.db.QueryRow(ctx, `
INSERT INTO library_jobs (id, scope, kind, state, stage, idempotency_key, request_digest, request,
queue_job_id, snapshot_id, target_snapshot_id, actor, error, recovery, operation_id, created_at, updated_at)
VALUES ($1,$2,$3,'pending','',$4,$5,$6,$7,$8,$9,$10,'','',$11,$12,$12)
queue_job_id, snapshot_id, target_snapshot_id, actor, error, recovery, operation_id, created_at, updated_at, target_id)
VALUES ($1,$2,$3,'pending','',$4,$5,$6,$7,$8,$9,$10,'','',$11,$12,$12,$13)
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING id`,
job.ID, job.Scope, string(job.Kind), job.IdempotencyKey, request, rawRequest,
job.QueueJobID, job.SnapshotID, job.TargetSnapshotID, job.Actor, job.OperationID, now.UTC()).Scan(&id)
job.QueueJobID, job.SnapshotID, job.TargetSnapshotID, job.Actor, job.OperationID, now.UTC(), s.libraryTargetID).Scan(&id)
if err != nil {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
@@ -87,7 +87,7 @@ func (s *Store) LibraryJob(ctx context.Context, id string) (governance.LibraryJo
if err := s.db.QueryRow(ctx, `
SELECT id, scope, kind, state, stage, idempotency_key, request_digest, queue_job_id, snapshot_id,
target_snapshot_id, actor, error, recovery, operation_id, attempt_epoch, created_at, updated_at, finished_at
FROM library_jobs WHERE id=$1`, id).Scan(&job.ID, &job.Scope, &kind, &state, &job.Stage, &job.IdempotencyKey,
FROM library_jobs WHERE id=$1 AND (kind='seal' OR target_id=$2)`, id, s.libraryTargetID).Scan(&job.ID, &job.Scope, &kind, &state, &job.Stage, &job.IdempotencyKey,
&job.RequestDigest, &job.QueueJobID, &job.SnapshotID, &job.TargetSnapshotID, &job.Actor, &job.Error,
&job.Recovery, &job.OperationID, &job.AttemptEpoch, &job.CreatedAt, &job.UpdatedAt, &finished); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
@@ -123,16 +123,16 @@ func (s *Store) LibraryReuseSources(ctx context.Context, scope string, limit int
rows, err := s.db.Query(ctx, `
SELECT j.id, j.target_snapshot_id, 'sync', coalesce(j.finished_at, j.updated_at)
FROM library_jobs j
WHERE j.scope=$1 AND j.kind='sync' AND j.state='succeeded' AND coalesce(j.target_snapshot_id,'')<>''
WHERE j.scope=$1 AND j.target_id=$3 AND j.kind='sync' AND j.state='succeeded' AND coalesce(j.target_snapshot_id,'')<>''
AND EXISTS (SELECT 1 FROM library_versions v
WHERE v.scope=j.scope AND v.kind='production_effective'
WHERE v.scope=j.scope AND v.target_id=j.target_id AND v.kind='production_effective'
AND v.snapshot_id=j.target_snapshot_id AND v.source_job_id=j.id)
UNION ALL
SELECT coalesce(v.source_job_id,''), v.snapshot_id, 'prebackup', v.created_at
FROM library_versions v
WHERE v.scope=$1 AND v.kind='production_prebackup' AND coalesce(v.snapshot_id,'')<>''
WHERE v.scope=$1 AND v.target_id=$3 AND v.kind='production_prebackup' AND coalesce(v.snapshot_id,'')<>''
ORDER BY 4 DESC
LIMIT $2`, scope, limit)
LIMIT $2`, scope, limit, s.libraryTargetID)
if err != nil {
return nil, fmt.Errorf("load library reuse sources: %w", err)
}
@@ -173,7 +173,7 @@ func (s *Store) ListLibraryJobs(ctx context.Context, scope string, limit int) ([
if limit < 1 || limit > 50 {
return nil, errors.New("library job list limit out of range")
}
rows, err := s.db.Query(ctx, `SELECT id FROM library_jobs WHERE scope=$1 ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit)
rows, err := s.db.Query(ctx, `SELECT id FROM library_jobs WHERE scope=$1 AND (kind='seal' OR target_id=$3) ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit, s.libraryTargetID)
if err != nil {
return nil, fmt.Errorf("list library jobs: %w", err)
}
@@ -273,6 +273,10 @@ WHERE id=$1`, jobID, string(state), stage, message, recovery, snapshotID, target
// 更早登记的事实不能把指针拉回历史,旧 epoch 在写边界就被守卫拒绝(见 guard)。
// - 生效/恢复事件才动指针;预备份/封存只追加事件。
func (s *Store) RecordLibraryVersion(ctx context.Context, version governance.LibraryVersion) error {
targetID := s.libraryTargetID
if version.Kind == governance.LibraryVersionTestSealed {
targetID = ""
}
evidence, err := json.Marshal(version.Evidence)
if err != nil {
return fmt.Errorf("encode library version evidence: %w", err)
@@ -301,17 +305,25 @@ func (s *Store) RecordLibraryVersion(ctx context.Context, version governance.Lib
var inserted bool
err = tx.QueryRow(ctx, `
INSERT INTO library_versions (id, scope, kind, snapshot_id, version_label, source_job_id,
operation_id, attempt_epoch, evidence, created_by, created_at)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)
operation_id, attempt_epoch, evidence, created_by, created_at, target_id)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12)
ON CONFLICT (id) DO UPDATE
SET evidence = EXCLUDED.evidence || library_versions.evidence
WHERE library_versions.source_job_id = EXCLUDED.source_job_id
AND library_versions.operation_id = EXCLUDED.operation_id
AND library_versions.target_id = EXCLUDED.target_id
RETURNING (xmax = 0)`,
version.ID, version.Scope, string(version.Kind), version.SnapshotID, version.VersionLabel,
version.SourceJobID, version.OperationID, version.AttemptEpoch, evidence, version.CreatedBy,
version.CreatedAt.UTC()).Scan(&inserted)
version.CreatedAt.UTC(), targetID).Scan(&inserted)
if errors.Is(err, pgx.ErrNoRows) {
var existingTarget string
if loadErr := tx.QueryRow(ctx, `SELECT target_id FROM library_versions WHERE id=$1`, version.ID).Scan(&existingTarget); loadErr != nil {
return loadErr
}
if existingTarget != targetID {
return errors.New("library version identity belongs to another target")
}
// 同一身份已经存在、但归属是别的执行者/别的意图:不覆盖、不报错,也不推进 current。
inserted = false
err = nil
@@ -321,7 +333,7 @@ RETURNING (xmax = 0)`,
}
if version.Kind == governance.LibraryVersionProductionEffective || version.Kind == governance.LibraryVersionRecoveryVerified {
if err := advanceLibraryCurrent(ctx, tx, version, inserted); err != nil {
if err := advanceLibraryCurrent(ctx, tx, version, inserted, targetID); err != nil {
return err
}
}
@@ -338,7 +350,7 @@ RETURNING (xmax = 0)`,
// 恢复要不要能把 current 指回更早的**内容**?要,但它是通过**新的意图**(kind=recover,
// 创建于恢复时刻)做到的:内容更旧、意图更新,两者不矛盾。旧代次能不能写由 epoch
// 守卫回答(见 libraryFence),不由时间回答。
func advanceLibraryCurrent(ctx context.Context, tx pgx.Tx, version governance.LibraryVersion, inserted bool) error {
func advanceLibraryCurrent(ctx context.Context, tx pgx.Tx, version governance.LibraryVersion, inserted bool, targetID string) error {
orderAt := version.CreatedAt
if version.OperationID != "" {
var created *time.Time
@@ -358,8 +370,8 @@ func advanceLibraryCurrent(ctx context.Context, tx pgx.Tx, version governance.Li
if !inserted {
// 重放:事件已经在台账里。确认指针没有被别的更晚事实覆盖,否则只确认自己的历史。
var currentID string
err := tx.QueryRow(ctx, `SELECT version_id FROM library_current_versions WHERE scope=$1 FOR UPDATE`,
version.Scope).Scan(&currentID)
err := tx.QueryRow(ctx, `SELECT version_id FROM library_current_versions WHERE scope=$1 AND target_id=$2 FOR UPDATE`,
version.Scope, targetID).Scan(&currentID)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
@@ -369,21 +381,21 @@ func advanceLibraryCurrent(ctx context.Context, tx pgx.Tx, version governance.Li
return nil
}
tag, err := tx.Exec(ctx, `
INSERT INTO library_current_versions (scope, version_id, snapshot_id, operation_id, attempt_epoch, order_key, updated_at)
VALUES ($1,$2,$3,$4,$5,$6,$7)
ON CONFLICT (scope) DO UPDATE SET
INSERT INTO library_current_versions (scope, version_id, snapshot_id, operation_id, attempt_epoch, order_key, updated_at, target_id)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)
ON CONFLICT (scope, target_id) DO UPDATE SET
version_id=EXCLUDED.version_id, snapshot_id=EXCLUDED.snapshot_id,
operation_id=EXCLUDED.operation_id, attempt_epoch=EXCLUDED.attempt_epoch,
order_key=EXCLUDED.order_key, updated_at=EXCLUDED.updated_at
WHERE EXCLUDED.order_key > library_current_versions.order_key`,
version.Scope, version.ID, version.SnapshotID, version.OperationID, version.AttemptEpoch, orderKey,
version.CreatedAt.UTC())
version.CreatedAt.UTC(), targetID)
if err != nil {
return fmt.Errorf("advance library current pointer: %w", err)
}
var currentID string
if err := tx.QueryRow(ctx, `SELECT version_id FROM library_current_versions WHERE scope=$1`,
version.Scope).Scan(&currentID); err != nil {
if err := tx.QueryRow(ctx, `SELECT version_id FROM library_current_versions WHERE scope=$1 AND target_id=$2`,
version.Scope, targetID).Scan(&currentID); err != nil {
return fmt.Errorf("read back library current pointer: %w", err)
}
if tag.RowsAffected() == 0 && currentID != version.ID {
@@ -394,8 +406,8 @@ WHERE EXCLUDED.order_key > library_current_versions.order_key`,
// 它跟着指针走:指针指向谁,谁就是未顶替的那一行。
if _, err := tx.Exec(ctx, `
UPDATE library_versions SET superseded_at = CASE WHEN id=$2 THEN NULL ELSE COALESCE(superseded_at, $3) END
WHERE scope=$1 AND kind IN ('production_effective','recovery_verified')`, version.Scope, currentID,
version.CreatedAt.UTC()); err != nil {
WHERE scope=$1 AND target_id=$4 AND kind IN ('production_effective','recovery_verified')`, version.Scope, currentID,
version.CreatedAt.UTC(), targetID); err != nil {
return fmt.Errorf("refresh library version supersede metadata: %w", err)
}
return nil
@@ -417,7 +429,8 @@ WHERE lj.kind IN ('sync','restore','baseline')
-- 业务作业已被前一轮接管置为 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`)
AND lj.target_id=$1
ORDER BY lj.created_at`, s.libraryTargetID)
if err != nil {
return nil, fmt.Errorf("list interrupted library jobs: %w", err)
}
@@ -454,6 +467,9 @@ ORDER BY lj.created_at`)
// 条件更新:只有 failed/cancelled 才允许置回 pending;终态时间与错误清零,
// 旧 attempt 行保留(历史不可变)。代次由 BeginLibraryAttempt 在 worker 起手时递增。
func (s *Store) PrepareLibraryJobResume(ctx context.Context, jobID string, now time.Time) (governance.LibraryJob, bool, error) {
if _, err := s.LibraryJob(ctx, jobID); err != nil {
return governance.LibraryJob{}, false, err
}
tx, err := s.db.Begin(ctx)
if err != nil {
return governance.LibraryJob{}, false, fmt.Errorf("prepare library job resume: %w", err)
@@ -512,8 +528,8 @@ WHERE id=$1 AND state IN ('running','retry','failed','pending')
// 然后各自跑一遍同一个窗口(F13)。租约仍有效时直接失败,让调用方跳过。
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')
AND (lease_owner='' OR lease_until IS NULL OR lease_until < $2)`, jobID, now.UTC())
WHERE id=$1 AND target_id=$3 AND state IN ('running','pending')
AND (lease_owner='' OR lease_until IS NULL OR lease_until < $2)`, jobID, now.UTC(), s.libraryTargetID)
if err != nil {
return false, fmt.Errorf("claim interrupted library job: %w", err)
}
@@ -540,19 +556,20 @@ SET state='failed', error='队列中已无对应作业,业务作业未收到
updated_at=$1, finished_at=$1
WHERE lj.state IN ('pending','running')
AND lj.kind = ANY($2)
AND (lj.kind='seal' OR lj.target_id=$3)
AND lj.queue_job_id <> ''
AND NOT EXISTS (
SELECT 1 FROM jobs AS j
WHERE j.id = lj.queue_job_id AND j.state IN ('pending','running','retry')
)`, now.UTC(), kinds); err != nil {
)`, now.UTC(), kinds, s.libraryTargetID); err != nil {
return 0, fmt.Errorf("reconcile library jobs: %w", err)
}
// 建了业务作业但队列投递没完成(queue_job_id 为空)超过 5 分钟,也是孤儿。
tag, err := s.db.Exec(ctx, `
UPDATE library_jobs
SET state='failed', error='队列投递未完成,作业从未开始', recovery='无需恢复来源;可直接重发', updated_at=$1, finished_at=$1
WHERE state IN ('pending','running') AND queue_job_id='' AND kind = ANY($3) AND created_at < $2`,
now.UTC(), now.Add(-5*time.Minute).UTC(), kinds)
WHERE state IN ('pending','running') AND queue_job_id='' AND kind = ANY($3) AND (kind='seal' OR target_id=$4) AND created_at < $2`,
now.UTC(), now.Add(-5*time.Minute).UTC(), kinds, s.libraryTargetID)
if err != nil {
return 0, fmt.Errorf("reconcile unattached library jobs: %w", err)
}
@@ -577,8 +594,8 @@ func (s *Store) LibraryVersionByRef(ctx context.Context, scope string, kind gove
rows, err := s.db.Query(ctx, `
SELECT id, scope, kind, snapshot_id, version_label, source_job_id, operation_id, attempt_epoch, evidence, created_by, created_at, superseded_at
FROM library_versions
WHERE scope=$1 AND kind=$2 AND source_job_id=$3 AND snapshot_id=$4
ORDER BY created_at DESC, id DESC LIMIT 2`, scope, string(kind), sourceJobID, snapshotID)
WHERE scope=$1 AND kind=$2 AND source_job_id=$3 AND snapshot_id=$4 AND (kind='test_sealed' OR target_id=$5)
ORDER BY created_at DESC, id DESC LIMIT 2`, scope, string(kind), sourceJobID, snapshotID, s.libraryTargetID)
if err != nil {
return governance.LibraryVersion{}, false, fmt.Errorf("load library version by ref: %w", err)
}
@@ -597,8 +614,8 @@ ORDER BY created_at DESC, id DESC LIMIT 2`, scope, string(kind), sourceJobID, sn
// 当成"没有记录"就会允许调用方覆盖别人的台账。
var owner string
err = s.db.QueryRow(ctx, `
SELECT source_job_id FROM library_versions WHERE scope=$1 AND kind=$2 AND snapshot_id=$3
ORDER BY created_at DESC LIMIT 1`, scope, string(kind), snapshotID).Scan(&owner)
SELECT source_job_id FROM library_versions WHERE scope=$1 AND kind=$2 AND snapshot_id=$3 AND (kind='test_sealed' OR target_id=$4)
ORDER BY created_at DESC LIMIT 1`, scope, string(kind), snapshotID, s.libraryTargetID).Scan(&owner)
if errors.Is(err, pgx.ErrNoRows) {
return governance.LibraryVersion{}, false, nil
}
@@ -639,7 +656,7 @@ func (s *Store) LibraryVersions(ctx context.Context, scope string, limit int) ([
}
rows, err := s.db.Query(ctx, `
SELECT id, scope, kind, snapshot_id, version_label, source_job_id, operation_id, attempt_epoch, evidence, created_by, created_at, superseded_at
FROM library_versions WHERE scope=$1 ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit)
FROM library_versions WHERE scope=$1 AND (kind='test_sealed' OR target_id=$3) ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit, s.libraryTargetID)
if err != nil {
return nil, fmt.Errorf("list library versions: %w", err)
}
@@ -654,7 +671,7 @@ FROM library_versions WHERE scope=$1 ORDER BY created_at DESC, id DESC LIMIT $2`
// 任何"最近 N 条",接管/基线/闸口就会把"已生效"读成"没有生效"。
// · 不能靠扫 library_versions.kind='production_effective' 挑未顶替行——事件不可变,
// "谁是当前"是指针的事实,不是事件行的可变字段(F02)。
// · 指针每 scope 至多一行(主键),所以这里不需要"挑一条看起来对的"。
// · 指针每 (scope, target_id) 至多一行,历史归属不明的空身份不归新目标。
//
// 指针可能指向 production_effective,也可能指向 recovery_verified(按预备份恢复后
// 的当前内容身份)——调用方只能用它回答"当前是什么内容",不能假设它是一次成功发布。
@@ -666,7 +683,7 @@ func (s *Store) LibraryCurrentVersion(ctx context.Context, scope string) (govern
SELECT v.id, v.scope, v.kind, v.snapshot_id, v.version_label, v.source_job_id, v.operation_id, v.attempt_epoch,
v.evidence, v.created_by, v.created_at, v.superseded_at
FROM library_current_versions c JOIN library_versions v ON v.id = c.version_id
WHERE c.scope=$1`, scope)
WHERE c.scope=$1 AND c.target_id=$2 AND v.target_id=c.target_id`, scope, s.libraryTargetID)
if err != nil {
return governance.LibraryVersion{}, false, fmt.Errorf("load current library version: %w", err)
}
@@ -697,8 +714,8 @@ func (s *Store) LibraryVersionOfSnapshot(ctx context.Context, scope string,
rows, err := s.db.Query(ctx, `
SELECT id, scope, kind, snapshot_id, version_label, source_job_id, operation_id, attempt_epoch, evidence, created_by, created_at, superseded_at
FROM library_versions
WHERE scope=$1 AND kind=$2 AND snapshot_id=$3
ORDER BY created_at DESC, id DESC LIMIT 2`, scope, string(kind), snapshotID)
WHERE scope=$1 AND kind=$2 AND snapshot_id=$3 AND (kind='test_sealed' OR target_id=$4)
ORDER BY created_at DESC, id DESC LIMIT 2`, scope, string(kind), snapshotID, s.libraryTargetID)
if err != nil {
return governance.LibraryVersion{}, false, fmt.Errorf("load library version of snapshot: %w", err)
}
@@ -732,9 +749,9 @@ func (s *Store) CreateLibraryAuthorization(ctx context.Context, item governance.
return errors.New("invalid library release authorization")
}
_, err := s.db.Exec(ctx, `
INSERT INTO library_release_authorizations (id, scope, snapshot_id, params_digest, authorized_by, expires_at, created_at)
VALUES ($1,$2,$3,$4,$5,$6,$7)`,
item.ID, item.Scope, item.SnapshotID, item.ParamsDigest, item.AuthorizedBy, item.ExpiresAt.UTC(), item.CreatedAt.UTC())
INSERT INTO library_release_authorizations (id, scope, snapshot_id, params_digest, authorized_by, expires_at, created_at, target_id)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)`,
item.ID, item.Scope, item.SnapshotID, item.ParamsDigest, item.AuthorizedBy, item.ExpiresAt.UTC(), item.CreatedAt.UTC(), s.libraryTargetID)
if err != nil {
return fmt.Errorf("create library release authorization: %w", err)
}
@@ -748,9 +765,9 @@ func (s *Store) ActiveLibraryAuthorization(ctx context.Context, scope, snapshotI
err := s.db.QueryRow(ctx, `
SELECT id, scope, snapshot_id, params_digest, authorized_by, expires_at, revoked_at, created_at
FROM library_release_authorizations
WHERE scope=$1 AND snapshot_id=$2 AND params_digest=$3 AND revoked_at IS NULL AND expires_at > $4
WHERE scope=$1 AND snapshot_id=$2 AND params_digest=$3 AND target_id=$5 AND revoked_at IS NULL AND expires_at > $4
ORDER BY expires_at DESC, created_at DESC
LIMIT 1`, scope, snapshotID, paramsDigest, now.UTC()).Scan(&item.ID, &item.Scope, &item.SnapshotID,
LIMIT 1`, scope, snapshotID, paramsDigest, now.UTC(), s.libraryTargetID).Scan(&item.ID, &item.Scope, &item.SnapshotID,
&item.ParamsDigest, &item.AuthorizedBy, &item.ExpiresAt, &item.RevokedAt, &item.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return governance.LibraryReleaseAuthorization{}, false, nil
@@ -762,7 +779,7 @@ LIMIT 1`, scope, snapshotID, paramsDigest, now.UTC()).Scan(&item.ID, &item.Scope
}
func (s *Store) RevokeLibraryAuthorization(ctx context.Context, id string, now time.Time) error {
tag, err := s.db.Exec(ctx, `UPDATE library_release_authorizations SET revoked_at=$2 WHERE id=$1 AND revoked_at IS NULL`, id, now.UTC())
tag, err := s.db.Exec(ctx, `UPDATE library_release_authorizations SET revoked_at=$2 WHERE id=$1 AND target_id=$3 AND revoked_at IS NULL`, id, now.UTC(), s.libraryTargetID)
if err != nil {
return fmt.Errorf("revoke library authorization: %w", err)
}
@@ -778,7 +795,7 @@ func (s *Store) LibraryAuthorizations(ctx context.Context, scope string, limit i
}
rows, err := s.db.Query(ctx, `
SELECT id, scope, snapshot_id, params_digest, authorized_by, expires_at, revoked_at, created_at
FROM library_release_authorizations WHERE scope=$1 ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit)
FROM library_release_authorizations WHERE scope=$1 AND target_id=$3 ORDER BY created_at DESC, id DESC LIMIT $2`, scope, limit, s.libraryTargetID)
if err != nil {
return nil, fmt.Errorf("list library authorizations: %w", err)
}
@@ -806,7 +823,7 @@ func (s *Store) LibraryVersionsBySnapshot(ctx context.Context, scope, snapshotID
}
rows, err := s.db.Query(ctx, `
SELECT id, scope, kind, snapshot_id, source_job_id, COALESCE(evidence, '{}'::jsonb), created_at
FROM library_versions WHERE scope=$1 AND snapshot_id=$2 ORDER BY created_at`, scope, snapshotID)
FROM library_versions WHERE scope=$1 AND snapshot_id=$2 AND (kind='test_sealed' OR target_id=$3) ORDER BY created_at`, scope, snapshotID, s.libraryTargetID)
if err != nil {
return nil, fmt.Errorf("read snapshot versions: %w", err)
}
@@ -859,7 +876,7 @@ func (s *Store) LibrarySnapshotKinds(ctx context.Context, scope, snapshotID stri
if scope == "" || snapshotID == "" {
return nil, errors.New("snapshot kinds requires scope and snapshot")
}
rows, err := s.db.Query(ctx, `SELECT DISTINCT kind FROM library_versions WHERE scope=$1 AND snapshot_id=$2`, scope, snapshotID)
rows, err := s.db.Query(ctx, `SELECT DISTINCT kind FROM library_versions WHERE scope=$1 AND snapshot_id=$2 AND (kind='test_sealed' OR target_id=$3)`, scope, snapshotID, s.libraryTargetID)
if err != nil {
return nil, fmt.Errorf("read snapshot provenance: %w", err)
}
@@ -903,11 +920,11 @@ func (s *Store) LibrarySnapshotCandidates(ctx context.Context, scope string, aft
}
rows, err := s.db.Query(ctx, `
WITH referenced AS (
SELECT snapshot_id, created_at FROM library_versions WHERE scope=$1 AND snapshot_id <> ''
SELECT snapshot_id, created_at FROM library_versions WHERE scope=$1 AND (kind='test_sealed' OR target_id=$5) AND snapshot_id <> ''
UNION ALL
SELECT snapshot_id, created_at FROM library_jobs WHERE scope=$1 AND snapshot_id <> ''
SELECT snapshot_id, created_at FROM library_jobs WHERE scope=$1 AND (kind='seal' OR target_id=$5) AND snapshot_id <> ''
UNION ALL
SELECT target_snapshot_id, created_at FROM library_jobs WHERE scope=$1 AND target_snapshot_id <> ''
SELECT target_snapshot_id, created_at FROM library_jobs WHERE scope=$1 AND (kind='seal' OR target_id=$5) AND target_snapshot_id <> ''
), grouped AS (
SELECT snapshot_id, MAX(created_at) AS created_at FROM referenced GROUP BY snapshot_id
)
@@ -916,7 +933,7 @@ 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)
LIMIT $4`, scope, cursor, afterID, limit, s.libraryTargetID)
if err != nil {
return nil, fmt.Errorf("list snapshot candidates: %w", err)
}
@@ -31,11 +31,11 @@ func (s *Store) EnsureLibraryOperation(ctx context.Context, op governance.Librar
}
var id string
err := s.db.QueryRow(ctx, `
INSERT INTO library_operations (id, scope, kind, target_snapshot_id, request_digest, operation_key, actor, created_at)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8)
INSERT INTO library_operations (id, scope, kind, target_snapshot_id, request_digest, operation_key, actor, created_at, target_id)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)
ON CONFLICT (scope, kind, operation_key) DO NOTHING
RETURNING id`, op.ID, op.Scope, string(op.Kind), op.TargetSnapshotID, op.RequestDigest,
op.OperationKey, op.Actor, op.CreatedAt.UTC()).Scan(&id)
op.OperationKey, op.Actor, op.CreatedAt.UTC(), s.libraryTargetID).Scan(&id)
if err == nil {
return op, true, nil
}
@@ -70,7 +70,7 @@ func (s *Store) LibraryOperation(ctx context.Context, id string) (governance.Lib
var kind string
err := s.db.QueryRow(ctx, `
SELECT id, scope, kind, target_snapshot_id, request_digest, operation_key, actor, created_at
FROM library_operations WHERE id=$1`, id).Scan(&op.ID, &op.Scope, &kind, &op.TargetSnapshotID,
FROM library_operations WHERE id=$1 AND (kind='seal' OR target_id=$2)`, id, s.libraryTargetID).Scan(&op.ID, &op.Scope, &kind, &op.TargetSnapshotID,
&op.RequestDigest, &op.OperationKey, &op.Actor, &op.CreatedAt)
if err != nil {
if errors.Is(err, pgx.ErrNoRows) {
@@ -0,0 +1,166 @@
package postgres
import (
"context"
"testing"
"time"
"knowledge-governance/internal/governance"
)
// Exercise the existing SQL against a real disposable PostgreSQL schema.
// Keep the unbound legacy namespace available to prove history survives
// while configured targets cannot adopt it.
func targetTestStore(s *Store, target string) *Store {
return s.WithLibraryTarget(target)
}
func TestLibraryTargetRejectsForeignEvidenceJobsAndGrants(t *testing.T) {
legacy, _ := openVersionStore(t)
a, b := legacy.WithLibraryTarget("target-a"), legacy.WithLibraryTarget("target-b")
ctx := context.Background()
now := time.Now().UTC()
recordPrebackup(t, ctx, a, "internal", "backup-job", "backup", now)
if err := a.RecordLibraryVersion(ctx, governance.LibraryVersion{ID: "source-seal", Scope: "internal", Kind: governance.LibraryVersionTestSealed, SnapshotID: "source", SourceJobID: "seal-job", CreatedAt: now}); err != nil {
t.Fatal(err)
}
checks := []struct {
name string
run func() bool
}{
{"version list", func() bool {
rows, err := b.LibraryVersions(ctx, "internal", 100)
return err == nil && len(rows) == 1 && rows[0].Kind == governance.LibraryVersionTestSealed
}},
{"exact backup", func() bool {
_, found, err := b.LibraryVersionByRef(ctx, "internal", governance.LibraryVersionProductionPrebackup, "backup-job", "backup")
return err == nil && !found
}},
{"snapshot version", func() bool {
_, found, err := b.LibraryVersionOfSnapshot(ctx, "internal", governance.LibraryVersionProductionPrebackup, "backup")
return err == nil && !found
}},
{"provenance", func() bool {
rows, err := b.LibraryVersionsBySnapshot(ctx, "internal", "backup")
return err == nil && len(rows) == 0
}},
{"snapshot kinds", func() bool {
rows, err := b.LibrarySnapshotKinds(ctx, "internal", "backup")
return err == nil && len(rows) == 0
}},
{"reuse sources", func() bool {
rows, err := b.LibraryReuseSources(ctx, "internal", 100)
return err == nil && len(rows) == 0
}},
{"handoff candidates", func() bool {
rows, err := b.LibrarySnapshotCandidates(ctx, "internal", time.Time{}, "", 100)
return err == nil && len(rows) == 1 && rows[0].SnapshotID == "source"
}},
}
for _, check := range checks {
t.Run(check.name, func(t *testing.T) {
if !check.run() {
t.Fatal("foreign target evidence was accepted or source seal was hidden")
}
})
}
job, _, err := a.CreateLibraryJob(ctx, governance.LibraryJob{ID: "target-a-job", Scope: "internal", Kind: governance.LibraryJobSync, IdempotencyKey: "target-a-job", RequestDigest: "digest", TargetSnapshotID: "source"}, governance.SyncStages(), now)
if err != nil {
t.Fatal(err)
}
if _, err := b.LibraryJob(ctx, job.ID); err == nil {
t.Error("new executor admitted old target job")
}
if _, _, err := b.PrepareLibraryJobResume(ctx, job.ID, now); err == nil {
t.Error("new target resumed old target job")
}
grant := governance.LibraryReleaseAuthorization{ID: "grant-a", Scope: "internal", SnapshotID: "source", ParamsDigest: "same-input", AuthorizedBy: "admin", ExpiresAt: now.Add(time.Hour), CreatedAt: now}
if err := a.CreateLibraryAuthorization(ctx, grant); err != nil {
t.Fatal(err)
}
if _, found, err := b.ActiveLibraryAuthorization(ctx, "internal", "source", "same-input", now); err != nil || found {
t.Errorf("foreign grant accepted: found=%v err=%v", found, err)
}
if rows, err := b.LibraryAuthorizations(ctx, "internal", 100); err != nil || len(rows) != 0 {
t.Errorf("foreign grant listed: rows=%v err=%v", rows, err)
}
if err := b.RevokeLibraryAuthorization(ctx, grant.ID, now); err == nil {
t.Error("foreign grant revoked")
}
if _, found, err := a.ActiveLibraryAuthorization(ctx, "internal", "source", "same-input", now); err != nil || !found {
t.Errorf("original grant must remain valid: found=%v err=%v", found, err)
}
}
func TestLibraryTargetRejectsForeignOperationReplay(t *testing.T) {
legacy, _ := openVersionStore(t)
a, b := legacy.WithLibraryTarget("target-a"), legacy.WithLibraryTarget("target-b")
ctx := context.Background()
op := governance.LibraryOperation{ID: "operation", Scope: "internal", Kind: governance.LibraryJobSync, TargetSnapshotID: "snapshot", RequestDigest: "digest", OperationKey: "same-key", CreatedAt: time.Now(), Actor: "admin"}
if _, _, err := a.EnsureLibraryOperation(ctx, op); err != nil {
t.Fatal(err)
}
if _, _, err := b.EnsureLibraryOperation(ctx, op); err == nil {
t.Error("new target replayed foreign operation")
}
if _, err := b.LibraryOperation(ctx, op.ID); err == nil {
t.Error("new target read foreign operation as its own")
}
}
func TestLibraryTargetRejectsEventIdentityCollision(t *testing.T) {
legacy, _ := openVersionStore(t)
a, b := legacy.WithLibraryTarget("target-a"), legacy.WithLibraryTarget("target-b")
ctx := context.Background()
event := governance.LibraryVersion{ID: "same-event", Scope: "internal", Kind: governance.LibraryVersionProductionEffective, SnapshotID: "snapshot", SourceJobID: "job", CreatedAt: time.Now()}
if err := a.RecordLibraryVersion(ctx, event); err != nil {
t.Fatal(err)
}
if err := b.RecordLibraryVersion(ctx, event); err == nil {
t.Fatal("foreign event collision was silently accepted")
}
event.ID = "seal"
event.Kind = governance.LibraryVersionTestSealed
if err := a.RecordLibraryVersion(ctx, event); err != nil {
t.Fatal(err)
}
if err := b.RecordLibraryVersion(ctx, event); err != nil {
t.Fatalf("source seal replay must remain independent: %v", err)
}
}
func TestLibraryTargetSeparatesCurrentAndPreservesLegacy(t *testing.T) {
legacy, pool := openVersionStore(t)
a := targetTestStore(legacy, "target-a")
b := targetTestStore(legacy, "target-b")
ctx := context.Background()
now := time.Now().UTC()
record := func(s *Store, id string, at time.Time) {
t.Helper()
if err := s.RecordLibraryVersion(ctx, governance.LibraryVersion{
ID: id, Scope: "internal", Kind: governance.LibraryVersionProductionEffective,
SnapshotID: "snapshot-" + id, SourceJobID: "job-" + id, Evidence: map[string]any{"verified": true}, CreatedAt: at,
}); err != nil {
t.Fatal(err)
}
}
record(legacy, "legacy", now)
if _, found, err := b.LibraryCurrentVersion(ctx, "internal"); err != nil || found {
t.Fatalf("new target inherited legacy current: found=%v err=%v", found, err)
}
record(a, "a", now.Add(time.Second))
record(b, "b", now.Add(2*time.Second))
for _, tc := range []struct {
s *Store
want string
}{{legacy, "legacy"}, {a, "a"}, {b, "b"}} {
got, found, err := tc.s.LibraryCurrentVersion(ctx, "internal")
if err != nil || !found || got.ID != tc.want || got.SupersededAt != nil {
t.Fatalf("target current must remain independent: want=%s got=%+v found=%v err=%v", tc.want, got, found, err)
}
}
var count int
if err := pool.QueryRow(ctx, "SELECT count(*) FROM library_versions").Scan(&count); err != nil || count != 3 {
t.Fatalf("history changed: count=%d err=%v", count, err)
}
}
@@ -0,0 +1,17 @@
-- 已产生目标绑定证据时不可降级为 scope-only,否则会把不同目标历史混为一谈。
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM library_versions WHERE target_id <> '')
OR EXISTS (SELECT 1 FROM library_operations WHERE target_id <> '')
OR EXISTS (SELECT 1 FROM library_jobs WHERE target_id <> '')
OR EXISTS (SELECT 1 FROM library_release_authorizations WHERE target_id <> '') THEN
RAISE EXCEPTION 'target-bound release evidence exists; restore the verified control-plane backup instead of downgrading';
END IF;
END $$;
ALTER TABLE library_current_versions DROP CONSTRAINT library_current_versions_pkey;
ALTER TABLE library_current_versions DROP COLUMN target_id;
ALTER TABLE library_current_versions ADD PRIMARY KEY (scope);
DROP INDEX library_versions_target;
ALTER TABLE library_versions DROP COLUMN target_id;
ALTER TABLE library_operations DROP COLUMN target_id;
ALTER TABLE library_jobs DROP COLUMN target_id;
ALTER TABLE library_release_authorizations DROP COLUMN target_id;
@@ -0,0 +1,9 @@
-- 旧记录无法证明属于新配置目标;保留在空身份的历史空间,不猜测回填。
ALTER TABLE library_operations ADD COLUMN target_id TEXT NOT NULL DEFAULT '';
ALTER TABLE library_jobs ADD COLUMN target_id TEXT NOT NULL DEFAULT '';
ALTER TABLE library_release_authorizations ADD COLUMN target_id TEXT NOT NULL DEFAULT '';
ALTER TABLE library_versions ADD COLUMN target_id TEXT NOT NULL DEFAULT '';
ALTER TABLE library_current_versions ADD COLUMN target_id TEXT NOT NULL DEFAULT '';
ALTER TABLE library_current_versions DROP CONSTRAINT library_current_versions_pkey;
ALTER TABLE library_current_versions ADD PRIMARY KEY (scope, target_id);
CREATE INDEX library_versions_target ON library_versions (target_id, scope, kind, created_at DESC);
+16 -13
View File
@@ -11,59 +11,62 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
if len(migrations) != 76 {
t.Fatalf("migration count = %d, want 76", len(migrations))
if len(migrations) != 77 {
t.Fatalf("migration count = %d, want 77", len(migrations))
}
if target := migrations[76]; target.Version != 77 || !strings.Contains(target.UpSQL, "PRIMARY KEY (scope, target_id)") {
t.Fatalf("migration 77 = %#v", target)
}
// 76 是发布执行身份:operation / attempt(epoch) / 不可变事件 + current 指针。
// 它只动治理库,不碰 WeKnora Schema。
if identity := migrations[len(migrations)-1]; identity.Version != 76 ||
if identity := migrations[75]; identity.Version != 76 ||
!strings.Contains(identity.UpSQL, "library_operations") ||
!strings.Contains(identity.UpSQL, "library_attempts") ||
!strings.Contains(identity.UpSQL, "library_current_versions") {
t.Fatalf("migration 76 = %#v", identity)
}
// 75 允许"建立目标权威基线"作为独立业务作业,并与 sync/restore 共用写互斥。
if baseline := migrations[len(migrations)-2]; baseline.Version != 75 ||
if baseline := migrations[74]; baseline.Version != 75 ||
!strings.Contains(baseline.UpSQL, "library_jobs_write_target") ||
!strings.Contains(baseline.UpSQL, "'baseline'") {
t.Fatalf("migration 75 = %#v", baseline)
}
// 74 记录封存执行器的运行时状态:页面可用性来自真实观测,不来自配置字符串。
if executor := migrations[len(migrations)-3]; executor.Version != 74 ||
if executor := migrations[73]; executor.Version != 74 ||
!strings.Contains(executor.UpSQL, "library_executor_status") {
t.Fatalf("migration 74 = %#v", executor)
}
// 73 记录死信精确解除:保留上游行,只绑定指纹、重放引用与观测摘要。
if release := migrations[len(migrations)-4]; release.Version != 73 ||
if release := migrations[72]; release.Version != 73 ||
!strings.Contains(release.UpSQL, "library_dead_letter_releases") {
t.Fatalf("migration 73 = %#v", release)
}
// 72 让维护占用按实例互斥(internal/external 不再各有各的锁)。
if instance := migrations[len(migrations)-5]; instance.Version != 72 ||
if instance := migrations[71]; instance.Version != 72 ||
!strings.Contains(instance.UpSQL, "library_instance_maintenance") {
t.Fatalf("migration 72 = %#v", instance)
}
// 71 让维护记录能区分实例级维护与仅治理库互斥。
if level := migrations[len(migrations)-6]; level.Version != 71 ||
if level := migrations[70]; level.Version != 71 ||
!strings.Contains(level.UpSQL, "level") || !strings.Contains(level.UpSQL, "ingress_state") {
t.Fatalf("migration 71 = %#v", level)
}
if maint := migrations[len(migrations)-7]; maint.Version != 70 || !strings.Contains(maint.UpSQL, "library_maintenance") {
if maint := migrations[69]; maint.Version != 70 || !strings.Contains(maint.UpSQL, "library_maintenance") {
t.Fatalf("migration 70 = %#v", maint)
}
if tail := migrations[len(migrations)-8]; tail.Version != 69 ||
if tail := migrations[68]; tail.Version != 69 ||
!strings.Contains(tail.UpSQL, "library_jobs_write_target") {
t.Fatalf("migration 69 = %#v", tail)
}
if restore := migrations[len(migrations)-9]; restore.Version != 68 || !strings.Contains(restore.UpSQL, "restore") {
if restore := migrations[67]; restore.Version != 68 || !strings.Contains(restore.UpSQL, "restore") {
t.Fatalf("migration 68 = %#v", restore)
}
if last := migrations[len(migrations)-10]; last.Version != 67 ||
if last := migrations[66]; last.Version != 67 ||
!strings.Contains(last.UpSQL, "library_release_authorizations") ||
!strings.Contains(last.UpSQL, "params_digest") {
t.Fatalf("migration 67 = %#v", last)
}
if flow := migrations[len(migrations)-11]; flow.Version != 66 ||
if flow := migrations[65]; flow.Version != 66 ||
!strings.Contains(flow.UpSQL, "CREATE TABLE library_versions") ||
!strings.Contains(flow.UpSQL, "library_jobs_active") {
t.Fatalf("migration 66 = %#v", flow)
+11 -1
View File
@@ -23,7 +23,17 @@ type database interface {
}
type Store struct {
db database
db database
libraryTargetID string
}
// WithLibraryTarget isolates release facts without mutating a shared Store.
// The empty namespace retains legacy evidence; live API/workers bind a nonempty
// identity before exposing library operations. Source seals remain independent.
func (s *Store) WithLibraryTarget(id string) *Store {
copy := *s
copy.libraryTargetID = id
return &copy
}
func NewStore(db database) *Store {
+5
View File
@@ -9,6 +9,11 @@
"⚠️ 文件缺失或解析不了 ⇒ 门禁红:范围声明不出来时,不许默认放行。"
],
"optional": [
{
"package": "knowledge-governance/cmd/worker",
"test": "TestLibraryReleaseRejectsAnotherTargetBeforeMaintenance",
"reason": "需要 TEST_DATABASE_URL 指向可销毁 PostgreSQL;验证跨目标旧作业在维护与执行代次创建前被拒绝,本地隔离真库补验,CI 无库显式跳过"
},
{
"package": "knowledge-governance/internal/releaseadapter/v071",
"test": "TestLibrarySourceReadOnlyDiagnostic",