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,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 := `<link rel="canonical" href="` + tc.url + `"><div class="` + tc.root + `"><p>Synthetic editorial introduction.</p><p>Synthetic final editorial paragraph.</p></div>`
for _, marker := range []string{`<div class="Placeholder_content"></div>`, `<div id="px-captcha"></div>`, `<div class="paywall"></div>`, `<div data-content-state="partial"></div>`} {
a := ExtractHTML(tc.source, tc.url, []byte(strings.Replace(full, "</div>", marker+"</div>", 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(`<div class="`+tc.root+`"><p>Unassociated body</p></div>`))
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)
}
})
}
}

View File

@ -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
}

View File

@ -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(`<div class="paywall">subscribe</div>`)...))
a = ExtractHTML(source, fixtureArticleURL(source), append(raw, []byte(`<div class="paywall">subscribe</div>`)...))
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 := "<div class=caas-body><p>" + strings.Repeat("Full editorial paragraph. ", 2000) + "</p></div>"
body := `<link rel="canonical" href="https://finance.yahoo.com/news/fixture.html">` + "<div class=caas-body><p>" + strings.Repeat("Full editorial paragraph. ", 2000) + "</p></div>"
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"
}

View File

@ -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
}

View File

@ -1 +1 @@
<html><head><meta property="article:published_time" content="2026-01-02T03:04:05Z"></head><body><header>excluded navigation</header><div class="ArticleBody-articleBody"><div class="group"><p>Synthetic first editorial paragraph.</p><div data-component="related-stories"><p>excluded recommendation</p></div><p>Final editorial paragraph.</p></div></div></body></html>
<html><head><link rel="canonical" href="https://www.cnbc.com/2026/01/02/fixture.html"><meta property="article:published_time" content="2026-01-02T03:04:05Z"></head><body><header>excluded navigation</header><div class="ArticleBody-articleBody"><div class="group"><p>Synthetic first editorial paragraph.</p><div data-component="related-stories"><p>excluded recommendation</p></div><p>Final editorial paragraph.</p></div></div></body></html>

View File

@ -0,0 +1,4 @@
<!-- Synthetic source-layout contract, no publisher text. -->
<link rel="canonical" href="https://www.cnbc.com/2026/01/02/fixture.html">
<meta property="article:published_time" content="2026-01-02T03:04:05Z">
<div data-module="ArticleBody"><div class="group"><h2>Synthetic heading.</h2><p>Synthetic initial paragraph.</p><blockquote>Synthetic editorial quotation.</blockquote><div>Final editorial paragraph.</div></div><aside>excluded related content</aside></div>

View File

@ -1 +1 @@
<html><head><meta property="article:published_time" content="2026-01-02T03:04:05Z"></head><body><nav>excluded navigation</nav><div class="caas-body"><p>Synthetic first editorial paragraph.</p><aside><p>excluded recommendation</p></aside><p>Final editorial paragraph.</p></div></body></html>
<html><head><link rel="canonical" href="https://finance.yahoo.com/news/fixture.html"><meta property="article:published_time" content="2026-01-02T03:04:05Z"></head><body><nav>excluded navigation</nav><div class="caas-body"><p>Synthetic first editorial paragraph.</p><aside><p>excluded recommendation</p></aside><p>Final editorial paragraph.</p></div></body></html>

View File

@ -0,0 +1,4 @@
<!-- Synthetic source-layout contract, no publisher text. -->
<link rel="canonical" href="https://finance.yahoo.com/news/fixture.html">
<script type="application/ld+json">{"@type":"NewsArticle","url":"https://finance.yahoo.com/news/fixture.html","datePublished":"2026-01-02T03:04:05Z"}</script>
<article><div class="body yf-fixture"><h2>Synthetic heading.</h2><p>Synthetic initial paragraph.</p><ul><li>Synthetic list detail.</li></ul><div>Final editorial paragraph.</div><aside>excluded related content</aside></div></article>

View File

@ -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)
})

View File

@ -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(`<rss><channel><item><title>Fixture</title><link>https://finance.yahoo.com/news/fixture.html</link><description>Synthetic RSS teaser.</description></item></channel></rss>`)), 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")
}
}

View File

@ -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
}