package testweknora import ( "context" "crypto/sha256" "encoding/hex" "errors" "io" "os" "path/filepath" "testing" "time" "knowledge-governance/internal/governance" "knowledge-governance/internal/jobs" postgresstore "knowledge-governance/internal/platform/postgres" "knowledge-governance/internal/platform/spool" "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) } } type taskTokenKey struct{} // taskClient is a normal fake TaskConnector. BeginTask pins a token in the // context; every business method records which token it received. type taskClient struct { identity weknora.InstanceIdentity identityErr error beginCalls int tokens []string knowledge weknora.Knowledge uploadResult weknora.Knowledge listItems []weknora.Knowledge chunkTotal int64 deleteGone bool getCalls int chunkCalls int deleteCalls int uploadCalls int listCalls int } func (client *taskClient) BeginTask(ctx context.Context, _ string) (context.Context, weknora.InstanceIdentity, error) { client.beginCalls++ if client.identityErr != nil { return ctx, weknora.InstanceIdentity{}, client.identityErr } return context.WithValue(ctx, taskTokenKey{}, "connection-1"), client.identity, nil } func (client *taskClient) record(ctx context.Context) { token, _ := ctx.Value(taskTokenKey{}).(string) client.tokens = append(client.tokens, token) } func (client *taskClient) GetKnowledge(ctx context.Context, _ string) (weknora.Knowledge, error) { client.record(ctx) client.getCalls++ if client.deleteGone { return weknora.Knowledge{}, &weknora.HTTPError{StatusCode: 404} } return client.knowledge, nil } func (client *taskClient) ListChunks(ctx context.Context, _ string, _, _ int, _ []string) ([]weknora.Chunk, int64, error) { client.record(ctx) client.chunkCalls++ return []weknora.Chunk{{ID: "chunk-1"}}, client.chunkTotal, nil } func (client *taskClient) DeleteKnowledge(ctx context.Context, _ string) error { client.record(ctx) client.deleteCalls++ client.deleteGone = true return nil } func (client *taskClient) UploadFile(ctx context.Context, request weknora.UploadRequest) (weknora.Knowledge, error) { client.record(ctx) client.uploadCalls++ if request.Content != nil { _, _ = io.Copy(io.Discard, request.Content) } return client.uploadResult, nil } func (client *taskClient) ListKnowledge(ctx context.Context, _ string, _, _ int) ([]weknora.Knowledge, int64, error) { client.record(ctx) client.listCalls++ return client.listItems, int64(len(client.listItems)), nil } func (client *taskClient) assertOneConnection(t *testing.T) { t.Helper() if client.beginCalls != 1 { t.Fatalf("BeginTask calls=%d, want 1", client.beginCalls) } if len(client.tokens) == 0 { t.Fatal("no business call recorded") } for index, token := range client.tokens { if token != "connection-1" { t.Fatalf("call %d used connection %q, want pinned connection-1", index, token) } } } func TestPollUsesOneVerifiedConnectionForAllCalls(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 := &taskClient{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) } client.assertOneConnection(t) if client.getCalls != 1 || store.recordedState != governance.ProcessingFinalizing { t.Fatalf("getCalls=%d state=%v", client.getCalls, store.recordedState) } } func TestValidateUsesOneVerifiedConnectionForAllCalls(t *testing.T) { store := &validateStoreStub{publication: postgresstore.PublicationForValidation{ ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1", TestInstanceURL: instanceA, TestInstanceTenant: 10000, }} client := &taskClient{identity: weknora.InstanceIdentity{BaseURL: instanceA, TenantID: 10000}, 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) } client.assertOneConnection(t) if client.getCalls != 1 || client.chunkCalls != 1 { t.Fatalf("get=%d chunks=%d", client.getCalls, client.chunkCalls) } } func TestRemoveUsesOneVerifiedConnectionForDeleteAndReadBack(t *testing.T) { store := &removalStoreStub{candidate: postgresstore.PublicationForRemoval{ ID: "publication-1", TestKBID: "kb-1", KnowledgeID: "knowledge-1", TestInstanceURL: instanceA, TestInstanceTenant: 10000, }} client := &taskClient{identity: weknora.InstanceIdentity{BaseURL: instanceA, 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) } client.assertOneConnection(t) if client.getCalls != 2 || client.deleteCalls != 1 || store.completed != "publication-1" { t.Fatalf("get=%d delete=%d completed=%q", client.getCalls, client.deleteCalls, store.completed) } } func TestUploadUsesOneVerifiedConnectionForWrite(t *testing.T) { root := t.TempDir() if err := os.Mkdir(filepath.Join(root, "objects"), 0o700); err != nil { t.Fatal(err) } body := []byte("one connection only\n") if err := os.WriteFile(filepath.Join(root, "objects", "artifact.md"), body, 0o600); err != nil { t.Fatal(err) } digest := sha256.Sum256(body) sha := hex.EncodeToString(digest[:]) if inspected, inspectErr := spool.InspectVerified(root, "objects/artifact.md", "md", 1024); inspectErr != nil { t.Fatalf("inspect fixture: %v", inspectErr) } else if inspected.SHA256 != sha || inspected.SizeBytes != int64(len(body)) { t.Fatalf("inspect fixture = %#v", inspected) } store := &uploadStoreStub{candidate: postgresstore.PublicationForUpload{ ID: "publication-1", TestKBID: "kb-1", IngestState: governance.IngestPending, ProcessingState: governance.ProcessingPending, TargetScope: governance.VisibilityInternal, SHA256: sha, SizeBytes: int64(len(body)), ValidatedFormat: "md", LocalSpoolRef: "objects/artifact.md", Title: "One connection", }} client := &taskClient{identity: weknora.InstanceIdentity{BaseURL: instanceA, TenantID: 10000}, uploadResult: weknora.Knowledge{ID: "knowledge-1", KnowledgeBaseID: "kb-1", ParseStatus: "pending"}} handler, err := NewUploadHandler(UploadHandlerConfig{ Store: store, Client: client, SpoolRoot: root, MaxUploadBytes: 1024, FirstPollDelay: time.Second, }) if err != nil { t.Fatal(err) } 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) } client.assertOneConnection(t) if client.uploadCalls != 1 || store.markedInstanceURL != instanceA || store.markedInstanceTenant != 10000 { t.Fatalf("uploads=%d marked=%s/%d", client.uploadCalls, store.markedInstanceURL, store.markedInstanceTenant) } } func TestUploadRecoveryUsesTheSameVerifiedConnection(t *testing.T) { store := &uploadStoreStub{candidate: postgresstore.PublicationForUpload{ ID: "publication-1", TestKBID: "kb-1", IngestState: governance.IngestUploading, ProcessingState: governance.ProcessingPending, TargetScope: governance.VisibilityInternal, TestInstanceURL: instanceA, TestInstanceTenant: 10000, SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", SizeBytes: 10, ValidatedFormat: "md", LocalSpoolRef: "objects/artifact.md", Title: "Recovery", }} recovered := weknora.Knowledge{ ID: "knowledge-1", KnowledgeBaseID: "kb-1", Metadata: map[string]any{"publication_id": "publication-1", "content_sha256": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, } client := &taskClient{identity: weknora.InstanceIdentity{BaseURL: instanceA, TenantID: 10000}, knowledge: recovered, listItems: []weknora.Knowledge{recovered}} handler, err := NewUploadHandler(UploadHandlerConfig{ Store: store, Client: client, SpoolRoot: t.TempDir(), MaxUploadBytes: 1024, FirstPollDelay: time.Second, }) if err != nil { t.Fatal(err) } 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) } client.assertOneConnection(t) if client.listCalls != 1 || client.uploadCalls != 0 || store.recordedKnowledgeID != "knowledge-1" { t.Fatalf("list=%d upload=%d recorded=%q", client.listCalls, client.uploadCalls, store.recordedKnowledgeID) } }