package ai import ( "context" "encoding/json" "fmt" "github.com/tradarr/backend/internal/generation" "github.com/tradarr/backend/internal/models" "github.com/tradarr/backend/internal/scraper" "net/http" "net/http/httptest" "testing" ) func TestTicket29RepresentativeWorkloadCountsAndExhaustiveCoverage(t *testing.T) { assets := make([]models.UserAsset, 30) for i := range assets { id := fmt.Sprintf("opaque-%d", i) assets[i] = models.UserAsset{Name: fmt.Sprintf("Company %02d Incorporated", i), Symbol: fmt.Sprintf("T%02d", i), CompanyID: &id} } candidates := make([]generation.Candidate, 236) for i := range candidates { candidates[i] = generation.Candidate{ID: fmt.Sprint(i), Article: scraper.Article{Title: fmt.Sprintf("Company earnings article %03d", i)}} } coverage := map[string]map[string]int{} posts, states, maxStateBytes := 0, 0, 0 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { posts++ var body struct{ States []json.RawMessage } if err := json.NewDecoder(r.Body).Decode(&body); err != nil { t.Error(err) } if len(body.States) > 64 { t.Error("protocol batch limit exceeded") } results := []any{} for _, raw := range body.States { if len(raw) > maxStateBytes { maxStateBytes = len(raw) } if len(raw) > 768 { t.Error("representative state exceeds conservative budget") } var state struct { Indices []map[string]string Title string } if err := json.Unmarshal(raw, &state); err != nil { t.Error(err) } states++ if coverage[state.Title] == nil { coverage[state.Title] = map[string]int{} } for _, asset := range state.Indices { coverage[state.Title][asset["symbol"]]++ if _, ok := asset["company_id"]; ok { t.Error("opaque identity sent to model") } } results = append(results, map[string]any{"answers": map[string]any{"relevance": map[string]any{"type": "score", "score": 0.2, "answer_confidence": 0.99}}, "usage": map[string]any{"truncated": false}}) } _ = json.NewEncoder(w).Encode(map[string]any{"results": results}) })) defer srv.Close() ranker, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: srv.URL}) got, err := ranker.Rank(context.Background(), "title", assets, candidates) if err != nil { t.Fatal(err) } t.Logf("articles=236 assets=30 states=%d POST=%d max_state_bytes=%d", states, posts, maxStateBytes) if posts != 12 || states != 708 { t.Fatalf("too many POSTs: %d states=%d (target <=16)", posts, states) } for i, c := range candidates { if got[i].ID != c.ID { t.Fatal("unstable ties") } for _, a := range assets { if coverage[c.Article.Title][a.Symbol] != 1 { t.Fatal("missing/duplicate article-asset pair") } } } } func TestTicket29WholeWatchlistFitsOneJudgmentAndPreservesListing(t *testing.T) { country, exchange, mic, opaque, figi, yahoo := "HK", "Hong Kong", "XHKG", "opaque-local", "opaque-figi", "9988.HK" assets := []models.UserAsset{{Name: "Alibaba Group", Symbol: "BABA", CompanyID: &opaque, FIGI: &figi, YahooSymbol: &yahoo, CompanyCountry: &country, CompanyExchange: &exchange, CompanyMIC: &mic}, {Name: "Alibaba Group", Symbol: "9988.HK", CompanyCountry: &country, CompanyExchange: &exchange, CompanyMIC: &mic}} // More than ten assets can still share one judgment when the entire state fits. for i := 0; i < 10; i++ { assets = append(assets, models.UserAsset{Name: fmt.Sprintf("C%d", i), Symbol: fmt.Sprintf("S%d", i)}) } calls, states := 0, 0 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++ var body struct { States []struct { Indices []map[string]string Content string Mode string `json:"ranking_mode"` } } if err := json.NewDecoder(r.Body).Decode(&body); err != nil { t.Error(err) } states += len(body.States) for _, state := range body.States { if len(state.Indices) != len(assets) || state.Content != "Entire short content" || state.Mode != "title_content" { t.Error("whole-watchlist state/evidence changed") } for i, index := range state.Indices { if index["name"] != assets[i].Name || index["symbol"] != assets[i].Symbol { t.Error("exact semantic identity changed") } if i < 2 && (index["country"] != country || index["exchange"] != exchange || index["mic"] != mic || len(index) != 5) { t.Error("compact listing identity changed") } if i >= 2 && len(index) != 2 { t.Error("unnecessary fields") } } } _ = json.NewEncoder(w).Encode(map[string]any{"results": []any{map[string]any{"answers": map[string]any{"relevance": map[string]any{"type": "score", "score": 0.2, "answer_confidence": 0.99}}, "usage": map[string]any{"truncated": false}}}}) })) defer srv.Close() ranker, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: srv.URL}) got, err := ranker.Rank(context.Background(), "title_content", assets, []generation.Candidate{{ID: "original-id", Article: scraper.Article{Title: "headline", ContentState: scraper.ContentComplete, Content: "Entire short content"}}}) if err != nil || calls != 1 || states != 1 || len(got) != 1 || got[0].ID != "original-id" { t.Fatalf("calls=%d states=%d err=%v", calls, states, err) } if assets[0].CompanyID != &opaque || assets[0].FIGI != &figi || assets[0].YahooSymbol != &yahoo { t.Fatal("adapter identity mutated") } }