223 lines
9.7 KiB
Go
223 lines
9.7 KiB
Go
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"
|
|
"github.com/tradarr/backend/internal/scraper/bloomberg"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
type contentRepo struct {
|
|
mode string
|
|
saved []generation.GenerationRecord
|
|
}
|
|
|
|
func (r *contentRepo) LoadUserInput(context.Context, string) (generation.UserInput, error) {
|
|
key := models.SourceBloomberg
|
|
return generation.UserInput{Language: "fr", RankingMode: r.mode, GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Followed Fixture"}}, Sources: []models.Source{{ID: "s", SourceKey: &key, Enabled: true, ArticleLimit: 2}}}, nil
|
|
}
|
|
func (r *contentRepo) SaveGeneration(_ context.Context, _ string, record generation.GenerationRecord) error {
|
|
r.saved = append(r.saved, record)
|
|
return nil
|
|
}
|
|
|
|
type enrichedFeed struct{ client *bloomberg.Bloomberg }
|
|
|
|
func (f enrichedFeed) Name() string { return "bloomberg" }
|
|
func (f enrichedFeed) Scrape(ctx context.Context, s []string) ([]scraper.Article, error) {
|
|
return f.client.ScrapeWithCredentials(ctx, "fixture", "fixture", s)
|
|
}
|
|
func (f enrichedFeed) Enrich(ctx context.Context, a []scraper.Article) ([]scraper.Article, error) {
|
|
return f.client.EnrichWithCredentials(ctx, "fixture", "fixture", a)
|
|
}
|
|
|
|
type contentProvider struct {
|
|
prompt string
|
|
calls int
|
|
}
|
|
|
|
func (*contentProvider) Name() string { return "fixture" }
|
|
func (*contentProvider) ListModels(context.Context) ([]string, error) { return nil, nil }
|
|
func (p *contentProvider) Summarize(_ context.Context, prompt string, _ GenOptions) (string, error) {
|
|
p.prompt = prompt
|
|
p.calls++
|
|
return "synthetic synthesis", nil
|
|
}
|
|
func TestTicket36DTOThroughLayaAndSummaryWithStrictModelTruncation(t *testing.T) {
|
|
for _, scenario := range []string{"title", "title_content", "model_truncation"} {
|
|
t.Run(scenario, func(t *testing.T) {
|
|
mode := scenario
|
|
if scenario == "model_truncation" {
|
|
mode = "title_content"
|
|
}
|
|
enrichCalls := 0
|
|
service := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
if r.URL.Path == "/bloomberg/scrape" {
|
|
io.WriteString(w, `{"articles":[{"title":"report one","url":"https://www.bloomberg.com/news/articles/a"},{"title":"report two","url":"https://www.bloomberg.com/news/articles/b"},{"title":"excluded","url":"https://www.bloomberg.com/news/articles/c"}]}`)
|
|
return
|
|
}
|
|
if r.URL.Path != "/bloomberg/enrich" {
|
|
t.Error("unexpected RPC")
|
|
}
|
|
enrichCalls++
|
|
var request struct {
|
|
URLs []string `json:"urls"`
|
|
}
|
|
_ = json.NewDecoder(r.Body).Decode(&request)
|
|
if len(request.URLs) != 2 {
|
|
t.Error("enrichment before pool limit")
|
|
}
|
|
articles := []any{}
|
|
for _, url := range request.URLs {
|
|
articles = append(articles, map[string]any{"url": url, "content": "Synthetic editorial detail.", "content_truncated": false, "content_state": "complete", "published_at": nil})
|
|
}
|
|
_ = json.NewEncoder(w).Encode(map[string]any{"articles": articles})
|
|
}))
|
|
defer service.Close()
|
|
ranker, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: "http://fixture.invalid"})
|
|
ranker.client = &http.Client{Transport: ticket31Transport(func(req *http.Request) (*http.Response, error) {
|
|
var body struct {
|
|
States []map[string]any
|
|
Questions map[string]any
|
|
}
|
|
if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
key := ""
|
|
for k := range body.Questions {
|
|
key = k
|
|
}
|
|
results := []any{}
|
|
for _, state := range body.States {
|
|
if mode == "title_content" {
|
|
if state["content"] != "Synthetic editorial detail." || state["content_truncated"] != nil {
|
|
t.Error("content/limit flag missing from Laya")
|
|
}
|
|
} else if state["content"] != nil || state["content_truncated"] != nil {
|
|
t.Error("title mode leaked content")
|
|
}
|
|
results = append(results, map[string]any{"answers": map[string]any{key: map[string]any{"type": "noul", "noul": 0.9, "answer_confidence": 0.99}}, "usage": map[string]any{"truncated": scenario == "model_truncation"}})
|
|
}
|
|
raw, _ := json.Marshal(map[string]any{"results": results})
|
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(raw))), Header: make(http.Header)}, nil
|
|
})}
|
|
repo := &contentRepo{mode: mode}
|
|
provider := &contentProvider{}
|
|
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, Decider: ranker, Summarizer: generationSummarizer{providerName: "gemini", model: "gemini-2.5-flash", provider: provider}, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: enrichedFeed{bloomberg.New(service.URL)}}})
|
|
result, err := uc.Generate(context.Background(), "fixture")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if scenario == "model_truncation" {
|
|
if result.Summary != nil || provider.calls != 0 || result.Outcome.FailureCode != "ranking_failed" {
|
|
t.Fatal("accepted model truncation")
|
|
}
|
|
} else {
|
|
if result.Summary == nil || provider.calls != 1 {
|
|
t.Fatal(result.Outcome)
|
|
}
|
|
contains := strings.Contains(provider.prompt, "Synthetic editorial detail.") && !strings.Contains(provider.prompt, `"content_truncated":true`)
|
|
if contains != (mode == "title_content") {
|
|
t.Fatal("summary mode/limit metadata incorrect")
|
|
}
|
|
}
|
|
if (enrichCalls == 1) != (mode == "title_content") {
|
|
t.Fatal("unnecessary/missing page loading")
|
|
}
|
|
raw, _ := json.Marshal(result.Outcome)
|
|
if strings.Contains(string(raw), "editorial detail") {
|
|
t.Fatal("candidate persisted")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestTicket36ReviewRankingContentBudget(t *testing.T) {
|
|
c := generation.Candidate{Article: scraper.Article{Title: "Preserved title", ContentState: scraper.ContentComplete, Content: strings.Repeat("é漢🙂<&", 4096)}}
|
|
state := layaArticleState([]map[string]string{{"name": "Preserved identity", "symbol": "FIX"}}, c, "title_content")
|
|
data, err := json.Marshal(state)
|
|
if err != nil || len(data) > layaStateByteBudget {
|
|
t.Fatalf("state bytes=%d exceeds budget=%d", len(data), layaStateByteBudget)
|
|
}
|
|
t.Logf("ranking_state_bytes=%d budget=%d", len(data), layaStateByteBudget)
|
|
if state["title"] != c.Article.Title || state["content_truncated"] != true {
|
|
t.Fatal("title or explicit excerpt flag missing")
|
|
}
|
|
content, ok := state["content"].(string)
|
|
if !ok || content == "" || !utf8.ValidString(content) || !strings.HasPrefix(c.Article.Content, content) {
|
|
t.Fatal("invalid deterministic excerpt")
|
|
}
|
|
if c.Article.ContentTruncated {
|
|
t.Fatal("mutated candidate")
|
|
}
|
|
}
|
|
func TestTicket36ReviewSummaryAggregateBudget(t *testing.T) {
|
|
p := &contentProvider{}
|
|
candidates := make([]generation.Candidate, 200)
|
|
for i := range candidates {
|
|
candidates[i] = generation.Candidate{ID: fmt.Sprintf("id-%03d", i), Article: scraper.Article{Title: fmt.Sprintf("title-%03d", i), ContentState: scraper.ContentComplete, Content: strings.Repeat("漢🙂<&", 4096)}}
|
|
}
|
|
_, err := (generationSummarizer{providerName: "gemini", model: "gemini-2.5-flash", provider: p}).Summarize(context.Background(), "fr", nil, candidates)
|
|
if err == nil || p.calls != 0 {
|
|
t.Fatal("full aggregate over budget must not be truncated or sent")
|
|
}
|
|
|
|
}
|
|
|
|
func TestTicket36ReviewImmutableMetadataTooLargeNeverCallsProvider(t *testing.T) {
|
|
p := &contentProvider{}
|
|
_, err := (generationSummarizer{providerName: "gemini", model: "gemini-2.5-flash", provider: p}).Summarize(context.Background(), "fr", nil, []generation.Candidate{{ID: "preserved", Article: scraper.Article{Title: strings.Repeat("title", 60000)}}})
|
|
if err == nil || p.calls != 0 {
|
|
t.Fatal("oversized immutable prompt sent")
|
|
}
|
|
r, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: "http://fake.invalid"})
|
|
calls := 0
|
|
r.client = &http.Client{Transport: ticket31Transport(func(req *http.Request) (*http.Response, error) {
|
|
calls++
|
|
return nil, fmt.Errorf("unexpected transport")
|
|
})}
|
|
got, err := r.Rank(context.Background(), "title_content", []models.UserAsset{{Name: "identity"}}, []generation.Candidate{{ID: "one", Article: scraper.Article{Title: strings.Repeat("title", 200), ContentState: scraper.ContentComplete, Content: "available body"}}})
|
|
if err == nil || got != nil || calls != 0 {
|
|
t.Fatal("oversized immutable state sent")
|
|
}
|
|
}
|
|
func TestTicket36ReviewSerializedHTTPStatesAreBounded(t *testing.T) {
|
|
r, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: "http://fake.invalid"})
|
|
states := 0
|
|
r.client = &http.Client{Transport: ticket31Transport(func(req *http.Request) (*http.Response, error) {
|
|
var body struct{ States []json.RawMessage }
|
|
if err := json.NewDecoder(req.Body).Decode(&body); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
results := []any{}
|
|
for _, raw := range body.States {
|
|
states++
|
|
if len(raw) > layaStateByteBudget {
|
|
t.Fatalf("HTTP state bytes=%d", len(raw))
|
|
}
|
|
var state map[string]any
|
|
json.Unmarshal(raw, &state)
|
|
if state["content_truncated"] != true || state["content_available"] != true {
|
|
t.Fatal("missing excerpt semantics")
|
|
}
|
|
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}})
|
|
}
|
|
data, _ := json.Marshal(map[string]any{"results": results})
|
|
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(data))), Header: make(http.Header)}, nil
|
|
})}
|
|
got, err := r.Rank(context.Background(), "title_content", []models.UserAsset{{Name: "exact identity", Symbol: "FIX"}}, []generation.Candidate{{ID: "one", Article: scraper.Article{Title: "exact title", ContentState: scraper.ContentComplete, Content: strings.Repeat("漢<&🙂", 4096)}}})
|
|
if err != nil || len(got) != 1 || states != 1 {
|
|
t.Fatalf("states=%d err=%v", states, err)
|
|
}
|
|
}
|