package ml import ( "context" "encoding/json" "errors" "net/http" "net/http/httptest" "strings" "sync" "testing" "time" "lincodex/backend/internal/port/outbound" ) type fakeService struct { mutex sync.Mutex requests int batches []int models []string respond func(writer http.ResponseWriter, kind string, texts []string) } func (service *fakeService) ServeHTTP(writer http.ResponseWriter, request *http.Request) { var body struct { Model string `json:"model"` Kind string `json:"kind"` Texts []string `json:"texts"` } _ = json.NewDecoder(request.Body).Decode(&body) service.mutex.Lock() service.requests++ service.batches = append(service.batches, len(body.Texts)) service.models = append(service.models, body.Model) service.mutex.Unlock() service.respond(writer, body.Kind, body.Texts) } func validResponse(writer http.ResponseWriter, kind string, texts []string) { vectors := make([][]float32, 0, len(texts)) for range texts { vectors = append(vectors, []float32{0.6, 0.8}) } writer.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(writer).Encode(map[string]any{ "model": map[string]any{"id": "example/model", "revision": "abc", "dimension": 2, "max_tokens": 1024, "prompt_version": "v1"}, "kind": kind, "vectors": vectors, }) } func newTestEmbedder(t *testing.T, service *fakeService, clock func() time.Time) *Embedder { t.Helper() server := httptest.NewServer(service) t.Cleanup(server.Close) embedder, err := NewEmbedder(Settings{BaseURL: server.URL, Timeout: time.Second, FailureThreshold: 2, OpenDuration: time.Minute}, clock) if err != nil { t.Fatalf("NewEmbedder() error = %v", err) } return embedder } func TestEmbedSplitsBatchesAndChecksTheResponse(t *testing.T) { service := &fakeService{respond: validResponse} embedder := newTestEmbedder(t, service, time.Now) texts := make([]string, 40) for index := range texts { texts[index] = "text" } model, vectors, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingDocument, texts) if err != nil || len(vectors) != 40 || model.ID != "example/model" || model.PromptVersion != "v1" { t.Fatalf("Embed() = %+v, %d vectors, %v", model, len(vectors), err) } if len(service.batches) != 2 || service.batches[0] != outbound.MaxEmbeddingBatch || service.batches[1] != 8 { t.Fatalf("batches = %v, want 32 and 8", service.batches) } if strings.Join(service.models, ",") != "example/model,example/model" { t.Fatalf("requested models = %v, want the named model in every batch", service.models) } } func TestEmbedRejectsResponsesThatBreakTheContract(t *testing.T) { for name, respond := range map[string]func(http.ResponseWriter, string, []string){ "too few vectors": func(writer http.ResponseWriter, kind string, texts []string) { validResponse(writer, kind, texts[:1]) }, "not normalized": func(writer http.ResponseWriter, kind string, _ []string) { writer.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(writer).Encode(map[string]any{ "model": map[string]any{"id": "m/x", "revision": "r", "dimension": 2, "max_tokens": 1, "prompt_version": "v"}, "kind": kind, "vectors": [][]float32{{1, 1}, {1, 1}}, }) }, "bad request": func(writer http.ResponseWriter, _ string, _ []string) { writer.Header().Set("Content-Type", "application/problem+json") writer.WriteHeader(http.StatusBadRequest) _, _ = writer.Write([]byte(`{"type":"urn:lincodex:problem:validation_failed","title":"x","status":400,"code":"validation_failed"}`)) }, } { embedder := newTestEmbedder(t, &fakeService{respond: respond}, time.Now) if _, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingQuery, []string{"a", "b"}); !errors.Is(err, outbound.ErrEmbedderRejected) { t.Errorf("%s: error = %v, want ErrEmbedderRejected", name, err) } } } func TestEmbedOpensTheCircuitAfterRepeatedFailures(t *testing.T) { now := time.Date(2026, 10, 11, 12, 0, 0, 0, time.UTC) clock := func() time.Time { return now } service := &fakeService{respond: func(writer http.ResponseWriter, _ string, _ []string) { writer.Header().Set("Content-Type", "application/problem+json") writer.WriteHeader(http.StatusServiceUnavailable) _, _ = writer.Write([]byte(`{"type":"urn:lincodex:problem:service_unavailable","title":"x","status":503,"code":"service_unavailable"}`)) }} embedder := newTestEmbedder(t, service, clock) for range 3 { if _, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingQuery, []string{"a"}); !errors.Is(err, outbound.ErrEmbedderUnavailable) { t.Fatalf("error = %v, want ErrEmbedderUnavailable", err) } } if service.requests != 2 { t.Fatalf("requests = %d, want the circuit to stop calling after 2 failures", service.requests) } now = now.Add(2 * time.Minute) service.respond = validResponse if _, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingQuery, []string{"a"}); err != nil { t.Fatalf("probe after the open duration error = %v", err) } } func TestEmbedNeverQuotesTextsInErrors(t *testing.T) { embedder := newTestEmbedder(t, &fakeService{respond: func(writer http.ResponseWriter, _ string, _ []string) { writer.WriteHeader(http.StatusInternalServerError) }}, time.Now) _, _, err := embedder.Embed(context.Background(), "example/model", outbound.EmbeddingDocument, []string{"Jane Doe private summary"}) if err == nil || strings.Contains(err.Error(), "Jane") { t.Fatalf("error = %v, want a failure without the text", err) } } func TestNewEmbedderRejectsUnsafeURLs(t *testing.T) { for _, raw := range []string{"", "ftp://ml:8000", "http://user:secret@ml:8000", "ml:8000"} { if _, err := NewEmbedder(Settings{BaseURL: raw, Timeout: time.Second, FailureThreshold: 1, OpenDuration: time.Second}, time.Now); err == nil { t.Errorf("NewEmbedder(%q) accepted the URL", raw) } } }