fix(settings): 绑定留档名称并按旧目标重指向待入库
build / build (push) Successful in 1m48s

- 迁移 000084 保存对内/对外绑定名称快照;清除密钥后仍显示已绑定库,不再只显示裸 ID
- 测试/生产换绑只重指向同一侧的旧目标,避免测试保存误改另一环境的待入库
- 已保存连接但没有可用密钥时拒绝改绑定,禁止静默回落文件 Key
- 生产换绑返回重指向/退休数量,页面提示与测试侧一致

验证:make verify(含隔离 PostgreSQL 集成用例)15/15 通过
This commit is contained in:
狐友 GXXP & LEN
2026-11-23 12:47:22 +08:00
committed by 姚章浩
parent 8b900a9ffb
commit aac8538372
19 changed files with 633 additions and 140 deletions
@@ -0,0 +1,7 @@
ALTER TABLE production_kb_bindings
DROP COLUMN IF EXISTS internal_kb_name,
DROP COLUMN IF EXISTS external_kb_name;
ALTER TABLE routing_kb_bindings
DROP COLUMN IF EXISTS internal_kb_name,
DROP COLUMN IF EXISTS external_kb_name;
@@ -0,0 +1,10 @@
-- 「知识库绑定」保存选择时的库名快照:页面在密钥被清除或连接暂时不可达时
-- 仍要显示「对内/对外绑定的是哪个库」,不能退化成裸 ID。库名只是展示缓存,
-- 路由与发布仍以 *_kb_id 为准;换库时保存路径会同步覆盖或清空对应快照。
ALTER TABLE routing_kb_bindings
ADD COLUMN IF NOT EXISTS internal_kb_name TEXT NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS external_kb_name TEXT NOT NULL DEFAULT '';
ALTER TABLE production_kb_bindings
ADD COLUMN IF NOT EXISTS internal_kb_name TEXT NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS external_kb_name TEXT NOT NULL DEFAULT '';
+21 -13
View File
@@ -11,59 +11,67 @@ 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))
}
// 84 adds the display-name snapshots written with each binding save, so a
// cleared key keeps showing which base is bound instead of a raw id.
if names := migrations[len(migrations)-1]; names.Version != 84 ||
!strings.Contains(names.UpSQL, "internal_kb_name") ||
!strings.Contains(names.UpSQL, "production_kb_bindings") ||
!strings.Contains(names.DownSQL, "DROP COLUMN IF EXISTS external_kb_name") {
t.Fatalf("migration 84 = %#v", names)
}
// 83 把「连接(地址 + 写-only 密钥)」从文件引用搬进治理库;编号必须 ≥83,
// 因为现场 0.9.0 的 schema_migrations 已到 82,迁移器按号跳过且无顺序守卫。
if connections := migrations[len(migrations)-1]; connections.Version != 83 ||
if connections := migrations[len(migrations)-2]; connections.Version != 83 ||
!strings.Contains(connections.UpSQL, "weknora_environment_connections") ||
!strings.Contains(connections.UpSQL, "key_ciphertext") ||
!strings.Contains(connections.DownSQL, "DROP TABLE IF EXISTS weknora_environment_connections") {
t.Fatalf("migration 83 = %#v", connections)
}
// 75 允许"建立目标权威基线"作为独立业务作业,并与 sync/restore 共用写互斥。
if baseline := migrations[len(migrations)-2]; baseline.Version != 75 ||
if baseline := migrations[len(migrations)-3]; 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[len(migrations)-4]; 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[len(migrations)-5]; 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[len(migrations)-6]; 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[len(migrations)-7]; 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[len(migrations)-8]; 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[len(migrations)-9]; 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[len(migrations)-10]; 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[len(migrations)-11]; 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[len(migrations)-12]; flow.Version != 66 ||
!strings.Contains(flow.UpSQL, "CREATE TABLE library_versions") ||
!strings.Contains(flow.UpSQL, "library_jobs_active") {
t.Fatalf("migration 66 = %#v", flow)
@@ -3,6 +3,7 @@ package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
@@ -13,43 +14,105 @@ import (
// right side is the production-side base this table chooses. An empty side
// keeps the historical same-id semantics.
type ProductionBinding struct {
InternalKBID string
ExternalKBID string
InternalKBID string
ExternalKBID string
InternalKBName string
ExternalKBName string
UpdatedBy string
}
// ProductionBindingSave is one UI save of the production-side targets. Names
// are display snapshots; see RoutingBindingSave for the preserve rules.
type ProductionBindingSave struct {
InternalID string
ExternalID string
InternalName string
ExternalName string
UpdatedBy string
}
func (s *Store) loadProductionKBBinding(ctx context.Context) (ProductionBinding, bool, error) {
var binding ProductionBinding
err := s.db.QueryRow(ctx, `
SELECT internal_kb_id,external_kb_id,internal_kb_name,external_kb_name,updated_by
FROM production_kb_bindings WHERE id='active'`).
Scan(&binding.InternalKBID, &binding.ExternalKBID, &binding.InternalKBName, &binding.ExternalKBName, &binding.UpdatedBy)
if errors.Is(err, pgx.ErrNoRows) {
return ProductionBinding{}, false, nil
}
if err != nil {
return ProductionBinding{}, false, errors.New("load production kb bindings")
}
return binding, true, nil
}
// LoadProductionKBBindings reads the single active mapping row. A missing row
// reads back as unbound rather than an error.
func (s *Store) LoadProductionKBBindings(ctx context.Context) (string, string, string, error) {
var binding ProductionBinding
err := s.db.QueryRow(ctx, `SELECT internal_kb_id,external_kb_id,updated_by FROM production_kb_bindings WHERE id='active'`).
Scan(&binding.InternalKBID, &binding.ExternalKBID, &binding.UpdatedBy)
if errors.Is(err, pgx.ErrNoRows) {
return "", "", "", nil
}
binding, _, err := s.loadProductionKBBinding(ctx)
if err != nil {
return "", "", "", errors.New("load production kb bindings")
return "", "", "", err
}
return binding.InternalKBID, binding.ExternalKBID, binding.UpdatedBy, nil
}
// SaveProductionKBBindings upserts the mapping row. The knowledge base ids must
// already have been validated against the live production WeKnora by the caller.
func (s *Store) SaveProductionKBBindings(ctx context.Context, internalID, externalID, updatedBy string, now time.Time) error {
if now.IsZero() {
return errors.New("production binding save requires a timestamp")
// LoadProductionKBBindingNames reads the display snapshot stored with the
// production mapping.
func (s *Store) LoadProductionKBBindingNames(ctx context.Context) (string, string, error) {
binding, _, err := s.loadProductionKBBinding(ctx)
if err != nil {
return "", "", err
}
if _, err := s.db.Exec(ctx, `
INSERT INTO production_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at)
VALUES('active',$1,$2,$3,$4)
return binding.InternalKBName, binding.ExternalKBName, nil
}
// SaveProductionKBBindingsWithReplan saves the production mapping and, in the
// SAME transaction, re-points 待入库 publications that were still waiting for
// the previous production target. Only rows already aimed at the previous
// production id move; a test-side publication with the same scope is untouched.
func (s *Store) SaveProductionKBBindingsWithReplan(ctx context.Context, save ProductionBindingSave, previous, effective EffectiveKBIDs, now time.Time) (RoutingBindingReplanResult, error) {
var result RoutingBindingReplanResult
if now.IsZero() {
return result, errors.New("production binding replan requires a timestamp")
}
tx, err := s.db.Begin(ctx)
if err != nil {
return result, fmt.Errorf("begin production binding save: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
var previousRow ProductionBinding
err = tx.QueryRow(ctx, `
SELECT internal_kb_id,external_kb_id,internal_kb_name,external_kb_name
FROM production_kb_bindings WHERE id='active' FOR UPDATE`).
Scan(&previousRow.InternalKBID, &previousRow.ExternalKBID, &previousRow.InternalKBName, &previousRow.ExternalKBName)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return result, errors.New("load previous production kb bindings")
}
internalName := preservedBindingName(save.InternalID, save.InternalName, previousRow.InternalKBID, previousRow.InternalKBName)
externalName := preservedBindingName(save.ExternalID, save.ExternalName, previousRow.ExternalKBID, previousRow.ExternalKBName)
if _, err := tx.Exec(ctx, `
INSERT INTO production_kb_bindings(id,internal_kb_id,external_kb_id,internal_kb_name,external_kb_name,updated_by,updated_at)
VALUES('active',$1,$2,$3,$4,$5,$6)
ON CONFLICT(id) DO UPDATE SET
internal_kb_id=EXCLUDED.internal_kb_id,
external_kb_id=EXCLUDED.external_kb_id,
internal_kb_name=EXCLUDED.internal_kb_name,
external_kb_name=EXCLUDED.external_kb_name,
updated_by=EXCLUDED.updated_by,
updated_at=EXCLUDED.updated_at`, internalID, externalID, updatedBy, now); err != nil {
return errors.New("save production kb bindings")
updated_at=EXCLUDED.updated_at`,
save.InternalID, save.ExternalID, internalName, externalName, save.UpdatedBy, now); err != nil {
return result, errors.New("save production kb bindings")
}
return nil
result, err = replanPendingPublicationsTx(ctx, tx, previous, effective, now)
if err != nil {
return RoutingBindingReplanResult{}, err
}
if err := tx.Commit(ctx); err != nil {
return result, fmt.Errorf("commit production binding save: %w", err)
}
return result, nil
}
// ResolveProductionTargetKB maps a publication scope to the production base the
@@ -27,6 +27,12 @@ func TestProductionKBBindingsResolveAndFallBack(t *testing.T) {
}
store := NewStore(pool)
now := time.Date(2026, time.October, 8, 9, 0, 0, 0, time.UTC)
save := func(internal, external, updatedBy string, at time.Time) error {
_, err := store.SaveProductionKBBindingsWithReplan(ctx, ProductionBindingSave{
InternalID: internal, ExternalID: external, UpdatedBy: updatedBy,
}, EffectiveKBIDs{}, EffectiveKBIDs{}, at)
return err
}
internal, external, _, err := store.LoadProductionKBBindings(ctx)
if err != nil {
@@ -39,7 +45,7 @@ func TestProductionKBBindingsResolveAndFallBack(t *testing.T) {
t.Fatalf("unbound resolve = %q/%v, want the tested base", target, err)
}
if err := store.SaveProductionKBBindings(ctx, "prod-internal", "prod-external", "admin", now); err != nil {
if err := save("prod-internal", "prod-external", "admin", now); err != nil {
t.Fatal(err)
}
if target, err := store.ResolveProductionTargetKB(ctx, "internal", "test-kb"); err != nil || target != "prod-internal" {
@@ -53,7 +59,7 @@ func TestProductionKBBindingsResolveAndFallBack(t *testing.T) {
}
// Unbinding one side returns that side to the same-id semantics only.
if err := store.SaveProductionKBBindings(ctx, "", "prod-external", "admin", now); err != nil {
if err := save("", "prod-external", "admin", now); err != nil {
t.Fatal(err)
}
if target, err := store.ResolveProductionTargetKB(ctx, "internal", "test-kb"); err != nil || target != "test-kb" {
@@ -66,7 +72,7 @@ func TestProductionKBBindingsResolveAndFallBack(t *testing.T) {
if err != nil || saver != "admin" {
t.Fatalf("updated_by = %q (%v)", saver, err)
}
if err := store.SaveProductionKBBindings(ctx, "prod-internal", "", "admin", time.Time{}); err == nil {
if err := save("prod-internal", "", "admin", time.Time{}); err == nil {
t.Fatal("a save without a timestamp must be rejected")
}
}
+124 -55
View File
@@ -9,29 +9,68 @@ import (
"github.com/jackc/pgx/v5"
)
// EffectiveKBIDs are the knowledge-base ids the platform actually routes to:
// the UI binding when set, the deployment default otherwise.
type EffectiveKBIDs struct {
Internal string
External string
}
// RoutingBindingSave is one UI save of the test-side 对内/对外 targets. Names
// are display snapshots captured while the connected instance still answered;
// an empty name preserves the previous snapshot only when the id is unchanged.
type RoutingBindingSave struct {
InternalID string
ExternalID string
InternalName string
ExternalName string
UpdatedBy string
}
// RoutingBinding is the UI-managed knowledge base binding row. Empty ids mean
// "not bound in the UI"; callers fall back to their environment defaults.
type RoutingBinding struct {
InternalKBID string
ExternalKBID string
UpdatedBy string
InternalKBID string
ExternalKBID string
InternalKBName string
ExternalKBName string
UpdatedBy string
}
func (s *Store) loadRoutingKBBinding(ctx context.Context) (RoutingBinding, bool, error) {
var binding RoutingBinding
err := s.db.QueryRow(ctx, `
SELECT internal_kb_id,external_kb_id,internal_kb_name,external_kb_name,updated_by
FROM routing_kb_bindings WHERE id='active'`).
Scan(&binding.InternalKBID, &binding.ExternalKBID, &binding.InternalKBName, &binding.ExternalKBName, &binding.UpdatedBy)
if errors.Is(err, pgx.ErrNoRows) {
return RoutingBinding{}, false, nil
}
if err != nil {
return RoutingBinding{}, false, errors.New("load routing kb bindings")
}
return binding, true, nil
}
// LoadRoutingKBBindings reads the single active binding row. A missing row
// reads back as unbound rather than an error.
func (s *Store) LoadRoutingKBBindings(ctx context.Context) (string, string, string, error) {
var binding RoutingBinding
err := s.db.QueryRow(ctx, `SELECT internal_kb_id,external_kb_id,updated_by FROM routing_kb_bindings WHERE id='active'`).
Scan(&binding.InternalKBID, &binding.ExternalKBID, &binding.UpdatedBy)
if errors.Is(err, pgx.ErrNoRows) {
return "", "", "", nil
}
binding, _, err := s.loadRoutingKBBinding(ctx)
if err != nil {
return "", "", "", errors.New("load routing kb bindings")
return "", "", "", err
}
return binding.InternalKBID, binding.ExternalKBID, binding.UpdatedBy, nil
}
// LoadRoutingKBBindingNames reads the display snapshot stored with the binding.
func (s *Store) LoadRoutingKBBindingNames(ctx context.Context) (string, string, error) {
binding, _, err := s.loadRoutingKBBinding(ctx)
if err != nil {
return "", "", err
}
return binding.InternalKBName, binding.ExternalKBName, nil
}
// RoutingBindingReplanResult reports what a binding change did to publications
// that were still waiting in 待入库.
type RoutingBindingReplanResult struct {
@@ -43,31 +82,16 @@ type RoutingBindingReplanResult struct {
RetiredDuplicates int
}
// SaveRoutingKBBindings upserts the binding row. Each side is either empty
// (unbind, fall back to env) or a knowledge base id validated by the caller.
func (s *Store) SaveRoutingKBBindings(ctx context.Context, internalID, externalID, updatedBy string) error {
_, err := s.db.Exec(ctx, `
INSERT INTO routing_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at)
VALUES('active',$1,$2,$3,NOW())
ON CONFLICT(id) DO UPDATE SET
internal_kb_id=EXCLUDED.internal_kb_id,
external_kb_id=EXCLUDED.external_kb_id,
updated_by=EXCLUDED.updated_by,
updated_at=NOW()`, internalID, externalID, updatedBy)
if err != nil {
return errors.New("save routing kb bindings")
}
return nil
}
// replanRetireDuplicatesSQL retires a pending publication whose twin for the
// new knowledge base already exists — the unique key is
// (source_item_version_id, test_kb_id), so the row cannot simply be moved.
// It is scoped to the previous target ($3): a production-side pending row must
// never be retargeted by a test-side binding save.
const replanRetireDuplicatesSQL = `
UPDATE test_publications stale
SET superseded_at = $3, updated_at = $3
SET superseded_at = $4, updated_at = $4
WHERE stale.superseded_at IS NULL
AND stale.test_kb_id <> $1
AND stale.test_kb_id = $3
AND stale.processing_state = 'planned'
AND stale.ingest_state = 'pending'
AND stale.knowledge_id = ''
@@ -86,9 +110,9 @@ WHERE stale.superseded_at IS NULL
// already in flight keeps its frozen target and stays visible in 待入库.
const replanMovePendingSQL = `
UPDATE test_publications pending
SET test_kb_id = $1, updated_at = $3
SET test_kb_id = $1, updated_at = $4
WHERE pending.superseded_at IS NULL
AND pending.test_kb_id <> $1
AND pending.test_kb_id = $3
AND pending.processing_state = 'planned'
AND pending.ingest_state = 'pending'
AND pending.knowledge_id = ''
@@ -102,16 +126,60 @@ WHERE pending.superseded_at IS NULL
AND twin.superseded_at IS NULL)
`
func preservedBindingName(newID, newName, previousID, previousName string) string {
if newID == "" {
return ""
}
if newName != "" {
return newName
}
if newID == previousID {
return previousName
}
return ""
}
// replanPendingPublicationsTx moves only rows aimed at the SAME side's previous
// effective target. Test and production bindings share test_publications, so
// matching on target_scope alone would let one environment steal the other's
// pending rows.
func replanPendingPublicationsTx(ctx context.Context, tx pgx.Tx, previous, effective EffectiveKBIDs, now time.Time) (RoutingBindingReplanResult, error) {
var result RoutingBindingReplanResult
for _, scope := range []struct {
name string
from, to string
}{
{"internal", previous.Internal, effective.Internal},
{"external", previous.External, effective.External},
} {
if scope.from == "" || scope.to == "" || scope.from == scope.to {
continue
}
retired, err := tx.Exec(ctx, replanRetireDuplicatesSQL, scope.to, scope.name, scope.from, now)
if err != nil {
return result, fmt.Errorf("retire duplicate pending publications: %w", err)
}
moved, err := tx.Exec(ctx, replanMovePendingSQL, scope.to, scope.name, scope.from, now)
if err != nil {
return result, fmt.Errorf("replan pending publications: %w", err)
}
result.RetiredDuplicates += int(retired.RowsAffected())
result.Replanned += int(moved.RowsAffected())
}
return result, nil
}
// SaveRoutingKBBindingsWithReplan saves the binding and, in the SAME
// transaction, re-points 待入库 items that were still waiting for the old
// knowledge base. Without this, changing the binding left every pending
// publication aimed at the previous (possibly deleted) KB, and re-marking the
// file created a SECOND publication instead of moving the first.
//
// effectiveInternal/effectiveExternal are the ids the platform actually routes
// to (the saved binding, or the deployment default when a side is unbound);
// an empty effective id means that scope cannot be routed and is skipped.
func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID, externalID, effectiveInternal, effectiveExternal, updatedBy string, now time.Time) (RoutingBindingReplanResult, error) {
// previous/effective are the ids this environment actually routed to before
// and after the save (the saved binding, or the deployment default when a side
// is unbound). An empty previous target skips that scope: there is no reliable
// row to move.
func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, save RoutingBindingSave, previous, effective EffectiveKBIDs, now time.Time) (RoutingBindingReplanResult, error) {
var result RoutingBindingReplanResult
if now.IsZero() {
return result, errors.New("binding replan requires a timestamp")
@@ -121,33 +189,34 @@ func (s *Store) SaveRoutingKBBindingsWithReplan(ctx context.Context, internalID,
return result, fmt.Errorf("begin routing binding save: %w", err)
}
defer func() { _ = tx.Rollback(ctx) }()
var previousRow RoutingBinding
err = tx.QueryRow(ctx, `
SELECT internal_kb_id,external_kb_id,internal_kb_name,external_kb_name
FROM routing_kb_bindings WHERE id='active' FOR UPDATE`).
Scan(&previousRow.InternalKBID, &previousRow.ExternalKBID, &previousRow.InternalKBName, &previousRow.ExternalKBName)
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return result, errors.New("load previous routing kb bindings")
}
internalName := preservedBindingName(save.InternalID, save.InternalName, previousRow.InternalKBID, previousRow.InternalKBName)
externalName := preservedBindingName(save.ExternalID, save.ExternalName, previousRow.ExternalKBID, previousRow.ExternalKBName)
if _, err := tx.Exec(ctx, `
INSERT INTO routing_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at)
VALUES('active',$1,$2,$3,$4)
INSERT INTO routing_kb_bindings(id,internal_kb_id,external_kb_id,internal_kb_name,external_kb_name,updated_by,updated_at)
VALUES('active',$1,$2,$3,$4,$5,$6)
ON CONFLICT(id) DO UPDATE SET
internal_kb_id=EXCLUDED.internal_kb_id,
external_kb_id=EXCLUDED.external_kb_id,
internal_kb_name=EXCLUDED.internal_kb_name,
external_kb_name=EXCLUDED.external_kb_name,
updated_by=EXCLUDED.updated_by,
updated_at=EXCLUDED.updated_at`, internalID, externalID, updatedBy, now); err != nil {
updated_at=EXCLUDED.updated_at`,
save.InternalID, save.ExternalID, internalName, externalName, save.UpdatedBy, now); err != nil {
return result, errors.New("save routing kb bindings")
}
for _, scope := range []struct{ name, kbID string }{
{"internal", effectiveInternal},
{"external", effectiveExternal},
} {
if scope.kbID == "" {
continue
}
retired, err := tx.Exec(ctx, replanRetireDuplicatesSQL, scope.kbID, scope.name, now)
if err != nil {
return result, fmt.Errorf("retire duplicate pending publications: %w", err)
}
moved, err := tx.Exec(ctx, replanMovePendingSQL, scope.kbID, scope.name, now)
if err != nil {
return result, fmt.Errorf("replan pending publications: %w", err)
}
result.RetiredDuplicates += int(retired.RowsAffected())
result.Replanned += int(moved.RowsAffected())
result, err = replanPendingPublicationsTx(ctx, tx, previous, effective, now)
if err != nil {
return RoutingBindingReplanResult{}, err
}
if err := tx.Commit(ctx); err != nil {
return result, fmt.Errorf("commit routing binding save: %w", err)
@@ -33,18 +33,21 @@ INSERT INTO source_items(id,source_connection_id,stable_external_id,canonical_ur
('item-in','conn-replan','n-in',repeat('b',64),'docs/in.docx','in.docx','document','locator:r1','internal','configured_scope'),
('item-ext','conn-replan','n-ext',repeat('b',64),'docs/ext.docx','ext.docx','document','locator:r2','external','configured_scope'),
('item-sent','conn-replan','n-sent',repeat('b',64),'docs/sent.docx','sent.docx','document','locator:r3','internal','configured_scope'),
('item-dup','conn-replan','n-dup',repeat('b',64),'docs/dup.docx','dup.docx','document','locator:r4','internal','configured_scope');
('item-dup','conn-replan','n-dup',repeat('b',64),'docs/dup.docx','dup.docx','document','locator:r4','internal','configured_scope'),
('item-prod','conn-replan','n-prod',repeat('b',64),'docs/prod.docx','prod.docx','document','locator:r5','internal','configured_scope');
INSERT INTO source_item_versions(id,source_item_id,revision,content_object_id,content_state) VALUES
('v-in','item-in','locator:r1',NULL,'unknown'),
('v-ext','item-ext','locator:r2',NULL,'unknown'),
('v-sent','item-sent','locator:r3',NULL,'unknown'),
('v-dup','item-dup','locator:r4',NULL,'unknown');
('v-dup','item-dup','locator:r4',NULL,'unknown'),
('v-prod','item-prod','locator:r5',NULL,'unknown');
INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_state,ingest_state,target_scope) VALUES
('pub-in','v-in','kb-old-internal','planned','pending','internal'),
('pub-ext','v-ext','kb-old-external','planned','pending','external'),
('pub-sent','v-sent','kb-old-internal','pending','uploaded','internal'),
('pub-dup-old','v-dup','kb-old-internal','planned','pending','internal'),
('pub-dup-new','v-dup','kb-new-internal','planned','pending','internal');
('pub-dup-new','v-dup','kb-new-internal','planned','pending','internal'),
('pub-prod','v-prod','prod-old-internal','planned','pending','internal');
INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES
('job-sent','test.upload','{"publication_id":"pub-sent"}'::jsonb,'completed','test-start:pub-sent');
`); err != nil {
@@ -53,7 +56,11 @@ INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES
store := NewStore(pool)
now := time.Date(2026, time.October, 8, 7, 0, 0, 0, time.UTC)
result, err := store.SaveRoutingKBBindingsWithReplan(ctx, "kb-new-internal", "kb-new-external", "kb-new-internal", "kb-new-external", "tester", now)
result, err := store.SaveRoutingKBBindingsWithReplan(ctx, RoutingBindingSave{
InternalID: "kb-new-internal", ExternalID: "kb-new-external",
InternalName: "新对内库", ExternalName: "新对外库", UpdatedBy: "tester",
}, EffectiveKBIDs{Internal: "kb-old-internal", External: "kb-old-external"},
EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"}, now)
if err != nil {
t.Fatalf("SaveRoutingKBBindingsWithReplan() error = %v", err)
}
@@ -95,9 +102,39 @@ INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES
if states["pub-dup-old"].kb != "kb-old-internal" || !states["pub-dup-old"].superseded {
t.Fatalf("the duplicate stale row must be retired: %#v", states["pub-dup-old"])
}
// A production-side pending row with the same scope must not be stolen by
// the test-side binding change.
if states["pub-prod"].kb != "prod-old-internal" || states["pub-prod"].superseded {
t.Fatalf("production pending row was retargeted by a test save: %#v", states["pub-prod"])
}
// Production save moves only the row aimed at its previous target.
prodResult, err := store.SaveProductionKBBindingsWithReplan(ctx, ProductionBindingSave{
InternalID: "prod-new-internal", ExternalID: "prod-new-external",
InternalName: "生产对内库", ExternalName: "生产对外库", UpdatedBy: "tester",
}, EffectiveKBIDs{Internal: "prod-old-internal", External: "prod-old-external"},
EffectiveKBIDs{Internal: "prod-new-internal", External: "prod-new-external"}, now)
if err != nil {
t.Fatal(err)
}
if prodResult.Replanned != 1 || prodResult.RetiredDuplicates != 0 {
t.Fatalf("production replan result = %#v, want 1 moved", prodResult)
}
prodState := states["pub-prod"]
if err := pool.QueryRow(ctx, `SELECT test_kb_id FROM test_publications WHERE id='pub-prod'`).Scan(&prodState.kb); err != nil {
t.Fatal(err)
}
states["pub-prod"] = prodState
if states["pub-prod"].kb != "prod-new-internal" {
t.Fatalf("production pending row = %q", states["pub-prod"].kb)
}
// Re-saving the same binding is a no-op: nothing left to move or retire.
again, err := store.SaveRoutingKBBindingsWithReplan(ctx, "kb-new-internal", "kb-new-external", "kb-new-internal", "kb-new-external", "tester", now)
again, err := store.SaveRoutingKBBindingsWithReplan(ctx, RoutingBindingSave{
InternalID: "kb-new-internal", ExternalID: "kb-new-external",
InternalName: "新对内库", ExternalName: "新对外库", UpdatedBy: "tester",
}, EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"},
EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"}, now)
if err != nil {
t.Fatal(err)
}
@@ -112,4 +149,41 @@ INSERT INTO jobs(id,type,payload,state,idempotency_key) VALUES
if internal != "kb-new-internal" || external != "kb-new-external" || updatedBy != "tester" {
t.Fatalf("binding row = %s / %s / %s", internal, external, updatedBy)
}
var internalName, externalName string
if err = pool.QueryRow(ctx, `SELECT internal_kb_name, external_kb_name FROM routing_kb_bindings WHERE id='active'`).
Scan(&internalName, &externalName); err != nil {
t.Fatal(err)
}
if internalName != "新对内库" || externalName != "新对外库" {
t.Fatalf("binding names = %q / %q", internalName, externalName)
}
// A disconnected/cleared-key save carries no live names. Unchanged ids keep
// the snapshot; a changed id must not inherit the old name.
if _, err := store.SaveRoutingKBBindingsWithReplan(ctx, RoutingBindingSave{
InternalID: "kb-new-internal", ExternalID: "kb-new-external", UpdatedBy: "tester",
}, EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"},
EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"}, now); err != nil {
t.Fatal(err)
}
if err := pool.QueryRow(ctx, `SELECT internal_kb_name, external_kb_name FROM routing_kb_bindings WHERE id='active'`).
Scan(&internalName, &externalName); err != nil {
t.Fatal(err)
}
if internalName != "新对内库" || externalName != "新对外库" {
t.Fatalf("same-id save lost the name snapshot: %q / %q", internalName, externalName)
}
if _, err := store.SaveRoutingKBBindingsWithReplan(ctx, RoutingBindingSave{
InternalID: "kb-new-internal", ExternalID: "kb-other-external", UpdatedBy: "tester",
}, EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-new-external"},
EffectiveKBIDs{Internal: "kb-new-internal", External: "kb-other-external"}, now); err != nil {
t.Fatal(err)
}
if err := pool.QueryRow(ctx, `SELECT internal_kb_name, external_kb_name FROM routing_kb_bindings WHERE id='active'`).
Scan(&internalName, &externalName); err != nil {
t.Fatal(err)
}
if internalName != "新对内库" || externalName != "" {
t.Fatalf("changed id inherited a stale name: %q / %q", internalName, externalName)
}
}
@@ -52,15 +52,20 @@ func TestProcessingConfirmationMigrationBackfillsHistoricalExternalPublication(t
t.Fatal(err)
}
defer pool.Close()
migrations, err := loadMigrations()
if err != nil {
t.Fatal(err)
}
latest := int(migrations[len(migrations)-1].Version)
if err := ApplyMigrations(ctx, pool); err != nil {
t.Fatal(err)
}
for version := latest; version > 10; version-- {
// Roll back by the applied ledger, not by number: migrations are not
// contiguous (76-82 are deliberately absent), so a numeric countdown would
// remove the earlier schema this test needs.
for {
var latest int
if err := pool.QueryRow(ctx, `SELECT MAX(version)::INTEGER FROM schema_migrations`).Scan(&latest); err != nil {
t.Fatal(err)
}
if latest <= 10 {
break
}
if err := RollbackLatestMigration(ctx, pool); err != nil {
t.Fatal(err)
}
@@ -93,7 +93,23 @@ func TestWeKnoraConnectionsMigrationUpDownAndStore(t *testing.T) {
t.Fatalf("empty execution counts = %d/%d", frozen, retargetable)
}
// down 必须只删这三张新表,不碰既有绑定表。
// down 必须只删这三张新表,不碰既有绑定表。Roll 84 first so this test
// keeps exercising 83 specifically as later migrations land.
for {
var latest int64
if err := pool.QueryRow(ctx, "SELECT version FROM schema_migrations ORDER BY version DESC LIMIT 1").Scan(&latest); err != nil {
t.Fatalf("read latest migration: %v", err)
}
if latest == 83 {
break
}
if latest < 83 {
t.Fatalf("migration 83 is no longer applied (latest %d)", latest)
}
if err := RollbackLatestMigration(ctx, pool); err != nil {
t.Fatalf("rollback migration %d: %v", latest, err)
}
}
if err := RollbackLatestMigration(ctx, pool); err != nil {
t.Fatalf("rollback 83: %v", err)
}