feat(ml): fuse two embedding models and protect the ML service with a token

This commit is contained in:
shira committed 2026-10-11 14:40:52 +03:00
1 parent bc00d6901f
commit b24e5ff906
63 files changed
+2287 -276

No files matched your search

@@ -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")
}
}