fix(scraper): verify complete article evidence (#40)

This commit is contained in:
2026-11-24 19:24:29 +01:00
parent 70ffe41cfb
commit a55dc2e189
27 changed files with 833 additions and 132 deletions

View File

@ -0,0 +1,107 @@
package generation
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper"
"github.com/tradarr/backend/internal/scraper/articlecontent"
"github.com/tradarr/backend/internal/scraper/bloomberg"
)
type ticket40Transport func(*http.Request) (*http.Response, error)
func (f ticket40Transport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
type ticket40EvidenceFeed struct {
source string
articles []scraper.Article
client *http.Client
bb *bloomberg.Bloomberg
}
func (f ticket40EvidenceFeed) Name() string { return f.source }
func (f ticket40EvidenceFeed) Scrape(context.Context, []string) ([]scraper.Article, error) {
return append([]scraper.Article(nil), f.articles...), nil
}
func (f ticket40EvidenceFeed) Enrich(ctx context.Context, a []scraper.Article) ([]scraper.Article, error) {
if f.bb != nil {
return f.bb.EnrichWithCredentials(ctx, "fixture", "fixture", a)
}
return articlecontent.Enrich(ctx, f.client, f.source, a)
}
func TestTicket40RealEnrichmentPortsOnlyPropagateCompleteBodiesToSummary(t *testing.T) {
for _, key := range []string{models.SourceBloomberg, models.SourceYahooFinance, models.SourceCNBCBusiness} {
t.Run(key, func(t *testing.T) {
const full = "Synthetic full editorial body."
base, root := "https://finance.yahoo.com/news/", "caas-body"
if key == models.SourceCNBCBusiness {
base = "https://www.cnbc.com/2026/01/02/"
root = "ArticleBody-articleBody"
}
if key == models.SourceBloomberg {
base = "https://www.bloomberg.com/news/articles/"
}
feed := ticket40EvidenceFeed{source: key}
for _, kind := range []string{"complete", "partial", "absent"} {
feed.articles = append(feed.articles, scraper.Article{Title: "Followed fixture " + kind, URL: base + kind + ".html", Content: "RSS teaser", ContentState: scraper.ContentIncomplete})
}
if key == models.SourceBloomberg {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var req struct {
URLs []string `json:"urls"`
}
if r.URL.Path != "/bloomberg/enrich" || json.NewDecoder(r.Body).Decode(&req) != nil {
t.Error("unexpected fixture RPC")
w.WriteHeader(400)
return
}
result := []map[string]any{}
for _, url := range req.URLs {
body, state := full, scraper.ContentComplete
if strings.Contains(url, "partial") {
body = "Available introduction."
state = scraper.ContentIncomplete
}
if strings.Contains(url, "absent") {
body = ""
state = scraper.ContentUnavailable
}
result = append(result, map[string]any{"url": url, "content": body, "content_state": state})
}
json.NewEncoder(w).Encode(map[string]any{"articles": result})
}))
defer server.Close()
feed.bb = bloomberg.New(server.URL)
} else {
feed.client = &http.Client{Transport: ticket40Transport(func(r *http.Request) (*http.Response, error) {
body := `<link rel="canonical" href="` + r.URL.String() + `"><div class="` + root + `"><p>` + full + `</p></div>`
if strings.Contains(r.URL.Path, "partial") {
body += `<div data-content-state="partial"></div>`
}
if strings.Contains(r.URL.Path, "absent") {
body = `<div id="px-captcha"></div>`
}
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header), Request: r}, nil
})}
}
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{}
result, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: sum, Scrapers: map[string]scraper.Scraper{key: feed}}).Generate(context.Background(), "u")
o := result.Outcome
if err != nil || result.Summary == nil || o.Status != "partial" || o.ContentComplete != 1 || o.ContentIncomplete != 1 || o.ContentUnavailable != 1 || o.Selected != 1 || len(sum.articles) != 1 || sum.articles[0][0].Article.Content != full || o.SourceStats[0].Status != "ok" || o.SourceStats[0].SourceKey != key {
t.Fatal("enrichment status lost before summary", o, err)
}
raw, _ := json.Marshal(repo.saved["u"][0].Outcome)
if strings.Contains(string(raw), full) || strings.Contains(string(raw), "https://") {
t.Fatal("article data persisted in aggregate")
}
})
}
}

View File

@ -29,6 +29,7 @@ type Candidate struct {
orderFrozen bool
}
type SourceStat struct {
SourceKey string `json:"source_key"`
ContentComplete int `json:"content_complete"`
ContentIncomplete int `json:"content_incomplete"`
ContentUnavailable int `json:"content_unavailable"`
@ -206,7 +207,7 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
if !source.Operational() {
continue
}
stat := SourceStat{SourceID: source.ID, SourceType: source.Type, ArticleLimit: source.ArticleLimit, Status: "ok"}
stat := SourceStat{SourceKey: *source.SourceKey, SourceID: source.ID, SourceType: source.Type, ArticleLimit: source.ArticleLimit, Status: "ok"}
if stat.ArticleLimit <= 0 {
stat.ArticleLimit = 20
}

View File

@ -0,0 +1,36 @@
package generation
import (
"context"
"encoding/json"
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper"
"strings"
"testing"
)
func TestTicket40CanonicalSourceKeyAndReachabilitySeparateFromContent(t *testing.T) {
for _, key := range []string{models.SourceYahooFinance, models.SourceBloomberg, 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", Type: "stocktwits", SourceKey: &key, Enabled: true, ArticleLimit: 3}}}}, saved: map[string][]GenerationRecord{}}
r, err := NewUseCase(Dependencies{Repository: repo, Decider: &allYesMention{}, Summarizer: &contractSummarizer{}, Scrapers: map[string]scraper.Scraper{key: feed}}).Generate(context.Background(), "u")
if err != nil {
t.Fatal(err)
}
raw, _ := json.Marshal(r.Outcome)
var outcome struct {
SourceStats []map[string]any `json:"source_stats"`
}
json.Unmarshal(raw, &outcome)
stat := outcome.SourceStats[0]
if stat["source_key"] != key || stat["status"] != "ok" || stat["content_complete"] != float64(1) || stat["content_incomplete"] != float64(1) || stat["content_unavailable"] != float64(1) {
t.Fatal("canonical key or distinct content states missing")
}
saved, _ := json.Marshal(repo.saved["u"][0].Outcome)
if strings.Contains(string(saved), "fixture.invalid") || strings.Contains(string(saved), "Entire editorial") {
t.Fatal("sensitive article persisted in diagnostics")
}
})
}
}