"""StrategicPostureAgent (F-19): versioned, evidence-verified compute posture briefs with SHA-256 caching.""" from __future__ import annotations import asyncio import hashlib import json from typing import Any from pydantic import BaseModel, ConfigDict, Field from sqlalchemy import desc, select from sqlalchemy.ext.asyncio import AsyncSession from app.ai_tasks.prompts import get_effective_prompt from app.core.logging import get_logger from app.models.situational_assessment import EvidenceRecord, SituationalAssessment from app.schemas.ai import SituationalAnalysisRequest from app.services.ai.thinking_sanitizer import ( assert_no_thinking_leak, extract_json_object, extract_response_usage, prepare_situational_ai_call, ) from app.services.ai_client import AIProviderClient logger = get_logger(__name__, service="ai_posture") class PostureBullet(BaseModel): model_config = ConfigDict(extra="forbid") label: str = Field(min_length=1, max_length=120) label_en: str = Field(default="", max_length=160) detail: str = Field(min_length=1, max_length=600) detail_en: str = Field(default="", max_length=700) evidence_ids: list[str] = Field(min_length=1, max_length=8) class StrategicPostureBrief(BaseModel): model_config = ConfigDict(extra="forbid") headline: str = Field(min_length=1, max_length=240) headline_en: str = Field(min_length=1, max_length=280) executive_assertion: str = Field(min_length=1, max_length=800) executive_assertion_en: str = Field(min_length=1, max_length=900) causes: list[PostureBullet] = Field(default_factory=list, max_length=6) breakthrough_levers: list[PostureBullet] = Field(default_factory=list, max_length=6) blind_spots: list[str] = Field(default_factory=list, max_length=6) evidence_ids: list[str] = Field(min_length=1, max_length=16) def _freeze_json_snapshot(data: Any) -> Any: return json.loads(json.dumps(data, ensure_ascii=False, default=str)) def _raise_if_cancelled(cancel_event: asyncio.Event | None) -> None: if cancel_event is not None and cancel_event.is_set(): raise asyncio.CancelledError() def compute_posture_fingerprint( countries: list[str], mode: str, series_payload: dict[str, Any], *, time_basis: str = "retrospective", cutoff_at: str | None = None, ) -> str: canonical = { "countries": countries, "mode": mode, "time_basis": time_basis, "cutoff_at": cutoff_at if time_basis == "as_known_then" else None, "version": series_payload.get("version"), "compute": series_payload.get("compute"), "bilateral_rpi": series_payload.get("bilateral_rpi"), "denominator_attribution": series_payload.get("denominator_attribution"), "structures": series_payload.get("structures"), "innovation_summary": series_payload.get("innovation_summary"), } return hashlib.sha256(json.dumps(canonical, sort_keys=True, ensure_ascii=False).encode("utf-8")).hexdigest() def verify_brief_citations(brief: StrategicPostureBrief, allowed_evidence: dict[str, Any]) -> StrategicPostureBrief: """Reject any brief that references hallucinated or unknown `evidence_id`s.""" referenced: list[str] = list(brief.evidence_ids) for item in [*brief.causes, *brief.breakthrough_levers]: referenced.extend(item.evidence_ids) unknown = [eid for eid in referenced if eid not in allowed_evidence] if unknown: raise ValueError(f"Unverified evidence IDs in posture brief: {sorted(set(unknown))}") payload_dict = brief.model_dump(mode="json") assert_no_thinking_leak(payload_dict) brief.evidence_ids = list(dict.fromkeys(referenced)) return brief def build_deterministic_posture_brief(series_payload: dict[str, Any]) -> StrategicPostureBrief: """Zero-hallucination deterministic strategic brief synthesized strictly from verified ledger rows.""" evidence = series_payload.get("evidence") or {} rpi = series_payload.get("bilateral_rpi") attribution = (series_payload.get("denominator_attribution") or {}).get("CN") cn_structure = (series_payload.get("structures") or {}).get("CN") innovation = series_payload.get("innovation_summary") time_basis = series_payload.get("time_basis") or "retrospective" cutoff_at = series_payload.get("cutoff_at") withheld_sources = series_payload.get("withheld_source_ids") or [] cutoff_clause = ( f"(按当时可知口径截至 {cutoff_at},已隔离 {len(withheld_sources)} 份事后报告)" if time_basis == "as_known_then" and cutoff_at else "" ) if rpi and rpi.get("latest_total"): tot = rpi["latest_total"] intel = rpi.get("latest_intelligent") chip = rpi.get("latest_chip_inflow") def _pair_eids(pair: dict[str, Any] | None) -> list[str]: if not pair: return [] candidates = [ pair.get("cn_evidence_id"), pair.get("us_evidence_id"), pair.get("evidence_id"), ] return list(dict.fromkeys(str(eid) for eid in candidates if eid and eid in evidence)) tot_eids = _pair_eids(tot) tot_ev = tot_eids[0] if tot_eids else tot["evidence_id"] near_parity = float(tot["rpi_percent"]) >= 85.0 if near_parity: headline = ( f"{tot['year']} 年中美算力份额处于高位胶着区间(中 {tot['cn_value']}% vs 美 {tot['us_value']}%,RPI {tot['rpi_percent']}%){cutoff_clause}" ) headline_en = ( f"{tot['year']} US-China Compute Shares in Near-Parity Band ({tot['us_value']}% vs {tot['cn_value']}%, RPI {tot['rpi_percent']}%)" ) else: headline = ( f"中美算力份额剪刀差阶段性走阔({tot['cn_value']}% vs {tot['us_value']}%,RPI {tot['rpi_percent']}%)," f"但国内智算转型与创新追赶韧性凸显{cutoff_clause}" ) headline_en = ( f"US-China Compute Share Corridor Widens ({tot['us_value']}% vs {tot['cn_value']}%, RPI {tot['rpi_percent']}%), " f"Backed by Resilient Domestic AI Transition" ) intel_clause = ( f"全球智能算力份额为 {intel['cn_value']}% 对美国 {intel['us_value']}%(RPI {intel['rpi_percent']}%);" if intel else "" ) struct_clause = ( f"国内智能算力占本国总算力比重已跃升至 {cn_structure['intelligent_share']}%," if cn_structure else "" ) innov_clause = ( f"中美 AI 创新指数分差连续收窄至 {innovation['to_value']} 分(累计 {innovation['delta']} 分)。" if innovation else "综合算力应用效能保持稳健推进。" ) yoy_val = tot.get("yoy_cn_pp") yoy_clause = f"(较上年 {yoy_val:+.1f} pp)" if isinstance(yoy_val, (int, float)) else "" assertion = ( f"截至 {tot['year']} 年已核验观测,我国全球总算力份额为 {tot['cn_value']}% 对美国 {tot['us_value']}%{yoy_clause},{intel_clause}" f"{struct_clause}{innov_clause}" ) assertion_en = ( f"As of verified {tot['year']} observations, China's global compute share stands at {tot['cn_value']}% vs U.S. {tot['us_value']}% (RPI {tot['rpi_percent']}%)." ) causes: list[PostureBullet] = [ PostureBullet( label="全球分母膨胀与双边份额演进", label_en="Global Denominator Dynamics & Bilateral Share", detail=( f"我国算力总规模由 {attribution['country_from']:.0f} 增至 {attribution['country_to']:.0f} EFlops" f"(+{attribution['country_growth_pct']}%),同期全球总规模由 {attribution['global_from']:.0f} 暴增至 " f"{attribution['global_to']:.0f} EFlops(+{attribution['global_growth_pct']}%),相对占比呈分母稀释特征。" if attribution and attribution.get("global_to") else f"{tot['year']} 年美国全球总算力份额为 {tot['us_value']}%,我国为 {tot['cn_value']}%(RPI {tot['rpi_percent']}%)。" ), detail_en="China's absolute FP32 capacity grew strongly alongside global capacity expansion.", evidence_ids=[eid for eid in (attribution["evidence_ids"] if attribution else [tot_ev]) if eid in evidence] or [tot_ev], ) ] intel_eids = _pair_eids(intel) if intel and intel_eids: causes.append( PostureBullet( label="智能算力竞争成为核心分化面", label_en="Intelligent Compute Drives Primary Divergence", detail=( f"全球智能算力竞争中美国占 {intel['us_value']}%、我国占 {intel['cn_value']}%(RPI {intel['rpi_percent']}%)," f"高端训练集群供给差异直接拉开了总算力剪刀差。" ), detail_en=f"U.S. holds {intel['us_value']}% of global intelligent compute vs China's {intel['cn_value']}%.", evidence_ids=intel_eids, ) ) chip_eids = _pair_eids(chip) if chip and chip_eids: causes.append( PostureBullet( label="先进芯片管制重塑新增算力流向", label_en="Export Controls Reshape Frontier Chip Inflows", detail=( f"公开样本显示高端 AI 加速卡新增算力约 {chip['us_value']}% 流向美国,我国公开可统计流入约 {chip['cn_value']}%。" ), detail_en=f"~{chip['us_value']}% of tracked H100-equivalent compute inflows went to the U.S. vs ~{chip['cn_value']}% to China.", evidence_ids=chip_eids, ) ) levers: list[PostureBullet] = [] if cn_structure and cn_structure.get("source_id") in evidence: levers.append( PostureBullet( label="国内算力底座完成智算化跃迁", label_en="Domestic Capacity Shifted to AI Compute", detail=( f"截至 {cn_structure.get('period_label') or cn_structure['year']} 我国本国算力构成中智能算力占比达 " f"{cn_structure['intelligent_share']}%(全球平均 85%),算力质量结构高度聚焦大模型推理与训练。" ), detail_en=f"Intelligent compute accounts for {cn_structure['intelligent_share']}% of China's domestic capacity.", evidence_ids=[cn_structure["source_id"]], ) ) if innovation and innovation.get("evidence_id") in evidence: levers.append( PostureBullet( label="工程架构优化推动创新分差收敛", label_en="Algorithmic Efficiency Narrows Innovation Gap", detail=( f"中美 AI 创新指数综合分差由 {innovation['from_year']} 年 {innovation['from_value']} 分收窄至 " f"{innovation['to_year']} 年 {innovation['to_value']} 分({innovation['delta']} 分),单位算力产出效率显著提升。" ), detail_en=f"US-China AI innovation gap narrowed from {innovation['from_value']} to {innovation['to_value']} ({innovation['delta']}).", evidence_ids=[innovation["evidence_id"]], ) ) hubs = series_payload.get("national_hubs") or [] if hubs and hubs[0].get("source_id") in evidence: levers.append( PostureBullet( label="“东数西算”八大国家绿电枢纽纵深协同", label_en="8 National Green Compute Hubs ('East Data, West Compute')", detail="四大东部需求枢纽与四大西部风光水绿电枢纽结对调度(PUE ≤ 1.2–1.25),以低成本清洁电力对冲单卡制程约束。", detail_en="Four eastern demand hubs pair with four western green-power training bases (target PUE 1.2–1.25).", evidence_ids=[hubs[0]["source_id"]], ) ) blind_spots = list(series_payload.get("limitations") or [])[:3] if withheld_sources: blind_spots.insert( 0, f"当时可知回放模式(截至 {cutoff_at})已严格屏蔽事后发布报告:{', '.join(withheld_sources[:4])}。", ) blind_spots = blind_spots[:4] all_eids = list( dict.fromkeys( [tot_ev] + [eid for item in [*causes, *levers] for eid in item.evidence_ids] ) ) return verify_brief_citations( StrategicPostureBrief( headline=headline, headline_en=headline_en, executive_assertion=assertion, executive_assertion_en=assertion_en, causes=causes, breakthrough_levers=levers, blind_spots=blind_spots, evidence_ids=all_eids, ), evidence, ) fallback_eid = next(iter(evidence.keys()), None) if not fallback_eid: return StrategicPostureBrief( headline="当前所选参与方或时间截点暂无已核验对比报告", headline_en="No Verified Comparative Report Available for Selected Scope", executive_assertion="所选国家、区域或历史截点尚无同年同口径完整观测记录,系统严格保持留白,不从局部设施样本反推全国总算力。", executive_assertion_en="Selected scope lacks complete comparable observations; values remain blank without synthetic extrapolation.", causes=[], breakthrough_levers=[], blind_spots=list(series_payload.get("limitations") or [])[:2], evidence_ids=["unconfigured"], ) return StrategicPostureBrief( headline="多边算力观测态势摘要", headline_en="Multilateral Compute Observation Summary", executive_assertion="当前展示所选参与方在权威白皮书中的已核验观测值;区域汇总仅在全体成员国具备同年同口径数据时计算。", executive_assertion_en="Displaying verified whitepaper observations for selected participants without synthetic regional backfill.", causes=[], breakthrough_levers=[], blind_spots=list(series_payload.get("limitations") or [])[:3], evidence_ids=[fallback_eid], ) async def sync_curated_evidence_records(db: AsyncSession, evidence_map: dict[str, dict[str, Any]]) -> None: """Persist immutable `EvidenceRecord` rows when a real DB session is active.""" if not evidence_map or not hasattr(db, "execute") or not hasattr(db, "add"): return try: existing_ids = set( ( await db.execute( select(EvidenceRecord.id).where(EvidenceRecord.id.in_(list(evidence_map.keys()))) ) ) .scalars() .all() ) for eid, item in evidence_map.items(): if eid in existing_ids: continue serialized = json.dumps(item, sort_keys=True, ensure_ascii=False) db.add( EvidenceRecord( id=eid, source_type="curated_report", title=str(item.get("title") or eid), publisher=str(item.get("publisher") or ""), url=str(item.get("url") or ""), locator=str(item.get("locator") or ""), excerpt=str(item.get("locator") or ""), content_sha256=hashlib.sha256(serialized.encode("utf-8")).hexdigest(), published_at=str(item.get("published_at") or item.get("report_year") or ""), metadata_json={"report_year": item.get("report_year")}, ) ) except Exception as exc: logger.warning_event( "Skipping EvidenceRecord upsert on mock/non-relational session", event="ai_posture.evidence_sync.skipped", context={"error": str(exc)}, ) async def generate_or_get_compute_posture( db: AsyncSession, *, countries: list[str], mode: str, series_payload: dict[str, Any], ai_client: AIProviderClient | None = None, prefer_llm: bool = False, time_basis: str | None = None, cutoff_at: str | None = None, persist: bool = True, cancel_event: asyncio.Event | None = None, ) -> dict[str, Any]: """Return cached or freshly validated `SituationalAssessment` for compute posture.""" _raise_if_cancelled(cancel_event) effective_basis = str(time_basis or series_payload.get("time_basis") or "retrospective") effective_cutoff = cutoff_at if cutoff_at is not None else series_payload.get("cutoff_at") effective_publish_id = series_payload.get("publish_id") or series_payload.get("version") effective_published_at = series_payload.get("published_at") effective_as_of = series_payload.get("as_of") snapshot_unavailable = bool(series_payload.get("snapshot_unavailable")) basis_suffix = ( f":as_known_then:{effective_cutoff}" if effective_basis == "as_known_then" and effective_cutoff else "" ) subject_key = f"compute:{','.join(countries)}:{mode}{basis_suffix}" if snapshot_unavailable: notice = str( series_payload.get("notice") or "历史快照不完整:所选系统发布时间早于版本库基线时间,无法还原当时的系统台账。" ) brief_unavail = StrategicPostureBrief( headline="历史快照不完整", headline_en="Incomplete Historical Snapshot", executive_assertion=notice, executive_assertion_en=( "Historical snapshot incomplete: requested system publish timestamp precedes the revision baseline." ), causes=[], breakthrough_levers=[], blind_spots=[notice], evidence_ids=["snapshot_unavailable"], ) return { "id": None, "result_id": subject_key, "subject_type": "compute_posture", "subject_key": subject_key, "input_fingerprint": "snapshot_unavailable", "revision": 0, "generation_mode": "deterministic_baseline", "payload": brief_unavail.model_dump(mode="json"), "evidence_ids": [], "cache_hit": False, "time_basis": effective_basis, "cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None, "publish_id": None, "published_at": None, "as_of": effective_as_of, "snapshot_unavailable": True, "notice": notice, "usage": {}, "evidence": {}, } fingerprint = compute_posture_fingerprint( countries, mode, series_payload, time_basis=effective_basis, cutoff_at=effective_cutoff, ) evidence_map = series_payload.get("evidence") or {} fallback_cached: SituationalAssessment | None = None fallback_evidence_map: dict[str, Any] = evidence_map if hasattr(db, "execute"): try: cached_rows = ( ( await db.execute( select(SituationalAssessment) .where( SituationalAssessment.subject_type == "compute_posture", SituationalAssessment.subject_key == subject_key, SituationalAssessment.input_fingerprint == fingerprint, ) .order_by(desc(SituationalAssessment.revision), desc(SituationalAssessment.id)) .limit(5) ) ) .scalars() .all() ) cached = next( (r for r in cached_rows if getattr(r, "generation_mode", None) == "llm_verified"), cached_rows[0] if cached_rows else None, ) if isinstance(cached, SituationalAssessment) and cached.payload: cached_series = (cached.audit_meta or {}).get("frozen_series") cached_evidence_map = ( cached_series.get("evidence") if isinstance(cached_series, dict) and isinstance(cached_series.get("evidence"), dict) else evidence_map ) wants_llm_upgrade = ( prefer_llm and ai_client is not None and bool(getattr(ai_client, "service_url", "")) and bool(evidence_map) and cached.generation_mode != "llm_verified" ) if wants_llm_upgrade: fallback_cached = cached fallback_evidence_map = cached_evidence_map else: return { **cached.to_dict(), "cache_hit": True, "time_basis": effective_basis, "cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None, "publish_id": (cached.audit_meta or {}).get("publish_id") or effective_publish_id, "published_at": (cached.audit_meta or {}).get("published_at") or effective_published_at, "as_of": effective_as_of, "snapshot_unavailable": False, "usage": (cached.audit_meta or {}).get("llm_usage") or {}, "evidence": { eid: cached_evidence_map[eid] for eid in (cached.evidence_ids or []) if eid in cached_evidence_map }, } except Exception: pass generation_mode = "deterministic_baseline" frozen_series_snapshot = _freeze_json_snapshot(series_payload) audit_meta: dict[str, Any] = { "fingerprint": fingerprint, "publish_id": effective_publish_id, "published_at": effective_published_at, "as_of": effective_as_of, "time_basis": effective_basis, "cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None, "countries": list(countries), "mode": mode, "frozen_series": frozen_series_snapshot, } brief: StrategicPostureBrief | None = None llm_usage: dict[str, Any] = {} if prefer_llm and ai_client is not None and ai_client.service_url and evidence_map: _raise_if_cancelled(cancel_event) try: prompt_def = await get_effective_prompt(db, "compute.posture.brief") _raise_if_cancelled(cancel_event) effective_ai_client, thinking_arg = prepare_situational_ai_call(ai_client) compact_evidence = { eid: { "title": ev.get("title"), "publisher": ev.get("publisher"), "published_at": ev.get("published_at"), "locator": ev.get("locator"), } for eid, ev in evidence_map.items() } llm_response = await effective_ai_client.analyze( SituationalAnalysisRequest( title="中美及全球算力态势研判", objective=( f"{prompt_def.prompt}\n\n" "严格输出单个紧凑 JSON 对象(不加围栏外文字),字段结构:\n" '{"headline": str, "headline_en": str, "executive_assertion": str, ' '"executive_assertion_en": str, ' '"causes": [{"label": str, "label_en": str, "detail": str, "detail_en": str, "evidence_ids": [str]}], ' '"breakthrough_levers": [{"label": str, "label_en": str, "detail": str, "detail_en": str, "evidence_ids": [str]}], ' '"blind_spots": [str], "evidence_ids": [str]}' ), system_prompt=prompt_def.system_prompt, context={ "countries": countries, "mode": mode, "time_basis": effective_basis, "cutoff_at": effective_cutoff, "bilateral_rpi": series_payload.get("bilateral_rpi"), "denominator_attribution": series_payload.get("denominator_attribution"), "structures": series_payload.get("structures"), "innovation_summary": series_payload.get("innovation_summary"), "evidence": compact_evidence, }, constraints=[ "Output strict JSON matching StrategicPostureBrief.", "Every evidence_id must exist in context.evidence.", "Never output or chain-of-thought.", ], thinking=thinking_arg, ) ) _raise_if_cancelled(cancel_event) parsed = extract_json_object(llm_response.content) if parsed: candidate = StrategicPostureBrief.model_validate(parsed) brief = verify_brief_citations(candidate, evidence_map) generation_mode = "llm_verified" llm_usage = extract_response_usage(llm_response) audit_meta.update( { "provider": llm_response.provider, "model": llm_response.model, "thinking_block_count": len(llm_response.thinking_blocks or []), "llm_usage": llm_usage, } ) except Exception as exc: logger.warning_event( "LLM posture generation unavailable or failed citation check; falling back to deterministic baseline", event="ai_posture.llm.fallback", context={"error": str(exc)}, ) audit_meta["fallback_reason"] = str(exc) _raise_if_cancelled(cancel_event) if brief is None and fallback_cached is not None: return { **fallback_cached.to_dict(), "cache_hit": True, "time_basis": effective_basis, "cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None, "publish_id": (fallback_cached.audit_meta or {}).get("publish_id") or effective_publish_id, "published_at": (fallback_cached.audit_meta or {}).get("published_at") or effective_published_at, "as_of": effective_as_of, "snapshot_unavailable": False, "usage": {}, "evidence": { eid: fallback_evidence_map[eid] for eid in (fallback_cached.evidence_ids or []) if eid in fallback_evidence_map }, } if brief is None: brief = build_deterministic_posture_brief(series_payload) valid_eids = [eid for eid in brief.evidence_ids if eid in evidence_map] payload_json = brief.model_dump(mode="json") revision = 1 if persist and hasattr(db, "execute") and hasattr(db, "add"): try: await sync_curated_evidence_records(db, evidence_map) latest_rev = ( await db.execute( select(SituationalAssessment.revision) .where( SituationalAssessment.subject_type == "compute_posture", SituationalAssessment.subject_key == subject_key, ) .order_by(desc(SituationalAssessment.revision)) .limit(1) ) ).scalar_one_or_none() if isinstance(latest_rev, int): revision = latest_rev + 1 record = SituationalAssessment( subject_type="compute_posture", subject_key=subject_key, input_fingerprint=fingerprint, revision=revision, generation_mode=generation_mode, payload=payload_json, evidence_ids=valid_eids, audit_meta=audit_meta, ) db.add(record) await db.flush() return { **record.to_dict(), "cache_hit": False, "time_basis": effective_basis, "cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None, "publish_id": effective_publish_id, "published_at": effective_published_at, "as_of": effective_as_of, "snapshot_unavailable": False, "usage": llm_usage, "evidence": {eid: evidence_map[eid] for eid in valid_eids}, } except Exception as exc: logger.warning_event( "Posture assessment DB persistence skipped; returning validated in-memory payload", event="ai_posture.persist.skipped", context={"error": str(exc)}, ) return { "id": None, "result_id": subject_key, "subject_type": "compute_posture", "subject_key": subject_key, "input_fingerprint": fingerprint, "revision": revision, "generation_mode": generation_mode, "payload": payload_json, "evidence_ids": valid_eids, "cache_hit": False, "time_basis": effective_basis, "cutoff_at": effective_cutoff if effective_basis == "as_known_then" else None, "publish_id": effective_publish_id, "published_at": effective_published_at, "as_of": effective_as_of, "snapshot_unavailable": False, "usage": llm_usage, "evidence": {eid: evidence_map[eid] for eid in valid_eids}, }