Add the pinned Laya HTTP ranker and production composition, configure the CPU Compose service and cache, and document operations. Cover protocol validation, generation orchestration, sanitized logging, and Compose wiring. Refs #17 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
166 lines
6.4 KiB
Go
166 lines
6.4 KiB
Go
package ai
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"reflect"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/tradarr/backend/internal/generation"
|
|
"github.com/tradarr/backend/internal/models"
|
|
)
|
|
|
|
// These tests describe the expected v0.5.2 HTTP adapter contract. They are
|
|
// intentionally test-first: the adapter/configuration do not exist yet.
|
|
func TestLayaHTTPRankerUsesTaggedBatchWireShapeAndPreservesOrder(t *testing.T) {
|
|
calls := 0
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
calls++
|
|
if r.Method != http.MethodPost || r.URL.Path != "/v1/systemone/batch" {
|
|
t.Errorf("request = %s %s", r.Method, r.URL.Path)
|
|
}
|
|
var body struct {
|
|
States []map[string]any `json:"states"`
|
|
Model string `json:"model"`
|
|
Questions map[string]struct {
|
|
Type string `json:"type"`
|
|
Criteria []string `json:"criteria"`
|
|
Instructions string `json:"instructions"`
|
|
} `json:"questions"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
|
t.Errorf("decode request: %v", err)
|
|
w.WriteHeader(http.StatusBadRequest)
|
|
return
|
|
}
|
|
if body.Model != "multilingual" || len(body.States) != 2 {
|
|
t.Errorf("model=%q states=%d; want multilingual and 2 states", body.Model, len(body.States))
|
|
}
|
|
q, ok := body.Questions["relevance"]
|
|
if !ok || q.Type != "score" || len(q.Criteria) == 0 || q.Instructions == "" {
|
|
t.Errorf("relevance question missing or not score: %+v", q)
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
fmt.Fprint(w, `{"results":[{"answers":{"relevance":{"type":"score","score":0.9,"answer_confidence":0.91,"abstention":"passed","abstention_threshold":0.2,"low_confidence":false}},"usage":{"truncated":false,"state_tokens_dropped":0}},{"answers":{"relevance":{"type":"score","score":0.1,"answer_confidence":0.89,"abstention":"passed","abstention_threshold":0.2,"low_confidence":false}},"usage":{"truncated":false,"state_tokens_dropped":0}}],"total_usage":{"input_tokens":10,"output_tokens":0}}`)
|
|
}))
|
|
defer srv.Close()
|
|
|
|
ranker, err := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: srv.URL, Timeout: time.Second, BatchSize: 64})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
candidates := []generation.Candidate{{ID: "low"}, {ID: "high"}}
|
|
got, err := ranker.Rank(context.Background(), "title", []models.UserAsset{{Name: "S&P 500", Symbol: "SPX"}}, candidates)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if calls != 1 || !reflect.DeepEqual([]string{got[0].ID, got[1].ID}, []string{"high", "low"}) {
|
|
t.Fatalf("calls=%d ranked IDs=%v; want [high low]", calls, candidateIDs(got))
|
|
}
|
|
}
|
|
|
|
func TestLayaHTTPRankerBatchesAtProtocolLimitWithoutReordering(t *testing.T) {
|
|
var batchSizes []int
|
|
var next int
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
var body struct {
|
|
States []any `json:"states"`
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
|
t.Errorf("decode: %v", err)
|
|
}
|
|
batchSizes = append(batchSizes, len(body.States))
|
|
results := make([]map[string]any, len(body.States))
|
|
for i := range results {
|
|
results[i] = map[string]any{"answers": map[string]any{"relevance": map[string]any{"type": "score", "score": float64(next) / 64.0, "answer_confidence": 0.9}}, "usage": map[string]any{"truncated": false}}
|
|
next++
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"results": results, "total_usage": map[string]any{"input_tokens": 1, "output_tokens": 0}})
|
|
}))
|
|
defer srv.Close()
|
|
ranker, err := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: srv.URL, Timeout: time.Second, BatchSize: 64})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
candidates := make([]generation.Candidate, 65)
|
|
for i := range candidates {
|
|
candidates[i].ID = fmt.Sprintf("candidate-%02d", i)
|
|
}
|
|
got, err := ranker.Rank(context.Background(), "title", nil, candidates)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !reflect.DeepEqual(batchSizes, []int{64, 1}) {
|
|
t.Fatalf("batch sizes=%v; want [64 1]", batchSizes)
|
|
}
|
|
for i := range got {
|
|
if got[i].ID != candidates[i].ID {
|
|
t.Fatalf("position %d = %q, want %q", i, got[i].ID, candidates[i].ID)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestLayaHTTPRankerFailsClosedOnHTTPMalformedAbstainedOODOrTruncatedResponses(t *testing.T) {
|
|
cases := []struct{ name, status, payload string }{
|
|
{"http error", "503 Service Unavailable", `{"detail":"unavailable"}`},
|
|
{"missing score answer", "200 OK", `{"results":[{"answers":{},"usage":{"truncated":false}}]}`},
|
|
{"abstained", "200 OK", `{"results":[{"answers":{"relevance":{"type":"score","score":0.8,"answer_confidence":0.1,"abstention":"abstained","low_confidence":true}},"usage":{"truncated":false}}]}`},
|
|
{"truncated input", "200 OK", `{"results":[{"answers":{"relevance":{"type":"score","score":0.8,"answer_confidence":0.9}},"usage":{"truncated":true,"state_tokens_dropped":7}}]}`},
|
|
{"unevaluated answer without OOD confidence", "200 OK", `{"results":[{"answers":{"relevance":{"type":"score","score":0.8,"answer_confidence":null,"abstention":"unevaluated"}},"usage":{"truncated":false}}]}`},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
status := http.StatusOK
|
|
if tc.status != "200 OK" {
|
|
status = http.StatusServiceUnavailable
|
|
}
|
|
w.WriteHeader(status)
|
|
_, _ = w.Write([]byte(tc.payload))
|
|
}))
|
|
defer srv.Close()
|
|
ranker, err := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: srv.URL, Timeout: time.Second, BatchSize: 64})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
_, err = ranker.Rank(context.Background(), "title", nil, []generation.Candidate{{ID: "c1"}})
|
|
if err == nil {
|
|
t.Fatal("expected fail-closed ranking error")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestLayaHTTPRankerUsesConfiguredURLAndHonorsTimeout(t *testing.T) {
|
|
started := make(chan struct{})
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
_, _ = io.Copy(io.Discard, r.Body)
|
|
close(started)
|
|
<-r.Context().Done()
|
|
}))
|
|
defer srv.Close()
|
|
ranker, err := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: srv.URL, Timeout: 20 * time.Millisecond, BatchSize: 64})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
_, err = ranker.Rank(context.Background(), "title", nil, []generation.Candidate{{ID: "c1"}})
|
|
<-started
|
|
if err == nil || !strings.Contains(strings.ToLower(err.Error()), "timeout") {
|
|
t.Fatalf("error=%v; want timeout", err)
|
|
}
|
|
}
|
|
|
|
func candidateIDs(in []generation.Candidate) []string {
|
|
out := make([]string, len(in))
|
|
for i := range in {
|
|
out[i] = in[i].ID
|
|
}
|
|
return out
|
|
}
|