package ai
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"reflect"
"strings"
"testing"
"time"
"github.com/tradarr/backend/internal/generation"
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper"
"github.com/tradarr/backend/internal/scraper/quanwenrss"
"github.com/tradarr/backend/internal/sourcefeeds"
)
func TestTicket41RSSSourceLimitKeepsNewestUniqueArticlesThroughLayaAndSummary(t *testing.T) {
const limit = 3
item := func(id int, dated bool) string {
date := ""
if dated {
date = fmt.Sprintf("Fri, 02 Jan 2026 %02d:00:00 GMT", id)
}
return fmt.Sprintf(`- Synthetic candidate %dhttps://www.bloomberg.com/news/articles/2026-01-02/fixture-%dfixture-%d%sSynthetic complete body %d.
]]>`, id, id, id, date, id)
}
// Eight unique articles across all five feeds, including one undated item.
// The first feed itself exceeds N, with its newest item after position N.
// Other newest items arrive in later feeds; duplicates must not consume N.
urls := sourcefeeds.Defaults(models.SourceBloomberg)
bodies := map[string]string{
urls[0]: item(1, true) + item(2, true) + item(3, true) + item(7, true),
urls[1]: item(1, true) + item(6, true),
urls[2]: item(4, true) + item(6, true),
urls[3]: item(5, true) + item(2, true),
urls[4]: item(8, false),
}
fetches := 0
client := &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
body, ok := bodies[r.URL.String()]
if !ok || r.URL.Host != sourcefeeds.Host {
t.Fatal("request escaped fixture feed routes")
}
fetches++
return &http.Response{StatusCode: 200, Header: make(http.Header), Request: r, Body: io.NopCloser(strings.NewReader(`` + body + ``))}, nil
})}
expected := []string{"Synthetic candidate 7", "Synthetic candidate 6", "Synthetic candidate 5"}
layaCalls := 0
ranker, err := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: "http://fixture.invalid"})
if err != nil {
t.Fatal(err)
}
ranker.client = &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
layaCalls++
var payload struct {
States []struct{ Title, Content string }
Questions map[string]any
}
if json.NewDecoder(r.Body).Decode(&payload) != nil {
t.Fatal("invalid fixture ranking request")
}
titles := []string{}
results := []any{}
for _, state := range payload.States {
titles = append(titles, state.Title)
results = append(results, map[string]any{"answers": map[string]any{"direct_mention": map[string]any{"type": "noul", "noul": 0.9, "answer_confidence": 0.99}}, "usage": map[string]any{"truncated": false, "state_tokens_dropped": 0}})
}
if !reflect.DeepEqual(titles, expected) {
t.Fatalf("ranking did not receive precisely the N newest unique articles: got %v, want %v", titles, expected)
}
for i, state := range payload.States {
if state.Content != fmt.Sprintf("Synthetic complete body %d.", 7-i) {
t.Fatal("ranking received the wrong full body")
}
}
if len(payload.Questions) != 1 || payload.Questions["direct_mention"] == nil {
t.Fatal("unexpected selection pass")
}
raw, _ := json.Marshal(map[string]any{"results": results, "total_usage": map[string]any{"input_tokens": 1}})
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(string(raw)))}, nil
})}
key := models.SourceBloomberg
feed := quanwenrss.New(key, rss41Loader{}, client)
pool, err := feed.Scrape(context.Background(), nil)
if err != nil || len(pool) != 8 || len(pool) <= limit {
t.Fatal("fixture does not establish more than N unique articles after multi-feed merge")
}
fetches = 0
repo := &rss41Repo{input: generation.UserInput{Language: "fr", RankingMode: "title_content", SummaryContext: "Synthetic source limit context", SummaryPromptTokenBudget: 250000, GlobalLimit: 10, Assets: []models.UserAsset{{Name: "Followed Company", Symbol: "INTERNAL"}}, Sources: []models.Source{{ID: "b", Type: "bloomberg", SourceKey: &key, Enabled: true, ArticleLimit: limit}}}}
provider := &incident37Provider{}
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, LayaRanker: ranker, Summarizer: fullGenerationSummarizer{provider: provider, providerName: "openai", model: "gpt-4o-mini"}, Scrapers: map[string]scraper.Scraper{key: feed}})
result, err := uc.Generate(context.Background(), "fixture-user")
if err != nil || result.Summary == nil || fetches != 5 || layaCalls != 1 || provider.calls != 1 {
t.Fatal("multi-feed source limit integration did not reach ranking and synthesis")
}
if result.Outcome.TotalCandidates != limit || result.Outcome.Selected != limit || result.Outcome.ContentComplete != limit || len(result.Outcome.SourceStats) != 1 || result.Outcome.SourceStats[0].Candidates != limit {
t.Fatal("source limit was not applied before ranking")
}
counts := result.Outcome.SourceStats[0].Feeds
if counts == nil || counts.Attempted != 5 || counts.Succeeded != 5 || counts.Failed != 0 {
t.Fatal("not all configured feeds were merged")
}
var prompt struct {
Articles []struct {
Title, Content, Source string
PublishedAt *time.Time `json:"published_at"`
}
}
at := strings.Index(provider.prompt, "\n")
if at < 0 || json.Unmarshal([]byte(provider.prompt[at+1:]), &prompt) != nil {
t.Fatal("invalid summary prompt")
}
titles := []string{}
for i, a := range prompt.Articles {
titles = append(titles, a.Title)
expectedDate := time.Date(2026, 1, 2, 7-i, 0, 0, 0, time.UTC)
if a.Content != fmt.Sprintf("Synthetic complete body %d.", 7-i) || a.Source != key || a.PublishedAt == nil || !a.PublishedAt.Equal(expectedDate) {
t.Fatal("summary lost the newest article's full body/source/observed date")
}
}
if !reflect.DeepEqual(titles, expected) {
t.Fatalf("summary did not receive precisely the N newest unique articles: got %v, want %v", titles, expected)
}
}