forked from linkong/planet
759 lines
34 KiB
Python
759 lines
34 KiB
Python
"""M4 tests: read-time lineage derivation, redaction, public revisions, Copilot same-source, and 9-point E2E."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import copy
|
|
from datetime import UTC, datetime, timedelta
|
|
import json
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from unittest.mock import AsyncMock, patch
|
|
|
|
import httpx
|
|
import pytest
|
|
from sqlalchemy import create_engine, select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.api.v1 import compute_intelligence as ci_api
|
|
from app.core.enums import UserRole
|
|
from app.core.security import create_access_token, get_password_hash
|
|
from app.db.session import get_db
|
|
from app.main import app
|
|
from app.models.compute_configuration_revision import ComputeConfigurationRevision
|
|
from app.models.situational_assessment import (
|
|
ComputeEvidenceCandidate,
|
|
EvidenceRecord,
|
|
InvestigationSession,
|
|
SituationalAssessment,
|
|
StagePresentation,
|
|
TopicWatch,
|
|
WorkflowRun,
|
|
)
|
|
from app.models.system_log import AuditLog
|
|
from app.models.system_setting import SystemSetting
|
|
from app.models.user import User
|
|
from app.services.compute_configuration import ensure_compute_revision_baseline
|
|
|
|
|
|
FIXTURE_PATH = Path(__file__).parent / "fixtures" / "compute_revision_case.json"
|
|
|
|
|
|
async def _build_m4_harness():
|
|
engine = create_engine("sqlite://", connect_args={"check_same_thread": False})
|
|
for model in (
|
|
User,
|
|
SystemSetting,
|
|
AuditLog,
|
|
ComputeConfigurationRevision,
|
|
ComputeEvidenceCandidate,
|
|
EvidenceRecord,
|
|
SituationalAssessment,
|
|
StagePresentation,
|
|
TopicWatch,
|
|
InvestigationSession,
|
|
WorkflowRun,
|
|
):
|
|
model.__table__.create(engine)
|
|
|
|
def _new_db():
|
|
raw = Session(engine)
|
|
|
|
def _add_all(items):
|
|
raw.add_all(items)
|
|
|
|
return SimpleNamespace(
|
|
execute=AsyncMock(side_effect=raw.execute),
|
|
add=raw.add,
|
|
add_all=_add_all,
|
|
delete=AsyncMock(side_effect=raw.delete),
|
|
flush=AsyncMock(side_effect=raw.flush),
|
|
commit=AsyncMock(side_effect=raw.commit),
|
|
rollback=AsyncMock(side_effect=raw.rollback),
|
|
refresh=AsyncMock(side_effect=raw.refresh),
|
|
close=raw.close,
|
|
bind=engine,
|
|
)
|
|
|
|
init_db = _new_db()
|
|
try:
|
|
await ensure_compute_revision_baseline(init_db)
|
|
admin = User(
|
|
username="admin_m4",
|
|
email="admin_m4@planet.local",
|
|
password_hash=get_password_hash("AdminPass123!"),
|
|
role=UserRole.ADMIN.value,
|
|
is_active=True,
|
|
)
|
|
viewer = User(
|
|
username="viewer_m4",
|
|
email="viewer_m4@planet.local",
|
|
password_hash=get_password_hash("ViewerPass123!"),
|
|
role=UserRole.VIEWER.value,
|
|
gatekeeper_groups=["api_access"],
|
|
is_active=True,
|
|
)
|
|
init_db.add_all([admin, viewer])
|
|
await init_db.commit()
|
|
await init_db.refresh(admin)
|
|
await init_db.refresh(viewer)
|
|
admin_token = create_access_token({"sub": str(admin.id)})
|
|
viewer_token = create_access_token({"sub": str(viewer.id)})
|
|
finally:
|
|
init_db.close()
|
|
|
|
async def override_get_db():
|
|
db = _new_db()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
app.dependency_overrides[get_db] = override_get_db
|
|
return engine, _new_db, admin_token, viewer_token
|
|
|
|
|
|
def _load_m0_case() -> dict:
|
|
return json.loads(FIXTURE_PATH.read_text(encoding="utf-8"))
|
|
|
|
|
|
async def _publish_m0_revision_via_http(
|
|
client: httpx.AsyncClient,
|
|
admin_headers: dict[str, str],
|
|
m0: dict,
|
|
*,
|
|
review_reason: str = "Epoch AI 2026-11-12 官方变更日志将约 21.6 万颗 H20 由 2025 重分配至 2024,中国份额修订为 9.9%。",
|
|
publish_note: str = "同为 Epoch AI 累计芯片算力流入全球分母,仅将中国 2025 重述为 9.9%,美国保持原报告 72%。",
|
|
) -> tuple[str, str, int]:
|
|
"""Extract, approve, and publish the real Epoch AI M0 case; returns (rev_a, rev_b, candidate_id)."""
|
|
cfg_before = (
|
|
await client.get("/api/v1/data-products/compute/configuration", headers=admin_headers)
|
|
).json()
|
|
rev_a = cfg_before["publish_id"]
|
|
|
|
new_meta = m0["new"]
|
|
extract_resp = await client.post(
|
|
"/api/v1/situational-awareness/candidates/extract",
|
|
headers=admin_headers,
|
|
json={
|
|
"year": m0["year"],
|
|
"excerpt": new_meta["excerpt"],
|
|
"source_id": new_meta["source_id"],
|
|
"source_title": new_meta["title"],
|
|
"source_url": new_meta["url"],
|
|
"publisher": new_meta["publisher"],
|
|
"locator": new_meta["locator"],
|
|
"published_at": new_meta["published_at"],
|
|
"report_year": new_meta["report_year"],
|
|
"period_label": m0["period_label"],
|
|
},
|
|
)
|
|
assert extract_resp.status_code == 200, extract_resp.text
|
|
extract_body = extract_resp.json()
|
|
assert len(extract_body["items"]) == 1
|
|
cand = extract_body["items"][0]
|
|
cand_id = cand["id"]
|
|
|
|
review_resp = await client.post(
|
|
f"/api/v1/situational-awareness/candidates/{cand_id}/review",
|
|
headers=admin_headers,
|
|
json={
|
|
"decision": "approved",
|
|
"reason_code": "newer_authoritative_report",
|
|
"reason": review_reason,
|
|
},
|
|
)
|
|
assert review_resp.status_code == 200, review_resp.text
|
|
|
|
cfg_next = copy.deepcopy(cfg_before["config"])
|
|
cfg_next["sources"].append(
|
|
{
|
|
"id": new_meta["source_id"],
|
|
"title": new_meta["title"],
|
|
"publisher": new_meta["publisher"],
|
|
"url": new_meta["url"],
|
|
"locator": new_meta["locator"],
|
|
"report_year": new_meta["report_year"],
|
|
"published_at": new_meta["published_at"],
|
|
}
|
|
)
|
|
for obs in cfg_next["observations"]:
|
|
if obs["metric"] == m0["metric"] and obs["year"] == m0["year"]:
|
|
obs["values"]["CN"] = float(new_meta["values"]["CN"])
|
|
obs["value_sources"] = {"CN": new_meta["source_id"]}
|
|
break
|
|
|
|
pub_resp = await client.put(
|
|
"/api/v1/data-products/compute/configuration",
|
|
headers=admin_headers,
|
|
json={
|
|
"revision": cfg_before["revision"],
|
|
"config": cfg_next,
|
|
"publish_note": publish_note,
|
|
"source_candidate_ids": [cand_id],
|
|
},
|
|
)
|
|
assert pub_resp.status_code == 200, pub_resp.text
|
|
rev_b = pub_resp.json()["publish_id"]
|
|
return rev_a, rev_b, cand_id
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_m4_public_revisions_and_lineage_redaction():
|
|
engine, _sf, admin_token, viewer_token = await _build_m4_harness()
|
|
m0 = _load_m0_case()
|
|
admin_headers = {"Authorization": f"Bearer {admin_token}"}
|
|
viewer_headers = {"Authorization": f"Bearer {viewer_token}"}
|
|
|
|
try:
|
|
with patch.object(ci_api, "_broadcast_compute_configuration_update", new=AsyncMock()):
|
|
async with httpx.AsyncClient(
|
|
transport=httpx.ASGITransport(app=app),
|
|
base_url="http://test",
|
|
) as client:
|
|
raw_reason = "内部核验备注:Epoch AI 2026-11-12 修订了 H20 发货年份归属,CN 降为 9.9%。"
|
|
raw_note = "内部发布说明:保持同分母仅更新中国 2025 芯片流向占比。"
|
|
_rev_a, rev_b, _cand_id = await _publish_m0_revision_via_http(
|
|
client,
|
|
admin_headers,
|
|
m0,
|
|
review_reason=raw_reason,
|
|
publish_note=raw_note,
|
|
)
|
|
|
|
# 1. Public revisions endpoint redacts raw publish_note and actor name
|
|
pub_revs = await client.get("/api/v1/data-products/compute/revisions/public?limit=10")
|
|
assert pub_revs.status_code == 200
|
|
pub_items = pub_revs.json()["items"]
|
|
assert len(pub_items) >= 2
|
|
latest_pub = pub_items[0]
|
|
assert latest_pub["publish_id"] == rev_b
|
|
assert "publish_note" not in latest_pub
|
|
assert "published_by_name" not in latest_pub
|
|
assert "published_by_role" not in latest_pub
|
|
assert latest_pub["summary"]
|
|
assert raw_note not in latest_pub["summary"]
|
|
|
|
# Admin revisions endpoint exposes full note & actor
|
|
adm_revs = await client.get(
|
|
"/api/v1/data-products/compute/revisions?limit=10",
|
|
headers=admin_headers,
|
|
)
|
|
assert adm_revs.status_code == 200
|
|
latest_adm = adm_revs.json()["items"][0]
|
|
assert latest_adm["publish_note"] == raw_note
|
|
assert latest_adm["published_by_name"] == "admin_m4"
|
|
assert latest_adm["published_by_role"] == "admin"
|
|
|
|
# Viewer blocked on admin revisions
|
|
viewer_revs = await client.get(
|
|
"/api/v1/data-products/compute/revisions",
|
|
headers=viewer_headers,
|
|
)
|
|
assert viewer_revs.status_code == 403
|
|
|
|
# 2. Public lineage on CN 2025 chip_inflow_share -> redacted
|
|
cn_pub_resp = await client.get(
|
|
"/api/v1/data-products/compute/lineage",
|
|
params={"code": "CN", "metric": "chip_inflow_share", "year": 2025},
|
|
)
|
|
assert cn_pub_resp.status_code == 200
|
|
cn_pub = cn_pub_resp.json()
|
|
assert cn_pub["redacted"] is True
|
|
assert cn_pub["publish_id"] == rev_b
|
|
assert cn_pub["current"]["value"] == 9.9
|
|
assert cn_pub["current"]["source"]["id"] == "epoch-chip-imports-2026-11"
|
|
assert cn_pub["current"]["source"]["published_at"] == "2026-11-12"
|
|
assert cn_pub["current"]["source"]["locator"] == m0["new"]["locator"]
|
|
assert len(cn_pub["current"]["source"]["content_sha256"]) == 64
|
|
assert "9.9%" in cn_pub["current"]["source"]["excerpt"]
|
|
assert cn_pub["timestamps"]["observation_period"] == "2025"
|
|
assert cn_pub["timestamps"]["report_published_at"] == "2026-11-12"
|
|
assert cn_pub["timestamps"]["ingested_at"] is not None
|
|
assert cn_pub["timestamps"]["effective_published_at"] is not None
|
|
|
|
assert len(cn_pub["timeline"]) == 1
|
|
t0_pub = cn_pub["timeline"][0]
|
|
assert t0_pub["old_value"] == 11.0
|
|
assert t0_pub["new_value"] == 9.9
|
|
assert t0_pub["delta"] == -1.1
|
|
assert t0_pub["change_kind"] == "historical_revision"
|
|
assert t0_pub["review_reason_code"] == "newer_authoritative_report"
|
|
assert t0_pub["review_reason_label"] == "更权威新版报告更新"
|
|
assert t0_pub["review_reason"] is None
|
|
assert t0_pub["publish_note"] is None
|
|
assert t0_pub["reviewed_by"] == "已人工复核"
|
|
assert t0_pub["published_by_name"] == "已人工复核"
|
|
assert "published_by_role" not in t0_pub
|
|
assert raw_reason not in json.dumps(cn_pub, ensure_ascii=False)
|
|
assert raw_note not in json.dumps(cn_pub, ensure_ascii=False)
|
|
assert "admin_m4" not in json.dumps(cn_pub, ensure_ascii=False)
|
|
|
|
# 3. Logged-in viewer ALSO gets redacted lineage
|
|
cn_viewer = (
|
|
await client.get(
|
|
"/api/v1/data-products/compute/lineage",
|
|
params={"code": "CN", "metric": "chip_inflow_share", "year": 2025},
|
|
headers=viewer_headers,
|
|
)
|
|
).json()
|
|
assert cn_viewer["redacted"] is True
|
|
assert cn_viewer["timeline"][0]["reviewed_by"] == "已人工复核"
|
|
assert cn_viewer["timeline"][0]["review_reason"] is None
|
|
|
|
# 4. Logged-in admin sees full reviewer username, raw reason & publish_note
|
|
cn_adm = (
|
|
await client.get(
|
|
"/api/v1/data-products/compute/lineage",
|
|
params={"code": "CN", "metric": "chip_inflow_share", "year": 2025},
|
|
headers=admin_headers,
|
|
)
|
|
).json()
|
|
assert cn_adm["redacted"] is False
|
|
t0_adm = cn_adm["timeline"][0]
|
|
assert t0_adm["reviewed_by"] == "admin_m4"
|
|
assert t0_adm["review_reason"] == raw_reason
|
|
assert t0_adm["publish_note"] == raw_note
|
|
assert t0_adm["published_by_name"] == "admin_m4"
|
|
assert t0_adm["published_by_role"] == "admin"
|
|
|
|
# 5. US unchanged value still cites original report (epoch-chip-imports-2026)
|
|
us_pub = (
|
|
await client.get(
|
|
"/api/v1/data-products/compute/lineage",
|
|
params={"code": "US", "metric": "chip_inflow_share", "year": 2025},
|
|
)
|
|
).json()
|
|
assert us_pub["current"]["value"] == 72.0
|
|
assert us_pub["current"]["source_id"] == "epoch-chip-imports-2026"
|
|
assert us_pub["current"]["source"]["id"] == "epoch-chip-imports-2026"
|
|
assert us_pub["timeline"] == []
|
|
assert us_pub["timestamps"]["ingested_at"] is None
|
|
finally:
|
|
app.dependency_overrides.clear()
|
|
engine.dispose()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_m4_copilot_same_source_as_of_and_why_changed():
|
|
engine, _sf, admin_token, _viewer_token = await _build_m4_harness()
|
|
m0 = _load_m0_case()
|
|
admin_headers = {"Authorization": f"Bearer {admin_token}"}
|
|
|
|
try:
|
|
with patch.object(ci_api, "_broadcast_compute_configuration_update", new=AsyncMock()):
|
|
async with httpx.AsyncClient(
|
|
transport=httpx.ASGITransport(app=app),
|
|
base_url="http://test",
|
|
) as client:
|
|
raw_reason = "敏感复核原话:依据 Epoch AI 2026-11-12 勘误重述 CN=9.9%。"
|
|
rev_a, rev_b, _cand_id = await _publish_m0_revision_via_http(
|
|
client,
|
|
admin_headers,
|
|
m0,
|
|
review_reason=raw_reason,
|
|
)
|
|
|
|
# 1. Create public Copilot session pinned to current post-revision rev_b
|
|
sess_resp = await client.post(
|
|
"/api/v1/situational-awareness/sessions",
|
|
json={
|
|
"domain": "compute",
|
|
"selected_codes": ["CN", "US"],
|
|
"mode": "chip_inflow_share",
|
|
"focus_year": 2025,
|
|
"publish_id": rev_b,
|
|
},
|
|
)
|
|
assert sess_resp.status_code == 200, sess_resp.text
|
|
sess = sess_resp.json()
|
|
sess_id = sess["id"]
|
|
sess_headers = {"X-Planet-Session-Token": sess["session_token"]}
|
|
|
|
# Turn 1: overview under rev_b
|
|
turn_b = await client.post(
|
|
f"/api/v1/situational-awareness/sessions/{sess_id}/turns",
|
|
headers=sess_headers,
|
|
json={
|
|
"question": "当前中美芯片流向份额是多少?",
|
|
"mode": "chip_inflow_share",
|
|
"focus_year": 2025,
|
|
"publish_id": rev_b,
|
|
},
|
|
)
|
|
assert turn_b.status_code == 200, turn_b.text
|
|
tb = turn_b.json()
|
|
assert tb["view_spec"]["publish_id"] == rev_b
|
|
assert tb["view_spec"]["mode"] == "chip_inflow_share"
|
|
assert tb["view_spec"]["focus_year"] == 2025
|
|
assert "9.9%" in tb["reply"]["answer_markdown"]
|
|
assert "epoch-chip-imports-2026-11" in tb["evidence"]
|
|
|
|
# Turn 2: follow-up "这次为什么变了" under rev_b (public tier -> redacted, same publish_id evidence)
|
|
turn_why = await client.post(
|
|
f"/api/v1/situational-awareness/sessions/{sess_id}/turns",
|
|
headers=sess_headers,
|
|
json={
|
|
"question": "这次为什么变了?",
|
|
"mode": "chip_inflow_share",
|
|
"focus_year": 2025,
|
|
"publish_id": rev_b,
|
|
},
|
|
)
|
|
assert turn_why.status_code == 200, turn_why.text
|
|
tw = turn_why.json()
|
|
assert tw["view_spec"]["publish_id"] == rev_b
|
|
ans_why = tw["reply"]["answer_markdown"]
|
|
assert "9.9" in ans_why and "11" in ans_why
|
|
assert "历史" in ans_why
|
|
assert "更权威新版报告更新" in ans_why
|
|
assert raw_reason not in ans_why
|
|
for eid in tw["reply"]["evidence_ids"]:
|
|
assert eid in tw["evidence"]
|
|
|
|
# Turn 3: switch back to pre-revision rev_a -> old values (11%) & old evidence
|
|
turn_a = await client.post(
|
|
f"/api/v1/situational-awareness/sessions/{sess_id}/turns",
|
|
headers=sess_headers,
|
|
json={
|
|
"question": "切回修订前的中美芯片流向份额对照",
|
|
"mode": "chip_inflow_share",
|
|
"focus_year": 2025,
|
|
"publish_id": rev_a,
|
|
},
|
|
)
|
|
assert turn_a.status_code == 200, turn_a.text
|
|
ta = turn_a.json()
|
|
assert ta["view_spec"]["publish_id"] == rev_a
|
|
assert ("11%" in ta["reply"]["answer_markdown"] or "11.0%" in ta["reply"]["answer_markdown"])
|
|
assert "9.9%" not in ta["reply"]["answer_markdown"]
|
|
assert "epoch-chip-imports-2026" in ta["evidence"]
|
|
assert "epoch-chip-imports-2026-11" not in ta["evidence"]
|
|
|
|
# Turn 4: as_of earlier than baseline -> snapshot_unavailable notice
|
|
turn_pre = await client.post(
|
|
f"/api/v1/situational-awareness/sessions/{sess_id}/turns",
|
|
headers=sess_headers,
|
|
json={
|
|
"question": "查看 2020 年历史版本算力份额",
|
|
"mode": "chip_inflow_share",
|
|
"focus_year": 2025,
|
|
"as_of": "2020-01-01T00:00:00Z",
|
|
},
|
|
)
|
|
assert turn_pre.status_code == 200, turn_pre.text
|
|
tp = turn_pre.json()
|
|
assert tp["view_spec"]["replay_supported"] is False
|
|
assert tp["view_spec"]["publish_id"] is None
|
|
assert "历史快照不完整" in tp["reply"]["answer_markdown"]
|
|
finally:
|
|
app.dependency_overrides.clear()
|
|
engine.dispose()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_m4_end_to_end_all_9_acceptance_checks():
|
|
"""Verify all 9 Phase 1 acceptance criteria (Plan §7.5) with the real Epoch AI M0 case."""
|
|
engine, session_factory, admin_token, viewer_token = await _build_m4_harness()
|
|
m0 = _load_m0_case()
|
|
admin_headers = {"Authorization": f"Bearer {admin_token}"}
|
|
viewer_headers = {"Authorization": f"Bearer {viewer_token}"}
|
|
|
|
try:
|
|
with patch.object(ci_api, "_broadcast_compute_configuration_update", new=AsyncMock()):
|
|
async with httpx.AsyncClient(
|
|
transport=httpx.ASGITransport(app=app),
|
|
base_url="http://test",
|
|
) as client:
|
|
# ── Check 1: 修订识别 ──
|
|
new_meta = m0["new"]
|
|
ext1 = await client.post(
|
|
"/api/v1/situational-awareness/candidates/extract",
|
|
headers=admin_headers,
|
|
json={
|
|
"year": m0["year"],
|
|
"excerpt": new_meta["excerpt"],
|
|
"source_id": new_meta["source_id"],
|
|
"source_title": new_meta["title"],
|
|
"source_url": new_meta["url"],
|
|
"publisher": new_meta["publisher"],
|
|
"locator": new_meta["locator"],
|
|
"published_at": new_meta["published_at"],
|
|
"report_year": new_meta["report_year"],
|
|
},
|
|
)
|
|
assert ext1.status_code == 200
|
|
cand_ok = ext1.json()["items"][0]
|
|
comp = cand_ok["comparison"]
|
|
assert comp["has_historical_revision"] is True
|
|
assert comp["metric"] == "chip_inflow_share"
|
|
assert comp["denominator"] == "ai_chip_inflow"
|
|
assert comp["codes"]["CN"]["old_value"] == 11.0
|
|
assert comp["codes"]["CN"]["new_value"] == 9.9
|
|
assert comp["codes"]["CN"]["delta"] == -1.1
|
|
assert comp["codes"]["CN"]["change_kind"] == "historical_revision"
|
|
assert cand_ok["source_payload"]["locator"] == new_meta["locator"]
|
|
|
|
# Duplicate extraction does NOT create a new candidate (Check 3 dedupe part)
|
|
ext_dup = await client.post(
|
|
"/api/v1/situational-awareness/candidates/extract",
|
|
headers=admin_headers,
|
|
json={
|
|
"year": m0["year"],
|
|
"excerpt": new_meta["excerpt"],
|
|
"source_id": new_meta["source_id"],
|
|
"source_title": new_meta["title"],
|
|
"source_url": new_meta["url"],
|
|
"publisher": new_meta["publisher"],
|
|
"locator": new_meta["locator"],
|
|
"published_at": new_meta["published_at"],
|
|
"report_year": new_meta["report_year"],
|
|
},
|
|
)
|
|
assert ext_dup.status_code == 200
|
|
assert ext_dup.json()["items"][0]["duplicate"] is True
|
|
assert ext_dup.json()["items"][0]["id"] == cand_ok["id"]
|
|
|
|
# ── Check 2: 人工决策留痕 + viewer 403 ──
|
|
# Extract a second candidate to reject
|
|
ext_rej = await client.post(
|
|
"/api/v1/situational-awareness/candidates/extract",
|
|
headers=admin_headers,
|
|
json={
|
|
"year": 2024,
|
|
"excerpt": "2024年,美国全球算力份额为45%,中国全球算力份额为22%。",
|
|
"source_id": "unverified-blog-2026",
|
|
"source_title": "Unverified Blog",
|
|
"source_url": "https://example.invalid/blog",
|
|
"publisher": "Unknown",
|
|
"locator": "Paragraph 1",
|
|
},
|
|
)
|
|
assert ext_rej.status_code == 200
|
|
rej_id = ext_rej.json()["items"][0]["id"]
|
|
|
|
# Viewer gets 403 on review and publish
|
|
assert (
|
|
await client.post(
|
|
f"/api/v1/situational-awareness/candidates/{cand_ok['id']}/review",
|
|
headers=viewer_headers,
|
|
json={
|
|
"decision": "approved",
|
|
"reason_code": "newer_authoritative_report",
|
|
"reason": "Viewer attempt",
|
|
},
|
|
)
|
|
).status_code == 403
|
|
cfg_a = (
|
|
await client.get("/api/v1/data-products/compute/configuration", headers=admin_headers)
|
|
).json()
|
|
assert (
|
|
await client.put(
|
|
"/api/v1/data-products/compute/configuration",
|
|
headers=viewer_headers,
|
|
json={"revision": cfg_a["revision"], "config": cfg_a["config"]},
|
|
)
|
|
).status_code == 403
|
|
|
|
# Admin rejects invalid candidate with recorded reason
|
|
rej_resp = await client.post(
|
|
f"/api/v1/situational-awareness/candidates/{rej_id}/review",
|
|
headers=admin_headers,
|
|
json={
|
|
"decision": "rejected",
|
|
"reason_code": "unverifiable_source",
|
|
"reason": "博客二手引用无法核验原始口径与分母。",
|
|
},
|
|
)
|
|
assert rej_resp.status_code == 200
|
|
assert rej_resp.json()["review_reason_code"] == "unverifiable_source"
|
|
assert "无法核验" in rej_resp.json()["review_reason"]
|
|
|
|
# Admin approves real M0 candidate & publishes rev B
|
|
appr_resp = await client.post(
|
|
f"/api/v1/situational-awareness/candidates/{cand_ok['id']}/review",
|
|
headers=admin_headers,
|
|
json={
|
|
"decision": "approved",
|
|
"reason_code": "newer_authoritative_report",
|
|
"reason": "Epoch AI 官方 2026-11-12 Changelog 明确修订 CN=9.9%。",
|
|
},
|
|
)
|
|
assert appr_resp.status_code == 200
|
|
|
|
cfg_b_payload = copy.deepcopy(cfg_a["config"])
|
|
cfg_b_payload["sources"].append(
|
|
{
|
|
"id": new_meta["source_id"],
|
|
"title": new_meta["title"],
|
|
"publisher": new_meta["publisher"],
|
|
"url": new_meta["url"],
|
|
"locator": new_meta["locator"],
|
|
"report_year": new_meta["report_year"],
|
|
"published_at": new_meta["published_at"],
|
|
}
|
|
)
|
|
for obs in cfg_b_payload["observations"]:
|
|
if obs["metric"] == "chip_inflow_share" and obs["year"] == 2025:
|
|
obs["values"]["CN"] = 9.9
|
|
obs["value_sources"] = {"CN": new_meta["source_id"]}
|
|
break
|
|
|
|
rev_a = cfg_a["publish_id"]
|
|
pub_b = await client.put(
|
|
"/api/v1/data-products/compute/configuration",
|
|
headers=admin_headers,
|
|
json={
|
|
"revision": cfg_a["revision"],
|
|
"config": cfg_b_payload,
|
|
"publish_note": "采用 Epoch AI 2026-11-12 同分母修订值更新中国 2025 份额。",
|
|
"source_candidate_ids": [cand_ok["id"]],
|
|
},
|
|
)
|
|
assert pub_b.status_code == 200
|
|
rev_b_body = pub_b.json()
|
|
rev_b = rev_b_body["publish_id"]
|
|
assert rev_b_body["presentation_status"] == "delivered"
|
|
|
|
# ── Check 3: 主动演播内容 ──
|
|
pres_resp = await client.get("/api/v1/situational-awareness/presentations")
|
|
assert pres_resp.status_code == 200
|
|
rev_pres = [
|
|
p
|
|
for p in pres_resp.json()["items"]
|
|
if p.get("presentation_key") == "compute-revision-notice"
|
|
]
|
|
assert len(rev_pres) == 1
|
|
contract_b = rev_pres[0]["contract"]
|
|
assert contract_b["publish_id"] == rev_b
|
|
assert "2025" in contract_b["title"] and "获修订" in contract_b["title"]
|
|
assert "历史数据的修订" in contract_b["steps"][0]["caption"]
|
|
|
|
# ── Check 4, 5, 6, 7: 同源、血缘脱敏、切回发布前、只修订中国 ──
|
|
series_b = (
|
|
await client.get(
|
|
"/api/v1/data-products/compute/series",
|
|
params={"countries": "CN,US", "mode": "chip_inflow_share"},
|
|
)
|
|
).json()
|
|
assert series_b["publish_id"] == rev_b
|
|
row_2025_b = next(r for r in series_b["compute"] if r["year"] == 2025)
|
|
assert row_2025_b["values"] == {"CN": 9.9, "US": 72.0}
|
|
assert row_2025_b["evidence_by_code"]["CN"] == ["epoch-chip-imports-2026-11"]
|
|
assert row_2025_b["evidence_by_code"]["US"] == ["epoch-chip-imports-2026"]
|
|
|
|
# Switch back to rev_a -> old values in both /series and Copilot
|
|
series_a = (
|
|
await client.get(
|
|
"/api/v1/data-products/compute/series",
|
|
params={"countries": "CN,US", "mode": "chip_inflow_share", "publish_id": rev_a},
|
|
)
|
|
).json()
|
|
assert series_a["publish_id"] == rev_a
|
|
row_2025_a = next(r for r in series_a["compute"] if r["year"] == 2025)
|
|
assert row_2025_a["values"] == {"CN": 11.0, "US": 72.0}
|
|
|
|
# ── Check 8: A -> B -> A + stale revision 409 ──
|
|
stale_resp = await client.put(
|
|
"/api/v1/data-products/compute/configuration",
|
|
headers=admin_headers,
|
|
json={
|
|
"revision": cfg_a["revision"], # stale token!
|
|
"config": cfg_b_payload,
|
|
"publish_note": "stale write",
|
|
},
|
|
)
|
|
assert stale_resp.status_code == 409
|
|
|
|
# Reset back to A with simulated presentation failure (also exercises Check 9!)
|
|
with patch(
|
|
"app.services.ai.proactive_pipeline.process_compute_revision_presentation",
|
|
side_effect=RuntimeError("simulated outage during reset"),
|
|
):
|
|
reset_resp = await client.post(
|
|
"/api/v1/data-products/compute/configuration/reset",
|
|
headers=admin_headers,
|
|
json={
|
|
"revision": rev_b,
|
|
"publish_note": "回退至内置基线口径以便对照验证。",
|
|
},
|
|
)
|
|
assert reset_resp.status_code == 200
|
|
rev_a2 = reset_resp.json()["publish_id"]
|
|
assert rev_a2 != rev_a and rev_a2 != rev_b
|
|
assert reset_resp.json()["presentation_status"] == "failed"
|
|
|
|
# Verify 3 distinct points A, B, A2
|
|
s_a = (
|
|
await client.get(
|
|
"/api/v1/data-products/compute/series",
|
|
params={"countries": "CN,US", "mode": "chip_inflow_share", "publish_id": rev_a},
|
|
)
|
|
).json()
|
|
s_b = (
|
|
await client.get(
|
|
"/api/v1/data-products/compute/series",
|
|
params={"countries": "CN,US", "mode": "chip_inflow_share", "publish_id": rev_b},
|
|
)
|
|
).json()
|
|
s_a2 = (
|
|
await client.get(
|
|
"/api/v1/data-products/compute/series",
|
|
params={"countries": "CN,US", "mode": "chip_inflow_share", "publish_id": rev_a2},
|
|
)
|
|
).json()
|
|
assert next(r for r in s_a["compute"] if r["year"] == 2025)["values"]["CN"] == 11.0
|
|
assert next(r for r in s_b["compute"] if r["year"] == 2025)["values"]["CN"] == 9.9
|
|
assert next(r for r in s_a2["compute"] if r["year"] == 2025)["values"]["CN"] == 11.0
|
|
|
|
# ── Check 9: 中断补播 + 幂等 ──
|
|
retry_resp = await client.post(
|
|
"/api/v1/situational-awareness/proactive/evaluate",
|
|
headers=admin_headers,
|
|
json={"domain": "compute"},
|
|
)
|
|
assert retry_resp.status_code == 200
|
|
assert retry_resp.json()["delivered"] == 1
|
|
|
|
db_check = session_factory()
|
|
try:
|
|
all_rev_pres = (
|
|
await db_check.execute(
|
|
select(StagePresentation)
|
|
.where(StagePresentation.presentation_key == "compute-revision-notice")
|
|
.order_by(StagePresentation.revision.asc())
|
|
)
|
|
).scalars().all()
|
|
# One for rev_b, one for rev_a2 (B->A)
|
|
assert len(all_rev_pres) == 2
|
|
assert all_rev_pres[0].contract["publish_id"] == rev_b
|
|
assert all_rev_pres[1].contract["publish_id"] == rev_a2
|
|
assert all_rev_pres[1].revision > all_rev_pres[0].revision
|
|
finally:
|
|
db_check.close()
|
|
|
|
# Running retry again creates zero duplicate presentations
|
|
retry_again = await client.post(
|
|
"/api/v1/situational-awareness/proactive/evaluate",
|
|
headers=admin_headers,
|
|
json={"domain": "compute"},
|
|
)
|
|
assert retry_again.status_code == 200
|
|
assert retry_again.json()["delivered"] == 0
|
|
db_check2 = session_factory()
|
|
try:
|
|
count_after = len(
|
|
(
|
|
await db_check2.execute(
|
|
select(StagePresentation).where(
|
|
StagePresentation.presentation_key == "compute-revision-notice"
|
|
)
|
|
)
|
|
).scalars().all()
|
|
)
|
|
assert count_after == 2
|
|
finally:
|
|
db_check2.close()
|
|
finally:
|
|
app.dependency_overrides.clear()
|
|
engine.dispose()
|