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
@@ -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"))
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user