From a55dc2e1899151a971bb72ed6f205936e05d06ea Mon Sep 17 00:00:00 2001 From: Blomios Date: Tue, 24 Nov 2026 19:24:29 +0100 Subject: [PATCH] fix(scraper): verify complete article evidence (#40) --- .../enrichment_propagation_ticket40_test.go | 107 +++++++++++ backend/internal/generation/generation.go | 3 +- .../generation/source_key_ticket40_test.go | 36 ++++ .../completeness_ticket40_test.go | 44 +++++ .../scraper/articlecontent/enrichment.go | 177 +++++++++--------- .../scraper/articlecontent/enrichment_test.go | 13 +- .../scraper/articlecontent/evidence.go | 169 +++++++++++++++++ .../testdata/cnbc_business.html | 2 +- .../articlecontent/testdata/cnbc_module.html | 4 + .../testdata/yahoo_finance.html | 2 +- .../articlecontent/testdata/yahoo_modern.html | 4 + .../yahoofinance/diagnostics_ticket20_test.go | 4 +- .../reachability_ticket40_test.go | 29 +++ .../scraper/yahoofinance/yahoofinance.go | 6 + docs/operations.md | 78 ++++++++ frontend/src/api/summaries.ts | 1 + frontend/src/components/GenerationDetails.tsx | 35 +++- frontend/tests/dashboard-generation.test.tsx | 8 +- .../tests/prompt-budget-ticket39.test.tsx | 2 +- .../source-completeness-ticket40.test.tsx | 80 ++++++++ .../source-diagnostics-ticket23.test.tsx | 13 +- scraper-service/article-content.js | 51 ++++- scraper-service/index.js | 11 +- scraper-service/tests/article-content.test.js | 13 +- .../tests/completeness-ticket40.test.js | 31 +++ .../tests/enrichment-route.test.js | 33 +++- .../fixtures/content-gift-placeholders.html | 9 + 27 files changed, 833 insertions(+), 132 deletions(-) create mode 100644 backend/internal/generation/enrichment_propagation_ticket40_test.go create mode 100644 backend/internal/generation/source_key_ticket40_test.go create mode 100644 backend/internal/scraper/articlecontent/completeness_ticket40_test.go create mode 100644 backend/internal/scraper/articlecontent/evidence.go create mode 100644 backend/internal/scraper/articlecontent/testdata/cnbc_module.html create mode 100644 backend/internal/scraper/articlecontent/testdata/yahoo_modern.html create mode 100644 backend/internal/scraper/yahoofinance/reachability_ticket40_test.go create mode 100644 frontend/tests/source-completeness-ticket40.test.tsx create mode 100644 scraper-service/tests/completeness-ticket40.test.js create mode 100644 scraper-service/tests/fixtures/content-gift-placeholders.html diff --git a/backend/internal/generation/enrichment_propagation_ticket40_test.go b/backend/internal/generation/enrichment_propagation_ticket40_test.go new file mode 100644 index 0000000..78e3177 --- /dev/null +++ b/backend/internal/generation/enrichment_propagation_ticket40_test.go @@ -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 := `

` + full + `

` + if strings.Contains(r.URL.Path, "partial") { + body += `
` + } + if strings.Contains(r.URL.Path, "absent") { + body = `
` + } + 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") + } + }) + } +} diff --git a/backend/internal/generation/generation.go b/backend/internal/generation/generation.go index 2166b57..1270976 100644 --- a/backend/internal/generation/generation.go +++ b/backend/internal/generation/generation.go @@ -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 } diff --git a/backend/internal/generation/source_key_ticket40_test.go b/backend/internal/generation/source_key_ticket40_test.go new file mode 100644 index 0000000..e16a564 --- /dev/null +++ b/backend/internal/generation/source_key_ticket40_test.go @@ -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") + } + }) + } +} diff --git a/backend/internal/scraper/articlecontent/completeness_ticket40_test.go b/backend/internal/scraper/articlecontent/completeness_ticket40_test.go new file mode 100644 index 0000000..56af61e --- /dev/null +++ b/backend/internal/scraper/articlecontent/completeness_ticket40_test.go @@ -0,0 +1,44 @@ +package articlecontent + +import ( + "github.com/tradarr/backend/internal/scraper" + "os" + "strings" + "testing" +) + +func TestTicket40AssociationAndIncompleteBodies(t *testing.T) { + for _, tc := range []struct{ source, url, root string }{{"yahoo_finance", "https://finance.yahoo.com/news/fixture.html", "caas-body"}, {"cnbc_business", "https://www.cnbc.com/2026/01/02/fixture.html", "ArticleBody-articleBody"}} { + t.Run(tc.source, func(t *testing.T) { + full := `

Synthetic editorial introduction.

Synthetic final editorial paragraph.

` + for _, marker := range []string{`
`, `
`, `
`, `
`} { + a := ExtractHTML(tc.source, tc.url, []byte(strings.Replace(full, "", marker+"", 1))) + if a.ContentState == scraper.ContentComplete { + t.Fatal("blocked or partial page marked complete") + } + } + wrong := ExtractHTML(tc.source, tc.url, []byte(strings.Replace(full, tc.url, tc.url+"-other", 1))) + if wrong.ContentState != scraper.ContentUnavailable || wrong.Content != "" || wrong.PublishedAt != nil { + t.Fatal("wrong article accepted") + } + missing := ExtractHTML(tc.source, tc.url, []byte(`

Unassociated body

`)) + if missing.ContentState == scraper.ContentComplete { + t.Fatal("unassociated body marked complete") + } + }) + } +} +func TestTicket40SourceSpecificLayoutsPreserveFullEditorialText(t *testing.T) { + for _, tc := range []struct{ source, url, fixture string }{{"yahoo_finance", "https://finance.yahoo.com/news/fixture.html", "yahoo_modern.html"}, {"cnbc_business", "https://www.cnbc.com/2026/01/02/fixture.html", "cnbc_module.html"}} { + t.Run(tc.source, func(t *testing.T) { + raw, err := os.ReadFile("testdata/" + tc.fixture) + if err != nil { + t.Fatal(err) + } + a := ExtractHTML(tc.source, tc.url, raw) + if a.ContentState != scraper.ContentComplete || a.PublishedAt == nil || !strings.Contains(a.Content, "Final editorial paragraph.") || !strings.Contains(a.Content, "Synthetic heading.") || strings.Contains(a.Content, "excluded") { + t.Fatalf("unrecognized or incomplete fixture extraction: state=%s", a.ContentState) + } + }) + } +} diff --git a/backend/internal/scraper/articlecontent/enrichment.go b/backend/internal/scraper/articlecontent/enrichment.go index dfe5c22..6ae7d33 100644 --- a/backend/internal/scraper/articlecontent/enrichment.go +++ b/backend/internal/scraper/articlecontent/enrichment.go @@ -5,7 +5,6 @@ package articlecontent import ( "bytes" "context" - "encoding/json" "io" "net/http" "net/url" @@ -71,7 +70,7 @@ func Enrich(ctx context.Context, client *http.Client, source string, articles [] extracted = scraper.Article{ContentState: scraper.ContentUnavailable} resp, err := bounded.Do(req) if err == nil { - if resp.StatusCode == http.StatusOK { + if resp.StatusCode == http.StatusOK && sameResponseArticle(source, target, resp) { raw, readErr := io.ReadAll(io.LimitReader(resp.Body, maxHTMLBytes+1)) if readErr == nil && len(raw) <= maxHTMLBytes { extracted = ExtractHTML(source, target, raw) @@ -119,27 +118,48 @@ func excluded(n *html.Node) bool { } } for _, s := range []string{"related-stories", "advertisement", "disclaimer", "placeholder", "promo"} { - if strings.Contains(attr(n, "class")+" "+attr(n, "data-component"), s) { + if strings.Contains(strings.ToLower(attr(n, "class")+" "+attr(n, "data-component")), s) { return true } } return false } -func nodeText(n *html.Node) string { - if excluded(n) { - return "" +func knownRoot(source string, n *html.Node) bool { + if n.Type != html.ElementNode { + return false } - if n.Type == html.TextNode { - return n.Data - } - var b strings.Builder - for c := n.FirstChild; c != nil; c = c.NextSibling { - b.WriteString(nodeText(c)) - if c.Data == "br" { - b.WriteByte(' ') + switch source { + case "yahoo_finance": + if hasClass(n, "caas-body") { + return true } + if hasClass(n, "body") { + hashed := false + for _, c := range strings.Fields(attr(n, "class")) { + if strings.HasPrefix(c, "yf-") { + hashed = true + } + } + if hashed { + for p := n.Parent; p != nil; p = p.Parent { + if p.Type == html.ElementNode && p.Data == "article" { + return true + } + } + } + } + case "cnbc_business": + return hasClass(n, "ArticleBody-articleBody") || attr(n, "data-module") == "ArticleBody" } - return b.String() + return false +} +func missingMarker(n *html.Node) bool { + marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id") + " " + attr(n, "data-component")) + return strings.Contains(marker, "placeholder") || strings.Contains(marker, "skeleton") || attr(n, "data-content-truncated") == "true" || attr(n, "data-content-state") == "partial" || attr(n, "data-content-state") == "incomplete" +} +func accessMarker(n *html.Node) bool { + marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id")) + return strings.Contains(marker, "paywall") || strings.Contains(marker, "giftarticle") || strings.Contains(marker, "captcha") || strings.HasPrefix(attr(n, "id"), "cf-chl") || strings.HasPrefix(attr(n, "id"), "challenge") || strings.Contains(attr(n, "src"), "challenge-platform") || attr(n, "data-test") == "paywall" || attr(n, "data-testid") == "paywall" || attr(n, "data-content-state") == "partial" || attr(n, "data-content-state") == "incomplete" || attr(n, "data-content-truncated") == "true" } func ExtractHTML(source, articleURL string, raw []byte) scraper.Article { a := scraper.Article{ContentState: scraper.ContentUnavailable} @@ -150,109 +170,98 @@ func ExtractHTML(source, articleURL string, raw []byte) scraper.Article { if err != nil { return a } - rootClass := "" - switch source { - case "yahoo_finance": - rootClass = "caas-body" - case "cnbc_business": - rootClass = "ArticleBody-articleBody" - default: + evidence := inspectEvidence(doc, source, articleURL) + if evidence.mismatch { return a } var roots []*html.Node - blocked := false + blocked := evidence.blocked var walk func(*html.Node) walk = func(n *html.Node) { - if n.Type == html.ElementNode { - if hasClass(n, rootClass) { + if knownRoot(source, n) { + valid := true + for p := n; p != nil; p = p.Parent { + if excluded(p) { + valid = false + break + } + } + if valid { roots = append(roots, n) } - if strings.Contains(strings.ToLower(attr(n, "class")), "paywall") || attr(n, "data-test") == "paywall" || attr(n, "data-testid") == "paywall" || attr(n, "data-content-state") == "incomplete" || attr(n, "data-content-truncated") == "true" { - blocked = true - } - if n.Data == "meta" && attr(n, "property") == "article:published_time" { - if date, err := time.Parse(time.RFC3339Nano, attr(n, "content")); err == nil { - a.PublishedAt = &date - } - } - if n.Data == "script" && attr(n, "type") == "application/ld+json" { - // JSON-LD is used only for matching publication metadata/access flags. - // It never substitutes an unverified articleBody for the editorial root. - var values any - if json.Unmarshal([]byte(nText(n)), &values) == nil { - var inspect func(any) - inspect = func(v any) { - switch x := v.(type) { - case []any: - for _, v := range x { - inspect(v) - } - case map[string]any: - if graph, ok := x["@graph"]; ok { - inspect(graph) - } - typ, _ := x["@type"].(string) - u, _ := x["url"].(string) - if u == "" { - u, _ = x["@id"].(string) - } - if (typ == "NewsArticle" || typ == "Article") && u == articleURL { - if x["isAccessibleForFree"] == false || x["isAccessibleForFree"] == "False" { - blocked = true - } - if s, ok := x["datePublished"].(string); ok { - if date, err := time.Parse(time.RFC3339Nano, s); err == nil { - a.PublishedAt = &date - } - } - } - } - } - inspect(values) - } - } + } + if accessMarker(n) { + blocked = true } for c := n.FirstChild; c != nil; c = c.NextSibling { walk(c) } } walk(doc) + if evidence.associated && !evidence.dateConflict { + a.PublishedAt = evidence.date + } if len(roots) != 1 { return a } paragraphs := []string{} + var chunk strings.Builder + flush := func() { + text := strings.Join(strings.Fields(chunk.String()), " ") + if text != "" { + paragraphs = append(paragraphs, text) + } + chunk.Reset() + } var collect func(*html.Node) collect = func(n *html.Node) { + if missingMarker(n) { + blocked = true + } if excluded(n) { return } - if n.Type == html.ElementNode && (n.Data == "p" || n.Data == "h1" || n.Data == "h2" || n.Data == "h3" || n.Data == "h4" || n.Data == "h5" || n.Data == "h6" || n.Data == "li" || n.Data == "blockquote" || n.Data == "pre" || n.Data == "figcaption" || n.Data == "tr") { - text := strings.Join(strings.Fields(nodeText(n)), " ") - if text != "" { - paragraphs = append(paragraphs, text) - } + if n.Type == html.TextNode { + chunk.WriteString(n.Data) return } + block := false + switch n.Data { + case "p", "div", "section", "h1", "h2", "h3", "h4", "h5", "h6", "li", "ul", "ol", "blockquote", "pre", "figcaption", "table", "tr", "td", "th": + block = true + } + if block { + flush() + } + if n.Data == "br" { + chunk.WriteByte(' ') + } for c := n.FirstChild; c != nil; c = c.NextSibling { collect(c) } + if block { + flush() + } } collect(roots[0]) + flush() a.Content = strings.Join(paragraphs, "\n\n") + if evidence.fullBody != nil && strings.Join(strings.Fields(*evidence.fullBody), " ") != strings.Join(strings.Fields(a.Content), " ") { + blocked = true + } if a.Content != "" { - a.ContentState = scraper.ContentComplete - if blocked { - a.ContentState = scraper.ContentIncomplete + a.ContentState = scraper.ContentIncomplete + if evidence.associated && !blocked { + a.ContentState = scraper.ContentComplete } } return a } -func nText(n *html.Node) string { - var b strings.Builder - for c := n.FirstChild; c != nil; c = c.NextSibling { - if c.Type == html.TextNode { - b.WriteString(c.Data) - } + +func sameResponseArticle(source, target string, resp *http.Response) bool { + if resp.Request == nil || resp.Request.URL == nil { + return true } - return b.String() + actual, ok := safeURL(source, resp.Request.URL.String()) + return ok && actual == target } diff --git a/backend/internal/scraper/articlecontent/enrichment_test.go b/backend/internal/scraper/articlecontent/enrichment_test.go index 57086b2..0ced37f 100644 --- a/backend/internal/scraper/articlecontent/enrichment_test.go +++ b/backend/internal/scraper/articlecontent/enrichment_test.go @@ -20,11 +20,11 @@ func TestTicket39SourceFixtures(t *testing.T) { if err != nil { t.Fatal(err) } - a := ExtractHTML(source, "https://fixture.invalid/article", raw) + a := ExtractHTML(source, fixtureArticleURL(source), raw) if a.ContentState != scraper.ContentComplete || !strings.Contains(a.Content, "Final editorial paragraph.") || strings.Contains(a.Content, "excluded") || a.PublishedAt == nil { t.Fatalf("bad full content: state=%s date=%v", a.ContentState, a.PublishedAt) } - a = ExtractHTML(source, "https://fixture.invalid/article", append(raw, []byte(`
subscribe
`)...)) + a = ExtractHTML(source, fixtureArticleURL(source), append(raw, []byte(`
subscribe
`)...)) if a.ContentState != scraper.ContentIncomplete { t.Fatal("paywall claimed complete") } @@ -33,7 +33,7 @@ func TestTicket39SourceFixtures(t *testing.T) { } func TestTicket39FetchRestrictionsAndFullBody(t *testing.T) { calls := 0 - body := "

" + strings.Repeat("Full editorial paragraph. ", 2000) + "

" + body := `` + "

" + strings.Repeat("Full editorial paragraph. ", 2000) + "

" client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) { calls++ return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil @@ -73,3 +73,10 @@ func TestTicket39EditorialHeadingsListsAndQuotesAreNotDropped(t *testing.T) { } } } + +func fixtureArticleURL(source string) string { + if source == "yahoo_finance" { + return "https://finance.yahoo.com/news/fixture.html" + } + return "https://www.cnbc.com/2026/01/02/fixture.html" +} diff --git a/backend/internal/scraper/articlecontent/evidence.go b/backend/internal/scraper/articlecontent/evidence.go new file mode 100644 index 0000000..d52b437 --- /dev/null +++ b/backend/internal/scraper/articlecontent/evidence.go @@ -0,0 +1,169 @@ +package articlecontent + +import ( + "encoding/json" + "golang.org/x/net/html" + "net/url" + "strings" + "time" +) + +type articleEvidence struct { + associated, mismatch, blocked, dateConflict bool + date *time.Time + fullBody *string +} + +func inspectEvidence(doc *html.Node, source, expected string) articleEvidence { + e := articleEvidence{} + wanted, valid := safeURL(source, expected) + key := func(value string) string { + if value == "" { + return "" + } + base, err := url.Parse(expected) + if err != nil { + return "" + } + ref, err := url.Parse(value) + if err != nil { + return "" + } + value, ok := safeURL(source, base.ResolveReference(ref).String()) + if !ok { + return "" + } + return value + } + primary, articleIDs, matching := 0, 0, false + recordDate := func(value string) { + if parsed, err := time.Parse(time.RFC3339Nano, value); err == nil { + if e.date != nil && !e.date.Equal(parsed) { + e.dateConflict = true + } else { + e.date = &parsed + } + } + } + identity := func(v any) string { + switch x := v.(type) { + case string: + return x + case map[string]any: + s, _ := x["@id"].(string) + return s + } + return "" + } + visited := 0 + var inspect func(any, int) + inspect = func(v any, depth int) { + visited++ + if depth > 32 || visited > 2000 { + return + } + switch x := v.(type) { + case []any: + for _, v := range x { + inspect(v, depth+1) + } + case map[string]any: + types := []string{} + switch typ := x["@type"].(type) { + case string: + types = append(types, typ) + case []any: + for _, v := range typ { + if t, ok := v.(string); ok { + types = append(types, t) + } + } + } + article := false + for _, typ := range types { + if typ == "Article" || typ == "NewsArticle" || typ == "ReportageNewsArticle" { + article = true + } + } + if article { + value := identity(x["url"]) + if value == "" { + value = identity(x["mainEntityOfPage"]) + } + if value == "" { + value = identity(x["@id"]) + } + if value != "" { + articleIDs++ + } + if valid && key(value) == wanted { + e.associated = true + matching = true + if x["isAccessibleForFree"] == false || strings.EqualFold(identity(x["isAccessibleForFree"]), "false") { + e.blocked = true + } + if d, ok := x["datePublished"].(string); ok { + recordDate(d) + } + if body, ok := x["articleBody"].(string); ok { + e.fullBody = &body + } + } + } + // Traverse metadata graphs and nested Article objects, never HTML text. + for _, v := range x { + if _, ok := v.(map[string]any); ok { + inspect(v, depth+1) + } else if _, ok := v.([]any); ok { + inspect(v, depth+1) + } + } + } + } + var walk func(*html.Node) + walk = func(n *html.Node) { + if n.Type == html.ElementNode { + value := "" + if n.Data == "link" && strings.EqualFold(attr(n, "rel"), "canonical") { + value = attr(n, "href") + } + if n.Data == "meta" && attr(n, "property") == "og:url" { + value = attr(n, "content") + } + if value != "" { + primary++ + if valid && key(value) == wanted { + e.associated = true + } else { + e.mismatch = true + } + } + if n.Data == "meta" && (attr(n, "property") == "article:published_time" || attr(n, "itemprop") == "datePublished") { + recordDate(attr(n, "content")) + } + if n.Data == "time" && attr(n, "itemprop") == "datePublished" { + recordDate(attr(n, "datetime")) + } + if n.Data == "script" && attr(n, "type") == "application/ld+json" { + var text strings.Builder + for c := n.FirstChild; c != nil; c = c.NextSibling { + if c.Type == html.TextNode { + text.WriteString(c.Data) + } + } + var value any + if json.Unmarshal([]byte(text.String()), &value) == nil { + inspect(value, 0) + } + } + } + for c := n.FirstChild; c != nil; c = c.NextSibling { + walk(c) + } + } + walk(doc) + if primary == 0 && articleIDs > 0 && !matching { + e.mismatch = true + } + return e +} diff --git a/backend/internal/scraper/articlecontent/testdata/cnbc_business.html b/backend/internal/scraper/articlecontent/testdata/cnbc_business.html index 69f3c26..ff24f3f 100644 --- a/backend/internal/scraper/articlecontent/testdata/cnbc_business.html +++ b/backend/internal/scraper/articlecontent/testdata/cnbc_business.html @@ -1 +1 @@ -
excluded navigation

Synthetic first editorial paragraph.

excluded recommendation

Final editorial paragraph.

+
excluded navigation

Synthetic first editorial paragraph.

excluded recommendation

Final editorial paragraph.

diff --git a/backend/internal/scraper/articlecontent/testdata/cnbc_module.html b/backend/internal/scraper/articlecontent/testdata/cnbc_module.html new file mode 100644 index 0000000..5adb6d7 --- /dev/null +++ b/backend/internal/scraper/articlecontent/testdata/cnbc_module.html @@ -0,0 +1,4 @@ + + + +

Synthetic heading.

Synthetic initial paragraph.

Synthetic editorial quotation.
Final editorial paragraph.
diff --git a/backend/internal/scraper/articlecontent/testdata/yahoo_finance.html b/backend/internal/scraper/articlecontent/testdata/yahoo_finance.html index b3f95bc..2218184 100644 --- a/backend/internal/scraper/articlecontent/testdata/yahoo_finance.html +++ b/backend/internal/scraper/articlecontent/testdata/yahoo_finance.html @@ -1 +1 @@ -

Synthetic first editorial paragraph.

Final editorial paragraph.

+

Synthetic first editorial paragraph.

Final editorial paragraph.

diff --git a/backend/internal/scraper/articlecontent/testdata/yahoo_modern.html b/backend/internal/scraper/articlecontent/testdata/yahoo_modern.html new file mode 100644 index 0000000..5088e25 --- /dev/null +++ b/backend/internal/scraper/articlecontent/testdata/yahoo_modern.html @@ -0,0 +1,4 @@ + + + +

Synthetic heading.

Synthetic initial paragraph.

  • Synthetic list detail.
Final editorial paragraph.
diff --git a/backend/internal/scraper/yahoofinance/diagnostics_ticket20_test.go b/backend/internal/scraper/yahoofinance/diagnostics_ticket20_test.go index bcd8e06..b223ef9 100644 --- a/backend/internal/scraper/yahoofinance/diagnostics_ticket20_test.go +++ b/backend/internal/scraper/yahoofinance/diagnostics_ticket20_test.go @@ -46,8 +46,8 @@ func TestTicket20Yahoo400DiagnosticConnectsSymbolsStatusAndCountWithoutResponseB var articles int logs := ticket20CaptureStdout(t, func() { got, err := yahoo.Scrape(context.Background(), []string{"SSAAPL INDEX"}) - if err != nil { - t.Fatalf("Scrape returned error: %v", err) + if err == nil { + t.Fatal("failed RSS must be a source failure, not a reachable empty source") } articles = len(got) }) diff --git a/backend/internal/scraper/yahoofinance/reachability_ticket40_test.go b/backend/internal/scraper/yahoofinance/reachability_ticket40_test.go new file mode 100644 index 0000000..b4307b0 --- /dev/null +++ b/backend/internal/scraper/yahoofinance/reachability_ticket40_test.go @@ -0,0 +1,29 @@ +package yahoofinance + +import ( + "context" + "github.com/tradarr/backend/internal/scraper" + "io" + "net/http" + "strings" + "testing" +) + +func TestTicket40FailedRSSIsNotReportedAsReachableEmptySource(t *testing.T) { + y := &YahooFinance{client: &http.Client{Transport: ticket20RoundTrip(func(r *http.Request) (*http.Response, error) { + return &http.Response{StatusCode: 503, Body: io.NopCloser(strings.NewReader("PRIVATE unavailable")), Header: make(http.Header), Request: r}, nil + })}} + a, err := y.Scrape(context.Background(), []string{"FIX"}) + if err == nil || len(a) != 0 || strings.Contains(err.Error(), "PRIVATE") { + t.Fatal("failed RSS must produce a sanitized source failure") + } +} +func TestTicket40RSSDescriptionNeverClaimsComplete(t *testing.T) { + y := &YahooFinance{client: &http.Client{Transport: ticket20RoundTrip(func(r *http.Request) (*http.Response, error) { + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`Fixturehttps://finance.yahoo.com/news/fixture.htmlSynthetic RSS teaser.`)), Header: make(http.Header), Request: r}, nil + })}} + a, err := y.Scrape(context.Background(), []string{"FIX"}) + if err != nil || len(a) != 1 || scraper.ContentStatus(a[0]) == scraper.ContentComplete { + t.Fatal("RSS description claimed full article") + } +} diff --git a/backend/internal/scraper/yahoofinance/yahoofinance.go b/backend/internal/scraper/yahoofinance/yahoofinance.go index 43f2b05..1fd4e84 100644 --- a/backend/internal/scraper/yahoofinance/yahoofinance.go +++ b/backend/internal/scraper/yahoofinance/yahoofinance.go @@ -3,6 +3,7 @@ package yahoofinance import ( "context" "encoding/xml" + "errors" "fmt" "net/http" "strings" @@ -37,6 +38,7 @@ type rssFeed struct { func (y *YahooFinance) Scrape(ctx context.Context, symbols []string) ([]scraper.Article, error) { var articles []scraper.Article + reachable := false for i, symbol := range symbols { if i > 0 { @@ -50,8 +52,12 @@ func (y *YahooFinance) Scrape(ctx context.Context, symbols []string) ([]scraper. if err != nil { continue } + reachable = true articles = append(articles, items...) } + if len(symbols) > 0 && !reachable { + return nil, errors.New("yahoofinance: source unavailable") + } return articles, nil } diff --git a/docs/operations.md b/docs/operations.md index dc5dbb0..cb8e2b2 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -222,3 +222,81 @@ Le worker utilise son propre contexte borné à deux heures. Navigation, déconn Au démarrage du serveur, les jobs `running` du processus précédent deviennent `failed/interrupted`. Ils ne sont pas relancés automatiquement, pour éviter de répéter les appels fournisseurs. L’opérateur peut alors démarrer une nouvelle génération. Cette récupération suppose un seul processus serveur actif (déploiement actuel) ; elle n’est pas un mécanisme de bail pour un déploiement multi-réplicas. Une erreur de récupération empêche le démarrage. Une erreur de finalisation DB est signalée par un log générique ; le job resté `running` sera récupéré au prochain redémarrage. Le downgrade 000019 refuse une suppression implicite de l’historique. Ce changement porte sur les générations manuelles ; le scheduler conserve son flux de génération existant. L’interface doit utiliser ce contrat asynchrone avant livraison du parcours complet. + +## Rebuild ciblé du récupérateur et diagnostic de complétude (#40) + +Depuis la racine du projet, avec la configuration Compose existante, reconstruire +uniquement le service du récupérateur : + +```sh +docker compose up --build scraper +``` + +La commande reste au premier plan et peut démarrer sa dépendance `byparr` ; elle +ne démarre ni `backend`, ni Laya, ni le scheduler. Garder le backend déjà arrêté +si l'intervention doit exclure toute collecte automatique ; cette commande +n'arrête pas un backend qui tournait auparavant. Ne pas utiliser `make up` ou un +`docker compose up` sans nom de service pour cette intervention. Aucune lecture +ou réimpression de credentials Bloomberg n'est nécessaire. + +Dans un autre terminal, vérifier localement la présence de la route, sans fournir +de credentials, sans ouvrir de navigateur et sans contacter Bloomberg : + +```sh +docker compose exec -T scraper node -e "fetch('http://127.0.0.1:3001/bloomberg/enrich', {method:'POST', headers:{'Content-Type':'application/json'}, body:'{}'}).then(r => {console.log(r.status); if(r.status !== 400) process.exitCode=1}).catch(() => {console.error('verification indisponible'); process.exitCode=1})" +``` + +Le résultat attendu est **400** (validation du corps), et non **404** (ancienne +image ou mauvaise route). Ce contrôle ne déclenche aucune récupération et ne +prouve ni l'authentification ni la disponibilité d'un article réel. Aucun rebuild, +démarrage Docker ou essai live n'est requis par les tests de ce ticket. + +Les rubriques Bloomberg conservent Byparr. `/bloomberg/enrich` réutilise toujours +la session Puppeteer authentifiée et les identifiants déjà reçus du backend, +même avec `BYPARR_URL`. Un échec d'authentification n'active aucun fallback anonyme. +Les états de contenu restent `complete`, `incomplete`, `unavailable` : HTTP 200 +ou deux paragraphes disponibles ne constituent pas une preuve de corps complet. + +L'association exige une identité de page canonique/`og:url` ou un objet Article +JSON-LD correspondant à l'URL attendue. Une identité contradictoire rejette le +corps et sa date. Une racine éditoriale inconnue/ambiguë est indisponible ; une +racine reconnue sans association est au mieux partielle. GiftArticle, +placeholders/squelettes éditoriaux, challenge/captcha, paywall, état partial ou +troncature annoncée interdisent `complete`. Si un `articleBody` associé existe +mais ne correspond pas au texte éditorial extrait, le résultat est partiel. +Aucun seuil arbitraire de longueur ne transforme un extrait en article complet. + +Yahoo reconnaît `caas-body` et la variante `article .body.yf-*` ; CNBC reconnaît +`ArticleBody-articleBody` et le module explicite `data-module="ArticleBody"`. +Les paragraphes, intertitres, listes, citations et texte éditorial direct sont +conservés, en excluant navigation, recommandations et placeholders. Les +métadonnées étrangères ne fournissent ni association ni date ; des dates +contradictoires restent nulles. Les descriptions RSS restent des extraits. + +Les fixtures ajoutées sont **synthétiques**, sans prose d'éditeur : notamment +GiftArticle avec dix-neuf placeholders, variantes Yahoo/CNBC et pages de blocage. +Elles démontrent les critères structurels testés, pas la compatibilité live d'une +page éditeur future. Sans identité/racine reconnue ou en présence de pièces +manquantes, aucun corps complet n'est revendiqué. Un extrait non marqué dans une +structure autrement valide ne peut être distingué d'un petit article par le +seul HTML : `complete` décrit les preuves structurelles disponibles, pas une +validation indépendante de la longueur éditoriale chez le fournisseur. + +### Contrat du bilan pour le frontend + +Chaque `source_stats[]` ajoute `source_key` (`yahoo_finance`, `bloomberg`, +`cnbc_business`). Le frontend doit choisir le libellé canonique à partir de cette +clé et conserver un fallback pour les anciens bilans où elle manque. Le champ +legacy `source_type` reste inchangé ; aucune migration de `stocktwits` ni +réécriture de l'historique n'est effectuée. + +`status: "ok"` décrit la collecte sans erreur, distincte des compteurs +`content_complete`, `content_incomplete`, `content_unavailable`. Un échec de tous +les flux Yahoo est une erreur de source, et non un succès vide. En revanche, +une collecte réussie suivie de corps absents/partiels garde `status: "ok"` et ses +compteurs explicites. N'affirmer une cause abonnement/auth/challenge que si elle +est établie ; le bilan ne transmet pas de diagnostic sensible ou de cause précise +par article. Seuls les corps qualifiés complets restent sélectionnables en mode +`title_content`. Le code `no_complete_content` reste explicite si aucun ne l'est. +Articles, pages et URL restent transitoires ; seuls ces agrégats et la synthèse +éventuelle sont persistés. Aucun nouveau champ article n'est exposé dans le bilan. diff --git a/frontend/src/api/summaries.ts b/frontend/src/api/summaries.ts index c9cf0c3..c5a26fc 100644 --- a/frontend/src/api/summaries.ts +++ b/frontend/src/api/summaries.ts @@ -27,6 +27,7 @@ export interface PromptBudgetUsage { export interface SourceGenerationStat extends ContentCompleteness { source_id: string + source_key?: string | null source_type: string status: string candidates: number diff --git a/frontend/src/components/GenerationDetails.tsx b/frontend/src/components/GenerationDetails.tsx index 2750172..8268f19 100644 --- a/frontend/src/components/GenerationDetails.tsx +++ b/frontend/src/components/GenerationDetails.tsx @@ -1,11 +1,30 @@ -import type { GenerationOutcome } from '@/api/summaries' +import type { GenerationOutcome, SourceGenerationStat } from '@/api/summaries' -function sourceLabel(type: string) { - return type === 'cnbc_business' ? 'CNBC Business' : type +function sourceLabel(key?: string | null) { + switch (key) { + case 'yahoo_finance': return 'Yahoo Finance' + case 'bloomberg': return 'Bloomberg' + case 'cnbc_business': return 'CNBC Business' + default: return 'Source non identifiée' + } +} + +function sourceState(source: SourceGenerationStat, mode: GenerationOutcome['ranking_mode']) { + if (source.status === 'failed') return 'Récupération impossible' + if (source.status !== 'ok') return 'État de collecte non renseigné' + if (mode === 'title') return 'Source joignable · contenu non évalué' + const counts = [source.content_complete, source.content_incomplete, source.content_unavailable] + if (counts.some(count => count === undefined)) return 'Source joignable · complétude non renseignée' + if (source.candidates === 0) return 'Source joignable · aucun article examiné' + if (counts.filter(count => (count ?? 0) > 0).length > 1) return 'Source joignable · contenus de complétude variable' + if ((source.content_complete ?? 0) > 0) return 'Source joignable · contenus complets' + if ((source.content_incomplete ?? 0) > 0) return 'Source joignable · contenu partiel' + if ((source.content_unavailable ?? 0) > 0) return 'Source joignable · contenu absent' + return 'Source joignable · complétude non renseignée' } export function GenerationDetails({ outcome }: { outcome: GenerationOutcome }) { - const unavailable = outcome.source_stats.filter(source => source.status === 'failed').map(source => sourceLabel(source.source_type)) + const unavailable = outcome.source_stats.filter(source => source.status === 'failed').map(source => sourceLabel(source.source_key)) const hasCompleteness = outcome.content_complete !== undefined && outcome.content_incomplete !== undefined && outcome.content_unavailable !== undefined const usage = outcome.prompt_budget const number = (value: number) => value.toLocaleString('fr-FR') @@ -42,14 +61,16 @@ export function GenerationDetails({ outcome }: { outcome: GenerationOutcome }) {

{outcome.ranking_mode === 'title_content' ? 'Classement effectué à partir des titres et du contenu disponible.' : 'Classement effectué à partir des titres uniquement.'}

Plafond global : {outcome.global_limit} articles par génération

{!hasCompleteness && outcome.content_fallbacks > 0 &&

Pour {outcome.content_fallbacks} articles examinés, le contenu était indisponible. Laya a utilisé leur titre uniquement.

} +

Une réponse HTTP 200 ne garantit pas que le texte intégral d’un article soit accessible. L’état de collecte et la complétude des contenus sont distincts.

+ {outcome.ranking_mode === 'title_content' && outcome.source_stats.some(source => (source.content_incomplete ?? 0) > 0 || (source.content_unavailable ?? 0) > 0) &&

Le texte intégral n’a pas pu être récupéré pour certains articles. Le bilan ne permet pas d’en confirmer la cause.

}
- {outcome.ranking_mode === 'title_content' && <>} + {outcome.ranking_mode === 'title_content' && <>}{outcome.source_stats.map(source => ( - - + + {outcome.ranking_mode === 'title_content' && <>} diff --git a/frontend/tests/dashboard-generation.test.tsx b/frontend/tests/dashboard-generation.test.tsx index 6568edd..f409231 100644 --- a/frontend/tests/dashboard-generation.test.tsx +++ b/frontend/tests/dashboard-generation.test.tsx @@ -67,12 +67,12 @@ const outcome = (status: string, overrides: Record = {}) => ({ global_limit: 50, source_stats: [ { - source_id: 'source-yahoo', source_type: 'Yahoo Finance', status: 'ok', + source_id: 'source-yahoo', source_key: 'yahoo_finance', source_type: 'Yahoo Finance', status: 'ok', candidates: 15, laya_selected: 12, selected: 10, article_limit: 20, content_fallbacks: 0, }, { - source_id: 'source-bloomberg', source_type: 'Bloomberg', status: 'ok', + source_id: 'source-bloomberg', source_key: 'bloomberg', source_type: 'Bloomberg', status: 'ok', candidates: 15, laya_selected: 8, selected: 8, article_limit: 20, content_fallbacks: 0, }, @@ -288,12 +288,12 @@ describe('Dashboard — génération de synthèses éphémères', () => { content_fallbacks: 8, source_stats: [ { - source_id: 'source-yahoo', source_type: 'Yahoo Finance', status: 'ok', + source_id: 'source-yahoo', source_key: 'yahoo_finance', source_type: 'Yahoo Finance', status: 'ok', candidates: 20, laya_selected: 18, selected: 10, article_limit: 20, content_fallbacks: 8, }, { - source_id: 'source-bloomberg', source_type: 'Bloomberg', status: 'failed', + source_id: 'source-bloomberg', source_key: 'bloomberg', source_type: 'Bloomberg', status: 'failed', candidates: 0, laya_selected: 0, selected: 0, article_limit: 20, content_fallbacks: 0, failure_code: 'source_unavailable', }, diff --git a/frontend/tests/prompt-budget-ticket39.test.tsx b/frontend/tests/prompt-budget-ticket39.test.tsx index b005e41..eb65d43 100644 --- a/frontend/tests/prompt-budget-ticket39.test.tsx +++ b/frontend/tests/prompt-budget-ticket39.test.tsx @@ -83,7 +83,7 @@ const outcome = { content_complete: 3, content_incomplete: 2, content_unavailable: 1, dates_available: 4, failure_code: 'content_incomplete', prompt_budget: { requested_tokens: 250000, effective_tokens: 123904, prompt_tokens: 42000, output_reserve_tokens: 4096, token_count_method: 'utf8_bytes_upper_bound_v1' }, - source_stats: [{ source_id: 'y', source_type: 'Yahoo Finance', status: 'ok', candidates: 6, selected: 2, laya_selected: 2, article_limit: 10, content_fallbacks: 1, content_complete: 3, content_incomplete: 2, content_unavailable: 1, dates_available: 4 }], + source_stats: [{ source_id: 'y', source_key: 'yahoo_finance', source_type: 'Yahoo Finance', status: 'ok', candidates: 6, selected: 2, laya_selected: 2, article_limit: 10, content_fallbacks: 1, content_complete: 3, content_incomplete: 2, content_unavailable: 1, dates_available: 4 }], } as GenerationOutcome it('présente uniquement les compteurs agrégés et les budgets, avec les limites de la couverture partielle', () => { diff --git a/frontend/tests/source-completeness-ticket40.test.tsx b/frontend/tests/source-completeness-ticket40.test.tsx new file mode 100644 index 0000000..09c29a3 --- /dev/null +++ b/frontend/tests/source-completeness-ticket40.test.tsx @@ -0,0 +1,80 @@ +import { cleanup, fireEvent, render, screen, within } from '@testing-library/react' +import { afterEach, expect, it } from 'vitest' +import { GenerationDetails } from '../src/components/GenerationDetails' +import type { GenerationOutcome, SourceGenerationStat } from '../src/api/summaries' + +afterEach(cleanup) +const stat = (overrides: Record = {}): SourceGenerationStat => ({ + source_id: 'source', source_type: 'stocktwits', status: 'ok', candidates: 6, + selected: 2, laya_selected: 2, article_limit: 10, content_fallbacks: 1, + content_complete: 3, content_incomplete: 2, content_unavailable: 1, dates_available: 4, + ...overrides, +}) +const outcome = (source: SourceGenerationStat, overrides: Partial = {}): GenerationOutcome => ({ + id: 'generation', status: 'partial', language: 'fr', ranking_mode: 'title_content', + total_candidates: 6, selected: 2, laya_selected: 2, global_limit: 50, content_fallbacks: 1, + content_complete: 3, content_incomplete: 2, content_unavailable: 1, dates_available: 4, + failure_code: 'content_incomplete', source_stats: [source], ...overrides, +}) +function show(value: GenerationOutcome) { + const view = render() + fireEvent.click(screen.getByText('Détails de la génération')) + return view +} + +it.each([ + ['yahoo_finance', 'Yahoo Finance'], ['bloomberg', 'Bloomberg'], ['cnbc_business', 'CNBC Business'], + [undefined, 'Source non identifiée'], [null, 'Source non identifiée'], ['unknown', 'Source non identifiée'], + ['stocktwits', 'Source non identifiée'], ['toString', 'Source non identifiée'], +])('nomme %s à partir de la clé canonique, sans exposer le type legacy', (source_key, label) => { + const { container } = show(outcome(stat({ source_key }))) + expect(screen.getByRole('rowheader', { name: label })).toBeInTheDocument() + expect(container.innerHTML).not.toMatch(/stocktwits/i) +}) + +it.each([ + [0, 0, 6, 'Source joignable · contenu absent'], + [0, 6, 0, 'Source joignable · contenu partiel'], + [6, 0, 0, 'Source joignable · contenus complets'], + [3, 2, 1, 'Source joignable · contenus de complétude variable'], + [0, 2, 4, 'Source joignable · contenus de complétude variable'], +])('distingue la collecte de la complétude (%s/%s/%s)', (complete, incomplete, unavailable, label) => { + show(outcome(stat({ source_key: 'bloomberg', content_complete: complete, content_incomplete: incomplete, content_unavailable: unavailable }))) + const row = screen.getByRole('row', { name: /Bloomberg/ }) + expect(within(row).getByRole('cell', { name: label, exact: true })).toBeInTheDocument() + expect(screen.queryByRole('cell', { name: 'Disponible', exact: true })).not.toBeInTheDocument() + expect(screen.getByText(/HTTP 200 ne garantit pas/)).toBeInTheDocument() +}) + +it('conserve les agrégats, les compteurs par source et l’éligibilité sans inventer une cause', () => { + const { container } = show(outcome(stat({ source_key: 'yahoo_finance', failure_code: 'PRIVATE_CAUSE', title: 'PRIVATE_TITLE', url: 'https://private.invalid', content: 'PRIVATE_CONTENT', prompt: 'PRIVATE_PROMPT' }))) + const table = screen.getByRole('table', { name: 'Bilan par source' }) + for (const name of ['Articles examinés', 'Contenus complets', 'Contenus partiels', 'Contenus absents']) { + expect(within(table).getByRole('columnheader', { name })).toBeInTheDocument() + } + const row = within(table).getByRole('row', { name: /Yahoo Finance/ }) + expect(within(row).getAllByRole('cell').map(cell => cell.textContent)).toEqual([ + 'Source joignable · contenus de complétude variable', '6', '2', '2', '10', '4', '3', '2', '1', + ]) + expect(screen.getByText('Contenus complets : 3')).toBeInTheDocument() + expect(screen.getByText(/Seuls les contenus complets sont éligibles/)).toBeInTheDocument() + expect(screen.getByText(/Le texte intégral n’a pas pu être récupéré pour certains articles/)).toBeInTheDocument() + expect(container.innerHTML).not.toMatch(/PRIVATE_|private.invalid|abonnement|authentification|challenge|captcha|paywall/i) +}) + +it('signale un échec de récupération et utilise aussi la clé dans l’avertissement de couverture', () => { + const { container } = show(outcome(stat({ source_key: 'bloomberg', status: 'failed' }))) + expect(screen.getByRole('cell', { name: 'Récupération impossible' })).toBeInTheDocument() + expect(screen.getByText(/sans Bloomberg, indisponible lors du traitement/)).toBeInTheDocument() + expect(container.innerHTML).not.toMatch(/stocktwits/i) +}) + +it.each([ + ['title', { content_complete: 0, content_incomplete: 0, content_unavailable: 0 }, 'Source joignable · contenu non évalué'], + ['title_content', { content_complete: undefined, content_incomplete: undefined, content_unavailable: undefined }, 'Source joignable · complétude non renseignée'], + ['title_content', { candidates: 0, content_complete: 0, content_incomplete: 0, content_unavailable: 0 }, 'Source joignable · aucun article examiné'], + ['title_content', { status: 'unknown' }, 'État de collecte non renseigné'], +])('ne fabrique pas de complétude en mode %s', (ranking_mode, values, label) => { + show(outcome(stat({ source_key: 'cnbc_business', ...values }), { ranking_mode: ranking_mode as 'title' | 'title_content' })) + expect(screen.getByRole('cell', { name: label, exact: true })).toBeInTheDocument() +}) diff --git a/frontend/tests/source-diagnostics-ticket23.test.tsx b/frontend/tests/source-diagnostics-ticket23.test.tsx index da64454..37df530 100644 --- a/frontend/tests/source-diagnostics-ticket23.test.tsx +++ b/frontend/tests/source-diagnostics-ticket23.test.tsx @@ -5,29 +5,30 @@ import type { GenerationOutcome } from '../src/api/summaries' afterEach(cleanup) -function outcome(sourceType: string): GenerationOutcome { +function outcome(sourceType: string, sourceKey?: string): GenerationOutcome { return { id: 'generation-23', status: 'partial', language: 'fr', ranking_mode: 'title', total_candidates: 0, content_fallbacks: 0, laya_selected: 0, selected: 0, global_limit: 50, - source_stats: [{ source_id: 'source-23', source_type: sourceType, status: 'failed', candidates: 0, laya_selected: 0, selected: 0, article_limit: 20, content_fallbacks: 0, failure_code: 'source_unavailable' }], + source_stats: [{ source_id: 'source-23', source_key: sourceKey, source_type: sourceType, status: 'failed', candidates: 0, laya_selected: 0, selected: 0, article_limit: 20, content_fallbacks: 0, failure_code: 'source_unavailable' }], } } it('nomme CNBC Business dans le diagnostic agrégé sans exposer de détails de récupération', () => { - const result = outcome('cnbc_business') + const result = outcome('cnbc_business', 'cnbc_business') render() expect(screen.getByText('Cette synthèse a été générée sans CNBC Business, indisponible lors du traitement.')).toBeInTheDocument() const row = screen.getByText('CNBC Business').closest('tr')! - expect(within(row).getByText('Indisponible')).toBeInTheDocument() + expect(within(row).getByText('Récupération impossible')).toBeInTheDocument() expect(screen.queryByText('source_unavailable')).not.toBeInTheDocument() expect(screen.queryByRole('link')).not.toBeInTheDocument() }) -it.each(['watcherguru', 'Watcher.Guru', 'Watcher Guru'])('garde le bilan historique %s sans réécrire son identité', sourceType => { +it.each(['watcherguru', 'Watcher.Guru', 'Watcher Guru'])('affiche le fallback du bilan historique %s sans réécrire ses données', sourceType => { const result = outcome(sourceType) const before = JSON.stringify(result) render() - expect(screen.getByText(sourceType, { exact: true })).toBeInTheDocument() + expect(screen.getByText('Source non identifiée', { exact: true })).toBeInTheDocument() + expect(screen.queryByText(sourceType, { exact: true })).not.toBeInTheDocument() expect(screen.queryByText(/CNBC Business/)).not.toBeInTheDocument() expect(JSON.stringify(result)).toBe(before) }) diff --git a/scraper-service/article-content.js b/scraper-service/article-content.js index 74e5bd3..54a88d7 100644 --- a/scraper-service/article-content.js +++ b/scraper-service/article-content.js @@ -7,15 +7,56 @@ const CONCURRENCY = 2 const ARTICLE_TIMEOUT_MS = 30000 const TOTAL_TIMEOUT_MS = 90000 +// Identity is established from primary page metadata or an associated Article +// object, never from an arbitrary anchor or the presence of editorial classes. +function articleEvidence ($, expectedURL) { + const expected = canonicalURL(expectedURL) + const key = value => { + if (typeof value !== 'string' || !value.trim()) return null + try { return canonicalURL(new URL(value, expectedURL).href) } catch { return null } + } + const primary = $('link[rel="canonical"], meta[property="og:url"]').toArray().map(n => $(n).attr(n.tagName === 'link' ? 'href' : 'content')).filter(Boolean) + let associated = Boolean(expected && primary.some(v => key(v) === expected)) + let mismatch = Boolean(expected && primary.some(v => key(v) !== expected)) + let blocked = false; let fullBody = null; let articleIdentities = 0; let matching = false + for (const script of $('script[type="application/ld+json"]').toArray()) { + try { + const stack = [[JSON.parse($(script).text()), 0]]; let visited = 0 + while (stack.length && ++visited <= 2000) { + const [node, depth] = stack.pop() + if (!node || typeof node !== 'object' || depth > 32) continue + const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']] + if (types.some(t => ['Article', 'NewsArticle', 'ReportageNewsArticle'].includes(t))) { + const identity = node.url || node.mainEntityOfPage || node['@id'] + const value = typeof identity === 'string' ? identity : identity?.['@id'] + if (value) articleIdentities++ + if (expected && key(value) === expected) { + associated = matching = true + if (node.isAccessibleForFree === false || String(node.isAccessibleForFree).toLowerCase() === 'false') blocked = true + if (typeof node.articleBody === 'string') fullBody = node.articleBody + } + } + for (const child of Object.values(node)) if (child && typeof child === 'object') stack.push([child, depth + 1]) + } + } catch { /* Unusable metadata cannot prove completeness. */ } + } + if (!primary.length && articleIdentities && !matching) mismatch = true + return { associated, mismatch, blocked, fullBody } +} + function extractArticle (html, articleURL) { const empty = { content: '', published_at: null, content_truncated: false, content_state: 'unavailable' } if (typeof html !== 'string' || Buffer.byteLength(html) > MAX_HTML_BYTES) return empty const $ = cheerio.load(html) + const evidence = articleEvidence($, articleURL) + if (evidence.mismatch) return empty const roots = $('article.articleLayout_basic__gcpQk div.body-content, article div.FeatureContent_body__NTf8M') const root = roots.length === 1 ? roots.first() : $() + const excludedRoot = 'aside, nav, footer, [hidden], [aria-hidden="true"], [data-component="related-stories"]' + if (root.is(excludedRoot) || root.parents(excludedRoot).length) return empty const paragraphs = [] root.find('p.ArticleBodyText_articleBodyContent__17wqE, p.typography_articleBody___5jDr, h1, h2, h3, h4, h5, h6, li, blockquote, pre, figcaption, tr').each((_, node) => { - const excluded = 'script, style, noscript, nav, aside, footer, button, form, svg, [hidden], [aria-hidden="true"], .placeholder, .disclaimer, [data-component="placeholder"], [data-component="disclaimer"], [data-component="related-stories"]' + const excluded = 'script, style, noscript, nav, aside, footer, button, form, svg, [hidden], [aria-hidden="true"], [class*="placeholder" i], [class*="skeleton" i], .disclaimer, [data-component="placeholder"], [data-component="disclaimer"], [data-component="related-stories"]' if ($(node).parentsUntil(root).addBack().is(excluded)) return // A nested paragraph is already represented by its enclosing editorial block. if ($(node).parentsUntil(root, 'li, blockquote, pre, figcaption, tr').length) return @@ -29,8 +70,12 @@ function extractArticle (html, articleURL) { const full = paragraphs.join('\n\n') // Keep the full editorial extraction; resource limits reject an extraction // rather than turning a prefix into a supposedly complete article. - const blocked = $('[class*="paywall"], [data-test="paywall"], [data-testid="paywall"], [data-content-state="incomplete"], [data-content-truncated="true"]').length > 0 - return { content: full, published_at: extractPublicationDate(html, articleURL), content_truncated: false, content_state: full ? (blocked ? 'incomplete' : 'complete') : 'unavailable' } + const accessMarkers = $('[class*="giftarticle" i], [class*="paywall" i], [id*="captcha" i], [class*="captcha" i], [id^="cf-chl"], [id^="challenge"], script[src*="challenge-platform"], [data-test="paywall"], [data-testid="paywall"], [data-content-state="incomplete"], [data-content-state="partial"], [data-content-truncated="true"]').length > 0 + const missing = root.find('[class*="placeholder" i], [class*="skeleton" i], [data-component="placeholder"]').addBack('[class*="placeholder" i], [class*="skeleton" i]').length > 0 + const normalized = value => value.normalize('NFC').replace(/\s+/gu, ' ').trim() + const bodyConflict = evidence.fullBody !== null && normalized(evidence.fullBody) !== normalized(full) + const blocked = evidence.blocked || accessMarkers || missing || bodyConflict || !evidence.associated + return { content: full, published_at: evidence.associated ? extractPublicationDate(html, articleURL) : null, content_truncated: false, content_state: full ? (blocked ? 'incomplete' : 'complete') : 'unavailable' } } function canonicalURL (value) { try { diff --git a/scraper-service/index.js b/scraper-service/index.js index dffebef..ab16307 100644 --- a/scraper-service/index.js +++ b/scraper-service/index.js @@ -257,7 +257,8 @@ async function scrapeBloombergViaPuppeteer(username, password, enrichment) { options.signal.addEventListener('abort', close, { once: true }) try { if (options.signal.aborted) throw new Error('article expired') - await articlePage.goto(url, { waitUntil: 'domcontentloaded', timeout: options.timeoutMs }) + const navigation = await articlePage.goto(url, { waitUntil: 'domcontentloaded', timeout: options.timeoutMs }) + if (!navigation || navigation.status() !== 200) throw new Error('article response unavailable') if (canonicalURL(articlePage.url()) !== canonicalURL(url)) throw new Error('article association unavailable') return await articlePage.content() } finally { @@ -341,7 +342,7 @@ app.post('/bloomberg/enrich', async (req, res) => { const { username, password, urls } = req.body || {} if (!username || !password || !Array.isArray(urls) || urls.some(url => typeof url !== 'string')) return res.status(400).json({ error: 'invalid enrichment request' }) if (!urls.length) return res.json({ articles: [] }) - const empty = () => urls.map(url => ({ url, content: '', published_at: null, content_truncated: false })) + const empty = () => urls.map(url => ({ url, content: '', published_at: null, content_truncated: false, content_state: 'unavailable' })) if (!urls.some(url => canonicalURL(url))) return res.json({ articles: empty() }) const controller = new AbortController() const deadline = Date.now() + TOTAL_TIMEOUT_MS @@ -352,9 +353,9 @@ app.post('/bloomberg/enrich', async (req, res) => { const onClose = () => { if (!res.writableEnded) stop() } res.once?.('close', onClose) try { - const operation = BYPARR_URL - ? enrichArticles(urls, async (url, options) => (await byparrFetch(url, true, options)).html, { signal: controller.signal }) - : scrapeBloombergViaPuppeteer(username, password, { urls, signal: controller.signal, deadline }) + // Section discovery still uses Byparr. Article bodies require the existing + // authenticated browser session, with no anonymous transport fallback. + const operation = scrapeBloombergViaPuppeteer(username, password, { urls, signal: controller.signal, deadline }) const articles = await Promise.race([operation.catch(empty), expired]) if (!res.destroyed) res.json({ articles }) } finally { diff --git a/scraper-service/tests/article-content.test.js b/scraper-service/tests/article-content.test.js index 4f81a29..57128da 100644 --- a/scraper-service/tests/article-content.test.js +++ b/scraper-service/tests/article-content.test.js @@ -5,7 +5,8 @@ const paragraph = 'ArticleBodyText_articleBodyContent__17wqE typography_articleB const basic = text => `

${text}

excluded placeholder

` test('observed basic and feature layouts extract only editorial paragraphs within the observed root', () => { for (const html of [basic(' First synthetic paragraph. '), `

First synthetic paragraph.

`]) { - const result = extractArticle(`${html}`) + const identity = "https://www.bloomberg.com/news/articles/fixture" + const result = extractArticle(`${html}`, identity) assert.equal(result.content, 'First synthetic paragraph.') assert.equal(result.published_at, '2026-01-02T03:04:05.000Z') } @@ -16,9 +17,10 @@ test('no broad article/main or JSON-LD content fallback; paragraph normalization assert.equal(extractArticle(basic('one  two') .replace('', `

three\n four

`)).content, 'one two\n\nthree four') }) test('large non-ASCII editorial content remains complete without truncation', () => { - const html = basic('é漢🙂'.repeat(MAX_CONTENT_BYTES)) - const first = extractArticle(html) - assert.equal(first.content, extractArticle(html).content) + const identity = 'https://www.bloomberg.com/news/articles/fixture' + const html = `` + basic('é漢🙂'.repeat(MAX_CONTENT_BYTES)).replace(/
.*?<\/div>/, '') + const first = extractArticle(html, identity) + assert.equal(first.content, extractArticle(html, identity).content) assert.equal(first.content, 'é漢🙂'.repeat(MAX_CONTENT_BYTES)) assert.ok(!first.content.includes('\ufffd')) assert.equal(first.content_truncated, false) @@ -48,7 +50,8 @@ test('failure and ignored cancellation stay bounded without reusing occupied slo test('JSON-LD belonging to another article cannot supply this article date', () => { const html = basic('synthetic paragraph') + '' const result = extractArticle(html, 'https://www.bloomberg.com/news/articles/current') - assert.equal(result.content, 'synthetic paragraph') + assert.equal(result.content, '') + assert.equal(result.content_state, 'unavailable') assert.equal(result.published_at, null) }) diff --git a/scraper-service/tests/completeness-ticket40.test.js b/scraper-service/tests/completeness-ticket40.test.js new file mode 100644 index 0000000..d29d237 --- /dev/null +++ b/scraper-service/tests/completeness-ticket40.test.js @@ -0,0 +1,31 @@ +const { test } = require('node:test') +const assert = require('node:assert/strict') +const fs = require('node:fs') +const path = require('node:path') +const { extractArticle } = require('../article-content') +const url = 'https://www.bloomberg.com/news/articles/fixture' +const full = `

Synthetic first paragraph.

Synthetic final paragraph.

` +test('ticket40 GiftArticle with nineteen placeholders never claims complete', () => { + const raw = fs.readFileSync(path.join(__dirname, 'fixtures/content-gift-placeholders.html'), 'utf8').replace('
', '
'.repeat(18) + '') + assert.equal((raw.match(/Placeholder_placeholder__fixture/g) || []).length, 19) + const a = extractArticle(raw, url) + assert.equal(a.content_state, 'incomplete') + assert.ok(!a.content.includes('Placeholder')) +}) +test('ticket40 completeness requires article identity, a known root and no missing-body markers', () => { + assert.equal(extractArticle(full, url).content_state, 'complete') + for (const marker of ['
', '
', '
', '
']) { + const raw = full.replace('', marker + '') + assert.equal(extractArticle(raw, url).content_state, 'incomplete') + } + assert.equal(extractArticle(full.replace(url, url + '-other'), url).content_state, 'unavailable') + assert.notEqual(extractArticle(full.replace(/]+>/, ''), url).content_state, 'complete') + assert.equal(extractArticle('
challenge
', url).content_state, 'unavailable') + assert.equal(extractArticle(full.replace('body-content', 'unknown-root'), url).content_state, 'unavailable') +}) + +test('ticket40 hidden or recommendation roots are not the requested visible editorial body', () => { + for (const html of [full.replace('class="body-content"', 'class="body-content" hidden'), ``]) { + assert.notEqual(extractArticle(html, url).content_state, 'complete') + } +}) diff --git a/scraper-service/tests/enrichment-route.test.js b/scraper-service/tests/enrichment-route.test.js index a59e21b..58c9b27 100644 --- a/scraper-service/tests/enrichment-route.test.js +++ b/scraper-service/tests/enrichment-route.test.js @@ -6,18 +6,18 @@ const vm = require('node:vm') const { createRequire } = require('node:module') const html = '

Synthetic editorial paragraph.

' -async function request (byparr, failOne = false, poolSize = 2, authTimeout = false) { - const routes = {}; const loads = []; const logs = []; const timers = []; let pages = 0; let closed = false; let active = 0; let peak = 0 +async function request (byparr, failOne = false, poolSize = 2, authTimeout = false, httpDenied = false) { + const routes = {}; const loads = []; const logs = []; const timers = []; let pages = 0; let closed = false; let active = 0; let peak = 0; let byparrCalls = 0; const typed = [] const app = { use () {}, get () {}, post (url, handler) { routes[url] = handler }, listen () {} } const express = () => app; express.json = () => () => {} function page (auth) { let url = ''; let evals = 0 return { - async setViewport () {}, async evaluateOnNewDocument () {}, async waitForSelector () {}, async type () {}, async waitForFunction () {}, + async setViewport () {}, async evaluateOnNewDocument () {}, async waitForSelector () {}, async type (selector,value) {typed.push(value)}, async waitForFunction () {}, async waitForNavigation () { url = 'https://www.bloomberg.com/markets' }, async evaluate () { return evals++ === 0 ? [] : true }, async $ () { return null }, keyboard: { async press () {} }, - async goto (value) { url = value; if (auth && authTimeout) return new Promise(() => {}); if (!auth) { loads.push(value); active++; peak = Math.max(peak, active); await new Promise(resolve => setTimeout(resolve, 1)); active-- } }, url () { return url }, - async content () { return html }, async close () {} + async goto (value) { url = value; if (auth && authTimeout) return new Promise(() => {}); if (!auth) { loads.push(value); active++; peak = Math.max(peak, active); await new Promise(resolve => setTimeout(resolve, 1)); active--; if (failOne && value.endsWith('/b')) throw new Error('PRIVATE loader failed') }; return { status () { return !auth && httpDenied ? 403 : 200 } } }, url () { return url }, + async content () { return `` + html }, async close () {} } } const browser = { async newPage () { return page(pages++ === 0) }, async close () { closed = true } } @@ -33,7 +33,7 @@ async function request (byparr, failOne = false, poolSize = 2, authTimeout = fal setTimeout (fn, ms) { timers.push(ms); if (authTimeout && ms === 30000) { queueMicrotask(fn); return undefined }; if ([2000, 800, 500, 3000].includes(ms)) { queueMicrotask(fn); return undefined }; return setTimeout(fn, ms) }, clearTimeout, console: { log (...values) { logs.push(values.join(' ')) }, error (...values) { logs.push(values.join(' ')) } }, async fetch (_url, options) { - const body = JSON.parse(options.body); loads.push(body.url); active++; peak = Math.max(peak, active) + byparrCalls++; const body = JSON.parse(options.body); loads.push(body.url); active++; peak = Math.max(peak, active) assert.ok(body.maxTimeout <= 30000); assert.ok(options.signal) await new Promise(resolve => setTimeout(resolve, 1)); active-- if (failOne && body.url.endsWith('/b')) throw new Error('PRIVATE_BODY http://private.invalid') @@ -46,10 +46,13 @@ async function request (byparr, failOne = false, poolSize = 2, authTimeout = fal assert.deepEqual(result.articles.map(a => a.url), urls) assert.equal(loads.length, authTimeout ? 0 : poolSize) assert.ok(logs.every(line => !line.includes('PRIVATE') && !line.includes('http') && !line.includes('Synthetic editorial'))) - return { result, pages, peak, closed, timers } + return { result, pages, peak, closed, timers, byparrCalls, typed } } -test('Byparr enrichment endpoint returns content and date from each unique HTML load', async () => { - const { result, peak } = await request(true) +test('enrichment always uses authenticated Puppeteer even when Byparr is configured', async () => { + const { result, peak, pages, closed, byparrCalls, typed } = await request(true) + assert.equal(byparrCalls, 0) + assert.equal(pages, 3); assert.equal(closed,true) + assert.ok(typed.includes('PRIVATE_USER') && typed.includes('PRIVATE_SECRET')) assert.equal(peak, 2) assert.ok(result.articles.every(a => a.content === 'Synthetic editorial paragraph.' && a.published_at === '2026-01-02T03:04:05.000Z')) }) @@ -79,3 +82,15 @@ test('Puppeteer login deadline returns safe empty results and closes the shared assert.equal(result.articles.length,30) assert.ok(result.articles.every(a => a.content === '' && a.published_at === null)) }) + +test('authenticated enrichment failure never falls back to configured anonymous Byparr', async () => { + const {result,closed,byparrCalls} = await request(true,false,30,true) + assert.equal(byparrCalls,0); assert.equal(closed,true) + assert.ok(result.articles.every(a => a.content_state === 'unavailable' && a.content === '')) +}) + +test('HTTP denied article responses cannot be complete even with a plausible editorial DOM', async () => { + const {result,byparrCalls} = await request(true,false,2,false,true) + assert.equal(byparrCalls,0) + assert.ok(result.articles.every(a => a.content_state === 'unavailable' && a.content === '')) +}) diff --git a/scraper-service/tests/fixtures/content-gift-placeholders.html b/scraper-service/tests/fixtures/content-gift-placeholders.html new file mode 100644 index 0000000..f8964ed --- /dev/null +++ b/scraper-service/tests/fixtures/content-gift-placeholders.html @@ -0,0 +1,9 @@ + + + +
+

Synthetic available introduction.

+
+

Synthetic available second paragraph.

+
Bilan par source
SourceÉtatExaminésSélectionnés par LayaRetenusPlafondDates disponiblesContenus completsContenus partielsContenus absents
SourceCollecte et complétudeArticles examinésSélectionnés par LayaRetenusPlafondDates disponiblesContenus completsContenus partielsContenus absents
{sourceLabel(source.source_type)}{source.status === 'failed' ? 'Indisponible' : 'Disponible'}{sourceLabel(source.source_key)}{sourceState(source, outcome.ranking_mode)} {source.candidates}{source.laya_selected}{source.selected}{source.article_limit}{source.dates_available ?? 'Non renseigné'}{source.content_complete ?? 'Non renseigné'}{source.content_incomplete ?? 'Non renseigné'}{source.content_unavailable ?? 'Non renseigné'}