fix(bloomberg): avoid collection timeouts
This commit is contained in:
172
backend/internal/generation/summary_errors_ticket35_test.go
Normal file
172
backend/internal/generation/summary_errors_ticket35_test.go
Normal file
@ -0,0 +1,172 @@
|
||||
package generation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"github.com/tradarr/backend/internal/scraper/bloomberg"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestTicket35SummaryFailureDistinguishesTimeoutCancellationAndProvider(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
err error
|
||||
code string
|
||||
}{
|
||||
{"timeout", fmt.Errorf("PRIVATE_BODY: %w", context.DeadlineExceeded), "summary_timeout"},
|
||||
{"cancel", fmt.Errorf("PRIVATE_BODY: %w", context.Canceled), "summary_canceled"},
|
||||
{"http timeout", &url.Error{URL: "https://PRIVATE_URL.invalid", Err: context.DeadlineExceeded}, "summary_timeout"},
|
||||
{"provider", errors.New("PRIVATE_BODY timeout https://PRIVATE_URL.invalid"), "summary_failed"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
|
||||
sum := &contractSummarizer{err: tc.err}
|
||||
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: []scraper.Article{{Title: "Fixture Company"}}}}}).Generate(context.Background(), "u")
|
||||
if err != nil || r.Summary != nil || r.Outcome.Status != "failed" || r.Outcome.FailureCode != tc.code {
|
||||
t.Fatalf("status=%s code=%s err=%v", r.Outcome.Status, r.Outcome.FailureCode, err)
|
||||
}
|
||||
encoded, _ := json.Marshal(repo.saved)
|
||||
if strings.Contains(string(encoded), "PRIVATE") || strings.Contains(string(encoded), "https://") {
|
||||
t.Fatal("raw provider error persisted")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type cancelSummary struct{ cancel context.CancelFunc }
|
||||
|
||||
func (s cancelSummary) Summarize(context.Context, string, []models.UserAsset, []Candidate) (string, error) {
|
||||
s.cancel()
|
||||
return "", fmt.Errorf("PRIVATE_PROVIDER_ERROR: %w", context.Canceled)
|
||||
}
|
||||
|
||||
type terminalRepo struct {
|
||||
*contractRepository
|
||||
expectedJob string
|
||||
checked bool
|
||||
}
|
||||
|
||||
func (r *terminalRepo) SaveGeneration(ctx context.Context, user string, record GenerationRecord) error {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if models.GenerationJobID(ctx) != r.expectedJob {
|
||||
return errors.New("job identity lost")
|
||||
}
|
||||
deadline, ok := ctx.Deadline()
|
||||
if !ok || time.Until(deadline) > 10*time.Second {
|
||||
return errors.New("terminal persistence is not bounded")
|
||||
}
|
||||
r.checked = true
|
||||
return r.contractRepository.SaveGeneration(ctx, user, record)
|
||||
}
|
||||
func TestTicket35CanceledSummaryStillPersistsSafeTerminalOutcome(t *testing.T) {
|
||||
base := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
|
||||
repo := &terminalRepo{contractRepository: base, expectedJob: "fixture-job"}
|
||||
ctx, cancel := context.WithCancel(models.WithGenerationJob(context.Background(), repo.expectedJob))
|
||||
defer cancel()
|
||||
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: cancelSummary{cancel}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: []scraper.Article{{Title: "Fixture Company"}}}}}).Generate(ctx, "u")
|
||||
if err != nil || !repo.checked || r.Summary != nil || r.Outcome.FailureCode != "summary_canceled" || len(base.saved["u"]) != 1 {
|
||||
t.Fatal(r.Outcome, err)
|
||||
}
|
||||
}
|
||||
|
||||
type budgetMention struct {
|
||||
contexts []context.Context
|
||||
budgetCalls int
|
||||
failIndirect bool
|
||||
}
|
||||
|
||||
func (b *budgetMention) WithSelectionBudget(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
b.budgetCalls++
|
||||
return context.WithTimeout(ctx, 5*time.Minute)
|
||||
}
|
||||
func (b *budgetMention) DecideMentions(ctx context.Context, _, pass string, _ []models.UserAsset, candidates []Candidate) ([]Candidate, error) {
|
||||
b.contexts = append(b.contexts, ctx)
|
||||
if pass == MentionIndirect {
|
||||
if b.failIndirect {
|
||||
return nil, context.DeadlineExceeded
|
||||
}
|
||||
return candidates, nil
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
func TestTicket35ThreePassBudgetIsSharedAndFailureDropsAllSelection(t *testing.T) {
|
||||
articles := []scraper.Article{{Title: "Fixture Company"}}
|
||||
for i := 0; i < 65; i++ {
|
||||
articles = append(articles, scraper.Article{Title: fmt.Sprintf("unmatched %d", i)})
|
||||
}
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 100, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 100}}}}, saved: map[string][]GenerationRecord{}}
|
||||
gate := &budgetMention{failIndirect: true}
|
||||
sum := &contractSummarizer{}
|
||||
r, err := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: articles}}}).Generate(context.Background(), "u")
|
||||
if err != nil || r.Summary != nil || r.Outcome.FailureCode != "ranking_failed" || len(sum.articles) != 0 || gate.budgetCalls != 1 || len(gate.contexts) != 3 {
|
||||
t.Fatal(r.Outcome, err)
|
||||
}
|
||||
first, _ := gate.contexts[0].Deadline()
|
||||
for _, ctx := range gate.contexts {
|
||||
deadline, ok := ctx.Deadline()
|
||||
if !ok || !deadline.Equal(first) || time.Until(deadline) < 4*time.Minute+59*time.Second || time.Until(deadline) > 5*time.Minute {
|
||||
t.Fatal("ranking deadline reset/reduced")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type bloombergFixtureFeed struct{ client *bloomberg.Bloomberg }
|
||||
|
||||
func (b bloombergFixtureFeed) Name() string { return "bloomberg" }
|
||||
func (b bloombergFixtureFeed) Scrape(ctx context.Context, symbols []string) ([]scraper.Article, error) {
|
||||
return b.client.ScrapeWithCredentials(ctx, "fixture", "fixture", symbols)
|
||||
}
|
||||
func TestTicket35BloombergMissingContentProducesHonestGenerationFallback(t *testing.T) {
|
||||
requests := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
requests++
|
||||
if r.URL.Path != "/bloomberg/scrape" {
|
||||
t.Error("unexpected scraper path")
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"articles":[{"title":"Fixture Company","url":"https://fixture.invalid/article","published_at":null}]}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
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 {
|
||||
t.Fatal("inaccurate Bloomberg content availability", r.Outcome, err)
|
||||
}
|
||||
}
|
||||
|
||||
type liveContextSummary struct{ called bool }
|
||||
|
||||
func (s *liveContextSummary) Summarize(ctx context.Context, _ string, _ []models.UserAsset, _ []Candidate) (string, error) {
|
||||
s.called = true
|
||||
if ctx.Err() != nil {
|
||||
return "", ctx.Err()
|
||||
}
|
||||
return "fixture synthesis", nil
|
||||
}
|
||||
func TestTicket35SummaryDoesNotInheritCanceledSelectionBudget(t *testing.T) {
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 1, Assets: []models.UserAsset{{Name: "Fixture Company"}}, Sources: []models.Source{{ID: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 1}}}}, saved: map[string][]GenerationRecord{}}
|
||||
gate := &budgetMention{}
|
||||
sum := &liveContextSummary{}
|
||||
r, err := NewUseCase(Dependencies{Repository: repo, Decider: gate, Summarizer: sum, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{articles: []scraper.Article{{Title: "unmatched"}}}}}).Generate(context.Background(), "u")
|
||||
if err != nil || r.Summary == nil || !sum.called || gate.budgetCalls != 1 || len(gate.contexts) != 2 {
|
||||
t.Fatal(r.Outcome, err)
|
||||
}
|
||||
for _, ctx := range gate.contexts {
|
||||
if ctx.Err() != context.Canceled {
|
||||
t.Fatal("selection context was not released")
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user