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")
}
}
+1 -1
View File
@@ -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 {
+12
View File
@@ -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)
}
}