feat(matching): rank with semantic embeddings and explain matches by evidence
This commit is contained in:
1 parent
facc1789b1
commit
24b64d698a
215 files changed
+16951
-327
No files matched your search
@@ -0,0 +1,159 @@
|
||||
package semantic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"regexp"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/port/inbound"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var repositoryDigestPattern = regexp.MustCompile(`^[0-9a-f]{16}$`)
|
||||
|
||||
// RepositoryCheckJob checks one linked repository on the public GitHub API
|
||||
// and stores the result. It implements the handler of RepositoryCheckJobKind.
|
||||
type RepositoryCheckJob struct {
|
||||
fetcher outbound.RepositoryMetadataFetcher
|
||||
trigger *Trigger
|
||||
clock func() time.Time
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
// NewRepositoryCheckJob returns the handler. trigger schedules the vector
|
||||
// refresh after a check changed what the card text contains.
|
||||
func NewRepositoryCheckJob(
|
||||
fetcher outbound.RepositoryMetadataFetcher, trigger *Trigger, clock func() time.Time, logger *slog.Logger,
|
||||
) (*RepositoryCheckJob, error) {
|
||||
if fetcher == nil || clock == nil {
|
||||
return nil, errors.New("semantic.NewRepositoryCheckJob - fetcher and clock must be set")
|
||||
}
|
||||
if logger == nil {
|
||||
logger = slog.New(slog.DiscardHandler)
|
||||
}
|
||||
return &RepositoryCheckJob{fetcher: fetcher, trigger: trigger, clock: clock, logger: logger}, nil
|
||||
}
|
||||
|
||||
// JobKind is the stable kind name.
|
||||
func (*RepositoryCheckJob) JobKind() string { return RepositoryCheckJobKind }
|
||||
|
||||
// Handle fetches the repository that the payload digest names among the
|
||||
// candidate's current projects. A repository that is no longer linked is
|
||||
// skipped. A GitHub rate limit stores the state unavailable and reschedules
|
||||
// the check after the limit resets; a network or server failure is retried
|
||||
// by the worker. The log names the job and the outcome, never the repository.
|
||||
func (job *RepositoryCheckJob) Handle(ctx context.Context, unit outbound.UnitOfWork, claimed outbound.ClaimedJob) error {
|
||||
const location = "semantic.RepositoryCheckJob.Handle"
|
||||
candidateID, digest, err := repositoryPayload(claimed.Payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
profile, err := unit.CandidateProfiles().Get(ctx, candidateID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read profile: %w", location, err)
|
||||
}
|
||||
repository, linked := linkedRepository(profile.Content(), digest)
|
||||
if !linked {
|
||||
return nil
|
||||
}
|
||||
store := unit.ProjectRepositories()
|
||||
previous, found, err := store.GetForUpdate(ctx, candidateID, repository.Key())
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - lock check: %w", location, err)
|
||||
}
|
||||
now := job.clock().UTC()
|
||||
if !found {
|
||||
if err := store.Request(ctx, candidateID, repository.Key(), now); err != nil {
|
||||
return fmt.Errorf("%s - create check: %w", location, err)
|
||||
}
|
||||
previous = outbound.RepositoryCheck{Key: repository.Key(), State: outbound.RepositoryCheckPending}
|
||||
}
|
||||
fetched, err := job.fetcher.Fetch(ctx, repository, previous)
|
||||
next, retryAfter, err := checkResult(previous, fetched, err, now)
|
||||
if err != nil {
|
||||
job.logger.WarnContext(ctx, "repository check failed and will be retried",
|
||||
slog.Int64("job_id", claimed.ID), slog.Int("attempt", claimed.Attempt))
|
||||
return fmt.Errorf("%s - fetch repository: %w", location, err)
|
||||
}
|
||||
if err := store.Save(ctx, candidateID, next); err != nil {
|
||||
return fmt.Errorf("%s - store check: %w", location, err)
|
||||
}
|
||||
job.logger.InfoContext(ctx, "repository check finished",
|
||||
slog.Int64("job_id", claimed.ID), slog.String("state", string(next.State)), slog.String("failure", string(next.Failure)))
|
||||
if retryAfter > 0 {
|
||||
if err := scheduleRepositoryCheck(ctx, unit, candidateID, repository.Key(), now.Add(retryAfter)); err != nil {
|
||||
return fmt.Errorf("%s - reschedule after the rate limit: %w", location, err)
|
||||
}
|
||||
}
|
||||
if evidenceChanged(previous, next) {
|
||||
if err := job.trigger.CandidateChanged(ctx, unit, candidateID, now); err != nil {
|
||||
return fmt.Errorf("%s - schedule vector refresh: %w", location, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// repositoryPayload reads the candidate and the repository digest; a payload
|
||||
// that names neither can never run, so it is final.
|
||||
func repositoryPayload(payload json.RawMessage) (uuid.UUID, string, error) {
|
||||
var fields struct {
|
||||
CandidateID string `json:"candidate_id"`
|
||||
Repository string `json:"repository"`
|
||||
}
|
||||
if err := json.Unmarshal(payload, &fields); err != nil {
|
||||
return uuid.Nil, "", fmt.Errorf("decode payload: %w", inbound.ErrJobRejected)
|
||||
}
|
||||
candidateID, err := uuid.Parse(fields.CandidateID)
|
||||
if err != nil || candidateID == uuid.Nil || !repositoryDigestPattern.MatchString(fields.Repository) {
|
||||
return uuid.Nil, "", fmt.Errorf("payload names no repository: %w", inbound.ErrJobRejected)
|
||||
}
|
||||
return candidateID, fields.Repository, nil
|
||||
}
|
||||
|
||||
// checkResult turns a fetch into the stored check. It returns a wait for a
|
||||
// rate limit and an error for a failure the worker should retry.
|
||||
func checkResult(previous outbound.RepositoryCheck, fetched outbound.RepositoryFetch, err error, now time.Time) (outbound.RepositoryCheck, time.Duration, error) {
|
||||
next := outbound.RepositoryCheck{Key: previous.Key, RequestedAt: previous.RequestedAt, CheckedAt: now}
|
||||
var fetchError *outbound.RepositoryFetchError
|
||||
switch {
|
||||
case errors.As(err, &fetchError) && fetchError.Class == outbound.RepositoryFailureRateLimited:
|
||||
next.State, next.Failure = outbound.RepositoryCheckUnavailable, outbound.RepositoryFailureRateLimited
|
||||
return next, fetchError.RetryAfter, nil
|
||||
case errors.As(err, &fetchError) && fetchError.Class == outbound.RepositoryFailureInvalidResponse:
|
||||
next.State, next.Failure = outbound.RepositoryCheckUnavailable, outbound.RepositoryFailureInvalidResponse
|
||||
return next, 0, nil
|
||||
case err != nil:
|
||||
return outbound.RepositoryCheck{}, 0, err
|
||||
case !fetched.Found:
|
||||
next.State = outbound.RepositoryCheckNotFound
|
||||
default:
|
||||
next.State = outbound.RepositoryCheckVerified
|
||||
next.GitHubID, next.Evidence = fetched.GitHubID, fetched.Evidence
|
||||
next.RepositoryETag, next.ReadmeETag = fetched.RepositoryETag, fetched.ReadmeETag
|
||||
}
|
||||
return next, 0, nil
|
||||
}
|
||||
|
||||
// evidenceChanged reports whether the card text can change: the verified
|
||||
// state or the fetched metadata moved.
|
||||
func evidenceChanged(previous, next outbound.RepositoryCheck) bool {
|
||||
wasVerified := previous.State == outbound.RepositoryCheckVerified
|
||||
isVerified := next.State == outbound.RepositoryCheckVerified
|
||||
if wasVerified != isVerified {
|
||||
return true
|
||||
}
|
||||
if !isVerified {
|
||||
return false
|
||||
}
|
||||
return previous.Evidence.Description != next.Evidence.Description ||
|
||||
previous.Evidence.ReadmeExcerpt != next.Evidence.ReadmeExcerpt ||
|
||||
!slices.Equal(previous.Evidence.Topics, next.Evidence.Topics) ||
|
||||
!slices.Equal(previous.Evidence.Languages, next.Evidence.Languages)
|
||||
}
|
||||
Reference in new issue
Block a user