feat(generation): select articles in three passes

This commit is contained in:
2026-11-24 00:38:02 +01:00
parent d22f84529f
commit 8022ee0547
27 changed files with 916 additions and 68 deletions

View 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
}