GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Electricity markets and data pipelines / globalgrid2050 / automation/news/acquisition/browser

Evidence Store and 4 more files

A Python module in the acquisition folder of GlobalGrid2050 that reads checksums, solar and the Renewable Energy Planning Database (REPD) register, using SHA-256.

696 lines of Python and JavaScript from globalgrid2050, in 5 files. Topic: Electricity markets and data pipelines. Section 775 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Prospecting Priority Config other · globalgrid2050 / automation/news/acquisition/browser/prospecting-priority.config.mjs lines 1–11
  2. Prospecting Priority Spec test · globalgrid2050 / automation/news/acquisition/browser/prospecting-priority.spec.mjs lines 1–114
  3. Server ingest · globalgrid2050 / automation/news/acquisition/browser/server.mjs lines 1–30
  4. Evidence Store storage · globalgrid2050 / automation/news/acquisition/evidence_store.py lines 1–358
  5. Fetch ingest · globalgrid2050 / automation/news/acquisition/fetch.py lines 1–183

Prospecting Priority Config

A JavaScript module in the browser folder of GlobalGrid2050.

otherglobalgrid2050 / automation/news/acquisition/browser/prospecting-priority.config.mjs · lines 1–11 of 11 · Not reached from any entry point (candidate for review)

What it does
Uses libraries @playwright/test.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name. Described from its file name only (a candidate, not yet checked against the code).
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · automation/news/acquisition/browser · JavaScript module
Uses
Server (import), @playwright/test
Used by
none found
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/acquisition/browser/prospecting-priority.config.mjs:1-11 · blob 5e6fa74e3cae160a9e58c34a3b0f0a0fa32b72d2 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import {defineConfig} from '@playwright/test';
import {getTestPort} from './server.mjs';
const baseURL=`http://127.0.0.1:${getTestPort()}`;
export default defineConfig({
  testDir:'.',testMatch:'prospecting-priority.spec.mjs',timeout:45000,
  outputDir:'test-results/prospecting-priority',
  fullyParallel:true,workers:3,reporter:[['list']],
  use:{baseURL,headless:true,channel:process.env.BROWSER_CHANNEL||undefined},
  projects:[{name:'mobile',use:{viewport:{width:375,height:812}}},{name:'tablet',use:{viewport:{width:768,height:1024}}},{name:'desktop',use:{viewport:{width:1440,height:900}}}],
  webServer:{command:'node server.mjs',url:`${baseURL}/uk_renewables_pipeline/202611161747/`,reuseExistingServer:false}
});

Prospecting Priority Spec

A test in the browser folder of GlobalGrid2050 covering the Renewable Energy Planning Database (REPD) register and solar, using SHA-256.

testglobalgrid2050 / automation/news/acquisition/browser/prospecting-priority.spec.mjs · lines 1–114 of 114 · Not reached from any entry point (candidate for review)

What it does
It tests the REPD register and solar. Defines hash, setup. Uses libraries @playwright/test, node:child_process, node:fs/promises, node:crypto, node:url. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: the REPD register, solar.
Inputs & outputs
In: JSON file priority.json; CSV file priority.csv; JSON file pipeline_headlines.json; JSON file .rank.json.
What it achieves
Defines `hash` and `setup`. It reads `priority.json`.
Why it matters
No other file in the estate was found to import it.
Application
globalgrid2050 · automation/news/acquisition/browser · test
Uses
@playwright/test, node:child_process, node:fs/promises, node:crypto, node:url, ./scripts/plugins/research-priority-v927.js?v=9.27
Used by
none found
Produces
hash, setup
Defines here
hash, setup
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/acquisition/browser/prospecting-priority.spec.mjs:1-114 · blob ea8e90822efb592143ff8186355523ac43cecd36 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
import {test,expect} from '@playwright/test';
import {execFileSync} from 'node:child_process';
import {readFile} from 'node:fs/promises';
import {createHash} from 'node:crypto';
import {fileURLToPath} from 'node:url';
const root=fileURLToPath(new URL('../../../../',import.meta.url));
const release='/uk_renewables_pipeline/202611161747/';
const directory=new URL('../../../../uk_renewables_pipeline/202611161747/prospecting/',import.meta.url);
const priorityRaw=await readFile(new URL('priority.json',directory));
const manifestRaw=await readFile(new URL('manifest.json',directory));
const csv=await readFile(new URL('priority.csv',directory));
const manifest=JSON.parse(manifestRaw),priority=JSON.parse(priorityRaw);
const ranked=priority.records[0],unranked=manifest.inventory.official_ids.find(id=>!priority.records.some(row=>row.id===id));
const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
const live='https://raw.githubusercontent.com/Ventusltd/globalgrid2050/pipeline-news-data/dist/pipeline_headlines.json';
// The prospecting bundle is actual pinned data. News below is an explicit offline fixture.
const newsFixture=JSON.parse(execFileSync(process.env.PYTHON||'python',['-c',`
import json
from automation.news.build_news_priority import build
from automation.news.tests.test_news_priority_export import document,raw
from automation.news.tests.test_news_algorithm import article
d=document([article('https://www.bloomberg.com/news/test-only','TEST FIXTURE: UK solar financing',source='Bloomberg'),article('https://www.gov.uk/news/test-only','TEST FIXTURE: UK solar planning policy',source='GOV.UK',category='policy')]);b=raw(d)
print(json.dumps({'raw':b.decode(),'rank':build(b)}))
`],{cwd:root,encoding:'utf8'}));

async function setup(page,mode='valid'){
  const origin=new URL(test.info().project.use.baseURL).origin;
  await page.clock.setFixedTime(new Date('2026-11-16T17:49:00Z'));
  await page.route('**/*',async route=>{
    const url=route.request().url();
    if(url===live)return route.fulfill({contentType:'application/json',body:newsFixture.raw});
    if(url===live.replace(/\.json$/,'.rank.json'))return route.fulfill({contentType:'application/json',body:JSON.stringify(newsFixture.rank)});
    if(url===origin+release+'prospecting/manifest.json'&&mode==='manifest')return route.fulfill({contentType:'application/json',body:manifestRaw.toString()+' '});
    if(url===origin+release+'prospecting/priority.json'){
      if(mode==='missing')return route.fulfill({status:404,body:'unavailable'});
      if(mode==='malformed')return route.fulfill({contentType:'application/json',body:'{'});
      if(mode==='typed-source'){const bad=structuredClone(priority);bad.records[0].capacities.repd_installed_mw='1000';return route.fulfill({contentType:'application/json',body:JSON.stringify(bad)});}
    }
    if(url.startsWith(origin+'/'))return route.continue();
    return route.abort();
  });
  await page.goto(release);
  await expect(page.locator('#tbody')).toHaveAttribute('data-complete','true');
  await expect(page.locator('#resultsMeta')).toContainText('7,775');
  await page.waitForFunction(()=>['accepted','rejected'].includes(window.projectResearchPriorityState));
}

test('actual export reproduces and source modules remain identical',async()=>{
  const actual=JSON.parse(execFileSync(process.env.PYTHON||'python',['-c',`
import json,hashlib
from automation.news.build_prospecting_priority import build_artifacts
b=build_artifacts(as_of='2026-11-16T17:48:52Z')
c=lambda v:(json.dumps(v,ensure_ascii=False,sort_keys=True,separators=(',',':'),allow_nan=False)+'\\n').encode()
b['priority.json']=c(json.loads(b['priority.json']))
m=json.loads(b['manifest.json']);m['files']['priority.json']={'sha256':hashlib.sha256(b['priority.json']).hexdigest(),'bytes':len(b['priority.json'])};b['manifest.json']=c(m)
print(json.dumps({k:hashlib.sha256(v).hexdigest() for k,v in b.items()}))
`],{cwd:root,encoding:'utf8'}));
  expect(actual).toEqual({'priority.json':hash(priorityRaw),'priority.csv':hash(csv),'manifest.json':hash(manifestRaw)});
  for(const name of ['adapter.mjs','bundle.mjs','view.mjs']){
    expect(await readFile(new URL(`../../../../uk_renewables_pipeline/202611161747/scripts/plugins/prospecting/${name}`,import.meta.url))).toEqual(await readFile(new URL(`../../prospecting-ui/${name}`,import.meta.url)));
  }
  expect(manifest.inventory.official_ids).toHaveLength(7775);expect(manifest.inventory.solar1000_ids).toHaveLength(1000);
  expect(priority.records.every(r=>r.research_state==='UNKNOWN'&&r.heat.state==='UNKNOWN'&&r.event_at===null)).toBe(true);
});

test('inline ranking, remarks, exact identity, rerenders, maps and full CSV',async({page},info)=>{
  const errors=[];page.on('pageerror',error=>errors.push(error.message));await setup(page);
  await expect(page.locator('#researchPriorityStatus')).toContainText('1,000 ranked from 7,775');
  await expect(page.locator('#solar1000Pilot')).toHaveCount(0);
  await expect(page.locator('#evidenceCoverage')).toHaveAttribute('data-selection-count','1000');
  await expect(page.locator('#newsStatus')).toHaveAttribute('data-order','priority');
  await expect(page.locator('#newsStatus')).toContainText('not project verification');
  await expect(page.locator('#liveNews')).toContainText('Bloomberg');
  await expect(page.locator('#liveNews .ln-title').first()).toContainText('planning policy');
  await page.locator('#search').fill(ranked.id.slice(5));
  const row=page.locator('#repd-'+ranked.id.slice(5)),map=row.locator('a.atlaslink');
  const mapBefore=await map.getAttribute('href');expect(new URL(mapBefore).searchParams.get('repd_ref')).toBe(ranked.id.slice(5));
  await row.locator('.v927-priority-hint').click();
  const detail=row.locator('[data-priority-id]');await expect(detail).toHaveAttribute('open','');
  await expect(detail).toContainText('Momentum: unknown');await expect(detail).toContainText(ranked.research_note);
  await page.evaluate(()=>window.dispatchEvent(new Event('pipeline-projects-rendered')));
  await expect(row.locator('[data-priority-id]')).toHaveCount(1);await expect(detail).toHaveAttribute('open','');
  await expect(map).toHaveAttribute('href',mapBefore);
  await expect(detail.locator('a').first()).toHaveAttribute('href',ranked.source.url);
  await page.screenshot({path:info.outputPath('priority-project.png')});
  await page.locator('#search').fill(unranked.slice(5));await page.locator('#repd-'+unranked.slice(5)+' .project-record > summary').click();
  await expect(page.locator('#repd-'+unranked.slice(5)+' [data-priority-state]')).toHaveText('Outside this research-priority subset');
  await page.locator('#clearFilters').click();
  const downloading=page.waitForEvent('download');await page.locator('#exportInline').click();
  const full=await readFile(await(await downloading).path(),'utf8');expect(full.trim().split(/\r?\n/)).toHaveLength(7776);
  await page.getByText('How to interpret statuses, maps and news',{exact:true}).click();
  const researchDownload=page.waitForEvent('download');await page.locator('a[href="prospecting/priority.csv"]').click();
  expect(hash(await readFile(await(await researchDownload).path()))).toBe(manifest.files['priority.csv'].sha256);
  await page.getByRole('tab',{name:'Global data centres',exact:true}).click();await expect(page.locator('.gdc-card')).toHaveCount(12);
  expect(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth)).toBe(true);expect(errors).toEqual([]);
});

for(const mode of ['missing','manifest','malformed','typed-source'])test(`${mode} priority leaves official dataset usable`,async({page})=>{
  await setup(page,mode);await expect(page.locator('#researchPriorityStatus')).toContainText('Research priority unavailable');
  await expect(page.locator('.v927-priority-hint')).toHaveCount(0);
  await page.locator('#search').fill('1018');await page.locator('#repd-1018 .project-record > summary').click();
  await expect(page.locator('#repd-1018 [data-priority-state]')).toHaveText('Research priority unavailable');
  await expect(page.locator('#repd-1018 a.atlaslink')).toHaveAttribute('href',/repd_ref=1018/);
  await page.locator('#clearFilters').click();await expect(page.locator('#resultsMeta')).toContainText('7,775');
});

test('failed reload clears previous rank without clearing project facts',async({page})=>{
  await setup(page);await page.locator('#search').fill(ranked.id.slice(5));await page.locator('.v927-priority-hint').click();
  await page.route('**/prospecting/manifest.json',route=>route.fulfill({status:503,body:'unavailable'}));
  await page.evaluate(async()=>{const module=await import('./scripts/plugins/research-priority-v927.js?v=9.27');await module.reloadPriority();});
  await expect(page.locator('[data-priority-id]')).toHaveCount(0);await expect(page.locator('.v927-priority-hint')).toHaveCount(0);
  await expect(page.locator('[data-priority-state]')).toHaveText('Research priority unavailable');
  await expect(page.locator('#repd-'+ranked.id.slice(5)+' .record-grid')).toBeVisible();
});

Server

A JavaScript module in the browser folder of GlobalGrid2050 that gets port (`getTestPort`). It gets test port (`getTestPort`) and creates test server (`createTestServer`).

ingestglobalgrid2050 / automation/news/acquisition/browser/server.mjs · lines 1–30 of 30

What it does
It loads data. Defines getTestPort, createTestServer. Uses libraries node:http, node:fs/promises, node:url, node:path. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 5 files: Harness Test (globalgrid2050); News Priority Config (globalgrid2050); Playwright Config (globalgrid2050); Prospecting Priority Config (globalgrid2050); and 1 more. Reached from 1 other entry point, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050).
What it achieves
Isolated local static server for browser tests; never a production server.
Why it matters
Imported by News Priority Config, Playwright Config and Prospecting Priority Config. Checked by 2 tests, including Harness Test.
Application
globalgrid2050 · automation/news/acquisition/browser · JavaScript module
Uses
node:http, node:fs/promises, node:url, node:path
Used by
run by Harness Test (script call), imported by News Priority Config (import), imported by Playwright Config (import), imported by Prospecting Priority Config (import), imported by Register Browser (import)
Produces
getTestPort, createTestServer
Defines here
getTestPort, createTestServer
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/acquisition/browser/server.mjs:1-30 · blob 9b19f8c96b05d73120e12e449ec33cf1e2865a5d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
// Isolated local static server for browser tests; never a production server.
import {createServer} from 'node:http';
import {readFile, stat} from 'node:fs/promises';
import {fileURLToPath} from 'node:url';
import {resolve, sep, extname} from 'node:path';
const root = fileURLToPath(new URL('../../../../',import.meta.url));
const types={'.html':'text/html','.js':'text/javascript','.mjs':'text/javascript','.json':'application/json','.geojson':'application/geo+json','.css':'text/css','.svg':'image/svg+xml'};
// One resolver keeps Playwright's origin and its child server in agreement.
// Use a distinct EVIDENCE_TEST_PORT for each concurrent worktree test run.
export function getTestPort(env=process.env){
  const value=env.EVIDENCE_TEST_PORT ?? '4173';
  if(!/^[1-9][0-9]*$/.test(value) || Number(value)>65535){
    throw new Error('EVIDENCE_TEST_PORT must be an integer from 1 to 65535');
  }
  return Number(value);
}
export function createTestServer(){
return createServer(async(req,res)=>{
  try{
    let file=resolve(root,'.'+decodeURIComponent(new URL(req.url,'http://localhost').pathname));
    if(!file.startsWith(root.endsWith(sep)?root:root+sep))throw Error('outside test root');
    if((await stat(file)).isDirectory())file=resolve(file,'index.html');
    res.writeHead(200,{'Content-Type':types[extname(file)]||'application/octet-stream','Cache-Control':'no-store'});
    res.end(await readFile(file));
  }catch{res.writeHead(404);res.end('not found');}
});
}
if(process.argv[1] && resolve(process.argv[1])===fileURLToPath(import.meta.url)){
  createTestServer().listen(getTestPort(),'127.0.0.1');
}

Evidence Store

A Python module in the acquisition folder of GlobalGrid2050 that reads checksums, solar and the Renewable Energy Planning Database (REPD) register, using SHA-256.

storageglobalgrid2050 / automation/news/acquisition/evidence_store.py · lines 1–358 of 358 · pattern EvidenceValidationError (shared by 2 files)

What it does
It loads checksums, solar and the REPD register. Defines 19 functions or classes, including EvidenceValidationError, _require, _moment, _url, _ids. Uses libraries __future__, csv, datetime, hashlib, io. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar, the REPD register.
Inputs & outputs
In: JSON file evidence.json; CSV file evidence.csv; GeoJSON file evidence.geojson; JSON file checksums.json; SQLite database. Out: JSON file latest.json.
Downstream impact
Used directly by 7 files: Analytics (globalgrid2050); News — Acquisition (globalgrid2050); Prospecting (globalgrid2050); Test Acquisition Analytics (globalgrid2050); and 3 more. Reached from 4 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050); Build Prospecting Priority (globalgrid2050).
What it achieves
It records run (`record_run`), validates snapshot (`validate_snapshot`) and exports snapshot (`export_snapshot`). Durable, provisional-only research results and immutable weekly exports.
Why it matters
Imported by Analytics, News — Acquisition and Prospecting. Checked by 4 tests, including Test Acquisition Analytics.
Application
globalgrid2050 · automation/news/acquisition · Python module
Uses
__future__, csv, datetime, hashlib, io, json, math, re
Used by
imported by Analytics (relative import), imported by News — Acquisition (relative import), imported by Prospecting (import), imported by Test Acquisition Analytics (import), imported by Test Acquisition Run (import), imported by Test Evidence Store (import), imported by Test Prospecting (import)
Produces
EvidenceValidationError, EvidenceStore, validate_snapshot, export_snapshot
Defines here
EvidenceValidationError, _require, _moment, _url, _ids, _coordinates, _sources, _article, _json, EvidenceStore, __init__, close, __enter__, __exit__, record_run, snapshot, validate_snapshot, _csv_cell, export_snapshot
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/acquisition/evidence_store.py:1-358 · blob 6b8b1ba08727b09ac09f8409de15fb22c3394544 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Durable, provisional-only research results and immutable weekly exports.

This is a research snapshot contract, not evidence_ledger's reviewed publication
contract. No event date or VERIFIED decision is inferred from an RSS headline.
Article bodies/snippets are deliberately never stored. Publish the snapshot and
latest.json together in one Git commit/push; this module only builds files.
"""
from __future__ import annotations

import csv
import datetime as dt
import hashlib
import io
import json
import math
import re
import sqlite3
from pathlib import Path
from urllib.parse import urlsplit

SCHEMA = "globalgrid2050.solar-evidence.provisional.v1"
COUNT = 1000
PROVISIONAL = "PROVISIONAL"
NO_EVIDENCE = "RESEARCH_ATTEMPTED_NO_EVIDENCE"
METHODS = {"exact_name", "repd_id"}


class EvidenceValidationError(ValueError):
    """A failed gate: keep the previous publication and require manual review."""


def _require(condition, message):
    if not condition:
        raise EvidenceValidationError(message)


def _moment(value):
    _require(isinstance(value, str) and bool(re.fullmatch(
        r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z", value)), "UTC second timestamp required")
    try:
        return dt.datetime.strptime(value, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=dt.timezone.utc)
    except ValueError as exc:
        raise EvidenceValidationError("Invalid UTC timestamp") from exc


def _url(value):
    try:
        p = urlsplit(value)
        valid = (p.scheme == "https" and p.hostname and not p.username
                 and not p.password and p.port in (None, 443))
    except (ValueError, TypeError):
        valid = False
    _require(valid, "Safe HTTPS URL required")


def _ids(values):
    result = list(values)
    _require(len(result) == COUNT and len(set(result)) == COUNT,
             "Exactly 1000 unique Solar-1000 project IDs required")
    _require(all(isinstance(x, str) and re.fullmatch(r"[1-9][0-9]*", x) for x in result),
             "Project IDs must be numeric REPD strings")
    return result


def _coordinates(latitude, longitude):
    if latitude is None and longitude is None:
        return
    _require(all(isinstance(x, (int, float)) and not isinstance(x, bool) and math.isfinite(x)
                 for x in (latitude, longitude)), "Coordinates must be finite numbers or both null")
    _require(-90 <= latitude <= 90 and -180 <= longitude <= 180, "Invalid coordinates")


def _sources(sources):
    _require(isinstance(sources, list) and bool(sources), "Successful source receipts required")
    ids = []
    for source in sources:
        _require(isinstance(source, dict) and source.get("status") == "ok",
                 "Critical source failure: manual review required")
        _require(source.get("eligible_for_publication") is True and source.get("probe_only") is False
                 and source.get("rights_status") == "accepted",
                 "Source rights unknown or probe-only: manual review required")
        _url(source.get("rights_review_url"))
        _require(isinstance(source.get("id"), str) and source["id"], "Source ID required")
        ids.append(source["id"])
        _url(source.get("url"))
        _moment(source.get("fetched_at"))
        _require(source.get("http_status") in (200, 304), "Successful HTTP receipt required")
        _require(isinstance(source.get("response_sha256"), str)
                 and re.fullmatch(r"[a-f0-9]{64}", source["response_sha256"]),
                 "Source response SHA256 required")
    _require(len(ids) == len(set(ids)), "Duplicate source IDs")
    return set(ids)


def _article(article):
    _require(isinstance(article, dict), "Article object required")
    for key in ("id", "url", "title", "pub_date", "source_id", "publisher"):
        _require(isinstance(article.get(key), str) and bool(article[key].strip()),
                 "Article field required: " + key)
    _url(article["url"])
    # A publication date is not an actual project event date.
    try:
        dt.datetime.fromisoformat(article["pub_date"].replace("Z", "+00:00"))
    except ValueError as exc:
        raise EvidenceValidationError("Invalid publication date") from exc


def _json(value):
    return (json.dumps(value, ensure_ascii=False, indent=2, allow_nan=False) + "\n").encode("utf-8")


class EvidenceStore:
    """SQLite storage; writes are transactional, repeated matches are idempotent."""

    def __init__(self, path=":memory:"):
        if str(path) != ":memory:":
            Path(path).parent.mkdir(parents=True, exist_ok=True)
        self.connection = sqlite3.connect(str(path))
        self.connection.row_factory = sqlite3.Row
        self.connection.execute("PRAGMA foreign_keys=ON")
        version = self.connection.execute("PRAGMA user_version").fetchone()[0]
        _require(version in (0, 1), "Unsupported evidence database schema")
        self.connection.executescript("""
            CREATE TABLE IF NOT EXISTS projects (
                id TEXT PRIMARY KEY, name TEXT NOT NULL,
                latitude REAL, longitude REAL, researched_at TEXT NOT NULL
            );
            CREATE TABLE IF NOT EXISTS articles (
                url TEXT PRIMARY KEY, id TEXT NOT NULL, title TEXT NOT NULL,
                pub_date TEXT NOT NULL, source_id TEXT NOT NULL, publisher TEXT NOT NULL
            );
            CREATE TABLE IF NOT EXISTS evidence (
                project_id TEXT NOT NULL REFERENCES projects(id),
                article_url TEXT REFERENCES articles(url), status TEXT NOT NULL,
                match_method TEXT, first_seen TEXT NOT NULL, last_seen TEXT NOT NULL,
                CHECK ((status='PROVISIONAL' AND article_url IS NOT NULL AND match_method IS NOT NULL
                        AND match_method IN ('exact_name','repd_id')) OR
                       (status='RESEARCH_ATTEMPTED_NO_EVIDENCE' AND article_url IS NULL
                        AND match_method IS NULL)),
                UNIQUE(project_id, article_url)
            );
            CREATE UNIQUE INDEX IF NOT EXISTS one_no_evidence_per_project
                ON evidence(project_id) WHERE article_url IS NULL;
            CREATE TABLE IF NOT EXISTS runs (
                fetched_at TEXT PRIMARY KEY, sources_json TEXT NOT NULL
            );
            PRAGMA user_version=1;
        """)
        expected = {
            "projects": {"id", "name", "latitude", "longitude", "researched_at"},
            "articles": {"url", "id", "title", "pub_date", "source_id", "publisher"},
            "evidence": {"project_id", "article_url", "status", "match_method", "first_seen", "last_seen"},
            "runs": {"fetched_at", "sources_json"},
        }
        for table, columns in expected.items():
            actual = {r[1] for r in self.connection.execute(f"PRAGMA table_info({table})")}
            _require(actual == columns, "Unexpected database schema: " + table)

    def close(self):
        self.connection.close()

    def __enter__(self):
        return self

    def __exit__(self, *_):
        self.close()

    def record_run(self, projects, articles, matches, fetched_at, sources):
        """Record a complete successful scan; failed scans must never call this."""
        _moment(fetched_at)
        source_ids = _sources(sources)
        last_run = self.connection.execute("SELECT MAX(fetched_at) FROM runs").fetchone()[0]
        _require(last_run is None or fetched_at >= last_run, "Acquisition timestamp would move backwards")
        projects, articles, matches = list(projects), list(articles), list(matches)
        project_ids = _ids(p["id"] for p in projects)
        existing = self.connection.execute("SELECT id,name,latitude,longitude FROM projects").fetchall()
        supplied = {p["id"]: p for p in projects}
        _require(not existing or {r["id"] for r in existing} == set(project_ids),
                 "Stored seed membership differs: manual review required")
        for project in projects:
            _require(isinstance(project.get("name"), str) and project["name"].strip(), "Project name required")
            _coordinates(project.get("latitude"), project.get("longitude"))
        for row in existing:
            project = supplied[row["id"]]
            _require((row["name"], row["latitude"], row["longitude"]) ==
                     (project["name"], project.get("latitude"), project.get("longitude")),
                     "Immutable seed project metadata changed")
        article_by_url = {}
        for article in articles:
            _article(article)
            _require(article["source_id"] in source_ids, "Article has no successful source receipt")
            _require(article["url"] not in article_by_url, "Duplicate article URLs in run")
            previous = self.connection.execute(
                "SELECT id,title,pub_date,source_id,publisher FROM articles WHERE url=?",
                (article["url"],)).fetchone()
            # Historical bindings refer to the metadata first observed at this
            # URL. Without versioned article identities, replacing it would
            # silently rewrite the evidence for every earlier project match.
            _require(previous is None or all(previous[key] == article[key] for key in previous.keys()),
                     "Stored article metadata changed; manual review required")
            article_by_url[article["url"]] = article
        for match in matches:
            _require(match.get("status") == PROVISIONAL, "Machine matches must remain PROVISIONAL")
            _require(match.get("project_id") in supplied, "Match outside Solar-1000")
            _require(match.get("article_url") in article_by_url, "Match article not fetched in this run")
            _require(match.get("match_method") in METHODS, "Unknown strict matching method")
        with self.connection:
            self.connection.executemany(
                "INSERT INTO projects VALUES (?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET researched_at=excluded.researched_at",
                [(p["id"], p["name"], p.get("latitude"), p.get("longitude"), fetched_at) for p in projects])
            self.connection.executemany(
                "INSERT INTO articles VALUES (?,?,?,?,?,?) ON CONFLICT(url) DO NOTHING",
                [(a["url"], a["id"], a["title"], a["pub_date"], a["source_id"], a["publisher"]) for a in articles])
            for match in matches:
                self.connection.execute("DELETE FROM evidence WHERE project_id=? AND article_url IS NULL", (match["project_id"],))
                self.connection.execute(
                    "INSERT INTO evidence VALUES (?,?,?,?,?,?) ON CONFLICT(project_id,article_url) DO UPDATE SET last_seen=excluded.last_seen",
                    (match["project_id"], match["article_url"], PROVISIONAL, match["match_method"], fetched_at, fetched_at))
            for project in projects:
                if not self.connection.execute("SELECT 1 FROM evidence WHERE project_id=? AND article_url IS NOT NULL", (project["id"],)).fetchone():
                    self.connection.execute("DELETE FROM evidence WHERE project_id=?", (project["id"],))
                    self.connection.execute("INSERT INTO evidence VALUES (?,NULL,?,NULL,?,?)", (project["id"], NO_EVIDENCE, fetched_at, fetched_at))
            self.connection.execute("INSERT INTO runs VALUES (?,?) ON CONFLICT(fetched_at) DO UPDATE SET sources_json=excluded.sources_json",
                                    (fetched_at, json.dumps(sources, sort_keys=True)))

    def snapshot(self, timestamp=None):
        _require(not self.connection.execute("PRAGMA foreign_key_check").fetchall(),
                 "Broken database relationships: manual review required")
        run = self.connection.execute("SELECT * FROM runs ORDER BY fetched_at DESC LIMIT 1").fetchone()
        _require(run is not None, "No successful acquisition run")
        timestamp = timestamp or run["fetched_at"]
        _moment(timestamp)
        _require(timestamp >= run["fetched_at"], "Snapshot cannot predate its acquisition run")
        rows = []
        for project in self.connection.execute("SELECT * FROM projects ORDER BY CAST(id AS INTEGER)"):
            evidence = [dict(row) for row in self.connection.execute(
                "SELECT a.*,e.status,e.match_method,e.first_seen,e.last_seen FROM evidence e "
                "JOIN articles a ON a.url=e.article_url WHERE e.project_id=? ORDER BY a.pub_date DESC,a.url",
                (project["id"],))]
            rows.append({
                "project_id": project["id"], "name": project["name"],
                "latitude": project["latitude"], "longitude": project["longitude"],
                "status": PROVISIONAL if evidence else NO_EVIDENCE,
                "evidence_count": len(evidence), "provisional_count": len(evidence), "verified_count": 0,
                "last_event": None, "last_researched_at": project["researched_at"], "evidence": evidence,
            })
        return {
            "schema": SCHEMA, "generated_at": timestamp, "source_run_at": run["fetched_at"],
            "seed_release": "202611161244", "project_count": len(rows),
            "evidence_count": sum(r["evidence_count"] for r in rows), "verified_count": 0,
            "review_required": True, "sources": json.loads(run["sources_json"]),
            "research_scope": "Completed bounded feed scan using strict name/REPD-ID matching; not independent project-first research. No match is not proof no evidence exists.",
            "projects": rows,
        }


def validate_snapshot(payload, expected_project_ids):
    """Validate types, statuses, membership and counts before any pointer update."""
    expected = set(_ids(expected_project_ids))
    _require(isinstance(payload, dict) and payload.get("schema") == SCHEMA, "Unexpected snapshot schema")
    _require(payload.get("seed_release") == "202611161244", "Wrong baseline release")
    _require(set(payload) == {"schema", "generated_at", "source_run_at", "seed_release", "project_count",
                             "evidence_count", "verified_count", "review_required", "sources", "research_scope", "projects"},
             "Unexpected snapshot fields")
    _require(isinstance(payload.get("research_scope"), str) and payload["research_scope"], "Research scope required")
    _moment(payload.get("generated_at"))
    _moment(payload.get("source_run_at"))
    source_ids = _sources(payload.get("sources"))
    _require(payload.get("review_required") is True and type(payload.get("verified_count")) is int
             and payload["verified_count"] == 0, "Provisional snapshot cannot assert verification")
    rows = payload.get("projects")
    _require(isinstance(rows, list) and type(payload.get("project_count")) is int
             and payload["project_count"] == COUNT and len(rows) == COUNT, "Snapshot must contain 1000 projects")
    ids = _ids(r.get("project_id") for r in rows)
    _require(set(ids) == expected, "Snapshot Solar-1000 membership differs")
    total = 0
    for row in rows:
        _require(set(row) == {"project_id", "name", "latitude", "longitude", "status", "evidence_count",
                             "provisional_count", "verified_count", "last_event", "last_researched_at", "evidence"},
                 "Unexpected project snapshot fields")
        _require(isinstance(row.get("name"), str) and row["name"].strip(), "Project name required")
        _coordinates(row.get("latitude"), row.get("longitude"))
        _moment(row.get("last_researched_at"))
        evidence = row.get("evidence")
        _require(isinstance(evidence, list), "Evidence must be a list")
        for field in ("evidence_count", "provisional_count", "verified_count"):
            _require(type(row.get(field)) is int, "Evidence counts must be integers")
        _require(row["evidence_count"] == row["provisional_count"] == len(evidence)
                 and row["verified_count"] == 0, "Evidence counts inconsistent")
        _require("last_event" in row and row["last_event"] is None, "RSS match cannot assert a project event")
        _require(row.get("status") == (PROVISIONAL if evidence else NO_EVIDENCE), "Invalid research status")
        urls = []
        for article in evidence:
            _require(set(article) == {"id", "url", "title", "pub_date", "source_id", "publisher", "status",
                                     "match_method", "first_seen", "last_seen"}, "Unexpected evidence fields")
            _article(article)
            _require(article["source_id"] in source_ids, "Article has no successful source receipt")
            _require(article.get("status") == PROVISIONAL and article.get("match_method") in METHODS,
                     "Evidence must be a strict provisional match")
            _require(not any(k in article for k in ("content", "body", "summary", "description")),
                     "Article bodies must not be exported")
            _moment(article.get("first_seen"))
            _moment(article.get("last_seen"))
            urls.append(article["url"])
        _require(len(urls) == len(set(urls)), "Duplicate project/article association")
        total += len(evidence)
    _require(type(payload.get("evidence_count")) is int and payload["evidence_count"] == total,
             "Snapshot evidence total inconsistent")
    return payload


def _csv_cell(value):
    # Prevent untrusted publisher/project titles becoming spreadsheet formulas.
    return "'" + value if isinstance(value, str) and value.lstrip().startswith(("=", "+", "-", "@")) else value


def export_snapshot(store, out_dir, timestamp=None, *, expected_project_ids):
    """Build immutable exports and then latest.json; no publication occurs here."""
    payload = validate_snapshot(store.snapshot(timestamp), expected_project_ids)
    stamp = _moment(payload["generated_at"]).strftime("%Y%m%dT%H%M%SZ")
    folder = "snapshot_" + stamp
    out_dir = Path(out_dir)
    target = out_dir / folder
    stream = io.StringIO(newline="")
    fields = ["project_id", "name", "status", "evidence_count", "provisional_count", "verified_count", "last_event", "last_researched_at"]
    writer = csv.DictWriter(stream, fieldnames=fields, lineterminator="\n")
    writer.writeheader()
    writer.writerows({key: _csv_cell(row[key]) for key in fields} for row in payload["projects"])
    geojson = {
        "type": "FeatureCollection", "schema": SCHEMA, "generated_at": payload["generated_at"],
        "features": [{"type": "Feature", "id": row["project_id"],
                      "geometry": None if row["latitude"] is None else {
                          "type": "Point", "coordinates": [row["longitude"], row["latitude"]]},
                      "properties": {key: row[key] for key in fields}}
                     for row in payload["projects"]],
    }
    files = {"evidence.json": _json(payload), "evidence.csv": stream.getvalue().encode("utf-8"),
             "evidence.geojson": _json(geojson)}
    hashes = {name: hashlib.sha256(data).hexdigest() for name, data in files.items()}
    files["checksums.json"] = _json(hashes)
    if target.exists():
        _require(target.is_dir() and {p.name for p in target.iterdir()} == set(files)
                 and all((target / name).read_bytes() == data for name, data in files.items()),
                 "Immutable snapshot already exists with different bytes; manual review required")
    else:
        target.mkdir(parents=True, exist_ok=False)
        for name, data in files.items():
            with (target / name).open("xb") as handle:
                handle.write(data)
    # Verify disk bytes before writing a pointer. A partial directory is never reused.
    for name, data in files.items():
        _require((target / name).read_bytes() == data, "Snapshot readback mismatch")
    pointer = {"schema": SCHEMA, "generated_at": payload["generated_at"], "snapshot": folder,
               "json": folder + "/evidence.json", "csv": folder + "/evidence.csv",
               "geojson": folder + "/evidence.geojson", "sha256": hashes,
               "project_count": COUNT, "evidence_count": payload["evidence_count"], "review_required": True}
    (out_dir / "latest.json").write_bytes(_json(pointer))
    return pointer

Fetch

A Python module in the acquisition folder of GlobalGrid2050 that fetches solar, using SHA-256. It fetches error (`FetchError`), loads sources (`load_sources`) and parses feed (`parse_feed`).

ingestglobalgrid2050 / automation/news/acquisition/fetch.py · lines 1–183 of 183 · pattern FetchError (shared by 2 files)

What it does
It fetches solar. Defines 10 functions or classes, including FetchError, _PublicHTTPSConnection, _new_conn, _PublicHTTPSPool, _PublicHTTPSAdapter. Uses libraries __future__, datetime, hashlib, ipaddress, pathlib. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage upstream_foresight (topic 'markets-data'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight. Domain terms in the code: solar. README: "`fetch.py` restricts the publisher host, HTTPS, resolved public addresses and redirects"
Downstream impact
Used directly by 3 files: News — Acquisition (globalgrid2050); Test Acquisition (globalgrid2050); Test Acquisition Run (globalgrid2050). Reached from 2 other entry points, including GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Bounded, fail-closed HTTP acquisition for the one approved solar RSS source.
Why it matters
Imported by News — Acquisition. Checked by 2 tests, including Test Acquisition.
Application
globalgrid2050 · automation/news/acquisition · Python module
Uses
Normalise (relative import), __future__, datetime, hashlib, ipaddress, pathlib, socket, urllib.parse, xml.etree.ElementTree
Used by
imported by News — Acquisition (relative import), imported by Test Acquisition (import), imported by Test Acquisition Run (import)
Produces
FetchError, load_sources, parse_feed, fetch_source
Defines here
FetchError, _PublicHTTPSConnection, _new_conn, _PublicHTTPSPool, _PublicHTTPSAdapter, init_poolmanager, _rights_accepted, load_sources, parse_feed, fetch_source
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
globalgrid2050@0aca5121f0795e469b6cf4fc3d3b628edba8d883 automation/news/acquisition/fetch.py:1-183 · blob f8a342b030467455930a7c4ad159b1f9c9d7acc3 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Bounded, fail-closed HTTP acquisition for the one approved solar RSS source."""
from __future__ import annotations

from datetime import datetime, timezone
import hashlib
import ipaddress
from pathlib import Path
import socket
from urllib.parse import urlsplit
import xml.etree.ElementTree as ET

import requests
import yaml
from urllib3.connection import HTTPSConnection
from urllib3.connectionpool import HTTPSConnectionPool
from urllib3.exceptions import NewConnectionError

from .normalise import normalise_article, safe_publisher_url

MAX_BYTES = 4 * 1024 * 1024
MAX_ENTRIES = 200


class FetchError(RuntimeError):
    """Critical fetch/parse failure: retain previous snapshot, require review."""


class _PublicHTTPSConnection(HTTPSConnection):
    """Resolve once, reject private answers, connect to that validated address.

    The surrounding urllib3 TLS implementation still verifies the original
    hostname. Connecting to the resolved sockaddr avoids a DNS rebind between
    a separate safety check and the actual connection.
    """
    def _new_conn(self):
        try:
            addresses = socket.getaddrinfo(self._dns_host, self.port, type=socket.SOCK_STREAM)
            ips = [ipaddress.ip_address(a[4][0]) for a in addresses]
            if not ips or any(not ip.is_global or ip.is_multicast or ip.is_reserved for ip in ips):
                raise FetchError("Publisher DNS resolved to a non-public address")
            for family, socktype, proto, _, address in addresses:
                sock = socket.socket(family, socktype, proto)
                try:
                    sock.settimeout(self.timeout)
                    for option in self.socket_options or []:
                        sock.setsockopt(*option)
                    if self.source_address:
                        sock.bind(self.source_address)
                    sock.connect(address)
                    return sock
                except OSError:
                    sock.close()
            raise NewConnectionError(self, "Publisher connection failed")
        except (OSError, ValueError) as exc:
            raise NewConnectionError(self, "Publisher DNS or connection failed") from exc


class _PublicHTTPSPool(HTTPSConnectionPool):
    ConnectionCls = _PublicHTTPSConnection


class _PublicHTTPSAdapter(requests.adapters.HTTPAdapter):
    def init_poolmanager(self, *args, **kwargs):
        super().init_poolmanager(*args, **kwargs)
        self.poolmanager.pool_classes_by_scheme = dict(self.poolmanager.pool_classes_by_scheme)
        self.poolmanager.pool_classes_by_scheme["https"] = _PublicHTTPSPool


def _rights_accepted(source):
    try:
        review = urlsplit(source.get("rights_review_url") or "")
        return (source.get("rights_status") == "accepted" and review.scheme == "https"
                and bool(review.hostname) and not review.username and not review.password)
    except ValueError:
        return False


def load_sources(path=None, *, include_disabled=False):
    sources = yaml.safe_load(Path(path or Path(__file__).with_name("sources.yaml")).read_text(encoding="utf-8"))
    if not isinstance(sources, list) or not sources:
        raise ValueError("sources must be a nonempty list")
    seen = set()
    for source in sources:
        if not isinstance(source, dict) or source.get("id") != "pv_magazine_global":
            raise ValueError("Only approved pv_magazine_global is enabled in this sprint")
        if source["id"] in seen:
            raise ValueError("Duplicate source ID")
        seen.add(source["id"])
        if (not safe_publisher_url(source.get("url")) or source.get("kind") != "rss"
                or source.get("technology") != ["solar"] or type(source.get("enabled")) is not bool
                or source.get("rights_status") not in {"unknown", "accepted"}
                or source.get("output_policy") != "headline_link_only"
                or type(source.get("interval_hours")) is not int or source["interval_hours"] != 168
                or not isinstance(source.get("publisher"), str) or not source["publisher"].strip()):
            raise ValueError("Invalid solar source configuration")
        if source["enabled"] and not _rights_accepted(source):
            raise ValueError("Source requires attributable rights acceptance before enabling")
    return sources if include_disabled else [s for s in sources if s["enabled"]]


def parse_feed(raw, source):
    if len(raw) > MAX_BYTES or b"<!DOCTYPE" in raw.upper() or b"<!ENTITY" in raw.upper():
        raise FetchError("Oversized or unsafe XML")
    try:
        root = ET.fromstring(raw)
        if root.tag != "rss":
            raise ValueError("Expected RSS document")
        entries = root.findall("./channel/item")
        if not entries or len(entries) > MAX_ENTRIES:
            raise ValueError("Empty or excessive feed")
        articles = []
        for item in entries:
            articles.append(normalise_article({
                "title": item.findtext("title"), "link": item.findtext("link"),
                "pub_date": item.findtext("pubDate"),
                "content": item.findtext("{http://purl.org/rss/1.0/modules/content/}encoded") or item.findtext("description"),
            }, source))
        return list({a["url"]: a for a in articles}.values())
    except (ValueError, TypeError, ET.ParseError) as exc:
        raise FetchError(f"Invalid RSS: {exc}") from exc


def fetch_source(source, cache=None, *, session=None, now=None, probe=False):
    """Return articles, a source receipt, and raw in-memory conditional cache.

    Cached XML is intentionally caller-owned and must not be included in public
    artifacts. A 304 without a byte-verified cached body fails closed.
    """
    if not probe and (source.get("enabled") is not True or not _rights_accepted(source)):
        raise FetchError("Source disabled or rights unaccepted; explicit health probe only")
    if not safe_publisher_url(source.get("url")):
        raise FetchError("Unapproved source URL")
    client = session or requests.Session()
    if session is None:
        # An environment proxy would resolve the publisher elsewhere and defeat
        # the validated-address connection policy.
        client.trust_env = False
        client.mount("https://", _PublicHTTPSAdapter())
    headers = {"User-Agent": "GlobalGrid2050-Evidence/9.25 (+https://globalgrid2050.com)", "Accept": "application/rss+xml, application/xml"}
    if cache and cache.get("url") == source["url"] and cache.get("etag"):
        headers["If-None-Match"] = cache["etag"]
    try:
        url = source["url"]
        for redirect in range(4):
            with client.get(url, headers=headers, timeout=(10, 25), stream=True, allow_redirects=False) as response:
                if response.status_code in {301, 302, 303, 307, 308}:
                    from urllib.parse import urljoin
                    url = urljoin(url, response.headers.get("Location", ""))
                    if not safe_publisher_url(url) or redirect == 3:
                        raise FetchError("Unapproved or excessive redirect")
                    continue
                if response.status_code == 304:
                    if (not cache or cache.get("url") != source["url"] or not isinstance(cache.get("body"), bytes)
                            or hashlib.sha256(cache["body"]).hexdigest() != cache.get("response_sha256")):
                        raise FetchError("304 without a valid cached feed")
                    raw = cache["body"]
                elif response.status_code == 200:
                    raw = b""
                    for chunk in response.iter_content(65536):
                        raw += chunk
                        if len(raw) > MAX_BYTES:
                            raise FetchError("RSS exceeds size limit")
                else:
                    raise FetchError(f"Critical source HTTP {response.status_code}: {source['id']}")
                digest = hashlib.sha256(raw).hexdigest()
                articles = parse_feed(raw, source)
                fetched_at = (now or datetime.now(timezone.utc)).isoformat(timespec="seconds").replace("+00:00", "Z")
                etag = response.headers.get("ETag") or (cache or {}).get("etag")
                return {"articles": articles, "source": {
                    "id": source["id"], "status": "ok", "url": source["url"], "final_url": url,
                    "publisher": source["publisher"], "fetched_at": fetched_at,
                    "http_status": response.status_code, "response_sha256": digest, "etag": etag,
                    "article_count": len(articles), "output_policy": "headline_link_only",
                    "probe_only": probe, "eligible_for_publication": not probe and _rights_accepted(source),
                    "rights_status": source.get("rights_status", "unknown"),
                    "rights_review_url": source.get("rights_review_url"),
                }, "cache": {"url": source["url"], "etag": etag, "body": raw, "response_sha256": digest}}
    except requests.RequestException as exc:
        raise FetchError(f"Critical source transport failure: {source['id']}") from exc
    finally:
        if session is None:
            client.close()
    raise FetchError("No successful source response")