feat(matching): rank with semantic embeddings and explain matches by evidence
This commit is contained in:
1 parent
facc1789b1
commit
24b64d698a
215 files changed
+16951
-327
No files matched your search
@@ -26,19 +26,28 @@ var (
|
||||
type Dependencies struct {
|
||||
Transactor outbound.Transactor
|
||||
Clock func() time.Time
|
||||
// Semantic schedules the card vector refresh after a publication change;
|
||||
// nil schedules nothing.
|
||||
Semantic SemanticTrigger
|
||||
}
|
||||
|
||||
// SemanticTrigger schedules the refresh of a candidate's card vectors.
|
||||
type SemanticTrigger interface {
|
||||
CandidateChanged(ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, at time.Time) error
|
||||
}
|
||||
|
||||
// Service applies candidate-owned privacy settings in one transaction.
|
||||
type Service struct {
|
||||
transactor outbound.Transactor
|
||||
clock func() time.Time
|
||||
semantic SemanticTrigger
|
||||
}
|
||||
|
||||
func NewService(deps Dependencies) (*Service, error) {
|
||||
if deps.Transactor == nil || deps.Clock == nil {
|
||||
return nil, fmt.Errorf("candidateprivacy.NewService - dependencies are missing: %w", ErrPrivacyServiceUnavailable)
|
||||
}
|
||||
return &Service{transactor: deps.Transactor, clock: deps.Clock}, nil
|
||||
return &Service{transactor: deps.Transactor, clock: deps.Clock, semantic: deps.Semantic}, nil
|
||||
}
|
||||
|
||||
func (service *Service) GetMyPrivacySettings(ctx context.Context, userID uuid.UUID) (outbound.CandidatePrivacySettings, error) {
|
||||
@@ -110,7 +119,17 @@ func (service *Service) SetMyPublication(
|
||||
if !change.Changed {
|
||||
return nil
|
||||
}
|
||||
return persistPublicationChange(ctx, unit, repository, userID, expectedVersion, change, at, location)
|
||||
if err := persistPublicationChange(ctx, unit, repository, userID, expectedVersion, change, at, location); err != nil {
|
||||
return err
|
||||
}
|
||||
// The published fields are the text of the card vectors: a closed card
|
||||
// drops them, and another field set renders another text.
|
||||
if service.semantic != nil {
|
||||
if err := service.semantic.CandidateChanged(ctx, unit, userID, at); err != nil {
|
||||
return fmt.Errorf("%s - schedule vector refresh: %w", location, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Publication{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
|
||||
@@ -766,6 +766,9 @@ func cardViewAccessEvent(
|
||||
if view.SalaryCompatibility != nil {
|
||||
fields = append(fields, domain.CardFieldSalaryCompatibility)
|
||||
}
|
||||
if len(view.Projects) > 0 {
|
||||
fields = append(fields, domain.CardFieldProjects)
|
||||
}
|
||||
if !domain.IsCandidateViewPseudonym(view.Pseudonym) {
|
||||
return domain.CandidateCardAccess{}, ErrInvalidCandidateHandle
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@ type explanationInput struct {
|
||||
// percentileReason is the reason that the percentile is null; the zero
|
||||
// value means the cohort is below the minimum.
|
||||
percentileReason UnknownReason
|
||||
// semanticsKnown is true when Sem came from stored vectors.
|
||||
semanticsKnown bool
|
||||
}
|
||||
|
||||
// explain builds the bounded, templated explanation and the unknown flags.
|
||||
@@ -111,7 +113,9 @@ func skillGroupState(input explanationInput, required bool) (EvidenceState, bool
|
||||
// the specialization has no confirmation instead.
|
||||
func unknownFlags(input explanationInput) []UnknownFlag {
|
||||
flags := make([]UnknownFlag, 0, 9)
|
||||
flags = append(flags, UnknownFlag{Component: UnknownSemantics, Reason: ReasonMLUnavailable})
|
||||
if !input.semanticsKnown {
|
||||
flags = append(flags, UnknownFlag{Component: UnknownSemantics, Reason: ReasonMLUnavailable})
|
||||
}
|
||||
if input.confirmed {
|
||||
reason := input.percentileReason
|
||||
if reason == "" {
|
||||
|
||||
@@ -60,7 +60,7 @@ func TestRankKeepsTheNeutralTWhenTheRealCohortReachesTheMinimum(t *testing.T) {
|
||||
confirmedCard(domain.SpecializationBackend, domain.GradeIntern),
|
||||
confirmedCard(domain.SpecializationFrontend, domain.GradeJunior),
|
||||
}
|
||||
ranked, err := service.rank(context.Background(), cohortUnit{evidence: evidence}, Request{}, searchBasis{}, policy, cards)
|
||||
ranked, err := service.rank(context.Background(), cohortUnit{evidence: evidence}, Request{}, searchBasis{}, policy, needSemantics{}, cards)
|
||||
if err != nil {
|
||||
t.Fatalf("rank() error = %v, want a result whatever the real cohort size", err)
|
||||
}
|
||||
|
||||
@@ -67,7 +67,7 @@ func TestRevealCutsEachGroupAndRecordsTheFieldsReturned(t *testing.T) {
|
||||
policy := domain.DemoMatchingPolicy()
|
||||
policy.MaxResultsPerGroup = 2
|
||||
views := newViewsFake(10)
|
||||
result, err := revealService(views).reveal(context.Background(), nil, Request{}, policy, groups{
|
||||
result, err := revealService(views).reveal(context.Background(), nil, Request{}, policy, needSemantics{}, groups{
|
||||
main: []rankedEntry{confirmedItem(first), confirmedItem(second), confirmedItem(uuid.New())},
|
||||
unconfirmed: []rankedEntry{declaredItem(first, domain.SpecializationNetworkEngineer)},
|
||||
})
|
||||
@@ -97,7 +97,7 @@ func TestRevealCutsEachGroupAndRecordsTheFieldsReturned(t *testing.T) {
|
||||
func TestRevealReturnsThePrefixThatIsPaidForWhenTheAllowanceEnds(t *testing.T) {
|
||||
ids := []uuid.UUID{uuid.New(), uuid.New(), uuid.New(), uuid.New()}
|
||||
views := newViewsFake(2)
|
||||
result, err := revealService(views).reveal(context.Background(), nil, Request{}, domain.DemoMatchingPolicy(), groups{
|
||||
result, err := revealService(views).reveal(context.Background(), nil, Request{}, domain.DemoMatchingPolicy(), needSemantics{}, groups{
|
||||
main: []rankedEntry{confirmedItem(ids[0])},
|
||||
near: []rankedEntry{confirmedItem(ids[1]), confirmedItem(ids[2])},
|
||||
unconfirmed: []rankedEntry{declaredItem(ids[0], domain.SpecializationNetworkEngineer), declaredItem(ids[3], domain.SpecializationQA)},
|
||||
@@ -116,13 +116,13 @@ func TestRevealReturnsThePrefixThatIsPaidForWhenTheAllowanceEnds(t *testing.T) {
|
||||
|
||||
func TestRevealDoesNotFlagACompleteResult(t *testing.T) {
|
||||
views := newViewsFake(5)
|
||||
result, err := revealService(views).reveal(context.Background(), nil, Request{}, domain.DemoMatchingPolicy(), groups{
|
||||
result, err := revealService(views).reveal(context.Background(), nil, Request{}, domain.DemoMatchingPolicy(), needSemantics{}, groups{
|
||||
main: []rankedEntry{confirmedItem(uuid.New())},
|
||||
})
|
||||
if err != nil || result.Truncated || len(result.Main) != 1 {
|
||||
t.Fatalf("reveal() = %+v, %v, want one entry that is not truncated", result, err)
|
||||
}
|
||||
empty, err := revealService(newViewsFake(0)).reveal(context.Background(), nil, Request{}, domain.DemoMatchingPolicy(), groups{})
|
||||
empty, err := revealService(newViewsFake(0)).reveal(context.Background(), nil, Request{}, domain.DemoMatchingPolicy(), needSemantics{}, groups{})
|
||||
if err != nil || empty.Truncated || len(empty.Main)+len(empty.Near)+len(empty.Unconfirmed) != 0 {
|
||||
t.Fatalf("an empty search = %+v, %v, want an empty result that is not truncated", empty, err)
|
||||
}
|
||||
|
||||
@@ -68,10 +68,14 @@ type scoreInput struct {
|
||||
policy domain.MatchingPolicy
|
||||
skills []requestedSkill
|
||||
evidence []evidenceSource
|
||||
// semantics is the calibrated Sem in micro units, or nil when it is
|
||||
// unknown and the neutral value applies.
|
||||
semantics *int64
|
||||
}
|
||||
|
||||
// computeScores applies the FR09 model. Unknown components are neutral: Dom,
|
||||
// Sem, Fr, and Rsp use the neutral value, T is neutral because there is no
|
||||
// computeScores applies the FR09 model. Sem is the calibrated similarity when
|
||||
// stored vectors give one. Unknown components are neutral: Dom, Sem without
|
||||
// vectors, Fr, and Rsp use the neutral value, T is neutral because there is no
|
||||
// comparable real cohort, and V is zero because no competition evidence
|
||||
// exists, which is not a penalty.
|
||||
func computeScores(input scoreInput) scores {
|
||||
@@ -80,6 +84,9 @@ func computeScores(input scoreInput) scores {
|
||||
result := scores{
|
||||
domain: neutral, semantics: neutral, t: neutral, freshness: neutral, responsive: neutral,
|
||||
}
|
||||
if input.semantics != nil {
|
||||
result.semantics = *input.semantics
|
||||
}
|
||||
result.skills = make([]skillOutcome, 0, len(input.skills))
|
||||
var weighted, weights int64
|
||||
for _, skill := range input.skills {
|
||||
|
||||
@@ -153,11 +153,15 @@ func (service *Service) searchOnce(ctx context.Context, request Request) (Result
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ranked, err := service.rank(ctx, unit, request, basis, policy, cards)
|
||||
semantics, err := loadNeedSemantics(ctx, unit, policy, basis)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err = service.reveal(ctx, unit, request, policy, ranked)
|
||||
ranked, err := service.rank(ctx, unit, request, basis, policy, semantics, cards)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err = service.reveal(ctx, unit, request, policy, semantics, ranked)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
@@ -182,6 +186,9 @@ func (service *Service) matchingPolicy(ctx context.Context, unit outbound.UnitOf
|
||||
// searchBasis is what a need snapshot contributes to the search. A bank search
|
||||
// has an empty basis.
|
||||
type searchBasis struct {
|
||||
// need is the requirements snapshot of a need search; nil for a bank
|
||||
// search.
|
||||
need *domain.NeedSnapshot
|
||||
specialization *domain.SpecializationCode
|
||||
skills []requestedSkill
|
||||
requestedFormats []domain.QuestionnaireWorkFormat
|
||||
@@ -205,7 +212,9 @@ func loadBasis(ctx context.Context, unit outbound.UnitOfWork, request Request) (
|
||||
if need.RequirementsVersion() != request.Need.RequirementsVersion {
|
||||
return searchBasis{}, ErrNeedNotFound
|
||||
}
|
||||
requirements := need.Snapshot().Requirements
|
||||
snapshot := need.Snapshot()
|
||||
basis.need = &snapshot
|
||||
requirements := snapshot.Requirements
|
||||
if requirements.Specialization.Status == domain.NeedValueConfirmed && requirements.Specialization.Value != nil {
|
||||
specialization := *requirements.Specialization.Value
|
||||
basis.specialization = &specialization
|
||||
@@ -315,10 +324,13 @@ func entriesOf(visible domain.VisibleCandidateCard) []candidateEntry {
|
||||
type rankedEntry struct {
|
||||
entry Entry
|
||||
candidate uuid.UUID
|
||||
fit int64
|
||||
coverage int64
|
||||
rank int64
|
||||
near bool
|
||||
// card is the card as this organization reads it; the semantic
|
||||
// explanation names only what it shows.
|
||||
card domain.AnonymousCandidateViewDTO
|
||||
fit int64
|
||||
coverage int64
|
||||
rank int64
|
||||
near bool
|
||||
}
|
||||
|
||||
// groups holds the ranked entries of the three groups before the output is cut.
|
||||
@@ -332,6 +344,7 @@ func (service *Service) rank(
|
||||
request Request,
|
||||
basis searchBasis,
|
||||
policy domain.MatchingPolicy,
|
||||
semantics needSemantics,
|
||||
cards []domain.VisibleCandidateCard,
|
||||
) (groups, error) {
|
||||
specialization, compatible := effectiveSpecialization(request.Filters.Specialization, basis.specialization)
|
||||
@@ -358,9 +371,17 @@ func (service *Service) rank(
|
||||
if err != nil {
|
||||
return groups{}, err
|
||||
}
|
||||
semanticValues, err := candidateSemantics(ctx, unit, semantics, accepted)
|
||||
if err != nil {
|
||||
return groups{}, err
|
||||
}
|
||||
var result groups
|
||||
for _, entry := range accepted {
|
||||
ranked := scoreEntry(entry, policy, basis, requestedFormats, facts[entry.candidateID], reachedCohorts)
|
||||
var semantic *int64
|
||||
if value, known := semanticValues[entry.candidateID]; known {
|
||||
semantic = &value
|
||||
}
|
||||
ranked := scoreEntry(entry, policy, basis, requestedFormats, facts[entry.candidateID], reachedCohorts, semantic)
|
||||
switch {
|
||||
case entry.category == nil:
|
||||
result.unconfirmed = append(result.unconfirmed, ranked)
|
||||
@@ -460,15 +481,15 @@ func (service *Service) reveal(
|
||||
unit outbound.UnitOfWork,
|
||||
request Request,
|
||||
policy domain.MatchingPolicy,
|
||||
semantics needSemantics,
|
||||
ranked groups,
|
||||
) (Result, error) {
|
||||
result := Result{Source: sourceOf(request), Main: []Entry{}, Near: []Entry{}, Unconfirmed: []Entry{}}
|
||||
limit := int(policy.MaxResultsPerGroup)
|
||||
for _, group := range []*[]rankedEntry{&ranked.main, &ranked.near, &ranked.unconfirmed} {
|
||||
if len(*group) > limit {
|
||||
*group = (*group)[:limit]
|
||||
result.Truncated = true
|
||||
}
|
||||
result.Truncated = cutGroups(&ranked, int(policy.MaxResultsPerGroup))
|
||||
// The explanation is part of what is revealed and charged, so it is
|
||||
// attached before the charge records the fields.
|
||||
if err := attachSemanticEvidence(ctx, unit, semantics, ranked); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
views, err := service.views(ctx, unit, request.ActorID, request.OrganizationID)
|
||||
if err != nil {
|
||||
@@ -522,6 +543,18 @@ func (service *Service) reveal(
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// cutGroups cuts each group to the limit and reports whether one was longer.
|
||||
func cutGroups(ranked *groups, limit int) bool {
|
||||
truncated := false
|
||||
for _, group := range []*[]rankedEntry{&ranked.main, &ranked.near, &ranked.unconfirmed} {
|
||||
if len(*group) > limit {
|
||||
*group = (*group)[:limit]
|
||||
truncated = true
|
||||
}
|
||||
}
|
||||
return truncated
|
||||
}
|
||||
|
||||
// entryFields lists the card fields that an entry actually shows, so the
|
||||
// candidate's history names what the search returned about them.
|
||||
func entryFields(entry Entry) []domain.CardField {
|
||||
@@ -545,6 +578,12 @@ func entryFields(entry Entry) []domain.CardField {
|
||||
if entry.PublicContext.SalaryCompatibility != nil {
|
||||
fields = append(fields, domain.CardFieldSalaryCompatibility)
|
||||
}
|
||||
for _, evidence := range entry.SemanticEvidence {
|
||||
if evidence.ProjectTitle != nil {
|
||||
fields = append(fields, domain.CardFieldProjects)
|
||||
break
|
||||
}
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
@@ -553,6 +592,7 @@ func orderedFields(set map[domain.CardField]struct{}) []domain.CardField {
|
||||
for _, field := range []domain.CardField{
|
||||
domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience,
|
||||
domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, domain.CardFieldSalaryCompatibility,
|
||||
domain.CardFieldProjects,
|
||||
} {
|
||||
if _, shown := set[field]; shown {
|
||||
fields = append(fields, field)
|
||||
@@ -595,6 +635,7 @@ func scoreEntry(
|
||||
requestedFormats []domain.QuestionnaireWorkFormat,
|
||||
facts []evidenceSource,
|
||||
reachedCohorts map[outbound.CategoryKey]bool,
|
||||
semantic *int64,
|
||||
) rankedEntry {
|
||||
evidence := make([]evidenceSource, 0, len(entry.card.Skills)+len(facts))
|
||||
for _, skill := range entry.card.Skills {
|
||||
@@ -609,7 +650,7 @@ func scoreEntry(
|
||||
}
|
||||
}
|
||||
}
|
||||
computed := computeScores(scoreInput{confirmed: confirmed, policy: policy, skills: basis.skills, evidence: evidence})
|
||||
computed := computeScores(scoreInput{confirmed: confirmed, policy: policy, skills: basis.skills, evidence: evidence, semantics: semantic})
|
||||
context := PublicContext{
|
||||
ExperienceBand: entry.card.ExperienceBand, SalaryCompatibility: entry.card.SalaryCompatibility,
|
||||
}
|
||||
@@ -622,7 +663,7 @@ func scoreEntry(
|
||||
summary, flags := explain(explanationInput{
|
||||
confirmed: confirmed, declaredGrade: entry.declaredGrade, policy: policy, scores: computed, context: context,
|
||||
requestedFormats: requestedFormats, needDomainConfirmed: basis.needDomainConfirmed,
|
||||
percentileReason: percentileReason(entry, reachedCohorts),
|
||||
percentileReason: percentileReason(entry, reachedCohorts), semanticsKnown: semantic != nil,
|
||||
})
|
||||
components := Components{Fit: microToFloat(computed.fit), Coverage: microToFloat(computed.coverage)}
|
||||
if confirmed {
|
||||
@@ -639,7 +680,7 @@ func scoreEntry(
|
||||
DeclaredGrade: entry.declaredGrade, Category: entry.category,
|
||||
PublicContext: context, EvidenceSummary: summary, Components: components, UnknownFlags: flags,
|
||||
},
|
||||
candidate: entry.candidateID, fit: computed.fit, coverage: computed.coverage, rank: computed.rank,
|
||||
candidate: entry.candidateID, card: entry.card, fit: computed.fit, coverage: computed.coverage, rank: computed.rank,
|
||||
near: confirmed && computed.belongsToNearGroup(policy),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,275 @@
|
||||
package matching
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"cmp"
|
||||
"context"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// needSemantics holds the stored vectors of the need of a search: the whole
|
||||
// view of every policy member, in member order, and each confirmed
|
||||
// requirement of the explanation model. It is empty when the policy names no
|
||||
// model, for a bank search, and while the need vectors are not computed.
|
||||
type needSemantics struct {
|
||||
policy *domain.MatchingSemanticsPolicy
|
||||
wholes []domain.SemanticVector
|
||||
requirements []needRequirement
|
||||
}
|
||||
|
||||
type needRequirement struct {
|
||||
item domain.SemanticItem
|
||||
vector domain.SemanticVector
|
||||
order int
|
||||
}
|
||||
|
||||
// available reports whether Sem can be computed for candidates with vectors:
|
||||
// every member has the whole view of the need.
|
||||
func (semantics needSemantics) available() bool {
|
||||
return semantics.policy != nil && len(semantics.policy.Members) > 0 && len(semantics.wholes) == len(semantics.policy.Members)
|
||||
}
|
||||
|
||||
// loadNeedSemantics renders the need snapshot the search uses and reads the
|
||||
// stored vectors whose text digests match it, so a stale vector of another
|
||||
// snapshot or rendering is never used. The search never calls ML.
|
||||
func loadNeedSemantics(
|
||||
ctx context.Context, unit outbound.UnitOfWork, policy domain.MatchingPolicy, basis searchBasis,
|
||||
) (needSemantics, error) {
|
||||
if policy.Semantics == nil || basis.need == nil {
|
||||
return needSemantics{}, nil
|
||||
}
|
||||
document := domain.NewNeedSemanticDocument(*basis.need)
|
||||
items := document.All()
|
||||
digests := make([][32]byte, 0, len(items))
|
||||
for _, item := range items {
|
||||
digests = append(digests, item.ContentDigest())
|
||||
}
|
||||
result, complete := needSemantics{policy: policy.Semantics}, true
|
||||
for index, member := range policy.Semantics.Members {
|
||||
requested := digests
|
||||
if index > 0 {
|
||||
// Other members store the whole view only.
|
||||
requested = [][32]byte{document.Whole.ContentDigest()}
|
||||
}
|
||||
stored, err := unit.SemanticVectors().NeedVectors(ctx, basis.need.ID, member.Model, requested)
|
||||
if err != nil {
|
||||
return needSemantics{}, fmt.Errorf("matching.loadNeedSemantics - read need vectors: %w", err)
|
||||
}
|
||||
if index == 0 {
|
||||
for order, item := range document.Items {
|
||||
if vector, ok := stored[item.Key]; ok {
|
||||
result.requirements = append(result.requirements, needRequirement{item: item, vector: vector, order: order})
|
||||
}
|
||||
}
|
||||
}
|
||||
if whole, ok := stored[document.Whole.Key]; ok {
|
||||
result.wholes = append(result.wholes, whole)
|
||||
} else {
|
||||
complete = false
|
||||
}
|
||||
}
|
||||
if !complete {
|
||||
// Without every whole view Sem stays unknown; the explanation still
|
||||
// works from the requirement vectors.
|
||||
result.wholes = nil
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// candidateSemantics returns Sem in micro units for every candidate whose
|
||||
// whole-view vector is stored for every policy member: the calibrated fused
|
||||
// score of the member cosines.
|
||||
func candidateSemantics(
|
||||
ctx context.Context, unit outbound.UnitOfWork, semantics needSemantics, accepted []candidateEntry,
|
||||
) (map[uuid.UUID]int64, error) {
|
||||
values := make(map[uuid.UUID]int64)
|
||||
if !semantics.available() {
|
||||
return values, nil
|
||||
}
|
||||
ids := distinctCandidates(accepted)
|
||||
cosines := make(map[uuid.UUID][]float64, len(ids))
|
||||
for index, member := range semantics.policy.Members {
|
||||
vectors, err := unit.SemanticVectors().CandidateWholeVectors(ctx, member.Model, ids)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("matching.candidateSemantics - read card vectors: %w", err)
|
||||
}
|
||||
for id, vector := range vectors {
|
||||
// A candidate missing an earlier member stays incomplete.
|
||||
if len(cosines[id]) != index {
|
||||
continue
|
||||
}
|
||||
if cosine, ok := semantics.wholes[index].Cosine(vector); ok {
|
||||
cosines[id] = append(cosines[id], cosine)
|
||||
}
|
||||
}
|
||||
}
|
||||
for id, memberCosines := range cosines {
|
||||
if score, ok := semantics.policy.FusedScore(memberCosines); ok {
|
||||
values[id] = semantics.policy.Probability(score)
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
func distinctCandidates(entries []candidateEntry) []uuid.UUID {
|
||||
seen := make(map[uuid.UUID]struct{}, len(entries))
|
||||
ids := make([]uuid.UUID, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if _, repeated := seen[entry.candidateID]; repeated {
|
||||
continue
|
||||
}
|
||||
seen[entry.candidateID] = struct{}{}
|
||||
ids = append(ids, entry.candidateID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
|
||||
// attachSemanticEvidence explains the entries that a search returns. It
|
||||
// reads the item vectors of those candidates only, so its cost depends on
|
||||
// the output limit, not on the bank.
|
||||
func attachSemanticEvidence(
|
||||
ctx context.Context, unit outbound.UnitOfWork, semantics needSemantics, ranked groups,
|
||||
) error {
|
||||
if semantics.policy == nil || len(semantics.requirements) == 0 {
|
||||
return nil
|
||||
}
|
||||
var ids []uuid.UUID
|
||||
seen := make(map[uuid.UUID]struct{})
|
||||
for _, group := range [][]rankedEntry{ranked.main, ranked.near, ranked.unconfirmed} {
|
||||
for _, entry := range group {
|
||||
if _, repeated := seen[entry.candidate]; !repeated {
|
||||
seen[entry.candidate] = struct{}{}
|
||||
ids = append(ids, entry.candidate)
|
||||
}
|
||||
}
|
||||
}
|
||||
items, err := unit.SemanticVectors().CandidateItemVectors(ctx, semantics.policy.ExplanationModel(), ids)
|
||||
if err != nil {
|
||||
return fmt.Errorf("matching.attachSemanticEvidence - read item vectors: %w", err)
|
||||
}
|
||||
for _, group := range [][]rankedEntry{ranked.main, ranked.near, ranked.unconfirmed} {
|
||||
for index := range group {
|
||||
group[index].entry.SemanticEvidence = selectEvidence(semantics, group[index].card, items[group[index].candidate])
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// cardItem is a stored candidate item that the card shows to this
|
||||
// organization now.
|
||||
type cardItem struct {
|
||||
key string
|
||||
kind domain.SemanticItemKind
|
||||
title *string
|
||||
verified bool
|
||||
vector domain.SemanticVector
|
||||
}
|
||||
|
||||
// visibleItems keeps the stored items that the card, as this organization
|
||||
// reads it, still shows: a project only while the card has a project at the
|
||||
// same position with the same title, the stack and roles only while the card
|
||||
// shows them after cohort generalization. A stale or hidden item never
|
||||
// explains anything.
|
||||
func visibleItems(card domain.AnonymousCandidateViewDTO, stored []outbound.SemanticItemVector) []cardItem {
|
||||
var visible []cardItem
|
||||
for _, item := range stored {
|
||||
kind, position, ok := strings.Cut(item.Key, ":")
|
||||
switch domain.SemanticItemKind(kind) {
|
||||
case domain.SemanticItemProject:
|
||||
index, err := strconv.Atoi(position)
|
||||
if !ok || err != nil || index < 0 || index >= len(card.Projects) {
|
||||
continue
|
||||
}
|
||||
project := card.Projects[index]
|
||||
if !bytes.Equal(domain.SemanticLabelDigest(project.Title), item.LabelDigest) {
|
||||
continue
|
||||
}
|
||||
title := project.Title
|
||||
visible = append(visible, cardItem{
|
||||
key: item.Key, kind: domain.SemanticItemProject, title: &title,
|
||||
verified: project.RepositoryVerified, vector: item.Vector,
|
||||
})
|
||||
case domain.SemanticItemStack:
|
||||
if len(card.Skills) > 0 {
|
||||
visible = append(visible, cardItem{key: item.Key, kind: domain.SemanticItemStack, vector: item.Vector})
|
||||
}
|
||||
case domain.SemanticItemRoles:
|
||||
if len(card.SelfAssessment) > 0 || len(card.Categories) > 0 {
|
||||
visible = append(visible, cardItem{key: item.Key, kind: domain.SemanticItemRoles, vector: item.Vector})
|
||||
}
|
||||
case domain.SemanticItemWhole, domain.SemanticItemRequiredSkill, domain.SemanticItemDesiredSkill, domain.SemanticItemTask:
|
||||
// Not a card item: the whole view ranks, and requirements belong to needs.
|
||||
}
|
||||
}
|
||||
slices.SortFunc(visible, func(left, right cardItem) int { return strings.Compare(left.key, right.key) })
|
||||
return visible
|
||||
}
|
||||
|
||||
type scoredEvidence struct {
|
||||
evidence SemanticEvidence
|
||||
cosine float64
|
||||
order int
|
||||
}
|
||||
|
||||
// selectEvidence pairs every requirement with its closest visible card item
|
||||
// and keeps the pairs that reach a band, high before medium, then by
|
||||
// similarity, then in requirement order, up to the policy limit.
|
||||
func selectEvidence(semantics needSemantics, card domain.AnonymousCandidateViewDTO, stored []outbound.SemanticItemVector) []SemanticEvidence {
|
||||
items := visibleItems(card, stored)
|
||||
if len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
var scored []scoredEvidence
|
||||
for _, requirement := range semantics.requirements {
|
||||
bestIndex, bestCosine := -1, 0.0
|
||||
for index, item := range items {
|
||||
cosine, ok := requirement.vector.Cosine(item.vector)
|
||||
if ok && (bestIndex < 0 || cosine > bestCosine) {
|
||||
bestIndex, bestCosine = index, cosine
|
||||
}
|
||||
}
|
||||
if bestIndex < 0 {
|
||||
continue
|
||||
}
|
||||
band := semantics.policy.ItemBand(requirement.item.Kind == domain.SemanticItemTask, bestCosine)
|
||||
if band == "" {
|
||||
continue
|
||||
}
|
||||
best := items[bestIndex]
|
||||
scored = append(scored, scoredEvidence{
|
||||
evidence: SemanticEvidence{
|
||||
RequirementKind: requirement.item.Kind, RequirementText: requirement.item.Label,
|
||||
ItemKind: best.kind, ProjectTitle: best.title, RepositoryVerified: best.verified, Similarity: band,
|
||||
},
|
||||
cosine: bestCosine, order: requirement.order,
|
||||
})
|
||||
}
|
||||
slices.SortStableFunc(scored, func(left, right scoredEvidence) int {
|
||||
return cmp.Or(
|
||||
cmp.Compare(bandRank(left.evidence.Similarity), bandRank(right.evidence.Similarity)),
|
||||
cmp.Compare(right.cosine, left.cosine),
|
||||
cmp.Compare(left.order, right.order),
|
||||
)
|
||||
})
|
||||
limit := min(len(scored), int(semantics.policy.MaxEvidencePerEntry))
|
||||
evidence := make([]SemanticEvidence, 0, limit)
|
||||
for _, item := range scored[:limit] {
|
||||
evidence = append(evidence, item.evidence)
|
||||
}
|
||||
return evidence
|
||||
}
|
||||
|
||||
func bandRank(band domain.SemanticSimilarityBand) int {
|
||||
if band == domain.SemanticSimilarityHigh {
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package matching
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math"
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// unit returns a normalized two-dimensional vector at the given cosine to
|
||||
// the first axis.
|
||||
func unit(cosine float64) domain.SemanticVector {
|
||||
return domain.SemanticVector{float32(cosine), float32(math.Sqrt(1 - cosine*cosine))}
|
||||
}
|
||||
|
||||
func semanticFixture() needSemantics {
|
||||
policy := domain.DemoMatchingSemanticsPolicy()
|
||||
return needSemantics{
|
||||
policy: &policy,
|
||||
wholes: []domain.SemanticVector{unit(1)},
|
||||
requirements: []needRequirement{
|
||||
{item: domain.SemanticItem{Key: "required_skill:0", Kind: domain.SemanticItemRequiredSkill, Label: "Kafka"}, vector: unit(1), order: 0},
|
||||
{item: domain.SemanticItem{Key: "task:0", Kind: domain.SemanticItemTask, Label: "Make callbacks idempotent"}, vector: unit(1), order: 1},
|
||||
{item: domain.SemanticItem{Key: "task:1", Kind: domain.SemanticItemTask, Label: "Unrelated task"}, vector: domain.SemanticVector{-1, 0}, order: 2},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func TestSelectEvidenceNamesOnlyWhatTheCardShowsAndOrdersStably(t *testing.T) {
|
||||
semantics := semanticFixture()
|
||||
card := domain.AnonymousCandidateViewDTO{
|
||||
Skills: []domain.CandidateViewSkillCode{domain.CandidateViewSkillKafka},
|
||||
Projects: []domain.CandidateViewProject{{Title: "Ledger", RepositoryVerified: true}},
|
||||
}
|
||||
stored := []outbound.SemanticItemVector{
|
||||
{Key: "stack", Vector: unit(0.40)},
|
||||
{Key: "project:0", LabelDigest: domain.SemanticLabelDigest("Ledger"), Vector: unit(0.50)},
|
||||
}
|
||||
evidence := selectEvidence(semantics, card, stored)
|
||||
if len(evidence) != 2 {
|
||||
t.Fatalf("evidence = %+v, want two items above the thresholds", evidence)
|
||||
}
|
||||
// The project is the closest item to both requirements and reaches the
|
||||
// high band; equal similarities keep the requirement order, and the
|
||||
// unrelated task produces nothing.
|
||||
first, second := evidence[0], evidence[1]
|
||||
if first.RequirementText != "Kafka" || first.Similarity != domain.SemanticSimilarityHigh ||
|
||||
first.ItemKind != domain.SemanticItemProject || first.ProjectTitle == nil || *first.ProjectTitle != "Ledger" || !first.RepositoryVerified {
|
||||
t.Fatalf("first = %+v", first)
|
||||
}
|
||||
if second.RequirementText != "Make callbacks idempotent" || second.RequirementKind != domain.SemanticItemTask {
|
||||
t.Fatalf("second = %+v", second)
|
||||
}
|
||||
if again := selectEvidence(semantics, card, slices.Clone(stored)); !slices.EqualFunc(evidence, again, func(a, b SemanticEvidence) bool {
|
||||
return a.RequirementText == b.RequirementText && a.ItemKind == b.ItemKind && a.Similarity == b.Similarity
|
||||
}) {
|
||||
t.Fatal("the same vectors gave another explanation")
|
||||
}
|
||||
|
||||
t.Run("a stale project title is never shown", func(t *testing.T) {
|
||||
renamed := card
|
||||
renamed.Projects = []domain.CandidateViewProject{{Title: "Renamed"}}
|
||||
for _, item := range selectEvidence(semantics, renamed, stored) {
|
||||
if item.ItemKind == domain.SemanticItemProject {
|
||||
t.Fatalf("evidence names a project whose title changed: %+v", item)
|
||||
}
|
||||
}
|
||||
})
|
||||
t.Run("unpublished projects and a generalized stack explain nothing", func(t *testing.T) {
|
||||
hidden := domain.AnonymousCandidateViewDTO{}
|
||||
if got := selectEvidence(semantics, hidden, stored); len(got) != 0 {
|
||||
t.Fatalf("evidence = %+v for a card that shows neither the stack nor projects", got)
|
||||
}
|
||||
})
|
||||
t.Run("the limit cuts the list", func(t *testing.T) {
|
||||
limited := semanticFixture()
|
||||
limited.policy.MaxEvidencePerEntry = 1
|
||||
if got := selectEvidence(limited, card, stored); len(got) != 1 {
|
||||
t.Fatalf("evidence = %d items, want 1", len(got))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestSemanticsEnterFitAndClearTheFlagOnlyWhenKnown(t *testing.T) {
|
||||
policy := domain.DemoSemanticMatchingPolicy()
|
||||
skills := []requestedSkill{{code: "go", required: true}}
|
||||
high, low := int64(900_000), int64(100_000)
|
||||
withHigh := computeScores(scoreInput{policy: policy, skills: skills, semantics: &high})
|
||||
withLow := computeScores(scoreInput{policy: policy, skills: skills, semantics: &low})
|
||||
unknown := computeScores(scoreInput{policy: policy, skills: skills})
|
||||
// Cov is 0, Dom neutral 0.5: Fit = 0.0833*0.5 + 0.5*Sem.
|
||||
if withHigh.fit != 491_650 || withLow.fit != 91_650 || unknown.fit != 291_650 {
|
||||
t.Fatalf("fit = %d / %d / %d", withHigh.fit, withLow.fit, unknown.fit)
|
||||
}
|
||||
flags := unknownFlags(explanationInput{semanticsKnown: true})
|
||||
for _, flag := range flags {
|
||||
if flag.Component == UnknownSemantics {
|
||||
t.Fatal("a known Sem is still flagged")
|
||||
}
|
||||
}
|
||||
if flags := unknownFlags(explanationInput{}); flags[0] != (UnknownFlag{Component: UnknownSemantics, Reason: ReasonMLUnavailable}) {
|
||||
t.Fatalf("flags = %v, want the ML flag first", flags)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProjectEvidenceIsRecordedAsTheProjectsField(t *testing.T) {
|
||||
title := "Ledger"
|
||||
fields := entryFields(Entry{SemanticEvidence: []SemanticEvidence{{ItemKind: domain.SemanticItemProject, ProjectTitle: &title}}})
|
||||
if !slices.Contains(fields, domain.CardFieldProjects) {
|
||||
t.Fatalf("fields = %v, want projects", fields)
|
||||
}
|
||||
if fields := entryFields(Entry{SemanticEvidence: []SemanticEvidence{{ItemKind: domain.SemanticItemStack}}}); slices.Contains(fields, domain.CardFieldProjects) {
|
||||
t.Fatalf("fields = %v, a stack item is not a project", fields)
|
||||
}
|
||||
}
|
||||
|
||||
type wholeVectorsFake struct {
|
||||
outbound.SemanticVectorRepository
|
||||
|
||||
byModel map[domain.SemanticModel]map[uuid.UUID]domain.SemanticVector
|
||||
}
|
||||
|
||||
func (fake wholeVectorsFake) CandidateWholeVectors(
|
||||
_ context.Context, model domain.SemanticModel, _ []uuid.UUID,
|
||||
) (map[uuid.UUID]domain.SemanticVector, error) {
|
||||
return fake.byModel[model], nil
|
||||
}
|
||||
|
||||
type semanticUnitFake struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
vectors wholeVectorsFake
|
||||
}
|
||||
|
||||
func (unit semanticUnitFake) SemanticVectors() outbound.SemanticVectorRepository { return unit.vectors }
|
||||
|
||||
func TestCandidateSemanticsFusesEveryMemberAndSkipsPartialCandidates(t *testing.T) {
|
||||
policy := domain.DemoMatchingSemanticsPolicy()
|
||||
second := domain.SemanticModel{ID: "example/second", Revision: "r1", PromptVersion: "v1"}
|
||||
policy.Members[0].Weight = 5000
|
||||
policy.Members = append(policy.Members, domain.MatchingSemanticMember{
|
||||
Model: second, Weight: 5000, Mean: 0, StandardDeviation: 10000,
|
||||
})
|
||||
first := policy.Members[0].Model
|
||||
complete, partial := uuid.New(), uuid.New()
|
||||
unitOfWork := semanticUnitFake{vectors: wholeVectorsFake{byModel: map[domain.SemanticModel]map[uuid.UUID]domain.SemanticVector{
|
||||
first: {complete: unit(0.2), partial: unit(0.9)},
|
||||
second: {complete: unit(0.6)},
|
||||
}}}
|
||||
semantics := needSemantics{policy: &policy, wholes: []domain.SemanticVector{unit(1), unit(1)}}
|
||||
values, err := candidateSemantics(context.Background(), unitOfWork, semantics,
|
||||
[]candidateEntry{{candidateID: complete}, {candidateID: partial}, {candidateID: complete}})
|
||||
if err != nil {
|
||||
t.Fatalf("candidateSemantics() error = %v", err)
|
||||
}
|
||||
if _, ok := values[partial]; ok {
|
||||
t.Fatal("a candidate without a vector of every member got Sem")
|
||||
}
|
||||
// 0.5 * 0.2 + 0.5 * 0.6 = 0.4 on the calibration of the fused score.
|
||||
if got, want := values[complete], policy.Probability(0.4); len(values) != 1 || got != want {
|
||||
t.Fatalf("Sem = %v, want %d for the complete candidate only", values, want)
|
||||
}
|
||||
semantics.wholes = semantics.wholes[:1]
|
||||
if values, _ := candidateSemantics(context.Background(), unitOfWork, semantics, []candidateEntry{{candidateID: complete}}); len(values) != 0 {
|
||||
t.Fatal("Sem was computed without the whole view of every member of the need")
|
||||
}
|
||||
}
|
||||
@@ -159,6 +159,21 @@ type Components struct {
|
||||
Percentile *float64
|
||||
}
|
||||
|
||||
// SemanticEvidence is one explanation item of the semantic layer: a
|
||||
// confirmed requirement of the need and the published card item closest to
|
||||
// it. Every value is computed from stored vectors and the versioned
|
||||
// thresholds or copied from the need and the published card; no model writes
|
||||
// text into it.
|
||||
type SemanticEvidence struct {
|
||||
RequirementKind domain.SemanticItemKind
|
||||
RequirementText string
|
||||
ItemKind domain.SemanticItemKind
|
||||
// ProjectTitle is the published title for a project item, else nil.
|
||||
ProjectTitle *string
|
||||
RepositoryVerified bool
|
||||
Similarity domain.SemanticSimilarityBand
|
||||
}
|
||||
|
||||
// Entry is one candidate specialization of a result. The handle is the
|
||||
// organization-scoped pseudonym; no account or profile identifier leaves.
|
||||
type Entry struct {
|
||||
@@ -169,8 +184,11 @@ type Entry struct {
|
||||
Category *domain.CandidateViewCategory
|
||||
PublicContext PublicContext
|
||||
EvidenceSummary []EvidenceItem
|
||||
Components Components
|
||||
UnknownFlags []UnknownFlag
|
||||
// SemanticEvidence explains a need search; it is empty for a bank search
|
||||
// and while vectors are missing.
|
||||
SemanticEvidence []SemanticEvidence
|
||||
Components Components
|
||||
UnknownFlags []UnknownFlag
|
||||
}
|
||||
|
||||
// Result holds the three separate groups. Their scores are never merged into
|
||||
|
||||
@@ -33,6 +33,14 @@ type Dependencies struct {
|
||||
Transactor outbound.Transactor
|
||||
Keyring Keyring
|
||||
Clock func() time.Time
|
||||
// Semantic schedules the vectors of a new requirements snapshot; nil
|
||||
// schedules nothing.
|
||||
Semantic SemanticTrigger
|
||||
}
|
||||
|
||||
// SemanticTrigger schedules the vectors of a need's requirements snapshot.
|
||||
type SemanticTrigger interface {
|
||||
NeedRequirementsChanged(ctx context.Context, unit outbound.UnitOfWork, organizationID, needID uuid.UUID, requirementsVersion int64, at time.Time) error
|
||||
}
|
||||
|
||||
// Service applies organization-scoped need commands and reads.
|
||||
@@ -40,6 +48,7 @@ type Service struct {
|
||||
transactor outbound.Transactor
|
||||
keyring Keyring
|
||||
clock func() time.Time
|
||||
semantic SemanticTrigger
|
||||
}
|
||||
|
||||
// NewService fails at startup when a required dependency is missing.
|
||||
@@ -47,7 +56,7 @@ func NewService(deps Dependencies) (*Service, error) {
|
||||
if deps.Transactor == nil || deps.Keyring == nil || deps.Clock == nil {
|
||||
return nil, errors.New("need.NewService - every dependency must be set")
|
||||
}
|
||||
return &Service{transactor: deps.Transactor, keyring: deps.Keyring, clock: deps.Clock}, nil
|
||||
return &Service{transactor: deps.Transactor, keyring: deps.Keyring, clock: deps.Clock, semantic: deps.Semantic}, nil
|
||||
}
|
||||
|
||||
// CreateCommand binds the authenticated actor and path organization to one
|
||||
@@ -110,6 +119,9 @@ func (service *Service) createInTransaction(
|
||||
if err := unit.Needs().Create(ctx, createdNeed); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - store need: %w", createLocation, err)
|
||||
}
|
||||
if err := service.scheduleSemantic(ctx, unit, command.OrganizationID, needID, createdNeed.RequirementsVersion(), request.now); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - %w", createLocation, err)
|
||||
}
|
||||
if err := unit.NeedCreationResults().SaveCreationResult(ctx, request.scope, snapshot); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - store immutable creation response: %w", createLocation, err)
|
||||
}
|
||||
@@ -305,9 +317,28 @@ func (service *Service) updateInTransaction(
|
||||
}
|
||||
return service.recoverConcurrentUpdate(ctx, store, command, now)
|
||||
}
|
||||
if updated.RequirementsVersion() != current.RequirementsVersion() {
|
||||
if err := service.scheduleSemantic(ctx, unit, command.OrganizationID, command.NeedID, updated.RequirementsVersion(), now); err != nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
}
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
// scheduleSemantic schedules the vectors of a new requirements snapshot in
|
||||
// the transaction that created it.
|
||||
func (service *Service) scheduleSemantic(
|
||||
ctx context.Context, unit outbound.UnitOfWork, organizationID, needID uuid.UUID, requirementsVersion int64, at time.Time,
|
||||
) error {
|
||||
if service.semantic == nil {
|
||||
return nil
|
||||
}
|
||||
if err := service.semantic.NeedRequirementsChanged(ctx, unit, organizationID, needID, requirementsVersion, at); err != nil {
|
||||
return fmt.Errorf("schedule need vectors: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service *Service) recoverConcurrentUpdate(
|
||||
ctx context.Context,
|
||||
store outbound.NeedRepository,
|
||||
|
||||
@@ -33,7 +33,31 @@ type MatchingResult struct {
|
||||
// latest version that is not a demonstration version and a family without a
|
||||
// version, because the section is only an addition to a policy that exists.
|
||||
func (publisher *Publisher) EnsureDemoMatchingSection(ctx context.Context, author domain.PolicyAuthor) (MatchingResult, error) {
|
||||
const location = "Publisher.EnsureDemoMatchingSection"
|
||||
return publisher.ensureMatching(ctx, author, "Publisher.EnsureDemoMatchingSection",
|
||||
func(current *domain.MatchingPolicy) bool { return current != nil },
|
||||
domain.DemoMatchingPolicy)
|
||||
}
|
||||
|
||||
// EnsureDemoSemanticMatchingSection makes the latest demonstration version
|
||||
// carry the semantic matching section (domain.DemoSemanticMatchingPolicy): the
|
||||
// encoder identity, the calibration of Sem, the explanation thresholds, and
|
||||
// the Fit weights with Sem 0.5. A version that already has a semantic section
|
||||
// is left alone. Otherwise it publishes the next version, a copy of the latest
|
||||
// one whose matching section is replaced, so the earlier PRD point stays as
|
||||
// the previous version.
|
||||
func (publisher *Publisher) EnsureDemoSemanticMatchingSection(ctx context.Context, author domain.PolicyAuthor) (MatchingResult, error) {
|
||||
return publisher.ensureMatching(ctx, author, "Publisher.EnsureDemoSemanticMatchingSection",
|
||||
func(current *domain.MatchingPolicy) bool { return current != nil && current.Semantics != nil },
|
||||
domain.DemoSemanticMatchingPolicy)
|
||||
}
|
||||
|
||||
func (publisher *Publisher) ensureMatching(
|
||||
ctx context.Context,
|
||||
author domain.PolicyAuthor,
|
||||
location string,
|
||||
present func(*domain.MatchingPolicy) bool,
|
||||
section func() domain.MatchingPolicy,
|
||||
) (MatchingResult, error) {
|
||||
latest, err := publisher.policies.GetLatest(ctx, domain.ProductPolicyKey)
|
||||
if errors.Is(err, outbound.ErrPolicyVersionNotFound) {
|
||||
return MatchingResult{}, fmt.Errorf("%s - the product policy has no version to extend: %w", location, err)
|
||||
@@ -42,13 +66,13 @@ func (publisher *Publisher) EnsureDemoMatchingSection(ctx context.Context, autho
|
||||
return MatchingResult{}, fmt.Errorf("%s - read latest version: %w", location, err)
|
||||
}
|
||||
current := latest.Policy()
|
||||
if current.Matching != nil {
|
||||
if present(current.Matching) {
|
||||
return MatchingResult{Version: latest}, nil
|
||||
}
|
||||
if latest.Kind() != domain.PolicyKindDemo {
|
||||
return MatchingResult{}, fmt.Errorf("%s - latest version %d is %s: %w", location, latest.Version(), latest.Kind(), ErrNotDemoPolicy)
|
||||
}
|
||||
matching := domain.DemoMatchingPolicy()
|
||||
matching := section()
|
||||
current.Matching = &matching
|
||||
// The new version is built on the version that was read, so it takes the
|
||||
// next number exactly once. A taken number means the base is no longer the
|
||||
|
||||
@@ -21,8 +21,31 @@ var (
|
||||
|
||||
// ErrEmailNotVerified reports an account whose current email is not confirmed.
|
||||
ErrEmailNotVerified = errors.New("candidate profile requires a confirmed email")
|
||||
|
||||
// ErrRepositoryChecksTooSoon reports a check request inside the
|
||||
// per-candidate interval; RepositoryCheckLimitError carries the wait.
|
||||
ErrRepositoryChecksTooSoon = errors.New("repository checks were requested too recently")
|
||||
)
|
||||
|
||||
// RepositoryCheckLimitError is ErrRepositoryChecksTooSoon with the time
|
||||
// until the next request is allowed.
|
||||
type RepositoryCheckLimitError struct {
|
||||
RetryAfter time.Duration
|
||||
}
|
||||
|
||||
func (err *RepositoryCheckLimitError) Error() string { return ErrRepositoryChecksTooSoon.Error() }
|
||||
|
||||
func (err *RepositoryCheckLimitError) Unwrap() error { return ErrRepositoryChecksTooSoon }
|
||||
|
||||
// SemanticTrigger schedules the background work that a profile change needs:
|
||||
// the vector refresh of the card and the checks of linked repositories. A
|
||||
// nil trigger schedules nothing.
|
||||
type SemanticTrigger interface {
|
||||
CandidateChanged(ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, at time.Time) error
|
||||
RepositoriesChanged(ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, previous, current []domain.GitHubRepository, at time.Time) error
|
||||
RequestChecks(ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, repositories []domain.GitHubRepository, at time.Time) error
|
||||
}
|
||||
|
||||
// View is the profile as the candidate reads it: the saved document and the
|
||||
// categories that assessment results confirmed. The categories are derived by
|
||||
// the server, are read-only, and are never part of the saved document.
|
||||
@@ -31,6 +54,9 @@ type View struct {
|
||||
// ConfirmedCategories holds at most one category per specialization, in
|
||||
// catalog order.
|
||||
ConfirmedCategories []domain.CandidateAssessmentCategory
|
||||
// RepositoryChecks are the server checks of the linked repositories, by
|
||||
// repository key.
|
||||
RepositoryChecks map[string]outbound.RepositoryCheck
|
||||
}
|
||||
|
||||
// Service is stateless between calls. Profile data, its history, and onboarding
|
||||
@@ -38,8 +64,15 @@ type View struct {
|
||||
type Service struct {
|
||||
transactor outbound.Transactor
|
||||
clock func() time.Time
|
||||
semantic SemanticTrigger
|
||||
// checkInterval is the shortest time between two check requests of one
|
||||
// candidate through RequestRepositoryChecks.
|
||||
checkInterval time.Duration
|
||||
}
|
||||
|
||||
// defaultRepositoryCheckInterval applies until WithSemantic sets another.
|
||||
const defaultRepositoryCheckInterval = 10 * time.Minute
|
||||
|
||||
// NewService takes the transaction boundary and application clock. A nil
|
||||
// dependency is a wiring error and panics at construction.
|
||||
func NewService(transactor outbound.Transactor, clock func() time.Time) *Service {
|
||||
@@ -49,7 +82,16 @@ func NewService(transactor outbound.Transactor, clock func() time.Time) *Service
|
||||
if clock == nil {
|
||||
panic("profile.NewService - clock must not be nil")
|
||||
}
|
||||
return &Service{transactor: transactor, clock: clock}
|
||||
return &Service{transactor: transactor, clock: clock, checkInterval: defaultRepositoryCheckInterval}
|
||||
}
|
||||
|
||||
// WithSemantic sets the background trigger and the check request interval.
|
||||
func (service *Service) WithSemantic(trigger SemanticTrigger, checkInterval time.Duration) *Service {
|
||||
service.semantic = trigger
|
||||
if checkInterval > 0 {
|
||||
service.checkInterval = checkInterval
|
||||
}
|
||||
return service
|
||||
}
|
||||
|
||||
// GetMyProfile reads only the profile owned by userID, with the categories
|
||||
@@ -114,6 +156,9 @@ func (service *Service) SaveMyProfile(
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - save profile: %w", location, err)
|
||||
}
|
||||
if err := service.scheduleBackground(ctx, unit, userID, current, updated, at); err != nil {
|
||||
return fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
}
|
||||
if err := repository.AdvanceOnboarding(ctx, userID, at); err != nil {
|
||||
return fmt.Errorf("%s - advance onboarding: %w", location, err)
|
||||
@@ -130,6 +175,68 @@ func (service *Service) SaveMyProfile(
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// scheduleBackground schedules the card vector refresh and the checks of
|
||||
// newly linked repositories in the save transaction, so they exist exactly
|
||||
// when the change committed and the save never waits for them.
|
||||
func (service *Service) scheduleBackground(
|
||||
ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, previous, updated domain.CandidateProfile, at time.Time,
|
||||
) error {
|
||||
if service.semantic == nil {
|
||||
return nil
|
||||
}
|
||||
if err := service.semantic.RepositoriesChanged(ctx, unit, userID,
|
||||
previous.Content().ProjectRepositories(), updated.Content().ProjectRepositories(), at); err != nil {
|
||||
return fmt.Errorf("schedule repository checks: %w", err)
|
||||
}
|
||||
if err := service.semantic.CandidateChanged(ctx, unit, userID, at); err != nil {
|
||||
return fmt.Errorf("schedule vector refresh: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RequestRepositoryChecks schedules a new check of every repository that the
|
||||
// current profile links. A candidate may ask once per check interval; an
|
||||
// earlier request answers RepositoryCheckLimitError and schedules nothing.
|
||||
func (service *Service) RequestRepositoryChecks(ctx context.Context, userID uuid.UUID) (int, error) {
|
||||
const location = "Service.RequestRepositoryChecks"
|
||||
if userID == uuid.Nil {
|
||||
return 0, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile)
|
||||
}
|
||||
at := service.clock().UTC()
|
||||
var scheduled int
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireCandidate(ctx, unit, userID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
profile, err := unit.CandidateProfiles().Get(ctx, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read profile: %w", location, err)
|
||||
}
|
||||
repositories := profile.Content().ProjectRepositories()
|
||||
if len(repositories) == 0 {
|
||||
return nil
|
||||
}
|
||||
latest, err := unit.ProjectRepositories().LatestRequest(ctx, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read latest request: %w", location, err)
|
||||
}
|
||||
if next := latest.Add(service.checkInterval); !latest.IsZero() && at.Before(next) {
|
||||
return &RepositoryCheckLimitError{RetryAfter: next.Sub(at)}
|
||||
}
|
||||
if service.semantic != nil {
|
||||
if err := service.semantic.RequestChecks(ctx, unit, userID, repositories, at); err != nil {
|
||||
return fmt.Errorf("%s - schedule checks: %w", location, err)
|
||||
}
|
||||
}
|
||||
scheduled = len(repositories)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return scheduled, nil
|
||||
}
|
||||
|
||||
// readView attaches the confirmed categories of the candidate to a profile
|
||||
// that was read or written in the same transaction.
|
||||
func readView(
|
||||
@@ -143,7 +250,17 @@ func readView(
|
||||
if err != nil {
|
||||
return View{}, fmt.Errorf("%s - read confirmed categories: %w", location, err)
|
||||
}
|
||||
return View{Profile: profile, ConfirmedCategories: inCatalogOrder(categories)}, nil
|
||||
checks := make(map[string]outbound.RepositoryCheck)
|
||||
if len(profile.Content().ProjectRepositories()) > 0 {
|
||||
stored, err := unit.ProjectRepositories().List(ctx, userID)
|
||||
if err != nil {
|
||||
return View{}, fmt.Errorf("%s - read repository checks: %w", location, err)
|
||||
}
|
||||
for _, check := range stored {
|
||||
checks[check.Key] = check
|
||||
}
|
||||
}
|
||||
return View{Profile: profile, ConfirmedCategories: inCatalogOrder(categories), RepositoryChecks: checks}, nil
|
||||
}
|
||||
|
||||
// inCatalogOrder sorts the categories by their place in the catalog. A
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user