feat(matching): rank with semantic embeddings and explain matches by evidence

This commit is contained in:
shira committed 2026-10-11 10:39:46 +03:00
1 parent facc1789b1
commit 24b64d698a
215 files changed
+16951 -327

No files matched your search

@@ -0,0 +1,124 @@
package semantic
import (
"context"
"errors"
"fmt"
"regexp"
"strconv"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/port/outbound"
)
// BackfillPageSize is the number of subjects one backfill transaction
// schedules.
const BackfillPageSize = 200
var backfillRunPattern = regexp.MustCompile(`^[a-z0-9-]{1,32}$`)
// BackfillScope selects what a backfill schedules.
type BackfillScope string
const (
BackfillCandidates BackfillScope = "candidates"
BackfillNeeds BackfillScope = "needs"
)
// BackfillProgress reports one finished page: how many jobs it scheduled
// and the cursor to resume after.
type BackfillProgress struct {
Scope BackfillScope
Scheduled int
After uuid.UUID
Done bool
}
// Backfill schedules vector jobs for every candidate with a saved profile or
// every need, page by page in identifier order. The job of a candidate who is
// not published removes any stored vectors, so the backfill also cleans up.
// A run label makes the job keys, so repeating a run schedules nothing twice,
// and a new label recomputes again; a job whose texts did not change costs no
// ML call. The cursor of the last page resumes an interrupted run.
type Backfill struct {
transactor outbound.Transactor
clock func() time.Time
}
// NewBackfill returns the backfill.
func NewBackfill(transactor outbound.Transactor, clock func() time.Time) (*Backfill, error) {
if transactor == nil || clock == nil {
return nil, errors.New("semantic.NewBackfill - transactor and clock must be set")
}
return &Backfill{transactor: transactor, clock: clock}, nil
}
// Run schedules pages until the scope is exhausted and reports each page.
func (backfill *Backfill) Run(
ctx context.Context, scope BackfillScope, run string, after uuid.UUID, report func(BackfillProgress) error,
) error {
const location = "semantic.Backfill.Run"
if !backfillRunPattern.MatchString(run) {
return errors.New(location + " - run label must be 1 to 32 lower-case letters, digits, or hyphens")
}
if scope != BackfillCandidates && scope != BackfillNeeds {
return errors.New(location + " - scope must be candidates or needs")
}
cursor := after
for {
progress, err := backfill.page(ctx, scope, run, cursor)
if err != nil {
return fmt.Errorf("%s - schedule page: %w", location, err)
}
if report != nil {
if err := report(progress); err != nil {
return err
}
}
if progress.Done {
return nil
}
cursor = progress.After
}
}
func (backfill *Backfill) page(ctx context.Context, scope BackfillScope, run string, after uuid.UUID) (BackfillProgress, error) {
progress := BackfillProgress{Scope: scope, After: after}
err := backfill.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
at := backfill.clock().UTC()
if scope == BackfillCandidates {
ids, err := unit.SemanticVectors().CandidatesAfter(ctx, after, BackfillPageSize)
if err != nil {
return err
}
for _, id := range ids {
if err := schedule(ctx, unit, CandidateJobKind, id.String()+":backfill-"+run, at,
map[string]string{"candidate_id": id.String()}, vectorJobAttempts); err != nil {
return err
}
progress.After = id
}
progress.Scheduled, progress.Done = len(ids), len(ids) < BackfillPageSize
return nil
}
needs, err := unit.SemanticVectors().NeedsAfter(ctx, after, BackfillPageSize)
if err != nil {
return err
}
for _, need := range needs {
key := need.NeedID.String() + ":" + strconv.FormatInt(need.RequirementsVersion, 10) + ":backfill-" + run
if err := schedule(ctx, unit, NeedJobKind, key, at, map[string]any{
"organization_id": need.OrganizationID.String(), "need_id": need.NeedID.String(),
"requirements_version": need.RequirementsVersion,
}, vectorJobAttempts); err != nil {
return err
}
progress.After = need.NeedID
}
progress.Scheduled, progress.Done = len(needs), len(needs) < BackfillPageSize
return nil
})
return progress, err
}
+306
View File
@@ -0,0 +1,306 @@
package semantic
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"strings"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
)
// ErrModelMismatch reports an ML service that answers with another model
// than the effective policy names. The job is retried: an operator either
// deploys the named model or publishes a policy for the running one.
var ErrModelMismatch = errors.New("the ML service runs another model than the policy names")
// projectionPseudonym is a syntactically valid alias for the private
// projection of the job; the job never shows the card to anyone.
var projectionPseudonym = "cv1_" + strings.Repeat("A", 43)
// VectorJobs computes the vectors of candidates and needs. It implements
// the handlers of CandidateJobKind and NeedJobKind.
type VectorJobs struct {
embedder outbound.TextEmbedder
clock func() time.Time
logger *slog.Logger
}
// NewVectorJobs returns the vector job runner.
func NewVectorJobs(embedder outbound.TextEmbedder, clock func() time.Time, logger *slog.Logger) (*VectorJobs, error) {
if embedder == nil || clock == nil {
return nil, errors.New("semantic.NewVectorJobs - embedder and clock must be set")
}
if logger == nil {
logger = slog.New(slog.DiscardHandler)
}
return &VectorJobs{embedder: embedder, clock: clock, logger: logger}, nil
}
// CandidateHandler returns the handler of CandidateJobKind.
func (jobs *VectorJobs) CandidateHandler() inbound.JobHandler { return candidateHandler{jobs: jobs} }
// NeedHandler returns the handler of NeedJobKind.
func (jobs *VectorJobs) NeedHandler() inbound.JobHandler { return needHandler{jobs: jobs} }
type candidateHandler struct{ jobs *VectorJobs }
func (candidateHandler) JobKind() string { return CandidateJobKind }
func (handler candidateHandler) Handle(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error {
var payload struct {
CandidateID string `json:"candidate_id"`
}
if err := json.Unmarshal(job.Payload, &payload); err != nil {
return fmt.Errorf("semantic.candidateHandler.Handle - decode payload: %w", inbound.ErrJobRejected)
}
candidateID, err := uuid.Parse(payload.CandidateID)
if err != nil || candidateID == uuid.Nil {
return fmt.Errorf("semantic.candidateHandler.Handle - payload names no candidate: %w", inbound.ErrJobRejected)
}
return handler.jobs.RefreshCandidate(ctx, unit, candidateID)
}
type needHandler struct{ jobs *VectorJobs }
func (needHandler) JobKind() string { return NeedJobKind }
func (handler needHandler) Handle(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error {
var payload struct {
OrganizationID string `json:"organization_id"`
NeedID string `json:"need_id"`
RequirementsVersion int64 `json:"requirements_version"`
}
if err := json.Unmarshal(job.Payload, &payload); err != nil {
return fmt.Errorf("semantic.needHandler.Handle - decode payload: %w", inbound.ErrJobRejected)
}
organizationID, organizationErr := uuid.Parse(payload.OrganizationID)
needID, needErr := uuid.Parse(payload.NeedID)
if organizationErr != nil || needErr != nil || payload.RequirementsVersion < 1 {
return fmt.Errorf("semantic.needHandler.Handle - payload names no need snapshot: %w", inbound.ErrJobRejected)
}
return handler.jobs.RefreshNeed(ctx, unit, organizationID, needID)
}
// semanticPolicy reads the semantic section of the effective policy; false
// means the policy names no model, and nothing is computed.
func (jobs *VectorJobs) semanticPolicy(ctx context.Context, unit outbound.UnitOfWork) (domain.MatchingSemanticsPolicy, bool, error) {
version, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, jobs.clock().UTC())
if errors.Is(err, outbound.ErrPolicyVersionNotFound) {
return domain.MatchingSemanticsPolicy{}, false, nil
}
if err != nil {
return domain.MatchingSemanticsPolicy{}, false, fmt.Errorf("read effective policy: %w", err)
}
matching := version.Policy().Matching
if matching == nil || matching.Semantics == nil {
return domain.MatchingSemanticsPolicy{}, false, nil
}
return *matching.Semantics, true, nil
}
// RefreshCandidate brings the stored card vectors of one candidate up to
// date. A candidate who is not published keeps no vectors at all. A card
// whose texts did not change costs no ML call.
func (jobs *VectorJobs) RefreshCandidate(ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID) error {
const location = "semantic.VectorJobs.RefreshCandidate"
vectors := unit.SemanticVectors()
if err := vectors.Lock(ctx, domain.SemanticSubjectCandidate, candidateID); err != nil {
return fmt.Errorf("%s - lock subject: %w", location, err)
}
policy, configured, err := jobs.semanticPolicy(ctx, unit)
if err != nil || !configured {
return wrapOptional(location, err)
}
document, published, err := candidateDocument(ctx, unit, candidateID, jobs.clock().UTC())
if err != nil {
return fmt.Errorf("%s - render card: %w", location, err)
}
if !published || document.IsEmpty() {
if err := vectors.DeleteSubject(ctx, domain.SemanticSubjectCandidate, candidateID); err != nil {
return fmt.Errorf("%s - remove vectors: %w", location, err)
}
return nil
}
if err := jobs.storeMembers(ctx, unit, domain.SemanticSubjectCandidate, candidateID, outbound.EmbeddingDocument, policy, document); err != nil {
return fmt.Errorf("%s - %w", location, err)
}
return nil
}
// RefreshNeed computes the vectors of the current requirements snapshot of
// a need. A job of an older snapshot finds the newer one current and
// computes that instead, so the stored vectors never go back in time.
func (jobs *VectorJobs) RefreshNeed(ctx context.Context, unit outbound.UnitOfWork, organizationID, needID uuid.UUID) error {
const location = "semantic.VectorJobs.RefreshNeed"
vectors := unit.SemanticVectors()
if err := vectors.Lock(ctx, domain.SemanticSubjectNeed, needID); err != nil {
return fmt.Errorf("%s - lock subject: %w", location, err)
}
policy, configured, err := jobs.semanticPolicy(ctx, unit)
if err != nil || !configured {
return wrapOptional(location, err)
}
current, err := unit.Needs().Get(ctx, organizationID, needID)
if errors.Is(err, outbound.ErrNeedNotFound) {
return nil
}
if err != nil {
return fmt.Errorf("%s - read need: %w", location, err)
}
snapshot, err := unit.Needs().GetVersion(ctx, organizationID, needID, current.RequirementsVersion())
if err != nil {
return fmt.Errorf("%s - read requirements snapshot: %w", location, err)
}
document := domain.NewNeedSemanticDocument(snapshot.Snapshot())
if err := jobs.storeMembers(ctx, unit, domain.SemanticSubjectNeed, needID, outbound.EmbeddingQuery, policy, document); err != nil {
return fmt.Errorf("%s - %w", location, err)
}
return nil
}
func wrapOptional(location string, err error) error {
if err == nil {
return nil
}
return fmt.Errorf("%s - %w", location, err)
}
// storeMembers stores the vectors of every policy member. The first member
// explains entries and stores every item; the other members only rank, so
// they store the whole view alone. Vectors of models that the policy no
// longer names stay until DeleteSubject or a model cleanup removes them;
// the search never reads them.
func (jobs *VectorJobs) storeMembers(
ctx context.Context, unit outbound.UnitOfWork, kind domain.SemanticSubjectKind, subjectID uuid.UUID,
embedding outbound.EmbeddingKind, policy domain.MatchingSemanticsPolicy, document domain.SemanticDocument,
) error {
for index, member := range policy.Members {
items := document.All()
if index > 0 {
items = []domain.SemanticItem{document.Whole}
}
if err := jobs.store(ctx, unit, kind, subjectID, embedding, member.Model, items); err != nil {
return err
}
}
return nil
}
// store encodes the texts of the items unless the stored digests show the
// same texts, and replaces the stored set of the subject for the model.
func (jobs *VectorJobs) store(
ctx context.Context, unit outbound.UnitOfWork, kind domain.SemanticSubjectKind, subjectID uuid.UUID,
embedding outbound.EmbeddingKind, model domain.SemanticModel, items []domain.SemanticItem,
) error {
stored, err := unit.SemanticVectors().Digests(ctx, kind, subjectID, model)
if err != nil {
return fmt.Errorf("read stored digests: %w", err)
}
if sameDigests(stored, items) {
return nil
}
texts := make([]string, 0, len(items))
for _, item := range items {
texts = append(texts, item.Text)
}
encoder, vectors, err := jobs.embedder.Embed(ctx, model.ID, embedding, texts)
if err != nil {
return fmt.Errorf("encode texts: %w", err)
}
if encoder != model {
jobs.logger.WarnContext(ctx, "the ML service runs another model than the effective policy",
slog.String("service_model", encoder.ID), slog.String("service_revision", encoder.Revision),
slog.String("policy_model", model.ID), slog.String("policy_revision", model.Revision))
return ErrModelMismatch
}
rows := make([]outbound.StoredSemanticItem, 0, len(items))
for index, item := range items {
rows = append(rows, outbound.StoredSemanticItem{
Key: item.Key, ContentDigest: item.ContentDigest(), LabelDigest: item.LabelDigest(), Vector: vectors[index],
})
}
if err := unit.SemanticVectors().Replace(ctx, kind, subjectID, model, rows, jobs.clock().UTC()); err != nil {
return fmt.Errorf("store vectors: %w", err)
}
return nil
}
func sameDigests(stored map[string][32]byte, items []domain.SemanticItem) bool {
if len(stored) != len(items) {
return false
}
for _, item := range items {
if digest, ok := stored[item.Key]; !ok || digest != item.ContentDigest() {
return false
}
}
return true
}
// candidateDocument renders the card of a published candidate as the
// organization-facing projection builds it, before any cohort
// generalization, plus the public metadata of its verified repositories.
func candidateDocument(ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, now time.Time) (domain.SemanticDocument, bool, error) {
source, err := unit.PrivacyView().ReadCandidateViewSourceForPreview(ctx, candidateID)
if errors.Is(err, outbound.ErrPrivacyCohortUnavailable) {
return domain.SemanticDocument{}, false, nil
}
if err != nil {
return domain.SemanticDocument{}, false, fmt.Errorf("read card source: %w", err)
}
view, err := domain.NewAnonymousCandidateView(source.Input(projectionPseudonym, now))
if err != nil {
return domain.SemanticDocument{}, false, fmt.Errorf("project card: %w", err)
}
card := view.DTO()
evidence := map[int]domain.RepositoryEvidence{}
if len(card.Projects) > 0 {
evidence, err = projectEvidence(ctx, unit, candidateID)
if err != nil {
return domain.SemanticDocument{}, false, err
}
}
return domain.NewCandidateSemanticDocument(card, evidence), true, nil
}
// projectEvidence maps the position of each card project to the metadata of
// its verified repository. The card lists the confirmed projects in profile
// order, and so does this mapping.
func projectEvidence(ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID) (map[int]domain.RepositoryEvidence, error) {
profile, err := unit.CandidateProfiles().Get(ctx, candidateID)
if err != nil {
return nil, fmt.Errorf("read profile projects: %w", err)
}
checks, err := unit.ProjectRepositories().List(ctx, candidateID)
if err != nil {
return nil, fmt.Errorf("read repository checks: %w", err)
}
verified := make(map[string]domain.RepositoryEvidence)
for _, check := range checks {
if check.State == outbound.RepositoryCheckVerified {
verified[check.Key] = check.Evidence
}
}
evidence := make(map[int]domain.RepositoryEvidence)
position := 0
for _, claim := range profile.Content().Projects() {
if claim.Status() != domain.ProfileClaimConfirmed {
continue
}
if repository, ok := claim.Value().Repository(); ok {
if found, ok := verified[repository.Key()]; ok {
evidence[position] = found
}
}
position++
}
return evidence, nil
}
@@ -0,0 +1,159 @@
package semantic
import (
"context"
"encoding/json"
"errors"
"fmt"
"log/slog"
"regexp"
"slices"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
)
var repositoryDigestPattern = regexp.MustCompile(`^[0-9a-f]{16}$`)
// RepositoryCheckJob checks one linked repository on the public GitHub API
// and stores the result. It implements the handler of RepositoryCheckJobKind.
type RepositoryCheckJob struct {
fetcher outbound.RepositoryMetadataFetcher
trigger *Trigger
clock func() time.Time
logger *slog.Logger
}
// NewRepositoryCheckJob returns the handler. trigger schedules the vector
// refresh after a check changed what the card text contains.
func NewRepositoryCheckJob(
fetcher outbound.RepositoryMetadataFetcher, trigger *Trigger, clock func() time.Time, logger *slog.Logger,
) (*RepositoryCheckJob, error) {
if fetcher == nil || clock == nil {
return nil, errors.New("semantic.NewRepositoryCheckJob - fetcher and clock must be set")
}
if logger == nil {
logger = slog.New(slog.DiscardHandler)
}
return &RepositoryCheckJob{fetcher: fetcher, trigger: trigger, clock: clock, logger: logger}, nil
}
// JobKind is the stable kind name.
func (*RepositoryCheckJob) JobKind() string { return RepositoryCheckJobKind }
// Handle fetches the repository that the payload digest names among the
// candidate's current projects. A repository that is no longer linked is
// skipped. A GitHub rate limit stores the state unavailable and reschedules
// the check after the limit resets; a network or server failure is retried
// by the worker. The log names the job and the outcome, never the repository.
func (job *RepositoryCheckJob) Handle(ctx context.Context, unit outbound.UnitOfWork, claimed outbound.ClaimedJob) error {
const location = "semantic.RepositoryCheckJob.Handle"
candidateID, digest, err := repositoryPayload(claimed.Payload)
if err != nil {
return fmt.Errorf("%s - %w", location, err)
}
profile, err := unit.CandidateProfiles().Get(ctx, candidateID)
if err != nil {
return fmt.Errorf("%s - read profile: %w", location, err)
}
repository, linked := linkedRepository(profile.Content(), digest)
if !linked {
return nil
}
store := unit.ProjectRepositories()
previous, found, err := store.GetForUpdate(ctx, candidateID, repository.Key())
if err != nil {
return fmt.Errorf("%s - lock check: %w", location, err)
}
now := job.clock().UTC()
if !found {
if err := store.Request(ctx, candidateID, repository.Key(), now); err != nil {
return fmt.Errorf("%s - create check: %w", location, err)
}
previous = outbound.RepositoryCheck{Key: repository.Key(), State: outbound.RepositoryCheckPending}
}
fetched, err := job.fetcher.Fetch(ctx, repository, previous)
next, retryAfter, err := checkResult(previous, fetched, err, now)
if err != nil {
job.logger.WarnContext(ctx, "repository check failed and will be retried",
slog.Int64("job_id", claimed.ID), slog.Int("attempt", claimed.Attempt))
return fmt.Errorf("%s - fetch repository: %w", location, err)
}
if err := store.Save(ctx, candidateID, next); err != nil {
return fmt.Errorf("%s - store check: %w", location, err)
}
job.logger.InfoContext(ctx, "repository check finished",
slog.Int64("job_id", claimed.ID), slog.String("state", string(next.State)), slog.String("failure", string(next.Failure)))
if retryAfter > 0 {
if err := scheduleRepositoryCheck(ctx, unit, candidateID, repository.Key(), now.Add(retryAfter)); err != nil {
return fmt.Errorf("%s - reschedule after the rate limit: %w", location, err)
}
}
if evidenceChanged(previous, next) {
if err := job.trigger.CandidateChanged(ctx, unit, candidateID, now); err != nil {
return fmt.Errorf("%s - schedule vector refresh: %w", location, err)
}
}
return nil
}
// repositoryPayload reads the candidate and the repository digest; a payload
// that names neither can never run, so it is final.
func repositoryPayload(payload json.RawMessage) (uuid.UUID, string, error) {
var fields struct {
CandidateID string `json:"candidate_id"`
Repository string `json:"repository"`
}
if err := json.Unmarshal(payload, &fields); err != nil {
return uuid.Nil, "", fmt.Errorf("decode payload: %w", inbound.ErrJobRejected)
}
candidateID, err := uuid.Parse(fields.CandidateID)
if err != nil || candidateID == uuid.Nil || !repositoryDigestPattern.MatchString(fields.Repository) {
return uuid.Nil, "", fmt.Errorf("payload names no repository: %w", inbound.ErrJobRejected)
}
return candidateID, fields.Repository, nil
}
// checkResult turns a fetch into the stored check. It returns a wait for a
// rate limit and an error for a failure the worker should retry.
func checkResult(previous outbound.RepositoryCheck, fetched outbound.RepositoryFetch, err error, now time.Time) (outbound.RepositoryCheck, time.Duration, error) {
next := outbound.RepositoryCheck{Key: previous.Key, RequestedAt: previous.RequestedAt, CheckedAt: now}
var fetchError *outbound.RepositoryFetchError
switch {
case errors.As(err, &fetchError) && fetchError.Class == outbound.RepositoryFailureRateLimited:
next.State, next.Failure = outbound.RepositoryCheckUnavailable, outbound.RepositoryFailureRateLimited
return next, fetchError.RetryAfter, nil
case errors.As(err, &fetchError) && fetchError.Class == outbound.RepositoryFailureInvalidResponse:
next.State, next.Failure = outbound.RepositoryCheckUnavailable, outbound.RepositoryFailureInvalidResponse
return next, 0, nil
case err != nil:
return outbound.RepositoryCheck{}, 0, err
case !fetched.Found:
next.State = outbound.RepositoryCheckNotFound
default:
next.State = outbound.RepositoryCheckVerified
next.GitHubID, next.Evidence = fetched.GitHubID, fetched.Evidence
next.RepositoryETag, next.ReadmeETag = fetched.RepositoryETag, fetched.ReadmeETag
}
return next, 0, nil
}
// evidenceChanged reports whether the card text can change: the verified
// state or the fetched metadata moved.
func evidenceChanged(previous, next outbound.RepositoryCheck) bool {
wasVerified := previous.State == outbound.RepositoryCheckVerified
isVerified := next.State == outbound.RepositoryCheckVerified
if wasVerified != isVerified {
return true
}
if !isVerified {
return false
}
return previous.Evidence.Description != next.Evidence.Description ||
previous.Evidence.ReadmeExcerpt != next.Evidence.ReadmeExcerpt ||
!slices.Equal(previous.Evidence.Topics, next.Evidence.Topics) ||
!slices.Equal(previous.Evidence.Languages, next.Evidence.Languages)
}
@@ -0,0 +1,126 @@
package semantic
import (
"context"
"errors"
"strings"
"testing"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
var testNow = time.Date(2026, 10, 11, 12, 0, 0, 0, time.UTC)
type schedulerFake struct {
jobs []domain.ScheduledJob
}
func (scheduler *schedulerFake) Schedule(_ context.Context, job domain.ScheduledJob) (bool, error) {
scheduler.jobs = append(scheduler.jobs, job)
return true, nil
}
func (*schedulerFake) Cancel(context.Context, string, string) (bool, error) { return false, nil }
type repositoriesFake struct {
outbound.ProjectRepositoryStore
requested []string
linked []string
}
func (store *repositoriesFake) Request(_ context.Context, _ uuid.UUID, key string, _ time.Time) error {
store.requested = append(store.requested, key)
return nil
}
func (store *repositoriesFake) DeleteUnlinked(_ context.Context, _ uuid.UUID, keys []string) error {
store.linked = keys
return nil
}
type unitFake struct {
outbound.UnitOfWork
scheduler *schedulerFake
repositories *repositoriesFake
}
func (unit unitFake) ScheduledJobs() outbound.JobScheduler { return unit.scheduler }
func (unit unitFake) ProjectRepositories() outbound.ProjectRepositoryStore { return unit.repositories }
func repo(t *testing.T, raw string) domain.GitHubRepository {
t.Helper()
parsed, err := domain.ParseGitHubRepositoryURL(raw)
if err != nil {
t.Fatalf("ParseGitHubRepositoryURL() error = %v", err)
}
return parsed
}
func TestTriggerSchedulesOnlyEnabledWorkAndNamesNoRepository(t *testing.T) {
unit := unitFake{scheduler: &schedulerFake{}, repositories: &repositoriesFake{}}
candidate := uuid.New()
kept := repo(t, "https://github.com/Private-Owner/kept")
added := repo(t, "https://github.com/Private-Owner/added")
trigger := NewTrigger(true, true)
if err := trigger.RepositoriesChanged(context.Background(), unit, candidate, []domain.GitHubRepository{kept}, []domain.GitHubRepository{kept, added}, testNow); err != nil {
t.Fatalf("RepositoriesChanged() error = %v", err)
}
if err := trigger.CandidateChanged(context.Background(), unit, candidate, testNow); err != nil {
t.Fatalf("CandidateChanged() error = %v", err)
}
if strings.Join(unit.repositories.requested, ",") != "private-owner/added" || len(unit.repositories.linked) != 2 {
t.Fatalf("requested %v linked %v, want only the new repository requested", unit.repositories.requested, unit.repositories.linked)
}
kinds := map[string]int{}
for _, job := range unit.scheduler.jobs {
kinds[job.Kind()]++
text := strings.ToLower(job.Key() + string(job.Payload()))
if strings.Contains(text, "private-owner") || strings.Contains(text, "github") {
t.Fatalf("job %s names the repository: %s %s", job.Kind(), job.Key(), job.Payload())
}
}
if kinds[RepositoryCheckJobKind] != 1 || kinds[CandidateJobKind] != 1 {
t.Fatalf("jobs = %v", kinds)
}
disabled := unitFake{scheduler: &schedulerFake{}, repositories: &repositoriesFake{}}
off := NewTrigger(false, false)
if err := off.RepositoriesChanged(context.Background(), disabled, candidate, nil, []domain.GitHubRepository{added}, testNow); err != nil {
t.Fatalf("RepositoriesChanged(off) error = %v", err)
}
if err := off.CandidateChanged(context.Background(), disabled, candidate, testNow); err != nil {
t.Fatalf("CandidateChanged(off) error = %v", err)
}
if len(disabled.scheduler.jobs) != 0 || len(disabled.repositories.requested) != 1 {
t.Fatalf("disabled trigger scheduled %d jobs and requested %v, want only the recorded request", len(disabled.scheduler.jobs), disabled.repositories.requested)
}
}
func TestCheckResultMapsFetchOutcomes(t *testing.T) {
previous := outbound.RepositoryCheck{Key: "a/b", State: outbound.RepositoryCheckVerified, Evidence: domain.RepositoryEvidence{Description: "old"}}
verified, wait, err := checkResult(previous, outbound.RepositoryFetch{Found: true, GitHubID: 3, Evidence: domain.RepositoryEvidence{Description: "new"}}, nil, testNow)
if err != nil || wait != 0 || verified.State != outbound.RepositoryCheckVerified || !evidenceChanged(previous, verified) {
t.Fatalf("verified = %+v, %v, %v", verified, wait, err)
}
missing, _, _ := checkResult(previous, outbound.RepositoryFetch{}, nil, testNow)
if missing.State != outbound.RepositoryCheckNotFound || missing.Evidence.Description != "" || !evidenceChanged(previous, missing) {
t.Fatalf("missing = %+v", missing)
}
limited, wait, err := checkResult(previous, outbound.RepositoryFetch{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureRateLimited, RetryAfter: time.Hour}, testNow)
if err != nil || wait != time.Hour || limited.State != outbound.RepositoryCheckUnavailable || limited.Failure != outbound.RepositoryFailureRateLimited {
t.Fatalf("limited = %+v, %v, %v", limited, wait, err)
}
if _, _, err := checkResult(previous, outbound.RepositoryFetch{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureNetwork}, testNow); !errors.Is(err, outbound.ErrRepositoryFetchUnavailable) {
t.Fatalf("a network failure was not returned for a retry: %v", err)
}
same := previous
if evidenceChanged(previous, same) {
t.Fatal("an unchanged check reported a change")
}
}
@@ -0,0 +1,182 @@
// Package semantic keeps the stored vectors of candidate cards and need
// snapshots current and checks the GitHub repositories of projects. Every
// change that can move a vector schedules a durable job in the transaction of
// the change; the jobs call the ML service and GitHub later, so no user
// request ever waits for either.
package semantic
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"slices"
"strconv"
"time"
"github.com/google/uuid"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// Job kinds. Renaming one strands the jobs scheduled under the old name.
const (
CandidateJobKind = "semantic.candidate"
NeedJobKind = "semantic.need"
RepositoryCheckJobKind = "profile.repository_check"
)
const (
// vectorJobAttempts lets a vector job outlast an ML outage of about an
// hour and a half with the default backoff; the backfill command repairs
// anything older.
vectorJobAttempts = 20
// repositoryJobAttempts bounds retries of network and server failures;
// a rate limit reschedules instead of failing.
repositoryJobAttempts = 5
// repositoryDigestBytes is the length of the repository digest in a job
// key and payload: the repository address names an account, so jobs
// carry only its digest.
repositoryDigestBytes = 8
)
// Trigger schedules the jobs. With vectors off it schedules no vector job;
// with repository checks off it records the request but schedules no check.
type Trigger struct {
vectors bool
repositories bool
}
// NewTrigger returns the scheduler of the enabled features.
func NewTrigger(vectors, repositories bool) *Trigger {
return &Trigger{vectors: vectors, repositories: repositories}
}
// CandidateChanged schedules a refresh of the card vectors of a candidate.
// Every change gets its own job; a job that finds nothing changed is a no-op.
func (trigger *Trigger) CandidateChanged(ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, at time.Time) error {
if trigger == nil || !trigger.vectors {
return nil
}
occurrence, err := uuid.NewV7()
if err != nil {
return fmt.Errorf("semantic.Trigger.CandidateChanged - generate key: %w", err)
}
return schedule(ctx, unit, CandidateJobKind, candidateID.String()+":"+occurrence.String(), at,
map[string]string{"candidate_id": candidateID.String()}, vectorJobAttempts)
}
// NeedRequirementsChanged schedules the vectors of a new requirements
// snapshot. The key is the snapshot, so a repeat schedules nothing.
func (trigger *Trigger) NeedRequirementsChanged(
ctx context.Context, unit outbound.UnitOfWork, organizationID, needID uuid.UUID, requirementsVersion int64, at time.Time,
) error {
if trigger == nil || !trigger.vectors {
return nil
}
return schedule(ctx, unit, NeedJobKind, needID.String()+":"+strconv.FormatInt(requirementsVersion, 10), at,
map[string]any{
"organization_id": organizationID.String(), "need_id": needID.String(),
"requirements_version": requirementsVersion,
}, vectorJobAttempts)
}
// RepositoriesChanged follows a profile save: it removes the checks of
// repositories that no project links any more and requests a check of every
// newly linked repository. A repository that was linked before keeps its
// check; the candidate asks for a new one explicitly.
func (trigger *Trigger) RepositoriesChanged(
ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID,
previous, current []domain.GitHubRepository, at time.Time,
) error {
const location = "semantic.Trigger.RepositoriesChanged"
keys := make([]string, 0, len(current))
for _, repository := range current {
keys = append(keys, repository.Key())
}
if err := unit.ProjectRepositories().DeleteUnlinked(ctx, candidateID, keys); err != nil {
return fmt.Errorf("%s - remove unlinked checks: %w", location, err)
}
known := make(map[string]bool, len(previous))
for _, repository := range previous {
known[repository.Key()] = true
}
for _, repository := range current {
if known[repository.Key()] {
continue
}
if err := trigger.requestCheck(ctx, unit, candidateID, repository, at); err != nil {
return fmt.Errorf("%s - request check: %w", location, err)
}
}
return nil
}
// RequestChecks requests a new check of every given repository.
func (trigger *Trigger) RequestChecks(
ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, repositories []domain.GitHubRepository, at time.Time,
) error {
for _, repository := range repositories {
if err := trigger.requestCheck(ctx, unit, candidateID, repository, at); err != nil {
return fmt.Errorf("semantic.Trigger.RequestChecks - request check: %w", err)
}
}
return nil
}
func (trigger *Trigger) requestCheck(
ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, repository domain.GitHubRepository, at time.Time,
) error {
if err := unit.ProjectRepositories().Request(ctx, candidateID, repository.Key(), at); err != nil {
return err
}
if trigger == nil || !trigger.repositories {
return nil
}
return scheduleRepositoryCheck(ctx, unit, candidateID, repository.Key(), at)
}
func scheduleRepositoryCheck(ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, key string, at time.Time) error {
occurrence, err := uuid.NewV7()
if err != nil {
return fmt.Errorf("generate key: %w", err)
}
digest := repositoryDigest(key)
return schedule(ctx, unit, RepositoryCheckJobKind, candidateID.String()+":"+digest+":"+occurrence.String(), at,
map[string]string{"candidate_id": candidateID.String(), "repository": digest}, repositoryJobAttempts)
}
// repositoryDigest identifies a repository in a job without naming its owner.
func repositoryDigest(key string) string {
digest := sha256.Sum256([]byte(key))
return hex.EncodeToString(digest[:repositoryDigestBytes])
}
func schedule(ctx context.Context, unit outbound.UnitOfWork, kind, key string, at time.Time, payload any, attempts int) error {
encoded, err := json.Marshal(payload)
if err != nil {
return fmt.Errorf("semantic.schedule - encode payload: %w", err)
}
job, err := domain.NewScheduledJob(domain.ScheduledJobInput{Kind: kind, Key: key, DueAt: at, Payload: encoded, MaxAttempts: attempts})
if err != nil {
return fmt.Errorf("semantic.schedule - build job: %w", err)
}
if _, err := unit.ScheduledJobs().Schedule(ctx, job); err != nil {
return fmt.Errorf("semantic.schedule - schedule job: %w", err)
}
return nil
}
// linkedRepositories returns the repositories of the current projects that
// match a digest.
func linkedRepository(content domain.CandidateProfileContent, digest string) (domain.GitHubRepository, bool) {
index := slices.IndexFunc(content.ProjectRepositories(), func(repository domain.GitHubRepository) bool {
return repositoryDigest(repository.Key()) == digest
})
if index < 0 {
return domain.GitHubRepository{}, false
}
return content.ProjectRepositories()[index], true
}