diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2102213..2d0c225 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,28 @@
# Changelog
+## 开发快照 0.1.403(实例身份约束:绑定、发布与测试对象不跨实例)
+
+### Added
+
+- 迁移 000082:`production_kb_bindings` 冻结每个方向核验时的实例地址与租户,
+ `release_item_executions` 冻结 `target_instance_url/target_tenant_id`,
+ `test_publications` 记录对象实际写入的测试实例地址/租户。
+- 文档发布执行器在 `Contract/Prepare/Activate/Restore/Compensate` 前统一核对实例身份:
+ 网页在实例 A 列库、执行器连实例 B 时,即使知识库 ID/租户相同也以
+ `release_contract_mismatch` 失败关闭,不写目标;整库发布目标不变。
+- 测试入库的上传/轮询/验收/移除按对象记录的身份核对当前连接;改绑实例或租户后,
+ 旧对象不会在克隆实例上继续轮询、验收或删除。
+- 回归:实例 A/B 同名同 ID 的隔离夹具、绑定身份写入计划、四个测试 handler 的正反例。
+
+### Changed
+
+- 「知识库绑定」保存必须为对内/对外各选一个库;显式“未绑定”不再回落部署默认 ID,
+ 避免换绑实例后把旧实例的默认库带到新实例。旧页面留下的既有绑定行保持原语义。
+
+### Security
+
+- 实例身份不匹配一律失败关闭;旧发布项缺少身份信息时也不再猜测,避免写错克隆实例。
+
## 开发快照 0.1.402(知识库绑定:按环境一次保存连接与内外库)
### Added
diff --git a/cmd/api/main.go b/cmd/api/main.go
index 35a9fe8..0c53269 100644
--- a/cmd/api/main.go
+++ b/cmd/api/main.go
@@ -147,9 +147,6 @@ func run(ctx context.Context, getenv func(string) string) error {
}
return internal, external, err
},
- RoutingDefaults: func() (string, string) {
- return config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID
- },
})
productionEndpointResolver := func(resolveCtx context.Context) string {
return kbBindings.ResolveBaseURL(resolveCtx, kbbinding.EnvProduction)
diff --git a/cmd/release-worker/runtime.go b/cmd/release-worker/runtime.go
index fe6a905..b33a335 100644
--- a/cmd/release-worker/runtime.go
+++ b/cmd/release-worker/runtime.go
@@ -163,7 +163,12 @@ func buildReleaseRoute(ctx context.Context, archiveRoot string, snapshot release
if err != nil {
return cleanup(errors.New("create target WeKnora verifier"))
}
- documentTarget, err := v071.NewDocumentTarget(v071.DocumentTargetConfig{Archive: archive, Contract: targetContract, Postgres: postgresImporter, Search: targetSearch, Objects: objectImporter, Verifier: verifier})
+ documentTarget, err := v071.NewDocumentTarget(v071.DocumentTargetConfig{
+ Archive: archive, Contract: targetContract, Postgres: postgresImporter, Search: targetSearch,
+ Objects: objectImporter, Verifier: verifier,
+ TargetInstanceURL: route.Target.WeKnora.BaseURL,
+ TargetTenantID: route.TenantID,
+ })
if err != nil {
return cleanup(errors.New("create v0.7.1 document target"))
}
diff --git a/cmd/worker/main.go b/cmd/worker/main.go
index 69f4900..44888ef 100644
--- a/cmd/worker/main.go
+++ b/cmd/worker/main.go
@@ -221,9 +221,6 @@ func run(ctx context.Context, getenv func(string) string) error {
}
return internal, external, err
},
- RoutingDefaults: func() (string, string) {
- return config.InternalRoutingKnowledgeBaseID, config.ExternalRoutingKnowledgeBaseID
- },
})
log.Printf("library target evidence identity=%s", config.LibraryTargetIdentity())
// 启动先接管被中断的写作业(复用已持久化的预备份),再把剩下的孤儿判失败:
diff --git a/docs/USER_FLOWS_ACCEPTANCE.md b/docs/USER_FLOWS_ACCEPTANCE.md
index 9ad2fcd..6b94429 100644
--- a/docs/USER_FLOWS_ACCEPTANCE.md
+++ b/docs/USER_FLOWS_ACCEPTANCE.md
@@ -257,10 +257,11 @@
### D1 知识库绑定(测试 090 / 生产 090:连接 + 内外库)
- 入口:**系统设置 → 知识库绑定**(管理员;普通用户只读)
-- 步骤:选择环境 → 填写该环境服务地址与 API Key(已配置可保留,不回显)→ **验证并读取知识库**(服务器真实列库,分页;区分空库/无权限/不可达)→ 选对内、对外库(名称 + 短 ID,禁止同一个库)→ **保存该环境绑定**
+- 步骤:选择环境 → 填写该环境服务地址与 API Key(已配置可保留,不回显)→ **验证并读取知识库**(服务器真实列库,分页;区分空库/无权限/不可达)→ 选对内、对外库(名称 + 短 ID,禁止同一个库;**两个方向都必须选择**)→ **保存该环境绑定**
- 期望:一次保存同时生效连接与内外绑定;顶部「当前生效」回读服务器真实值;失败保留旧绑定,未保存草稿不影响当前值;切换环境时迟到的列库响应不串库
- 兼容:没有新配置行的旧部署继续使用文件凭据/默认绑定;保存新密钥需要独立主密钥文件 `WEKNORA_BINDING_MASTER_KEY_FILE`
-- 证据:`internal/kbbinding`(单元 + 隔离 PostgreSQL 集成)、`KnowledgeBaseBinding.test.tsx`
+- 实例约束:网页在实例 A 核验的绑定会冻结地址/租户;文档发布执行器连实例 B 时,即使知识库 ID/租户相同也拒绝写入(`release_contract_mismatch`)。测试对象改绑实例/租户后,旧对象不会被轮询/验收/移除。
+- 证据:`internal/kbbinding`(单元 + 隔离 PostgreSQL 集成)、`KnowledgeBaseBinding.test.tsx`、`TestStartReleaseExecutionFreezesTheBindingInstanceIdentity`、`TestDocumentTargetRejectsBindingVerifiedOnAnotherInstance`
- 状态:✅ 本地验证(未做业务验收)
### D2 测试知识库绑定(折叠诊断;主入口已并入 D1)
diff --git a/internal/kbbinding/binding.go b/internal/kbbinding/binding.go
index 1bd73bb..5e6e543 100644
--- a/internal/kbbinding/binding.go
+++ b/internal/kbbinding/binding.go
@@ -127,10 +127,7 @@ type Options struct {
LegacyKey func(string) (string, error)
// LegacyBinding resolves the pre-existing internal/external binding ids.
LegacyBinding func(context.Context, string) (string, string, error)
- // RoutingDefaults are the deployment bootstrap ids used to replan pending
- // publications when a saved side is empty.
- RoutingDefaults func() (string, string)
- Now func() time.Time
+ Now func() time.Time
}
type DB interface {
diff --git a/internal/kbbinding/binding_test.go b/internal/kbbinding/binding_test.go
index a35579c..2e412ee 100644
--- a/internal/kbbinding/binding_test.go
+++ b/internal/kbbinding/binding_test.go
@@ -119,6 +119,7 @@ func TestSaveInputValidationRejectsDuplicateAndBadIDs(t *testing.T) {
store := New(emptyDB{}, Options{Now: func() time.Time { return now }})
for _, input := range []SaveInput{
{BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb", ExternalKBID: "kb"},
+ {BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb-in"},
{BaseURL: "https://x.example", KeyAction: "replace", APIKey: "k", InternalKBID: "kb/1"},
{BaseURL: "https://x.example?token=1", KeyAction: "replace", APIKey: "k"},
} {
diff --git a/internal/kbbinding/save_integration_test.go b/internal/kbbinding/save_integration_test.go
index 172a2bb..6433777 100644
--- a/internal/kbbinding/save_integration_test.go
+++ b/internal/kbbinding/save_integration_test.go
@@ -32,9 +32,9 @@ func fakeCandidate(t *testing.T) *httptest.Server {
case r.URL.Path == "/api/v1/knowledge-bases":
_, _ = w.Write([]byte(`{"success":true,"total":2,"data":[{"id":"kb-in","name":"内部技术资料","knowledge_count":3},{"id":"kb-out","name":"客户使用手册","knowledge_count":4}]}`))
case r.URL.Path == "/api/v1/knowledge-bases/kb-in":
- _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-in","name":"内部技术资料"}}`))
+ _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-in","name":"内部技术资料","tenant_id":10000}}`))
case r.URL.Path == "/api/v1/knowledge-bases/kb-out":
- _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-out","name":"客户使用手册"}}`))
+ _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-out","name":"客户使用手册","tenant_id":10000}}`))
default:
w.WriteHeader(http.StatusNotFound)
}
@@ -82,9 +82,14 @@ INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_st
MasterKeyFile: masterKey(t),
Timeout: 2 * time.Second,
AllowDockerHTTP: map[string]bool{kbbinding.EnvTest: true, kbbinding.EnvProduction: true},
- RoutingDefaults: func() (string, string) { return "env-in", "env-out" },
})
now := time.Date(2026, 11, 19, 8, 0, 0, 0, time.UTC)
+ if _, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
+ BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
+ InternalKBID: "kb-in",
+ }, "admin", now); !errors.Is(err, kbbinding.ErrInvalid) {
+ t.Fatalf("save with an unbound side = %v, want ErrInvalid", err)
+ }
view, err := store.Save(ctx, kbbinding.EnvTest, kbbinding.SaveInput{
BaseRevision: 0, BaseURL: server.URL, KeyAction: "replace", APIKey: testSecret(),
InternalKBID: "kb-in", ExternalKBID: "kb-out",
@@ -169,11 +174,12 @@ INSERT INTO test_publications(id,source_item_version_id,test_kb_id,processing_st
if prodView.Environment != kbbinding.EnvProduction || prodView.Revision != 1 {
t.Fatalf("production view = %#v", prodView)
}
- var productionInternal string
- if err := pool.QueryRow(ctx, `SELECT internal_kb_id FROM production_kb_bindings WHERE id='active'`).Scan(&productionInternal); err != nil {
+ var productionInternal, productionURL string
+ var productionTenant uint64
+ if err := pool.QueryRow(ctx, `SELECT internal_kb_id, internal_instance_url, internal_tenant_id FROM production_kb_bindings WHERE id='active'`).Scan(&productionInternal, &productionURL, &productionTenant); err != nil {
t.Fatal(err)
}
- if productionInternal != "kb-in" {
- t.Fatalf("production binding = %s", productionInternal)
+ if productionInternal != "kb-in" || productionURL != server.URL || productionTenant != 10000 {
+ t.Fatalf("production binding = %s / %s / %d", productionInternal, productionURL, productionTenant)
}
}
diff --git a/internal/kbbinding/store.go b/internal/kbbinding/store.go
index d3d8f42..82ff755 100644
--- a/internal/kbbinding/store.go
+++ b/internal/kbbinding/store.go
@@ -106,7 +106,12 @@ func (s *Store) Save(ctx context.Context, env string, input SaveInput, actor str
len(internal) > 128 || len(external) > 128 || !validBaseID(internal) || !validBaseID(external) {
return View{}, ErrInvalid
}
- if internal != "" && internal == external {
+ // 新页面必须给两个方向各选一个库:显式“未绑定”会回落到部署默认 ID,
+ // 而那个 ID 可能属于旧实例;在换绑实例后继续沿用就是错误目标。
+ if internal == "" || external == "" {
+ return View{}, ErrInvalid
+ }
+ if internal == external {
return View{}, ErrInvalid
}
saved, found, err := s.load(ctx, env)
@@ -121,7 +126,7 @@ func (s *Store) Save(ctx context.Context, env string, input SaveInput, actor str
if err != nil {
return View{}, ErrInvalid
}
- names, err := s.verifySelection(ctx, client, internal, external)
+ selected, err := s.verifySelection(ctx, client, internal, external)
if err != nil {
return View{}, err
}
@@ -169,7 +174,7 @@ ON CONFLICT(environment) DO UPDATE SET
internal_kb_name=EXCLUDED.internal_kb_name,external_kb_name=EXCLUDED.external_kb_name,
verification=EXCLUDED.verification,checked_at=EXCLUDED.checked_at,
updated_by=EXCLUDED.updated_by,updated_at=EXCLUDED.updated_at`,
- env, revision, baseURL, sealed, internal, external, names[internal], names[external], verification, now.UTC(), actor); err != nil {
+ env, revision, baseURL, sealed, internal, external, selected[internal].Name, selected[external].Name, verification, now.UTC(), actor); err != nil {
return View{}, ErrStorage
}
if _, err := tx.Exec(ctx, `
@@ -184,23 +189,16 @@ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
if err := postgresstore.SaveRoutingKBBindingsTx(ctx, tx, internal, external, actor, now.UTC()); err != nil {
return View{}, ErrStorage
}
- effectiveInternal, effectiveExternal := internal, external
- if s.options.RoutingDefaults != nil {
- defaultInternal, defaultExternal := s.options.RoutingDefaults()
- if effectiveInternal == "" {
- effectiveInternal = defaultInternal
- }
- if effectiveExternal == "" {
- effectiveExternal = defaultExternal
- }
- }
- replan, err = postgresstore.ReplanPendingPublicationsTx(ctx, tx, effectiveInternal, effectiveExternal, now.UTC())
+ replan, err = postgresstore.ReplanPendingPublicationsTx(ctx, tx, internal, external, now.UTC())
if err != nil {
return View{}, ErrStorage
}
} else {
// 生产页这里沿用「文档级发布」语义;整库发布目标由部署配置决定,本保存不写它。
- if err := postgresstore.SaveProductionKBBindingsTx(ctx, tx, internal, external, actor, now.UTC()); err != nil {
+ // 同时冻结候选实例地址与租户,执行器写入前必须与自己的目标一致。
+ if err := postgresstore.SaveProductionKBBindingsWithIdentityTx(ctx, tx,
+ internal, external, baseURL, baseURL,
+ selected[internal].TenantID, selected[external].TenantID, actor, now.UTC()); err != nil {
return View{}, ErrStorage
}
}
@@ -219,13 +217,18 @@ VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
// verifySelection proves both chosen bases belong to THIS candidate instance by
// reading them with the draft credential. An empty selection still probes the
// list endpoint, so a save cannot store a connection nobody verified.
-func (s *Store) verifySelection(ctx context.Context, client *weknora.Client, internal, external string) (map[string]string, error) {
- names := map[string]string{}
+type selectedBase struct {
+ Name string
+ TenantID uint64
+}
+
+func (s *Store) verifySelection(ctx context.Context, client *weknora.Client, internal, external string) (map[string]selectedBase, error) {
+ selected := map[string]selectedBase{}
if internal == "" && external == "" {
if _, err := client.ListKnowledgeBasesPage(ctx, 1, 1); err != nil {
return nil, selectionError(err, "无法确认候选连接")
}
- return names, nil
+ return selected, nil
}
for _, id := range []string{internal, external} {
if id == "" {
@@ -238,9 +241,9 @@ func (s *Store) verifySelection(ctx context.Context, client *weknora.Client, int
if base.ID != id {
return nil, ErrInvalid
}
- names[id] = base.Name
+ selected[id] = selectedBase{Name: base.Name, TenantID: base.TenantID}
}
- return names, nil
+ return selected, nil
}
func selectionError(err error, message string) error {
diff --git a/internal/platform/postgres/migrations/000082_instance_identity_contract.down.sql b/internal/platform/postgres/migrations/000082_instance_identity_contract.down.sql
new file mode 100644
index 0000000..ec4e8eb
--- /dev/null
+++ b/internal/platform/postgres/migrations/000082_instance_identity_contract.down.sql
@@ -0,0 +1,13 @@
+ALTER TABLE test_publications
+ DROP COLUMN IF EXISTS test_instance_tenant,
+ DROP COLUMN IF EXISTS test_instance_url;
+
+ALTER TABLE release_item_executions
+ DROP COLUMN IF EXISTS target_tenant_id,
+ DROP COLUMN IF EXISTS target_instance_url;
+
+ALTER TABLE production_kb_bindings
+ DROP COLUMN IF EXISTS external_tenant_id,
+ DROP COLUMN IF EXISTS internal_tenant_id,
+ DROP COLUMN IF EXISTS external_instance_url,
+ DROP COLUMN IF EXISTS internal_instance_url;
\ No newline at end of file
diff --git a/internal/platform/postgres/migrations/000082_instance_identity_contract.up.sql b/internal/platform/postgres/migrations/000082_instance_identity_contract.up.sql
new file mode 100644
index 0000000..30f6668
--- /dev/null
+++ b/internal/platform/postgres/migrations/000082_instance_identity_contract.up.sql
@@ -0,0 +1,20 @@
+-- 实例身份约束:网页(kbbinding)在实例 A 上列库/选库,而文档发布执行器可能
+-- 连的是实例 B。同名/同 ID 的知识库在克隆实例里完全可能存在,所以 ID 本身
+-- 不能证明“写的是网页看到的那个实例”。这里把候选连接地址与租户随绑定冻结到
+-- 每个发布项,执行器在写入前用自己的目标地址/租户核对;不一致即失败关闭。
+--
+-- 同时给测试入库的发布项记录“对象实际写入的测试实例地址/租户”:
+-- 改绑实例或租户后,旧对象不能在克隆实例上继续轮询/验收/移除。
+ALTER TABLE production_kb_bindings
+ ADD COLUMN IF NOT EXISTS internal_instance_url TEXT NOT NULL DEFAULT '',
+ ADD COLUMN IF NOT EXISTS external_instance_url TEXT NOT NULL DEFAULT '',
+ ADD COLUMN IF NOT EXISTS internal_tenant_id BIGINT NOT NULL DEFAULT 0,
+ ADD COLUMN IF NOT EXISTS external_tenant_id BIGINT NOT NULL DEFAULT 0;
+
+ALTER TABLE release_item_executions
+ ADD COLUMN IF NOT EXISTS target_instance_url TEXT NOT NULL DEFAULT '',
+ ADD COLUMN IF NOT EXISTS target_tenant_id BIGINT NOT NULL DEFAULT 0;
+
+ALTER TABLE test_publications
+ ADD COLUMN IF NOT EXISTS test_instance_url TEXT NOT NULL DEFAULT '',
+ ADD COLUMN IF NOT EXISTS test_instance_tenant BIGINT NOT NULL DEFAULT 0;
\ No newline at end of file
diff --git a/internal/platform/postgres/migrations_test.go b/internal/platform/postgres/migrations_test.go
index 292bfb1..590235b 100644
--- a/internal/platform/postgres/migrations_test.go
+++ b/internal/platform/postgres/migrations_test.go
@@ -11,8 +11,16 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
if err != nil {
t.Fatalf("loadMigrations() error = %v", err)
}
- if len(migrations) != 81 {
- t.Fatalf("migration count = %d, want 81", len(migrations))
+ if len(migrations) != 82 {
+ t.Fatalf("migration count = %d, want 82", len(migrations))
+ }
+ // 82 是实例身份约束:绑定冻结候选实例地址/租户,发布项与测试对象都记录
+ // 实际实例身份;克隆实例同名/同 ID 不能冒充。
+ if identity := migrations[81]; identity.Version != 82 ||
+ !strings.Contains(identity.UpSQL, "target_instance_url") ||
+ !strings.Contains(identity.UpSQL, "test_instance_url") ||
+ !strings.Contains(identity.UpSQL, "internal_tenant_id") {
+ t.Fatalf("migration 82 = %#v", identity)
}
// 81 是环境级「知识库绑定」:连接密文与内外库同表同事务,历史只记是否配置密钥。
if binding := migrations[80]; binding.Version != 81 ||
diff --git a/internal/platform/postgres/production_bindings.go b/internal/platform/postgres/production_bindings.go
index f3a2a7a..ef526da 100644
--- a/internal/platform/postgres/production_bindings.go
+++ b/internal/platform/postgres/production_bindings.go
@@ -39,26 +39,48 @@ func (s *Store) SaveProductionKBBindings(ctx context.Context, internalID, extern
if now.IsZero() {
return errors.New("production binding save requires a timestamp")
}
- if _, err := s.db.Exec(ctx, productionBindingUpsertSQL, internalID, externalID, updatedBy, now); err != nil {
+ // 旧入口没有实例身份可写:显式清空身份列,执行器随后会失败关闭,
+ // 而不是沿用上一条(可能属于另一个实例的)地址/租户。
+ if _, err := s.db.Exec(ctx, productionBindingIdentityUpsertSQL,
+ internalID, externalID, updatedBy, now, "", "", 0, 0); err != nil {
return errors.New("save production kb bindings")
}
return nil
}
-const productionBindingUpsertSQL = `
-INSERT INTO production_kb_bindings(id,internal_kb_id,external_kb_id,updated_by,updated_at)
-VALUES('active',$1,$2,$3,$4)
+// productionBindingIdentityUpsertSQL freezes the instance identity the console
+// verified each side on. An empty URL keeps the legacy same-id behaviour for
+// old callers; the executor then cannot prove the instance and refuses a mapped
+// write instead of guessing.
+const productionBindingIdentityUpsertSQL = `
+INSERT INTO production_kb_bindings(
+ id,internal_kb_id,external_kb_id,updated_by,updated_at,
+ internal_instance_url,external_instance_url,internal_tenant_id,external_tenant_id)
+VALUES('active',$1,$2,$3,$4,$5,$6,$7,$8)
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=EXCLUDED.updated_at`
+ updated_at=EXCLUDED.updated_at,
+ internal_instance_url=EXCLUDED.internal_instance_url,
+ external_instance_url=EXCLUDED.external_instance_url,
+ internal_tenant_id=EXCLUDED.internal_tenant_id,
+ external_tenant_id=EXCLUDED.external_tenant_id`
// SaveProductionKBBindingsTx lets the environment-scoped 「知识库绑定」save
// update the same row inside its own transaction, so connection and bindings
// cannot be half-written.
func SaveProductionKBBindingsTx(ctx context.Context, tx pgx.Tx, internalID, externalID, updatedBy string, now time.Time) error {
- if _, err := tx.Exec(ctx, productionBindingUpsertSQL, internalID, externalID, updatedBy, now); err != nil {
+ return SaveProductionKBBindingsWithIdentityTx(ctx, tx, internalID, externalID, "", "", 0, 0, updatedBy, now)
+}
+
+// SaveProductionKBBindingsWithIdentityTx is used by the environment-scoped
+// 「知识库绑定」save: it stores which instance/tenant each side was verified on,
+// so the release executor can refuse a cloned instance with the same base id.
+func SaveProductionKBBindingsWithIdentityTx(ctx context.Context, tx pgx.Tx, internalID, externalID, internalURL, externalURL string, internalTenant, externalTenant uint64, updatedBy string, now time.Time) error {
+ if _, err := tx.Exec(ctx, productionBindingIdentityUpsertSQL,
+ internalID, externalID, updatedBy, now,
+ internalURL, externalURL, internalTenant, externalTenant); err != nil {
return errors.New("save production kb bindings")
}
return nil
diff --git a/internal/platform/postgres/publication_removal.go b/internal/platform/postgres/publication_removal.go
index 30159ab..2cba3ac 100644
--- a/internal/platform/postgres/publication_removal.go
+++ b/internal/platform/postgres/publication_removal.go
@@ -11,19 +11,22 @@ import (
)
type PublicationForRemoval struct {
- ID string
- TestKBID string
- KnowledgeID string
- RetrievalState governance.RetrievalState
+ ID string
+ TestKBID string
+ KnowledgeID string
+ TestInstanceURL string
+ TestInstanceTenant uint64
+ RetrievalState governance.RetrievalState
}
func (s *Store) LoadPublicationForRemoval(ctx context.Context, publicationID string) (PublicationForRemoval, error) {
var candidate PublicationForRemoval
var retrievalState string
- err := s.db.QueryRow(ctx, `SELECT id,test_kb_id,knowledge_id,retrieval_state
+ err := s.db.QueryRow(ctx, `SELECT id,test_kb_id,knowledge_id,test_instance_url,test_instance_tenant,retrieval_state
FROM test_publications
WHERE id=$1 AND knowledge_id<>'' AND retrieval_state='disabling'`, publicationID).Scan(
- &candidate.ID, &candidate.TestKBID, &candidate.KnowledgeID, &retrievalState,
+ &candidate.ID, &candidate.TestKBID, &candidate.KnowledgeID,
+ &candidate.TestInstanceURL, &candidate.TestInstanceTenant, &retrievalState,
)
if errors.Is(err, pgx.ErrNoRows) {
return PublicationForRemoval{}, ErrPublicationStateConflict
diff --git a/internal/platform/postgres/release_execution_worker_store.go b/internal/platform/postgres/release_execution_worker_store.go
index 5e131df..490fa4b 100644
--- a/internal/platform/postgres/release_execution_worker_store.go
+++ b/internal/platform/postgres/release_execution_worker_store.go
@@ -75,13 +75,32 @@ execution_gate AS (
WHEN 'internal' THEN binding.internal_kb_id
WHEN 'external' THEN binding.external_kb_id
END, ''),
- publication.test_kb_id) AS target_kb_id
+ publication.test_kb_id) AS target_kb_id,
+ -- 身份必须与 target_kb_id 来自同一来源:重试/回滚沿用的旧目标若
+ -- 没有身份(迁移前),不能拿当前绑定去补,否则会把旧项写到新实例;
+ -- 这种情况留空,由执行器失败关闭。
+ CASE
+ WHEN NULLIF(prior_item.target_knowledge_base_id, '') IS NOT NULL
+ THEN COALESCE(prior_item.target_instance_url, '')
+ ELSE COALESCE(NULLIF(CASE publication.target_scope
+ WHEN 'internal' THEN binding.internal_instance_url
+ WHEN 'external' THEN binding.external_instance_url
+ END, ''), '')
+ END AS target_instance_url,
+ CASE
+ WHEN NULLIF(prior_item.target_knowledge_base_id, '') IS NOT NULL
+ THEN COALESCE(prior_item.target_tenant_id, 0)
+ ELSE COALESCE(NULLIF(CASE publication.target_scope
+ WHEN 'internal' THEN binding.internal_tenant_id
+ WHEN 'external' THEN binding.external_tenant_id
+ END, 0), 0)
+ END AS target_tenant_id
FROM started
JOIN release_batch_items AS item ON item.release_batch_id = started.release_batch_id
JOIN test_publications AS publication ON publication.id = item.publication_id
LEFT JOIN production_kb_bindings AS binding ON binding.id = 'active'
LEFT JOIN LATERAL (
- SELECT candidate.target_knowledge_base_id
+ SELECT candidate.target_knowledge_base_id, candidate.target_instance_url, candidate.target_tenant_id
FROM release_item_executions AS candidate
JOIN release_executions AS candidate_execution ON candidate_execution.id = candidate.release_execution_id
WHERE candidate.publication_id = item.publication_id
@@ -94,11 +113,14 @@ execution_gate AS (
) AS prior_item ON TRUE
), seeded AS (
INSERT INTO release_item_executions (
- id, release_execution_id, publication_id, action, state, created_at, updated_at, target_knowledge_base_id
+ id, release_execution_id, publication_id, action, state, created_at, updated_at,
+ target_knowledge_base_id, target_instance_url, target_tenant_id
)
SELECT 'ri-' || SUBSTR(MD5(started.id || ':' || item.publication_id), 1, 32),
started.id, item.publication_id, item.action, 'pending', $4::TIMESTAMPTZ, $4::TIMESTAMPTZ,
- COALESCE(target_base.target_kb_id, '')
+ COALESCE(target_base.target_kb_id, ''),
+ COALESCE(target_base.target_instance_url, ''),
+ COALESCE(target_base.target_tenant_id, 0)
FROM started
JOIN release_batch_items AS item ON item.release_batch_id = started.release_batch_id
LEFT JOIN target_base ON target_base.publication_id = item.publication_id
@@ -129,6 +151,8 @@ execution_gate AS (
item.review_id AS release_revision,
publication.test_kb_id,
COALESCE(target_base.target_kb_id, '') AS target_kb_id,
+ COALESCE(target_base.target_instance_url, '') AS target_instance_url,
+ COALESCE(target_base.target_tenant_id, 0) AS target_tenant_id,
publication.knowledge_id,
item.decided_visibility,
COALESCE(previous.production_revision, '') AS previous_production_revision
@@ -180,6 +204,8 @@ SELECT COUNT(DISTINCT started.id)::INTEGER,
'release_revision', plan.release_revision,
'test_knowledge_base_id', plan.test_kb_id,
'target_knowledge_base_id', plan.target_kb_id,
+ 'target_instance_url', plan.target_instance_url,
+ 'target_tenant_id', plan.target_tenant_id,
'knowledge_id', plan.knowledge_id,
'decided_visibility', plan.decided_visibility,
'previous_production_revision', plan.previous_production_revision
@@ -307,7 +333,8 @@ func (s *Store) StartExecution(ctx context.Context, request releaseworkflow.Star
if !validShortID(item.PublicationID) || !validShortID(item.SourceItemVersionID) ||
!validRemoteIdentifier(item.TestKnowledgeBaseID) || !validRemoteIdentifier(item.TargetKnowledgeBaseID) || !validRemoteIdentifier(item.KnowledgeID) ||
(item.DecidedVisibility != governance.VisibilityInternal && item.DecidedVisibility != governance.VisibilityExternal) ||
- len(item.PreviousProductionRevision) > 128 {
+ len(item.PreviousProductionRevision) > 128 || len(item.TargetInstanceURL) > 300 ||
+ strings.ContainsAny(item.TargetInstanceURL, " \r\n\x00") {
return nil, errors.New("invalid release execution plan")
}
}
diff --git a/internal/platform/postgres/release_execution_worker_store_test.go b/internal/platform/postgres/release_execution_worker_store_test.go
index b61b212..a26c8df 100644
--- a/internal/platform/postgres/release_execution_worker_store_test.go
+++ b/internal/platform/postgres/release_execution_worker_store_test.go
@@ -13,7 +13,7 @@ import (
)
func TestStartReleaseExecutionSeedsItemsAndReturnsOnlyPendingPlan(t *testing.T) {
- payload := `[{"release_execution_id":"rx-safe","publication_id":"tp-safe","action":"delete","source_item_version_id":"sv-safe","source_revision":"source-v1","parse_revision":"parser-v1@index-v1","release_revision":"review-v1","test_knowledge_base_id":"kb-safe","target_knowledge_base_id":"prod-kb","knowledge_id":"knowledge-safe","decided_visibility":"internal","previous_production_revision":"prod-old"}]`
+ payload := `[{"release_execution_id":"rx-safe","publication_id":"tp-safe","action":"delete","source_item_version_id":"sv-safe","source_revision":"source-v1","parse_revision":"parser-v1@index-v1","release_revision":"review-v1","test_knowledge_base_id":"kb-safe","target_knowledge_base_id":"prod-kb","target_instance_url":"https://instance-a.weknora.example","target_tenant_id":10000,"knowledge_id":"knowledge-safe","decided_visibility":"internal","previous_production_revision":"prod-old"}]`
db := &recordingDB{row: startExecutionRow{executionCount: 1, payload: []byte(payload)}}
items, err := NewStore(db).StartExecution(context.Background(), releaseworkflow.StartExecutionRequest{
ExecutionID: "rx-safe", JobID: "job-safe", Operation: "publish", Now: time.Now(),
@@ -24,7 +24,7 @@ func TestStartReleaseExecutionSeedsItemsAndReturnsOnlyPendingPlan(t *testing.T)
if len(items) != 1 || items[0].PublicationID != "tp-safe" || items[0].Action != "delete" || items[0].KnowledgeID != "knowledge-safe" || items[0].PreviousProductionRevision != "prod-old" {
t.Fatalf("items=%#v", items)
}
- if items[0].TargetBase() != "prod-kb" {
+ if items[0].TargetBase() != "prod-kb" || items[0].TargetInstanceURL != "https://instance-a.weknora.example" || items[0].TargetTenantID != 10000 {
t.Fatalf("target base=%q, want the mapped 源库 → 目标库 target", items[0].TargetBase())
}
sql := strings.ToLower(db.queryRowSQL)
@@ -39,6 +39,7 @@ func TestStartReleaseExecutionSeedsItemsAndReturnsOnlyPendingPlan(t *testing.T)
"release_delete_ready", "item.action = 'delete'", "execution_gate.valid_items = execution_gate.item_count",
// the 源库 → 目标库 mapping is resolved into the plan and frozen per item
"production_kb_bindings", "target_knowledge_base_id", "target_base.target_kb_id",
+ "target_instance_url", "target_tenant_id", "internal_instance_url", "internal_tenant_id",
} {
if !strings.Contains(sql, required) {
t.Fatalf("start execution SQL missing %q", required)
diff --git a/internal/platform/postgres/release_identity_integration_test.go b/internal/platform/postgres/release_identity_integration_test.go
new file mode 100644
index 0000000..03ad5ed
--- /dev/null
+++ b/internal/platform/postgres/release_identity_integration_test.go
@@ -0,0 +1,71 @@
+package postgres
+
+import (
+ "context"
+ "os"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+
+ "knowledge-governance/internal/governance"
+ releaseworkflow "knowledge-governance/internal/workflows/release"
+)
+
+// The console verified the production binding on instance A. The release plan
+// must freeze that instance identity with each item; the executor later compares
+// it with its own route target before writing. Same knowledge-base id/tenant on
+// a cloned instance is not enough.
+func TestStartReleaseExecutionFreezesTheBindingInstanceIdentity(t *testing.T) {
+ databaseURL := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
+ if databaseURL == "" {
+ t.Skip("TEST_DATABASE_URL is not set")
+ }
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, databaseURL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer pool.Close()
+ if err := ApplyMigrations(ctx, pool); err != nil {
+ t.Fatal(err)
+ }
+ store := NewStore(pool)
+ now := time.Date(2026, 11, 19, 9, 0, 0, 0, time.UTC)
+ if _, err := pool.Exec(ctx, `INSERT INTO source_connections (id, source_type, name) VALUES ('conn-manual', 'manual', 'Manual')`); err != nil {
+ t.Fatal(err)
+ }
+ publicationID := "tp-identity-e2e"
+ insertReviewFixture(t, ctx, pool, 9, publicationID, now)
+ if _, err := store.ReviewPublication(ctx, governance.ReviewPublicationRequest{PublicationID: publicationID, Decision: governance.ReviewApproved, DecidedVisibility: governance.VisibilityInternal, ReviewerRef: "engineer-1", DecisionCode: "approved_for_release", Now: now.Add(time.Minute)}); err != nil {
+ t.Fatal(err)
+ }
+ batch, err := store.CreateReleaseBatch(ctx, governance.CreateReleaseBatchRequest{Name: "Identity publish", CreatedBy: "engineer-1", PublicationIDs: []string{publicationID}, Now: now.Add(2 * time.Minute)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := store.SealReleaseBatch(ctx, governance.SealReleaseBatchRequest{BatchID: batch.ID, SealedBy: "engineer-2", Now: now.Add(3 * time.Minute)}); err != nil {
+ t.Fatal(err)
+ }
+ execution, err := store.AuthorizeReleaseBatch(ctx, governance.AuthorizeReleaseBatchRequest{BatchID: batch.ID, AuthorizedBy: "release-owner", AuthorizationCode: "production_release_authorized", Now: now.Add(4 * time.Minute)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ tx, err := pool.Begin(ctx)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := SaveProductionKBBindingsWithIdentityTx(ctx, tx, "test-kb", "test-kb", "https://instance-a.weknora.example", "https://instance-a.weknora.example", 10000, 10000, "admin", now); err != nil {
+ t.Fatal(err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ t.Fatal(err)
+ }
+ plan, err := store.StartExecution(ctx, releaseworkflow.StartExecutionRequest{ExecutionID: execution.ID, JobID: execution.JobID, Operation: governance.ReleaseOperationPublish, Now: now.Add(5 * time.Minute)})
+ if err != nil || len(plan) != 1 {
+ t.Fatalf("plan=%#v error=%v", plan, err)
+ }
+ if plan[0].TargetKnowledgeBaseID != "test-kb" || plan[0].TargetInstanceURL != "https://instance-a.weknora.example" || plan[0].TargetTenantID != 10000 {
+ t.Fatalf("plan identity = %s / %s / %d", plan[0].TargetKnowledgeBaseID, plan[0].TargetInstanceURL, plan[0].TargetTenantID)
+ }
+}
diff --git a/internal/platform/postgres/routing_bindings.go b/internal/platform/postgres/routing_bindings.go
index 7a23e97..d47fdaa 100644
--- a/internal/platform/postgres/routing_bindings.go
+++ b/internal/platform/postgres/routing_bindings.go
@@ -86,7 +86,7 @@ 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, test_instance_url = '', test_instance_tenant = 0, updated_at = $3
WHERE pending.superseded_at IS NULL
AND pending.test_kb_id <> $1
AND pending.processing_state = 'planned'
diff --git a/internal/platform/postgres/test_publications.go b/internal/platform/postgres/test_publications.go
index 094ceed..9342115 100644
--- a/internal/platform/postgres/test_publications.go
+++ b/internal/platform/postgres/test_publications.go
@@ -29,22 +29,27 @@ type PublicationForUpload struct {
SourceItemVersionID string
TestKBID string
KnowledgeID string
- IngestState governance.IngestState
- ProcessingState governance.ProcessingState
- TargetScope governance.Visibility
- ContentObjectID string
- SHA256 string
- SizeBytes int64
- MIME string
- ValidatedFormat string
- LocalSpoolRef string
- Title string
+ // 对象实际写入的测试实例身份;空 = 迁移前的旧行,无法证明归属。
+ TestInstanceURL string
+ TestInstanceTenant uint64
+ IngestState governance.IngestState
+ ProcessingState governance.ProcessingState
+ TargetScope governance.Visibility
+ ContentObjectID string
+ SHA256 string
+ SizeBytes int64
+ MIME string
+ ValidatedFormat string
+ LocalSpoolRef string
+ Title string
}
type PublicationForPoll struct {
ID string
TestKBID string
KnowledgeID string
+ TestInstanceURL string
+ TestInstanceTenant uint64
ProcessingState governance.ProcessingState
PollSequence int
LastRemoteStatus string
@@ -55,9 +60,11 @@ type PublicationForPoll struct {
}
type PublicationForValidation struct {
- ID string
- TestKBID string
- KnowledgeID string
+ ID string
+ TestKBID string
+ KnowledgeID string
+ TestInstanceURL string
+ TestInstanceTenant uint64
// TargetScope 决定这条知识发到哪个生产库(对内/对外)。自动批准策略依赖它:
// 默认只自动批准"对内","对外"仍要人工。
TargetScope string
@@ -71,6 +78,7 @@ type LegacyVerificationCandidate struct {
const loadPublicationForUploadSQL = `
SELECT p.id, p.source_item_version_id, p.test_kb_id, p.knowledge_id,
+ p.test_instance_url, p.test_instance_tenant,
p.ingest_state, p.processing_state, p.target_scope,
co.id, co.sha256, co.size_bytes, co.mime, co.validated_format,
co.local_spool_ref, si.title
@@ -89,7 +97,8 @@ WHERE p.id = $1
`
const loadPublicationForPollSQL = `
-SELECT id, test_kb_id, knowledge_id, processing_state, poll_sequence,
+SELECT id, test_kb_id, knowledge_id, test_instance_url, test_instance_tenant,
+ processing_state, poll_sequence,
last_remote_status, last_remote_updated_at, processing_started_at,
last_observed_at, updated_at
FROM test_publications
@@ -97,7 +106,7 @@ WHERE id = $1
`
const loadPublicationForValidationSQL = `
-SELECT id, test_kb_id, knowledge_id, target_scope
+SELECT id, test_kb_id, knowledge_id, test_instance_url, test_instance_tenant, target_scope
FROM test_publications
WHERE id = $1
AND ingest_state = 'uploaded'
@@ -223,8 +232,10 @@ ON CONFLICT (idempotency_key) DO NOTHING
const markUploadingSQL = `
UPDATE test_publications
SET ingest_state = 'uploading',
+ test_instance_url = $2,
+ test_instance_tenant = $3,
last_error = '',
- updated_at = $2
+ updated_at = $4
WHERE id = $1
AND ingest_state IN ('pending', 'uploading')
AND processing_state = 'pending'
@@ -393,6 +404,8 @@ func (s *Store) LoadPublicationForUpload(ctx context.Context, publicationID stri
&candidate.SourceItemVersionID,
&candidate.TestKBID,
&candidate.KnowledgeID,
+ &candidate.TestInstanceURL,
+ &candidate.TestInstanceTenant,
&ingestState,
&processingState,
&candidate.TargetScope,
@@ -422,6 +435,8 @@ func (s *Store) LoadPublicationForPoll(ctx context.Context, publicationID string
&publication.ID,
&publication.TestKBID,
&publication.KnowledgeID,
+ &publication.TestInstanceURL,
+ &publication.TestInstanceTenant,
&processingState,
&publication.PollSequence,
&publication.LastRemoteStatus,
@@ -446,6 +461,8 @@ func (s *Store) LoadPublicationForValidation(ctx context.Context, publicationID
&publication.ID,
&publication.TestKBID,
&publication.KnowledgeID,
+ &publication.TestInstanceURL,
+ &publication.TestInstanceTenant,
&publication.TargetScope,
)
if errors.Is(err, pgx.ErrNoRows) {
@@ -594,8 +611,8 @@ func (s *Store) RetryPublication(ctx context.Context, publicationID string, now
return nil
}
-func (s *Store) MarkUploading(ctx context.Context, publicationID string, now time.Time) error {
- tag, err := s.db.Exec(ctx, markUploadingSQL, publicationID, now)
+func (s *Store) MarkUploading(ctx context.Context, publicationID, instanceURL string, instanceTenant uint64, now time.Time) error {
+ tag, err := s.db.Exec(ctx, markUploadingSQL, publicationID, instanceURL, instanceTenant, now)
if err != nil {
return fmt.Errorf("mark test publication uploading: %w", err)
}
diff --git a/internal/platform/postgres/test_publications_integration_test.go b/internal/platform/postgres/test_publications_integration_test.go
index 211bc09..4c68024 100644
--- a/internal/platform/postgres/test_publications_integration_test.go
+++ b/internal/platform/postgres/test_publications_integration_test.go
@@ -64,7 +64,7 @@ func TestPublicationOrchestrationIsAtomicAndRejectsStaleTransitions(t *testing.T
if _, err := store.LoadPublicationForUpload(ctx, "publication-1"); err != nil {
t.Fatal(err)
}
- if err := store.MarkUploading(ctx, "publication-1", now); err != nil {
+ if err := store.MarkUploading(ctx, "publication-1", "", 0, now); err != nil {
t.Fatal(err)
}
if sequence, err := store.RecordUploadAndSchedulePoll(ctx, "publication-1", "knowledge-1", now, now.Add(10*time.Second)); err != nil || sequence != 1 {
diff --git a/internal/platform/postgres/test_publications_test.go b/internal/platform/postgres/test_publications_test.go
index 255dfe7..6b9eb62 100644
--- a/internal/platform/postgres/test_publications_test.go
+++ b/internal/platform/postgres/test_publications_test.go
@@ -39,7 +39,7 @@ func TestLoadPublicationForUploadMapsVerifiedCandidate(t *testing.T) {
func TestMarkUploadingRejectsStalePublicationState(t *testing.T) {
db := &recordingDB{commandTag: pgconn.NewCommandTag("UPDATE 0")}
- err := NewStore(db).MarkUploading(context.Background(), "publication-1", time.Date(2026, time.September, 4, 2, 0, 0, 0, time.UTC))
+ err := NewStore(db).MarkUploading(context.Background(), "publication-1", "", 0, time.Date(2026, time.September, 4, 2, 0, 0, 0, time.UTC))
if !errors.Is(err, ErrPublicationStateConflict) {
t.Fatalf("MarkUploading() error = %v, want ErrPublicationStateConflict", err)
}
@@ -380,6 +380,8 @@ func (publicationValidationRow) Scan(dest ...any) error {
*(dest[0].(*string)) = "publication-1"
*(dest[1].(*string)) = "kb-1"
*(dest[2].(*string)) = "knowledge-1"
+ *(dest[3].(*string)) = ""
+ *(dest[4].(*uint64)) = 0
return nil
}
@@ -547,13 +549,15 @@ func (row publicationPollRow) Scan(dest ...any) error {
*(dest[0].(*string)) = "publication-1"
*(dest[1].(*string)) = "kb-1"
*(dest[2].(*string)) = "knowledge-1"
- *(dest[3].(*string)) = string(governance.ProcessingProcessing)
- *(dest[4].(*int)) = 2
- *(dest[5].(*string)) = "processing"
- *(dest[6].(**time.Time)) = &row.now
- *(dest[7].(**time.Time)) = &row.now
+ *(dest[3].(*string)) = ""
+ *(dest[4].(*uint64)) = 0
+ *(dest[5].(*string)) = string(governance.ProcessingProcessing)
+ *(dest[6].(*int)) = 2
+ *(dest[7].(*string)) = "processing"
*(dest[8].(**time.Time)) = &row.now
*(dest[9].(**time.Time)) = &row.now
+ *(dest[10].(**time.Time)) = &row.now
+ *(dest[11].(**time.Time)) = &row.now
return nil
}
@@ -572,6 +576,8 @@ func (publicationUploadRow) Scan(dest ...any) error {
"version-1",
"kb-1",
"",
+ "", // test_instance_url
+ uint64(0),
string(governance.IngestPending),
string(governance.ProcessingPending),
"internal",
@@ -589,6 +595,8 @@ func (publicationUploadRow) Scan(dest ...any) error {
*target = value.(string)
case *int64:
*target = value.(int64)
+ case *uint64:
+ *target = value.(uint64)
case *governance.Visibility:
*target = governance.Visibility(value.(string))
case nil:
diff --git a/internal/platform/weknora/types.go b/internal/platform/weknora/types.go
index 71e5374..b3ebe6f 100644
--- a/internal/platform/weknora/types.go
+++ b/internal/platform/weknora/types.go
@@ -2,6 +2,8 @@ package weknora
import (
"io"
+ "net/url"
+ "strings"
"time"
)
@@ -98,6 +100,34 @@ type knowledgeBaseResponse struct {
Data KnowledgeBase `json:"data"`
}
+// InstanceIdentity is the verifiable identity of the WeKnora instance a call
+// actually reached: the normalized service address plus the tenant that owns
+// the knowledge base. Knowledge base ids alone cannot distinguish a cloned
+// instance, so workflows that stored an object must compare this before using
+// the object again.
+type InstanceIdentity struct {
+ BaseURL string
+ TenantID uint64
+}
+
+// NormalizeInstanceURL is the single comparison form for service addresses:
+// scheme/host are case-insensitive and a trailing slash is not a different
+// instance. Userinfo/query/fragment never reach storage (endpoints are
+// validated as bare origins), so they are deliberately dropped here.
+func NormalizeInstanceURL(raw string) string {
+ parsed, err := url.Parse(strings.TrimSpace(raw))
+ if err != nil || parsed.Host == "" {
+ return strings.TrimSpace(raw)
+ }
+ parsed.Scheme = strings.ToLower(parsed.Scheme)
+ parsed.Host = strings.ToLower(parsed.Host)
+ parsed.Path = strings.TrimRight(parsed.Path, "/")
+ parsed.User = nil
+ parsed.RawQuery = ""
+ parsed.Fragment = ""
+ return parsed.String()
+}
+
type chunkListResponse struct {
Success bool `json:"success"`
Data []Chunk `json:"data"`
diff --git a/internal/releaseadapter/v071/archive_test.go b/internal/releaseadapter/v071/archive_test.go
index b73f0f9..b5e7ed6 100644
--- a/internal/releaseadapter/v071/archive_test.go
+++ b/internal/releaseadapter/v071/archive_test.go
@@ -151,5 +151,5 @@ func testDocumentBundle(t *testing.T) *DocumentBundle {
func fixedArchiveTime() time.Time { return time.Date(2026, 9, 6, 11, 0, 0, 0, time.UTC) }
func releasePlanForArchive() releaseworkflow.PlanItem {
- return releaseworkflow.PlanItem{ReleaseExecutionID: "rx-safe", PublicationID: "tp-safe", SourceItemVersionID: "sv-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-v1", TestKnowledgeBaseID: "kb-safe", KnowledgeID: "knowledge-safe", DecidedVisibility: "internal"}
+ return releaseworkflow.PlanItem{ReleaseExecutionID: "rx-safe", PublicationID: "tp-safe", SourceItemVersionID: "sv-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-v1", TestKnowledgeBaseID: "kb-safe", TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000, KnowledgeID: "knowledge-safe", DecidedVisibility: "internal"}
}
diff --git a/internal/releaseadapter/v071/document_target.go b/internal/releaseadapter/v071/document_target.go
index d08ad93..b2a5201 100644
--- a/internal/releaseadapter/v071/document_target.go
+++ b/internal/releaseadapter/v071/document_target.go
@@ -3,7 +3,9 @@ package v071
import (
"context"
"errors"
+ "fmt"
+ "knowledge-governance/internal/platform/weknora"
"knowledge-governance/internal/releasebundle"
releaseworkflow "knowledge-governance/internal/workflows/release"
)
@@ -49,6 +51,11 @@ type DocumentTargetConfig struct {
Search searchDocumentTarget
Objects objectDocumentTarget
Verifier ProductionVerifier
+ // TargetInstanceURL/TargetTenantID are the executor's own route target. The
+ // console freezes the instance it verified the binding on; this side must
+ // match before any document write/restore.
+ TargetInstanceURL string
+ TargetTenantID uint64
}
type DocumentTarget struct {
@@ -63,6 +70,9 @@ func NewDocumentTarget(config DocumentTargetConfig) (*DocumentTarget, error) {
}
func (target *DocumentTarget) Contract(ctx context.Context, item releaseworkflow.PlanItem) (releasebundle.TargetContract, error) {
+ if err := target.checkInstance(item); err != nil {
+ return releasebundle.TargetContract{}, err
+ }
contract, err := target.config.Contract.Contract(ctx, item)
if err != nil {
return releasebundle.TargetContract{}, errors.New("inspect target release contract")
@@ -75,6 +85,9 @@ func (target *DocumentTarget) Contract(ctx context.Context, item releaseworkflow
// same target base. The archive itself keeps the canonical source-form bundle:
// the remap is deterministic, so a rollback re-derives the same target form.
func (target *DocumentTarget) loadBundle(item releaseworkflow.PlanItem, revision string) (*DocumentBundle, error) {
+ if err := target.checkInstance(item); err != nil {
+ return nil, err
+ }
bundle, err := target.config.Archive.Load(revision)
if err != nil {
return nil, err
@@ -86,6 +99,9 @@ func (target *DocumentTarget) loadBundle(item releaseworkflow.PlanItem, revision
}
func (target *DocumentTarget) Prepare(ctx context.Context, item releaseworkflow.PlanItem, exported releaseworkflow.ExportedBundle) (releaseworkflow.PreparedChange, error) {
+ if err := target.checkInstance(item); err != nil {
+ return releaseworkflow.PreparedChange{}, err
+ }
bundle, ok := exported.(*DocumentBundle)
if !ok || validateDocumentBundle(bundle) != nil || bundle.Manifest.ReleaseRevision != item.ReleaseRevision {
return releaseworkflow.PreparedChange{}, errors.New("invalid v0.7.1 target bundle")
@@ -219,6 +235,30 @@ func (target *DocumentTarget) VerifyRestored(ctx context.Context, item releasewo
return nil
}
+// checkInstance is the single instance-identity boundary for the document
+// release path. Empty identity means a pre-identity binding: the executor
+// cannot prove which instance it is, so it fails closed instead of writing to a
+// cloned instance that happens to expose the same knowledge base id.
+func (target *DocumentTarget) checkInstance(item releaseworkflow.PlanItem) error {
+ if item.TargetInstanceURL == "" || item.TargetTenantID == 0 {
+ return fmt.Errorf("%w: binding has no verified instance identity", releaseworkflow.ErrTargetInstanceMismatch)
+ }
+ if target.config.TargetInstanceURL == "" || target.config.TargetTenantID == 0 {
+ return fmt.Errorf("%w: executor target identity is not configured", releaseworkflow.ErrTargetInstanceMismatch)
+ }
+ if weknora.NormalizeInstanceURL(item.TargetInstanceURL) != weknora.NormalizeInstanceURL(target.config.TargetInstanceURL) {
+ return fmt.Errorf("%w: binding verified on %s, executor writes %s",
+ releaseworkflow.ErrTargetInstanceMismatch,
+ weknora.NormalizeInstanceURL(item.TargetInstanceURL),
+ weknora.NormalizeInstanceURL(target.config.TargetInstanceURL))
+ }
+ if item.TargetTenantID != target.config.TargetTenantID {
+ return fmt.Errorf("%w: binding tenant %d, executor tenant %d",
+ releaseworkflow.ErrTargetInstanceMismatch, item.TargetTenantID, target.config.TargetTenantID)
+ }
+ return nil
+}
+
func (target *DocumentTarget) restoreBundle(ctx context.Context, item releaseworkflow.PlanItem, revision string) error {
bundle, err := target.loadBundle(item, revision)
if err != nil {
diff --git a/internal/releaseadapter/v071/document_target_test.go b/internal/releaseadapter/v071/document_target_test.go
index 2a972f8..4fd3ba8 100644
--- a/internal/releaseadapter/v071/document_target_test.go
+++ b/internal/releaseadapter/v071/document_target_test.go
@@ -2,6 +2,7 @@ package v071
import (
"context"
+ "errors"
"os"
"reflect"
"testing"
@@ -20,7 +21,7 @@ func TestDocumentTargetCoordinatesPrepareActivateVerifyAndRollback(t *testing.T)
t.Fatal(err)
}
calls := []string{}
- target, err := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(current)}, Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}})
+ target, err := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(current)}, Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}, TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000})
if err != nil {
t.Fatal(err)
}
@@ -60,7 +61,7 @@ func TestDocumentTargetCompensatesFirstReleaseByDisableWithoutDelete(t *testing.
archive, _ := NewBundleArchive(root, 16*1024*1024)
bundle := testDocumentBundle(t)
calls := []string{}
- target, _ := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(bundle)}, Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}})
+ target, _ := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(bundle)}, Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls}, Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls}, TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000})
item := releasePlanForArchive()
change, err := target.Prepare(context.Background(), item, bundle)
if err != nil {
@@ -179,3 +180,44 @@ func revisionFromSearch(snapshot SearchSnapshot) string {
}
return "unknown"
}
+
+// 网页在实例 A 上列库并保存了绑定,执行器实际连的是实例 B;即使两边知识库
+// ID 与租户完全相同,也不得写入 B。这里复用 DocumentTarget 的唯一实例身份
+// 检查,正例证明同一实例仍可通过。
+func TestDocumentTargetRejectsBindingVerifiedOnAnotherInstance(t *testing.T) {
+ root := t.TempDir()
+ _ = os.Chmod(root, 0o700)
+ archive, _ := NewBundleArchive(root, 16*1024*1024)
+ bundle := testDocumentBundle(t)
+ calls := []string{}
+ target, err := NewDocumentTarget(DocumentTargetConfig{
+ Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(bundle)},
+ Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls},
+ Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls},
+ TargetInstanceURL: "https://instance-b.weknora.example", TargetTenantID: 10000,
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ item := releasePlanForArchive() // verified on instance A, same kb id, same tenant
+ item.TargetKnowledgeBaseID = "kb-safe"
+ if _, err := target.Contract(context.Background(), item); !errors.Is(err, releaseworkflow.ErrTargetInstanceMismatch) {
+ t.Fatalf("contract error = %v, want ErrTargetInstanceMismatch", err)
+ }
+ if _, err := target.Prepare(context.Background(), item, bundle); !errors.Is(err, releaseworkflow.ErrTargetInstanceMismatch) {
+ t.Fatalf("prepare error = %v, want ErrTargetInstanceMismatch", err)
+ }
+ if len(calls) != 0 {
+ t.Fatalf("no write/stage may happen before identity matches: %v", calls)
+ }
+
+ item.TargetInstanceURL = "https://instance-b.weknora.example"
+ item.TargetTenantID = 10000
+ if _, err := target.Contract(context.Background(), item); err != nil {
+ t.Fatalf("same instance must pass: %v", err)
+ }
+ item.TargetTenantID = 20000
+ if _, err := target.Contract(context.Background(), item); !errors.Is(err, releaseworkflow.ErrTargetInstanceMismatch) {
+ t.Fatalf("tenant mismatch error = %v, want ErrTargetInstanceMismatch", err)
+ }
+}
diff --git a/internal/releaseadapter/v071/three_lane_integration_test.go b/internal/releaseadapter/v071/three_lane_integration_test.go
index 29857bd..2478983 100644
--- a/internal/releaseadapter/v071/three_lane_integration_test.go
+++ b/internal/releaseadapter/v071/three_lane_integration_test.go
@@ -97,7 +97,7 @@ func TestLegacyThreeLanePublishRefusesUnplannedWritesIntegration(t *testing.T) {
}
verification := &verificationClient{knowledge: weknora.Knowledge{ID: "knowledge-release-safe", KnowledgeBaseID: "kb-release-safe", ParseStatus: "completed"}, chunkTotal: 1, search: []weknora.SearchResult{{ID: "chunk-release-safe", KnowledgeID: "knowledge-release-safe", Score: 0.8}}}
verifier, _ := NewWeKnoraVerifier(verification)
- target, err := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: contract}, Postgres: postgresImporter, Search: targetSearch, Objects: objectImporter, Verifier: verifier})
+ target, err := NewDocumentTarget(DocumentTargetConfig{Archive: archive, Contract: &stubContractInspector{contract: contract}, Postgres: postgresImporter, Search: targetSearch, Objects: objectImporter, Verifier: verifier, TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000})
if err != nil {
t.Fatal(err)
}
@@ -106,7 +106,7 @@ func TestLegacyThreeLanePublishRefusesUnplannedWritesIntegration(t *testing.T) {
t.Fatal(err)
}
- first := releaseworkflow.PlanItem{ReleaseExecutionID: "rx-release-1", PublicationID: "tp-release-1", SourceItemVersionID: "version-release-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-release-1", TestKnowledgeBaseID: "kb-release-safe", KnowledgeID: "knowledge-release-safe", DecidedVisibility: "internal"}
+ first := releaseworkflow.PlanItem{ReleaseExecutionID: "rx-release-1", PublicationID: "tp-release-1", SourceItemVersionID: "version-release-safe", SourceRevision: "source-v1", ParseRevision: "parser-v1@index-v1", ReleaseRevision: "review-release-1", TestKnowledgeBaseID: "kb-release-safe", TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000, KnowledgeID: "knowledge-release-safe", DecidedVisibility: "internal"}
if _, err := exporter.Export(ctx, first); err != nil {
t.Fatalf("export preflight: %v", err)
}
diff --git a/internal/releaseadapter/v071/wiki_channel_test.go b/internal/releaseadapter/v071/wiki_channel_test.go
index c40a4cf..86aa5b8 100644
--- a/internal/releaseadapter/v071/wiki_channel_test.go
+++ b/internal/releaseadapter/v071/wiki_channel_test.go
@@ -182,6 +182,7 @@ func TestDocumentTargetAppliesWikiSnapshotWhenWithdrawing(t *testing.T) {
Archive: archive, Contract: &stubContractInspector{contract: targetContractForBundle(bundle)},
Postgres: &stubPostgresTarget{calls: &calls}, Search: &stubSearchTarget{calls: &calls},
Objects: &stubObjectTarget{calls: &calls}, Verifier: &stubProductionVerifier{calls: &calls},
+ TargetInstanceURL: "https://executor.weknora.example", TargetTenantID: 10000,
})
if err != nil {
t.Fatal(err)
diff --git a/internal/weknoraaccess/client.go b/internal/weknoraaccess/client.go
index 2ce9dab..dd12f31 100644
--- a/internal/weknoraaccess/client.go
+++ b/internal/weknoraaccess/client.go
@@ -47,6 +47,37 @@ func (client *Client) with(ctx context.Context, call func(*weknora.Client) error
return call(remote)
}
+func (client *Client) TargetIdentity(ctx context.Context, knowledgeBaseID string) (weknora.InstanceIdentity, error) {
+ target, err := client.Resolver.Resolve(ctx)
+ if err != nil {
+ return weknora.InstanceIdentity{}, err
+ }
+ if target.BaseURL == "" || target.APIKey == "" || knowledgeBaseID == "" {
+ return weknora.InstanceIdentity{}, ErrNotConfigured
+ }
+ timeout := client.Timeout
+ if timeout <= 0 {
+ timeout = defaultBusinessTimeout
+ }
+ remote, err := weknora.NewClient(weknora.ClientConfig{
+ BaseURL: target.BaseURL,
+ APIKey: target.APIKey,
+ Timeout: timeout,
+ AllowDockerHTTP: client.AllowDockerHTTP,
+ })
+ if err != nil {
+ return weknora.InstanceIdentity{}, err
+ }
+ base, err := remote.GetKnowledgeBase(ctx, knowledgeBaseID)
+ if err != nil {
+ return weknora.InstanceIdentity{}, err
+ }
+ return weknora.InstanceIdentity{
+ BaseURL: weknora.NormalizeInstanceURL(target.BaseURL),
+ TenantID: base.TenantID,
+ }, nil
+}
+
func (client *Client) UploadFile(ctx context.Context, request weknora.UploadRequest) (weknora.Knowledge, error) {
var knowledge weknora.Knowledge
err := client.with(ctx, func(remote *weknora.Client) error {
diff --git a/internal/weknoraaccess/client_test.go b/internal/weknoraaccess/client_test.go
index 6faedc2..e51db15 100644
--- a/internal/weknoraaccess/client_test.go
+++ b/internal/weknoraaccess/client_test.go
@@ -108,3 +108,26 @@ func TestExplicitShortBusinessTimeoutStillApplies(t *testing.T) {
t.Fatalf("explicit short timeout took %s", elapsed)
}
}
+
+func TestTargetIdentityReadsTheOwnedTenantFromTheCurrentBinding(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/v1/knowledge-bases/kb-current" {
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ _, _ = w.Write([]byte(`{"success":true,"data":{"id":"kb-current","name":"Current","tenant_id":10000}}`))
+ }))
+ defer server.Close()
+ client := &Client{Resolver: readiness.Resolver{
+ Endpoint: func(context.Context) string { return server.URL + "/" },
+ ReadKey: func() (string, error) { return "isolated-test-key", nil },
+ LoadBinding: func(context.Context) (string, error) { return "kb-current", nil },
+ }, Timeout: time.Second}
+ identity, err := client.TargetIdentity(context.Background(), "kb-current")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if identity.BaseURL != server.URL || identity.TenantID != 10000 {
+ t.Fatalf("identity = %#v", identity)
+ }
+}
diff --git a/internal/workflows/release/handler.go b/internal/workflows/release/handler.go
index bdf550b..f9b0a7c 100644
--- a/internal/workflows/release/handler.go
+++ b/internal/workflows/release/handler.go
@@ -37,6 +37,9 @@ var (
ErrInvalidReleaseJob = errors.New("invalid_release_job")
ErrReleaseRetryable = errors.New("release_retryable")
ErrReleaseState = errors.New("release_state_failed")
+ // ErrTargetInstanceMismatch: the binding was verified on instance A while
+ // the executor writes instance B (even with the same knowledge base id).
+ ErrTargetInstanceMismatch = errors.New("release_target_instance_mismatch")
)
type PlanItem struct {
@@ -51,7 +54,13 @@ type PlanItem struct {
// TargetKnowledgeBaseID is the 源库 → 目标库 mapping resolved when the
// execution started (see production_kb_bindings). It equals the tested base
// when the scope is unbound, which is the historical same-id semantics.
- TargetKnowledgeBaseID string `json:"target_knowledge_base_id"`
+ TargetKnowledgeBaseID string `json:"target_knowledge_base_id"`
+ // TargetInstanceURL/TargetTenantID freeze the instance identity the console
+ // verified the selected base on. The executor compares them with its own
+ // route target before any write; a cloned instance with the same base id is
+ // not the same target.
+ TargetInstanceURL string `json:"target_instance_url,omitempty"`
+ TargetTenantID uint64 `json:"target_tenant_id,omitempty"`
KnowledgeID string `json:"knowledge_id"`
DecidedVisibility governance.Visibility `json:"decided_visibility"`
PreviousProductionRevision string `json:"previous_production_revision"`
diff --git a/internal/workflows/release/sidecar_publisher.go b/internal/workflows/release/sidecar_publisher.go
index 9e4744e..8ec3dd4 100644
--- a/internal/workflows/release/sidecar_publisher.go
+++ b/internal/workflows/release/sidecar_publisher.go
@@ -132,7 +132,7 @@ func (publisher *SidecarPublisher) Publish(ctx context.Context, item PlanItem) (
}
targetContract, err := publisher.target.Contract(ctx, item)
if err != nil {
- return ItemResult{}, newSidecarError(ErrorCodeTargetUnavailable, true, err)
+ return ItemResult{}, targetError(err)
}
if err := releasebundle.Validate(manifest, targetContract, releaseItemMapping(item)); err != nil {
return ItemResult{}, newSidecarError(ErrorCodeContractMismatch, false, err)
@@ -166,7 +166,7 @@ func (publisher *SidecarPublisher) Rollback(ctx context.Context, item PlanItem)
}
restoredRevision, err := publisher.target.Restore(ctx, item, item.PreviousProductionRevision)
if err != nil {
- return ItemResult{}, newSidecarError(ErrorCodeTargetWriteFailed, true, err)
+ return ItemResult{}, targetError(err)
}
if restoredRevision != item.PreviousProductionRevision {
return ItemResult{}, newSidecarError(ErrorCodeContractMismatch, false, errors.New("restored revision mismatch"))
@@ -197,7 +197,7 @@ func (publisher *SidecarPublisher) Delete(ctx context.Context, item PlanItem) (I
}
targetContract, err := publisher.target.Contract(ctx, item)
if err != nil {
- return ItemResult{}, newSidecarError(ErrorCodeTargetUnavailable, true, err)
+ return ItemResult{}, targetError(err)
}
if err := releasebundle.Validate(manifest, targetContract, releaseItemMapping(item)); err != nil {
return ItemResult{}, newSidecarError(ErrorCodeContractMismatch, false, err)
@@ -224,6 +224,9 @@ func (publisher *SidecarPublisher) Delete(ctx context.Context, item PlanItem) (I
func (publisher *SidecarPublisher) compensateError(ctx context.Context, item PlanItem, change PreparedChange, code string, cause error) error {
if err := publisher.target.Compensate(ctx, item, change); err != nil {
+ if errors.Is(err, ErrTargetInstanceMismatch) {
+ return newSidecarError(ErrorCodeContractMismatch, false, err)
+ }
return newSidecarError(ErrorCodeRollbackFailed, false, err)
}
return newSidecarError(code, false, cause)
@@ -233,6 +236,15 @@ func newSidecarError(code string, retryable bool, cause error) error {
return &ItemError{Code: code, Retryable: retryable, Cause: cause}
}
+// targetError keeps an instance mismatch non-retryable: retrying the same item
+// on the same wrong instance will never become the verified target.
+func targetError(err error) error {
+ if errors.Is(err, ErrTargetInstanceMismatch) {
+ return newSidecarError(ErrorCodeContractMismatch, false, err)
+ }
+ return newSidecarError(ErrorCodeTargetUnavailable, true, err)
+}
+
func validRevision(value string) bool {
return value == strings.TrimSpace(value) && value != "" && len(value) <= 128 && !strings.ContainsAny(value, "\x00\r\n\t/?#\\")
}
diff --git a/internal/workflows/release/sidecar_publisher_test.go b/internal/workflows/release/sidecar_publisher_test.go
index efb334f..d375e04 100644
--- a/internal/workflows/release/sidecar_publisher_test.go
+++ b/internal/workflows/release/sidecar_publisher_test.go
@@ -163,6 +163,7 @@ func (bundle fakeExportedBundle) ReleaseManifest() releasebundle.Manifest { retu
type fakeSidecarTarget struct {
contract releasebundle.TargetContract
+ contractErr error
calls *[]string
prepared PreparedChange
prepareErr, activateErr, verifyErr, compensateErr, restoreErr, verifyRestoredErr error
@@ -172,7 +173,7 @@ type fakeSidecarTarget struct {
func (f *fakeSidecarTarget) Contract(context.Context, PlanItem) (releasebundle.TargetContract, error) {
*f.calls = append(*f.calls, "contract")
- return f.contract, nil
+ return f.contract, f.contractErr
}
func (f *fakeSidecarTarget) Prepare(context.Context, PlanItem, ExportedBundle) (PreparedChange, error) {
*f.calls = append(*f.calls, "prepare")
@@ -360,3 +361,26 @@ func TestSidecarPublisherGatesDeleteAndRollbackToo(t *testing.T) {
}
}
}
+
+// Instance identity mismatch is a contract failure, not a transient target
+// outage: retrying the same item on the same wrong instance can never succeed.
+func TestSidecarPublisherMapsInstanceMismatchToNonRetryableContractError(t *testing.T) {
+ calls := []string{}
+ manifest, err := releasebundle.Seal(testManifest())
+ if err != nil {
+ t.Fatal(err)
+ }
+ publisher, err := NewSidecarPublisher(&fakeExporter{manifest: manifest, calls: &calls},
+ &fakeSidecarTarget{contract: testTargetContract(), contractErr: ErrTargetInstanceMismatch, calls: &calls})
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = publisher.Publish(context.Background(), testPlanItem())
+ var itemErr *ItemError
+ if !errors.As(err, &itemErr) || itemErr.Code != ErrorCodeContractMismatch || itemErr.Retryable {
+ t.Fatalf("error=%#v", err)
+ }
+ if !reflect.DeepEqual(calls, []string{"export", "contract"}) {
+ t.Fatalf("calls=%v", calls)
+ }
+}
diff --git a/internal/workflows/testweknora/identity.go b/internal/workflows/testweknora/identity.go
new file mode 100644
index 0000000..53bd741
--- /dev/null
+++ b/internal/workflows/testweknora/identity.go
@@ -0,0 +1,38 @@
+package testweknora
+
+import (
+ "context"
+
+ "knowledge-governance/internal/platform/weknora"
+)
+
+// IdentityProvider is implemented by the production WeKnora access client. Unit
+// fakes may omit it; a handler must then treat stored identities as unverifiable
+// and never write/delete/adopt an object across instances.
+type IdentityProvider interface {
+ TargetIdentity(context.Context, string) (weknora.InstanceIdentity, error)
+}
+
+func resolveIdentity(ctx context.Context, client any, knowledgeBaseID string) (weknora.InstanceIdentity, bool, error) {
+ provider, ok := client.(IdentityProvider)
+ if !ok {
+ return weknora.InstanceIdentity{}, false, nil
+ }
+ identity, err := provider.TargetIdentity(ctx, knowledgeBaseID)
+ if err != nil {
+ return weknora.InstanceIdentity{}, true, err
+ }
+ identity.BaseURL = weknora.NormalizeInstanceURL(identity.BaseURL)
+ return identity, true, nil
+}
+
+// identityMatches requires BOTH the instance address and the owning tenant to
+// match. A cloned instance can expose the same knowledge base id and tenant id;
+// an empty stored identity is never treated as "matches anything".
+func identityMatches(storedURL string, storedTenant uint64, current weknora.InstanceIdentity) bool {
+ if storedURL == "" || storedTenant == 0 {
+ return false
+ }
+ return weknora.NormalizeInstanceURL(storedURL) == weknora.NormalizeInstanceURL(current.BaseURL) &&
+ storedTenant == current.TenantID
+}
diff --git a/internal/workflows/testweknora/identity_test.go b/internal/workflows/testweknora/identity_test.go
new file mode 100644
index 0000000..1fd9e97
--- /dev/null
+++ b/internal/workflows/testweknora/identity_test.go
@@ -0,0 +1,152 @@
+package testweknora
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+
+ "knowledge-governance/internal/governance"
+ "knowledge-governance/internal/jobs"
+ postgresstore "knowledge-governance/internal/platform/postgres"
+ "knowledge-governance/internal/platform/weknora"
+)
+
+const (
+ instanceA = "https://instance-a.weknora.example"
+ instanceB = "https://instance-b.weknora.example"
+)
+
+type identityClient struct {
+ identity weknora.InstanceIdentity
+ identityErr error
+ knowledge weknora.Knowledge
+ chunkTotal int64
+ getCalls int
+ chunkCalls int
+ deleteCalls int
+ uploadCalls int
+}
+
+func (client *identityClient) TargetIdentity(context.Context, string) (weknora.InstanceIdentity, error) {
+ return client.identity, client.identityErr
+}
+func (client *identityClient) GetKnowledge(context.Context, string) (weknora.Knowledge, error) {
+ client.getCalls++
+ if client.knowledge.ID == "" {
+ return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404}
+ }
+ return client.knowledge, nil
+}
+func (client *identityClient) ListChunks(context.Context, string, int, int, []string) ([]weknora.Chunk, int64, error) {
+ client.chunkCalls++
+ return []weknora.Chunk{{ID: "chunk-1"}}, client.chunkTotal, nil
+}
+func (client *identityClient) DeleteKnowledge(context.Context, string) error {
+ client.deleteCalls++
+ return nil
+}
+func (client *identityClient) UploadFile(context.Context, weknora.UploadRequest) (weknora.Knowledge, error) {
+ client.uploadCalls++
+ return weknora.Knowledge{}, errors.New("unexpected upload")
+}
+func (client *identityClient) ListKnowledge(context.Context, string, int, int) ([]weknora.Knowledge, int64, error) {
+ return nil, 0, nil
+}
+
+func TestPollRejectsObjectUploadedToAnotherInstance(t *testing.T) {
+ now := time.Date(2026, 11, 19, 9, 0, 0, 0, time.UTC)
+ store := &pollStoreStub{publication: postgresstore.PublicationForPoll{
+ ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1",
+ TestInstanceURL: instanceA, TestInstanceTenant: 10000,
+ ProcessingState: governance.ProcessingProcessing, PollSequence: 2,
+ }}
+ client := &identityClient{
+ identity: weknora.InstanceIdentity{BaseURL: instanceB, TenantID: 10000},
+ knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1", ParseStatus: "completed"},
+ }
+ handler, _ := NewPollHandler(PollHandlerConfig{Store: store, Client: client, PollDelay: time.Second, StallAfter: time.Hour, Now: func() time.Time { return now }})
+ if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1","sequence":2}`)}); err != nil {
+ t.Fatalf("identity mismatch must be a visible terminal state, not a retry error: %v", err)
+ }
+ if client.getCalls != 0 || store.failureCode != "remote_instance_changed" {
+ t.Fatalf("getCalls=%d failureCode=%q", client.getCalls, store.failureCode)
+ }
+}
+
+func TestPollAcceptsObjectOnTheSameInstanceAndTenant(t *testing.T) {
+ now := time.Date(2026, 11, 19, 9, 0, 0, 0, time.UTC)
+ store := &pollStoreStub{publication: postgresstore.PublicationForPoll{
+ ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1",
+ TestInstanceURL: instanceA, TestInstanceTenant: 10000,
+ ProcessingState: governance.ProcessingProcessing, PollSequence: 2,
+ }}
+ client := &identityClient{
+ identity: weknora.InstanceIdentity{BaseURL: instanceA, TenantID: 10000},
+ knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1", ParseStatus: "finalizing"},
+ }
+ handler, _ := NewPollHandler(PollHandlerConfig{Store: store, Client: client, PollDelay: time.Second, StallAfter: time.Hour, Now: func() time.Time { return now }})
+ if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1","sequence":2}`)}); err != nil {
+ t.Fatal(err)
+ }
+ if client.getCalls != 1 || store.recordedState != governance.ProcessingFinalizing {
+ t.Fatalf("getCalls=%d state=%v", client.getCalls, store.recordedState)
+ }
+}
+
+func TestRemoveRefusesToDeleteACloneObject(t *testing.T) {
+ store := &removalStoreStub{candidate: postgresstore.PublicationForRemoval{
+ ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1",
+ TestInstanceURL: instanceA, TestInstanceTenant: 10000,
+ }}
+ client := &identityClient{identity: weknora.InstanceIdentity{BaseURL: instanceB, TenantID: 10000},
+ knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1"}}
+ handler, _ := NewRemoveHandler(RemoveHandlerConfig{Store: store, Client: client})
+ if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1"}`)}); err != nil {
+ t.Fatal(err)
+ }
+ if client.deleteCalls != 0 || client.getCalls != 0 || store.failed != "publication-1:removal_instance_changed" {
+ t.Fatalf("deleteCalls=%d getCalls=%d failed=%q", client.deleteCalls, client.getCalls, store.failed)
+ }
+}
+
+func TestValidateFailsClosedWithoutReadingTheClone(t *testing.T) {
+ store := &validateStoreStub{publication: postgresstore.PublicationForValidation{
+ ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1",
+ TestInstanceURL: instanceA, TestInstanceTenant: 10000,
+ }}
+ client := &identityClient{identity: weknora.InstanceIdentity{BaseURL: instanceB, TenantID: 20000},
+ knowledge: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1"}, chunkTotal: 3}
+ handler, _ := NewValidateHandler(ValidateHandlerConfig{Store: store, Client: client, PolicyVersion: "structural-v1"})
+ if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1"}`)}); err != nil {
+ t.Fatal(err)
+ }
+ if client.getCalls != 0 || client.chunkCalls != 0 {
+ t.Fatalf("clone was read: get=%d chunks=%d", client.getCalls, client.chunkCalls)
+ }
+ states := map[string]governance.AcceptanceState{}
+ for _, result := range store.appended {
+ states[result.CheckType] = result.State
+ }
+ if states["knowledge_exists"] != governance.AcceptanceFailed || states["chunks_present"] != governance.AcceptanceFailed {
+ t.Fatalf("acceptance states = %#v", states)
+ }
+}
+
+func TestUploadRefusesToWriteAfterRebindingToAnotherInstance(t *testing.T) {
+ store := &uploadStoreStub{candidate: postgresstore.PublicationForUpload{
+ ID: "publication-1", TestKBID: "kb-1", TestInstanceURL: instanceA, TestInstanceTenant: 10000,
+ IngestState: governance.IngestPending, ProcessingState: governance.ProcessingPending,
+ TargetScope: governance.VisibilityInternal,
+ }}
+ client := &identityClient{identity: weknora.InstanceIdentity{BaseURL: instanceB, TenantID: 10000}}
+ handler, _ := NewUploadHandler(UploadHandlerConfig{
+ Store: store, Client: client, SpoolRoot: t.TempDir(), MaxUploadBytes: 1024, FirstPollDelay: time.Second,
+ })
+ if err := handler.Handle(context.Background(), jobs.Job{Payload: []byte(`{"publication_id":"publication-1","target_kb_id":"kb-1","target_scope":"internal"}`)}); err != nil {
+ t.Fatal(err)
+ }
+ if client.uploadCalls != 0 || store.uploadFailureCode != "upload_instance_changed" {
+ t.Fatalf("uploadCalls=%d failure=%q", client.uploadCalls, store.uploadFailureCode)
+ }
+}
diff --git a/internal/workflows/testweknora/poll.go b/internal/workflows/testweknora/poll.go
index 8af0a59..bc1ffcf 100644
--- a/internal/workflows/testweknora/poll.go
+++ b/internal/workflows/testweknora/poll.go
@@ -82,6 +82,17 @@ func (handler *PollHandler) Handle(ctx context.Context, job jobs.Job) error {
return ErrPollStateConflict
}
now := handler.now()
+ identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, publication.TestKBID)
+ if identityErr != nil {
+ return ErrPollRemoteFailed
+ }
+ if hasProvider && !identityMatches(publication.TestInstanceURL, publication.TestInstanceTenant, identity) {
+ // 旧对象属于另一个实例/租户:不能在新实例上按同名/同 ID 的对象继续推进。
+ if err := handler.store.RecordProcessingFailure(ctx, publication.ID, publication.PollSequence, "remote_instance_changed", now); err != nil {
+ return ErrPollStateConflict
+ }
+ return nil
+ }
knowledge, err := handler.client.GetKnowledge(ctx, publication.KnowledgeID)
if err != nil {
return ErrPollRemoteFailed
diff --git a/internal/workflows/testweknora/poll_test.go b/internal/workflows/testweknora/poll_test.go
index 4987fcc..890c4e5 100644
--- a/internal/workflows/testweknora/poll_test.go
+++ b/internal/workflows/testweknora/poll_test.go
@@ -158,6 +158,7 @@ type pollStoreStub struct {
completedValidated bool
stalledMarked bool
stalledCutoff time.Time
+ failureCode string
}
func (store *pollStoreStub) LoadPublicationForPoll(context.Context, string) (postgresstore.PublicationForPoll, error) {
@@ -177,7 +178,8 @@ func (store *pollStoreStub) RecordCompletedAndScheduleValidation(_ context.Conte
return nil
}
-func (store *pollStoreStub) RecordProcessingFailure(context.Context, string, int, string, time.Time) error {
+func (store *pollStoreStub) RecordProcessingFailure(_ context.Context, _ string, _ int, code string, _ time.Time) error {
+ store.failureCode = code
return nil
}
diff --git a/internal/workflows/testweknora/remove.go b/internal/workflows/testweknora/remove.go
index ebacadd..b76cba6 100644
--- a/internal/workflows/testweknora/remove.go
+++ b/internal/workflows/testweknora/remove.go
@@ -65,6 +65,14 @@ func (handler *RemoveHandler) Handle(ctx context.Context, job jobs.Job) error {
if err != nil {
return ErrRemoveStateConflict
}
+ identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, candidate.TestKBID)
+ if identityErr != nil {
+ return ErrRemoveRemoteFailed
+ }
+ if hasProvider && !identityMatches(candidate.TestInstanceURL, candidate.TestInstanceTenant, identity) {
+ // 不能拿旧实例的对象 ID 到新实例上删除同名对象。
+ return handler.failClosed(ctx, candidate.ID, "removal_instance_changed")
+ }
knowledge, err := handler.client.GetKnowledge(ctx, candidate.KnowledgeID)
if isNotFound(err) {
return handler.complete(ctx, candidate.ID)
diff --git a/internal/workflows/testweknora/upload.go b/internal/workflows/testweknora/upload.go
index d520238..0d794b7 100644
--- a/internal/workflows/testweknora/upload.go
+++ b/internal/workflows/testweknora/upload.go
@@ -27,7 +27,7 @@ var (
type UploadStore interface {
LoadPublicationForUpload(context.Context, string) (postgresstore.PublicationForUpload, error)
- MarkUploading(context.Context, string, time.Time) error
+ MarkUploading(context.Context, string, string, uint64, time.Time) error
RecordUploadAndSchedulePoll(context.Context, string, string, time.Time, time.Time) (int, error)
RecordUploadFailure(context.Context, string, string, time.Time) error
}
@@ -93,6 +93,20 @@ func (handler *UploadHandler) Handle(ctx context.Context, job jobs.Job) error {
if payload.TargetScope != "" && payload.TargetScope != string(candidate.TargetScope) {
return ErrUploadStateConflict
}
+ identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, candidate.TestKBID)
+ if identityErr != nil {
+ return ErrUploadRemoteFailed
+ }
+ if hasProvider {
+ if candidate.TestInstanceURL != "" || candidate.TestInstanceTenant != 0 {
+ if !identityMatches(candidate.TestInstanceURL, candidate.TestInstanceTenant, identity) {
+ return handler.recordTerminalUploadFailure(ctx, candidate.ID, "upload_instance_changed")
+ }
+ } else if candidate.IngestState == governance.IngestUploading {
+ // 旧行没有实例身份,又可能已经写到了旧实例:不能在克隆实例上恢复/接管。
+ return handler.recordTerminalUploadFailure(ctx, candidate.ID, "upload_instance_unknown")
+ }
+ }
if candidate.IngestState == governance.IngestUploading {
knowledge, err := handler.recoverAmbiguousUpload(ctx, candidate)
if err != nil {
@@ -117,7 +131,7 @@ func (handler *UploadHandler) Handle(ctx context.Context, job jobs.Job) error {
return handler.recordTerminalUploadFailure(ctx, candidate.ID, "upload_artifact_invalid")
}
defer artifact.Close()
- if err := handler.store.MarkUploading(ctx, candidate.ID, handler.now()); err != nil {
+ if err := handler.store.MarkUploading(ctx, candidate.ID, identity.BaseURL, identity.TenantID, handler.now()); err != nil {
return ErrUploadStateConflict
}
knowledge, uploadErr := handler.client.UploadFile(ctx, weknora.UploadRequest{
diff --git a/internal/workflows/testweknora/upload_test.go b/internal/workflows/testweknora/upload_test.go
index b60826d..257b857 100644
--- a/internal/workflows/testweknora/upload_test.go
+++ b/internal/workflows/testweknora/upload_test.go
@@ -312,19 +312,23 @@ func TestUploadHandlerRecordsInvalidArtifactForManualRetry(t *testing.T) {
}
type uploadStoreStub struct {
- candidate postgresstore.PublicationForUpload
- markedUploading bool
- recordedKnowledgeID string
- nextPollAt time.Time
- uploadFailureCode string
+ candidate postgresstore.PublicationForUpload
+ markedUploading bool
+ markedInstanceURL string
+ markedInstanceTenant uint64
+ recordedKnowledgeID string
+ nextPollAt time.Time
+ uploadFailureCode string
}
func (store *uploadStoreStub) LoadPublicationForUpload(context.Context, string) (postgresstore.PublicationForUpload, error) {
return store.candidate, nil
}
-func (store *uploadStoreStub) MarkUploading(context.Context, string, time.Time) error {
+func (store *uploadStoreStub) MarkUploading(_ context.Context, _ string, instanceURL string, tenantID uint64, _ time.Time) error {
store.markedUploading = true
+ store.markedInstanceURL = instanceURL
+ store.markedInstanceTenant = tenantID
return nil
}
diff --git a/internal/workflows/testweknora/validate.go b/internal/workflows/testweknora/validate.go
index 911bb52..17a5d51 100644
--- a/internal/workflows/testweknora/validate.go
+++ b/internal/workflows/testweknora/validate.go
@@ -101,10 +101,25 @@ func (handler *ValidateHandler) Handle(ctx context.Context, job jobs.Job) error
runID = job.ID
}
- knowledge, knowledgeErr := handler.client.GetKnowledge(ctx, publication.KnowledgeID)
+ identity, hasProvider, identityErr := resolveIdentity(ctx, handler.client, publication.TestKBID)
+ identityOK := !hasProvider || (identityErr == nil &&
+ identityMatches(publication.TestInstanceURL, publication.TestInstanceTenant, identity))
+ identityReason := ""
+ if hasProvider {
+ switch {
+ case identityErr != nil:
+ identityReason = "instance_identity_unreadable"
+ case !identityOK:
+ identityReason = "instance_changed"
+ }
+ }
knowledgeState := governance.AcceptancePassed
knowledgeEvidence := json.RawMessage(`{"matched":true}`)
- if knowledgeErr != nil || knowledge.ID != publication.KnowledgeID || knowledge.KnowledgeBaseID != publication.TestKBID {
+ if !identityOK {
+ knowledgeState = governance.AcceptanceFailed
+ knowledgeEvidence = mustJSON(map[string]any{"matched": false, "reason": identityReason})
+ } else if knowledge, knowledgeErr := handler.client.GetKnowledge(ctx, publication.KnowledgeID); knowledgeErr != nil ||
+ knowledge.ID != publication.KnowledgeID || knowledge.KnowledgeBaseID != publication.TestKBID {
knowledgeState = governance.AcceptanceFailed
knowledgeEvidence = json.RawMessage(`{"matched":false}`)
}
@@ -112,10 +127,14 @@ func (handler *ValidateHandler) Handle(ctx context.Context, job jobs.Job) error
return err
}
- _, chunkTotal, chunksErr := handler.client.ListChunks(ctx, publication.KnowledgeID, 1, 1, nil)
chunksState := governance.AcceptancePassed
- if chunksErr != nil || chunkTotal <= 0 {
+ chunkTotal := int64(0)
+ if !identityOK {
chunksState = governance.AcceptanceFailed
+ } else if _, total, chunksErr := handler.client.ListChunks(ctx, publication.KnowledgeID, 1, 1, nil); chunksErr != nil || total <= 0 {
+ chunksState = governance.AcceptanceFailed
+ } else {
+ chunkTotal = total
}
if err := handler.append(ctx, publication.ID, runID, "chunks_present", chunksState, mustJSON(map[string]any{"chunk_total": chunkTotal}), now); err != nil {
return err
diff --git a/scripts/test-scope.json b/scripts/test-scope.json
index 4b6884b..8995585 100644
--- a/scripts/test-scope.json
+++ b/scripts/test-scope.json
@@ -658,6 +658,11 @@
"test": "TestV090ProductionTargetPublishIsolated",
"reason": "需显式一次性本机PG(两份 0.9.0 真 schema 库)/ES/对象存储:真实导出→封存→ProductionLibraryTarget 写入 134 目标→逐表核对→写前镜像回滚,验证 0.9.0 无 wiki_log_entries、chunks 新增 NOT NULL 列走默认值、seq_id 由目标序列分配;普通CI没有这些服务,跳过不是通过"
},
+ {
+ "package": "knowledge-governance/internal/platform/postgres",
+ "test": "TestStartReleaseExecutionFreezesTheBindingInstanceIdentity",
+ "reason": "需显式一次性本机治理PG(TEST_DATABASE_URL):真实迁移、审核/封存/授权后 StartExecution 必须把绑定实例地址与租户冻结进发布项;普通CI没有该库,跳过不是通过"
+ },
{
"package": "knowledge-governance/internal/kbbinding",
"test": "TestSaveReadsBackResolvesTheKeyAndReplansPendingInOneTransaction",
diff --git a/web/src/KnowledgeBaseBinding.test.tsx b/web/src/KnowledgeBaseBinding.test.tsx
index 33dec3f..ff5132c 100644
--- a/web/src/KnowledgeBaseBinding.test.tsx
+++ b/web/src/KnowledgeBaseBinding.test.tsx
@@ -181,6 +181,26 @@ describe('KnowledgeBaseBinding', () => {
expect(body.api_key).toBeUndefined()
})
+ it('does not allow saving until both directions have an explicit base', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn((url: string) => {
+ if (String(url) === '/api/v1/kb-bindings') return Promise.resolve(json(snapshot))
+ if (String(url).includes('/catalog')) return Promise.resolve(json(catalog))
+ return Promise.resolve(json({ data: binding('test') }))
+ })
+ )
+ await render()
+ await click('验证并读取知识库')
+ await choose('对内知识库', 'kb-new-in-0001')
+ await choose('对外知识库', '')
+ const save = [...host.querySelectorAll('button')].find((button) => button.textContent?.includes('保存测试绑定'))
+ expect(save?.hasAttribute('disabled')).toBe(true)
+ expect(host.textContent).toContain('未选择不会回落到旧实例的默认库')
+ await choose('对外知识库', 'kb-new-out-0001')
+ expect(save?.hasAttribute('disabled')).toBe(false)
+ })
+
it('gives viewers a read-only summary with no editing inputs', async () => {
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(json(snapshot)))
await render('viewer')
diff --git a/web/src/KnowledgeBaseBinding.tsx b/web/src/KnowledgeBaseBinding.tsx
index 6e9ce9e..a11e1b6 100644
--- a/web/src/KnowledgeBaseBinding.tsx
+++ b/web/src/KnowledgeBaseBinding.tsx
@@ -148,6 +148,8 @@ export function KnowledgeBaseBinding() {
storageReady &&
endpointValid &&
keyReady &&
+ draft.internalID !== '' &&
+ draft.externalID !== '' &&
!duplicate &&
catalogReady
)
@@ -520,7 +522,7 @@ export function KnowledgeBaseBinding() {
}}
disabled={busyNow !== '' || !draft.catalog || draft.catalog.status !== 'ok'}
>
-
+
{currentOptions.internal.map((option) => (
+
{currentOptions.external.map((option) => (