forked from linkong/planet
431 lines
16 KiB
Python
431 lines
16 KiB
Python
"""Read-time lineage derivation and revision change context for compute observations."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
from typing import Any
|
|
|
|
from fastapi import HTTPException
|
|
from sqlalchemy import select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.enums import UserRole
|
|
from app.models.compute_configuration_revision import ComputeConfigurationRevision
|
|
from app.models.situational_assessment import ComputeEvidenceCandidate, EvidenceRecord
|
|
from app.models.user import User
|
|
from app.schemas.compute_configuration import (
|
|
ComputeConfiguration,
|
|
has_mixed_sources,
|
|
source_for,
|
|
)
|
|
from app.services.compute_catalog import PARTICIPANTS
|
|
from app.services.compute_configuration import read_configuration
|
|
from app.services.compute_revision_diff import (
|
|
COUNTRY_ZH_LABELS,
|
|
METRIC_ZH_LABELS,
|
|
format_diff_entry,
|
|
)
|
|
|
|
REVIEW_REASON_LABELS_ZH: dict[str, str] = {
|
|
"newer_authoritative_report": "更权威新版报告更新",
|
|
"corrects_prior_error": "更正历史录入误差",
|
|
"adds_missing_observation": "补充缺失年份观测",
|
|
"methodology_update": "同分母方法学修订",
|
|
"unverifiable_source": "来源无法核验",
|
|
"denominator_mismatch": "统计口径或分母不一致",
|
|
"extraction_error": "自动提取数值错误",
|
|
"superseded": "已被更新报告取代",
|
|
"duplicate": "重复候选",
|
|
}
|
|
|
|
REDACTED_ACTOR_LABEL = "已人工复核"
|
|
|
|
_REVISION_QUESTION_KEYWORDS = (
|
|
"为什么变",
|
|
"为何变",
|
|
"怎么变",
|
|
"修订",
|
|
"改了",
|
|
"更正",
|
|
"重述",
|
|
"变动原因",
|
|
"变化原因",
|
|
"why did it change",
|
|
"what changed",
|
|
"why changed",
|
|
"revised",
|
|
"restated",
|
|
"revision",
|
|
)
|
|
|
|
|
|
def is_admin_user(user: User | None) -> bool:
|
|
return bool(
|
|
user is not None
|
|
and user.role in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}
|
|
)
|
|
|
|
|
|
def is_revision_question(question: str | None) -> bool:
|
|
q = (question or "").strip().lower()
|
|
if not q:
|
|
return False
|
|
return any(kw in q for kw in _REVISION_QUESTION_KEYWORDS)
|
|
|
|
|
|
def _iso(dt: Any) -> str | None:
|
|
if isinstance(dt, datetime):
|
|
return dt.isoformat()
|
|
if isinstance(dt, str):
|
|
return dt
|
|
return None
|
|
|
|
|
|
def _source_payload(
|
|
source_id: str | None,
|
|
sources_by_id: dict[str, Any],
|
|
ev_by_id: dict[str, EvidenceRecord],
|
|
) -> dict[str, Any] | None:
|
|
if not source_id:
|
|
return None
|
|
src = sources_by_id.get(source_id)
|
|
ev = ev_by_id.get(source_id)
|
|
if src is None and ev is None:
|
|
return {"id": source_id}
|
|
published_at: str | None = None
|
|
if src is not None and getattr(src, "published_at", None) is not None:
|
|
published_at = src.published_at.isoformat()
|
|
elif ev is not None and ev.published_at is not None:
|
|
published_at = _iso(ev.published_at)
|
|
return {
|
|
"id": source_id,
|
|
"title": (src.title if src is not None else None) or (ev.title if ev is not None else source_id),
|
|
"publisher": (src.publisher if src is not None else None) or (ev.publisher if ev is not None else ""),
|
|
"url": (src.url if src is not None else None) or (ev.url if ev is not None else ""),
|
|
"locator": (src.locator if src is not None else None) or (ev.locator if ev is not None else ""),
|
|
"report_year": src.report_year if src is not None else None,
|
|
"published_at": published_at,
|
|
"excerpt": ev.excerpt if ev is not None else None,
|
|
"content_sha256": ev.content_sha256 if ev is not None else None,
|
|
"retrieved_at": _iso(ev.retrieved_at) if ev is not None else None,
|
|
}
|
|
|
|
|
|
def _match_candidate_for_diff(
|
|
candidates: list[ComputeEvidenceCandidate],
|
|
*,
|
|
metric: str,
|
|
year: int,
|
|
code: str,
|
|
) -> ComputeEvidenceCandidate | None:
|
|
for cand in candidates:
|
|
proposed = cand.proposed_payload if isinstance(cand.proposed_payload, dict) else {}
|
|
if (
|
|
str(proposed.get("metric") or "") == metric
|
|
and int(proposed.get("year") or 0) == year
|
|
and code in (proposed.get("values") or {})
|
|
):
|
|
return cand
|
|
for cand in candidates:
|
|
proposed = cand.proposed_payload if isinstance(cand.proposed_payload, dict) else {}
|
|
if str(proposed.get("metric") or "") == metric and int(proposed.get("year") or 0) == year:
|
|
return cand
|
|
return candidates[0] if len(candidates) == 1 else None
|
|
|
|
|
|
async def build_observation_lineage(
|
|
db: AsyncSession,
|
|
*,
|
|
code: str,
|
|
metric: str,
|
|
year: int,
|
|
publish_id: str | None = None,
|
|
as_of: str | None = None,
|
|
redact: bool = True,
|
|
max_revisions: int = 50,
|
|
) -> dict[str, Any]:
|
|
"""Derive full observation provenance & revision timeline at read time without a mirror table."""
|
|
norm_code = (code or "").strip().upper()
|
|
if norm_code not in PARTICIPANTS:
|
|
raise HTTPException(status_code=422, detail=f"Unknown compute participant code: {code}")
|
|
if metric not in METRIC_ZH_LABELS:
|
|
raise HTTPException(status_code=422, detail=f"Unknown compute metric: {metric}")
|
|
|
|
envelope = await read_configuration(db, as_of=as_of, publish_id=publish_id)
|
|
if envelope.get("snapshot_unavailable"):
|
|
return {
|
|
"code": norm_code,
|
|
"country_name": COUNTRY_ZH_LABELS.get(norm_code) or PARTICIPANTS[norm_code].get("name") or norm_code,
|
|
"metric": metric,
|
|
"metric_label": METRIC_ZH_LABELS[metric],
|
|
"year": year,
|
|
"period_label": None,
|
|
"publish_id": None,
|
|
"published_at": None,
|
|
"as_of": envelope.get("as_of"),
|
|
"snapshot_unavailable": True,
|
|
"notice": envelope.get("notice"),
|
|
"redacted": redact,
|
|
"current": None,
|
|
"timestamps": {
|
|
"observation_period": str(year),
|
|
"report_published_at": None,
|
|
"ingested_at": None,
|
|
"effective_published_at": None,
|
|
},
|
|
"timeline": [],
|
|
}
|
|
|
|
cfg = ComputeConfiguration.model_validate(envelope["config"])
|
|
effective_pid = str(envelope.get("publish_id") or envelope.get("revision") or "")
|
|
sources_by_id = {src.id: src for src in cfg.sources}
|
|
obs_row = next(
|
|
(obs for obs in cfg.observations if obs.metric == metric and obs.year == year),
|
|
None,
|
|
)
|
|
current_value = float(obs_row.values[norm_code]) if (obs_row is not None and norm_code in obs_row.values) else None
|
|
current_source_id: str | None = None
|
|
if obs_row is not None:
|
|
current_source_id = source_for(obs_row, norm_code) if norm_code in obs_row.values else obs_row.source_id
|
|
|
|
revisions: list[ComputeConfigurationRevision] = []
|
|
if hasattr(db, "execute"):
|
|
target_rev: ComputeConfigurationRevision | None = None
|
|
if effective_pid:
|
|
target_rev = (
|
|
await db.execute(
|
|
select(ComputeConfigurationRevision).where(
|
|
ComputeConfigurationRevision.publish_id == effective_pid
|
|
)
|
|
)
|
|
).scalar_one_or_none()
|
|
stmt = select(ComputeConfigurationRevision)
|
|
if target_rev is not None:
|
|
stmt = stmt.where(ComputeConfigurationRevision.id <= target_rev.id)
|
|
stmt = stmt.order_by(ComputeConfigurationRevision.id.desc()).limit(max_revisions)
|
|
revisions = list((await db.execute(stmt)).scalars().all())
|
|
|
|
candidate_ids: set[int] = set()
|
|
referenced_source_ids: set[str] = set()
|
|
if current_source_id:
|
|
referenced_source_ids.add(current_source_id)
|
|
|
|
matched_pairs: list[tuple[ComputeConfigurationRevision, dict[str, Any]]] = []
|
|
for rev in revisions:
|
|
for entry in rev.diff_summary or []:
|
|
if not isinstance(entry, dict):
|
|
continue
|
|
if (
|
|
entry.get("kind") == "observation_value"
|
|
and str(entry.get("metric") or "") == metric
|
|
and int(entry.get("year") or 0) == year
|
|
and str(entry.get("code") or "").upper() == norm_code
|
|
):
|
|
matched_pairs.append((rev, entry))
|
|
for cid in rev.source_candidate_ids or []:
|
|
if isinstance(cid, int):
|
|
candidate_ids.add(cid)
|
|
for sid_key in ("old_source_id", "new_source_id"):
|
|
sid_val = entry.get(sid_key)
|
|
if isinstance(sid_val, str) and sid_val:
|
|
referenced_source_ids.add(sid_val)
|
|
|
|
candidates_by_id: dict[int, ComputeEvidenceCandidate] = {}
|
|
ev_by_id: dict[str, EvidenceRecord] = {}
|
|
if hasattr(db, "execute"):
|
|
if candidate_ids:
|
|
cand_rows = (
|
|
await db.execute(
|
|
select(ComputeEvidenceCandidate).where(
|
|
ComputeEvidenceCandidate.id.in_(sorted(candidate_ids))
|
|
)
|
|
)
|
|
).scalars().all()
|
|
candidates_by_id = {c.id: c for c in cand_rows}
|
|
if referenced_source_ids:
|
|
ev_rows = (
|
|
await db.execute(
|
|
select(EvidenceRecord).where(
|
|
EvidenceRecord.id.in_(sorted(referenced_source_ids))
|
|
)
|
|
)
|
|
).scalars().all()
|
|
ev_by_id = {ev.id: ev for ev in ev_rows}
|
|
|
|
timeline: list[dict[str, Any]] = []
|
|
latest_ingested_at: str | None = None
|
|
latest_effective_published_at: str | None = None
|
|
for rev, entry in matched_pairs:
|
|
rev_candidates = [
|
|
candidates_by_id[cid]
|
|
for cid in (rev.source_candidate_ids or [])
|
|
if isinstance(cid, int) and cid in candidates_by_id
|
|
]
|
|
cand = _match_candidate_for_diff(
|
|
rev_candidates, metric=metric, year=year, code=norm_code
|
|
)
|
|
reason_code = cand.review_reason_code if cand is not None else None
|
|
reason_label = REVIEW_REASON_LABELS_ZH.get(reason_code) if reason_code else None
|
|
cand_created = _iso(cand.created_at) if cand is not None else None
|
|
rev_pub_at = _iso(rev.published_at)
|
|
if latest_effective_published_at is None and rev_pub_at:
|
|
latest_effective_published_at = rev_pub_at
|
|
if latest_ingested_at is None and cand_created:
|
|
latest_ingested_at = cand_created
|
|
|
|
old_src_id = entry.get("old_source_id")
|
|
new_src_id = entry.get("new_source_id")
|
|
item: dict[str, Any] = {
|
|
"revision_id": rev.id,
|
|
"publish_id": rev.publish_id,
|
|
"published_at": rev_pub_at,
|
|
"action": rev.action,
|
|
"old_value": entry.get("old_value"),
|
|
"new_value": entry.get("new_value"),
|
|
"delta": entry.get("delta"),
|
|
"change_kind": entry.get("change_kind"),
|
|
"summary": format_diff_entry(entry),
|
|
"old_source_id": old_src_id,
|
|
"new_source_id": new_src_id,
|
|
"old_source": _source_payload(old_src_id, sources_by_id, ev_by_id) if old_src_id else None,
|
|
"new_source": _source_payload(new_src_id, sources_by_id, ev_by_id) if new_src_id else None,
|
|
"candidate_id": cand.id if cand is not None else None,
|
|
"candidate_created_at": cand_created,
|
|
"review_reason_code": reason_code,
|
|
"review_reason_label": reason_label,
|
|
"review_reason": None if redact else (cand.review_reason if cand is not None else None),
|
|
"reviewed_by": (
|
|
(REDACTED_ACTOR_LABEL if (cand is not None and cand.reviewed_by) else None)
|
|
if redact
|
|
else (cand.reviewed_by if cand is not None else None)
|
|
),
|
|
"reviewed_at": _iso(cand.reviewed_at) if cand is not None else None,
|
|
"publish_note": None if redact else (rev.publish_note or None),
|
|
"published_by_name": (
|
|
(REDACTED_ACTOR_LABEL if rev.published_by_name else None)
|
|
if redact
|
|
else rev.published_by_name
|
|
),
|
|
}
|
|
if not redact:
|
|
item["published_by_role"] = rev.published_by_role
|
|
timeline.append(item)
|
|
|
|
current_source = _source_payload(current_source_id, sources_by_id, ev_by_id)
|
|
effective_published_at = latest_effective_published_at or envelope.get("published_at")
|
|
return {
|
|
"code": norm_code,
|
|
"country_name": COUNTRY_ZH_LABELS.get(norm_code) or PARTICIPANTS[norm_code].get("name") or norm_code,
|
|
"metric": metric,
|
|
"metric_label": METRIC_ZH_LABELS[metric],
|
|
"year": year,
|
|
"period_label": obs_row.period_label if obs_row is not None else None,
|
|
"publish_id": effective_pid,
|
|
"published_at": envelope.get("published_at"),
|
|
"as_of": envelope.get("as_of"),
|
|
"snapshot_unavailable": False,
|
|
"redacted": redact,
|
|
"current": {
|
|
"value": current_value,
|
|
"unit": "EFlops" if metric == "absolute" else "%",
|
|
"source_id": current_source_id,
|
|
"mixed_sources": has_mixed_sources(obs_row) if obs_row is not None else False,
|
|
"source": current_source,
|
|
},
|
|
"timestamps": {
|
|
"observation_period": (
|
|
obs_row.period_label
|
|
if (obs_row is not None and obs_row.period_label)
|
|
else str(year)
|
|
),
|
|
"report_published_at": (current_source or {}).get("published_at"),
|
|
"ingested_at": latest_ingested_at,
|
|
"effective_published_at": effective_published_at,
|
|
},
|
|
"timeline": timeline,
|
|
}
|
|
|
|
|
|
async def build_revision_change_context(
|
|
db: AsyncSession,
|
|
*,
|
|
publish_id: str | None = None,
|
|
redact: bool = True,
|
|
) -> dict[str, Any] | None:
|
|
"""Return current/pinned revision diff & linked candidate review rationale for Copilot context."""
|
|
if not hasattr(db, "execute"):
|
|
return None
|
|
rev_row: ComputeConfigurationRevision | None = None
|
|
if publish_id:
|
|
rev_row = (
|
|
await db.execute(
|
|
select(ComputeConfigurationRevision).where(
|
|
ComputeConfigurationRevision.publish_id == publish_id
|
|
)
|
|
)
|
|
).scalar_one_or_none()
|
|
if rev_row is None:
|
|
rev_row = (
|
|
await db.execute(
|
|
select(ComputeConfigurationRevision)
|
|
.order_by(ComputeConfigurationRevision.id.desc())
|
|
.limit(1)
|
|
)
|
|
).scalar_one_or_none()
|
|
if rev_row is None:
|
|
return None
|
|
|
|
cand_ids = [cid for cid in (rev_row.source_candidate_ids or []) if isinstance(cid, int)]
|
|
candidates: list[ComputeEvidenceCandidate] = []
|
|
if cand_ids:
|
|
candidates = list(
|
|
(
|
|
await db.execute(
|
|
select(ComputeEvidenceCandidate).where(
|
|
ComputeEvidenceCandidate.id.in_(cand_ids)
|
|
)
|
|
)
|
|
).scalars().all()
|
|
)
|
|
|
|
diff_items: list[dict[str, Any]] = []
|
|
for entry in rev_row.diff_summary or []:
|
|
if not isinstance(entry, dict):
|
|
continue
|
|
item = {
|
|
**entry,
|
|
"summary": format_diff_entry(entry),
|
|
}
|
|
diff_items.append(item)
|
|
|
|
candidate_reasons: list[dict[str, Any]] = []
|
|
for cand in candidates:
|
|
code = cand.review_reason_code
|
|
reason_label = REVIEW_REASON_LABELS_ZH.get(code) if code else None
|
|
src_payload = cand.source_payload if isinstance(cand.source_payload, dict) else {}
|
|
prop_payload = cand.proposed_payload if isinstance(cand.proposed_payload, dict) else {}
|
|
candidate_reasons.append(
|
|
{
|
|
"candidate_id": cand.id,
|
|
"source_id": src_payload.get("id") or prop_payload.get("source_id"),
|
|
"source_title": src_payload.get("title") or "",
|
|
"review_reason_code": code,
|
|
"review_reason_label": reason_label,
|
|
"review_reason": None if redact else (cand.review_reason or None),
|
|
"reviewed_by": (REDACTED_ACTOR_LABEL if cand.reviewed_by else None) if redact else cand.reviewed_by,
|
|
"reviewed_at": _iso(cand.reviewed_at),
|
|
}
|
|
)
|
|
|
|
return {
|
|
"revision_id": rev_row.id,
|
|
"publish_id": rev_row.publish_id,
|
|
"parent_publish_id": rev_row.parent_publish_id,
|
|
"published_at": _iso(rev_row.published_at),
|
|
"action": rev_row.action,
|
|
"publish_note": None if redact else (rev_row.publish_note or None),
|
|
"diff_summary": diff_items,
|
|
"candidate_reasons": candidate_reasons,
|
|
"redacted": redact,
|
|
}
|