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
@@ -1,5 +1,6 @@
|
||||
// Package policypublish implements the local operator command that adds the
|
||||
// demo matching section to the product policy. Until an administrative policy
|
||||
// demo matching section, or the semantic matching section, to the product
|
||||
// policy. Until an administrative policy
|
||||
// editor exists, this is how a stand gets the coefficients that the match
|
||||
// search needs: startup seeds only the first demo version.
|
||||
package policypublish
|
||||
@@ -20,24 +21,38 @@ import (
|
||||
"lincodex/backend/internal/usecase/policy"
|
||||
)
|
||||
|
||||
const usage = "usage: policy-publish matching --actor operator:<handle>"
|
||||
const usage = "usage: policy-publish matching|semantic --actor operator:<handle>"
|
||||
|
||||
// Track names which section a command publishes.
|
||||
type Track string
|
||||
|
||||
const (
|
||||
// TrackMatching adds the PRD matching section (Sem weight 0.10).
|
||||
TrackMatching Track = "matching"
|
||||
// TrackSemantic adds the semantic matching section (Sem weight 0.5, the
|
||||
// encoder identity, the calibration, and the explanation thresholds).
|
||||
TrackSemantic Track = "semantic"
|
||||
)
|
||||
|
||||
// Command is a parsed, validated request.
|
||||
type Command struct {
|
||||
Track Track
|
||||
Author domain.PolicyAuthor
|
||||
}
|
||||
|
||||
// Extender publishes the demo matching section.
|
||||
type Extender interface {
|
||||
EnsureDemoMatchingSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error)
|
||||
EnsureDemoSemanticMatchingSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error)
|
||||
}
|
||||
|
||||
// Parse validates every argument before Run reads configuration or connects.
|
||||
func Parse(args []string) (Command, error) {
|
||||
if len(args) == 0 || args[0] != "matching" {
|
||||
if len(args) == 0 || (args[0] != string(TrackMatching) && args[0] != string(TrackSemantic)) {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
flags := flag.NewFlagSet("policy-publish matching", flag.ContinueOnError)
|
||||
track := Track(args[0])
|
||||
flags := flag.NewFlagSet("policy-publish "+args[0], flag.ContinueOnError)
|
||||
flags.SetOutput(io.Discard)
|
||||
actor := flags.String("actor", "", "operator handle")
|
||||
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 {
|
||||
@@ -48,7 +63,7 @@ func Parse(args []string) (Command, error) {
|
||||
if err != nil || !strings.HasPrefix(value, "operator:") {
|
||||
return Command{}, errors.New("actor must be operator:<handle>")
|
||||
}
|
||||
return Command{Author: author}, nil
|
||||
return Command{Track: track, Author: author}, nil
|
||||
}
|
||||
|
||||
// Run parses the command, loads only DATABASE_URL from the supplied
|
||||
@@ -81,7 +96,14 @@ func Execute(ctx context.Context, command Command, extender Extender, output io.
|
||||
if extender == nil || output == nil {
|
||||
return errors.New("policy publication command dependencies are required")
|
||||
}
|
||||
result, err := extender.EnsureDemoMatchingSection(ctx, command.Author)
|
||||
publish, section, note := extender.EnsureDemoMatchingSection, "the demo matching section",
|
||||
"note: demonstration values, not calibrated; they apply to new searches at once and change no stored result\n"
|
||||
if command.Track == TrackSemantic {
|
||||
publish, section, note = extender.EnsureDemoSemanticMatchingSection, "the semantic matching section",
|
||||
"note: research-calibrated values (LincodexMatch DEV split), not product measurements; searches use them at once,\n"+
|
||||
"and Sem stays neutral for subjects without vectors until the semantic-backfill command has run\n"
|
||||
}
|
||||
result, err := publish(ctx, command.Author)
|
||||
if err != nil {
|
||||
return safeOperationError(err)
|
||||
}
|
||||
@@ -89,11 +111,7 @@ func Execute(ctx context.Context, command Command, extender Extender, output io.
|
||||
if result.Created {
|
||||
status = "published"
|
||||
}
|
||||
if _, err := fmt.Fprintf(output,
|
||||
"%s: product policy version %d carries the demo matching section\n"+
|
||||
"note: demonstration values, not calibrated; they apply to new searches at once and change no stored result\n",
|
||||
status, result.Version.Version(),
|
||||
); err != nil {
|
||||
if _, err := fmt.Fprintf(output, "%s: product policy version %d carries %s\n%s", status, result.Version.Version(), section, note); err != nil {
|
||||
return errors.New("could not write the result")
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -13,9 +13,10 @@ import (
|
||||
)
|
||||
|
||||
type extenderFake struct {
|
||||
result policy.MatchingResult
|
||||
err error
|
||||
author domain.PolicyAuthor
|
||||
result policy.MatchingResult
|
||||
err error
|
||||
author domain.PolicyAuthor
|
||||
semantic bool
|
||||
}
|
||||
|
||||
func (extender *extenderFake) EnsureDemoMatchingSection(_ context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) {
|
||||
@@ -23,11 +24,21 @@ func (extender *extenderFake) EnsureDemoMatchingSection(_ context.Context, autho
|
||||
return extender.result, extender.err
|
||||
}
|
||||
|
||||
func (extender *extenderFake) EnsureDemoSemanticMatchingSection(_ context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) {
|
||||
extender.author = author
|
||||
extender.semantic = true
|
||||
return extender.result, extender.err
|
||||
}
|
||||
|
||||
func TestParseRequiresTheMatchingTrackAndAnOperatorHandle(t *testing.T) {
|
||||
command, err := Parse([]string{"matching", "--actor", "operator:night"})
|
||||
if err != nil || command.Author != "operator:night" {
|
||||
if err != nil || command.Author != "operator:night" || command.Track != TrackMatching {
|
||||
t.Fatalf("Parse(valid) = %+v, %v", command, err)
|
||||
}
|
||||
semantic, err := Parse([]string{"semantic", "--actor", "operator:night"})
|
||||
if err != nil || semantic.Track != TrackSemantic {
|
||||
t.Fatalf("Parse(semantic) = %+v, %v", semantic, err)
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
nil, {"list"}, {"matching"}, {"matching", "--actor", "alice"}, {"matching", "--actor", "system:demo-seed"},
|
||||
{"matching", "--actor", "operator:night", "extra"},
|
||||
@@ -62,3 +73,14 @@ func TestExecutePrintsOnlyTheVersionAndMapsFailuresToSafeMessages(t *testing.T)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteSemanticTrackPublishesTheSemanticSection(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
extender := &extenderFake{}
|
||||
if err := Execute(context.Background(), Command{Track: TrackSemantic, Author: "operator:night"}, extender, &output); err != nil {
|
||||
t.Fatalf("Execute() error = %v", err)
|
||||
}
|
||||
if !extender.semantic || !strings.Contains(output.String(), "the semantic matching section") {
|
||||
t.Fatalf("output = %q, semantic called %v", output.String(), extender.semantic)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
// Package semanticbackfill implements the operator command that schedules
|
||||
// vector jobs for existing published candidates and needs, for example after
|
||||
// semantic matching is enabled, the semantic policy is published, or the ML
|
||||
// model changes. The jobs run in the backend worker; the command only
|
||||
// schedules them and prints the resume cursor of every page.
|
||||
package semanticbackfill
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/adapter/secondary/postgres"
|
||||
"lincodex/backend/internal/usecase/semantic"
|
||||
)
|
||||
|
||||
const usage = "usage: semantic-backfill candidates|needs|all --run <label> [--after <uuid>]"
|
||||
|
||||
// Command is a parsed, validated request.
|
||||
type Command struct {
|
||||
Scopes []semantic.BackfillScope
|
||||
Run string
|
||||
After uuid.UUID
|
||||
}
|
||||
|
||||
// Runner schedules the jobs of one scope.
|
||||
type Runner interface {
|
||||
Run(ctx context.Context, scope semantic.BackfillScope, run string, after uuid.UUID, report func(semantic.BackfillProgress) error) error
|
||||
}
|
||||
|
||||
// Parse validates every argument before Run reads configuration or connects.
|
||||
func Parse(args []string) (Command, error) {
|
||||
if len(args) == 0 {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
var scopes []semantic.BackfillScope
|
||||
switch args[0] {
|
||||
case string(semantic.BackfillCandidates):
|
||||
scopes = []semantic.BackfillScope{semantic.BackfillCandidates}
|
||||
case string(semantic.BackfillNeeds):
|
||||
scopes = []semantic.BackfillScope{semantic.BackfillNeeds}
|
||||
case "all":
|
||||
scopes = []semantic.BackfillScope{semantic.BackfillCandidates, semantic.BackfillNeeds}
|
||||
default:
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
flags := flag.NewFlagSet("semantic-backfill", flag.ContinueOnError)
|
||||
flags.SetOutput(io.Discard)
|
||||
run := flags.String("run", "", "run label; a new label recomputes again")
|
||||
after := flags.String("after", "", "resume after this identifier")
|
||||
if err := flags.Parse(args[1:]); err != nil || flags.NArg() != 0 || *run == "" {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
command := Command{Scopes: scopes, Run: *run}
|
||||
if *after != "" {
|
||||
if len(scopes) != 1 {
|
||||
return Command{}, errors.New("--after needs a single scope")
|
||||
}
|
||||
parsed, err := uuid.Parse(*after)
|
||||
if err != nil {
|
||||
return Command{}, errors.New("--after must be a UUID")
|
||||
}
|
||||
command.After = parsed
|
||||
}
|
||||
return command, nil
|
||||
}
|
||||
|
||||
// Run parses the command, loads only DATABASE_URL, and schedules.
|
||||
func Run(ctx context.Context, args []string, lookup config.LookupEnv, output io.Writer, clock func() time.Time) error {
|
||||
command, err := Parse(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if lookup == nil || output == nil || clock == nil {
|
||||
return errors.New("semantic backfill command dependencies are required")
|
||||
}
|
||||
databaseURL := config.DatabaseURLFromEnv(lookup)
|
||||
if databaseURL == "" {
|
||||
return errors.New("DATABASE_URL is not set")
|
||||
}
|
||||
pool, err := postgres.NewPool(ctx, databaseURL)
|
||||
if err != nil {
|
||||
return errors.New("database configuration is invalid")
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
return errors.New("database is unavailable")
|
||||
}
|
||||
backfill, err := semantic.NewBackfill(postgres.NewTransactor(pool), clock)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return Execute(ctx, command, backfill, output)
|
||||
}
|
||||
|
||||
// Execute runs every scope and prints one line per page.
|
||||
func Execute(ctx context.Context, command Command, runner Runner, output io.Writer) error {
|
||||
for _, scope := range command.Scopes {
|
||||
total := 0
|
||||
err := runner.Run(ctx, scope, command.Run, command.After, func(progress semantic.BackfillProgress) error {
|
||||
total += progress.Scheduled
|
||||
_, err := fmt.Fprintf(output, "%s: scheduled %d (total %d), resume with --after %s\n",
|
||||
progress.Scope, progress.Scheduled, total, progress.After)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return errors.New("the backfill stopped; run it again with --after of the last printed line")
|
||||
}
|
||||
if _, err := fmt.Fprintf(output, "%s: done, %d jobs scheduled; the backend worker computes them\n", scope, total); err != nil {
|
||||
return errors.New("could not write the result")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package semanticbackfill
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/usecase/semantic"
|
||||
)
|
||||
|
||||
type runnerFake struct {
|
||||
scopes []semantic.BackfillScope
|
||||
err error
|
||||
}
|
||||
|
||||
func (runner *runnerFake) Run(_ context.Context, scope semantic.BackfillScope, _ string, after uuid.UUID, report func(semantic.BackfillProgress) error) error {
|
||||
runner.scopes = append(runner.scopes, scope)
|
||||
if runner.err != nil {
|
||||
return runner.err
|
||||
}
|
||||
return report(semantic.BackfillProgress{Scope: scope, Scheduled: 2, After: after, Done: true})
|
||||
}
|
||||
|
||||
func TestParseRequiresAScopeAndARunLabel(t *testing.T) {
|
||||
command, err := Parse([]string{"all", "--run", "2026-10-11"})
|
||||
if err != nil || len(command.Scopes) != 2 || command.Run != "2026-10-11" {
|
||||
t.Fatalf("Parse(all) = %+v, %v", command, err)
|
||||
}
|
||||
after := uuid.New()
|
||||
command, err = Parse([]string{"needs", "--run", "r1", "--after", after.String()})
|
||||
if err != nil || command.After != after {
|
||||
t.Fatalf("Parse(needs --after) = %+v, %v", command, err)
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
nil, {"vectors"}, {"candidates"}, {"all", "--run", "r1", "--after", after.String()},
|
||||
{"needs", "--run", "r1", "--after", "x"}, {"needs", "--run", "r1", "extra"},
|
||||
} {
|
||||
if _, err := Parse(args); err == nil {
|
||||
t.Errorf("Parse(%v) accepted invalid arguments", args)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteReportsEveryScopeAndHidesStorageErrors(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
runner := &runnerFake{}
|
||||
command := Command{Scopes: []semantic.BackfillScope{semantic.BackfillCandidates, semantic.BackfillNeeds}, Run: "r1"}
|
||||
if err := Execute(context.Background(), command, runner, &output); err != nil {
|
||||
t.Fatalf("Execute() error = %v", err)
|
||||
}
|
||||
if len(runner.scopes) != 2 || !strings.Contains(output.String(), "needs: done, 2 jobs scheduled") {
|
||||
t.Fatalf("output = %q", output.String())
|
||||
}
|
||||
failing := &runnerFake{err: errors.New("pq: password authentication failed for user x")}
|
||||
err := Execute(context.Background(), command, failing, &bytes.Buffer{})
|
||||
if err == nil || strings.Contains(err.Error(), "password") {
|
||||
t.Fatalf("Execute(failing) error = %v, want a safe message", err)
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,7 @@ var regexMap = map[string]ogenregex.Regexp{
|
||||
"^__Host-lincodex_session=": ogenregex.MustCompile("^__Host-lincodex_session="),
|
||||
"^cv1_[A-Za-z0-9_-]{43}$": ogenregex.MustCompile("^cv1_[A-Za-z0-9_-]{43}$"),
|
||||
"^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$": ogenregex.MustCompile("^https://[^\\s/?#@]+(?:[/?#][^\\s]*)?$"),
|
||||
"^https://github\\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$": ogenregex.MustCompile("^https://github\\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$"),
|
||||
}
|
||||
var (
|
||||
// Allocate option closure once.
|
||||
|
||||
@@ -12806,6 +12806,223 @@ func (s *Server) handleRequestMyAccountDeletionRequest(args [0]string, argsEscap
|
||||
}
|
||||
}
|
||||
|
||||
// handleRequestMyRepositoryChecksRequest handles RequestMyRepositoryChecks operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
|
||||
// and an allowed Origin. The request has no body. It schedules a new check of every repository that
|
||||
// the current profile links, for example after the candidate made a repository public, and answers 202
|
||||
// with the number of scheduled checks; the checks run in the background and `GetMyProfile` shows their
|
||||
// state in `projects[].repository_check`. A profile without linked repositories answers 202 with 0.
|
||||
//
|
||||
// A check reads only public metadata from the public GitHub API (`api.github.com`): whether the
|
||||
// repository exists and is public, its description, topics, languages, and the beginning of its README
|
||||
// as plain text. The server never fetches any other host, never follows a redirect to another host,
|
||||
// and never shows the fetched text; it uses it only for semantic ranking. A verified repository does
|
||||
// not prove that the candidate wrote the code.
|
||||
//
|
||||
// The operation is limited per candidate: a second request inside the versioned window answers 429
|
||||
// rate_limited with Retry-After and schedules nothing. A missing, unknown, expired, or revoked session
|
||||
// answers 401 unauthenticated; an employer account answers 403 forbidden.
|
||||
//
|
||||
// POST /api/v1/me/profile/repository-checks
|
||||
func (s *Server) handleRequestMyRepositoryChecksRequest(args [0]string, argsEscaped bool, w http.ResponseWriter, r *http.Request) {
|
||||
statusWriter := &codeRecorder{ResponseWriter: w}
|
||||
w = statusWriter
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("RequestMyRepositoryChecks"),
|
||||
semconv.HTTPRequestMethodKey.String("POST"),
|
||||
semconv.HTTPRouteKey.String("/api/v1/me/profile/repository-checks"),
|
||||
}
|
||||
// Add attributes from config.
|
||||
otelAttrs = append(otelAttrs, s.cfg.Attributes...)
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := s.cfg.Tracer.Start(r.Context(), RequestMyRepositoryChecksOperation,
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
serverSpanKind,
|
||||
)
|
||||
defer span.End()
|
||||
|
||||
// Add Labeler to context.
|
||||
labeler := &Labeler{attrs: otelAttrs}
|
||||
ctx = contextWithLabeler(ctx, labeler)
|
||||
|
||||
// Run stopwatch.
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
elapsedDuration := time.Since(startTime)
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
code := statusWriter.status
|
||||
if code != 0 {
|
||||
codeAttr := semconv.HTTPResponseStatusCode(code)
|
||||
attrs = append(attrs, codeAttr)
|
||||
span.SetAttributes(attrs...)
|
||||
}
|
||||
attrOpt := metric.WithAttributes(attrs...)
|
||||
|
||||
// Increment request counter.
|
||||
s.requests.Add(ctx, 1, attrOpt)
|
||||
|
||||
// Use floating point division here for higher precision (instead of Millisecond method).
|
||||
s.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), attrOpt)
|
||||
}()
|
||||
|
||||
var (
|
||||
recordError = func(stage string, err error) {
|
||||
span.RecordError(err)
|
||||
|
||||
// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status
|
||||
// Span Status MUST be left unset if HTTP status code was in the 1xx, 2xx or 3xx ranges,
|
||||
// unless there was another error (e.g., network error receiving the response body; or 3xx codes with
|
||||
// max redirects exceeded), in which case status MUST be set to Error.
|
||||
code := statusWriter.status
|
||||
if code < 100 || code >= 500 {
|
||||
span.SetStatus(codes.Error, stage)
|
||||
}
|
||||
|
||||
attrSet := labeler.AttributeSet()
|
||||
attrs := attrSet.ToSlice()
|
||||
if code != 0 {
|
||||
attrs = append(attrs, semconv.HTTPResponseStatusCode(code))
|
||||
}
|
||||
|
||||
s.errors.Add(ctx, 1, metric.WithAttributes(attrs...))
|
||||
}
|
||||
err error
|
||||
opErrContext = ogenerrors.OperationContext{
|
||||
Name: RequestMyRepositoryChecksOperation,
|
||||
ID: "RequestMyRepositoryChecks",
|
||||
}
|
||||
)
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
sctx, ok, err := s.securitySessionCookie(ctx, RequestMyRepositoryChecksOperation, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Security: "SessionCookie",
|
||||
Err: err,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security:SessionCookie", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
satisfied[0] |= 1 << 0
|
||||
ctx = sctx
|
||||
}
|
||||
}
|
||||
{
|
||||
sctx, ok, err := s.securitySessionCsrf(ctx, RequestMyRepositoryChecksOperation, r)
|
||||
if err != nil {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Security: "SessionCsrf",
|
||||
Err: err,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security:SessionCsrf", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ok {
|
||||
satisfied[0] |= 1 << 1
|
||||
ctx = sctx
|
||||
}
|
||||
}
|
||||
|
||||
if ok := func() bool {
|
||||
nextRequirement:
|
||||
for _, requirement := range []bitset{
|
||||
{0b00000011},
|
||||
} {
|
||||
for i, mask := range requirement {
|
||||
if satisfied[i]&mask != mask {
|
||||
continue nextRequirement
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}(); !ok {
|
||||
err = &ogenerrors.SecurityError{
|
||||
OperationContext: opErrContext,
|
||||
Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied,
|
||||
}
|
||||
if encodeErr := encodeErrorResponse(s.h.NewError(ctx, err), w, span); encodeErr != nil {
|
||||
defer recordError("Security", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var rawBody []byte
|
||||
|
||||
var response RequestMyRepositoryChecksRes
|
||||
if m := s.cfg.Middleware; m != nil {
|
||||
mreq := middleware.Request{
|
||||
Context: ctx,
|
||||
OperationName: RequestMyRepositoryChecksOperation,
|
||||
OperationSummary: "Ask the server to check the linked project repositories again.",
|
||||
OperationID: "RequestMyRepositoryChecks",
|
||||
Body: nil,
|
||||
RawBody: rawBody,
|
||||
Params: middleware.Parameters{},
|
||||
Raw: r,
|
||||
}
|
||||
|
||||
type (
|
||||
Request = struct{}
|
||||
Params = struct{}
|
||||
Response = RequestMyRepositoryChecksRes
|
||||
)
|
||||
response, err = middleware.HookMiddleware[
|
||||
Request,
|
||||
Params,
|
||||
Response,
|
||||
](
|
||||
m,
|
||||
mreq,
|
||||
nil,
|
||||
func(ctx context.Context, request Request, params Params) (response Response, err error) {
|
||||
response, err = s.h.RequestMyRepositoryChecks(ctx)
|
||||
return response, err
|
||||
},
|
||||
)
|
||||
} else {
|
||||
response, err = s.h.RequestMyRepositoryChecks(ctx)
|
||||
}
|
||||
if err != nil {
|
||||
if errRes, ok := errors.Into[*ProblemStatusCode](err); ok {
|
||||
if err := encodeErrorResponse(errRes, w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if errors.Is(err, ht.ErrNotImplemented) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
return
|
||||
}
|
||||
if err := encodeErrorResponse(s.h.NewError(ctx, err), w, span); err != nil {
|
||||
defer recordError("Internal", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err := encodeRequestMyRepositoryChecksResponse(response, w, span); err != nil {
|
||||
defer recordError("EncodeResponse", err)
|
||||
if !errors.Is(err, ht.ErrInternalServerErrorResponse) {
|
||||
s.cfg.ErrorHandler(ctx, w, r, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// handleResendEmailVerificationRequest handles ResendEmailVerification operation.
|
||||
//
|
||||
// Public operation without a session. The answer is the same 202 for an unknown email, a verified
|
||||
@@ -13976,13 +14193,23 @@ func (s *Server) handleSaveMyQuestionnaireRequest(args [0]string, argsEscaped bo
|
||||
// The card context is limited to safe public fields: recognized stack tags, coarse experience,
|
||||
// accepted work formats, and coarse salary compatibility. It contains no contact, candidate location,
|
||||
// salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data.
|
||||
// Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity
|
||||
// uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30
|
||||
// comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names
|
||||
// `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile
|
||||
// is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5,
|
||||
// the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not
|
||||
// fail.
|
||||
// Evidence explanations use bounded codes, not free text.
|
||||
//
|
||||
// Semantic similarity `Sem` is the calibrated cosine between the stored vector of the need's confirmed
|
||||
// requirements snapshot and the stored vector of the candidate's published card text (roles,
|
||||
// recognized stack, and published projects with the public metadata of their verified repositories).
|
||||
// The search never calls the ML service: vectors are computed in the background after a change, and an
|
||||
// entry whose vectors are missing, stale for the current model, or not computed because ML is
|
||||
// unavailable uses the neutral 0.5 and names `ml_unavailable` in `unknown_flags`. `semantic_evidence`
|
||||
// lists, for a need search, the confirmed requirements whose closest published card item reaches a
|
||||
// similarity band of the versioned policy; it names a project only by the title that the candidate
|
||||
// published with the `projects` card field and says whether its repository is a verified public one,
|
||||
// never the repository address or owner. Showing a project title records the `projects` field in the
|
||||
// candidate's access history. For fewer than 30 comparable real candidates, the search uses neutral T
|
||||
// = 0.5, returns no percentile value, and names `cohort_below_30`. When the comparable real cohort of
|
||||
// a category reaches the minimum, the percentile is still not computed (the organization-safe
|
||||
// projection carries no theta), T stays the neutral 0.5, the percentile stays null, and
|
||||
// `unknown_flags` names `percentile_not_computed`; the search does not fail.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
|
||||
// answers 403 forbidden; an unknown organization or account without active membership answers 404
|
||||
|
||||
@@ -221,6 +221,10 @@ type RequestMyAccountDeletionRes interface {
|
||||
requestMyAccountDeletionRes()
|
||||
}
|
||||
|
||||
type RequestMyRepositoryChecksRes interface {
|
||||
requestMyRepositoryChecksRes()
|
||||
}
|
||||
|
||||
type ResendEmailVerificationRes interface {
|
||||
resendEmailVerificationRes()
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -63,6 +63,7 @@ const (
|
||||
RecordMyAssessmentAttemptSignalsOperation OperationName = "RecordMyAssessmentAttemptSignals"
|
||||
RegisterAccountOperation OperationName = "RegisterAccount"
|
||||
RequestMyAccountDeletionOperation OperationName = "RequestMyAccountDeletion"
|
||||
RequestMyRepositoryChecksOperation OperationName = "RequestMyRepositoryChecks"
|
||||
ResendEmailVerificationOperation OperationName = "ResendEmailVerification"
|
||||
RevokeMyConsentOperation OperationName = "RevokeMyConsent"
|
||||
RevokeMyOrganizationContactConsentOperation OperationName = "RevokeMyOrganizationContactConsent"
|
||||
|
||||
@@ -4933,6 +4933,97 @@ func encodeRequestMyAccountDeletionResponse(response RequestMyAccountDeletionRes
|
||||
}
|
||||
}
|
||||
|
||||
func encodeRequestMyRepositoryChecksResponse(response RequestMyRepositoryChecksRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *ProfileRepositoryCheckRequestHeaders:
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Cache-Control" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Cache-Control",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
return e.EncodeValue(conv.StringToString(string(response.CacheControl)))
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Cache-Control header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(202)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *RequestMyRepositoryChecksUnauthorized:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(401)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *RequestMyRepositoryChecksForbidden:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.WriteHeader(403)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
case *TooManyRequestsHeaders:
|
||||
w.Header().Set("Content-Type", "application/problem+json")
|
||||
w.Header().Set("Access-Control-Expose-Headers", "Retry-After")
|
||||
// Encoding response headers.
|
||||
{
|
||||
h := uri.NewHeaderEncoder(w.Header())
|
||||
// Encode "Retry-After" header.
|
||||
{
|
||||
cfg := uri.HeaderParameterEncodingConfig{
|
||||
Name: "Retry-After",
|
||||
Explode: false,
|
||||
}
|
||||
if err := h.EncodeParam(cfg, func(e uri.Encoder) error {
|
||||
if val, ok := response.RetryAfter.Get(); ok {
|
||||
return e.EncodeValue(conv.Int32ToString(val))
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "encode Retry-After header")
|
||||
}
|
||||
}
|
||||
}
|
||||
w.WriteHeader(429)
|
||||
|
||||
e := new(jx.Encoder)
|
||||
response.Response.Encode(e)
|
||||
if _, err := e.WriteTo(w); err != nil {
|
||||
return errors.Wrap(err, "write")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
default:
|
||||
return errors.Errorf("unexpected response type: %T", response)
|
||||
}
|
||||
}
|
||||
|
||||
func encodeResendEmailVerificationResponse(response ResendEmailVerificationRes, w http.ResponseWriter, span trace.Span) error {
|
||||
switch response := response.(type) {
|
||||
case *IdentityRequestAccepted:
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
rn84AllowedHeaders = map[string]string{
|
||||
rn85AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type",
|
||||
}
|
||||
rn9AllowedHeaders = map[string]string{
|
||||
@@ -35,13 +35,13 @@ var (
|
||||
rn12AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn95AllowedHeaders = map[string]string{
|
||||
rn96AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn23AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn94AllowedHeaders = map[string]string{
|
||||
rn95AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn79AllowedHeaders = map[string]string{
|
||||
@@ -50,7 +50,7 @@ var (
|
||||
rn5AllowedHeaders = map[string]string{
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn86AllowedHeaders = map[string]string{
|
||||
rn87AllowedHeaders = map[string]string{
|
||||
"DELETE": "X-Csrf-Token",
|
||||
}
|
||||
rn54AllowedHeaders = map[string]string{
|
||||
@@ -66,7 +66,7 @@ var (
|
||||
rn20AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn96AllowedHeaders = map[string]string{
|
||||
rn97AllowedHeaders = map[string]string{
|
||||
"POST": "X-Csrf-Token",
|
||||
}
|
||||
rn73AllowedHeaders = map[string]string{
|
||||
@@ -76,15 +76,18 @@ var (
|
||||
"DELETE": "X-Csrf-Token",
|
||||
"PUT": "X-Csrf-Token",
|
||||
}
|
||||
rn91AllowedHeaders = map[string]string{
|
||||
rn92AllowedHeaders = map[string]string{
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn92AllowedHeaders = map[string]string{
|
||||
rn93AllowedHeaders = map[string]string{
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn39AllowedHeaders = map[string]string{
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn83AllowedHeaders = map[string]string{
|
||||
"POST": "X-Csrf-Token",
|
||||
}
|
||||
rn40AllowedHeaders = map[string]string{
|
||||
"PUT": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
@@ -106,13 +109,13 @@ var (
|
||||
rn78AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn89AllowedHeaders = map[string]string{
|
||||
rn90AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn97AllowedHeaders = map[string]string{
|
||||
rn98AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,Idempotency-Key,X-Csrf-Token",
|
||||
}
|
||||
rn87AllowedHeaders = map[string]string{
|
||||
rn88AllowedHeaders = map[string]string{
|
||||
"POST": "Content-Type,X-Csrf-Token",
|
||||
}
|
||||
rn19AllowedHeaders = map[string]string{
|
||||
@@ -278,7 +281,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn84AllowedHeaders,
|
||||
allowedHeaders: rn85AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -607,7 +610,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn95AllowedHeaders,
|
||||
allowedHeaders: rn96AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -700,7 +703,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn94AllowedHeaders,
|
||||
allowedHeaders: rn95AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -938,7 +941,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "DELETE",
|
||||
allowedHeaders: rn86AllowedHeaders,
|
||||
allowedHeaders: rn87AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1180,7 +1183,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn96AllowedHeaders,
|
||||
allowedHeaders: rn97AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1527,7 +1530,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "PUT",
|
||||
allowedHeaders: rn91AllowedHeaders,
|
||||
allowedHeaders: rn92AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1554,7 +1557,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "PUT",
|
||||
allowedHeaders: rn92AllowedHeaders,
|
||||
allowedHeaders: rn93AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -1576,7 +1579,6 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
s.handleGetMyProfileRequest([0]string{}, elemIsEscaped, w, r)
|
||||
@@ -1593,6 +1595,33 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
return
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/repository-checks"
|
||||
|
||||
if l := len("/repository-checks"); len(elem) >= l && elem[0:l] == "/repository-checks" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch r.Method {
|
||||
case "POST":
|
||||
s.handleRequestMyRepositoryChecksRequest([0]string{}, elemIsEscaped, w, r)
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn83AllowedHeaders,
|
||||
acceptPost: "",
|
||||
acceptPatch: "",
|
||||
})
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -2000,7 +2029,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn89AllowedHeaders,
|
||||
allowedHeaders: rn90AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -2030,7 +2059,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn97AllowedHeaders,
|
||||
allowedHeaders: rn98AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -2063,7 +2092,7 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
default:
|
||||
s.notAllowed(w, r, notAllowedParams{
|
||||
allowedMethods: "POST",
|
||||
allowedHeaders: rn87AllowedHeaders,
|
||||
allowedHeaders: rn88AllowedHeaders,
|
||||
acceptPost: "application/json",
|
||||
acceptPatch: "",
|
||||
})
|
||||
@@ -3759,7 +3788,6 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "GET":
|
||||
r.name = GetMyProfileOperation
|
||||
@@ -3783,6 +3811,33 @@ func (s *Server) FindPath(method string, u *url.URL) (r Route, _ bool) {
|
||||
return
|
||||
}
|
||||
}
|
||||
switch elem[0] {
|
||||
case '/': // Prefix: "/repository-checks"
|
||||
|
||||
if l := len("/repository-checks"); len(elem) >= l && elem[0:l] == "/repository-checks" {
|
||||
elem = elem[l:]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
|
||||
if len(elem) == 0 {
|
||||
// Leaf node.
|
||||
switch method {
|
||||
case "POST":
|
||||
r.name = RequestMyRepositoryChecksOperation
|
||||
r.summary = "Ask the server to check the linked project repositories again."
|
||||
r.operationID = "RequestMyRepositoryChecks"
|
||||
r.operationGroup = ""
|
||||
r.pathPattern = "/api/v1/me/profile/repository-checks"
|
||||
r.args = args
|
||||
r.count = 0
|
||||
return r, true
|
||||
default:
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -106,6 +106,7 @@ var operationRolesSessionCookie = map[string][]string{
|
||||
RaiseOrganizationInvitationSalaryOperation: []string{},
|
||||
RecordMyAssessmentAttemptSignalsOperation: []string{},
|
||||
RequestMyAccountDeletionOperation: []string{},
|
||||
RequestMyRepositoryChecksOperation: []string{},
|
||||
RevokeMyConsentOperation: []string{},
|
||||
RevokeMyOrganizationContactConsentOperation: []string{},
|
||||
SaveMyProfileOperation: []string{},
|
||||
@@ -165,6 +166,7 @@ var operationRolesSessionCsrf = map[string][]string{
|
||||
RaiseOrganizationInvitationSalaryOperation: []string{},
|
||||
RecordMyAssessmentAttemptSignalsOperation: []string{},
|
||||
RequestMyAccountDeletionOperation: []string{},
|
||||
RequestMyRepositoryChecksOperation: []string{},
|
||||
RevokeMyConsentOperation: []string{},
|
||||
RevokeMyOrganizationContactConsentOperation: []string{},
|
||||
SaveMyProfileOperation: []string{},
|
||||
|
||||
@@ -1556,6 +1556,26 @@ type Handler interface {
|
||||
//
|
||||
// POST /api/v1/me/account-deletion-requests
|
||||
RequestMyAccountDeletion(ctx context.Context) (RequestMyAccountDeletionRes, error)
|
||||
// RequestMyRepositoryChecks implements RequestMyRepositoryChecks operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
|
||||
// and an allowed Origin. The request has no body. It schedules a new check of every repository that
|
||||
// the current profile links, for example after the candidate made a repository public, and answers 202
|
||||
// with the number of scheduled checks; the checks run in the background and `GetMyProfile` shows their
|
||||
// state in `projects[].repository_check`. A profile without linked repositories answers 202 with 0.
|
||||
//
|
||||
// A check reads only public metadata from the public GitHub API (`api.github.com`): whether the
|
||||
// repository exists and is public, its description, topics, languages, and the beginning of its README
|
||||
// as plain text. The server never fetches any other host, never follows a redirect to another host,
|
||||
// and never shows the fetched text; it uses it only for semantic ranking. A verified repository does
|
||||
// not prove that the candidate wrote the code.
|
||||
//
|
||||
// The operation is limited per candidate: a second request inside the versioned window answers 429
|
||||
// rate_limited with Retry-After and schedules nothing. A missing, unknown, expired, or revoked session
|
||||
// answers 401 unauthenticated; an employer account answers 403 forbidden.
|
||||
//
|
||||
// POST /api/v1/me/profile/repository-checks
|
||||
RequestMyRepositoryChecks(ctx context.Context) (RequestMyRepositoryChecksRes, error)
|
||||
// ResendEmailVerification implements ResendEmailVerification operation.
|
||||
//
|
||||
// Public operation without a session. The answer is the same 202 for an unknown email, a verified
|
||||
@@ -1730,13 +1750,23 @@ type Handler interface {
|
||||
// The card context is limited to safe public fields: recognized stack tags, coarse experience,
|
||||
// accepted work formats, and coarse salary compatibility. It contains no contact, candidate location,
|
||||
// salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data.
|
||||
// Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity
|
||||
// uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30
|
||||
// comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names
|
||||
// `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile
|
||||
// is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5,
|
||||
// the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not
|
||||
// fail.
|
||||
// Evidence explanations use bounded codes, not free text.
|
||||
//
|
||||
// Semantic similarity `Sem` is the calibrated cosine between the stored vector of the need's confirmed
|
||||
// requirements snapshot and the stored vector of the candidate's published card text (roles,
|
||||
// recognized stack, and published projects with the public metadata of their verified repositories).
|
||||
// The search never calls the ML service: vectors are computed in the background after a change, and an
|
||||
// entry whose vectors are missing, stale for the current model, or not computed because ML is
|
||||
// unavailable uses the neutral 0.5 and names `ml_unavailable` in `unknown_flags`. `semantic_evidence`
|
||||
// lists, for a need search, the confirmed requirements whose closest published card item reaches a
|
||||
// similarity band of the versioned policy; it names a project only by the title that the candidate
|
||||
// published with the `projects` card field and says whether its repository is a verified public one,
|
||||
// never the repository address or owner. Showing a project title records the `projects` field in the
|
||||
// candidate's access history. For fewer than 30 comparable real candidates, the search uses neutral T
|
||||
// = 0.5, returns no percentile value, and names `cohort_below_30`. When the comparable real cohort of
|
||||
// a category reaches the minimum, the percentile is still not computed (the organization-safe
|
||||
// projection carries no theta), T stays the neutral 0.5, the percentile stays null, and
|
||||
// `unknown_flags` names `percentile_not_computed`; the search does not fail.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
|
||||
// answers 403 forbidden; an unknown organization or account without active membership answers 404
|
||||
|
||||
@@ -1732,6 +1732,29 @@ func (UnimplementedHandler) RequestMyAccountDeletion(ctx context.Context) (r Req
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// RequestMyRepositoryChecks implements RequestMyRepositoryChecks operation.
|
||||
//
|
||||
// Requires the session cookie of a candidate account, the CSRF token of that session in X-CSRF-Token,
|
||||
// and an allowed Origin. The request has no body. It schedules a new check of every repository that
|
||||
// the current profile links, for example after the candidate made a repository public, and answers 202
|
||||
// with the number of scheduled checks; the checks run in the background and `GetMyProfile` shows their
|
||||
// state in `projects[].repository_check`. A profile without linked repositories answers 202 with 0.
|
||||
//
|
||||
// A check reads only public metadata from the public GitHub API (`api.github.com`): whether the
|
||||
// repository exists and is public, its description, topics, languages, and the beginning of its README
|
||||
// as plain text. The server never fetches any other host, never follows a redirect to another host,
|
||||
// and never shows the fetched text; it uses it only for semantic ranking. A verified repository does
|
||||
// not prove that the candidate wrote the code.
|
||||
//
|
||||
// The operation is limited per candidate: a second request inside the versioned window answers 429
|
||||
// rate_limited with Retry-After and schedules nothing. A missing, unknown, expired, or revoked session
|
||||
// answers 401 unauthenticated; an employer account answers 403 forbidden.
|
||||
//
|
||||
// POST /api/v1/me/profile/repository-checks
|
||||
func (UnimplementedHandler) RequestMyRepositoryChecks(ctx context.Context) (r RequestMyRepositoryChecksRes, _ error) {
|
||||
return r, ht.ErrNotImplemented
|
||||
}
|
||||
|
||||
// ResendEmailVerification implements ResendEmailVerification operation.
|
||||
//
|
||||
// Public operation without a session. The answer is the same 202 for an unknown email, a verified
|
||||
@@ -1921,13 +1944,23 @@ func (UnimplementedHandler) SaveMyQuestionnaire(ctx context.Context, req *Candid
|
||||
// The card context is limited to safe public fields: recognized stack tags, coarse experience,
|
||||
// accepted work formats, and coarse salary compatibility. It contains no contact, candidate location,
|
||||
// salary amount or minimum, raw answer, arbitrary profile text, or reason for withheld FSP data.
|
||||
// Evidence explanations use bounded codes, not free text. When ML is unavailable, semantic similarity
|
||||
// uses the neutral 0.5 specified by FR09 and `unknown_flags` names `ml_unavailable`. For fewer than 30
|
||||
// comparable real candidates, the search uses neutral T = 0.5, returns no percentile value, and names
|
||||
// `cohort_below_30`. When the comparable real cohort of a category reaches the minimum, the percentile
|
||||
// is still not computed (the organization-safe projection carries no theta), T stays the neutral 0.5,
|
||||
// the percentile stays null, and `unknown_flags` names `percentile_not_computed`; the search does not
|
||||
// fail.
|
||||
// Evidence explanations use bounded codes, not free text.
|
||||
//
|
||||
// Semantic similarity `Sem` is the calibrated cosine between the stored vector of the need's confirmed
|
||||
// requirements snapshot and the stored vector of the candidate's published card text (roles,
|
||||
// recognized stack, and published projects with the public metadata of their verified repositories).
|
||||
// The search never calls the ML service: vectors are computed in the background after a change, and an
|
||||
// entry whose vectors are missing, stale for the current model, or not computed because ML is
|
||||
// unavailable uses the neutral 0.5 and names `ml_unavailable` in `unknown_flags`. `semantic_evidence`
|
||||
// lists, for a need search, the confirmed requirements whose closest published card item reaches a
|
||||
// similarity band of the versioned policy; it names a project only by the title that the candidate
|
||||
// published with the `projects` card field and says whether its repository is a verified public one,
|
||||
// never the repository address or owner. Showing a project title records the `projects` field in the
|
||||
// candidate's access history. For fewer than 30 comparable real candidates, the search uses neutral T
|
||||
// = 0.5, returns no percentile value, and names `cohort_below_30`. When the comparable real cohort of
|
||||
// a category reaches the minimum, the percentile is still not computed (the organization-safe
|
||||
// projection carries no theta), T stays the neutral 0.5, the percentile stays null, and
|
||||
// `unknown_flags` names `percentile_not_computed`; the search does not fail.
|
||||
//
|
||||
// A missing, unknown, expired, or revoked session answers 401 unauthenticated; a candidate account
|
||||
// answers 403 forbidden; an unknown organization or account without active membership answers 404
|
||||
|
||||
@@ -396,6 +396,42 @@ func (s *AnonymousCardContent) Validate() error {
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if s.Projects == nil {
|
||||
return nil // null
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 0,
|
||||
MinLengthSet: false,
|
||||
MaxLength: 10,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(s.Projects)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range s.Projects {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "projects",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
@@ -5687,6 +5723,42 @@ func (s *CandidateProfile) Validate() error {
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if s.Projects == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 0,
|
||||
MinLengthSet: false,
|
||||
MaxLength: 10,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(s.Projects)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range s.Projects {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "projects",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Terms.Validate(); err != nil {
|
||||
return err
|
||||
@@ -6000,6 +6072,42 @@ func (s *CandidateProfileUpdate) Validate() error {
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if s.Projects == nil {
|
||||
return nil // optional
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 0,
|
||||
MinLengthSet: false,
|
||||
MaxLength: 10,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(s.Projects)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range s.Projects {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "projects",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Terms.Validate(); err != nil {
|
||||
return err
|
||||
@@ -6454,6 +6562,8 @@ func (s CardField) Validate() error {
|
||||
return nil
|
||||
case "work_formats":
|
||||
return nil
|
||||
case "projects":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
@@ -6467,7 +6577,7 @@ func (s CardFieldSet) Validate() error {
|
||||
if err := (validate.Array{
|
||||
MinLength: 0,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 9,
|
||||
MaxLength: 10,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(alias)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
@@ -6599,6 +6709,107 @@ func (s *CardPreviewHeaders) Validate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CardProject) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 100,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(s.Title)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "title",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := s.Description.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 500,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(value)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "description",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if s.Stack == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 0,
|
||||
MinLengthSet: false,
|
||||
MaxLength: 10,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(s.Stack)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range s.Stack {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "stack",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CardSelfAssessment) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
@@ -12275,6 +12486,17 @@ func (s *MatchConfirmedCandidate) Validate() error {
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.SemanticEvidence.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "semantic_evidence",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Components.Validate(); err != nil {
|
||||
return err
|
||||
@@ -12713,6 +12935,19 @@ func (s MatchPublicStack) Validate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s MatchRequirementKind) Validate() error {
|
||||
switch s {
|
||||
case "required_skill":
|
||||
return nil
|
||||
case "desired_skill":
|
||||
return nil
|
||||
case "task":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s MatchScore) Validate() error {
|
||||
alias := (float64)(s)
|
||||
if err := (validate.Float{
|
||||
@@ -13322,6 +13557,161 @@ func (s MatchSearchStackTag) Validate() error {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MatchSemanticEvidence) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.RequirementKind.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "requirement_kind",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 300,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(s.RequirementText)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "requirement_text",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.ItemKind.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "item_kind",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := s.ProjectTitle.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 100,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(value)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "project_title",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Similarity.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "similarity",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s MatchSemanticEvidenceList) Validate() error {
|
||||
alias := ([]MatchSemanticEvidence)(s)
|
||||
if alias == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 0,
|
||||
MinLengthSet: false,
|
||||
MaxLength: 12,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(alias)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range alias {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s MatchSemanticItemKind) Validate() error {
|
||||
switch s {
|
||||
case "project":
|
||||
return nil
|
||||
case "stack":
|
||||
return nil
|
||||
case "roles":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s MatchSimilarityBand) Validate() error {
|
||||
switch s {
|
||||
case "high":
|
||||
return nil
|
||||
case "medium":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s MatchStrength) Validate() error {
|
||||
switch s {
|
||||
case "standard":
|
||||
@@ -13412,6 +13802,17 @@ func (s *MatchUnconfirmedCandidate) Validate() error {
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.SemanticEvidence.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "semantic_evidence",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Components.Validate(); err != nil {
|
||||
return err
|
||||
@@ -19485,6 +19886,8 @@ func (s ProblemCode) Validate() error {
|
||||
return nil
|
||||
case "not_implemented":
|
||||
return nil
|
||||
case "service_unavailable":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
@@ -20803,6 +21206,270 @@ func (s *ProfilePhoneInput) Validate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s ProfileProjectDescription) Validate() error {
|
||||
alias := (string)(s)
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 500,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(alias)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ProfileProjectItem) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.Title.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "title",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := s.Description.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := value.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "description",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Stack.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "stack",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := s.RepositoryURL.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := value.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "repository_url",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := s.RepositoryCheck.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := value.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "repository_check",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Status.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "status",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Source.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "source",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ProfileProjectItemInput) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.Title.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "title",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := s.Description.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := value.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "description",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Stack.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "stack",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if value, ok := s.RepositoryURL.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := value.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "repository_url",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Status.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "status",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s ProfileProjectStack) Validate() error {
|
||||
alias := ([]StackTag)(s)
|
||||
if alias == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 0,
|
||||
MinLengthSet: false,
|
||||
MaxLength: 10,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(alias)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range alias {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s ProfileProjectTitle) Validate() error {
|
||||
alias := (string)(s)
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 100,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: regexMap["^\\S(?:.*\\S)?$"],
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(alias)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ProfileRelocationClaim) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
@@ -20867,6 +21534,131 @@ func (s *ProfileRelocationInput) Validate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ProfileRepositoryCheck) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.State.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "state",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ProfileRepositoryCheckRequest) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := (validate.Int{
|
||||
MinSet: true,
|
||||
Min: 0,
|
||||
MaxSet: true,
|
||||
Max: 10,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: 0,
|
||||
Pattern: nil,
|
||||
}).Validate(int64(s.Scheduled)); err != nil {
|
||||
return errors.Wrap(err, "int")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "scheduled",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ProfileRepositoryCheckRequestHeaders) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.CacheControl.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "CacheControl",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "Response",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s ProfileRepositoryCheckState) Validate() error {
|
||||
switch s {
|
||||
case "pending":
|
||||
return nil
|
||||
case "verified":
|
||||
return nil
|
||||
case "not_found":
|
||||
return nil
|
||||
case "unavailable":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s ProfileRepositoryUrl) Validate() error {
|
||||
alias := (string)(s)
|
||||
if err := (validate.String{
|
||||
MinLength: 22,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 160,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: regexMap["^https://github\\.com/[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})/[A-Za-z0-9._-]{1,100}/?$"],
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(alias)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ProfileRoleItem) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
@@ -22099,6 +22891,22 @@ func (s *RequestMyAccountDeletionUnauthorized) Validate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *RequestMyRepositoryChecksForbidden) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *RequestMyRepositoryChecksUnauthorized) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ResendEmailVerificationBadRequest) Validate() error {
|
||||
alias := (*Problem)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
|
||||
@@ -33,7 +33,7 @@ var (
|
||||
hiddenSchemas = []string{"HiddenOrganization", "HiddenOrganizationList", "PrivacyOrganization"}
|
||||
privacyOnlySchemas = []string{
|
||||
"PrivacySettings", "CardPreview", "AnonymousCardContent", "CardCategory", "CardCategoryStrength", "CardSelfAssessment",
|
||||
"CardSelfAssessmentConfirmationStatus",
|
||||
"CardSelfAssessmentConfirmationStatus", "CardProject",
|
||||
"CandidateExperienceBand", "CandidateWorkFormat", "CandidateSalaryCompatibility",
|
||||
"PrivacyEvent", "PrivacyEventKind", "PrivacyEventList", "CardAccess", "CardAccessKind", "CardAccessList",
|
||||
}
|
||||
@@ -218,14 +218,14 @@ func TestPublicationAndSearchStatusAreNotConsents(t *testing.T) {
|
||||
fields := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CardField"}))
|
||||
want := []string{
|
||||
"categories", "stack", "experience", "soft_skills", "location", "relocation",
|
||||
"self_assessment", "work_formats", "salary_compatibility",
|
||||
"self_assessment", "work_formats", "salary_compatibility", "projects",
|
||||
}
|
||||
slices.Sort(fields)
|
||||
slices.Sort(want)
|
||||
if !slices.Equal(fields, want) {
|
||||
t.Errorf("CardField = %v, want %v", fields, want)
|
||||
}
|
||||
if update := spec.Components.Schemas["CardFieldSet"]; update.UniqueItems != true || update.MaxItems == nil || *update.MaxItems != 9 {
|
||||
if update := spec.Components.Schemas["CardFieldSet"]; update.UniqueItems != true || update.MaxItems == nil || *update.MaxItems != 10 {
|
||||
t.Error("CardFieldSet must hold distinct items and at most one per field")
|
||||
}
|
||||
status := enumValues(t, resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/SearchStatusValue"}))
|
||||
@@ -246,7 +246,7 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
t.Fatal("the contract has no AnonymousCardContent")
|
||||
}
|
||||
if got, want := propertyNames(card), []string{
|
||||
"categories", "experience_band", "pseudonym", "salary_compatibility", "self_assessment", "stack", "work_formats",
|
||||
"categories", "experience_band", "projects", "pseudonym", "salary_compatibility", "self_assessment", "stack", "work_formats",
|
||||
}; !slices.Equal(got, want) {
|
||||
t.Errorf("AnonymousCardContent properties = %v, want %v", got, want)
|
||||
}
|
||||
@@ -269,7 +269,7 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
allowed := slices.Concat([]string{
|
||||
"AnonymousCardContent", "CardCategory", "CardCategoryStrength", "CardSelfAssessment", "CardSelfAssessmentConfirmationStatus", "CandidateExperienceBand", "CandidateWorkFormat",
|
||||
"CandidateSalaryCompatibility", "CardField", "CardFieldSet", "PublicationState", "SpecializationCode",
|
||||
"GradeCode", "StackTag", "Timestamp", "CardPreview",
|
||||
"GradeCode", "StackTag", "Timestamp", "CardPreview", "CardProject",
|
||||
}, previewEvidenceSchemas)
|
||||
for _, name := range []string{"AnonymousCardContent", "CardPreview"} {
|
||||
for reached := range reachableSchemas(index, mustJSONValue(t, spec.Components.Schemas[name])) {
|
||||
@@ -323,7 +323,7 @@ func TestAnonymousCardReachesNoProfileOrContactSchema(t *testing.T) {
|
||||
slices.Contains([]string{
|
||||
"AnonymousCardContent", "CardCategory", "CardCategoryStrength", "CardSelfAssessment",
|
||||
"CardSelfAssessmentConfirmationStatus", "CandidateExperienceBand", "CandidateWorkFormat",
|
||||
"CandidateSalaryCompatibility",
|
||||
"CandidateSalaryCompatibility", "CardProject",
|
||||
}, reached) {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -106,7 +106,7 @@ func TestCandidateProfileSeparatesSelfAssessedGradeFromConfirmedCategory(t *test
|
||||
t.Error("the profile does not state confirmed categories apart from the claims")
|
||||
}
|
||||
update := resolveSchema(t, spec, &ogen.Schema{Ref: "#/components/schemas/CandidateProfileUpdate"})
|
||||
wantUpdate := []string{"confirmed_parallel_periods", "contacts", "expected_version", "experience", "full_name", "roles", "soft_skills", "stack", "terms"}
|
||||
wantUpdate := []string{"confirmed_parallel_periods", "contacts", "expected_version", "experience", "full_name", "projects", "roles", "soft_skills", "stack", "terms"}
|
||||
if got := propertyNames(update); !slices.Equal(got, wantUpdate) {
|
||||
t.Errorf("CandidateProfileUpdate properties = %v, want %v", got, wantUpdate)
|
||||
}
|
||||
|
||||
@@ -128,6 +128,11 @@ var definitions = map[api.ProblemCode]definition{
|
||||
title: "Operation not implemented",
|
||||
detail: "This operation is not available yet.",
|
||||
},
|
||||
api.ProblemCodeServiceUnavailable: {
|
||||
status: http.StatusServiceUnavailable,
|
||||
title: "Service unavailable",
|
||||
detail: "The service cannot serve the request now. Retry later.",
|
||||
},
|
||||
}
|
||||
|
||||
// New returns the problem response for code with its fixed status, title,
|
||||
|
||||
@@ -219,6 +219,7 @@ func matchConfirmedCandidate(entry matching.Entry) api.MatchConfirmedCandidate {
|
||||
ConfirmationStatus: api.MatchConfirmedCandidateConfirmationStatusConfirmed,
|
||||
PublicContext: matchPublicContext(entry.PublicContext),
|
||||
EvidenceSummary: matchEvidenceSummary(entry.EvidenceSummary),
|
||||
SemanticEvidence: matchSemanticEvidence(entry.SemanticEvidence),
|
||||
UnknownFlags: matchUnknownFlags(entry.UnknownFlags),
|
||||
}
|
||||
candidate.DeclaredGrade = matchDeclaredGrade(entry.DeclaredGrade)
|
||||
@@ -251,6 +252,7 @@ func matchUnconfirmedCandidate(entry matching.Entry) api.MatchUnconfirmedCandida
|
||||
DeclaredGrade: matchDeclaredGrade(entry.DeclaredGrade),
|
||||
PublicContext: matchPublicContext(entry.PublicContext),
|
||||
EvidenceSummary: matchEvidenceSummary(entry.EvidenceSummary),
|
||||
SemanticEvidence: matchSemanticEvidence(entry.SemanticEvidence),
|
||||
Components: api.MatchUnconfirmedComponents{Fit: entry.Components.Fit, Coverage: entry.Components.Coverage},
|
||||
UnknownFlags: matchUnknownFlags(entry.UnknownFlags),
|
||||
}
|
||||
@@ -300,6 +302,24 @@ func matchEvidenceSummary(items []matching.EvidenceItem) api.MatchEvidenceSummar
|
||||
return summary
|
||||
}
|
||||
|
||||
// matchSemanticEvidence maps the computed explanation. The list is never
|
||||
// null, so a client tells "nothing to explain" from a missing field.
|
||||
func matchSemanticEvidence(items []matching.SemanticEvidence) api.MatchSemanticEvidenceList {
|
||||
evidence := make(api.MatchSemanticEvidenceList, 0, len(items))
|
||||
for _, item := range items {
|
||||
title := api.NilString{Null: true}
|
||||
if item.ProjectTitle != nil {
|
||||
title = api.NewNilString(*item.ProjectTitle)
|
||||
}
|
||||
evidence = append(evidence, api.MatchSemanticEvidence{
|
||||
RequirementKind: api.MatchRequirementKind(item.RequirementKind), RequirementText: item.RequirementText,
|
||||
ItemKind: api.MatchSemanticItemKind(item.ItemKind), ProjectTitle: title,
|
||||
RepositoryVerified: item.RepositoryVerified, Similarity: api.MatchSimilarityBand(item.Similarity),
|
||||
})
|
||||
}
|
||||
return evidence
|
||||
}
|
||||
|
||||
func matchUnknownFlags(flags []matching.UnknownFlag) api.MatchUnknownFlags {
|
||||
response := make(api.MatchUnknownFlags, 0, len(flags))
|
||||
for _, flag := range flags {
|
||||
|
||||
@@ -112,7 +112,7 @@ func TestSearchOrganizationMatchesMapsANeedRequestAndKeepsUnconfirmedEntriesStri
|
||||
}
|
||||
want := `[{"candidate_handle":"` + handle + `","specialization":"network_engineer","confirmation_status":"unconfirmed","declared_grade":"junior",` +
|
||||
`"category":null,"strength":null,"public_context":{"stack":null,"experience_band":null,"work_formats":null,"salary_compatibility":null},` +
|
||||
`"evidence_summary":[{"code":"declared_grade","state":"declared_only"}],"components":{"fit":0.3125,"coverage":0.25},` +
|
||||
`"evidence_summary":[{"code":"declared_grade","state":"declared_only"}],"semantic_evidence":[],"components":{"fit":0.3125,"coverage":0.25},` +
|
||||
`"unknown_flags":[{"component":"assessment","reason":"no_confirmation_for_specialization"}]}]`
|
||||
if string(encoded) != want {
|
||||
t.Fatalf("unconfirmed entries = %s\nwant %s", encoded, want)
|
||||
|
||||
@@ -565,6 +565,19 @@ func anonymousCardResponse(view domain.AnonymousCandidateViewDTO) api.AnonymousC
|
||||
if view.SalaryCompatibility != nil {
|
||||
content.SalaryCompatibility.SetTo(api.CandidateSalaryCompatibility(*view.SalaryCompatibility))
|
||||
}
|
||||
for _, project := range view.Projects {
|
||||
description := api.NilString{Null: true}
|
||||
if project.Description != nil {
|
||||
description.SetTo(*project.Description)
|
||||
}
|
||||
stack := make([]api.StackTag, 0, len(project.Stack))
|
||||
for _, tag := range project.Stack {
|
||||
stack = append(stack, api.StackTag(tag))
|
||||
}
|
||||
content.Projects = append(content.Projects, api.CardProject{
|
||||
Title: project.Title, Description: description, Stack: stack, RepositoryVerified: project.RepositoryVerified,
|
||||
})
|
||||
}
|
||||
return content
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package v1
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"math"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
@@ -18,6 +19,7 @@ import (
|
||||
type ProfileOperations interface {
|
||||
GetMyProfile(ctx context.Context, userID uuid.UUID) (profile.View, error)
|
||||
SaveMyProfile(ctx context.Context, userID uuid.UUID, expectedVersion int64, input domain.CandidateProfileInput) (profile.View, error)
|
||||
RequestRepositoryChecks(ctx context.Context, userID uuid.UUID) (int, error)
|
||||
}
|
||||
|
||||
// ProfileHandler serves the candidate's own profile operations.
|
||||
@@ -46,6 +48,39 @@ func (handler *Handler) SaveMyProfile(ctx context.Context, request *api.Candidat
|
||||
return handler.profile.SaveMyProfile(ctx, request)
|
||||
}
|
||||
|
||||
func (handler *Handler) RequestMyRepositoryChecks(ctx context.Context) (api.RequestMyRepositoryChecksRes, error) {
|
||||
if handler.profile == nil {
|
||||
return handler.UnimplementedHandler.RequestMyRepositoryChecks(ctx)
|
||||
}
|
||||
return handler.profile.RequestMyRepositoryChecks(ctx)
|
||||
}
|
||||
|
||||
// RequestMyRepositoryChecks schedules new checks of the linked repositories.
|
||||
func (handler *ProfileHandler) RequestMyRepositoryChecks(ctx context.Context) (api.RequestMyRepositoryChecksRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
return (*api.RequestMyRepositoryChecksUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
}
|
||||
scheduled, err := handler.operations.RequestRepositoryChecks(ctx, principal.UserID)
|
||||
if err != nil {
|
||||
if limit, ok := errors.AsType[*profile.RepositoryCheckLimitError](err); ok {
|
||||
return problem.RateLimited(ctx, int32(math.Ceil(limit.RetryAfter.Seconds()))), nil
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, profile.ErrForbidden), errors.Is(err, profile.ErrEmailNotVerified):
|
||||
return (*api.RequestMyRepositoryChecksForbidden)(&problem.New(ctx, api.ProblemCodeForbidden).Response), nil
|
||||
case errors.Is(err, outbound.ErrUserNotFound):
|
||||
return (*api.RequestMyRepositoryChecksUnauthorized)(&problem.New(ctx, api.ProblemCodeUnauthenticated).Response), nil
|
||||
default:
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &api.ProfileRepositoryCheckRequestHeaders{
|
||||
CacheControl: api.CacheControlNoStoreNoStore,
|
||||
Response: api.ProfileRepositoryCheckRequest{Scheduled: int32(scheduled)}, //nolint:gosec // at most ten projects
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (handler *ProfileHandler) GetMyProfile(ctx context.Context) (api.GetMyProfileRes, error) {
|
||||
principal, ok := PrincipalFromContext(ctx)
|
||||
if !ok {
|
||||
@@ -167,6 +202,7 @@ func candidateProfileInput(request *api.CandidateProfileUpdate) domain.Candidate
|
||||
for _, item := range request.SoftSkills {
|
||||
input.SoftSkills = append(input.SoftSkills, domain.ProfileClaimInput[string]{Value: string(item.Skill), Status: domain.ProfileClaimStatus(item.Status)})
|
||||
}
|
||||
input.Projects = projectInputs(request.Projects)
|
||||
if value, ok := request.Terms.Location.Get(); ok {
|
||||
input.Location = profileStringInput(string(value.Value), value.Status)
|
||||
}
|
||||
@@ -277,6 +313,7 @@ func candidateProfileResponse(view profile.View) api.CandidateProfile {
|
||||
Skill: api.ProfileSoftSkill(item.Value()), Status: api.ProfileItemStatus(item.Status()), Source: profileClaimSourceResponse(item.Source()),
|
||||
})
|
||||
}
|
||||
response.Projects = projectResponses(content, view.RepositoryChecks)
|
||||
response.Terms = candidateProfileTerms(content)
|
||||
updatedAt := api.NilTimestamp{}
|
||||
if saved.UpdatedAt().IsZero() {
|
||||
@@ -289,6 +326,75 @@ func candidateProfileResponse(view profile.View) api.CandidateProfile {
|
||||
return response
|
||||
}
|
||||
|
||||
// projectInputs maps the request projects. An absent list keeps the stored
|
||||
// projects and maps to nil; an empty one clears them.
|
||||
func projectInputs(items []api.ProfileProjectItemInput) *[]domain.ProfileClaimInput[domain.ProfileProject] {
|
||||
if items == nil {
|
||||
return nil
|
||||
}
|
||||
projects := make([]domain.ProfileClaimInput[domain.ProfileProject], 0, len(items))
|
||||
for _, item := range items {
|
||||
description := ""
|
||||
if value, ok := item.Description.Get(); ok {
|
||||
description = string(value)
|
||||
}
|
||||
repository := ""
|
||||
if value, ok := item.RepositoryURL.Get(); ok {
|
||||
repository = string(value)
|
||||
}
|
||||
stack := make([]string, 0, len(item.Stack))
|
||||
for _, tag := range item.Stack {
|
||||
stack = append(stack, string(tag))
|
||||
}
|
||||
projects = append(projects, domain.ProfileClaimInput[domain.ProfileProject]{
|
||||
Value: domain.NewProfileProject(string(item.Title), description, stack, repository),
|
||||
Status: domain.ProfileClaimStatus(item.Status),
|
||||
})
|
||||
}
|
||||
return &projects
|
||||
}
|
||||
|
||||
func projectResponses(content domain.CandidateProfileContent, checks map[string]outbound.RepositoryCheck) []api.ProfileProjectItem {
|
||||
projects := make([]api.ProfileProjectItem, 0, len(content.Projects()))
|
||||
for _, item := range content.Projects() {
|
||||
projects = append(projects, profileProjectResponse(item, checks))
|
||||
}
|
||||
return projects
|
||||
}
|
||||
|
||||
// profileProjectResponse maps one project with the state of its repository
|
||||
// check. A linked repository without a stored check is pending.
|
||||
func profileProjectResponse(item domain.ProfileClaim[domain.ProfileProject], checks map[string]outbound.RepositoryCheck) api.ProfileProjectItem {
|
||||
value := item.Value()
|
||||
description := api.NilProfileProjectDescription{Null: true}
|
||||
if value.Description != "" {
|
||||
description.SetTo(api.ProfileProjectDescription(value.Description))
|
||||
}
|
||||
stack := make(api.ProfileProjectStack, 0, len(value.StackTags()))
|
||||
for _, tag := range value.StackTags() {
|
||||
stack = append(stack, api.StackTag(tag))
|
||||
}
|
||||
project := api.ProfileProjectItem{
|
||||
Title: api.ProfileProjectTitle(value.Title), Description: description, Stack: stack,
|
||||
RepositoryURL: api.NilProfileRepositoryUrl{Null: true}, RepositoryCheck: api.NilProfileRepositoryCheck{Null: true},
|
||||
Status: api.ProfileItemStatus(item.Status()), Source: profileClaimSourceResponse(item.Source()),
|
||||
}
|
||||
repository, linked := value.Repository()
|
||||
if !linked {
|
||||
return project
|
||||
}
|
||||
project.RepositoryURL.SetTo(api.ProfileRepositoryUrl(repository.URL()))
|
||||
check := api.ProfileRepositoryCheck{State: api.ProfileRepositoryCheckStatePending, CheckedAt: api.NilTimestamp{Null: true}}
|
||||
if stored, ok := checks[repository.Key()]; ok {
|
||||
check.State = api.ProfileRepositoryCheckState(stored.State)
|
||||
if !stored.CheckedAt.IsZero() {
|
||||
check.CheckedAt.SetTo(api.Timestamp(stored.CheckedAt))
|
||||
}
|
||||
}
|
||||
project.RepositoryCheck.SetTo(check)
|
||||
return project
|
||||
}
|
||||
|
||||
// confirmedCategoriesResponse maps the categories in their stored order. The
|
||||
// result is never nil, so a profile without categories encodes as an empty list.
|
||||
func confirmedCategoriesResponse(categories []domain.CandidateAssessmentCategory) []api.ProfileConfirmedCategory {
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
// Package github reads public repository metadata from the public GitHub
|
||||
// REST API. It is SSRF-safe by construction: the only origin it contacts is
|
||||
// https://api.github.com, a repository coordinate is validated by the domain
|
||||
// before it becomes a path, and a redirect to any other origin is refused.
|
||||
package github
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
// apiOrigin is the only origin the fetcher ever contacts.
|
||||
apiOrigin = "https://api.github.com"
|
||||
apiVersion = "2022-11-28"
|
||||
userAgent = "lincodex-repository-check"
|
||||
// Response caps: a repository document is a few KiB, the language map
|
||||
// smaller; a README is read only up to its excerpt budget.
|
||||
maxMetadataBytes = 1 << 20
|
||||
maxReadmeBytes = 64 << 10
|
||||
// maxRedirects bounds same-origin redirects, such as a renamed repository.
|
||||
maxRedirects = 3
|
||||
// The stored bounds of candidate_project_repositories.
|
||||
maxDescriptionRunes = 1000
|
||||
maxReadmeRunes = 4000
|
||||
maxTopics = 20
|
||||
// maxLanguages keeps the main languages by size.
|
||||
maxLanguages = 3
|
||||
// Rate limit waits are clamped, so a wrong header cannot stall a check
|
||||
// for days or make it spin.
|
||||
minRateLimitWait = time.Minute
|
||||
maxRateLimitWait = time.Hour
|
||||
)
|
||||
|
||||
// Fetcher implements outbound.RepositoryMetadataFetcher.
|
||||
type Fetcher struct {
|
||||
client *http.Client
|
||||
origin string
|
||||
token string
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
var _ outbound.RepositoryMetadataFetcher = (*Fetcher)(nil)
|
||||
|
||||
// NewFetcher builds a fetcher for api.github.com. token is optional; it is
|
||||
// sent only to that origin and never logged.
|
||||
func NewFetcher(timeout time.Duration, token string, clock func() time.Time) (*Fetcher, error) {
|
||||
return newFetcher(apiOrigin, timeout, token, clock, &http.Transport{
|
||||
// No proxy from the environment: the request goes to GitHub directly.
|
||||
Proxy: nil,
|
||||
DialContext: (&net.Dialer{Timeout: timeout}).DialContext,
|
||||
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12},
|
||||
TLSHandshakeTimeout: timeout,
|
||||
ResponseHeaderTimeout: timeout,
|
||||
MaxIdleConns: 4,
|
||||
IdleConnTimeout: time.Minute,
|
||||
ForceAttemptHTTP2: true,
|
||||
})
|
||||
}
|
||||
|
||||
// newFetcher lets tests point the fetcher at an httptest server; production
|
||||
// code reaches it only through NewFetcher with the fixed origin.
|
||||
func newFetcher(origin string, timeout time.Duration, token string, clock func() time.Time, transport http.RoundTripper) (*Fetcher, error) {
|
||||
if timeout <= 0 || clock == nil || transport == nil {
|
||||
return nil, errors.New("github.newFetcher - timeout, clock, and transport must be set")
|
||||
}
|
||||
parsed, err := url.Parse(origin)
|
||||
if err != nil || parsed.Host == "" || parsed.Path != "" {
|
||||
return nil, errors.New("github.newFetcher - origin is invalid")
|
||||
}
|
||||
return &Fetcher{
|
||||
client: &http.Client{
|
||||
Timeout: timeout,
|
||||
Transport: transport,
|
||||
CheckRedirect: func(request *http.Request, via []*http.Request) error {
|
||||
if len(via) >= maxRedirects {
|
||||
return errors.New("too many redirects")
|
||||
}
|
||||
if request.URL.Scheme != parsed.Scheme || request.URL.Host != parsed.Host {
|
||||
return errors.New("redirect to another origin")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
},
|
||||
origin: parsed.Scheme + "://" + parsed.Host,
|
||||
token: token,
|
||||
clock: clock,
|
||||
}, nil
|
||||
}
|
||||
|
||||
type repositoryDocument struct {
|
||||
ID int64 `json:"id"`
|
||||
Private bool `json:"private"`
|
||||
Visibility string `json:"visibility"`
|
||||
Description *string `json:"description"`
|
||||
Topics []string `json:"topics"`
|
||||
}
|
||||
|
||||
// Fetch reads the repository, its languages, and its README. A repository
|
||||
// that does not exist or is not public is Found=false with no metadata.
|
||||
func (fetcher *Fetcher) Fetch(
|
||||
ctx context.Context, repository domain.GitHubRepository, previous outbound.RepositoryCheck,
|
||||
) (outbound.RepositoryFetch, error) {
|
||||
if repository.IsZero() {
|
||||
return outbound.RepositoryFetch{}, fmt.Errorf("github.Fetcher.Fetch - repository is not set: %w", domain.ErrInvalidGitHubRepository)
|
||||
}
|
||||
base := "/repos/" + url.PathEscape(repository.Owner()) + "/" + url.PathEscape(repository.Name())
|
||||
repositoryETag := ""
|
||||
if previous.State == outbound.RepositoryCheckVerified {
|
||||
repositoryETag = previous.RepositoryETag
|
||||
}
|
||||
response, err := fetcher.get(ctx, base, "application/vnd.github+json", repositoryETag, maxMetadataBytes)
|
||||
if err != nil {
|
||||
return outbound.RepositoryFetch{}, err
|
||||
}
|
||||
switch {
|
||||
case response.status == http.StatusNotModified && repositoryETag != "":
|
||||
return outbound.RepositoryFetch{
|
||||
Found: true, NotModified: true, GitHubID: previous.GitHubID, Evidence: previous.Evidence,
|
||||
RepositoryETag: previous.RepositoryETag, ReadmeETag: previous.ReadmeETag,
|
||||
}, nil
|
||||
case response.status == http.StatusNotFound || response.status == http.StatusGone ||
|
||||
response.status == http.StatusUnavailableForLegalReasons:
|
||||
return outbound.RepositoryFetch{Found: false}, nil
|
||||
case response.status != http.StatusOK:
|
||||
return outbound.RepositoryFetch{}, fetcher.statusError(response)
|
||||
}
|
||||
return fetcher.publicRepository(ctx, base, response)
|
||||
}
|
||||
|
||||
// publicRepository reads the metadata of a repository document that GitHub
|
||||
// returned: a private or internal one is not found, a public one gets its
|
||||
// languages and README.
|
||||
func (fetcher *Fetcher) publicRepository(ctx context.Context, base string, response fetched) (outbound.RepositoryFetch, error) {
|
||||
var document repositoryDocument
|
||||
if err := json.Unmarshal(response.body, &document); err != nil || document.ID <= 0 {
|
||||
return outbound.RepositoryFetch{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureInvalidResponse}
|
||||
}
|
||||
if document.Private || (document.Visibility != "" && document.Visibility != "public") {
|
||||
return outbound.RepositoryFetch{Found: false}, nil
|
||||
}
|
||||
languages, err := fetcher.languages(ctx, base)
|
||||
if err != nil {
|
||||
return outbound.RepositoryFetch{}, err
|
||||
}
|
||||
readme, readmeETag, err := fetcher.readme(ctx, base)
|
||||
if err != nil {
|
||||
return outbound.RepositoryFetch{}, err
|
||||
}
|
||||
description := ""
|
||||
if document.Description != nil {
|
||||
description = truncate(plainLine(*document.Description), maxDescriptionRunes)
|
||||
}
|
||||
return outbound.RepositoryFetch{
|
||||
Found: true, GitHubID: document.ID, RepositoryETag: boundedETag(response.etag), ReadmeETag: readmeETag,
|
||||
Evidence: domain.RepositoryEvidence{
|
||||
Description: description, Topics: cleanTopics(document.Topics), Languages: languages, ReadmeExcerpt: readme,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (fetcher *Fetcher) languages(ctx context.Context, base string) ([]string, error) {
|
||||
response, err := fetcher.get(ctx, base+"/languages", "application/vnd.github+json", "", maxMetadataBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if response.status == http.StatusNotFound {
|
||||
return []string{}, nil
|
||||
}
|
||||
if response.status != http.StatusOK {
|
||||
return nil, fetcher.statusError(response)
|
||||
}
|
||||
var sizes map[string]int64
|
||||
if err := json.Unmarshal(response.body, &sizes); err != nil {
|
||||
return nil, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureInvalidResponse}
|
||||
}
|
||||
type language struct {
|
||||
name string
|
||||
bytes int64
|
||||
}
|
||||
var ordered []language
|
||||
for name, size := range sizes {
|
||||
if clean := plainLine(name); clean != "" && utf8.RuneCountInString(clean) <= 50 {
|
||||
ordered = append(ordered, language{name: clean, bytes: size})
|
||||
}
|
||||
}
|
||||
slices.SortFunc(ordered, func(left, right language) int {
|
||||
return cmp.Or(cmp.Compare(right.bytes, left.bytes), strings.Compare(left.name, right.name))
|
||||
})
|
||||
names := make([]string, 0, maxLanguages)
|
||||
for _, item := range ordered[:min(len(ordered), maxLanguages)] {
|
||||
names = append(names, item.name)
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func (fetcher *Fetcher) readme(ctx context.Context, base string) (string, string, error) {
|
||||
response, err := fetcher.get(ctx, base+"/readme", "application/vnd.github.raw+json", "", maxReadmeBytes)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
if response.status == http.StatusNotFound {
|
||||
return "", "", nil
|
||||
}
|
||||
if response.status != http.StatusOK {
|
||||
return "", "", fetcher.statusError(response)
|
||||
}
|
||||
// A cut body may end inside a multi-byte character; invalid bytes are
|
||||
// dropped instead of failing the check.
|
||||
text := strings.ToValidUTF8(string(response.body), "")
|
||||
return truncate(MarkdownToText(text), maxReadmeRunes), boundedETag(response.etag), nil
|
||||
}
|
||||
|
||||
type fetched struct {
|
||||
status int
|
||||
etag string
|
||||
body []byte
|
||||
headers http.Header
|
||||
}
|
||||
|
||||
func (fetcher *Fetcher) get(ctx context.Context, path, accept, etag string, limit int64) (fetched, error) {
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, fetcher.origin+path, nil)
|
||||
if err != nil {
|
||||
return fetched{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureNetwork}
|
||||
}
|
||||
request.Header.Set("Accept", accept)
|
||||
request.Header.Set("User-Agent", userAgent)
|
||||
request.Header.Set("X-GitHub-Api-Version", apiVersion)
|
||||
if etag != "" {
|
||||
request.Header.Set("If-None-Match", etag)
|
||||
}
|
||||
if fetcher.token != "" {
|
||||
request.Header.Set("Authorization", "Bearer "+fetcher.token)
|
||||
}
|
||||
response, err := fetcher.client.Do(request)
|
||||
if err != nil {
|
||||
// The error can carry the URL; only the class leaves this function.
|
||||
return fetched{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureNetwork}
|
||||
}
|
||||
defer func() { _ = response.Body.Close() }()
|
||||
body, err := io.ReadAll(io.LimitReader(response.Body, limit))
|
||||
if err != nil {
|
||||
return fetched{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureNetwork}
|
||||
}
|
||||
return fetched{status: response.StatusCode, etag: response.Header.Get("ETag"), body: body, headers: response.Header}, nil
|
||||
}
|
||||
|
||||
// statusError classifies an unexpected status. GitHub reports an exhausted
|
||||
// rate limit as 403 or 429 with x-ratelimit-remaining 0 or Retry-After.
|
||||
func (fetcher *Fetcher) statusError(response fetched) error {
|
||||
limited := response.status == http.StatusTooManyRequests ||
|
||||
(response.status == http.StatusForbidden &&
|
||||
(response.headers.Get("X-RateLimit-Remaining") == "0" || response.headers.Get("Retry-After") != ""))
|
||||
switch {
|
||||
case limited:
|
||||
return &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureRateLimited, RetryAfter: fetcher.rateLimitWait(response.headers)}
|
||||
case response.status >= http.StatusInternalServerError:
|
||||
return &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureServerError}
|
||||
default:
|
||||
return &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureInvalidResponse}
|
||||
}
|
||||
}
|
||||
|
||||
func (fetcher *Fetcher) rateLimitWait(headers http.Header) time.Duration {
|
||||
wait := minRateLimitWait
|
||||
if seconds, err := strconv.ParseInt(headers.Get("Retry-After"), 10, 64); err == nil && seconds > 0 {
|
||||
wait = time.Duration(seconds) * time.Second
|
||||
} else if reset, err := strconv.ParseInt(headers.Get("X-RateLimit-Reset"), 10, 64); err == nil {
|
||||
wait = time.Unix(reset, 0).Sub(fetcher.clock())
|
||||
}
|
||||
return min(max(wait, minRateLimitWait), maxRateLimitWait)
|
||||
}
|
||||
|
||||
func boundedETag(etag string) string {
|
||||
if etag == "" || len(etag) > 200 || strings.ContainsFunc(etag, func(character rune) bool { return character < 0x20 || character > 0x7e }) {
|
||||
return ""
|
||||
}
|
||||
return etag
|
||||
}
|
||||
|
||||
func cleanTopics(topics []string) []string {
|
||||
cleaned := make([]string, 0, min(len(topics), maxTopics))
|
||||
for _, topic := range topics {
|
||||
if len(cleaned) == maxTopics {
|
||||
break
|
||||
}
|
||||
if clean := plainLine(topic); clean != "" && utf8.RuneCountInString(clean) <= 50 {
|
||||
cleaned = append(cleaned, clean)
|
||||
}
|
||||
}
|
||||
return cleaned
|
||||
}
|
||||
|
||||
// plainLine keeps printable text on one line.
|
||||
func plainLine(value string) string {
|
||||
value = strings.Map(func(character rune) rune {
|
||||
if character < 0x20 || character == 0x7f || character == '
' || character == '
' {
|
||||
return ' '
|
||||
}
|
||||
return character
|
||||
}, value)
|
||||
return strings.Join(strings.Fields(value), " ")
|
||||
}
|
||||
|
||||
func truncate(value string, limit int) string {
|
||||
if utf8.RuneCountInString(value) <= limit {
|
||||
return value
|
||||
}
|
||||
return strings.TrimSpace(string([]rune(value)[:limit]))
|
||||
}
|
||||
|
||||
var (
|
||||
fencedCodePattern = regexp.MustCompile("(?s)```.*?(```|$)|~~~.*?(~~~|$)")
|
||||
htmlCommentPatter = regexp.MustCompile(`(?s)<!--.*?-->`)
|
||||
htmlTagPattern = regexp.MustCompile(`(?s)<[^>]{0,500}>`)
|
||||
imagePattern = regexp.MustCompile(`!\[[^\]]*\]\([^)]*\)`)
|
||||
linkPattern = regexp.MustCompile(`\[([^\]]*)\]\([^)]*\)`)
|
||||
referencePattern = regexp.MustCompile(`(?m)^\s*\[[^\]]+\]:\s*\S+.*$`)
|
||||
urlPattern = regexp.MustCompile(`https?://\S+`)
|
||||
headingPattern = regexp.MustCompile(`(?m)^\s{0,3}#{1,6}\s*`)
|
||||
listPattern = regexp.MustCompile(`(?m)^\s*(?:[-*+]|\d+[.)])\s+`)
|
||||
quotePattern = regexp.MustCompile(`(?m)^\s*>\s?`)
|
||||
emphasisPattern = regexp.MustCompile("[*_`~|]+")
|
||||
rulePattern = regexp.MustCompile(`(?m)^\s*[-=*_]{3,}\s*$`)
|
||||
)
|
||||
|
||||
// MarkdownToText turns a README into plain text for ranking: code blocks,
|
||||
// HTML, images, link targets, and bare URLs are removed and the markup
|
||||
// characters are dropped. The result is never rendered.
|
||||
func MarkdownToText(markdown string) string {
|
||||
text := strings.ReplaceAll(markdown, "\r\n", "\n")
|
||||
for _, step := range []struct {
|
||||
pattern *regexp.Regexp
|
||||
replacement string
|
||||
}{
|
||||
{fencedCodePattern, " "}, {htmlCommentPatter, " "}, {imagePattern, " "}, {linkPattern, "$1"},
|
||||
{referencePattern, " "}, {htmlTagPattern, " "}, {urlPattern, " "}, {rulePattern, " "},
|
||||
{headingPattern, ""}, {listPattern, ""}, {quotePattern, ""}, {emphasisPattern, " "},
|
||||
} {
|
||||
text = step.pattern.ReplaceAllString(text, step.replacement)
|
||||
}
|
||||
return plainLine(text)
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
package github
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var testNow = time.Date(2026, 10, 11, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
type recordedRequest struct {
|
||||
path, authorization, accept, ifNoneMatch string
|
||||
}
|
||||
|
||||
type fakeGitHub struct {
|
||||
mutex sync.Mutex
|
||||
requests []recordedRequest
|
||||
handler func(writer http.ResponseWriter, request *http.Request)
|
||||
}
|
||||
|
||||
func (fake *fakeGitHub) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
||||
fake.mutex.Lock()
|
||||
fake.requests = append(fake.requests, recordedRequest{
|
||||
path: request.URL.EscapedPath(), authorization: request.Header.Get("Authorization"),
|
||||
accept: request.Header.Get("Accept"), ifNoneMatch: request.Header.Get("If-None-Match"),
|
||||
})
|
||||
fake.mutex.Unlock()
|
||||
fake.handler(writer, request)
|
||||
}
|
||||
|
||||
func publicRepository(writer http.ResponseWriter, request *http.Request) {
|
||||
switch request.URL.Path {
|
||||
case "/repos/Example/ledger":
|
||||
writer.Header().Set("ETag", `"repo-1"`)
|
||||
_, _ = writer.Write([]byte(`{"id":7,"private":false,"visibility":"public","description":"Payments\nledger","topics":["payments","go"],"language":"Go"}`))
|
||||
case "/repos/Example/ledger/languages":
|
||||
_, _ = writer.Write([]byte(`{"Shell":10,"Go":5000,"Python":900,"Makefile":5}`))
|
||||
case "/repos/Example/ledger/readme":
|
||||
writer.Header().Set("ETag", `"readme-1"`)
|
||||
_, _ = writer.Write([]byte("# Ledger\n\nIdempotent [callbacks](https://example.test/x) with `outbox`.\n\n```sh\nmake run\n```\n<img src=x onerror=alert(1)>"))
|
||||
default:
|
||||
http.NotFound(writer, request)
|
||||
}
|
||||
}
|
||||
|
||||
func newTestFetcher(t *testing.T, fake *fakeGitHub, token string) *Fetcher {
|
||||
t.Helper()
|
||||
server := httptest.NewTLSServer(fake)
|
||||
t.Cleanup(server.Close)
|
||||
fetcher, err := newFetcher(server.URL, time.Second, token, func() time.Time { return testNow }, server.Client().Transport)
|
||||
if err != nil {
|
||||
t.Fatalf("newFetcher() error = %v", err)
|
||||
}
|
||||
return fetcher
|
||||
}
|
||||
|
||||
func repository(t *testing.T, raw string) domain.GitHubRepository {
|
||||
t.Helper()
|
||||
parsed, err := domain.ParseGitHubRepositoryURL(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseGitHubRepositoryURL() error = %v", err)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func TestFetchReadsPublicMetadataAsPlainText(t *testing.T) {
|
||||
fake := &fakeGitHub{handler: publicRepository}
|
||||
fetcher := newTestFetcher(t, fake, "")
|
||||
result, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), outbound.RepositoryCheck{})
|
||||
if err != nil {
|
||||
t.Fatalf("Fetch() error = %v", err)
|
||||
}
|
||||
if !result.Found || result.GitHubID != 7 || result.RepositoryETag != `"repo-1"` || result.ReadmeETag != `"readme-1"` {
|
||||
t.Fatalf("result = %+v", result)
|
||||
}
|
||||
evidence := result.Evidence
|
||||
if evidence.Description != "Payments ledger" || strings.Join(evidence.Topics, ",") != "payments,go" ||
|
||||
strings.Join(evidence.Languages, ",") != "Go,Python,Shell" {
|
||||
t.Fatalf("evidence = %+v", evidence)
|
||||
}
|
||||
if evidence.ReadmeExcerpt != "Ledger Idempotent callbacks with outbox ." {
|
||||
t.Fatalf("readme = %q, want plain text without markup, links, code, or HTML", evidence.ReadmeExcerpt)
|
||||
}
|
||||
for _, request := range fake.requests {
|
||||
if request.authorization != "" {
|
||||
t.Fatalf("a request without a token sent Authorization %q", request.authorization)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchSendsTheTokenAndTheStoredETag(t *testing.T) {
|
||||
fake := &fakeGitHub{handler: func(writer http.ResponseWriter, request *http.Request) {
|
||||
if request.Header.Get("If-None-Match") == `"repo-1"` {
|
||||
writer.WriteHeader(http.StatusNotModified)
|
||||
return
|
||||
}
|
||||
publicRepository(writer, request)
|
||||
}}
|
||||
fetcher := newTestFetcher(t, fake, "secret-token")
|
||||
previous := outbound.RepositoryCheck{
|
||||
State: outbound.RepositoryCheckVerified, RepositoryETag: `"repo-1"`, GitHubID: 7,
|
||||
Evidence: domain.RepositoryEvidence{Description: "kept"},
|
||||
}
|
||||
result, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), previous)
|
||||
if err != nil || !result.NotModified || result.Evidence.Description != "kept" {
|
||||
t.Fatalf("Fetch(not modified) = %+v, %v", result, err)
|
||||
}
|
||||
if len(fake.requests) != 1 || fake.requests[0].authorization != "Bearer secret-token" || fake.requests[0].ifNoneMatch != `"repo-1"` {
|
||||
t.Fatalf("requests = %+v", fake.requests)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchTreatsMissingAndPrivateRepositoriesAsNotFound(t *testing.T) {
|
||||
for name, handler := range map[string]http.HandlerFunc{
|
||||
"missing": http.NotFound,
|
||||
"private": func(writer http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = writer.Write([]byte(`{"id":7,"private":true,"visibility":"private","description":"secret"}`))
|
||||
},
|
||||
"internal": func(writer http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = writer.Write([]byte(`{"id":7,"private":false,"visibility":"internal"}`))
|
||||
},
|
||||
} {
|
||||
fetcher := newTestFetcher(t, &fakeGitHub{handler: handler}, "")
|
||||
result, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), outbound.RepositoryCheck{})
|
||||
if err != nil || result.Found || result.Evidence.Description != "" {
|
||||
t.Errorf("%s: result = %+v, %v; want not found without metadata", name, result, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchClassifiesRateLimitsAndFailures(t *testing.T) {
|
||||
reset := strconv.FormatInt(testNow.Add(20*time.Minute).Unix(), 10)
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
write func(http.ResponseWriter)
|
||||
class outbound.RepositoryFailureClass
|
||||
wait time.Duration
|
||||
}{
|
||||
{"primary limit", func(writer http.ResponseWriter) {
|
||||
writer.Header().Set("X-RateLimit-Remaining", "0")
|
||||
writer.Header().Set("X-RateLimit-Reset", reset)
|
||||
writer.WriteHeader(http.StatusForbidden)
|
||||
}, outbound.RepositoryFailureRateLimited, 20 * time.Minute},
|
||||
{"secondary limit", func(writer http.ResponseWriter) {
|
||||
writer.Header().Set("Retry-After", "5")
|
||||
writer.WriteHeader(http.StatusTooManyRequests)
|
||||
}, outbound.RepositoryFailureRateLimited, minRateLimitWait},
|
||||
{"server error", func(writer http.ResponseWriter) { writer.WriteHeader(http.StatusBadGateway) }, outbound.RepositoryFailureServerError, 0},
|
||||
{"bad token", func(writer http.ResponseWriter) { writer.WriteHeader(http.StatusUnauthorized) }, outbound.RepositoryFailureInvalidResponse, 0},
|
||||
{"broken body", func(writer http.ResponseWriter) { _, _ = writer.Write([]byte(`{"id":`)) }, outbound.RepositoryFailureInvalidResponse, 0},
|
||||
} {
|
||||
fetcher := newTestFetcher(t, &fakeGitHub{handler: func(writer http.ResponseWriter, _ *http.Request) { test.write(writer) }}, "")
|
||||
_, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), outbound.RepositoryCheck{})
|
||||
var fetchError *outbound.RepositoryFetchError
|
||||
if !errors.As(err, &fetchError) || fetchError.Class != test.class || fetchError.RetryAfter != test.wait {
|
||||
t.Errorf("%s: error = %v, want class %s wait %s", test.name, err, test.class, test.wait)
|
||||
}
|
||||
if !errors.Is(err, outbound.ErrRepositoryFetchUnavailable) {
|
||||
t.Errorf("%s: error does not match ErrRepositoryFetchUnavailable", test.name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchFollowsOnlySameOriginRedirects(t *testing.T) {
|
||||
other := httptest.NewTLSServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
|
||||
t.Error("the fetcher followed a redirect to another origin")
|
||||
_, _ = writer.Write([]byte(`{"id":1}`))
|
||||
}))
|
||||
defer other.Close()
|
||||
fake := &fakeGitHub{}
|
||||
fake.handler = func(writer http.ResponseWriter, request *http.Request) {
|
||||
switch request.URL.Path {
|
||||
case "/repos/Example/renamed":
|
||||
http.Redirect(writer, request, "/repos/Example/ledger", http.StatusMovedPermanently)
|
||||
case "/repos/Example/escape":
|
||||
http.Redirect(writer, request, other.URL+"/repos/Example/ledger", http.StatusMovedPermanently)
|
||||
default:
|
||||
publicRepository(writer, request)
|
||||
}
|
||||
}
|
||||
fetcher := newTestFetcher(t, fake, "secret-token")
|
||||
if result, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/renamed"), outbound.RepositoryCheck{}); err != nil || !result.Found {
|
||||
t.Fatalf("same-origin redirect = %+v, %v", result, err)
|
||||
}
|
||||
_, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/escape"), outbound.RepositoryCheck{})
|
||||
var fetchError *outbound.RepositoryFetchError
|
||||
if !errors.As(err, &fetchError) || fetchError.Class != outbound.RepositoryFailureNetwork {
|
||||
t.Fatalf("cross-origin redirect error = %v, want a refused request", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFetchCapsTheBodiesItReads(t *testing.T) {
|
||||
huge := strings.Repeat("word ", maxReadmeBytes)
|
||||
fake := &fakeGitHub{handler: func(writer http.ResponseWriter, request *http.Request) {
|
||||
if request.URL.Path == "/repos/Example/ledger/readme" {
|
||||
_, _ = writer.Write([]byte(huge))
|
||||
return
|
||||
}
|
||||
publicRepository(writer, request)
|
||||
}}
|
||||
fetcher := newTestFetcher(t, fake, "")
|
||||
result, err := fetcher.Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), outbound.RepositoryCheck{})
|
||||
if err != nil {
|
||||
t.Fatalf("Fetch() error = %v", err)
|
||||
}
|
||||
if runes := len([]rune(result.Evidence.ReadmeExcerpt)); runes == 0 || runes > maxReadmeRunes {
|
||||
t.Fatalf("readme excerpt has %d runes, want at most %d", runes, maxReadmeRunes)
|
||||
}
|
||||
oversized := &fakeGitHub{handler: func(writer http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = writer.Write([]byte(`{"id":7,"description":"` + strings.Repeat("x", maxMetadataBytes) + `"}`))
|
||||
}}
|
||||
if _, err := newTestFetcher(t, oversized, "").Fetch(context.Background(), repository(t, "https://github.com/Example/ledger"), outbound.RepositoryCheck{}); err == nil {
|
||||
t.Fatal("a repository document over the cap was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewFetcherUsesOnlyTheGitHubOrigin(t *testing.T) {
|
||||
fetcher, err := NewFetcher(time.Second, "", time.Now)
|
||||
if err != nil || fetcher.origin != "https://api.github.com" {
|
||||
t.Fatalf("NewFetcher() origin = %q, %v", fetcher.origin, err)
|
||||
}
|
||||
if _, err := fetcher.Fetch(context.Background(), domain.GitHubRepository{}, outbound.RepositoryCheck{}); !errors.Is(err, domain.ErrInvalidGitHubRepository) {
|
||||
t.Fatalf("Fetch(zero repository) error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,8 @@ import (
|
||||
var regexMap = map[string]ogenregex.Regexp{
|
||||
"^(/([^~/]|~[01])*)*$": ogenregex.MustCompile("^(/([^~/]|~[01])*)*$"),
|
||||
"^[A-Za-z0-9._-]+$": ogenregex.MustCompile("^[A-Za-z0-9._-]+$"),
|
||||
"^[A-Za-z0-9._/-]+$": ogenregex.MustCompile("^[A-Za-z0-9._/-]+$"),
|
||||
"^[a-z0-9._-]+$": ogenregex.MustCompile("^[a-z0-9._-]+$"),
|
||||
"^[a-z][a-z0-9_]*$": ogenregex.MustCompile("^[a-z][a-z0-9_]*$"),
|
||||
}
|
||||
var (
|
||||
|
||||
@@ -27,6 +27,19 @@ func trimTrailingSlashes(u *url.URL) {
|
||||
|
||||
// Invoker invokes operations described by OpenAPI v3 specification.
|
||||
type Invoker interface {
|
||||
// CreateMLEmbeddings invokes CreateMLEmbeddings operation.
|
||||
//
|
||||
// Internal operation for the Go backend; it is not reachable from browsers and needs no credentials on
|
||||
// the private network. The request carries only text that the caller is allowed to process, and the
|
||||
// service never logs it.
|
||||
//
|
||||
// The service answers 503 service_unavailable until the model is loaded from the image and a warm-up
|
||||
// encode has finished; `/readyz` reports the same state. A request above the body limit answers 413,
|
||||
// and a request that breaks the schema, such as too many texts or a text over 8000 characters, or
|
||||
// names a model that the service does not serve, answers 400.
|
||||
//
|
||||
// POST /v1/embeddings
|
||||
CreateMLEmbeddings(ctx context.Context, request *EmbeddingRequest) (CreateMLEmbeddingsRes, error)
|
||||
// GetMLHealthz invokes GetMLHealthz operation.
|
||||
//
|
||||
// Check whether the ML process is responding.
|
||||
@@ -80,6 +93,96 @@ func (c *Client) requestURL(ctx context.Context) *url.URL {
|
||||
return u
|
||||
}
|
||||
|
||||
// CreateMLEmbeddings invokes CreateMLEmbeddings operation.
|
||||
//
|
||||
// Internal operation for the Go backend; it is not reachable from browsers and needs no credentials on
|
||||
// the private network. The request carries only text that the caller is allowed to process, and the
|
||||
// service never logs it.
|
||||
//
|
||||
// The service answers 503 service_unavailable until the model is loaded from the image and a warm-up
|
||||
// encode has finished; `/readyz` reports the same state. A request above the body limit answers 413,
|
||||
// and a request that breaks the schema, such as too many texts or a text over 8000 characters, or
|
||||
// names a model that the service does not serve, answers 400.
|
||||
//
|
||||
// POST /v1/embeddings
|
||||
func (c *Client) CreateMLEmbeddings(ctx context.Context, request *EmbeddingRequest) (CreateMLEmbeddingsRes, error) {
|
||||
res, err := c.sendCreateMLEmbeddings(ctx, request)
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (c *Client) sendCreateMLEmbeddings(ctx context.Context, request *EmbeddingRequest) (res CreateMLEmbeddingsRes, err error) {
|
||||
otelAttrs := []attribute.KeyValue{
|
||||
otelogen.OperationID("CreateMLEmbeddings"),
|
||||
semconv.HTTPRequestMethodKey.String("POST"),
|
||||
semconv.URLTemplateKey.String("/v1/embeddings"),
|
||||
}
|
||||
otelAttrs = append(otelAttrs, c.cfg.Attributes...)
|
||||
|
||||
// Run stopwatch.
|
||||
startTime := time.Now()
|
||||
defer func() {
|
||||
// Use floating point division here for higher precision (instead of Millisecond method).
|
||||
elapsedDuration := time.Since(startTime)
|
||||
c.duration.Record(ctx, float64(elapsedDuration)/float64(time.Millisecond), metric.WithAttributes(otelAttrs...))
|
||||
}()
|
||||
|
||||
// Increment request counter.
|
||||
c.requests.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
|
||||
|
||||
// Start a span for this request.
|
||||
ctx, span := c.cfg.Tracer.Start(ctx, CreateMLEmbeddingsOperation,
|
||||
trace.WithAttributes(otelAttrs...),
|
||||
clientSpanKind,
|
||||
)
|
||||
// Track stage for error reporting.
|
||||
var stage string
|
||||
defer func() {
|
||||
if err != nil {
|
||||
span.RecordError(err)
|
||||
span.SetStatus(codes.Error, stage)
|
||||
c.errors.Add(ctx, 1, metric.WithAttributes(otelAttrs...))
|
||||
}
|
||||
span.End()
|
||||
}()
|
||||
|
||||
stage = "BuildURL"
|
||||
u := uri.Clone(c.requestURL(ctx))
|
||||
var pathParts [1]string
|
||||
pathParts[0] = "/v1/embeddings"
|
||||
uri.AddPathParts(u, pathParts[:]...)
|
||||
|
||||
stage = "EncodeRequest"
|
||||
r, err := ht.NewRequest(ctx, "POST", u)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "create request")
|
||||
}
|
||||
if err := encodeCreateMLEmbeddingsRequest(request, r); err != nil {
|
||||
return res, errors.Wrap(err, "encode request")
|
||||
}
|
||||
|
||||
stage = "SendRequest"
|
||||
resp, err := c.cfg.Client.Do(r)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "do request")
|
||||
}
|
||||
body := resp.Body
|
||||
defer func() {
|
||||
// Drain the body to EOF before closing, so the underlying
|
||||
// connection can be reused by the Transport regardless of the
|
||||
// response status code. See https://github.com/ogen-go/ogen/issues/1670.
|
||||
_, _ = io.Copy(io.Discard, body)
|
||||
_ = body.Close()
|
||||
}()
|
||||
|
||||
stage = "DecodeResponse"
|
||||
result, err := decodeCreateMLEmbeddingsResponse(resp)
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "decode response")
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GetMLHealthz invokes GetMLHealthz operation.
|
||||
//
|
||||
// Check whether the ML process is responding.
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
package api
|
||||
|
||||
type CreateMLEmbeddingsRes interface {
|
||||
createMLEmbeddingsRes()
|
||||
}
|
||||
|
||||
type GetMLReadyzRes interface {
|
||||
getMLReadyzRes()
|
||||
}
|
||||
@@ -11,6 +11,576 @@ import (
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
// Encode encodes EmbeddingInputKind as json.
|
||||
func (s EmbeddingInputKind) Encode(e *jx.Encoder) {
|
||||
e.Str(string(s))
|
||||
}
|
||||
|
||||
// Decode decodes EmbeddingInputKind from json.
|
||||
func (s *EmbeddingInputKind) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode EmbeddingInputKind to nil")
|
||||
}
|
||||
v, err := d.StrBytes()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Try to use constant string.
|
||||
switch EmbeddingInputKind(v) {
|
||||
case EmbeddingInputKindQuery:
|
||||
*s = EmbeddingInputKindQuery
|
||||
case EmbeddingInputKindDocument:
|
||||
*s = EmbeddingInputKindDocument
|
||||
default:
|
||||
*s = EmbeddingInputKind(v)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s EmbeddingInputKind) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *EmbeddingInputKind) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode implements json.Marshaler.
|
||||
func (s *EmbeddingModel) Encode(e *jx.Encoder) {
|
||||
e.ObjStart()
|
||||
s.encodeFields(e)
|
||||
e.ObjEnd()
|
||||
}
|
||||
|
||||
// encodeFields encodes fields.
|
||||
func (s *EmbeddingModel) encodeFields(e *jx.Encoder) {
|
||||
{
|
||||
e.FieldStart("id")
|
||||
e.Str(s.ID)
|
||||
}
|
||||
{
|
||||
e.FieldStart("revision")
|
||||
e.Str(s.Revision)
|
||||
}
|
||||
{
|
||||
e.FieldStart("dimension")
|
||||
e.Int32(s.Dimension)
|
||||
}
|
||||
{
|
||||
e.FieldStart("max_tokens")
|
||||
e.Int32(s.MaxTokens)
|
||||
}
|
||||
{
|
||||
e.FieldStart("prompt_version")
|
||||
e.Str(s.PromptVersion)
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfEmbeddingModel = [5]string{
|
||||
0: "id",
|
||||
1: "revision",
|
||||
2: "dimension",
|
||||
3: "max_tokens",
|
||||
4: "prompt_version",
|
||||
}
|
||||
|
||||
// Decode decodes EmbeddingModel from json.
|
||||
func (s *EmbeddingModel) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode EmbeddingModel to nil")
|
||||
}
|
||||
var requiredBitSet [1]uint8
|
||||
|
||||
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
|
||||
switch string(k) {
|
||||
case "id":
|
||||
requiredBitSet[0] |= 1 << 0
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
s.ID = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"id\"")
|
||||
}
|
||||
case "revision":
|
||||
requiredBitSet[0] |= 1 << 1
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
s.Revision = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"revision\"")
|
||||
}
|
||||
case "dimension":
|
||||
requiredBitSet[0] |= 1 << 2
|
||||
if err := func() error {
|
||||
v, err := d.Int32()
|
||||
s.Dimension = int32(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"dimension\"")
|
||||
}
|
||||
case "max_tokens":
|
||||
requiredBitSet[0] |= 1 << 3
|
||||
if err := func() error {
|
||||
v, err := d.Int32()
|
||||
s.MaxTokens = int32(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"max_tokens\"")
|
||||
}
|
||||
case "prompt_version":
|
||||
requiredBitSet[0] |= 1 << 4
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
s.PromptVersion = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"prompt_version\"")
|
||||
}
|
||||
default:
|
||||
return errors.Errorf("unexpected field %q", k)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "decode EmbeddingModel")
|
||||
}
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00011111,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
//
|
||||
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
|
||||
// Bits of fields which would be set are actually bits of missed fields.
|
||||
missed := bits.OnesCount8(result)
|
||||
for bitN := 0; bitN < missed; bitN++ {
|
||||
bitIdx := bits.TrailingZeros8(result)
|
||||
fieldIdx := i*8 + bitIdx
|
||||
var name string
|
||||
if fieldIdx < len(jsonFieldsNameOfEmbeddingModel) {
|
||||
name = jsonFieldsNameOfEmbeddingModel[fieldIdx]
|
||||
} else {
|
||||
name = strconv.Itoa(fieldIdx)
|
||||
}
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: name,
|
||||
Error: validate.ErrFieldRequired,
|
||||
})
|
||||
// Reset bit.
|
||||
result &^= 1 << bitIdx
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *EmbeddingModel) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *EmbeddingModel) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode implements json.Marshaler.
|
||||
func (s *EmbeddingRequest) Encode(e *jx.Encoder) {
|
||||
e.ObjStart()
|
||||
s.encodeFields(e)
|
||||
e.ObjEnd()
|
||||
}
|
||||
|
||||
// encodeFields encodes fields.
|
||||
func (s *EmbeddingRequest) encodeFields(e *jx.Encoder) {
|
||||
{
|
||||
if s.Model.Set {
|
||||
e.FieldStart("model")
|
||||
s.Model.Encode(e)
|
||||
}
|
||||
}
|
||||
{
|
||||
e.FieldStart("kind")
|
||||
s.Kind.Encode(e)
|
||||
}
|
||||
{
|
||||
e.FieldStart("texts")
|
||||
e.ArrStart()
|
||||
for _, elem := range s.Texts {
|
||||
elem.Encode(e)
|
||||
}
|
||||
e.ArrEnd()
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfEmbeddingRequest = [3]string{
|
||||
0: "model",
|
||||
1: "kind",
|
||||
2: "texts",
|
||||
}
|
||||
|
||||
// Decode decodes EmbeddingRequest from json.
|
||||
func (s *EmbeddingRequest) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode EmbeddingRequest to nil")
|
||||
}
|
||||
var requiredBitSet [1]uint8
|
||||
|
||||
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
|
||||
switch string(k) {
|
||||
case "model":
|
||||
if err := func() error {
|
||||
s.Model.Reset()
|
||||
if err := s.Model.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"model\"")
|
||||
}
|
||||
case "kind":
|
||||
requiredBitSet[0] |= 1 << 1
|
||||
if err := func() error {
|
||||
if err := s.Kind.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"kind\"")
|
||||
}
|
||||
case "texts":
|
||||
requiredBitSet[0] |= 1 << 2
|
||||
if err := func() error {
|
||||
s.Texts = make([]EmbeddingText, 0)
|
||||
if err := d.Arr(func(d *jx.Decoder) error {
|
||||
var elem EmbeddingText
|
||||
if err := elem.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
s.Texts = append(s.Texts, elem)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"texts\"")
|
||||
}
|
||||
default:
|
||||
return errors.Errorf("unexpected field %q", k)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "decode EmbeddingRequest")
|
||||
}
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00000110,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
//
|
||||
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
|
||||
// Bits of fields which would be set are actually bits of missed fields.
|
||||
missed := bits.OnesCount8(result)
|
||||
for bitN := 0; bitN < missed; bitN++ {
|
||||
bitIdx := bits.TrailingZeros8(result)
|
||||
fieldIdx := i*8 + bitIdx
|
||||
var name string
|
||||
if fieldIdx < len(jsonFieldsNameOfEmbeddingRequest) {
|
||||
name = jsonFieldsNameOfEmbeddingRequest[fieldIdx]
|
||||
} else {
|
||||
name = strconv.Itoa(fieldIdx)
|
||||
}
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: name,
|
||||
Error: validate.ErrFieldRequired,
|
||||
})
|
||||
// Reset bit.
|
||||
result &^= 1 << bitIdx
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *EmbeddingRequest) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *EmbeddingRequest) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode implements json.Marshaler.
|
||||
func (s *EmbeddingResponse) Encode(e *jx.Encoder) {
|
||||
e.ObjStart()
|
||||
s.encodeFields(e)
|
||||
e.ObjEnd()
|
||||
}
|
||||
|
||||
// encodeFields encodes fields.
|
||||
func (s *EmbeddingResponse) encodeFields(e *jx.Encoder) {
|
||||
{
|
||||
e.FieldStart("model")
|
||||
s.Model.Encode(e)
|
||||
}
|
||||
{
|
||||
e.FieldStart("kind")
|
||||
s.Kind.Encode(e)
|
||||
}
|
||||
{
|
||||
e.FieldStart("vectors")
|
||||
e.ArrStart()
|
||||
for _, elem := range s.Vectors {
|
||||
elem.Encode(e)
|
||||
}
|
||||
e.ArrEnd()
|
||||
}
|
||||
}
|
||||
|
||||
var jsonFieldsNameOfEmbeddingResponse = [3]string{
|
||||
0: "model",
|
||||
1: "kind",
|
||||
2: "vectors",
|
||||
}
|
||||
|
||||
// Decode decodes EmbeddingResponse from json.
|
||||
func (s *EmbeddingResponse) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode EmbeddingResponse to nil")
|
||||
}
|
||||
var requiredBitSet [1]uint8
|
||||
|
||||
if err := d.ObjBytes(func(d *jx.Decoder, k []byte) error {
|
||||
switch string(k) {
|
||||
case "model":
|
||||
requiredBitSet[0] |= 1 << 0
|
||||
if err := func() error {
|
||||
if err := s.Model.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"model\"")
|
||||
}
|
||||
case "kind":
|
||||
requiredBitSet[0] |= 1 << 1
|
||||
if err := func() error {
|
||||
if err := s.Kind.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"kind\"")
|
||||
}
|
||||
case "vectors":
|
||||
requiredBitSet[0] |= 1 << 2
|
||||
if err := func() error {
|
||||
s.Vectors = make([]EmbeddingVector, 0)
|
||||
if err := d.Arr(func(d *jx.Decoder) error {
|
||||
var elem EmbeddingVector
|
||||
if err := elem.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
s.Vectors = append(s.Vectors, elem)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "decode field \"vectors\"")
|
||||
}
|
||||
default:
|
||||
return errors.Errorf("unexpected field %q", k)
|
||||
}
|
||||
return nil
|
||||
}); err != nil {
|
||||
return errors.Wrap(err, "decode EmbeddingResponse")
|
||||
}
|
||||
// Validate required fields.
|
||||
var failures []validate.FieldError
|
||||
for i, mask := range [1]uint8{
|
||||
0b00000111,
|
||||
} {
|
||||
if result := (requiredBitSet[i] & mask) ^ mask; result != 0 {
|
||||
// Mask only required fields and check equality to mask using XOR.
|
||||
//
|
||||
// If XOR result is not zero, result is not equal to expected, so some fields are missed.
|
||||
// Bits of fields which would be set are actually bits of missed fields.
|
||||
missed := bits.OnesCount8(result)
|
||||
for bitN := 0; bitN < missed; bitN++ {
|
||||
bitIdx := bits.TrailingZeros8(result)
|
||||
fieldIdx := i*8 + bitIdx
|
||||
var name string
|
||||
if fieldIdx < len(jsonFieldsNameOfEmbeddingResponse) {
|
||||
name = jsonFieldsNameOfEmbeddingResponse[fieldIdx]
|
||||
} else {
|
||||
name = strconv.Itoa(fieldIdx)
|
||||
}
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: name,
|
||||
Error: validate.ErrFieldRequired,
|
||||
})
|
||||
// Reset bit.
|
||||
result &^= 1 << bitIdx
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s *EmbeddingResponse) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *EmbeddingResponse) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode encodes EmbeddingText as json.
|
||||
func (s EmbeddingText) Encode(e *jx.Encoder) {
|
||||
unwrapped := string(s)
|
||||
|
||||
e.Str(unwrapped)
|
||||
}
|
||||
|
||||
// Decode decodes EmbeddingText from json.
|
||||
func (s *EmbeddingText) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode EmbeddingText to nil")
|
||||
}
|
||||
var unwrapped string
|
||||
if err := func() error {
|
||||
v, err := d.Str()
|
||||
unwrapped = string(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "alias")
|
||||
}
|
||||
*s = EmbeddingText(unwrapped)
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s EmbeddingText) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *EmbeddingText) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode encodes EmbeddingVector as json.
|
||||
func (s EmbeddingVector) Encode(e *jx.Encoder) {
|
||||
unwrapped := []float32(s)
|
||||
|
||||
e.ArrStart()
|
||||
for _, elem := range unwrapped {
|
||||
e.Float32(elem)
|
||||
}
|
||||
e.ArrEnd()
|
||||
}
|
||||
|
||||
// Decode decodes EmbeddingVector from json.
|
||||
func (s *EmbeddingVector) Decode(d *jx.Decoder) error {
|
||||
if s == nil {
|
||||
return errors.New("invalid: unable to decode EmbeddingVector to nil")
|
||||
}
|
||||
var unwrapped []float32
|
||||
if err := func() error {
|
||||
unwrapped = make([]float32, 0)
|
||||
if err := d.Arr(func(d *jx.Decoder) error {
|
||||
var elem float32
|
||||
v, err := d.Float32()
|
||||
elem = float32(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
unwrapped = append(unwrapped, elem)
|
||||
return nil
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return errors.Wrap(err, "alias")
|
||||
}
|
||||
*s = EmbeddingVector(unwrapped)
|
||||
return nil
|
||||
}
|
||||
|
||||
// MarshalJSON implements stdjson.Marshaler.
|
||||
func (s EmbeddingVector) MarshalJSON() ([]byte, error) {
|
||||
e := jx.Encoder{}
|
||||
s.Encode(&e)
|
||||
return e.Bytes(), nil
|
||||
}
|
||||
|
||||
// UnmarshalJSON implements stdjson.Unmarshaler.
|
||||
func (s *EmbeddingVector) UnmarshalJSON(data []byte) error {
|
||||
d := jx.DecodeBytes(data)
|
||||
return s.Decode(d)
|
||||
}
|
||||
|
||||
// Encode encodes GetMLReadyzOK as json.
|
||||
func (s *GetMLReadyzOK) Encode(e *jx.Encoder) {
|
||||
unwrapped := (*MLReadinessResponse)(s)
|
||||
@@ -668,6 +1238,8 @@ func (s *ProblemCode) Decode(d *jx.Decoder) error {
|
||||
*s = ProblemCodeInternal
|
||||
case ProblemCodeNotImplemented:
|
||||
*s = ProblemCodeNotImplemented
|
||||
case ProblemCodeServiceUnavailable:
|
||||
*s = ProblemCodeServiceUnavailable
|
||||
default:
|
||||
*s = ProblemCode(v)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ package api
|
||||
type OperationName = string
|
||||
|
||||
const (
|
||||
GetMLHealthzOperation OperationName = "GetMLHealthz"
|
||||
GetMLReadyzOperation OperationName = "GetMLReadyz"
|
||||
CreateMLEmbeddingsOperation OperationName = "CreateMLEmbeddings"
|
||||
GetMLHealthzOperation OperationName = "GetMLHealthz"
|
||||
GetMLReadyzOperation OperationName = "GetMLReadyz"
|
||||
)
|
||||
@@ -1,3 +1,25 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-faster/jx"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
)
|
||||
|
||||
func encodeCreateMLEmbeddingsRequest(
|
||||
req *EmbeddingRequest,
|
||||
r *http.Request,
|
||||
) error {
|
||||
const contentType = "application/json"
|
||||
e := new(jx.Encoder)
|
||||
{
|
||||
req.Encode(e)
|
||||
}
|
||||
encoded := e.Bytes()
|
||||
ht.SetBody(r, bytes.NewReader(encoded), contentType)
|
||||
return nil
|
||||
}
|
||||
@@ -13,6 +13,248 @@ import (
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
func decodeCreateMLEmbeddingsResponse(resp *http.Response) (res CreateMLEmbeddingsRes, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 200:
|
||||
// Code 200.
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response EmbeddingResponse
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
// Validate response.
|
||||
if err := func() error {
|
||||
if err := response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &response, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 400:
|
||||
// Code 400.
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/problem+json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Problem
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
// Validate response.
|
||||
if err := func() error {
|
||||
if err := response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &CreateMLEmbeddingsBadRequest{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 413:
|
||||
// Code 413.
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/problem+json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Problem
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
// Validate response.
|
||||
if err := func() error {
|
||||
if err := response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &CreateMLEmbeddingsRequestEntityTooLarge{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 503:
|
||||
// Code 503.
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/problem+json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Problem
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
// Validate response.
|
||||
if err := func() error {
|
||||
if err := response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &CreateMLEmbeddingsServiceUnavailable{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}
|
||||
// Convenient error response.
|
||||
defRes, err := func() (res *ProblemStatusCode, err error) {
|
||||
ct, _, err := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if err != nil {
|
||||
return res, errors.Wrap(err, "parse media type")
|
||||
}
|
||||
switch {
|
||||
case ct == "application/problem+json":
|
||||
buf, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
d := jx.DecodeBytes(buf)
|
||||
|
||||
var response Problem
|
||||
if err := func() error {
|
||||
if err := response.Decode(d); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Skip(); err != io.EOF {
|
||||
return errors.New("unexpected trailing data")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
err = &ogenerrors.DecodeBodyError{
|
||||
ContentType: ct,
|
||||
Body: buf,
|
||||
Err: err,
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
// Validate response.
|
||||
if err := func() error {
|
||||
if err := response.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return res, errors.Wrap(err, "validate")
|
||||
}
|
||||
return &ProblemStatusCode{
|
||||
StatusCode: resp.StatusCode,
|
||||
Response: response,
|
||||
}, nil
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
}()
|
||||
if err != nil {
|
||||
return res, errors.Wrapf(err, "default (code %d)", resp.StatusCode)
|
||||
}
|
||||
return res, errors.Wrap(defRes, "error")
|
||||
}
|
||||
|
||||
func decodeGetMLHealthzResponse(resp *http.Response) (res *MLHealthResponse, _ error) {
|
||||
switch resp.StatusCode {
|
||||
case 200:
|
||||
|
||||
@@ -12,6 +12,223 @@ func (s *ProblemStatusCode) Error() string {
|
||||
return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response)
|
||||
}
|
||||
|
||||
type CreateMLEmbeddingsBadRequest ProblemStatusCode
|
||||
|
||||
func (*CreateMLEmbeddingsBadRequest) createMLEmbeddingsRes() {}
|
||||
|
||||
type CreateMLEmbeddingsRequestEntityTooLarge ProblemStatusCode
|
||||
|
||||
func (*CreateMLEmbeddingsRequestEntityTooLarge) createMLEmbeddingsRes() {}
|
||||
|
||||
type CreateMLEmbeddingsServiceUnavailable ProblemStatusCode
|
||||
|
||||
func (*CreateMLEmbeddingsServiceUnavailable) createMLEmbeddingsRes() {}
|
||||
|
||||
// Side of the retrieval pair that the texts belong to. The service owns the prompt of each side, so
|
||||
// callers never send model instructions.
|
||||
//
|
||||
// - query: the side that searches, such as a hiring need or one requirement of it. The service
|
||||
// prepends the retrieval instruction of the model.
|
||||
// - document: the side that is searched, such as a candidate card or one item of it. The service adds
|
||||
// no prompt.
|
||||
//
|
||||
// Ref: #/components/schemas/EmbeddingInputKind
|
||||
type EmbeddingInputKind string
|
||||
|
||||
const (
|
||||
EmbeddingInputKindQuery EmbeddingInputKind = "query"
|
||||
EmbeddingInputKindDocument EmbeddingInputKind = "document"
|
||||
)
|
||||
|
||||
// AllValues returns all EmbeddingInputKind values.
|
||||
func (EmbeddingInputKind) AllValues() []EmbeddingInputKind {
|
||||
return []EmbeddingInputKind{
|
||||
EmbeddingInputKindQuery,
|
||||
EmbeddingInputKindDocument,
|
||||
}
|
||||
}
|
||||
|
||||
// MarshalText implements encoding.TextMarshaler.
|
||||
func (s EmbeddingInputKind) MarshalText() ([]byte, error) {
|
||||
switch s {
|
||||
case EmbeddingInputKindQuery:
|
||||
return []byte(s), nil
|
||||
case EmbeddingInputKindDocument:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalText implements encoding.TextUnmarshaler.
|
||||
func (s *EmbeddingInputKind) UnmarshalText(data []byte) error {
|
||||
switch EmbeddingInputKind(data) {
|
||||
case EmbeddingInputKindQuery:
|
||||
*s = EmbeddingInputKindQuery
|
||||
return nil
|
||||
case EmbeddingInputKindDocument:
|
||||
*s = EmbeddingInputKindDocument
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
}
|
||||
|
||||
// The model that produced the vectors. A caller stores these values with every vector and never
|
||||
// compares vectors of different models, revisions, or prompt versions.
|
||||
// Ref: #/components/schemas/EmbeddingModel
|
||||
type EmbeddingModel struct {
|
||||
// Model repository identifier, for example ai-sage/Giga-Embeddings-instruct-480M-0826.
|
||||
ID string `json:"id"`
|
||||
// Pinned revision of the weights, a commit hash for a published model.
|
||||
Revision string `json:"revision"`
|
||||
// Length of every vector.
|
||||
Dimension int32 `json:"dimension"`
|
||||
// Token limit after which a text is truncated.
|
||||
MaxTokens int32 `json:"max_tokens"`
|
||||
// Version of the prompt and pooling recipe of the service. A change of the query instruction or the
|
||||
// pooling changes it.
|
||||
PromptVersion string `json:"prompt_version"`
|
||||
}
|
||||
|
||||
// GetID returns the value of ID.
|
||||
func (s *EmbeddingModel) GetID() string {
|
||||
return s.ID
|
||||
}
|
||||
|
||||
// GetRevision returns the value of Revision.
|
||||
func (s *EmbeddingModel) GetRevision() string {
|
||||
return s.Revision
|
||||
}
|
||||
|
||||
// GetDimension returns the value of Dimension.
|
||||
func (s *EmbeddingModel) GetDimension() int32 {
|
||||
return s.Dimension
|
||||
}
|
||||
|
||||
// GetMaxTokens returns the value of MaxTokens.
|
||||
func (s *EmbeddingModel) GetMaxTokens() int32 {
|
||||
return s.MaxTokens
|
||||
}
|
||||
|
||||
// GetPromptVersion returns the value of PromptVersion.
|
||||
func (s *EmbeddingModel) GetPromptVersion() string {
|
||||
return s.PromptVersion
|
||||
}
|
||||
|
||||
// SetID sets the value of ID.
|
||||
func (s *EmbeddingModel) SetID(val string) {
|
||||
s.ID = val
|
||||
}
|
||||
|
||||
// SetRevision sets the value of Revision.
|
||||
func (s *EmbeddingModel) SetRevision(val string) {
|
||||
s.Revision = val
|
||||
}
|
||||
|
||||
// SetDimension sets the value of Dimension.
|
||||
func (s *EmbeddingModel) SetDimension(val int32) {
|
||||
s.Dimension = val
|
||||
}
|
||||
|
||||
// SetMaxTokens sets the value of MaxTokens.
|
||||
func (s *EmbeddingModel) SetMaxTokens(val int32) {
|
||||
s.MaxTokens = val
|
||||
}
|
||||
|
||||
// SetPromptVersion sets the value of PromptVersion.
|
||||
func (s *EmbeddingModel) SetPromptVersion(val string) {
|
||||
s.PromptVersion = val
|
||||
}
|
||||
|
||||
// Texts to encode in one call. The service encodes them in a fixed, deterministic way: texts are
|
||||
// ordered by length with the request position as the tie-breaker, encoded in micro-batches of the
|
||||
// configured size, and returned in request order. The same texts in the same request on the same image
|
||||
// and thread count give the same vectors.
|
||||
// Ref: #/components/schemas/EmbeddingRequest
|
||||
type EmbeddingRequest struct {
|
||||
// Identifier of the model to use, as `EmbeddingModel.id` reports it. Absent means the default model of
|
||||
// the service. A service may load several models, for example the members of an ensemble; a model it
|
||||
// does not serve answers 400 validation_failed with the pointer `/model`.
|
||||
Model OptString `json:"model"`
|
||||
Kind EmbeddingInputKind `json:"kind"`
|
||||
Texts []EmbeddingText `json:"texts"`
|
||||
}
|
||||
|
||||
// GetModel returns the value of Model.
|
||||
func (s *EmbeddingRequest) GetModel() OptString {
|
||||
return s.Model
|
||||
}
|
||||
|
||||
// GetKind returns the value of Kind.
|
||||
func (s *EmbeddingRequest) GetKind() EmbeddingInputKind {
|
||||
return s.Kind
|
||||
}
|
||||
|
||||
// GetTexts returns the value of Texts.
|
||||
func (s *EmbeddingRequest) GetTexts() []EmbeddingText {
|
||||
return s.Texts
|
||||
}
|
||||
|
||||
// SetModel sets the value of Model.
|
||||
func (s *EmbeddingRequest) SetModel(val OptString) {
|
||||
s.Model = val
|
||||
}
|
||||
|
||||
// SetKind sets the value of Kind.
|
||||
func (s *EmbeddingRequest) SetKind(val EmbeddingInputKind) {
|
||||
s.Kind = val
|
||||
}
|
||||
|
||||
// SetTexts sets the value of Texts.
|
||||
func (s *EmbeddingRequest) SetTexts(val []EmbeddingText) {
|
||||
s.Texts = val
|
||||
}
|
||||
|
||||
// Vectors in the order of the request texts.
|
||||
// Ref: #/components/schemas/EmbeddingResponse
|
||||
type EmbeddingResponse struct {
|
||||
Model EmbeddingModel `json:"model"`
|
||||
Kind EmbeddingInputKind `json:"kind"`
|
||||
Vectors []EmbeddingVector `json:"vectors"`
|
||||
}
|
||||
|
||||
// GetModel returns the value of Model.
|
||||
func (s *EmbeddingResponse) GetModel() EmbeddingModel {
|
||||
return s.Model
|
||||
}
|
||||
|
||||
// GetKind returns the value of Kind.
|
||||
func (s *EmbeddingResponse) GetKind() EmbeddingInputKind {
|
||||
return s.Kind
|
||||
}
|
||||
|
||||
// GetVectors returns the value of Vectors.
|
||||
func (s *EmbeddingResponse) GetVectors() []EmbeddingVector {
|
||||
return s.Vectors
|
||||
}
|
||||
|
||||
// SetModel sets the value of Model.
|
||||
func (s *EmbeddingResponse) SetModel(val EmbeddingModel) {
|
||||
s.Model = val
|
||||
}
|
||||
|
||||
// SetKind sets the value of Kind.
|
||||
func (s *EmbeddingResponse) SetKind(val EmbeddingInputKind) {
|
||||
s.Kind = val
|
||||
}
|
||||
|
||||
// SetVectors sets the value of Vectors.
|
||||
func (s *EmbeddingResponse) SetVectors(val []EmbeddingVector) {
|
||||
s.Vectors = val
|
||||
}
|
||||
|
||||
func (*EmbeddingResponse) createMLEmbeddingsRes() {}
|
||||
|
||||
type EmbeddingText string
|
||||
|
||||
type EmbeddingVector []float32
|
||||
|
||||
type GetMLReadyzOK MLReadinessResponse
|
||||
|
||||
func (*GetMLReadyzOK) getMLReadyzRes() {}
|
||||
@@ -297,6 +514,8 @@ func (s *Problem) SetErrors(val []ProblemFieldError) {
|
||||
// - rate_limited (429): too many requests; see Retry-After.
|
||||
// - internal (500): unexpected server error.
|
||||
// - not_implemented (501): the operation is in the contract but not implemented yet.
|
||||
// - service_unavailable (503): the service cannot serve the request now, for example while a model
|
||||
// loads; retry later.
|
||||
//
|
||||
// The enum keeps the public API codes so both contracts share one Problem shape. The identity codes
|
||||
// verification_token_invalid, verification_token_expired, invalid_credentials, email_not_verified, and
|
||||
@@ -325,6 +544,7 @@ const (
|
||||
ProblemCodeRateLimited ProblemCode = "rate_limited"
|
||||
ProblemCodeInternal ProblemCode = "internal"
|
||||
ProblemCodeNotImplemented ProblemCode = "not_implemented"
|
||||
ProblemCodeServiceUnavailable ProblemCode = "service_unavailable"
|
||||
)
|
||||
|
||||
// AllValues returns all ProblemCode values.
|
||||
@@ -350,6 +570,7 @@ func (ProblemCode) AllValues() []ProblemCode {
|
||||
ProblemCodeRateLimited,
|
||||
ProblemCodeInternal,
|
||||
ProblemCodeNotImplemented,
|
||||
ProblemCodeServiceUnavailable,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -396,6 +617,8 @@ func (s ProblemCode) MarshalText() ([]byte, error) {
|
||||
return []byte(s), nil
|
||||
case ProblemCodeNotImplemented:
|
||||
return []byte(s), nil
|
||||
case ProblemCodeServiceUnavailable:
|
||||
return []byte(s), nil
|
||||
default:
|
||||
return nil, errors.Errorf("invalid value: %q", s)
|
||||
}
|
||||
@@ -464,6 +687,9 @@ func (s *ProblemCode) UnmarshalText(data []byte) error {
|
||||
case ProblemCodeNotImplemented:
|
||||
*s = ProblemCodeNotImplemented
|
||||
return nil
|
||||
case ProblemCodeServiceUnavailable:
|
||||
*s = ProblemCodeServiceUnavailable
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %q", data)
|
||||
}
|
||||
|
||||
@@ -9,6 +9,376 @@ import (
|
||||
"github.com/ogen-go/ogen/validate"
|
||||
)
|
||||
|
||||
func (s *CreateMLEmbeddingsBadRequest) Validate() error {
|
||||
alias := (*ProblemStatusCode)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CreateMLEmbeddingsRequestEntityTooLarge) Validate() error {
|
||||
alias := (*ProblemStatusCode)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CreateMLEmbeddingsServiceUnavailable) Validate() error {
|
||||
alias := (*ProblemStatusCode)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s EmbeddingInputKind) Validate() error {
|
||||
switch s {
|
||||
case "query":
|
||||
return nil
|
||||
case "document":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *EmbeddingModel) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 200,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: regexMap["^[A-Za-z0-9._/-]+$"],
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(s.ID)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "id",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 64,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: regexMap["^[A-Za-z0-9._-]+$"],
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(s.Revision)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "revision",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.Int{
|
||||
MinSet: true,
|
||||
Min: 1,
|
||||
MaxSet: true,
|
||||
Max: 4096,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: 0,
|
||||
Pattern: nil,
|
||||
}).Validate(int64(s.Dimension)); err != nil {
|
||||
return errors.Wrap(err, "int")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "dimension",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.Int{
|
||||
MinSet: true,
|
||||
Min: 1,
|
||||
MaxSet: true,
|
||||
Max: 32768,
|
||||
MinExclusive: false,
|
||||
MaxExclusive: false,
|
||||
MultipleOfSet: false,
|
||||
MultipleOf: 0,
|
||||
Pattern: nil,
|
||||
}).Validate(int64(s.MaxTokens)); err != nil {
|
||||
return errors.Wrap(err, "int")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "max_tokens",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 64,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: regexMap["^[a-z0-9._-]+$"],
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(s.PromptVersion)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "prompt_version",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EmbeddingRequest) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if value, ok := s.Model.Get(); ok {
|
||||
if err := func() error {
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 200,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: regexMap["^[A-Za-z0-9._/-]+$"],
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(value)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "model",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Kind.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "kind",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if s.Texts == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 32,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(s.Texts)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range s.Texts {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "texts",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *EmbeddingResponse) Validate() error {
|
||||
if s == nil {
|
||||
return validate.ErrNilPointer
|
||||
}
|
||||
|
||||
var failures []validate.FieldError
|
||||
if err := func() error {
|
||||
if err := s.Model.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "model",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if err := s.Kind.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "kind",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if err := func() error {
|
||||
if s.Vectors == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 32,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(s.Vectors)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range s.Vectors {
|
||||
if err := func() error {
|
||||
if err := elem.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: "vectors",
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s EmbeddingText) Validate() error {
|
||||
alias := (string)(s)
|
||||
if err := (validate.String{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 8000,
|
||||
MaxLengthSet: true,
|
||||
Email: false,
|
||||
Hostname: false,
|
||||
Regex: nil,
|
||||
MinNumeric: 0,
|
||||
MinNumericSet: false,
|
||||
MaxNumeric: 0,
|
||||
MaxNumericSet: false,
|
||||
}).Validate(string(alias)); err != nil {
|
||||
return errors.Wrap(err, "string")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s EmbeddingVector) Validate() error {
|
||||
alias := ([]float32)(s)
|
||||
if alias == nil {
|
||||
return errors.New("nil is invalid value")
|
||||
}
|
||||
if err := (validate.Array{
|
||||
MinLength: 1,
|
||||
MinLengthSet: true,
|
||||
MaxLength: 4096,
|
||||
MaxLengthSet: true,
|
||||
}).ValidateLength(len(alias)); err != nil {
|
||||
return errors.Wrap(err, "array")
|
||||
}
|
||||
var failures []validate.FieldError
|
||||
for i, elem := range alias {
|
||||
if err := func() error {
|
||||
if err := (validate.Float{}).Validate(float64(elem)); err != nil {
|
||||
return errors.Wrap(err, "float")
|
||||
}
|
||||
return nil
|
||||
}(); err != nil {
|
||||
failures = append(failures, validate.FieldError{
|
||||
Name: fmt.Sprintf("[%d]", i),
|
||||
Error: err,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(failures) > 0 {
|
||||
return &validate.Error{Fields: failures}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *GetMLReadyzOK) Validate() error {
|
||||
alias := (*MLReadinessResponse)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
@@ -349,6 +719,8 @@ func (s ProblemCode) Validate() error {
|
||||
return nil
|
||||
case "not_implemented":
|
||||
return nil
|
||||
case "service_unavailable":
|
||||
return nil
|
||||
default:
|
||||
return errors.Errorf("invalid value: %v", s)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
// Package ml is the client of the internal ML service. The generated ogen
|
||||
// client in ./api carries the contract; this adapter adds the request
|
||||
// timeout, a response size cap, a circuit breaker, batching, and the checks
|
||||
// that turn the response into domain vectors.
|
||||
package ml
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/ml/api"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
const (
|
||||
// maxResponseBytes caps one response: 32 vectors of 4096 floats as JSON
|
||||
// stay far below it.
|
||||
maxResponseBytes = 16 << 20
|
||||
// maxTextRunes is the contract bound of one text; longer texts are cut
|
||||
// before they are sent, the model truncates at its token limit anyway.
|
||||
maxTextRunes = 8000
|
||||
)
|
||||
|
||||
// Settings configure the client.
|
||||
type Settings struct {
|
||||
// BaseURL is the ML service origin, for example http://ml:8000.
|
||||
BaseURL string
|
||||
// Timeout bounds one HTTP request.
|
||||
Timeout time.Duration
|
||||
// FailureThreshold consecutive failures open the circuit for OpenDuration.
|
||||
FailureThreshold int
|
||||
OpenDuration time.Duration
|
||||
}
|
||||
|
||||
// Embedder implements outbound.TextEmbedder over HTTP.
|
||||
type Embedder struct {
|
||||
client *api.Client
|
||||
breaker *breaker
|
||||
}
|
||||
|
||||
var _ outbound.TextEmbedder = (*Embedder)(nil)
|
||||
|
||||
// NewEmbedder validates the settings and builds the client. Nothing connects.
|
||||
func NewEmbedder(settings Settings, clock func() time.Time) (*Embedder, error) {
|
||||
const location = "ml.NewEmbedder"
|
||||
parsed, err := url.Parse(settings.BaseURL)
|
||||
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" || parsed.User != nil {
|
||||
return nil, errors.New(location + " - ML service URL must be an http or https origin without credentials")
|
||||
}
|
||||
if settings.Timeout <= 0 || settings.FailureThreshold < 1 || settings.OpenDuration <= 0 || clock == nil {
|
||||
return nil, errors.New(location + " - timeout, failure threshold, open duration, and clock must be set")
|
||||
}
|
||||
httpClient := &http.Client{
|
||||
Timeout: settings.Timeout,
|
||||
Transport: limitedTransport{next: http.DefaultTransport},
|
||||
// The service is a fixed internal origin; a redirect is never expected.
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
}
|
||||
client, err := api.NewClient(parsed.String(), api.WithClient(httpClient))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - create client: %w", location, err)
|
||||
}
|
||||
return &Embedder{
|
||||
client: client,
|
||||
breaker: &breaker{threshold: settings.FailureThreshold, open: settings.OpenDuration, clock: clock},
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Embed encodes texts with the named model in contract-sized batches and
|
||||
// checks that every batch came from the same model. The caller compares the
|
||||
// returned identity with the one it expects.
|
||||
func (embedder *Embedder) Embed(
|
||||
ctx context.Context, modelID string, kind outbound.EmbeddingKind, texts []string,
|
||||
) (domain.SemanticModel, []domain.SemanticVector, error) {
|
||||
const location = "ml.Embedder.Embed"
|
||||
var model domain.SemanticModel
|
||||
vectors := make([]domain.SemanticVector, 0, len(texts))
|
||||
for start := 0; start < len(texts); start += outbound.MaxEmbeddingBatch {
|
||||
end := min(start+outbound.MaxEmbeddingBatch, len(texts))
|
||||
batchModel, batch, err := embedder.embedBatch(ctx, modelID, kind, texts[start:end])
|
||||
if err != nil {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("%s - encode batch: %w", location, err)
|
||||
}
|
||||
if start > 0 && batchModel != model {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("%s - the model changed between batches: %w", location, outbound.ErrEmbedderUnavailable)
|
||||
}
|
||||
model = batchModel
|
||||
vectors = append(vectors, batch...)
|
||||
}
|
||||
return model, vectors, nil
|
||||
}
|
||||
|
||||
func (embedder *Embedder) embedBatch(
|
||||
ctx context.Context, modelID string, kind outbound.EmbeddingKind, texts []string,
|
||||
) (domain.SemanticModel, []domain.SemanticVector, error) {
|
||||
if len(texts) == 0 {
|
||||
return domain.SemanticModel{}, nil, nil
|
||||
}
|
||||
if !embedder.breaker.allow() {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("circuit is open: %w", outbound.ErrEmbedderUnavailable)
|
||||
}
|
||||
request := &api.EmbeddingRequest{
|
||||
Model: api.NewOptString(modelID), Kind: api.EmbeddingInputKind(kind), Texts: make([]api.EmbeddingText, 0, len(texts)),
|
||||
}
|
||||
for _, text := range texts {
|
||||
request.Texts = append(request.Texts, api.EmbeddingText(cutRunes(text, maxTextRunes)))
|
||||
}
|
||||
result, err := embedder.client.CreateMLEmbeddings(ctx, request)
|
||||
if err != nil {
|
||||
embedder.breaker.failure()
|
||||
// The client error can quote the URL but never the request body.
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("call the ML service: %w", outbound.ErrEmbedderUnavailable)
|
||||
}
|
||||
switch response := result.(type) {
|
||||
case *api.EmbeddingResponse:
|
||||
model, vectors, err := decodeResponse(response, kind, len(texts))
|
||||
if err != nil {
|
||||
embedder.breaker.failure()
|
||||
return domain.SemanticModel{}, nil, err
|
||||
}
|
||||
embedder.breaker.success()
|
||||
return model, vectors, nil
|
||||
case *api.CreateMLEmbeddingsServiceUnavailable:
|
||||
embedder.breaker.failure()
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("the ML service is not ready: %w", outbound.ErrEmbedderUnavailable)
|
||||
default:
|
||||
// 400 or 413: the request breaks the contract or names a model the
|
||||
// service does not serve, and a repeat cannot fix it.
|
||||
embedder.breaker.success()
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("the ML service refused the request: %w", outbound.ErrEmbedderRejected)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeResponse(response *api.EmbeddingResponse, kind outbound.EmbeddingKind, count int) (domain.SemanticModel, []domain.SemanticVector, error) {
|
||||
model := domain.SemanticModel{
|
||||
ID: response.Model.ID, Revision: response.Model.Revision, PromptVersion: response.Model.PromptVersion,
|
||||
}
|
||||
if err := model.Validate(); err != nil || string(response.Kind) != string(kind) || len(response.Vectors) != count {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("the response does not match the request: %w", outbound.ErrEmbedderRejected)
|
||||
}
|
||||
vectors := make([]domain.SemanticVector, 0, count)
|
||||
for _, raw := range response.Vectors {
|
||||
if len(raw) != int(response.Model.Dimension) {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("a vector has the wrong dimension: %w", outbound.ErrEmbedderRejected)
|
||||
}
|
||||
vector, err := domain.NewSemanticVector(raw)
|
||||
if err != nil {
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("a vector is invalid: %w", outbound.ErrEmbedderRejected)
|
||||
}
|
||||
vectors = append(vectors, vector)
|
||||
}
|
||||
return model, vectors, nil
|
||||
}
|
||||
|
||||
func cutRunes(text string, limit int) string {
|
||||
runes := []rune(text)
|
||||
if len(runes) <= limit {
|
||||
return text
|
||||
}
|
||||
return string(runes[:limit])
|
||||
}
|
||||
|
||||
// limitedTransport caps the bytes read from a response body.
|
||||
type limitedTransport struct {
|
||||
next http.RoundTripper
|
||||
}
|
||||
|
||||
func (transport limitedTransport) RoundTrip(request *http.Request) (*http.Response, error) {
|
||||
response, err := transport.next.RoundTrip(request)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response.Body = limitedBody{Reader: io.LimitReader(response.Body, maxResponseBytes), Closer: response.Body}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
type limitedBody struct {
|
||||
io.Reader
|
||||
io.Closer
|
||||
}
|
||||
|
||||
// breaker opens after threshold consecutive failures and lets one probe
|
||||
// through after the open duration; a success closes it.
|
||||
type breaker struct {
|
||||
mutex sync.Mutex
|
||||
threshold int
|
||||
open time.Duration
|
||||
clock func() time.Time
|
||||
failures int
|
||||
openUntil time.Time
|
||||
probing bool
|
||||
}
|
||||
|
||||
func (circuit *breaker) allow() bool {
|
||||
circuit.mutex.Lock()
|
||||
defer circuit.mutex.Unlock()
|
||||
if circuit.failures < circuit.threshold {
|
||||
return true
|
||||
}
|
||||
if circuit.clock().Before(circuit.openUntil) || circuit.probing {
|
||||
return false
|
||||
}
|
||||
circuit.probing = true
|
||||
return true
|
||||
}
|
||||
|
||||
func (circuit *breaker) success() {
|
||||
circuit.mutex.Lock()
|
||||
defer circuit.mutex.Unlock()
|
||||
circuit.failures, circuit.probing = 0, false
|
||||
}
|
||||
|
||||
func (circuit *breaker) failure() {
|
||||
circuit.mutex.Lock()
|
||||
defer circuit.mutex.Unlock()
|
||||
circuit.failures++
|
||||
circuit.probing = false
|
||||
if circuit.failures >= circuit.threshold {
|
||||
circuit.openUntil = circuit.clock().Add(circuit.open)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
package ml
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
type fakeService struct {
|
||||
mutex sync.Mutex
|
||||
requests int
|
||||
batches []int
|
||||
models []string
|
||||
respond func(writer http.ResponseWriter, kind string, texts []string)
|
||||
}
|
||||
|
||||
func (service *fakeService) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
||||
var body struct {
|
||||
Model string `json:"model"`
|
||||
Kind string `json:"kind"`
|
||||
Texts []string `json:"texts"`
|
||||
}
|
||||
_ = json.NewDecoder(request.Body).Decode(&body)
|
||||
service.mutex.Lock()
|
||||
service.requests++
|
||||
service.batches = append(service.batches, len(body.Texts))
|
||||
service.models = append(service.models, body.Model)
|
||||
service.mutex.Unlock()
|
||||
service.respond(writer, body.Kind, body.Texts)
|
||||
}
|
||||
|
||||
func validResponse(writer http.ResponseWriter, kind string, texts []string) {
|
||||
vectors := make([][]float32, 0, len(texts))
|
||||
for range texts {
|
||||
vectors = append(vectors, []float32{0.6, 0.8})
|
||||
}
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(writer).Encode(map[string]any{
|
||||
"model": map[string]any{"id": "example/model", "revision": "abc", "dimension": 2, "max_tokens": 1024, "prompt_version": "v1"},
|
||||
"kind": kind, "vectors": vectors,
|
||||
})
|
||||
}
|
||||
|
||||
func newTestEmbedder(t *testing.T, service *fakeService, clock func() time.Time) *Embedder {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(service)
|
||||
t.Cleanup(server.Close)
|
||||
embedder, err := NewEmbedder(Settings{BaseURL: server.URL, Timeout: time.Second, FailureThreshold: 2, OpenDuration: time.Minute}, clock)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmbedder() error = %v", err)
|
||||
}
|
||||
return embedder
|
||||
}
|
||||
|
||||
func TestEmbedSplitsBatchesAndChecksTheResponse(t *testing.T) {
|
||||
service := &fakeService{respond: validResponse}
|
||||
embedder := newTestEmbedder(t, service, time.Now)
|
||||
texts := make([]string, 40)
|
||||
for index := range texts {
|
||||
texts[index] = "text"
|
||||
}
|
||||
model, vectors, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingDocument, texts)
|
||||
if err != nil || len(vectors) != 40 || model.ID != "example/model" || model.PromptVersion != "v1" {
|
||||
t.Fatalf("Embed() = %+v, %d vectors, %v", model, len(vectors), err)
|
||||
}
|
||||
if len(service.batches) != 2 || service.batches[0] != outbound.MaxEmbeddingBatch || service.batches[1] != 8 {
|
||||
t.Fatalf("batches = %v, want 32 and 8", service.batches)
|
||||
}
|
||||
if strings.Join(service.models, ",") != "example/model,example/model" {
|
||||
t.Fatalf("requested models = %v, want the named model in every batch", service.models)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbedRejectsResponsesThatBreakTheContract(t *testing.T) {
|
||||
for name, respond := range map[string]func(http.ResponseWriter, string, []string){
|
||||
"too few vectors": func(writer http.ResponseWriter, kind string, texts []string) { validResponse(writer, kind, texts[:1]) },
|
||||
"not normalized": func(writer http.ResponseWriter, kind string, _ []string) {
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(writer).Encode(map[string]any{
|
||||
"model": map[string]any{"id": "m/x", "revision": "r", "dimension": 2, "max_tokens": 1, "prompt_version": "v"},
|
||||
"kind": kind, "vectors": [][]float32{{1, 1}, {1, 1}},
|
||||
})
|
||||
},
|
||||
"bad request": func(writer http.ResponseWriter, _ string, _ []string) {
|
||||
writer.Header().Set("Content-Type", "application/problem+json")
|
||||
writer.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = writer.Write([]byte(`{"type":"urn:lincodex:problem:validation_failed","title":"x","status":400,"code":"validation_failed"}`))
|
||||
},
|
||||
} {
|
||||
embedder := newTestEmbedder(t, &fakeService{respond: respond}, time.Now)
|
||||
if _, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingQuery, []string{"a", "b"}); !errors.Is(err, outbound.ErrEmbedderRejected) {
|
||||
t.Errorf("%s: error = %v, want ErrEmbedderRejected", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbedOpensTheCircuitAfterRepeatedFailures(t *testing.T) {
|
||||
now := time.Date(2026, 10, 11, 12, 0, 0, 0, time.UTC)
|
||||
clock := func() time.Time { return now }
|
||||
service := &fakeService{respond: func(writer http.ResponseWriter, _ string, _ []string) {
|
||||
writer.Header().Set("Content-Type", "application/problem+json")
|
||||
writer.WriteHeader(http.StatusServiceUnavailable)
|
||||
_, _ = writer.Write([]byte(`{"type":"urn:lincodex:problem:service_unavailable","title":"x","status":503,"code":"service_unavailable"}`))
|
||||
}}
|
||||
embedder := newTestEmbedder(t, service, clock)
|
||||
for range 3 {
|
||||
if _, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingQuery, []string{"a"}); !errors.Is(err, outbound.ErrEmbedderUnavailable) {
|
||||
t.Fatalf("error = %v, want ErrEmbedderUnavailable", err)
|
||||
}
|
||||
}
|
||||
if service.requests != 2 {
|
||||
t.Fatalf("requests = %d, want the circuit to stop calling after 2 failures", service.requests)
|
||||
}
|
||||
now = now.Add(2 * time.Minute)
|
||||
service.respond = validResponse
|
||||
if _, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingQuery, []string{"a"}); err != nil {
|
||||
t.Fatalf("probe after the open duration error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbedNeverQuotesTextsInErrors(t *testing.T) {
|
||||
embedder := newTestEmbedder(t, &fakeService{respond: func(writer http.ResponseWriter, _ string, _ []string) {
|
||||
writer.WriteHeader(http.StatusInternalServerError)
|
||||
}}, time.Now)
|
||||
_, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingDocument, []string{"Jane Doe private summary"})
|
||||
if err == nil || strings.Contains(err.Error(), "Jane") {
|
||||
t.Fatalf("error = %v, want a failure without the text", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewEmbedderRejectsUnsafeURLs(t *testing.T) {
|
||||
for _, raw := range []string{"", "ftp://ml:8000", "http://user:secret@ml:8000", "ml:8000"} {
|
||||
if _, err := NewEmbedder(Settings{BaseURL: raw, Timeout: time.Second, FailureThreshold: 1, OpenDuration: time.Second}, time.Now); err == nil {
|
||||
t.Errorf("NewEmbedder(%q) accepted the URL", raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,9 @@ type privacyCohortCandidate struct {
|
||||
acknowledgements []domain.ProfileParallelPeriodAcknowledgement
|
||||
workFormats []domain.QuestionnaireWorkFormat
|
||||
categories []domain.CandidateViewConfirmedCategoryInput
|
||||
// verifiedRepositories holds the keys of the repositories whose latest
|
||||
// check found them public.
|
||||
verifiedRepositories map[string]bool
|
||||
}
|
||||
|
||||
func (repository privacyCohortRepository) ListVisibleCandidateViewSources(
|
||||
@@ -94,6 +97,7 @@ func (repository privacyCohortRepository) ListVisibleCandidateViewSources(
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - restore candidate source: %w", location, err)
|
||||
}
|
||||
current.verifiedRepositories = verifiedRepositorySet(row.VerifiedRepositories)
|
||||
}
|
||||
if row.Kind.Valid {
|
||||
claim, err := privacyCohortStoredClaim(row)
|
||||
@@ -210,11 +214,22 @@ func buildPrivacyCohortSource(candidate privacyCohortCandidate) (domain.Candidat
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("validate safe profile claims: %w", domain.ErrInvalidCandidateViewSource)
|
||||
}
|
||||
return domain.NewCandidateViewSource(
|
||||
candidate.id, candidate.fields, domain.CandidateViewProfileFromContent(content), candidate.categories,
|
||||
candidate.workFormats, nil,
|
||||
candidate.id, candidate.fields,
|
||||
domain.CandidateViewProfileFromContentWithRepositories(content, candidate.verifiedRepositories),
|
||||
candidate.categories, candidate.workFormats, nil,
|
||||
)
|
||||
}
|
||||
|
||||
// verifiedRepositorySet turns the keys of the verified repositories of one
|
||||
// candidate into a set.
|
||||
func verifiedRepositorySet(keys []string) map[string]bool {
|
||||
set := make(map[string]bool, len(keys))
|
||||
for _, key := range keys {
|
||||
set[key] = true
|
||||
}
|
||||
return set
|
||||
}
|
||||
|
||||
func privacyCohortJSONBytes(value any) ([]byte, error) {
|
||||
switch typed := value.(type) {
|
||||
case []byte:
|
||||
|
||||
@@ -134,6 +134,7 @@ func buildPreviewCandidateViewSource(
|
||||
if err != nil {
|
||||
return domain.CandidateViewSource{}, fmt.Errorf("%s - restore candidate input: %w", location, err)
|
||||
}
|
||||
candidate.verifiedRepositories = verifiedRepositorySet(first.VerifiedRepositories)
|
||||
for _, row := range rows {
|
||||
if row.Kind.Valid {
|
||||
claim, err := previewStoredClaim(row)
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// SemanticVectors returns the vector repository of the transaction.
|
||||
func (unit *UnitOfWork) SemanticVectors() outbound.SemanticVectorRepository {
|
||||
return semanticVectorRepository{queries: unit.queries}
|
||||
}
|
||||
|
||||
// ProjectRepositories returns the repository check store of the transaction.
|
||||
func (unit *UnitOfWork) ProjectRepositories() outbound.ProjectRepositoryStore {
|
||||
return projectRepositoryStore{queries: unit.queries}
|
||||
}
|
||||
|
||||
type semanticVectorRepository struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func subjectColumns(kind domain.SemanticSubjectKind, subjectID uuid.UUID) (pgtype.UUID, pgtype.UUID, error) {
|
||||
switch kind {
|
||||
case domain.SemanticSubjectCandidate:
|
||||
return pgUUID(subjectID), pgtype.UUID{}, nil
|
||||
case domain.SemanticSubjectNeed:
|
||||
return pgtype.UUID{}, pgUUID(subjectID), nil
|
||||
default:
|
||||
return pgtype.UUID{}, pgtype.UUID{}, fmt.Errorf("postgres.subjectColumns - subject kind is unknown: %w", domain.ErrInvalidSemanticVector)
|
||||
}
|
||||
}
|
||||
|
||||
func (repository semanticVectorRepository) Replace(
|
||||
ctx context.Context,
|
||||
kind domain.SemanticSubjectKind,
|
||||
subjectID uuid.UUID,
|
||||
model domain.SemanticModel,
|
||||
items []outbound.StoredSemanticItem,
|
||||
at time.Time,
|
||||
) error {
|
||||
const location = "semanticVectorRepository.Replace"
|
||||
candidateID, needID, err := subjectColumns(kind, subjectID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := repository.queries.DeleteSemanticVectorsOfModel(ctx, sqlc.DeleteSemanticVectorsOfModelParams{
|
||||
SubjectKind: string(kind), SubjectID: pgUUID(subjectID),
|
||||
ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - delete previous vectors: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
for _, item := range items {
|
||||
if err := repository.queries.InsertSemanticVector(ctx, sqlc.InsertSemanticVectorParams{
|
||||
SubjectKind: string(kind), SubjectID: pgUUID(subjectID), CandidateID: candidateID, NeedID: needID,
|
||||
ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
|
||||
ItemKey: item.Key, ContentSha256: item.ContentDigest[:], LabelSha256: item.LabelDigest,
|
||||
Dimension: int32(len(item.Vector)), Vector: item.Vector.Encode(), ComputedAt: pgTime(at), //nolint:gosec // a domain vector has at most 4096 dimensions
|
||||
}); err != nil {
|
||||
return fmt.Errorf("%s - insert vector: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// semanticLockNamespace keeps the advisory lock keys of vector jobs apart
|
||||
// from any other advisory lock of the database.
|
||||
const semanticLockNamespace = 0x53454d41 // "SEMA"
|
||||
|
||||
func (repository semanticVectorRepository) Lock(ctx context.Context, kind domain.SemanticSubjectKind, subjectID uuid.UUID) error {
|
||||
digest := sha256.Sum256([]byte(string(kind) + ":" + subjectID.String()))
|
||||
key := int64(binary.BigEndian.Uint64(digest[:8])>>16) ^ semanticLockNamespace
|
||||
if err := repository.queries.LockSemanticSubject(ctx, key); err != nil {
|
||||
return fmt.Errorf("semanticVectorRepository.Lock - take lock: %w", markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository semanticVectorRepository) DeleteSubject(ctx context.Context, kind domain.SemanticSubjectKind, subjectID uuid.UUID) error {
|
||||
if err := repository.queries.DeleteSemanticVectorsOfSubject(ctx, sqlc.DeleteSemanticVectorsOfSubjectParams{
|
||||
SubjectKind: string(kind), SubjectID: pgUUID(subjectID),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("semanticVectorRepository.DeleteSubject - delete vectors: %w", markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (repository semanticVectorRepository) Digests(
|
||||
ctx context.Context, kind domain.SemanticSubjectKind, subjectID uuid.UUID, model domain.SemanticModel,
|
||||
) (map[string][32]byte, error) {
|
||||
rows, err := repository.queries.ListSemanticVectorDigests(ctx, sqlc.ListSemanticVectorDigestsParams{
|
||||
SubjectKind: string(kind), SubjectID: pgUUID(subjectID),
|
||||
ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("semanticVectorRepository.Digests - select digests: %w", markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
digests := make(map[string][32]byte, len(rows))
|
||||
for _, row := range rows {
|
||||
var digest [32]byte
|
||||
if len(row.ContentSha256) != len(digest) {
|
||||
return nil, fmt.Errorf("semanticVectorRepository.Digests - digest length is invalid: %w", domain.ErrInvalidSemanticVector)
|
||||
}
|
||||
copy(digest[:], row.ContentSha256)
|
||||
digests[row.ItemKey] = digest
|
||||
}
|
||||
return digests, nil
|
||||
}
|
||||
|
||||
func pgUUIDs(ids []uuid.UUID) []pgtype.UUID {
|
||||
values := make([]pgtype.UUID, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
values = append(values, pgUUID(id))
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func (repository semanticVectorRepository) CandidateWholeVectors(
|
||||
ctx context.Context, model domain.SemanticModel, candidateIDs []uuid.UUID,
|
||||
) (map[uuid.UUID]domain.SemanticVector, error) {
|
||||
const location = "semanticVectorRepository.CandidateWholeVectors"
|
||||
vectors := make(map[uuid.UUID]domain.SemanticVector)
|
||||
if len(candidateIDs) == 0 {
|
||||
return vectors, nil
|
||||
}
|
||||
rows, err := repository.queries.ListCandidateWholeVectors(ctx, sqlc.ListCandidateWholeVectorsParams{
|
||||
ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
|
||||
CandidateIds: pgUUIDs(candidateIDs),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - select vectors: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
for _, row := range rows {
|
||||
vector, err := domain.DecodeSemanticVector(row.Vector, int(row.Dimension))
|
||||
if err != nil || !row.CandidateID.Valid {
|
||||
return nil, fmt.Errorf("%s - stored vector is invalid: %w", location, domain.ErrInvalidSemanticVector)
|
||||
}
|
||||
vectors[uuid.UUID(row.CandidateID.Bytes)] = vector
|
||||
}
|
||||
return vectors, nil
|
||||
}
|
||||
|
||||
func (repository semanticVectorRepository) CandidateItemVectors(
|
||||
ctx context.Context, model domain.SemanticModel, candidateIDs []uuid.UUID,
|
||||
) (map[uuid.UUID][]outbound.SemanticItemVector, error) {
|
||||
const location = "semanticVectorRepository.CandidateItemVectors"
|
||||
vectors := make(map[uuid.UUID][]outbound.SemanticItemVector)
|
||||
if len(candidateIDs) == 0 {
|
||||
return vectors, nil
|
||||
}
|
||||
rows, err := repository.queries.ListCandidateItemVectors(ctx, sqlc.ListCandidateItemVectorsParams{
|
||||
ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
|
||||
CandidateIds: pgUUIDs(candidateIDs),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - select vectors: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
for _, row := range rows {
|
||||
vector, err := domain.DecodeSemanticVector(row.Vector, int(row.Dimension))
|
||||
if err != nil || !row.CandidateID.Valid {
|
||||
return nil, fmt.Errorf("%s - stored vector is invalid: %w", location, domain.ErrInvalidSemanticVector)
|
||||
}
|
||||
id := uuid.UUID(row.CandidateID.Bytes)
|
||||
vectors[id] = append(vectors[id], outbound.SemanticItemVector{Key: row.ItemKey, LabelDigest: row.LabelSha256, Vector: vector})
|
||||
}
|
||||
return vectors, nil
|
||||
}
|
||||
|
||||
func (repository semanticVectorRepository) NeedVectors(
|
||||
ctx context.Context, needID uuid.UUID, model domain.SemanticModel, digests [][32]byte,
|
||||
) (map[string]domain.SemanticVector, error) {
|
||||
const location = "semanticVectorRepository.NeedVectors"
|
||||
vectors := make(map[string]domain.SemanticVector)
|
||||
if len(digests) == 0 {
|
||||
return vectors, nil
|
||||
}
|
||||
values := make([][]byte, 0, len(digests))
|
||||
for _, digest := range digests {
|
||||
values = append(values, digest[:])
|
||||
}
|
||||
rows, err := repository.queries.ListNeedVectors(ctx, sqlc.ListNeedVectorsParams{
|
||||
NeedID: pgUUID(needID), ModelID: model.ID, ModelRevision: model.Revision, PromptVersion: model.PromptVersion,
|
||||
ContentDigests: values,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - select vectors: %w", location, markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
for _, row := range rows {
|
||||
vector, err := domain.DecodeSemanticVector(row.Vector, int(row.Dimension))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - stored vector is invalid: %w", location, domain.ErrInvalidSemanticVector)
|
||||
}
|
||||
vectors[row.ItemKey] = vector
|
||||
}
|
||||
return vectors, nil
|
||||
}
|
||||
|
||||
func (repository semanticVectorRepository) CandidatesAfter(ctx context.Context, after uuid.UUID, limit int) ([]uuid.UUID, error) {
|
||||
rows, err := repository.queries.ListProfileCandidatesAfter(ctx, sqlc.ListProfileCandidatesAfterParams{
|
||||
AfterID: pgUUID(after), PageSize: int32(limit), //nolint:gosec // the caller bounds the page size
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("semanticVectorRepository.CandidatesAfter - select candidates: %w", markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
ids := make([]uuid.UUID, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
ids = append(ids, uuid.UUID(row.Bytes))
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func (repository semanticVectorRepository) NeedsAfter(ctx context.Context, after uuid.UUID, limit int) ([]outbound.NeedReference, error) {
|
||||
rows, err := repository.queries.ListNeedsAfter(ctx, sqlc.ListNeedsAfterParams{
|
||||
AfterID: pgUUID(after), PageSize: int32(limit), //nolint:gosec // the caller bounds the page size
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("semanticVectorRepository.NeedsAfter - select needs: %w", markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
needs := make([]outbound.NeedReference, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
needs = append(needs, outbound.NeedReference{
|
||||
NeedID: uuid.UUID(row.ID.Bytes), OrganizationID: uuid.UUID(row.OrganizationID.Bytes),
|
||||
RequirementsVersion: row.RequirementsVersion,
|
||||
})
|
||||
}
|
||||
return needs, nil
|
||||
}
|
||||
|
||||
type projectRepositoryStore struct {
|
||||
queries *sqlc.Queries
|
||||
}
|
||||
|
||||
func repositoryCheckFromRow(row sqlc.CandidateProjectRepository) outbound.RepositoryCheck {
|
||||
check := outbound.RepositoryCheck{
|
||||
Key: row.RepositoryKey, State: outbound.RepositoryCheckState(row.State),
|
||||
GitHubID: row.GithubID.Int64, RepositoryETag: row.RepositoryEtag.String, ReadmeETag: row.ReadmeEtag.String,
|
||||
Failure: outbound.RepositoryFailureClass(row.FailureClass.String), RequestedAt: row.RequestedAt.Time.UTC(),
|
||||
Evidence: domain.RepositoryEvidence{
|
||||
Description: row.Description.String, Topics: row.Topics, Languages: row.Languages,
|
||||
ReadmeExcerpt: row.ReadmeExcerpt.String,
|
||||
},
|
||||
}
|
||||
if row.CheckedAt.Valid {
|
||||
check.CheckedAt = row.CheckedAt.Time.UTC()
|
||||
}
|
||||
return check
|
||||
}
|
||||
|
||||
func (store projectRepositoryStore) List(ctx context.Context, candidateID uuid.UUID) ([]outbound.RepositoryCheck, error) {
|
||||
rows, err := store.queries.ListCandidateProjectRepositories(ctx, pgUUID(candidateID))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("projectRepositoryStore.List - select checks: %w", markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
checks := make([]outbound.RepositoryCheck, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
checks = append(checks, repositoryCheckFromRow(row))
|
||||
}
|
||||
return checks, nil
|
||||
}
|
||||
|
||||
func (store projectRepositoryStore) GetForUpdate(ctx context.Context, candidateID uuid.UUID, key string) (outbound.RepositoryCheck, bool, error) {
|
||||
row, err := store.queries.GetCandidateProjectRepositoryForUpdate(ctx, sqlc.GetCandidateProjectRepositoryForUpdateParams{
|
||||
CandidateID: pgUUID(candidateID), RepositoryKey: key,
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return outbound.RepositoryCheck{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return outbound.RepositoryCheck{}, false, fmt.Errorf("projectRepositoryStore.GetForUpdate - select check: %w", markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
return repositoryCheckFromRow(row), true, nil
|
||||
}
|
||||
|
||||
func (store projectRepositoryStore) Request(ctx context.Context, candidateID uuid.UUID, key string, at time.Time) error {
|
||||
if err := store.queries.RequestCandidateProjectRepositoryCheck(ctx, sqlc.RequestCandidateProjectRepositoryCheckParams{
|
||||
CandidateID: pgUUID(candidateID), RepositoryKey: key, RequestedAt: pgTime(at),
|
||||
}); err != nil {
|
||||
return fmt.Errorf("projectRepositoryStore.Request - record request: %w", markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func optionalPgText(value string) pgtype.Text {
|
||||
if value == "" {
|
||||
return pgtype.Text{}
|
||||
}
|
||||
return pgText(value)
|
||||
}
|
||||
|
||||
func (store projectRepositoryStore) Save(ctx context.Context, candidateID uuid.UUID, check outbound.RepositoryCheck) error {
|
||||
params := sqlc.SaveCandidateProjectRepositoryCheckParams{
|
||||
State: string(check.State), Topics: []string{}, Languages: []string{},
|
||||
RepositoryEtag: optionalPgText(check.RepositoryETag), ReadmeEtag: optionalPgText(check.ReadmeETag),
|
||||
FailureClass: optionalPgText(string(check.Failure)), CheckedAt: pgTime(check.CheckedAt),
|
||||
CandidateID: pgUUID(candidateID), RepositoryKey: check.Key,
|
||||
}
|
||||
if check.State == outbound.RepositoryCheckVerified {
|
||||
params.GithubID = pgtype.Int8{Int64: check.GitHubID, Valid: check.GitHubID > 0}
|
||||
params.Description = optionalPgText(check.Evidence.Description)
|
||||
params.ReadmeExcerpt = optionalPgText(check.Evidence.ReadmeExcerpt)
|
||||
if check.Evidence.Topics != nil {
|
||||
params.Topics = check.Evidence.Topics
|
||||
}
|
||||
if check.Evidence.Languages != nil {
|
||||
params.Languages = check.Evidence.Languages
|
||||
}
|
||||
}
|
||||
if err := store.queries.SaveCandidateProjectRepositoryCheck(ctx, params); err != nil {
|
||||
return fmt.Errorf("projectRepositoryStore.Save - store check: %w", markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store projectRepositoryStore) DeleteUnlinked(ctx context.Context, candidateID uuid.UUID, linkedKeys []string) error {
|
||||
if linkedKeys == nil {
|
||||
linkedKeys = []string{}
|
||||
}
|
||||
if err := store.queries.DeleteUnlinkedCandidateProjectRepositories(ctx, sqlc.DeleteUnlinkedCandidateProjectRepositoriesParams{
|
||||
CandidateID: pgUUID(candidateID), LinkedKeys: linkedKeys,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("projectRepositoryStore.DeleteUnlinked - delete checks: %w", markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store projectRepositoryStore) LatestRequest(ctx context.Context, candidateID uuid.UUID) (time.Time, error) {
|
||||
latest, err := store.queries.GetLatestRepositoryCheckRequest(ctx, pgUUID(candidateID))
|
||||
if err != nil {
|
||||
return time.Time{}, fmt.Errorf("projectRepositoryStore.LatestRequest - select request: %w", markTransactionConflict(sanitizeConnectError(err)))
|
||||
}
|
||||
if !latest.Valid {
|
||||
return time.Time{}, nil
|
||||
}
|
||||
return latest.Time.UTC(), nil
|
||||
}
|
||||
@@ -361,6 +361,24 @@ type CandidateProfileOverlapConfirmation struct {
|
||||
SecondEndedOn pgtype.Text
|
||||
}
|
||||
|
||||
type CandidateProjectRepository struct {
|
||||
CandidateID pgtype.UUID
|
||||
RepositoryKey string
|
||||
State string
|
||||
GithubID pgtype.Int8
|
||||
Description pgtype.Text
|
||||
Topics []string
|
||||
Languages []string
|
||||
ReadmeExcerpt pgtype.Text
|
||||
RepositoryEtag pgtype.Text
|
||||
ReadmeEtag pgtype.Text
|
||||
FailureClass pgtype.Text
|
||||
CheckedAt pgtype.Timestamptz
|
||||
RequestedAt pgtype.Timestamptz
|
||||
CreatedAt pgtype.Timestamptz
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type CandidatePublication struct {
|
||||
UserID pgtype.UUID
|
||||
State string
|
||||
@@ -838,6 +856,22 @@ type ScheduledJob struct {
|
||||
UpdatedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type SemanticVector struct {
|
||||
SubjectKind string
|
||||
SubjectID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
NeedID pgtype.UUID
|
||||
ModelID string
|
||||
ModelRevision string
|
||||
PromptVersion string
|
||||
ItemKey string
|
||||
ContentSha256 []byte
|
||||
LabelSha256 []byte
|
||||
Dimension int32
|
||||
Vector []byte
|
||||
ComputedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
ID pgtype.UUID
|
||||
UserID pgtype.UUID
|
||||
|
||||
@@ -68,11 +68,21 @@ SELECT
|
||||
WHERE category.candidate_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS confirmed_categories
|
||||
) AS confirmed_categories,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT array_agg(repository.repository_key ORDER BY repository.repository_key)
|
||||
FROM candidate_project_repositories AS repository
|
||||
WHERE
|
||||
repository.candidate_id = effective.user_id
|
||||
AND repository.state = 'verified'
|
||||
),
|
||||
'{}'::text []
|
||||
)::text [] AS verified_repositories
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
AND claim.kind IN ('stack', 'role', 'experience')
|
||||
AND claim.kind IN ('stack', 'role', 'experience', 'project')
|
||||
LEFT JOIN candidate_questionnaires AS questionnaire
|
||||
ON questionnaire.user_id = effective.user_id
|
||||
WHERE NOT EXISTS (
|
||||
@@ -98,15 +108,18 @@ type ListVisibleCandidateViewSourcesRow struct {
|
||||
WorkFormats []string
|
||||
ParallelPeriodAcknowledgements interface{}
|
||||
ConfirmedCategories interface{}
|
||||
VerifiedRepositories []string
|
||||
}
|
||||
|
||||
// Organization-facing anonymous candidate projection inputs. The calling
|
||||
// usecase has already authorized the active organization membership. This
|
||||
// single statement snapshot filters both revoked/unpublished C2 states and
|
||||
// candidates hidden from this organization before any profile value is read.
|
||||
// The projection reads only stack, declared role, and experience dates. It
|
||||
// deliberately excludes names, contacts, salary, location, soft skills,
|
||||
// employer names, summaries, and imported excerpts. The only assessment data
|
||||
// The projection reads only stack, declared role, experience dates, and
|
||||
// projects with the keys of their verified repositories. It deliberately
|
||||
// excludes names, contacts, salary, location, soft skills, employer names,
|
||||
// summaries, and imported excerpts; the repository address of a project stays
|
||||
// in the private input and never reaches the card. The only assessment data
|
||||
// is the current category (specialization and grade) of the separate current
|
||||
// category table; it carries no attempt, score, review, policy, or history.
|
||||
func (q *Queries) ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error) {
|
||||
@@ -132,6 +145,7 @@ func (q *Queries) ListVisibleCandidateViewSources(ctx context.Context, organizat
|
||||
&i.WorkFormats,
|
||||
&i.ParallelPeriodAcknowledgements,
|
||||
&i.ConfirmedCategories,
|
||||
&i.VerifiedRepositories,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -301,11 +315,21 @@ SELECT
|
||||
WHERE category.candidate_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS confirmed_categories
|
||||
) AS confirmed_categories,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT array_agg(repository.repository_key ORDER BY repository.repository_key)
|
||||
FROM candidate_project_repositories AS repository
|
||||
WHERE
|
||||
repository.candidate_id = effective.user_id
|
||||
AND repository.state = 'verified'
|
||||
),
|
||||
'{}'::text []
|
||||
)::text [] AS verified_repositories
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
AND claim.kind IN ('stack', 'role', 'experience')
|
||||
AND claim.kind IN ('stack', 'role', 'experience', 'project')
|
||||
LEFT JOIN candidate_questionnaires AS questionnaire
|
||||
ON questionnaire.user_id = effective.user_id
|
||||
WHERE effective.user_id = $1
|
||||
@@ -326,6 +350,7 @@ type ReadCandidateViewSourceForPreviewRow struct {
|
||||
WorkFormats []string
|
||||
ParallelPeriodAcknowledgements interface{}
|
||||
ConfirmedCategories interface{}
|
||||
VerifiedRepositories []string
|
||||
}
|
||||
|
||||
// Read the candidate's current private projection inputs after the caller
|
||||
@@ -354,6 +379,7 @@ func (q *Queries) ReadCandidateViewSourceForPreview(ctx context.Context, candida
|
||||
&i.WorkFormats,
|
||||
&i.ParallelPeriodAcknowledgements,
|
||||
&i.ConfirmedCategories,
|
||||
&i.VerifiedRepositories,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: project_repositories.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const deleteUnlinkedCandidateProjectRepositories = `-- name: DeleteUnlinkedCandidateProjectRepositories :exec
|
||||
DELETE FROM candidate_project_repositories
|
||||
WHERE
|
||||
candidate_id = $1
|
||||
AND NOT (repository_key = ANY($2::text []))
|
||||
`
|
||||
|
||||
type DeleteUnlinkedCandidateProjectRepositoriesParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
LinkedKeys []string
|
||||
}
|
||||
|
||||
// Removes the checks of repositories that no project links any more.
|
||||
func (q *Queries) DeleteUnlinkedCandidateProjectRepositories(ctx context.Context, arg DeleteUnlinkedCandidateProjectRepositoriesParams) error {
|
||||
_, err := q.db.Exec(ctx, deleteUnlinkedCandidateProjectRepositories, arg.CandidateID, arg.LinkedKeys)
|
||||
return err
|
||||
}
|
||||
|
||||
const getCandidateProjectRepositoryForUpdate = `-- name: GetCandidateProjectRepositoryForUpdate :one
|
||||
SELECT
|
||||
candidate_id, repository_key, state, github_id, description, topics,
|
||||
languages, readme_excerpt, repository_etag, readme_etag, failure_class,
|
||||
checked_at, requested_at, created_at, updated_at
|
||||
FROM candidate_project_repositories
|
||||
WHERE candidate_id = $1 AND repository_key = $2
|
||||
FOR UPDATE
|
||||
`
|
||||
|
||||
type GetCandidateProjectRepositoryForUpdateParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
RepositoryKey string
|
||||
}
|
||||
|
||||
func (q *Queries) GetCandidateProjectRepositoryForUpdate(ctx context.Context, arg GetCandidateProjectRepositoryForUpdateParams) (CandidateProjectRepository, error) {
|
||||
row := q.db.QueryRow(ctx, getCandidateProjectRepositoryForUpdate, arg.CandidateID, arg.RepositoryKey)
|
||||
var i CandidateProjectRepository
|
||||
err := row.Scan(
|
||||
&i.CandidateID,
|
||||
&i.RepositoryKey,
|
||||
&i.State,
|
||||
&i.GithubID,
|
||||
&i.Description,
|
||||
&i.Topics,
|
||||
&i.Languages,
|
||||
&i.ReadmeExcerpt,
|
||||
&i.RepositoryEtag,
|
||||
&i.ReadmeEtag,
|
||||
&i.FailureClass,
|
||||
&i.CheckedAt,
|
||||
&i.RequestedAt,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getLatestRepositoryCheckRequest = `-- name: GetLatestRepositoryCheckRequest :one
|
||||
SELECT MAX(requested_at)::timestamptz AS requested_at
|
||||
FROM candidate_project_repositories
|
||||
WHERE candidate_id = $1
|
||||
`
|
||||
|
||||
// The latest check request of a candidate, for the per-candidate limit.
|
||||
func (q *Queries) GetLatestRepositoryCheckRequest(ctx context.Context, candidateID pgtype.UUID) (pgtype.Timestamptz, error) {
|
||||
row := q.db.QueryRow(ctx, getLatestRepositoryCheckRequest, candidateID)
|
||||
var requested_at pgtype.Timestamptz
|
||||
err := row.Scan(&requested_at)
|
||||
return requested_at, err
|
||||
}
|
||||
|
||||
const listCandidateProjectRepositories = `-- name: ListCandidateProjectRepositories :many
|
||||
|
||||
SELECT
|
||||
candidate_id, repository_key, state, github_id, description, topics,
|
||||
languages, readme_excerpt, repository_etag, readme_etag, failure_class,
|
||||
checked_at, requested_at, created_at, updated_at
|
||||
FROM candidate_project_repositories
|
||||
WHERE candidate_id = $1
|
||||
ORDER BY repository_key
|
||||
`
|
||||
|
||||
// Server checks of the GitHub repositories that candidate projects link.
|
||||
// Every statement is scoped by the candidate.
|
||||
func (q *Queries) ListCandidateProjectRepositories(ctx context.Context, candidateID pgtype.UUID) ([]CandidateProjectRepository, error) {
|
||||
rows, err := q.db.Query(ctx, listCandidateProjectRepositories, candidateID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []CandidateProjectRepository
|
||||
for rows.Next() {
|
||||
var i CandidateProjectRepository
|
||||
if err := rows.Scan(
|
||||
&i.CandidateID,
|
||||
&i.RepositoryKey,
|
||||
&i.State,
|
||||
&i.GithubID,
|
||||
&i.Description,
|
||||
&i.Topics,
|
||||
&i.Languages,
|
||||
&i.ReadmeExcerpt,
|
||||
&i.RepositoryEtag,
|
||||
&i.ReadmeEtag,
|
||||
&i.FailureClass,
|
||||
&i.CheckedAt,
|
||||
&i.RequestedAt,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const requestCandidateProjectRepositoryCheck = `-- name: RequestCandidateProjectRepositoryCheck :exec
|
||||
INSERT INTO candidate_project_repositories (
|
||||
candidate_id, repository_key, state, requested_at, created_at, updated_at
|
||||
) VALUES (
|
||||
$1, $2, 'pending', $3,
|
||||
$3, $3
|
||||
)
|
||||
ON CONFLICT (candidate_id, repository_key) DO UPDATE
|
||||
SET
|
||||
requested_at = excluded.requested_at,
|
||||
updated_at = GREATEST(candidate_project_repositories.updated_at, excluded.updated_at)
|
||||
`
|
||||
|
||||
type RequestCandidateProjectRepositoryCheckParams struct {
|
||||
CandidateID pgtype.UUID
|
||||
RepositoryKey string
|
||||
RequestedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
// A new repository starts pending; a known one only records the request.
|
||||
func (q *Queries) RequestCandidateProjectRepositoryCheck(ctx context.Context, arg RequestCandidateProjectRepositoryCheckParams) error {
|
||||
_, err := q.db.Exec(ctx, requestCandidateProjectRepositoryCheck, arg.CandidateID, arg.RepositoryKey, arg.RequestedAt)
|
||||
return err
|
||||
}
|
||||
|
||||
const saveCandidateProjectRepositoryCheck = `-- name: SaveCandidateProjectRepositoryCheck :exec
|
||||
UPDATE candidate_project_repositories
|
||||
SET
|
||||
state = $1,
|
||||
github_id = $2,
|
||||
description = $3,
|
||||
topics = $4,
|
||||
languages = $5,
|
||||
readme_excerpt = $6,
|
||||
repository_etag = $7,
|
||||
readme_etag = $8,
|
||||
failure_class = $9,
|
||||
checked_at = $10,
|
||||
updated_at = GREATEST(updated_at, $10)
|
||||
WHERE candidate_id = $11 AND repository_key = $12
|
||||
`
|
||||
|
||||
type SaveCandidateProjectRepositoryCheckParams struct {
|
||||
State string
|
||||
GithubID pgtype.Int8
|
||||
Description pgtype.Text
|
||||
Topics []string
|
||||
Languages []string
|
||||
ReadmeExcerpt pgtype.Text
|
||||
RepositoryEtag pgtype.Text
|
||||
ReadmeEtag pgtype.Text
|
||||
FailureClass pgtype.Text
|
||||
CheckedAt pgtype.Timestamptz
|
||||
CandidateID pgtype.UUID
|
||||
RepositoryKey string
|
||||
}
|
||||
|
||||
func (q *Queries) SaveCandidateProjectRepositoryCheck(ctx context.Context, arg SaveCandidateProjectRepositoryCheckParams) error {
|
||||
_, err := q.db.Exec(ctx, saveCandidateProjectRepositoryCheck,
|
||||
arg.State,
|
||||
arg.GithubID,
|
||||
arg.Description,
|
||||
arg.Topics,
|
||||
arg.Languages,
|
||||
arg.ReadmeExcerpt,
|
||||
arg.RepositoryEtag,
|
||||
arg.ReadmeEtag,
|
||||
arg.FailureClass,
|
||||
arg.CheckedAt,
|
||||
arg.CandidateID,
|
||||
arg.RepositoryKey,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -217,9 +217,19 @@ type Querier interface {
|
||||
DeleteExpiredCompanyCardViewQuotaUsage(ctx context.Context, arg DeleteExpiredCompanyCardViewQuotaUsageParams) (int64, error)
|
||||
DeleteMailRequest(ctx context.Context, id pgtype.UUID) (int64, error)
|
||||
DeleteOrganizationRepresentatives(ctx context.Context, organizationID pgtype.UUID) error
|
||||
// Stored embedding vectors. A candidate keeps one set of rows for a model:
|
||||
// the job deletes every other row of the candidate and model before it
|
||||
// inserts the new set, in one transaction. A need keeps the rows of its
|
||||
// latest computed requirements snapshot the same way.
|
||||
DeleteSemanticVectorsOfModel(ctx context.Context, arg DeleteSemanticVectorsOfModelParams) error
|
||||
// Removes every vector of a subject, of any model: a closed card or a need
|
||||
// without requirements keeps no derived data.
|
||||
DeleteSemanticVectorsOfSubject(ctx context.Context, arg DeleteSemanticVectorsOfSubjectParams) error
|
||||
// No raw Idempotency-Key or request body reaches these statements. Failure
|
||||
// responses pass {} as case_snapshot and the CASE stores SQL NULL instead.
|
||||
DeleteSupportCaseCreateOutcome(ctx context.Context, scopeHash []byte) error
|
||||
// Removes the checks of repositories that no project links any more.
|
||||
DeleteUnlinkedCandidateProjectRepositories(ctx context.Context, arg DeleteUnlinkedCandidateProjectRepositoriesParams) error
|
||||
// Deletes one batch of accounts that stayed unverified since before cutoff,
|
||||
// oldest first, with their tokens, sessions, mail requests, mail deliveries
|
||||
// (and through the deliveries their attempts), and consent records. The
|
||||
@@ -314,6 +324,7 @@ type Querier interface {
|
||||
// Reads one hiding of the candidate with the current name of the
|
||||
// organization.
|
||||
GetCandidateHiddenOrganization(ctx context.Context, arg GetCandidateHiddenOrganizationParams) (GetCandidateHiddenOrganizationRow, error)
|
||||
GetCandidateProjectRepositoryForUpdate(ctx context.Context, arg GetCandidateProjectRepositoryForUpdateParams) (CandidateProjectRepository, error)
|
||||
GetConsentText(ctx context.Context, arg GetConsentTextParams) (ConsentText, error)
|
||||
GetContactConsentRecordByInvitation(ctx context.Context, arg GetContactConsentRecordByInvitationParams) (GetContactConsentRecordByInvitationRow, error)
|
||||
// Read the grant of one invitation of one organization. An invitation of
|
||||
@@ -374,6 +385,8 @@ type Querier interface {
|
||||
// resend, which issues its token with the same credentials.
|
||||
GetLatestPendingRegistration(ctx context.Context, arg GetLatestPendingRegistrationParams) (GetLatestPendingRegistrationRow, error)
|
||||
GetLatestPolicyVersion(ctx context.Context, policyKey string) (PolicyVersion, error)
|
||||
// The latest check request of a candidate, for the per-candidate limit.
|
||||
GetLatestRepositoryCheckRequest(ctx context.Context, candidateID pgtype.UUID) (pgtype.Timestamptz, error)
|
||||
// Reads the latest root in a specialization, optionally restricted to grade.
|
||||
GetLatestRootAssessmentAttempt(ctx context.Context, arg GetLatestRootAssessmentAttemptParams) (AssessmentAttempt, error)
|
||||
GetLiveIdempotencyRecord(ctx context.Context, arg GetLiveIdempotencyRecordParams) (IdempotencyRecord, error)
|
||||
@@ -599,6 +612,7 @@ type Querier interface {
|
||||
// moves a deadline. A concurrent insert of the same key waits for the first
|
||||
// transaction and then inserts nothing, or inserts after its rollback.
|
||||
InsertScheduledJob(ctx context.Context, arg InsertScheduledJobParams) (int64, error)
|
||||
InsertSemanticVector(ctx context.Context, arg InsertSemanticVectorParams) error
|
||||
InsertSession(ctx context.Context, arg InsertSessionParams) error
|
||||
// The initial public history is inserted in the caller's case transaction.
|
||||
// Any unique business conflict leaves the transaction usable so the caller can
|
||||
@@ -687,6 +701,9 @@ type Querier interface {
|
||||
// have no delivery and are never listed. The candidate scopes the rows, so
|
||||
// no identifier of another candidate can appear.
|
||||
ListCandidateInvitations(ctx context.Context, arg ListCandidateInvitationsParams) ([]ListCandidateInvitationsRow, error)
|
||||
// The item vectors of the candidates that a search returns, at most a few
|
||||
// dozen candidates.
|
||||
ListCandidateItemVectors(ctx context.Context, arg ListCandidateItemVectorsParams) ([]ListCandidateItemVectorsRow, error)
|
||||
// The same selection for the candidate's own card preview, so the candidate
|
||||
// sees what an organization would read. It is scoped by the owner and runs
|
||||
// after the caller locked the effective C2 and publication; it does not apply
|
||||
@@ -697,6 +714,11 @@ type Querier interface {
|
||||
// read time, and is the current name. The page continues after the
|
||||
// (occurred_at, id) position of the last event of the previous page.
|
||||
ListCandidatePrivacyEvents(ctx context.Context, arg ListCandidatePrivacyEventsParams) ([]ListCandidatePrivacyEventsRow, error)
|
||||
// Server checks of the GitHub repositories that candidate projects link.
|
||||
// Every statement is scoped by the candidate.
|
||||
ListCandidateProjectRepositories(ctx context.Context, candidateID pgtype.UUID) ([]CandidateProjectRepository, error)
|
||||
// The whole-view vectors of the candidates of one search.
|
||||
ListCandidateWholeVectors(ctx context.Context, arg ListCandidateWholeVectorsParams) ([]ListCandidateWholeVectorsRow, error)
|
||||
// One page of the subject's ledger, newest grant first, optionally limited
|
||||
// to one state. Every record query is scoped by the subject, so a caller
|
||||
// never reads or revokes another subject's consent. The state is computed,
|
||||
@@ -721,6 +743,11 @@ type Querier interface {
|
||||
// One bounded newest-first page. Both the organization scope and the tuple
|
||||
// cursor are applied before the limit.
|
||||
ListInvitations(ctx context.Context, arg ListInvitationsParams) ([]ListInvitationsRow, error)
|
||||
// The vectors of a need whose texts match the given digests of the
|
||||
// requirements snapshot that the search renders.
|
||||
ListNeedVectors(ctx context.Context, arg ListNeedVectorsParams) ([]ListNeedVectorsRow, error)
|
||||
// Needs and their current requirements snapshot for the backfill.
|
||||
ListNeedsAfter(ctx context.Context, arg ListNeedsAfterParams) ([]ListNeedsAfterRow, error)
|
||||
// List only the authenticated recipient's rows, optionally narrowed to one
|
||||
// organization context. The caller resolves current source visibility before
|
||||
// returning content.
|
||||
@@ -763,13 +790,22 @@ type Querier interface {
|
||||
// Owner-scoped newest-first list. It omits descriptions, complaint reason,
|
||||
// and event history. The tuple cursor matches the composite sort key.
|
||||
ListOwnedSupportCases(ctx context.Context, arg ListOwnedSupportCasesParams) ([]ListOwnedSupportCasesRow, error)
|
||||
// Candidates with a saved profile for the backfill, in identifier order
|
||||
// after a cursor. The job of a candidate who is not published removes the
|
||||
// stored vectors, so a backfill also cleans up after a closed card.
|
||||
ListProfileCandidatesAfter(ctx context.Context, arg ListProfileCandidatesAfterParams) ([]pgtype.UUID, error)
|
||||
// The digests of the stored rows of a subject and model, for the job that
|
||||
// decides whether anything changed.
|
||||
ListSemanticVectorDigests(ctx context.Context, arg ListSemanticVectorDigestsParams) ([]ListSemanticVectorDigestsRow, error)
|
||||
// Organization-facing anonymous candidate projection inputs. The calling
|
||||
// usecase has already authorized the active organization membership. This
|
||||
// single statement snapshot filters both revoked/unpublished C2 states and
|
||||
// candidates hidden from this organization before any profile value is read.
|
||||
// The projection reads only stack, declared role, and experience dates. It
|
||||
// deliberately excludes names, contacts, salary, location, soft skills,
|
||||
// employer names, summaries, and imported excerpts. The only assessment data
|
||||
// The projection reads only stack, declared role, experience dates, and
|
||||
// projects with the keys of their verified repositories. It deliberately
|
||||
// excludes names, contacts, salary, location, soft skills, employer names,
|
||||
// summaries, and imported excerpts; the repository address of a project stays
|
||||
// in the private input and never reaches the card. The only assessment data
|
||||
// is the current category (specialization and grade) of the separate current
|
||||
// category table; it carries no attempt, score, review, policy, or history.
|
||||
ListVisibleCandidateViewSources(ctx context.Context, organizationID pgtype.UUID) ([]ListVisibleCandidateViewSourcesRow, error)
|
||||
@@ -904,6 +940,10 @@ type Querier interface {
|
||||
LockPublicationForCandidatePreview(ctx context.Context, candidateID pgtype.UUID) (pgtype.UUID, error)
|
||||
// Locks the active registration C1 while its pending registration is applied.
|
||||
LockRegistrationConsentRecord(ctx context.Context, arg LockRegistrationConsentRecordParams) (LockRegistrationConsentRecordRow, error)
|
||||
// Serializes the vector jobs of one subject: a job takes this lock before it
|
||||
// reads the subject, so the job that runs last also read last and its vectors
|
||||
// describe the latest committed state. User requests never take it.
|
||||
LockSemanticSubject(ctx context.Context, lockKey int64) error
|
||||
// Serialize per-owner budget checks even before the first event exists.
|
||||
LockSupportCaseRequestBudget(ctx context.Context, ownerID pgtype.UUID) error
|
||||
// Lock and recheck one candidate's exact current publication only after the
|
||||
@@ -1080,6 +1120,8 @@ type Querier interface {
|
||||
// the job did not cause the failure. The same guard as the completion
|
||||
// applies, one (id, attempt) pair per job. It returns the IDs it released.
|
||||
ReleaseScheduledJobs(ctx context.Context, arg ReleaseScheduledJobsParams) ([]int64, error)
|
||||
// A new repository starts pending; a known one only records the request.
|
||||
RequestCandidateProjectRepositoryCheck(ctx context.Context, arg RequestCandidateProjectRepositoryCheckParams) error
|
||||
// Stores the replay record of a command. A record whose retention has passed
|
||||
// is replaced, so the key is accepted as new after the retention. A live
|
||||
// record is left as it is and nothing is returned; the caller then reads it
|
||||
@@ -1109,6 +1151,7 @@ type Querier interface {
|
||||
// grading policy is read from the immutable opening, and the guard trigger
|
||||
// compares it with the policy captured in the assigned result.
|
||||
SaveCandidateAssessmentCategory(ctx context.Context, arg SaveCandidateAssessmentCategoryParams) (int64, error)
|
||||
SaveCandidateProjectRepositoryCheck(ctx context.Context, arg SaveCandidateProjectRepositoryCheckParams) error
|
||||
SaveCompanyCardViewQuotaUsage(ctx context.Context, arg SaveCompanyCardViewQuotaUsageParams) error
|
||||
SaveInvitationCreationResult(ctx context.Context, arg SaveInvitationCreationResultParams) error
|
||||
// Stores the immutable domain snapshot of a successful create command. The
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: semantic.sql
|
||||
|
||||
package sqlc
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const deleteSemanticVectorsOfModel = `-- name: DeleteSemanticVectorsOfModel :exec
|
||||
|
||||
DELETE FROM semantic_vectors
|
||||
WHERE
|
||||
subject_kind = $1
|
||||
AND subject_id = $2
|
||||
AND model_id = $3
|
||||
AND model_revision = $4
|
||||
AND prompt_version = $5
|
||||
`
|
||||
|
||||
type DeleteSemanticVectorsOfModelParams struct {
|
||||
SubjectKind string
|
||||
SubjectID pgtype.UUID
|
||||
ModelID string
|
||||
ModelRevision string
|
||||
PromptVersion string
|
||||
}
|
||||
|
||||
// Stored embedding vectors. A candidate keeps one set of rows for a model:
|
||||
// the job deletes every other row of the candidate and model before it
|
||||
// inserts the new set, in one transaction. A need keeps the rows of its
|
||||
// latest computed requirements snapshot the same way.
|
||||
func (q *Queries) DeleteSemanticVectorsOfModel(ctx context.Context, arg DeleteSemanticVectorsOfModelParams) error {
|
||||
_, err := q.db.Exec(ctx, deleteSemanticVectorsOfModel,
|
||||
arg.SubjectKind,
|
||||
arg.SubjectID,
|
||||
arg.ModelID,
|
||||
arg.ModelRevision,
|
||||
arg.PromptVersion,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const deleteSemanticVectorsOfSubject = `-- name: DeleteSemanticVectorsOfSubject :exec
|
||||
DELETE FROM semantic_vectors
|
||||
WHERE subject_kind = $1 AND subject_id = $2
|
||||
`
|
||||
|
||||
type DeleteSemanticVectorsOfSubjectParams struct {
|
||||
SubjectKind string
|
||||
SubjectID pgtype.UUID
|
||||
}
|
||||
|
||||
// Removes every vector of a subject, of any model: a closed card or a need
|
||||
// without requirements keeps no derived data.
|
||||
func (q *Queries) DeleteSemanticVectorsOfSubject(ctx context.Context, arg DeleteSemanticVectorsOfSubjectParams) error {
|
||||
_, err := q.db.Exec(ctx, deleteSemanticVectorsOfSubject, arg.SubjectKind, arg.SubjectID)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertSemanticVector = `-- name: InsertSemanticVector :exec
|
||||
INSERT INTO semantic_vectors (
|
||||
subject_kind, subject_id, candidate_id, need_id, model_id, model_revision,
|
||||
prompt_version, item_key, content_sha256, label_sha256, dimension, vector,
|
||||
computed_at
|
||||
) VALUES (
|
||||
$1, $2, $3,
|
||||
$4, $5, $6,
|
||||
$7, $8, $9,
|
||||
$10, $11, $12,
|
||||
$13
|
||||
)
|
||||
`
|
||||
|
||||
type InsertSemanticVectorParams struct {
|
||||
SubjectKind string
|
||||
SubjectID pgtype.UUID
|
||||
CandidateID pgtype.UUID
|
||||
NeedID pgtype.UUID
|
||||
ModelID string
|
||||
ModelRevision string
|
||||
PromptVersion string
|
||||
ItemKey string
|
||||
ContentSha256 []byte
|
||||
LabelSha256 []byte
|
||||
Dimension int32
|
||||
Vector []byte
|
||||
ComputedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
func (q *Queries) InsertSemanticVector(ctx context.Context, arg InsertSemanticVectorParams) error {
|
||||
_, err := q.db.Exec(ctx, insertSemanticVector,
|
||||
arg.SubjectKind,
|
||||
arg.SubjectID,
|
||||
arg.CandidateID,
|
||||
arg.NeedID,
|
||||
arg.ModelID,
|
||||
arg.ModelRevision,
|
||||
arg.PromptVersion,
|
||||
arg.ItemKey,
|
||||
arg.ContentSha256,
|
||||
arg.LabelSha256,
|
||||
arg.Dimension,
|
||||
arg.Vector,
|
||||
arg.ComputedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const listCandidateItemVectors = `-- name: ListCandidateItemVectors :many
|
||||
SELECT candidate_id, item_key, label_sha256, dimension, vector
|
||||
FROM semantic_vectors
|
||||
WHERE
|
||||
subject_kind = 'candidate'
|
||||
AND item_key <> 'whole'
|
||||
AND model_id = $1
|
||||
AND model_revision = $2
|
||||
AND prompt_version = $3
|
||||
AND candidate_id = ANY($4::uuid [])
|
||||
ORDER BY candidate_id, item_key
|
||||
`
|
||||
|
||||
type ListCandidateItemVectorsParams struct {
|
||||
ModelID string
|
||||
ModelRevision string
|
||||
PromptVersion string
|
||||
CandidateIds []pgtype.UUID
|
||||
}
|
||||
|
||||
type ListCandidateItemVectorsRow struct {
|
||||
CandidateID pgtype.UUID
|
||||
ItemKey string
|
||||
LabelSha256 []byte
|
||||
Dimension int32
|
||||
Vector []byte
|
||||
}
|
||||
|
||||
// The item vectors of the candidates that a search returns, at most a few
|
||||
// dozen candidates.
|
||||
func (q *Queries) ListCandidateItemVectors(ctx context.Context, arg ListCandidateItemVectorsParams) ([]ListCandidateItemVectorsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listCandidateItemVectors,
|
||||
arg.ModelID,
|
||||
arg.ModelRevision,
|
||||
arg.PromptVersion,
|
||||
arg.CandidateIds,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListCandidateItemVectorsRow
|
||||
for rows.Next() {
|
||||
var i ListCandidateItemVectorsRow
|
||||
if err := rows.Scan(
|
||||
&i.CandidateID,
|
||||
&i.ItemKey,
|
||||
&i.LabelSha256,
|
||||
&i.Dimension,
|
||||
&i.Vector,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listCandidateWholeVectors = `-- name: ListCandidateWholeVectors :many
|
||||
SELECT candidate_id, dimension, vector
|
||||
FROM semantic_vectors
|
||||
WHERE
|
||||
subject_kind = 'candidate'
|
||||
AND item_key = 'whole'
|
||||
AND model_id = $1
|
||||
AND model_revision = $2
|
||||
AND prompt_version = $3
|
||||
AND candidate_id = ANY($4::uuid [])
|
||||
ORDER BY candidate_id
|
||||
`
|
||||
|
||||
type ListCandidateWholeVectorsParams struct {
|
||||
ModelID string
|
||||
ModelRevision string
|
||||
PromptVersion string
|
||||
CandidateIds []pgtype.UUID
|
||||
}
|
||||
|
||||
type ListCandidateWholeVectorsRow struct {
|
||||
CandidateID pgtype.UUID
|
||||
Dimension int32
|
||||
Vector []byte
|
||||
}
|
||||
|
||||
// The whole-view vectors of the candidates of one search.
|
||||
func (q *Queries) ListCandidateWholeVectors(ctx context.Context, arg ListCandidateWholeVectorsParams) ([]ListCandidateWholeVectorsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listCandidateWholeVectors,
|
||||
arg.ModelID,
|
||||
arg.ModelRevision,
|
||||
arg.PromptVersion,
|
||||
arg.CandidateIds,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListCandidateWholeVectorsRow
|
||||
for rows.Next() {
|
||||
var i ListCandidateWholeVectorsRow
|
||||
if err := rows.Scan(&i.CandidateID, &i.Dimension, &i.Vector); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listNeedVectors = `-- name: ListNeedVectors :many
|
||||
SELECT item_key, content_sha256, dimension, vector
|
||||
FROM semantic_vectors
|
||||
WHERE
|
||||
subject_kind = 'need'
|
||||
AND need_id = $1
|
||||
AND model_id = $2
|
||||
AND model_revision = $3
|
||||
AND prompt_version = $4
|
||||
AND content_sha256 = ANY($5::bytea [])
|
||||
ORDER BY item_key
|
||||
`
|
||||
|
||||
type ListNeedVectorsParams struct {
|
||||
NeedID pgtype.UUID
|
||||
ModelID string
|
||||
ModelRevision string
|
||||
PromptVersion string
|
||||
ContentDigests [][]byte
|
||||
}
|
||||
|
||||
type ListNeedVectorsRow struct {
|
||||
ItemKey string
|
||||
ContentSha256 []byte
|
||||
Dimension int32
|
||||
Vector []byte
|
||||
}
|
||||
|
||||
// The vectors of a need whose texts match the given digests of the
|
||||
// requirements snapshot that the search renders.
|
||||
func (q *Queries) ListNeedVectors(ctx context.Context, arg ListNeedVectorsParams) ([]ListNeedVectorsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listNeedVectors,
|
||||
arg.NeedID,
|
||||
arg.ModelID,
|
||||
arg.ModelRevision,
|
||||
arg.PromptVersion,
|
||||
arg.ContentDigests,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListNeedVectorsRow
|
||||
for rows.Next() {
|
||||
var i ListNeedVectorsRow
|
||||
if err := rows.Scan(
|
||||
&i.ItemKey,
|
||||
&i.ContentSha256,
|
||||
&i.Dimension,
|
||||
&i.Vector,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listNeedsAfter = `-- name: ListNeedsAfter :many
|
||||
SELECT id, organization_id, requirements_version
|
||||
FROM organization_needs
|
||||
WHERE id > $1
|
||||
ORDER BY id
|
||||
LIMIT $2
|
||||
`
|
||||
|
||||
type ListNeedsAfterParams struct {
|
||||
AfterID pgtype.UUID
|
||||
PageSize int32
|
||||
}
|
||||
|
||||
type ListNeedsAfterRow struct {
|
||||
ID pgtype.UUID
|
||||
OrganizationID pgtype.UUID
|
||||
RequirementsVersion int64
|
||||
}
|
||||
|
||||
// Needs and their current requirements snapshot for the backfill.
|
||||
func (q *Queries) ListNeedsAfter(ctx context.Context, arg ListNeedsAfterParams) ([]ListNeedsAfterRow, error) {
|
||||
rows, err := q.db.Query(ctx, listNeedsAfter, arg.AfterID, arg.PageSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListNeedsAfterRow
|
||||
for rows.Next() {
|
||||
var i ListNeedsAfterRow
|
||||
if err := rows.Scan(&i.ID, &i.OrganizationID, &i.RequirementsVersion); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listProfileCandidatesAfter = `-- name: ListProfileCandidatesAfter :many
|
||||
SELECT profiles.user_id
|
||||
FROM candidate_profiles AS profiles
|
||||
WHERE profiles.user_id > $1
|
||||
ORDER BY profiles.user_id
|
||||
LIMIT $2
|
||||
`
|
||||
|
||||
type ListProfileCandidatesAfterParams struct {
|
||||
AfterID pgtype.UUID
|
||||
PageSize int32
|
||||
}
|
||||
|
||||
// Candidates with a saved profile for the backfill, in identifier order
|
||||
// after a cursor. The job of a candidate who is not published removes the
|
||||
// stored vectors, so a backfill also cleans up after a closed card.
|
||||
func (q *Queries) ListProfileCandidatesAfter(ctx context.Context, arg ListProfileCandidatesAfterParams) ([]pgtype.UUID, error) {
|
||||
rows, err := q.db.Query(ctx, listProfileCandidatesAfter, arg.AfterID, arg.PageSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []pgtype.UUID
|
||||
for rows.Next() {
|
||||
var user_id pgtype.UUID
|
||||
if err := rows.Scan(&user_id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, user_id)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listSemanticVectorDigests = `-- name: ListSemanticVectorDigests :many
|
||||
SELECT item_key, content_sha256
|
||||
FROM semantic_vectors
|
||||
WHERE
|
||||
subject_kind = $1
|
||||
AND subject_id = $2
|
||||
AND model_id = $3
|
||||
AND model_revision = $4
|
||||
AND prompt_version = $5
|
||||
ORDER BY item_key, content_sha256
|
||||
`
|
||||
|
||||
type ListSemanticVectorDigestsParams struct {
|
||||
SubjectKind string
|
||||
SubjectID pgtype.UUID
|
||||
ModelID string
|
||||
ModelRevision string
|
||||
PromptVersion string
|
||||
}
|
||||
|
||||
type ListSemanticVectorDigestsRow struct {
|
||||
ItemKey string
|
||||
ContentSha256 []byte
|
||||
}
|
||||
|
||||
// The digests of the stored rows of a subject and model, for the job that
|
||||
// decides whether anything changed.
|
||||
func (q *Queries) ListSemanticVectorDigests(ctx context.Context, arg ListSemanticVectorDigestsParams) ([]ListSemanticVectorDigestsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listSemanticVectorDigests,
|
||||
arg.SubjectKind,
|
||||
arg.SubjectID,
|
||||
arg.ModelID,
|
||||
arg.ModelRevision,
|
||||
arg.PromptVersion,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListSemanticVectorDigestsRow
|
||||
for rows.Next() {
|
||||
var i ListSemanticVectorDigestsRow
|
||||
if err := rows.Scan(&i.ItemKey, &i.ContentSha256); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockSemanticSubject = `-- name: LockSemanticSubject :exec
|
||||
SELECT pg_advisory_xact_lock($1::bigint)
|
||||
`
|
||||
|
||||
// Serializes the vector jobs of one subject: a job takes this lock before it
|
||||
// reads the subject, so the job that runs last also read last and its vectors
|
||||
// describe the latest committed state. User requests never take it.
|
||||
func (q *Queries) LockSemanticSubject(ctx context.Context, lockKey int64) error {
|
||||
_, err := q.db.Exec(ctx, lockSemanticSubject, lockKey)
|
||||
return err
|
||||
}
|
||||
@@ -233,6 +233,7 @@ var problemCodes = []string{
|
||||
"state_conflict", "version_conflict", "payload_too_large", "unsupported_media_type",
|
||||
"idempotency_key_reused", "precondition_required", "rate_limited", "internal",
|
||||
"not_implemented",
|
||||
"service_unavailable",
|
||||
}
|
||||
|
||||
// ObserveProblem counts one error response. A code outside the contract
|
||||
|
||||
@@ -49,7 +49,12 @@ func newJobWorker(
|
||||
logger *slog.Logger,
|
||||
metrics *prometheus.Metrics,
|
||||
) (*jobrunner.Worker, func(), error) {
|
||||
return buildJobWorker(ctx, settings, logger, metrics, jobHandlers(logger.With(slog.String("component", "assessment_review"))))
|
||||
handlers := jobHandlers(logger.With(slog.String("component", "assessment_review")))
|
||||
semanticHandlers, err := semanticJobHandlers(settings, logger.With(slog.String("component", "semantic")))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return buildJobWorker(ctx, settings, logger, metrics, append(handlers, semanticHandlers...))
|
||||
}
|
||||
|
||||
// buildJobWorker builds the scheduled job worker and the PostgreSQL pool it
|
||||
|
||||
@@ -36,6 +36,7 @@ func newNeedHandler(
|
||||
Transactor: postgres.NewTransactor(pool),
|
||||
Keyring: keyring,
|
||||
Clock: time.Now,
|
||||
Semantic: newSemanticTrigger(settings),
|
||||
})
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
|
||||
@@ -47,7 +47,9 @@ func newPrivacyHandler(
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newPrivacyHandler - create view service: %w", err)
|
||||
}
|
||||
privacy, err := candidateprivacy.NewService(candidateprivacy.Dependencies{Transactor: transactor, Clock: time.Now})
|
||||
privacy, err := candidateprivacy.NewService(candidateprivacy.Dependencies{
|
||||
Transactor: transactor, Clock: time.Now, Semantic: newSemanticTrigger(settings),
|
||||
})
|
||||
if err != nil {
|
||||
pool.Close()
|
||||
return nil, nil, fmt.Errorf("bootstrap.newPrivacyHandler - create settings service: %w", err)
|
||||
|
||||
@@ -22,6 +22,7 @@ func newProfileHandler(ctx context.Context, settings config.Config, logger *slog
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
service := profileusecase.NewService(postgres.NewTransactor(pool), time.Now)
|
||||
service := profileusecase.NewService(postgres.NewTransactor(pool), time.Now).
|
||||
WithSemantic(newSemanticTrigger(settings), settings.Semantic.RepositoryCheckInterval)
|
||||
return v1.NewProfileHandler(service), pool.Close, nil
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"lincodex/backend/config"
|
||||
"lincodex/backend/internal/adapter/secondary/github"
|
||||
"lincodex/backend/internal/adapter/secondary/ml"
|
||||
"lincodex/backend/internal/port/inbound"
|
||||
"lincodex/backend/internal/usecase/semantic"
|
||||
)
|
||||
|
||||
// newSemanticTrigger returns the scheduler of the enabled background work.
|
||||
// It is never nil; with both features off it schedules no job.
|
||||
func newSemanticTrigger(settings config.Config) *semantic.Trigger {
|
||||
return semantic.NewTrigger(settings.Semantic.SemanticMatchingEnabled, settings.Semantic.GitHubChecksEnabled)
|
||||
}
|
||||
|
||||
// semanticJobHandlers registers the vector jobs when semantic matching is on
|
||||
// and the repository check when GitHub checks are on. Jobs of a kind without
|
||||
// a handler wait in the database, so turning a feature off never loses work.
|
||||
func semanticJobHandlers(settings config.Config, logger *slog.Logger) ([]inbound.JobHandler, error) {
|
||||
var handlers []inbound.JobHandler
|
||||
trigger := newSemanticTrigger(settings)
|
||||
if settings.Semantic.SemanticMatchingEnabled {
|
||||
embedder, err := ml.NewEmbedder(ml.Settings{
|
||||
BaseURL: settings.Semantic.MLServiceURL, Timeout: settings.Semantic.MLRequestTimeout,
|
||||
FailureThreshold: settings.Semantic.MLCircuitFailures, OpenDuration: settings.Semantic.MLCircuitOpen,
|
||||
}, time.Now)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bootstrap.semanticJobHandlers - create ML client: %w", err)
|
||||
}
|
||||
jobs, err := semantic.NewVectorJobs(embedder, time.Now, logger)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bootstrap.semanticJobHandlers - create vector jobs: %w", err)
|
||||
}
|
||||
handlers = append(handlers, jobs.CandidateHandler(), jobs.NeedHandler())
|
||||
} else {
|
||||
logger.Info("semantic matching is disabled; searches use the neutral semantic value")
|
||||
}
|
||||
if settings.Semantic.GitHubChecksEnabled {
|
||||
fetcher, err := github.NewFetcher(settings.Semantic.GitHubTimeout, settings.Semantic.GitHubToken, time.Now)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bootstrap.semanticJobHandlers - create GitHub fetcher: %w", err)
|
||||
}
|
||||
check, err := semantic.NewRepositoryCheckJob(fetcher, trigger, time.Now, logger)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("bootstrap.semanticJobHandlers - create repository check: %w", err)
|
||||
}
|
||||
handlers = append(handlers, check)
|
||||
}
|
||||
return handlers, nil
|
||||
}
|
||||
@@ -444,9 +444,12 @@ type CandidateProfileInput struct {
|
||||
// the exact periods and indices in Experience.
|
||||
ParallelPeriodAcknowledgements []ProfileParallelPeriodAcknowledgement
|
||||
SoftSkills []ProfileClaimInput[string]
|
||||
Location *ProfileClaimInput[string]
|
||||
Relocation *ProfileClaimInput[bool]
|
||||
SalaryMinimum *ProfileClaimInput[ProfileSalaryMinimum]
|
||||
// Projects replaces the stored projects; nil keeps them, so a client
|
||||
// that does not know the section never deletes it.
|
||||
Projects *[]ProfileClaimInput[ProfileProject]
|
||||
Location *ProfileClaimInput[string]
|
||||
Relocation *ProfileClaimInput[bool]
|
||||
SalaryMinimum *ProfileClaimInput[ProfileSalaryMinimum]
|
||||
}
|
||||
|
||||
// CandidateProfileContent is the validated content of a profile: every claim
|
||||
@@ -464,6 +467,7 @@ type CandidateProfileContent struct {
|
||||
experience []ProfileClaim[ProfileExperience]
|
||||
parallelPeriodAcknowledgements []ProfileParallelPeriodAcknowledgement
|
||||
softSkills []ProfileClaim[string]
|
||||
projects []ProfileClaim[ProfileProject]
|
||||
location *ProfileClaim[string]
|
||||
relocation *ProfileClaim[bool]
|
||||
salaryMinimum *ProfileClaim[ProfileSalaryMinimum]
|
||||
@@ -562,6 +566,12 @@ func (content CandidateProfileContent) SoftSkills() []ProfileClaim[string] {
|
||||
return slices.Clone(content.softSkills)
|
||||
}
|
||||
|
||||
// Projects returns a copy of the projects in the order the candidate gave
|
||||
// them.
|
||||
func (content CandidateProfileContent) Projects() []ProfileClaim[ProfileProject] {
|
||||
return slices.Clone(content.projects)
|
||||
}
|
||||
|
||||
// Equal reports whether both contents hold the same claims with the same
|
||||
// provenance, which tells a change from a body that changes nothing.
|
||||
func (content CandidateProfileContent) Equal(other CandidateProfileContent) bool {
|
||||
@@ -576,7 +586,8 @@ func (content CandidateProfileContent) Equal(other CandidateProfileContent) bool
|
||||
slices.EqualFunc(content.roles, other.roles, claimsEqual) &&
|
||||
slices.EqualFunc(content.experience, other.experience, claimsEqual) &&
|
||||
slices.Equal(content.parallelPeriodAcknowledgements, other.parallelPeriodAcknowledgements) &&
|
||||
slices.EqualFunc(content.softSkills, other.softSkills, claimsEqual)
|
||||
slices.EqualFunc(content.softSkills, other.softSkills, claimsEqual) &&
|
||||
slices.EqualFunc(content.projects, other.projects, claimsEqual)
|
||||
}
|
||||
|
||||
func (CandidateProfileContent) String() string { return redactedProfile }
|
||||
@@ -790,6 +801,7 @@ type profileRules struct {
|
||||
softSkills claimRules[string]
|
||||
roles claimRules[ProfileRole]
|
||||
experience claimRules[ProfileExperience]
|
||||
projects claimRules[ProfileProject]
|
||||
}
|
||||
|
||||
func newProfileRules(now time.Time) profileRules {
|
||||
@@ -815,6 +827,7 @@ func newProfileRules(now time.Time) profileRules {
|
||||
validate: roleRules, key: func(role ProfileRole) string { return string(role.Specialization) }, keyPointer: "/specialization",
|
||||
},
|
||||
experience: claimRules[ProfileExperience]{validate: experienceRules(now)},
|
||||
projects: claimRules[ProfileProject]{validate: projectRules, key: projectKey, keyPointer: "/repository_url"},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1028,6 +1041,14 @@ func ResolveCandidateProfileContent(stored CandidateProfileContent, input Candid
|
||||
content.softSkills, err = resolveItems(rules.softSkills, location, "/soft_skills", input.SoftSkills, stored.softSkills, maxProfileSoftSkills, at)
|
||||
return err
|
||||
},
|
||||
func() (err error) {
|
||||
if input.Projects == nil {
|
||||
content.projects = slices.Clone(stored.projects)
|
||||
return nil
|
||||
}
|
||||
content.projects, err = resolveItems(rules.projects, location, "/projects", *input.Projects, stored.projects, maxProfileProjects, at)
|
||||
return err
|
||||
},
|
||||
func() (err error) {
|
||||
content.location, err = resolveOptional(rules.location, location, "/terms/location", input.Location, stored.location, at)
|
||||
return err
|
||||
@@ -1188,6 +1209,7 @@ const (
|
||||
profileKindLocation = "terms_location"
|
||||
profileKindRelocation = "terms_relocation"
|
||||
profileKindSalaryMinimum = "terms_salary_minimum"
|
||||
profileKindProject = "project"
|
||||
)
|
||||
|
||||
// StoredProfileClaim is a claim as the claims table holds it: the kind, the
|
||||
@@ -1302,6 +1324,7 @@ func (content CandidateProfileContent) StoredClaims() ([]StoredProfileClaim, err
|
||||
entries = appendList(entries, profileKindRole, content.roles, roleStoredValue)
|
||||
entries = appendList(entries, profileKindExperience, content.experience, experienceStoredValue)
|
||||
entries = appendList(entries, profileKindSoftSkill, content.softSkills, plainValue[string])
|
||||
entries = appendList(entries, profileKindProject, content.projects, projectStoredValue)
|
||||
|
||||
rows := make([]StoredProfileClaim, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
@@ -1394,6 +1417,8 @@ func restoreCandidateProfileClaim(
|
||||
return restoreItem(&content.roles, rules.roles, row, status, source)
|
||||
case profileKindExperience:
|
||||
return restoreItem(&content.experience, rules.experience, row, status, source)
|
||||
case profileKindProject:
|
||||
return restoreItem(&content.projects, rules.projects, row, status, source)
|
||||
default:
|
||||
return errors.New("kind is unknown")
|
||||
}
|
||||
@@ -1443,6 +1468,15 @@ func decodeStoredValue[V comparable](row StoredProfileClaim) (V, error) {
|
||||
EmployerName: stringOrEmpty(stored.EmployerName), Specialization: SpecializationCode(stored.Specialization),
|
||||
StartedOn: stored.StartedOn, EndedOn: stringOrEmpty(stored.EndedOn), Summary: stringOrEmpty(stored.Summary),
|
||||
}
|
||||
case *ProfileProject:
|
||||
var stored storedProjectValue
|
||||
if err := decodeStrictJSON(row.Value, &stored); err != nil {
|
||||
return value, err
|
||||
}
|
||||
if stored.Stack == nil {
|
||||
return value, errors.New("value has an unexpected shape")
|
||||
}
|
||||
*target = NewProfileProject(stored.Title, stringOrEmpty(stored.Description), stored.Stack, stringOrEmpty(stored.RepositoryURL))
|
||||
case *ProfileSalaryMinimum:
|
||||
var stored storedSalaryValue
|
||||
if err := decodeStrictJSON(row.Value, &stored); err != nil {
|
||||
|
||||
@@ -90,7 +90,7 @@ func validateCandidateCardAccessFields(input CandidateCardAccessInput, requireAc
|
||||
}
|
||||
switch input.Kind {
|
||||
case CandidateCardAccessCardViewed:
|
||||
if len(input.ContactFields) != 0 || len(input.ProjectionFields) > 6 {
|
||||
if len(input.ContactFields) != 0 || len(input.ProjectionFields) > maxCardViewedFields {
|
||||
return ErrInvalidCandidateCardAccess
|
||||
}
|
||||
seen := make(map[CardField]struct{}, len(input.ProjectionFields))
|
||||
@@ -116,10 +116,14 @@ func validateCandidateCardAccessFields(input CandidateCardAccessInput, requireAc
|
||||
return nil
|
||||
}
|
||||
|
||||
// maxCardViewedFields is the number of card groups that a view can return;
|
||||
// the CHECK of candidate_card_access_events allows the same.
|
||||
const maxCardViewedFields = 7
|
||||
|
||||
func candidateCardProjectionField(field CardField) bool {
|
||||
switch field {
|
||||
case CardFieldCategories, CardFieldStack, CardFieldExperience, CardFieldSelfAssessment,
|
||||
CardFieldWorkFormats, CardFieldSalaryCompatibility:
|
||||
CardFieldWorkFormats, CardFieldSalaryCompatibility, CardFieldProjects:
|
||||
return true
|
||||
case CardFieldSoftSkills, CardFieldLocation, CardFieldRelocation:
|
||||
return false
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// ErrInvalidGitHubRepository reports a repository address that is not a
|
||||
// GitHub repository address of the accepted form.
|
||||
var ErrInvalidGitHubRepository = errors.New("invalid GitHub repository address")
|
||||
|
||||
const (
|
||||
maxProfileProjects = 10
|
||||
maxProfileProjectTitleRunes = 100
|
||||
maxProfileProjectDescription = 500
|
||||
maxProfileProjectStackItems = 10
|
||||
maxRepositoryURLRunes = 160
|
||||
githubRepositoryPrefix = "https://github.com/"
|
||||
// projectStackSeparator joins the tags of a project into one comparable
|
||||
// string. A tag is one line, so a line break never occurs inside one.
|
||||
projectStackSeparator = "\n"
|
||||
)
|
||||
|
||||
var (
|
||||
// GitHub owner names: letters, digits, and single hyphens, at most 39
|
||||
// characters, not starting with a hyphen.
|
||||
githubOwnerPattern = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$`)
|
||||
// GitHub repository names: letters, digits, '.', '_', and '-'.
|
||||
githubNamePattern = regexp.MustCompile(`^[A-Za-z0-9._-]{1,100}$`)
|
||||
)
|
||||
|
||||
// GitHubRepository is a validated public repository coordinate. Owner and
|
||||
// Name keep the letter case the candidate typed; Key is the lower-case form
|
||||
// that GitHub treats as the same repository.
|
||||
type GitHubRepository struct {
|
||||
owner string
|
||||
name string
|
||||
}
|
||||
|
||||
// ParseGitHubRepositoryURL accepts only https://github.com/<owner>/<name>
|
||||
// with an optional trailing slash or .git suffix. Any other scheme, host,
|
||||
// port, user information, query, fragment, or path is rejected, so the
|
||||
// address can never point the server at another host.
|
||||
func ParseGitHubRepositoryURL(raw string) (GitHubRepository, error) {
|
||||
const location = "domain.ParseGitHubRepositoryURL"
|
||||
fail := func(reason string) (GitHubRepository, error) {
|
||||
return GitHubRepository{}, fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidGitHubRepository)
|
||||
}
|
||||
if !utf8.ValidString(raw) || utf8.RuneCountInString(raw) > maxRepositoryURLRunes {
|
||||
return fail("address is too long or not UTF-8")
|
||||
}
|
||||
if !strings.HasPrefix(raw, githubRepositoryPrefix) {
|
||||
return fail("address must start with https://github.com/")
|
||||
}
|
||||
path := strings.TrimPrefix(raw, githubRepositoryPrefix)
|
||||
path = strings.TrimSuffix(path, "/")
|
||||
parts := strings.Split(path, "/")
|
||||
if len(parts) != 2 {
|
||||
return fail("address must name exactly an owner and a repository")
|
||||
}
|
||||
owner, name := parts[0], strings.TrimSuffix(parts[1], ".git")
|
||||
switch {
|
||||
case !githubOwnerPattern.MatchString(owner) || strings.Contains(owner, "--"):
|
||||
return fail("owner is not a GitHub account name")
|
||||
case !githubNamePattern.MatchString(name) || name == "." || name == "..":
|
||||
return fail("repository is not a GitHub repository name")
|
||||
}
|
||||
return GitHubRepository{owner: owner, name: name}, nil
|
||||
}
|
||||
|
||||
// Owner returns the account part of the address.
|
||||
func (repository GitHubRepository) Owner() string { return repository.owner }
|
||||
|
||||
// Name returns the repository part of the address.
|
||||
func (repository GitHubRepository) Name() string { return repository.name }
|
||||
|
||||
// URL returns the canonical address https://github.com/<owner>/<name>.
|
||||
func (repository GitHubRepository) URL() string {
|
||||
return githubRepositoryPrefix + repository.owner + "/" + repository.name
|
||||
}
|
||||
|
||||
// Key is "<owner>/<name>" in lower case: the identity of the repository for
|
||||
// deduplication and for its stored check.
|
||||
func (repository GitHubRepository) Key() string {
|
||||
return strings.ToLower(repository.owner + "/" + repository.name)
|
||||
}
|
||||
|
||||
// IsZero reports a repository that was not parsed.
|
||||
func (repository GitHubRepository) IsZero() bool { return repository.owner == "" }
|
||||
|
||||
// The coordinate names an account, so formatting redacts it like profile data.
|
||||
func (GitHubRepository) String() string { return redactedProfile }
|
||||
func (GitHubRepository) GoString() string { return redactedProfile }
|
||||
func (GitHubRepository) LogValue() slog.Value {
|
||||
return slog.StringValue(redactedProfile)
|
||||
}
|
||||
func (GitHubRepository) Format(state fmt.State, _ rune) { writeRedacted(state, redactedProfile) }
|
||||
|
||||
// ProfileProject is one project of the profile. Description and
|
||||
// RepositoryURL are "" when not given. The stack is kept as one string so the
|
||||
// value stays comparable; StackTags returns the tags. The project is personal
|
||||
// data: formatting redacts it.
|
||||
type ProfileProject struct {
|
||||
Title string
|
||||
Description string
|
||||
RepositoryURL string
|
||||
stack string
|
||||
}
|
||||
|
||||
// NewProfileProject builds a project value from request parts. Validation
|
||||
// happens when the profile resolves it.
|
||||
func NewProfileProject(title, description string, stack []string, repositoryURL string) ProfileProject {
|
||||
return ProfileProject{
|
||||
Title: title, Description: description, RepositoryURL: repositoryURL,
|
||||
stack: strings.Join(stack, projectStackSeparator),
|
||||
}
|
||||
}
|
||||
|
||||
// StackTags returns the stack tags in the order the candidate gave them.
|
||||
func (project ProfileProject) StackTags() []string {
|
||||
if project.stack == "" {
|
||||
return nil
|
||||
}
|
||||
return strings.Split(project.stack, projectStackSeparator)
|
||||
}
|
||||
|
||||
// Repository returns the parsed repository and whether the project links one.
|
||||
func (project ProfileProject) Repository() (GitHubRepository, bool) {
|
||||
if project.RepositoryURL == "" {
|
||||
return GitHubRepository{}, false
|
||||
}
|
||||
repository, err := ParseGitHubRepositoryURL(project.RepositoryURL)
|
||||
if err != nil {
|
||||
return GitHubRepository{}, false
|
||||
}
|
||||
return repository, true
|
||||
}
|
||||
|
||||
func (ProfileProject) String() string { return redactedProfile }
|
||||
func (ProfileProject) GoString() string { return redactedProfile }
|
||||
func (ProfileProject) LogValue() slog.Value {
|
||||
return slog.StringValue(redactedProfile)
|
||||
}
|
||||
func (ProfileProject) Format(state fmt.State, _ rune) { writeRedacted(state, redactedProfile) }
|
||||
|
||||
// projectRules validates and normalizes one project. The repository address
|
||||
// becomes canonical, so a trailing slash or a .git suffix never creates a
|
||||
// second value for the same repository.
|
||||
func projectRules(value ProfileProject) (ProfileProject, string, string) {
|
||||
value.Description = strings.ReplaceAll(value.Description, "\r\n", "\n")
|
||||
if problem := singleLineTextProblem(value.Title, maxProfileProjectTitleRunes); problem != "" {
|
||||
return value, "/title", problem
|
||||
}
|
||||
if value.Description != "" {
|
||||
if problem := multiLineTextProblem(value.Description, maxProfileProjectDescription); problem != "" {
|
||||
return value, "/description", problem
|
||||
}
|
||||
}
|
||||
tags := value.StackTags()
|
||||
if len(tags) > maxProfileProjectStackItems {
|
||||
return value, "/stack", fmt.Sprintf("must have at most %d items", maxProfileProjectStackItems)
|
||||
}
|
||||
seen := make(map[string]struct{}, len(tags))
|
||||
for index, tag := range tags {
|
||||
if problem := singleLineTextProblem(tag, maxProfileTagRunes); problem != "" {
|
||||
return value, fmt.Sprintf("/stack/%d", index), problem
|
||||
}
|
||||
key := strings.ToLower(tag)
|
||||
if _, repeated := seen[key]; repeated {
|
||||
return value, fmt.Sprintf("/stack/%d", index), "must not repeat an earlier item"
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
}
|
||||
if value.RepositoryURL != "" {
|
||||
repository, err := ParseGitHubRepositoryURL(value.RepositoryURL)
|
||||
if err != nil {
|
||||
return value, "/repository_url", "must be a GitHub repository address https://github.com/<owner>/<repository>"
|
||||
}
|
||||
value.RepositoryURL = repository.URL()
|
||||
}
|
||||
return value, "", ""
|
||||
}
|
||||
|
||||
// projectKey identifies a project for the repeat rule: two projects may not
|
||||
// link the same repository. A project without a repository never repeats.
|
||||
func projectKey(value ProfileProject) string {
|
||||
repository, ok := value.Repository()
|
||||
if !ok {
|
||||
return "\x00" + value.Title + "\x00" + value.Description + "\x00" + value.stack
|
||||
}
|
||||
return repository.Key()
|
||||
}
|
||||
|
||||
// storedProjectValue is the JSON shape of a project claim that the CHECK of
|
||||
// candidate_profile_claims requires.
|
||||
type storedProjectValue struct {
|
||||
Title string `json:"title"`
|
||||
Description *string `json:"description"`
|
||||
Stack []string `json:"stack"`
|
||||
RepositoryURL *string `json:"repository_url"`
|
||||
}
|
||||
|
||||
func projectStoredValue(project ProfileProject) any {
|
||||
stack := project.StackTags()
|
||||
if stack == nil {
|
||||
stack = []string{}
|
||||
}
|
||||
return storedProjectValue{
|
||||
Title: project.Title, Description: optionalString(project.Description), Stack: stack,
|
||||
RepositoryURL: optionalString(project.RepositoryURL),
|
||||
}
|
||||
}
|
||||
|
||||
// ProjectRepositories returns the distinct repositories that the projects of
|
||||
// the content link, in project order.
|
||||
func (content CandidateProfileContent) ProjectRepositories() []GitHubRepository {
|
||||
var repositories []GitHubRepository
|
||||
seen := make(map[string]struct{})
|
||||
for _, claim := range content.projects {
|
||||
repository, ok := claim.value.Repository()
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if _, repeated := seen[repository.Key()]; repeated {
|
||||
continue
|
||||
}
|
||||
seen[repository.Key()] = struct{}{}
|
||||
repositories = append(repositories, repository)
|
||||
}
|
||||
return repositories
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestParseGitHubRepositoryURLAcceptsOnlyCanonicalGitHubAddresses(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
raw, url, key string
|
||||
}{
|
||||
{"https://github.com/Example-Org/Payments.Ledger", "https://github.com/Example-Org/Payments.Ledger", "example-org/payments.ledger"},
|
||||
{"https://github.com/example/repo/", "https://github.com/example/repo", "example/repo"},
|
||||
{"https://github.com/example/repo.git", "https://github.com/example/repo", "example/repo"},
|
||||
} {
|
||||
repository, err := ParseGitHubRepositoryURL(test.raw)
|
||||
if err != nil || repository.URL() != test.url || repository.Key() != test.key {
|
||||
t.Errorf("ParseGitHubRepositoryURL(%q) = %q %q, %v", test.raw, repository.URL(), repository.Key(), err)
|
||||
}
|
||||
}
|
||||
for _, raw := range []string{
|
||||
"http://github.com/example/repo",
|
||||
"https://gitlab.com/example/repo",
|
||||
"https://github.com.evil.example/example/repo",
|
||||
"https://user:secret@github.com/example/repo",
|
||||
"https://github.com:443/example/repo",
|
||||
"https://github.com/example",
|
||||
"https://github.com/example/repo/tree/main",
|
||||
"https://github.com/example/repo?tab=readme",
|
||||
"https://github.com/example/repo#readme",
|
||||
"https://github.com/-example/repo",
|
||||
"https://github.com/exa--mple/repo",
|
||||
"https://github.com/example/..",
|
||||
"https://github.com/example/re po",
|
||||
"https://github.com/../../evil",
|
||||
"https://api.github.com/repos/example/repo",
|
||||
"https://github.com/" + strings.Repeat("a", 40) + "/repo",
|
||||
"https://GITHUB.com/example/repo",
|
||||
} {
|
||||
if _, err := ParseGitHubRepositoryURL(raw); !errors.Is(err, ErrInvalidGitHubRepository) {
|
||||
t.Errorf("ParseGitHubRepositoryURL(%q) accepted an address outside the allowed form", raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGitHubRepositoryRedactsItselfInLogs(t *testing.T) {
|
||||
repository, err := ParseGitHubRepositoryURL("https://github.com/private-owner/repo")
|
||||
if err != nil {
|
||||
t.Fatalf("ParseGitHubRepositoryURL() error = %v", err)
|
||||
}
|
||||
if text := fmt.Sprintf("%v %+v %#v %s", repository, repository, repository, repository); strings.Contains(text, "private-owner") {
|
||||
t.Fatalf("formatting leaks the owner: %s", text)
|
||||
}
|
||||
}
|
||||
|
||||
func projectInput(title, description string, stack []string, repository string) ProfileClaimInput[ProfileProject] {
|
||||
return ProfileClaimInput[ProfileProject]{Value: NewProfileProject(title, description, stack, repository), Status: ProfileClaimConfirmed}
|
||||
}
|
||||
|
||||
func TestProfileProjectsAreValidatedNormalizedAndOptionalInARequest(t *testing.T) {
|
||||
at := time.Date(2026, 10, 11, 9, 0, 0, 0, time.UTC)
|
||||
projects := []ProfileClaimInput[ProfileProject]{
|
||||
projectInput("Ledger", "Idempotent\r\ncallbacks", []string{"Go", "PostgreSQL"}, "https://github.com/example/ledger.git"),
|
||||
projectInput("Notes", "", nil, ""),
|
||||
}
|
||||
content, err := ResolveCandidateProfileContent(CandidateProfileContent{}, CandidateProfileInput{Projects: &projects}, at)
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveCandidateProfileContent() error = %v", err)
|
||||
}
|
||||
stored := content.Projects()
|
||||
if len(stored) != 2 || stored[0].Value().RepositoryURL != "https://github.com/example/ledger" ||
|
||||
stored[0].Value().Description != "Idempotent\ncallbacks" || strings.Join(stored[0].Value().StackTags(), ",") != "Go,PostgreSQL" {
|
||||
t.Fatalf("projects = %+v, want the normalized values", stored)
|
||||
}
|
||||
if repositories := content.ProjectRepositories(); len(repositories) != 1 || repositories[0].Key() != "example/ledger" {
|
||||
t.Fatalf("ProjectRepositories() = %d, want the linked repository", len(repositories))
|
||||
}
|
||||
|
||||
// A request without the section keeps the stored projects.
|
||||
kept, err := ResolveCandidateProfileContent(content, CandidateProfileInput{}, at)
|
||||
if err != nil || len(kept.Projects()) != 2 || !kept.Equal(content) {
|
||||
t.Fatalf("a request without projects changed them: %v", err)
|
||||
}
|
||||
// An empty list removes them.
|
||||
empty := []ProfileClaimInput[ProfileProject]{}
|
||||
cleared, err := ResolveCandidateProfileContent(content, CandidateProfileInput{Projects: &empty}, at)
|
||||
if err != nil || len(cleared.Projects()) != 0 {
|
||||
t.Fatalf("an empty list kept the projects: %v", err)
|
||||
}
|
||||
|
||||
// The stored rows restore to the same content.
|
||||
rows, err := content.StoredClaims()
|
||||
if err != nil {
|
||||
t.Fatalf("StoredClaims() error = %v", err)
|
||||
}
|
||||
restored, err := RestoreCandidateProfileContent(rows)
|
||||
if err != nil || !restored.Equal(content) {
|
||||
t.Fatalf("RestoreCandidateProfileContent() = %v, want the same projects", err)
|
||||
}
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
projects []ProfileClaimInput[ProfileProject]
|
||||
pointer string
|
||||
}{
|
||||
{"empty title", []ProfileClaimInput[ProfileProject]{projectInput("", "", nil, "")}, "/projects/0/title"},
|
||||
{"long title", []ProfileClaimInput[ProfileProject]{projectInput(strings.Repeat("a", 101), "", nil, "")}, "/projects/0/title"},
|
||||
{"another host", []ProfileClaimInput[ProfileProject]{projectInput("A", "", nil, "https://gitlab.com/a/b")}, "/projects/0/repository_url"},
|
||||
{"repeated tag", []ProfileClaimInput[ProfileProject]{projectInput("A", "", []string{"Go", "go"}, "")}, "/projects/0/stack/1"},
|
||||
{"repeated repository", []ProfileClaimInput[ProfileProject]{
|
||||
projectInput("A", "", nil, "https://github.com/a/b"), projectInput("B", "", nil, "https://github.com/A/B/"),
|
||||
}, "/projects/1/repository_url"},
|
||||
{"too many", func() []ProfileClaimInput[ProfileProject] {
|
||||
many := make([]ProfileClaimInput[ProfileProject], 0, maxProfileProjects+1)
|
||||
for index := range maxProfileProjects + 1 {
|
||||
many = append(many, projectInput(fmt.Sprintf("P%d", index), "", nil, ""))
|
||||
}
|
||||
return many
|
||||
}(), "/projects"},
|
||||
} {
|
||||
_, err := ResolveCandidateProfileContent(CandidateProfileContent{}, CandidateProfileInput{Projects: &test.projects}, at)
|
||||
var field *CandidateProfileFieldError
|
||||
if !errors.As(err, &field) || field.Pointer != test.pointer {
|
||||
t.Errorf("%s: error = %v, want pointer %s", test.name, err, test.pointer)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishedProjectsReachTheCardWithoutTheRepository(t *testing.T) {
|
||||
at := time.Date(2026, 10, 11, 9, 0, 0, 0, time.UTC)
|
||||
projects := []ProfileClaimInput[ProfileProject]{
|
||||
projectInput("Ledger", "Callbacks", []string{"Go"}, "https://github.com/private-owner/ledger"),
|
||||
}
|
||||
content, err := ResolveCandidateProfileContent(CandidateProfileContent{}, CandidateProfileInput{Projects: &projects}, at)
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveCandidateProfileContent() error = %v", err)
|
||||
}
|
||||
profile := CandidateViewProfileFromContentWithRepositories(content, map[string]bool{"private-owner/ledger": true})
|
||||
pseudonym := "cv1_" + strings.Repeat("A", 43)
|
||||
for _, test := range []struct {
|
||||
fields []CardField
|
||||
want int
|
||||
}{
|
||||
{[]CardField{CardFieldStack}, 0},
|
||||
{[]CardField{CardFieldStack, CardFieldProjects}, 1},
|
||||
} {
|
||||
fields, err := NewCardFieldSet(test.fields)
|
||||
if err != nil {
|
||||
t.Fatalf("NewCardFieldSet() error = %v", err)
|
||||
}
|
||||
view, err := NewAnonymousCandidateView(CandidateViewInput{Pseudonym: pseudonym, PublishedFields: fields, Profile: profile, AsOf: at})
|
||||
if err != nil {
|
||||
t.Fatalf("NewAnonymousCandidateView() error = %v", err)
|
||||
}
|
||||
card := view.DTO()
|
||||
if len(card.Projects) != test.want {
|
||||
t.Fatalf("fields %v: projects = %d, want %d", test.fields, len(card.Projects), test.want)
|
||||
}
|
||||
if test.want == 1 && (!card.Projects[0].RepositoryVerified || card.Projects[0].Title != "Ledger") {
|
||||
t.Fatalf("card project = %+v, want the verified title", card.Projects[0])
|
||||
}
|
||||
if text := fmt.Sprintf("%+v", card.Projects); strings.Contains(text, "private-owner") || strings.Contains(text, "github") {
|
||||
t.Fatalf("card projects carry the repository: %s", text)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -191,6 +191,14 @@ type candidateViewRoleClaim struct {
|
||||
status ProfileClaimStatus
|
||||
}
|
||||
|
||||
// candidateViewProjectClaim is a project with the verification of its
|
||||
// repository. The repository key never leaves the private projection input.
|
||||
type candidateViewProjectClaim struct {
|
||||
value ProfileProject
|
||||
status ProfileClaimStatus
|
||||
verified bool
|
||||
}
|
||||
|
||||
type candidateViewExperienceClaim struct {
|
||||
startedOn string
|
||||
endedOn string
|
||||
@@ -204,6 +212,7 @@ type CandidateViewProfile struct {
|
||||
stack []candidateViewStackClaim
|
||||
roles []candidateViewRoleClaim
|
||||
experience []candidateViewExperienceClaim
|
||||
projects []candidateViewProjectClaim
|
||||
}
|
||||
|
||||
func (CandidateViewProfile) String() string { return "[candidate view profile]" }
|
||||
@@ -213,9 +222,28 @@ func (CandidateViewProfile) LogValue() slog.Value {
|
||||
}
|
||||
|
||||
// CandidateViewProfileFromContent removes private profile values that are
|
||||
// not needed to build the anonymous organization-facing view.
|
||||
// not needed to build the anonymous organization-facing view. No project is
|
||||
// marked as backed by a verified repository.
|
||||
func CandidateViewProfileFromContent(content CandidateProfileContent) CandidateViewProfile {
|
||||
return CandidateViewProfileFromContentWithRepositories(content, nil)
|
||||
}
|
||||
|
||||
// CandidateViewProfileFromContentWithRepositories also marks each project
|
||||
// whose repository key is in verifiedRepositories, the keys whose latest
|
||||
// check found a public repository.
|
||||
func CandidateViewProfileFromContentWithRepositories(
|
||||
content CandidateProfileContent, verifiedRepositories map[string]bool,
|
||||
) CandidateViewProfile {
|
||||
profile := CandidateViewProfile{}
|
||||
for _, claim := range content.Projects() {
|
||||
verified := false
|
||||
if repository, ok := claim.Value().Repository(); ok {
|
||||
verified = verifiedRepositories[repository.Key()]
|
||||
}
|
||||
profile.projects = append(profile.projects, candidateViewProjectClaim{
|
||||
value: claim.Value(), status: claim.Status(), verified: verified,
|
||||
})
|
||||
}
|
||||
for _, claim := range content.Stack() {
|
||||
profile.stack = append(profile.stack, candidateViewStackClaim{value: claim.Value(), status: claim.Status()})
|
||||
}
|
||||
@@ -263,6 +291,15 @@ func (compatibility CandidateViewSalaryCompatibility) IsKnown() bool {
|
||||
return compatibility == CandidateViewSalaryCompatible || compatibility == CandidateViewSalaryNotCompatible
|
||||
}
|
||||
|
||||
// CandidateViewProject is one published project as the card shows it: no
|
||||
// repository address, owner, or fetched repository text.
|
||||
type CandidateViewProject struct {
|
||||
Title string `json:"title"`
|
||||
Description *string `json:"description"`
|
||||
Stack []string `json:"stack"`
|
||||
RepositoryVerified bool `json:"repository_verified"`
|
||||
}
|
||||
|
||||
// AnonymousCandidateViewDTO is the complete closed organization-facing data
|
||||
// transfer object. It contains no account ID, raw profile fields, or history.
|
||||
type AnonymousCandidateViewDTO struct {
|
||||
@@ -273,6 +310,9 @@ type AnonymousCandidateViewDTO struct {
|
||||
ExperienceBand *CandidateExperienceBand `json:"experience_band"`
|
||||
WorkFormats []QuestionnaireWorkFormat `json:"work_formats"`
|
||||
SalaryCompatibility *CandidateViewSalaryCompatibility `json:"salary_compatibility"`
|
||||
// Projects are published free text; cohort generalization leaves them
|
||||
// unchanged and they are not a cohort feature.
|
||||
Projects []CandidateViewProject `json:"projects"`
|
||||
}
|
||||
|
||||
func (AnonymousCandidateViewDTO) String() string { return "[anonymous candidate view]" }
|
||||
@@ -348,6 +388,9 @@ func NewAnonymousCandidateView(input CandidateViewInput) (AnonymousCandidateView
|
||||
value := *input.SalaryCompatibility
|
||||
view.dto.SalaryCompatibility = &value
|
||||
}
|
||||
if input.PublishedFields.Contains(CardFieldProjects) {
|
||||
view.dto.Projects = candidateViewProjects(input.Profile)
|
||||
}
|
||||
return view, nil
|
||||
}
|
||||
|
||||
@@ -366,9 +409,38 @@ func cloneAnonymousCandidateViewDTO(dto AnonymousCandidateViewDTO) AnonymousCand
|
||||
dto.ExperienceBand = clonePointer(dto.ExperienceBand)
|
||||
dto.WorkFormats = slices.Clone(dto.WorkFormats)
|
||||
dto.SalaryCompatibility = clonePointer(dto.SalaryCompatibility)
|
||||
if dto.Projects != nil {
|
||||
projects := make([]CandidateViewProject, len(dto.Projects))
|
||||
for index, project := range dto.Projects {
|
||||
project.Description = clonePointer(project.Description)
|
||||
project.Stack = slices.Clone(project.Stack)
|
||||
projects[index] = project
|
||||
}
|
||||
dto.Projects = projects
|
||||
}
|
||||
return dto
|
||||
}
|
||||
|
||||
// candidateViewProjects lists the confirmed projects in profile order, so
|
||||
// the position of a project in the card equals its position in the profile.
|
||||
func candidateViewProjects(profile CandidateViewProfile) []CandidateViewProject {
|
||||
var projects []CandidateViewProject
|
||||
for _, claim := range profile.projects {
|
||||
if claim.status != ProfileClaimConfirmed {
|
||||
continue
|
||||
}
|
||||
stack := claim.value.StackTags()
|
||||
if stack == nil {
|
||||
stack = []string{}
|
||||
}
|
||||
projects = append(projects, CandidateViewProject{
|
||||
Title: claim.value.Title, Description: optionalString(claim.value.Description),
|
||||
Stack: stack, RepositoryVerified: claim.verified,
|
||||
})
|
||||
}
|
||||
return projects
|
||||
}
|
||||
|
||||
func validCandidateViewPseudonym(pseudonym string) bool {
|
||||
if !strings.HasPrefix(pseudonym, candidateViewPseudonymPrefix) {
|
||||
return false
|
||||
|
||||
@@ -74,6 +74,7 @@ func cloneCandidateViewProfile(profile CandidateViewProfile) CandidateViewProfil
|
||||
return CandidateViewProfile{
|
||||
stack: slices.Clone(profile.stack), roles: slices.Clone(profile.roles),
|
||||
experience: slices.Clone(profile.experience),
|
||||
projects: slices.Clone(profile.projects),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -106,3 +106,14 @@ func DemoProductPolicyV4() ProductPolicy {
|
||||
policy.Matching = &matching
|
||||
return policy
|
||||
}
|
||||
|
||||
// DemoProductPolicyV5 returns DemoProductPolicyV4 with the semantic matching
|
||||
// section and the semantic Fit weights (DemoSemanticMatchingPolicy). V4 stays
|
||||
// the PRD point with Sem weight 0.10. It is published explicitly with the
|
||||
// policy-publish command; startup seeding publishes V1 only.
|
||||
func DemoProductPolicyV5() ProductPolicy {
|
||||
policy := DemoProductPolicyV4()
|
||||
matching := DemoSemanticMatchingPolicy()
|
||||
policy.Matching = &matching
|
||||
return policy
|
||||
}
|
||||
@@ -185,6 +185,34 @@ type matchingPolicyDocument struct {
|
||||
PercentileMinCohort *int32 `json:"percentile_min_cohort"`
|
||||
MaxResultsPerGroup *int32 `json:"max_results_per_group"`
|
||||
SkillTaxonomy *[]matchingSkillGroupDocument `json:"skill_taxonomy"`
|
||||
// Semantics is optional: a document without it is a matching section
|
||||
// that ranks with the neutral Sem.
|
||||
Semantics *matchingSemanticsDocument `json:"semantics,omitempty"`
|
||||
}
|
||||
|
||||
type matchingSemanticsDocument struct {
|
||||
Members *[]matchingSemanticMemberDocument `json:"members"`
|
||||
Calibration *[]matchingCalibrationPointDocument `json:"calibration"`
|
||||
SkillMediumBP *BasisPoints `json:"skill_medium_bp"`
|
||||
SkillHighBP *BasisPoints `json:"skill_high_bp"`
|
||||
TaskMediumBP *BasisPoints `json:"task_medium_bp"`
|
||||
TaskHighBP *BasisPoints `json:"task_high_bp"`
|
||||
MaxEvidencePerEntry *int32 `json:"max_evidence_per_entry"`
|
||||
Source *string `json:"source"`
|
||||
}
|
||||
|
||||
type matchingSemanticMemberDocument struct {
|
||||
ModelID *string `json:"model_id"`
|
||||
ModelRevision *string `json:"model_revision"`
|
||||
PromptVersion *string `json:"prompt_version"`
|
||||
WeightBP *BasisPoints `json:"weight_bp"`
|
||||
MeanBP *int32 `json:"mean_bp"`
|
||||
StandardDeviationBP *int32 `json:"standard_deviation_bp"`
|
||||
}
|
||||
|
||||
type matchingCalibrationPointDocument struct {
|
||||
ScoreBP *int32 `json:"score_bp"`
|
||||
ProbabilityBP *BasisPoints `json:"probability_bp"`
|
||||
}
|
||||
|
||||
type matchingSkillGroupDocument struct {
|
||||
@@ -359,6 +387,31 @@ func encodeMatchingPolicy(policy *MatchingPolicy) *matchingPolicyDocument {
|
||||
PercentileMinCohort: pointer(policy.PercentileMinCohort),
|
||||
MaxResultsPerGroup: pointer(policy.MaxResultsPerGroup),
|
||||
SkillTaxonomy: pointer(encodeMatchingSkillGroups(policy.SkillTaxonomy)),
|
||||
Semantics: encodeMatchingSemantics(policy.Semantics),
|
||||
}
|
||||
}
|
||||
|
||||
func encodeMatchingSemantics(policy *MatchingSemanticsPolicy) *matchingSemanticsDocument {
|
||||
if policy == nil {
|
||||
return nil
|
||||
}
|
||||
points := make([]matchingCalibrationPointDocument, 0, len(policy.Calibration))
|
||||
for _, point := range policy.Calibration {
|
||||
points = append(points, matchingCalibrationPointDocument{ScoreBP: pointer(point.Score), ProbabilityBP: pointer(point.Probability)})
|
||||
}
|
||||
members := make([]matchingSemanticMemberDocument, 0, len(policy.Members))
|
||||
for _, member := range policy.Members {
|
||||
members = append(members, matchingSemanticMemberDocument{
|
||||
ModelID: pointer(member.Model.ID), ModelRevision: pointer(member.Model.Revision),
|
||||
PromptVersion: pointer(member.Model.PromptVersion), WeightBP: pointer(member.Weight),
|
||||
MeanBP: pointer(member.Mean), StandardDeviationBP: pointer(member.StandardDeviation),
|
||||
})
|
||||
}
|
||||
return &matchingSemanticsDocument{
|
||||
Members: pointer(members), Calibration: pointer(points),
|
||||
SkillMediumBP: pointer(policy.SkillMedium), SkillHighBP: pointer(policy.SkillHigh),
|
||||
TaskMediumBP: pointer(policy.TaskMedium), TaskHighBP: pointer(policy.TaskHigh),
|
||||
MaxEvidencePerEntry: pointer(policy.MaxEvidencePerEntry), Source: pointer(policy.Source),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -621,6 +674,43 @@ func decodeOptionalMatchingPolicy(reader *documentReader, document *matchingPoli
|
||||
PercentileMinCohort: require(reader, "matching.percentile_min_cohort", document.PercentileMinCohort),
|
||||
MaxResultsPerGroup: require(reader, "matching.max_results_per_group", document.MaxResultsPerGroup),
|
||||
SkillTaxonomy: taxonomy,
|
||||
Semantics: decodeOptionalMatchingSemantics(reader, document.Semantics),
|
||||
}
|
||||
}
|
||||
|
||||
func decodeOptionalMatchingSemantics(reader *documentReader, document *matchingSemanticsDocument) *MatchingSemanticsPolicy {
|
||||
if document == nil {
|
||||
return nil
|
||||
}
|
||||
points := make([]MatchingCalibrationPoint, 0)
|
||||
for _, point := range require(reader, "matching.semantics.calibration", document.Calibration) {
|
||||
points = append(points, MatchingCalibrationPoint{
|
||||
Score: require(reader, "matching.semantics.calibration.score_bp", point.ScoreBP),
|
||||
Probability: require(reader, "matching.semantics.calibration.probability_bp", point.ProbabilityBP),
|
||||
})
|
||||
}
|
||||
members := make([]MatchingSemanticMember, 0)
|
||||
for _, member := range require(reader, "matching.semantics.members", document.Members) {
|
||||
members = append(members, MatchingSemanticMember{
|
||||
Model: SemanticModel{
|
||||
ID: require(reader, "matching.semantics.members.model_id", member.ModelID),
|
||||
Revision: require(reader, "matching.semantics.members.model_revision", member.ModelRevision),
|
||||
PromptVersion: require(reader, "matching.semantics.members.prompt_version", member.PromptVersion),
|
||||
},
|
||||
Weight: require(reader, "matching.semantics.members.weight_bp", member.WeightBP),
|
||||
Mean: require(reader, "matching.semantics.members.mean_bp", member.MeanBP),
|
||||
StandardDeviation: require(reader, "matching.semantics.members.standard_deviation_bp", member.StandardDeviationBP),
|
||||
})
|
||||
}
|
||||
return &MatchingSemanticsPolicy{
|
||||
Members: members,
|
||||
Calibration: points,
|
||||
SkillMedium: require(reader, "matching.semantics.skill_medium_bp", document.SkillMediumBP),
|
||||
SkillHigh: require(reader, "matching.semantics.skill_high_bp", document.SkillHighBP),
|
||||
TaskMedium: require(reader, "matching.semantics.task_medium_bp", document.TaskMediumBP),
|
||||
TaskHigh: require(reader, "matching.semantics.task_high_bp", document.TaskHighBP),
|
||||
MaxEvidencePerEntry: require(reader, "matching.semantics.max_evidence_per_entry", document.MaxEvidencePerEntry),
|
||||
Source: require(reader, "matching.semantics.source", document.Source),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -70,6 +70,11 @@ type MatchingPolicy struct {
|
||||
// that stays below the daily card-view allowance of the first tier.
|
||||
MaxResultsPerGroup int32
|
||||
|
||||
// Semantics is the optional semantic section: the encoder of the stored
|
||||
// vectors, the calibration of Sem, and the explanation thresholds. A
|
||||
// version without it ranks with the neutral Sem, as before.
|
||||
Semantics *MatchingSemanticsPolicy
|
||||
|
||||
// SkillTaxonomy lists, for each specialization, the technologies that fall
|
||||
// inside it. Evidence for a specialization is broader evidence for each of
|
||||
// them, and evidence for one of them is narrower evidence for the
|
||||
@@ -90,6 +95,10 @@ func (policy MatchingPolicy) Clone() MatchingPolicy {
|
||||
for index := range policy.SkillTaxonomy {
|
||||
policy.SkillTaxonomy[index].Skills = slices.Clone(policy.SkillTaxonomy[index].Skills)
|
||||
}
|
||||
if policy.Semantics != nil {
|
||||
semantics := policy.Semantics.Clone()
|
||||
policy.Semantics = &semantics
|
||||
}
|
||||
return policy
|
||||
}
|
||||
|
||||
@@ -164,6 +173,20 @@ func DemoMatchingPolicy() MatchingPolicy {
|
||||
}
|
||||
}
|
||||
|
||||
// DemoSemanticMatchingPolicy returns DemoMatchingPolicy with semantic
|
||||
// similarity in Fit. The research shows that the PRD weight 0.10 hides
|
||||
// almost all of the encoder's gain (TEST nDCG@10 of Fit 0.649 against 0.818
|
||||
// for the encoder alone) and that 0.5 recovers it (0.838). Sem therefore
|
||||
// weighs 0.5 and Cov and Dom keep their PRD ratio 5:1 in the rest
|
||||
// (0.4167 and 0.0833), so the weights still add up to one.
|
||||
func DemoSemanticMatchingPolicy() MatchingPolicy {
|
||||
policy := DemoMatchingPolicy()
|
||||
policy.FitCoverageWeight, policy.FitDomainWeight, policy.FitSemanticsWeight = 4167, 833, 5000
|
||||
semantics := DemoMatchingSemanticsPolicy()
|
||||
policy.Semantics = &semantics
|
||||
return policy
|
||||
}
|
||||
|
||||
// TrustCoefficient returns the coefficient of an evidence trust level. An
|
||||
// unknown level has none.
|
||||
func (policy MatchingPolicy) TrustCoefficient(trust EvidenceTrust) (BasisPoints, bool) {
|
||||
@@ -214,11 +237,17 @@ func (policy MatchingPolicy) RelationCoefficient(relation EvidenceSkillRelation)
|
||||
|
||||
// Validate rejects a zero, out-of-range, or inconsistent section.
|
||||
func (policy MatchingPolicy) Validate() error {
|
||||
return firstError(
|
||||
if err := firstError(
|
||||
policy.validateShares(),
|
||||
policy.validateWeights(),
|
||||
policy.validateOrdering(),
|
||||
)
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
if policy.Semantics != nil {
|
||||
return policy.Semantics.Validate()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (policy MatchingPolicy) validateShares() error {
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// MatchingSemanticsPolicy is the versioned semantic part of matching: which
|
||||
// encoders the stored vectors must come from, how their cosines of the two
|
||||
// whole views become Sem, and which item similarities an explanation may show.
|
||||
// Values come from the research run named in Source; they are not product
|
||||
// measurements.
|
||||
type MatchingSemanticsPolicy struct {
|
||||
// Members are the encoders whose cosines form the semantic score: the
|
||||
// weighted sum of each cosine standardized by the member's mean and
|
||||
// standard deviation. The first member also provides the item vectors of
|
||||
// the explanation. The default is one member, Giga-480M, with weight 1,
|
||||
// mean 0, and standard deviation 1, so the score is its cosine; an
|
||||
// ensemble (for example 0.4 Giga + 0.6 Qwen3-Embedding) adds a member and
|
||||
// needs a calibration fitted on its fused score.
|
||||
Members []MatchingSemanticMember
|
||||
// Calibration maps the fused score of the need view and the card view to
|
||||
// Sem by linear interpolation between points, clipped at both ends. The
|
||||
// points are an isotonic fit, so both coordinates never decrease.
|
||||
Calibration []MatchingCalibrationPoint
|
||||
// The item thresholds are cosines in basis points: a requirement whose
|
||||
// closest card item reaches Medium is shown as "medium", reaching High as
|
||||
// "high". Skills and tasks have their own pairs.
|
||||
SkillMedium BasisPoints
|
||||
SkillHigh BasisPoints
|
||||
TaskMedium BasisPoints
|
||||
TaskHigh BasisPoints
|
||||
// MaxEvidencePerEntry bounds the explanation items of one entry.
|
||||
MaxEvidencePerEntry int32
|
||||
// Source names the data and the fit behind the values.
|
||||
Source string
|
||||
}
|
||||
|
||||
// MatchingSemanticMember is one encoder of the semantic score. Mean and
|
||||
// StandardDeviation describe its cosine of a need and a card in basis
|
||||
// points; the member contributes Weight * (cosine - Mean) / StandardDeviation.
|
||||
type MatchingSemanticMember struct {
|
||||
Model SemanticModel
|
||||
Weight BasisPoints
|
||||
Mean int32
|
||||
StandardDeviation int32
|
||||
}
|
||||
|
||||
// ExplanationModel is the encoder whose item vectors explain an entry.
|
||||
func (policy MatchingSemanticsPolicy) ExplanationModel() SemanticModel {
|
||||
if len(policy.Members) == 0 {
|
||||
return SemanticModel{}
|
||||
}
|
||||
return policy.Members[0].Model
|
||||
}
|
||||
|
||||
// FusedScore combines the whole-view cosines of the members, in member order,
|
||||
// into the score that the calibration reads. It returns false unless every
|
||||
// member has a cosine: a partial ensemble would put the entry on another scale.
|
||||
func (policy MatchingSemanticsPolicy) FusedScore(cosines []float64) (float64, bool) {
|
||||
if len(policy.Members) == 0 || len(cosines) != len(policy.Members) {
|
||||
return 0, false
|
||||
}
|
||||
var score float64
|
||||
for index, cosine := range cosines {
|
||||
member := policy.Members[index]
|
||||
weight := float64(member.Weight) / float64(basisPointsPerUnit)
|
||||
mean := float64(member.Mean) / float64(basisPointsPerUnit)
|
||||
deviation := float64(member.StandardDeviation) / float64(basisPointsPerUnit)
|
||||
// The explicit conversion rounds the product, so no platform fuses it
|
||||
// with the sum and every server computes the same score.
|
||||
score += float64(weight * ((cosine - mean) / deviation))
|
||||
}
|
||||
return score, true
|
||||
}
|
||||
|
||||
// MatchingCalibrationPoint is one point of the calibration curve: a fused
|
||||
// score in basis points (-1..1 for a single cosine) and the probability that
|
||||
// the pair is relevant.
|
||||
type MatchingCalibrationPoint struct {
|
||||
Score int32
|
||||
Probability BasisPoints
|
||||
}
|
||||
|
||||
const (
|
||||
minCalibrationPoints = 2
|
||||
maxCalibrationPoints = 256
|
||||
maxSemanticEvidencePerEntry = 12
|
||||
maxSemanticSourceRunes = 300
|
||||
maxSemanticMembers = 4
|
||||
// A standardized fused score can leave -1..1; the bound only rejects a
|
||||
// value in the wrong unit.
|
||||
minScoreBasisPoints = -100000
|
||||
maxScoreBasisPoints = 100000
|
||||
)
|
||||
|
||||
// Clone copies the members and the calibration points.
|
||||
func (policy MatchingSemanticsPolicy) Clone() MatchingSemanticsPolicy {
|
||||
policy.Members = slices.Clone(policy.Members)
|
||||
policy.Calibration = slices.Clone(policy.Calibration)
|
||||
return policy
|
||||
}
|
||||
|
||||
// Validate rejects a malformed section.
|
||||
func (policy MatchingSemanticsPolicy) Validate() error {
|
||||
const location = "MatchingSemanticsPolicy.Validate"
|
||||
if err := policy.validateMembers(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(policy.Calibration) < minCalibrationPoints || len(policy.Calibration) > maxCalibrationPoints {
|
||||
return invalidPolicy(location, fmt.Sprintf("matching.semantics.calibration needs between %d and %d points", minCalibrationPoints, maxCalibrationPoints))
|
||||
}
|
||||
for index, point := range policy.Calibration {
|
||||
if err := firstError(
|
||||
checkRange(location, "matching.semantics.calibration.score_bp", point.Score, minScoreBasisPoints, maxScoreBasisPoints),
|
||||
checkRange(location, "matching.semantics.calibration.probability_bp", point.Probability, 0, basisPointsPerUnit),
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
if index > 0 {
|
||||
previous := policy.Calibration[index-1]
|
||||
if point.Score < previous.Score || point.Probability < previous.Probability {
|
||||
return invalidPolicy(location, "matching.semantics.calibration must not decrease")
|
||||
}
|
||||
}
|
||||
}
|
||||
if first, last := policy.Calibration[0], policy.Calibration[len(policy.Calibration)-1]; first.Score == last.Score {
|
||||
return invalidPolicy(location, "matching.semantics.calibration must span a cosine range")
|
||||
}
|
||||
if err := firstError(
|
||||
checkRange(location, "matching.semantics.skill_medium_bp", policy.SkillMedium, 1, basisPointsPerUnit),
|
||||
checkRange(location, "matching.semantics.skill_high_bp", policy.SkillHigh, policy.SkillMedium, basisPointsPerUnit),
|
||||
checkRange(location, "matching.semantics.task_medium_bp", policy.TaskMedium, 1, basisPointsPerUnit),
|
||||
checkRange(location, "matching.semantics.task_high_bp", policy.TaskHigh, policy.TaskMedium, basisPointsPerUnit),
|
||||
checkRange(location, "matching.semantics.max_evidence_per_entry", policy.MaxEvidencePerEntry, 0, maxSemanticEvidencePerEntry),
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
if policy.Source == "" || utf8.RuneCountInString(policy.Source) > maxSemanticSourceRunes || singleLineTextProblem(policy.Source, maxSemanticSourceRunes) != "" {
|
||||
return invalidPolicy(location, "matching.semantics.source must name the data behind the values")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (policy MatchingSemanticsPolicy) validateMembers() error {
|
||||
const location = "MatchingSemanticsPolicy.Validate"
|
||||
if len(policy.Members) == 0 || len(policy.Members) > maxSemanticMembers {
|
||||
return invalidPolicy(location, fmt.Sprintf("matching.semantics.members needs between 1 and %d members", maxSemanticMembers))
|
||||
}
|
||||
var total BasisPoints
|
||||
seen := make(map[SemanticModel]struct{}, len(policy.Members))
|
||||
for _, member := range policy.Members {
|
||||
if err := member.Model.Validate(); err != nil {
|
||||
return invalidPolicy(location, "matching.semantics.members model identity is malformed")
|
||||
}
|
||||
if _, repeated := seen[member.Model]; repeated {
|
||||
return invalidPolicy(location, "matching.semantics.members repeats a model")
|
||||
}
|
||||
seen[member.Model] = struct{}{}
|
||||
if err := firstError(
|
||||
checkRange(location, "matching.semantics.members.weight_bp", member.Weight, 1, basisPointsPerUnit),
|
||||
checkRange(location, "matching.semantics.members.mean_bp", member.Mean, -basisPointsPerUnit32, basisPointsPerUnit32),
|
||||
checkRange(location, "matching.semantics.members.standard_deviation_bp", member.StandardDeviation, 1, basisPointsPerUnit32),
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
total += member.Weight
|
||||
}
|
||||
if total != basisPointsPerUnit {
|
||||
return invalidPolicy(location, "matching.semantics.members weights must add up to 1.0000")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// basisPointsPerUnit32 is basisPointsPerUnit for int32 fields.
|
||||
const basisPointsPerUnit32 = int32(basisPointsPerUnit)
|
||||
|
||||
// Probability maps a fused score to Sem in micro units (1e-6), interpolating
|
||||
// linearly between calibration points in integer arithmetic. A score at a
|
||||
// repeated point takes the higher probability, the right limit of the step.
|
||||
func (policy MatchingSemanticsPolicy) Probability(score float64) int64 {
|
||||
const microPerBasisPoint = 100
|
||||
points := policy.Calibration
|
||||
if len(points) == 0 {
|
||||
return 0
|
||||
}
|
||||
// The score in micro units, rounded half away from zero.
|
||||
value := int64(math.Round(score * 1_000_000))
|
||||
micro := func(point MatchingCalibrationPoint) (int64, int64) {
|
||||
return int64(point.Score) * microPerBasisPoint, int64(point.Probability) * microPerBasisPoint
|
||||
}
|
||||
firstX, firstY := micro(points[0])
|
||||
if value < firstX {
|
||||
return firstY
|
||||
}
|
||||
for index := len(points) - 1; index >= 0; index-- {
|
||||
x0, y0 := micro(points[index])
|
||||
if value < x0 {
|
||||
continue
|
||||
}
|
||||
if index == len(points)-1 {
|
||||
return y0
|
||||
}
|
||||
x1, y1 := micro(points[index+1])
|
||||
if x1 == x0 {
|
||||
return y1
|
||||
}
|
||||
return y0 + ((y1-y0)*(value-x0)+(x1-x0)/2)/(x1-x0)
|
||||
}
|
||||
return firstY
|
||||
}
|
||||
|
||||
// ItemBand returns the explanation band of an item similarity for a skill or
|
||||
// a task requirement, or "" below the medium threshold.
|
||||
func (policy MatchingSemanticsPolicy) ItemBand(task bool, cosine float64) SemanticSimilarityBand {
|
||||
medium, high := policy.SkillMedium, policy.SkillHigh
|
||||
if task {
|
||||
medium, high = policy.TaskMedium, policy.TaskHigh
|
||||
}
|
||||
scaled := cosine * float64(basisPointsPerUnit)
|
||||
switch {
|
||||
case scaled >= float64(high):
|
||||
return SemanticSimilarityHigh
|
||||
case scaled >= float64(medium):
|
||||
return SemanticSimilarityMedium
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
// SemanticSimilarityBand is the coarse band of an explanation item.
|
||||
type SemanticSimilarityBand string
|
||||
|
||||
const (
|
||||
SemanticSimilarityHigh SemanticSimilarityBand = "high"
|
||||
SemanticSimilarityMedium SemanticSimilarityBand = "medium"
|
||||
)
|
||||
|
||||
// Giga-Embeddings-instruct-480M at the pinned revision with the service
|
||||
// prompt recipe; the ML service reports the same identity.
|
||||
const (
|
||||
GigaEmbeddingsModelID = "ai-sage/Giga-Embeddings-instruct-480M-0826"
|
||||
GigaEmbeddingsModelRevision = "1763d603adac8057bd6482a708001b0ed2e0a903"
|
||||
GigaEmbeddingsPromptVersion = "giga-card-mean-v1"
|
||||
)
|
||||
|
||||
// DemoMatchingSemanticsPolicy returns the semantic section fitted on the DEV
|
||||
// split of the LincodexMatch research (30 needs, 3220 judged pairs, 994 with
|
||||
// consensus >= 2):
|
||||
// - Calibration is the isotonic fit of P(consensus >= 2) on the cosine of
|
||||
// the need view with the query prompt and the profile view without one
|
||||
// (ECE 0.015-0.049 against 0.17-0.57 for the raw cosine), rounded to four
|
||||
// decimals.
|
||||
// - The item thresholds are where an isotonic fit of P(pair relevant) on
|
||||
// the best item cosine of a requirement reaches 0.5 (medium) and 0.7
|
||||
// (high): skills 0.3673 and 0.4607, tasks 0.2997 and 0.4192.
|
||||
//
|
||||
// The research profiles carry experience texts that the anonymous card does
|
||||
// not, so product cosines are lower; the values are a calibrated starting
|
||||
// point, not a product measurement.
|
||||
func DemoMatchingSemanticsPolicy() MatchingSemanticsPolicy {
|
||||
return MatchingSemanticsPolicy{
|
||||
Members: []MatchingSemanticMember{{
|
||||
Model: SemanticModel{
|
||||
ID: GigaEmbeddingsModelID, Revision: GigaEmbeddingsModelRevision, PromptVersion: GigaEmbeddingsPromptVersion,
|
||||
},
|
||||
Weight: basisPointsPerUnit, Mean: 0, StandardDeviation: basisPointsPerUnit32,
|
||||
}},
|
||||
Calibration: demoSemanticCalibration(),
|
||||
SkillMedium: 3673,
|
||||
SkillHigh: 4607,
|
||||
TaskMedium: 2997,
|
||||
TaskHigh: 4192,
|
||||
MaxEvidencePerEntry: 6,
|
||||
Source: "LincodexMatch research 2026-10-10, DEV split, giga-480m isotonic fit (reports/step3)",
|
||||
}
|
||||
}
|
||||
|
||||
func demoSemanticCalibration() []MatchingCalibrationPoint {
|
||||
return []MatchingCalibrationPoint{
|
||||
{674, 0}, {2120, 0}, {2120, 45}, {2567, 45},
|
||||
{2570, 154}, {2692, 154}, {2692, 458}, {2970, 458},
|
||||
{2972, 735}, {3064, 735}, {3067, 758}, {3319, 758},
|
||||
{3319, 833}, {3334, 833}, {3335, 1000}, {3345, 1000},
|
||||
{3345, 1006}, {3666, 1006}, {3669, 1071}, {3726, 1071},
|
||||
{3727, 1702}, {3762, 1702}, {3763, 1744}, {3837, 1744},
|
||||
{3838, 1962}, {3998, 1962}, {3999, 2000}, {4002, 2000},
|
||||
{4003, 2143}, {4018, 2143}, {4019, 2353}, {4070, 2353},
|
||||
{4070, 2674}, {4130, 2674}, {4130, 2816}, {4286, 2816},
|
||||
{4287, 3404}, {4330, 3404}, {4331, 3497}, {4462, 3497},
|
||||
{4463, 4000}, {4494, 4000}, {4494, 4286}, {4503, 4286},
|
||||
{4506, 4583}, {4537, 4583}, {4538, 5000}, {4543, 5000},
|
||||
{4543, 5117}, {4760, 5117}, {4760, 5667}, {4795, 5667},
|
||||
{4795, 5714}, {4822, 5714}, {4824, 5769}, {4852, 5769},
|
||||
{4854, 5890}, {4935, 5890}, {4935, 6111}, {4949, 6111},
|
||||
{4950, 7097}, {4988, 7097}, {4988, 7324}, {5078, 7324},
|
||||
{5078, 7647}, {5108, 7647}, {5113, 7714}, {5161, 7714},
|
||||
{5162, 7778}, {5392, 7778}, {5394, 8049}, {5461, 8049},
|
||||
{5463, 9167}, {5532, 9167}, {5533, 9259}, {5926, 9259},
|
||||
{5932, 9574}, {6260, 9574}, {6269, 10000}, {7049, 10000},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// ErrInvalidSemanticVector reports a vector that cannot be stored or used.
|
||||
var ErrInvalidSemanticVector = errors.New("invalid semantic vector")
|
||||
|
||||
const (
|
||||
// MaxSemanticDimension matches the ML contract bound of one vector.
|
||||
MaxSemanticDimension = 4096
|
||||
// semanticNormTolerance is how far a stored vector may be from unit
|
||||
// length; float32 encoding stays far below it.
|
||||
semanticNormTolerance = 1e-3
|
||||
maxSemanticModelText = 200
|
||||
)
|
||||
|
||||
var semanticModelTextPattern = regexp.MustCompile(`^[A-Za-z0-9._/-]{1,200}$`)
|
||||
|
||||
// SemanticModel identifies the encoder of a vector: the model, the pinned
|
||||
// revision of its weights, and the prompt and pooling recipe. Vectors of two
|
||||
// different models are never compared.
|
||||
type SemanticModel struct {
|
||||
ID string
|
||||
Revision string
|
||||
PromptVersion string
|
||||
}
|
||||
|
||||
// Validate rejects an empty or malformed model identity.
|
||||
func (model SemanticModel) Validate() error {
|
||||
for _, part := range []string{model.ID, model.Revision, model.PromptVersion} {
|
||||
if len(part) > maxSemanticModelText || !semanticModelTextPattern.MatchString(part) {
|
||||
return fmt.Errorf("domain.SemanticModel.Validate - model identity is malformed: %w", ErrInvalidSemanticVector)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SemanticVector is one L2-normalized float32 vector.
|
||||
type SemanticVector []float32
|
||||
|
||||
// NewSemanticVector checks the dimension, finiteness, and unit length.
|
||||
func NewSemanticVector(values []float32) (SemanticVector, error) {
|
||||
const location = "domain.NewSemanticVector"
|
||||
if len(values) == 0 || len(values) > MaxSemanticDimension {
|
||||
return nil, fmt.Errorf("%s - dimension is out of range: %w", location, ErrInvalidSemanticVector)
|
||||
}
|
||||
var norm float64
|
||||
for _, value := range values {
|
||||
if math.IsNaN(float64(value)) || math.IsInf(float64(value), 0) {
|
||||
return nil, fmt.Errorf("%s - value is not finite: %w", location, ErrInvalidSemanticVector)
|
||||
}
|
||||
norm += float64(value) * float64(value)
|
||||
}
|
||||
if math.Abs(math.Sqrt(norm)-1) > semanticNormTolerance {
|
||||
return nil, fmt.Errorf("%s - vector is not normalized: %w", location, ErrInvalidSemanticVector)
|
||||
}
|
||||
return append(SemanticVector(nil), values...), nil
|
||||
}
|
||||
|
||||
// Encode stores the vector as little-endian float32: exact, compact (four
|
||||
// bytes a dimension), and independent of the platform.
|
||||
func (vector SemanticVector) Encode() []byte {
|
||||
encoded := make([]byte, 4*len(vector))
|
||||
for index, value := range vector {
|
||||
binary.LittleEndian.PutUint32(encoded[4*index:], math.Float32bits(value))
|
||||
}
|
||||
return encoded
|
||||
}
|
||||
|
||||
// DecodeSemanticVector reads a stored vector of the given dimension.
|
||||
func DecodeSemanticVector(encoded []byte, dimension int) (SemanticVector, error) {
|
||||
if dimension <= 0 || dimension > MaxSemanticDimension || len(encoded) != 4*dimension {
|
||||
return nil, fmt.Errorf("domain.DecodeSemanticVector - length does not match the dimension: %w", ErrInvalidSemanticVector)
|
||||
}
|
||||
vector := make(SemanticVector, dimension)
|
||||
for index := range vector {
|
||||
vector[index] = math.Float32frombits(binary.LittleEndian.Uint32(encoded[4*index:]))
|
||||
}
|
||||
return vector, nil
|
||||
}
|
||||
|
||||
// Cosine is the dot product of two normalized vectors, summed in float64 in
|
||||
// index order without fused multiply-add so the same vectors give the same value on every platform. It
|
||||
// returns false for vectors of different dimensions.
|
||||
func (vector SemanticVector) Cosine(other SemanticVector) (float64, bool) {
|
||||
if len(vector) == 0 || len(vector) != len(other) {
|
||||
return 0, false
|
||||
}
|
||||
var sum float64
|
||||
for index := range vector {
|
||||
// The explicit conversion rounds the product before the addition,
|
||||
// so no platform fuses them into one multiply-add with another result.
|
||||
sum += float64(float64(vector[index]) * float64(other[index])) //nolint:gosec // the lengths are equal, checked above
|
||||
}
|
||||
return sum, true
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// SemanticViewVersion names the text rendering below. It is hashed into the
|
||||
// content digest of every view, so a change of the rendering never reuses a
|
||||
// vector of the old one.
|
||||
const SemanticViewVersion = "semantic-views-v1"
|
||||
|
||||
const (
|
||||
// maxSemanticViewRunes keeps a whole view under the 8000-character input
|
||||
// limit of the ML contract; the model truncates at its token limit.
|
||||
maxSemanticViewRunes = 7000
|
||||
// maxSemanticItemRunes bounds one item text.
|
||||
maxSemanticItemRunes = 2000
|
||||
// maxReadmeRunesInView is the README excerpt length that one project
|
||||
// contributes, so ten projects still fit into one view.
|
||||
maxReadmeRunesInView = 600
|
||||
// MaxSemanticNeedItems bounds the requirement items of one need: the
|
||||
// contract limits required, desired skills and tasks to 20 each.
|
||||
MaxSemanticNeedItems = 60
|
||||
)
|
||||
|
||||
// SemanticSubjectKind is the owner of a stored vector.
|
||||
type SemanticSubjectKind string
|
||||
|
||||
const (
|
||||
SemanticSubjectCandidate SemanticSubjectKind = "candidate"
|
||||
SemanticSubjectNeed SemanticSubjectKind = "need"
|
||||
)
|
||||
|
||||
// SemanticItemKind is the kind of one text of a view.
|
||||
type SemanticItemKind string
|
||||
|
||||
const (
|
||||
// SemanticItemWhole is the whole view of a candidate or a need; Sem is
|
||||
// the calibrated cosine of the two whole views.
|
||||
SemanticItemWhole SemanticItemKind = "whole"
|
||||
// Candidate items: one published project, the recognized stack, the roles.
|
||||
SemanticItemProject SemanticItemKind = "project"
|
||||
SemanticItemStack SemanticItemKind = "stack"
|
||||
SemanticItemRoles SemanticItemKind = "roles"
|
||||
// Need items: one confirmed requirement.
|
||||
SemanticItemRequiredSkill SemanticItemKind = "required_skill"
|
||||
SemanticItemDesiredSkill SemanticItemKind = "desired_skill"
|
||||
SemanticItemTask SemanticItemKind = "task"
|
||||
)
|
||||
|
||||
// SemanticItem is one text to encode. Key is stable inside a subject:
|
||||
// "whole", "stack", "roles", or "<kind>:<position>". Label is the text that
|
||||
// an explanation may show for it (a published project title or a
|
||||
// requirement text) and is empty for other kinds. The text is personal data
|
||||
// of a candidate or the need text of an organization: never log it.
|
||||
type SemanticItem struct {
|
||||
Key string
|
||||
Kind SemanticItemKind
|
||||
Text string
|
||||
Label string
|
||||
// Position is the index of the project or requirement the item names.
|
||||
Position int
|
||||
}
|
||||
|
||||
func (SemanticItem) String() string { return "[semantic item]" }
|
||||
func (SemanticItem) GoString() string { return "[semantic item]" }
|
||||
func (SemanticItem) LogValue() slog.Value {
|
||||
return slog.StringValue("[semantic item]")
|
||||
}
|
||||
|
||||
// ContentDigest is the SHA-256 of the rendering version, the item key, and
|
||||
// the text. A stored vector is current only while its digest matches.
|
||||
func (item SemanticItem) ContentDigest() [sha256.Size]byte {
|
||||
return sha256.Sum256([]byte(SemanticViewVersion + "\x00" + item.Key + "\x00" + item.Text))
|
||||
}
|
||||
|
||||
// LabelDigest is the SHA-256 of the label, so a stored project vector can be
|
||||
// matched to the title that the card shows without storing the title twice.
|
||||
func (item SemanticItem) LabelDigest() []byte {
|
||||
if item.Label == "" {
|
||||
return nil
|
||||
}
|
||||
digest := sha256.Sum256([]byte(item.Label))
|
||||
return digest[:]
|
||||
}
|
||||
|
||||
// SemanticLabelDigest returns the digest of a label as LabelDigest computes it.
|
||||
func SemanticLabelDigest(label string) []byte {
|
||||
return SemanticItem{Label: label}.LabelDigest()
|
||||
}
|
||||
|
||||
// SemanticDocument is the rendered view of one subject: the whole text and
|
||||
// its items in a stable order.
|
||||
type SemanticDocument struct {
|
||||
Whole SemanticItem
|
||||
Items []SemanticItem
|
||||
}
|
||||
|
||||
// All returns the whole view followed by the items.
|
||||
func (document SemanticDocument) All() []SemanticItem {
|
||||
return append([]SemanticItem{document.Whole}, document.Items...)
|
||||
}
|
||||
|
||||
// IsEmpty reports a view without any text, which has nothing to encode.
|
||||
func (document SemanticDocument) IsEmpty() bool { return document.Whole.Text == "" }
|
||||
|
||||
// RepositoryEvidence is the public metadata of a verified repository that a
|
||||
// published project links. It feeds ranking only; no field of it is shown.
|
||||
type RepositoryEvidence struct {
|
||||
Description string
|
||||
Topics []string
|
||||
Languages []string
|
||||
ReadmeExcerpt string
|
||||
}
|
||||
|
||||
func (RepositoryEvidence) String() string { return "[repository evidence]" }
|
||||
func (RepositoryEvidence) GoString() string { return "[repository evidence]" }
|
||||
func (RepositoryEvidence) LogValue() slog.Value {
|
||||
return slog.StringValue("[repository evidence]")
|
||||
}
|
||||
|
||||
// cleanText collapses every run of white space to one space, as the
|
||||
// research views did, so line breaks and indentation never change a vector.
|
||||
func cleanText(value string) string { return strings.Join(strings.Fields(value), " ") }
|
||||
|
||||
// truncateRunes cuts a text to at most limit runes.
|
||||
func truncateRunes(value string, limit int) string {
|
||||
if utf8.RuneCountInString(value) <= limit {
|
||||
return value
|
||||
}
|
||||
runes := []rune(value)
|
||||
return strings.TrimSpace(string(runes[:limit]))
|
||||
}
|
||||
|
||||
// NewCandidateSemanticDocument renders the published card of a candidate.
|
||||
// It reads only the anonymous card content: the roles and grades that the
|
||||
// card shows, its recognized stack codes, and its published projects, plus
|
||||
// the public metadata of the repositories the card marks verified (keyed by
|
||||
// project position). Private profile text such as experience summaries is
|
||||
// never part of it.
|
||||
func NewCandidateSemanticDocument(card AnonymousCandidateViewDTO, evidence map[int]RepositoryEvidence) SemanticDocument {
|
||||
var document SemanticDocument
|
||||
var lines []string
|
||||
if roles := semanticRoles(card); roles != "" {
|
||||
text := "Roles: " + roles
|
||||
lines = append(lines, text)
|
||||
document.Items = append(document.Items, SemanticItem{Key: string(SemanticItemRoles), Kind: SemanticItemRoles, Text: text})
|
||||
}
|
||||
if len(card.Skills) > 0 {
|
||||
codes := make([]string, 0, len(card.Skills))
|
||||
for _, skill := range card.Skills {
|
||||
codes = append(codes, string(skill))
|
||||
}
|
||||
slices.Sort(codes)
|
||||
text := "Stack: " + strings.Join(codes, ", ")
|
||||
lines = append(lines, text)
|
||||
document.Items = append(document.Items, SemanticItem{Key: string(SemanticItemStack), Kind: SemanticItemStack, Text: text})
|
||||
}
|
||||
if len(card.Projects) > 0 {
|
||||
lines = append(lines, "Projects:")
|
||||
for position, project := range card.Projects {
|
||||
var repository *RepositoryEvidence
|
||||
if found, ok := evidence[position]; ok && project.RepositoryVerified {
|
||||
repository = &found
|
||||
}
|
||||
text := truncateRunes(projectText(project, repository), maxSemanticItemRunes)
|
||||
lines = append(lines, "- "+text)
|
||||
document.Items = append(document.Items, SemanticItem{
|
||||
Key: fmt.Sprintf("%s:%d", SemanticItemProject, position), Kind: SemanticItemProject,
|
||||
Text: text, Label: project.Title, Position: position,
|
||||
})
|
||||
}
|
||||
}
|
||||
whole := truncateRunes(strings.Join(lines, "\n"), maxSemanticViewRunes)
|
||||
document.Whole = SemanticItem{Key: string(SemanticItemWhole), Kind: SemanticItemWhole, Text: whole}
|
||||
return document
|
||||
}
|
||||
|
||||
// semanticRoles lists the specializations of the card in catalog order with
|
||||
// the confirmed grade when the card shows a category, else the declared grade.
|
||||
func semanticRoles(card AnonymousCandidateViewDTO) string {
|
||||
grades := make(map[SpecializationCode]string)
|
||||
shown := make(map[SpecializationCode]bool)
|
||||
for _, assessment := range card.SelfAssessment {
|
||||
shown[assessment.Specialization] = true
|
||||
if assessment.DeclaredGrade != nil {
|
||||
grades[assessment.Specialization] = string(*assessment.DeclaredGrade)
|
||||
}
|
||||
}
|
||||
for _, category := range card.Categories {
|
||||
shown[category.Specialization] = true
|
||||
grades[category.Specialization] = string(category.Grade)
|
||||
}
|
||||
var roles []string
|
||||
for _, code := range specializationCodes {
|
||||
if !shown[code] {
|
||||
continue
|
||||
}
|
||||
if grade := grades[code]; grade != "" {
|
||||
roles = append(roles, fmt.Sprintf("%s (%s)", code, grade))
|
||||
} else {
|
||||
roles = append(roles, string(code))
|
||||
}
|
||||
}
|
||||
return strings.Join(roles, "; ")
|
||||
}
|
||||
|
||||
func projectText(project CandidateViewProject, repository *RepositoryEvidence) string {
|
||||
head := cleanText(project.Title)
|
||||
if project.Description != nil && cleanText(*project.Description) != "" {
|
||||
head += ": " + cleanText(*project.Description)
|
||||
}
|
||||
parts := []string{head}
|
||||
if len(project.Stack) > 0 {
|
||||
parts = append(parts, "Stack: "+cleanText(strings.Join(project.Stack, ", ")))
|
||||
}
|
||||
if repository != nil {
|
||||
if description := cleanText(repository.Description); description != "" {
|
||||
parts = append(parts, "Repository: "+description)
|
||||
}
|
||||
if len(repository.Topics) > 0 {
|
||||
parts = append(parts, "Topics: "+cleanText(strings.Join(repository.Topics, ", ")))
|
||||
}
|
||||
if len(repository.Languages) > 0 {
|
||||
parts = append(parts, "Languages: "+cleanText(strings.Join(repository.Languages, ", ")))
|
||||
}
|
||||
if readme := truncateRunes(cleanText(repository.ReadmeExcerpt), maxReadmeRunesInView); readme != "" {
|
||||
parts = append(parts, "README: "+readme)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, "; ")
|
||||
}
|
||||
|
||||
// NewNeedSemanticDocument renders a need snapshot as the research need view
|
||||
// and lists one item per confirmed requirement. Only confirmed values enter,
|
||||
// the same ones the search scores; the title and the source text are the
|
||||
// organization's own text of that snapshot.
|
||||
func NewNeedSemanticDocument(snapshot NeedSnapshot) SemanticDocument {
|
||||
requirements := snapshot.Requirements
|
||||
required := confirmedSkillNames(requirements.RequiredSkills)
|
||||
desired := confirmedSkillNames(requirements.DesiredSkills)
|
||||
var tasks []string
|
||||
for _, task := range requirements.Tasks {
|
||||
if task.Status == NeedItemConfirmed && cleanText(task.Text) != "" {
|
||||
tasks = append(tasks, cleanText(task.Text))
|
||||
}
|
||||
}
|
||||
lines := needViewLines(snapshot, required, desired, tasks)
|
||||
document := SemanticDocument{Whole: SemanticItem{
|
||||
Key: string(SemanticItemWhole), Kind: SemanticItemWhole, Text: truncateRunes(strings.Join(lines, "\n"), maxSemanticViewRunes),
|
||||
}}
|
||||
appendRequirements := func(kind SemanticItemKind, texts []string) {
|
||||
for position, text := range texts {
|
||||
if len(document.Items) >= MaxSemanticNeedItems {
|
||||
return
|
||||
}
|
||||
document.Items = append(document.Items, SemanticItem{
|
||||
Key: fmt.Sprintf("%s:%d", kind, position), Kind: kind,
|
||||
Text: truncateRunes(text, maxSemanticItemRunes), Label: text, Position: position,
|
||||
})
|
||||
}
|
||||
}
|
||||
appendRequirements(SemanticItemRequiredSkill, required)
|
||||
appendRequirements(SemanticItemDesiredSkill, desired)
|
||||
appendRequirements(SemanticItemTask, tasks)
|
||||
return document
|
||||
}
|
||||
|
||||
// needViewLines renders the lines of the research need view.
|
||||
func needViewLines(snapshot NeedSnapshot, required, desired, tasks []string) []string {
|
||||
requirements := snapshot.Requirements
|
||||
lines := []string{"Title: " + cleanText(snapshot.Title)}
|
||||
if requirements.Grade.Status == NeedValueConfirmed && requirements.Grade.Value != nil {
|
||||
lines = append(lines, "Grade: "+string(*requirements.Grade.Value))
|
||||
}
|
||||
if requirements.Domain.Status == NeedValueConfirmed && requirements.Domain.Value != nil && cleanText(*requirements.Domain.Value) != "" {
|
||||
lines = append(lines, "Domain: "+cleanText(*requirements.Domain.Value))
|
||||
}
|
||||
if len(required) > 0 {
|
||||
lines = append(lines, "Required skills: "+strings.Join(required, "; "))
|
||||
}
|
||||
if len(desired) > 0 {
|
||||
lines = append(lines, "Desired skills: "+strings.Join(desired, "; "))
|
||||
}
|
||||
if len(tasks) > 0 {
|
||||
lines = append(lines, "Tasks:")
|
||||
for _, task := range tasks {
|
||||
lines = append(lines, "- "+task)
|
||||
}
|
||||
}
|
||||
if snapshot.SourceText != nil && cleanText(*snapshot.SourceText) != "" {
|
||||
lines = append(lines, "Description: "+cleanText(*snapshot.SourceText))
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
func confirmedSkillNames(skills []NeedSkill) []string {
|
||||
var names []string
|
||||
for _, skill := range skills {
|
||||
if skill.Status == NeedItemConfirmed && cleanText(skill.Name) != "" {
|
||||
names = append(names, cleanText(skill.Name))
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
@@ -89,6 +89,11 @@ const (
|
||||
CardFieldSelfAssessment CardField = "self_assessment"
|
||||
CardFieldWorkFormats CardField = "work_formats"
|
||||
CardFieldSalaryCompatibility CardField = "salary_compatibility"
|
||||
// CardFieldProjects publishes the projects of the profile: title,
|
||||
// description, stack, and whether a linked repository is verified public.
|
||||
// It is the one free-text group of the card and is excluded from cohort
|
||||
// generalization; the repository address never reaches it.
|
||||
CardFieldProjects CardField = "projects"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -103,6 +108,7 @@ var cardFields = []CardField{
|
||||
CardFieldCategories, CardFieldStack, CardFieldExperience,
|
||||
CardFieldSoftSkills, CardFieldLocation, CardFieldRelocation,
|
||||
CardFieldSelfAssessment, CardFieldWorkFormats, CardFieldSalaryCompatibility,
|
||||
CardFieldProjects,
|
||||
}
|
||||
|
||||
// CardFields returns every card field the contract defines.
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
package outbound
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrEmbedderUnavailable reports that the ML service could not encode
|
||||
// now: it is not ready, unreachable, slow, or the circuit is open. A
|
||||
// later attempt may succeed.
|
||||
ErrEmbedderUnavailable = errors.New("text embedder is unavailable")
|
||||
// ErrEmbedderRejected reports a request or a response that breaks the
|
||||
// ML contract; repeating it gives the same result.
|
||||
ErrEmbedderRejected = errors.New("text embedder rejected the request")
|
||||
// ErrRepositoryFetchUnavailable reports that the public GitHub API could
|
||||
// not answer now, for example because of its rate limit.
|
||||
ErrRepositoryFetchUnavailable = errors.New("repository metadata is unavailable")
|
||||
)
|
||||
|
||||
// EmbeddingKind is the side of the retrieval pair; see the ML contract.
|
||||
type EmbeddingKind string
|
||||
|
||||
const (
|
||||
EmbeddingQuery EmbeddingKind = "query"
|
||||
EmbeddingDocument EmbeddingKind = "document"
|
||||
)
|
||||
|
||||
// MaxEmbeddingBatch is the number of texts of one ML request, the contract
|
||||
// bound.
|
||||
const MaxEmbeddingBatch = 32
|
||||
|
||||
// TextEmbedder encodes texts with the ML service. Texts are personal data
|
||||
// or an organization's need text: an implementation never logs them.
|
||||
type TextEmbedder interface {
|
||||
// Embed encodes the texts with the named model of the service and
|
||||
// returns one normalized vector per text in order and the identity of
|
||||
// the model that produced them. At most MaxEmbeddingBatch texts are sent
|
||||
// at once. A model that the service does not serve is ErrEmbedderRejected.
|
||||
Embed(ctx context.Context, modelID string, kind EmbeddingKind, texts []string) (domain.SemanticModel, []domain.SemanticVector, error)
|
||||
}
|
||||
|
||||
// StoredSemanticItem is one vector to store with the digests of its text.
|
||||
type StoredSemanticItem struct {
|
||||
Key string
|
||||
ContentDigest [32]byte
|
||||
LabelDigest []byte
|
||||
Vector domain.SemanticVector
|
||||
}
|
||||
|
||||
// SemanticItemVector is a stored item vector of a candidate.
|
||||
type SemanticItemVector struct {
|
||||
Key string
|
||||
LabelDigest []byte
|
||||
Vector domain.SemanticVector
|
||||
}
|
||||
|
||||
// SemanticVectorRepository stores and reads vectors inside the caller's
|
||||
// transaction.
|
||||
type SemanticVectorRepository interface {
|
||||
// Lock serializes the vector jobs of one subject until the transaction
|
||||
// ends.
|
||||
Lock(ctx context.Context, kind domain.SemanticSubjectKind, subjectID uuid.UUID) error
|
||||
// Replace makes the given items the only vectors of the subject for the
|
||||
// model: it deletes the other rows of that subject and model first.
|
||||
Replace(ctx context.Context, kind domain.SemanticSubjectKind, subjectID uuid.UUID, model domain.SemanticModel, items []StoredSemanticItem, at time.Time) error
|
||||
// DeleteSubject removes every vector of a subject, of any model.
|
||||
DeleteSubject(ctx context.Context, kind domain.SemanticSubjectKind, subjectID uuid.UUID) error
|
||||
// Digests returns the content digest of every stored item of the subject
|
||||
// and model, by item key.
|
||||
Digests(ctx context.Context, kind domain.SemanticSubjectKind, subjectID uuid.UUID, model domain.SemanticModel) (map[string][32]byte, error)
|
||||
// CandidateWholeVectors returns the whole-view vector of each candidate
|
||||
// that has one for the model.
|
||||
CandidateWholeVectors(ctx context.Context, model domain.SemanticModel, candidateIDs []uuid.UUID) (map[uuid.UUID]domain.SemanticVector, error)
|
||||
// CandidateItemVectors returns the item vectors of each candidate.
|
||||
CandidateItemVectors(ctx context.Context, model domain.SemanticModel, candidateIDs []uuid.UUID) (map[uuid.UUID][]SemanticItemVector, error)
|
||||
// NeedVectors returns the stored vectors of a need whose content digest
|
||||
// is one of digests, by item key.
|
||||
NeedVectors(ctx context.Context, needID uuid.UUID, model domain.SemanticModel, digests [][32]byte) (map[string]domain.SemanticVector, error)
|
||||
// CandidatesAfter lists the candidates with a saved profile after a cursor.
|
||||
CandidatesAfter(ctx context.Context, after uuid.UUID, limit int) ([]uuid.UUID, error)
|
||||
// NeedsAfter lists needs after a cursor with their current requirements
|
||||
// version.
|
||||
NeedsAfter(ctx context.Context, after uuid.UUID, limit int) ([]NeedReference, error)
|
||||
}
|
||||
|
||||
// NeedReference names one need and its current requirements snapshot.
|
||||
type NeedReference struct {
|
||||
OrganizationID uuid.UUID
|
||||
NeedID uuid.UUID
|
||||
RequirementsVersion int64
|
||||
}
|
||||
|
||||
// RepositoryCheckState is the state of a repository check; see
|
||||
// ProfileRepositoryCheckState in the public contract.
|
||||
type RepositoryCheckState string
|
||||
|
||||
const (
|
||||
RepositoryCheckPending RepositoryCheckState = "pending"
|
||||
RepositoryCheckVerified RepositoryCheckState = "verified"
|
||||
RepositoryCheckNotFound RepositoryCheckState = "not_found"
|
||||
RepositoryCheckUnavailable RepositoryCheckState = "unavailable"
|
||||
)
|
||||
|
||||
// RepositoryFailureClass is the bounded cause of an unavailable check.
|
||||
type RepositoryFailureClass string
|
||||
|
||||
const (
|
||||
RepositoryFailureRateLimited RepositoryFailureClass = "rate_limited"
|
||||
RepositoryFailureServerError RepositoryFailureClass = "server_error"
|
||||
RepositoryFailureNetwork RepositoryFailureClass = "network"
|
||||
RepositoryFailureInvalidResponse RepositoryFailureClass = "invalid_response"
|
||||
)
|
||||
|
||||
// RepositoryCheck is the stored check of one linked repository. Evidence
|
||||
// is set only for a verified repository.
|
||||
type RepositoryCheck struct {
|
||||
Key string
|
||||
State RepositoryCheckState
|
||||
GitHubID int64
|
||||
Evidence domain.RepositoryEvidence
|
||||
RepositoryETag string
|
||||
ReadmeETag string
|
||||
Failure RepositoryFailureClass
|
||||
CheckedAt time.Time
|
||||
RequestedAt time.Time
|
||||
}
|
||||
|
||||
// ProjectRepositoryStore keeps the repository checks of candidates inside
|
||||
// the caller's transaction.
|
||||
type ProjectRepositoryStore interface {
|
||||
List(ctx context.Context, candidateID uuid.UUID) ([]RepositoryCheck, error)
|
||||
// GetForUpdate locks and returns the check, or false when none exists.
|
||||
GetForUpdate(ctx context.Context, candidateID uuid.UUID, key string) (RepositoryCheck, bool, error)
|
||||
// Request creates a pending check or records a new request of a known one.
|
||||
Request(ctx context.Context, candidateID uuid.UUID, key string, at time.Time) error
|
||||
// Save stores the result of a finished check.
|
||||
Save(ctx context.Context, candidateID uuid.UUID, check RepositoryCheck) error
|
||||
// DeleteUnlinked removes the checks of repositories not in linkedKeys.
|
||||
DeleteUnlinked(ctx context.Context, candidateID uuid.UUID, linkedKeys []string) error
|
||||
// LatestRequest returns the time of the newest check request, or the zero
|
||||
// time when the candidate has none.
|
||||
LatestRequest(ctx context.Context, candidateID uuid.UUID) (time.Time, error)
|
||||
}
|
||||
|
||||
// RepositoryFetch is what one check read from the public GitHub API.
|
||||
type RepositoryFetch struct {
|
||||
// Found is false when the repository does not exist or is not public.
|
||||
Found bool
|
||||
GitHubID int64
|
||||
Evidence domain.RepositoryEvidence
|
||||
// NotModified is true when the conditional request matched the stored
|
||||
// ETag: the stored evidence is still current.
|
||||
NotModified bool
|
||||
RepositoryETag string
|
||||
ReadmeETag string
|
||||
}
|
||||
|
||||
// RepositoryFetchError carries the bounded failure class and, for a rate
|
||||
// limit, when GitHub allows the next request.
|
||||
type RepositoryFetchError struct {
|
||||
Class RepositoryFailureClass
|
||||
RetryAfter time.Duration
|
||||
}
|
||||
|
||||
func (err *RepositoryFetchError) Error() string {
|
||||
return "repository fetch failed: " + string(err.Class)
|
||||
}
|
||||
|
||||
func (err *RepositoryFetchError) Unwrap() error { return ErrRepositoryFetchUnavailable }
|
||||
|
||||
// RepositoryMetadataFetcher reads public repository metadata. The only host
|
||||
// it may contact is the public GitHub API.
|
||||
type RepositoryMetadataFetcher interface {
|
||||
Fetch(ctx context.Context, repository domain.GitHubRepository, previous RepositoryCheck) (RepositoryFetch, error)
|
||||
}
|
||||
@@ -82,6 +82,8 @@ type UnitOfWork interface {
|
||||
NotificationRights() NotificationRightsReader
|
||||
Outbox() OutboxWriter
|
||||
ScheduledJobs() JobScheduler
|
||||
SemanticVectors() SemanticVectorRepository
|
||||
ProjectRepositories() ProjectRepositoryStore
|
||||
}
|
||||
|
||||
// OutboxWriter appends domain events to the transactional outbox. Events become
|
||||
|
||||
@@ -26,19 +26,28 @@ var (
|
||||
type Dependencies struct {
|
||||
Transactor outbound.Transactor
|
||||
Clock func() time.Time
|
||||
// Semantic schedules the card vector refresh after a publication change;
|
||||
// nil schedules nothing.
|
||||
Semantic SemanticTrigger
|
||||
}
|
||||
|
||||
// SemanticTrigger schedules the refresh of a candidate's card vectors.
|
||||
type SemanticTrigger interface {
|
||||
CandidateChanged(ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, at time.Time) error
|
||||
}
|
||||
|
||||
// Service applies candidate-owned privacy settings in one transaction.
|
||||
type Service struct {
|
||||
transactor outbound.Transactor
|
||||
clock func() time.Time
|
||||
semantic SemanticTrigger
|
||||
}
|
||||
|
||||
func NewService(deps Dependencies) (*Service, error) {
|
||||
if deps.Transactor == nil || deps.Clock == nil {
|
||||
return nil, fmt.Errorf("candidateprivacy.NewService - dependencies are missing: %w", ErrPrivacyServiceUnavailable)
|
||||
}
|
||||
return &Service{transactor: deps.Transactor, clock: deps.Clock}, nil
|
||||
return &Service{transactor: deps.Transactor, clock: deps.Clock, semantic: deps.Semantic}, nil
|
||||
}
|
||||
|
||||
func (service *Service) GetMyPrivacySettings(ctx context.Context, userID uuid.UUID) (outbound.CandidatePrivacySettings, error) {
|
||||
@@ -110,7 +119,17 @@ func (service *Service) SetMyPublication(
|
||||
if !change.Changed {
|
||||
return nil
|
||||
}
|
||||
return persistPublicationChange(ctx, unit, repository, userID, expectedVersion, change, at, location)
|
||||
if err := persistPublicationChange(ctx, unit, repository, userID, expectedVersion, change, at, location); err != nil {
|
||||
return err
|
||||
}
|
||||
// The published fields are the text of the card vectors: a closed card
|
||||
// drops them, and another field set renders another text.
|
||||
if service.semantic != nil {
|
||||
if err := service.semantic.CandidateChanged(ctx, unit, userID, at); err != nil {
|
||||
return fmt.Errorf("%s - schedule vector refresh: %w", location, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Publication{}, fmt.Errorf("%s - run transaction: %w", location, err)
|
||||
|
||||
@@ -766,6 +766,9 @@ func cardViewAccessEvent(
|
||||
if view.SalaryCompatibility != nil {
|
||||
fields = append(fields, domain.CardFieldSalaryCompatibility)
|
||||
}
|
||||
if len(view.Projects) > 0 {
|
||||
fields = append(fields, domain.CardFieldProjects)
|
||||
}
|
||||
if !domain.IsCandidateViewPseudonym(view.Pseudonym) {
|
||||
return domain.CandidateCardAccess{}, ErrInvalidCandidateHandle
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -33,6 +33,14 @@ type Dependencies struct {
|
||||
Transactor outbound.Transactor
|
||||
Keyring Keyring
|
||||
Clock func() time.Time
|
||||
// Semantic schedules the vectors of a new requirements snapshot; nil
|
||||
// schedules nothing.
|
||||
Semantic SemanticTrigger
|
||||
}
|
||||
|
||||
// SemanticTrigger schedules the vectors of a need's requirements snapshot.
|
||||
type SemanticTrigger interface {
|
||||
NeedRequirementsChanged(ctx context.Context, unit outbound.UnitOfWork, organizationID, needID uuid.UUID, requirementsVersion int64, at time.Time) error
|
||||
}
|
||||
|
||||
// Service applies organization-scoped need commands and reads.
|
||||
@@ -40,6 +48,7 @@ type Service struct {
|
||||
transactor outbound.Transactor
|
||||
keyring Keyring
|
||||
clock func() time.Time
|
||||
semantic SemanticTrigger
|
||||
}
|
||||
|
||||
// NewService fails at startup when a required dependency is missing.
|
||||
@@ -47,7 +56,7 @@ func NewService(deps Dependencies) (*Service, error) {
|
||||
if deps.Transactor == nil || deps.Keyring == nil || deps.Clock == nil {
|
||||
return nil, errors.New("need.NewService - every dependency must be set")
|
||||
}
|
||||
return &Service{transactor: deps.Transactor, keyring: deps.Keyring, clock: deps.Clock}, nil
|
||||
return &Service{transactor: deps.Transactor, keyring: deps.Keyring, clock: deps.Clock, semantic: deps.Semantic}, nil
|
||||
}
|
||||
|
||||
// CreateCommand binds the authenticated actor and path organization to one
|
||||
@@ -110,6 +119,9 @@ func (service *Service) createInTransaction(
|
||||
if err := unit.Needs().Create(ctx, createdNeed); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - store need: %w", createLocation, err)
|
||||
}
|
||||
if err := service.scheduleSemantic(ctx, unit, command.OrganizationID, needID, createdNeed.RequirementsVersion(), request.now); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - %w", createLocation, err)
|
||||
}
|
||||
if err := unit.NeedCreationResults().SaveCreationResult(ctx, request.scope, snapshot); err != nil {
|
||||
return domain.NeedResponseSnapshot{}, fmt.Errorf("%s - store immutable creation response: %w", createLocation, err)
|
||||
}
|
||||
@@ -305,9 +317,28 @@ func (service *Service) updateInTransaction(
|
||||
}
|
||||
return service.recoverConcurrentUpdate(ctx, store, command, now)
|
||||
}
|
||||
if updated.RequirementsVersion() != current.RequirementsVersion() {
|
||||
if err := service.scheduleSemantic(ctx, unit, command.OrganizationID, command.NeedID, updated.RequirementsVersion(), now); err != nil {
|
||||
return domain.Need{}, fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
}
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
// scheduleSemantic schedules the vectors of a new requirements snapshot in
|
||||
// the transaction that created it.
|
||||
func (service *Service) scheduleSemantic(
|
||||
ctx context.Context, unit outbound.UnitOfWork, organizationID, needID uuid.UUID, requirementsVersion int64, at time.Time,
|
||||
) error {
|
||||
if service.semantic == nil {
|
||||
return nil
|
||||
}
|
||||
if err := service.semantic.NeedRequirementsChanged(ctx, unit, organizationID, needID, requirementsVersion, at); err != nil {
|
||||
return fmt.Errorf("schedule need vectors: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service *Service) recoverConcurrentUpdate(
|
||||
ctx context.Context,
|
||||
store outbound.NeedRepository,
|
||||
|
||||
@@ -33,7 +33,31 @@ type MatchingResult struct {
|
||||
// latest version that is not a demonstration version and a family without a
|
||||
// version, because the section is only an addition to a policy that exists.
|
||||
func (publisher *Publisher) EnsureDemoMatchingSection(ctx context.Context, author domain.PolicyAuthor) (MatchingResult, error) {
|
||||
const location = "Publisher.EnsureDemoMatchingSection"
|
||||
return publisher.ensureMatching(ctx, author, "Publisher.EnsureDemoMatchingSection",
|
||||
func(current *domain.MatchingPolicy) bool { return current != nil },
|
||||
domain.DemoMatchingPolicy)
|
||||
}
|
||||
|
||||
// EnsureDemoSemanticMatchingSection makes the latest demonstration version
|
||||
// carry the semantic matching section (domain.DemoSemanticMatchingPolicy): the
|
||||
// encoder identity, the calibration of Sem, the explanation thresholds, and
|
||||
// the Fit weights with Sem 0.5. A version that already has a semantic section
|
||||
// is left alone. Otherwise it publishes the next version, a copy of the latest
|
||||
// one whose matching section is replaced, so the earlier PRD point stays as
|
||||
// the previous version.
|
||||
func (publisher *Publisher) EnsureDemoSemanticMatchingSection(ctx context.Context, author domain.PolicyAuthor) (MatchingResult, error) {
|
||||
return publisher.ensureMatching(ctx, author, "Publisher.EnsureDemoSemanticMatchingSection",
|
||||
func(current *domain.MatchingPolicy) bool { return current != nil && current.Semantics != nil },
|
||||
domain.DemoSemanticMatchingPolicy)
|
||||
}
|
||||
|
||||
func (publisher *Publisher) ensureMatching(
|
||||
ctx context.Context,
|
||||
author domain.PolicyAuthor,
|
||||
location string,
|
||||
present func(*domain.MatchingPolicy) bool,
|
||||
section func() domain.MatchingPolicy,
|
||||
) (MatchingResult, error) {
|
||||
latest, err := publisher.policies.GetLatest(ctx, domain.ProductPolicyKey)
|
||||
if errors.Is(err, outbound.ErrPolicyVersionNotFound) {
|
||||
return MatchingResult{}, fmt.Errorf("%s - the product policy has no version to extend: %w", location, err)
|
||||
@@ -42,13 +66,13 @@ func (publisher *Publisher) EnsureDemoMatchingSection(ctx context.Context, autho
|
||||
return MatchingResult{}, fmt.Errorf("%s - read latest version: %w", location, err)
|
||||
}
|
||||
current := latest.Policy()
|
||||
if current.Matching != nil {
|
||||
if present(current.Matching) {
|
||||
return MatchingResult{Version: latest}, nil
|
||||
}
|
||||
if latest.Kind() != domain.PolicyKindDemo {
|
||||
return MatchingResult{}, fmt.Errorf("%s - latest version %d is %s: %w", location, latest.Version(), latest.Kind(), ErrNotDemoPolicy)
|
||||
}
|
||||
matching := domain.DemoMatchingPolicy()
|
||||
matching := section()
|
||||
current.Matching = &matching
|
||||
// The new version is built on the version that was read, so it takes the
|
||||
// next number exactly once. A taken number means the base is no longer the
|
||||
|
||||
@@ -21,8 +21,31 @@ var (
|
||||
|
||||
// ErrEmailNotVerified reports an account whose current email is not confirmed.
|
||||
ErrEmailNotVerified = errors.New("candidate profile requires a confirmed email")
|
||||
|
||||
// ErrRepositoryChecksTooSoon reports a check request inside the
|
||||
// per-candidate interval; RepositoryCheckLimitError carries the wait.
|
||||
ErrRepositoryChecksTooSoon = errors.New("repository checks were requested too recently")
|
||||
)
|
||||
|
||||
// RepositoryCheckLimitError is ErrRepositoryChecksTooSoon with the time
|
||||
// until the next request is allowed.
|
||||
type RepositoryCheckLimitError struct {
|
||||
RetryAfter time.Duration
|
||||
}
|
||||
|
||||
func (err *RepositoryCheckLimitError) Error() string { return ErrRepositoryChecksTooSoon.Error() }
|
||||
|
||||
func (err *RepositoryCheckLimitError) Unwrap() error { return ErrRepositoryChecksTooSoon }
|
||||
|
||||
// SemanticTrigger schedules the background work that a profile change needs:
|
||||
// the vector refresh of the card and the checks of linked repositories. A
|
||||
// nil trigger schedules nothing.
|
||||
type SemanticTrigger interface {
|
||||
CandidateChanged(ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, at time.Time) error
|
||||
RepositoriesChanged(ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, previous, current []domain.GitHubRepository, at time.Time) error
|
||||
RequestChecks(ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, repositories []domain.GitHubRepository, at time.Time) error
|
||||
}
|
||||
|
||||
// View is the profile as the candidate reads it: the saved document and the
|
||||
// categories that assessment results confirmed. The categories are derived by
|
||||
// the server, are read-only, and are never part of the saved document.
|
||||
@@ -31,6 +54,9 @@ type View struct {
|
||||
// ConfirmedCategories holds at most one category per specialization, in
|
||||
// catalog order.
|
||||
ConfirmedCategories []domain.CandidateAssessmentCategory
|
||||
// RepositoryChecks are the server checks of the linked repositories, by
|
||||
// repository key.
|
||||
RepositoryChecks map[string]outbound.RepositoryCheck
|
||||
}
|
||||
|
||||
// Service is stateless between calls. Profile data, its history, and onboarding
|
||||
@@ -38,8 +64,15 @@ type View struct {
|
||||
type Service struct {
|
||||
transactor outbound.Transactor
|
||||
clock func() time.Time
|
||||
semantic SemanticTrigger
|
||||
// checkInterval is the shortest time between two check requests of one
|
||||
// candidate through RequestRepositoryChecks.
|
||||
checkInterval time.Duration
|
||||
}
|
||||
|
||||
// defaultRepositoryCheckInterval applies until WithSemantic sets another.
|
||||
const defaultRepositoryCheckInterval = 10 * time.Minute
|
||||
|
||||
// NewService takes the transaction boundary and application clock. A nil
|
||||
// dependency is a wiring error and panics at construction.
|
||||
func NewService(transactor outbound.Transactor, clock func() time.Time) *Service {
|
||||
@@ -49,7 +82,16 @@ func NewService(transactor outbound.Transactor, clock func() time.Time) *Service
|
||||
if clock == nil {
|
||||
panic("profile.NewService - clock must not be nil")
|
||||
}
|
||||
return &Service{transactor: transactor, clock: clock}
|
||||
return &Service{transactor: transactor, clock: clock, checkInterval: defaultRepositoryCheckInterval}
|
||||
}
|
||||
|
||||
// WithSemantic sets the background trigger and the check request interval.
|
||||
func (service *Service) WithSemantic(trigger SemanticTrigger, checkInterval time.Duration) *Service {
|
||||
service.semantic = trigger
|
||||
if checkInterval > 0 {
|
||||
service.checkInterval = checkInterval
|
||||
}
|
||||
return service
|
||||
}
|
||||
|
||||
// GetMyProfile reads only the profile owned by userID, with the categories
|
||||
@@ -114,6 +156,9 @@ func (service *Service) SaveMyProfile(
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - save profile: %w", location, err)
|
||||
}
|
||||
if err := service.scheduleBackground(ctx, unit, userID, current, updated, at); err != nil {
|
||||
return fmt.Errorf("%s - %w", location, err)
|
||||
}
|
||||
}
|
||||
if err := repository.AdvanceOnboarding(ctx, userID, at); err != nil {
|
||||
return fmt.Errorf("%s - advance onboarding: %w", location, err)
|
||||
@@ -130,6 +175,68 @@ func (service *Service) SaveMyProfile(
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// scheduleBackground schedules the card vector refresh and the checks of
|
||||
// newly linked repositories in the save transaction, so they exist exactly
|
||||
// when the change committed and the save never waits for them.
|
||||
func (service *Service) scheduleBackground(
|
||||
ctx context.Context, unit outbound.UnitOfWork, userID uuid.UUID, previous, updated domain.CandidateProfile, at time.Time,
|
||||
) error {
|
||||
if service.semantic == nil {
|
||||
return nil
|
||||
}
|
||||
if err := service.semantic.RepositoriesChanged(ctx, unit, userID,
|
||||
previous.Content().ProjectRepositories(), updated.Content().ProjectRepositories(), at); err != nil {
|
||||
return fmt.Errorf("schedule repository checks: %w", err)
|
||||
}
|
||||
if err := service.semantic.CandidateChanged(ctx, unit, userID, at); err != nil {
|
||||
return fmt.Errorf("schedule vector refresh: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RequestRepositoryChecks schedules a new check of every repository that the
|
||||
// current profile links. A candidate may ask once per check interval; an
|
||||
// earlier request answers RepositoryCheckLimitError and schedules nothing.
|
||||
func (service *Service) RequestRepositoryChecks(ctx context.Context, userID uuid.UUID) (int, error) {
|
||||
const location = "Service.RequestRepositoryChecks"
|
||||
if userID == uuid.Nil {
|
||||
return 0, fmt.Errorf("%s - user ID must be set: %w", location, domain.ErrInvalidCandidateProfile)
|
||||
}
|
||||
at := service.clock().UTC()
|
||||
var scheduled int
|
||||
err := service.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
if err := requireCandidate(ctx, unit, userID, location); err != nil {
|
||||
return err
|
||||
}
|
||||
profile, err := unit.CandidateProfiles().Get(ctx, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read profile: %w", location, err)
|
||||
}
|
||||
repositories := profile.Content().ProjectRepositories()
|
||||
if len(repositories) == 0 {
|
||||
return nil
|
||||
}
|
||||
latest, err := unit.ProjectRepositories().LatestRequest(ctx, userID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - read latest request: %w", location, err)
|
||||
}
|
||||
if next := latest.Add(service.checkInterval); !latest.IsZero() && at.Before(next) {
|
||||
return &RepositoryCheckLimitError{RetryAfter: next.Sub(at)}
|
||||
}
|
||||
if service.semantic != nil {
|
||||
if err := service.semantic.RequestChecks(ctx, unit, userID, repositories, at); err != nil {
|
||||
return fmt.Errorf("%s - schedule checks: %w", location, err)
|
||||
}
|
||||
}
|
||||
scheduled = len(repositories)
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s - transaction: %w", location, err)
|
||||
}
|
||||
return scheduled, nil
|
||||
}
|
||||
|
||||
// readView attaches the confirmed categories of the candidate to a profile
|
||||
// that was read or written in the same transaction.
|
||||
func readView(
|
||||
@@ -143,7 +250,17 @@ func readView(
|
||||
if err != nil {
|
||||
return View{}, fmt.Errorf("%s - read confirmed categories: %w", location, err)
|
||||
}
|
||||
return View{Profile: profile, ConfirmedCategories: inCatalogOrder(categories)}, nil
|
||||
checks := make(map[string]outbound.RepositoryCheck)
|
||||
if len(profile.Content().ProjectRepositories()) > 0 {
|
||||
stored, err := unit.ProjectRepositories().List(ctx, userID)
|
||||
if err != nil {
|
||||
return View{}, fmt.Errorf("%s - read repository checks: %w", location, err)
|
||||
}
|
||||
for _, check := range stored {
|
||||
checks[check.Key] = check
|
||||
}
|
||||
}
|
||||
return View{Profile: profile, ConfirmedCategories: inCatalogOrder(categories), RepositoryChecks: checks}, nil
|
||||
}
|
||||
|
||||
// inCatalogOrder sorts the categories by their place in the catalog. A
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
package semantic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// BackfillPageSize is the number of subjects one backfill transaction
|
||||
// schedules.
|
||||
const BackfillPageSize = 200
|
||||
|
||||
var backfillRunPattern = regexp.MustCompile(`^[a-z0-9-]{1,32}$`)
|
||||
|
||||
// BackfillScope selects what a backfill schedules.
|
||||
type BackfillScope string
|
||||
|
||||
const (
|
||||
BackfillCandidates BackfillScope = "candidates"
|
||||
BackfillNeeds BackfillScope = "needs"
|
||||
)
|
||||
|
||||
// BackfillProgress reports one finished page: how many jobs it scheduled
|
||||
// and the cursor to resume after.
|
||||
type BackfillProgress struct {
|
||||
Scope BackfillScope
|
||||
Scheduled int
|
||||
After uuid.UUID
|
||||
Done bool
|
||||
}
|
||||
|
||||
// Backfill schedules vector jobs for every candidate with a saved profile or
|
||||
// every need, page by page in identifier order. The job of a candidate who is
|
||||
// not published removes any stored vectors, so the backfill also cleans up.
|
||||
// A run label makes the job keys, so repeating a run schedules nothing twice,
|
||||
// and a new label recomputes again; a job whose texts did not change costs no
|
||||
// ML call. The cursor of the last page resumes an interrupted run.
|
||||
type Backfill struct {
|
||||
transactor outbound.Transactor
|
||||
clock func() time.Time
|
||||
}
|
||||
|
||||
// NewBackfill returns the backfill.
|
||||
func NewBackfill(transactor outbound.Transactor, clock func() time.Time) (*Backfill, error) {
|
||||
if transactor == nil || clock == nil {
|
||||
return nil, errors.New("semantic.NewBackfill - transactor and clock must be set")
|
||||
}
|
||||
return &Backfill{transactor: transactor, clock: clock}, nil
|
||||
}
|
||||
|
||||
// Run schedules pages until the scope is exhausted and reports each page.
|
||||
func (backfill *Backfill) Run(
|
||||
ctx context.Context, scope BackfillScope, run string, after uuid.UUID, report func(BackfillProgress) error,
|
||||
) error {
|
||||
const location = "semantic.Backfill.Run"
|
||||
if !backfillRunPattern.MatchString(run) {
|
||||
return errors.New(location + " - run label must be 1 to 32 lower-case letters, digits, or hyphens")
|
||||
}
|
||||
if scope != BackfillCandidates && scope != BackfillNeeds {
|
||||
return errors.New(location + " - scope must be candidates or needs")
|
||||
}
|
||||
cursor := after
|
||||
for {
|
||||
progress, err := backfill.page(ctx, scope, run, cursor)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s - schedule page: %w", location, err)
|
||||
}
|
||||
if report != nil {
|
||||
if err := report(progress); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if progress.Done {
|
||||
return nil
|
||||
}
|
||||
cursor = progress.After
|
||||
}
|
||||
}
|
||||
|
||||
func (backfill *Backfill) page(ctx context.Context, scope BackfillScope, run string, after uuid.UUID) (BackfillProgress, error) {
|
||||
progress := BackfillProgress{Scope: scope, After: after}
|
||||
err := backfill.transactor.WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
|
||||
at := backfill.clock().UTC()
|
||||
if scope == BackfillCandidates {
|
||||
ids, err := unit.SemanticVectors().CandidatesAfter(ctx, after, BackfillPageSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, id := range ids {
|
||||
if err := schedule(ctx, unit, CandidateJobKind, id.String()+":backfill-"+run, at,
|
||||
map[string]string{"candidate_id": id.String()}, vectorJobAttempts); err != nil {
|
||||
return err
|
||||
}
|
||||
progress.After = id
|
||||
}
|
||||
progress.Scheduled, progress.Done = len(ids), len(ids) < BackfillPageSize
|
||||
return nil
|
||||
}
|
||||
needs, err := unit.SemanticVectors().NeedsAfter(ctx, after, BackfillPageSize)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, need := range needs {
|
||||
key := need.NeedID.String() + ":" + strconv.FormatInt(need.RequirementsVersion, 10) + ":backfill-" + run
|
||||
if err := schedule(ctx, unit, NeedJobKind, key, at, map[string]any{
|
||||
"organization_id": need.OrganizationID.String(), "need_id": need.NeedID.String(),
|
||||
"requirements_version": need.RequirementsVersion,
|
||||
}, vectorJobAttempts); err != nil {
|
||||
return err
|
||||
}
|
||||
progress.After = need.NeedID
|
||||
}
|
||||
progress.Scheduled, progress.Done = len(needs), len(needs) < BackfillPageSize
|
||||
return nil
|
||||
})
|
||||
return progress, err
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package semantic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
var testNow = time.Date(2026, 10, 11, 12, 0, 0, 0, time.UTC)
|
||||
|
||||
type schedulerFake struct {
|
||||
jobs []domain.ScheduledJob
|
||||
}
|
||||
|
||||
func (scheduler *schedulerFake) Schedule(_ context.Context, job domain.ScheduledJob) (bool, error) {
|
||||
scheduler.jobs = append(scheduler.jobs, job)
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (*schedulerFake) Cancel(context.Context, string, string) (bool, error) { return false, nil }
|
||||
|
||||
type repositoriesFake struct {
|
||||
outbound.ProjectRepositoryStore
|
||||
|
||||
requested []string
|
||||
linked []string
|
||||
}
|
||||
|
||||
func (store *repositoriesFake) Request(_ context.Context, _ uuid.UUID, key string, _ time.Time) error {
|
||||
store.requested = append(store.requested, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *repositoriesFake) DeleteUnlinked(_ context.Context, _ uuid.UUID, keys []string) error {
|
||||
store.linked = keys
|
||||
return nil
|
||||
}
|
||||
|
||||
type unitFake struct {
|
||||
outbound.UnitOfWork
|
||||
|
||||
scheduler *schedulerFake
|
||||
repositories *repositoriesFake
|
||||
}
|
||||
|
||||
func (unit unitFake) ScheduledJobs() outbound.JobScheduler { return unit.scheduler }
|
||||
func (unit unitFake) ProjectRepositories() outbound.ProjectRepositoryStore { return unit.repositories }
|
||||
|
||||
func repo(t *testing.T, raw string) domain.GitHubRepository {
|
||||
t.Helper()
|
||||
parsed, err := domain.ParseGitHubRepositoryURL(raw)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseGitHubRepositoryURL() error = %v", err)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func TestTriggerSchedulesOnlyEnabledWorkAndNamesNoRepository(t *testing.T) {
|
||||
unit := unitFake{scheduler: &schedulerFake{}, repositories: &repositoriesFake{}}
|
||||
candidate := uuid.New()
|
||||
kept := repo(t, "https://github.com/Private-Owner/kept")
|
||||
added := repo(t, "https://github.com/Private-Owner/added")
|
||||
trigger := NewTrigger(true, true)
|
||||
if err := trigger.RepositoriesChanged(context.Background(), unit, candidate, []domain.GitHubRepository{kept}, []domain.GitHubRepository{kept, added}, testNow); err != nil {
|
||||
t.Fatalf("RepositoriesChanged() error = %v", err)
|
||||
}
|
||||
if err := trigger.CandidateChanged(context.Background(), unit, candidate, testNow); err != nil {
|
||||
t.Fatalf("CandidateChanged() error = %v", err)
|
||||
}
|
||||
if strings.Join(unit.repositories.requested, ",") != "private-owner/added" || len(unit.repositories.linked) != 2 {
|
||||
t.Fatalf("requested %v linked %v, want only the new repository requested", unit.repositories.requested, unit.repositories.linked)
|
||||
}
|
||||
kinds := map[string]int{}
|
||||
for _, job := range unit.scheduler.jobs {
|
||||
kinds[job.Kind()]++
|
||||
text := strings.ToLower(job.Key() + string(job.Payload()))
|
||||
if strings.Contains(text, "private-owner") || strings.Contains(text, "github") {
|
||||
t.Fatalf("job %s names the repository: %s %s", job.Kind(), job.Key(), job.Payload())
|
||||
}
|
||||
}
|
||||
if kinds[RepositoryCheckJobKind] != 1 || kinds[CandidateJobKind] != 1 {
|
||||
t.Fatalf("jobs = %v", kinds)
|
||||
}
|
||||
|
||||
disabled := unitFake{scheduler: &schedulerFake{}, repositories: &repositoriesFake{}}
|
||||
off := NewTrigger(false, false)
|
||||
if err := off.RepositoriesChanged(context.Background(), disabled, candidate, nil, []domain.GitHubRepository{added}, testNow); err != nil {
|
||||
t.Fatalf("RepositoriesChanged(off) error = %v", err)
|
||||
}
|
||||
if err := off.CandidateChanged(context.Background(), disabled, candidate, testNow); err != nil {
|
||||
t.Fatalf("CandidateChanged(off) error = %v", err)
|
||||
}
|
||||
if len(disabled.scheduler.jobs) != 0 || len(disabled.repositories.requested) != 1 {
|
||||
t.Fatalf("disabled trigger scheduled %d jobs and requested %v, want only the recorded request", len(disabled.scheduler.jobs), disabled.repositories.requested)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckResultMapsFetchOutcomes(t *testing.T) {
|
||||
previous := outbound.RepositoryCheck{Key: "a/b", State: outbound.RepositoryCheckVerified, Evidence: domain.RepositoryEvidence{Description: "old"}}
|
||||
verified, wait, err := checkResult(previous, outbound.RepositoryFetch{Found: true, GitHubID: 3, Evidence: domain.RepositoryEvidence{Description: "new"}}, nil, testNow)
|
||||
if err != nil || wait != 0 || verified.State != outbound.RepositoryCheckVerified || !evidenceChanged(previous, verified) {
|
||||
t.Fatalf("verified = %+v, %v, %v", verified, wait, err)
|
||||
}
|
||||
missing, _, _ := checkResult(previous, outbound.RepositoryFetch{}, nil, testNow)
|
||||
if missing.State != outbound.RepositoryCheckNotFound || missing.Evidence.Description != "" || !evidenceChanged(previous, missing) {
|
||||
t.Fatalf("missing = %+v", missing)
|
||||
}
|
||||
limited, wait, err := checkResult(previous, outbound.RepositoryFetch{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureRateLimited, RetryAfter: time.Hour}, testNow)
|
||||
if err != nil || wait != time.Hour || limited.State != outbound.RepositoryCheckUnavailable || limited.Failure != outbound.RepositoryFailureRateLimited {
|
||||
t.Fatalf("limited = %+v, %v, %v", limited, wait, err)
|
||||
}
|
||||
if _, _, err := checkResult(previous, outbound.RepositoryFetch{}, &outbound.RepositoryFetchError{Class: outbound.RepositoryFailureNetwork}, testNow); !errors.Is(err, outbound.ErrRepositoryFetchUnavailable) {
|
||||
t.Fatalf("a network failure was not returned for a retry: %v", err)
|
||||
}
|
||||
same := previous
|
||||
if evidenceChanged(previous, same) {
|
||||
t.Fatal("an unchanged check reported a change")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
// Package semantic keeps the stored vectors of candidate cards and need
|
||||
// snapshots current and checks the GitHub repositories of projects. Every
|
||||
// change that can move a vector schedules a durable job in the transaction of
|
||||
// the change; the jobs call the ML service and GitHub later, so no user
|
||||
// request ever waits for either.
|
||||
package semantic
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"slices"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// Job kinds. Renaming one strands the jobs scheduled under the old name.
|
||||
const (
|
||||
CandidateJobKind = "semantic.candidate"
|
||||
NeedJobKind = "semantic.need"
|
||||
RepositoryCheckJobKind = "profile.repository_check"
|
||||
)
|
||||
|
||||
const (
|
||||
// vectorJobAttempts lets a vector job outlast an ML outage of about an
|
||||
// hour and a half with the default backoff; the backfill command repairs
|
||||
// anything older.
|
||||
vectorJobAttempts = 20
|
||||
// repositoryJobAttempts bounds retries of network and server failures;
|
||||
// a rate limit reschedules instead of failing.
|
||||
repositoryJobAttempts = 5
|
||||
// repositoryDigestBytes is the length of the repository digest in a job
|
||||
// key and payload: the repository address names an account, so jobs
|
||||
// carry only its digest.
|
||||
repositoryDigestBytes = 8
|
||||
)
|
||||
|
||||
// Trigger schedules the jobs. With vectors off it schedules no vector job;
|
||||
// with repository checks off it records the request but schedules no check.
|
||||
type Trigger struct {
|
||||
vectors bool
|
||||
repositories bool
|
||||
}
|
||||
|
||||
// NewTrigger returns the scheduler of the enabled features.
|
||||
func NewTrigger(vectors, repositories bool) *Trigger {
|
||||
return &Trigger{vectors: vectors, repositories: repositories}
|
||||
}
|
||||
|
||||
// CandidateChanged schedules a refresh of the card vectors of a candidate.
|
||||
// Every change gets its own job; a job that finds nothing changed is a no-op.
|
||||
func (trigger *Trigger) CandidateChanged(ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, at time.Time) error {
|
||||
if trigger == nil || !trigger.vectors {
|
||||
return nil
|
||||
}
|
||||
occurrence, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return fmt.Errorf("semantic.Trigger.CandidateChanged - generate key: %w", err)
|
||||
}
|
||||
return schedule(ctx, unit, CandidateJobKind, candidateID.String()+":"+occurrence.String(), at,
|
||||
map[string]string{"candidate_id": candidateID.String()}, vectorJobAttempts)
|
||||
}
|
||||
|
||||
// NeedRequirementsChanged schedules the vectors of a new requirements
|
||||
// snapshot. The key is the snapshot, so a repeat schedules nothing.
|
||||
func (trigger *Trigger) NeedRequirementsChanged(
|
||||
ctx context.Context, unit outbound.UnitOfWork, organizationID, needID uuid.UUID, requirementsVersion int64, at time.Time,
|
||||
) error {
|
||||
if trigger == nil || !trigger.vectors {
|
||||
return nil
|
||||
}
|
||||
return schedule(ctx, unit, NeedJobKind, needID.String()+":"+strconv.FormatInt(requirementsVersion, 10), at,
|
||||
map[string]any{
|
||||
"organization_id": organizationID.String(), "need_id": needID.String(),
|
||||
"requirements_version": requirementsVersion,
|
||||
}, vectorJobAttempts)
|
||||
}
|
||||
|
||||
// RepositoriesChanged follows a profile save: it removes the checks of
|
||||
// repositories that no project links any more and requests a check of every
|
||||
// newly linked repository. A repository that was linked before keeps its
|
||||
// check; the candidate asks for a new one explicitly.
|
||||
func (trigger *Trigger) RepositoriesChanged(
|
||||
ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID,
|
||||
previous, current []domain.GitHubRepository, at time.Time,
|
||||
) error {
|
||||
const location = "semantic.Trigger.RepositoriesChanged"
|
||||
keys := make([]string, 0, len(current))
|
||||
for _, repository := range current {
|
||||
keys = append(keys, repository.Key())
|
||||
}
|
||||
if err := unit.ProjectRepositories().DeleteUnlinked(ctx, candidateID, keys); err != nil {
|
||||
return fmt.Errorf("%s - remove unlinked checks: %w", location, err)
|
||||
}
|
||||
known := make(map[string]bool, len(previous))
|
||||
for _, repository := range previous {
|
||||
known[repository.Key()] = true
|
||||
}
|
||||
for _, repository := range current {
|
||||
if known[repository.Key()] {
|
||||
continue
|
||||
}
|
||||
if err := trigger.requestCheck(ctx, unit, candidateID, repository, at); err != nil {
|
||||
return fmt.Errorf("%s - request check: %w", location, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RequestChecks requests a new check of every given repository.
|
||||
func (trigger *Trigger) RequestChecks(
|
||||
ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, repositories []domain.GitHubRepository, at time.Time,
|
||||
) error {
|
||||
for _, repository := range repositories {
|
||||
if err := trigger.requestCheck(ctx, unit, candidateID, repository, at); err != nil {
|
||||
return fmt.Errorf("semantic.Trigger.RequestChecks - request check: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (trigger *Trigger) requestCheck(
|
||||
ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, repository domain.GitHubRepository, at time.Time,
|
||||
) error {
|
||||
if err := unit.ProjectRepositories().Request(ctx, candidateID, repository.Key(), at); err != nil {
|
||||
return err
|
||||
}
|
||||
if trigger == nil || !trigger.repositories {
|
||||
return nil
|
||||
}
|
||||
return scheduleRepositoryCheck(ctx, unit, candidateID, repository.Key(), at)
|
||||
}
|
||||
|
||||
func scheduleRepositoryCheck(ctx context.Context, unit outbound.UnitOfWork, candidateID uuid.UUID, key string, at time.Time) error {
|
||||
occurrence, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return fmt.Errorf("generate key: %w", err)
|
||||
}
|
||||
digest := repositoryDigest(key)
|
||||
return schedule(ctx, unit, RepositoryCheckJobKind, candidateID.String()+":"+digest+":"+occurrence.String(), at,
|
||||
map[string]string{"candidate_id": candidateID.String(), "repository": digest}, repositoryJobAttempts)
|
||||
}
|
||||
|
||||
// repositoryDigest identifies a repository in a job without naming its owner.
|
||||
func repositoryDigest(key string) string {
|
||||
digest := sha256.Sum256([]byte(key))
|
||||
return hex.EncodeToString(digest[:repositoryDigestBytes])
|
||||
}
|
||||
|
||||
func schedule(ctx context.Context, unit outbound.UnitOfWork, kind, key string, at time.Time, payload any, attempts int) error {
|
||||
encoded, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return fmt.Errorf("semantic.schedule - encode payload: %w", err)
|
||||
}
|
||||
job, err := domain.NewScheduledJob(domain.ScheduledJobInput{Kind: kind, Key: key, DueAt: at, Payload: encoded, MaxAttempts: attempts})
|
||||
if err != nil {
|
||||
return fmt.Errorf("semantic.schedule - build job: %w", err)
|
||||
}
|
||||
if _, err := unit.ScheduledJobs().Schedule(ctx, job); err != nil {
|
||||
return fmt.Errorf("semantic.schedule - schedule job: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// linkedRepositories returns the repositories of the current projects that
|
||||
// match a digest.
|
||||
func linkedRepository(content domain.CandidateProfileContent, digest string) (domain.GitHubRepository, bool) {
|
||||
index := slices.IndexFunc(content.ProjectRepositories(), func(repository domain.GitHubRepository) bool {
|
||||
return repositoryDigest(repository.Key()) == digest
|
||||
})
|
||||
if index < 0 {
|
||||
return domain.GitHubRepository{}, false
|
||||
}
|
||||
return content.ProjectRepositories()[index], true
|
||||
}
|
||||
Reference in new issue
Block a user