// Package matching ranks the organization-visible candidate bank // deterministically. It filters by the current visibility rules first, scores // each candidate specialization with the versioned matching policy, and builds // the explanation from the same computed components. It reads no contact, no // raw assessment data, and no hidden minimum, and it consumes no ML result. package matching import ( "cmp" "context" "errors" "fmt" "log/slog" "slices" "strings" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) // VisibleCards returns the current organization-visible cards inside the // caller's transaction. candidateview.Service.ListVisibleCards provides it; // bootstrap passes it in so this package depends on no other usecase. type VisibleCards func( ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID, ) ([]domain.VisibleCandidateCard, error) // ViewSession charges and records the candidates that one search reveals, // inside the caller's transaction. type ViewSession interface { // Reserve counts the candidate as a distinct card view of the organization. // A candidate already viewed inside the window is allowed without another // charge. It reports false and writes nothing once the allowance is used up. Reserve(ctx context.Context, candidateID uuid.UUID) (bool, error) // Record appends the access history entry for the fields that were returned. Record(ctx context.Context, candidateID uuid.UUID, fields []domain.CardField) error } // BeginViews opens a ViewSession for an authorized actor and organization. // candidateview.Service.BeginSearchViews provides it through bootstrap. type BeginViews func(ctx context.Context, unit outbound.UnitOfWork, actorID, organizationID uuid.UUID) (ViewSession, error) // Dependencies configure the search service. type Dependencies struct { Transactor outbound.Transactor Cards VisibleCards Views BeginViews Clock func() time.Time // Logger receives the warnings of a search. A nil logger discards them. Logger *slog.Logger } // Service searches and ranks the visible bank. type Service struct { transactor outbound.Transactor cards VisibleCards views BeginViews clock func() time.Time logger *slog.Logger } func NewService(deps Dependencies) (*Service, error) { if deps.Transactor == nil || deps.Cards == nil || deps.Views == nil || deps.Clock == nil { return nil, fmt.Errorf("matching.NewService - dependencies are missing: %w", ErrServiceMissing) } logger := deps.Logger if logger == nil { logger = slog.New(slog.DiscardHandler) } return &Service{transactor: deps.Transactor, cards: deps.Cards, views: deps.Views, clock: deps.Clock, logger: logger}, nil } // Search returns the groups for one request. Everything runs in one // transaction: the owner role, the membership, and the candidate visibility are // checked and locked before any card is read, the need snapshot and the policy // are read from storage, and the permitted evidence is read through the // organization-safe projection queries, so no later read can widen what the // first one allowed. // // A search reveals card content, so it is charged like card reads. The whole // visible bank is ranked, but each group is cut to the policy's // MaxResultsPerGroup, and no total is returned. Walking the output in the // order main, near, unconfirmed, each newly revealed candidate is reserved as a // distinct card view of the organization (a candidate already viewed inside the // window costs nothing again) and recorded in the candidate's access history // with the fields actually returned, in the same transaction. When the // allowance runs out the entries already paid for are returned with Truncated // set, and nothing is written for the rest. func (service *Service) Search(ctx context.Context, request Request) (Result, error) { const location = "matching.Service.Search" if request.ActorID == uuid.Nil || request.OrganizationID == uuid.Nil { return Result{}, ErrForbidden } var result Result var err error // The visible cohort can change while it is locked. The whole search is // then repeated, a bounded number of times, and the writes of a failed // attempt roll back with it. for range maxSearchAttempts { result, err = service.searchOnce(ctx, request) if !errors.Is(err, outbound.ErrConcurrentVisibilityChange) { break } } if err != nil { return Result{}, fmt.Errorf("%s - run transaction: %w", location, err) } return result, nil } // maxSearchAttempts bounds the repeats after a concurrent visibility change. const maxSearchAttempts = 3 func (service *Service) searchOnce(ctx context.Context, request Request) (Result, error) { const location = "matching.Service.searchOnce" var result Result err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error { // The MVP milestone allows only the active owner; a membership alone // grants nothing here. The HTTP boundary checks the same rule, and the // repeat keeps the usecase closed when it is called another way. The // role is settled before the cohort is read and locked. // The reservations below take the exclusive organization lock. Taking it // first, before the share lock of the membership check, keeps two // searches of one organization from deadlocking on the upgrade, and it // serializes their charges. if err := unit.CompanyQuotas().LockOrganization(ctx, request.OrganizationID); err != nil { if errors.Is(err, outbound.ErrCompanyQuotaSnapshotChanged) { return outbound.ErrOrganizationNotFound } return fmt.Errorf("%s - lock organization: %w", location, err) } membership, err := unit.Organizations().LockActiveMembership(ctx, request.OrganizationID, request.ActorID) if err != nil { return fmt.Errorf("%s - lock active membership: %w", location, err) } if membership.Role() != domain.OrganizationRoleOwner { return ErrForbidden } cards, err := service.cards(ctx, unit, request.ActorID, request.OrganizationID) if err != nil { return err } policy, err := service.matchingPolicy(ctx, unit) if err != nil { return err } basis, err := loadBasis(ctx, unit, request) if err != nil { return err } ranked, err := service.rank(ctx, unit, request, basis, policy, cards) if err != nil { return err } result, err = service.reveal(ctx, unit, request, policy, ranked) return err }) if err != nil { return Result{}, fmt.Errorf("%s - run transaction: %w", location, err) } return result, nil } func (service *Service) matchingPolicy(ctx context.Context, unit outbound.UnitOfWork) (domain.MatchingPolicy, error) { const location = "matching.Service.matchingPolicy" version, err := unit.Policies().GetEffective(ctx, domain.ProductPolicyKey, service.clock().UTC()) if err != nil { return domain.MatchingPolicy{}, fmt.Errorf("%s - read effective product policy: %w", location, err) } policy := version.Policy().Matching if policy == nil { return domain.MatchingPolicy{}, fmt.Errorf("%s - the effective product policy has no matching section, publish it with the policy-publish command: %w", location, ErrPolicyUnavailable) } return *policy, nil } // searchBasis is what a need snapshot contributes to the search. A bank search // has an empty basis. type searchBasis struct { specialization *domain.SpecializationCode skills []requestedSkill requestedFormats []domain.QuestionnaireWorkFormat needDomainConfirmed bool } func loadBasis(ctx context.Context, unit outbound.UnitOfWork, request Request) (searchBasis, error) { const location = "matching.loadBasis" var needSkills, needDesired []domain.NeedSkill basis := searchBasis{} if request.Need != nil { need, err := unit.Needs().GetVersion(ctx, request.OrganizationID, request.Need.NeedID, request.Need.RequirementsVersion) if err != nil { if errors.Is(err, outbound.ErrNeedNotFound) { return searchBasis{}, ErrNeedNotFound } return searchBasis{}, fmt.Errorf("%s - read need snapshot: %w", location, err) } // A version that only edited a title or a suggestion is not a // requirements snapshot of its own. if need.RequirementsVersion() != request.Need.RequirementsVersion { return searchBasis{}, ErrNeedNotFound } requirements := need.Snapshot().Requirements if requirements.Specialization.Status == domain.NeedValueConfirmed && requirements.Specialization.Value != nil { specialization := *requirements.Specialization.Value basis.specialization = &specialization } if requirements.WorkFormats.Status == domain.NeedValueConfirmed && requirements.WorkFormats.Value != nil { for _, format := range *requirements.WorkFormats.Value { basis.requestedFormats = append(basis.requestedFormats, domain.QuestionnaireWorkFormat(format)) } } basis.needDomainConfirmed = requirements.Domain.Status == domain.NeedValueConfirmed needSkills, needDesired = requirements.RequiredSkills, requirements.DesiredSkills } basis.skills = requestedSkills(needSkills, needDesired, request.Filters.Stack) return basis, nil } // requestedSkills lists each distinct requested skill once. A confirmed // required skill weighs more than a desired one, a stack filter tag counts as // required, and a repeated code never counts twice, so repeating a skill in a // need cannot raise or lower a score. func requestedSkills(required, desired []domain.NeedSkill, stack []domain.CandidateViewSkillCode) []requestedSkill { var skills []requestedSkill byCode := make(map[string]int) seenUnmapped := make(map[string]struct{}) add := func(code, name string, isRequired bool) { if code == "" { key := strings.ToLower(strings.TrimSpace(name)) if _, repeated := seenUnmapped[key]; repeated { return } seenUnmapped[key] = struct{}{} skills = append(skills, requestedSkill{required: isRequired}) return } if index, repeated := byCode[code]; repeated { skills[index].required = skills[index].required || isRequired return } byCode[code] = len(skills) skills = append(skills, requestedSkill{code: code, required: isRequired}) } for _, group := range []struct { skills []domain.NeedSkill isRequired bool }{{required, true}, {desired, false}} { for _, skill := range group.skills { if skill.Status != domain.NeedItemConfirmed { continue } code := "" if skill.TaxonomyCode != nil { code = *skill.TaxonomyCode } add(code, skill.Name, group.isRequired) } } for _, tag := range stack { add(string(tag), "", true) } return skills } // candidateEntry is one candidate specialization before scoring. type candidateEntry struct { candidateID uuid.UUID card domain.AnonymousCandidateViewDTO specialization domain.SpecializationCode category *domain.CandidateViewCategory declaredGrade *domain.GradeCode } // entriesOf derives the specializations that a card shows. A specialization is // confirmed only when the card shows its category; one specialization never // confirms another. A specialization that the self-assessment marks confirmed // but whose category the card does not show is left out: a result cannot // claim a confirmation that the candidate did not publish. func entriesOf(visible domain.VisibleCandidateCard) []candidateEntry { card := visible.Card declared := make(map[domain.SpecializationCode]*domain.GradeCode, len(card.SelfAssessment)) for _, assessment := range card.SelfAssessment { declared[assessment.Specialization] = assessment.DeclaredGrade } entries := make([]candidateEntry, 0, len(card.Categories)+len(card.SelfAssessment)) confirmed := make(map[domain.SpecializationCode]struct{}, len(card.Categories)) for index := range card.Categories { category := card.Categories[index] confirmed[category.Specialization] = struct{}{} entries = append(entries, candidateEntry{ candidateID: visible.CandidateID, card: card, specialization: category.Specialization, category: &category, declaredGrade: declared[category.Specialization], }) } for _, assessment := range card.SelfAssessment { if _, isConfirmed := confirmed[assessment.Specialization]; isConfirmed || assessment.ConfirmationStatus != domain.CandidateViewConfirmationUnconfirmed { continue } entries = append(entries, candidateEntry{ candidateID: visible.CandidateID, card: card, specialization: assessment.Specialization, declaredGrade: assessment.DeclaredGrade, }) } return entries } // rankedEntry carries the sort keys next to the entry that leaves. type rankedEntry struct { entry Entry candidate uuid.UUID fit int64 coverage int64 rank int64 near bool } // groups holds the ranked entries of the three groups before the output is cut. type groups struct { main, near, unconfirmed []rankedEntry } func (service *Service) rank( ctx context.Context, unit outbound.UnitOfWork, request Request, basis searchBasis, policy domain.MatchingPolicy, cards []domain.VisibleCandidateCard, ) (groups, error) { specialization, compatible := effectiveSpecialization(request.Filters.Specialization, basis.specialization) if !compatible { return groups{}, nil } requestedFormats := basis.requestedFormats if conditions := request.Filters.Conditions; conditions != nil && len(conditions.WorkFormats) > 0 { requestedFormats = conditions.WorkFormats } var accepted []candidateEntry for _, visible := range cards { for _, entry := range entriesOf(visible) { if request.Filters.accepts(entry, specialization) { accepted = append(accepted, entry) } } } reachedCohorts, err := service.reachedPercentileCohorts(ctx, unit, policy, accepted) if err != nil { return groups{}, err } facts, err := service.permittedFacts(ctx, unit, request, basis, accepted) if err != nil { return groups{}, err } var result groups for _, entry := range accepted { ranked := scoreEntry(entry, policy, basis, requestedFormats, facts[entry.candidateID], reachedCohorts) switch { case entry.category == nil: result.unconfirmed = append(result.unconfirmed, ranked) case ranked.near: result.near = append(result.near, ranked) default: result.main = append(result.main, ranked) } } slices.SortStableFunc(result.main, compareByRank) slices.SortStableFunc(result.near, compareByRank) slices.SortStableFunc(result.unconfirmed, compareByFit) return result, nil } // reachedPercentileCohorts returns the categories among the accepted entries // whose comparable real cohort has reached the policy minimum. The cohort of a // category is the number of candidates who hold it from a source that is not a // synthetic demonstration; only the categories of the accepted entries are // counted. A percentile would need the theta of those members, which the // organization-safe projection does not carry, so T stays the neutral value and // the percentile stays null, but the reason is then "not computed" instead of // "cohort below the minimum". The search never fails for it and logs one // warning for each such category. func (service *Service) reachedPercentileCohorts( ctx context.Context, unit outbound.UnitOfWork, policy domain.MatchingPolicy, accepted []candidateEntry, ) (map[outbound.CategoryKey]bool, error) { seen := make(map[outbound.CategoryKey]struct{}) var categories []outbound.CategoryKey for _, entry := range accepted { if entry.category == nil { continue } key := outbound.CategoryKey{Specialization: entry.category.Specialization, Grade: entry.category.Grade} if _, repeated := seen[key]; !repeated { seen[key] = struct{}{} categories = append(categories, key) } } counts, err := unit.Evidence().CountComparableRealCategories(ctx, categories) if err != nil { return nil, fmt.Errorf("matching.Service.reachedPercentileCohorts - count real cohorts: %w", err) } reached := make(map[outbound.CategoryKey]bool) for _, key := range categories { if counts[key] >= int64(policy.PercentileMinCohort) { reached[key] = true service.logger.WarnContext(ctx, "the real cohort of a category reached the percentile minimum, but the percentile is not computed", slog.String("specialization", string(key.Specialization)), slog.String("grade", string(key.Grade)), slog.Int64("cohort_size", counts[key]), slog.Int("minimum", int(policy.PercentileMinCohort)), ) } } return reached, nil } // permittedFacts reads the permitted evidence of every candidate with a // confirmed entry in one statement, and only when the request names skills. func (service *Service) permittedFacts( ctx context.Context, unit outbound.UnitOfWork, request Request, basis searchBasis, accepted []candidateEntry, ) (map[uuid.UUID][]evidenceSource, error) { sources := make(map[uuid.UUID][]evidenceSource) if len(basis.skills) == 0 { return sources, nil } seen := make(map[uuid.UUID]struct{}) var requests []outbound.EvidenceCandidateCategories for _, entry := range accepted { if _, repeated := seen[entry.candidateID]; repeated || entry.category == nil { continue } seen[entry.candidateID] = struct{}{} requests = append(requests, outbound.EvidenceCandidateCategories{CandidateID: entry.candidateID, Categories: entry.card.Categories}) } facts, err := unit.Evidence().ListOrganizationFactsBatch(ctx, request.OrganizationID, requests) if err != nil { return nil, fmt.Errorf("matching.Service.permittedFacts - read permitted evidence: %w", err) } for candidateID, candidateFacts := range facts { sources[candidateID] = factSources(candidateFacts) } return sources, nil } // reveal cuts each group to the policy bound and charges the output in order. func (service *Service) reveal( ctx context.Context, unit outbound.UnitOfWork, request Request, policy domain.MatchingPolicy, 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 } } views, err := service.views(ctx, unit, request.ActorID, request.OrganizationID) if err != nil { return Result{}, fmt.Errorf("matching.Service.reveal - open card views: %w", err) } revealed := make(map[uuid.UUID]map[domain.CardField]struct{}) var order []uuid.UUID charge := func(entries []rankedEntry) ([]Entry, bool, error) { kept := make([]Entry, 0, len(entries)) for _, item := range entries { if _, paid := revealed[item.candidate]; !paid { allowed, err := views.Reserve(ctx, item.candidate) if err != nil { return nil, false, fmt.Errorf("matching.Service.reveal - reserve card view: %w", err) } if !allowed { return kept, false, nil } revealed[item.candidate] = make(map[domain.CardField]struct{}) order = append(order, item.candidate) } for _, field := range entryFields(item.entry) { revealed[item.candidate][field] = struct{}{} } kept = append(kept, item.entry) } return kept, true, nil } complete := true for _, step := range []struct { entries []rankedEntry target *[]Entry }{{ranked.main, &result.Main}, {ranked.near, &result.Near}, {ranked.unconfirmed, &result.Unconfirmed}} { if !complete { break } kept, ok, err := charge(step.entries) if err != nil { return Result{}, err } *step.target, complete = kept, ok } if !complete { result.Truncated = true } for _, candidateID := range order { if err := views.Record(ctx, candidateID, orderedFields(revealed[candidateID])); err != nil { return Result{}, fmt.Errorf("matching.Service.reveal - record card view: %w", err) } } return result, nil } // 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 { var fields []domain.CardField if entry.Category != nil { fields = append(fields, domain.CardFieldCategories) } if len(entry.PublicContext.Stack) > 0 { fields = append(fields, domain.CardFieldStack) } if entry.PublicContext.ExperienceBand != nil { fields = append(fields, domain.CardFieldExperience) } // An unconfirmed entry exists only because the self-assessment is published. if entry.Category == nil || entry.DeclaredGrade != nil { fields = append(fields, domain.CardFieldSelfAssessment) } if len(entry.PublicContext.WorkFormats) > 0 { fields = append(fields, domain.CardFieldWorkFormats) } if entry.PublicContext.SalaryCompatibility != nil { fields = append(fields, domain.CardFieldSalaryCompatibility) } return fields } func orderedFields(set map[domain.CardField]struct{}) []domain.CardField { fields := make([]domain.CardField, 0, len(set)) for _, field := range []domain.CardField{ domain.CardFieldCategories, domain.CardFieldStack, domain.CardFieldExperience, domain.CardFieldSelfAssessment, domain.CardFieldWorkFormats, domain.CardFieldSalaryCompatibility, } { if _, shown := set[field]; shown { fields = append(fields, field) } } return fields } // effectiveSpecialization combines the filter with the specialization of the // need. Two different specializations leave nothing to show. func effectiveSpecialization(filter, need *domain.SpecializationCode) (*domain.SpecializationCode, bool) { switch { case filter != nil && need != nil && *filter != *need: return nil, false case filter != nil: return filter, true default: return need, true } } // factSources turns the permitted assessment facts into evidence. Each fact is // the one measurement that supports a confirmed category, tagged with that // category's specialization. func factSources(facts []domain.EvidenceOrganizationFact) []evidenceSource { sources := make([]evidenceSource, 0, len(facts)) for _, fact := range facts { input := fact.Input() sources = append(sources, evidenceSource{ code: string(input.Skill), trust: input.Trust, attribution: domain.EvidenceAttributionPersonal, measured: true, }) } return sources } func scoreEntry( entry candidateEntry, policy domain.MatchingPolicy, basis searchBasis, requestedFormats []domain.QuestionnaireWorkFormat, facts []evidenceSource, reachedCohorts map[outbound.CategoryKey]bool, ) rankedEntry { evidence := make([]evidenceSource, 0, len(entry.card.Skills)+len(facts)) for _, skill := range entry.card.Skills { evidence = append(evidence, evidenceSource{code: string(skill), trust: domain.EvidenceTrustStated, attribution: domain.EvidenceAttributionPersonal}) } confirmed := entry.category != nil if confirmed { for _, fact := range facts { // A fact supports only its own specialization's category. if fact.code == string(entry.specialization) { evidence = append(evidence, fact) } } } computed := computeScores(scoreInput{confirmed: confirmed, policy: policy, skills: basis.skills, evidence: evidence}) context := PublicContext{ ExperienceBand: entry.card.ExperienceBand, SalaryCompatibility: entry.card.SalaryCompatibility, } if len(entry.card.Skills) > 0 { context.Stack = slices.Clone(entry.card.Skills) } if len(entry.card.WorkFormats) > 0 { context.WorkFormats = slices.Clone(entry.card.WorkFormats) } summary, flags := explain(explanationInput{ confirmed: confirmed, declaredGrade: entry.declaredGrade, policy: policy, scores: computed, context: context, requestedFormats: requestedFormats, needDomainConfirmed: basis.needDomainConfirmed, percentileReason: percentileReason(entry, reachedCohorts), }) components := Components{Fit: microToFloat(computed.fit), Coverage: microToFloat(computed.coverage)} if confirmed { components.Domain = microToFloat(computed.domain) components.Semantics = microToFloat(computed.semantics) components.Competition = microToFloat(computed.competition) components.Freshness = microToFloat(computed.freshness) components.Responsiveness = microToFloat(computed.responsive) components.RankScore = microToFloat(computed.rank) } return rankedEntry{ entry: Entry{ CandidateHandle: entry.card.Pseudonym, Specialization: entry.specialization, 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, near: confirmed && computed.belongsToNearGroup(policy), } } // compareByRank orders a confirmed group: S descending, then coverage // descending, then the internal identifier ascending. The identifier is the // stable tie-breaker and never leaves the server; the specialization only // separates two entries of the same candidate. func compareByRank(left, right rankedEntry) int { return cmp.Or( cmp.Compare(right.rank, left.rank), cmp.Compare(right.coverage, left.coverage), slices.Compare(left.candidate[:], right.candidate[:]), strings.Compare(string(left.entry.Specialization), string(right.entry.Specialization)), ) } // compareByFit orders the unconfirmed group: Fit descending, then coverage // descending, then the internal identifier ascending. It never uses a // confirmed-profile score. func compareByFit(left, right rankedEntry) int { return cmp.Or( cmp.Compare(right.fit, left.fit), cmp.Compare(right.coverage, left.coverage), slices.Compare(left.candidate[:], right.candidate[:]), strings.Compare(string(left.entry.Specialization), string(right.entry.Specialization)), ) } // sourceOf echoes the search basis. A bank search carries its normalized // filters, so the result stays tied to what was asked. func sourceOf(request Request) Source { if request.Need != nil { need := *request.Need return Source{Need: &need} } filters := request.Filters filters.Stack = slices.Clone(filters.Stack) slices.Sort(filters.Stack) if conditions := filters.Conditions; conditions != nil { normalized := *conditions normalized.WorkFormats = slices.Clone(conditions.WorkFormats) slices.Sort(normalized.WorkFormats) filters.Conditions = &normalized } return Source{Filters: filters} } // percentileReason says why the percentile of a confirmed entry is null. func percentileReason(entry candidateEntry, reachedCohorts map[outbound.CategoryKey]bool) UnknownReason { if entry.category != nil && reachedCohorts[outbound.CategoryKey{Specialization: entry.category.Specialization, Grade: entry.category.Grade}] { return ReasonPercentileNotComputed } return ReasonCohortBelow30 }