feat(ranking): add safe article ranking and limits

Rank candidate articles using the selected preference and enforce global and per-source article limits.

Refs #6

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 19:54:17 +01:00
parent 50bde816ed
commit a4d63015d4
13 changed files with 918 additions and 138 deletions

View File

@ -0,0 +1,175 @@
package ai
import (
"context"
"database/sql"
"database/sql/driver"
"errors"
"io"
"reflect"
"strconv"
"strings"
"testing"
"github.com/tradarr/backend/internal/models"
)
type fixedSettingsConnector struct{ batchSize string }
func (c fixedSettingsConnector) Connect(context.Context) (driver.Conn, error) {
return fixedSettingsConn{batchSize: c.batchSize}, nil
}
func (c fixedSettingsConnector) Driver() driver.Driver { return fixedSettingsDriver{} }
type fixedSettingsDriver struct{}
func (fixedSettingsDriver) Open(string) (driver.Conn, error) { return nil, errors.New("use connector") }
type fixedSettingsConn struct{ batchSize string }
func (c fixedSettingsConn) Prepare(string) (driver.Stmt, error) {
return nil, errors.New("unsupported")
}
func (fixedSettingsConn) Close() error { return nil }
func (fixedSettingsConn) Begin() (driver.Tx, error) { return nil, errors.New("unsupported") }
func (c fixedSettingsConn) QueryContext(_ context.Context, _ string, _ []driver.NamedValue) (driver.Rows, error) {
return &fixedValueRows{value: c.batchSize}, nil
}
type fixedValueRows struct {
value string
done bool
}
func (*fixedValueRows) Columns() []string { return []string{"value"} }
func (*fixedValueRows) Close() error { return nil }
func (r *fixedValueRows) Next(dest []driver.Value) error {
if r.done {
return io.EOF
}
dest[0] = r.value
r.done = true
return nil
}
type rankingFakeProvider struct {
responses []string
prompts []string
}
// ApplyArticleCaps is the pure seam for applying per-source caps before the
// generation-wide cap to an already ranked sequence.
type articleCapper interface {
ApplyArticleCaps([]models.Article, map[string]int, int) []models.Article
}
func (*rankingFakeProvider) Name() string { return "fake" }
func (p *rankingFakeProvider) Summarize(_ context.Context, prompt string, _ GenOptions) (string, error) {
p.prompts = append(p.prompts, prompt)
if len(p.prompts) > len(p.responses) {
return "", errors.New("unexpected extra Laya batch")
}
return p.responses[len(p.prompts)-1], nil
}
func (*rankingFakeProvider) ListModels(context.Context) ([]string, error) { return nil, nil }
func rankingTestPipeline(t *testing.T, batchSize int) *Pipeline {
t.Helper()
db := sql.OpenDB(fixedSettingsConnector{batchSize: strconv.Itoa(batchSize)})
t.Cleanup(func() { _ = db.Close() })
return NewPipeline(models.NewRepository(db), nil)
}
func rankingArticles(ids ...string) []models.Article {
articles := make([]models.Article, len(ids))
for i, id := range ids {
articles[i] = models.Article{ID: id, Title: "Title " + id, SourceName: "Source"}
}
return articles
}
func articleIDs(articles []models.Article) []string {
ids := make([]string, len(articles))
for i, article := range articles {
ids[i] = article.ID
}
return ids
}
func TestRankedArticleParserRejectsNonJSONText(t *testing.T) {
if got := parseIndexArray("Laya says: [0, 1]", 2); len(got) != 0 {
t.Fatalf("parser accepted text outside strict JSON: %v", got)
}
}
func TestLayaSelectionParsesRankedArticleIDs(t *testing.T) {
pipeline := rankingTestPipeline(t, 2)
provider := &rankingFakeProvider{responses: []string{`{"ranked_article_ids":["a1","a2"]}`}}
got := pipeline.filterByRelevance(context.Background(), provider, []string{"S&P 500"}, rankingArticles("a1", "a2"), 10)
if !reflect.DeepEqual(articleIDs(got), []string{"a1", "a2"}) {
t.Fatalf("selected ids=%v, want ranked_article_ids [a1 a2]", articleIDs(got))
}
if len(provider.prompts) != 1 {
t.Fatalf("provider calls=%d, want 1", len(provider.prompts))
}
}
func TestRankingProcessesAllBatchesAndInterleavesLocalRanksStably(t *testing.T) {
pipeline := rankingTestPipeline(t, 2)
provider := &rankingFakeProvider{responses: []string{`{"ranked_article_ids":["b","a"]}`, `{"ranked_article_ids":["d","c"]}`, `{"ranked_article_ids":["f","e"]}`}}
got := pipeline.filterByRelevance(context.Background(), provider, []string{"S&P 500"}, rankingArticles("a", "b", "c", "d", "e", "f"), 10)
if len(provider.prompts) != 3 {
t.Fatalf("processed %d Laya batches, want all 3", len(provider.prompts))
}
want := []string{"b", "d", "f", "a", "c", "e"}
if !reflect.DeepEqual(articleIDs(got), want) {
t.Fatalf("stable rank interleave=%v, want %v", articleIDs(got), want)
}
}
func TestBatchProcessingDoesNotStopOrTruncateAfterEnoughLocalResults(t *testing.T) {
pipeline := rankingTestPipeline(t, 2)
provider := &rankingFakeProvider{responses: []string{`{"ranked_article_ids":["a","b"]}`, `{"ranked_article_ids":["c","d"]}`, `{"ranked_article_ids":["e","f"]}`}}
got := pipeline.filterByRelevance(context.Background(), provider, nil, rankingArticles("a", "b", "c", "d", "e", "f"), 1)
if len(provider.prompts) != 3 {
t.Fatalf("processed %d batches, want all 3 even after global target is reached", len(provider.prompts))
}
if len(got) != 6 {
t.Fatalf("ranking truncated candidates before source/global caps: got %d, want 6", len(got))
}
}
func TestSourceCapsAreAppliedBeforeGlobalCapWithoutReordering(t *testing.T) {
capper, ok := any(&Pipeline{}).(articleCapper)
if !ok {
t.Fatal("Pipeline.ApplyArticleCaps pure ranking cap seam is not implemented")
}
ranked := []models.Article{
{ID: "a1", SourceID: "source-a"},
{ID: "a2", SourceID: "source-a"},
{ID: "b1", SourceID: "source-b"},
{ID: "b2", SourceID: "source-b"},
{ID: "c1", SourceID: "source-c"},
}
got := capper.ApplyArticleCaps(ranked, map[string]int{"source-a": 1, "source-b": 2, "source-c": 2}, 3)
want := []string{"a1", "b1", "b2"}
if !reflect.DeepEqual(articleIDs(got), want) {
t.Fatalf("caps result=%v, want source caps then global cap preserving rank order %v", articleIDs(got), want)
}
}
func TestTitleContentUsesTitleFallbackWhenContentUnavailable(t *testing.T) {
prompt := buildFilterBatchPrompt([]string{"S&P 500"}, []models.Article{{ID: "a1", Title: "Market shock", Content: ""}})
if !containsAll(prompt, "Market shock", "contenu indisponible", "titre seul") {
t.Fatalf("title_content fallback not made explicit in Laya prompt: %q", prompt)
}
}
func containsAll(value string, fragments ...string) bool {
for _, fragment := range fragments {
if !strings.Contains(strings.ToLower(value), strings.ToLower(fragment)) {
return false
}
}
return true
}