In this section
- Publish Federation JSON storage · data-federation-map-for-globalgrid2050-all-repos / scripts/publish_federation_json.py lines 701–818
- Render Internal Dashboard storage · data-federation-map-for-globalgrid2050-all-repos / scripts/render_internal_dashboard.py lines 1–194
- OSM Power Plants transform · data-grid-gb / conventional/fetchers/osm_power_plants.py lines 1–20
- OSM Datacentres transform · data-grid-gb / datacentres/fetchers/osm_datacentres.py lines 1–20
Publish Federation JSON
A Python command-line tool in the scripts folder of Data Federation Map for GlobalGrid2050 All Repos that reads federation publish and federation map, using SHA-256.
storagedata-federation-map-for-globalgrid2050-all-repos / scripts/publish_federation_json.py · lines 701–818 of 818 (continued from section 475) · Entry point · pattern canonical_text (shared by 2 files)
- What it does
- It loads federation publish and federation map. Defines 29 functions or classes, including StopPlan, utcnow, rel, sql_path, json_text. Uses libraries __future__, argparse, datetime, hashlib, json. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage site_feasibility (topic 'maps-gis'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief.
- Inputs & outputs
- In: Parquet file nodes.parquet; Parquet file edges.parquet; JSON file FEDERATION_PUBLISH_LATEST.json; JSON file FEDERATION_MAP_LATEST.json; JSON file nodes.json; JSON file edges.json; DuckDB queries; command-line arguments.
- Downstream impact
- Used directly by 1 file: Gridbot Federation Map Weekly Workflow (data-federation-map-for-globalgrid2050-all-repos).
- What it achieves
- It stops plan (`StopPlan`), reads JSON (`read_json`) and reads text if exists (`read_text_if_exists`). Its name says it publishes federation JSON. Defines `StopPlan`, `utcnow`, `rel` and 25 more. It accepts `--mode`, `--repository` and `--source-nodes`.
- Why it matters
- Run by Gridbot Federation Map Weekly Workflow.
- Application
- data-federation-map-for-globalgrid2050-all-repos · scripts · Python CLI
- Uses
- __future__, argparse, datetime, hashlib, json, os, subprocess, sys
- Used by
- run by Gridbot Federation Map Weekly Workflow (workflow run)
- Produces
- StopPlan, utcnow, rel, sql_path, json_text, canonical_text, sha256_text, read_json, read_text_if_exists, write_text, current_commit_sha, empty_report
- Defines here
- parse_args, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-federation-map-for-globalgrid2050-all-repos@fffd624e77d820ebc04ab25f9d97871b254be61c scripts/publish_federation_json.py:701-818 · blob a7db4fdceab2ffcdaf79902e425949d367d9202b · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: supporting_data
"expectedHash": expected_hash,
}
pre_write_pass = all_checks_pass(report)
if mode == "apply" and pre_write_pass:
old_nodes = read_text_if_exists(target_nodes)
old_edges = read_text_if_exists(target_edges)
if old_nodes != target_nodes_text:
write_text(target_nodes, target_nodes_text)
actually_changed_apply.append(rel(target_nodes))
if old_edges != target_edges_text:
write_text(target_edges, target_edges_text)
actually_changed_apply.append(rel(target_edges))
old_dependencies = read_text_if_exists(args.dependencies)
new_dependencies, dependencies_changed = update_dependencies_text(old_dependencies)
if dependencies_changed:
write_text(args.dependencies, new_dependencies)
actually_changed_apply.append(rel(args.dependencies))
actual_projection = projection_for_reconciliation(read_json(target_nodes), read_json(target_edges))
actual_hash = sha256_text(canonical_text(actual_projection))
reconciliation_passed = actual_projection == expected_projection
report["projection"]["actualHash"] = actual_hash
add_check(
report,
"published_json_reconciles_exactly_against_parquet_projection",
reconciliation_passed,
f"expectedHash={expected_hash}; actualHash={actual_hash}",
{"expectedHash": expected_hash, "actualHash": actual_hash},
)
elif mode == "apply" and not pre_write_pass:
add_check(
report,
"published_json_reconciles_exactly_against_parquet_projection",
False,
"Apply write blocked because one or more pre-write declared checks failed.",
)
else:
audit_projection = projection_for_reconciliation(planned_nodes_obj, planned_edges_obj)
actual_hash = sha256_text(canonical_text(audit_projection))
add_check(
report,
"planned_json_reconciles_exactly_against_parquet_projection",
audit_projection == expected_projection,
f"expectedHash={expected_hash}; plannedHash={actual_hash}",
{"expectedHash": expected_hash, "plannedHash": actual_hash},
)
existing_nodes_text = read_text_if_exists(target_nodes)
existing_edges_text = read_text_if_exists(target_edges)
report["auditOnlyTargetDrift"] = {
"nodesJsonWouldChange": existing_nodes_text != target_nodes_text,
"edgesJsonWouldChange": existing_edges_text != target_edges_text,
}
report["actuallyChangedFilesUnderApply"] = actually_changed_apply if mode == "apply" else []
except StopPlan as exc:
report["fatalErrors"].append(str(exc))
except Exception as exc:
report["fatalErrors"].append(f"{type(exc).__name__}: {exc}")
publish_succeeded = all_checks_pass(report)
report["dataLawResult"] = "PASS" if publish_succeeded else "FAIL"
if publish_succeeded:
if mode == "apply":
report["nextAction"] = "Apply completed. Commit the target JSON, DEPENDENCIES.md, paired report, and append-only ledger evidence together; rollback is revert of that apply commit."
else:
drift = report.get("auditOnlyTargetDrift", {})
if drift.get("nodesJsonWouldChange") or drift.get("edgesJsonWouldChange"):
report["nextAction"] = "Review this audit report. If approved, manually dispatch mode=apply to publish the planned JSON bridge output."
else:
report["nextAction"] = "No apply is required unless a human wants to refresh the evidence trail."
else:
report["nextAction"] = "Do not apply. Fix the failed declared check, then re-run audit."
report_md_text = write_markdown_report(report)
report_json_text = json_text(report)
write_text(args.report_md, report_md_text)
write_text(args.report_json, report_json_text)
append_ledger(args.ledger, report, publish_succeeded)
write_text(args.report_md, write_markdown_report(report))
write_text(args.report_json, json_text(report))
return (0 if publish_succeeded else 1), report
def parse_args(argv: list[str]) -> argparse.Namespace:
ap = argparse.ArgumentParser(description="Publish federation map Parquet into federation control ledger JSON")
ap.add_argument("--mode", choices=["audit", "apply"], default="audit")
ap.add_argument("--repository", default=os.environ.get("GITHUB_REPOSITORY", "Ventusltd/data-federation-map-for-globalgrid2050-all-repos"))
ap.add_argument("--source-nodes", type=Path, default=DEFAULT_SOURCE_NODES)
ap.add_argument("--source-edges", type=Path, default=DEFAULT_SOURCE_EDGES)
ap.add_argument("--target-dir", type=Path, default=DEFAULT_TARGET_DIR)
ap.add_argument("--report-md", type=Path, default=DEFAULT_REPORT_MD)
ap.add_argument("--report-json", type=Path, default=DEFAULT_REPORT_JSON)
ap.add_argument("--ledger", type=Path, default=DEFAULT_LEDGER)
ap.add_argument("--scanner-report", type=Path, default=DEFAULT_SCANNER_REPORT)
ap.add_argument("--scanner-status", choices=["success", "failure", "cancelled", "skipped", "unknown"], default="unknown")
ap.add_argument("--dependencies", type=Path, default=DEFAULT_DEPENDENCIES)
return ap.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
args = parse_args(argv or sys.argv[1:])
code, report = execute(args)
print(json.dumps({
"mode": report.get("mode"),
"dataLawResult": report.get("dataLawResult"),
"reportMarkdown": rel(args.report_md),
"reportJson": rel(args.report_json),
"ledger": rel(args.ledger),
}, indent=2))
return code
if __name__ == "__main__":
raise SystemExit(main())Render Internal Dashboard
A Python command-line tool in the scripts folder of Data Federation Map for GlobalGrid2050 All Repos that reads federation map and federation dashboard.
storagedata-federation-map-for-globalgrid2050-all-repos / scripts/render_internal_dashboard.py · lines 1–194 of 194 · Entry point · pattern build_payload (shared by 3 files)
- What it does
- It loads federation map and federation dashboard. Defines 7 functions or classes, including utcnow, sql_path, load_latest_report, colour_for_repo, build_payload. Uses libraries __future__, datetime, html, json, pathlib. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage site_feasibility (topic 'maps-gis'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief.
- Inputs & outputs
- In: JSON file FEDERATION_MAP_LATEST.json; Parquet file nodes.parquet; Parquet file edges.parquet; DuckDB queries. Out: JSON file federation_dashboard.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It builds payload (`build_payload`) and renders HTML (`render_html`). Its name says it renders internal dashboard. Defines `utcnow`, `sql_path`, `load_latest_report` and 3 more.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- data-federation-map-for-globalgrid2050-all-repos · scripts · Python CLI
- Uses
- __future__, datetime, html, json, pathlib, duckdb
- Used by
- none found
- Produces
- utcnow, sql_path, load_latest_report, colour_for_repo, build_payload, render_html, main
- Defines here
- utcnow, sql_path, load_latest_report, colour_for_repo, build_payload, render_html, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-federation-map-for-globalgrid2050-all-repos@fffd624e77d820ebc04ab25f9d97871b254be61c scripts/render_internal_dashboard.py:1-194 · blob 503cb37e096ab9d94852472ed4538be71401bbfc · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: supporting_data
#!/usr/bin/env python3
from __future__ import annotations
import datetime as dt
import html
import json
from pathlib import Path
import duckdb
ROOT = Path(__file__).resolve().parents[1]
MAP = ROOT / "data/federation_map/current"
REPORT_JSON = ROOT / "reports/json/FEDERATION_MAP_LATEST.json"
OUT = ROOT / "internal_dashboard"
METHOD_VERSION = "internal_dashboard_v1_static_duckdb"
def utcnow() -> str:
return dt.datetime.now(dt.timezone.utc).isoformat().replace("+00:00", "Z")
def sql_path(path: Path) -> str:
return str(path).replace("'", "''")
def load_latest_report() -> dict:
if REPORT_JSON.exists():
return json.loads(REPORT_JSON.read_text(encoding="utf-8"))
return {}
def colour_for_repo(repo_type: str, status: str, files: str) -> tuple[str, list[str]]:
reasons: list[str] = []
colour = "green"
if "README.md" not in files:
colour = "red"
reasons.append("README missing")
if repo_type == "data" and "DATA_CONTRACT.md" not in files:
colour = "red"
reasons.append("data contract missing")
if ".github/workflows/" not in files:
if colour != "red":
colour = "amber"
reasons.append("workflow missing")
if "federation.yaml" not in files and "federation.yml" not in files:
if colour == "green":
colour = "amber"
reasons.append("federation manifest missing")
if status == "archived":
colour = "blue"
reasons.append("archived")
if not reasons:
reasons.append("v1 evidence complete")
return colour, reasons
def build_payload() -> dict:
nodes_path = MAP / "nodes.parquet"
edges_path = MAP / "edges.parquet"
if not nodes_path.exists():
raise FileNotFoundError(nodes_path)
if not edges_path.exists():
raise FileNotFoundError(edges_path)
con = duckdb.connect()
nodes = sql_path(nodes_path)
edges = sql_path(edges_path)
node_rows = con.execute(f"SELECT count(*) FROM read_parquet('{nodes}')").fetchone()[0]
edge_rows = con.execute(f"SELECT count(*) FROM read_parquet('{edges}')").fetchone()[0]
type_rows = con.execute(f"SELECT coalesce(repoType,'unknown'), count(*) FROM read_parquet('{nodes}') GROUP BY 1 ORDER BY 2 DESC, 1").fetchall()
edge_type_rows = con.execute(f"SELECT coalesce(edgeType,'unknown'), count(*) FROM read_parquet('{edges}') GROUP BY 1 ORDER BY 2 DESC, 1").fetchall()
repo_rows = con.execute(f"""
SELECT nodeId, repoName, repoType, status, visibility, defaultBranch, canonicalFilesPresent, description, htmlUrl
FROM read_parquet('{nodes}')
WHERE nodeKind='github_repo'
ORDER BY repoType, repoName
""").fetchall()
repos = []
colour_counts: dict[str, int] = {}
for row in repo_rows:
node_id, repo_name, repo_type, status, visibility, default_branch, files, description, url = row
files = files or ""
colour, reasons = colour_for_repo(repo_type or "unknown", status or "unknown", files)
colour_counts[colour] = colour_counts.get(colour, 0) + 1
repos.append({
"nodeId": node_id,
"repoName": repo_name,
"repoType": repo_type or "unknown",
"status": status or "unknown",
"visibility": visibility or "unknown",
"defaultBranch": default_branch or "",
"colour": colour,
"reasons": reasons,
"description": description or "",
"htmlUrl": url or "",
})
return {
"schemaVersion": "globalgrid2050.internal_dashboard.v1",
"generatedUTC": utcnow(),
"methodVersion": METHOD_VERSION,
"summary": {
"nodeRows": int(node_rows),
"edgeRows": int(edge_rows),
"repoCount": len(repos),
"colourCounts": colour_counts,
"repoTypes": [{"repoType": a, "count": int(b)} for a, b in type_rows],
"edgeTypes": [{"edgeType": a, "count": int(b)} for a, b in edge_type_rows],
},
"repos": repos,
"latestReport": load_latest_report(),
}
def render_html(payload: dict) -> str:
colour_order = ["red", "amber", "grey", "blue", "green"]
cards = []
cards.append(("Repos", payload["summary"]["repoCount"]))
cards.append(("Nodes", payload["summary"]["nodeRows"]))
cards.append(("Edges", payload["summary"]["edgeRows"]))
for colour in colour_order:
cards.append((colour.upper(), payload["summary"]["colourCounts"].get(colour, 0)))
rows = []
for repo in payload["repos"]:
rows.append(
"<tr>"
f"<td class='{html.escape(repo['colour'])}'>{html.escape(repo['colour'].upper())}</td>"
f"<td><a href='{html.escape(repo['htmlUrl'])}'>{html.escape(repo['nodeId'])}</a></td>"
f"<td>{html.escape(repo['repoType'])}</td>"
f"<td>{html.escape('; '.join(repo['reasons']))}</td>"
f"<td>{html.escape(repo['description'])}</td>"
"</tr>"
)
card_html = "\n".join(f"<div class='card'><div class='value'>{value}</div><div class='label'>{html.escape(label)}</div></div>" for label, value in cards)
table_html = "\n".join(rows)
return f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>GlobalGrid2050 Federation Control Ledger</title>
<style>
body {{ margin:0; font-family:system-ui, sans-serif; background:#071019; color:#eef6ff; }}
header {{ padding:24px; background:#0b1724; border-bottom:1px solid #20354b; }}
main {{ padding:20px; }}
h1 {{ margin:0 0 8px; font-size:24px; }}
.small {{ color:#aab9c8; font-size:13px; }}
.cards {{ display:grid; grid-template-columns:repeat(auto-fit, minmax(130px, 1fr)); gap:12px; margin-bottom:22px; }}
.card {{ background:#0c1825; border:1px solid #263d55; border-radius:10px; padding:14px; }}
.value {{ font-size:26px; font-weight:800; }}
.label {{ color:#aab9c8; font-size:12px; letter-spacing:.08em; }}
table {{ width:100%; border-collapse:collapse; font-size:13px; }}
th, td {{ padding:8px; border-bottom:1px solid #20354b; vertical-align:top; }}
th {{ text-align:left; color:#b9cadb; }}
a {{ color:#8ac5ff; }}
.green {{ color:#45d483; font-weight:800; }}
.amber {{ color:#ffcc4d; font-weight:800; }}
.red {{ color:#ff6b6b; font-weight:800; }}
.grey {{ color:#9aa7b4; font-weight:800; }}
.blue {{ color:#65a9ff; font-weight:800; }}
</style>
</head>
<body>
<header>
<h1>GlobalGrid2050 Federation Control Ledger</h1>
<div class="small">Internal static visibility surface generated from DuckDB-verified Parquet.</div>
<div class="small">Generated UTC: {html.escape(payload['generatedUTC'])}</div>
</header>
<main>
<section class="cards">{card_html}</section>
<table>
<thead><tr><th>Status</th><th>Repo</th><th>Type</th><th>Reasons</th><th>Description</th></tr></thead>
<tbody>{table_html}</tbody>
</table>
</main>
</body>
</html>
"""
def main() -> int:
payload = build_payload()
OUT.mkdir(parents=True, exist_ok=True)
(OUT / "federation_dashboard.json").write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
(OUT / "index.html").write_text(render_html(payload), encoding="utf-8")
print(json.dumps({"generatedUTC": payload["generatedUTC"], "repoCount": payload["summary"]["repoCount"]}, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())OSM Power Plants
A Python module in the fetchers folder of Data Grid GB. It is built from the raw requests helper (`raw_requests`) and the normalise step (`normalise`).
transformdata-grid-gb / conventional/fetchers/osm_power_plants.py · lines 1–20 of 20 · Not reached from any entry point (candidate for review) · pattern raw_requests (shared by 11 files)
- What it does
- It calculates its inputs. Defines raw_requests, normalise.
- Why it exists in the grid workflow
- Domain stage site_feasibility (topic 'maps-gis'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief.
- What it achieves
- OpenStreetMap power=plant with a conventional plant:source.
- Why it matters
- No other file in the estate was found to import it.
- Application
- data-grid-gb · conventional/fetchers · Python module
- Uses
- none found
- Used by
- none found
- Produces
- raw_requests, normalise
- Defines here
- raw_requests, normalise
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 conventional/fetchers/osm_power_plants.py:1-20 · blob 9b28c0572c614334c213103da96185b8b0c9c099 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: unreached_review
"""OpenStreetMap power=plant with a conventional plant:source.
PLACEHOLDER. Lane TBC (DC-A1..A6) owns this source; its fetcher replaces this file when it
lands, keeping the contract in assetpipe/pipeline.py (FETCHER_CONTRACT). Until then the
pipeline skips it and never fails because of it.
Registry entry: conventional/sources.json id "osm-power-plants" (open: yes, licence: ODbL-1.0).
"""
SOURCE_ID = "osm-power-plants"
LANE = "TBC (DC-A1..A6)"
STATUS = "placeholder"
def raw_requests():
return []
def normalise(raw):
raise NotImplementedError("osm-power-plants: fetcher not yet delivered by lane TBC (DC-A1..A6)")OSM Datacentres
A Python module in the fetchers folder of Data Grid GB. It is built from the raw requests helper (`raw_requests`) and the normalise step (`normalise`).
transformdata-grid-gb / datacentres/fetchers/osm_datacentres.py · lines 1–20 of 20 · Not reached from any entry point (candidate for review) · pattern raw_requests (shared by 11 files)
- What it does
- It calculates its inputs. Defines raw_requests, normalise.
- Why it exists in the grid workflow
- Domain stage upstream_foresight (path word 'datacentres'): 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
- OpenStreetMap features tagged as data centres (telecom=`data_center`, building=`data_center` and related).
- Why it matters
- No other file in the estate was found to import it.
- Application
- data-grid-gb · datacentres/fetchers · Python module
- Uses
- none found
- Used by
- none found
- Produces
- raw_requests, normalise
- Defines here
- raw_requests, normalise
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- data-grid-gb@4a9cef6c7c791f76d416c8b2fbafac8265f7a263 datacentres/fetchers/osm_datacentres.py:1-20 · blob 3bf1088127af80037eecb699c4c34be74b0ebed7 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
"""OpenStreetMap features tagged as data centres (telecom=data_center, building=data_center and related).
PLACEHOLDER. Lane DC-A4 owns this source; its fetcher replaces this file when it
lands, keeping the contract in assetpipe/pipeline.py (FETCHER_CONTRACT). Until then the
pipeline skips it and never fails because of it.
Registry entry: datacentres/sources.json id "osm-datacentres" (open: yes, licence: ODbL-1.0).
"""
SOURCE_ID = "osm-datacentres"
LANE = "DC-A4"
STATUS = "placeholder"
def raw_requests():
return []
def normalise(raw):
raise NotImplementedError("osm-datacentres: fetcher not yet delivered by lane DC-A4")