fix(scraper): verify complete article evidence (#40)
This commit is contained in:
@ -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 {
|
||||
|
||||
@ -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 {
|
||||
|
||||
@ -5,7 +5,8 @@ const paragraph = 'ArticleBodyText_articleBodyContent__17wqE typography_articleB
|
||||
const basic = text => `<article class="articleLayout_basic__gcpQk"><div class="body-content"><p class="${paragraph}">${text}</p><div class="placeholder"><p class="${paragraph}">excluded placeholder</p></div></div></article>`
|
||||
test('observed basic and feature layouts extract only editorial paragraphs within the observed root', () => {
|
||||
for (const html of [basic(' First <em>synthetic</em> paragraph. '), `<article><div class="FeatureContent_body__NTf8M"><p class="${paragraph}"> First <em>synthetic</em> paragraph. </p></div></article>`]) {
|
||||
const result = extractArticle(`<nav>excluded navigation</nav><meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z">${html}`)
|
||||
const identity = "https://www.bloomberg.com/news/articles/fixture"
|
||||
const result = extractArticle(`<link rel="canonical" href="${identity}"><nav>excluded navigation</nav><meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z">${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<script>excluded</script>') .replace('</div></article>', `<p class="${paragraph}"> three\n four </p></div></article>`)).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 = `<link rel="canonical" href="${identity}">` + basic('é漢🙂'.repeat(MAX_CONTENT_BYTES)).replace(/<div class="placeholder">.*?<\/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') + '<script type="application/ld+json">{"@type":"NewsArticle","url":"https://www.bloomberg.com/news/articles/other","datePublished":"2026-01-02T03:04:05Z"}</script>'
|
||||
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)
|
||||
})
|
||||
|
||||
|
||||
31
scraper-service/tests/completeness-ticket40.test.js
Normal file
31
scraper-service/tests/completeness-ticket40.test.js
Normal file
@ -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 = `<link rel="canonical" href="${url}"><article class="articleLayout_basic__gcpQk"><div class="body-content"><p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic first paragraph.</p><p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic final paragraph.</p></div></article>`
|
||||
test('ticket40 GiftArticle with nineteen placeholders never claims complete', () => {
|
||||
const raw = fs.readFileSync(path.join(__dirname, 'fixtures/content-gift-placeholders.html'), 'utf8').replace('</div></article>', '<div class="Placeholder_placeholder__fixture"></div>'.repeat(18) + '</div></article>')
|
||||
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 ['<div class="GiftArticle_teaser"></div>', '<div class="Placeholder_placeholder__x"></div>', '<div id="px-captcha"></div>', '<div class="paywall"></div>']) {
|
||||
const raw = full.replace('</div></article>', marker + '</div></article>')
|
||||
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(/<link[^>]+>/, ''), url).content_state, 'complete')
|
||||
assert.equal(extractArticle('<div id="px-captcha">challenge</div>', 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'), `<aside>${full}</aside>`]) {
|
||||
assert.notEqual(extractArticle(html, url).content_state, 'complete')
|
||||
}
|
||||
})
|
||||
@ -6,18 +6,18 @@ const vm = require('node:vm')
|
||||
const { createRequire } = require('node:module')
|
||||
const html = '<meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z"><article class="articleLayout_basic__gcpQk"><div class="body-content"><p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic editorial paragraph.</p></div></article>'
|
||||
|
||||
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 `<link rel="canonical" href="${url}">` + 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 === ''))
|
||||
})
|
||||
|
||||
9
scraper-service/tests/fixtures/content-gift-placeholders.html
vendored
Normal file
9
scraper-service/tests/fixtures/content-gift-placeholders.html
vendored
Normal file
@ -0,0 +1,9 @@
|
||||
<!-- Synthetic fixture derived only from the structural observations in #40.
|
||||
No publisher prose or supplied full HTML is reproduced. -->
|
||||
<link rel="canonical" href="https://www.bloomberg.com/news/articles/fixture">
|
||||
<meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z">
|
||||
<article class="articleLayout_basic__gcpQk GiftArticle_article__fixture"><div class="body-content">
|
||||
<p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic available introduction.</p>
|
||||
<div class="Placeholder_placeholder__fixture" data-component="placeholder"></div>
|
||||
<p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic available second paragraph.</p>
|
||||
</div></article>
|
||||
Reference in New Issue
Block a user