2070 lines
87 KiB
Python
2070 lines
87 KiB
Python
"""Workflow-driven dynamic workbench runtime, ViewSpec compiler, and frozen revision exporter (Gate 0–2)."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import copy
|
||
from dataclasses import dataclass, field
|
||
from datetime import UTC, datetime
|
||
import hashlib
|
||
import json
|
||
import re
|
||
import uuid
|
||
from typing import Any, Literal
|
||
|
||
from fastapi import HTTPException
|
||
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 (
|
||
InvestigationSession,
|
||
SituationalAssessment,
|
||
WorkflowRun,
|
||
)
|
||
from app.services.ai.access_policy import AccessContext, enforce_paid_research_gate
|
||
from app.services.ai.copilot_agent import run_contextual_copilot
|
||
from app.services.ai.domain_catalog import (
|
||
SPATIAL_POSTURE_DOMAINS,
|
||
SUPPORTED_WORKBENCH_DOMAINS,
|
||
WorkbenchDomain,
|
||
subject_type_to_domain,
|
||
)
|
||
from app.services.ai.entity_resolver import resolve_compute_entities, resolve_incident_entities
|
||
from app.services.ai.incident_agent import (
|
||
DRILL_INCIDENT_KEY,
|
||
IncidentFocus,
|
||
classify_incident_focus,
|
||
investigate_infrastructure_incident,
|
||
)
|
||
from app.services.ai.posture_agent import generate_or_get_compute_posture
|
||
from app.services.ai.spatial_domain_agent import (
|
||
_INCOMPLETE_SPATIAL_REPLAY_NOTICE,
|
||
compile_spatial_domain_view_spec,
|
||
investigate_spatial_domain,
|
||
)
|
||
from app.services.ai.thinking_sanitizer import merge_usage_dicts
|
||
from app.services.ai.tool_registry import TimeBasis, query_bgp_incidents_tool, query_compute_posture_tool
|
||
from app.services.ai_client import AIProviderClient
|
||
from app.services.compute_catalog import PARTICIPANTS
|
||
|
||
logger = get_logger(__name__, service="ai_workflow")
|
||
|
||
|
||
@dataclass(slots=True)
|
||
class ActiveRunHandle:
|
||
run_id: str
|
||
session_id: str | None
|
||
actor_key: str
|
||
workflow_id: str
|
||
access_tier: str
|
||
question: str
|
||
started_at: datetime
|
||
cancel_event: asyncio.Event = field(default_factory=asyncio.Event)
|
||
task: asyncio.Task[Any] | None = None
|
||
|
||
def to_dict(self) -> dict[str, Any]:
|
||
status = "cancelled" if self.cancel_event.is_set() else "running"
|
||
return {
|
||
"run_id": self.run_id,
|
||
"id": self.run_id,
|
||
"session_id": self.session_id,
|
||
"workflow_id": self.workflow_id,
|
||
"status": status,
|
||
"access_tier": self.access_tier,
|
||
"actor_key": self.actor_key,
|
||
"question": self.question,
|
||
"input_params": {},
|
||
"tool_trace": [],
|
||
"budget_used": {},
|
||
"result_subject_key": None,
|
||
"result_revision": None,
|
||
"error_message": "",
|
||
"started_at": self.started_at.isoformat(),
|
||
"completed_at": None,
|
||
}
|
||
|
||
|
||
_ACTIVE_RUNS: dict[str, ActiveRunHandle] = {}
|
||
|
||
|
||
def get_active_run_handle(run_id: str) -> ActiveRunHandle | None:
|
||
"""Return active in-flight run handle if currently executing."""
|
||
return _ACTIVE_RUNS.get(run_id)
|
||
|
||
|
||
def cancel_active_run_handle(run_id: str) -> bool:
|
||
"""Signal cancellation event and abort in-flight asyncio task if active."""
|
||
handle = _ACTIVE_RUNS.get(run_id)
|
||
if handle is None:
|
||
return False
|
||
handle.cancel_event.set()
|
||
if handle.task is not None and not handle.task.done():
|
||
handle.task.cancel()
|
||
return True
|
||
|
||
BlockType = Literal[
|
||
"comparison_matrix",
|
||
"trend_corridor",
|
||
"causal_brief",
|
||
"impact_topology",
|
||
"evidence_drawer",
|
||
"executive_onepager",
|
||
]
|
||
|
||
ViewPreset = Literal[
|
||
"default",
|
||
"comparison",
|
||
"table",
|
||
"trend",
|
||
"causal",
|
||
"topology",
|
||
"evidence",
|
||
"onepager",
|
||
]
|
||
|
||
|
||
class WorkbenchBlockSpec(BaseModel):
|
||
model_config = ConfigDict(extra="forbid")
|
||
|
||
block_id: str
|
||
block_type: BlockType
|
||
title: str
|
||
title_en: str
|
||
collapsed: bool = False
|
||
data: dict[str, Any] = Field(default_factory=dict)
|
||
|
||
|
||
class SceneSpec(BaseModel):
|
||
model_config = ConfigDict(extra="forbid")
|
||
|
||
domain: WorkbenchDomain
|
||
highlight_entities: list[str] = Field(default_factory=list)
|
||
compute_mode: str | None = None
|
||
focus_year: int | None = None
|
||
enable_national_hubs: bool = False
|
||
camera_hint: dict[str, float] | None = None
|
||
presentation_key: str | None = None
|
||
auto_play_presentation: bool = False
|
||
|
||
|
||
class ViewSpec(BaseModel):
|
||
model_config = ConfigDict(extra="forbid")
|
||
|
||
view_id: str
|
||
active_preset: ViewPreset = "default"
|
||
available_presets: list[dict[str, str]] = Field(default_factory=list)
|
||
headline: str
|
||
headline_en: str = ""
|
||
subtitle: str = ""
|
||
is_drill: bool = False
|
||
time_basis: TimeBasis = "retrospective"
|
||
cutoff_at: str | None = None
|
||
replay_supported: bool = True
|
||
replay_status: Literal["frozen", "incomplete_snapshot"] = "frozen"
|
||
replay_notice: str | None = None
|
||
blocks: list[WorkbenchBlockSpec] = Field(default_factory=list)
|
||
followups: list[str] = Field(default_factory=list)
|
||
|
||
|
||
_INCOMPLETE_COMPUTE_REPLAY_NOTICE = (
|
||
"不支持完整重放:当前历史记录缺少冻结数据快照,已禁止回查当前实时配置替代历史图表与数值,"
|
||
"仅保留原始文字结论与已绑定证据编号。"
|
||
)
|
||
_INCOMPLETE_BGP_REPLAY_NOTICE = (
|
||
"不支持完整重放:当前历史事件记录缺少冻结拓扑快照,已禁止回查当前实时事件表,"
|
||
"仅保留原始文字结论与已绑定证据编号。"
|
||
)
|
||
|
||
|
||
def _collect_payload_evidence_ids(payload: dict[str, Any] | None, row_eids: list[str] | None) -> list[str]:
|
||
collected: list[str] = []
|
||
for eid in row_eids or []:
|
||
if isinstance(eid, str) and eid and eid not in collected:
|
||
collected.append(eid)
|
||
p = payload or {}
|
||
for eid in p.get("evidence_ids") or []:
|
||
if isinstance(eid, str) and eid and eid not in collected:
|
||
collected.append(eid)
|
||
for list_key in ("causes", "breakthrough_levers", "confirmed_facts", "candidate_explanations"):
|
||
for item in p.get(list_key) or []:
|
||
if isinstance(item, dict):
|
||
for eid in item.get("evidence_ids") or []:
|
||
if isinstance(eid, str) and eid and eid not in collected:
|
||
collected.append(eid)
|
||
return collected
|
||
|
||
|
||
_COUNTRY_ALIASES: tuple[tuple[str, str], ...] = (
|
||
("中美", "CN,US"),
|
||
("中日美", "CN,US,JP"),
|
||
("中欧", "CN,EUROPE"),
|
||
("美欧", "US,EUROPE"),
|
||
("中国", "CN"),
|
||
("我国", "CN"),
|
||
("国内", "CN"),
|
||
("china", "CN"),
|
||
("美国", "US"),
|
||
("北美", "US"),
|
||
("united states", "US"),
|
||
("u.s.", "US"),
|
||
("日本", "JP"),
|
||
("japan", "JP"),
|
||
("欧洲", "EUROPE"),
|
||
("欧盟", "EUROPE"),
|
||
("europe", "EUROPE"),
|
||
("亚太", "APAC"),
|
||
("apac", "APAC"),
|
||
("德国", "DE"),
|
||
("germany", "DE"),
|
||
("英国", "GB"),
|
||
("uk", "GB"),
|
||
("韩国", "KR"),
|
||
("korea", "KR"),
|
||
("印度", "IN"),
|
||
("india", "IN"),
|
||
("法国", "FR"),
|
||
("加拿大", "CA"),
|
||
("新加坡", "SG"),
|
||
)
|
||
|
||
_METRIC_LABELS: dict[str, tuple[str, str, str]] = {
|
||
"global_share": ("全球总算力份额", "Global Compute Share", "%"),
|
||
"intelligent_share": ("全球智能算力份额", "Global Intelligent Compute Share", "%"),
|
||
"absolute": ("国家算力绝对规模", "National Compute Capacity", "EFlops"),
|
||
"frontier_cluster_share": ("公开前沿集群样本占比", "Public Frontier Cluster Share", "%"),
|
||
"chip_inflow_share": ("高端 AI 算力卡新增流向占比", "Frontier AI Chip Inflow Share", "%"),
|
||
}
|
||
|
||
_DATE_OR_YEAR_RE = re.compile(r"\b(202[0-6](?:-\d{2}-\d{2})?)\b")
|
||
_INCIDENT_KEY_RE = re.compile(r"\b((?:path_flap|route_leak|origin_hijack|origin_change|withdrawal_storm|replay-as13335)[^\s,,。??]*)", re.I)
|
||
|
||
|
||
def classify_turn_intent(
|
||
question: str,
|
||
current_ctx: dict[str, Any] | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Deterministic multi-expression intent router supporting 30+ natural analyst phrasings."""
|
||
ctx = dict(current_ctx or {})
|
||
raw = (question or "").strip()
|
||
q = raw.lower()
|
||
|
||
# 1. Domain detection with conversational context inheritance across all 6 domains
|
||
bgp_core_signals = (
|
||
"bgp", "asn", "路由", "前缀", "劫持", "泄漏", "泄露", "抖动",
|
||
"path_flap", "route_leak", "origin", "rrc", "as13335", "自治系统", "撤销", "withdraw",
|
||
)
|
||
cable_signals = (
|
||
"海缆", "光缆", "海底", "登陆站", "登陆点", "断缆", "subsea", "cable", "landing point",
|
||
)
|
||
satellite_signals = (
|
||
"卫星", "星座", "星历", "轨道", "tle", "starlink", "norad", "satellite", "orbit", "constellation",
|
||
)
|
||
vessel_signals = (
|
||
"船舶", "船只", "ais", "海运", "航运", "货轮", "油轮", "港口", "mmsi", "在航", "锚泊",
|
||
"vessel", "ship", "maritime", "tanker", "cargo",
|
||
)
|
||
global_signals = (
|
||
"全局", "全图层", "所有图层", "综合态势", "多域", "全网态势", "全球态势", "全盘",
|
||
"global overview", "all layers", "multi-domain",
|
||
)
|
||
compute_signals = (
|
||
"算力", "智算", "超算", "东数西算", "枢纽", "eflops", "rpi", "剪刀差",
|
||
"中美", "芯片", "capex", "pue", "绿电", "创新指数", "创新分差", "compute",
|
||
)
|
||
|
||
inc_match = _INCIDENT_KEY_RE.search(raw)
|
||
explicit_inc_key = inc_match.group(1) if inc_match else None
|
||
visible_layers = dict(ctx.get("visible_layers")) if isinstance(ctx.get("visible_layers"), dict) else {}
|
||
|
||
if explicit_inc_key or any(sig in q for sig in bgp_core_signals):
|
||
domain: WorkbenchDomain = "bgp"
|
||
elif any(sig in q for sig in cable_signals):
|
||
if ctx.get("domain") == "bgp" or (ctx.get("domain") != "cable" and any(k in q for k in ("这次事件", "该事件", "物理层关联"))):
|
||
domain = "bgp"
|
||
else:
|
||
domain = "cable"
|
||
elif any(sig in q for sig in satellite_signals):
|
||
domain = "satellite"
|
||
elif any(sig in q for sig in vessel_signals):
|
||
domain = "vessel"
|
||
elif any(sig in q for sig in global_signals):
|
||
domain = "global"
|
||
elif any(sig in q for sig in compute_signals):
|
||
domain = "compute"
|
||
else:
|
||
prior_dom = str(ctx.get("domain") or "").strip().lower()
|
||
domain = prior_dom if prior_dom in SUPPORTED_WORKBENCH_DOMAINS else "global" # type: ignore[assignment]
|
||
|
||
# 2. Pure view projection check (0 token, reuses existing ResultRevision)
|
||
view_preset: ViewPreset = "default"
|
||
is_pure_projection = False
|
||
|
||
if any(kw in q for kw in ("换成表格", "换成数据表", "切换表格", "用表格", "看表格", "数据表", "表格形式", "as table", "show table", "table view")):
|
||
view_preset = "table"
|
||
is_pure_projection = True
|
||
elif any(kw in q for kw in ("做成一页", "一页纸", "领导简报", "高管简报", "汇报版", "一页简报", "onepager", "one-pager", "executive brief")):
|
||
view_preset = "onepager"
|
||
is_pure_projection = True
|
||
elif any(kw in q for kw in ("换成对比图", "换成柱状图", "换成条形图", "切回对比图", "切换对比图", "柱状对比", "bar chart", "comparison chart")):
|
||
view_preset = "comparison"
|
||
is_pure_projection = True
|
||
elif any(kw in q for kw in ("换成走势图", "换成趋势图", "换成折线图", "切换走势图", "切换趋势图", "trend chart", "line chart")):
|
||
view_preset = "trend"
|
||
is_pure_projection = True
|
||
elif any(kw in q for kw in ("只看证据", "证据清单", "查看出处", "引用列表", "show sources", "evidence list")):
|
||
view_preset = "evidence"
|
||
is_pure_projection = True
|
||
|
||
# 3. Globe stage presentation trigger
|
||
auto_play = any(
|
||
kw in q
|
||
for kw in (
|
||
"在地球上演示",
|
||
"地球上演示",
|
||
"在地球演示",
|
||
"上球播报",
|
||
"播放演示",
|
||
"演示给我看",
|
||
"地球推演",
|
||
"上球演示",
|
||
"播放导览",
|
||
"四幕导览",
|
||
"五段式复盘",
|
||
"自动分镜",
|
||
"play on globe",
|
||
"stage tour",
|
||
)
|
||
)
|
||
|
||
# 4. Time basis & cutoff extraction
|
||
time_basis: TimeBasis = ctx.get("time_basis") if ctx.get("time_basis") in {"live", "as_known_then", "retrospective"} else "retrospective"
|
||
cutoff_at: str | None = ctx.get("cutoff_at")
|
||
|
||
if any(kw in q for kw in ("当时可知", "事发当时", "不看事后", "屏蔽事后", "历史回放", "as known then", "at the time")):
|
||
time_basis = "as_known_then"
|
||
m = _DATE_OR_YEAR_RE.search(raw)
|
||
if m:
|
||
cutoff_at = m.group(1)
|
||
elif any(kw in q for kw in ("回到202", "回到 202", "截至202", "截至 202", "站在202", "站在 202")):
|
||
m = _DATE_OR_YEAR_RE.search(raw)
|
||
if m:
|
||
time_basis = "as_known_then"
|
||
cutoff_at = m.group(1)
|
||
elif any(kw in q for kw in ("事后复盘", "完整复盘", "含后续报告", "全部报告", "retrospective")):
|
||
time_basis = "retrospective"
|
||
cutoff_at = None
|
||
elif any(kw in q for kw in ("切回实时", "实时观测", "最新实时", "live mode")):
|
||
time_basis = "live"
|
||
cutoff_at = None
|
||
|
||
# 5. Drill archive detection
|
||
include_drill = bool(ctx.get("include_drill")) or any(
|
||
kw in q for kw in ("演练档案", "教学样板", "as13335", "replay-as13335", "drill")
|
||
)
|
||
|
||
if domain == "bgp":
|
||
focus: IncidentFocus = classify_incident_focus(raw)
|
||
entity_id = explicit_inc_key or (
|
||
DRILL_INCIDENT_KEY
|
||
if include_drill and "13335" in q
|
||
else ctx.get("entity_id") if ctx.get("domain") in {"bgp", "cable"} else None
|
||
)
|
||
if is_pure_projection:
|
||
workflow_id = "incident.project_view"
|
||
elif auto_play:
|
||
workflow_id = "incident.present_on_globe"
|
||
elif time_basis == "as_known_then" and any(kw in q for kw in ("当时可知", "事发当时", "as known")):
|
||
workflow_id = "incident.replay_as_known"
|
||
else:
|
||
workflow_id = f"incident.{focus}"
|
||
if view_preset == "default":
|
||
view_preset = "topology" if focus in {"impact", "cable_correlation"} else "causal" if focus == "cause" else "default"
|
||
return {
|
||
"domain": domain,
|
||
"workflow_id": workflow_id,
|
||
"is_pure_projection": is_pure_projection,
|
||
"view_preset": view_preset,
|
||
"auto_play_presentation": auto_play,
|
||
"selected_codes": ctx.get("selected_codes") or ["CN", "US"],
|
||
"mode": ctx.get("mode") or "global_share",
|
||
"focus_year": ctx.get("focus_year"),
|
||
"entity_id": entity_id,
|
||
"incident_focus": focus,
|
||
"time_basis": time_basis,
|
||
"cutoff_at": cutoff_at,
|
||
"include_drill": include_drill,
|
||
"visible_layers": visible_layers,
|
||
}
|
||
|
||
if domain in SPATIAL_POSTURE_DOMAINS:
|
||
if is_pure_projection:
|
||
workflow_id = f"{domain}.project_view"
|
||
elif auto_play:
|
||
workflow_id = f"{domain}.present_on_globe"
|
||
elif domain == "global" and any(kw in q for kw in ("对比", "compare", "一览", "总览")):
|
||
workflow_id = "global.compare"
|
||
elif domain == "cable" and any(kw in q for kw in ("登陆", "枢纽", "landing")):
|
||
workflow_id = "cable.landing_hubs"
|
||
elif domain == "satellite" and any(kw in q for kw in ("轨道", "星座", "leo", "meo", "geo", "orbit")):
|
||
workflow_id = "satellite.orbit_distribution"
|
||
elif domain == "vessel" and any(kw in q for kw in ("在航", "锚泊", "船型", "流量", "traffic")):
|
||
workflow_id = "vessel.traffic_status"
|
||
else:
|
||
workflow_id = f"{domain}.overview"
|
||
if view_preset == "default" and any(kw in q for kw in ("拓扑", "分布", "结点", "节点")):
|
||
view_preset = "topology"
|
||
spatial_entity = ctx.get("entity_id") if ctx.get("domain") == domain else None
|
||
return {
|
||
"domain": domain,
|
||
"workflow_id": workflow_id,
|
||
"is_pure_projection": is_pure_projection,
|
||
"view_preset": view_preset,
|
||
"auto_play_presentation": auto_play,
|
||
"selected_codes": ctx.get("selected_codes") or ["CN", "US"],
|
||
"mode": ctx.get("mode") or "global_share",
|
||
"focus_year": ctx.get("focus_year"),
|
||
"entity_id": spatial_entity,
|
||
"incident_focus": "overview",
|
||
"time_basis": time_basis,
|
||
"cutoff_at": cutoff_at,
|
||
"include_drill": include_drill,
|
||
"visible_layers": visible_layers,
|
||
}
|
||
|
||
# 6. Compute participant codes extraction (inheriting session codes if pronouns or omitted)
|
||
extracted_codes: list[str] = []
|
||
for phrase, mapped in _COUNTRY_ALIASES:
|
||
if phrase in q:
|
||
for c in mapped.split(","):
|
||
if c in PARTICIPANTS and c not in extracted_codes:
|
||
extracted_codes.append(c)
|
||
selected_codes = extracted_codes if extracted_codes else list(ctx.get("selected_codes") or ["CN", "US"])
|
||
if len(selected_codes) == 1 and selected_codes[0] == "CN" and any(kw in q for kw in ("对比", "差距", "剪刀差", "vs", "平价", "份额")):
|
||
selected_codes = ["CN", "US"]
|
||
|
||
# 7. Compute metric mode resolution
|
||
prev_mode = str(ctx.get("mode") or "global_share")
|
||
mode = prev_mode
|
||
metric_switched = False
|
||
if any(kw in q for kw in ("智算", "智能算力", "ai算力", "ai compute", "intelligent")):
|
||
mode = "intelligent_share"
|
||
metric_switched = mode != prev_mode
|
||
elif any(kw in q for kw in ("绝对规模", "绝对算力", "总规模", "eflops", "absolute")):
|
||
mode = "absolute"
|
||
metric_switched = mode != prev_mode
|
||
elif any(kw in q for kw in ("前沿集群", "集群样本", "万卡", "超算样本", "frontier cluster")):
|
||
mode = "frontier_cluster_share"
|
||
metric_switched = mode != prev_mode
|
||
elif any(kw in q for kw in ("芯片流向", "高端芯片", "加速卡流向", "h100", "芯片进口", "chip inflow")):
|
||
mode = "chip_inflow_share"
|
||
metric_switched = mode != prev_mode
|
||
elif any(kw in q for kw in ("总算力份额", "全球总份额", "双边rpi", "global share")):
|
||
mode = "global_share"
|
||
metric_switched = mode != prev_mode
|
||
|
||
# 8. Compute workflow & default preset selection
|
||
if is_pure_projection:
|
||
workflow_id = "compute.project_view"
|
||
elif auto_play:
|
||
workflow_id = "compute.present_on_globe"
|
||
elif any(kw in q for kw in ("趋势", "走势", "历年", "演变", "走廊", "2020", "trend", "trajectory")):
|
||
workflow_id = "compute.compare"
|
||
view_preset = "trend"
|
||
elif any(kw in q for kw in ("为什么", "成因", "归因", "稀释", "回落", "剪刀差", "创新", "东数西算", "枢纽", "解释", "why", "explain")):
|
||
workflow_id = "compute.explain_gap"
|
||
view_preset = "causal"
|
||
elif metric_switched or any(kw in q for kw in ("只看", "切换", "改看", "switch")):
|
||
workflow_id = "compute.switch_metric"
|
||
view_preset = "comparison"
|
||
else:
|
||
workflow_id = "compute.compare"
|
||
view_preset = "default"
|
||
|
||
return {
|
||
"domain": "compute",
|
||
"workflow_id": workflow_id,
|
||
"is_pure_projection": is_pure_projection,
|
||
"view_preset": view_preset,
|
||
"auto_play_presentation": auto_play,
|
||
"selected_codes": selected_codes[:8],
|
||
"mode": mode,
|
||
"focus_year": ctx.get("focus_year"),
|
||
"entity_id": "CN" if "枢纽" in q or "东数西算" in q else (selected_codes[0] if selected_codes else "CN"),
|
||
"incident_focus": "overview",
|
||
"time_basis": time_basis,
|
||
"cutoff_at": cutoff_at,
|
||
"include_drill": include_drill,
|
||
"visible_layers": visible_layers,
|
||
}
|
||
|
||
|
||
def _compute_available_presets() -> list[dict[str, str]]:
|
||
return [
|
||
{"id": "default", "label": "综合工作台", "label_en": "Workbench"},
|
||
{"id": "comparison", "label": "对照图", "label_en": "Chart"},
|
||
{"id": "table", "label": "数据表", "label_en": "Table"},
|
||
{"id": "trend", "label": "趋势走廊", "label_en": "Trend"},
|
||
{"id": "causal", "label": "归因拆解", "label_en": "Attribution"},
|
||
{"id": "onepager", "label": "一页简报", "label_en": "One-Pager"},
|
||
]
|
||
|
||
|
||
def _incident_available_presets() -> list[dict[str, str]]:
|
||
return [
|
||
{"id": "default", "label": "取证工作台", "label_en": "Forensics"},
|
||
{"id": "topology", "label": "波及与拓扑", "label_en": "Topology"},
|
||
{"id": "causal", "label": "成因与反证", "label_en": "Causes"},
|
||
{"id": "evidence", "label": "证据链", "label_en": "Evidence"},
|
||
{"id": "onepager", "label": "一页复盘", "label_en": "One-Pager"},
|
||
]
|
||
|
||
|
||
def compile_compute_view_spec(
|
||
*,
|
||
codes: list[str],
|
||
mode: str,
|
||
series: dict[str, Any],
|
||
posture: dict[str, Any],
|
||
preset: ViewPreset = "default",
|
||
enable_hubs: bool = False,
|
||
auto_play: bool = False,
|
||
replay_supported: bool = True,
|
||
replay_notice: str | None = None,
|
||
) -> tuple[ViewSpec, SceneSpec]:
|
||
"""Compile stateless 6-block `ViewSpec` & `SceneSpec` from verified compute `series` + `posture`."""
|
||
brief = posture.get("payload") or {}
|
||
evidence_map = series.get("evidence") or {}
|
||
time_basis: TimeBasis = series.get("time_basis") or "retrospective"
|
||
cutoff_at = series.get("cutoff_at")
|
||
metric_zh, metric_en, default_unit = _METRIC_LABELS.get(mode, ("算力指标", "Compute Metric", "%"))
|
||
unit = str(series.get("unit") or default_unit)
|
||
effective_replay_notice = replay_notice or (_INCOMPLETE_COMPUTE_REPLAY_NOTICE if not replay_supported else None)
|
||
|
||
years: list[int] = [int(y) for y in (series.get("years") or [])]
|
||
compute_rows: list[dict[str, Any]] = list(series.get("compute") or [])
|
||
observed_rows = [
|
||
r for r in compute_rows
|
||
if any(r.get("values", {}).get(c) is not None for c in codes)
|
||
]
|
||
latest_year = int(observed_rows[-1]["year"]) if observed_rows else (years[-1] if years else None)
|
||
|
||
matrix_rows: list[dict[str, Any]] = []
|
||
max_numeric = 0.0
|
||
for code in codes:
|
||
meta = PARTICIPANTS.get(code, {})
|
||
latest_val: float | None = None
|
||
latest_pt_year = latest_year
|
||
latest_eid: str | None = None
|
||
for r_item in reversed(compute_rows):
|
||
val = (r_item.get("values") or {}).get(code)
|
||
if val is not None:
|
||
latest_val = float(val)
|
||
latest_pt_year = int(r_item.get("year") or latest_year or 0) or latest_year
|
||
latest_eid = r_item.get("evidence_id")
|
||
break
|
||
if latest_val is not None:
|
||
max_numeric = max(max_numeric, latest_val)
|
||
missing_formatted = "不支持完整重放(快照缺失)" if not replay_supported else "暂无同口径公开发布值"
|
||
missing_reason_text = (
|
||
(effective_replay_notice or _INCOMPLETE_COMPUTE_REPLAY_NOTICE)
|
||
if not replay_supported
|
||
else "权威白皮书未单列同年同口径数据(严格留白,不以局部样本外推)"
|
||
)
|
||
matrix_rows.append(
|
||
{
|
||
"code": code,
|
||
"label": str(meta.get("name") or meta.get("name_zh") or code),
|
||
"label_en": str(meta.get("name_en") or code),
|
||
"year": latest_pt_year,
|
||
"value": latest_val,
|
||
"unit": unit,
|
||
"formatted": f"{latest_val:g} {unit}".strip() if latest_val is not None else missing_formatted,
|
||
"is_missing": latest_val is None,
|
||
"missing_reason": missing_reason_text if latest_val is None else "",
|
||
"evidence_id": latest_eid if latest_eid in evidence_map else next(iter(evidence_map.keys()), None),
|
||
}
|
||
)
|
||
|
||
for r in matrix_rows:
|
||
if r["value"] is not None and max_numeric > 0:
|
||
r["bar_pct"] = round(min(100.0, (float(r["value"]) / max_numeric) * 100.0), 1)
|
||
else:
|
||
r["bar_pct"] = 0.0
|
||
|
||
rpi = series.get("bilateral_rpi") or {}
|
||
latest_tot = rpi.get("latest_total") or {}
|
||
latest_intel = rpi.get("latest_intelligent") or {}
|
||
rpi_val = (
|
||
latest_intel.get("rpi_percent")
|
||
if mode == "intelligent_share" and latest_intel
|
||
else latest_tot.get("rpi_percent")
|
||
)
|
||
|
||
# Trend corridor with explicit missing-year gap markers (never interpolated!)
|
||
row_by_year = {int(r["year"]): r for r in compute_rows if r.get("year") is not None}
|
||
all_span_years = years
|
||
gap_years = [
|
||
y for y in all_span_years
|
||
if all((row_by_year.get(y, {}).get("values") or {}).get(c) is None for c in codes)
|
||
]
|
||
corridor_series: list[dict[str, Any]] = []
|
||
for code in codes:
|
||
meta = PARTICIPANTS.get(code, {})
|
||
corridor_pts = []
|
||
for y in all_span_years:
|
||
v = (row_by_year.get(y, {}).get("values") or {}).get(code)
|
||
corridor_pts.append(
|
||
{
|
||
"year": y,
|
||
"value": float(v) if v is not None else None,
|
||
"is_gap": v is None,
|
||
}
|
||
)
|
||
corridor_series.append(
|
||
{
|
||
"code": code,
|
||
"label": str(meta.get("name") or meta.get("name_zh") or code),
|
||
"label_en": str(meta.get("name_en") or code),
|
||
"points": corridor_pts,
|
||
}
|
||
)
|
||
|
||
# Causal brief separating mathematical denominator decomposition vs causal candidates vs levers vs blind spots
|
||
attr_cn = (series.get("denominator_attribution") or {}).get("CN")
|
||
math_decomp: list[dict[str, Any]] = []
|
||
if attr_cn and attr_cn.get("global_to"):
|
||
math_decomp.append(
|
||
{
|
||
"formula_label": "份额变化数学分解(分子增速 vs 全球分母增速)",
|
||
"detail": (
|
||
f"中国绝对总算力:{attr_cn['country_from']:.0f} → {attr_cn['country_to']:.0f} EFlops(+{attr_cn['country_growth_pct']}%);"
|
||
f"全球总算力分母:{attr_cn['global_from']:.0f} → {attr_cn['global_to']:.0f} EFlops(+{attr_cn['global_growth_pct']}%)。"
|
||
"当全球分母扩张速度高于本国分子增速时,本国绝对算力翻倍增长与全球相对份额回落同时成立。"
|
||
),
|
||
"evidence_ids": [eid for eid in (attr_cn.get("evidence_ids") or []) if eid in evidence_map],
|
||
}
|
||
)
|
||
|
||
causal_candidates = [
|
||
{
|
||
"label": c.get("label"),
|
||
"detail": c.get("detail"),
|
||
"evidence_ids": [eid for eid in (c.get("evidence_ids") or []) if eid in evidence_map],
|
||
}
|
||
for c in (brief.get("causes") or [])
|
||
]
|
||
levers = [
|
||
{
|
||
"label": lv.get("label"),
|
||
"detail": lv.get("detail"),
|
||
"evidence_ids": [eid for eid in (lv.get("evidence_ids") or []) if eid in evidence_map],
|
||
}
|
||
for lv in (brief.get("breakthrough_levers") or [])
|
||
]
|
||
blind_spots = list(brief.get("blind_spots") or series.get("limitations") or [])[:4]
|
||
|
||
evidence_items = []
|
||
for eid, ev in evidence_map.items():
|
||
ev_hash = hashlib.sha256(json.dumps(ev, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()[:12]
|
||
evidence_items.append(
|
||
{
|
||
"evidence_id": eid,
|
||
"title": str(ev.get("title") or eid),
|
||
"publisher": str(ev.get("publisher") or ""),
|
||
"published_at": str(ev.get("published_at") or ev.get("report_year") or ""),
|
||
"locator": str(ev.get("locator") or ""),
|
||
"url": str(ev.get("url") or ""),
|
||
"sha256_prefix": ev_hash,
|
||
}
|
||
)
|
||
|
||
rev_num = int(posture.get("revision") or 1)
|
||
boundary_notes = list(blind_spots[:3])
|
||
if not replay_supported and effective_replay_notice:
|
||
boundary_notes = [effective_replay_notice, *[n for n in boundary_notes if n != effective_replay_notice]][:3]
|
||
onepager_data = {
|
||
"headline": str(brief.get("headline") or f"{metric_zh}研判简报"),
|
||
"scope_line": f"范围:{', '.join(codes)} · 口径:{metric_zh} · 时间语义:{time_basis}" + (f"(截点 {cutoff_at})" if cutoff_at else ""),
|
||
"revision_tag": f"Rev.{rev_num}",
|
||
"executive_assertion": str(brief.get("executive_assertion") or ""),
|
||
"key_metrics": [
|
||
f"{r['label']}:{r['formatted']}" if r["is_missing"] else f"{r['label']}({r['year'] or '—'}):{r['formatted']}"
|
||
for r in matrix_rows
|
||
],
|
||
"core_takeaways": [c["detail"] for c in causal_candidates[:2]] + [lv["detail"] for lv in levers[:2]],
|
||
"boundary_notes": boundary_notes,
|
||
"replay_supported": replay_supported,
|
||
}
|
||
|
||
blocks: list[WorkbenchBlockSpec] = []
|
||
if preset == "onepager":
|
||
blocks.append(
|
||
WorkbenchBlockSpec(
|
||
block_id="blk-onepager",
|
||
block_type="executive_onepager",
|
||
title="一页决策简报",
|
||
title_en="Executive One-Pager",
|
||
data=onepager_data,
|
||
)
|
||
)
|
||
blocks.append(
|
||
WorkbenchBlockSpec(
|
||
block_id="blk-evidence",
|
||
block_type="evidence_drawer",
|
||
title=f"核验出处({len(evidence_items)})",
|
||
title_en=f"Verified Sources ({len(evidence_items)})",
|
||
collapsed=True,
|
||
data={"items": evidence_items, "withheld_source_ids": series.get("withheld_source_ids") or []},
|
||
)
|
||
)
|
||
else:
|
||
display_mode = "table" if preset == "table" else "bars"
|
||
if preset in {"default", "comparison", "table"}:
|
||
blocks.append(
|
||
WorkbenchBlockSpec(
|
||
block_id="blk-matrix",
|
||
block_type="comparison_matrix",
|
||
title=f"{metric_zh}对照" + (f"({latest_year})" if latest_year else ("(不支持完整重放)" if not replay_supported else "")),
|
||
title_en=f"{metric_en} Matrix",
|
||
data={
|
||
"display_mode": display_mode,
|
||
"metric": mode,
|
||
"metric_label": metric_zh,
|
||
"unit": unit,
|
||
"year": latest_year,
|
||
"rpi_percent": rpi_val if "CN" in codes and "US" in codes else None,
|
||
"rows": matrix_rows,
|
||
"replay_supported": replay_supported,
|
||
},
|
||
)
|
||
)
|
||
if preset in {"default", "trend"} and (all_span_years or (not replay_supported and preset == "trend")):
|
||
trend_title = (
|
||
f"{min(all_span_years)}–{max(all_span_years)} 演进走廊"
|
||
if all_span_years
|
||
else "历史走势快照缺失(不支持完整重放)"
|
||
)
|
||
blocks.append(
|
||
WorkbenchBlockSpec(
|
||
block_id="blk-trend",
|
||
block_type="trend_corridor",
|
||
title=trend_title,
|
||
title_en="Multi-Year Trajectory Corridor" if all_span_years else "Trajectory Snapshot Missing",
|
||
collapsed=(preset == "default" and len(codes) > 3),
|
||
data={
|
||
"metric": mode,
|
||
"metric_label": metric_zh,
|
||
"unit": unit,
|
||
"years": all_span_years,
|
||
"gap_years": gap_years,
|
||
"series": corridor_series if all_span_years else [],
|
||
"innovation_summary": series.get("innovation_summary"),
|
||
"replay_supported": replay_supported,
|
||
"replay_notice": effective_replay_notice,
|
||
},
|
||
)
|
||
)
|
||
if preset in {"default", "causal"}:
|
||
blocks.append(
|
||
WorkbenchBlockSpec(
|
||
block_id="blk-causal",
|
||
block_type="causal_brief",
|
||
title="分母分解与态势归因",
|
||
title_en="Denominator & Causal Attribution",
|
||
data={
|
||
"executive_assertion": str(brief.get("executive_assertion") or ""),
|
||
"math_decomposition": math_decomp,
|
||
"causal_candidates": causal_candidates,
|
||
"counter_evidence_and_levers": levers,
|
||
"unknown_gaps": blind_spots,
|
||
},
|
||
)
|
||
)
|
||
if enable_hubs and series.get("national_hubs"):
|
||
hubs = series.get("national_hubs") or []
|
||
blocks.append(
|
||
WorkbenchBlockSpec(
|
||
block_id="blk-hubs-topology",
|
||
block_type="impact_topology",
|
||
title="“东数西算”八大国家算力枢纽拓扑",
|
||
title_en="8 National Compute Hubs Topology",
|
||
data={
|
||
"topology_kind": "compute_hubs",
|
||
"network_layer_notice": "四大东部低时延推理需求枢纽 ⇄ 四大西部清洁绿电训练底座",
|
||
"hubs": [
|
||
{
|
||
"id": h.get("id"),
|
||
"name": h.get("name") or h.get("name_zh"),
|
||
"role": "东部需求枢纽" if "east" in str(h.get("role")) else "西部绿电枢纽",
|
||
"target_pue": h.get("target_pue"),
|
||
}
|
||
for h in hubs[:8]
|
||
],
|
||
},
|
||
)
|
||
)
|
||
blocks.append(
|
||
WorkbenchBlockSpec(
|
||
block_id="blk-evidence",
|
||
block_type="evidence_drawer",
|
||
title=f"权威证据源({len(evidence_items)})",
|
||
title_en=f"Verified Evidence ({len(evidence_items)})",
|
||
collapsed=(preset != "evidence"),
|
||
data={"items": evidence_items, "withheld_source_ids": series.get("withheld_source_ids") or []},
|
||
)
|
||
)
|
||
|
||
verify_view_spec_consistency(blocks, evidence_map, matrix_rows=matrix_rows)
|
||
|
||
followups = [
|
||
"只看智能算力份额对照" if mode != "intelligent_share" else "切回全球总算力份额对照",
|
||
"为什么中国绝对算力翻倍增长,全球份额却回落?",
|
||
"换成数据表视图" if preset != "table" else "做成一页决策简报",
|
||
"在三维地球上演绎四幕算力导览",
|
||
]
|
||
|
||
entities, _ = resolve_compute_entities(codes, series, include_hubs=enable_hubs)
|
||
highlight_ids = [e.entity_id for e in entities if e.entity_type in ("country", "national_hub")][:10]
|
||
|
||
view_spec = ViewSpec(
|
||
view_id=f"view-{posture.get('subject_key', 'compute')}-v{rev_num}-{preset}",
|
||
active_preset=preset,
|
||
available_presets=_compute_available_presets(),
|
||
headline=str(brief.get("headline") or f"{metric_zh}工作台"),
|
||
headline_en=str(brief.get("headline_en") or f"{metric_en} Workbench"),
|
||
subtitle=f"{', '.join(codes)} · {metric_zh} · Rev.{rev_num}" + (" · 不支持完整重放" if not replay_supported else ""),
|
||
is_drill=False,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
replay_supported=replay_supported,
|
||
replay_status="frozen" if replay_supported else "incomplete_snapshot",
|
||
replay_notice=effective_replay_notice,
|
||
blocks=blocks,
|
||
followups=followups[:3],
|
||
)
|
||
scene_spec = SceneSpec(
|
||
domain="compute",
|
||
highlight_entities=highlight_ids,
|
||
compute_mode=mode,
|
||
focus_year=latest_year,
|
||
enable_national_hubs=enable_hubs,
|
||
presentation_key="compute-posture-cn-us",
|
||
auto_play_presentation=auto_play,
|
||
)
|
||
return view_spec, scene_spec
|
||
|
||
|
||
def compile_incident_view_spec(
|
||
*,
|
||
incident_res: dict[str, Any],
|
||
preset: ViewPreset = "default",
|
||
auto_play: bool = False,
|
||
) -> tuple[ViewSpec, SceneSpec]:
|
||
"""Compile stateless 6-block `ViewSpec` & `SceneSpec` for real or explicit-drill BGP incidents."""
|
||
payload = incident_res["payload"]
|
||
incident = incident_res.get("incident") or {}
|
||
evidence_map = incident_res.get("evidence") or {}
|
||
is_drill = bool(incident_res.get("is_drill") or payload.get("is_drill"))
|
||
time_basis: TimeBasis = incident_res.get("time_basis") or "retrospective"
|
||
cutoff_at = incident_res.get("cutoff_at")
|
||
rev_num = int(incident_res.get("revision") or 0)
|
||
focus = str(incident_res.get("analysis_focus") or payload.get("analysis_focus") or "overview")
|
||
replay_supported = bool(incident_res.get("replay_supported", True))
|
||
replay_notice = incident_res.get("replay_notice") or (
|
||
_INCOMPLETE_BGP_REPLAY_NOTICE if not replay_supported else None
|
||
)
|
||
|
||
entities, relations = (
|
||
resolve_incident_entities(incident)
|
||
if incident and replay_supported
|
||
else ([], [])
|
||
)
|
||
cable_clues = [rel.note for rel in relations if rel.relation_type == "geographic_proximity_cable"]
|
||
|
||
evidence_items = []
|
||
for eid, ev in evidence_map.items():
|
||
ev_hash = hashlib.sha256(json.dumps(ev, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()[:12]
|
||
evidence_items.append(
|
||
{
|
||
"evidence_id": eid,
|
||
"title": str(ev.get("title") or eid),
|
||
"publisher": str(ev.get("publisher") or ""),
|
||
"published_at": str(ev.get("published_at") or ""),
|
||
"locator": str(ev.get("locator") or ""),
|
||
"url": str(ev.get("url") or ""),
|
||
"sha256_prefix": ev_hash,
|
||
}
|
||
)
|
||
|
||
topology_data = {
|
||
"topology_kind": "bgp_incident",
|
||
"network_layer_notice": "高空弧线仅代表控制面逻辑 AS 路由传播关系,不等同于海底物理光缆走向或断缆。",
|
||
"incident_key": payload["incident_key"],
|
||
"incident_type": str(incident.get("incident_type") or "none"),
|
||
"severity": str(incident.get("severity") or "info"),
|
||
"status": str(incident.get("status") or "no_active_incident"),
|
||
"measured_asns": [f"AS{a}" for a in (incident.get("affected_asns") or [])],
|
||
"affected_prefixes": [str(p) for p in (incident.get("affected_prefixes") or [])],
|
||
"collector_vantage_points": [str(c) for c in (incident.get("affected_collectors") or [])],
|
||
"candidate_proximity_cables": cable_clues,
|
||
"physical_cable_state": (
|
||
"candidate_proximity_unconfirmed"
|
||
if cable_clues
|
||
else "unknown_no_independent_fault_telemetry"
|
||
),
|
||
"timeline": [
|
||
{"label": "异常初发捕获", "timestamp": str(incident.get("started_at") or "—"), "state": "detected"},
|
||
{
|
||
"label": "收敛恢复确认",
|
||
"timestamp": str(incident.get("ended_at") or ("已按当时可知截点隔离" if incident.get("withheld_post_cutoff_recovery") else "待确认 / 持续监测")),
|
||
"state": "resolved" if incident.get("ended_at") else "pending",
|
||
},
|
||
] if incident else [],
|
||
}
|
||
|
||
causal_data = {
|
||
"executive_assertion": (payload.get("confirmed_facts") or [{}])[0].get("statement", ""),
|
||
"math_decomposition": [],
|
||
"causal_candidates": [
|
||
{
|
||
"label": f"已核验事实 #{idx + 1}",
|
||
"detail": item["statement"],
|
||
"evidence_ids": [eid for eid in item["evidence_ids"] if eid in evidence_map],
|
||
}
|
||
for idx, item in enumerate(payload.get("confirmed_facts") or [])
|
||
]
|
||
+ [
|
||
{
|
||
"label": f"候选成因研判 #{idx + 1}",
|
||
"detail": item["statement"],
|
||
"evidence_ids": [eid for eid in item["evidence_ids"] if eid in evidence_map],
|
||
}
|
||
for idx, item in enumerate(payload.get("candidate_explanations") or [])
|
||
],
|
||
"counter_evidence_and_levers": [
|
||
{"label": "反证与边界校验", "detail": ce, "evidence_ids": list(evidence_map.keys())[:1]}
|
||
for ce in (payload.get("counter_evidence") or [])
|
||
],
|
||
"unknown_gaps": list(payload.get("open_gaps") or []),
|
||
}
|
||
|
||
inc_boundary_notes = list(payload.get("open_gaps") or [])
|
||
if not replay_supported and replay_notice:
|
||
inc_boundary_notes = [replay_notice, *[n for n in inc_boundary_notes if n != replay_notice]]
|
||
onepager_data = {
|
||
"headline": payload["title"],
|
||
"scope_line": f"对象:{payload['incident_key']} · 聚焦:{focus} · 时间语义:{time_basis}",
|
||
"revision_tag": f"Rev.{rev_num}" if rev_num > 0 else "Live Empty",
|
||
"executive_assertion": payload.get("cable_correlation_policy", ""),
|
||
"key_metrics": (
|
||
[
|
||
"状态:不支持完整重放(历史事件快照缺失)",
|
||
]
|
||
if not replay_supported
|
||
else [
|
||
f"涉事自治系统:{', '.join(topology_data['measured_asns']) or '无'}",
|
||
f"涉事路由前缀:{', '.join(topology_data['affected_prefixes']) or '无'}",
|
||
f"当前状态:{topology_data['status']}",
|
||
]
|
||
),
|
||
"core_takeaways": [item["statement"] for item in (payload.get("confirmed_facts") or [])]
|
||
+ [item["statement"] for item in (payload.get("candidate_explanations") or [])[:2]],
|
||
"boundary_notes": inc_boundary_notes,
|
||
"replay_supported": replay_supported,
|
||
}
|
||
|
||
blocks: list[WorkbenchBlockSpec] = []
|
||
if preset == "onepager":
|
||
blocks.append(
|
||
WorkbenchBlockSpec(
|
||
block_id="blk-inc-onepager",
|
||
block_type="executive_onepager",
|
||
title="基础设施取证一页复盘",
|
||
title_en="Incident Forensics One-Pager",
|
||
data=onepager_data,
|
||
)
|
||
)
|
||
else:
|
||
if preset in {"default", "topology"} and incident and replay_supported:
|
||
blocks.append(
|
||
WorkbenchBlockSpec(
|
||
block_id="blk-inc-topology",
|
||
block_type="impact_topology",
|
||
title="控制面波及范围与海缆物理边界",
|
||
title_en="Control-Plane Scope & Subsea Cable Boundary",
|
||
data=topology_data,
|
||
)
|
||
)
|
||
if preset in {"default", "causal", "topology"}:
|
||
blocks.append(
|
||
WorkbenchBlockSpec(
|
||
block_id="blk-inc-causal",
|
||
block_type="causal_brief",
|
||
title=f"取证结论与待查缺口(维度:{focus})",
|
||
title_en=f"Forensic Findings & Open Gaps ({focus})",
|
||
data=causal_data,
|
||
)
|
||
)
|
||
blocks.append(
|
||
WorkbenchBlockSpec(
|
||
block_id="blk-inc-evidence",
|
||
block_type="evidence_drawer",
|
||
title=f"取证报文与外部证据({len(evidence_items)})",
|
||
title_en=f"Forensic Evidence ({len(evidence_items)})",
|
||
collapsed=(preset not in {"evidence"}),
|
||
data={"items": evidence_items, "withheld_source_ids": incident.get("withheld_evidence_ids") or []},
|
||
)
|
||
)
|
||
|
||
verify_view_spec_consistency(blocks, evidence_map)
|
||
|
||
followups = [
|
||
"这次路由异动具体影响谁、波及哪些前缀和观测站?",
|
||
"这次事件和附近海底光缆有关吗?物理层状态是什么?",
|
||
"按“当时可知”模式重放,隔离事后复盘报告会怎样?",
|
||
"做成一页复盘简报",
|
||
]
|
||
pres_key = f"incident-{payload['incident_key']}" if incident_res.get("found") else None
|
||
highlight_ids = [e.entity_id for e in entities[:6]]
|
||
|
||
view_spec = ViewSpec(
|
||
view_id=f"view-{payload['incident_key']}-v{rev_num}-{preset}",
|
||
active_preset=preset,
|
||
available_presets=_incident_available_presets(),
|
||
headline=payload["title"],
|
||
headline_en=payload["title"],
|
||
subtitle=f"{'[演练档案] · ' if is_drill else ''}{payload['incident_key']} · 维度:{focus}" + (f" · Rev.{rev_num}" if rev_num else "") + (" · 不支持完整重放" if not replay_supported else ""),
|
||
is_drill=is_drill,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
replay_supported=replay_supported,
|
||
replay_status="frozen" if replay_supported else "incomplete_snapshot",
|
||
replay_notice=replay_notice,
|
||
blocks=blocks,
|
||
followups=followups[:3],
|
||
)
|
||
scene_spec = SceneSpec(
|
||
domain="bgp",
|
||
highlight_entities=highlight_ids,
|
||
presentation_key=pres_key,
|
||
auto_play_presentation=bool(auto_play and pres_key),
|
||
)
|
||
return view_spec, scene_spec
|
||
|
||
|
||
def verify_view_spec_consistency(
|
||
blocks: list[WorkbenchBlockSpec],
|
||
evidence_map: dict[str, Any],
|
||
*,
|
||
matrix_rows: list[dict[str, Any]] | None = None,
|
||
) -> None:
|
||
"""Assert numerical and citation consistency across all compiled ViewSpec blocks."""
|
||
for blk in blocks:
|
||
assert blk.block_type in {
|
||
"comparison_matrix",
|
||
"trend_corridor",
|
||
"causal_brief",
|
||
"impact_topology",
|
||
"evidence_drawer",
|
||
"executive_onepager",
|
||
}
|
||
if blk.block_type == "comparison_matrix" and matrix_rows is not None:
|
||
rendered_rows = blk.data.get("rows") or []
|
||
if len(rendered_rows) != len(matrix_rows):
|
||
raise ValueError("ViewSpec comparison_matrix row count diverged from source series")
|
||
for r1, r2 in zip(rendered_rows, matrix_rows, strict=True):
|
||
if r1.get("value") != r2.get("value"):
|
||
raise ValueError(f"ViewSpec numerical mismatch for {r1.get('code')}")
|
||
if blk.block_type == "causal_brief":
|
||
for group_key in ("math_decomposition", "causal_candidates", "counter_evidence_and_levers"):
|
||
for item in blk.data.get(group_key) or []:
|
||
for eid in item.get("evidence_ids") or []:
|
||
if eid not in evidence_map:
|
||
raise ValueError(f"ViewSpec causal_brief cited unknown evidence_id: {eid}")
|
||
|
||
|
||
async def _finalize_workflow_run_db(
|
||
db: AsyncSession,
|
||
*,
|
||
run_id: str,
|
||
session_id_val: str | None,
|
||
status_value: Literal["completed", "cancelled", "failed"],
|
||
domain: str,
|
||
tool_trace: list[str],
|
||
budget_used: dict[str, Any],
|
||
result_subject_key: str | None = None,
|
||
result_revision: int | None = None,
|
||
next_context: dict[str, Any] | None = None,
|
||
fallback_run: WorkflowRun | None = None,
|
||
error_message: str = "",
|
||
) -> str:
|
||
"""Persist terminal `WorkflowRun` and session state without clobbering prior cancellation."""
|
||
final_status = status_value
|
||
now = datetime.now(UTC)
|
||
|
||
if hasattr(db, "execute"):
|
||
try:
|
||
db_run = (
|
||
await db.execute(select(WorkflowRun).where(WorkflowRun.id == run_id))
|
||
).scalar_one_or_none()
|
||
if db_run is not None:
|
||
if db_run.status == "cancelled":
|
||
final_status = "cancelled"
|
||
else:
|
||
db_run.status = status_value
|
||
db_run.tool_trace = list(tool_trace)
|
||
db_run.budget_used = dict(budget_used)
|
||
db_run.completed_at = db_run.completed_at or now
|
||
if final_status == "completed":
|
||
db_run.result_subject_key = result_subject_key
|
||
db_run.result_revision = result_revision
|
||
if error_message:
|
||
db_run.error_message = error_message[:500]
|
||
elif fallback_run is not None and hasattr(db, "add"):
|
||
fallback_run.status = status_value
|
||
fallback_run.tool_trace = list(tool_trace)
|
||
fallback_run.budget_used = dict(budget_used)
|
||
fallback_run.completed_at = now
|
||
fallback_run.result_subject_key = result_subject_key if final_status == "completed" else None
|
||
fallback_run.result_revision = result_revision if final_status == "completed" else None
|
||
fallback_run.error_message = error_message[:500]
|
||
db.add(fallback_run)
|
||
|
||
if session_id_val and session_id_val != "stateless":
|
||
db_session = (
|
||
await db.execute(
|
||
select(InvestigationSession).where(InvestigationSession.id == session_id_val)
|
||
)
|
||
).scalar_one_or_none()
|
||
if db_session is not None:
|
||
if final_status == "completed" and next_context is not None:
|
||
db_session.domain = domain
|
||
db_session.context_state = {**next_context, "active_run_id": None}
|
||
else:
|
||
curr_ctx = dict(db_session.context_state or {})
|
||
if curr_ctx.get("active_run_id") == run_id:
|
||
curr_ctx["active_run_id"] = None
|
||
db_session.context_state = curr_ctx
|
||
|
||
if hasattr(db, "flush"):
|
||
await db.flush()
|
||
if hasattr(db, "commit"):
|
||
await db.commit()
|
||
except Exception as exc:
|
||
logger.warning_event(
|
||
"Session/WorkflowRun finalize skipped on mock session",
|
||
event="ai_workflow.finalize.skipped",
|
||
context={"run_id": run_id, "status": final_status, "error": str(exc)},
|
||
)
|
||
return final_status
|
||
|
||
|
||
_ANALYTICAL_AUTO_LLM_WORKFLOWS = frozenset(
|
||
{
|
||
"compute.compare",
|
||
"compute.explain_gap",
|
||
"incident.overview",
|
||
"incident.impact",
|
||
"incident.cause",
|
||
"incident.cable_correlation",
|
||
"incident.recovery",
|
||
"incident.replay_as_known",
|
||
"global.overview",
|
||
"global.compare",
|
||
"cable.overview",
|
||
"cable.landing_hubs",
|
||
"satellite.overview",
|
||
"satellite.orbit_distribution",
|
||
"vessel.overview",
|
||
"vessel.traffic_status",
|
||
}
|
||
)
|
||
|
||
|
||
async def execute_session_turn(
|
||
db: AsyncSession,
|
||
*,
|
||
session: InvestigationSession | None,
|
||
question: str,
|
||
context_override: dict[str, Any] | None = None,
|
||
explicit_preset: ViewPreset | None = None,
|
||
prefer_llm: bool | Literal["auto"] = False,
|
||
external_urls: list[str] | None = None,
|
||
access: AccessContext,
|
||
ai_client: AIProviderClient | None = None,
|
||
client_run_id: str | None = None,
|
||
) -> dict[str, Any]:
|
||
"""Execute one continuous workbench turn with strict access gates, live run tracking, and real cancellation."""
|
||
session_id_val = str(session.id) if session is not None else None
|
||
merged_ctx: dict[str, Any] = {}
|
||
if session is not None and isinstance(session.context_state, dict):
|
||
merged_ctx.update(session.context_state)
|
||
if context_override:
|
||
for k, v in context_override.items():
|
||
if v is not None:
|
||
merged_ctx[k] = v
|
||
|
||
routed = classify_turn_intent(question, merged_ctx)
|
||
workflow_id = routed["workflow_id"]
|
||
preset: ViewPreset = explicit_preset or routed["view_preset"]
|
||
needs_external = bool(external_urls)
|
||
if prefer_llm == "auto":
|
||
use_paid_llm = bool(
|
||
access.can_use_paid_llm
|
||
and ai_client is not None
|
||
and bool(getattr(ai_client, "service_url", ""))
|
||
and not routed["is_pure_projection"]
|
||
and not routed["auto_play_presentation"]
|
||
and workflow_id in _ANALYTICAL_AUTO_LLM_WORKFLOWS
|
||
)
|
||
else:
|
||
use_paid_llm = bool(prefer_llm)
|
||
|
||
if use_paid_llm or needs_external:
|
||
await enforce_paid_research_gate(
|
||
access,
|
||
db,
|
||
workflow_id=workflow_id,
|
||
needs_external_fetch=needs_external,
|
||
)
|
||
|
||
if client_run_id:
|
||
existing_handle = _ACTIVE_RUNS.get(client_run_id)
|
||
if existing_handle is not None:
|
||
if existing_handle.actor_key != access.actor_key:
|
||
raise HTTPException(
|
||
status_code=401 if access.tier == "public_zero_cost" else 403,
|
||
detail="Workflow run_id belongs to another actor",
|
||
)
|
||
raise HTTPException(status_code=409, detail=f"Duplicate active run_id: {client_run_id}")
|
||
if hasattr(db, "execute"):
|
||
try:
|
||
existing_row = (
|
||
await db.execute(select(WorkflowRun).where(WorkflowRun.id == client_run_id))
|
||
).scalar_one_or_none()
|
||
if existing_row is not None:
|
||
if existing_row.actor_key != access.actor_key:
|
||
raise HTTPException(
|
||
status_code=401 if access.tier == "public_zero_cost" else 403,
|
||
detail="Workflow run_id belongs to another actor",
|
||
)
|
||
raise HTTPException(status_code=409, detail=f"Duplicate run_id: {client_run_id}")
|
||
except HTTPException:
|
||
raise
|
||
except Exception:
|
||
pass
|
||
run_id = client_run_id
|
||
else:
|
||
run_id = f"run-{uuid.uuid4().hex[:12]}"
|
||
|
||
started_at = datetime.now(UTC)
|
||
tool_trace: list[str] = [f"intent_router:{workflow_id}"]
|
||
|
||
domain = routed["domain"]
|
||
time_basis: TimeBasis = routed["time_basis"]
|
||
cutoff_at: str | None = routed["cutoff_at"]
|
||
|
||
run_record = WorkflowRun(
|
||
id=run_id,
|
||
session_id=session_id_val,
|
||
workflow_id=workflow_id,
|
||
status="running",
|
||
access_tier=access.tier,
|
||
actor_key=access.actor_key,
|
||
question=question,
|
||
input_params=routed,
|
||
tool_trace=list(tool_trace),
|
||
budget_used={"llm_calls": 0, "web_fetches": 0, "zero_token": True},
|
||
started_at=started_at,
|
||
)
|
||
if session is not None:
|
||
running_ctx = dict(merged_ctx)
|
||
running_ctx["active_run_id"] = run_id
|
||
session.context_state = running_ctx
|
||
|
||
if hasattr(db, "add") and hasattr(db, "flush"):
|
||
try:
|
||
db.add(run_record)
|
||
await db.flush()
|
||
if hasattr(db, "commit"):
|
||
await db.commit()
|
||
except Exception as exc:
|
||
logger.warning_event(
|
||
"Initial running WorkflowRun flush skipped on mock session",
|
||
event="ai_workflow.run_init.skipped",
|
||
context={"run_id": run_id, "error": str(exc)},
|
||
)
|
||
|
||
handle = ActiveRunHandle(
|
||
run_id=run_id,
|
||
session_id=session_id_val,
|
||
actor_key=access.actor_key,
|
||
workflow_id=workflow_id,
|
||
access_tier=access.tier,
|
||
question=question,
|
||
started_at=started_at,
|
||
)
|
||
_ACTIVE_RUNS[run_id] = handle
|
||
|
||
def _check_cancelled() -> None:
|
||
if handle.cancel_event.is_set():
|
||
raise asyncio.CancelledError()
|
||
|
||
async def _run_turn_work() -> dict[str, Any]:
|
||
_check_cancelled()
|
||
llm_calls_used = 0
|
||
web_fetches_used = 0
|
||
|
||
can_reuse_frozen = (
|
||
(routed["is_pure_projection"] or routed["auto_play_presentation"])
|
||
and not (prefer_llm is True)
|
||
and not needs_external
|
||
and bool(merged_ctx.get("active_result_id"))
|
||
and int(merged_ctx.get("active_revision") or 0) >= 1
|
||
and domain == merged_ctx.get("domain")
|
||
and time_basis == (merged_ctx.get("time_basis") or time_basis)
|
||
and cutoff_at == merged_ctx.get("cutoff_at")
|
||
and (
|
||
domain != "compute"
|
||
or (
|
||
routed["selected_codes"] == (merged_ctx.get("selected_codes") or routed["selected_codes"])
|
||
and routed["mode"] == (merged_ctx.get("mode") or routed["mode"])
|
||
)
|
||
)
|
||
)
|
||
if can_reuse_frozen and hasattr(db, "execute"):
|
||
try:
|
||
frozen = await read_frozen_result_revision(
|
||
db,
|
||
result_id=str(merged_ctx["active_result_id"]),
|
||
revision=int(merged_ctx["active_revision"]),
|
||
preset=preset,
|
||
output_format="onepager" if preset == "onepager" else "json",
|
||
)
|
||
tool_trace.append(
|
||
f"read_frozen_result_revision:{frozen['subject_key']}:v{frozen['revision']}:{preset}"
|
||
)
|
||
f_view = ViewSpec.model_validate(frozen["view_spec"])
|
||
f_scene = SceneSpec.model_validate(frozen["scene_spec"])
|
||
if routed["auto_play_presentation"]:
|
||
f_scene.auto_play_presentation = True
|
||
f_payload = frozen.get("payload") or {}
|
||
f_title = str(f_payload.get("headline") or f_payload.get("title") or f_view.headline)
|
||
f_summary = str(f_payload.get("executive_assertion") or f_view.subtitle or "")
|
||
return {
|
||
"view_spec": f_view,
|
||
"scene_spec": f_scene,
|
||
"answer_md": f"### {f_title}\n\n{f_summary}".strip(),
|
||
"subject_key": frozen["subject_key"],
|
||
"revision": int(frozen["revision"]),
|
||
"evidence_out": frozen.get("evidence") or {},
|
||
"generation_mode": str(frozen.get("generation_mode") or "deterministic_baseline"),
|
||
"llm_calls_used": 0,
|
||
"web_fetches_used": 0,
|
||
"llm_usage": {},
|
||
}
|
||
except HTTPException:
|
||
pass
|
||
|
||
if domain == "bgp":
|
||
tool_trace.append("query_bgp_incidents_tool")
|
||
inc_res = await investigate_infrastructure_incident(
|
||
db,
|
||
incident_key=routed["entity_id"],
|
||
question=question,
|
||
analysis_focus=routed["incident_focus"],
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
allow_drill=bool(routed["include_drill"]),
|
||
persist=not routed["is_pure_projection"],
|
||
external_urls=external_urls if access.can_use_external_fetch else None,
|
||
ai_client=ai_client if (use_paid_llm and access.can_use_paid_llm) else None,
|
||
max_fetches=access.max_web_fetches_per_run,
|
||
cancel_event=handle.cancel_event,
|
||
)
|
||
_check_cancelled()
|
||
inc_usage = inc_res.get("usage") if not inc_res.get("cache_hit") else None
|
||
if inc_res.get("generation_mode") == "llm_verified" and not inc_res.get("cache_hit"):
|
||
llm_calls_used += 1
|
||
web_fetches_used += min(len(external_urls or []), access.max_web_fetches_per_run)
|
||
view_spec, scene_spec = compile_incident_view_spec(
|
||
incident_res=inc_res,
|
||
preset=preset,
|
||
auto_play=routed["auto_play_presentation"],
|
||
)
|
||
payload = inc_res["payload"]
|
||
answer_md = (
|
||
f"### {payload['title']}\n\n"
|
||
+ "\n".join(f"- **已核验事实**:{c['statement']}" for c in (payload.get("confirmed_facts") or []))
|
||
+ (
|
||
"\n" + "\n".join(f"- **候选研判**:{c['statement']}" for c in (payload.get("candidate_explanations") or []))
|
||
if payload.get("candidate_explanations")
|
||
else ""
|
||
)
|
||
+ (
|
||
"\n" + "\n".join(f"- **待核查边界**:{g}" for g in (payload.get("open_gaps") or [])[:2])
|
||
if payload.get("open_gaps")
|
||
else ""
|
||
)
|
||
)
|
||
return {
|
||
"view_spec": view_spec,
|
||
"scene_spec": scene_spec,
|
||
"answer_md": answer_md,
|
||
"subject_key": inc_res["subject_key"],
|
||
"revision": int(inc_res.get("revision") or 0),
|
||
"evidence_out": inc_res["evidence"],
|
||
"generation_mode": inc_res["generation_mode"],
|
||
"llm_calls_used": llm_calls_used,
|
||
"web_fetches_used": web_fetches_used,
|
||
"llm_usage": merge_usage_dicts(inc_usage),
|
||
}
|
||
|
||
if domain in SPATIAL_POSTURE_DOMAINS:
|
||
tool_trace.append(f"query_{domain}_posture_tool")
|
||
dom_res = await investigate_spatial_domain(
|
||
db,
|
||
domain=domain, # type: ignore[arg-type]
|
||
question=question,
|
||
selected_codes=routed["selected_codes"],
|
||
entity_id=routed.get("entity_id"),
|
||
visible_layers=routed.get("visible_layers"),
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
persist=not routed["is_pure_projection"],
|
||
ai_client=ai_client if (use_paid_llm and access.can_use_paid_llm) else None,
|
||
cancel_event=handle.cancel_event,
|
||
)
|
||
_check_cancelled()
|
||
dom_usage = dom_res.get("usage") if not dom_res.get("cache_hit") else None
|
||
if dom_res.get("generation_mode") == "llm_verified" and not dom_res.get("cache_hit"):
|
||
llm_calls_used += 1
|
||
view_spec, scene_spec = compile_spatial_domain_view_spec(
|
||
domain_res=dom_res,
|
||
preset=preset,
|
||
auto_play=routed["auto_play_presentation"],
|
||
)
|
||
payload = dom_res["payload"]
|
||
facts = payload.get("confirmed_facts") or []
|
||
notes = payload.get("analytical_notes") or []
|
||
gaps = payload.get("open_gaps") or []
|
||
answer_md = (
|
||
f"### {payload['title']}\n\n"
|
||
+ f"{payload.get('executive_assertion') or ''}\n\n"
|
||
+ "\n".join(f"- **已核验态势**:{c['statement']}" for c in facts)
|
||
+ ("\n" + "\n".join(f"- **综合研判**:{n['statement']}" for n in notes[:2]) if notes else "")
|
||
+ ("\n" + "\n".join(f"- **口径边界**:{g}" for g in gaps[:2]) if gaps else "")
|
||
).strip()
|
||
return {
|
||
"view_spec": view_spec,
|
||
"scene_spec": scene_spec,
|
||
"answer_md": answer_md,
|
||
"subject_key": dom_res["subject_key"],
|
||
"revision": int(dom_res.get("revision") or 0),
|
||
"evidence_out": dom_res["evidence"],
|
||
"generation_mode": dom_res["generation_mode"],
|
||
"llm_calls_used": llm_calls_used,
|
||
"web_fetches_used": web_fetches_used,
|
||
"llm_usage": merge_usage_dicts(dom_usage),
|
||
}
|
||
|
||
codes = routed["selected_codes"]
|
||
mode = routed["mode"]
|
||
enable_hubs = bool("枢纽" in question or "东数西算" in question or "hub" in question.lower())
|
||
tool_trace.append(f"query_compute_posture_tool:{','.join(codes)}:{mode}")
|
||
series = await query_compute_posture_tool(
|
||
db,
|
||
codes,
|
||
mode=mode,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
)
|
||
_check_cancelled()
|
||
posture = await generate_or_get_compute_posture(
|
||
db,
|
||
countries=codes,
|
||
mode=mode,
|
||
series_payload=series,
|
||
ai_client=ai_client if (use_paid_llm and access.can_use_paid_llm) else None,
|
||
prefer_llm=bool(use_paid_llm and access.can_use_paid_llm),
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
persist=not routed["is_pure_projection"],
|
||
cancel_event=handle.cancel_event,
|
||
)
|
||
_check_cancelled()
|
||
posture_usage = posture.get("usage") if not posture.get("cache_hit") else None
|
||
if posture.get("generation_mode") == "llm_verified" and not posture.get("cache_hit"):
|
||
llm_calls_used += 1
|
||
|
||
copilot_out = await run_contextual_copilot(
|
||
db,
|
||
domain="compute",
|
||
selected_codes=codes,
|
||
focus_year=routed["focus_year"],
|
||
mode=mode,
|
||
entity_id=routed["entity_id"],
|
||
question=question,
|
||
time_basis=time_basis,
|
||
cutoff_at=cutoff_at,
|
||
series_override=series,
|
||
posture_override=posture,
|
||
ai_client=ai_client if (use_paid_llm and access.can_use_paid_llm) else None,
|
||
cancel_event=handle.cancel_event,
|
||
)
|
||
_check_cancelled()
|
||
copilot_usage = copilot_out.get("usage") if copilot_out.get("generation_mode") == "llm_verified" else None
|
||
if copilot_out.get("generation_mode") == "llm_verified":
|
||
llm_calls_used += 1
|
||
|
||
view_spec, scene_spec = compile_compute_view_spec(
|
||
codes=codes,
|
||
mode=mode,
|
||
series=series,
|
||
posture=posture,
|
||
preset=preset,
|
||
enable_hubs=enable_hubs,
|
||
auto_play=routed["auto_play_presentation"],
|
||
)
|
||
return {
|
||
"view_spec": view_spec,
|
||
"scene_spec": scene_spec,
|
||
"answer_md": copilot_out["reply"]["answer_markdown"],
|
||
"subject_key": posture["subject_key"],
|
||
"revision": int(posture.get("revision") or 1),
|
||
"evidence_out": series.get("evidence") or {},
|
||
"generation_mode": copilot_out["generation_mode"],
|
||
"llm_calls_used": llm_calls_used,
|
||
"web_fetches_used": web_fetches_used,
|
||
"llm_usage": merge_usage_dicts(posture_usage, copilot_usage),
|
||
}
|
||
|
||
inner_task = asyncio.create_task(_run_turn_work())
|
||
handle.task = inner_task
|
||
|
||
try:
|
||
work_out = await inner_task
|
||
if handle.cancel_event.is_set():
|
||
raise asyncio.CancelledError()
|
||
except asyncio.CancelledError:
|
||
if not inner_task.done():
|
||
inner_task.cancel()
|
||
await asyncio.gather(inner_task, return_exceptions=True)
|
||
await _finalize_workflow_run_db(
|
||
db,
|
||
run_id=run_id,
|
||
session_id_val=session_id_val,
|
||
status_value="cancelled",
|
||
domain=domain,
|
||
tool_trace=tool_trace,
|
||
budget_used={"llm_calls": 0, "web_fetches": 0, "zero_token": True},
|
||
fallback_run=run_record,
|
||
)
|
||
if handle.cancel_event.is_set():
|
||
return {
|
||
"session_id": session_id_val,
|
||
"run_id": run_id,
|
||
"workflow_id": workflow_id,
|
||
"status": "cancelled",
|
||
"access_tier": access.tier,
|
||
"zero_token": True,
|
||
"domain": domain,
|
||
"result_id": merged_ctx.get("active_result_id"),
|
||
"subject_key": merged_ctx.get("active_result_id"),
|
||
"revision": int(merged_ctx.get("active_revision") or 0),
|
||
"generation_mode": "cancelled",
|
||
"time_basis": time_basis,
|
||
"cutoff_at": cutoff_at,
|
||
"context_state": {**merged_ctx, "active_run_id": None},
|
||
"reply": {
|
||
"answer_markdown": "已停止并取消当前后台研究运行。",
|
||
"highlight_entities": [],
|
||
"suggested_followups": [],
|
||
"evidence_ids": [],
|
||
},
|
||
"view_spec": None,
|
||
"scene_spec": None,
|
||
"evidence": {},
|
||
}
|
||
raise
|
||
except Exception as exc:
|
||
await _finalize_workflow_run_db(
|
||
db,
|
||
run_id=run_id,
|
||
session_id_val=session_id_val,
|
||
status_value="failed",
|
||
domain=domain,
|
||
tool_trace=tool_trace,
|
||
budget_used={"llm_calls": 0, "web_fetches": 0, "zero_token": True},
|
||
fallback_run=run_record,
|
||
error_message=str(exc),
|
||
)
|
||
raise
|
||
finally:
|
||
_ACTIVE_RUNS.pop(run_id, None)
|
||
|
||
view_spec = work_out["view_spec"]
|
||
scene_spec = work_out["scene_spec"]
|
||
answer_md = work_out["answer_md"]
|
||
subject_key = work_out["subject_key"]
|
||
revision = work_out["revision"]
|
||
evidence_out = work_out["evidence_out"]
|
||
generation_mode = work_out["generation_mode"]
|
||
llm_calls_used = work_out["llm_calls_used"]
|
||
web_fetches_used = work_out["web_fetches_used"]
|
||
llm_usage = work_out.get("llm_usage") or {}
|
||
|
||
next_context = {
|
||
"domain": domain,
|
||
"selected_codes": routed["selected_codes"],
|
||
"mode": routed["mode"],
|
||
"focus_year": scene_spec.focus_year,
|
||
"entity_id": routed["entity_id"],
|
||
"visible_layers": routed.get("visible_layers") or {},
|
||
"time_basis": time_basis,
|
||
"cutoff_at": cutoff_at,
|
||
"include_drill": routed["include_drill"],
|
||
"active_result_id": subject_key,
|
||
"active_revision": revision,
|
||
"active_preset": preset,
|
||
"active_run_id": None,
|
||
}
|
||
budget_used = {
|
||
"llm_calls": llm_calls_used,
|
||
"web_fetches": web_fetches_used,
|
||
"zero_token": llm_calls_used == 0,
|
||
"input_tokens": int(llm_usage.get("input_tokens") or 0),
|
||
"output_tokens": int(llm_usage.get("output_tokens") or 0),
|
||
"thinking_tokens": int(llm_usage.get("thinking_tokens") or 0),
|
||
"total_tokens": int(llm_usage.get("total_tokens") or 0),
|
||
"provider": str(llm_usage.get("provider") or ""),
|
||
"model": str(llm_usage.get("model") or ""),
|
||
}
|
||
final_status = await _finalize_workflow_run_db(
|
||
db,
|
||
run_id=run_id,
|
||
session_id_val=session_id_val,
|
||
status_value="completed",
|
||
domain=domain,
|
||
tool_trace=tool_trace,
|
||
budget_used=budget_used,
|
||
result_subject_key=subject_key,
|
||
result_revision=revision,
|
||
next_context=next_context,
|
||
fallback_run=run_record,
|
||
)
|
||
|
||
return {
|
||
"session_id": session_id_val,
|
||
"run_id": run_id,
|
||
"workflow_id": workflow_id,
|
||
"status": final_status,
|
||
"access_tier": access.tier,
|
||
"zero_token": llm_calls_used == 0,
|
||
"domain": domain,
|
||
"result_id": subject_key,
|
||
"subject_key": subject_key,
|
||
"revision": revision,
|
||
"generation_mode": generation_mode,
|
||
"time_basis": time_basis,
|
||
"cutoff_at": cutoff_at,
|
||
"context_state": next_context,
|
||
"reply": {
|
||
"answer_markdown": answer_md,
|
||
"highlight_entities": scene_spec.highlight_entities,
|
||
"suggested_followups": view_spec.followups,
|
||
"evidence_ids": list(evidence_out.keys())[:12],
|
||
},
|
||
"view_spec": view_spec.model_dump(mode="json"),
|
||
"scene_spec": scene_spec.model_dump(mode="json"),
|
||
"evidence": evidence_out,
|
||
}
|
||
|
||
|
||
async def read_frozen_result_revision(
|
||
db: AsyncSession,
|
||
*,
|
||
result_id: str,
|
||
revision: int,
|
||
preset: ViewPreset = "default",
|
||
output_format: Literal["json", "markdown", "onepager"] = "json",
|
||
) -> dict[str, Any]:
|
||
"""Gate 0 · R7: Strictly read-only (`0` DB writes) exact `(result_id, revision)` lookup & projection."""
|
||
target_row: SituationalAssessment | None = None
|
||
latest_rev_num: int | None = None
|
||
|
||
if hasattr(db, "execute"):
|
||
target_row = (
|
||
await db.execute(
|
||
select(SituationalAssessment)
|
||
.where(
|
||
SituationalAssessment.subject_key == result_id,
|
||
SituationalAssessment.revision == revision,
|
||
)
|
||
.order_by(desc(SituationalAssessment.id))
|
||
.limit(1)
|
||
)
|
||
).scalar_one_or_none()
|
||
|
||
latest_rev_num = (
|
||
await db.execute(
|
||
select(SituationalAssessment.revision)
|
||
.where(SituationalAssessment.subject_key == result_id)
|
||
.order_by(desc(SituationalAssessment.revision))
|
||
.limit(1)
|
||
)
|
||
).scalar_one_or_none()
|
||
|
||
if target_row is None:
|
||
raise HTTPException(
|
||
status_code=404,
|
||
detail=f"Result revision not found: result_id={result_id}, revision={revision}",
|
||
)
|
||
|
||
has_newer = isinstance(latest_rev_num, int) and latest_rev_num > revision
|
||
audit_meta = target_row.audit_meta or {}
|
||
time_basis: TimeBasis = audit_meta.get("time_basis") if audit_meta.get("time_basis") in {"live", "as_known_then", "retrospective"} else "retrospective"
|
||
cutoff_at: str | None = audit_meta.get("cutoff_at")
|
||
effective_preset: ViewPreset = "onepager" if output_format == "onepager" else preset
|
||
replay_supported = True
|
||
replay_status: Literal["frozen", "incomplete_snapshot"] = "frozen"
|
||
replay_notice: str | None = None
|
||
|
||
if target_row.subject_type == "compute_posture":
|
||
parts = result_id.split(":")
|
||
fallback_codes = [c for c in (parts[1].split(",") if len(parts) > 1 else ["CN", "US"]) if c in PARTICIPANTS] or ["CN", "US"]
|
||
fallback_mode = parts[2] if len(parts) > 2 else "global_share"
|
||
codes = list(audit_meta.get("countries") or fallback_codes)
|
||
mode = str(audit_meta.get("mode") or fallback_mode)
|
||
frozen_series = audit_meta.get("frozen_series")
|
||
if isinstance(frozen_series, dict) and isinstance(frozen_series.get("compute"), list):
|
||
series = copy.deepcopy(frozen_series)
|
||
mode = str(audit_meta.get("mode") or series.get("mode") or fallback_mode)
|
||
else:
|
||
# Legacy record missing `frozen_series`: NEVER query live config (would mix old text + new numbers).
|
||
replay_supported = False
|
||
replay_status = "incomplete_snapshot"
|
||
replay_notice = _INCOMPLETE_COMPUTE_REPLAY_NOTICE
|
||
legacy_eids = _collect_payload_evidence_ids(target_row.payload, target_row.evidence_ids)
|
||
stub_evidence = {
|
||
eid: {
|
||
"id": eid,
|
||
"title": f"历史引用证据 · {eid}(快照缺失)",
|
||
"publisher": "Historical Revision Ledger",
|
||
"url": "",
|
||
"published_at": None,
|
||
"locator": f"result_id={result_id} · rev=v{revision} · incomplete_snapshot",
|
||
}
|
||
for eid in legacy_eids
|
||
}
|
||
series = {
|
||
"countries": [{"code": c, **(PARTICIPANTS.get(c) or {})} for c in codes],
|
||
"mode": mode,
|
||
"unit": _METRIC_LABELS.get(mode, ("", "", "%"))[2],
|
||
"years": [],
|
||
"compute": [],
|
||
"bilateral_rpi": None,
|
||
"denominator_attribution": {},
|
||
"structures": {},
|
||
"innovation_summary": None,
|
||
"national_hubs": [],
|
||
"evidence": stub_evidence,
|
||
"withheld_source_ids": [],
|
||
"limitations": [_INCOMPLETE_COMPUTE_REPLAY_NOTICE],
|
||
"time_basis": time_basis,
|
||
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
|
||
}
|
||
stored_posture = target_row.to_dict()
|
||
view_spec, scene_spec = compile_compute_view_spec(
|
||
codes=codes,
|
||
mode=mode,
|
||
series=series,
|
||
posture=stored_posture,
|
||
preset=effective_preset,
|
||
replay_supported=replay_supported,
|
||
replay_notice=replay_notice,
|
||
)
|
||
evidence_map = {
|
||
eid: series["evidence"][eid]
|
||
for eid in (target_row.evidence_ids or [])
|
||
if eid in (series.get("evidence") or {})
|
||
} or (series.get("evidence") or {})
|
||
elif target_row.subject_type in {"global_posture", "cable_posture", "satellite_posture", "vessel_posture"}:
|
||
spatial_domain = subject_type_to_domain(target_row.subject_type)
|
||
frozen_snap = audit_meta.get("frozen_snapshot")
|
||
frozen_ev = audit_meta.get("frozen_evidence")
|
||
if isinstance(frozen_snap, dict):
|
||
snap_dict = copy.deepcopy(frozen_snap)
|
||
else:
|
||
replay_supported = False
|
||
replay_status = "incomplete_snapshot"
|
||
replay_notice = _INCOMPLETE_SPATIAL_REPLAY_NOTICE
|
||
snap_dict = {
|
||
"domain": spatial_domain,
|
||
"available": False,
|
||
"selected_codes": audit_meta.get("selected_codes") or ["CN", "US"],
|
||
"time_basis": time_basis,
|
||
"cutoff_at": cutoff_at,
|
||
"limitations": [_INCOMPLETE_SPATIAL_REPLAY_NOTICE],
|
||
}
|
||
if isinstance(frozen_ev, dict) and frozen_ev:
|
||
ev_map = {
|
||
eid: copy.deepcopy(frozen_ev[eid])
|
||
for eid in (target_row.evidence_ids or list(frozen_ev.keys()))
|
||
if eid in frozen_ev
|
||
} or copy.deepcopy(frozen_ev)
|
||
else:
|
||
legacy_spatial_eids = _collect_payload_evidence_ids(target_row.payload, target_row.evidence_ids) or [f"ev-{result_id}"]
|
||
ev_map = {
|
||
eid: {
|
||
"id": eid,
|
||
"title": f"Frozen Spatial Evidence · {eid}",
|
||
"publisher": "Planet Spatial Ledger",
|
||
"url": "",
|
||
"published_at": None,
|
||
"locator": f"result_id={result_id} · rev=v{revision}",
|
||
}
|
||
for eid in legacy_spatial_eids
|
||
}
|
||
dom_res = {
|
||
"domain": spatial_domain,
|
||
"subject_type": target_row.subject_type,
|
||
"subject_key": result_id,
|
||
"revision": revision,
|
||
"generation_mode": target_row.generation_mode,
|
||
"time_basis": time_basis,
|
||
"cutoff_at": cutoff_at,
|
||
"snapshot": snap_dict,
|
||
"payload": target_row.payload,
|
||
"evidence": ev_map,
|
||
"replay_supported": replay_supported,
|
||
"replay_notice": replay_notice,
|
||
}
|
||
view_spec, scene_spec = compile_spatial_domain_view_spec(
|
||
domain_res=dom_res,
|
||
preset=effective_preset,
|
||
)
|
||
evidence_map = ev_map
|
||
else:
|
||
frozen_inc = audit_meta.get("frozen_incident")
|
||
frozen_ev = audit_meta.get("frozen_evidence")
|
||
if isinstance(frozen_inc, dict):
|
||
inc_dict = copy.deepcopy(frozen_inc)
|
||
else:
|
||
# Legacy BGP record missing `frozen_incident`: NEVER query live BGPIncident table.
|
||
replay_supported = False
|
||
replay_status = "incomplete_snapshot"
|
||
replay_notice = _INCOMPLETE_BGP_REPLAY_NOTICE
|
||
inc_dict = {
|
||
"incident_key": result_id,
|
||
"title": target_row.payload.get("title", result_id),
|
||
"severity": "unknown",
|
||
"status": "incomplete_snapshot",
|
||
}
|
||
if isinstance(frozen_ev, dict) and frozen_ev:
|
||
ev_map = {
|
||
eid: copy.deepcopy(frozen_ev[eid])
|
||
for eid in (target_row.evidence_ids or list(frozen_ev.keys()))
|
||
if eid in frozen_ev
|
||
} or copy.deepcopy(frozen_ev)
|
||
else:
|
||
legacy_inc_eids = _collect_payload_evidence_ids(target_row.payload, target_row.evidence_ids) or [f"ev-{result_id}"]
|
||
ev_map = {
|
||
eid: {
|
||
"title": f"Frozen Evidence · {eid}",
|
||
"publisher": str(inc_dict.get("source") or "Planet Ledger"),
|
||
"url": "",
|
||
"published_at": str(inc_dict.get("started_at") or "")[:10],
|
||
"locator": f"result_id={result_id} · rev=v{revision}",
|
||
}
|
||
for eid in legacy_inc_eids
|
||
}
|
||
inc_res = {
|
||
"found": True,
|
||
"is_drill": bool(audit_meta.get("is_drill") or target_row.payload.get("is_drill")),
|
||
"subject_type": "bgp_incident",
|
||
"subject_key": result_id,
|
||
"revision": revision,
|
||
"generation_mode": target_row.generation_mode,
|
||
"analysis_focus": audit_meta.get("analysis_focus") or target_row.payload.get("analysis_focus", "overview"),
|
||
"time_basis": time_basis,
|
||
"cutoff_at": cutoff_at,
|
||
"incident": inc_dict,
|
||
"payload": target_row.payload,
|
||
"evidence": ev_map,
|
||
"replay_supported": replay_supported,
|
||
"replay_notice": replay_notice,
|
||
}
|
||
view_spec, scene_spec = compile_incident_view_spec(
|
||
incident_res=inc_res,
|
||
preset=effective_preset,
|
||
)
|
||
evidence_map = ev_map
|
||
|
||
response_obj: dict[str, Any] = {
|
||
"result_id": result_id,
|
||
"subject_type": target_row.subject_type,
|
||
"subject_key": result_id,
|
||
"revision": revision,
|
||
"latest_revision": latest_rev_num or revision,
|
||
"is_historical_revision": has_newer,
|
||
"replay_supported": replay_supported,
|
||
"replay_status": replay_status,
|
||
"replay_notice": replay_notice,
|
||
"newer_revision_notice": (
|
||
f"当前对象已存在更新版本 v{latest_rev_num};本视图/报告严格冻结于请求版本 v{revision}。"
|
||
if has_newer
|
||
else None
|
||
),
|
||
"input_fingerprint": target_row.input_fingerprint,
|
||
"generation_mode": target_row.generation_mode,
|
||
"time_basis": time_basis,
|
||
"cutoff_at": cutoff_at,
|
||
"payload": target_row.payload,
|
||
"view_spec": view_spec.model_dump(mode="json"),
|
||
"scene_spec": scene_spec.model_dump(mode="json"),
|
||
"evidence": evidence_map,
|
||
}
|
||
|
||
if output_format in {"markdown", "onepager"}:
|
||
md = format_frozen_revision_markdown(response_obj)
|
||
response_obj["markdown"] = md
|
||
response_obj["filename"] = f"planet-report-{result_id.replace(':', '-')}-v{revision}.md"
|
||
response_obj["content_sha256"] = hashlib.sha256(md.encode("utf-8")).hexdigest()
|
||
|
||
return response_obj
|
||
|
||
|
||
def format_frozen_revision_markdown(frozen: dict[str, Any]) -> str:
|
||
"""Render deterministic, citation-complete Markdown strictly from a frozen revision snapshot."""
|
||
now_iso = datetime.now(UTC).strftime("%Y-%m-%d %H:%M:%S UTC")
|
||
payload = frozen["payload"]
|
||
rev = frozen["revision"]
|
||
result_id = frozen["result_id"]
|
||
evidence = frozen.get("evidence") or {}
|
||
notice = frozen.get("newer_revision_notice")
|
||
replay_supported = bool(frozen.get("replay_supported", True))
|
||
replay_notice = frozen.get("replay_notice")
|
||
|
||
header_title = payload.get("headline") or payload.get("title") or result_id
|
||
lines: list[str] = [
|
||
f"# {header_title}",
|
||
"",
|
||
f"- **结果标识(Result ID)**:`{result_id}`",
|
||
f"- **绑定研判版本(Revision)**:`v{rev}`(指纹 `{str(frozen.get('input_fingerprint') or '')[:16]}`)",
|
||
f"- **时间回放口径**:`{frozen.get('time_basis', 'retrospective')}`"
|
||
+ (f"(截点 `{frozen['cutoff_at']}`)" if frozen.get("cutoff_at") else ""),
|
||
f"- **重放完整性**:`{'支持完整冻结重放' if replay_supported else '不支持完整重放(历史快照缺失)'}`",
|
||
f"- **导出时间**:`{now_iso}`",
|
||
]
|
||
if notice:
|
||
lines.extend(["", f"> **版本冻结提示**:{notice}"])
|
||
if not replay_supported and replay_notice:
|
||
lines.extend(["", f"> **重放完整性警示**:{replay_notice}"])
|
||
|
||
if frozen["subject_type"] == "compute_posture":
|
||
view_spec_dict = frozen.get("view_spec") or {}
|
||
matrix_blk = next(
|
||
(b for b in (view_spec_dict.get("blocks") or []) if b.get("block_type") == "comparison_matrix"),
|
||
None,
|
||
)
|
||
metric_lines: list[str] = []
|
||
if not replay_supported:
|
||
metric_lines.extend(
|
||
[
|
||
"",
|
||
"### 核心指标快照",
|
||
"- 当前旧版本记录缺少冻结数据快照,**不支持完整重放**(已禁止读取当前配置替代历史数值)。",
|
||
]
|
||
)
|
||
elif matrix_blk:
|
||
mdata = matrix_blk.get("data") or {}
|
||
rows = mdata.get("rows") or []
|
||
if rows or mdata.get("rpi_percent") is not None:
|
||
metric_lines.extend(["", "### 核心指标快照(冻结版本数据)"])
|
||
if mdata.get("rpi_percent") is not None:
|
||
metric_lines.append(f"- **双边相对平价(RPI)**:`{mdata['rpi_percent']}%`")
|
||
for r in rows:
|
||
metric_lines.append(
|
||
f"- **{r.get('label') or r.get('code')}**({r.get('year') or 'N/A'}):`{r.get('formatted')}`"
|
||
)
|
||
lines.extend(
|
||
[
|
||
"",
|
||
"## 一、核心战略态势断言",
|
||
"",
|
||
str(payload.get("executive_assertion") or ""),
|
||
*metric_lines,
|
||
"",
|
||
"## 二、关键成因与分母拆解",
|
||
*[
|
||
f"- **{item['label']}**:{item['detail']} (证据:`{', '.join(item['evidence_ids'])}`)"
|
||
for item in (payload.get("causes") or [])
|
||
],
|
||
"",
|
||
"## 三、结构韧性与协同支点",
|
||
*[
|
||
f"- **{item['label']}**:{item['detail']} (证据:`{', '.join(item['evidence_ids'])}`)"
|
||
for item in (payload.get("breakthrough_levers") or [])
|
||
],
|
||
"",
|
||
"## 四、数据覆盖边界与留白说明",
|
||
*[f"- {b}" for b in (payload.get("blind_spots") or [])],
|
||
]
|
||
)
|
||
elif frozen["subject_type"] in {"global_posture", "cable_posture", "satellite_posture", "vessel_posture"}:
|
||
lines.extend(
|
||
[
|
||
"",
|
||
"## 一、核心空间态势断言",
|
||
"",
|
||
str(payload.get("executive_assertion") or ""),
|
||
"",
|
||
"## 二、已核验态势事实",
|
||
*[
|
||
f"- {item['statement']} (证据:`{', '.join(item['evidence_ids'])}`)"
|
||
for item in (payload.get("confirmed_facts") or [])
|
||
],
|
||
"",
|
||
"## 三、域内观测注释与口径说明",
|
||
*[
|
||
f"- {item['statement']} (证据:`{', '.join(item['evidence_ids'])}`)"
|
||
for item in (payload.get("analytical_notes") or [])
|
||
],
|
||
"",
|
||
"## 四、覆盖边界与留白说明",
|
||
*[f"- **口径边界**:{item}" for item in (payload.get("open_gaps") or [])],
|
||
]
|
||
)
|
||
else:
|
||
lines.extend(
|
||
[
|
||
"",
|
||
"## 一、已核验观测事实",
|
||
*[
|
||
f"- {item['statement']} (证据:`{', '.join(item['evidence_ids'])}`)"
|
||
for item in (payload.get("confirmed_facts") or [])
|
||
],
|
||
"",
|
||
"## 二、候选成因研判",
|
||
*[
|
||
f"- {item['statement']} (证据:`{', '.join(item['evidence_ids'])}`)"
|
||
for item in (payload.get("candidate_explanations") or [])
|
||
],
|
||
"",
|
||
"## 三、反证与待核查缺口",
|
||
*[f"- **反证校验**:{item}" for item in (payload.get("counter_evidence") or [])],
|
||
*[f"- **待查缺口**:{item}" for item in (payload.get("open_gaps") or [])],
|
||
]
|
||
)
|
||
|
||
lines.extend(["", "## 五、完整证据链与哈希校验"])
|
||
for eid, ev in evidence.items():
|
||
ev_hash = hashlib.sha256(json.dumps(ev, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest()[:16]
|
||
lines.append(
|
||
f"- **[{eid}]** {ev.get('title')} — {ev.get('publisher')} ({ev.get('published_at') or 'N/A'}) · 位置:{ev.get('locator')} · URL: {ev.get('url')} · `sha256:{ev_hash}`"
|
||
)
|
||
return "\n".join(lines)
|