feat(bloomberg): enrich article content for summaries (#36)
This commit is contained in:
80
backend/internal/generation/content_ticket36_test.go
Normal file
80
backend/internal/generation/content_ticket36_test.go
Normal file
@ -0,0 +1,80 @@
|
||||
package generation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type contentFeed struct {
|
||||
contractScraper
|
||||
calls int
|
||||
sizes []int
|
||||
fail bool
|
||||
}
|
||||
|
||||
func (f *contentFeed) Enrich(_ context.Context, a []scraper.Article) ([]scraper.Article, error) {
|
||||
f.calls++
|
||||
f.sizes = append(f.sizes, len(a))
|
||||
if f.fail {
|
||||
return nil, errors.New("private error")
|
||||
}
|
||||
out := append([]scraper.Article(nil), a...)
|
||||
for i := range out {
|
||||
out[i].Content = "synthetic editorial paragraph"
|
||||
d := time.Date(2026, 1, 1, i+1, 0, 0, 0, time.UTC)
|
||||
out[i].PublishedAt = &d
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func TestTicket36EnrichmentAfterPoolAndNoReordering(t *testing.T) {
|
||||
for _, mode := range []string{"title_content", "title", "failure", "other_source"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
source := models.SourceBloomberg
|
||||
rankingMode := mode
|
||||
if mode == "failure" || mode == "other_source" {
|
||||
rankingMode = "title_content"
|
||||
}
|
||||
if mode == "other_source" {
|
||||
source = models.SourceYahooFinance
|
||||
}
|
||||
feed := &contentFeed{fail: mode == "failure", contractScraper: contractScraper{articles: []scraper.Article{{Title: "Fixture first"}, {Title: "Fixture second"}, {Title: "excluded"}}}}
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: rankingMode, GlobalLimit: 2, Assets: []models.UserAsset{{Name: "Fixture"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(source), Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
|
||||
sum := &contractSummarizer{}
|
||||
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{source: feed}}).Generate(context.Background(), "u")
|
||||
if err != nil || r.Summary == nil {
|
||||
t.Fatal(err, r.Outcome)
|
||||
}
|
||||
if mode == "title_content" {
|
||||
if feed.calls != 1 || feed.sizes[0] != 2 || sum.articles[0][0].Article.Content == "" || r.Outcome.ContentFallbacks != 0 {
|
||||
t.Fatal("enrichment missing or before N", feed.calls, feed.sizes)
|
||||
}
|
||||
} else if mode == "failure" {
|
||||
if feed.calls != 1 || r.Outcome.ContentFallbacks != 2 {
|
||||
t.Fatal("failed enrichment dropped candidates")
|
||||
}
|
||||
} else if feed.calls != 0 || sum.articles[0][0].Article.Content != "" {
|
||||
t.Fatal("unnecessary enrichment")
|
||||
}
|
||||
if sum.articles[0][0].Article.Title != "Fixture first" {
|
||||
t.Fatal("enriched dates reordered pool")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicket36EnrichedDateDoesNotChangeCrossSourceOrder(t *testing.T) {
|
||||
keyB, keyY := models.SourceBloomberg, models.SourceYahooFinance
|
||||
feed := &contentFeed{contractScraper: contractScraper{articles: []scraper.Article{{Title: "Fixture Bloomberg"}}}}
|
||||
old := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
other := &contractScraper{articles: []scraper.Article{{Title: "Fixture Yahoo", PublishedAt: &old}}}
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 2, Assets: []models.UserAsset{{Name: "Fixture"}}, Sources: []models.Source{{ID: "b", SourceKey: &keyB, Enabled: true, ArticleLimit: 1}, {ID: "y", SourceKey: &keyY, Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
|
||||
sum := &contractSummarizer{}
|
||||
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{keyB: feed, keyY: other}}).Generate(context.Background(), "u")
|
||||
if err != nil || r.Summary == nil || sum.articles[0][0].Article.Title != "Fixture Yahoo" || sum.articles[0][1].Article.PublishedAt == nil {
|
||||
t.Fatal("new publication date reranked the frozen pool", r.Outcome, err)
|
||||
}
|
||||
}
|
||||
@ -22,6 +22,8 @@ type UserInput struct {
|
||||
type Candidate struct {
|
||||
ID, SourceID string
|
||||
Article scraper.Article
|
||||
orderDate *time.Time
|
||||
orderFrozen bool
|
||||
}
|
||||
type SourceStat struct {
|
||||
SourceID string `json:"source_id"`
|
||||
@ -201,18 +203,50 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
if len(articles) > stat.ArticleLimit {
|
||||
articles = articles[:stat.ArticleLimit]
|
||||
}
|
||||
for _, article := range articles {
|
||||
orderDates := make([]*time.Time, len(articles))
|
||||
for i, a := range articles {
|
||||
if a.PublishedAt != nil {
|
||||
date := *a.PublishedAt
|
||||
orderDates[i] = &date
|
||||
}
|
||||
}
|
||||
if input.RankingMode == "title_content" && *source.SourceKey == models.SourceBloomberg {
|
||||
if enricher, ok := feed.(scraper.ArticleEnricher); ok {
|
||||
enriched, enrichErr := enricher.Enrich(ctx, append([]scraper.Article(nil), articles...))
|
||||
valid := enrichErr == nil && len(enriched) == len(articles)
|
||||
if valid {
|
||||
for i, a := range enriched {
|
||||
if a.URL != articles[i].URL || a.Title != articles[i].Title {
|
||||
valid = false
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if valid {
|
||||
for i, a := range enriched {
|
||||
articles[i].Content = a.Content
|
||||
articles[i].ContentTruncated = a.ContentTruncated
|
||||
if a.PublishedAt != nil {
|
||||
articles[i].PublishedAt = a.PublishedAt
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for i, article := range articles {
|
||||
stat.Candidates++
|
||||
out.TotalCandidates++
|
||||
if input.RankingMode == "title_content" && (strings.TrimSpace(article.Content) == "" || strings.TrimSpace(article.Content) == strings.TrimSpace(article.Title)) {
|
||||
stat.ContentFallbacks++
|
||||
out.ContentFallbacks++
|
||||
article.Content = ""
|
||||
article.ContentTruncated = false
|
||||
}
|
||||
if input.RankingMode == "title" {
|
||||
article.Content = ""
|
||||
article.ContentTruncated = false
|
||||
}
|
||||
candidates = append(candidates, Candidate{ID: NewID(), SourceID: source.ID, Article: article})
|
||||
candidates = append(candidates, Candidate{ID: NewID(), SourceID: source.ID, Article: article, orderDate: orderDates[i], orderFrozen: true})
|
||||
}
|
||||
}
|
||||
stats[source.ID] = len(out.SourceStats)
|
||||
|
||||
@ -24,19 +24,20 @@ func TestTicket28GenerationAggregatesAllAssetsBeforeSelectionAndFailsClosed(t *t
|
||||
calls++
|
||||
var body struct {
|
||||
States []struct {
|
||||
Indices []map[string]string
|
||||
Title, Content string
|
||||
Indices []map[string]string
|
||||
Title, Content string
|
||||
ContentTruncated bool `json:"content_truncated"`
|
||||
}
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if len(body.States) != 2 {
|
||||
t.Error("expected both articles")
|
||||
t.Error("expected full two-state batch")
|
||||
}
|
||||
for _, state := range body.States {
|
||||
if len(state.Indices) != 1 || state.Content != content {
|
||||
t.Error("asset grouping or exact content lost")
|
||||
if len(state.Indices) != 1 || state.Content == "" || !strings.HasPrefix(content, state.Content) || !state.ContentTruncated {
|
||||
t.Error("asset grouping or explicit excerpt lost")
|
||||
}
|
||||
}
|
||||
if calls == 2 && failure == "http" {
|
||||
@ -64,7 +65,7 @@ func TestTicket28GenerationAggregatesAllAssetsBeforeSelectionAndFailsClosed(t *t
|
||||
model, key := "model", models.SourceYahooFinance
|
||||
feed := &ticket17HTTPScraper{articles: []scraper.Article{{Title: "first", URL: "https://fixture.invalid/first", Content: content}, {Title: "second", URL: "https://fixture.invalid/second", Content: content}}}
|
||||
summary := &ticket17HTTPSummary{}
|
||||
repo := &ticket17HTTPRepo{input: generation.UserInput{SummaryModelID: &model, Language: "fr", RankingMode: "title_content", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "A", Symbol: "A"}, {Name: "B", Symbol: "B"}}, Sources: []models.Source{{ID: "source", SourceKey: &key, Enabled: true, ArticleLimit: 2}}}}
|
||||
repo := &ticket17HTTPRepo{input: generation.UserInput{SummaryModelID: &model, Language: "fr", RankingMode: "title_content", GlobalLimit: 1, Assets: []models.UserAsset{{Name: strings.Repeat("A", 400), Symbol: "A"}, {Name: strings.Repeat("B", 400), Symbol: "B"}}, Sources: []models.Source{{ID: "source", SourceKey: &key, Enabled: true, ArticleLimit: 2}}}}
|
||||
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(), "owner")
|
||||
if err != nil || calls != 2 || feed.calls != 1 {
|
||||
@ -74,7 +75,7 @@ func TestTicket28GenerationAggregatesAllAssetsBeforeSelectionAndFailsClosed(t *t
|
||||
if result.Summary != nil || summary.calls != 0 || result.Outcome.Status != "failed" || result.Outcome.FailureCode != "ranking_failed" || repo.saved.Summary != nil {
|
||||
t.Fatal("partial summary after group failure")
|
||||
}
|
||||
} else if summary.calls != 1 || len(summary.candidates) != 1 || summary.candidates[0].Article.Title != "second" || result.Outcome.Status != "succeeded" {
|
||||
} else if summary.calls != 1 || len(summary.candidates) != 1 || summary.candidates[0].Article.Title != "second" || summary.candidates[0].Article.Content != content || result.Outcome.Status != "succeeded" {
|
||||
t.Fatal("selection happened before all groups", fmt.Sprint(result.Outcome))
|
||||
}
|
||||
saved, _ := json.Marshal(repo.saved.Outcome)
|
||||
|
||||
@ -59,7 +59,7 @@ func mergeSourceCandidates(candidates []Candidate) []Candidate {
|
||||
if positions[i] >= len(queue) {
|
||||
continue
|
||||
}
|
||||
if best < 0 || newer(queue[positions[i]].Article, queues[best][positions[best]].Article) {
|
||||
if best < 0 || newer(orderArticle(queue[positions[i]]), orderArticle(queues[best][positions[best]])) {
|
||||
best = i
|
||||
}
|
||||
}
|
||||
@ -68,6 +68,12 @@ func mergeSourceCandidates(candidates []Candidate) []Candidate {
|
||||
}
|
||||
return out
|
||||
}
|
||||
func orderArticle(c Candidate) scraper.Article {
|
||||
if c.orderFrozen {
|
||||
return scraper.Article{PublishedAt: c.orderDate}
|
||||
}
|
||||
return c.Article
|
||||
}
|
||||
func newer(a, b scraper.Article) bool {
|
||||
if a.PublishedAt == nil {
|
||||
return false
|
||||
|
||||
Reference in New Issue
Block a user