//go:build integration package integration_test import ( "context" "encoding/json" "fmt" "log/slog" "math" "net/http" "net/http/httptest" "slices" "strings" "sync" "testing" "time" "github.com/google/uuid" mladapter "lincodex/backend/internal/adapter/secondary/ml" postgresadapter "lincodex/backend/internal/adapter/secondary/postgres" "lincodex/backend/internal/adapter/secondary/prometheus" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/inbound" "lincodex/backend/internal/port/outbound" "lincodex/backend/internal/usecase/semantic" "lincodex/backend/internal/worker/jobrunner" "lincodex/backend/internal/worker/retry" ) const ( semanticHTTPTimeout = 10 * time.Minute semanticCheckInterval = 10 * time.Minute // semanticRepository is the address a project links; its owner must // never reach an organization. semanticRepository = "https://github.com/Private-Owner-Marker/payments-ledger" semanticRepositoryOwner = "Private-Owner-Marker" ) // fakeMLService answers the ML embedding contract with a bag-of-topics // encoder: each topic word lights one dimension, so texts about the same // topic are close and others are not. It reports the policy model, so the // vectors pass the model check, and counts the texts it encoded. type fakeMLService struct { mutex sync.Mutex texts int down bool } var fakeTopics = [][]string{ {"payment", "idempot", "webhook", "callback", "ledger"}, {"kafka", "stream", "event"}, {"react", "frontend", "css"}, {"kubernetes", "terraform", "infra"}, } func fakeTopicVector(text string) []float32 { lower := strings.ToLower(text) vector := make([]float32, len(fakeTopics)+1) vector[len(fakeTopics)] = 0.2 for index, words := range fakeTopics { for _, word := range words { if strings.Contains(lower, word) { vector[index]++ } } } var norm float64 for _, value := range vector { norm += float64(value) * float64(value) } for index := range vector { vector[index] = float32(float64(vector[index]) / math.Sqrt(norm)) } return vector } func (service *fakeMLService) ServeHTTP(writer http.ResponseWriter, request *http.Request) { service.mutex.Lock() down := service.down service.mutex.Unlock() if down { writer.Header().Set("Content-Type", "application/problem+json") writer.WriteHeader(http.StatusServiceUnavailable) _, _ = writer.Write([]byte(`{"type":"urn:lincodex:problem:service_unavailable","title":"Service unavailable","status":503,"code":"service_unavailable"}`)) return } var body struct { Model string `json:"model"` Kind string `json:"kind"` Texts []string `json:"texts"` } // The service serves one model; a request for another one is refused // as the real service refuses it. if request.URL.Path != "/v1/embeddings" || json.NewDecoder(request.Body).Decode(&body) != nil || body.Model != domain.GigaEmbeddingsModelID { writer.WriteHeader(http.StatusBadRequest) return } service.mutex.Lock() service.texts += len(body.Texts) service.mutex.Unlock() vectors := make([][]float32, 0, len(body.Texts)) for _, text := range body.Texts { vectors = append(vectors, fakeTopicVector(text)) } writer.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(writer).Encode(map[string]any{ "model": map[string]any{ "id": domain.GigaEmbeddingsModelID, "revision": domain.GigaEmbeddingsModelRevision, "dimension": len(fakeTopics) + 1, "max_tokens": 1024, "prompt_version": domain.GigaEmbeddingsPromptVersion, }, "kind": body.Kind, "vectors": vectors, }) } func (service *fakeMLService) encodedTexts() int { service.mutex.Lock() defer service.mutex.Unlock() return service.texts } func (service *fakeMLService) setDown(down bool) { service.mutex.Lock() defer service.mutex.Unlock() service.down = down } // fakeRepositoryFetcher stands in for the public GitHub API; tests never // call GitHub. type fakeRepositoryFetcher struct { mutex sync.Mutex calls int } func (fetcher *fakeRepositoryFetcher) Fetch(_ context.Context, repository domain.GitHubRepository, _ outbound.RepositoryCheck) (outbound.RepositoryFetch, error) { fetcher.mutex.Lock() defer fetcher.mutex.Unlock() fetcher.calls++ if repository.Owner() != semanticRepositoryOwner { return outbound.RepositoryFetch{Found: false}, nil } return outbound.RepositoryFetch{ Found: true, GitHubID: 42, RepositoryETag: `"etag-1"`, Evidence: domain.RepositoryEvidence{ Description: "Ledger with idempotent payment webhooks", Topics: []string{"payments"}, Languages: []string{"Go"}, ReadmeExcerpt: "Deduplicates acquirer callbacks by operation key.", }, }, nil } type semanticEntryBody struct { matchEntryBody SemanticEvidence []struct { RequirementKind string `json:"requirement_kind"` RequirementText string `json:"requirement_text"` ItemKind string `json:"item_kind"` ProjectTitle *string `json:"project_title"` RepositoryVerified bool `json:"repository_verified"` Similarity string `json:"similarity"` } `json:"semantic_evidence"` } type semanticSearchBody struct { Groups struct { Unconfirmed []semanticEntryBody `json:"unconfirmed"` } `json:"groups"` } func TestSemanticMatchingOverHTTP(t *testing.T) { env := bootstrap(t, postgresService, redisService) ctx, cancel := context.WithTimeout(t.Context(), semanticHTTPTimeout) defer cancel() databaseURL := env.createIsolatedDatabase(ctx, t) applyMigrations(ctx, t, databaseURL) isolatedEnv := *env isolatedEnv.Config.DatabaseURL = databaseURL trigger := semantic.NewTrigger(true, true) harness := newMatchSearchHarnessWithSemantic(ctx, t, &isolatedEnv, trigger) client := &categoryHTTPClient{harness: harness.assessmentAttemptHTTPHarness, ctx: ctx} transactor := postgresadapter.NewTransactor(harness.pool) product := domain.DemoProductPolicyV5() product.Matching.MaxResultsPerGroup = 100 // The questionnaire of a candidate needs the assessment bank; the bank // seed publishes the semantic policy V5 with it. seedAssessmentCategoryHTTPBank(ctx, t, harness.pool, product, true) ml := &fakeMLService{} mlServer := httptest.NewServer(ml) defer mlServer.Close() embedder, err := mladapter.NewEmbedder(mladapter.Settings{ BaseURL: mlServer.URL, Timeout: 5 * time.Second, FailureThreshold: 100, OpenDuration: time.Second, }, time.Now) if err != nil { t.Fatalf("NewEmbedder() error = %v", err) } vectorJobs, err := semantic.NewVectorJobs(embedder, time.Now, nil) if err != nil { t.Fatalf("NewVectorJobs() error = %v", err) } fetcher := &fakeRepositoryFetcher{} repositoryJob, err := semantic.NewRepositoryCheckJob(fetcher, trigger, time.Now, nil) if err != nil { t.Fatalf("NewRepositoryCheckJob() error = %v", err) } jobPool := isolatedEnv.newPool(ctx, t) worker, err := jobrunner.New( []inbound.JobHandler{vectorJobs.CandidateHandler(), vectorJobs.NeedHandler(), repositoryJob}, postgresadapter.NewScheduledJobStore(jobPool, time.Minute), prometheus.New(), slog.New(slog.DiscardHandler), jobrunner.Settings{ BatchSize: 50, PollInterval: 10 * time.Millisecond, Lease: time.Minute, MaxAttempts: 3, Backoff: retry.Backoff{Initial: time.Millisecond, Max: time.Millisecond}, ShutdownGrace: time.Second, StoreTimeout: 5 * time.Second, BacklogInterval: time.Second, }, func() time.Time { return time.Now().Add(time.Hour) }) if err != nil { t.Fatalf("jobrunner.New() error = %v", err) } // drain runs passes until no job is due; follow-up jobs that a job // schedules run in the next pass. drain := func() { t.Helper() for range 10 { result, err := worker.RunDue(ctx) if err != nil { t.Fatalf("RunDue() error = %v", err) } if result.Claimed == 0 { return } } t.Fatal("jobs kept falling due") } countRows := func(query string, args ...any) int { t.Helper() var count int if err := harness.pool.QueryRow(ctx, query, args...).Scan(&count); err != nil { t.Fatalf("count rows: %v", err) } return count } mustCall := func(who categoryHTTPCandidate, method, path, body string, want int) []byte { t.Helper() status, response := client.call(t, who, method, path, body, "") if status != want { t.Fatalf("%s %s = %d %s, want %d", method, path, status, response, want) } return response } profileBody := func(version int, projects string) string { return fmt.Sprintf(`{"expected_version":%d,"full_name":null,"contacts":{"email":null,"phone":null,"telegram":null}, "stack":[{"tag":"go","status":"confirmed"}],"roles":[{"specialization":"backend","self_assessed_grade":"junior","status":"confirmed"}], "experience":[],"confirmed_parallel_periods":[],"soft_skills":[],"projects":%s, "terms":{"location":null,"relocation":null,"salary_minimum":null}}`, version, projects) } publishFields := func(who categoryHTTPCandidate, version int, fields string) { t.Helper() mustCall(who, http.MethodPut, "/api/v1/me/privacy/publication", fmt.Sprintf(`{"expected_version":%d,"state":"published","fields":%s}`, version, fields), http.StatusOK) } payments := `[{"title":"Payment webhook deduplication","description":"Idempotent callback receiver","stack":["Go","PostgreSQL"],"repository_url":"` + semanticRepository + `/","status":"confirmed"}]` frontendProject := `[{"title":"Landing page","description":"React and CSS components","stack":["React"],"repository_url":null,"status":"confirmed"}]` candidates := make([]categoryHTTPCandidate, 0, 6) for index := range 6 { member := client.candidate(t, fmt.Sprintf("semantic-%d@example.test", index)) projects := frontendProject if index == 0 { projects = payments } mustCall(member, http.MethodPut, "/api/v1/me/profile", profileBody(0, projects), http.StatusOK) mustCall(member, http.MethodPut, "/api/v1/me/consents/c2", fmt.Sprintf(`{"text_version":%q,"accepted":true}`, privacyC2Version), http.StatusOK) publishFields(member, 0, `["projects","self_assessment","stack"]`) candidates = append(candidates, member) } paymentsCandidate := candidates[0] t.Run("a profile save schedules jobs whose keys and payloads name no repository", func(t *testing.T) { if got := countRows(`SELECT count(*) FROM scheduled_jobs WHERE kind = $1`, semantic.CandidateJobKind); got < 6 { t.Fatalf("candidate jobs = %d, want one per save and publication", got) } if got := countRows(`SELECT count(*) FROM scheduled_jobs WHERE kind = $1`, semantic.RepositoryCheckJobKind); got != 1 { t.Fatalf("repository jobs = %d, want 1", got) } if got := countRows(`SELECT count(*) FROM scheduled_jobs WHERE dedup_key ILIKE '%owner-marker%' OR payload::text ILIKE '%owner-marker%'`); got != 0 { t.Fatalf("%d jobs name the repository owner", got) } profile := mustCall(paymentsCandidate, http.MethodGet, "/api/v1/me/profile", "", http.StatusOK) if !strings.Contains(string(profile), `"repository_url":"`+semanticRepository+`"`) || !strings.Contains(string(profile), `"state":"pending"`) { t.Fatalf("profile = %s, want the canonical address and a pending check", profile) } }) t.Run("the jobs verify the repository and store the card vectors", func(t *testing.T) { drain() if fetcher.calls != 1 { t.Fatalf("repository fetches = %d, want 1", fetcher.calls) } profile := mustCall(paymentsCandidate, http.MethodGet, "/api/v1/me/profile", "", http.StatusOK) if !strings.Contains(string(profile), `"state":"verified"`) { t.Fatalf("profile = %s, want a verified check", profile) } if got := countRows(`SELECT count(DISTINCT candidate_id) FROM semantic_vectors WHERE subject_kind = 'candidate' AND item_key = 'whole'`); got != 6 { t.Fatalf("candidates with a whole vector = %d, want 6", got) } if got := countRows(`SELECT count(*) FROM semantic_vectors WHERE candidate_id = $1`, paymentsCandidate.id); got != 4 { t.Fatalf("vectors of the payments candidate = %d, want whole, roles, stack, and one project", got) } }) employer := client.employer(t, "semantic-employer@example.test") organizations := organizationFixture{ctx: ctx, pool: harness.pool, identity: identityFixture{ctx: ctx, pool: harness.pool, store: harness.store, now: time.Now().UTC()}, transactor: transactor, now: time.Now().UTC()} org := organizations.create(t, domain.User{ID: employer.id}, organizations.completeProfile(t, "Semantic organization"), time.Now().UTC()) harness.clock.Set(time.Now().UTC().Add(time.Minute).Truncate(time.Microsecond)) status, created := client.call(t, employer, http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/needs", org.ID()), `{"title":"Payments backend","specialization":{"value":"backend","status":"confirmed"},"required_skills":[{"name":"Kafka","status":"confirmed"}],"tasks":[{"text":"Make payment callbacks idempotent","status":"confirmed"}]}`, "semantic-need-1") var need struct { ID uuid.UUID `json:"id"` RequirementsVersion int64 `json:"requirements_version"` } if status != http.StatusCreated || json.Unmarshal(created, &need) != nil { t.Fatalf("create need = %d %s", status, created) } searchBody := fmt.Sprintf(`{"need_id":%q,"requirements_version":%d}`, need.ID, need.RequirementsVersion) search := func() (semanticSearchBody, []byte) { t.Helper() response := mustCall(employer, http.MethodPost, fmt.Sprintf("/api/v1/organizations/%s/matches", org.ID()), searchBody, http.StatusOK) var decoded semanticSearchBody if err := json.Unmarshal(response, &decoded); err != nil { t.Fatalf("decode search: %v", err) } return decoded, response } paymentsHandle, err := harness.key.ForOrganization(org.ID(), paymentsCandidate.id) if err != nil { t.Fatalf("ForOrganization() error = %v", err) } t.Run("before the need vectors exist every entry keeps the neutral Sem and the ML flag", func(t *testing.T) { result, _ := search() if len(result.Groups.Unconfirmed) != 6 { t.Fatalf("unconfirmed entries = %d, want 6", len(result.Groups.Unconfirmed)) } for _, entry := range result.Groups.Unconfirmed { if !slices.Contains(entry.flags(), "semantics:ml_unavailable") || len(entry.SemanticEvidence) != 0 { t.Fatalf("entry flags %v evidence %v, want the ML flag and no evidence", entry.flags(), entry.SemanticEvidence) } } }) t.Run("with vectors the related project ranks first and explains the match without the repository", func(t *testing.T) { drain() first, raw := search() second, rawAgain := search() if string(raw) != string(rawAgain) || len(first.Groups.Unconfirmed) != len(second.Groups.Unconfirmed) { t.Fatal("two searches over the same vectors differ") } top := first.Groups.Unconfirmed[0] if top.CandidateHandle != paymentsHandle { t.Fatalf("first entry = %s, want the payments candidate", top.CandidateHandle) } if slices.Contains(top.flags(), "semantics:ml_unavailable") { t.Fatalf("flags = %v, want Sem known", top.flags()) } if top.component("fit") <= first.Groups.Unconfirmed[1].component("fit") { t.Fatalf("fit %v is not above the next entry %v", top.component("fit"), first.Groups.Unconfirmed[1].component("fit")) } var project bool for _, item := range top.SemanticEvidence { if item.ItemKind == "project" && item.ProjectTitle != nil && *item.ProjectTitle == "Payment webhook deduplication" && item.RepositoryVerified && item.RequirementKind == "task" && item.RequirementText == "Make payment callbacks idempotent" { project = true } } if !project { t.Fatalf("evidence = %+v, want the task matched to the verified project", top.SemanticEvidence) } for _, forbidden := range []string{"github.com", semanticRepositoryOwner, "owner-marker", "payments-ledger", "acquirer"} { if strings.Contains(strings.ToLower(string(raw)), strings.ToLower(forbidden)) { t.Fatalf("the search result contains %q", forbidden) } } var fields []string if err := harness.pool.QueryRow(ctx, `SELECT field_codes FROM candidate_card_access_events WHERE candidate_id = $1 AND organization_id = $2 ORDER BY occurred_at DESC, id DESC LIMIT 1`, paymentsCandidate.id, org.ID()).Scan(&fields); err != nil { t.Fatalf("read access history: %v", err) } if !slices.Contains(fields, "projects") { t.Fatalf("access history fields = %v, want projects", fields) } }) t.Run("the card shows the published project but never the repository address", func(t *testing.T) { card := mustCall(employer, http.MethodGet, fmt.Sprintf("/api/v1/organizations/%s/candidate-cards/%s", org.ID(), paymentsHandle), "", http.StatusOK) if !strings.Contains(string(card), `"title":"Payment webhook deduplication"`) || !strings.Contains(string(card), `"repository_verified":true`) { t.Fatalf("card = %s, want the published project", card) } if strings.Contains(string(card), "github.com") || strings.Contains(string(card), semanticRepositoryOwner) { t.Fatalf("card = %s, leaks the repository", card) } }) t.Run("an unchanged card costs no ML call and a repeated backfill schedules nothing twice", func(t *testing.T) { backfill, err := semantic.NewBackfill(transactor, time.Now) if err != nil { t.Fatalf("NewBackfill() error = %v", err) } for range 2 { if err := backfill.Run(ctx, semantic.BackfillCandidates, "it-1", uuid.Nil, nil); err != nil { t.Fatalf("Backfill.Run() error = %v", err) } if err := backfill.Run(ctx, semantic.BackfillNeeds, "it-1", uuid.Nil, nil); err != nil { t.Fatalf("Backfill.Run(needs) error = %v", err) } } if got := countRows(`SELECT count(*) FROM scheduled_jobs WHERE dedup_key LIKE '%:backfill-it-1'`); got != 6+1 { t.Fatalf("backfill jobs = %d, want one per published candidate and need", got) } before := ml.encodedTexts() drain() if after := ml.encodedTexts(); after != before { t.Fatalf("the backfill encoded %d texts, want none for unchanged cards", after-before) } }) t.Run("unpublishing projects removes them from the vectors and the explanation", func(t *testing.T) { publishFields(paymentsCandidate, 1, `["self_assessment","stack"]`) drain() if got := countRows(`SELECT count(*) FROM semantic_vectors WHERE candidate_id = $1 AND item_key LIKE 'project:%'`, paymentsCandidate.id); got != 0 { t.Fatalf("project vectors = %d, want 0 after unpublishing", got) } result, _ := search() for _, entry := range result.Groups.Unconfirmed { for _, item := range entry.SemanticEvidence { if item.ProjectTitle != nil && entry.CandidateHandle == paymentsHandle { t.Fatalf("evidence still names a project: %+v", item) } } } }) t.Run("an ML outage keeps the job pending and the search answering", func(t *testing.T) { ml.setDown(true) defer ml.setDown(false) mustCall(candidates[1], http.MethodPut, "/api/v1/me/profile", profileBody(1, `[{"title":"Kafka event pipeline","description":null,"stack":["Kafka"],"repository_url":null,"status":"confirmed"}]`), http.StatusOK) if _, err := worker.RunDue(ctx); err != nil { t.Fatalf("RunDue() error = %v", err) } if got := countRows(`SELECT count(*) FROM scheduled_jobs WHERE kind = $1 AND status = 'failed'`, semantic.CandidateJobKind); got == 0 { t.Fatal("the vector job did not record a failed attempt while ML was down") } search() }) t.Run("the refresh of repository checks is limited per candidate", func(t *testing.T) { harness.clock.Set(time.Now().UTC().Add(time.Hour).Truncate(time.Microsecond)) for _, member := range []categoryHTTPCandidate{candidates[2]} { mustCall(member, http.MethodPut, "/api/v1/me/profile", profileBody(1, `[{"title":"Infra","description":null,"stack":[],"repository_url":"https://github.com/someone/infra","status":"confirmed"}]`), http.StatusOK) status, body := client.call(t, member, http.MethodPost, "/api/v1/me/profile/repository-checks", "", "") if status != http.StatusTooManyRequests { t.Fatalf("refresh right after the save = %d %s, want 429", status, body) } harness.clock.Set(time.Now().UTC().Add(2 * time.Hour).Truncate(time.Microsecond)) status, body = client.call(t, member, http.MethodPost, "/api/v1/me/profile/repository-checks", "", "") if status != http.StatusAccepted || !strings.Contains(string(body), `"scheduled":1`) { t.Fatalf("refresh after the interval = %d %s, want 202 with one check", status, body) } } status, body := client.call(t, candidates[3], http.MethodPost, "/api/v1/me/profile/repository-checks", "", "") if status != http.StatusAccepted || !strings.Contains(string(body), `"scheduled":0`) { t.Fatalf("refresh without repositories = %d %s, want 202 with nothing", status, body) } }) }