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

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

No files matched your search

+5 -1
View File
@@ -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)
}
+9 -2
View File
@@ -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 {
+58 -17
View File
@@ -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")
}
}
+20 -2
View File
@@ -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