194 lines
8.1 KiB
Go
194 lines
8.1 KiB
Go
package generation_test
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/tradarr/backend/internal/ai"
|
|
"github.com/tradarr/backend/internal/generation"
|
|
"github.com/tradarr/backend/internal/models"
|
|
"github.com/tradarr/backend/internal/scraper"
|
|
)
|
|
|
|
type ticket17HTTPRepo struct {
|
|
input generation.UserInput
|
|
saved generation.GenerationRecord
|
|
}
|
|
|
|
func (r *ticket17HTTPRepo) LoadUserInput(context.Context, string) (generation.UserInput, error) {
|
|
return r.input, nil
|
|
}
|
|
func (r *ticket17HTTPRepo) SaveGeneration(_ context.Context, _ string, result generation.GenerationRecord) error {
|
|
r.saved = result
|
|
return nil
|
|
}
|
|
|
|
type ticket17HTTPScraper struct {
|
|
calls int
|
|
articles []scraper.Article
|
|
}
|
|
|
|
func (*ticket17HTTPScraper) Name() string { return "fake-loopback-source" }
|
|
func (s *ticket17HTTPScraper) Scrape(context.Context, []string) ([]scraper.Article, error) {
|
|
s.calls++
|
|
if s.articles != nil {
|
|
return s.articles, nil
|
|
}
|
|
return []scraper.Article{
|
|
{Title: "Less relevant title", Content: "Less relevant body", URL: "https://article-secret.invalid/less", Symbols: []string{"SPX"}},
|
|
{Title: "Selected title", Content: "Selected body", URL: "https://article-secret.invalid/selected", Symbols: []string{"SPX"}},
|
|
}, nil
|
|
}
|
|
|
|
type ticket17HTTPResolver struct {
|
|
requested string
|
|
provider *ticket17HTTPSummary
|
|
}
|
|
|
|
func (r *ticket17HTTPResolver) Resolve(_ context.Context, _ string, selected *string) (generation.ResolvedSummary, error) {
|
|
if selected == nil {
|
|
return generation.ResolvedSummary{}, models.ErrSummaryModelUnavailable
|
|
}
|
|
r.requested = *selected
|
|
return generation.ResolvedSummary{Summarizer: r.provider, CatalogID: *selected, ProviderID: "provider-test", Provider: "fake-provider", Model: "selected-summary-model"}, nil
|
|
}
|
|
|
|
type ticket17HTTPSummary struct {
|
|
calls int
|
|
candidates []generation.Candidate
|
|
}
|
|
|
|
func (s *ticket17HTTPSummary) Summarize(_ context.Context, _ string, _ []models.UserAsset, candidates []generation.Candidate) (string, error) {
|
|
s.calls++
|
|
s.candidates = append([]generation.Candidate(nil), candidates...)
|
|
return "selected model summary", nil
|
|
}
|
|
|
|
func TestGenerationUsesLayaHTTPContractThenSelectedSummaryModel(t *testing.T) {
|
|
var requestBody map[string]any
|
|
laya := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost || r.URL.Path != "/v1/systemone/batch" {
|
|
t.Errorf("Laya request=%s %s", r.Method, r.URL.Path)
|
|
}
|
|
if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil {
|
|
t.Errorf("decode Laya request: %v", err)
|
|
w.WriteHeader(400)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
fmt.Fprint(w, `{"results":[{"answers":{"relevance":{"type":"score","score":0.9,"answer_confidence":0.91}},"usage":{"truncated":false,"state_tokens_dropped":0,"truncated_questions":[]}},{"answers":{"relevance":{"type":"score","score":0.1,"answer_confidence":0.89}},"usage":{"truncated":false,"state_tokens_dropped":0,"truncated_questions":[]}}],"total_usage":{"input_tokens":15,"output_tokens":0}}`)
|
|
}))
|
|
defer laya.Close()
|
|
ranker, err := ai.NewLayaHTTPRanker(ai.LayaHTTPConfig{BaseURL: laya.URL, Timeout: time.Second})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
modelID := "summary-model-user-a"
|
|
key := models.SourceYahooFinance
|
|
feed := &ticket17HTTPScraper{}
|
|
summary := &ticket17HTTPSummary{}
|
|
resolver := &ticket17HTTPResolver{provider: summary}
|
|
repo := &ticket17HTTPRepo{input: generation.UserInput{
|
|
SummaryModelID: &modelID, Language: "en", RankingMode: "title_content", GlobalLimit: 5,
|
|
Assets: []models.UserAsset{{Name: "S&P 500", Symbol: "SPX", FIGI: stringPointer("BBG000SPX001")}},
|
|
Sources: []models.Source{{ID: "source-yahoo", Type: "yahoo", SourceKey: &key, Enabled: true, ArticleLimit: 1}},
|
|
}}
|
|
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, SummaryResolver: resolver, LayaRanker: ranker, Scrapers: map[string]scraper.Scraper{key: feed}})
|
|
result, err := uc.Generate(context.Background(), "user-a")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if feed.calls != 1 || summary.calls != 1 || resolver.requested != modelID {
|
|
t.Fatalf("scraper=%d summary=%d selected model=%q", feed.calls, summary.calls, resolver.requested)
|
|
}
|
|
if requestBody["model"] != "multilingual" {
|
|
t.Errorf("Laya model=%v; want multilingual", requestBody["model"])
|
|
}
|
|
states, ok := requestBody["states"].([]any)
|
|
if !ok || len(states) != 2 {
|
|
t.Fatalf("Laya states=%#v; want two candidate states", requestBody["states"])
|
|
}
|
|
wantTitles := []string{"Less relevant title", "Selected title"}
|
|
for i, title := range wantTitles {
|
|
state, ok := states[i].(map[string]any)
|
|
if !ok {
|
|
t.Fatalf("state %d=%T", i, states[i])
|
|
}
|
|
if state["title"] != title || state["content"] == nil {
|
|
t.Errorf("state %d lacks article title/content: %#v", i, state)
|
|
}
|
|
indices, ok := state["indices"].([]any)
|
|
if !ok || len(indices) != 1 {
|
|
t.Errorf("state %d indices=%#v", i, state["indices"])
|
|
continue
|
|
}
|
|
index := indices[0].(map[string]any)
|
|
if index["name"] != "S&P 500" || index["symbol"] != "SPX" || index["figi"] != nil {
|
|
t.Errorf("Laya index identity=%#v", index)
|
|
}
|
|
}
|
|
if len(summary.candidates) != 1 || summary.candidates[0].Article.Title != "Selected title" || summary.candidates[0].Article.URL != "https://article-secret.invalid/selected" {
|
|
t.Fatalf("summary received candidates=%+v; expected only Laya-selected candidate", summary.candidates)
|
|
}
|
|
if result.Summary == nil || result.Summary.Content != "selected model summary" || result.Summary.SummaryModelID == nil || *result.Summary.SummaryModelID != modelID {
|
|
t.Fatalf("summary/result provenance=%+v", result)
|
|
}
|
|
}
|
|
|
|
func TestGenerationLogsSanitizedLayaFailureCause(t *testing.T) {
|
|
var logs strings.Builder
|
|
oldWriter, oldFlags, oldPrefix := log.Writer(), log.Flags(), log.Prefix()
|
|
log.SetOutput(&logs)
|
|
defer func() { log.SetOutput(oldWriter); log.SetFlags(oldFlags); log.SetPrefix(oldPrefix) }()
|
|
const articleTitle = "PRIVATE_ARTICLE_TITLE_DO_NOT_LOG"
|
|
const articleBody = "PRIVATE_ARTICLE_BODY_DO_NOT_LOG"
|
|
const articleURL = "https://private-article.invalid/path"
|
|
const apiKey = "PRIVATE_LAYA_KEY_DO_NOT_LOG"
|
|
laya := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusServiceUnavailable)
|
|
fmt.Fprint(w, `{"detail":"`+apiKey+` article=`+articleTitle+` body=`+articleBody+` url=`+articleURL+`"}`)
|
|
}))
|
|
defer laya.Close()
|
|
ranker, err := ai.NewLayaHTTPRanker(ai.LayaHTTPConfig{BaseURL: laya.URL, Timeout: time.Second, APIKey: apiKey})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
modelID := "summary-model-user-a"
|
|
key := models.SourceYahooFinance
|
|
feed := &ticket17HTTPScraper{articles: []scraper.Article{{Title: articleTitle, Content: articleBody, URL: articleURL}}}
|
|
summary := &ticket17HTTPSummary{}
|
|
repo := &ticket17HTTPRepo{input: generation.UserInput{SummaryModelID: &modelID, Language: "en", RankingMode: "title", GlobalLimit: 5, Assets: []models.UserAsset{{Name: "S&P 500", Symbol: "SPX"}}, Sources: []models.Source{{ID: "source-yahoo", Type: "yahoo", SourceKey: &key, Enabled: true, ArticleLimit: 5}}}}
|
|
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, SummaryResolver: &ticket17HTTPResolver{provider: summary}, LayaRanker: ranker, Scrapers: map[string]scraper.Scraper{key: feed}})
|
|
result, err := uc.Generate(context.Background(), "user-a")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if result.Outcome.FailureCode != "ranking_failed" || result.Summary != nil || summary.calls != 0 {
|
|
t.Fatalf("failure result=%+v summary calls=%d", result.Outcome, summary.calls)
|
|
}
|
|
line := logs.String()
|
|
if !strings.Contains(strings.ToLower(line), "laya") || !strings.Contains(line, "503") {
|
|
t.Fatalf("backend logs lack a readable Laya HTTP cause: %q", line)
|
|
}
|
|
for _, secret := range []string{articleTitle, articleBody, articleURL, apiKey} {
|
|
if strings.Contains(line, secret) {
|
|
t.Errorf("sensitive value was logged: %q", secret)
|
|
}
|
|
}
|
|
encoded, _ := json.Marshal(result.Outcome)
|
|
for _, secret := range []string{articleTitle, articleBody, articleURL, apiKey} {
|
|
if strings.Contains(string(encoded), secret) {
|
|
t.Errorf("sensitive value leaked into outcome: %s", encoded)
|
|
}
|
|
}
|
|
}
|
|
|
|
func stringPointer(s string) *string { return &s }
|