"""Pure diff utilities for versioned compute comparison configurations.""" from __future__ import annotations from typing import Any from app.schemas.compute_configuration import ( ComputeConfiguration, ComputeObservation, source_for, ) METRIC_ZH_LABELS: dict[str, str] = { "global_share": "全球总算力份额", "intelligent_share": "全球智能算力份额", "absolute": "计算设备总规模", "frontier_cluster_share": "前沿智算集群份额", "chip_inflow_share": "高端算力芯片流向份额", } COUNTRY_ZH_LABELS: dict[str, str] = { "CN": "中国", "US": "美国", "JP": "日本", "DE": "德国", "GB": "英国", "FR": "法国", "KR": "韩国", "IN": "印度", } def _observation_key(row: ComputeObservation) -> tuple[str, int]: return (row.metric, row.year) def _diff_keyed_section( section: str, old_items: dict[Any, dict[str, Any]], new_items: dict[Any, dict[str, Any]], ) -> dict[str, Any] | None: old_keys = set(old_items) new_keys = set(new_items) added = len(new_keys - old_keys) removed = len(old_keys - new_keys) modified = sum(1 for key in (old_keys & new_keys) if old_items[key] != new_items[key]) if not (added or removed or modified): return None return { "kind": "section_changed", "section": section, "added": added, "removed": removed, "modified": modified, } def diff_compute_configurations( old: ComputeConfiguration, new: ComputeConfiguration, ) -> list[dict[str, Any]]: """Compute structured observation-level diffs and section-level counts between two configs.""" diffs: list[dict[str, Any]] = [] old_obs = {_observation_key(row): row for row in old.observations} new_obs = {_observation_key(row): row for row in new.observations} all_keys = sorted(set(old_obs) | set(new_obs), key=lambda k: (k[0], k[1])) for metric, year in all_keys: old_row = old_obs.get((metric, year)) new_row = new_obs.get((metric, year)) if old_row is None and new_row is not None: diffs.append( { "kind": "observation_row_added", "metric": metric, "year": year, "period_label": new_row.period_label, } ) for code in sorted(new_row.values): new_val = float(new_row.values[code]) diffs.append( { "kind": "observation_value", "metric": metric, "year": year, "period_label": new_row.period_label, "code": code, "old_value": None, "new_value": new_val, "delta": round(new_val, 4), "change_kind": "new_observation", "old_source_id": None, "new_source_id": source_for(new_row, code), } ) continue if old_row is not None and new_row is None: diffs.append( { "kind": "observation_row_removed", "metric": metric, "year": year, "period_label": old_row.period_label, } ) for code in sorted(old_row.values): old_val = float(old_row.values[code]) diffs.append( { "kind": "observation_value", "metric": metric, "year": year, "period_label": old_row.period_label, "code": code, "old_value": old_val, "new_value": None, "delta": round(-old_val, 4), "change_kind": "observation_removed", "old_source_id": source_for(old_row, code), "new_source_id": None, } ) continue assert old_row is not None and new_row is not None if (old_row.period_label or None) != (new_row.period_label or None): diffs.append( { "kind": "period_label_changed", "metric": metric, "year": year, "old": old_row.period_label, "new": new_row.period_label, } ) for code in sorted(set(old_row.values) | set(new_row.values)): has_old = code in old_row.values has_new = code in new_row.values old_val = float(old_row.values[code]) if has_old else None new_val = float(new_row.values[code]) if has_new else None old_src = source_for(old_row, code) if has_old else None new_src = source_for(new_row, code) if has_new else None if old_val is None and new_val is not None: diffs.append( { "kind": "observation_value", "metric": metric, "year": year, "period_label": new_row.period_label, "code": code, "old_value": None, "new_value": new_val, "delta": round(new_val, 4), "change_kind": "new_observation", "old_source_id": None, "new_source_id": new_src, } ) elif old_val is not None and new_val is None: diffs.append( { "kind": "observation_value", "metric": metric, "year": year, "period_label": new_row.period_label, "code": code, "old_value": old_val, "new_value": None, "delta": round(-old_val, 4), "change_kind": "observation_removed", "old_source_id": old_src, "new_source_id": None, } ) elif old_val is not None and new_val is not None: delta = round(new_val - old_val, 4) if delta != 0: diffs.append( { "kind": "observation_value", "metric": metric, "year": year, "period_label": new_row.period_label, "code": code, "old_value": old_val, "new_value": new_val, "delta": delta, "change_kind": "historical_revision", "old_source_id": old_src, "new_source_id": new_src, } ) elif old_src != new_src: diffs.append( { "kind": "observation_value", "metric": metric, "year": year, "period_label": new_row.period_label, "code": code, "old_value": old_val, "new_value": new_val, "delta": 0.0, "change_kind": "source_reattributed", "old_source_id": old_src, "new_source_id": new_src, } ) section_specs = [ ( "sources", {s.id: s.model_dump(mode="json") for s in old.sources}, {s.id: s.model_dump(mode="json") for s in new.sources}, ), ( "innovation", {row.year: row.model_dump(mode="json") for row in old.innovation}, {row.year: row.model_dump(mode="json") for row in new.innovation}, ), ( "structures", {(row.scope, row.year): row.model_dump(mode="json") for row in old.structures}, {(row.scope, row.year): row.model_dump(mode="json") for row in new.structures}, ), ( "milestones", {row.id: row.model_dump(mode="json") for row in old.milestones}, {row.id: row.model_dump(mode="json") for row in new.milestones}, ), ( "national_hubs", {row.id: row.model_dump(mode="json") for row in old.national_hubs}, {row.id: row.model_dump(mode="json") for row in new.national_hubs}, ), ] for section_name, old_map, new_map in section_specs: entry = _diff_keyed_section(section_name, old_map, new_map) if entry is not None: diffs.append(entry) return diffs def has_observation_value_delta(diff_summary: list[dict[str, Any]]) -> bool: """Return True when diff_summary contains at least one non-zero observation value delta.""" return any( item.get("kind") == "observation_value" and item.get("delta") is not None and float(item["delta"]) != 0.0 for item in (diff_summary or []) ) def format_diff_entry(entry: dict[str, Any]) -> str: """Render a concise Chinese summary string for one diff_summary entry.""" kind = entry.get("kind") if kind == "observation_value": metric = METRIC_ZH_LABELS.get(str(entry.get("metric") or ""), str(entry.get("metric") or "")) year = entry.get("year") code = str(entry.get("code") or "") country = COUNTRY_ZH_LABELS.get(code, code) unit = " EFlops" if entry.get("metric") == "absolute" else "%" change_kind = entry.get("change_kind") if change_kind == "historical_revision": delta = float(entry.get("delta") or 0.0) delta_unit = " EFlops" if entry.get("metric") == "absolute" else "pp" return ( f"{year} 年 {metric} {country} " f"{entry.get('old_value')}{unit} → {entry.get('new_value')}{unit}({delta:+.2g}{delta_unit})" ) if change_kind == "new_observation": return f"新增 {year} 年 {metric} {country} {entry.get('new_value')}{unit}" if change_kind == "observation_removed": return f"移除 {year} 年 {metric} {country}(原 {entry.get('old_value')}{unit})" if change_kind == "source_reattributed": return f"{year} 年 {metric} {country} 来源变更:{entry.get('old_source_id')} → {entry.get('new_source_id')}" if kind == "period_label_changed": return f"{entry.get('year')} 年统计周期标签变更:{entry.get('old') or '全年'} → {entry.get('new') or '全年'}" if kind == "observation_row_added": return f"新增 {entry.get('year')} 年 {METRIC_ZH_LABELS.get(str(entry.get('metric') or ''), entry.get('metric'))} 观测行" if kind == "observation_row_removed": return f"移除 {entry.get('year')} 年 {METRIC_ZH_LABELS.get(str(entry.get('metric') or ''), entry.get('metric'))} 观测行" if kind == "section_changed": return ( f"{entry.get('section')} 变更(+{entry.get('added', 0)} / " f"-{entry.get('removed', 0)} / ~{entry.get('modified', 0)})" ) return "配置已更新" def summarize_diff(diff_summary: list[dict[str, Any]], action: str = "publish") -> tuple[int, str]: """Return (change_count, first_summary) suitable for revision lists.""" entries = list(diff_summary or []) if not entries: if action == "baseline": return 0, "初始基线封存" if action == "reset": return 0, "恢复内置权威报告数据" return 0, "无观测数值变更" primary = next( (item for item in entries if item.get("kind") == "observation_value"), entries[0], ) return len(entries), format_diff_entry(primary)