feat(sources): add managed RSS feeds (#41)
This commit is contained in:
146
backend/internal/ai/quanwen_generation_ticket41_test.go
Normal file
146
backend/internal/ai/quanwen_generation_ticket41_test.go
Normal file
@ -0,0 +1,146 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"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"
|
||||
)
|
||||
|
||||
type rss41Repo struct {
|
||||
input generation.UserInput
|
||||
saved generation.GenerationRecord
|
||||
}
|
||||
|
||||
func (r *rss41Repo) LoadUserInput(context.Context, string) (generation.UserInput, error) {
|
||||
return r.input, nil
|
||||
}
|
||||
func (r *rss41Repo) SaveGeneration(_ context.Context, _ string, record generation.GenerationRecord) error {
|
||||
r.saved = record
|
||||
return nil
|
||||
}
|
||||
|
||||
type rss41Loader struct{}
|
||||
|
||||
func (rss41Loader) SourceFeedURLs(_ context.Context, key string) ([]string, error) {
|
||||
return sourcefeeds.Defaults(key), nil
|
||||
}
|
||||
func TestTicket41RSSMergeThreePassSelectionAndFullSummaryPrompt(t *testing.T) {
|
||||
item := func(title, id, host, body string, full, dated bool) string {
|
||||
date := ""
|
||||
if dated {
|
||||
date = "<pubDate>Fri, 02 Jan 2026 03:04:05 GMT</pubDate>"
|
||||
}
|
||||
field := "description"
|
||||
if full {
|
||||
field = "content:encoded"
|
||||
}
|
||||
return fmt.Sprintf(`<item><title>%s</title><link>https://%s/news/%s</link><guid>%s</guid>%s<%s><![CDATA[<article><p>%s</p></article>]]></%s></item>`, title, host, id, id, date, field, body, field)
|
||||
}
|
||||
literal := item("Watched Company literal", "literal", "www.bloomberg.com", "Synthetic full literal body.", true, true)
|
||||
direct := item("Synthetic direct", "direct", "www.bloomberg.com", "Synthetic full direct body.", true, true)
|
||||
indirect := item("Synthetic indirect", "indirect", "www.bloomberg.com", "Synthetic full indirect body.", true, true)
|
||||
partial := item("Synthetic partial", "partial", "www.bloomberg.com", "Synthetic teaser excluded from Laya.", false, true)
|
||||
investment := item("Synthetic investment", "investment", "www.investing.com", "Synthetic complete investment body.", true, false)
|
||||
urls := sourcefeeds.Defaults(sourcefeeds.Bloomberg)
|
||||
bodies := map[string]string{urls[0]: literal, urls[1]: literal + direct, urls[2]: indirect, urls[3]: partial, sourcefeeds.Defaults(sourcefeeds.Investing)[0]: investment}
|
||||
fetches := 0
|
||||
client := &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
|
||||
fetches++
|
||||
if r.URL.Host != sourcefeeds.Host {
|
||||
t.Fatal("article host was fetched")
|
||||
}
|
||||
status := 200
|
||||
content, ok := bodies[r.URL.String()]
|
||||
if !ok {
|
||||
status = 503
|
||||
}
|
||||
body := `<rss xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel>` + content + `</channel></rss>`
|
||||
return &http.Response{StatusCode: status, Header: make(http.Header), Request: r, Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||
})}
|
||||
ranker, _ := NewLayaHTTPRanker(LayaHTTPConfig{BaseURL: "http://fixture.invalid"})
|
||||
passes := []string{}
|
||||
ranker.client = &http.Client{Transport: ticket31Transport(func(r *http.Request) (*http.Response, error) {
|
||||
var payload struct {
|
||||
States []struct{ Title, Content string }
|
||||
Questions map[string]any
|
||||
}
|
||||
if json.NewDecoder(r.Body).Decode(&payload) != nil {
|
||||
t.Fatal("invalid Laya request")
|
||||
}
|
||||
pass := ""
|
||||
for key := range payload.Questions {
|
||||
pass = key
|
||||
}
|
||||
passes = append(passes, pass)
|
||||
results := []any{}
|
||||
for _, state := range payload.States {
|
||||
if strings.Contains(state.Title, "partial") || state.Title == "Watched Company literal" || state.Content == "" {
|
||||
t.Fatal("partial article or literal first-pass selection leaked into Laya")
|
||||
}
|
||||
yes := state.Title == "Synthetic direct" || state.Title == "Synthetic investment"
|
||||
if pass == "indirect_mention" {
|
||||
yes = state.Title == "Synthetic indirect"
|
||||
}
|
||||
probability := 0.1
|
||||
if yes {
|
||||
probability = 0.9
|
||||
}
|
||||
results = append(results, map[string]any{"answers": map[string]any{pass: map[string]any{"type": "noul", "noul": probability, "answer_confidence": 0.99}}, "usage": map[string]any{"truncated": false, "state_tokens_dropped": 0}})
|
||||
}
|
||||
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
|
||||
})}
|
||||
bloom, invest := models.SourceBloomberg, models.SourceInvesting
|
||||
repo := &rss41Repo{input: generation.UserInput{Language: "fr", RankingMode: "title_content", SummaryContext: "Synthetic personalized context", SummaryPromptTokenBudget: 250000, GlobalLimit: 4, Assets: []models.UserAsset{{Name: "Watched Company", Symbol: "INTERNAL"}}, Sources: []models.Source{{ID: "b", Type: "bloomberg", SourceKey: &bloom, Enabled: true, ArticleLimit: 4}, {ID: "i", Type: "investing_com", SourceKey: &invest, Enabled: true, ArticleLimit: 1}}}}
|
||||
provider := &incident37Provider{}
|
||||
summarizer := fullGenerationSummarizer{provider: provider, providerName: "openai", model: "gpt-4o-mini"}
|
||||
uc := generation.NewUseCase(generation.Dependencies{Repository: repo, LayaRanker: ranker, Summarizer: summarizer, Scrapers: map[string]scraper.Scraper{bloom: quanwenrss.New(bloom, rss41Loader{}, client), invest: quanwenrss.New(invest, rss41Loader{}, client)}})
|
||||
result, err := uc.Generate(context.Background(), "fixture-user")
|
||||
if err != nil || result.Summary == nil || provider.calls != 1 || fetches != 6 || len(passes) != 2 || passes[0] != "direct_mention" || passes[1] != "indirect_mention" || result.Outcome.Selected != 4 || result.Outcome.ContentIncomplete != 1 || result.Outcome.Status != "partial" {
|
||||
t.Fatal("RSS source/three-pass/synthesis integration contract failed")
|
||||
}
|
||||
if result.Outcome.SourceStats[0].Candidates != 4 || result.Outcome.SourceStats[0].Feeds == nil || result.Outcome.SourceStats[0].Feeds.Failed != 1 {
|
||||
t.Fatal("dedup/source limit/feed diagnostics are wrong")
|
||||
}
|
||||
var prompt struct {
|
||||
Articles []struct {
|
||||
Title, Content, Source string
|
||||
PublishedAt *time.Time `json:"published_at"`
|
||||
}
|
||||
Indices []map[string]string
|
||||
Context struct{ Instructions string }
|
||||
}
|
||||
at := strings.Index(provider.prompt, "\n")
|
||||
if at < 0 || json.Unmarshal([]byte(provider.prompt[at+1:]), &prompt) != nil || len(prompt.Articles) != 4 || prompt.Context.Instructions != repo.input.SummaryContext || len(prompt.Indices) != 1 || prompt.Indices[0]["name"] != "Watched Company" {
|
||||
t.Fatal("summary lost full articles/watchlist/context")
|
||||
}
|
||||
nullable := false
|
||||
for _, article := range prompt.Articles {
|
||||
if article.Content == "" || strings.Contains(article.Title, "partial") {
|
||||
t.Fatal("summary received incomplete content")
|
||||
}
|
||||
if article.Source == invest {
|
||||
nullable = article.PublishedAt == nil
|
||||
}
|
||||
}
|
||||
if !nullable {
|
||||
t.Fatal("missing RSS date was invented")
|
||||
}
|
||||
saved, _ := json.Marshal(repo.saved.Outcome)
|
||||
for _, private := range []string{"http://", "https://", "Synthetic full", "Synthetic complete", "Watched Company", "personalized context"} {
|
||||
if strings.Contains(string(saved), private) {
|
||||
t.Fatal("sensitive article data persisted in outcome")
|
||||
}
|
||||
}
|
||||
}
|
||||
127
backend/internal/ai/quanwen_source_limit_ticket41_test.go
Normal file
127
backend/internal/ai/quanwen_source_limit_ticket41_test.go
Normal file
@ -0,0 +1,127 @@
|
||||
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("<pubDate>Fri, 02 Jan 2026 %02d:00:00 GMT</pubDate>", id)
|
||||
}
|
||||
return fmt.Sprintf(`<item><title>Synthetic candidate %d</title><link>https://www.bloomberg.com/news/articles/2026-01-02/fixture-%d</link><guid>fixture-%d</guid>%s<content:encoded><![CDATA[<p>Synthetic complete body %d.</p>]]></content:encoded></item>`, 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(`<rss xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel>` + body + `</channel></rss>`))}, 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)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user