feat(laya): integrate HTTP ranking service

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>
This commit is contained in:
2026-11-22 00:55:18 +01:00
parent 89503c52fc
commit 1123360914
15 changed files with 1023 additions and 9 deletions

View File

@ -0,0 +1,120 @@
package ai
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"time"
"github.com/tradarr/backend/internal/generation"
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper"
)
func TestLayaHTTPRejectsInvalidConfiguration(t *testing.T) {
for _, cfg := range []LayaHTTPConfig{
{BaseURL: ""}, {BaseURL: "ftp://localhost"}, {BaseURL: "http://user:secret@localhost"}, {BaseURL: "http://localhost?secret=value"},
{BaseURL: "http://localhost", BatchSize: 65}, {BaseURL: "http://localhost", Timeout: -time.Second}, {BaseURL: "http://localhost", APIKey: "secret\nvalue"},
} {
if _, err := NewLayaHTTPRanker(cfg); err == nil {
t.Errorf("accepted invalid configuration")
}
}
}
func TestLayaHTTPRejectsInvalidScoresFramingAndPartialBatches(t *testing.T) {
for _, payload := range []string{
`{"results":[]}`, `{"results":[{},{}]}`, `{"results":[{}]} {}`,
`{"results":[{"answers":{"relevance":{"type":"score","score":2,"answer_confidence":0.9}},"usage":{"truncated":false}}]}`,
`{"results":[{"answers":{"relevance":{"type":"score","score":null,"answer_confidence":0.9}},"usage":{"truncated":false}}]}`,
`{"results":[{"answers":{"relevance":{"type":"score","score":0.2,"answer_confidence":1.1}},"usage":{"truncated":false}}]}`,
`{"results":[{"answers":{"relevance":{"type":"score","score":0.2,"answer_confidence":0.9}},"usage":{}}]}`,
`{"results":[{"answers":{"relevance":{"type":"score","score":0.2,"answer_confidence":0.9}},"usage":{"truncated":false,"truncated_questions":["relevance"]}}]}`,
`{"results":[{"answers":{"relevance":{"type":"score","score":0.2,"answer_confidence":0.9,"abstention":"passed","abstention_threshold":0.95}},"usage":{"truncated":false}}]}`,
} {
t.Run(payload, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, payload) }))
defer srv.Close()
ranker, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: srv.URL})
got, err := ranker.Rank(context.Background(), "title", nil, []generation.Candidate{{ID: "1"}})
if err == nil || got != nil {
t.Fatalf("invalid response returned candidates: %v, %v", got, err)
}
})
}
calls := 0
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
if calls == 1 {
fmt.Fprint(w, `{"results":[{"answers":{"relevance":{"type":"score","score":0.2,"answer_confidence":0.9}},"usage":{"truncated":false}}]}`)
} else {
w.WriteHeader(503)
fmt.Fprint(w, "secret-prompt-article")
}
}))
defer srv.Close()
ranker, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: srv.URL, BatchSize: 1})
got, err := ranker.Rank(context.Background(), "title", nil, []generation.Candidate{{ID: "1"}, {ID: "2"}})
if err == nil || got != nil || calls != 2 || strings.Contains(err.Error(), "secret-prompt-article") || strings.Contains(err.Error(), srv.URL) {
t.Fatalf("not fail-closed/sanitized: calls=%d err=%v", calls, err)
}
}
func TestLayaHTTPBearerEvidenceFallbackAndStableTies(t *testing.T) {
var states []map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "Bearer test-secret" {
t.Error("missing bearer")
}
var body struct {
States []map[string]any `json:"states"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Error(err)
}
states = body.States
fmt.Fprint(w, `{"results":[{"answers":{"relevance":{"type":"score","score":0.2,"answer_confidence":0.9}},"usage":{"truncated":false}},{"answers":{"relevance":{"type":"score","score":0.2,"answer_confidence":0.9}},"usage":{"truncated":false}}]}`)
}))
defer srv.Close()
ranker, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: srv.URL, APIKey: "test-secret"})
figi := "BBG000000001"
candidates := []generation.Candidate{{ID: "1", Article: scraper.Article{Title: "Title", Content: "Title"}}, {ID: "2", Article: scraper.Article{Title: "Second", Content: "Available evidence", Symbols: []string{"SPX"}}}}
got, err := ranker.Rank(context.Background(), "title_content", []models.UserAsset{{Name: "S&P 500", Symbol: "SPX", FIGI: &figi}}, candidates)
if err != nil || !reflect.DeepEqual(got, candidates) {
t.Fatalf("unstable ties or changed evidence: %v", err)
}
if states[0]["content_fallback"] != "title_only" || states[0]["content"] != nil || states[1]["content"] != "Available evidence" {
t.Fatalf("bad content/fallback: %v", states)
}
indices := states[0]["indices"].([]any)
if indices[0].(map[string]any)["figi"] != figi {
t.Fatal("lost exact index identity")
}
_, err = ranker.Rank(context.Background(), "title", nil, candidates)
if err != nil {
t.Fatal(err)
}
if states[1]["content"] != nil {
t.Fatal("title mode sent content")
}
}
func TestLayaHTTPDoesNotForwardBearerOnRedirect(t *testing.T) {
targetCalls := 0
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { targetCalls++ }))
defer target.Close()
source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, target.URL, http.StatusTemporaryRedirect)
}))
defer source.Close()
ranker, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: source.URL, APIKey: "secret"})
got, err := ranker.Rank(context.Background(), "title", nil, []generation.Candidate{{ID: "1"}})
if err == nil || got != nil || targetCalls != 0 {
t.Fatalf("followed redirect: %v", err)
}
}