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

307 lines
12 KiB
Go

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
}