"""Deterministic StagePresentationContract compiler (F-14, F-15, F-17, F-18 · R1/R2/R5/R8 hardened).""" from __future__ import annotations import hashlib import json from typing import Any, Literal from pydantic import BaseModel, ConfigDict, Field from sqlalchemy import desc, select from sqlalchemy.ext.asyncio import AsyncSession from app.core.logging import get_logger from app.models.situational_assessment import StagePresentation from app.services.ai.domain_catalog import SPATIAL_POSTURE_DOMAINS, SpatialDomain, WorkbenchDomain from app.services.ai.incident_agent import ( DRILL_INCIDENT_KEY, investigate_infrastructure_incident, ) from app.services.ai.spatial_domain_agent import investigate_spatial_domain from app.services.ai.tool_registry import TimeBasis, query_bgp_incidents_tool, query_compute_posture_tool logger = get_logger(__name__, service="stage_compiler") class StageCameraPose(BaseModel): model_config = ConfigDict(extra="forbid") lat: float = Field(ge=-90, le=90) lon: float = Field(ge=-180, le=180) zoom: float = Field(ge=0.5, le=3.5, default=1.05) class StageArcSpec(BaseModel): model_config = ConfigDict(extra="forbid") from_label: str from_lat: float = Field(ge=-90, le=90) from_lon: float = Field(ge=-180, le=180) to_label: str to_lat: float = Field(ge=-90, le=90) to_lon: float = Field(ge=-180, le=180) relation_kind: Literal["logical_as_route", "hub_synergy_preview"] phase: Literal["before", "after", "synergy"] = "after" label: str = "" class StageStepSpec(BaseModel): model_config = ConfigDict(extra="forbid") step_id: str = Field(min_length=1, max_length=80) stage: Literal[ "overview", "divergence", "attribution", "convergence_hubs", "discover", "unfold", "explain", "impact", "recover", ] title: str = Field(min_length=1, max_length=180) title_en: str = Field(min_length=1, max_length=200) caption: str = Field(min_length=1, max_length=500) caption_en: str = Field(min_length=1, max_length=560) dwell_ms: int = Field(ge=2000, le=20000, default=5600) camera: StageCameraPose compute_mode: str | None = None focus_year: int | None = None spotlight_Statistic_codes: list[str] = Field(default_factory=list) highlight_milestone_id: str | None = None enable_national_hubs: bool = False logical_arcs: list[StageArcSpec] = Field(default_factory=list) measured_impact_regions: list[str] = Field(default_factory=list) evidence_ids: list[str] = Field(default_factory=list) class StagePresentationContract(BaseModel): model_config = ConfigDict(extra="forbid") presentation_key: str domain: WorkbenchDomain time_basis: TimeBasis cutoff_date: str | None = None publish_id: str | None = None is_drill: bool = False title: str title_en: str summary: str summary_en: str reduced_motion_supported: bool = True steps: list[StageStepSpec] = Field(min_length=1, max_length=12) evidence: dict[str, dict[str, Any]] = Field(default_factory=dict) def _filter_evidence_by_time_basis( evidence: dict[str, dict[str, Any]], *, time_basis: TimeBasis, cutoff_date: str | None, ) -> tuple[dict[str, dict[str, Any]], list[str]]: """Enforce F-15 / R5: `as_known_then` strictly withholds post-cutoff retrospectives/whitepapers.""" if time_basis != "as_known_then" or not cutoff_date: return dict(evidence), [] kept: dict[str, dict[str, Any]] = {} withheld: list[str] = [] for eid, item in evidence.items(): pub = str(item.get("published_at") or "") if pub and len(pub) >= 10 and pub[:10] > cutoff_date[:10]: withheld.append(eid) continue kept[eid] = item return kept, withheld def _contract_fingerprint(contract: StagePresentationContract) -> str: return hashlib.sha256( json.dumps(contract.model_dump(mode="json"), sort_keys=True, ensure_ascii=False).encode("utf-8") ).hexdigest() def compile_compute_posture_presentation( series: dict[str, Any], *, time_basis: TimeBasis = "retrospective", cutoff_date: str | None = None, ) -> StagePresentationContract: """Compile the Strategic Compute Posture tour dynamically from filtered `series`.""" effective_cutoff = cutoff_date or series.get("cutoff_at") raw_evidence = series.get("evidence") or {} evidence, _ = _filter_evidence_by_time_basis( raw_evidence, time_basis=time_basis, cutoff_date=effective_cutoff ) rpi = series.get("bilateral_rpi") or {} tot = rpi.get("latest_total") or {"year": 2024, "cn_value": 23, "us_value": 44, "rpi_percent": 52.3} intel = rpi.get("latest_intelligent") innov = series.get("innovation_summary") attr = (series.get("denominator_attribution") or {}).get("CN") cn_struct = (series.get("structures") or {}).get("CN") def _valid_eids(*candidates: str) -> list[str]: matched = [c for c in candidates if c in evidence] if matched: return matched return list(evidence.keys())[:2] steps: list[StageStepSpec] = [ StageStepSpec( step_id="act-1-global-concentration", stage="overview", title=f"第一幕 · {tot['year']} 全球算力高集中度格局", title_en=f"Act I · {tot['year']} Global Compute Concentration Overview", caption=( f"截至 {tot['year']} 年观测,全球算力向头部经济体集聚(美 {tot['us_value']}%、中 {tot['cn_value']}%,双边 RPI {tot['rpi_percent']}%)," "中美构成全球算力博弈双主轴。" ), caption_en=( f"As of {tot['year']}, global compute concentrates in top poles (U.S. {tot['us_value']}%, China {tot['cn_value']}%, RPI {tot['rpi_percent']}%)." ), dwell_ms=5400, camera=StageCameraPose(lat=28.0, lon=145.0, zoom=0.96), compute_mode="global_share", focus_year=tot["year"], spotlight_Statistic_codes=["CN", "US"], evidence_ids=_valid_eids("caict-2025", "caict-2024", "caict-2023", "caict-2022"), ), StageStepSpec( step_id="act-2-scissors-divergence", stage="divergence", title=f"第二幕 · 截至 {tot['year']} 双边份额走廊演进", title_en=f"Act II · Bilateral Share Trajectory Through {tot['year']}", caption=( f"2021–2022 年中美总算力一度接近平价(33% vs 34%,RPI 97.1%);截至 {tot['year']} 年已核验读数为 " f"中 {tot['cn_value']}% vs 美 {tot['us_value']}%(RPI {tot['rpi_percent']}%)。" ), caption_en=( f"Following 2021–2022 near-parity (RPI 97.1%), verified {tot['year']} shares stand at " f"China {tot['cn_value']}% vs U.S. {tot['us_value']}% (RPI {tot['rpi_percent']}%)." ), dwell_ms=6200, camera=StageCameraPose(lat=36.0, lon=-98.0, zoom=1.08), compute_mode="global_share", focus_year=tot["year"], spotlight_Statistic_codes=["US", "CN"], highlight_milestone_id="ms-2022-bis-chip-controls", evidence_ids=_valid_eids("caict-2023", "caict-2024", "caict-2025", "bis-export-controls-2022"), ), ] if intel: attr_clause = ( f"我国总算力增至 {attr['country_to']:.0f} EFlops(+{attr['country_growth_pct']}%),份额波动主因是全球总盘子扩张至 {attr['global_to']:.0f} EFlops(+{attr['global_growth_pct']}%)。" if attr and attr.get("global_to") else "智算集群供给节奏成为双边份额变化的核心变量。" ) steps.append( StageStepSpec( step_id="act-3-intelligent-denominator", stage="attribution", title="第三幕 · 智能算力分化与全球分母稀释归因", title_en="Act III · Intelligent Compute & Global Denominator Dilution", caption=f"全球智能算力竞争份额美 {intel['us_value']}% vs 中 {intel['cn_value']}%(RPI {intel['rpi_percent']}%);{attr_clause}", caption_en=( f"Global intelligent compute stands at {intel['us_value']}% U.S. vs {intel['cn_value']}% China (RPI {intel['rpi_percent']}%)." ), dwell_ms=6200, camera=StageCameraPose(lat=34.5, lon=112.0, zoom=1.12), compute_mode="intelligent_share", focus_year=intel["year"], spotlight_Statistic_codes=["CN", "US"], highlight_milestone_id="ms-2024-capex-divergence", evidence_ids=_valid_eids("caict-2025", "epoch-chip-imports-2026"), ) ) hubs_available = bool(series.get("national_hubs")) struct_pct = cn_struct["intelligent_share"] if cn_struct else None if hubs_available: struct_txt = f"我国国内智算构成已达 {struct_pct}%," if struct_pct else "" innov_txt = ( f"中美 AI 创新指数分差收窄至 {innov['to_value']} 分({innov['delta']} 分);" if innov else "" ) steps.append( StageStepSpec( step_id="act-4-innovation-and-eight-hubs", stage="convergence_hubs", title="第四幕 · 智算结构演进与八大国家算力枢纽布局", title_en="Act IV · AI Compute Structure & 8 National Green Hubs", caption=f"{struct_txt}{innov_txt}“东数西算”八大国家算力枢纽以西部清洁绿电协同支撑大模型训推需求。", caption_en="China's 8 National Compute Hubs pair eastern low-latency inference demand with western green-power training bases.", dwell_ms=7000, camera=StageCameraPose(lat=34.8, lon=107.8, zoom=1.36), compute_mode="global_share", focus_year=tot["year"], spotlight_Statistic_codes=["CN"], highlight_milestone_id="ms-2025-moe-innovation-convergence" if innov else None, enable_national_hubs=True, evidence_ids=_valid_eids("caict-2025", "innovation-2026", "ndrc-east-west-2022"), ) ) return StagePresentationContract( presentation_key="compute-posture-cn-us", domain="compute", time_basis=time_basis, cutoff_date=effective_cutoff, is_drill=False, title="中美算力博弈全景与八大国家枢纽战略导览", title_en="US-China Compute Posture & 8 National Hubs Strategic Tour", summary="多幕式解析中美总算力与智算剪刀差成因、全球分母稀释效应、创新分差收敛及东数西算空间布局。", summary_en="Spatial tour of US-China compute share divergence, denominator dilution, innovation convergence, and China's 8 National Hubs.", steps=steps, evidence=evidence, ) def _derive_real_incident_arcs_and_camera( incident: dict[str, Any], ) -> tuple[list[StageArcSpec], list[StageArcSpec], StageCameraPose, list[str]]: """Build logical AS arcs strictly from the incident's own coordinates/collectors (zero AS13335 splicing).""" if incident.get("logical_paths_before") or incident.get("logical_paths_after"): before = [ StageArcSpec( from_label=arc["from_label"], from_lat=arc["from_lat"], from_lon=arc["from_lon"], to_label=arc["to_label"], to_lat=arc["to_lat"], to_lon=arc["to_lon"], relation_kind="logical_as_route", phase="before", label=f"逻辑路由关系(变更前):{arc.get('asn_path', '')}", ) for arc in (incident.get("logical_paths_before") or []) ] after = [ StageArcSpec( from_label=arc["from_label"], from_lat=arc["from_lat"], from_lon=arc["from_lon"], to_label=arc["to_label"], to_lat=arc["to_lat"], to_lon=arc["to_lon"], relation_kind="logical_as_route", phase="after", label=f"逻辑路由关系(异常期):{arc.get('asn_path', '')}", ) for arc in (incident.get("logical_paths_after") or []) ] regions = [str(r) for r in (incident.get("affected_regions") or []) if isinstance(r, str)][:6] return before, after, StageCameraPose(lat=36.0, lon=-32.0, zoom=1.02), regions coord_points: list[dict[str, Any]] = [] region_labels: list[str] = [] for reg in incident.get("affected_regions") or []: if isinstance(reg, dict): country = str(reg.get("country") or "").strip() city = str(reg.get("city") or "").strip() lbl = "·".join(p for p in (country, city) if p) or str(reg.get("collector") or "观测点") if lbl and lbl not in region_labels: region_labels.append(lbl) lat = reg.get("latitude") lon = reg.get("longitude") if isinstance(lat, (int, float)) and isinstance(lon, (int, float)): coord_points.append({"label": lbl, "lat": float(lat), "lon": float(lon)}) elif reg: s = str(reg).strip() if s and s not in region_labels: region_labels.append(s) asns = [f"AS{a}" for a in (incident.get("affected_asns") or [])] asn_label = " → ".join(asns[:3]) if asns else str(incident.get("incident_type") or "BGP") after_arcs: list[StageArcSpec] = [] if len(coord_points) >= 2: for idx in range(min(3, len(coord_points) - 1)): p1, p2 = coord_points[idx], coord_points[idx + 1] after_arcs.append( StageArcSpec( from_label=p1["label"], from_lat=p1["lat"], from_lon=p1["lon"], to_label=p2["label"], to_lat=p2["lat"], to_lon=p2["lon"], relation_kind="logical_as_route", phase="after", label=f"控制面异常传播:{asn_label}", ) ) elif len(coord_points) == 1: p1 = coord_points[0] # Connect RIPE RIS Amsterdam primary route collector hub to the measured region if abs(p1["lat"] - 52.3676) > 1.5 or abs(p1["lon"] - 4.9041) > 1.5: after_arcs.append( StageArcSpec( from_label="RIPE RIS Collector Hub", from_lat=52.3676, from_lon=4.9041, to_label=p1["label"], to_lat=p1["lat"], to_lon=p1["lon"], relation_kind="logical_as_route", phase="after", label=f"控制面观测路径:{asn_label}", ) ) primary_cam = ( StageCameraPose(lat=coord_points[0]["lat"], lon=coord_points[0]["lon"], zoom=1.12) if coord_points else StageCameraPose(lat=38.0, lon=-40.0, zoom=1.02) ) return [], after_arcs, primary_cam, region_labels[:6] def compile_incident_five_act_presentation( incident: dict[str, Any], assessment_payload: dict[str, Any], raw_evidence: dict[str, dict[str, Any]], *, time_basis: TimeBasis = "retrospective", cutoff_date: str | None = None, ) -> StagePresentationContract: """Compile the 5-act Infrastructure Incident stage presentation strictly from `incident`.""" effective_cutoff = ( cutoff_date or incident.get("cutoff_at") or (str(incident.get("started_at") or "")[:10] if time_basis == "as_known_then" else None) ) evidence, withheld = _filter_evidence_by_time_basis( raw_evidence, time_basis=time_basis, cutoff_date=effective_cutoff ) eids = list(evidence.keys()) is_drill = bool(incident.get("is_drill")) before_arcs, after_arcs, primary_cam, measured_regions = _derive_real_incident_arcs_and_camera(incident) raw_title = str(incident.get("title") or incident["incident_key"]) if is_drill and not raw_title.startswith("[演练档案]"): raw_title = f"[演练档案] {raw_title}" basis_note = ( f"(当时可知模式:已隔离 {len(withheld)} 份事后复盘资料)" if time_basis == "as_known_then" and withheld else "(当时可知模式:仅展示截点前已捕获报文)" if time_basis == "as_known_then" else "" ) scope_desc = "、".join(measured_regions) if measured_regions else "当前采集器观测视点" is_resolved = ( str(incident.get("status") or "").lower() == "resolved" and not incident.get("withheld_post_cutoff_recovery") ) recover_title = ( "5/5 恢复归档 · 异常路由撤销与路径收敛" if is_resolved else "5/5 持续跟踪 · 待后续报文确认收敛" ) recover_title_en = ( "5/5 Resolved · Route Withdrawal & Convergence" if is_resolved else "5/5 Ongoing Tracking · Awaiting Convergence Confirmation" ) recover_caption = ( "异常通告撤销后控制面路径回归基准状态,事件与证据快照已固化供回放。" if is_resolved else "截至当前观测截点,该异常仍处于活跃或待确认收敛状态,持续监测后续 BGP UPDATE 撤销通告。" ) recover_caption_en = ( "Control-plane paths converged back to baseline following route withdrawal." if is_resolved else "As of this observation cutoff, full route convergence is not yet confirmed; monitoring continues." ) steps = [ StageStepSpec( step_id="inc-1-discover", stage="discover", title="1/5 发现 · 观测流捕获控制面路由异动", title_en="1/5 Discover · BGP Control-Plane Anomaly Captured", caption=f"{raw_title} — 监测源 {incident.get('source', 'BGP Monitor')} 捕获前缀异常通告 {basis_note}".strip(), caption_en=f"{raw_title} — BGP monitoring stream detected abnormal prefix announcements.", dwell_ms=4800, camera=primary_cam, evidence_ids=eids[:1], ), StageStepSpec( step_id="inc-2-unfold", stage="unfold", title="2/5 展开 · 控制面逻辑 AS 传播路径对照", title_en="2/5 Unfold · Logical AS Propagation Path View", caption="高空弧线表征自治系统(AS)控制面逻辑传播关系,与海底物理光缆图层分层独立展示。", caption_en="High-altitude arcs depict logical AS control-plane propagation, distinct from subsea physical cable geometry.", dwell_ms=6000, camera=StageCameraPose(lat=primary_cam.lat * 0.7, lon=primary_cam.lon, zoom=0.98), logical_arcs=[*before_arcs, *after_arcs], evidence_ids=eids[:2], ), StageStepSpec( step_id="inc-3-explain", stage="explain", title="3/5 解释 · 已确认事实与候选成因边界", title_en="3/5 Explain · Confirmed Observations vs Candidate Causes", caption=( (assessment_payload.get("candidate_explanations") or [{}])[0].get( "statement", "基于控制面报文区分策略/会话异常候选成因;无独立海缆告警时不归咎于物理断缆。", ) ), caption_en="Separating verified BGP UPDATE observations from candidate control-plane causes.", dwell_ms=5800, camera=primary_cam, logical_arcs=after_arcs, evidence_ids=eids, ), StageStepSpec( step_id="inc-4-impact", stage="impact", title="4/5 影响 · 实测与采集器视点范围", title_en="4/5 Impact · Measured & Collector Vantage Scope", caption=f"实测与采集器关联范围:{scope_desc}(基于已捕获异常通告的自治系统与采集站视点,未覆盖区域暂缺样本)。", caption_en=f"Measured & collector-observed scope: {scope_desc}.", dwell_ms=5200, camera=primary_cam, measured_impact_regions=measured_regions, evidence_ids=eids[:1], ), StageStepSpec( step_id="inc-5-recover", stage="recover", title=recover_title, title_en=recover_title_en, caption=recover_caption, caption_en=recover_caption_en, dwell_ms=4800, camera=primary_cam, logical_arcs=before_arcs if is_resolved else after_arcs, evidence_ids=eids, ), ] return StagePresentationContract( presentation_key=f"incident-{incident['incident_key']}", domain="bgp", time_basis=time_basis, cutoff_date=effective_cutoff, is_drill=is_drill, title=f"{'[演练档案] ' if is_drill else ''}五段式异动推演:{incident['title'].removeprefix('[演练档案] ')}", title_en=f"{'[Drill] ' if is_drill else ''}5-Act Incident Playback: {incident['title']}", summary=str(incident.get("summary") or ""), summary_en="Five-stage verified BGP control-plane incident playback (Discover → Unfold → Explain → Impact → Recover).", steps=steps, evidence=evidence, ) def _wrap_ephemeral_contract(contract: StagePresentationContract, cursor: int, revision: int = 1) -> dict[str, Any]: return { "cursor": cursor, "id": cursor, "presentation_key": contract.presentation_key, "domain": contract.domain, "time_basis": contract.time_basis, "is_drill": contract.is_drill, "revision": revision, "title": contract.title, "summary": contract.summary, "contract": contract.model_dump(mode="json"), "evidence_ids": list(contract.evidence.keys()), } _COUNTRY_CAMERA_ANCHORS: dict[str, tuple[float, float, float]] = { "CN": (35.0, 105.0, 1.18), "US": (39.0, -98.0, 1.12), "JP": (36.2, 138.2, 1.25), "DE": (51.1, 10.4, 1.25), "GB": (54.0, -2.0, 1.25), "FR": (46.6, 2.2, 1.25), "KR": (36.5, 127.8, 1.28), "IN": (21.5, 79.0, 1.18), } _REVISION_METRIC_LABELS_EN: dict[str, str] = { "global_share": "Global Compute Share", "intelligent_share": "Global AI Compute Share", "absolute": "Total Compute Capacity", "frontier_cluster_share": "Frontier AI Cluster Share", "chip_inflow_share": "AI Chip Inflow Share", } def compile_compute_revision_presentation( *, publish_id: str, action: str, series: dict[str, Any], value_diffs: list[dict[str, Any]], time_basis: TimeBasis = "retrospective", ) -> StagePresentationContract: """Compile a revision-driven stage presentation notice from structured observation diffs.""" from app.services.compute_revision_diff import COUNTRY_ZH_LABELS, METRIC_ZH_LABELS raw_evidence = series.get("evidence") or {} evidence = dict(raw_evidence) historical_diffs = [d for d in value_diffs if d.get("change_kind") == "historical_revision"] has_historical = bool(historical_diffs) primary = historical_diffs[0] if has_historical else value_diffs[0] metric = str(primary.get("metric") or "global_share") year = int(primary.get("year") or 2024) metric_zh = METRIC_ZH_LABELS.get(metric, metric) metric_en = _REVISION_METRIC_LABELS_EN.get(metric, metric) spotlight_codes = list( dict.fromkeys(str(d.get("code")) for d in value_diffs if d.get("code")) ) or ["CN", "US"] first_code = spotlight_codes[0] cam_lat, cam_lon, cam_zoom = _COUNTRY_CAMERA_ANCHORS.get(first_code, (34.5, 110.0, 1.12)) change_lines_zh: list[str] = [] change_lines_en: list[str] = [] referenced_eids: list[str] = [] for item in value_diffs[:4]: code = str(item.get("code") or "") c_zh = COUNTRY_ZH_LABELS.get(code, code) item_metric = str(item.get("metric") or metric) item_unit = " EFlops" if item_metric == "absolute" else "%" item_delta_unit = " EFlops" if item_metric == "absolute" else "pp" old_val = item.get("old_value") new_val = item.get("new_value") delta = float(item.get("delta") or 0.0) if old_val is not None and new_val is not None: change_lines_zh.append( f"{c_zh} {old_val}{item_unit} → {new_val}{item_unit}({delta:+.2g}{item_delta_unit})" ) change_lines_en.append( f"{code} {old_val}{item_unit} -> {new_val}{item_unit} ({delta:+.2g}{item_delta_unit})" ) elif new_val is not None: change_lines_zh.append(f"{c_zh} 新增 {new_val}{item_unit}") change_lines_en.append(f"{code} added {new_val}{item_unit}") elif old_val is not None: change_lines_zh.append(f"{c_zh} 移除(原 {old_val}{item_unit})") change_lines_en.append(f"{code} removed (was {old_val}{item_unit})") for src_key in ("new_source_id", "old_source_id"): eid = item.get(src_key) if eid and eid in evidence and eid not in referenced_eids: referenced_eids.append(str(eid)) if not referenced_eids: referenced_eids = list(evidence.keys())[:2] changes_zh = ";".join(change_lines_zh) changes_en = "; ".join(change_lines_en) if has_historical: title_zh = f"{year} 年{metric_zh}数据获修订" title_en = f"{year} {metric_en} Data Revised" caption_zh = f"{changes_zh}。这是对历史数据的修订,不代表当期算力跃升。" caption_en = f"{changes_en}. This is a historical data revision, not a current-period jump." elif action == "reset": title_zh = f"{year} 年{metric_zh}已恢复内置版本" title_en = f"{year} {metric_en} Restored to Bundled Baseline" caption_zh = f"{changes_zh}。台账已恢复至内置权威报告基线。" caption_en = f"{changes_en}. Ledger restored to bundled authoritative report baseline." else: title_zh = f"{year} 年{metric_zh}台账已更新" title_en = f"{year} {metric_en} Ledger Updated" caption_zh = f"{changes_zh}。" caption_en = f"{changes_en}." steps = [ StageStepSpec( step_id="rev-act-1-notice", stage="overview", title=title_zh, title_en=title_en, caption=caption_zh, caption_en=caption_en, dwell_ms=6400, camera=StageCameraPose(lat=cam_lat, lon=cam_lon, zoom=cam_zoom), compute_mode=metric, focus_year=year, spotlight_Statistic_codes=spotlight_codes, evidence_ids=referenced_eids, ), StageStepSpec( step_id="rev-act-2-lineage", stage="attribution", title=f"版本 {publish_id[:8]} · 证据溯源与口径校验", title_en=f"Revision {publish_id[:8]} · Evidence & Denominator Check", caption=( f"当前已生效版本 {publish_id[:8]},共更新 {len(value_diffs)} 项观测值(口径:{metric_zh},{year} 年)。" "点击卡片数值旁溯源按钮可查看报告原文页码、复核记录与历史对比。" ), caption_en=( f"Active revision {publish_id[:8]} updated {len(value_diffs)} observation value(s) " f"({metric_en}, {year}). Inspect lineage from the compute card for full provenance." ), dwell_ms=5600, camera=StageCameraPose(lat=cam_lat, lon=cam_lon, zoom=max(0.95, cam_zoom - 0.1)), compute_mode=metric, focus_year=year, spotlight_Statistic_codes=spotlight_codes, evidence_ids=referenced_eids, ), ] return StagePresentationContract( presentation_key="compute-revision-notice", domain="compute", time_basis=time_basis, publish_id=publish_id, is_drill=False, title=title_zh, title_en=title_en, summary=caption_zh, summary_en=caption_en, steps=steps, evidence=evidence, ) async def publish_stage_contract( db: AsyncSession, contract: StagePresentationContract, *, explicit_revision: int | None = None, ) -> StagePresentation | None: """Idempotently persist a `StagePresentation` ONLY on explicit write-side snapshot/config pipelines.""" if not hasattr(db, "execute") or not hasattr(db, "add") or not hasattr(db, "flush"): return None if contract.publish_id: existing_rows = ( ( await db.execute( select(StagePresentation) .where( StagePresentation.presentation_key == contract.presentation_key, StagePresentation.time_basis == contract.time_basis, ) .order_by(desc(StagePresentation.revision), desc(StagePresentation.id)) .limit(50) ) ) .scalars() .all() ) for row in existing_rows: if isinstance(row.contract, dict) and row.contract.get("publish_id") == contract.publish_id: return row new_fp = _contract_fingerprint(contract) existing = ( await db.execute( select(StagePresentation) .where( StagePresentation.presentation_key == contract.presentation_key, StagePresentation.time_basis == contract.time_basis, ) .order_by(desc(StagePresentation.revision), desc(StagePresentation.id)) .limit(1) ) ).scalar_one_or_none() if explicit_revision is not None: next_rev = int(explicit_revision) elif isinstance(existing, StagePresentation) and existing.contract: old_fp = hashlib.sha256( json.dumps(existing.contract, sort_keys=True, ensure_ascii=False).encode("utf-8") ).hexdigest() if old_fp == new_fp: return existing next_rev = int(existing.revision or 1) + 1 else: next_rev = 1 row = StagePresentation( presentation_key=contract.presentation_key, domain=contract.domain, time_basis=contract.time_basis, revision=next_rev, title=contract.title, summary=contract.summary, contract=contract.model_dump(mode="json"), evidence_ids=list(contract.evidence.keys()), ) db.add(row) await db.flush() return row async def list_or_compile_presentations( db: AsyncSession, *, after_cursor: int = 0, countries: list[str] | None = None, time_basis: TimeBasis = "retrospective", cutoff_at: str | None = None, include_drill: bool = False, persist: bool = False, ) -> dict[str, Any]: """Read-only by default (`persist=False`): zero DB writes, zero LLM calls, strict drill isolation.""" codes = countries or ["CN", "US"] series = await query_compute_posture_tool( db, codes, mode="global_share", time_basis=time_basis, cutoff_at=cutoff_at ) compute_contract = compile_compute_posture_presentation( series, time_basis=time_basis, cutoff_date=cutoff_at ) contracts: list[StagePresentationContract] = [compute_contract] real_incidents = await query_bgp_incidents_tool( db, limit=1, time_basis=time_basis, cutoff_at=cutoff_at ) if real_incidents: real_inc = real_incidents[0] inc_eval = await investigate_infrastructure_incident( db, incident_key=real_inc["incident_key"], time_basis=time_basis, cutoff_at=cutoff_at, allow_drill=False, persist=persist, ) if inc_eval.get("found"): contracts.append( compile_incident_five_act_presentation( inc_eval["incident"], inc_eval["payload"], inc_eval["evidence"], time_basis=time_basis, cutoff_date=cutoff_at, ) ) if include_drill: drill_eval = await investigate_infrastructure_incident( db, incident_key=DRILL_INCIDENT_KEY, time_basis=time_basis, cutoff_at=cutoff_at, allow_drill=True, persist=persist, ) if drill_eval.get("found"): contracts.append( compile_incident_five_act_presentation( drill_eval["incident"], drill_eval["payload"], drill_eval["evidence"], time_basis=time_basis, cutoff_date=cutoff_at, ) ) if persist and hasattr(db, "execute") and hasattr(db, "add"): for contract in contracts: try: await publish_stage_contract(db, contract) except Exception as exc: logger.warning_event( "StagePresentation publish skipped", event="stage_compiler.publish.skipped", context={"error": str(exc)}, ) persisted_by_key: dict[str, StagePresentation] = {} max_db_cursor = 0 if hasattr(db, "execute"): try: rows = ( ( await db.execute( select(StagePresentation) .where(StagePresentation.time_basis == time_basis) .order_by(StagePresentation.id.asc()) ) ) .scalars() .all() ) for row in rows: is_row_drill = ( DRILL_INCIDENT_KEY in str(row.presentation_key) or bool((row.contract or {}).get("is_drill")) ) if is_row_drill and not include_drill: continue persisted_by_key[row.presentation_key] = row max_db_cursor = max(max_db_cursor, int(row.id or 0)) except Exception: pass assembled: list[dict[str, Any]] = [] synthetic_cursor = max_db_cursor for idx, contract in enumerate(contracts, start=1): stored = persisted_by_key.get(contract.presentation_key) if stored is not None and not cutoff_at: item_dict = stored.to_dict() # Overlay freshly compiled contract when non-persisted query parameters (e.g. countries) vary if contract.domain == "compute" and codes != ["CN", "US"]: item_dict["contract"] = contract.model_dump(mode="json") item_dict["title"] = contract.title item_dict["summary"] = contract.summary assembled.append(item_dict) else: synthetic_cursor = max(synthetic_cursor, idx) assembled.append(_wrap_ephemeral_contract(contract, cursor=synthetic_cursor, revision=1)) # Also append any additional published StagePresentations from proactive pipeline not in `contracts` seen_keys = {item["presentation_key"] for item in assembled} for key, stored in persisted_by_key.items(): if key not in seen_keys: assembled.append(stored.to_dict()) assembled.sort(key=lambda it: int(it.get("cursor") or 0)) latest_cursor = max((int(it.get("cursor") or 0) for it in assembled), default=0) if after_cursor > latest_cursor and latest_cursor > 0: return { "cursor": latest_cursor, "cursor_expired_full_sync": True, "items": assembled, } incremental = [it for it in assembled if int(it.get("cursor") or 0) > after_cursor] if after_cursor > 0 else assembled return { "cursor": latest_cursor, "cursor_expired_full_sync": False, "items": incremental, } def compile_spatial_domain_presentation( *, domain: SpatialDomain, snapshot: dict[str, Any], payload: dict[str, Any], evidence_map: dict[str, Any], time_basis: TimeBasis = "retrospective", cutoff_date: str | None = None, ) -> StagePresentationContract: """Compile a 3-act spatial stage presentation for `global`, `cable`, `satellite`, or `vessel`.""" filtered_ev, _ = _filter_evidence_by_time_basis( evidence_map, time_basis=time_basis, cutoff_date=cutoff_date, ) ev_keys = list(filtered_ev.keys())[:3] assertion = str(payload.get("executive_assertion") or "")[:440] or f"Planet {domain} 态势导览" facts = [str(item.get("statement") or "") for item in (payload.get("confirmed_facts") or []) if item.get("statement")] gaps = [str(g) for g in (payload.get("open_gaps") or []) if g] title_map: dict[SpatialDomain, tuple[str, str]] = { "global": ("全球全图层态势导览", "Global Multi-Domain Earth Tour"), "cable": ("全球海底光缆态势导览", "Subsea Cable Network Tour"), "satellite": ("在轨卫星星座态势导览", "Orbital Constellation Tour"), "vessel": ("全球海运 AIS 船舶导览", "Maritime AIS Vessel Tour"), } zh_title, en_title = title_map[domain] cam_hint = snapshot.get("camera_hint") if isinstance(snapshot.get("camera_hint"), dict) else None focus_lat = float(cam_hint["lat"]) if cam_hint and "lat" in cam_hint else (1.35 if domain in {"cable", "vessel"} else 24.0) focus_lon = float(cam_hint["lon"]) if cam_hint and "lon" in cam_hint else (103.8 if domain in {"cable", "vessel"} else 112.0) act2_text = (facts[0] if facts else assertion)[:440] act3_text = (gaps[0] if gaps else "各内置图层按自身遥测口径独立观测,未混合未证实的外部告警。")[:440] steps = [ StageStepSpec( step_id=f"{domain}-act1-overview", stage="overview", title="第一幕 · 全球态势全景基线", title_en="Act 1 · Global Telemetry Baseline", caption=assertion, caption_en=assertion, dwell_ms=5200, camera=StageCameraPose(lat=20.0, lon=105.0, zoom=1.0), evidence_ids=ev_keys, ), StageStepSpec( step_id=f"{domain}-act2-focus", stage="unfold", title="第二幕 · 核心空间枢纽与结构聚焦", title_en="Act 2 · Spatial Concentration Focus", caption=act2_text, caption_en=act2_text, dwell_ms=5600, camera=StageCameraPose(lat=focus_lat, lon=focus_lon, zoom=1.45), evidence_ids=ev_keys, ), StageStepSpec( step_id=f"{domain}-act3-boundary", stage="explain", title="第三幕 · 观测口径与边界校验", title_en="Act 3 · Provenance & Boundary Check", caption=act3_text, caption_en=act3_text, dwell_ms=5200, camera=StageCameraPose(lat=32.0, lon=116.0, zoom=1.1), evidence_ids=ev_keys, ), ] return StagePresentationContract( presentation_key=f"spatial-{domain}-tour", domain=domain, time_basis=time_basis, cutoff_date=cutoff_date if time_basis == "as_known_then" else None, is_drill=False, title=zh_title, title_en=en_title, summary=assertion[:240], summary_en=assertion[:240], steps=steps, evidence=filtered_ev, ) async def get_or_compile_presentation_by_key( db: AsyncSession, presentation_key: str, *, time_basis: TimeBasis = "retrospective", cutoff_at: str | None = None, include_drill: bool = False, countries: list[str] | None = None, ) -> dict[str, Any] | None: """Resolve a persisted/builtin StagePresentation by key without mutating the DB on GET.""" result = await list_or_compile_presentations( db, time_basis=time_basis, cutoff_at=cutoff_at, include_drill=include_drill, countries=countries, persist=False, ) matched = next( (it for it in result["items"] if it["presentation_key"] == presentation_key), None, ) if matched is not None: return matched norm_key = str(presentation_key or "").strip().lower() if norm_key.startswith("spatial-") and norm_key.endswith("-tour"): dom_candidate = norm_key[len("spatial-") : -len("-tour")] if dom_candidate in SPATIAL_POSTURE_DOMAINS: dom_res = await investigate_spatial_domain( db, domain=dom_candidate, # type: ignore[arg-type] selected_codes=countries, time_basis=time_basis, cutoff_at=cutoff_at, persist=False, ) contract = compile_spatial_domain_presentation( domain=dom_candidate, # type: ignore[arg-type] snapshot=dom_res["snapshot"], payload=dom_res["payload"], evidence_map=dom_res["evidence"], time_basis=time_basis, cutoff_date=cutoff_at, ) return _wrap_ephemeral_contract(contract, cursor=0, revision=1) return None