441 lines
17 KiB
Python
441 lines
17 KiB
Python
"""Tests for M1 compute configuration revision ledger, ABA protection, as-of replay, diff, and migration 0007."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from contextlib import asynccontextmanager
|
|
from copy import deepcopy
|
|
from datetime import UTC, datetime, timedelta
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from unittest.mock import AsyncMock
|
|
|
|
from fastapi import FastAPI
|
|
from httpx import ASGITransport, AsyncClient
|
|
import pytest
|
|
from sqlalchemy import create_engine, select, text
|
|
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.migration_steps import __file__ as migration_steps_init
|
|
from app.db.migrations import run_migrations
|
|
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_client import get_ai_provider_client
|
|
from app.services.compute_configuration import (
|
|
DEFAULT_CONFIGURATION,
|
|
DEFAULT_REVISION,
|
|
default_envelope,
|
|
ensure_compute_revision_baseline,
|
|
list_configuration_revisions,
|
|
publish_configuration,
|
|
read_configuration,
|
|
)
|
|
from app.services.compute_revision_diff import (
|
|
diff_compute_configurations,
|
|
has_observation_value_delta,
|
|
)
|
|
|
|
|
|
def _make_sqlite_async_session():
|
|
engine = create_engine("sqlite://")
|
|
for model in (
|
|
SystemSetting,
|
|
AuditLog,
|
|
ComputeConfigurationRevision,
|
|
ComputeEvidenceCandidate,
|
|
EvidenceRecord,
|
|
SituationalAssessment,
|
|
):
|
|
model.__table__.create(engine)
|
|
raw = Session(engine)
|
|
session = 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, session
|
|
|
|
|
|
def _mutated_config(cn_2024: float = 24.5) -> ComputeConfiguration:
|
|
payload = DEFAULT_CONFIGURATION.model_dump(mode="json")
|
|
for obs in payload["observations"]:
|
|
if obs["metric"] == "global_share" and obs["year"] == 2024:
|
|
obs["values"]["CN"] = cn_2024
|
|
break
|
|
return ComputeConfiguration.model_validate(payload)
|
|
|
|
|
|
def _cn_2024(envelope: dict) -> float:
|
|
for obs in envelope["config"]["observations"]:
|
|
if obs["metric"] == "global_share" and obs["year"] == 2024:
|
|
return float(obs["values"]["CN"])
|
|
raise AssertionError("2024 global_share row not found")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_aba_history_as_of_replay_and_stale_token_conflict():
|
|
engine, raw, db = _make_sqlite_async_session()
|
|
try:
|
|
actor = SimpleNamespace(id=1, username="admin", role="admin")
|
|
t_before_baseline = datetime.now(UTC) - timedelta(seconds=10)
|
|
baseline = await ensure_compute_revision_baseline(
|
|
db, published_at=datetime.now(UTC) - timedelta(seconds=5)
|
|
)
|
|
assert baseline is not None
|
|
t0_token = baseline.publish_id
|
|
assert t0_token == DEFAULT_REVISION
|
|
t_after_a = datetime.now(UTC) - timedelta(seconds=3)
|
|
|
|
# Publish B (CN 2024: 23 -> 24.5)
|
|
env_b = await publish_configuration(
|
|
db,
|
|
revision=t0_token,
|
|
config=_mutated_config(24.5),
|
|
actor=actor,
|
|
publish_note="Revise 2024 CN share",
|
|
)
|
|
assert env_b["no_changes"] is False
|
|
assert env_b["publish_id"] != t0_token
|
|
assert env_b["presentation_status"] == "pending"
|
|
|
|
# Separate timestamps cleanly for deterministic as_of checks.
|
|
rows = raw.execute(
|
|
select(ComputeConfigurationRevision).order_by(ComputeConfigurationRevision.id.asc())
|
|
).scalars().all()
|
|
assert len(rows) == 2
|
|
rows[1].published_at = (datetime.now(UTC) - timedelta(seconds=2)).replace(tzinfo=None)
|
|
raw.commit()
|
|
t_after_b = datetime.now(UTC) - timedelta(seconds=1)
|
|
|
|
# Reset B -> A (creates a 3rd revision with a brand new publish_id, never reusing DEFAULT_REVISION)
|
|
env_a2 = await publish_configuration(
|
|
db,
|
|
revision=env_b["publish_id"],
|
|
config=DEFAULT_CONFIGURATION,
|
|
actor=actor,
|
|
reset=True,
|
|
)
|
|
assert env_a2["is_default"] is True
|
|
assert env_a2["publish_id"] not in {t0_token, env_b["publish_id"]}
|
|
assert env_a2["publish_id"] != DEFAULT_REVISION
|
|
assert env_a2["action"] == "reset"
|
|
assert env_a2["presentation_status"] == "pending"
|
|
t_after_a2 = datetime.now(UTC) + timedelta(seconds=2)
|
|
|
|
# Verify 3 distinct revisions exist
|
|
revisions = await list_configuration_revisions(db, limit=10)
|
|
assert len(revisions) == 3
|
|
assert len({r["publish_id"] for r in revisions}) == 3
|
|
|
|
# Verify as_of returns A, B, A at the three timestamps
|
|
snap_before = await read_configuration(db, as_of=t_before_baseline)
|
|
assert snap_before["snapshot_unavailable"] is True
|
|
assert snap_before["publish_id"] is None
|
|
|
|
snap_a1 = await read_configuration(db, as_of=t_after_a)
|
|
assert snap_a1["snapshot_unavailable"] is False
|
|
assert snap_a1["publish_id"] == t0_token
|
|
assert _cn_2024(snap_a1) == 23.0
|
|
|
|
snap_b = await read_configuration(db, as_of=t_after_b)
|
|
assert snap_b["publish_id"] == env_b["publish_id"]
|
|
assert _cn_2024(snap_b) == 24.5
|
|
|
|
snap_a2 = await read_configuration(db, as_of=t_after_a2)
|
|
assert snap_a2["publish_id"] == env_a2["publish_id"]
|
|
assert _cn_2024(snap_a2) == 23.0
|
|
|
|
# ABA conflict: stale client holding T0 after B -> A reset must receive 409!
|
|
from fastapi import HTTPException
|
|
|
|
with pytest.raises(HTTPException) as conflict:
|
|
await publish_configuration(
|
|
db,
|
|
revision=t0_token,
|
|
config=_mutated_config(26.0),
|
|
actor=actor,
|
|
)
|
|
assert conflict.value.status_code == 409
|
|
|
|
# Direct publish_id lookup
|
|
pinned_b = await read_configuration(db, publish_id=env_b["publish_id"])
|
|
assert _cn_2024(pinned_b) == 24.5
|
|
with pytest.raises(HTTPException) as missing:
|
|
await read_configuration(db, publish_id="nonexistent-pid")
|
|
assert missing.value.status_code == 404
|
|
finally:
|
|
raw.close()
|
|
engine.dispose()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_no_changes_publish_and_baseline_idempotency():
|
|
engine, raw, db = _make_sqlite_async_session()
|
|
try:
|
|
# Pre-seed an existing custom SystemSetting to test baseline preserves pre-upgrade revision
|
|
custom_env = default_envelope()
|
|
custom_env["revision"] = "legacy-pre-upgrade-rev-123"
|
|
custom_env["is_default"] = False
|
|
raw.add(SystemSetting(category="compute_comparison", payload=custom_env))
|
|
raw.commit()
|
|
|
|
b1 = await ensure_compute_revision_baseline(db)
|
|
b2 = await ensure_compute_revision_baseline(db)
|
|
assert b1 is not None and b2 is not None
|
|
assert b1.id == b2.id
|
|
assert b1.publish_id == "legacy-pre-upgrade-rev-123"
|
|
count = raw.execute(select(ComputeConfigurationRevision)).scalars().all()
|
|
assert len(count) == 1
|
|
|
|
# Submitting unchanged content returns no_changes=True and inserts no new revision
|
|
actor = SimpleNamespace(id=1, username="admin", role="admin")
|
|
res = await publish_configuration(
|
|
db,
|
|
revision="legacy-pre-upgrade-rev-123",
|
|
config=DEFAULT_CONFIGURATION,
|
|
actor=actor,
|
|
)
|
|
assert res["no_changes"] is True
|
|
assert res["publish_id"] == "legacy-pre-upgrade-rev-123"
|
|
assert len(raw.execute(select(ComputeConfigurationRevision)).scalars().all()) == 1
|
|
finally:
|
|
raw.close()
|
|
engine.dispose()
|
|
|
|
|
|
def test_diff_compute_configurations_captures_small_revisions_new_years_and_non_obs():
|
|
old = DEFAULT_CONFIGURATION
|
|
new_payload = old.model_dump(mode="json")
|
|
# 1.5pp revision on 2024 CN global_share (below legacy 2.0pp threshold)
|
|
for obs in new_payload["observations"]:
|
|
if obs["metric"] == "global_share" and obs["year"] == 2024:
|
|
obs["values"]["CN"] = 24.5
|
|
# Add new year observation
|
|
new_payload["sources"].append(
|
|
{
|
|
"id": "caict-2026-test",
|
|
"title": "CAICT 2026 Test",
|
|
"url": "https://www.caict.ac.cn/test",
|
|
"publisher": "CAICT",
|
|
"report_year": 2026,
|
|
"published_at": "2026-10-01",
|
|
"locator": "Page 10",
|
|
}
|
|
)
|
|
new_payload["observations"].append(
|
|
{
|
|
"year": 2025,
|
|
"metric": "global_share",
|
|
"source_id": "caict-2026-test",
|
|
"values": {"CN": 25.0, "US": 43.0},
|
|
}
|
|
)
|
|
new_cfg = ComputeConfiguration.model_validate(new_payload)
|
|
diffs = diff_compute_configurations(old, new_cfg)
|
|
|
|
rev_entry = next(
|
|
d
|
|
for d in diffs
|
|
if d["kind"] == "observation_value"
|
|
and d["metric"] == "global_share"
|
|
and d["year"] == 2024
|
|
and d["code"] == "CN"
|
|
)
|
|
assert rev_entry["old_value"] == 23.0
|
|
assert rev_entry["new_value"] == 24.5
|
|
assert rev_entry["delta"] == 1.5
|
|
assert rev_entry["change_kind"] == "historical_revision"
|
|
assert has_observation_value_delta(diffs) is True
|
|
|
|
new_year_entry = next(
|
|
d
|
|
for d in diffs
|
|
if d["kind"] == "observation_value"
|
|
and d["metric"] == "global_share"
|
|
and d["year"] == 2025
|
|
and d["code"] == "CN"
|
|
)
|
|
assert new_year_entry["change_kind"] == "new_observation"
|
|
assert new_year_entry["new_source_id"] == "caict-2026-test"
|
|
|
|
# Milestone-only edit has no observation value delta
|
|
ms_payload = old.model_dump(mode="json")
|
|
ms_payload["milestones"][0]["title"] = "Updated milestone title"
|
|
ms_diffs = diff_compute_configurations(old, ComputeConfiguration.model_validate(ms_payload))
|
|
assert has_observation_value_delta(ms_diffs) is False
|
|
assert any(d["kind"] == "section_changed" and d["section"] == "milestones" for d in ms_diffs)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_series_posture_and_revisions_http_endpoints_with_as_of():
|
|
engine, raw, db = _make_sqlite_async_session()
|
|
try:
|
|
actor = SimpleNamespace(id=1, username="admin", role="admin")
|
|
baseline = await ensure_compute_revision_baseline(
|
|
db, published_at=datetime.now(UTC) - timedelta(seconds=10)
|
|
)
|
|
assert baseline is not None
|
|
env_b = await publish_configuration(
|
|
db,
|
|
revision=baseline.publish_id,
|
|
config=_mutated_config(24.5),
|
|
actor=actor,
|
|
publish_note="HTTP test revision",
|
|
)
|
|
|
|
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_ai_provider_client] = lambda: SimpleNamespace(service_url="")
|
|
app.dependency_overrides[get_current_user] = lambda: actor
|
|
|
|
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
|
|
# Admin revisions endpoint
|
|
rev_resp = await client.get("/data-products/compute/revisions?limit=10")
|
|
assert rev_resp.status_code == 200
|
|
items = rev_resp.json()["items"]
|
|
assert len(items) == 2
|
|
assert items[0]["publish_id"] == env_b["publish_id"]
|
|
assert items[0]["publish_note"] == "HTTP test revision"
|
|
|
|
# Series pinned to baseline publish_id shows 23.0, current shows 24.5
|
|
cur_series = (await client.get("/data-products/compute/series")).json()
|
|
assert cur_series["publish_id"] == env_b["publish_id"]
|
|
row_cur = next(r for r in cur_series["compute"] if r["year"] == 2024)
|
|
assert row_cur["values"]["CN"] == 24.5
|
|
|
|
old_series = (
|
|
await client.get(
|
|
f"/data-products/compute/series?publish_id={baseline.publish_id}"
|
|
)
|
|
).json()
|
|
assert old_series["publish_id"] == baseline.publish_id
|
|
row_old = next(r for r in old_series["compute"] if r["year"] == 2024)
|
|
assert row_old["values"]["CN"] == 23.0
|
|
|
|
# Pre-baseline as_of returns snapshot_unavailable=True on both /series and /posture/compute
|
|
early_iso = (datetime.now(UTC) - timedelta(days=1)).isoformat()
|
|
unavail_series = (
|
|
await client.get(f"/data-products/compute/series?as_of={early_iso}")
|
|
).json()
|
|
assert unavail_series["snapshot_unavailable"] is True
|
|
assert unavail_series["publish_id"] is None
|
|
|
|
unavail_posture = (
|
|
await client.get(f"/situational-awareness/posture/compute?as_of={early_iso}")
|
|
).json()
|
|
assert unavail_posture["snapshot_unavailable"] is True
|
|
assert "历史快照不完整" in unavail_posture["payload"]["headline"]
|
|
|
|
# Posture pinned to baseline vs current have different publish_id & distinct content
|
|
p_old = (
|
|
await client.get(
|
|
f"/situational-awareness/posture/compute?publish_id={baseline.publish_id}"
|
|
)
|
|
).json()
|
|
p_new = (
|
|
await client.get(
|
|
f"/situational-awareness/posture/compute?publish_id={env_b['publish_id']}"
|
|
)
|
|
).json()
|
|
assert p_old["publish_id"] == baseline.publish_id
|
|
assert p_new["publish_id"] == env_b["publish_id"]
|
|
assert p_old["input_fingerprint"] != p_new["input_fingerprint"]
|
|
finally:
|
|
raw.close()
|
|
engine.dispose()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_migration_0007_idempotent_on_sqlite_and_postgresql_path():
|
|
steps_dir = Path(migration_steps_init).resolve().parent
|
|
migration_file = steps_dir / "0007_add_compute_configuration_revisions.py"
|
|
assert migration_file.exists()
|
|
|
|
import importlib.util
|
|
|
|
spec = importlib.util.spec_from_file_location("m0007_test", migration_file)
|
|
assert spec and spec.loader
|
|
mod = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(mod)
|
|
|
|
# 1. SQLite path: run upgrade twice idempotently on pre-existing candidate table
|
|
sync_engine = create_engine("sqlite://")
|
|
with sync_engine.begin() as conn:
|
|
conn.execute(
|
|
text(
|
|
"""
|
|
CREATE TABLE compute_evidence_candidates (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
status VARCHAR(24) NOT NULL DEFAULT 'pending',
|
|
candidate_type VARCHAR(40) NOT NULL DEFAULT 'observation',
|
|
proposed_payload JSON NOT NULL DEFAULT '{}',
|
|
source_payload JSON NOT NULL DEFAULT '{}',
|
|
confidence FLOAT NOT NULL DEFAULT 0.8,
|
|
extractor_note TEXT NOT NULL DEFAULT '',
|
|
reviewed_by VARCHAR(120),
|
|
reviewed_at TIMESTAMP,
|
|
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
)
|
|
"""
|
|
)
|
|
)
|
|
|
|
class _ConnAdapter:
|
|
def __init__(self, conn):
|
|
self._conn = conn
|
|
self.dialect = conn.dialect
|
|
|
|
async def execute(self, stmt, params=None):
|
|
return self._conn.execute(stmt, params) if params is not None else self._conn.execute(stmt)
|
|
|
|
class _EngineAdapter:
|
|
@asynccontextmanager
|
|
async def begin(self):
|
|
with sync_engine.begin() as c:
|
|
yield _ConnAdapter(c)
|
|
|
|
async with _EngineAdapter().begin() as conn:
|
|
await mod.upgrade(conn)
|
|
await mod.upgrade(conn) # idempotent second run
|
|
|
|
with sync_engine.connect() as conn:
|
|
rev_cols = {row[1] for row in conn.execute(text("PRAGMA table_info(compute_configuration_revisions)")).fetchall()}
|
|
assert {"id", "publish_id", "content_fingerprint", "config_payload", "diff_summary", "presentation_status"}.issubset(rev_cols)
|
|
cand_cols = {row[1] for row in conn.execute(text("PRAGMA table_info(compute_evidence_candidates)")).fetchall()}
|
|
assert {"comparison", "dedupe_fingerprint", "review_reason_code", "review_reason", "published_publish_id"}.issubset(cand_cols)
|
|
|
|
# Also test migration runner picks up 0007 cleanly in an isolated steps copy
|
|
sync_engine.dispose()
|
|
|
|
# 2. PostgreSQL dialect SQL path verification (idempotent DDL statements emitted)
|
|
pg_statements: list[str] = []
|
|
|
|
class _FakePgConn:
|
|
dialect = SimpleNamespace(name="postgresql")
|
|
|
|
async def execute(self, stmt, _params=None):
|
|
pg_statements.append(str(stmt))
|
|
return SimpleNamespace(fetchall=lambda: [])
|
|
|
|
await mod.upgrade(_FakePgConn())
|
|
await mod.upgrade(_FakePgConn())
|
|
assert any("CREATE TABLE IF NOT EXISTS compute_configuration_revisions" in s for s in pg_statements)
|
|
assert any("ALTER TABLE compute_evidence_candidates" in s and "IF NOT EXISTS" in s for s in pg_statements)
|