feat(generation): select articles in three passes
This commit is contained in:
@ -78,6 +78,8 @@ type UseCase interface {
|
||||
Generate(context.Context, string) (Result, error)
|
||||
}
|
||||
type Dependencies struct {
|
||||
Decider MentionDecider
|
||||
Names MentionNameResolver
|
||||
Repository Repository
|
||||
SummaryResolver SummaryResolver
|
||||
LayaRanker LayaRanker
|
||||
@ -92,6 +94,9 @@ func NewUseCase(d Dependencies) UseCase {
|
||||
if d.LayaRanker != nil {
|
||||
d.Ranker = d.LayaRanker
|
||||
}
|
||||
if d.Decider == nil {
|
||||
d.Decider, _ = d.Ranker.(MentionDecider)
|
||||
}
|
||||
if d.Clock == nil {
|
||||
d.Clock = time.Now
|
||||
}
|
||||
@ -149,7 +154,7 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
if resolved.Summarizer == nil {
|
||||
return finish("failed", "summary_model_unavailable", "")
|
||||
}
|
||||
if u.Ranker == nil {
|
||||
if u.Decider == nil {
|
||||
return finish("failed", "laya_unavailable", "")
|
||||
}
|
||||
symbols := []string{}
|
||||
@ -183,6 +188,10 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
stat.FailureCode = "source_unavailable"
|
||||
partial = true
|
||||
} else {
|
||||
articles = recentArticles(articles)
|
||||
if len(articles) > stat.ArticleLimit {
|
||||
articles = articles[:stat.ArticleLimit]
|
||||
}
|
||||
for _, article := range articles {
|
||||
stat.Candidates++
|
||||
out.TotalCandidates++
|
||||
@ -206,35 +215,18 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
}
|
||||
return finish("no_results", "", "")
|
||||
}
|
||||
ranked, err := u.Ranker.Rank(ctx, input.RankingMode, input.Assets, candidates)
|
||||
selected, layaAccepted, err := u.selectThreePass(ctx, input, candidates)
|
||||
if err != nil {
|
||||
return finish("failed", "ranking_failed", "")
|
||||
return finish("failed", err.Error(), "")
|
||||
}
|
||||
originals := map[string]Candidate{}
|
||||
for _, c := range candidates {
|
||||
originals[c.ID] = c
|
||||
for source, n := range layaAccepted {
|
||||
out.SourceStats[stats[source]].LayaSelected = n
|
||||
out.LayaSelected += n
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
selected := []Candidate{}
|
||||
for _, c := range ranked {
|
||||
original, ok := originals[c.ID]
|
||||
if !ok || seen[c.ID] {
|
||||
return finish("failed", "ranking_invalid", "")
|
||||
}
|
||||
seen[c.ID] = true
|
||||
i := stats[original.SourceID]
|
||||
out.SourceStats[i].LayaSelected++
|
||||
out.LayaSelected++
|
||||
}
|
||||
for _, c := range ranked {
|
||||
c = originals[c.ID]
|
||||
i := stats[c.SourceID]
|
||||
if out.SourceStats[i].Selected >= out.SourceStats[i].ArticleLimit || len(selected) >= input.GlobalLimit {
|
||||
continue
|
||||
}
|
||||
selected = append(selected, c)
|
||||
out.SourceStats[i].Selected++
|
||||
for _, c := range selected {
|
||||
out.SourceStats[stats[c.SourceID]].Selected++
|
||||
}
|
||||
|
||||
out.Selected = len(selected)
|
||||
if len(selected) == 0 {
|
||||
return finish("no_results", "", "")
|
||||
|
||||
@ -140,7 +140,7 @@ func TestUseCaseIsolatesTwoUsersAndUsesOnlyEnabledSourcesAndUserInputs(t *testin
|
||||
}
|
||||
}
|
||||
|
||||
func TestUseCasePreservesLayaOrderThenAppliesPerSourceAndGlobalCaps(t *testing.T) {
|
||||
func TestUseCasePreservesRecentInputOrderWithSourcePoolsAndGlobalOutputCap(t *testing.T) {
|
||||
articles := []scraper.Article{
|
||||
{Title: "a1"}, {Title: "a2"}, {Title: "b1"}, {Title: "a3"}, {Title: "b2"},
|
||||
}
|
||||
@ -157,7 +157,7 @@ func TestUseCasePreservesLayaOrderThenAppliesPerSourceAndGlobalCaps(t *testing.T
|
||||
t.Fatalf("summary calls=%d, want 1", len(summarizer.articles))
|
||||
}
|
||||
got := candidateTitles(summarizer.articles[0])
|
||||
want := []string{"a2", "b1", "b2"}
|
||||
want := []string{"a1", "b1", "a3"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("rank order/caps got %v, want %v", got, want)
|
||||
}
|
||||
|
||||
@ -97,7 +97,7 @@ func TestGenerationInjectsLayaRankerAndSummaryProviderAsSeparatePorts(t *testing
|
||||
order := []string{}
|
||||
ranker := &ticket14LayaRanker{selectedTitle: "Market title B", order: &order}
|
||||
summary := &ticket14SummaryProvider{order: &order}
|
||||
repo := &ticket14Repository{input: UserInput{Language: "en", RankingMode: "title_content", GlobalLimit: 10, Assets: []models.UserAsset{{Name: "S&P 500", Symbol: "SPX", FIGI: &figi}}, Sources: []models.Source{{ID: "yahoo-row", Name: "Yahoo Finance", Type: "stocktwits", SourceKey: &key, Enabled: true, ArticleLimit: 10}}}}
|
||||
repo := &ticket14Repository{input: UserInput{Language: "en", RankingMode: "title_content", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "S&P 500", Symbol: "SPX", FIGI: &figi}}, Sources: []models.Source{{ID: "yahoo-row", Name: "Yahoo Finance", Type: "stocktwits", SourceKey: &key, Enabled: true, ArticleLimit: 10}}}}
|
||||
useCase := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{key: feed}, Ranker: ranker, Summarizer: summary, Clock: func() time.Time { return time.Unix(1, 0) }})
|
||||
result, err := useCase.Generate(context.Background(), "user-id")
|
||||
if err != nil {
|
||||
@ -136,7 +136,7 @@ func TestGenerationRunsTwoAccountsWithDistinctInjectedSummaryModels(t *testing.T
|
||||
for _, account := range accounts {
|
||||
t.Run(account.id, func(t *testing.T) {
|
||||
figi, key := "BBG000SPX001", models.SourceYahooFinance
|
||||
repo := &ticket14Repository{input: UserInput{Language: "en", RankingMode: "title", GlobalLimit: 5, Assets: []models.UserAsset{{Name: "S&P 500", Symbol: "SPX", FIGI: &figi}}, Sources: []models.Source{{ID: "yahoo-row", Type: "yahoo", SourceKey: &key, Enabled: true, ArticleLimit: 5}}}}
|
||||
repo := &ticket14Repository{input: UserInput{Language: "en", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "S&P 500", Symbol: "SPX", FIGI: &figi}}, Sources: []models.Source{{ID: "yahoo-row", Type: "yahoo", SourceKey: &key, Enabled: true, ArticleLimit: 5}}}}
|
||||
feed := &ticket14Feed{}
|
||||
ranker := &ticket14LayaRanker{selectedTitle: "Market title A"}
|
||||
selectedModel := &ticket14SummaryProvider{content: account.content}
|
||||
@ -171,7 +171,7 @@ func TestGenerationWithoutSelectedSummaryProviderFailsBeforeScrapeOrLaya(t *test
|
||||
figi, key := "BBG000SPX001", models.SourceYahooFinance
|
||||
feed := &ticket14Feed{}
|
||||
ranker := &ticket14LayaRanker{selectedTitle: "Market title A"}
|
||||
repo := &ticket14Repository{input: UserInput{Language: "en", RankingMode: "title", GlobalLimit: 10, Assets: []models.UserAsset{{Name: "S&P 500", Symbol: "SPX", FIGI: &figi}}, Sources: []models.Source{{ID: "yahoo-row", Type: "yahoo", SourceKey: &key, Enabled: true, ArticleLimit: 10}}}}
|
||||
repo := &ticket14Repository{input: UserInput{Language: "en", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "S&P 500", Symbol: "SPX", FIGI: &figi}}, Sources: []models.Source{{ID: "yahoo-row", Type: "yahoo", SourceKey: &key, Enabled: true, ArticleLimit: 10}}}}
|
||||
var result Result
|
||||
var err error
|
||||
panicked := false
|
||||
@ -215,7 +215,7 @@ func TestGenerationDoesNotSummarizeWhenLayaFailsOrReturnsInvalidSelectedIDs(t *t
|
||||
ranker := &ticket14LayaRanker{selectedTitle: "unknown"}
|
||||
tc.setup(ranker)
|
||||
summary := &ticket14SummaryProvider{}
|
||||
repo := &ticket14Repository{input: UserInput{Language: "en", RankingMode: "title_content", GlobalLimit: 10, Assets: []models.UserAsset{{Name: "S&P 500", Symbol: "SPX", FIGI: &figi}}, Sources: []models.Source{{ID: "yahoo-row", Type: "stocktwits", SourceKey: &key, Enabled: true, ArticleLimit: 10}}}}
|
||||
repo := &ticket14Repository{input: UserInput{Language: "en", RankingMode: "title_content", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "S&P 500", Symbol: "SPX", FIGI: &figi}}, Sources: []models.Source{{ID: "yahoo-row", Type: "stocktwits", SourceKey: &key, Enabled: true, ArticleLimit: 10}}}}
|
||||
result, err := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{key: feed}, Ranker: ranker, Summarizer: summary}).Generate(context.Background(), "user-id")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
@ -45,7 +45,7 @@ func TestTicket28GenerationAggregatesAllAssetsBeforeSelectionAndFailsClosed(t *t
|
||||
}
|
||||
results := []any{}
|
||||
for i := range body.States {
|
||||
score := []float64{0.2, 0.9}[i]
|
||||
score := []float64{0.9, 0.9}[i]
|
||||
if calls == 2 {
|
||||
score = []float64{0.8, 0.05}[i]
|
||||
}
|
||||
@ -53,9 +53,9 @@ func TestTicket28GenerationAggregatesAllAssetsBeforeSelectionAndFailsClosed(t *t
|
||||
if calls == 2 && failure == "truncated_long_article" {
|
||||
usage["truncated"] = true
|
||||
usage["state_tokens_dropped"] = 800
|
||||
usage["truncated_questions"] = []string{"relevance"}
|
||||
usage["truncated_questions"] = []string{"direct_mention"}
|
||||
}
|
||||
results = append(results, map[string]any{"answers": map[string]any{"relevance": map[string]any{"type": "score", "score": score, "answer_confidence": 0.99}}, "usage": usage})
|
||||
results = append(results, map[string]any{"answers": map[string]any{"direct_mention": map[string]any{"type": "noul", "noul": 1 - score, "answer_confidence": 0.99}}, "usage": usage})
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"results": results})
|
||||
}))
|
||||
@ -64,7 +64,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: 1}}}}
|
||||
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}}}}
|
||||
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 {
|
||||
|
||||
@ -83,7 +83,7 @@ func TestGenerationUsesLayaHTTPContractThenSelectedSummaryModel(t *testing.T) {
|
||||
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}}`)
|
||||
fmt.Fprint(w, `{"results":[{"answers":{"direct_mention":{"type":"noul","noul":0.1,"answer_confidence":0.91}},"usage":{"truncated":false,"state_tokens_dropped":0,"truncated_questions":[]}},{"answers":{"direct_mention":{"type":"noul","noul":0.9,"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})
|
||||
@ -96,9 +96,9 @@ func TestGenerationUsesLayaHTTPContractThenSelectedSummaryModel(t *testing.T) {
|
||||
summary := &ticket17HTTPSummary{}
|
||||
resolver := &ticket17HTTPResolver{provider: summary}
|
||||
repo := &ticket17HTTPRepo{input: generation.UserInput{
|
||||
SummaryModelID: &modelID, Language: "en", RankingMode: "title_content", GlobalLimit: 5,
|
||||
SummaryModelID: &modelID, Language: "en", RankingMode: "title_content", GlobalLimit: 1,
|
||||
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}},
|
||||
Sources: []models.Source{{ID: "source-yahoo", Type: "yahoo", SourceKey: &key, Enabled: true, ArticleLimit: 2}},
|
||||
}}
|
||||
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")
|
||||
@ -164,7 +164,7 @@ func TestGenerationLogsSanitizedLayaFailureCause(t *testing.T) {
|
||||
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}}}}
|
||||
repo := &ticket17HTTPRepo{input: generation.UserInput{SummaryModelID: &modelID, Language: "en", RankingMode: "title", GlobalLimit: 1, 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 {
|
||||
|
||||
@ -37,7 +37,7 @@ func TestTicket29CompactGroupsIntegrateBeforeSelectionAndFailureIsGlobal(t *test
|
||||
states++
|
||||
score := 0.8
|
||||
if state.Title == "first" {
|
||||
score = 0.2
|
||||
score = 0.9
|
||||
}
|
||||
if state.Title == "second" && state.Indices[len(state.Indices)-1]["symbol"] == "T29" {
|
||||
score = 0.05
|
||||
@ -47,9 +47,9 @@ func TestTicket29CompactGroupsIntegrateBeforeSelectionAndFailureIsGlobal(t *test
|
||||
usage["state_tokens_dropped"] = 1
|
||||
}
|
||||
if posts == 2 && failure == "question" {
|
||||
usage["truncated_questions"] = []string{"relevance"}
|
||||
usage["truncated_questions"] = []string{"direct_mention"}
|
||||
}
|
||||
results = append(results, map[string]any{"answers": map[string]any{"relevance": map[string]any{"type": "score", "score": score, "answer_confidence": 0.99}}, "usage": usage})
|
||||
results = append(results, map[string]any{"answers": map[string]any{"direct_mention": map[string]any{"type": "noul", "noul": 1 - score, "answer_confidence": 0.99}}, "usage": usage})
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"results": results})
|
||||
}))
|
||||
@ -62,7 +62,7 @@ func TestTicket29CompactGroupsIntegrateBeforeSelectionAndFailureIsGlobal(t *test
|
||||
model, key := "selected-model", models.SourceYahooFinance
|
||||
feed := &ticket17HTTPScraper{articles: []scraper.Article{{Title: "first", URL: "https://fixture.invalid/1"}, {Title: "second", URL: "https://fixture.invalid/2"}}}
|
||||
summary := &ticket17HTTPSummary{}
|
||||
repo := &ticket17HTTPRepo{input: generation.UserInput{SummaryModelID: &model, Language: "en", RankingMode: "title", GlobalLimit: 1, Assets: assets, Sources: []models.Source{{ID: "source", SourceKey: &key, Enabled: true, ArticleLimit: 1}}}}
|
||||
repo := &ticket17HTTPRepo{input: generation.UserInput{SummaryModelID: &model, Language: "en", RankingMode: "title", GlobalLimit: 1, Assets: assets, 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 || posts != 2 || feed.calls != 1 {
|
||||
|
||||
21
backend/internal/generation/mention_fakes_test.go
Normal file
21
backend/internal/generation/mention_fakes_test.go
Normal file
@ -0,0 +1,21 @@
|
||||
package generation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
)
|
||||
|
||||
// Historical fixture selectors now implement the binary mention port. Their
|
||||
// returned subset is the yes decision; their ordering cannot change chronology.
|
||||
func (r *contractRanker) DecideMentions(c context.Context, m, p string, a []models.UserAsset, v []Candidate) ([]Candidate, error) {
|
||||
return r.Rank(c, m, a, v)
|
||||
}
|
||||
func (r *ticket14LayaRanker) DecideMentions(c context.Context, m, p string, a []models.UserAsset, v []Candidate) ([]Candidate, error) {
|
||||
return r.Rank(c, m, a, v)
|
||||
}
|
||||
func (r ticket14DuplicateRanker) DecideMentions(c context.Context, m, p string, a []models.UserAsset, v []Candidate) ([]Candidate, error) {
|
||||
return r.Rank(c, m, a, v)
|
||||
}
|
||||
func (r *ticket4AssetRecorder) DecideMentions(c context.Context, m, p string, a []models.UserAsset, v []Candidate) ([]Candidate, error) {
|
||||
return r.Rank(c, m, a, v)
|
||||
}
|
||||
197
backend/internal/generation/selection.go
Normal file
197
backend/internal/generation/selection.go
Normal file
@ -0,0 +1,197 @@
|
||||
package generation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"golang.org/x/text/unicode/norm"
|
||||
"sort"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
const MentionDirect = "direct"
|
||||
const MentionIndirect = "indirect"
|
||||
const mentionBatchSize = 64
|
||||
|
||||
type MentionDecider interface {
|
||||
DecideMentions(context.Context, string, string, []models.UserAsset, []Candidate) ([]Candidate, error)
|
||||
}
|
||||
type MentionNameResolver interface {
|
||||
MentionNames(string) ([]string, error)
|
||||
}
|
||||
|
||||
// Source-level ordering is decided on the whole received pool, before N.
|
||||
// A complete dated source is sorted by publication date. If any date is absent,
|
||||
// receipt order is authoritative for the entire source (including mixed RSS).
|
||||
func recentArticles(articles []scraper.Article) []scraper.Article {
|
||||
out := append([]scraper.Article(nil), articles...)
|
||||
for _, article := range out {
|
||||
if article.PublishedAt == nil {
|
||||
return out
|
||||
}
|
||||
}
|
||||
sort.SliceStable(out, func(i, j int) bool { return newer(out[i], out[j]) })
|
||||
return out
|
||||
}
|
||||
|
||||
// Merge ordered source queues without reordering a source. Compare only the
|
||||
// currently available heads; equal/unknown heads retain source arrival priority.
|
||||
// This is a deterministic merge, not a conditional non-transitive sort.
|
||||
func mergeSourceCandidates(candidates []Candidate) []Candidate {
|
||||
queues := [][]Candidate{}
|
||||
sources := map[string]int{}
|
||||
for _, candidate := range candidates {
|
||||
i, ok := sources[candidate.SourceID]
|
||||
if !ok {
|
||||
i = len(queues)
|
||||
sources[candidate.SourceID] = i
|
||||
queues = append(queues, nil)
|
||||
}
|
||||
queues[i] = append(queues[i], candidate)
|
||||
}
|
||||
positions := make([]int, len(queues))
|
||||
out := make([]Candidate, 0, len(candidates))
|
||||
for len(out) < len(candidates) {
|
||||
best := -1
|
||||
for i, queue := range queues {
|
||||
if positions[i] >= len(queue) {
|
||||
continue
|
||||
}
|
||||
if best < 0 || newer(queue[positions[i]].Article, queues[best][positions[best]].Article) {
|
||||
best = i
|
||||
}
|
||||
}
|
||||
out = append(out, queues[best][positions[best]])
|
||||
positions[best]++
|
||||
}
|
||||
return out
|
||||
}
|
||||
func newer(a, b scraper.Article) bool {
|
||||
if a.PublishedAt == nil {
|
||||
return false
|
||||
}
|
||||
if b.PublishedAt == nil {
|
||||
return true
|
||||
}
|
||||
return a.PublishedAt.After(*b.PublishedAt)
|
||||
}
|
||||
func mentionText(s string) string {
|
||||
var b strings.Builder
|
||||
for _, r := range norm.NFKD.String(strings.ToLower(s)) {
|
||||
switch {
|
||||
case unicode.Is(unicode.Mn, r):
|
||||
continue
|
||||
case unicode.IsLetter(r) || unicode.IsNumber(r) || unicode.IsSymbol(r):
|
||||
b.WriteRune(r)
|
||||
case r == '.' || r == '\'' || r == '’':
|
||||
continue
|
||||
default:
|
||||
b.WriteByte(' ')
|
||||
}
|
||||
}
|
||||
return " " + strings.Join(strings.Fields(b.String()), " ") + " "
|
||||
}
|
||||
func (u *useCase) selectThreePass(ctx context.Context, input UserInput, candidates []Candidate) ([]Candidate, map[string]int, error) {
|
||||
if budget, ok := u.Decider.(interface {
|
||||
WithSelectionBudget(context.Context) (context.Context, context.CancelFunc)
|
||||
}); ok {
|
||||
var cancel context.CancelFunc
|
||||
ctx, cancel = budget.WithSelectionBudget(ctx)
|
||||
defer cancel()
|
||||
}
|
||||
names := []string{}
|
||||
for _, a := range input.Assets {
|
||||
terms := []string{a.Name}
|
||||
if a.CompanyID != nil && u.Names != nil {
|
||||
var err error
|
||||
terms, err = u.Names.MentionNames(*a.CompanyID)
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("ranking_unavailable")
|
||||
}
|
||||
}
|
||||
for _, term := range terms {
|
||||
normalized := mentionText(term)
|
||||
if normalized != " " {
|
||||
names = append(names, normalized)
|
||||
}
|
||||
}
|
||||
}
|
||||
ordered := mergeSourceCandidates(candidates)
|
||||
selected := []Candidate{}
|
||||
laya := map[string]int{}
|
||||
remaining := []Candidate{}
|
||||
accept := func(batch []Candidate) {
|
||||
// Incoming batches follow the source-aware ordering. Trim only this batch's last accepts;
|
||||
// previously selected higher-priority passes/batches are never displaced.
|
||||
for _, c := range batch {
|
||||
if len(selected) >= input.GlobalLimit {
|
||||
break
|
||||
}
|
||||
selected = append(selected, c)
|
||||
}
|
||||
}
|
||||
for _, c := range ordered {
|
||||
text := c.Article.Title
|
||||
if input.RankingMode == "title_content" {
|
||||
text += "\n" + c.Article.Content
|
||||
}
|
||||
normalized := mentionText(text)
|
||||
matched := false
|
||||
for _, name := range names {
|
||||
if strings.Contains(normalized, name) {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if matched {
|
||||
accept([]Candidate{c})
|
||||
} else {
|
||||
remaining = append(remaining, c)
|
||||
}
|
||||
if len(selected) >= input.GlobalLimit {
|
||||
return selected, laya, nil
|
||||
}
|
||||
}
|
||||
for _, pass := range []string{MentionDirect, MentionIndirect} {
|
||||
next := []Candidate{}
|
||||
for start := 0; start < len(remaining); start += mentionBatchSize {
|
||||
end := start + mentionBatchSize
|
||||
if end > len(remaining) {
|
||||
end = len(remaining)
|
||||
}
|
||||
batch := remaining[start:end]
|
||||
decisions, err := u.Decider.DecideMentions(ctx, input.RankingMode, pass, input.Assets, append([]Candidate(nil), batch...))
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("ranking_failed")
|
||||
}
|
||||
originals := map[string]Candidate{}
|
||||
for _, c := range batch {
|
||||
originals[c.ID] = c
|
||||
}
|
||||
yes := map[string]bool{}
|
||||
for _, c := range decisions {
|
||||
if _, ok := originals[c.ID]; !ok || yes[c.ID] {
|
||||
return nil, nil, errors.New("ranking_invalid")
|
||||
}
|
||||
yes[c.ID] = true
|
||||
}
|
||||
accepted := []Candidate{}
|
||||
for _, c := range batch {
|
||||
if yes[c.ID] {
|
||||
accepted = append(accepted, c)
|
||||
laya[c.SourceID]++
|
||||
} else {
|
||||
next = append(next, c)
|
||||
}
|
||||
}
|
||||
accept(accepted)
|
||||
if len(selected) >= input.GlobalLimit {
|
||||
return selected, laya, nil
|
||||
}
|
||||
}
|
||||
remaining = next
|
||||
}
|
||||
return selected, laya, nil
|
||||
}
|
||||
@ -0,0 +1,78 @@
|
||||
package generation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func reviewDate(title string, hour int) scraper.Article {
|
||||
d := time.Date(2026, 1, 1, hour, 0, 0, 0, time.UTC)
|
||||
return scraper.Article{Title: title, PublishedAt: &d}
|
||||
}
|
||||
func TestTicket34MixedSourceUsesReceiptOrderBeforeInputLimit(t *testing.T) {
|
||||
for _, articles := range [][]scraper.Article{
|
||||
{{Title: "first-undated"}, reviewDate("second-old", 1), reviewDate("third-new", 9)},
|
||||
{reviewDate("first-old", 1), reviewDate("second-new", 9), {Title: "third-undated"}},
|
||||
} {
|
||||
ordered := recentArticles(articles)
|
||||
got := []string{ordered[0].Title, ordered[1].Title}
|
||||
want := []string{articles[0].Title, articles[1].Title}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("mixed source reordered before N: got %v want %v", got, want)
|
||||
}
|
||||
sum := &contractSummarizer{}
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 2, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
|
||||
result, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: articles}}}).Generate(context.Background(), "u")
|
||||
if err != nil || result.Outcome.TotalCandidates != 2 || len(sum.articles) != 1 || !reflect.DeepEqual(candidateTitles(sum.articles[0]), want) {
|
||||
t.Fatal("source mode must be chosen before N and preserved through passes", result.Outcome, err)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
func TestTicket34MergePreservesEachSourceOrderIncludingMixedDates(t *testing.T) {
|
||||
gate := &allYesMention{}
|
||||
sum := &contractSummarizer{}
|
||||
a := &contractScraper{articles: []scraper.Article{reviewDate("a-old", 1), {Title: "a-undated"}, reviewDate("a-new", 9)}}
|
||||
b := &contractScraper{articles: []scraper.Article{reviewDate("b-new", 10), reviewDate("b-mid", 5)}}
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 5, Sources: []models.Source{{ID: "a", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 3}, {ID: "b", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
|
||||
r, err := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: a, models.SourceBloomberg: b}}).Generate(context.Background(), "u")
|
||||
if err != nil || r.Summary == nil {
|
||||
t.Fatal(r, err)
|
||||
}
|
||||
got := candidateTitles(sum.articles[0])
|
||||
want := []string{"b-new", "b-mid", "a-old", "a-undated", "a-new"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("merge violated source order: got %v want %v", got, want)
|
||||
}
|
||||
}
|
||||
func TestTicket34SelectionHasOnlyGlobalOutputLimit(t *testing.T) {
|
||||
// The selector receives an already bounded pool. No independent per-source
|
||||
// output quota should be necessary or consulted at this stage.
|
||||
gate := &allYesMention{}
|
||||
uc := &useCase{Dependencies: Dependencies{Decider: gate}}
|
||||
pool := []Candidate{{ID: "a", SourceID: "s", Article: reviewDate("a", 3)}, {ID: "b", SourceID: "s", Article: reviewDate("b", 2)}, {ID: "c", SourceID: "s", Article: reviewDate("c", 1)}}
|
||||
selected, _, err := uc.selectThreePass(context.Background(), UserInput{RankingMode: "title", GlobalLimit: 2}, pool)
|
||||
if err != nil || len(selected) != 2 {
|
||||
t.Fatalf("selector reapplied a source output quota: %d %v", len(selected), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTicket34FullyDatedSourcesMergeChronologicallyWithStableTies(t *testing.T) {
|
||||
a := recentArticles([]scraper.Article{reviewDate("a-old", 1), reviewDate("a-new", 3)})
|
||||
b := recentArticles([]scraper.Article{reviewDate("b-mid", 2), reviewDate("b-new", 3)})
|
||||
pool := []Candidate{}
|
||||
for _, article := range a {
|
||||
pool = append(pool, Candidate{SourceID: "a", Article: article})
|
||||
}
|
||||
for _, article := range b {
|
||||
pool = append(pool, Candidate{SourceID: "b", Article: article})
|
||||
}
|
||||
got := candidateTitles(mergeSourceCandidates(pool))
|
||||
if !reflect.DeepEqual(got, []string{"a-new", "b-new", "b-mid", "a-old"}) {
|
||||
t.Fatal(got)
|
||||
}
|
||||
}
|
||||
131
backend/internal/generation/three_pass_ticket34_test.go
Normal file
131
backend/internal/generation/three_pass_ticket34_test.go
Normal file
@ -0,0 +1,131 @@
|
||||
package generation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type mentionFixture struct {
|
||||
calls []string
|
||||
batches [][]string
|
||||
yes map[string]map[string]bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *mentionFixture) DecideMentions(_ context.Context, mode, pass string, _ []models.UserAsset, c []Candidate) ([]Candidate, error) {
|
||||
f.calls = append(f.calls, pass)
|
||||
f.batches = append(f.batches, candidateTitles(c))
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
}
|
||||
out := []Candidate{}
|
||||
for _, v := range c {
|
||||
if f.yes[pass][v.Article.Title] {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func TestTicket34ThreePassesInputPoolPriorityAndLastBatchTrim(t *testing.T) {
|
||||
dated := func(title string, h int) scraper.Article {
|
||||
d := time.Date(2026, 1, 1, h, 0, 0, 0, time.UTC)
|
||||
return scraper.Article{Title: title, PublishedAt: &d}
|
||||
}
|
||||
a := &contractScraper{articles: []scraper.Article{dated("Acme Holdings", 1), dated("a9", 9), dated("a8", 8), dated("a7", 7), dated("excluded", 0)}}
|
||||
b := &contractScraper{articles: []scraper.Article{{Title: "b1"}, {Title: "b2"}, {Title: "b3"}, {Title: "excluded-b"}}}
|
||||
gate := &mentionFixture{yes: map[string]map[string]bool{"direct": {"a9": true, "b1": true}, "indirect": {"a8": true, "b2": true, "b3": true}}}
|
||||
sum := &contractSummarizer{}
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 4, Assets: []models.UserAsset{{Name: "Acme Holdings"}}, Sources: []models.Source{{ID: "a", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 4}, {ID: "b", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 3}}}}, saved: map[string][]GenerationRecord{}}
|
||||
uc := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: a, models.SourceBloomberg: b}})
|
||||
result, err := uc.Generate(context.Background(), "u")
|
||||
if err != nil || result.Summary == nil {
|
||||
t.Fatalf("%+v %v", result.Outcome, err)
|
||||
}
|
||||
if !reflect.DeepEqual(candidateTitles(sum.articles[0]), []string{"Acme Holdings", "a9", "b1", "a8"}) {
|
||||
t.Fatal(candidateTitles(sum.articles[0]))
|
||||
}
|
||||
if !reflect.DeepEqual(gate.calls, []string{"direct", "indirect"}) || !reflect.DeepEqual(gate.batches, [][]string{{"a9", "a8", "a7", "b1", "b2", "b3"}, {"a8", "a7", "b2", "b3"}}) {
|
||||
t.Fatal(gate.calls, gate.batches)
|
||||
}
|
||||
if result.Outcome.TotalCandidates != 7 || result.Outcome.SourceStats[0].Candidates != 4 || result.Outcome.SourceStats[1].Candidates != 3 || result.Outcome.SourceStats[0].Selected != 3 || result.Outcome.SourceStats[1].Selected != 1 {
|
||||
t.Fatal(result.Outcome)
|
||||
}
|
||||
}
|
||||
func TestTicket34NoPartialSummaryOnMentionFailure(t *testing.T) {
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 5, Assets: []models.UserAsset{{Name: "Acme"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
|
||||
sum := &contractSummarizer{}
|
||||
gate := &mentionFixture{err: errors.New("private failure")}
|
||||
uc := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: []scraper.Article{{Title: "Acme"}, {Title: "unmatched"}}}}})
|
||||
r, err := uc.Generate(context.Background(), "u")
|
||||
if err != nil || r.Summary != nil || r.Outcome.Status != "failed" || len(sum.articles) != 0 {
|
||||
t.Fatal(r, err)
|
||||
}
|
||||
}
|
||||
|
||||
type allYesMention struct {
|
||||
passes []string
|
||||
sizes []int
|
||||
}
|
||||
|
||||
func (f *allYesMention) DecideMentions(_ context.Context, _, pass string, _ []models.UserAsset, c []Candidate) ([]Candidate, error) {
|
||||
f.passes = append(f.passes, pass)
|
||||
f.sizes = append(f.sizes, len(c))
|
||||
return c, nil
|
||||
}
|
||||
func TestTicket34StopsAtReachingBatchWithoutReplacingEarlierPass(t *testing.T) {
|
||||
gate := &allYesMention{}
|
||||
sum := &contractSummarizer{}
|
||||
newest := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
|
||||
articles := []scraper.Article{}
|
||||
for i := 0; i < 130; i++ {
|
||||
d := newest.Add(-time.Duration(i) * time.Minute)
|
||||
articles = append(articles, scraper.Article{Title: fmt.Sprintf("article-%03d", i), PublishedAt: &d})
|
||||
}
|
||||
old := newest.Add(-1000 * time.Hour)
|
||||
articles = append(articles, scraper.Article{Title: "Acme Holdings", PublishedAt: &old})
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 66, Assets: []models.UserAsset{{Name: "Acme Holdings"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 200}}}}, saved: map[string][]GenerationRecord{}}
|
||||
uc := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: articles}}})
|
||||
r, err := uc.Generate(context.Background(), "u")
|
||||
if err != nil || r.Outcome.Selected != 66 || !reflect.DeepEqual(gate.passes, []string{"direct", "direct"}) || !reflect.DeepEqual(gate.sizes, []int{64, 64}) {
|
||||
t.Fatal(r.Outcome, gate.passes, gate.sizes, err)
|
||||
}
|
||||
got := candidateTitles(sum.articles[0])
|
||||
if got[0] != "Acme Holdings" || got[65] != "article-064" {
|
||||
t.Fatal("priority/trim changed", got[0], got[65])
|
||||
}
|
||||
}
|
||||
|
||||
type fixtureNames struct{}
|
||||
|
||||
func (fixtureNames) MentionNames(id string) ([]string, error) {
|
||||
if id != "resolved" {
|
||||
return nil, errors.New("unknown")
|
||||
}
|
||||
return []string{"Intel Corporation", "intel"}, nil
|
||||
}
|
||||
func TestTicket34DeterministicMentionUsesResolvedNamesAliasesAndModeOnly(t *testing.T) {
|
||||
for _, mode := range []string{"title", "title_content"} {
|
||||
id := "resolved"
|
||||
gate := &mentionFixture{yes: map[string]map[string]bool{}}
|
||||
sum := &contractSummarizer{}
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: mode, GlobalLimit: 1, Assets: []models.UserAsset{{Name: "untrusted stored spelling", Symbol: "INTC", CompanyID: &id}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
|
||||
feed := &contractScraper{articles: []scraper.Article{{Title: "Intelligence and INTC", Content: "Intel invests."}}}
|
||||
r, err := NewUseCase(Dependencies{Repository: repo, Decider: gate, Names: fixtureNames{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feed}}).Generate(context.Background(), "u")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mode == "title_content" {
|
||||
if r.Summary == nil || len(gate.calls) != 0 {
|
||||
t.Fatal("body alias not accepted in pass 1")
|
||||
}
|
||||
} else if r.Summary != nil || !reflect.DeepEqual(gate.calls, []string{"direct", "indirect"}) {
|
||||
t.Fatal("substring/symbol incorrectly matched", gate.calls)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user