"""Refresh a bounded tail of official monthly demand before on-demand inference. Archived prefixes retain their recorded geographic scope. Refreshed observations are validated independently; a failed refresh never turns an archive into a current dataset. Only allowlisted official publisher URLs are fetched. """ from collections import OrderedDict from copy import deepcopy from datetime import datetime, timezone from pathlib import Path from threading import Lock from urllib.parse import urlencode import hashlib import json import math import time import pandas as pd from sources import (AU_REGIONS, REN_BASE, get_json, latest_complete_month, live_market, check_month) ROOT = Path(__file__).resolve().parent MAX_BACKFILL_MONTHS = 12 CACHE_TTL_SECONDS = 600 MAX_CACHE_MONTHS = 40 _MONTH_CACHE = OrderedDict() _CACHE_LOCK = Lock() SCOPES = { "PT": "Portugal mainland grid consumption; not customer or retailer demand", "DE": "Germany SMARD country grid load; not total final energy consumption", "AU": "AEMO NEM TOTALDEMAND proxy: NSW1 + QLD1 + SA1 + TAS1 + VIC1; excludes WA/NT", } def _now(): return datetime.now(timezone.utc).isoformat() def _market(country, region=""): if country not in SCOPES: raise ValueError("country must be PT, DE or AU.") if country == "AU" and region not in {"", "NEM", *AU_REGIONS}: raise ValueError("Australian region must be NEM, NSW1, QLD1, VIC1, SA1 or TAS1.") def _finite_nonnegative(value, label): if isinstance(value, bool): raise ValueError(f"{label} must be a finite nonnegative value.") try: number = float(value) except (TypeError, ValueError): raise ValueError(f"{label} must be a finite nonnegative value.") from None if not math.isfinite(number) or number < 0: raise ValueError(f"{label} must be a finite nonnegative value.") return number def _pt_month(month): parsed = check_month(month) url = REN_BASE + "ElectricityConsumptionSupplyMonthly?" + urlencode( {"culture": "en-US", "year": parsed.year, "month": parsed.month}) data, digest, retrieved = get_json(url) if not isinstance(data, list): raise ValueError("REN monthly response schema changed.") consumption = [row for row in data if isinstance(row, dict) and row.get("type") == "CONSUMPTION"] if len(consumption) != 1: raise ValueError("REN must publish exactly one CONSUMPTION aggregate.") value = _finite_nonnegative(consumption[0].get("monthly_Accumulation"), "REN consumption") return value, {"source_urls": [url], "response_sha256": [digest], "source_retrieved_at": [retrieved], "coverage_basis": "Published non-null monthly aggregate; not an independent interval audit"} def _de_month(month): from sources import smard_month frame, meta = smard_month(410, "DE", month, reader=get_json) meta["transformation"] = "Sum hourly MWh / 1000 = monthly GWh" return float(frame.value.sum()) / 1000, meta def _au_month(month): urls, hashes, times, values = [], [], [], [] for region in AU_REGIONS: _, meta = live_market("AU", region, month) value = _finite_nonnegative(meta.get("integrated_demand_GWh"), "AEMO integrated demand") values.append(value) urls.extend(meta["source_urls"]) hashes.extend(meta["response_sha256"]) # live_market AU performs an uncached bounded download and validates all # settlement interval ends. Record completion, not the outer request time. times.append(_now()) return sum(values), {"source_urls": urls, "response_sha256": hashes, "source_retrieved_at": times, "regions": list(AU_REGIONS), "regional_demand_GWh": dict(zip(AU_REGIONS, values)), "coverage_basis": "All expected settlement intervals validated separately in all five NEM regions", "transformation": "Sum region TOTALDEMAND MW × interval hours / 1000; published demand proxy"} def _fetch_month(country, month): """One synchronized, bounded public cache; no customer input is stored.""" key = (country, month) with _CACHE_LOCK: cached = _MONTH_CACHE.get(key) if cached and time.monotonic() - cached[0] < CACHE_TTL_SECONDS: _MONTH_CACHE.move_to_end(key) value, metadata = deepcopy(cached[1]) metadata["cache_hit"] = True return value, metadata try: value, metadata = {"PT": _pt_month, "DE": _de_month, "AU": _au_month}[country](month) except ValueError: raise except Exception: raise ValueError(f"{country} official feed is unavailable for {month}; archived data was not substituted.") from None metadata = {**metadata, "month": month, "retrieved_at": _now(), "cache_hit": False} _MONTH_CACHE[key] = (time.monotonic(), (value, deepcopy(metadata))) _MONTH_CACHE.move_to_end(key) while len(_MONTH_CACHE) > MAX_CACHE_MONTHS: _MONTH_CACHE.popitem(last=False) return value, metadata def _archive(country, latest): path = ROOT / "data" / f"{country.lower()}_monthly.csv" try: raw = path.read_bytes() d = pd.read_csv(path) if not {"timestamp", "value", "unit", "coverage"} <= set(d) or not 12 <= len(d) <= 600: raise ValueError("invalid archive schema") dates = pd.to_datetime(d.timestamp, format="ISO8601", errors="raise") expected = pd.date_range(start=dates.iloc[0], periods=len(d), freq="MS") if dates.dt.tz is not None or not pd.DatetimeIndex(dates).equals(expected): raise ValueError("archive months are not ordered and consecutive") if set(d.unit) != {"GWh"} or not (pd.to_numeric(d.coverage) == 1).all(): raise ValueError("archive unit/coverage changed") values = [_finite_nonnegative(v, "Archived demand") for v in d.value] if dates.iloc[-1].strftime("%Y-%m") > latest: raise ValueError("archive contains incomplete/future months") except Exception: raise ValueError("The official archive failed validation; no forecast input returned.") from None records = [{"timestamp": t.date().isoformat(), "value": v, "unit": "GWh", "coverage": 1.0} for t, v in zip(dates, values)] return records, hashlib.sha256(raw).hexdigest() def official_history(country, region=""): """Return archive + verified fresh tail, or raise without a stale fallback. At least the final archived month is fetched again. Up to twelve subsequent complete months may be appended. Earlier archived months are not represented as freshly revalidated. Australian history always retains its five-region NEM scope, even when the caller requests a region for separate market context. """ _market(country, region) requested = _now() latest = latest_complete_month() records, archive_digest = _archive(country, latest) cutoff = records[-1]["timestamp"][:7] months = [t.strftime("%Y-%m") for t in pd.date_range(cutoff + "-01", latest + "-01", freq="MS")] if len(months) - 1 > MAX_BACKFILL_MONTHS: raise ValueError("Official archive is more than 12 complete months behind; rebuild the archive before live inference.") refreshed, sources = {}, [] for month in months: value, metadata = _fetch_month(country, month) refreshed[month] = {"timestamp": month + "-01", "value": value, "unit": "GWh", "coverage": 1.0} sources.append(metadata) merged = [row for row in records if row["timestamp"][:7] < cutoff] + list(refreshed.values()) urls = [url for source in sources for url in source["source_urls"]] hashes = [value for source in sources for value in source["response_sha256"]] times = [value for source in sources for value in source["source_retrieved_at"]] metadata = { "country": country, "scope": SCOPES[country], "region_used": "NEM" if country == "AU" else "PT-mainland" if country == "PT" else "DE", "requested_region": region, "requested_at": requested, "archive_cutoff": cutoff, "archive_sha256": archive_digest, "archive_prefix_refreshed": False, "latest_observation": merged[-1]["timestamp"], "latest_complete_month": latest, "verified_months": months, "refreshed_months": months, "appended_months": months[1:], "source_urls": urls, "response_sha256": hashes, "source_retrieved_at": times, "cache_ttl_seconds": CACHE_TTL_SECONDS, "cache_hit": all(s["cache_hit"] for s in sources), "monthly_sources": sources, "record_sha256": hashlib.sha256(json.dumps(merged, sort_keys=True, allow_nan=False).encode()).hexdigest(), "limits": [ "Grid-demand target only; not a household consumption or retail-price forecast.", "Older archive observations retain their archived vintage; only listed months were rechecked.", "Publisher values can be revised. Current revised history is not a historical publication-vintage backtest.", ], } return {"status": "verified_official_history", "records": merged, "metadata": metadata} def live_market_context(country, region="", month=None): """Return a bounded inspection of the existing official market reader. DE's legacy context reader returns only its last monthly publication block. It is deliberately not used to construct official_history monthly totals. """ _market(country, region) month = month or latest_complete_month() check_month(month) if country == "AU" and region in {"", "NEM"}: region = "NSW1" requested = _now() try: frame, meta = live_market(country, region, month) except Exception: return {"status": "unavailable", "records": [], "metadata": {"country": country, "month": month, "requested_at": requested, "scope": SCOPES[country]}, "message": "Official market context is unavailable. No archived values substituted."} metadata = dict(meta) metadata["requested_at"] = requested metadata["rows_total"] = len(frame) metadata["preview_rows"] = min(120, len(frame)) metadata["preview_truncated"] = len(frame) > 120 metadata["complete_month"] = country != "DE" if country == "DE": # Re-read the same JSON cache entries to retain actual fetch timestamps, # rather than presenting the legacy request timestamp as retrieval time. metadata["source_retrieved_at"] = [get_json(url)[2] for url in meta["source_urls"]] metadata["retrieved_at"] = max(metadata["source_retrieved_at"]) metadata["coverage_note"] = "Last SMARD publication block only; not a complete monthly series or total." elif country == "PT": metadata["retrieved_at"] = max(metadata["source_retrieved_at"]) else: metadata["retrieved_at"] = _now() metadata["source_retrieved_at"] = [metadata["retrieved_at"]] metadata["cache_ttl_seconds"] = 0 # Existing AEMO context downloads are uncached. rows = json.loads(frame.tail(120).to_json(orient="records")) return {"status": "available", "records": rows, "metadata": metadata}