feat(summary): send complete articles within user budget (#39)
This commit is contained in:
@ -24,6 +24,7 @@ func (f *contentFeed) Enrich(_ context.Context, a []scraper.Article) ([]scraper.
|
||||
}
|
||||
out := append([]scraper.Article(nil), a...)
|
||||
for i := range out {
|
||||
out[i].ContentState = scraper.ContentComplete
|
||||
out[i].Content = "synthetic editorial paragraph"
|
||||
d := time.Date(2026, 1, 1, i+1, 0, 0, 0, time.UTC)
|
||||
out[i].PublishedAt = &d
|
||||
@ -45,10 +46,16 @@ func TestTicket36EnrichmentAfterPoolAndNoReordering(t *testing.T) {
|
||||
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 mode == "failure" {
|
||||
if err != nil || r.Summary != nil || r.Outcome.FailureCode != "no_complete_content" || feed.calls != 1 || r.Outcome.ContentFallbacks != 2 {
|
||||
t.Fatal("incomplete enrichment must stop before summary")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || r.Summary == nil {
|
||||
t.Fatal(err, r.Outcome)
|
||||
}
|
||||
if mode == "title_content" {
|
||||
if mode == "title_content" || mode == "other_source" {
|
||||
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)
|
||||
}
|
||||
@ -70,7 +77,7 @@ 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}}}
|
||||
other := &contractScraper{articles: []scraper.Article{{Title: "Fixture Yahoo", ContentState: scraper.ContentComplete, Content: "synthetic full Yahoo body", 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")
|
||||
|
||||
56
backend/internal/generation/full_content_ticket39_test.go
Normal file
56
backend/internal/generation/full_content_ticket39_test.go
Normal file
@ -0,0 +1,56 @@
|
||||
package generation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTicket39NoContentIsExplicit(t *testing.T) {
|
||||
key := models.SourceYahooFinance
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 2, Assets: []models.UserAsset{{Name: "Fixture"}}, Sources: []models.Source{{ID: "s", SourceKey: &key, 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{key: &contractScraper{articles: []scraper.Article{{Title: "Fixture", Content: "RSS teaser", ContentTruncated: true}}}}}).Generate(context.Background(), "u")
|
||||
if err != nil || r.Summary != nil || r.Outcome.FailureCode != "no_complete_content" || r.Outcome.PromptBudget.RequestedTokens != 250000 {
|
||||
t.Fatalf("incomplete body was selected: %+v %v", r.Outcome, err)
|
||||
}
|
||||
}
|
||||
|
||||
type ticket39ContentFeed struct{ calls, size int }
|
||||
|
||||
func (*ticket39ContentFeed) Name() string { return "fixture" }
|
||||
func (*ticket39ContentFeed) Scrape(context.Context, []string) ([]scraper.Article, error) {
|
||||
return []scraper.Article{{Title: "Followed fixture one", URL: "https://fixture.invalid/one"}, {Title: "Followed fixture two", URL: "https://fixture.invalid/two"}, {Title: "Followed fixture three", URL: "https://fixture.invalid/three"}, {Title: "outside source limit"}}, nil
|
||||
}
|
||||
func (f *ticket39ContentFeed) Enrich(_ context.Context, a []scraper.Article) ([]scraper.Article, error) {
|
||||
f.calls++
|
||||
f.size = len(a)
|
||||
out := append([]scraper.Article(nil), a...)
|
||||
for i := range out {
|
||||
switch i {
|
||||
case 0:
|
||||
out[i].Content = "Entire editorial body."
|
||||
out[i].ContentState = scraper.ContentComplete
|
||||
case 1:
|
||||
out[i].Content = "Partial teaser."
|
||||
out[i].ContentState = scraper.ContentIncomplete
|
||||
default:
|
||||
out[i].ContentState = scraper.ContentUnavailable
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func TestTicket39AllRuntimeSourcesEnrichAfterLimitAndOnlyCompleteSelectable(t *testing.T) {
|
||||
for _, key := range []string{models.SourceBloomberg, models.SourceYahooFinance, models.SourceCNBCBusiness} {
|
||||
t.Run(key, func(t *testing.T) {
|
||||
feed := &ticket39ContentFeed{}
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 3, Assets: []models.UserAsset{{Name: "Followed fixture"}}, Sources: []models.Source{{ID: "s", SourceKey: &key, Enabled: true, ArticleLimit: 3}}}}, saved: map[string][]GenerationRecord{}}
|
||||
sum := &contractSummarizer{}
|
||||
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{key: feed}}).Generate(context.Background(), "u")
|
||||
if err != nil || feed.calls != 1 || feed.size != 3 || r.Summary == nil || r.Outcome.Status != "partial" || r.Outcome.ContentComplete != 1 || r.Outcome.ContentIncomplete != 1 || r.Outcome.ContentUnavailable != 1 || r.Outcome.Selected != 1 || sum.articles[0][0].Article.Content != "Entire editorial body." || sum.articles[0][0].Article.Source != key {
|
||||
t.Fatalf("incorrect full-content flow %+v %v", r.Outcome, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -10,14 +10,17 @@ import (
|
||||
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"github.com/tradarr/backend/internal/summarybudget"
|
||||
)
|
||||
|
||||
type UserInput struct {
|
||||
SummaryModelID *string
|
||||
Language, RankingMode string
|
||||
GlobalLimit int
|
||||
Assets []models.UserAsset
|
||||
Sources []models.Source
|
||||
SummaryContext string
|
||||
SummaryPromptTokenBudget int
|
||||
SummaryModelID *string
|
||||
Language, RankingMode string
|
||||
GlobalLimit int
|
||||
Assets []models.UserAsset
|
||||
Sources []models.Source
|
||||
}
|
||||
type Candidate struct {
|
||||
ID, SourceID string
|
||||
@ -26,29 +29,38 @@ type Candidate struct {
|
||||
orderFrozen bool
|
||||
}
|
||||
type SourceStat struct {
|
||||
SourceID string `json:"source_id"`
|
||||
SourceType string `json:"source_type"`
|
||||
Status string `json:"status"`
|
||||
Candidates int `json:"candidates"`
|
||||
LayaSelected int `json:"laya_selected"`
|
||||
Selected int `json:"selected"`
|
||||
ArticleLimit int `json:"article_limit"`
|
||||
ContentFallbacks int `json:"content_fallbacks"`
|
||||
FailureCode string `json:"failure_code,omitempty"`
|
||||
ContentComplete int `json:"content_complete"`
|
||||
ContentIncomplete int `json:"content_incomplete"`
|
||||
ContentUnavailable int `json:"content_unavailable"`
|
||||
DatesAvailable int `json:"dates_available"`
|
||||
SourceID string `json:"source_id"`
|
||||
SourceType string `json:"source_type"`
|
||||
Status string `json:"status"`
|
||||
Candidates int `json:"candidates"`
|
||||
LayaSelected int `json:"laya_selected"`
|
||||
Selected int `json:"selected"`
|
||||
ArticleLimit int `json:"article_limit"`
|
||||
ContentFallbacks int `json:"content_fallbacks"`
|
||||
FailureCode string `json:"failure_code,omitempty"`
|
||||
}
|
||||
type GenerationOutcome struct {
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Language string `json:"language"`
|
||||
RankingMode string `json:"ranking_mode"`
|
||||
TotalCandidates int `json:"total_candidates"`
|
||||
ContentFallbacks int `json:"content_fallbacks"`
|
||||
LayaSelected int `json:"laya_selected"`
|
||||
Selected int `json:"selected"`
|
||||
GlobalLimit int `json:"global_limit"`
|
||||
SourceStats []SourceStat `json:"source_stats"`
|
||||
FailureCode string `json:"failure_code,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ContentComplete int `json:"content_complete"`
|
||||
ContentIncomplete int `json:"content_incomplete"`
|
||||
ContentUnavailable int `json:"content_unavailable"`
|
||||
DatesAvailable int `json:"dates_available"`
|
||||
PromptBudget summarybudget.Usage `json:"prompt_budget"`
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Language string `json:"language"`
|
||||
RankingMode string `json:"ranking_mode"`
|
||||
TotalCandidates int `json:"total_candidates"`
|
||||
ContentFallbacks int `json:"content_fallbacks"`
|
||||
LayaSelected int `json:"laya_selected"`
|
||||
Selected int `json:"selected"`
|
||||
GlobalLimit int `json:"global_limit"`
|
||||
SourceStats []SourceStat `json:"source_stats"`
|
||||
FailureCode string `json:"failure_code,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
type Result struct {
|
||||
Summary *models.Summary `json:"summary"`
|
||||
@ -69,6 +81,17 @@ type Ranker = LayaRanker
|
||||
type Summarizer interface {
|
||||
Summarize(context.Context, string, []models.UserAsset, []Candidate) (string, error)
|
||||
}
|
||||
type SummaryRequest struct {
|
||||
Language string
|
||||
Assets []models.UserAsset
|
||||
Candidates []Candidate
|
||||
Budget int
|
||||
Context string
|
||||
GeneratedAt time.Time
|
||||
}
|
||||
type BudgetedSummarizer interface {
|
||||
SummarizeWithBudget(context.Context, SummaryRequest) (string, summarybudget.Usage, error)
|
||||
}
|
||||
type ResolvedSummary struct {
|
||||
Summarizer Summarizer
|
||||
CatalogID, ProviderID, Provider, Model string
|
||||
@ -123,7 +146,11 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
if id == "" {
|
||||
id = NewID()
|
||||
}
|
||||
out := GenerationOutcome{ID: id, Language: input.Language, RankingMode: input.RankingMode, GlobalLimit: input.GlobalLimit, CreatedAt: u.Clock(), SourceStats: []SourceStat{}}
|
||||
requestedBudget := input.SummaryPromptTokenBudget
|
||||
if requestedBudget == 0 {
|
||||
requestedBudget = models.DefaultSummaryPromptTokenBudget
|
||||
}
|
||||
out := GenerationOutcome{PromptBudget: summarybudget.Usage{RequestedTokens: requestedBudget}, ID: id, Language: input.Language, RankingMode: input.RankingMode, GlobalLimit: input.GlobalLimit, CreatedAt: u.Clock(), SourceStats: []SourceStat{}}
|
||||
resolved := ResolvedSummary{Summarizer: u.Summarizer}
|
||||
finish := func(status, code, content string) (Result, error) {
|
||||
out.Status = status
|
||||
@ -151,7 +178,7 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
if (input.Language != "fr" && input.Language != "en") || (input.RankingMode != "title" && input.RankingMode != "title_content") || input.GlobalLimit <= 0 {
|
||||
if (input.Language != "fr" && input.Language != "en") || (input.RankingMode != "title" && input.RankingMode != "title_content") || input.GlobalLimit <= 0 || requestedBudget < 1 || requestedBudget > models.MaxSummaryPromptTokenBudget {
|
||||
return finish("failed", "invalid_preferences", "")
|
||||
}
|
||||
// Explicit Summarizer is a test/injected port. Production always resolves
|
||||
@ -210,7 +237,7 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
orderDates[i] = &date
|
||||
}
|
||||
}
|
||||
if input.RankingMode == "title_content" && *source.SourceKey == models.SourceBloomberg {
|
||||
if input.RankingMode == "title_content" {
|
||||
if enricher, ok := feed.(scraper.ArticleEnricher); ok {
|
||||
enriched, enrichErr := enricher.Enrich(ctx, append([]scraper.Article(nil), articles...))
|
||||
valid := enrichErr == nil && len(enriched) == len(articles)
|
||||
@ -224,6 +251,7 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
}
|
||||
if valid {
|
||||
for i, a := range enriched {
|
||||
articles[i].ContentState = a.ContentState
|
||||
articles[i].Content = a.Content
|
||||
articles[i].ContentTruncated = a.ContentTruncated
|
||||
if a.PublishedAt != nil {
|
||||
@ -242,6 +270,28 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
article.Content = ""
|
||||
article.ContentTruncated = false
|
||||
}
|
||||
article.Source = *source.SourceKey
|
||||
if article.PublishedAt != nil {
|
||||
stat.DatesAvailable++
|
||||
out.DatesAvailable++
|
||||
}
|
||||
if input.RankingMode == "title_content" {
|
||||
switch scraper.ContentStatus(article) {
|
||||
case scraper.ContentComplete:
|
||||
stat.ContentComplete++
|
||||
out.ContentComplete++
|
||||
case scraper.ContentIncomplete:
|
||||
stat.ContentIncomplete++
|
||||
out.ContentIncomplete++
|
||||
partial = true
|
||||
continue
|
||||
default:
|
||||
stat.ContentUnavailable++
|
||||
out.ContentUnavailable++
|
||||
partial = true
|
||||
continue
|
||||
}
|
||||
}
|
||||
if input.RankingMode == "title" {
|
||||
article.Content = ""
|
||||
article.ContentTruncated = false
|
||||
@ -253,6 +303,9 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
out.SourceStats = append(out.SourceStats, stat)
|
||||
}
|
||||
if len(candidates) == 0 {
|
||||
if input.RankingMode == "title_content" && out.TotalCandidates > 0 {
|
||||
return finish("no_results", "no_complete_content", "")
|
||||
}
|
||||
if partial {
|
||||
return finish("failed", "sources_unavailable", "")
|
||||
}
|
||||
@ -274,7 +327,13 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
if len(selected) == 0 {
|
||||
return finish("no_results", "", "")
|
||||
}
|
||||
content, err := resolved.Summarizer.Summarize(ctx, input.Language, input.Assets, selected)
|
||||
var content string
|
||||
if budgeted, ok := resolved.Summarizer.(BudgetedSummarizer); ok {
|
||||
budget := requestedBudget
|
||||
content, out.PromptBudget, err = budgeted.SummarizeWithBudget(ctx, SummaryRequest{Language: input.Language, Assets: input.Assets, Candidates: selected, Budget: budget, Context: input.SummaryContext, GeneratedAt: out.CreatedAt})
|
||||
} else {
|
||||
content, err = resolved.Summarizer.Summarize(ctx, input.Language, input.Assets, selected)
|
||||
}
|
||||
if err != nil || ctx.Err() != nil {
|
||||
return finish("failed", summaryFailureCode(ctx, err), "")
|
||||
}
|
||||
@ -282,12 +341,25 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
|
||||
return finish("failed", "summary_failed", "")
|
||||
}
|
||||
if partial {
|
||||
return finish("partial", "source_unavailable", content)
|
||||
code := "content_incomplete"
|
||||
for _, s := range out.SourceStats {
|
||||
if s.Status == "failed" {
|
||||
code = "source_unavailable"
|
||||
break
|
||||
}
|
||||
}
|
||||
return finish("partial", code, content)
|
||||
}
|
||||
return finish("succeeded", "", content)
|
||||
}
|
||||
|
||||
func summaryFailureCode(ctx context.Context, err error) string {
|
||||
if errors.Is(err, summarybudget.ErrUnknown) {
|
||||
return "summary_capacity_unknown"
|
||||
}
|
||||
if errors.Is(err, summarybudget.ErrExceeded) {
|
||||
return "summary_prompt_budget_exceeded"
|
||||
}
|
||||
if errors.Is(ctx.Err(), context.DeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return "summary_timeout"
|
||||
}
|
||||
|
||||
@ -95,8 +95,8 @@ func TestUseCaseIsolatesTwoUsersAndUsesOnlyEnabledSourcesAndUserInputs(t *testin
|
||||
alphaSource := models.Source{ID: "alpha-feed", Type: "alpha", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 5}
|
||||
betaSource := models.Source{ID: "beta-feed", Type: "beta", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 5}
|
||||
disabled := models.Source{ID: "disabled-feed", Type: "disabled", SourceKey: testSourceKey(models.SourceWatcherGuru), Enabled: false, ArticleLimit: 5}
|
||||
alphaScraper := &contractScraper{name: "alpha", articles: []scraper.Article{{Title: "alpha-only", URL: "https://private.test/alpha", Content: "alpha-secret"}}}
|
||||
betaScraper := &contractScraper{name: "beta", articles: []scraper.Article{{Title: "beta-only", URL: "https://private.test/beta", Content: "beta-secret"}}}
|
||||
alphaScraper := &contractScraper{name: "alpha", articles: []scraper.Article{{Title: "alpha-only", URL: "https://private.test/alpha", ContentState: scraper.ContentComplete, Content: "alpha-secret"}}}
|
||||
betaScraper := &contractScraper{name: "beta", articles: []scraper.Article{{Title: "beta-only", URL: "https://private.test/beta", ContentState: scraper.ContentComplete, Content: "beta-secret"}}}
|
||||
disabledScraper := &contractScraper{name: "disabled"}
|
||||
ranker := &contractRanker{}
|
||||
summarizer := &contractSummarizer{}
|
||||
@ -195,7 +195,7 @@ func TestUseCaseNoResultsInvalidLayaAndSummaryFailurePersistNoSummary(t *testing
|
||||
}
|
||||
|
||||
func TestUseCasePartialSourceFailureCanSummarizeRemainingSources(t *testing.T) {
|
||||
good := &contractScraper{name: "good", articles: []scraper.Article{{Title: "good-result"}}}
|
||||
good := &contractScraper{name: "good", articles: []scraper.Article{{Title: "good-result", ContentState: scraper.ContentComplete, Content: "Synthetic full report."}}}
|
||||
bad := &contractScraper{name: "bad", err: errors.New("private error with URL https://private.test/article")}
|
||||
ranker := &contractRanker{order: []string{"good-result"}}
|
||||
summarizer := &contractSummarizer{}
|
||||
@ -218,7 +218,7 @@ func TestUseCasePartialSourceFailureCanSummarizeRemainingSources(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestUseCaseOutcomeContainsAggregateCountsWithoutArticleIdentifiers(t *testing.T) {
|
||||
feed := &contractScraper{name: "source", articles: []scraper.Article{{Title: "candidate-title-secret", URL: "https://private.test/x", Content: "candidate-content-secret"}}}
|
||||
feed := &contractScraper{name: "source", articles: []scraper.Article{{Title: "candidate-title-secret", URL: "https://private.test/x", ContentState: scraper.ContentComplete, Content: "candidate-content-secret"}}}
|
||||
ranker := &contractRanker{order: []string{"candidate-title-secret"}}
|
||||
summarizer := &contractSummarizer{}
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 10, Sources: []models.Source{{ID: "source-id", Type: "source", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
|
||||
@ -242,14 +242,14 @@ func TestUseCaseOutcomeContainsAggregateCountsWithoutArticleIdentifiers(t *testi
|
||||
}
|
||||
|
||||
func TestUseCaseCountsTitleOnlyFallbackWhenContentIsUnavailable(t *testing.T) {
|
||||
feed := &contractScraper{name: "source", articles: []scraper.Article{{Title: "title-without-content", Content: ""}}}
|
||||
feed := &contractScraper{name: "source", articles: []scraper.Article{{Title: "title-without-content", ContentState: scraper.ContentComplete, Content: ""}}}
|
||||
ranker := &contractRanker{}
|
||||
summarizer := &contractSummarizer{}
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "en", RankingMode: "title_content", GlobalLimit: 4, Sources: []models.Source{{ID: "source", Type: "source", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 4}}}}, saved: map[string][]GenerationRecord{}}
|
||||
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feed}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
|
||||
result, err := uc.Generate(context.Background(), "u")
|
||||
if err != nil || result.Summary == nil {
|
||||
t.Fatalf("content fallback should permit generation: result=%+v err=%v", result, err)
|
||||
if err != nil || result.Summary != nil || result.Outcome.FailureCode != "no_complete_content" || len(summarizer.articles) != 0 {
|
||||
t.Fatalf("missing content must prevent generation: result=%+v err=%v", result, err)
|
||||
}
|
||||
if result.Outcome.ContentFallbacks != 1 {
|
||||
t.Fatalf("content fallback count=%d, want 1", result.Outcome.ContentFallbacks)
|
||||
|
||||
@ -16,7 +16,7 @@ type ticket14Feed struct{ calls int }
|
||||
func (*ticket14Feed) Name() string { return "fake-yahoo" }
|
||||
func (f *ticket14Feed) Scrape(_ context.Context, _ []string) ([]scraper.Article, error) {
|
||||
f.calls++
|
||||
return []scraper.Article{{Title: "Market title A", Content: "Market body A", URL: "https://fake.invalid/a"}, {Title: "Market title B", Content: "Market body B", URL: "https://fake.invalid/b"}}, nil
|
||||
return []scraper.Article{{Title: "Market title A", ContentState: scraper.ContentComplete, Content: "Market body A", URL: "https://fake.invalid/a"}, {Title: "Market title B", ContentState: scraper.ContentComplete, Content: "Market body B", URL: "https://fake.invalid/b"}}, nil
|
||||
}
|
||||
|
||||
type ticket14Repository struct {
|
||||
|
||||
@ -63,7 +63,7 @@ func TestTicket28GenerationAggregatesAllAssetsBeforeSelectionAndFailsClosed(t *t
|
||||
defer srv.Close()
|
||||
ranker, _ := ai.NewLayaHTTPRanker(ai.LayaHTTPConfig{BaseURL: srv.URL, BatchSize: 2})
|
||||
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}}}
|
||||
feed := &ticket17HTTPScraper{articles: []scraper.Article{{Title: "first", URL: "https://fixture.invalid/first", ContentState: scraper.ContentComplete, Content: content}, {Title: "second", URL: "https://fixture.invalid/second", ContentState: scraper.ContentComplete, Content: content}}}
|
||||
summary := &ticket17HTTPSummary{}
|
||||
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}})
|
||||
|
||||
@ -42,8 +42,8 @@ func (s *ticket17HTTPScraper) Scrape(context.Context, []string) ([]scraper.Artic
|
||||
return s.articles, nil
|
||||
}
|
||||
return []scraper.Article{
|
||||
{Title: "Less relevant title", Content: "Less relevant body", URL: "https://article-secret.invalid/less", Symbols: []string{"SPX"}},
|
||||
{Title: "Selected title", Content: "Selected body", URL: "https://article-secret.invalid/selected", Symbols: []string{"SPX"}},
|
||||
{Title: "Less relevant title", ContentState: scraper.ContentComplete, Content: "Less relevant body", URL: "https://article-secret.invalid/less", Symbols: []string{"SPX"}},
|
||||
{Title: "Selected title", ContentState: scraper.ContentComplete, Content: "Selected body", URL: "https://article-secret.invalid/selected", Symbols: []string{"SPX"}},
|
||||
}, nil
|
||||
}
|
||||
|
||||
@ -162,7 +162,7 @@ func TestGenerationLogsSanitizedLayaFailureCause(t *testing.T) {
|
||||
}
|
||||
modelID := "summary-model-user-a"
|
||||
key := models.SourceYahooFinance
|
||||
feed := &ticket17HTTPScraper{articles: []scraper.Article{{Title: articleTitle, Content: articleBody, URL: articleURL}}}
|
||||
feed := &ticket17HTTPScraper{articles: []scraper.Article{{Title: articleTitle, ContentState: scraper.ContentComplete, Content: articleBody, URL: articleURL}}}
|
||||
summary := &ticket17HTTPSummary{}
|
||||
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}})
|
||||
|
||||
@ -50,7 +50,7 @@ func TestLegacyNullFIGIAssetStillContributesToGenerationPostgres(t *testing.T) {
|
||||
})
|
||||
const userID = "00000000-0000-0000-0000-000000000401"
|
||||
for _, statement := range []string{
|
||||
`CREATE TABLE users (id UUID PRIMARY KEY, language TEXT NOT NULL DEFAULT 'fr', ranking_mode TEXT NOT NULL DEFAULT 'title',summary_model_id UUID NULL)`,
|
||||
`CREATE TABLE users (id UUID PRIMARY KEY, language TEXT NOT NULL DEFAULT 'fr', ranking_mode TEXT NOT NULL DEFAULT 'title',summary_prompt_token_budget INT NOT NULL DEFAULT 250000,summary_model_id UUID NULL)`,
|
||||
`CREATE TABLE user_assets (id UUID PRIMARY KEY, user_id UUID NOT NULL, symbol VARCHAR(20) NOT NULL, name TEXT NOT NULL DEFAULT '', figi TEXT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE sources (id UUID PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, enabled BOOLEAN NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), article_limit INT NOT NULL DEFAULT 20, source_key TEXT)`,
|
||||
`CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
|
||||
@ -58,7 +58,7 @@ func TestLegacyNullFIGIAssetStillContributesToGenerationPostgres(t *testing.T) {
|
||||
`INSERT INTO user_assets(id,user_id,symbol,name,figi) VALUES ('00000000-0000-0000-0000-000000000411','` + userID + `','LEGACY','Historic asset',NULL)`,
|
||||
`INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES ('00000000-0000-0000-0000-000000000421','test source','ticket4',TRUE,20,'yahoo_finance')`,
|
||||
`INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES ('00000000-0000-0000-0000-000000000422','Historic enabled','reuters',TRUE,42,NULL),('00000000-0000-0000-0000-000000000423','Disabled target','bloomberg',FALSE,77,'bloomberg')`,
|
||||
`INSERT INTO settings(key,value) VALUES ('summary_max_articles','50')`,
|
||||
`INSERT INTO settings(key,value) VALUES ('summary_max_articles','50'),('ai_system_prompt','Configured generation context')`,
|
||||
} {
|
||||
if _, err := db.Exec(statement); err != nil {
|
||||
t.Fatal(err)
|
||||
@ -69,6 +69,9 @@ func TestLegacyNullFIGIAssetStillContributesToGenerationPostgres(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("load legacy generation input from PostgreSQL: %v", err)
|
||||
}
|
||||
if input.SummaryContext != "Configured generation context" {
|
||||
t.Fatal("existing generation context lost")
|
||||
}
|
||||
if len(input.Sources) != 1 || input.Sources[0].SourceKey == nil || *input.Sources[0].SourceKey != models.SourceYahooFinance || input.Sources[0].ArticleLimit != 20 {
|
||||
t.Fatalf("LoadUserInput must exclude unsupported/disabled sources, preserving target caps: %+v", input.Sources)
|
||||
}
|
||||
|
||||
@ -33,7 +33,11 @@ func (r RepositoryAdapter) LoadUserInput(ctx context.Context, id string) (UserIn
|
||||
if value == "" {
|
||||
limit = 50
|
||||
}
|
||||
return UserInput{SummaryModelID: p.SummaryModelID, Language: p.Language, RankingMode: p.RankingMode, GlobalLimit: limit, Assets: assets, Sources: models.OperationalSources(sources)}, nil
|
||||
summaryContext, err := r.Repo.GetSetting("ai_system_prompt")
|
||||
if err != nil {
|
||||
return UserInput{}, err
|
||||
}
|
||||
return UserInput{SummaryContext: summaryContext, SummaryPromptTokenBudget: p.SummaryPromptTokenBudget, SummaryModelID: p.SummaryModelID, Language: p.Language, RankingMode: p.RankingMode, GlobalLimit: limit, Assets: assets, Sources: models.OperationalSources(sources)}, nil
|
||||
}
|
||||
func (r RepositoryAdapter) SaveGeneration(ctx context.Context, id string, record GenerationRecord) error {
|
||||
payload, err := json.Marshal(record.Outcome)
|
||||
|
||||
@ -142,7 +142,7 @@ func TestTicket35BloombergMissingContentProducesHonestGenerationFallback(t *test
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
|
||||
summary := &contractSummarizer{}
|
||||
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: summary, Scrapers: map[string]scraper.Scraper{models.SourceBloomberg: bloombergFixtureFeed{bloomberg.New(server.URL)}}}).Generate(context.Background(), "u")
|
||||
if err != nil || r.Summary == nil || requests != 1 || r.Outcome.ContentFallbacks != 1 || r.Outcome.SourceStats[0].ContentFallbacks != 1 || len(summary.articles) != 1 || summary.articles[0][0].Article.Content != "" || summary.articles[0][0].Article.PublishedAt != nil {
|
||||
if err != nil || r.Summary != nil || requests != 1 || r.Outcome.ContentFallbacks != 1 || r.Outcome.SourceStats[0].ContentFallbacks != 1 || len(summary.articles) != 0 || r.Outcome.FailureCode != "no_complete_content" {
|
||||
t.Fatal("inaccurate Bloomberg content availability", r.Outcome, err)
|
||||
}
|
||||
}
|
||||
|
||||
@ -115,7 +115,7 @@ func TestTicket34DeterministicMentionUsesResolvedNamesAliasesAndModeOnly(t *test
|
||||
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."}}}
|
||||
feed := &contractScraper{articles: []scraper.Article{{Title: "Intelligence and INTC", ContentState: scraper.ContentComplete, 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)
|
||||
|
||||
Reference in New Issue
Block a user