Files

243 lines
10 KiB
Go

package domain
import (
"encoding/json"
"errors"
"math"
"slices"
"strings"
"testing"
"github.com/google/uuid"
)
func TestNeedSemanticDocumentMirrorsTheResearchViewWithConfirmedValuesOnly(t *testing.T) {
grade, domainText, source := GradeJunior, " e-commerce,\n catalog ", "Vacancy:\n\tbuild the catalog"
confirmed := NeedValueSource{Origin: NeedValueManual}
snapshot := NeedSnapshot{
ID: uuid.New(), Title: "Junior backend developer", SourceText: &source,
Requirements: NeedRequirements{
Grade: NeedValue[GradeCode]{Status: NeedValueConfirmed, Value: &grade},
Domain: NeedValue[string]{Status: NeedValueConfirmed, Value: &domainText},
RequiredSkills: []NeedSkill{
{Name: "Python", Status: NeedItemConfirmed, Source: confirmed},
{Name: "Secret suggestion", Status: NeedItemExtracted, Source: confirmed},
},
DesiredSkills: []NeedSkill{{Name: "FastAPI", Status: NeedItemConfirmed, Source: confirmed}},
Tasks: []NeedTask{{Text: "build card endpoints", Status: NeedItemConfirmed, Source: confirmed}},
},
}
document := NewNeedSemanticDocument(snapshot)
want := "Title: Junior backend developer\nGrade: junior\nDomain: e-commerce, catalog\nRequired skills: Python\n" +
"Desired skills: FastAPI\nTasks:\n- build card endpoints\nDescription: Vacancy: build the catalog"
if document.Whole.Text != want {
t.Fatalf("need view =\n%q\nwant\n%q", document.Whole.Text, want)
}
keys := make([]string, 0, len(document.Items))
for _, item := range document.Items {
keys = append(keys, item.Key+"="+item.Label)
}
if got := strings.Join(keys, ","); got != "required_skill:0=Python,desired_skill:0=FastAPI,task:0=build card endpoints" {
t.Fatalf("items = %s", got)
}
if NewNeedSemanticDocument(snapshot).Whole.ContentDigest() != document.Whole.ContentDigest() {
t.Fatal("the same snapshot renders a different digest")
}
}
func TestCandidateSemanticDocumentReadsOnlyTheCard(t *testing.T) {
declared := GradeMiddle
description := "Idempotent receiver"
card := AnonymousCandidateViewDTO{
Skills: []CandidateViewSkillCode{CandidateViewSkillKafka, CandidateViewSkillGo},
Categories: []CandidateViewCategory{{Specialization: SpecializationBackend, Grade: GradeJunior}},
SelfAssessment: []CandidateViewSelfAssessment{{Specialization: SpecializationDSML, DeclaredGrade: &declared}},
Projects: []CandidateViewProject{
{Title: "Ledger", Description: &description, Stack: []string{"Go"}, RepositoryVerified: true},
{Title: "Unverified", Stack: []string{}},
},
}
evidence := map[int]RepositoryEvidence{
0: {Description: "Payments ledger", Topics: []string{"payments"}, Languages: []string{"Go"}, ReadmeExcerpt: strings.Repeat("r", 700)},
1: {Description: "must not be used: the card does not mark it verified"},
}
document := NewCandidateSemanticDocument(card, evidence)
lines := strings.Split(document.Whole.Text, "\n")
if lines[0] != "Roles: backend (junior); ds_ml (middle)" || lines[1] != "Stack: go, kafka" || lines[2] != "Projects:" {
t.Fatalf("card view = %q", document.Whole.Text)
}
if !strings.HasPrefix(lines[3], "- Ledger: Idempotent receiver; Stack: Go; Repository: Payments ledger; Topics: payments; Languages: Go; README: ") ||
strings.Count(lines[3], "r") > maxReadmeRunesInView+20 {
t.Fatalf("project line = %q", lines[3])
}
if strings.Contains(document.Whole.Text, "must not be used") {
t.Fatal("evidence of an unverified project entered the view")
}
var projectKeys []string
for _, item := range document.Items {
if item.Kind == SemanticItemProject {
projectKeys = append(projectKeys, item.Key+"="+item.Label)
}
}
if strings.Join(projectKeys, ",") != "project:0=Ledger,project:1=Unverified" {
t.Fatalf("project items = %v", projectKeys)
}
if !NewCandidateSemanticDocument(AnonymousCandidateViewDTO{}, nil).IsEmpty() {
t.Fatal("an empty card renders text")
}
}
func TestSemanticVectorsEncodeExactlyAndRejectInvalidValues(t *testing.T) {
values := []float32{0.6, -0.8, 0}
vector, err := NewSemanticVector(values)
if err != nil {
t.Fatalf("NewSemanticVector() error = %v", err)
}
decoded, err := DecodeSemanticVector(vector.Encode(), 3)
if err != nil || len(decoded) != 3 || decoded[0] != 0.6 || decoded[1] != -0.8 {
t.Fatalf("round trip = %v, %v", decoded, err)
}
if cosine, ok := vector.Cosine(decoded); !ok || math.Abs(cosine-1) > 1e-6 {
t.Fatalf("Cosine(self) = %v", cosine)
}
if _, ok := vector.Cosine(SemanticVector{1}); ok {
t.Fatal("vectors of different dimensions were compared")
}
for _, invalid := range [][]float32{{}, {2, 0}, {float32(math.NaN()), 1}} {
if _, err := NewSemanticVector(invalid); !errors.Is(err, ErrInvalidSemanticVector) {
t.Errorf("NewSemanticVector(%v) accepted an invalid vector", invalid)
}
}
if _, err := DecodeSemanticVector([]byte{1, 2, 3}, 1); !errors.Is(err, ErrInvalidSemanticVector) {
t.Fatal("a stored vector of the wrong length was accepted")
}
}
func TestSemanticFusedScoreStandardizesAndNeedsEveryMember(t *testing.T) {
single := DemoMatchingSemanticsPolicy()
if score, ok := single.FusedScore([]float64{0.42}); !ok || score != 0.42 {
t.Fatalf("single-member score = %v, %v, want the cosine itself", score, ok)
}
ensemble := single.Clone()
ensemble.Members[0].Weight, ensemble.Members[0].Mean, ensemble.Members[0].StandardDeviation = 4000, 3000, 1000
ensemble.Members = append(ensemble.Members, MatchingSemanticMember{
Model: SemanticModel{ID: "Qwen/Qwen3-Embedding-0.6B", Revision: "97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3", PromptVersion: "qwen3-v1"},
Weight: 6000, Mean: 5000, StandardDeviation: 500,
})
if err := ensemble.validateMembers(); err != nil {
t.Fatalf("ensemble members invalid: %v", err)
}
// 0.4 * (0.5 - 0.3) / 0.1 + 0.6 * (0.55 - 0.5) / 0.05 = 0.8 + 0.6.
if score, ok := ensemble.FusedScore([]float64{0.5, 0.55}); !ok || math.Abs(score-1.4) > 1e-12 {
t.Fatalf("ensemble score = %v, %v, want 1.4", score, ok)
}
if _, ok := ensemble.FusedScore([]float64{0.5}); ok {
t.Fatal("a score was fused without every member")
}
if ensemble.ExplanationModel() != single.Members[0].Model {
t.Fatal("the first member must explain entries")
}
ensemble.Members[0].Model = ensemble.Members[1].Model
if err := ensemble.validateMembers(); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("a repeated member was accepted: %v", err)
}
}
func TestSemanticCalibrationInterpolatesClipsAndKeepsSteps(t *testing.T) {
policy := MatchingSemanticsPolicy{Calibration: []MatchingCalibrationPoint{
{Score: 2000, Probability: 0}, {Score: 3000, Probability: 0}, {Score: 3000, Probability: 4000}, {Score: 5000, Probability: 8000},
}}
for _, test := range []struct {
cosine float64
want int64
}{
{-0.5, 0}, {0.25, 0}, {0.3, 400_000}, {0.4, 600_000}, {0.5, 800_000}, {0.9, 800_000},
} {
if got := policy.Probability(test.cosine); got != test.want {
t.Errorf("Probability(%v) = %d, want %d", test.cosine, got, test.want)
}
}
demo := DemoMatchingSemanticsPolicy()
if err := demo.Validate(); err != nil {
t.Fatalf("demo semantics invalid: %v", err)
}
previous := int64(-1)
for cosine := 0.0; cosine <= 1.0; cosine += 0.01 {
value := demo.Probability(cosine)
if value < previous || value < 0 || value > 1_000_000 {
t.Fatalf("Probability is not monotone in [0,1] at %v: %d after %d", cosine, value, previous)
}
previous = value
}
if band := demo.ItemBand(true, 0.45); band != SemanticSimilarityHigh {
t.Fatalf("task band at 0.45 = %q", band)
}
if band := demo.ItemBand(false, 0.40); band != SemanticSimilarityMedium {
t.Fatalf("skill band at 0.40 = %q", band)
}
if band := demo.ItemBand(false, 0.30); band != "" {
t.Fatalf("skill band at 0.30 = %q, want none", band)
}
}
func TestSemanticPolicyValidationAndDocumentRoundTrip(t *testing.T) {
for name, edit := range map[string]func(*MatchingSemanticsPolicy){
"decreasing calibration": func(policy *MatchingSemanticsPolicy) {
policy.Calibration = []MatchingCalibrationPoint{{Score: 1000, Probability: 5000}, {Score: 2000, Probability: 4000}}
},
"one point": func(policy *MatchingSemanticsPolicy) { policy.Calibration = policy.Calibration[:1] },
"high below mid": func(policy *MatchingSemanticsPolicy) { policy.SkillHigh = policy.SkillMedium - 1 },
"no source": func(policy *MatchingSemanticsPolicy) { policy.Source = "" },
"bad model": func(policy *MatchingSemanticsPolicy) { policy.Members[0].Model.Revision = "main branch" },
"no members": func(policy *MatchingSemanticsPolicy) { policy.Members = nil },
"weights short": func(policy *MatchingSemanticsPolicy) { policy.Members[0].Weight = 9999 },
"zero deviation": func(policy *MatchingSemanticsPolicy) { policy.Members[0].StandardDeviation = 0 },
"repeated model": func(policy *MatchingSemanticsPolicy) {
policy.Members[0].Weight = 5000
policy.Members = append(policy.Members, policy.Members[0])
},
"evidence limit": func(policy *MatchingSemanticsPolicy) { policy.MaxEvidencePerEntry = 13 },
} {
semantics := DemoMatchingSemanticsPolicy()
edit(&semantics)
if err := semantics.Validate(); !errors.Is(err, ErrInvalidPolicy) {
t.Errorf("%s: Validate() = %v, want ErrInvalidPolicy", name, err)
}
}
v5 := DemoProductPolicyV5()
if v5.Matching.FitSemanticsWeight != 5000 || v5.Matching.FitCoverageWeight+v5.Matching.FitDomainWeight+v5.Matching.FitSemanticsWeight != basisPointsPerUnit {
t.Fatalf("V5 weights = %+v", v5.Matching)
}
if v4 := DemoProductPolicyV4(); v4.Matching.FitSemanticsWeight != 1000 || v4.Matching.Semantics != nil {
t.Fatal("V4 must stay the PRD point without a semantic section")
}
encoded, _, err := encodeProductPolicy(v5)
if err != nil {
t.Fatalf("encodeProductPolicy(V5) error = %v", err)
}
decoded, err := decodeProductPolicy(encoded)
if err != nil {
t.Fatalf("decodeProductPolicy(V5) error = %v", err)
}
if decoded.Matching == nil || decoded.Matching.Semantics == nil ||
len(decoded.Matching.Semantics.Calibration) != len(v5.Matching.Semantics.Calibration) ||
!slices.Equal(decoded.Matching.Semantics.Members, v5.Matching.Semantics.Members) {
t.Fatal("the semantic section did not survive the document round trip")
}
var document map[string]any
if err := json.Unmarshal(encoded, &document); err != nil {
t.Fatalf("decode document: %v", err)
}
matching := document["matching"].(map[string]any)
semantics := matching["semantics"].(map[string]any)
delete(semantics, "source")
broken, _ := json.Marshal(document)
if _, err := decodeProductPolicy(broken); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("a semantic section without a source decoded: %v", err)
}
if err := v5.Validate(); err != nil {
t.Fatalf("V5 Validate() = %v", err)
}
}