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) } }