feat(ml): fuse two embedding models and protect the ML service with a token
This commit is contained in:
1 parent
bc00d6901f
commit
b24e5ff906
63 files changed
+2287
-276
No files matched your search
@@ -143,7 +143,7 @@ The candidate reads the facts at `GET /api/v1/me/evidence` (`usecase/evidence/re
|
||||
|
||||
## Match search
|
||||
|
||||
`POST /api/v1/organizations/{org_id}/matches` ranks the organization-visible candidate bank without ML (`usecase/matching/`). It runs in one transaction: `candidateview.Service.ListVisibleCards` applies the checks of a card read (verified employer, locked active membership, `ListVisibleCandidateViewSources` over `candidate_effective_publications` with `NOT EXISTS` over the hidden organizations, the account, C2, and publication locks, and the anonymous projection with its minimum cohort of five), the need snapshot is read by `requirements_version`, and the permitted evidence comes only from `ListOrganizationFacts`. The usecase repeats the owner role check; the HTTP boundary lists the operation in `ownerCompanyOperations`. A search is charged like card reads: each group is cut to the policy limit, and each candidate returned is reserved through the company quota port and recorded in the access history with the returned fields (`candidateview.SearchViews`); when the allowance ends the response is cut and flagged `truncated`. The operator publishes the matching section with `make policy-publish ARGS='matching --actor operator:<handle>'` (`cmd/policy-publish`), the semantic section with `ARGS='semantic --actor operator:<handle>'`, and schedules vectors for existing data with `make semantic-backfill ARGS='all --run <label>'` (`cmd/semantic-backfill`), see [DEPLOY](../docs/en/DEPLOY.md#match-search-policy-on-a-stand) and [semantic matching](../docs/en/DEPLOY.md#semantic-matching). The search itself never calls ML: it reads the vectors that the `semantic.candidate` and `semantic.need` jobs compute (`usecase/semantic/`).
|
||||
`POST /api/v1/organizations/{org_id}/matches` ranks the organization-visible candidate bank without ML (`usecase/matching/`). It runs in one transaction: `candidateview.Service.ListVisibleCards` applies the checks of a card read (verified employer, locked active membership, `ListVisibleCandidateViewSources` over `candidate_effective_publications` with `NOT EXISTS` over the hidden organizations, the account, C2, and publication locks, and the anonymous projection with its minimum cohort of five), the need snapshot is read by `requirements_version`, and the permitted evidence comes only from `ListOrganizationFacts`. The usecase repeats the owner role check; the HTTP boundary lists the operation in `ownerCompanyOperations`. A search is charged like card reads: each group is cut to the policy limit, and each candidate returned is reserved through the company quota port and recorded in the access history with the returned fields (`candidateview.SearchViews`); when the allowance ends the response is cut and flagged `truncated`. The operator publishes the matching section with `make policy-publish ARGS='matching --actor operator:<handle>'` (`cmd/policy-publish`), the semantic section with `ARGS='semantic --actor operator:<handle>'`, the Giga + Qwen3-Embedding ensemble with `ARGS='semantic-ensemble --actor operator:<handle>'`, and schedules vectors for existing data with `make semantic-backfill ARGS='all --run <label>'` (`cmd/semantic-backfill`), see [DEPLOY](../docs/en/DEPLOY.md#match-search-policy-on-a-stand) and [semantic matching](../docs/en/DEPLOY.md#semantic-matching). The search itself never calls ML: it reads the vectors that the `semantic.candidate` and `semantic.need` jobs compute (`usecase/semantic/`).
|
||||
|
||||
Each entry is one candidate specialization. Scores use the `matching` section of the effective product policy (`domain.MatchingPolicy`, demo version `DemoProductPolicyV4`); a policy without the section makes the search fail closed. The arithmetic is integer (micro units for components, basis points for shares), so the order is reproducible: confirmed groups sort by S, then coverage, then the internal candidate identifier; the unconfirmed group by Fit, then coverage, then the identifier, and it never computes theta, T, P, a percentile, or S. The explanation and the unknown flags are built from the same computed contributions. The model, the neutral values, and what is not implemented are described in [architecture](../docs/en/ARCHITECTURE.md#matching-and-explanations).
|
||||
|
||||
|
||||
+1
-1
@@ -142,7 +142,7 @@
|
||||
|
||||
## Подбор
|
||||
|
||||
`POST /api/v1/organizations/{org_id}/matches` ранжирует банк кандидатов, видимый организации, без ML (`usecase/matching/`). Он выполняется в одной транзакции: `candidateview.Service.ListVisibleCards` применяет проверки чтения карточки (подтвержденный работодатель, заблокированное действующее членство, `ListVisibleCandidateViewSources` по `candidate_effective_publications` с `NOT EXISTS` по скрытым организациям, блокировки аккаунта, C2 и публикации и анонимная проекция с минимальной когортой из пяти), снимок потребности читается по `requirements_version`, а разрешенные доказательства приходят только из `ListOrganizationFacts`. Usecase повторяет проверку роли владельца; HTTP-граница перечисляет операцию в `ownerCompanyOperations`. Поиск оплачивается как чтение карточек: каждая группа обрезается до предела политики, а каждый возвращенный кандидат резервируется через порт квоты компании и записывается в историю доступа с возвращенными полями (`candidateview.SearchViews`); когда лимит заканчивается, ответ обрезается и получает флаг `truncated`. Раздел подбора оператор публикует командой `make policy-publish ARGS='matching --actor operator:<handle>'` (`cmd/policy-publish`), семантический раздел - `ARGS='semantic --actor operator:<handle>'`, а векторы существующих данных ставит `make semantic-backfill ARGS='all --run <метка>'` (`cmd/semantic-backfill`), см. [DEPLOY](../docs/ru/DEPLOY.md#политика-подбора-на-стенде) и [семантический подбор](../docs/ru/DEPLOY.md#семантический-подбор). Поиск сам ML не вызывает: он читает векторы, которые считают задания `semantic.candidate` и `semantic.need` (`usecase/semantic/`).
|
||||
`POST /api/v1/organizations/{org_id}/matches` ранжирует банк кандидатов, видимый организации, без ML (`usecase/matching/`). Он выполняется в одной транзакции: `candidateview.Service.ListVisibleCards` применяет проверки чтения карточки (подтвержденный работодатель, заблокированное действующее членство, `ListVisibleCandidateViewSources` по `candidate_effective_publications` с `NOT EXISTS` по скрытым организациям, блокировки аккаунта, C2 и публикации и анонимная проекция с минимальной когортой из пяти), снимок потребности читается по `requirements_version`, а разрешенные доказательства приходят только из `ListOrganizationFacts`. Usecase повторяет проверку роли владельца; HTTP-граница перечисляет операцию в `ownerCompanyOperations`. Поиск оплачивается как чтение карточек: каждая группа обрезается до предела политики, а каждый возвращенный кандидат резервируется через порт квоты компании и записывается в историю доступа с возвращенными полями (`candidateview.SearchViews`); когда лимит заканчивается, ответ обрезается и получает флаг `truncated`. Раздел подбора оператор публикует командой `make policy-publish ARGS='matching --actor operator:<handle>'` (`cmd/policy-publish`), семантический раздел - `ARGS='semantic --actor operator:<handle>'`, ансамбль Giga + Qwen3-Embedding - `ARGS='semantic-ensemble --actor operator:<handle>'`, а векторы существующих данных ставит `make semantic-backfill ARGS='all --run <метка>'` (`cmd/semantic-backfill`), см. [DEPLOY](../docs/ru/DEPLOY.md#политика-подбора-на-стенде) и [семантический подбор](../docs/ru/DEPLOY.md#семантический-подбор). Поиск сам ML не вызывает: он читает векторы, которые считают задания `semantic.candidate` и `semantic.need` (`usecase/semantic/`).
|
||||
|
||||
Каждая запись - одна специализация кандидата. Баллы используют раздел `matching` действующей политики `product` (`domain.MatchingPolicy`, демонстрационная версия `DemoProductPolicyV4`); политика без раздела приводит к закрытому отказу. Арифметика целочисленная (микроединицы для компонентов, базисные пункты для долей), поэтому порядок воспроизводим: подтвержденные группы сортируются по S, затем по покрытию, затем по внутреннему идентификатору кандидата; неподтвержденная - по Fit, затем по покрытию, затем по идентификатору, и она никогда не вычисляет theta, T, P, перцентиль или S. Объяснение и признаки неизвестности строятся из тех же рассчитанных вкладов. Модель, нейтральные значения и нереализованное описаны в [архитектуре](../docs/ru/ARCHITECTURE.md#подбор-и-объяснение).
|
||||
|
||||
|
||||
@@ -2,6 +2,8 @@ package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -25,6 +27,10 @@ const (
|
||||
defaultGitHubChecksEnabled = false
|
||||
defaultGitHubTimeout = 10 * time.Second
|
||||
maxGitHubTimeout = time.Minute
|
||||
// minMLServiceTokenLength matches the ML service: 32 printable characters
|
||||
// of a CSPRNG token are far beyond an online guess.
|
||||
minMLServiceTokenLength = 32
|
||||
maxMLServiceTokenLength = 512
|
||||
// defaultRepositoryCheckInterval is the shortest time between two check
|
||||
// requests of one candidate through the refresh operation.
|
||||
defaultRepositoryCheckInterval = 10 * time.Minute
|
||||
@@ -32,14 +38,20 @@ const (
|
||||
)
|
||||
|
||||
// SemanticSettings configure semantic matching and repository checks.
|
||||
//
|
||||
// String, GoString, Format, and LogValue redact everything, because the ML
|
||||
// service token and the GitHub token are secrets of the deployment.
|
||||
type SemanticSettings struct {
|
||||
// SemanticMatchingEnabled schedules vector jobs on changes and runs them
|
||||
// against MLServiceURL. The search reads stored vectors either way.
|
||||
SemanticMatchingEnabled bool
|
||||
MLServiceURL string
|
||||
MLRequestTimeout time.Duration
|
||||
MLCircuitFailures int
|
||||
MLCircuitOpen time.Duration
|
||||
// MLServiceToken is the shared bearer token of the ML service. It is
|
||||
// required while semantic matching is enabled and is a secret: never log it.
|
||||
MLServiceToken string
|
||||
MLRequestTimeout time.Duration
|
||||
MLCircuitFailures int
|
||||
MLCircuitOpen time.Duration
|
||||
// GitHubChecksEnabled schedules and runs repository checks against the
|
||||
// public GitHub API.
|
||||
GitHubChecksEnabled bool
|
||||
@@ -50,12 +62,28 @@ type SemanticSettings struct {
|
||||
RepositoryCheckInterval time.Duration
|
||||
}
|
||||
|
||||
const redactedSemanticSettings = "[semantic settings redacted]"
|
||||
|
||||
func (settings SemanticSettings) String() string { return redactedSemanticSettings }
|
||||
|
||||
func (settings SemanticSettings) GoString() string { return redactedSemanticSettings }
|
||||
|
||||
// Format redacts every verb; without it %+v would print the tokens.
|
||||
func (settings SemanticSettings) Format(state fmt.State, _ rune) {
|
||||
_, _ = state.Write([]byte(redactedSemanticSettings))
|
||||
}
|
||||
|
||||
func (settings SemanticSettings) LogValue() slog.Value {
|
||||
return slog.StringValue(redactedSemanticSettings)
|
||||
}
|
||||
|
||||
// LoadSemanticSettings reads the semantic settings; the operator commands
|
||||
// that need only them use it directly.
|
||||
func LoadSemanticSettings(lookup LookupEnv) (SemanticSettings, error) {
|
||||
settings := SemanticSettings{
|
||||
MLServiceURL: strings.TrimSpace(valueOrDefault(lookup, "ML_SERVICE_URL", "")),
|
||||
GitHubToken: strings.TrimSpace(valueOrDefault(lookup, "GITHUB_TOKEN", "")),
|
||||
MLServiceURL: strings.TrimSpace(valueOrDefault(lookup, "ML_SERVICE_URL", "")),
|
||||
MLServiceToken: strings.TrimSpace(valueOrDefault(lookup, "ML_SERVICE_TOKEN", "")),
|
||||
GitHubToken: strings.TrimSpace(valueOrDefault(lookup, "GITHUB_TOKEN", "")),
|
||||
}
|
||||
var err error
|
||||
if settings.SemanticMatchingEnabled, err = boolOrDefault(lookup, "SEMANTIC_MATCHING_ENABLED", defaultSemanticMatchingEnabled); err != nil {
|
||||
@@ -96,6 +124,12 @@ func (settings SemanticSettings) validateMLService() error {
|
||||
if settings.SemanticMatchingEnabled && settings.MLServiceURL == "" {
|
||||
return errors.New(location + " - ML_SERVICE_URL is required when SEMANTIC_MATCHING_ENABLED is true")
|
||||
}
|
||||
if settings.SemanticMatchingEnabled && settings.MLServiceToken == "" {
|
||||
return errors.New(location + " - ML_SERVICE_TOKEN is required when SEMANTIC_MATCHING_ENABLED is true")
|
||||
}
|
||||
if err := validateMLServiceToken(settings.MLServiceToken); err != nil {
|
||||
return err
|
||||
}
|
||||
if settings.MLServiceURL != "" {
|
||||
parsed, err := url.Parse(settings.MLServiceURL)
|
||||
if err != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") || parsed.Host == "" ||
|
||||
@@ -106,6 +140,24 @@ func (settings SemanticSettings) validateMLService() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateMLServiceToken checks an optional token; the messages never quote
|
||||
// the value.
|
||||
func validateMLServiceToken(token string) error {
|
||||
const location = "SemanticSettings.Validate"
|
||||
if token == "" {
|
||||
return nil
|
||||
}
|
||||
if len(token) < minMLServiceTokenLength || len(token) > maxMLServiceTokenLength {
|
||||
return errors.New(location + " - ML_SERVICE_TOKEN must have between 32 and 512 characters")
|
||||
}
|
||||
for _, character := range token {
|
||||
if character < 0x21 || character > 0x7e {
|
||||
return errors.New(location + " - ML_SERVICE_TOKEN must be printable ASCII without white space")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (settings SemanticSettings) validateLimits() error {
|
||||
const location = "SemanticSettings.Validate"
|
||||
switch {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -19,14 +20,24 @@ func TestSemanticSettingsDefaultOffAndValidateTheMLOrigin(t *testing.T) {
|
||||
settings.MLRequestTimeout != 30*time.Second || settings.RepositoryCheckInterval != 10*time.Minute {
|
||||
t.Fatalf("defaults = %+v, %v", settings, err)
|
||||
}
|
||||
const mlToken = "ml-service-token-0123456789abcdefghij"
|
||||
enabled, err := LoadSemanticSettings(lookupOf(map[string]string{
|
||||
"SEMANTIC_MATCHING_ENABLED": "true", "ML_SERVICE_URL": "http://ml:8000", "GITHUB_TOKEN": "token-value",
|
||||
"SEMANTIC_MATCHING_ENABLED": "true", "ML_SERVICE_URL": "http://192.168.10.25:8790", "ML_SERVICE_TOKEN": mlToken,
|
||||
"GITHUB_TOKEN": "token-value",
|
||||
}))
|
||||
if err != nil || !enabled.SemanticMatchingEnabled || enabled.GitHubToken != "token-value" {
|
||||
t.Fatalf("enabled = %+v, %v", enabled, err)
|
||||
if err != nil || !enabled.SemanticMatchingEnabled || enabled.GitHubToken != "token-value" || enabled.MLServiceToken != mlToken {
|
||||
t.Fatalf("enabled = %v, %v", enabled.SemanticMatchingEnabled, err)
|
||||
}
|
||||
for _, rendered := range []string{fmt.Sprintf("%v %+v %#v %s", enabled, enabled, enabled, enabled), enabled.LogValue().String()} {
|
||||
if strings.Contains(rendered, mlToken) || strings.Contains(rendered, "token-value") {
|
||||
t.Fatalf("formatted settings quote a token: %s", rendered)
|
||||
}
|
||||
}
|
||||
for name, values := range map[string]map[string]string{
|
||||
"missing URL": {"SEMANTIC_MATCHING_ENABLED": "true"},
|
||||
"missing URL": {"SEMANTIC_MATCHING_ENABLED": "true", "ML_SERVICE_TOKEN": "ml-service-token-0123456789abcdefghij"},
|
||||
"missing token": {"SEMANTIC_MATCHING_ENABLED": "true", "ML_SERVICE_URL": "http://ml:8000"},
|
||||
"short token": {"ML_SERVICE_TOKEN": "secret-but-short"},
|
||||
"spaced token": {"ML_SERVICE_TOKEN": "secret 0123456789abcdefghijklmnopqrstuvwxyz"},
|
||||
"credentials": {"ML_SERVICE_URL": "http://user:secret@ml:8000"},
|
||||
"path": {"ML_SERVICE_URL": "http://ml:8000/v1"},
|
||||
"scheme": {"ML_SERVICE_URL": "file:///tmp/ml"},
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"lincodex/backend/internal/domain"
|
||||
"lincodex/backend/internal/port/inbound"
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
"lincodex/backend/internal/usecase/policy"
|
||||
"lincodex/backend/internal/usecase/semantic"
|
||||
"lincodex/backend/internal/worker/jobrunner"
|
||||
"lincodex/backend/internal/worker/retry"
|
||||
@@ -36,16 +37,32 @@ const (
|
||||
// never reach an organization.
|
||||
semanticRepository = "https://github.com/Private-Owner-Marker/payments-ledger"
|
||||
semanticRepositoryOwner = "Private-Owner-Marker"
|
||||
// semanticMLToken is the bearer token the fake ML service expects.
|
||||
semanticMLToken = "integration-ml-service-token-0123456789"
|
||||
)
|
||||
|
||||
// fakeMLService answers the ML embedding contract with a bag-of-topics
|
||||
// encoder: each topic word lights one dimension, so texts about the same
|
||||
// topic are close and others are not. It reports the policy model, so the
|
||||
// vectors pass the model check, and counts the texts it encoded.
|
||||
// topic are close and others are not. Like the real service it requires the
|
||||
// bearer token and serves the two ensemble models, reports the requested
|
||||
// model, so the vectors pass the model check, and counts the texts it
|
||||
// encoded per model.
|
||||
type fakeMLService struct {
|
||||
mutex sync.Mutex
|
||||
texts int
|
||||
down bool
|
||||
mutex sync.Mutex
|
||||
texts int
|
||||
byModel map[string]int
|
||||
down bool
|
||||
}
|
||||
|
||||
var fakeMLModels = map[string]map[string]any{
|
||||
domain.GigaEmbeddingsModelID: {
|
||||
"id": domain.GigaEmbeddingsModelID, "revision": domain.GigaEmbeddingsModelRevision,
|
||||
"prompt_version": domain.GigaEmbeddingsPromptVersion,
|
||||
},
|
||||
domain.Qwen3EmbeddingModelID: {
|
||||
"id": domain.Qwen3EmbeddingModelID, "revision": domain.Qwen3EmbeddingModelRevision,
|
||||
"prompt_version": domain.Qwen3EmbeddingPromptVersion,
|
||||
},
|
||||
}
|
||||
|
||||
var fakeTopics = [][]string{
|
||||
@@ -80,6 +97,12 @@ func (service *fakeMLService) ServeHTTP(writer http.ResponseWriter, request *htt
|
||||
service.mutex.Lock()
|
||||
down := service.down
|
||||
service.mutex.Unlock()
|
||||
if request.Header.Get("Authorization") != "Bearer "+semanticMLToken {
|
||||
writer.Header().Set("Content-Type", "application/problem+json")
|
||||
writer.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = writer.Write([]byte(`{"type":"urn:lincodex:problem:unauthenticated","title":"Authentication required","status":401,"code":"unauthenticated"}`))
|
||||
return
|
||||
}
|
||||
if down {
|
||||
writer.Header().Set("Content-Type", "application/problem+json")
|
||||
writer.WriteHeader(http.StatusServiceUnavailable)
|
||||
@@ -91,28 +114,36 @@ func (service *fakeMLService) ServeHTTP(writer http.ResponseWriter, request *htt
|
||||
Kind string `json:"kind"`
|
||||
Texts []string `json:"texts"`
|
||||
}
|
||||
// The service serves one model; a request for another one is refused
|
||||
// as the real service refuses it.
|
||||
// A model the service does not serve is refused as the real service
|
||||
// refuses it.
|
||||
if request.URL.Path != "/v1/embeddings" || json.NewDecoder(request.Body).Decode(&body) != nil ||
|
||||
body.Model != domain.GigaEmbeddingsModelID {
|
||||
fakeMLModels[body.Model] == nil {
|
||||
writer.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
service.mutex.Lock()
|
||||
service.texts += len(body.Texts)
|
||||
if service.byModel == nil {
|
||||
service.byModel = map[string]int{}
|
||||
}
|
||||
service.byModel[body.Model] += len(body.Texts)
|
||||
service.mutex.Unlock()
|
||||
vectors := make([][]float32, 0, len(body.Texts))
|
||||
for _, text := range body.Texts {
|
||||
vectors = append(vectors, fakeTopicVector(text))
|
||||
}
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(writer).Encode(map[string]any{
|
||||
"model": map[string]any{
|
||||
"id": domain.GigaEmbeddingsModelID, "revision": domain.GigaEmbeddingsModelRevision,
|
||||
"dimension": len(fakeTopics) + 1, "max_tokens": 1024, "prompt_version": domain.GigaEmbeddingsPromptVersion,
|
||||
},
|
||||
"kind": body.Kind, "vectors": vectors,
|
||||
})
|
||||
model := map[string]any{"dimension": len(fakeTopics) + 1, "max_tokens": 1024}
|
||||
for key, value := range fakeMLModels[body.Model] {
|
||||
model[key] = value
|
||||
}
|
||||
_ = json.NewEncoder(writer).Encode(map[string]any{"model": model, "kind": body.Kind, "vectors": vectors})
|
||||
}
|
||||
|
||||
func (service *fakeMLService) encodedTextsOf(model string) int {
|
||||
service.mutex.Lock()
|
||||
defer service.mutex.Unlock()
|
||||
return service.byModel[model]
|
||||
}
|
||||
|
||||
func (service *fakeMLService) encodedTexts() int {
|
||||
@@ -191,7 +222,7 @@ func TestSemanticMatchingOverHTTP(t *testing.T) {
|
||||
mlServer := httptest.NewServer(ml)
|
||||
defer mlServer.Close()
|
||||
embedder, err := mladapter.NewEmbedder(mladapter.Settings{
|
||||
BaseURL: mlServer.URL, Timeout: 5 * time.Second, FailureThreshold: 100, OpenDuration: time.Second,
|
||||
BaseURL: mlServer.URL, Token: semanticMLToken, Timeout: 5 * time.Second, FailureThreshold: 100, OpenDuration: time.Second,
|
||||
}, time.Now)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmbedder() error = %v", err)
|
||||
@@ -475,4 +506,61 @@ func TestSemanticMatchingOverHTTP(t *testing.T) {
|
||||
t.Fatalf("refresh without repositories = %d %s, want 202 with nothing", status, body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("the ensemble policy and a backfill add the Qwen3 views and the search fuses both models", func(t *testing.T) {
|
||||
// The payments candidate publishes the project again, so one card is
|
||||
// close to the need under both models. The publication job falls due
|
||||
// on the stand clock, ahead of the worker, so a backfill under the
|
||||
// single-model policy brings the Giga vectors up to date first.
|
||||
publishFields(paymentsCandidate, 2, `["projects","self_assessment","stack"]`)
|
||||
backfill, err := semantic.NewBackfill(transactor, time.Now)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBackfill() error = %v", err)
|
||||
}
|
||||
if err := backfill.Run(ctx, semantic.BackfillCandidates, "it-republish", uuid.Nil, nil); err != nil {
|
||||
t.Fatalf("Backfill.Run(republish) error = %v", err)
|
||||
}
|
||||
drain()
|
||||
gigaBefore := ml.encodedTextsOf(domain.GigaEmbeddingsModelID)
|
||||
publisher := policy.NewPublisher(postgresadapter.NewPolicyStore(harness.pool).Policies(), time.Now)
|
||||
published, err := publisher.EnsureDemoSemanticEnsembleSection(ctx, "operator:integration")
|
||||
if err != nil || !published.Created {
|
||||
t.Fatalf("EnsureDemoSemanticEnsembleSection() = %+v, %v", published, err)
|
||||
}
|
||||
// Until the need has a Qwen3 view, Sem is unknown for every entry.
|
||||
before, _ := search()
|
||||
for _, entry := range before.Groups.Unconfirmed {
|
||||
if !slices.Contains(entry.flags(), "semantics:ml_unavailable") {
|
||||
t.Fatalf("flags = %v before the backfill, want the ML flag", entry.flags())
|
||||
}
|
||||
}
|
||||
for _, scope := range []semantic.BackfillScope{semantic.BackfillCandidates, semantic.BackfillNeeds} {
|
||||
if err := backfill.Run(ctx, scope, "it-ensemble", uuid.Nil, nil); err != nil {
|
||||
t.Fatalf("Backfill.Run(%s) error = %v", scope, err)
|
||||
}
|
||||
}
|
||||
drain()
|
||||
if after := ml.encodedTextsOf(domain.GigaEmbeddingsModelID); after != gigaBefore {
|
||||
t.Fatalf("the backfill encoded %d Giga texts, want none: the Giga views did not change", after-gigaBefore)
|
||||
}
|
||||
if got := countRows(`SELECT count(*) FROM semantic_vectors WHERE model_id = $1 AND item_key = 'whole'`, domain.Qwen3EmbeddingModelID); got != 6+1 {
|
||||
t.Fatalf("Qwen3 whole views = %d, want one per published candidate and the need", got)
|
||||
}
|
||||
if got := countRows(`SELECT count(*) FROM semantic_vectors WHERE model_id = $1 AND item_key <> 'whole'`, domain.Qwen3EmbeddingModelID); got != 0 {
|
||||
t.Fatalf("Qwen3 item vectors = %d, want none: only Giga explains entries", got)
|
||||
}
|
||||
// Every candidate now has both whole views, so every entry has a
|
||||
// known Sem, and the fused score puts the related card first.
|
||||
result, _ := search()
|
||||
entries := result.Groups.Unconfirmed
|
||||
for _, entry := range entries {
|
||||
if slices.Contains(entry.flags(), "semantics:ml_unavailable") {
|
||||
t.Fatalf("flags = %v after the backfill, want a known Sem", entry.flags())
|
||||
}
|
||||
}
|
||||
if entries[0].CandidateHandle != paymentsHandle || entries[0].component("fit") <= entries[len(entries)-1].component("fit") {
|
||||
t.Fatalf("first entry %s with fit %v, last fit %v: the fused Sem did not put the related card first",
|
||||
entries[0].CandidateHandle, entries[0].component("fit"), entries[len(entries)-1].component("fit"))
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
// Package policypublish implements the local operator command that adds the
|
||||
// demo matching section, or the semantic matching section, to the product
|
||||
// policy. Until an administrative policy
|
||||
// demo matching section, the semantic matching section, or the two-model
|
||||
// semantic ensemble 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
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
"lincodex/backend/internal/usecase/policy"
|
||||
)
|
||||
|
||||
const usage = "usage: policy-publish matching|semantic --actor operator:<handle>"
|
||||
const usage = "usage: policy-publish matching|semantic|semantic-ensemble --actor operator:<handle>"
|
||||
|
||||
// Track names which section a command publishes.
|
||||
type Track string
|
||||
@@ -32,6 +32,10 @@ const (
|
||||
// TrackSemantic adds the semantic matching section (Sem weight 0.5, the
|
||||
// encoder identity, the calibration, and the explanation thresholds).
|
||||
TrackSemantic Track = "semantic"
|
||||
// TrackSemanticEnsemble replaces the semantic section with the two-model
|
||||
// ensemble (Giga and Qwen3-Embedding) and its calibration; the earlier
|
||||
// single-model version stays as the previous version.
|
||||
TrackSemanticEnsemble Track = "semantic-ensemble"
|
||||
)
|
||||
|
||||
// Command is a parsed, validated request.
|
||||
@@ -44,11 +48,12 @@ type Command struct {
|
||||
type Extender interface {
|
||||
EnsureDemoMatchingSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error)
|
||||
EnsureDemoSemanticMatchingSection(ctx context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error)
|
||||
EnsureDemoSemanticEnsembleSection(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] != string(TrackMatching) && args[0] != string(TrackSemantic)) {
|
||||
if len(args) == 0 || (args[0] != string(TrackMatching) && args[0] != string(TrackSemantic) && args[0] != string(TrackSemanticEnsemble)) {
|
||||
return Command{}, errors.New(usage)
|
||||
}
|
||||
track := Track(args[0])
|
||||
@@ -98,10 +103,16 @@ func Execute(ctx context.Context, command Command, extender Extender, output io.
|
||||
}
|
||||
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 {
|
||||
switch command.Track {
|
||||
case 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"
|
||||
case TrackSemanticEnsemble:
|
||||
publish, section, note = extender.EnsureDemoSemanticEnsembleSection, "the semantic ensemble section (Giga + Qwen3-Embedding)",
|
||||
"note: research-calibrated values (LincodexMatch DEV split), not product measurements; the ML service must serve both models,\n"+
|
||||
"and Sem stays neutral for subjects without Qwen3 vectors until the semantic-backfill command has run\n"
|
||||
case TrackMatching:
|
||||
}
|
||||
result, err := publish(ctx, command.Author)
|
||||
if err != nil {
|
||||
|
||||
@@ -17,6 +17,7 @@ type extenderFake struct {
|
||||
err error
|
||||
author domain.PolicyAuthor
|
||||
semantic bool
|
||||
ensemble bool
|
||||
}
|
||||
|
||||
func (extender *extenderFake) EnsureDemoMatchingSection(_ context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) {
|
||||
@@ -30,6 +31,12 @@ func (extender *extenderFake) EnsureDemoSemanticMatchingSection(_ context.Contex
|
||||
return extender.result, extender.err
|
||||
}
|
||||
|
||||
func (extender *extenderFake) EnsureDemoSemanticEnsembleSection(_ context.Context, author domain.PolicyAuthor) (policy.MatchingResult, error) {
|
||||
extender.author = author
|
||||
extender.ensemble = 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" || command.Track != TrackMatching {
|
||||
@@ -39,6 +46,10 @@ func TestParseRequiresTheMatchingTrackAndAnOperatorHandle(t *testing.T) {
|
||||
if err != nil || semantic.Track != TrackSemantic {
|
||||
t.Fatalf("Parse(semantic) = %+v, %v", semantic, err)
|
||||
}
|
||||
ensemble, err := Parse([]string{"semantic-ensemble", "--actor", "operator:night"})
|
||||
if err != nil || ensemble.Track != TrackSemanticEnsemble {
|
||||
t.Fatalf("Parse(semantic-ensemble) = %+v, %v", ensemble, err)
|
||||
}
|
||||
for _, args := range [][]string{
|
||||
nil, {"list"}, {"matching"}, {"matching", "--actor", "alice"}, {"matching", "--actor", "system:demo-seed"},
|
||||
{"matching", "--actor", "operator:night", "extra"},
|
||||
@@ -84,3 +95,14 @@ func TestExecuteSemanticTrackPublishesTheSemanticSection(t *testing.T) {
|
||||
t.Fatalf("output = %q, semantic called %v", output.String(), extender.semantic)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteSemanticEnsembleTrackPublishesTheEnsembleSection(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
extender := &extenderFake{}
|
||||
if err := Execute(context.Background(), Command{Track: TrackSemanticEnsemble, Author: "operator:night"}, extender, &output); err != nil {
|
||||
t.Fatalf("Execute() error = %v", err)
|
||||
}
|
||||
if !extender.ensemble || extender.semantic || !strings.Contains(output.String(), "semantic ensemble section") {
|
||||
t.Fatalf("output = %q, ensemble called %v", output.String(), extender.ensemble)
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
ht "github.com/ogen-go/ogen/http"
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/ogen-go/ogen/otelogen"
|
||||
"github.com/ogen-go/ogen/uri"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
@@ -29,13 +30,16 @@ func trimTrailingSlashes(u *url.URL) {
|
||||
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.
|
||||
// Internal operation for the Go backend; it is not reachable from browsers and needs the service
|
||||
// bearer token. 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
|
||||
// The service may load several pinned models, for example the members of an ensemble; `model` selects
|
||||
// one, and the response names the model, revision, dimension, and prompt version that produced the
|
||||
// vectors. The service answers 503 service_unavailable until every configured model is loaded and a
|
||||
// warm-up encode has finished, and when the device runs out of memory for a request; `/readyz` reports
|
||||
// the same state. A request without a valid token answers 401, 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
|
||||
@@ -57,11 +61,12 @@ type Invoker interface {
|
||||
// Client implements OAS client.
|
||||
type Client struct {
|
||||
serverURL *url.URL
|
||||
sec SecuritySource
|
||||
baseClient
|
||||
}
|
||||
|
||||
// NewClient initializes new Client defined by OAS.
|
||||
func NewClient(serverURL string, opts ...ClientOption) (*Client, error) {
|
||||
func NewClient(serverURL string, sec SecuritySource, opts ...ClientOption) (*Client, error) {
|
||||
u, err := url.Parse(serverURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -74,6 +79,7 @@ func NewClient(serverURL string, opts ...ClientOption) (*Client, error) {
|
||||
}
|
||||
return &Client{
|
||||
serverURL: u,
|
||||
sec: sec,
|
||||
baseClient: c,
|
||||
}, nil
|
||||
}
|
||||
@@ -95,13 +101,16 @@ func (c *Client) requestURL(ctx context.Context) *url.URL {
|
||||
|
||||
// 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.
|
||||
// Internal operation for the Go backend; it is not reachable from browsers and needs the service
|
||||
// bearer token. 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
|
||||
// The service may load several pinned models, for example the members of an ensemble; `model` selects
|
||||
// one, and the response names the model, revision, dimension, and prompt version that produced the
|
||||
// vectors. The service answers 503 service_unavailable until every configured model is loaded and a
|
||||
// warm-up encode has finished, and when the device runs out of memory for a request; `/readyz` reports
|
||||
// the same state. A request without a valid token answers 401, 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
|
||||
@@ -160,6 +169,39 @@ func (c *Client) sendCreateMLEmbeddings(ctx context.Context, request *EmbeddingR
|
||||
return res, errors.Wrap(err, "encode request")
|
||||
}
|
||||
|
||||
{
|
||||
type bitset = [1]uint8
|
||||
var satisfied bitset
|
||||
{
|
||||
stage = "Security:BearerAuth"
|
||||
switch err := c.securityBearerAuth(ctx, CreateMLEmbeddingsOperation, r); {
|
||||
case err == nil: // if NO error
|
||||
satisfied[0] |= 1 << 0
|
||||
case errors.Is(err, ogenerrors.ErrSkipClientSecurity):
|
||||
// Skip this security.
|
||||
default:
|
||||
return res, errors.Wrap(err, "security \"BearerAuth\"")
|
||||
}
|
||||
}
|
||||
|
||||
if ok := func() bool {
|
||||
nextRequirement:
|
||||
for _, requirement := range []bitset{
|
||||
{0b00000001},
|
||||
} {
|
||||
for i, mask := range requirement {
|
||||
if satisfied[i]&mask != mask {
|
||||
continue nextRequirement
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}(); !ok {
|
||||
return res, ogenerrors.ErrSecurityRequirementIsNotSatisfied
|
||||
}
|
||||
}
|
||||
|
||||
stage = "SendRequest"
|
||||
resp, err := c.cfg.Client.Do(r)
|
||||
if err != nil {
|
||||
|
||||
@@ -106,6 +106,53 @@ func decodeCreateMLEmbeddingsResponse(resp *http.Response) (res CreateMLEmbeddin
|
||||
default:
|
||||
return res, validate.InvalidContentType(ct)
|
||||
}
|
||||
case 401:
|
||||
// Code 401.
|
||||
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 &CreateMLEmbeddingsUnauthorized{
|
||||
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"))
|
||||
|
||||
@@ -12,6 +12,31 @@ func (s *ProblemStatusCode) Error() string {
|
||||
return fmt.Sprintf("code %d: %+v", s.StatusCode, s.Response)
|
||||
}
|
||||
|
||||
type BearerAuth struct {
|
||||
Token string
|
||||
Roles []string
|
||||
}
|
||||
|
||||
// GetToken returns the value of Token.
|
||||
func (s *BearerAuth) GetToken() string {
|
||||
return s.Token
|
||||
}
|
||||
|
||||
// GetRoles returns the value of Roles.
|
||||
func (s *BearerAuth) GetRoles() []string {
|
||||
return s.Roles
|
||||
}
|
||||
|
||||
// SetToken sets the value of Token.
|
||||
func (s *BearerAuth) SetToken(val string) {
|
||||
s.Token = val
|
||||
}
|
||||
|
||||
// SetRoles sets the value of Roles.
|
||||
func (s *BearerAuth) SetRoles(val []string) {
|
||||
s.Roles = val
|
||||
}
|
||||
|
||||
type CreateMLEmbeddingsBadRequest ProblemStatusCode
|
||||
|
||||
func (*CreateMLEmbeddingsBadRequest) createMLEmbeddingsRes() {}
|
||||
@@ -24,6 +49,10 @@ type CreateMLEmbeddingsServiceUnavailable ProblemStatusCode
|
||||
|
||||
func (*CreateMLEmbeddingsServiceUnavailable) createMLEmbeddingsRes() {}
|
||||
|
||||
type CreateMLEmbeddingsUnauthorized ProblemStatusCode
|
||||
|
||||
func (*CreateMLEmbeddingsUnauthorized) 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.
|
||||
//
|
||||
@@ -143,13 +172,14 @@ func (s *EmbeddingModel) SetPromptVersion(val string) {
|
||||
|
||||
// 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.
|
||||
// configured size, and returned in request order. The same texts in the same request on the same
|
||||
// installation, device, precision, 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`.
|
||||
// the service, the first one it is configured with. 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"`
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// Code generated by ogen, DO NOT EDIT.
|
||||
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-faster/errors"
|
||||
)
|
||||
|
||||
// SecuritySource is provider of security values (tokens, passwords, etc.).
|
||||
type SecuritySource interface {
|
||||
// BearerAuth provides bearerAuth security value.
|
||||
// Shared random service token sent as `Authorization: Bearer <token>`. The service compares it in
|
||||
// constant time and never logs it. Rotation replaces the secret on both sides; there are no per-user
|
||||
// tokens.
|
||||
BearerAuth(ctx context.Context, operationName OperationName) (BearerAuth, error)
|
||||
}
|
||||
|
||||
// operationRolesBearerAuth is a private map storing roles per operation.
|
||||
var operationRolesBearerAuth = map[string][]string{
|
||||
CreateMLEmbeddingsOperation: []string{},
|
||||
}
|
||||
|
||||
// GetRolesForBearerAuth returns the required roles for the given operation.
|
||||
//
|
||||
// This is useful for authorization scenarios where you need to know which roles
|
||||
// are required for an operation.
|
||||
//
|
||||
// Example:
|
||||
//
|
||||
// requiredRoles := GetRolesForBearerAuth(AddPetOperation)
|
||||
//
|
||||
// Returns nil if the operation has no role requirements or if the operation is unknown.
|
||||
func GetRolesForBearerAuth(operation string) []string {
|
||||
roles, ok := operationRolesBearerAuth[operation]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
// Return a copy to prevent external modification
|
||||
result := make([]string, len(roles))
|
||||
copy(result, roles)
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *Client) securityBearerAuth(ctx context.Context, operationName OperationName, req *http.Request) error {
|
||||
t, err := s.sec.BearerAuth(ctx, operationName)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "security source \"BearerAuth\"")
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+t.Token)
|
||||
return nil
|
||||
}
|
||||
@@ -33,6 +33,14 @@ func (s *CreateMLEmbeddingsServiceUnavailable) Validate() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *CreateMLEmbeddingsUnauthorized) Validate() error {
|
||||
alias := (*ProblemStatusCode)(s)
|
||||
if err := alias.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s EmbeddingInputKind) Validate() error {
|
||||
switch s {
|
||||
case "query":
|
||||
|
||||
@@ -32,6 +32,9 @@ const (
|
||||
type Settings struct {
|
||||
// BaseURL is the ML service origin, for example http://ml:8000.
|
||||
BaseURL string
|
||||
// Token is the shared bearer token of the ML service. It is a secret:
|
||||
// it travels only in the Authorization header and is never logged.
|
||||
Token string
|
||||
// Timeout bounds one HTTP request.
|
||||
Timeout time.Duration
|
||||
// FailureThreshold consecutive failures open the circuit for OpenDuration.
|
||||
@@ -57,13 +60,16 @@ func NewEmbedder(settings Settings, clock func() time.Time) (*Embedder, error) {
|
||||
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")
|
||||
}
|
||||
if settings.Token == "" {
|
||||
return nil, errors.New(location + " - the ML service token 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))
|
||||
client, err := api.NewClient(parsed.String(), staticToken{token: settings.Token}, api.WithClient(httpClient))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%s - create client: %w", location, err)
|
||||
}
|
||||
@@ -130,6 +136,12 @@ func (embedder *Embedder) embedBatch(
|
||||
case *api.CreateMLEmbeddingsServiceUnavailable:
|
||||
embedder.breaker.failure()
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("the ML service is not ready: %w", outbound.ErrEmbedderUnavailable)
|
||||
case *api.CreateMLEmbeddingsUnauthorized:
|
||||
// A wrong or missing token is a deployment mistake. The job retries
|
||||
// with backoff, so the vectors follow once the operator fixes the
|
||||
// token; the open circuit keeps the retries cheap meanwhile.
|
||||
embedder.breaker.failure()
|
||||
return domain.SemanticModel{}, nil, fmt.Errorf("the ML service refused the service token: %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.
|
||||
@@ -167,6 +179,15 @@ func cutRunes(text string, limit int) string {
|
||||
return string(runes[:limit])
|
||||
}
|
||||
|
||||
// staticToken supplies the configured bearer token to the generated client.
|
||||
type staticToken struct {
|
||||
token string
|
||||
}
|
||||
|
||||
func (source staticToken) BearerAuth(context.Context, api.OperationName) (api.BearerAuth, error) {
|
||||
return api.BearerAuth{Token: source.token}, nil
|
||||
}
|
||||
|
||||
// limitedTransport caps the bytes read from a response body.
|
||||
type limitedTransport struct {
|
||||
next http.RoundTripper
|
||||
|
||||
@@ -14,12 +14,17 @@ import (
|
||||
"lincodex/backend/internal/port/outbound"
|
||||
)
|
||||
|
||||
// testToken is a syntactically valid service token of the tests.
|
||||
const testToken = "test-ml-service-token-0123456789abcdef"
|
||||
|
||||
type fakeService struct {
|
||||
mutex sync.Mutex
|
||||
requests int
|
||||
batches []int
|
||||
models []string
|
||||
respond func(writer http.ResponseWriter, kind string, texts []string)
|
||||
// authorizations records the Authorization header of every request.
|
||||
authorizations []string
|
||||
respond func(writer http.ResponseWriter, kind string, texts []string)
|
||||
}
|
||||
|
||||
func (service *fakeService) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
|
||||
@@ -33,6 +38,7 @@ func (service *fakeService) ServeHTTP(writer http.ResponseWriter, request *http.
|
||||
service.requests++
|
||||
service.batches = append(service.batches, len(body.Texts))
|
||||
service.models = append(service.models, body.Model)
|
||||
service.authorizations = append(service.authorizations, request.Header.Get("Authorization"))
|
||||
service.mutex.Unlock()
|
||||
service.respond(writer, body.Kind, body.Texts)
|
||||
}
|
||||
@@ -53,7 +59,7 @@ func newTestEmbedder(t *testing.T, service *fakeService, clock func() time.Time)
|
||||
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)
|
||||
embedder, err := NewEmbedder(Settings{BaseURL: server.URL, Token: testToken, Timeout: time.Second, FailureThreshold: 2, OpenDuration: time.Minute}, clock)
|
||||
if err != nil {
|
||||
t.Fatalf("NewEmbedder() error = %v", err)
|
||||
}
|
||||
@@ -77,6 +83,25 @@ func TestEmbedSplitsBatchesAndChecksTheResponse(t *testing.T) {
|
||||
if strings.Join(service.models, ",") != "example/model,example/model" {
|
||||
t.Fatalf("requested models = %v, want the named model in every batch", service.models)
|
||||
}
|
||||
for _, header := range service.authorizations {
|
||||
if header != "Bearer "+testToken {
|
||||
t.Fatalf("Authorization = %q, want the bearer token on every request", header)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbedTreatsARefusedTokenAsUnavailableWithoutQuotingIt(t *testing.T) {
|
||||
service := &fakeService{respond: func(writer http.ResponseWriter, _ string, _ []string) {
|
||||
writer.Header().Set("Content-Type", "application/problem+json")
|
||||
writer.Header().Set("WWW-Authenticate", "Bearer")
|
||||
writer.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = writer.Write([]byte(`{"type":"urn:lincodex:problem:unauthenticated","title":"x","status":401,"code":"unauthenticated"}`))
|
||||
}}
|
||||
embedder := newTestEmbedder(t, service, time.Now)
|
||||
_, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingQuery, []string{"a"})
|
||||
if !errors.Is(err, outbound.ErrEmbedderUnavailable) || strings.Contains(err.Error(), testToken) {
|
||||
t.Fatalf("error = %v, want ErrEmbedderUnavailable without the token", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbedRejectsResponsesThatBreakTheContract(t *testing.T) {
|
||||
@@ -138,8 +163,11 @@ func TestEmbedNeverQuotesTextsInErrors(t *testing.T) {
|
||||
|
||||
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 {
|
||||
if _, err := NewEmbedder(Settings{BaseURL: raw, Token: testToken, Timeout: time.Second, FailureThreshold: 1, OpenDuration: time.Second}, time.Now); err == nil {
|
||||
t.Errorf("NewEmbedder(%q) accepted the URL", raw)
|
||||
}
|
||||
}
|
||||
if _, err := NewEmbedder(Settings{BaseURL: "http://ml:8000", Timeout: time.Second, FailureThreshold: 1, OpenDuration: time.Second}, time.Now); err == nil {
|
||||
t.Error("NewEmbedder() accepted a client without the service token")
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ func semanticJobHandlers(settings config.Config, logger *slog.Logger) ([]inbound
|
||||
trigger := newSemanticTrigger(settings)
|
||||
if settings.Semantic.SemanticMatchingEnabled {
|
||||
embedder, err := ml.NewEmbedder(ml.Settings{
|
||||
BaseURL: settings.Semantic.MLServiceURL, Timeout: settings.Semantic.MLRequestTimeout,
|
||||
BaseURL: settings.Semantic.MLServiceURL, Token: settings.Semantic.MLServiceToken, Timeout: settings.Semantic.MLRequestTimeout,
|
||||
FailureThreshold: settings.Semantic.MLCircuitFailures, OpenDuration: settings.Semantic.MLCircuitOpen,
|
||||
}, time.Now)
|
||||
if err != nil {
|
||||
|
||||
@@ -117,3 +117,15 @@ func DemoProductPolicyV5() ProductPolicy {
|
||||
policy.Matching = &matching
|
||||
return policy
|
||||
}
|
||||
|
||||
// DemoProductPolicyV6 returns DemoProductPolicyV5 with the two-model
|
||||
// semantic section (DemoSemanticEnsembleMatchingPolicy): Sem fuses Giga and
|
||||
// Qwen3-Embedding. V5 stays the previous version with Giga alone. It is
|
||||
// published explicitly with the policy-publish command; startup seeding
|
||||
// publishes V1 only.
|
||||
func DemoProductPolicyV6() ProductPolicy {
|
||||
policy := DemoProductPolicyV5()
|
||||
matching := DemoSemanticEnsembleMatchingPolicy()
|
||||
policy.Matching = &matching
|
||||
return policy
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package domain
|
||||
|
||||
// Qwen3-Embedding-0.6B at the pinned revision with the service prompt recipe
|
||||
// (the model's own query prompt, last-token pooling); the ML service reports
|
||||
// the same identity.
|
||||
const (
|
||||
Qwen3EmbeddingModelID = "Qwen/Qwen3-Embedding-0.6B"
|
||||
Qwen3EmbeddingModelRevision = "97b0c614be4d77ee51c0cef4e5f07c00f9eb65b3"
|
||||
Qwen3EmbeddingPromptVersion = "qwen3-card-last-v1"
|
||||
)
|
||||
|
||||
// DemoMatchingSemanticsEnsemblePolicy returns the semantic section of the
|
||||
// two-model ensemble S5-DE of the LincodexMatch research: Sem is the
|
||||
// calibrated fused score 0.4 * z(Giga) + 0.6 * z(Qwen3-Embedding) of the
|
||||
// cosines of the need view and the card view.
|
||||
//
|
||||
// - Weights: the research step 5 choice, made by 5-fold CV over the DEV
|
||||
// needs on the research views (w_giga = 0.4 in four folds of five).
|
||||
// - Mean and standard deviation: the research profiles and needs rendered
|
||||
// with the product view builder (needs exactly as the research; a card
|
||||
// with the catalog roles and declared grades, the card stack codes, and
|
||||
// one published project per research experience entry), encoded by the
|
||||
// ML service in float16 on CUDA. The mean is over all DEV need-profile
|
||||
// pairs; the deviation is the pooled within-need deviation, so the fixed
|
||||
// z-score reproduces the per-need z-score of the research (DEV nDCG@10
|
||||
// 0.809 / indirect 0.518 against 0.809 / 0.518; Giga alone 0.738 / 0.403).
|
||||
// - Calibration: the isotonic fit of P(consensus >= 2) on the fused score
|
||||
// of the 3220 judged DEV pairs (994 positive), computed with the rounded
|
||||
// mean and deviation below; 5-fold grouped CV ECE 0.025.
|
||||
//
|
||||
// The explanation thresholds stay those of Giga, the first member, which
|
||||
// alone provides the item vectors. The values are a calibrated starting
|
||||
// point, not a product measurement: real cards carry fewer projects than the
|
||||
// research profiles carry experience entries.
|
||||
func DemoMatchingSemanticsEnsemblePolicy() MatchingSemanticsPolicy {
|
||||
policy := DemoMatchingSemanticsPolicy()
|
||||
policy.Members = []MatchingSemanticMember{
|
||||
{
|
||||
Model: SemanticModel{
|
||||
ID: GigaEmbeddingsModelID, Revision: GigaEmbeddingsModelRevision, PromptVersion: GigaEmbeddingsPromptVersion,
|
||||
},
|
||||
Weight: 4000, Mean: 2497, StandardDeviation: 741,
|
||||
},
|
||||
{
|
||||
Model: SemanticModel{
|
||||
ID: Qwen3EmbeddingModelID, Revision: Qwen3EmbeddingModelRevision, PromptVersion: Qwen3EmbeddingPromptVersion,
|
||||
},
|
||||
Weight: 6000, Mean: 3636, StandardDeviation: 731,
|
||||
},
|
||||
}
|
||||
policy.Calibration = demoEnsembleCalibration()
|
||||
policy.Source = "LincodexMatch DEV split 2026-10-11, product card views, giga+qwen3 float16; weights 0.4/0.6 S5-DE (reports/step5), mean/std and isotonic fit on 3220 judged pairs"
|
||||
return policy
|
||||
}
|
||||
|
||||
// DemoSemanticEnsembleMatchingPolicy returns DemoSemanticMatchingPolicy with
|
||||
// the ensemble semantic section; the Fit weights stay those of the single
|
||||
// model section.
|
||||
func DemoSemanticEnsembleMatchingPolicy() MatchingPolicy {
|
||||
policy := DemoSemanticMatchingPolicy()
|
||||
semantics := DemoMatchingSemanticsEnsemblePolicy()
|
||||
policy.Semantics = &semantics
|
||||
return policy
|
||||
}
|
||||
|
||||
// demoEnsembleCalibration is the isotonic fit of the fused score in basis
|
||||
// points (a fused score of 1.0 is 10000).
|
||||
func demoEnsembleCalibration() []MatchingCalibrationPoint {
|
||||
return []MatchingCalibrationPoint{
|
||||
{-22961, 0}, {610, 0}, {619, 101}, {3279, 101}, {3279, 263}, {5629, 263}, {5682, 267}, {7140, 267},
|
||||
{7155, 559}, {9628, 559}, {9636, 985}, {12855, 985}, {12869, 1379}, {14934, 1379}, {14954, 1690}, {16934, 1690},
|
||||
{16971, 1940}, {17749, 1940}, {17751, 2283}, {18641, 2283}, {18642, 2632}, {18955, 2632}, {18960, 2667}, {19764, 2667},
|
||||
{19767, 3105}, {21601, 3105}, {21614, 3436}, {23072, 3436}, {23075, 4062}, {23840, 4062}, {23843, 4286}, {23906, 4286},
|
||||
{23933, 4444}, {24162, 4444}, {24179, 5059}, {27070, 5059}, {27076, 5766}, {28697, 5766}, {28701, 6706}, {29902, 6706},
|
||||
{29916, 7059}, {30450, 7059}, {30460, 7500}, {33107, 7500}, {33109, 7692}, {33320, 7692}, {33354, 8182}, {33738, 8182},
|
||||
{33753, 8391}, {35898, 8391}, {35939, 9244}, {40768, 9244}, {40885, 9792}, {44357, 9792}, {44390, 10000}, {52584, 10000},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"math"
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEnsembleSemanticsPolicyIsValidAndKeepsTheGigaExplanation(t *testing.T) {
|
||||
ensemble := DemoMatchingSemanticsEnsemblePolicy()
|
||||
if err := ensemble.Validate(); err != nil {
|
||||
t.Fatalf("ensemble Validate() = %v", err)
|
||||
}
|
||||
single := DemoMatchingSemanticsPolicy()
|
||||
if ensemble.ExplanationModel() != single.ExplanationModel() || ensemble.ExplanationModel().ID != GigaEmbeddingsModelID {
|
||||
t.Fatalf("explanation model = %+v, want Giga", ensemble.ExplanationModel())
|
||||
}
|
||||
if ensemble.SkillMedium != single.SkillMedium || ensemble.SkillHigh != single.SkillHigh ||
|
||||
ensemble.TaskMedium != single.TaskMedium || ensemble.TaskHigh != single.TaskHigh {
|
||||
t.Fatal("the explanation thresholds must stay those of Giga")
|
||||
}
|
||||
if ensemble.Members[1].Model != (SemanticModel{ID: Qwen3EmbeddingModelID, Revision: Qwen3EmbeddingModelRevision, PromptVersion: Qwen3EmbeddingPromptVersion}) {
|
||||
t.Fatalf("second member = %+v, want the pinned Qwen3-Embedding", ensemble.Members[1].Model)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsembleSemanticsMapsTheFusedScoreMonotonically(t *testing.T) {
|
||||
ensemble := DemoMatchingSemanticsEnsemblePolicy()
|
||||
// At the member means every standardized cosine, and so the fused score, is 0.
|
||||
score, ok := ensemble.FusedScore([]float64{0.2497, 0.3636})
|
||||
if !ok || math.Abs(score) > 1e-12 {
|
||||
t.Fatalf("score at the means = %v, %v, want 0", score, ok)
|
||||
}
|
||||
if low, high := ensemble.Probability(-1), ensemble.Probability(10); low != 0 || high != 1_000_000 {
|
||||
t.Fatalf("clipped ends = %d and %d, want 0 and 1", low, high)
|
||||
}
|
||||
previous := int64(-1)
|
||||
for giga := 0.0; giga <= 0.8; giga += 0.02 {
|
||||
score, ok := ensemble.FusedScore([]float64{giga, giga + 0.1})
|
||||
if !ok {
|
||||
t.Fatal("the fused score needs both members")
|
||||
}
|
||||
value := ensemble.Probability(score)
|
||||
if value < previous {
|
||||
t.Fatalf("Sem decreased at cosine %v: %d after %d", giga, value, previous)
|
||||
}
|
||||
previous = value
|
||||
}
|
||||
}
|
||||
|
||||
func TestProductPolicyV6CarriesTheEnsembleAndRoundTrips(t *testing.T) {
|
||||
v6 := DemoProductPolicyV6()
|
||||
if err := v6.Validate(); err != nil {
|
||||
t.Fatalf("V6 Validate() = %v", err)
|
||||
}
|
||||
v5 := DemoProductPolicyV5()
|
||||
if v6.Matching.FitSemanticsWeight != v5.Matching.FitSemanticsWeight || len(v5.Matching.Semantics.Members) != 1 {
|
||||
t.Fatal("V6 must keep the Fit weights of V5, and V5 must stay the single-model version")
|
||||
}
|
||||
encoded, _, err := encodeProductPolicy(v6)
|
||||
if err != nil {
|
||||
t.Fatalf("encodeProductPolicy(V6) error = %v", err)
|
||||
}
|
||||
decoded, err := decodeProductPolicy(encoded)
|
||||
if err != nil {
|
||||
t.Fatalf("decodeProductPolicy(V6) error = %v", err)
|
||||
}
|
||||
if !slices.Equal(decoded.Matching.Semantics.Members, v6.Matching.Semantics.Members) ||
|
||||
!slices.Equal(decoded.Matching.Semantics.Calibration, v6.Matching.Semantics.Calibration) {
|
||||
t.Fatal("the ensemble section did not survive the document round trip")
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,34 @@ func (publisher *Publisher) EnsureDemoSemanticMatchingSection(ctx context.Contex
|
||||
domain.DemoSemanticMatchingPolicy)
|
||||
}
|
||||
|
||||
// EnsureDemoSemanticEnsembleSection makes the latest demonstration version
|
||||
// carry the two-model semantic section
|
||||
// (domain.DemoSemanticEnsembleMatchingPolicy). A version whose semantic
|
||||
// section already names exactly the ensemble models, in order, is left
|
||||
// alone. Otherwise it publishes the next version, a copy of the latest one
|
||||
// whose matching section is replaced, so the single-model section stays as
|
||||
// the previous version and a rollback needs no recomputed vectors.
|
||||
func (publisher *Publisher) EnsureDemoSemanticEnsembleSection(ctx context.Context, author domain.PolicyAuthor) (MatchingResult, error) {
|
||||
ensemble := domain.DemoMatchingSemanticsEnsemblePolicy()
|
||||
return publisher.ensureMatching(ctx, author, "Publisher.EnsureDemoSemanticEnsembleSection",
|
||||
func(current *domain.MatchingPolicy) bool {
|
||||
return current != nil && current.Semantics != nil && sameMemberModels(current.Semantics.Members, ensemble.Members)
|
||||
},
|
||||
domain.DemoSemanticEnsembleMatchingPolicy)
|
||||
}
|
||||
|
||||
func sameMemberModels(left, right []domain.MatchingSemanticMember) bool {
|
||||
if len(left) != len(right) {
|
||||
return false
|
||||
}
|
||||
for index := range left {
|
||||
if left[index].Model != right[index].Model {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (publisher *Publisher) ensureMatching(
|
||||
ctx context.Context,
|
||||
author domain.PolicyAuthor,
|
||||
|
||||
@@ -81,3 +81,34 @@ func TestEnsureDemoMatchingSectionDoesNotRetryAfterAConcurrentPublication(t *tes
|
||||
t.Fatalf("versions = %d, want only the concurrent publication stored and no built-on-stale version", len(store.versions))
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureDemoSemanticEnsembleSectionKeepsTheSingleModelVersionBeforeIt(t *testing.T) {
|
||||
store := &memoryPolicies{}
|
||||
seedVersion(t, store, domain.PolicyKindDemo, domain.DemoProductPolicyV5())
|
||||
publisher := NewPublisher(store, testClock)
|
||||
|
||||
result, err := publisher.EnsureDemoSemanticEnsembleSection(context.Background(), "operator:night")
|
||||
if err != nil || !result.Created || result.Version.Version() != 2 {
|
||||
t.Fatalf("EnsureDemoSemanticEnsembleSection() = %+v, %v, want version 2 created", result, err)
|
||||
}
|
||||
semantics := result.Version.Policy().Matching.Semantics
|
||||
if semantics == nil || len(semantics.Members) != 2 ||
|
||||
semantics.Members[0].Model.ID != domain.GigaEmbeddingsModelID || semantics.Members[1].Model.ID != domain.Qwen3EmbeddingModelID {
|
||||
t.Fatalf("semantic members = %+v, want Giga first and Qwen3 second", semantics)
|
||||
}
|
||||
if previous := store.versions[0].Policy().Matching.Semantics; len(previous.Members) != 1 {
|
||||
t.Fatalf("previous version members = %d, want the single-model version kept", len(previous.Members))
|
||||
}
|
||||
if result.Version.Policy().Assessment.Signals == nil || result.Version.Policy().Support == nil {
|
||||
t.Fatal("the ensemble version dropped an earlier section")
|
||||
}
|
||||
|
||||
again, err := publisher.EnsureDemoSemanticEnsembleSection(context.Background(), "operator:night")
|
||||
if err != nil || again.Created || len(store.versions) != 2 {
|
||||
t.Fatalf("second call = %+v, %v with %d versions, want no new version", again, err, len(store.versions))
|
||||
}
|
||||
single, err := publisher.EnsureDemoSemanticMatchingSection(context.Background(), "operator:night")
|
||||
if err != nil || single.Created {
|
||||
t.Fatalf("the single-model command after the ensemble = %+v, %v, want it to leave the ensemble alone", single, err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user