GLOBALGRID2050 / EXPLORE CODE

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

Test Release Feature Migrations and 3 more files

A test in the tests folder of GlobalGrid2050 that checks Automation — Pipeline Release and Feature Contracts.

670 lines of Python from globalgrid2050, in 4 files. Topic: Electricity markets and data pipelines. Section 809 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. Test Prospecting Export test · globalgrid2050 / automation/news/tests/test_prospecting_export.py lines 1–104
  2. Test Real Data test · globalgrid2050 / automation/news/tests/test_real_data.py lines 1–125
  3. Test Release Audit test · globalgrid2050 / automation/news/tests/test_release_audit.py lines 1–99
  4. Test Release Feature Migrations test · globalgrid2050 / automation/news/tests/test_release_feature_migrations.py lines 1–342

Test Prospecting Export

A test in the tests folder of GlobalGrid2050 that checks Build Prospecting Priority, using SHA-256.

testglobalgrid2050 / automation/news/tests/test_prospecting_export.py · lines 1–104 of 104 · Entry point

What it does
It tests its inputs. Defines 12 functions or classes, including artifacts, test_real_population_and_ranking_are_separate, test_deterministic_and_exact_file_receipts, test_csv_matches_ranked_ids_and_nulls, test_csv_formula_safety. Uses libraries csv, hashlib, io, json, pathlib. 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: JSON file priority.json; CSV file priority.csv; JSON file invalid.json; JSON file unknown.json; JSON file projects.json.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Defines `artifacts`, `test_real_population_and_ranking_are_separate`, `test_deterministic_and_exact_file_receipts` and 9 more.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Build Prospecting Priority (import), csv, hashlib, io, json, pathlib, pytest
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
artifacts, test_real_population_and_ranking_are_separate, test_deterministic_and_exact_file_receipts, test_csv_matches_ranked_ids_and_nulls, test_csv_formula_safety, test_output_is_write_once_and_failed_digest_creates_nothing, test_invalid_optional_input_does_not_create_output, test_release_output_forbidden, test_missing_optional_pin_and_limit_are_errors, test_unknown_dc_remark_does_not_invent_numbers, test_real_dc_input_retains_separate_inventory_and_unknowns, test_oversized_output_rejected_before_writing
Defines here
artifacts, test_real_population_and_ranking_are_separate, test_deterministic_and_exact_file_receipts, test_csv_matches_ranked_ids_and_nulls, test_csv_formula_safety, test_output_is_write_once_and_failed_digest_creates_nothing, test_invalid_optional_input_does_not_create_output, test_release_output_forbidden, test_missing_optional_pin_and_limit_are_errors, test_unknown_dc_remark_does_not_invent_numbers, test_real_dc_input_retains_separate_inventory_and_unknowns, test_oversized_output_rejected_before_writing
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/tests/test_prospecting_export.py:1-104 · blob 12bc3e1ad2107547cae1819e91746481dc85e996 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
import csv
import hashlib
import io
import json
from pathlib import Path

import pytest

from automation.news import build_prospecting_priority as export

AS_OF = "2026-11-16T17:40:00Z"


@pytest.fixture(scope="module")
def artifacts():
    return export.build_artifacts(as_of=AS_OF)


def test_real_population_and_ranking_are_separate(artifacts):
    manifest = json.loads(artifacts["manifest.json"])
    triage = json.loads(artifacts["priority.json"])
    rows, pilot, _ = export.prospecting.official(None)
    assert manifest["inventory"]["official_ids"] == ["REPD-" + r["repd_ref"] for r, _ in rows]
    assert manifest["inventory"]["solar1000_ids"] == pilot
    assert len(rows) == 7775 and manifest["solar_count"] == 3604
    assert len(pilot) == 1000 and triage["returned_count"] == 1000
    assert all(r["heat"]["state"] == r["research_state"] == "UNKNOWN" for r in triage["records"])
    assert all(r["event_at"] is None and "This is not a new event" in r["research_note"] for r in triage["records"])
    assert manifest["rank_scope"].endswith("not the numeric Solar-1000 selection")


def test_deterministic_and_exact_file_receipts(artifacts):
    assert export.build_artifacts(as_of=AS_OF) == artifacts
    manifest = json.loads(artifacts["manifest.json"])
    for name, receipt in manifest["files"].items():
        assert receipt == {"sha256": hashlib.sha256(artifacts[name]).hexdigest(), "bytes": len(artifacts[name])}


def test_csv_matches_ranked_ids_and_nulls(artifacts):
    table = list(csv.DictReader(io.StringIO(artifacts["priority.csv"].decode())))
    triage = json.loads(artifacts["priority.json"])
    assert [r["project_id"] for r in table] == [r["id"] for r in triage["records"]]
    assert all(r["momentum_state"] == "UNKNOWN" and r["as_of"] == AS_OF for r in table)
    assert table[0]["source_url"] == triage["records"][0]["source"]["url"]


@pytest.mark.parametrize("value", ["=HYPERLINK(1)", "+1", "-1", "@cmd", "  =1", "\t1", "\r1", "\n1"])
def test_csv_formula_safety(value):
    assert export.csv_text(value) == "'" + value


def test_output_is_write_once_and_failed_digest_creates_nothing(tmp_path, artifacts):
    destination = tmp_path / "run"
    export.write_artifacts(destination, artifacts)
    assert {p.name: p.read_bytes() for p in destination.iterdir()} == artifacts
    with pytest.raises(FileExistsError):
        export.write_artifacts(destination, artifacts)
    changed = {**artifacts, "priority.json": b"{}"}
    with pytest.raises(ValueError, match="digest"):
        export.write_artifacts(tmp_path / "bad", changed)
    assert not (tmp_path / "bad").exists()


def test_invalid_optional_input_does_not_create_output(tmp_path):
    invalid = tmp_path / "invalid.json"
    invalid.write_text("{}")
    with pytest.raises(SystemExit) as exc:
        export.main(["--as-of", AS_OF, "--out-dir", str(tmp_path / "output"), "--evidence", str(invalid), "--evidence-sha256", "0" * 64])
    assert exc.value.code == 2 and not (tmp_path / "output").exists()


def test_release_output_forbidden(artifacts):
    with pytest.raises(ValueError, match="immutable"):
        export.write_artifacts(export.prospecting.queue.ROOT / "uk_renewables_pipeline" / "never-write-test", artifacts)


def test_missing_optional_pin_and_limit_are_errors(tmp_path):
    with pytest.raises(SystemExit):
        export.main(["--as-of", AS_OF, "--out-dir", str(tmp_path / "output"), "--datacentres", "unknown.json"])
    with pytest.raises(ValueError, match="Limit"):
        export.build_artifacts(as_of=AS_OF, limit=7775)


def test_unknown_dc_remark_does_not_invent_numbers():
    row = {"record_type": "data_centre"}
    note = export.remark(row)
    assert "unassessed" in note and "MW" not in note


def test_real_dc_input_retains_separate_inventory_and_unknowns():
    path = export.prospecting.queue.ROOT / "uk_renewables_pipeline/202611161630/global-datacentres/projects.json"
    raw = path.read_bytes()
    files = export.build_artifacts(as_of=AS_OF, datacentres=(path, export.sha(raw)))
    manifest = json.loads(files["manifest.json"])
    records = json.loads(raw)["records"]
    assert manifest["inventory"]["data_centre_ids"] == sorted(r["id"] for r in records)
    assert manifest["input_count"] == 7775 + len(records)
    assert manifest["input_receipts"][2]["sha256"] == export.sha(raw)


def test_oversized_output_rejected_before_writing(monkeypatch):
    monkeypatch.setattr(export.prospecting, "MAX_BYTES", 100)
    with pytest.raises(ValueError, match="consumer size"):
        export.build_artifacts(as_of=AS_OF)

Test Real Data

A test in the tests folder of GlobalGrid2050 that checks Events and Renewable Energy Planning Database (REPD) Diff, using SHA-256.

testglobalgrid2050 / automation/news/tests/test_real_data.py · lines 1–125 of 125 · Entry point

What it does
It tests its inputs. Defines 7 functions or classes, including _prev, test_milestones_reconcile_with_published_change_report, test_ranking_deterministic_and_profile_bounded, test_binder_on_labelled_set_meets_floor, test_committed_feed_matches_schema_and_invariants. Uses libraries __future__, json, os, datetime, pathlib. 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: CSV file repd-2026q3.csv; JSON file diff.json; JSON file major_project_news_v9_5_1.json; JSON file binding_labels_v9_5_1.json; JSON file repd_events_2026q3.json; JSON file repd-events-feed.v1.schema.json; JSON file project_identity_v6.json.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Real-data smoke tests. Skipped when the inputs are not present in the checkout.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Events (import), Renewable Energy Planning Database (REPD) Diff (import), __future__, json, os, datetime, pathlib, pytest
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
test_milestones_reconcile_with_published_change_report, test_ranking_deterministic_and_profile_bounded, test_binder_on_labelled_set_meets_floor, test_committed_feed_matches_schema_and_invariants, test_committed_feed_rebuilds_byte_identically, test_panel_fields_shared_with_datacentre_panel
Defines here
_prev, test_milestones_reconcile_with_published_change_report, test_ranking_deterministic_and_profile_bounded, test_binder_on_labelled_set_meets_floor, test_committed_feed_matches_schema_and_invariants, test_committed_feed_rebuilds_byte_identically, test_panel_fields_shared_with_datacentre_panel
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/tests/test_real_data.py:1-125 · blob 236811cdd6ed7fe3b9ce949dff07f6117f426169 · 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
"""Real-data smoke tests. Skipped when the inputs are not present in the checkout.

The official July 2026 cleaned CSV (REPD_Q2_2026_cleaned.csv, sha256 52e2c81c...) lives on branch
repd/2026-07-verified-archive-20261113; point NEWS_PREVIOUS_REPD at it to run the exact-reconciliation
tests. Without it the derived dist/project_identity_v6.json is used for structural checks only."""
from __future__ import annotations

import json
import os
from datetime import date
from pathlib import Path

import pytest

from automation.news import events as E
from automation.news import relevance as R
from automation.news import binder as B
from automation.repd import diff as repd

REPO = Path(__file__).resolve().parents[3]
NEW = REPO / "repd-2026q3.csv"
DIFF = REPO / "docs/repd/2026q3/changes-jul-to-oct/diff.json"
LEGACY_FEED = REPO / "dist/major_project_news_v9_5_1.json"
LABELS = REPO / "automation/news/labels/binding_labels_v9_5_1.json"
FEED = REPO / "dist/news/repd_events_2026q3.json"
SCHEMA = REPO / "automation/news/schema/repd-events-feed.v1.schema.json"
OFFICIAL_PREV = os.environ.get("NEWS_PREVIOUS_REPD")
DERIVED_PREV = REPO / "dist/project_identity_v6.json"

need_new = pytest.mark.skipif(not NEW.exists(), reason="repd-2026q3.csv not in checkout")


def _prev():
    if OFFICIAL_PREV and Path(OFFICIAL_PREV).exists():
        return Path(OFFICIAL_PREV), True
    if DERIVED_PREV.exists():
        return DERIVED_PREV, False
    pytest.skip("no previous release available")


@need_new
def test_milestones_reconcile_with_published_change_report():
    prev, official = _prev()
    old, new = E.load_pair(prev, NEW)
    doc = E.build_events(old, new)
    assert doc["new"]["unique_refs"] == 14967
    if not (official and DIFF.exists()):
        assert doc["counts"]["CONSENTED"] > 0
        pytest.skip("official July CSV not supplied; structural check only")
    d = json.loads(DIFF.read_text())
    assert doc["previous"]["sha256"] == d["previous"]["sha256"]
    m = d["summary"]["milestones"]
    for key, etype in (("consented", "CONSENTED"), ("under_construction", "CONSTRUCTION_STARTED"),
                       ("operational", "OPERATIONAL"), ("refused", "REFUSED"), ("withdrawn", "WITHDRAWN")):
        evs = [e for e in doc["events"] if e["event_type"] == etype]
        assert len(evs) == m[key]["n"], etype
        assert round(sum(e["capacity_mw"] or 0 for e in evs), 2) == pytest.approx(m[key]["mw"]), etype
        assert sum(1 for e in evs if e["capacity_mw"] is None) == m[key]["n_unknown_mw"], etype
    assert doc["counts"]["REMOVED_FROM_REGISTER"] == d["summary"]["removed"]
    added = sum(1 for e in doc["events"] if e["basis"] == "new_record")
    assert added == d["summary"]["added"]
    assert doc["counts"]["CAPACITY_CHANGE"] == d["capacity_edits"]["n"] + d["capacity_edits"]["unknown_to_known"]["n"] \
        + d["capacity_edits"]["known_to_unknown"]["n"]


@need_new
def test_ranking_deterministic_and_profile_bounded():
    prev, _ = _prev()
    old, new = E.load_pair(prev, NEW)
    doc = E.build_events(old, new)
    ref = date.fromisoformat(new["info"]["max_record_last_updated"])
    a = R.rank_events(doc["events"], ref)
    b = R.rank_events(doc["events"], ref)
    assert [e["event_id"] for e in a] == [e["event_id"] for e in b]
    assert all(0 <= e["relevance"]["score"] <= e["relevance"]["max_possible"] for e in a)
    assert len(R.top_events(a, 50)) == 50


@need_new
@pytest.mark.skipif(not LABELS.exists(), reason="labelled set absent")
def test_binder_on_labelled_set_meets_floor():
    index = B.ProjectIndex(repd.load_csv(NEW))
    labels = json.loads(LABELS.read_text())["labels"]
    ev = B.evaluate(labels, index)
    assert ev["signal_metrics"]["precision"] >= 0.95
    assert ev["signal_metrics"]["recall"] >= 0.90
    assert ev["per_class"]["STRONG"]["false_positive"] == 0


@pytest.mark.skipif(not (FEED.exists() and SCHEMA.exists()), reason="committed feed absent")
def test_committed_feed_matches_schema_and_invariants():
    jsonschema = pytest.importorskip("jsonschema")
    feed = json.loads(FEED.read_text())
    schema = json.loads(SCHEMA.read_text())
    jsonschema.Draft202012Validator(schema, format_checker=jsonschema.FormatChecker()).validate(feed)
    assert len(feed["top"]) == feed["top_n"] == 50
    assert feed["event_count"] == len(feed["events"]) == sum(feed["counts"].values())
    assert feed["profile_sha256"] == R.profile_sha256(feed["profile"])
    for ev in feed["events"]:
        assert round(sum(c["points"] for c in ev["relevance"]["components"]), 2) == ev["relevance"]["score"]
        if ev["capacity_mw"] is None:
            assert "capacity not stated" in ev["headline"] or ev["event_type"] in ("CAPACITY_CHANGE", "TECHNOLOGY_CHANGE")
    text = FEED.read_text()
    assert "/home/" not in text and "\\Users\\" not in text


@pytest.mark.skipif(not (FEED.exists() and OFFICIAL_PREV and LEGACY_FEED.exists()), reason="needs official July CSV")
def test_committed_feed_rebuilds_byte_identically(tmp_path):
    from automation.news import build_feed
    conv = REPO / "dist/convergence/2026q3"
    args = ["--previous", OFFICIAL_PREV, "--previous-label", "July 2026 (Q2)", "--new", str(NEW),
            "--new-label", "October 2026 (Q3)", "--release", "2026q3", "--previous-feed", str(LEGACY_FEED),
            "--out-dir", str(tmp_path)]
    if conv.is_dir():
        args += ["--convergence", str(conv)]
    build_feed.main(args)
    assert (tmp_path / "repd_events_2026q3.json").read_bytes() == FEED.read_bytes()


@pytest.mark.skipif(not FEED.exists(), reason="committed feed absent")
def test_panel_fields_shared_with_datacentre_panel():
    feed = json.loads(FEED.read_text())
    for ev in feed["top"]:
        assert ev["lane"] == "REPD_EVENTS" and ev["title"] == ev["headline"] and ev["score"] == ev["relevance"]["score"]
        assert ev["link"] is None and ev["ref"]

Test Release Audit

A test in the tests folder of GlobalGrid2050 that checks Automation — Pipeline Release and New Version.

testglobalgrid2050 / automation/news/tests/test_release_audit.py · lines 1–99 of 99 · Entry point

What it does
It tests solar. Defines 8 functions or classes, including test_dry_run_reports_parent_and_writes_nothing, test_release_text_is_utf8_lf, test_registry_round_trip_preserves_utf8_metadata, test_published_record_cannot_be_refinalized, test_older_registered_release_cannot_be_refinalized. Uses libraries json, pathlib, sys, pytest. 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. Domain terms in the code: solar.
Inputs & outputs
In: JSON file registry.json; JSON file interconnector-endpoints.json.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
Release tooling must preserve the frozen parent and candidate semantics.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Automation — Pipeline Release (sys.path import), New Version (sys.path import), json, pathlib, sys, pytest
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
test_dry_run_reports_parent_and_writes_nothing, test_release_text_is_utf8_lf, test_registry_round_trip_preserves_utf8_metadata, test_published_record_cannot_be_refinalized, test_older_registered_release_cannot_be_refinalized, test_unpublished_tail_can_be_refinalized, test_frozen_parent_tree_and_candidate_data, test_candidate_provenance_sanitization_changes_no_facts
Defines here
test_dry_run_reports_parent_and_writes_nothing, test_release_text_is_utf8_lf, test_registry_round_trip_preserves_utf8_metadata, test_published_record_cannot_be_refinalized, test_older_registered_release_cannot_be_refinalized, test_unpublished_tail_can_be_refinalized, test_frozen_parent_tree_and_candidate_data, test_candidate_provenance_sanitization_changes_no_facts
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/tests/test_release_audit.py:1-99 · blob 409400a298fd98b4fb843f3ffa6b135abb1ab8e5 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""Release tooling must preserve the frozen parent and candidate semantics."""
import json
from pathlib import Path
import sys
import pytest

ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT / "automation/pipeline_release"))
import common
import new_version


def test_dry_run_reports_parent_and_writes_nothing(tmp_path, monkeypatch, capsys):
    monkeypatch.setattr(new_version, "PIPELINE", tmp_path)
    monkeypatch.setattr(new_version, "load_registry", lambda: {
        "versions": [{"id": "202611161244", "version": "V9.24"}]})
    new_version.create("202611161630", "V9.25", "Evidence", dry_run=True)
    assert "parent: 202611161244 (V9.24)" in capsys.readouterr().out
    assert list(tmp_path.iterdir()) == []


def test_release_text_is_utf8_lf(tmp_path):
    path = tmp_path / "release.txt"
    new_version.write_text(path, "Solar · provisional\n")
    assert path.read_bytes() == "Solar · provisional\n".encode()


def test_registry_round_trip_preserves_utf8_metadata(tmp_path, monkeypatch):
    path = tmp_path / "registry.json"
    monkeypatch.setattr(common, "REGISTRY", path)
    registry = {"versions": [{"added": "Solar · quoted \u201ccandidate\u201d · 東京"}]}
    common.save_registry(registry)
    assert common.load_registry() == registry


def test_published_record_cannot_be_refinalized(monkeypatch):
    monkeypatch.setattr(new_version, "load_registry", lambda: {
        "versions": [{"id": "202611161244", "version": "V9.24", "state": "published"}]})
    with pytest.raises(AssertionError, match="cannot be rewritten"):
        new_version.finalize("202611161244", "change", [], [], "release_candidate_blocked")


@pytest.mark.parametrize("old_state", ["published", "release_candidate_blocked"])
def test_older_registered_release_cannot_be_refinalized(tmp_path, monkeypatch, old_state):
    registry = {"versions": [
        {"id": "202611161244", "version": "V9.24", "state": old_state},
        {"id": "202611161630", "version": "V9.25", "state": "release_candidate_blocked"},
    ]}
    monkeypatch.setattr(new_version, "load_registry", lambda: registry)
    monkeypatch.setattr(new_version, "PIPELINE", tmp_path)
    monkeypatch.setattr(new_version, "walk", lambda _: pytest.fail("Historical filesystem was accessed"))
    with pytest.raises(AssertionError, match="cannot be rewritten"):
        new_version.finalize("202611161244", "change", [], [], "release_candidate_blocked")
    assert len(registry["versions"]) == 2
    assert list(tmp_path.iterdir()) == []


@pytest.mark.parametrize("migration", [False, True])
def test_unpublished_tail_can_be_refinalized(tmp_path, monkeypatch, migration):
    registry = {"versions": [
        {"id": "202611161244", "version": "V9.24", "state": "published"},
        {"id": "202611161630", "version": "V9.25", "state": "release_candidate_blocked"},
    ]}
    if migration:
        registry["versions"][-1]["feature_migrations"] = [dict(new_version.SOLAR_MIGRATION)]
    parent = tmp_path / "202611161244"
    candidate = tmp_path / "202611161630"
    parent.mkdir()
    (candidate / "tests").mkdir(parents=True)
    runner = candidate / "tests/run_v9_25.sh"
    runner.write_text("CHANGED_FROM_PARENT=(\n)\nREMOVED_FROM_PARENT=(\n)\n", encoding="utf-8")
    monkeypatch.setattr(new_version, "load_registry", lambda: registry)
    monkeypatch.setattr(new_version, "PIPELINE", tmp_path)
    monkeypatch.setattr(new_version, "tree_hash", lambda _: "synthetic-candidate-tree")
    saved = []
    monkeypatch.setattr(new_version, "save_registry", saved.append)
    new_version.finalize("202611161630", "candidate revision", [], [], "release_candidate_blocked")
    assert len(saved[0]["versions"]) == 2
    assert saved[0]["versions"][-1]["parent"] == "202611161244"
    assert saved[0]["versions"][-1]["trees"] == ["synthetic-candidate-tree"]
    assert saved[0]["versions"][-1].get("feature_migrations", []) == ([new_version.SOLAR_MIGRATION] if migration else [])
    assert list(parent.iterdir()) == []


def test_frozen_parent_tree_and_candidate_data():
    assert common.tree_hash("202611161244") == "2d109396cdef80302914045b5330e4f7007e5830"
    parent = ROOT / "uk_renewables_pipeline/202611161244"
    candidate = ROOT / "uk_renewables_pipeline/202611161630"
    assert common.data_digest(parent) == common.data_digest(candidate)
    assert (parent / "solar1000/manifest.json").read_bytes() == (candidate / "solar1000/manifest.json").read_bytes()


def test_candidate_provenance_sanitization_changes_no_facts():
    relative = "fixtures/v9.8/interconnector-endpoints.json"
    old = json.loads((ROOT / "uk_renewables_pipeline/202611161244" / relative).read_text())
    new = json.loads((ROOT / "uk_renewables_pipeline/202611161630" / relative).read_text())
    old["flow_data"]["source"] = new["flow_data"]["source"]
    assert old == new
    assert new["flow_data"]["source"].startswith("https://github.com/Ventusltd/")

Test Release Feature Migrations

A test in the tests folder of GlobalGrid2050 that checks Automation — Pipeline Release and Feature Contracts.

testglobalgrid2050 / automation/news/tests/test_release_feature_migrations.py · lines 1–342 of 342 · Entry point · pattern releases (shared by 4 files)

What it does
It tests its inputs. Defines 19 functions or classes, including releases, check, test_actual_candidate_keeps_feature_through_explicit_migration, test_migration_is_inherited_but_historical_feature_is_still_checked, test_invalid_migration_fails_closed. Uses libraries copy, json, pathlib, shutil, sys. Side effects: changes the web page (DOM); 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: JSON file candidates.json; JSON file priority.json; CSV file priority.csv; JSON file pipeline_headlines.snapshot.json; JSON file projects.json; JSON file official-projects.json; JSON file project-groups.json; JSON file selection-audit.json. Out: JSON file official.json; JSON file pipeline_headlines.snapshot.json.
Downstream impact
Used directly by 2 files: GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (globalgrid2050); GlobalGrid2050 Project Signals Acid Workflow (globalgrid2050).
What it achieves
It is built from the releases step (`releases`), the check step (`check`) and the internal priorities helper (`internal_priorities`). A moved presentation must retain its frozen data and executable access contract.
Why it matters
Run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow and GlobalGrid2050 Project Signals Acid Workflow.
Application
globalgrid2050 · automation/news/tests · test
Uses
Automation — Pipeline Release (sys.path import), Feature Contracts (sys.path import), New Version (sys.path import), copy, json, pathlib, shutil, sys, pytest
Used by
run by GlobalGrid2050 Pipeline Project Evidence Weekly Workflow (workflow run), run by GlobalGrid2050 Project Signals Acid Workflow (workflow run)
Produces
releases, check, test_actual_candidate_keeps_feature_through_explicit_migration, test_migration_is_inherited_but_historical_feature_is_still_checked, test_invalid_migration_fails_closed, test_migration_rejects_lost_data_or_access, test_without_explicit_migration_old_marker_still_fails, internal_priorities, test_internal_migrations_preserve_algorithms_data_and_mandatory_browser_probes, test_internal_migrations_reject_lost_data_or_reintroduced_public_scores, test_internal_features_cannot_be_bypassed_by_removed_features, test_descendant_may_restate_exact_inherited_contract_but_not_duplicate_locally
Defines here
releases, check, test_actual_candidate_keeps_feature_through_explicit_migration, test_migration_is_inherited_but_historical_feature_is_still_checked, test_invalid_migration_fails_closed, test_migration_rejects_lost_data_or_access, test_without_explicit_migration_old_marker_still_fails, internal_priorities, test_internal_migrations_preserve_algorithms_data_and_mandatory_browser_probes, test_internal_migrations_reject_lost_data_or_reintroduced_public_scores, test_internal_features_cannot_be_bypassed_by_removed_features, test_descendant_may_restate_exact_inherited_contract_but_not_duplicate_locally, test_release_flags_expand_only_explicit_reviewed_contracts, test_release_flags_reject_unknown_or_duplicate_contracts, test_malformed_headline_provenance_returns_failed_verdict, test_migration_cannot_replace_original_sources_own_feature_check, datacentre_migration, test_datacentre_migration_retains_100_leads_12_semantics_and_mandatory_real_host_probe, test_datacentre_migration_rejects_changed_evidence_or_lost_host
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/tests/test_release_feature_migrations.py:1-342 · blob 35e4ef620fbcd0cc630ba9e175c43a45d59c6cb8 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: production_core
"""A moved presentation must retain its frozen data and executable access contract."""
import copy
import json
from pathlib import Path
import shutil
import sys

import pytest

ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT / "automation/pipeline_release"))
import common
from feature_contracts import check_features, NEWS_MIGRATION, RESEARCH_MIGRATIONS, KNOWN_MIGRATIONS, GLOBAL_DC_MIGRATION, NEON_MIGRATIONS
from new_version import migration_records

SOURCE = "202611161244"
CANDIDATE = "202611161630"
MIGRATION = {"id": "solar1000-pilot", "from": SOURCE, "contract": "solar1000-inline-v1"}


@pytest.fixture
def releases(tmp_path):
    versions = [
        {"id": SOURCE, "parent": None, "features": [
            {"id": "solar1000-pilot", "file": "index.html", "contains": "SOLAR 1000 EVIDENCE PILOT"}]},
        {"id": CANDIDATE, "parent": SOURCE, "features": [], "feature_migrations": [copy.deepcopy(MIGRATION)]},
    ]
    for version in versions:
        folder = tmp_path / version["id"]
        folder.mkdir()
        actual = ROOT / "uk_renewables_pipeline" / version["id"]
        for rel in ("solar1000/manifest.json", "solar1000/candidates.json", "index.html",
                    "scripts/plugins/solar1000-v924.js"):
            target = folder / rel
            target.parent.mkdir(parents=True, exist_ok=True)
            shutil.copyfile(actual / rel, target)
        (folder / "data").mkdir()
        (folder / "data/official.json").write_text('[{"repd_ref":"1018"}]', encoding="utf-8")
    return tmp_path, {v["id"]: v for v in versions}


def check(releases):
    root, versions = releases
    return check_features(versions[CANDIDATE], versions, root)


def test_actual_candidate_keeps_feature_through_explicit_migration():
    registry = common.load_registry()
    versions = {v["id"]: v for v in registry["versions"]}
    versions[CANDIDATE]["feature_migrations"] = [copy.deepcopy(MIGRATION)]
    result, probes = check_features(versions[CANDIDATE], versions, common.PIPELINE)
    assert result["pass"], result
    assert "solar1000-pilot" in result["features"]
    assert "solar1000-pilot" not in result["withdrawn_on_purpose"]
    assert result["migrations"][0]["pass"]
    assert len(probes) == 3
    candidates = json.loads((common.PIPELINE / SOURCE / "solar1000/candidates.json").read_text(encoding="utf-8"))
    for candidate, probe in zip(candidates, probes[1:]):
        assert probe["search"] == candidate["repd_ref"]
        assert candidate["source_url"] in probe["js"]
        assert ".project-record" in probe["js"]


def test_migration_is_inherited_but_historical_feature_is_still_checked(releases):
    root, versions = releases
    result, _ = check_features(versions[SOURCE], versions, root)
    assert result["pass"]
    (root / SOURCE / "index.html").write_text("lost", encoding="utf-8")
    result, _ = check_features(versions[SOURCE], versions, root)
    assert not result["pass"] and result["missing"] == ["solar1000-pilot"]
    successor = {"id": "202611170001", "parent": CANDIDATE, "features": []}
    shutil.copytree(root / CANDIDATE, root / successor["id"])
    versions[successor["id"]] = successor
    result, probes = check_features(successor, versions, root)
    assert result["pass"] and len(probes) == 3


@pytest.mark.parametrize("change", ["unknown_contract", "unknown_feature", "wrong_source", "duplicate", "removed"])
def test_invalid_migration_fails_closed(releases, change):
    _, versions = releases
    version = versions[CANDIDATE]
    migration = version["feature_migrations"][0]
    if change == "unknown_contract":
        migration["contract"] = "trust-me"
    elif change == "unknown_feature":
        migration["id"] = "map-deep-link"
    elif change == "wrong_source":
        migration["from"] = CANDIDATE
    elif change == "duplicate":
        version["feature_migrations"].append(copy.deepcopy(migration))
    else:
        version["removed_features"] = ["solar1000-pilot"]
    result, _ = check(releases)
    assert not result["pass"]


@pytest.mark.parametrize("change", ["order", "membership", "missing", "candidate_url", "official_data", "inline_host", "plugin_wiring"])
def test_migration_rejects_lost_data_or_access(releases, change):
    root, _ = releases
    folder = root / CANDIDATE
    if change in {"order", "membership"}:
        path = folder / "solar1000/manifest.json"
        manifest = json.loads(path.read_text(encoding="utf-8"))
        if change == "order":
            manifest["ids"][0], manifest["ids"][1] = manifest["ids"][1], manifest["ids"][0]
        else:
            manifest["ids"][-1] = "999999"
        path.write_text(json.dumps(manifest), encoding="utf-8")
    elif change == "missing":
        (folder / "solar1000/manifest.json").unlink()
    elif change == "candidate_url":
        path = folder / "solar1000/candidates.json"
        path.write_text(path.read_text(encoding="utf-8").replace("https://stiveslocal.uk/", "https://example.org/"), encoding="utf-8")
    elif change == "official_data":
        (folder / "data/official.json").write_text("[]", encoding="utf-8")
    else:
        path = folder / "index.html"
        old = 'id="evidenceCoverage"' if change == "inline_host" else 'src="scripts/plugins/solar1000-v924.js'
        path.write_text(path.read_text(encoding="utf-8").replace(old, "removed"), encoding="utf-8")
    result, _ = check(releases)
    assert not result["pass"], change


def test_without_explicit_migration_old_marker_still_fails(releases):
    _, versions = releases
    del versions[CANDIDATE]["feature_migrations"]
    result, probes = check(releases)
    assert not result["pass"] and result["missing"] == ["solar1000-pilot"]
    assert probes == []


@pytest.fixture
def internal_priorities(tmp_path):
    news_id, research_id, candidate_id = "202611161734", "202611161747", "202611162359"
    versions = [
        {"id": news_id, "parent": None, "features": [
            {"id": "news-editorial-priority", "file": "scripts/plugins/live-news.js",
             "contains": "globalgrid2050.news.headline-priority.v1"}]},
        {"id": research_id, "parent": news_id, "features": [
            {"id": "inline-research-priority", "file": "index.html", "contains": "research-priority-v927.js"},
            {"id": "source-bound-priority", "file": "index.html", "contains": "researchPriorityStatus"}]},
        {"id": candidate_id, "parent": research_id, "features": [],
         "feature_migrations": copy.deepcopy([NEWS_MIGRATION, *RESEARCH_MIGRATIONS])},
    ]
    research_paths = ("prospecting/manifest.json", "prospecting/priority.json", "prospecting/priority.csv",
                      "scripts/plugins/research-priority-v927.js", "scripts/plugins/prospecting/adapter.mjs",
                      "scripts/plugins/prospecting/bundle.mjs", "scripts/plugins/prospecting/view.mjs")
    for version in versions:
        folder = tmp_path / version["id"]
        (folder / "data").mkdir(parents=True)
        (folder / "data/official.json").write_text('[{"repd_ref":"1018"}]', encoding="utf-8")
        for path in ("scripts/plugins/live-news.js", "news/pipeline_headlines.snapshot.json"):
            destination = folder / path
            destination.parent.mkdir(parents=True, exist_ok=True)
            shutil.copyfile(ROOT / "uk_renewables_pipeline" / news_id / path, destination)
        if version["id"] != news_id:
            for path in research_paths:
                destination = folder / path
                destination.parent.mkdir(parents=True, exist_ok=True)
                shutil.copyfile(ROOT / "uk_renewables_pipeline" / research_id / path, destination)
        (folder / "index.html").write_text(
            '<script defer src="scripts/plugins/live-news.js?v=9.28"></script>', encoding="utf-8")
    by_id = {v["id"]: v for v in versions}
    return tmp_path, by_id, by_id[candidate_id]


def test_internal_migrations_preserve_algorithms_data_and_mandatory_browser_probes(internal_priorities):
    root, by_id, version = internal_priorities
    result, probes = check_features(version, by_id, root)
    assert result["pass"], result
    assert len(result["migrations"]) == 3
    assert result["withdrawn_on_purpose"] == []
    assert len(probes) == 2  # Research is one executable proof for its two inherited features.
    assert all(probe["js"].startswith("(async () =>") for probe in probes)
    assert "await p.validatePriority(doc,bytes,bad)" in probes[0]["js"]
    assert "Forged attribution" in probes[0]["js"]
    assert "dataset.order==='priority'" in probes[0]["js"]
    assert "items[i].source" in probes[0]["js"]
    assert "parsePriorityBundle" in probes[1]["js"]
    assert "bundle.members.size===7775" in probes[1]["js"]
    assert "bundle.byId.size===1000" in probes[1]["js"]


@pytest.mark.parametrize("change", ["research_json", "research_csv", "manifest", "parser", "public_script",
                                     "public_status", "validator", "schema", "news_wiring", "provenance", "official_data"])
def test_internal_migrations_reject_lost_data_or_reintroduced_public_scores(internal_priorities, change):
    root, by_id, version = internal_priorities
    folder = root / version["id"]
    if change in {"research_json", "research_csv", "manifest", "parser"}:
        path = folder / {"research_json": "prospecting/priority.json", "research_csv": "prospecting/priority.csv",
                         "manifest": "prospecting/manifest.json", "parser": "scripts/plugins/prospecting/bundle.mjs"}[change]
        path.write_bytes(path.read_bytes() + b" ")
    elif change in {"public_script", "public_status", "news_wiring"}:
        path = folder / "index.html"
        text = path.read_text(encoding="utf-8")
        if change == "public_script":
            text += "<script src='scripts/plugins/research-priority-v927.js?v=9.27'></script>"
        elif change == "public_status":
            text += "<span id='researchPriorityStatus'>Research #1</span>"
        else:
            text = "<p>No headline renderer</p>"
        path.write_text(text, encoding="utf-8")
    elif change in {"validator", "schema"}:
        path = folder / "scripts/plugins/live-news.js"
        before = "crypto.subtle.digest" if change == "validator" else "globalgrid2050.news.headline-priority.v1"
        path.write_text(path.read_text(encoding="utf-8").replace(before, "removed"), encoding="utf-8")
    elif change == "provenance":
        path = folder / "news/pipeline_headlines.snapshot.json"
        doc = json.loads(path.read_text(encoding="utf-8"))
        doc["items"] = [{"title": "Synthetic missing publisher", "source": "", "link": "https://example.org/fixture"}]
        path.write_text(json.dumps(doc), encoding="utf-8")
    else:
        (folder / "data/official.json").write_text("[]", encoding="utf-8")
    result, _ = check_features(version, by_id, root)
    assert not result["pass"], change


@pytest.mark.parametrize("feature", ["inline-research-priority", "source-bound-priority", "news-editorial-priority"])
def test_internal_features_cannot_be_bypassed_by_removed_features(internal_priorities, feature):
    root, by_id, version = internal_priorities
    version["removed_features"] = [feature]
    result, _ = check_features(version, by_id, root)
    assert not result["pass"]
    assert "internal priority features require an audited migration, not removal" in result["errors"]


def test_descendant_may_restate_exact_inherited_contract_but_not_duplicate_locally(internal_priorities):
    root, by_id, version = internal_priorities
    parent = by_id[version["parent"]]
    parent["feature_migrations"] = copy.deepcopy(RESEARCH_MIGRATIONS)
    result, _ = check_features(version, by_id, root)
    assert result["pass"], result
    version["feature_migrations"].append(copy.deepcopy(NEWS_MIGRATION))
    result, _ = check_features(version, by_id, root)
    assert not result["pass"] and "duplicate feature migration" in result["errors"]


def test_release_flags_expand_only_explicit_reviewed_contracts():
    old_flags = ["solar1000-inline-v1", "news-priority-internal-v1", "research-priority-internal-v1", "global-dc-ui-v928-v1"]
    assert migration_records(old_flags) == [MIGRATION, NEWS_MIGRATION, *RESEARCH_MIGRATIONS, GLOBAL_DC_MIGRATION]
    assert migration_records(["ticker-neon-v940-v1"]) == NEON_MIGRATIONS
    result = migration_records([*old_flags, "ticker-neon-v940-v1"])
    assert result == KNOWN_MIGRATIONS
    assert migration_records(["solar1000-inline-v1"]) == [MIGRATION]
    result[0]["contract"] = "caller mutation"
    assert migration_records(["solar1000-inline-v1"]) == [MIGRATION]


@pytest.mark.parametrize("flags", [["unknown"], ["solar1000-inline-v1", "solar1000-inline-v1"],
                                   ["research-priority-internal-v1", "research-priority-internal-v1"]])
def test_release_flags_reject_unknown_or_duplicate_contracts(flags):
    with pytest.raises(ValueError, match="Unknown or duplicate"):
        migration_records(flags)


@pytest.mark.parametrize("document", [[], {"schema": "globalgrid2050.news.pipeline-headlines.v1", "items": [None]}])
def test_malformed_headline_provenance_returns_failed_verdict(internal_priorities, document):
    root, by_id, version = internal_priorities
    (root / version["id"] / "news/pipeline_headlines.snapshot.json").write_text(json.dumps(document), encoding="utf-8")
    result, _ = check_features(version, by_id, root)
    assert not result["pass"]


def test_migration_cannot_replace_original_sources_own_feature_check(internal_priorities):
    root, by_id, _ = internal_priorities
    source = by_id[NEWS_MIGRATION["from"]]
    source["feature_migrations"] = [copy.deepcopy(NEWS_MIGRATION)]
    result, _ = check_features(source, by_id, root)
    assert not result["pass"]


@pytest.fixture
def datacentre_migration(tmp_path):
    pipeline = tmp_path / "pipeline"
    source_id, candidate_id = GLOBAL_DC_MIGRATION["from"], "202611162359"
    versions = {
        source_id: {"id": source_id, "parent": None, "features": [
            {"id": "global-dc-tab", "file": "index.html", "contains": "global-datacentres-v925.js"}]},
        candidate_id: {"id": candidate_id, "parent": source_id, "features": [],
                       "feature_migrations": [copy.deepcopy(GLOBAL_DC_MIGRATION)]},
    }
    for vid in versions:
        folder = pipeline / vid
        (folder / "data").mkdir(parents=True)
        (folder / "data/official.json").write_text('[{"repd_ref":"1018"}]', encoding="utf-8")
        actual = ROOT / "uk_renewables_pipeline" / (source_id if vid == source_id else "202611161757")
        paths = ["global-datacentres/projects.json", "index.html"]
        if vid == candidate_id:
            paths += ["global-datacentres/official-projects.json", "global-datacentres/project-groups.json",
                      "global-datacentres/selection-audit.json", "scripts/plugins/preview-v928.js"]
        for rel in paths:
            target = folder / rel
            target.parent.mkdir(parents=True, exist_ok=True)
            shutil.copyfile(actual / rel, target)
    return pipeline, versions, versions[candidate_id]


def test_datacentre_migration_retains_100_leads_12_semantics_and_mandatory_real_host_probe(datacentre_migration):
    pipeline, versions, candidate = datacentre_migration
    result, probes = check_features(candidate, versions, pipeline)
    assert result["pass"], result
    assert len(probes) == 1
    assert "tab.click()" in probes[0]["js"]
    assert "GGDataCentreModel.validateBundle(forged)" in probes[0]["js"]
    assert "length!==54" in probes[0]["js"] and "length!==100" in probes[0]["js"]
    assert "querySelectorAll('main>section').length!==2" in probes[0]["js"]


@pytest.mark.parametrize("change", ["identity", "mw", "status", "malformed_capacity", "audit", "old_semantics", "host", "old_renderer", "lazy"])
def test_datacentre_migration_rejects_changed_evidence_or_lost_host(datacentre_migration, change):
    pipeline, versions, candidate = datacentre_migration
    folder = pipeline / candidate["id"]
    if change in {"identity", "mw", "status", "malformed_capacity"}:
        path = folder / "global-datacentres/projects.json"
        doc = json.loads(path.read_text(encoding="utf-8"))
        if change == "identity":
            doc["records"][0]["id"] = "DC-WD-Q999999999"
        elif change == "mw":
            doc["records"][0]["capacity"]["it_load_mw"] = 100
        elif change == "malformed_capacity":
            doc["records"][0]["capacity"] = None
        else:
            doc["records"][0]["operating_status"] = "operational"
        path.write_text(json.dumps(doc), encoding="utf-8")
    elif change == "audit":
        path = folder / "global-datacentres/selection-audit.json"
        path.write_bytes(path.read_bytes() + b" ")
    elif change == "old_semantics":
        path = pipeline / GLOBAL_DC_MIGRATION["from"] / "global-datacentres/projects.json"
        doc = json.loads(path.read_text(encoding="utf-8"))
        doc["records"][0]["name"] = "Different original identity"
        path.write_text(json.dumps(doc), encoding="utf-8")
    elif change == "lazy":
        path = folder / "scripts/plugins/preview-v928.js"
        path.write_text(path.read_text(encoding="utf-8").replace("!dcStarted", "true"), encoding="utf-8")
    else:
        path = folder / "index.html"
        text = path.read_text(encoding="utf-8")
        text = text.replace('id="datacentreHost"', 'id="removed"') if change == "host" else text + '<script src="scripts/plugins/global-datacentres-v925.js"></script>'
        path.write_text(text, encoding="utf-8")
    result, _ = check_features(candidate, versions, pipeline)
    assert not result["pass"], change