Files
lincodex/backend/internal/usecase/matching/semantic.go
T

276 lines
9.3 KiB
Go

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
}