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

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

No files matched your search

@@ -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