forked from linkong/planet
344 lines
15 KiB
Python
344 lines
15 KiB
Python
"""Tests for M2 candidate comparison, dedupe, review reason validation, per-country value_sources, and M0 real case."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from unittest.mock import AsyncMock
|
|
|
|
from fastapi import FastAPI
|
|
from httpx import ASGITransport, AsyncClient
|
|
from pydantic import ValidationError
|
|
import pytest
|
|
from sqlalchemy import create_engine, select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.api.v1 import compute_intelligence, situational_awareness
|
|
from app.core.security import get_current_user
|
|
from app.db.session import get_db
|
|
from app.models.compute_configuration_revision import ComputeConfigurationRevision
|
|
from app.models.situational_assessment import (
|
|
ComputeEvidenceCandidate,
|
|
EvidenceRecord,
|
|
SituationalAssessment,
|
|
)
|
|
from app.models.system_log import AuditLog
|
|
from app.models.system_setting import SystemSetting
|
|
from app.schemas.compute_configuration import ComputeConfiguration
|
|
from app.services.ai.semantic_delta import extract_compute_candidates_deterministic
|
|
from app.services.ai.tool_registry import filter_compute_config_by_cutoff
|
|
from app.services.compute_configuration import (
|
|
DEFAULT_CONFIGURATION,
|
|
ensure_compute_revision_baseline,
|
|
)
|
|
from app.services.compute_history import compute_history
|
|
|
|
FIXTURE_PATH = Path(__file__).resolve().parent / "fixtures" / "compute_revision_case.json"
|
|
|
|
|
|
def _make_sqlite_db():
|
|
engine = create_engine("sqlite://")
|
|
for model in (
|
|
SystemSetting,
|
|
AuditLog,
|
|
ComputeConfigurationRevision,
|
|
ComputeEvidenceCandidate,
|
|
EvidenceRecord,
|
|
SituationalAssessment,
|
|
):
|
|
model.__table__.create(engine)
|
|
raw = Session(engine)
|
|
db = SimpleNamespace(
|
|
execute=AsyncMock(side_effect=raw.execute),
|
|
add=raw.add,
|
|
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),
|
|
get_bind=raw.get_bind,
|
|
bind=engine,
|
|
)
|
|
return engine, raw, db
|
|
|
|
|
|
def test_value_sources_schema_validation_rejects_invalid_keys_and_sources():
|
|
payload = DEFAULT_CONFIGURATION.model_dump(mode="json")
|
|
# Invalid key not present in values
|
|
bad_key = json.loads(json.dumps(payload))
|
|
bad_key["observations"][4]["value_sources"] = {"DE": "caict-2025"}
|
|
with pytest.raises(ValidationError, match="subset"):
|
|
ComputeConfiguration.model_validate(bad_key)
|
|
|
|
# Unknown source ID
|
|
bad_src = json.loads(json.dumps(payload))
|
|
bad_src["observations"][4]["value_sources"] = {"CN": "nonexistent-report"}
|
|
with pytest.raises(ValidationError, match="Missing report source"):
|
|
ComputeConfiguration.model_validate(bad_src)
|
|
|
|
# Report year earlier than observation year
|
|
bad_year = json.loads(json.dumps(payload))
|
|
bad_year["observations"][4]["value_sources"] = {"CN": "caict-2021"}
|
|
with pytest.raises(ValidationError, match="after its report year"):
|
|
ComputeConfiguration.model_validate(bad_year)
|
|
|
|
|
|
def test_extractor_handles_real_m0_epoch_ai_fixture_and_chinese_chip_inflow():
|
|
case = json.loads(FIXTURE_PATH.read_text(encoding="utf-8"))
|
|
extracted = extract_compute_candidates_deterministic(
|
|
case["new"]["excerpt"],
|
|
year=case["year"],
|
|
source_meta={"id": case["new"]["source_id"]},
|
|
period_label=case["period_label"],
|
|
)
|
|
assert len(extracted) == 1
|
|
item = extracted[0]
|
|
assert item["proposed_payload"]["metric"] == "chip_inflow_share"
|
|
assert item["proposed_payload"]["year"] == 2025
|
|
assert item["proposed_payload"]["values"] == {"CN": 9.9}
|
|
|
|
# Full sentence with both China and United States
|
|
full_excerpt = (
|
|
case["new"]["excerpt"]
|
|
+ " and lowers the United States' share from 72.2% to 72.0% (53,000 H100e)."
|
|
)
|
|
both = extract_compute_candidates_deterministic(
|
|
full_excerpt, year=2025, source_meta={"id": "epoch-both"}
|
|
)
|
|
assert both[0]["proposed_payload"]["values"] == {"CN": 9.9, "US": 72.0}
|
|
|
|
# Chinese chip inflow phrasing
|
|
zh = extract_compute_candidates_deterministic(
|
|
"报告指出中国高端AI芯片新增流向份额为 9.9%。",
|
|
year=2025,
|
|
source_meta={"id": "zh-chip"},
|
|
)
|
|
assert zh[0]["proposed_payload"]["metric"] == "chip_inflow_share"
|
|
assert zh[0]["proposed_payload"]["values"] == {"CN": 9.9}
|
|
|
|
|
|
def test_as_known_then_cutoff_drops_only_post_cutoff_country_in_mixed_source_row():
|
|
case = json.loads(FIXTURE_PATH.read_text(encoding="utf-8"))
|
|
payload = DEFAULT_CONFIGURATION.model_dump(mode="json")
|
|
payload["sources"].append(
|
|
{
|
|
"id": case["new"]["source_id"],
|
|
"title": case["new"]["title"],
|
|
"url": case["new"]["url"],
|
|
"publisher": case["new"]["publisher"],
|
|
"report_year": case["new"]["report_year"],
|
|
"published_at": case["new"]["published_at"],
|
|
"locator": case["new"]["locator"],
|
|
}
|
|
)
|
|
for obs in payload["observations"]:
|
|
if obs["metric"] == "chip_inflow_share" and obs["year"] == 2025:
|
|
obs["values"]["CN"] = 9.9
|
|
obs["value_sources"] = {"CN": case["new"]["source_id"]}
|
|
break
|
|
|
|
cfg = ComputeConfiguration.model_validate(payload)
|
|
# Full view: CN cites new report, US cites old report
|
|
full_series = compute_history(["CN", "US"], "chip_inflow_share", cfg)
|
|
row_2025 = next(r for r in full_series["compute"] if r["year"] == 2025)
|
|
assert row_2025["values"] == {"CN": 9.9, "US": 72.0}
|
|
assert row_2025["evidence_by_code"] == {
|
|
"CN": [case["new"]["source_id"]],
|
|
"US": ["epoch-chip-imports-2026"],
|
|
}
|
|
assert row_2025["mixed_sources"] is True
|
|
chip_rpi = full_series["bilateral_rpi"]["latest_chip_inflow"]
|
|
assert chip_rpi["cn_evidence_id"] == case["new"]["source_id"]
|
|
assert chip_rpi["us_evidence_id"] == "epoch-chip-imports-2026"
|
|
|
|
# Cut off at 2026-06-01: cuts off epoch-chip-imports-2026-11 (2026-11-12) while keeping epoch-chip-imports-2026 (2026-04-10)
|
|
filtered_cfg, withheld = filter_compute_config_by_cutoff(
|
|
cfg, time_basis="as_known_then", cutoff_at="2026-06-01"
|
|
)
|
|
assert case["new"]["source_id"] in withheld
|
|
assert "epoch-chip-imports-2026" not in withheld
|
|
cut_obs = next(
|
|
obs for obs in filtered_cfg.observations if obs.metric == "chip_inflow_share" and obs.year == 2025
|
|
)
|
|
assert "CN" not in cut_obs.values
|
|
assert cut_obs.values == {"US": 72.0}
|
|
assert cut_obs.source_id == "epoch-chip-imports-2026"
|
|
assert cut_obs.value_sources is None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_m2_full_extract_dedupe_review_mixed_source_guard_and_publish():
|
|
case = json.loads(FIXTURE_PATH.read_text(encoding="utf-8"))
|
|
engine, raw, db = _make_sqlite_db()
|
|
try:
|
|
await ensure_compute_revision_baseline(db)
|
|
actor = SimpleNamespace(id=1, username="admin", role="admin")
|
|
app = FastAPI()
|
|
app.include_router(compute_intelligence.router, prefix="/data-products/compute")
|
|
app.include_router(situational_awareness.router, prefix="/situational-awareness")
|
|
app.dependency_overrides[get_db] = lambda: db
|
|
app.dependency_overrides[get_current_user] = lambda: actor
|
|
|
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
|
extract_body = {
|
|
"year": case["year"],
|
|
"excerpt": case["new"]["excerpt"],
|
|
"source_id": case["new"]["source_id"],
|
|
"source_title": case["new"]["title"],
|
|
"source_url": case["new"]["url"],
|
|
"publisher": case["new"]["publisher"],
|
|
"locator": case["new"]["locator"],
|
|
"period_label": case["period_label"],
|
|
"published_at": case["new"]["published_at"],
|
|
"report_year": case["new"]["report_year"],
|
|
}
|
|
# 1. Extract real M0 case
|
|
res1 = await client.post("/situational-awareness/candidates/extract", json=extract_body)
|
|
assert res1.status_code == 200
|
|
items1 = res1.json()["items"]
|
|
assert len(items1) == 1
|
|
cand = items1[0]
|
|
assert cand["duplicate"] is False
|
|
assert cand["comparison"]["has_historical_revision"] is True
|
|
assert cand["comparison"]["denominator"] == "ai_chip_inflow"
|
|
cn_cmp = cand["comparison"]["codes"]["CN"]
|
|
assert cn_cmp["old_value"] == 11.0
|
|
assert cn_cmp["new_value"] == 9.9
|
|
assert cn_cmp["delta"] == -1.1
|
|
assert cn_cmp["change_kind"] == "historical_revision"
|
|
assert cn_cmp["old_source_id"] == "epoch-chip-imports-2026"
|
|
|
|
# Verify immutable EvidenceRecord persisted with excerpt sha256
|
|
ev_row = raw.execute(
|
|
select(EvidenceRecord).where(EvidenceRecord.id == case["new"]["source_id"])
|
|
).scalar_one()
|
|
assert ev_row.excerpt == case["new"]["excerpt"]
|
|
assert ev_row.content_sha256 == hashlib.sha256(case["new"]["excerpt"].encode("utf-8")).hexdigest()
|
|
|
|
# 2. Duplicate extraction returns existing candidate with duplicate=True
|
|
res2 = await client.post("/situational-awareness/candidates/extract", json=extract_body)
|
|
assert res2.status_code == 200
|
|
items2 = res2.json()["items"]
|
|
assert len(items2) == 1
|
|
assert items2[0]["id"] == cand["id"]
|
|
assert items2[0]["duplicate"] is True
|
|
assert len(raw.execute(select(ComputeEvidenceCandidate)).scalars().all()) == 1
|
|
|
|
# 3. Review validation: missing reason / mismatched reason_code -> 422
|
|
bad_missing = await client.post(
|
|
f"/situational-awareness/candidates/{cand['id']}/review",
|
|
json={"decision": "approved"},
|
|
)
|
|
assert bad_missing.status_code == 422
|
|
|
|
bad_mismatch = await client.post(
|
|
f"/situational-awareness/candidates/{cand['id']}/review",
|
|
json={
|
|
"decision": "approved",
|
|
"reason_code": "extraction_error",
|
|
"reason": "Wrong code for approval",
|
|
},
|
|
)
|
|
assert bad_mismatch.status_code == 422
|
|
|
|
# Viewer -> 403
|
|
app.dependency_overrides[get_current_user] = lambda: SimpleNamespace(
|
|
id=2, username="viewer", role="viewer"
|
|
)
|
|
forbidden = await client.post(
|
|
f"/situational-awareness/candidates/{cand['id']}/review",
|
|
json={
|
|
"decision": "approved",
|
|
"reason_code": "methodology_update",
|
|
"reason": "Viewer cannot approve",
|
|
},
|
|
)
|
|
assert forbidden.status_code == 403
|
|
app.dependency_overrides[get_current_user] = lambda: actor
|
|
|
|
# Valid approval
|
|
approved = await client.post(
|
|
f"/situational-awareness/candidates/{cand['id']}/review",
|
|
json={
|
|
"decision": "approved",
|
|
"reason_code": "methodology_update",
|
|
"reason": "Epoch AI 2026-11-12 修订中国 H20 到货时点并更新全球累计份额为 9.9%。",
|
|
},
|
|
)
|
|
assert approved.status_code == 200
|
|
assert approved.json()["status"] == "approved"
|
|
assert approved.json()["review_reason_code"] == "methodology_update"
|
|
|
|
# 4. Publish China-only mixed-source revision: empty publish_note -> 422
|
|
cfg_res = (await client.get("/data-products/compute/configuration")).json()
|
|
edited = json.loads(json.dumps(cfg_res["config"]))
|
|
edited["sources"].append(
|
|
{
|
|
"id": case["new"]["source_id"],
|
|
"title": case["new"]["title"],
|
|
"url": case["new"]["url"],
|
|
"publisher": case["new"]["publisher"],
|
|
"report_year": case["new"]["report_year"],
|
|
"published_at": case["new"]["published_at"],
|
|
"locator": case["new"]["locator"],
|
|
}
|
|
)
|
|
for obs in edited["observations"]:
|
|
if obs["metric"] == "chip_inflow_share" and obs["year"] == 2025:
|
|
obs["values"]["CN"] = 9.9
|
|
obs["value_sources"] = {"CN": case["new"]["source_id"]}
|
|
break
|
|
|
|
no_note_res = await client.put(
|
|
"/data-products/compute/configuration",
|
|
json={
|
|
"revision": cfg_res["revision"],
|
|
"config": edited,
|
|
"publish_note": "",
|
|
"source_candidate_ids": [cand["id"]],
|
|
},
|
|
)
|
|
assert no_note_res.status_code == 422
|
|
|
|
# With publish_note -> 200, backfills published_publish_id
|
|
pub_res = await client.put(
|
|
"/data-products/compute/configuration",
|
|
json={
|
|
"revision": cfg_res["revision"],
|
|
"config": edited,
|
|
"publish_note": "同分母依据:两版均采用 Epoch AI 全球累计 H100e 到货算力总盘子,美国维持 72.0% 未变。",
|
|
"source_candidate_ids": [cand["id"]],
|
|
},
|
|
)
|
|
assert pub_res.status_code == 200
|
|
pub_pid = pub_res.json()["publish_id"]
|
|
|
|
# Candidate now locked (published_publish_id set) -> re-review returns 409
|
|
locked_res = await client.post(
|
|
f"/situational-awareness/candidates/{cand['id']}/review",
|
|
json={
|
|
"decision": "rejected",
|
|
"reason_code": "superseded",
|
|
"reason": "Cannot alter after publish",
|
|
},
|
|
)
|
|
assert locked_res.status_code == 409
|
|
|
|
# Verify /series reflects CN->new source, US->old source
|
|
series = (
|
|
await client.get("/data-products/compute/series?countries=CN,US&mode=chip_inflow_share")
|
|
).json()
|
|
assert series["publish_id"] == pub_pid
|
|
row = next(r for r in series["compute"] if r["year"] == 2025)
|
|
assert row["values"] == {"CN": 9.9, "US": 72.0}
|
|
assert row["evidence_by_code"] == {
|
|
"CN": [case["new"]["source_id"]],
|
|
"US": ["epoch-chip-imports-2026"],
|
|
}
|
|
assert row["mixed_sources"] is True
|
|
finally:
|
|
raw.close()
|
|
engine.dispose()
|