fix(release): 以实例身份阻断绑定与发布跨实例

网页可能在实例 A 上列库并保存生产绑定,而文档发布执行器实际连实例 B。
克隆实例可以有相同知识库 ID、名称甚至租户,单靠 ID 无法证明写的是同一个
目标。现在绑定保存会冻结候选实例地址/租户,发布计划把身份冻结到每个项,
执行器在 Contract/Prepare/Activate/Restore/Compensate 前核对;不一致以
release_contract_mismatch 非重试失败关闭,不写目标。整库发布目标不变。

测试入库对象在上传前记录实际实例地址/租户;轮询、验收、移除先核对当前
连接,改绑实例或租户后旧对象不会被克隆实例接管。旧行没有身份时失败关闭。

「知识库绑定」保存要求对内/对外各选一个库,不再把显式未绑定回落到部署
默认 ID,避免换绑实例后带过去旧对象的默认库。

验证:隔离 PostgreSQL 覆盖绑定身份落库与发布计划冻结;v071 用同 ID/同租户
的 A/B 实例做正反例;四个测试 handler 的实例错配负例;前端 607 项通过。
This commit is contained in:
姚章浩
2026-11-19 15:17:17 +08:00
parent ce2a155ebc
commit 1f5bf72aec
43 changed files with 823 additions and 113 deletions
+10 -1
View File
@@ -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"`
@@ -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/?#\\")
}
@@ -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)
}
}
@@ -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
}
@@ -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)
}
}
+11
View File
@@ -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
+3 -1
View File
@@ -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
}
+8
View File
@@ -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)
+16 -2
View File
@@ -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{
+10 -6
View File
@@ -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
}
+23 -4
View File
@@ -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