Compare commits

...
3 Commits
Author SHA1 Message Date
linkong 5e6352f524 release: bump version to 0.84.1
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
2026-12-04 07:34:27 +08:00
linkong e1cc27f13d release: bump version to 0.84.0
ci / backend (push) Waiting to run
ci / frontend (push) Waiting to run
2026-12-04 07:07:19 +08:00
linkong 3b1b9ef68c release: bump version to 0.83.0
ci / backend (push) Canceled after 0s
ci / frontend (push) Canceled after 0s
ci / delivery (push) Canceled after 0s
2026-12-02 18:53:58 +08:00
289 changed files with 51239 additions and 6995 deletions

No files matched your search

+1 -1
View File
@@ -14,7 +14,7 @@
!config/
!config/earth-boundary-pov-policy.china-v1.json
!scripts/
!scripts/build_earth_boundary_china_pov_geojson.py
!scripts/earth_boundary_geometry.py
!scripts/build_earth_boundary_pmtiles.py
!scripts/db_migrate.py
!scripts/earth_boundary_policy.py
+7 -3
View File
@@ -170,10 +170,14 @@ temp/
# ----------------------
data/ai/bgp-briefs/
data/earth-boundary-sources/
data/earth-clouds/
data/earth-tiles/
data/earth-wind/
# Generated Earth boundary tile artifacts. Keep source configs and builders in
# Git; publish PMTiles/MVT artifacts through release/deploy storage instead of
# committing thousands of generated tile files.
# Earth boundary sources and generated PMTiles artifacts live in the backend
# boundary data volume (built by the Earth "高精" rebuild), never in Git or in
# the desktop Earth bundle.
backend/data/earth-boundaries/
frontend/public/earth/data/boundaries/
# Offline comparison originals; runtime 8K maps and provenance remain versioned.
+1 -1
View File
@@ -1 +1 @@
0.82.0
0.84.1
+100 -8
View File
@@ -126,6 +126,7 @@ class ProviderService:
native_web_search = bool(getattr(payload, "native_web_search", False))
images = self._normalize_images(getattr(payload, "images", None))
tool_calls: list[ToolCallRecord] = []
citation_urls: list[str] = []
stop_reason: str | None = None
if provider_api == "openai-completions":
@@ -160,6 +161,7 @@ class ProviderService:
content_blocks = self._extract_responses_blocks(data)
content = "".join(block.text for block in content_blocks if block.text)
tool_calls = self._extract_responses_tool_calls(data)
citation_urls = self._extract_responses_citations(data)
stop_reason = str(data.get("status") or "") or None
elif provider_api == "anthropic-messages":
data = await self._request_anthropic_messages(
@@ -177,6 +179,7 @@ class ProviderService:
content = self._extract_anthropic_content(data)
content_blocks = self._extract_anthropic_blocks(data)
tool_calls = self._extract_anthropic_tool_calls(data)
citation_urls = self._extract_anthropic_citations(data)
stop_reason = str(data.get("stop_reason") or "") or None
elif provider_api == "ollama-generate":
data = await self._request_ollama(
@@ -207,6 +210,7 @@ class ProviderService:
text_blocks=text_blocks,
thinking_blocks=thinking_blocks,
tool_calls=tool_calls,
citation_urls=citation_urls,
stop_reason=stop_reason,
raw_response=data,
)
@@ -332,7 +336,17 @@ class ProviderService:
anthropic_messages: list[dict[str, Any]] = []
source_messages = (
conversation_messages
if (conversation_messages and (len(conversation_messages) > 1 or any(m.get("role") == "tool" or m.get("tool_calls") for m in conversation_messages)))
if (
conversation_messages
and (
len(conversation_messages) > 1
or bool(tools)
or any(
m.get("role") == "tool" or m.get("tool_calls") or m.get("thinking_blocks")
for m in conversation_messages
)
)
)
else [{"role": "user", "content": prompt}]
)
for msg in source_messages:
@@ -354,8 +368,15 @@ class ProviderService:
else:
anthropic_messages.append({"role": "user", "content": [block]})
continue
if role == "assistant" and msg.get("tool_calls"):
if role == "assistant" and (msg.get("tool_calls") or msg.get("thinking_blocks")):
blocks: list[dict[str, Any]] = []
for tb in msg.get("thinking_blocks") or []:
if not isinstance(tb, dict):
continue
t_text = str(tb.get("thinking") or "")
sig = str(tb.get("signature") or "")
if t_text and sig:
blocks.append({"type": "thinking", "thinking": t_text, "signature": sig})
text = str(msg.get("content") or "").strip()
if text:
blocks.append({"type": "text", "text": text})
@@ -424,9 +445,12 @@ class ProviderService:
for tool in tools or []:
if not isinstance(tool, dict) or not tool.get("name"):
continue
tool_name = str(tool["name"])
if native_web_search and tool_name == "web_search":
continue
anthropic_tools.append(
{
"name": str(tool["name"]),
"name": tool_name,
"description": str(tool.get("description") or ""),
"input_schema": tool.get("parameters") or {"type": "object", "properties": {}},
}
@@ -437,13 +461,15 @@ class ProviderService:
request_body["tools"] = anthropic_tools
if isinstance(tool_choice, str):
if tool_choice == "required":
request_body["tool_choice"] = {"type": "any"}
request_body["tool_choice"] = {"type": "auto"} if thinking_active else {"type": "any"}
elif tool_choice == "auto":
request_body["tool_choice"] = {"type": "auto"}
elif tool_choice not in {"none", ""}:
request_body["tool_choice"] = {"type": "tool", "name": tool_choice}
request_body["tool_choice"] = {"type": "auto"} if thinking_active else {"type": "tool", "name": tool_choice}
elif isinstance(tool_choice, dict) and tool_choice.get("name"):
request_body["tool_choice"] = {"type": "tool", "name": str(tool_choice["name"])}
request_body["tool_choice"] = (
{"type": "auto"} if thinking_active else {"type": "tool", "name": str(tool_choice["name"])}
)
path = "/v1/messages" if self.provider == "minimax" and self.base_url.endswith("/anthropic") else "/messages"
headers = {
@@ -751,10 +777,15 @@ class ProviderService:
if not isinstance(item, dict)
else item.get("tool_calls")
)
or bool(
getattr(item, "thinking_blocks", None)
if not isinstance(item, dict)
else item.get("thinking_blocks")
)
)
for item in raw_items
)
if has_tool_turns:
if raw_items and (has_tool_turns or getattr(payload, "tools", None)):
preserved: list[dict[str, Any]] = []
for item in raw_items:
if isinstance(item, dict):
@@ -763,12 +794,14 @@ class ProviderService:
tool_call_id = item.get("tool_call_id")
name = item.get("name")
tool_calls = item.get("tool_calls")
thinking_blocks = item.get("thinking_blocks")
else:
role = str(getattr(item, "role", "") or "").strip().lower()
content = str(getattr(item, "content", "") or "")
tool_call_id = getattr(item, "tool_call_id", None)
name = getattr(item, "name", None)
tool_calls = getattr(item, "tool_calls", None)
thinking_blocks = getattr(item, "thinking_blocks", None)
if role not in {"user", "assistant", "tool"}:
continue
entry: dict[str, Any] = {"role": role, "content": content}
@@ -778,6 +811,8 @@ class ProviderService:
entry["name"] = str(name)
if tool_calls:
entry["tool_calls"] = list(tool_calls)
if thinking_blocks:
entry["thinking_blocks"] = list(thinking_blocks)
preserved.append(entry)
return preserved or [{"role": "user", "content": final_prompt}]
@@ -943,7 +978,14 @@ class ProviderService:
messages.append({"role": "system", "content": resolved_system_prompt})
source_messages = (
conversation_messages
if (conversation_messages and (len(conversation_messages) > 1 or any(m.get("role") == "tool" or m.get("tool_calls") for m in conversation_messages)))
if (
conversation_messages
and (
len(conversation_messages) > 1
or bool(tools)
or any(m.get("role") == "tool" or m.get("tool_calls") for m in conversation_messages)
)
)
else [{"role": "user", "content": prompt}]
)
for msg in source_messages:
@@ -1046,6 +1088,7 @@ class ProviderService:
conversation_messages
and (
len(conversation_messages) > 1
or bool(tools)
or any(m.get("role") == "tool" or m.get("tool_calls") for m in conversation_messages)
)
)
@@ -1480,3 +1523,52 @@ class ProviderService:
args = self._parse_tool_arguments(item.get("input"))
records.append(ToolCallRecord(id=call_id, name=name, arguments=args))
return records
@staticmethod
def _dedupe_urls(urls: list[str]) -> list[str]:
seen: set[str] = set()
out: list[str] = []
for raw in urls:
url = str(raw or "").strip()
if url.startswith(("http://", "https://")) and url not in seen:
seen.add(url)
out.append(url)
return out
def _extract_responses_citations(self, payload: dict[str, Any]) -> list[str]:
urls: list[str] = []
for item in payload.get("output") or []:
if not isinstance(item, dict):
continue
if item.get("type") == "message":
for part in item.get("content") or []:
if not isinstance(part, dict):
continue
for ann in part.get("annotations") or []:
if isinstance(ann, dict) and ann.get("type") == "url_citation" and ann.get("url"):
urls.append(str(ann["url"]))
elif item.get("type") == "web_search_call":
action = item.get("action") if isinstance(item.get("action"), dict) else {}
for src in action.get("sources") or []:
if isinstance(src, dict) and src.get("url"):
urls.append(str(src["url"]))
return self._dedupe_urls(urls)
def _extract_anthropic_citations(self, payload: dict[str, Any]) -> list[str]:
content = payload.get("content")
if not isinstance(content, list):
return []
urls: list[str] = []
for item in content:
if not isinstance(item, dict):
continue
item_type = str(item.get("type") or "")
if item_type == "web_search_tool_result":
for res in item.get("content") or []:
if isinstance(res, dict) and res.get("url"):
urls.append(str(res["url"]))
elif item_type == "text":
for cite in item.get("citations") or []:
if isinstance(cite, dict) and cite.get("url"):
urls.append(str(cite["url"]))
return self._dedupe_urls(urls)
+2
View File
@@ -9,6 +9,7 @@ class ChatMessage(BaseModel):
tool_call_id: str | None = Field(default=None, max_length=200)
name: str | None = Field(default=None, max_length=200)
tool_calls: list[dict[str, Any]] | None = None
thinking_blocks: list[dict[str, Any]] | None = None
class ToolCallRecord(BaseModel):
@@ -56,6 +57,7 @@ class SituationalAnalysisResponse(BaseModel):
text_blocks: list[str] = Field(default_factory=list)
thinking_blocks: list[str] = Field(default_factory=list)
tool_calls: list[ToolCallRecord] = Field(default_factory=list)
citation_urls: list[str] = Field(default_factory=list)
stop_reason: str | None = None
raw_response: dict[str, Any] = Field(default_factory=dict)
+23 -1
View File
@@ -4,6 +4,17 @@ ARG PYTHON_IMAGE=python:3.14-slim
ARG UV_IMAGE=ghcr.io/astral-sh/uv:latest
FROM ${UV_IMAGE} AS uv
# Earth boundary PMTiles builder (used by the Earth "高精" rebuild job).
FROM ${PYTHON_IMAGE} AS tippecanoe-build
ARG TIPPECANOE_REF=2.79.0
RUN apt-get update \
&& apt-get install -y --no-install-recommends build-essential ca-certificates git libsqlite3-dev zlib1g-dev \
&& rm -rf /var/lib/apt/lists/*
RUN git clone --depth 1 --branch "${TIPPECANOE_REF}" https://github.com/felt/tippecanoe.git /src/tippecanoe \
&& make -C /src/tippecanoe -j"$(nproc)" tippecanoe \
&& install -m 0755 /src/tippecanoe/tippecanoe /usr/local/bin/tippecanoe
FROM ${PYTHON_IMAGE}
COPY --from=uv /uv /uvx /bin/
@@ -20,8 +31,19 @@ RUN mkdir -p /root/.config/uv
RUN apt-get update && apt-get install -y --no-install-recommends \
curl \
libgl1 \
libglib2.0-0 \
libsm6 \
libsqlite3-0 \
libstdc++6 \
libxcb1 \
libxext6 \
libxrender1 \
zlib1g \
&& rm -rf /var/lib/apt/lists/*
COPY --from=tippecanoe-build /usr/local/bin/tippecanoe /usr/local/bin/tippecanoe
COPY pyproject.toml uv.lock /app/
RUN --mount=type=cache,target=/root/.cache/uv \
--mount=type=secret,id=planet_uv_config,target=/root/.config/uv/uv.toml,required=false \
@@ -29,8 +51,8 @@ RUN --mount=type=cache,target=/root/.cache/uv \
COPY backend /app/backend
COPY config/earth-boundary-pov-policy.china-v1.json /app/config/earth-boundary-pov-policy.china-v1.json
COPY scripts/build_earth_boundary_china_pov_geojson.py /app/scripts/build_earth_boundary_china_pov_geojson.py
COPY scripts/build_earth_boundary_pmtiles.py /app/scripts/build_earth_boundary_pmtiles.py
COPY scripts/earth_boundary_geometry.py /app/scripts/earth_boundary_geometry.py
COPY scripts/db_migrate.py /app/scripts/db_migrate.py
COPY scripts/earth_boundary_policy.py /app/scripts/earth_boundary_policy.py
COPY resources/earth/boundary-pov-geometry.china-v1.json /app/resources/earth/boundary-pov-geometry.china-v1.json
+3 -11
View File
@@ -31,21 +31,13 @@
"system_prompt": "你是 BGP 值班分析师。请直接输出面向值班人员的中文 Markdown 简报,只写最终研判内容;不要复述用户需求、提示词、写作计划、字段清单或“我将如何回答”。",
"prompt": "基于当前 BGP incidents、anomalies、原始观测事件、观测站覆盖与 prefix geography 证据,生成一份面向操作员的简明态势简报,突出区域热点、观测偏差、当前风险、证据和优先动作。"
},
{
"key": "location.factcheck.normalize",
"label": "位置事实核查结构化",
"group": "位置解析",
"version": "2026-05-16.1",
"system_prompt": "",
"prompt": "Convert the supplied location factcheck text into exactly one strict JSON object. Extract only facts present in the text or original query."
},
{
"key": "location.factcheck.resolve",
"label": "位置事实核查兜底",
"label": "位置事实核查单轮研判",
"group": "位置解析",
"version": "2026-05-16.1",
"version": "2026-12-03.3",
"system_prompt": "",
"prompt": "Return exactly one JSON object for the most likely physical location. Use only fact-checkable public knowledge; return null fields rather than guessing when evidence is weak."
"prompt": "严格基于输入的 evidence_items(编号 E1..En)与目标元数据判断物理部署城市与园区,输出严格 JSON 对象,禁止编造坐标或证据列表外的引用;reasoning 与 country_override_reason 必须使用不超过 120 字的简洁简体中文,严禁出现 E1、E6 等内部证据编号。"
},
{
"key": "datasource.mapping",
+6
View File
@@ -15,7 +15,9 @@ from app.api.v1 import (
alerts,
settings,
collected_data,
cloud_analysis,
compute_intelligence,
data_ledger,
data_products,
layers,
visualization,
@@ -28,6 +30,7 @@ from app.api.v1 import (
situational_awareness,
system_control,
tv,
wind_analysis,
)
api_router = APIRouter()
@@ -40,6 +43,7 @@ api_router.include_router(
)
api_router.include_router(datasources.router, prefix="/datasources", tags=["datasources"])
api_router.include_router(collected_data.router, prefix="/collected", tags=["collected-data"])
api_router.include_router(data_ledger.router, prefix="/data-ledger", tags=["data-ledger"])
api_router.include_router(docs.router, prefix="/docs", tags=["docs"])
api_router.include_router(earth.router, prefix="/earth", tags=["earth"])
api_router.include_router(client_updates.router, prefix="/client", tags=["client-updates"])
@@ -50,6 +54,8 @@ api_router.include_router(settings.router, prefix="/settings", tags=["settings"]
api_router.include_router(system_control.router, prefix="/system", tags=["system"])
api_router.include_router(api_keys.router, prefix="/system/api-keys", tags=["api-keys"])
api_router.include_router(data_products.router, prefix="/data-products", tags=["data-products"])
api_router.include_router(cloud_analysis.router, prefix="/data-products/clouds", tags=["clouds"])
api_router.include_router(wind_analysis.router, prefix="/data-products/wind", tags=["wind"])
api_router.include_router(compute_intelligence.router, prefix="/data-products/compute", tags=["compute"])
api_router.include_router(
situational_awareness.router,
+32 -35
View File
@@ -29,11 +29,13 @@ from app.services.ai.tool_registry import (
safe_web_fetch,
)
from app.services.ai.workflow_evolver import (
FIXTURE_EXPECT_KEY,
compute_workflow_health,
dismiss_ledger_entry,
get_evolution_ledger,
get_evolution_policy,
incubate_workflow_from_runs,
normalize_fixture_expect,
propose_meta_evolution,
propose_workflow_evolution,
record_run_feedback,
@@ -61,12 +63,8 @@ from app.services.ai_client import get_ai_provider_client
from app.services.alert_ai_brief import build_alert_brief_request
from app.services.bgp_ai_brief import build_bgp_brief_request
from app.services.compute_center_locations import build_compute_center_location_query
from app.services.location.agent_resolver import (
run_controlled_location_agent,
run_l1_structured_facility_resolvers,
)
from app.services.location.workflow_tools import run_location_workflow
from app.services.situational_alert_ai_brief import build_situational_alert_brief_request
from app.api.v1.settings import get_web_search_client
router = APIRouter()
logger = get_logger(__name__, service="ai_workflows")
@@ -176,6 +174,9 @@ class WorkflowFixtureCreateRequest(BaseModel):
earth_context: dict[str, Any] = Field(default_factory=dict)
context_json: dict[str, Any] | None = None
sample_question: str = ""
# Gradable assertions: numbers / must_include / must_not_include /
# require_uncertainty_without_evidence / min_evidence (stored in context_json["expect"]).
expect: dict[str, Any] | None = None
class AdvisorChatMessageInput(BaseModel):
@@ -421,6 +422,12 @@ async def create_ai_workflow_fixture(
ctx_payload = dict(payload.context_json if payload.context_json is not None else payload.earth_context or {})
if payload.description.strip() and "_description" not in ctx_payload:
ctx_payload["_description"] = payload.description.strip()
expect = normalize_fixture_expect(
payload.expect if payload.expect is not None else ctx_payload.get(FIXTURE_EXPECT_KEY)
)
ctx_payload.pop(FIXTURE_EXPECT_KEY, None)
if expect:
ctx_payload[FIXTURE_EXPECT_KEY] = expect
row = AIWorkflowFixture(
workflow_id=workflow_id,
name=payload.name.strip(),
@@ -690,41 +697,20 @@ async def _resolve_playground_slash_or_workflow(
active_wf = "location.resolve_unknown"
target_name = trimmed[len("/locate") :].strip() or "Unknown Facility"
query = build_compute_center_location_query(name=target_name)
l1_candidates, _, _ = await run_l1_structured_facility_resolvers(query, db=db)
tool_trace.extend(["l0_normalize", "l1_knowledge"])
if l1_candidates:
c0 = l1_candidates[0]
extra_meta["direct_reply"] = (
f"已通过 **L1 设施知识库** (`{c0.source}`) 定位到 **{c0.display_name}**:\n\n"
f"- 国家/地区:{c0.country or '-'}\n"
f"- 坐标:`{c0.latitude:.5f}, {c0.longitude:.5f}`(精度 `{c0.precision}`,置信度 `{c0.confidence:.2f}`)\n"
f"- 说明:{c0.source_note}"
)
return active_wf, tool_trace, None, extra_meta
try:
provider_client = await get_ai_provider_client(db)
web_search_client = await get_web_search_client(db)
res, term = await run_controlled_location_agent(
provider_client=provider_client,
web_search_client=web_search_client,
res = await run_location_workflow(
db=db,
query=query,
entity_type="compute_center",
db=db,
earth_context=earth_context if isinstance(earth_context, dict) else {},
use_draft=use_draft,
record_run=False,
trigger_evolution=False,
)
tool_trace.extend(["l2_agent_research", "l3_geo_guardrail"])
if res.candidates:
c0 = res.candidates[0]
extra_meta["direct_reply"] = (
f"已通过 **L2/L3 位置 Agent** 核验 **{c0.display_name}**:\n\n"
f"- 坐标:`{c0.latitude:.5f}, {c0.longitude:.5f}`(精度 `{c0.precision}`)\n"
f"- 结论:{c0.source_note}"
)
elif term:
extra_meta["direct_reply"] = f"位置 Agent 判定该目标属于终态 `{term}`:{res.failure_reason or ''}"
else:
extra_meta["direct_reply"] = f"未能定位目标「{target_name}」:{res.failure_reason or '暂无可核验公开证据'}。"
tool_trace.extend(res.get("tool_trace") or ["l0_normalize"])
extra_meta["direct_reply"] = res.get("answer_markdown") or f"未能定位目标「{target_name}」。"
except Exception as exc:
extra_meta["direct_reply"] = f"位置 Agent 调试执行失败:{exc}"
extra_meta["direct_reply"] = f"位置工作流调试执行失败:{exc}"
extra_meta["direct_reply_error"] = str(exc)
return active_wf, tool_trace, None, extra_meta
@@ -863,6 +849,7 @@ async def stream_advisor_playground_chat(
error_text = ""
resolved_model = str(payload.model_override or "").strip()
resolved_provider = ""
verification: dict[str, Any] = {}
workflow_revision = 1
is_slash_cmd = effective_message.strip().startswith(
("/bgp-brief", "/alerts-brief", "/situational-brief", "/locate")
@@ -996,6 +983,8 @@ async def stream_advisor_playground_chat(
resolved_model = str(ev_data["model"])
if ev_data.get("provider"):
resolved_provider = str(ev_data["provider"])
if isinstance(ev_data.get("verification"), dict):
verification = ev_data["verification"]
elif ev_name == "error":
status_value = "failed"
error_text = str(ev_data.get("message") or "Workflow execution failed")
@@ -1035,6 +1024,14 @@ async def stream_advisor_playground_chat(
"provider": resolved_provider,
"latency_ms": latency_ms,
"workflow_revision": workflow_revision,
**(
{
"verification_passed": bool(verification.get("passed", True)),
"verification_warnings": list(verification.get("warnings") or [])[:6],
}
if verification
else {}
),
},
error_message=error_text[:500],
started_at=started_at,
+2 -1
View File
@@ -528,7 +528,8 @@ async def create_earth_session(
detail="Too many desktop Earth session requests",
)
client_header = await verify_desktop_handshake(request)
token, ttl_seconds = create_earth_session_token("desktop", client_id=client_header)
desktop_client_id = f"{client_ip}:{client_header}"
token, ttl_seconds = create_earth_session_token("desktop", client_id=desktop_client_id)
return {
"token": token,
"expires_in": ttl_seconds,
+48 -52
View File
@@ -15,16 +15,10 @@ from app.models.bgp_observation import BGPObservation
from app.models.user import User
from app.services.bgp_collector_locations import (
build_bgp_collector_location_query,
collect_bgp_collector_location_candidates,
get_bgp_collector_location_dict,
)
from app.services.bgp_collectors import build_bgp_collector_coverage
from app.services.ai_client import get_ai_provider_client
from app.api.v1.settings import get_web_search_client
from app.services.location.llm_fallback import (
collect_llm_location_fallback_candidate,
collect_location_search_evidence,
)
from app.services.location.workflow_tools import run_location_workflow
router = APIRouter()
@@ -307,56 +301,56 @@ async def collect_bgp_collector_location(
city = payload.city or legacy.get("city")
country = payload.country or legacy.get("country")
operator = payload.operator or "RIPE NCC"
candidates, attempted_queries = collect_bgp_collector_location_candidates(
query = build_bgp_collector_location_query(
collector=collector_id,
site=site,
city=city,
country=country,
operator=operator,
)
llm_failure_reason = None
if not candidates:
query = build_bgp_collector_location_query(
collector=collector_id,
site=site,
city=city,
country=country,
operator=operator,
)
llm_result = None
try:
web_search_client = await get_web_search_client(db)
search_result = await collect_location_search_evidence(
web_search_client=web_search_client,
query=query,
entity_type="bgp_collector",
)
attempted_queries = [*attempted_queries, *search_result.attempted_queries]
if not search_result.evidence:
llm_failure_reason = search_result.failure_reason
raise RuntimeError(search_result.failure_reason or "no WebSearch evidence")
provider_client = await get_ai_provider_client(db)
llm_result = await collect_llm_location_fallback_candidate(
provider_client=provider_client,
query=query,
entity_type="bgp_collector",
db=db,
attempted_queries=attempted_queries,
search_evidence=search_result.evidence,
)
except Exception as exc:
if llm_failure_reason is None:
llm_failure_reason = f"LLM location factcheck unavailable: {exc}"
attempted_queries = [
*attempted_queries,
f"llm_factcheck:bgp_collector:{collector_id or 'unknown'}",
]
if llm_result is not None:
attempted_queries = [*attempted_queries, *llm_result.attempted_queries]
candidates = llm_result.candidates
llm_failure_reason = llm_result.failure_reason
try:
res = await run_location_workflow(
db=db,
query=query,
entity_type="bgp_collector",
earth_context={
"collector_id": collector_id,
"name": collector_id,
"site": site,
"city": city,
"country": country,
"operator": operator,
},
record_run=True,
trigger_evolution=True,
)
except Exception as exc:
return {
"collector_id": collector_id,
"name": collector_id,
"success": False,
"failure_reason": (
"No source coordinates or online geocoding result reached"
" city-level precision for this collector."
),
"candidates": [],
"attempted_queries": [],
"llm_failure_reason": f"Location workflow unavailable: {exc}",
"workflow_run_id": None,
"context": {
"collector": collector_id,
"site": site,
"city": city,
"country": country,
"operator": operator,
},
}
candidates = res.get("candidates") or []
attempted_queries = list(res.get("attempted_queries") or [])
llm_failure_reason = res.get("failure_reason")
workflow_run_id = res.get("workflow_run_id")
context = {
"collector": collector_id,
"site": site,
@@ -375,8 +369,9 @@ async def collect_bgp_collector_location(
" city-level precision for this collector."
),
"candidates": [],
"attempted_queries": list(attempted_queries),
"attempted_queries": attempted_queries,
"llm_failure_reason": llm_failure_reason,
"workflow_run_id": workflow_run_id,
"context": context,
}
@@ -386,7 +381,8 @@ async def collect_bgp_collector_location(
"success": True,
"candidates": [candidate.to_dict() for candidate in candidates],
"best_candidate": candidates[0].to_dict(),
"attempted_queries": list(attempted_queries),
"attempted_queries": attempted_queries,
"workflow_run_id": workflow_run_id,
"context": context,
}
+56
View File
@@ -0,0 +1,56 @@
"""Real-time cloud map spatial analytics & asset correlation APIs."""
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, Query
from pydantic import BaseModel, Field
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_earth_or_api_access
from app.core.security import get_current_user
from app.db.session import get_db
from app.models.user import User
from app.services.earth_clouds import (
correlate_cloud_with_assets,
get_cloud_analysis_summary,
query_cloud_point,
)
router = APIRouter()
class CloudAssetCorrelateRequest(BaseModel):
domain: str = Field(default="vessels")
min_density: float = Field(default=55.0, ge=0.0, le=100.0)
limit: int = Field(default=25, ge=1, le=100)
@router.get("/summary", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_clouds_summary(db: AsyncSession = Depends(get_db)):
return await get_cloud_analysis_summary(db)
@router.get("/point", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_clouds_point(
lat: float = Query(..., ge=-90.0, le=90.0),
lon: float = Query(..., ge=-180.0, le=180.0),
db: AsyncSession = Depends(get_db),
):
return await query_cloud_point(lat, lon, db=db)
@router.post("/correlate")
async def post_clouds_correlate(
payload: CloudAssetCorrelateRequest,
_current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
try:
return await correlate_cloud_with_assets(
db,
domain=payload.domain,
min_density=payload.min_density,
limit=payload.limit,
)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
+279 -157
View File
@@ -1,23 +1,32 @@
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status, Response
from fastapi.responses import StreamingResponse
from sqlalchemy import select, func, text
from sqlalchemy.ext.asyncio import AsyncSession
import json
import csv
import hashlib
import io
import json
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, status
from fastapi.responses import StreamingResponse
from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.cache import cache
from app.core.collected_data_fields import get_metadata_field
from app.core.countries import COUNTRY_OPTIONS, get_country_search_variants, normalize_country
from app.core.security import get_current_user
from app.core.time import to_iso8601_utc
from app.db.session import get_db
from app.models.user import User
from app.core.security import get_current_user
from app.models.collected_data import CollectedData
from app.models.datasource import DataSource
from app.models.user import User
router = APIRouter()
DEFAULT_EXCLUDED_DATA_TYPES: tuple[str, ...] = ("prefix_geography",)
DEFAULT_EXCLUDED_SOURCES: frozenset[str] = frozenset(
{"iptoasn_prefix_geo", "opengeofeed_prefix_geo", "nro_delegated_prefix_geo"}
)
COLLECTED_FACETS_CACHE_KEY = "collected:facets:v1"
COLLECTED_FACETS_TTL_SECONDS = 300
COLLECTED_SUMMARY_TTL_SECONDS = 60
COUNTRY_SQL = "metadata->>'country'"
SEARCHABLE_SQL = [
@@ -46,6 +55,50 @@ def build_in_condition(field_sql: str, values: list[str], param_prefix: str, par
return f"{field_sql} IN ({', '.join(placeholders)})"
def build_not_in_condition(field_sql: str, values: tuple[str, ...], param_prefix: str, params: dict) -> str:
placeholders = []
for index, value in enumerate(values):
key = f"{param_prefix}_{index}"
params[key] = value
placeholders.append(f":{key}")
return f"{field_sql} NOT IN ({', '.join(placeholders)})"
def _includes_default_excluded(source_values: list[str], data_type_values: list[str]) -> bool:
if any(dt in DEFAULT_EXCLUDED_DATA_TYPES for dt in data_type_values):
return True
if any(src in DEFAULT_EXCLUDED_SOURCES for src in source_values):
return True
return False
def _facets_cache_key(mode: str) -> str:
return COLLECTED_FACETS_CACHE_KEY if mode != "history" else f"{COLLECTED_FACETS_CACHE_KEY}:history"
def _summary_cache_key(
*,
mode: str,
source: Optional[str],
data_type: Optional[str],
country: Optional[str],
search: Optional[str],
) -> str:
payload = json.dumps(
{
"mode": "history" if mode == "history" else "current",
"source": source or "",
"data_type": data_type or "",
"country": country or "",
"search": (search or "").strip(),
},
sort_keys=True,
ensure_ascii=False,
)
digest = hashlib.sha256(payload.encode("utf-8")).hexdigest()[:24]
return f"collected:summary:v1:{digest}"
def build_search_condition(search: Optional[str], params: dict) -> Optional[str]:
if not search:
return None
@@ -108,7 +161,14 @@ def serialize_collected_row(
*,
include_metadata: bool = True,
) -> dict:
metadata = row[7]
raw_metadata = row[7]
if isinstance(raw_metadata, str):
try:
metadata = json.loads(raw_metadata)
except json.JSONDecodeError:
metadata = None
else:
metadata = raw_metadata
source = row[1]
return {
"id": row[0],
@@ -141,6 +201,43 @@ async def get_source_name_map(db: AsyncSession) -> dict[str, str]:
return {row[0]: row[1] for row in result.fetchall()}
async def _load_collected_facets(
db: AsyncSession,
*,
mode: str,
source_name_map: dict[str, str] | None = None,
) -> list[dict]:
cache_key = _facets_cache_key(mode)
cached_facets = cache.get(cache_key)
if isinstance(cached_facets, list):
return cached_facets
where_sql = "is_current IS TRUE" if mode != "history" else "1=1"
result = await db.execute(
text(
f"""
SELECT source, data_type, COUNT(*) AS count
FROM collected_data
WHERE {where_sql}
GROUP BY source, data_type
ORDER BY source, data_type
"""
)
)
names = source_name_map if source_name_map is not None else await get_source_name_map(db)
facets = [
{
"source": row[0],
"source_name": names.get(row[0], row[0]),
"data_type": row[1],
"count": int(row[2] or 0),
}
for row in result.fetchall()
]
cache.set(cache_key, facets, expire_seconds=COLLECTED_FACETS_TTL_SECONDS)
return facets
@router.get("")
async def list_collected_data(
mode: str = Query("current", description="查询模式: current/history"),
@@ -155,55 +252,64 @@ async def list_collected_data(
db: AsyncSession = Depends(get_db),
):
"""查询采集的数据列表"""
normalized_country = normalize_country(country) if country else None
source_values = parse_multi_values(source)
data_type_values = parse_multi_values(data_type)
# Build WHERE clause
conditions = []
params = {}
if mode != "history":
conditions.append("COALESCE(is_current, TRUE) = TRUE")
if source_values:
conditions.append(build_in_condition("source", source_values, "source", params))
if data_type_values:
conditions.append(build_in_condition("data_type", data_type_values, "data_type", params))
if normalized_country:
conditions.append(f"{COUNTRY_SQL} = :country")
params["country"] = normalized_country
search_condition = build_search_condition(search, params)
if search_condition:
conditions.append(search_condition)
where_sql = " AND ".join(conditions) if conditions else "1=1"
search_rank_sql = build_search_rank_sql(search)
where_sql, params, include_excluded = build_where_clause(
source,
data_type,
country,
search,
mode=mode,
)
has_search = bool(search and search.strip())
# Calculate offset
offset = (page - 1) * page_size
source_name_map = await get_source_name_map(db)
# Query total count
count_query = text(f"SELECT COUNT(*) FROM collected_data WHERE {where_sql}")
count_result = await db.execute(count_query, params)
total = count_result.scalar()
if not country and not has_search:
facets = await _load_collected_facets(db, mode=mode, source_name_map=source_name_map)
source_set = set(parse_multi_values(source))
type_set = set(parse_multi_values(data_type))
total = sum(
item["count"]
for item in facets
if (include_excluded or item["data_type"] not in DEFAULT_EXCLUDED_DATA_TYPES)
and (not source_set or item["source"] in source_set)
and (not type_set or item["data_type"] in type_set)
)
else:
count_query = text(f"SELECT COUNT(*) FROM collected_data WHERE {where_sql}")
count_result = await db.execute(count_query, params)
total = int(count_result.scalar() or 0)
# Query data
query = text(f"""
SELECT id, source, source_id, data_type, name, title, description,
metadata, collected_at, reference_date, is_valid,
{search_rank_sql} AS search_rank
FROM collected_data
WHERE {where_sql}
ORDER BY search_rank DESC, collected_at DESC
LIMIT :limit OFFSET :offset
""")
params["limit"] = page_size
params["offset"] = offset
if has_search:
search_rank_sql = build_search_rank_sql(search)
query = text(
f"""
SELECT id, source, source_id, data_type, name, title, description,
metadata, collected_at, reference_date, is_valid,
{search_rank_sql} AS search_rank
FROM collected_data
WHERE {where_sql}
ORDER BY search_rank DESC, collected_at DESC
LIMIT :limit OFFSET :offset
"""
)
else:
query = text(
f"""
SELECT id, source, source_id, data_type, name, title, description,
metadata, collected_at, reference_date, is_valid
FROM collected_data
WHERE {where_sql}
ORDER BY collected_at DESC
LIMIT :limit OFFSET :offset
"""
)
result = await db.execute(query, params)
rows = result.fetchall()
source_name_map = await get_source_name_map(db)
data = []
for row in rows:
@@ -217,6 +323,40 @@ async def list_collected_data(
}
def _aggregate_summary_from_facets(facets: list[dict], *, overall_total: int) -> dict:
by_source: dict[str, dict[str, int]] = {}
source_acc: dict[str, dict] = {}
type_acc: dict[str, int] = {}
total = 0
for item in facets:
src = str(item["source"])
src_name = str(item.get("source_name") or src)
dt = str(item["data_type"])
cnt = int(item["count"] or 0)
if cnt <= 0:
continue
by_source.setdefault(src_name, {})[dt] = by_source.get(src_name, {}).get(dt, 0) + cnt
if src not in source_acc:
source_acc[src] = {"source": src, "source_name": src_name, "count": 0}
source_acc[src]["count"] += cnt
type_acc[dt] = type_acc.get(dt, 0) + cnt
total += cnt
source_totals = sorted(source_acc.values(), key=lambda x: (-x["count"], x["source"]))
type_totals = [
{"data_type": dt, "count": cnt}
for dt, cnt in sorted(type_acc.items(), key=lambda item: (-item[1], item[0]))
]
return {
"total_records": total,
"overall_total_records": overall_total,
"by_source": by_source,
"source_totals": source_totals,
"type_totals": type_totals,
}
@router.get("/summary")
async def get_data_summary(
mode: str = Query("current", description="查询模式: current/history"),
@@ -228,89 +368,76 @@ async def get_data_summary(
db: AsyncSession = Depends(get_db),
):
"""获取数据汇总统计"""
where_sql, params = build_where_clause(source, data_type, country, search)
if mode != "history":
where_sql = f"({where_sql}) AND COALESCE(is_current, TRUE) = TRUE"
overall_where_sql = "COALESCE(is_current, TRUE) = TRUE" if mode != "history" else "1=1"
overall_total_result = await db.execute(
text(f"SELECT COUNT(*) FROM collected_data WHERE {overall_where_sql}")
cache_key = _summary_cache_key(
mode=mode,
source=source,
data_type=data_type,
country=country,
search=search,
)
overall_total = overall_total_result.scalar() or 0
cached_summary = cache.get(cache_key)
if isinstance(cached_summary, dict):
return cached_summary
# By source and data_type
result = await db.execute(
text(f"""
SELECT source, data_type, COUNT(*) as count
FROM collected_data
WHERE {where_sql}
GROUP BY source, data_type
ORDER BY source, data_type
"""),
params,
)
rows = result.fetchall()
source_name_map = await get_source_name_map(db)
by_source = {}
total = 0
for row in rows:
source = row[0]
data_type = row[1]
count = row[2]
source_key = source_name_map.get(source, source)
if source_key not in by_source:
by_source[source_key] = {}
by_source[source_key][data_type] = count
total += count
# Total by source
source_totals = await db.execute(
text(f"""
SELECT source, COUNT(*) as count
FROM collected_data
WHERE {where_sql}
GROUP BY source
ORDER BY count DESC
"""),
params,
unfiltered_facets = await _load_collected_facets(
db, mode=mode, source_name_map=source_name_map
)
source_rows = source_totals.fetchall()
type_totals = await db.execute(
text(f"""
SELECT data_type, COUNT(*) as count
FROM collected_data
WHERE {where_sql}
GROUP BY data_type
ORDER BY count DESC, data_type
"""),
params,
source_values = parse_multi_values(source)
data_type_values = parse_multi_values(data_type)
include_excluded = _includes_default_excluded(source_values, data_type_values)
overall_total = sum(
int(item["count"] or 0)
for item in unfiltered_facets
if include_excluded or item["data_type"] not in DEFAULT_EXCLUDED_DATA_TYPES
)
type_rows = type_totals.fetchall()
return {
"total_records": total,
"overall_total_records": overall_total,
"by_source": by_source,
"source_totals": [
normalized_country = normalize_country(country) if country else None
has_search = bool(search and search.strip())
if not normalized_country and not has_search:
source_set = set(source_values)
type_set = set(data_type_values)
filtered_facets = [
item
for item in unfiltered_facets
if (include_excluded or item["data_type"] not in DEFAULT_EXCLUDED_DATA_TYPES)
and (not source_set or item["source"] in source_set)
and (not type_set or item["data_type"] in type_set)
]
else:
where_sql, params, _ = build_where_clause(
source,
data_type,
country,
search,
mode=mode,
)
result = await db.execute(
text(
f"""
SELECT source, data_type, COUNT(*) AS count
FROM collected_data
WHERE {where_sql}
GROUP BY source, data_type
ORDER BY source, data_type
"""
),
params,
)
filtered_facets = [
{
"source": row[0],
"source_name": source_name_map.get(row[0], row[0]),
"count": row[1],
"data_type": row[1],
"count": int(row[2] or 0),
}
for row in source_rows
],
"type_totals": [
{
"data_type": row[0],
"count": row[1],
}
for row in type_rows
],
}
for row in result.fetchall()
]
payload = _aggregate_summary_from_facets(filtered_facets, overall_total=overall_total)
cache.set(cache_key, payload, expire_seconds=COLLECTED_SUMMARY_TTL_SECONDS)
return payload
@router.get("/sources")
@@ -320,21 +447,17 @@ async def get_data_sources(
db: AsyncSession = Depends(get_db),
):
"""获取所有数据源列表"""
result = await db.execute(
text("""
SELECT DISTINCT source FROM collected_data
""" + ("WHERE COALESCE(is_current, TRUE) = TRUE " if mode != "history" else "") + """
ORDER BY source
""")
)
rows = result.fetchall()
source_name_map = await get_source_name_map(db)
facets = await _load_collected_facets(db, mode=mode)
seen: dict[str, str] = {}
for item in facets:
src = str(item["source"])
if src not in seen:
seen[src] = str(item.get("source_name") or src)
return {
"sources": [
{"source": row[0], "source_name": source_name_map.get(row[0], row[0])}
for row in rows
{"source": src, "source_name": seen[src]}
for src in sorted(seen.keys())
],
}
@@ -346,18 +469,10 @@ async def get_data_types(
db: AsyncSession = Depends(get_db),
):
"""获取所有数据类型列表"""
result = await db.execute(
text("""
SELECT DISTINCT data_type FROM collected_data
""" + ("WHERE COALESCE(is_current, TRUE) = TRUE " if mode != "history" else "") + """
ORDER BY data_type
""")
)
rows = result.fetchall()
facets = await _load_collected_facets(db, mode=mode)
types = sorted({str(item["data_type"]) for item in facets if item.get("data_type")})
return {
"data_types": [row[0] for row in rows],
"data_types": types,
}
@@ -403,20 +518,31 @@ async def get_collected_data(
def build_where_clause(
source: Optional[str], data_type: Optional[str], country: Optional[str], search: Optional[str]
):
"""Build WHERE clause and params for queries"""
source: Optional[str],
data_type: Optional[str],
country: Optional[str],
search: Optional[str],
*,
mode: str = "current",
) -> tuple[str, dict, bool]:
"""Build WHERE clause and params for queries."""
conditions = []
params = {}
params: dict = {}
if mode != "history":
conditions.append("is_current IS TRUE")
source_values = parse_multi_values(source)
data_type_values = parse_multi_values(data_type)
include_excluded = _includes_default_excluded(source_values, data_type_values)
if source_values:
conditions.append(build_in_condition("source", source_values, "source", params))
if data_type_values:
conditions.append(build_in_condition("data_type", data_type_values, "data_type", params))
normalized_country = normalize_country(country) if country else None
if not include_excluded and DEFAULT_EXCLUDED_DATA_TYPES:
conditions.append(build_not_in_condition("data_type", DEFAULT_EXCLUDED_DATA_TYPES, "excl_dt", params))
normalized_country = normalize_country(country) if country else None
if normalized_country:
conditions.append(f"{COUNTRY_SQL} = :country")
params["country"] = normalized_country
@@ -425,7 +551,7 @@ def build_where_clause(
conditions.append(search_condition)
where_sql = " AND ".join(conditions) if conditions else "1=1"
return where_sql, params
return where_sql, params, include_excluded
@router.get("/export/json")
@@ -441,9 +567,7 @@ async def export_json(
):
"""导出数据为 JSON 格式"""
where_sql, params = build_where_clause(source, data_type, country, search)
if mode != "history":
where_sql = f"({where_sql}) AND COALESCE(is_current, TRUE) = TRUE"
where_sql, params, _ = build_where_clause(source, data_type, country, search, mode=mode)
params["limit"] = limit
query = text(f"""
@@ -486,9 +610,7 @@ async def export_csv(
):
"""导出数据为 CSV 格式"""
where_sql, params = build_where_clause(source, data_type, country, search)
if mode != "history":
where_sql = f"({where_sql}) AND COALESCE(is_current, TRUE) = TRUE"
where_sql, params, _ = build_where_clause(source, data_type, country, search, mode=mode)
params["limit"] = limit
query = text(f"""
+149 -23
View File
@@ -1,7 +1,6 @@
"""Compute observations, administrator configuration and independent facility samples."""
from datetime import UTC, datetime
from typing import Literal
from datetime import UTC, date, datetime
from app.core.compute_types import COMPUTE_SITE_TYPES, compute_record_filter, compute_site_type_expression
from app.api.v1.visualization import convert_compute_centers_to_geojson
@@ -9,10 +8,11 @@ from app.core.access_gate import require_earth_or_api_access
from app.core.earth_geography_policy import display_country
from app.core.enums import UserRole
from app.core.logging import get_logger
from app.core.security import get_current_user
from app.core.security import get_current_user, get_optional_current_user
from app.core.websocket.broadcaster import broadcaster
from app.db.session import get_db
from app.models.collected_data import CollectedData
from app.models.compute_configuration_revision import ComputeConfigurationRevision
from app.models.data_snapshot import DataSnapshot
from app.models.user import User
from app.schemas.compute_configuration import (
@@ -30,10 +30,12 @@ from app.services.compute_center_locations import refresh_compute_center_locatio
from app.services.compute_configuration import (
DEFAULT_CONFIGURATION,
configuration_response,
list_configuration_revisions,
publish_configuration,
read_configuration,
)
from app.services.compute_history import ComputeSeriesMode, compute_history
from app.services.compute_lineage import build_observation_lineage, is_admin_user
from fastapi import APIRouter, Depends, HTTPException, Query, Response
from sqlalchemy import and_, case, func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -71,13 +73,35 @@ async def get_series(
countries: str = "CN,US",
mode: ComputeSeriesMode = "global_share",
db: AsyncSession = Depends(get_db),
as_of: str | None = None,
publish_id: str | None = None,
):
codes = selected_countries(countries)
envelope = await read_configuration(db)
envelope = await read_configuration(db, as_of=as_of, publish_id=publish_id)
response.headers["Cache-Control"] = "no-store"
if envelope.get("snapshot_unavailable"):
empty_cfg = ComputeConfiguration(
reviewed_at=date.today(), sources=[], observations=[], innovation=[]
)
result = compute_history(codes, mode, empty_cfg)
result.update(
version=None,
publish_id=None,
published_at=None,
as_of=envelope.get("as_of"),
snapshot_unavailable=True,
notice=envelope.get("notice"),
provenance="snapshot_unavailable",
)
return result
result = compute_history(codes, mode, ComputeConfiguration.model_validate(envelope["config"]))
effective_pid = envelope.get("publish_id") or envelope["revision"]
result.update(
version=envelope["revision"],
version=effective_pid,
publish_id=effective_pid,
published_at=envelope.get("published_at"),
as_of=envelope.get("as_of"),
snapshot_unavailable=False,
provenance="bundled_reports" if envelope["is_default"] else "admin_curated_reports",
)
return result
@@ -99,6 +123,108 @@ async def get_configuration(
return configuration_response(await read_configuration(db))
@router.get("/revisions")
async def get_configuration_revisions(
response: Response,
limit: int = Query(20, ge=1, le=100),
_actor: User = Depends(configuration_admin),
db: AsyncSession = Depends(get_db),
):
response.headers["Cache-Control"] = "no-store"
items = await list_configuration_revisions(db, limit=limit, redact=False)
return {"items": items}
@router.get(
"/revisions/public",
dependencies=[Depends(require_earth_or_api_access("data_products:read"))],
)
async def get_public_configuration_revisions(
response: Response,
limit: int = Query(20, ge=1, le=50),
db: AsyncSession = Depends(get_db),
):
response.headers["Cache-Control"] = "no-store"
items = await list_configuration_revisions(db, limit=limit, redact=True)
return {"items": items}
@router.get(
"/lineage",
dependencies=[Depends(require_earth_or_api_access("data_products:read"))],
)
async def get_compute_observation_lineage(
response: Response,
code: str = Query(..., min_length=2, max_length=32),
metric: ComputeSeriesMode = "global_share",
year: int = Query(..., ge=2000, le=2100),
publish_id: str | None = None,
as_of: str | None = None,
current_user: User | None = Depends(get_optional_current_user),
db: AsyncSession = Depends(get_db),
):
response.headers["Cache-Control"] = "no-store"
return await build_observation_lineage(
db,
code=code,
metric=metric,
year=year,
publish_id=publish_id,
as_of=as_of,
redact=not is_admin_user(current_user),
)
async def _deliver_revision_presentation(
db: AsyncSession,
envelope: dict,
) -> dict:
"""Trigger revision-driven presentation after commit; record failures for scheduled retry."""
publish_id = envelope.get("publish_id") or envelope.get("revision")
if not publish_id or envelope.get("no_changes"):
return envelope
rev_row = (
await db.execute(
select(ComputeConfigurationRevision).where(
ComputeConfigurationRevision.publish_id == publish_id
)
)
).scalar_one_or_none()
if not isinstance(rev_row, ComputeConfigurationRevision):
return envelope
if rev_row.presentation_status == "skipped":
envelope["presentation_status"] = "skipped"
return envelope
from app.services.ai.proactive_pipeline import process_compute_revision_presentation
try:
res = await process_compute_revision_presentation(db, rev_row.id)
await db.commit()
envelope["presentation_status"] = str(res.get("status") or rev_row.presentation_status)
except Exception as exc:
await db.rollback()
logger.warning_event(
"Compute revision presentation failed; queued for retry",
event="compute.revision.presentation_failed",
context={"publish_id": publish_id, "revision_id": rev_row.id, "error": str(exc)},
)
failed_row = (
await db.execute(
select(ComputeConfigurationRevision).where(
ComputeConfigurationRevision.publish_id == publish_id
)
)
).scalar_one_or_none()
if isinstance(failed_row, ComputeConfigurationRevision):
failed_row.presentation_status = "failed"
failed_row.presentation_attempts = int(failed_row.presentation_attempts or 0) + 1
failed_row.presentation_error = str(exc)[:1000]
await db.commit()
envelope["presentation_status"] = "failed"
return envelope
@router.put("/configuration")
async def update_configuration(
payload: ComputeConfigurationWrite,
@@ -106,16 +232,16 @@ async def update_configuration(
db: AsyncSession = Depends(get_db),
):
envelope = await publish_configuration(
db, revision=payload.revision, config=payload.config, actor=actor,
db,
revision=payload.revision,
config=payload.config,
actor=actor,
publish_note=payload.publish_note,
source_candidate_ids=payload.source_candidate_ids,
)
try:
from app.services.ai.proactive_pipeline import process_compute_config_proactive_delta
await process_compute_config_proactive_delta(db)
await db.commit()
except Exception:
pass
await _broadcast_compute_configuration_update()
if not envelope.get("no_changes"):
envelope = await _deliver_revision_presentation(db, envelope)
await _broadcast_compute_configuration_update()
return configuration_response(envelope)
@@ -126,16 +252,16 @@ async def reset_configuration(
db: AsyncSession = Depends(get_db),
):
envelope = await publish_configuration(
db, revision=payload.revision, config=DEFAULT_CONFIGURATION, actor=actor, reset=True,
db,
revision=payload.revision,
config=DEFAULT_CONFIGURATION,
actor=actor,
reset=True,
publish_note=payload.publish_note,
)
try:
from app.services.ai.proactive_pipeline import process_compute_config_proactive_delta
await process_compute_config_proactive_delta(db)
await db.commit()
except Exception:
pass
await _broadcast_compute_configuration_update()
if not envelope.get("no_changes"):
envelope = await _deliver_revision_presentation(db, envelope)
await _broadcast_compute_configuration_update()
return configuration_response(envelope)
+958
View File
@@ -0,0 +1,958 @@
"""Admin layer-based data ledger APIs (read-only per-layer views + compute review)."""
from __future__ import annotations
from dataclasses import dataclass
import re
from typing import Any, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy import desc, func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.collected_data import DEFAULT_EXCLUDED_DATA_TYPES, _load_collected_facets
from app.api.v1.data_products import PRODUCT_DEFINITIONS
from app.core.cache import cache
from app.core.collected_data_fields import get_record_field
from app.core.compute_types import COMPUTE_SITE_TYPES, compute_record_filter, compute_site_type
from app.core.countries import normalize_country
from app.core.security import get_current_user
from app.core.time import to_iso8601_utc
from app.db.session import get_db
from app.models.bgp_collector_location import BGPCollectorLocation
from app.models.bgp_incident import BGPIncident
from app.models.collected_data import CollectedData
from app.models.compute_center_location import ComputeCenterLocationRecord
from app.models.datasource import DataSource
from app.models.earth_news import EarthNewsItem
from app.models.situational_assessment import WorkflowRun
from app.models.vessel import VesselCurrentState
from app.services.compute_center_locations import resolve_compute_center_location_full
from app.services.location.workflow_tools import (
TERMINAL_UNLOCATABLE_STATUSES,
sanitize_user_facing_reasoning,
)
router = APIRouter(dependencies=[Depends(get_current_user)])
DATA_LEDGER_LAYERS_CACHE_KEY = "data_ledger:layers:v2"
DATA_LEDGER_LAYERS_TTL_SECONDS = 60
LAYER_ORDER: tuple[str, ...] = (
"compute",
"satellites",
"cables",
"vessels",
"bgp",
"news",
"weather",
"geo",
)
LAYER_KINDS: dict[str, tuple[dict[str, str], ...]] = {
"cables": (
{"id": "submarine_cable", "label": "海缆系统"},
{"id": "landing_point", "label": "登陆点"},
{"id": "cable_landing_relation", "label": "海缆登陆关系"},
),
"bgp": (
{"id": "collectors", "label": "观测站"},
{"id": "incidents", "label": "BGP 事件"},
),
"news": (
{"id": "items", "label": "新闻条目"},
{"id": "live_streams", "label": "Live 直播源"},
),
"weather": (
{"id": "all", "label": "气象图层"},
{"id": "cloud_map_record", "label": "云图记录"},
{"id": "wind_field_record", "label": "风场记录"},
),
}
@dataclass(frozen=True)
class _CollectedLayerSpec:
data_types: tuple[str, ...]
columns: tuple[dict[str, str], ...]
include_data_type_col: bool = False
_COLLECTED_LAYER_SPECS: dict[str, _CollectedLayerSpec] = {
"satellites": _CollectedLayerSpec(
data_types=("satellite_tle",),
columns=(
{"key": "name", "label": "名称"},
{"key": "source_id", "label": "NORAD ID"},
{"key": "international_designator", "label": "国际编号"},
{"key": "constellation_group", "label": "星座分组"},
{"key": "inclination", "label": "轨道倾角"},
{"key": "source", "label": "数据源"},
{"key": "collected_at", "label": "采集时间"},
),
),
"cables": _CollectedLayerSpec(
data_types=("submarine_cable", "landing_point", "cable_landing_relation"),
columns=(
{"key": "name", "label": "名称"},
{"key": "source_id", "label": "原始 ID"},
{"key": "source", "label": "数据源"},
{"key": "country", "label": "国家/地区"},
{"key": "collected_at", "label": "采集时间"},
),
),
"news:live_streams": _CollectedLayerSpec(
data_types=("news_live_stream",),
columns=(
{"key": "name", "label": "频道名称"},
{"key": "source", "label": "数据源"},
{"key": "region", "label": "区域"},
{"key": "language", "label": "语言"},
{"key": "collected_at", "label": "采集时间"},
),
),
"weather": _CollectedLayerSpec(
data_types=("cloud_map_record", "wind_field_record"),
include_data_type_col=True,
columns=(
{"key": "name", "label": "名称"},
{"key": "data_type", "label": "数据类型"},
{"key": "source", "label": "数据源"},
{"key": "reference_date", "label": "观测时间"},
{"key": "collected_at", "label": "采集时间"},
),
),
"geo": _CollectedLayerSpec(
data_types=("earth_tile_pyramid",),
columns=(
{"key": "name", "label": "瓦片数据集"},
{"key": "source", "label": "数据源"},
{"key": "reference_date", "label": "参考日期"},
{"key": "collected_at", "label": "采集时间"},
),
),
}
_US_CA_STATE_ZIP_RE = re.compile(r"^[A-Z]{2}(?:\s+\d{5}(?:-\d{4})?)?$")
_POSTAL_PREFIX_RE = re.compile(r"^\d{4,6}(?:-\d{3,4})?\s+")
_POSTAL_SUFFIX_RE = re.compile(r"\s+\d{4,6}(?:-\d{3,4})?$")
_STREET_ADDRESS_RE = re.compile(
r"^\d+\s+.*\b(rd|road|ave|avenue|st|street|blvd|dr|drive|way|lane|pkwy|hwy|floor|suite|building)\b",
re.IGNORECASE,
)
_VAGUE_LOCATION_TOKENS = (
"on prem",
"various",
"multiple",
"global",
"nordics",
"europe",
"asia",
"unknown",
)
_US_STATE_NAMES = frozenset(
{
"alabama",
"alaska",
"arizona",
"arkansas",
"california",
"colorado",
"connecticut",
"delaware",
"florida",
"georgia",
"hawaii",
"idaho",
"illinois",
"indiana",
"iowa",
"kansas",
"kentucky",
"louisiana",
"maine",
"maryland",
"massachusetts",
"michigan",
"minnesota",
"mississippi",
"missouri",
"montana",
"nebraska",
"nevada",
"new hampshire",
"new jersey",
"new mexico",
"new york",
"north carolina",
"north dakota",
"ohio",
"oklahoma",
"oregon",
"pennsylvania",
"rhode island",
"south carolina",
"south dakota",
"tennessee",
"texas",
"utah",
"vermont",
"virginia",
"washington",
"west virginia",
"wisconsin",
"wyoming",
"district of columbia",
}
)
def _normalize_ledger_country(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
if not text:
return None
return normalize_country(text) or text
def _extract_city_from_location(location: Any, country: str | None = None) -> str | None:
if not isinstance(location, str):
return None
text = location.strip()
if not text:
return None
normalized_country = _normalize_ledger_country(country) if country else None
lines = [line.strip() for line in text.splitlines() if line.strip()]
for line in reversed(lines):
if "°" in line or '"' in line:
continue
lowered_line = line.casefold()
if any(token in lowered_line for token in _VAGUE_LOCATION_TOKENS):
continue
if "," not in line:
continue
parts = [part.strip() for part in line.split(",") if part.strip()]
while parts and normalize_country(parts[-1]) is not None:
parts.pop()
if not parts:
continue
if len(parts) >= 2:
tail = parts[-1]
if _US_CA_STATE_ZIP_RE.fullmatch(tail) or tail.casefold() in _US_STATE_NAMES:
parts.pop()
if not parts:
continue
candidate = parts[-1].strip()
candidate = _POSTAL_PREFIX_RE.sub("", candidate).strip()
candidate = _POSTAL_SUFFIX_RE.sub("", candidate).strip()
if not candidate or len(candidate) > 48:
continue
if candidate.isdigit():
continue
if _STREET_ADDRESS_RE.search(candidate):
continue
if normalize_country(candidate) is not None:
continue
if normalized_country and _normalize_ledger_country(candidate) == normalized_country:
continue
return candidate
return None
def _format_satellite_inclination(value: Any) -> str:
if value is None or value == "":
return "-"
try:
return f"{float(value):.2f}°"
except (TypeError, ValueError):
return "-"
async def _load_source_name_map(db: AsyncSession) -> dict[str, str]:
rows = (await db.execute(select(DataSource.source, DataSource.name))).all()
return {
str(source): str(name)
for source, name in rows
if source and name and str(name).strip()
}
def _has_valid_coords(latitude: Any, longitude: Any) -> bool:
try:
lat = float(latitude)
lon = float(longitude)
except (TypeError, ValueError):
return False
if lat == 0.0 or lon == 0.0:
return False
return -90.0 <= lat <= 90.0 and -180.0 <= lon <= 180.0
def _classify_compute_row(
record: CollectedData,
loc: ComputeCenterLocationRecord | None,
fallback_wf_run_id: str | None = None,
) -> dict[str, Any]:
metadata = record.extra_data if isinstance(record.extra_data, dict) else {}
site_type = compute_site_type(record)
operator = (
(loc.operator if loc else None)
or metadata.get("organization")
or metadata.get("operator")
or metadata.get("owner")
or metadata.get("manufacturer")
)
country = _normalize_ledger_country(
(loc.country if loc else None)
or get_record_field(record, "country")
or metadata.get("raw_country")
)
city = (loc.city if loc else None) or get_record_field(record, "city")
if not city:
city = _extract_city_from_location(metadata.get("location"), country)
lat = loc.latitude if loc else None
lon = loc.longitude if loc else None
precision = (loc.precision if loc else None) or "unknown"
confidence = loc.confidence if loc else None
location_source = (loc.location_source if loc else None) or ""
source_url = loc.source_url if loc else (metadata.get("source_url") or metadata.get("detail_url"))
raw_note = loc.source_note if loc else None
verification_status = str(loc.verification_status if loc else "").strip().lower()
raw_payload = (loc.raw_payload if loc and isinstance(loc.raw_payload, dict) else {}) or {}
workflow_run_id = raw_payload.get("workflow_run_id") or fallback_wf_run_id
terminal_status: str | None = None
if verification_status in TERMINAL_UNLOCATABLE_STATUSES:
status_bucket = "terminal"
terminal_status = verification_status
elif loc is None and metadata.get("compute_contract") == "v1" and metadata.get("anonymous"):
status_bucket = "terminal"
terminal_status = "anonymous"
verification_status = "anonymous"
location_source = "contract_anonymous"
raw_note = raw_note or "源数据声明为匿名集群,不披露具体物理设施。"
elif verification_status == "unverified":
status_bucket = "needs_confirmation"
elif (verification_status == "verified" and _has_valid_coords(lat, lon)) or (
verification_status == "source_provided" and _has_valid_coords(lat, lon)
):
status_bucket = "located"
elif loc is None:
resolved = resolve_compute_center_location_full(record, metadata)
if resolved.is_resolved and resolved.location and resolved.location.is_renderable:
res_loc = resolved.location
status_bucket = "needs_confirmation" if res_loc.needs_confirmation else "located"
lat = res_loc.latitude
lon = res_loc.longitude
precision = res_loc.location_precision
confidence = res_loc.location_confidence
location_source = res_loc.location_source or "source_coordinates"
verification_status = "unverified" if res_loc.needs_confirmation else "source_provided"
city = city or res_loc.city
country = country or _normalize_ledger_country(res_loc.country)
raw_note = res_loc.location_source_note or res_loc.estimated_reason
else:
status_bucket = "pending"
verification_status = "pending"
else:
status_bucket = "pending" if not _has_valid_coords(lat, lon) else "located"
if not verification_status:
verification_status = "pending"
sources_list = metadata.get("sources") if isinstance(metadata.get("sources"), list) else []
has_clues = bool(operator or city or sources_list)
is_anonymous_placeholder = bool(metadata.get("anonymous")) and not has_clues
updated_ts = (loc.verified_at or loc.updated_at if loc else None) or record.reference_date or record.collected_at
return {
"id": record.id,
"source": record.source,
"source_id": record.source_id,
"name": record.name or record.title or record.source_id,
"site_type": site_type,
"operator": operator,
"country": country,
"city": city,
"latitude": float(lat) if _has_valid_coords(lat, lon) else None,
"longitude": float(lon) if _has_valid_coords(lat, lon) else None,
"precision": precision,
"confidence": confidence,
"verification_status": verification_status,
"status_bucket": status_bucket,
"terminal_status": terminal_status,
"is_anonymous_placeholder": is_anonymous_placeholder,
"location_source": location_source or None,
"source_url": source_url,
"source_note": sanitize_user_facing_reasoning(raw_note) or None,
"workflow_run_id": workflow_run_id,
"updated_at": to_iso8601_utc(updated_ts),
}
def _compute_review_priority_tier(item: dict[str, Any]) -> int:
bucket = str(item.get("status_bucket") or "")
if bucket == "pending":
return 0
if bucket == "needs_confirmation":
return 1
if bucket == "located":
return 2
if item.get("is_anonymous_placeholder"):
return 4
return 3
async def _count_collected_types(db: AsyncSession, data_types: tuple[str, ...]) -> int:
stmt = (
select(func.count(CollectedData.id))
.where(CollectedData.is_current.is_(True))
.where(CollectedData.deleted_at.is_(None))
.where(CollectedData.data_type.in_(data_types))
)
if "satellite_tle" in data_types:
stmt = stmt.where(CollectedData.source_id.is_not(None)).where(CollectedData.source_id != "")
return int((await db.scalar(stmt)) or 0)
@router.get("/layers")
async def list_data_ledger_layers(db: AsyncSession = Depends(get_db)):
"""Return layer categories and item counts reusing `PRODUCT_DEFINITIONS`."""
cached = cache.get(DATA_LEDGER_LAYERS_CACHE_KEY)
if isinstance(cached, dict) and isinstance(cached.get("layers"), list):
return cached
compute_cnt = int(
(
await db.scalar(
select(func.count(CollectedData.id))
.where(CollectedData.is_current.is_(True))
.where(CollectedData.deleted_at.is_(None))
.where(compute_record_filter(CollectedData))
)
)
or 0
)
sat_cnt = await _count_collected_types(db, ("satellite_tle",))
cable_cnt = await _count_collected_types(
db, ("submarine_cable", "landing_point", "cable_landing_relation")
)
vessel_cnt = int((await db.scalar(select(func.count(VesselCurrentState.mmsi)))) or 0)
bgp_col_cnt = int((await db.scalar(select(func.count(BGPCollectorLocation.id)))) or 0)
bgp_inc_cnt = int((await db.scalar(select(func.count(BGPIncident.id)))) or 0)
news_items_cnt = int((await db.scalar(select(func.count(EarthNewsItem.id)))) or 0)
news_live_cnt = await _count_collected_types(db, ("news_live_stream",))
weather_cnt = await _count_collected_types(db, ("cloud_map_record", "wind_field_record"))
geo_cnt = await _count_collected_types(db, ("earth_tile_pyramid",))
facets = await _load_collected_facets(db, mode="current")
raw_cnt = sum(
int(item.get("count") or 0)
for item in facets
if item.get("data_type") not in DEFAULT_EXCLUDED_DATA_TYPES
)
counts_map = {
"compute": compute_cnt,
"satellites": sat_cnt,
"cables": cable_cnt,
"vessels": vessel_cnt,
"bgp": bgp_col_cnt + bgp_inc_cnt,
"news": news_items_cnt + news_live_cnt,
"weather": weather_cnt,
"geo": geo_cnt,
}
layers = [
{
"id": layer_id,
"name": str(PRODUCT_DEFINITIONS[layer_id]["name"]),
"count": counts_map[layer_id],
"kinds": list(LAYER_KINDS.get(layer_id, ())),
}
for layer_id in LAYER_ORDER
if layer_id in PRODUCT_DEFINITIONS
]
layers.append(
{
"id": "raw",
"name": "原始采集记录",
"count": raw_cnt,
"kinds": [],
}
)
payload = {"layers": layers}
cache.set(
DATA_LEDGER_LAYERS_CACHE_KEY,
payload,
expire_seconds=DATA_LEDGER_LAYERS_TTL_SECONDS,
)
return payload
@router.get("/compute-centers")
async def list_compute_center_ledger(
site_type: Optional[str] = Query(None),
status: Optional[str] = Query(None),
country: Optional[str] = Query(None),
search: Optional[str] = Query(None),
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=200),
db: AsyncSession = Depends(get_db),
):
"""Return compute center review ledger with site-type and status bucket counts."""
records = (
await db.execute(
select(CollectedData)
.where(CollectedData.is_current.is_(True))
.where(CollectedData.deleted_at.is_(None))
.where(compute_record_filter(CollectedData))
.order_by(desc(CollectedData.collected_at), desc(CollectedData.id))
)
).scalars().all()
loc_rows = (await db.execute(select(ComputeCenterLocationRecord))).scalars().all()
loc_map = {(r.source, r.source_id): r for r in loc_rows}
wf_rows = (
await db.execute(
select(WorkflowRun)
.where(WorkflowRun.workflow_id == "location.resolve_unknown")
.order_by(desc(WorkflowRun.started_at))
)
).scalars().all()
latest_wf_by_sid: dict[str, str] = {}
for wf in wf_rows:
sid = None
if isinstance(wf.input_params, dict):
sid = wf.input_params.get("source_id")
if not sid and isinstance(wf.budget_used, dict):
sid = wf.budget_used.get("source_id")
if sid and str(sid) not in latest_wf_by_sid:
latest_wf_by_sid[str(sid)] = wf.id
all_rows = [
_classify_compute_row(
rec,
loc_map.get((rec.source, rec.source_id)),
fallback_wf_run_id=latest_wf_by_sid.get(str(rec.source_id)),
)
for rec in records
]
search_needle = (search or "").strip().lower()
country_needle = _normalize_ledger_country(country) or ""
def _matches_base(item: dict[str, Any]) -> bool:
if country_needle and str(item.get("country") or "") != country_needle:
return False
if search_needle:
haystack = " ".join(
str(item.get(k) or "")
for k in ("name", "source_id", "operator", "city", "country", "source_note")
).lower()
if search_needle not in haystack:
return False
return True
base_filtered = [item for item in all_rows if _matches_base(item)]
status_filter = (status or "").strip()
site_type_filter = (site_type or "").strip()
by_site_type = dict.fromkeys(COMPUTE_SITE_TYPES, 0)
for item in base_filtered:
if status_filter and item["status_bucket"] != status_filter:
continue
st = item["site_type"]
if st in by_site_type:
by_site_type[st] += 1
by_status = {
"located": 0,
"needs_confirmation": 0,
"terminal": 0,
"pending": 0,
}
for item in base_filtered:
if site_type_filter and item["site_type"] != site_type_filter:
continue
bucket = item["status_bucket"]
if bucket in by_status:
by_status[bucket] += 1
filtered = [
item
for item in base_filtered
if (not site_type_filter or item["site_type"] == site_type_filter)
and (not status_filter or item["status_bucket"] == status_filter)
]
filtered = [
item
for _, item in sorted(
enumerate(filtered),
key=lambda pair: (_compute_review_priority_tier(pair[1]), pair[0]),
)
]
countries = sorted({str(item["country"]) for item in all_rows if item.get("country")})
total = len(filtered)
start = (page - 1) * page_size
paginated = filtered[start : start + page_size]
return {
"items": paginated,
"total": total,
"page": page,
"page_size": page_size,
"counts": {
"total": len(all_rows),
"by_site_type": by_site_type,
"by_status": by_status,
},
"countries": countries,
}
async def _query_collected_layer_items(
db: AsyncSession,
*,
layer: str,
spec: _CollectedLayerSpec,
kind: str,
kinds: list[dict[str, str]],
search: str,
page: int,
page_size: int,
) -> dict[str, Any]:
target_types = spec.data_types
if kind and kind != "all" and kind in spec.data_types:
target_types = (kind,)
stmt = (
select(CollectedData)
.where(CollectedData.is_current.is_(True))
.where(CollectedData.deleted_at.is_(None))
.where(CollectedData.data_type.in_(target_types))
)
if "satellite_tle" in target_types:
stmt = stmt.where(CollectedData.source_id.is_not(None)).where(CollectedData.source_id != "")
if search:
pat = f"%{search}%"
stmt = stmt.where(
or_(
CollectedData.name.ilike(pat),
CollectedData.title.ilike(pat),
CollectedData.source_id.ilike(pat),
CollectedData.source.ilike(pat),
)
)
total = int((await db.scalar(select(func.count()).select_from(stmt.subquery()))) or 0)
rows_orm = (
await db.execute(
stmt.order_by(desc(CollectedData.collected_at), desc(CollectedData.id))
.limit(page_size)
.offset((page - 1) * page_size)
)
).scalars().all()
source_name_map = await _load_source_name_map(db)
rows = []
for rec in rows_orm:
meta = rec.extra_data if isinstance(rec.extra_data, dict) else {}
country_val = _normalize_ledger_country(get_record_field(rec, "country")) or "-"
constellation = meta.get("constellation_group") or meta.get("celestrak_query_group") or "-"
rows.append(
{
"id": rec.id,
"name": rec.name or rec.title or rec.source_id,
"source_id": rec.source_id,
"source": source_name_map.get(rec.source, rec.source),
"data_type": rec.data_type,
"country": country_val,
"international_designator": meta.get("international_designator") or "-",
"constellation_group": constellation,
"inclination": _format_satellite_inclination(meta.get("inclination")),
"region": meta.get("region") or meta.get("country") or "-",
"language": meta.get("language") or meta.get("lang") or "-",
"reference_date": to_iso8601_utc(rec.reference_date),
"collected_at": to_iso8601_utc(rec.collected_at),
}
)
return {
"layer": layer,
"kind": kind or (kinds[0]["id"] if kinds else "all"),
"kinds": kinds,
"columns": list(spec.columns),
"rows": rows,
"total": total,
"page": page,
"page_size": page_size,
}
async def _query_vessels_items(
db: AsyncSession, *, search: str, page: int, page_size: int
) -> dict[str, Any]:
stmt = select(VesselCurrentState)
if search:
pat = f"%{search}%"
stmt = stmt.where(
or_(
VesselCurrentState.name.ilike(pat),
VesselCurrentState.callsign.ilike(pat),
VesselCurrentState.flag.ilike(pat),
VesselCurrentState.vessel_type_name.ilike(pat),
)
)
total = int((await db.scalar(select(func.count()).select_from(stmt.subquery()))) or 0)
rows_orm = (
await db.execute(
stmt.order_by(desc(VesselCurrentState.observed_at), desc(VesselCurrentState.mmsi))
.limit(page_size)
.offset((page - 1) * page_size)
)
).scalars().all()
source_name_map = await _load_source_name_map(db)
rows = [
{
"id": str(v.mmsi),
"mmsi": str(v.mmsi),
"name": v.name or f"MMSI {v.mmsi}",
"vessel_type_name": v.vessel_type_name or "-",
"flag": v.flag or "-",
"coordinates": f"{v.lat:.4f}, {v.lon:.4f}",
"sog": f"{v.sog:.1f} kn" if v.sog is not None else "-",
"source": source_name_map.get(v.source, v.source),
"observed_at": to_iso8601_utc(v.observed_at),
}
for v in rows_orm
]
return {
"layer": "vessels",
"kind": "all",
"kinds": [],
"columns": [
{"key": "name", "label": "船名"},
{"key": "mmsi", "label": "MMSI"},
{"key": "vessel_type_name", "label": "船型"},
{"key": "flag", "label": "船旗"},
{"key": "coordinates", "label": "坐标"},
{"key": "sog", "label": "航速"},
{"key": "source", "label": "数据源"},
{"key": "observed_at", "label": "观测时间"},
],
"rows": rows,
"total": total,
"page": page,
"page_size": page_size,
}
async def _query_bgp_items(
db: AsyncSession, *, kind: str, kinds: list[dict[str, str]], search: str, page: int, page_size: int
) -> dict[str, Any]:
active_kind = kind if kind in {"collectors", "incidents"} else "collectors"
if active_kind == "collectors":
stmt = select(BGPCollectorLocation)
if search:
pat = f"%{search}%"
stmt = stmt.where(
or_(
BGPCollectorLocation.collector_id.ilike(pat),
BGPCollectorLocation.operator.ilike(pat),
BGPCollectorLocation.city.ilike(pat),
BGPCollectorLocation.country.ilike(pat),
)
)
total = int((await db.scalar(select(func.count()).select_from(stmt.subquery()))) or 0)
rows_orm = (
await db.execute(
stmt.order_by(desc(BGPCollectorLocation.updated_at), desc(BGPCollectorLocation.id))
.limit(page_size)
.offset((page - 1) * page_size)
)
).scalars().all()
rows = [
{
"id": r.id,
"collector_id": r.collector_id,
"operator": r.operator or "-",
"country": r.country or "-",
"city": r.city or "-",
"verification_status": r.verification_status,
"updated_at": to_iso8601_utc(r.updated_at or r.verified_at),
}
for r in rows_orm
]
columns = [
{"key": "collector_id", "label": "观测站 ID"},
{"key": "operator", "label": "运营机构"},
{"key": "country", "label": "国家/地区"},
{"key": "city", "label": "城市"},
{"key": "verification_status", "label": "核验状态"},
{"key": "updated_at", "label": "更新时间"},
]
else:
stmt = select(BGPIncident)
if search:
pat = f"%{search}%"
stmt = stmt.where(
or_(
BGPIncident.title.ilike(pat),
BGPIncident.incident_type.ilike(pat),
BGPIncident.source.ilike(pat),
)
)
total = int((await db.scalar(select(func.count()).select_from(stmt.subquery()))) or 0)
rows_orm = (
await db.execute(
stmt.order_by(desc(BGPIncident.started_at), desc(BGPIncident.id))
.limit(page_size)
.offset((page - 1) * page_size)
)
).scalars().all()
rows = [
{
"id": r.id,
"title": r.title,
"incident_type": r.incident_type,
"severity": r.severity,
"status": r.status,
"source": r.source,
"started_at": to_iso8601_utc(r.started_at),
}
for r in rows_orm
]
columns = [
{"key": "title", "label": "事件标题"},
{"key": "incident_type", "label": "事件类型"},
{"key": "severity", "label": "级别"},
{"key": "status", "label": "状态"},
{"key": "source", "label": "数据源"},
{"key": "started_at", "label": "开始时间"},
]
return {
"layer": "bgp",
"kind": active_kind,
"kinds": kinds,
"columns": columns,
"rows": rows,
"total": total,
"page": page,
"page_size": page_size,
}
async def _query_news_items(
db: AsyncSession, *, kind: str, kinds: list[dict[str, str]], search: str, page: int, page_size: int
) -> dict[str, Any]:
active_kind = kind if kind in {"items", "live_streams"} else "items"
if active_kind == "live_streams":
return await _query_collected_layer_items(
db,
layer="news",
spec=_COLLECTED_LAYER_SPECS["news:live_streams"],
kind=active_kind,
kinds=kinds,
search=search,
page=page,
page_size=page_size,
)
stmt = select(EarthNewsItem)
if search:
pat = f"%{search}%"
stmt = stmt.where(
or_(
EarthNewsItem.title.ilike(pat),
EarthNewsItem.source.ilike(pat),
EarthNewsItem.region.ilike(pat),
EarthNewsItem.location_label.ilike(pat),
)
)
total = int((await db.scalar(select(func.count()).select_from(stmt.subquery()))) or 0)
rows_orm = (
await db.execute(
stmt.order_by(
desc(func.coalesce(EarthNewsItem.published_at, EarthNewsItem.last_seen_at)),
desc(EarthNewsItem.id),
)
.limit(page_size)
.offset((page - 1) * page_size)
)
).scalars().all()
rows = [
{
"id": r.id,
"title": r.title,
"source": r.source or r.feed_name or "-",
"region": r.region,
"location_label": r.location_label,
"enrichment_status": r.enrichment_status,
"published_at": to_iso8601_utc(r.published_at or r.last_seen_at),
}
for r in rows_orm
]
return {
"layer": "news",
"kind": "items",
"kinds": kinds,
"columns": [
{"key": "title", "label": "新闻标题"},
{"key": "source", "label": "来源"},
{"key": "region", "label": "区域"},
{"key": "location_label", "label": "地理落点"},
{"key": "enrichment_status", "label": "处理状态"},
{"key": "published_at", "label": "发布时间"},
],
"rows": rows,
"total": total,
"page": page,
"page_size": page_size,
}
@router.get("/{layer}/items")
async def list_layer_ledger_items(
layer: str,
kind: Optional[str] = Query(None),
search: Optional[str] = Query(None),
page: int = Query(1, ge=1),
page_size: int = Query(20, ge=1, le=200),
db: AsyncSession = Depends(get_db),
):
"""Return paginated read-only ledger rows for non-compute Earth layers."""
kinds = list(LAYER_KINDS.get(layer, ()))
resolved_kind = (kind or "").strip() or (kinds[0]["id"] if kinds else "all")
search_str = (search or "").strip()
if layer == "vessels":
return await _query_vessels_items(db, search=search_str, page=page, page_size=page_size)
if layer == "bgp":
return await _query_bgp_items(
db, kind=resolved_kind, kinds=kinds, search=search_str, page=page, page_size=page_size
)
if layer == "news":
return await _query_news_items(
db, kind=resolved_kind, kinds=kinds, search=search_str, page=page, page_size=page_size
)
if layer in _COLLECTED_LAYER_SPECS:
return await _query_collected_layer_items(
db,
layer=layer,
spec=_COLLECTED_LAYER_SPECS[layer],
kind=resolved_kind,
kinds=kinds,
search=search_str,
page=page,
page_size=page_size,
)
raise HTTPException(status_code=404, detail=f"Unknown ledger layer: {layer}")
+179 -7
View File
@@ -1,12 +1,20 @@
from datetime import UTC, datetime
from typing import Any
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.v1.visualization import get_visualization_geo_summary
from app.core.access_gate import require_earth_or_api_access
from app.core.time import to_iso8601_utc
from app.db.session import get_db
from app.models.collected_data import CollectedData
from app.models.datasource import DataSource
from app.models.earth_news import EarthNewsItem
from app.models.task import CollectionTask
from app.services.data_jobs import JOB_STATUS_CANCELLING, JOB_STATUS_QUEUED, JOB_STATUS_RUNNING
from app.services.earth_clouds import get_cloud_map_runtime_meta
router = APIRouter(dependencies=[Depends(require_earth_or_api_access("data_products:read"))])
@@ -55,20 +63,131 @@ PRODUCT_DEFINITIONS: dict[str, dict] = {
"primary_stat_key": "compute_center_count",
"stat_keys": ["compute_center_count", "supercomputer_count", "gpu_cluster_count", "data_center_count", "cloud_center_count", "edge_node_count"],
},
"weather": {
"name": "气象",
"sources": ["global_cloud_map", "cloud_hd_tiles", "global_wind_gfs"],
"primary_stat_key": "cloud_frame_count",
"stat_keys": ["cloud_frame_count", "cloud_record_count", "wind_available_flag"],
},
"geo": {
"name": "地理/底图",
"sources": ["earth_imagery_sentinel2", "earth_imagery_viirs_daily"],
"primary_stat_key": "cached_tile_count",
"stat_keys": ["cached_tile_count"],
},
"news": {
"name": "新闻与直播",
"sources": ["earth_news", "news_live_streams"],
"primary_stat_key": "news_count",
"stat_keys": ["news_count"],
},
}
def _build_product_status(product_id: str, summary: dict) -> dict:
async def _load_collector_product_states(
db: AsyncSession,
source_names: list[str],
) -> tuple[dict[str, bool], set[str]]:
if not source_names:
return {}, set()
ds_rows = (
await db.execute(
select(DataSource.id, DataSource.source, DataSource.is_active).where(
DataSource.source.in_(source_names)
)
)
).all()
active_by_source = {str(source): bool(is_active) for _, source, is_active in ds_rows}
id_to_source = {int(ds_id): str(source) for ds_id, source, _ in ds_rows}
running_sources: set[str] = set()
if id_to_source:
task_rows = (
await db.execute(
select(CollectionTask.datasource_id, func.count(CollectionTask.id))
.where(CollectionTask.datasource_id.in_(list(id_to_source.keys())))
.where(
CollectionTask.status.in_(
(JOB_STATUS_QUEUED, JOB_STATUS_RUNNING, JOB_STATUS_CANCELLING)
)
)
.group_by(CollectionTask.datasource_id)
)
).all()
for ds_id, cnt in task_rows:
if int(cnt or 0) > 0 and int(ds_id) in id_to_source:
running_sources.add(id_to_source[int(ds_id)])
return active_by_source, running_sources
def _build_product_status(
product_id: str,
summary: dict,
*,
active_by_source: dict[str, bool],
running_sources: set[str],
weather_meta: dict[str, Any] | None = None,
wind_meta: dict[str, Any] | None = None,
basemap_meta: dict[str, Any] | None = None,
news_count: int | None = None,
) -> dict:
definition = PRODUCT_DEFINITIONS[product_id]
stats = summary.get("stats", {})
product_stats = {key: stats.get(key, 0) for key in definition["stat_keys"]}
total_count = int(product_stats.get(definition["primary_stat_key"]) or 0)
sources = definition["sources"]
total_collector_count = len(sources)
active_collector_count = sum(1 for src in sources if active_by_source.get(src, False))
running_collector_count = sum(1 for src in sources if src in running_sources)
if product_id == "weather":
meta = weather_meta or {}
w_meta = wind_meta or {}
frames = meta.get("frames") if isinstance(meta.get("frames"), list) else []
frame_count = len(frames)
clusters = meta.get("convective_clusters") if isinstance(meta.get("convective_clusters"), list) else []
regions = meta.get("regions") if isinstance(meta.get("regions"), list) else []
wind_has_data = bool(w_meta.get("has_data"))
product_stats = {
"cloud_frame_count": frame_count,
"cloud_record_count": (1 + len(regions) + len(clusters)) if frame_count > 0 else 0,
"wind_available_flag": 1 if wind_has_data else 0,
}
total_count = frame_count + (1 if wind_has_data else 0)
has_data = frame_count > 0 or wind_has_data
captured_at = meta.get("captured_at") or w_meta.get("captured_at")
elif product_id == "geo":
b_meta = basemap_meta or {}
tile_sources = [
item for item in (b_meta.get("sources") or [])
if isinstance(item, dict) and item.get("source") in sources
]
cached_tiles = sum(int(item.get("cached_tiles") or 0) for item in tile_sources)
product_stats = {"cached_tile_count": cached_tiles}
total_count = cached_tiles
has_data = cached_tiles > 0
captured_at = None
elif product_id == "news":
resolved_news_count = int(news_count or 0)
product_stats = {"news_count": resolved_news_count}
total_count = resolved_news_count
has_data = resolved_news_count > 0
captured_at = None
else:
stats = summary.get("stats", {})
product_stats = {key: stats.get(key, 0) for key in definition["stat_keys"]}
total_count = int(product_stats.get(definition["primary_stat_key"]) or 0)
has_data = total_count > 0
captured_at = None
return {
"product_id": product_id,
"name": definition["name"],
"sources": definition["sources"],
"sources": sources,
"generated_at": summary.get("generated_at") or to_iso8601_utc(datetime.now(UTC)),
"captured_at": captured_at,
"total_count": total_count,
"has_data": has_data,
"total_collector_count": total_collector_count,
"active_collector_count": active_collector_count,
"running_collector_count": running_collector_count,
"datasources_url": f"/datasources?product={product_id}",
"stats": product_stats,
"build_state": "ready",
"stats_scope": "global",
@@ -76,13 +195,48 @@ def _build_product_status(product_id: str, summary: dict) -> dict:
}
async def _load_news_product_count(db: AsyncSession) -> int:
try:
items_cnt = await db.scalar(select(func.count(EarthNewsItem.id)))
except Exception:
items_cnt = 0
try:
live_cnt = await db.scalar(
select(func.count(CollectedData.id))
.where(CollectedData.is_current.is_(True))
.where(CollectedData.deleted_at.is_(None))
.where(CollectedData.data_type == "news_live_stream")
)
except Exception:
live_cnt = 0
return int(items_cnt or 0) + int(live_cnt or 0)
@router.get("")
async def list_data_products(db: AsyncSession = Depends(get_db)):
from app.services.earth_tiles import get_basemap_runtime_meta
from app.services.earth_wind import get_wind_runtime_meta
summary = await get_visualization_geo_summary(db)
all_sources = [src for definition in PRODUCT_DEFINITIONS.values() for src in definition["sources"]]
active_by_source, running_sources = await _load_collector_product_states(db, all_sources)
weather_meta = await get_cloud_map_runtime_meta(db)
wind_meta = await get_wind_runtime_meta(db)
basemap_meta = await get_basemap_runtime_meta(db)
news_count = await _load_news_product_count(db)
return {
"generated_at": summary.get("generated_at"),
"data": [
_build_product_status(product_id, summary)
_build_product_status(
product_id,
summary,
active_by_source=active_by_source,
running_sources=running_sources,
weather_meta=weather_meta if product_id == "weather" else None,
wind_meta=wind_meta if product_id == "weather" else None,
basemap_meta=basemap_meta if product_id == "geo" else None,
news_count=news_count if product_id == "news" else None,
)
for product_id in PRODUCT_DEFINITIONS
],
}
@@ -93,7 +247,25 @@ async def get_data_product_status(
product_id: str,
db: AsyncSession = Depends(get_db),
):
from app.services.earth_tiles import get_basemap_runtime_meta
from app.services.earth_wind import get_wind_runtime_meta
if product_id not in PRODUCT_DEFINITIONS:
raise HTTPException(status_code=404, detail="Unknown data product")
summary = await get_visualization_geo_summary(db)
return _build_product_status(product_id, summary)
sources = PRODUCT_DEFINITIONS[product_id]["sources"]
active_by_source, running_sources = await _load_collector_product_states(db, sources)
weather_meta = await get_cloud_map_runtime_meta(db) if product_id == "weather" else None
wind_meta = await get_wind_runtime_meta(db) if product_id == "weather" else None
basemap_meta = await get_basemap_runtime_meta(db) if product_id == "geo" else None
news_count = await _load_news_product_count(db) if product_id == "news" else None
return _build_product_status(
product_id,
summary,
active_by_source=active_by_source,
running_sources=running_sources,
weather_meta=weather_meta,
wind_meta=wind_meta,
basemap_meta=basemap_meta,
news_count=news_count,
)
+209 -35
View File
@@ -44,8 +44,9 @@ from app.services.custom_datasource_runtime import (
)
from app.services.datasource_connectivity import (
_resolve_aisstream_api_key,
_resolve_spacetrack_credentials_with_override,
get_builtin_connection_status,
get_connectivity_store,
resolve_spacetrack_credentials,
save_connectivity_success,
strip_connectivity_validation,
test_builtin_connectivity,
@@ -64,6 +65,70 @@ def _user_role_value(user: User) -> str:
return str(getattr(role, "value", role) or "").lower()
def mask_credential_value(value: Any, *, secret: bool = False, reveal_edges: bool = False) -> str:
"""Return a strictly non-plaintext masked representation of a credential or identifier."""
raw = str(value or "").strip()
if not raw:
return ""
if secret:
if reveal_edges and len(raw) >= 8:
return f"{raw[:3]}••••{raw[-4:]}"
return "••••••"
if len(raw) >= 6:
return f"{raw[:2]}•••{raw[-2:]}"
return "•••"
def build_masked_credential_preview(
*,
requires_credentials: bool,
auth_type: str | None,
auth_config: dict[str, Any] | None,
resolved_provider: str | None = None,
resolved_values: dict[str, str] | None = None,
) -> tuple[bool, str]:
"""Compute `(has_credentials, masked_preview)` without exposing plaintext secrets."""
cfg = auth_config if isinstance(auth_config, dict) else {}
resolved = resolved_values if isinstance(resolved_values, dict) else {}
norm_auth = str(auth_type or "none").strip().lower()
provider = str(resolved_provider or "").strip().lower()
if not requires_credentials and norm_auth in {"", "none"}:
return True, ""
if provider == "barentswatch" or "oauth" in norm_auth or cfg.get("client_id") or cfg.get("client_secret"):
client_id = str(resolved.get("client_id") or cfg.get("client_id") or "").strip()
client_secret = str(resolved.get("client_secret") or cfg.get("client_secret") or "").strip()
has_creds = bool(client_id and client_secret)
parts = [
mask_credential_value(client_id, secret=False),
mask_credential_value(client_secret, secret=True),
]
return has_creds, " · ".join(part for part in parts if part)
if provider == "spacetrack" or "basic" in norm_auth or cfg.get("username") or cfg.get("password"):
username = str(resolved.get("username") or cfg.get("username") or "").strip()
password = str(resolved.get("password") or cfg.get("password") or "").strip()
has_creds = bool(username and password)
parts = [
mask_credential_value(username, secret=False),
mask_credential_value(password, secret=True),
]
return has_creds, " · ".join(part for part in parts if part)
api_key = str(
resolved.get("api_key")
or cfg.get("api_key")
or cfg.get("token")
or cfg.get("bearer_token")
or ""
).strip()
if provider == "aisstream" or norm_auth in {"api_key", "bearer"} or api_key:
return bool(api_key), mask_credential_value(api_key, secret=True, reveal_edges=True)
return False, ""
def _user_display_name(user: User) -> str:
return str(getattr(user, "username", None) or getattr(user, "email", None) or getattr(user, "id", ""))
@@ -109,6 +174,45 @@ async def _ensure_datasource_secret_reveal_allowed(
)
def _default_builtin_config(name: str) -> dict[str, Any]:
if name == "global_cloud_map":
from app.services.earth_clouds import DEFAULT_CLOUD_CONFIG
return {
"primary_source": DEFAULT_CLOUD_CONFIG.primary_source,
"fallback_source": DEFAULT_CLOUD_CONFIG.fallback_source,
"resolution": DEFAULT_CLOUD_CONFIG.resolution,
"ir_threshold": DEFAULT_CLOUD_CONFIG.ir_threshold,
"contrast_gamma": DEFAULT_CLOUD_CONFIG.contrast_gamma,
"convective_threshold": DEFAULT_CLOUD_CONFIG.convective_threshold,
"min_cluster_area_km2": DEFAULT_CLOUD_CONFIG.min_cluster_area_km2,
"polar_feather_enabled": DEFAULT_CLOUD_CONFIG.polar_feather_enabled,
"max_history_frames": DEFAULT_CLOUD_CONFIG.max_history_frames,
"request_timeout_seconds": DEFAULT_CLOUD_CONFIG.request_timeout_seconds,
"geocolor_enabled": DEFAULT_CLOUD_CONFIG.geocolor_enabled,
"relief_shading_strength": DEFAULT_CLOUD_CONFIG.relief_shading_strength,
"optical_flow_enabled": DEFAULT_CLOUD_CONFIG.optical_flow_enabled,
}
if name == "cloud_hd_tiles":
return {
"warmup_max_zoom": 2,
"max_zoom": 6,
"max_cache_mb": 512,
"request_timeout_seconds": 15,
}
if name in {"earth_imagery_sentinel2", "earth_imagery_viirs_daily"}:
return {
"warmup_max_zoom": 3,
"max_zoom": 10 if name == "earth_imagery_sentinel2" else 9,
"max_cache_mb": 1024 if name == "earth_imagery_sentinel2" else 768,
"request_timeout_seconds": 15,
}
if name == "global_wind_gfs":
return {
"grid_step_deg": 2.0,
"gale_threshold_ms": 17.2,
"request_timeout_seconds": 25,
"max_history_runs": 12,
}
return {"timeout": 30, "retry": 3}
@@ -123,7 +227,10 @@ class DataSourceConfigCreate(BaseModel):
description: Optional[str] = None
source_type: str = Field(..., description="rest, websocket, http, api, database")
endpoint: str = Field(..., max_length=500)
auth_type: AuthType = Field(default=AuthType.NONE, description="none, bearer, api_key, basic")
auth_type: AuthType = Field(
default=AuthType.NONE,
description="none, bearer, api_key, basic, oauth_client",
)
auth_config: dict = Field(default={})
headers: dict = Field(default={})
config: dict = Field(default={"timeout": 30, "retry": 3})
@@ -162,28 +269,6 @@ def _is_builtin_config_name(name: str | None) -> bool:
return bool(name and name in DEFAULT_DATASOURCES)
async def _ensure_builtin_connection_verified(
db: AsyncSession,
config_data: DataSourceConfigCreate,
) -> None:
if not _is_builtin_config_name(config_data.name):
return
status_result = await get_builtin_connection_status(
db,
config_data.name,
config_data.endpoint,
config_data.auth_type,
config_data.headers,
config_data.config,
)
if not status_result.get("connected"):
raise HTTPException(
status_code=400,
detail=status_result.get("message") or "请先完成连接验证,再保存内置采集器配置。",
)
class CustomSampleRequest(BaseModel):
datasource_config_id: Optional[int] = None
config: Optional[DataSourceConfigCreate] = None
@@ -396,6 +481,8 @@ async def list_configs(
db: AsyncSession = Depends(get_db),
):
"""List all user-defined data source configurations"""
from app.api.v1.datasources import infer_datasource_product_key
query = select(DataSourceConfig)
if active_only:
query = query.where(DataSourceConfig.is_active)
@@ -410,10 +497,24 @@ async def list_configs(
{
"id": c.id,
"name": c.name,
"product": infer_datasource_product_key(c.name, c.description or "", c.name),
"description": c.description,
"source_type": c.source_type,
"endpoint": c.endpoint,
"auth_type": c.auth_type,
"requires_credentials": (c.auth_type or "none") != "none",
**(
lambda cred_state: {
"has_credentials": cred_state[0],
"credential_preview": cred_state[1],
}
)(
build_masked_credential_preview(
requires_credentials=(c.auth_type or "none") != "none",
auth_type=c.auth_type,
auth_config=c.auth_config,
)
),
"headers": c.headers,
"config": c.config,
"is_active": c.is_active,
@@ -431,12 +532,30 @@ async def list_all_datasources(
db: AsyncSession = Depends(get_db),
):
"""List all data sources: YAML defaults + DB overrides"""
from app.api.v1.datasources import infer_datasource_product_key
from app.core.data_sources import get_data_sources_config
config = get_data_sources_config()
db_query = await db.execute(select(DataSourceConfig))
db_configs = {c.name: c for c in db_query.scalars().all()}
connectivity_store = await get_connectivity_store(db)
resolved_provider_values: dict[str, dict[str, str]] = {}
bw_cfg = await resolve_barentswatch_config(db)
resolved_provider_values["barentswatch"] = {
"client_id": bw_cfg.client_id,
"client_secret": bw_cfg.client_secret,
}
st_user, st_pass, _ = await resolve_spacetrack_credentials(db)
resolved_provider_values["spacetrack"] = {
"username": st_user,
"password": st_pass,
}
ais_key, _ = await _resolve_aisstream_api_key(db)
resolved_provider_values["aisstream"] = {
"api_key": ais_key,
}
result = []
for name, metadata in DEFAULT_DATASOURCES.items():
@@ -445,13 +564,47 @@ async def list_all_datasources(
default_config = _default_builtin_config(name)
default_url = yaml_url
db_auth_config = db_config.auth_config or {} if db_config else {}
product = infer_datasource_product_key(name, str(metadata.get("name") or ""), name)
requires_credentials = bool(metadata.get("requires_credentials", False))
credential_provider = metadata.get("credential_provider")
provider_key = str(credential_provider or "").strip().lower()
effective_auth_type = db_config.auth_type if db_config else (
"oauth2" if provider_key == "barentswatch" else (
"basic" if provider_key == "spacetrack" else (
"api_key" if provider_key == "aisstream" else "none"
)
)
)
has_credentials, credential_preview = build_masked_credential_preview(
requires_credentials=requires_credentials,
auth_type=effective_auth_type,
auth_config=db_auth_config,
resolved_provider=provider_key,
resolved_values=resolved_provider_values.get(provider_key),
)
validation = connectivity_store.get(name) if isinstance(connectivity_store, dict) else None
connectivity_status = (
"missing_credentials"
if requires_credentials and not has_credentials
else (
"connected"
if isinstance(validation, dict) and validation.get("status") == "success"
else "unverified"
)
)
result.append(
{
"name": name,
"requires_credentials": bool(metadata.get("requires_credentials", False)),
"credential_provider": metadata.get("credential_provider"),
"display_name": metadata.get("display_name") or metadata.get("name") or name,
"product": product,
"requires_credentials": requires_credentials,
"credential_provider": credential_provider,
"credential_status": metadata.get("credential_status", "none"),
"has_credentials": has_credentials,
"credential_preview": credential_preview,
"connectivity_status": connectivity_status,
"connectivity_checked_at": validation.get("checked_at") if isinstance(validation, dict) else None,
"default_url": default_url,
"endpoint": db_config.endpoint if db_config else default_url,
"is_overridden": db_config is not None and db_config.endpoint != yaml_url
@@ -543,12 +696,7 @@ async def reveal_builtin_config_secrets(
payload.update({"api_key": api_key, "api_key_source": api_key_source})
details.update({"api_key_configured": bool(api_key), "api_key_source": api_key_source})
elif provider == "spacetrack":
if auth_config.get("username") or auth_config.get("password"):
username = str(auth_config.get("username") or "")
password = str(auth_config.get("password") or "")
credential_source = "datasource_config"
else:
username, password, credential_source = _resolve_spacetrack_credentials_with_override()
username, password, credential_source = await resolve_spacetrack_credentials(db)
payload.update(
{
"username": username,
@@ -606,6 +754,32 @@ async def get_config(
}
_SECRET_AUTH_KEYS = frozenset(
{"api_key", "client_secret", "password", "token", "access_token", "bearer_token"}
)
def _is_masked_secret(value: Any) -> bool:
if not isinstance(value, str):
return False
stripped = value.strip()
return bool(stripped) and set(stripped) <= {"•", "*"}
def _merge_auth_config(existing: dict[str, Any] | None, incoming: dict[str, Any] | None) -> dict[str, Any]:
"""Merge partial `auth_config` updates while preserving omitted or masked secrets."""
merged = dict(existing or {})
if not isinstance(incoming, dict):
return merged
for key, raw in incoming.items():
if key in _SECRET_AUTH_KEYS:
cleaned = str(raw or "").strip() if isinstance(raw, str) else raw
if not cleaned or _is_masked_secret(cleaned):
continue
merged[key] = raw
return merged
@router.post("/configs")
async def create_config(
config_data: DataSourceConfigCreate,
@@ -619,7 +793,7 @@ async def create_config(
source_type=config_data.source_type,
endpoint=config_data.endpoint,
auth_type=config_data.auth_type,
auth_config=config_data.auth_config,
auth_config=_merge_auth_config({}, config_data.auth_config),
headers=config_data.headers,
config=strip_connectivity_validation(config_data.config),
)
@@ -655,8 +829,8 @@ async def update_config(
for field, value in update_data.items():
if field == "config":
value = strip_connectivity_validation(value)
if field == "auth_config" and value == {} and (config.auth_config or {}):
continue
if field == "auth_config":
value = _merge_auth_config(config.auth_config or {}, value)
setattr(config, field, value)
await db.commit()
+18 -4
View File
@@ -43,6 +43,8 @@ DATASOURCE_ADMIN_ROLES = {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}
PRODUCT_SOURCE_KEYWORDS: tuple[tuple[str, tuple[str, ...]], ...] = (
("geo", ("earth_imagery", "sentinel2", "viirs", "basemap", "imagery")),
("weather", ("cloud", "weather", "meteorolog", "atmosphere", "ir108", "wind", "gfs")),
("vessels", ("vessel", "ais")),
("cables", ("cable", "landing", "telegeography", "arcgis", "fao")),
("satellites", ("tle", "satellite", "spacetrack", "celestrak")),
@@ -99,12 +101,16 @@ def datasource_metadata(source: str) -> dict:
}
def datasource_product_key(datasource: DataSource) -> str:
def infer_datasource_product_key(
source: str = "",
name: str = "",
collector_class: str = "",
) -> str:
haystack = " ".join(
[
datasource.source or "",
datasource.name or "",
datasource.collector_class or "",
source or "",
name or "",
collector_class or "",
]
).lower()
for product, keywords in PRODUCT_SOURCE_KEYWORDS:
@@ -113,6 +119,14 @@ def datasource_product_key(datasource: DataSource) -> str:
return "other"
def datasource_product_key(datasource: DataSource) -> str:
return infer_datasource_product_key(
datasource.source or "",
datasource.name or "",
datasource.collector_class or "",
)
def is_due_for_collection(datasource: DataSource, now: datetime) -> bool:
if datasource.last_run_at is None:
return True
+404 -1
View File
@@ -6,7 +6,8 @@ from pathlib import Path
from typing import Any
from uuid import uuid4
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile, status
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, Response, UploadFile, status
from fastapi.responses import FileResponse
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel, Field
from sqlalchemy import delete, func, select, text
@@ -14,6 +15,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_earth_or_api_access
from app.core.config import settings as app_settings
from app.core.enums import UserRole
from app.core.logging import get_logger
from app.core.security import (
decode_token,
@@ -53,6 +55,8 @@ from app.services.earth_boundaries import (
EarthBoundaryBuildError,
get_boundary_build_status,
get_boundary_status,
get_public_boundary_manifest,
resolve_boundary_artifact,
save_boundary_config,
start_boundary_build_job,
)
@@ -676,6 +680,38 @@ async def get_earth_oobe_status(
async def get_earth_boundary_status():
return get_boundary_status()
@router.get("/boundaries/manifest", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_boundary_manifest(response: Response):
manifest = get_public_boundary_manifest()
if manifest is None:
raise HTTPException(status_code=404, detail="Verified Earth boundary artifact not built")
response.headers["Cache-Control"] = "no-cache"
return manifest
BOUNDARY_ARTIFACT_MEDIA_TYPES = {".pmtiles": "application/vnd.pmtiles", ".json": "application/json"}
_boundary_file_access = Depends(
require_earth_or_api_access("earth:read", rate_limit_tier="tile")
)
@router.get("/boundaries/files/{name}", dependencies=[_boundary_file_access])
@router.head("/boundaries/files/{name}", include_in_schema=False, dependencies=[_boundary_file_access])
async def get_earth_boundary_file(name: str):
path = resolve_boundary_artifact(name)
if path is None:
raise HTTPException(status_code=404, detail="Earth boundary artifact not found")
# Artifact names embed the build hash, so clients may cache them forever.
# FileResponse answers Range requests with 206 for PMTiles reads.
return FileResponse(
path,
media_type=BOUNDARY_ARTIFACT_MEDIA_TYPES.get(path.suffix, "application/octet-stream"),
headers={"Cache-Control": "public, max-age=31536000, immutable"},
)
def _is_loopback_request(request: Request) -> bool:
host = request.client.host if request.client else ""
return host in {"127.0.0.1", "::1", "localhost"} or host.startswith("127.")
@@ -722,3 +758,370 @@ async def build_earth_boundary_assets(
@router.get("/boundaries/build/status", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_boundary_build_status():
return get_boundary_build_status()
def _require_cloud_admin(user: User) -> None:
role = getattr(user.role, "value", user.role)
if str(role).lower() not in {UserRole.ADMIN.value, UserRole.SUPER_ADMIN.value}:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only administrators can modify cloud map configuration",
)
def _require_cloud_operator(user: User) -> None:
role = getattr(user.role, "value", user.role)
if str(role).lower() not in {
UserRole.ADMIN.value,
UserRole.SUPER_ADMIN.value,
}:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Administrator access required",
)
class CloudMapConfigUpdatePayload(BaseModel):
revision: str = Field(..., min_length=4, max_length=128)
config: dict[str, Any] = Field(default_factory=dict)
class CloudMapSourceTestPayload(BaseModel):
source_id: str = Field(default="multi_sat_ir", max_length=64)
timeout_seconds: int = Field(default=15, ge=5, le=45)
@router.get("/clouds/meta", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_clouds_meta(db: AsyncSession = Depends(get_db)):
from app.services.earth_clouds import get_cloud_map_runtime_meta
return await get_cloud_map_runtime_meta(db)
@router.get("/clouds/frames/{version}", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_cloud_frame(version: str):
from app.services.earth_clouds import read_cloud_frame_bytes
content = read_cloud_frame_bytes(version)
if content is None:
raise HTTPException(status_code=404, detail="Cloud frame not found")
return Response(
content=content,
media_type="image/webp",
headers={"Cache-Control": "public, max-age=86400, immutable"},
)
@router.get("/clouds/configuration")
async def get_earth_cloud_configuration(
_current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
from app.services.earth_clouds import (
get_cloud_datasource_summary,
get_cloud_map_runtime_meta,
read_cloud_map_configuration,
)
envelope = await read_cloud_map_configuration(db)
meta = await get_cloud_map_runtime_meta(db)
datasource = await get_cloud_datasource_summary(db)
return {
**envelope,
"meta": meta,
"datasource": datasource,
}
@router.put("/clouds/configuration")
async def put_earth_cloud_configuration(
payload: CloudMapConfigUpdatePayload,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
from pydantic import ValidationError
from app.services.earth_clouds import (
CloudMapConfig,
CloudMapRevisionConflictError,
get_cloud_datasource_summary,
get_cloud_map_runtime_meta,
save_cloud_map_configuration,
)
_require_cloud_admin(current_user)
try:
validated = CloudMapConfig.model_validate(payload.config)
envelope = await save_cloud_map_configuration(
db,
revision=payload.revision,
config=validated,
actor=current_user,
reset=False,
)
except ValidationError as exc:
raise HTTPException(status_code=422, detail=exc.errors()) from exc
except CloudMapRevisionConflictError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
await _broadcast_earth_config_update("clouds")
return {
**envelope,
"meta": await get_cloud_map_runtime_meta(db),
"datasource": await get_cloud_datasource_summary(db),
}
@router.post("/clouds/configuration/reset")
async def reset_earth_cloud_configuration(
payload: CloudMapConfigUpdatePayload,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
from app.services.earth_clouds import (
CloudMapRevisionConflictError,
DEFAULT_CLOUD_CONFIG,
get_cloud_datasource_summary,
get_cloud_map_runtime_meta,
save_cloud_map_configuration,
)
_require_cloud_admin(current_user)
try:
envelope = await save_cloud_map_configuration(
db,
revision=payload.revision,
config=DEFAULT_CLOUD_CONFIG,
actor=current_user,
reset=True,
)
except CloudMapRevisionConflictError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
await _broadcast_earth_config_update("clouds")
return {
**envelope,
"meta": await get_cloud_map_runtime_meta(db),
"datasource": await get_cloud_datasource_summary(db),
}
@router.post("/clouds/test")
async def test_earth_cloud_source(
payload: CloudMapSourceTestPayload,
current_user: User = Depends(get_current_user),
):
from app.services.earth_clouds import test_cloud_map_source
_require_cloud_operator(current_user)
try:
return await test_cloud_map_source(payload.source_id, timeout_seconds=payload.timeout_seconds)
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@router.delete("/clouds/cache")
async def clear_earth_cloud_cache(
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
from app.services.earth_clouds import clear_all_cloud_map_artifacts, get_cloud_map_runtime_meta
_require_cloud_admin(current_user)
removed = clear_all_cloud_map_artifacts()
await _broadcast_earth_config_update("clouds")
return {
"removed_files": removed,
"meta": await get_cloud_map_runtime_meta(db),
}
@router.get("/clouds/frames/{version}/visual", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_cloud_visual_frame(version: str):
from app.services.earth_clouds import read_cloud_visual_frame_bytes
content = read_cloud_visual_frame_bytes(version)
if content is None:
raise HTTPException(status_code=404, detail="Cloud visual frame not found")
return Response(
content=content,
media_type="image/webp",
headers={"Cache-Control": "public, max-age=86400, immutable"},
)
@router.get("/clouds/flows/{version}", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_cloud_flow_map(version: str):
from app.services.earth_clouds import read_cloud_flow_bytes
content = read_cloud_flow_bytes(version)
if content is None:
raise HTTPException(status_code=404, detail="Cloud optical flow map not found")
return Response(
content=content,
media_type="image/webp",
headers={"Cache-Control": "public, max-age=86400, immutable"},
)
class BasemapConfigUpdatePayload(BaseModel):
revision: str = Field(..., min_length=4, max_length=128)
config: dict[str, Any] = Field(default_factory=dict)
@router.get(
"/tiles/{source_key}/{z}/{x}/{y}.webp",
dependencies=[Depends(require_earth_or_api_access("earth:read", rate_limit_tier="tile"))],
)
async def get_earth_managed_tile(
source_key: str,
z: int,
x: int,
y: int,
db: AsyncSession = Depends(get_db),
):
from app.services.earth_tiles import get_or_fetch_tile
try:
content, allowed = await get_or_fetch_tile(source_key, z, x, y, db=db)
except ValueError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
if not allowed:
raise HTTPException(status_code=403, detail=f"Tile source '{source_key}' is disabled")
if content is None:
raise HTTPException(status_code=404, detail="Tile not available")
cache_max_age = 300 if source_key == "cloud_hd_tiles" else 86400
return Response(
content=content,
media_type="image/webp",
headers={"Cache-Control": f"public, max-age={cache_max_age}"},
)
@router.get("/basemap/meta", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_basemap_meta(db: AsyncSession = Depends(get_db)):
from app.services.earth_tiles import get_basemap_runtime_meta
return await get_basemap_runtime_meta(db)
@router.get("/basemap/configuration")
async def get_earth_basemap_configuration(
_current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
from app.services.earth_tiles import get_basemap_runtime_meta, read_basemap_configuration
envelope = await read_basemap_configuration(db)
return {
**envelope,
"meta": await get_basemap_runtime_meta(db),
}
@router.put("/basemap/configuration")
async def put_earth_basemap_configuration(
payload: BasemapConfigUpdatePayload,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
from pydantic import ValidationError
from app.services.earth_tiles import (
BasemapConfig,
BasemapRevisionConflictError,
get_basemap_runtime_meta,
save_basemap_configuration,
)
_require_cloud_admin(current_user)
try:
validated = BasemapConfig.model_validate(payload.config)
envelope = await save_basemap_configuration(
db,
revision=payload.revision,
config=validated,
actor=current_user,
reset=False,
)
except ValidationError as exc:
raise HTTPException(status_code=422, detail=exc.errors()) from exc
except BasemapRevisionConflictError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
await _broadcast_earth_config_update("basemap")
return {
**envelope,
"meta": await get_basemap_runtime_meta(db),
}
@router.post("/basemap/configuration/reset")
async def reset_earth_basemap_configuration(
payload: BasemapConfigUpdatePayload,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
from app.services.earth_tiles import (
BasemapRevisionConflictError,
DEFAULT_BASEMAP_CONFIG,
get_basemap_runtime_meta,
save_basemap_configuration,
)
_require_cloud_admin(current_user)
try:
envelope = await save_basemap_configuration(
db,
revision=payload.revision,
config=DEFAULT_BASEMAP_CONFIG,
actor=current_user,
reset=True,
)
except BasemapRevisionConflictError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
await _broadcast_earth_config_update("basemap")
return {
**envelope,
"meta": await get_basemap_runtime_meta(db),
}
@router.delete("/tiles/{source_key}/cache")
async def clear_earth_tile_cache_route(
source_key: str,
current_user: User = Depends(get_current_user),
db: AsyncSession = Depends(get_db),
):
from app.services.earth_tiles import (
TILE_SOURCES,
clear_tile_source_cache,
get_basemap_runtime_meta,
)
_require_cloud_admin(current_user)
if source_key not in TILE_SOURCES:
raise HTTPException(status_code=404, detail="Unknown tile source")
removed = clear_tile_source_cache(source_key)
await _broadcast_earth_config_update("basemap")
return {
"source": source_key,
"removed_files": removed,
"meta": await get_basemap_runtime_meta(db),
}
@router.get("/wind/meta", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_wind_meta(db: AsyncSession = Depends(get_db)):
from app.services.earth_wind import get_wind_runtime_meta
return await get_wind_runtime_meta(db)
@router.get("/wind/grid/{version}", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_earth_wind_grid(version: str):
from app.services.earth_wind import read_wind_grid_payload
payload = read_wind_grid_payload(version)
if payload is None:
raise HTTPException(status_code=404, detail="Wind grid snapshot not found")
return payload
+1 -20
View File
@@ -2,7 +2,7 @@ from copy import deepcopy
from datetime import UTC, datetime
import os
from pathlib import Path
from typing import Literal, Optional
from typing import Optional
from urllib.parse import urlsplit
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
@@ -70,7 +70,6 @@ from app.services.llm_model_catalog import (
LLMProviderCatalogConfigError,
can_refresh_catalog_without_api_key,
catalog_error_message,
catalog_requires_api_key,
fetch_model_catalog,
)
from app.services.scheduler import sync_datasource_job
@@ -759,24 +758,6 @@ def _runtime_config_from_ai_payload(ai_payload: dict) -> dict:
}
def _ai_provider_runtime_fingerprint(ai_payload: dict) -> dict:
runtime_config = _runtime_config_from_ai_payload(ai_payload)
llm_config = runtime_config.get("llm_config") or {}
return {
"service_url": runtime_config.get("service_url") or "",
"service_token": runtime_config.get("service_token") or "",
"timeout_seconds": int(runtime_config.get("timeout_seconds") or 0),
"retry_attempts": int(runtime_config.get("retry_attempts") or 0),
"provider": llm_config.get("provider") or "",
"provider_api": llm_config.get("provider_api") or "",
"base_url": llm_config.get("base_url") or "",
"model": llm_config.get("model") or "",
"api_key": llm_config.get("api_key") or "",
"max_tokens": int(llm_config.get("max_tokens") or 0),
"anthropic_version": llm_config.get("anthropic_version") or "",
}
async def _validate_ai_provider_full_connection(ai_payload: dict) -> dict:
runtime_config = _runtime_config_from_ai_payload(ai_payload)
client = AIProviderClient(
+239 -14
View File
@@ -4,12 +4,14 @@ from __future__ import annotations
from dataclasses import replace
from datetime import UTC, datetime
import hashlib
import json
import uuid
from typing import Any, Literal
from typing import Any, Literal, Self
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Response
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, ConfigDict, Field
from pydantic import BaseModel, ConfigDict, Field, model_validator
from sqlalchemy import desc, select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -18,12 +20,16 @@ from app.core.access_gate import require_earth_or_api_access
from app.db.session import get_db
from app.models.situational_assessment import (
ComputeEvidenceCandidate,
EvidenceRecord,
InvestigationSession,
TopicWatch,
WorkflowRun,
)
from app.models.system_log import AuditLog
from app.models.user import User
from app.schemas.compute_configuration import ComputeConfiguration, source_for
from app.services.compute_configuration import read_configuration
from app.services.compute_history import MODE_DENOMINATOR, ComputeSeriesMode
from app.services.ai.access_policy import (
AccessContext,
enforce_paid_research_gate,
@@ -44,7 +50,7 @@ from app.services.ai.presentation_compiler import (
from app.services.ai.proactive_pipeline import (
audit_situational_hygiene,
process_bgp_snapshot_proactive_delta,
process_compute_config_proactive_delta,
retry_pending_compute_presentations,
)
from app.services.ai.semantic_delta import extract_compute_candidates_deterministic
from app.services.ai.tool_registry import TimeBasis, query_compute_posture_tool
@@ -57,7 +63,6 @@ from app.services.ai.workflow_runtime import (
)
from app.services.ai.stream_turn import stream_session_turn
from app.services.ai_client import AIProviderClient, get_ai_provider_client
from app.services.compute_history import ComputeSeriesMode
router = APIRouter()
@@ -73,6 +78,8 @@ class SessionCreateRequest(BaseModel):
visible_layers: dict[str, bool] = Field(default_factory=dict)
time_basis: TimeBasis = "retrospective"
cutoff_at: str | None = Field(default=None, max_length=40)
publish_id: str | None = Field(default=None, max_length=64)
as_of: str | None = Field(default=None, max_length=64)
include_drill: bool = False
@@ -116,6 +123,8 @@ class SessionTurnRequest(BaseModel):
visible_layers: dict[str, bool] | None = None
time_basis: TimeBasis | None = None
cutoff_at: str | None = Field(default=None, max_length=40)
publish_id: str | None = Field(default=None, max_length=64)
as_of: str | None = Field(default=None, max_length=64)
include_drill: bool | None = None
preset: ViewPreset | None = None
prefer_llm: bool | Literal["auto"] = False
@@ -160,6 +169,8 @@ class SpatialInvestigateRequest(BaseModel):
question: str = Field(min_length=2, max_length=1000)
time_basis: TimeBasis = "retrospective"
cutoff_at: str | None = Field(default=None, max_length=40)
publish_id: str | None = Field(default=None, max_length=64)
as_of: str | None = Field(default=None, max_length=64)
include_drill: bool = False
external_urls: list[str] = Field(default_factory=list, max_length=3)
@@ -177,6 +188,25 @@ class ReportExportRequest(BaseModel):
cutoff_at: str | None = Field(default=None, max_length=40)
APPROVE_REASON_CODES = frozenset(
{
"newer_authoritative_report",
"corrects_prior_error",
"adds_missing_observation",
"methodology_update",
}
)
REJECT_REASON_CODES = frozenset(
{
"unverifiable_source",
"denominator_mismatch",
"extraction_error",
"superseded",
"duplicate",
}
)
class CandidateExtractRequest(BaseModel):
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
@@ -187,12 +217,36 @@ class CandidateExtractRequest(BaseModel):
source_url: str = Field(min_length=8, max_length=2000)
publisher: str = Field(default="Research Institute", max_length=200)
locator: str = Field(default="Extracted excerpt", max_length=300)
period_label: str | None = Field(default=None, max_length=40)
published_at: str | None = Field(default=None, max_length=40)
report_year: int | None = Field(default=None, ge=2000, le=2100)
class CandidateReviewRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
decision: Literal["approved", "rejected"]
reason_code: Literal[
"newer_authoritative_report",
"corrects_prior_error",
"adds_missing_observation",
"methodology_update",
"unverifiable_source",
"denominator_mismatch",
"extraction_error",
"superseded",
"duplicate",
]
reason: str = Field(min_length=2, max_length=1000)
@model_validator(mode="after")
def matching_reason_code(self) -> Self:
allowed = APPROVE_REASON_CODES if self.decision == "approved" else REJECT_REASON_CODES
if self.reason_code not in allowed:
raise ValueError(
f"reason_code '{self.reason_code}' is not valid for decision '{self.decision}'"
)
return self
# ============================================================================
@@ -219,6 +273,8 @@ async def create_investigation_session(
"visible_layers": dict(payload.visible_layers or {}),
"time_basis": payload.time_basis,
"cutoff_at": payload.cutoff_at,
"publish_id": payload.publish_id,
"as_of": payload.as_of,
"include_drill": payload.include_drill,
"active_result_id": None,
"active_revision": None,
@@ -349,6 +405,8 @@ async def create_session_turn(
"visible_layers": payload.visible_layers,
"time_basis": payload.time_basis,
"cutoff_at": payload.cutoff_at,
"publish_id": payload.publish_id,
"as_of": payload.as_of,
"include_drill": payload.include_drill,
}
turn_result = await execute_session_turn(
@@ -404,6 +462,8 @@ async def stream_investigation_session_turn(
"visible_layers": payload.visible_layers,
"time_basis": payload.time_basis,
"cutoff_at": payload.cutoff_at,
"publish_id": payload.publish_id,
"as_of": payload.as_of,
"include_drill": payload.include_drill,
}
headers = {
@@ -702,7 +762,7 @@ async def evaluate_proactive_snapshot(
db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
if payload.domain == "compute":
res = await process_compute_config_proactive_delta(db)
res = await retry_pending_compute_presentations(db)
else:
res = await process_bgp_snapshot_proactive_delta(
db,
@@ -723,6 +783,8 @@ async def get_compute_posture(
mode: ComputeSeriesMode = "global_share",
time_basis: TimeBasis = "retrospective",
cutoff_at: str | None = None,
as_of: str | None = None,
publish_id: str | None = None,
prefer_llm: bool = False,
access: AccessContext = Depends(resolve_access_context),
db: AsyncSession = Depends(get_db),
@@ -733,7 +795,13 @@ async def get_compute_posture(
codes = selected_countries(countries)
response.headers["Cache-Control"] = "no-store"
series = await query_compute_posture_tool(
db, codes, mode=mode, time_basis=time_basis, cutoff_at=cutoff_at
db,
codes,
mode=mode,
time_basis=time_basis,
cutoff_at=cutoff_at,
as_of=as_of,
publish_id=publish_id,
)
# GET is strictly 100% read-only (`persist=False`) when `prefer_llm=False`
return await generate_or_get_compute_posture(
@@ -779,6 +847,8 @@ async def investigate_spatial_context(
question=payload.question,
time_basis=payload.time_basis,
cutoff_at=payload.cutoff_at,
publish_id=payload.publish_id,
as_of=payload.as_of,
allow_drill=payload.include_drill,
ai_client=ai_client,
)
@@ -819,48 +889,190 @@ async def list_compute_candidates(
return {"items": [row.to_dict() for row in rows]}
def _candidate_dedupe_fingerprint(
*,
source_id: str,
metric: str,
year: int,
period_label: str | None,
values: dict[str, Any],
) -> str:
sorted_vals = {
str(k): round(float(v), 6)
for k, v in sorted((values or {}).items(), key=lambda kv: str(kv[0]))
}
raw = f"{source_id}|{metric}|{year}|{period_label or ''}|{json.dumps(sorted_vals, sort_keys=True, separators=(',', ':'))}"
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
def _build_candidate_comparison(
*,
current_config: ComputeConfiguration,
current_publish_id: str,
proposed: dict[str, Any],
) -> dict[str, Any]:
metric = str(proposed.get("metric") or "global_share")
year = int(proposed.get("year") or 0)
proposed_period = (proposed.get("period_label") or None)
existing_row = next(
(obs for obs in current_config.observations if obs.metric == metric and obs.year == year),
None,
)
existing_period = existing_row.period_label if existing_row is not None else None
period_conflict = bool(
existing_row is not None and (existing_period or None) != (proposed_period or None)
)
codes_comparison: dict[str, dict[str, Any]] = {}
has_historical_revision = False
for code, raw_new in sorted((proposed.get("values") or {}).items()):
new_val = float(raw_new)
if existing_row is not None and code in existing_row.values:
old_val = float(existing_row.values[code])
old_src = source_for(existing_row, code)
delta = round(new_val - old_val, 4)
change_kind = "historical_revision" if delta != 0 else "unchanged"
if change_kind == "historical_revision":
has_historical_revision = True
else:
old_val = None
old_src = None
delta = round(new_val, 4)
change_kind = "new_observation"
codes_comparison[code] = {
"old_value": old_val,
"new_value": new_val,
"delta": delta,
"change_kind": change_kind,
"old_source_id": old_src,
}
return {
"publish_id": current_publish_id,
"metric": metric,
"year": year,
"period_label": proposed_period,
"existing_period_label": existing_period,
"period_conflict": period_conflict,
"denominator": MODE_DENOMINATOR.get(metric),
"codes": codes_comparison,
"has_historical_revision": has_historical_revision,
}
@router.post("/candidates/extract")
async def extract_compute_candidates(
payload: CandidateExtractRequest,
actor: User = Depends(configuration_admin),
db: AsyncSession = Depends(get_db),
) -> dict[str, Any]:
source_meta = {
effective_report_year = payload.report_year or payload.year
source_meta: dict[str, Any] = {
"id": payload.source_id,
"title": payload.source_title,
"url": payload.source_url,
"publisher": payload.publisher,
"report_year": payload.year,
"report_year": effective_report_year,
"published_at": payload.published_at,
"locator": payload.locator,
}
extracted = extract_compute_candidates_deterministic(
payload.excerpt, year=payload.year, source_meta=source_meta
payload.excerpt,
year=payload.year,
source_meta=source_meta,
period_label=payload.period_label,
)
envelope = await read_configuration(db)
current_config = ComputeConfiguration.model_validate(envelope["config"])
current_publish_id = str(envelope.get("publish_id") or envelope["revision"])
# Upsert immutable EvidenceRecord without overwriting existing record.
if extracted and hasattr(db, "execute") and hasattr(db, "add"):
existing_ev = (
await db.execute(select(EvidenceRecord).where(EvidenceRecord.id == payload.source_id))
).scalar_one_or_none()
if existing_ev is None:
db.add(
EvidenceRecord(
id=payload.source_id,
source_type="curated_report",
title=payload.source_title,
publisher=payload.publisher,
url=payload.source_url,
locator=payload.locator,
excerpt=payload.excerpt,
content_sha256=hashlib.sha256(payload.excerpt.encode("utf-8")).hexdigest(),
published_at=payload.published_at or str(effective_report_year),
metadata_json={
"report_year": effective_report_year,
"period_label": payload.period_label,
},
)
)
created: list[ComputeEvidenceCandidate] = []
ordered_entries: list[tuple[ComputeEvidenceCandidate, bool]] = []
for item in extracted:
proposed = item["proposed_payload"]
fp = _candidate_dedupe_fingerprint(
source_id=str(proposed.get("source_id") or payload.source_id),
metric=str(proposed.get("metric") or "global_share"),
year=int(proposed.get("year") or payload.year),
period_label=proposed.get("period_label"),
values=proposed.get("values") or {},
)
existing_cand = (
await db.execute(
select(ComputeEvidenceCandidate)
.where(ComputeEvidenceCandidate.dedupe_fingerprint == fp)
.order_by(desc(ComputeEvidenceCandidate.id))
.limit(1)
)
).scalar_one_or_none()
if existing_cand is not None:
ordered_entries.append((existing_cand, True))
continue
comparison = _build_candidate_comparison(
current_config=current_config,
current_publish_id=current_publish_id,
proposed=proposed,
)
record = ComputeEvidenceCandidate(
status="pending",
candidate_type=item["candidate_type"],
proposed_payload=item["proposed_payload"],
proposed_payload=proposed,
source_payload=item["source_payload"],
comparison=comparison,
dedupe_fingerprint=fp,
confidence=item["confidence"],
extractor_note=item["extractor_note"],
)
db.add(record)
created.append(record)
ordered_entries.append((record, False))
db.add(
AuditLog(
actor_id=actor.id,
actor_name=actor.username,
action="compute_candidates.extract",
target_type="compute_evidence_candidates",
target_id=payload.source_id,
details={"count": len(created), "year": payload.year},
details={
"count": len(created),
"duplicates": sum(1 for _, is_dup in ordered_entries if is_dup),
"year": payload.year,
},
)
)
await db.commit()
for rec in created:
await db.refresh(rec)
return {"items": [rec.to_dict() for rec in created]}
return {
"items": [
{**rec.to_dict(), "duplicate": is_dup}
for rec, is_dup in ordered_entries
]
}
@router.post("/candidates/{candidate_id}/review")
@@ -877,17 +1089,30 @@ async def review_compute_candidate(
).scalar_one_or_none()
if record is None:
raise HTTPException(status_code=404, detail="Candidate not found")
if record.published_publish_id:
raise HTTPException(
status_code=409,
detail="Candidate has already been published and cannot be modified.",
)
previous_status = record.status
record.status = payload.decision
record.review_reason_code = payload.reason_code
record.review_reason = payload.reason
record.reviewed_by = actor.username
record.reviewed_at = datetime.now(UTC)
db.add(
AuditLog(
actor_id=actor.id,
actor_name=actor.username,
action=f"compute_candidates.{payload.decision}",
target_type="compute_evidence_candidates",
target_id=str(candidate_id),
details={"before_status": previous_status, "after_status": payload.decision},
details={
"before_status": previous_status,
"after_status": payload.decision,
"reason_code": payload.reason_code,
"reason": payload.reason,
},
)
)
await db.commit()
+120 -162
View File
@@ -37,23 +37,17 @@ from app.services.cable_graph import build_graph_from_data, CableGraph, haversin
from app.services.compute_center_locations import (
RENDERABLE_PRECISIONS,
ResolutionDiagnostic,
build_compute_center_location_query,
collect_location_candidates,
get_compute_center_location_dict,
refresh_compute_center_location_cache,
resolve_compute_center_location_full,
upsert_compute_center_location,
)
from app.services.ai_client import get_ai_provider_client
from app.api.v1.settings import get_runtime_web_search_config, get_web_search_client
from app.api.v1.settings import get_runtime_web_search_config
from app.services.ai_tools.web_search import normalize_web_search_provider
from app.services.collectors.bgp_common import RIPE_RIS_COLLECTOR_COORDS
from app.services.location.llm_fallback import (
collect_llm_location_fallback_candidate,
collect_location_search_evidence,
)
from app.services.location.agent_resolver import (
run_controlled_location_agent,
run_l1_structured_facility_resolvers,
from app.services.location.workflow_tools import (
TERMINAL_UNLOCATABLE_STATUSES,
run_location_workflow,
)
from app.services.persistent_logs import record_system_log
from app.services.vessel_ais_aggregation import (
@@ -79,6 +73,9 @@ from app.core.logging import get_logger
router = APIRouter()
logger = get_logger(__name__, service="api")
_vis_read_dep = Depends(require_earth_or_api_access("visualization:read"))
_vis_tile_read_dep = Depends(
require_earth_or_api_access("visualization:read", rate_limit_tier="tile")
)
TERRAIN_TILE_URL_TEMPLATE = (
"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
)
@@ -296,7 +293,14 @@ def _extract_satellite_record(record: CollectedData) -> tuple[dict[str, Any], An
tle_line1 = metadata.get("tle_line1")
tle_line2 = metadata.get("tle_line2")
if not tle_line1 or not tle_line2:
# Stored 6-digit NORAD TLE lines (70+ chars) shift orbital element columns; regenerate using Alpha-5.
valid_tle = (
isinstance(tle_line1, str)
and isinstance(tle_line2, str)
and len(tle_line1.rstrip()) == 69
and len(tle_line2.rstrip()) == 69
)
if not valid_tle:
tle_line1, tle_line2 = build_tle_lines_from_elements(
norad_cat_id=norad_id,
epoch=metadata.get("epoch"),
@@ -719,16 +723,27 @@ def convert_compute_centers_to_geojson(records: List[CollectedData]) -> Dict[str
features: List[Dict[str, Any]] = []
unresolved: List[Dict[str, Any]] = []
withheld_count = 0
withheld_by_status: Dict[str, int] = {}
for record in records:
metadata = record.extra_data or {}
if metadata.get("compute_contract") == "v1" and metadata.get("anonymous"):
withheld_count += 1
withheld_by_status["anonymous"] = withheld_by_status.get("anonymous", 0) + 1
continue
result = resolve_compute_center_location_full(record, metadata)
site_type = compute_site_type(record)
if not result.is_resolved:
stored_loc = get_compute_center_location_dict(
getattr(record, "source", None),
getattr(record, "source_id", None),
)
stored_status = str(stored_loc.get("verification_status") or "").strip().lower()
if stored_status in TERMINAL_UNLOCATABLE_STATUSES:
withheld_count += 1
withheld_by_status[stored_status] = withheld_by_status.get(stored_status, 0) + 1
continue
diagnostic = result.diagnostic or ResolutionDiagnostic(
failure_reason="Unknown resolver failure",
attempted_queries=(),
@@ -816,7 +831,13 @@ def convert_compute_centers_to_geojson(records: List[CollectedData]) -> Dict[str
}
)
return {"type": "FeatureCollection", "features": features, "unresolved": unresolved, "withheld_count": withheld_count}
return {
"type": "FeatureCollection",
"features": features,
"unresolved": unresolved,
"withheld_count": withheld_count,
"withheld_by_status": withheld_by_status,
}
VESSEL_TYPE_FILTERS = {
@@ -1693,7 +1714,7 @@ async def _build_landing_points_geojson(db: AsyncSession) -> dict[str, Any]:
raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}")
@router.get("/terrain/terrarium/{z}/{x}/{y}.png", dependencies=[_vis_read_dep])
@router.get("/terrain/terrarium/{z}/{x}/{y}.png", dependencies=[_vis_tile_read_dep])
async def get_terrarium_tile(z: int, x: int, y: int):
"""Proxy Terrarium elevation tiles through the backend to avoid browser CORS issues."""
if not _is_valid_terrain_tile(z, x, y):
@@ -1783,7 +1804,7 @@ async def _fetch_terrain_tile(
return content, content_type, dict(headers)
@router.post("/terrain/terrarium/batch", dependencies=[_vis_read_dep])
@router.post("/terrain/terrarium/batch", dependencies=[_vis_tile_read_dep])
async def get_terrarium_tile_batch(payload: TerrariumTileBatchRequest):
"""Fetch Terrarium elevation tiles in batches so the browser avoids many tiny requests."""
unique_tiles: list[TerrariumTileRequest] = []
@@ -2095,6 +2116,8 @@ async def _build_compute_centers_geojson(
"type": "FeatureCollection",
"features": [],
"unresolved": [],
"withheld_count": 0,
"withheld_by_status": {},
"count": 0,
"stats": {
"total": 0,
@@ -2140,6 +2163,8 @@ async def _build_compute_centers_geojson(
"type": "FeatureCollection",
"features": sanitized_features,
"unresolved": unresolved,
"withheld_count": int(geojson.get("withheld_count") or 0),
"withheld_by_status": geojson.get("withheld_by_status") or {},
"count": len(sanitized_features),
"stats": {
"total": len(sanitized_features),
@@ -2188,6 +2213,8 @@ class SaveComputeCenterLocationRequest(BaseModel):
raw_payload: Dict[str, Any] = Field(default_factory=dict)
needs_confirmation: bool = False
verification_status: Optional[str] = None
workflow_run_id: Optional[str] = None
feedback_rating: Optional[int] = None
model_config = {"populate_by_name": True}
@@ -2202,7 +2229,11 @@ async def _compute_center_location_web_search_capability(db: AsyncSession) -> Di
"reason": f"WebSearch 配置读取失败:{exc}",
}
provider_config = config.active_provider_config
has_api_key = bool((provider_config.api_key or "").strip()) or not provider_config.api_key_env
provider_name = normalize_web_search_provider(provider_config.provider)
has_api_key = (
provider_name == "searxng"
or bool((provider_config.api_key or "").strip())
)
if not config.enabled:
return {
"enabled": False,
@@ -2230,9 +2261,6 @@ async def get_compute_center_location_capability(
return await _compute_center_location_web_search_capability(db)
_TERMINAL_UNLOCATABLE_STATUSES = frozenset({"undisclosed", "multi_site", "anonymous"})
@router.post("/compute-centers/{source_id}/collect-location")
async def collect_compute_center_location(
source_id: str,
@@ -2240,155 +2268,78 @@ async def collect_compute_center_location(
_admin: User = Depends(require_admin_user),
db: AsyncSession = Depends(get_db),
):
"""Run deterministic facility lookups, Wikidata/PeeringDB, and controlled Tool-Calling location resolution."""
"""Run the unified `location.resolve_unknown` DAG workflow to locate a compute facility."""
if not source_id or not source_id.strip():
raise HTTPException(status_code=400, detail="source_id is required")
record = await _load_compute_center_record(db, source_id)
name = payload.name or (record.name if record else None)
metadata = (record.extra_data or {}) if record else {}
operator = payload.operator or metadata.get("operator") or metadata.get("organization") or metadata.get("owner")
site = payload.site or metadata.get("site")
organization = payload.organization or metadata.get("organization")
city = payload.city or get_record_field(record, "city") if record else payload.city
city = payload.city or (get_record_field(record, "city") if record else None)
country = payload.country or (get_record_field(record, "country") if record else None)
source = payload.source or (record.source if record else None)
record_id = payload.record_id or (record.id if record else None)
raw_sources = metadata.get("sources") if isinstance(metadata.get("sources"), list) else []
raw_sources = list(metadata.get("sources") if isinstance(metadata.get("sources"), list) else [])
source_url = metadata.get("source_url") or metadata.get("detail_url")
builds_upon = metadata.get("builds_upon")
source_raw_country = metadata.get("raw_country")
if not payload.force and source and source_id:
cached = get_compute_center_location_dict(source, source_id)
cached_status = str(cached.get("verification_status") or "").strip().lower()
if cached_status in _TERMINAL_UNLOCATABLE_STATUSES:
return {
"source_id": source_id,
"record_id": record_id,
"name": name,
"success": False,
"terminal_status": cached_status,
"failure_reason": cached.get("source_note") or f"Marked as {cached_status}",
"candidates": [],
"attempted_queries": [],
"llm_failure_reason": None,
"context": {
"name": name,
"operator": operator,
"site": site,
"city": city,
"country": country,
},
}
earth_ctx = {
"entity_type": "compute_center",
"source_id": source_id,
"record_id": record_id,
"source": source,
"name": name,
"operator": operator,
"site": site,
"organization": organization,
"city": city,
"country": country,
"sources": raw_sources,
"source_url": source_url,
"builds_upon": builds_upon,
"source_raw_country": source_raw_country,
"force": bool(payload.force),
}
candidates, attempted_queries = await asyncio.to_thread(
collect_location_candidates,
name=name,
source=source,
source_id=source_id,
operator=operator,
site=site,
organization=organization,
city=city,
country=country,
record_id=record_id,
sources=raw_sources,
source_url=source_url,
builds_upon=builds_upon,
source_raw_country=source_raw_country,
res = await run_location_workflow(
db=db,
entity_type="compute_center",
earth_context=earth_ctx,
targets=[{"entity_type": "compute_center", "entity_id": source_id, "label": name or source_id}],
record_run=True,
trigger_evolution=True,
)
llm_failure_reason = None
terminal_status: str | None = None
query = build_compute_center_location_query(
name=name,
source=source,
source_id=source_id,
operator=operator,
site=site,
organization=organization,
city=city,
country=country,
sources=raw_sources,
source_url=source_url,
builds_upon=builds_upon,
source_raw_country=source_raw_country,
)
if not candidates:
l1_candidates, l1_queries, _allow_low_short_circuit = await run_l1_structured_facility_resolvers(
query, db=db
)
if l1_candidates:
candidates = l1_candidates
attempted_queries = [*attempted_queries, *l1_queries]
if not candidates:
capability = await _compute_center_location_web_search_capability(db)
llm_result = None
if not capability.get("enabled") and not raw_sources and not source_url:
llm_failure_reason = str(capability.get("reason") or "WebSearch unavailable")
else:
try:
provider_client = await get_ai_provider_client(db)
web_search_client = await get_web_search_client(db)
if hasattr(provider_client, "analyze"):
llm_result, terminal_status = await run_controlled_location_agent(
provider_client=provider_client,
web_search_client=web_search_client,
query=query,
entity_type="compute_center",
db=db,
attempted_queries=[],
)
else:
search_result = await collect_location_search_evidence(
web_search_client=web_search_client,
query=query,
entity_type="compute_center",
)
attempted_queries = [*attempted_queries, *search_result.attempted_queries]
if not search_result.evidence:
llm_failure_reason = search_result.failure_reason
raise RuntimeError(search_result.failure_reason or "no WebSearch evidence")
llm_result = await collect_llm_location_fallback_candidate(
provider_client=provider_client,
query=query,
entity_type="compute_center",
db=db,
attempted_queries=attempted_queries,
search_evidence=search_result.evidence,
)
except Exception as exc:
if llm_failure_reason is None:
llm_failure_reason = f"LLM location factcheck unavailable: {exc}"
attempted_queries = [
*attempted_queries,
f"llm_factcheck:compute_center:{name or source_id or 'unknown'}",
]
if llm_result is not None:
attempted_queries = [*attempted_queries, *llm_result.attempted_queries]
candidates = llm_result.candidates
llm_failure_reason = llm_result.failure_reason
candidates = res.get("candidates") or []
terminal_status = res.get("terminal_status")
failure_reason = res.get("failure_reason")
attempted_queries = list(res.get("attempted_queries") or [])
workflow_run_id = res.get("workflow_run_id")
context = {
"name": name,
"operator": operator,
"site": site,
"city": city,
"country": country,
}
if terminal_status in _TERMINAL_UNLOCATABLE_STATUSES:
if terminal_status in TERMINAL_UNLOCATABLE_STATUSES:
return {
"source_id": source_id,
"record_id": record_id,
"name": name,
"success": False,
"terminal_status": terminal_status,
"failure_reason": llm_failure_reason or f"Marked as {terminal_status}",
"failure_reason": failure_reason or f"Marked as {terminal_status}",
"candidates": [],
"attempted_queries": list(attempted_queries),
"llm_failure_reason": llm_failure_reason,
"context": {
"name": name,
"operator": operator,
"site": site,
"city": city,
"country": country,
},
"attempted_queries": attempted_queries,
"llm_failure_reason": failure_reason,
"workflow_run_id": workflow_run_id,
"context": context,
}
if not candidates:
@@ -2400,8 +2351,9 @@ async def collect_compute_center_location(
"record_id": record_id,
"name": name,
"success": False,
"llm_failure_reason": llm_failure_reason,
"attempted_queries": list(attempted_queries),
"llm_failure_reason": failure_reason,
"attempted_queries": attempted_queries,
"workflow_run_id": workflow_run_id,
"context": {
"operator": operator,
"site": site,
@@ -2420,15 +2372,10 @@ async def collect_compute_center_location(
" result reached city-level precision."
),
"candidates": [],
"attempted_queries": list(attempted_queries),
"llm_failure_reason": llm_failure_reason,
"context": {
"name": name,
"operator": operator,
"site": site,
"city": city,
"country": country,
},
"attempted_queries": attempted_queries,
"llm_failure_reason": failure_reason,
"workflow_run_id": workflow_run_id,
"context": context,
}
best_candidate = candidates[0].to_dict()
@@ -2442,8 +2389,9 @@ async def collect_compute_center_location(
"success": True,
"candidate_count": len(candidates),
"best_candidate": best_candidate,
"llm_failure_reason": llm_failure_reason,
"attempted_queries": list(attempted_queries),
"llm_failure_reason": failure_reason,
"attempted_queries": attempted_queries,
"workflow_run_id": workflow_run_id,
"context": {
"operator": operator,
"site": site,
@@ -2459,14 +2407,9 @@ async def collect_compute_center_location(
"success": True,
"candidates": [candidate.to_dict() for candidate in candidates],
"best_candidate": best_candidate,
"attempted_queries": list(attempted_queries),
"context": {
"name": name,
"operator": operator,
"site": site,
"city": city,
"country": country,
},
"attempted_queries": attempted_queries,
"workflow_run_id": workflow_run_id,
"context": context,
}
@@ -2521,6 +2464,21 @@ async def save_compute_center_location(
or ("unverified" if payload.needs_confirmation else "verified"),
)
if payload.workflow_run_id:
try:
from app.services.ai.workflow_evolver import record_run_feedback
rating = payload.feedback_rating if payload.feedback_rating in (-1, 0, 1) else 1
await record_run_feedback(
db,
payload.workflow_run_id,
rating=rating,
note=f"Adopted compute-center location for {source_id}",
actor=f"admin:{getattr(_admin, 'username', 'admin')}",
)
except Exception:
pass
return {
"success": True,
"source": saved.source,
+26
View File
@@ -0,0 +1,26 @@
"""Real-time global 10m wind field analytics & spatial point query APIs."""
from __future__ import annotations
from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.access_gate import require_earth_or_api_access
from app.db.session import get_db
from app.services.earth_wind import get_wind_analysis_summary, query_wind_point
router = APIRouter()
@router.get("/summary", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_wind_summary(db: AsyncSession = Depends(get_db)):
return await get_wind_analysis_summary(db)
@router.get("/point", dependencies=[Depends(require_earth_or_api_access("earth:read"))])
async def get_wind_point(
lat: float = Query(..., ge=-90.0, le=90.0),
lon: float = Query(..., ge=-180.0, le=180.0),
db: AsyncSession = Depends(get_db),
):
return await query_wind_point(lat, lon, db=db)
+64 -9
View File
@@ -47,6 +47,14 @@ TURNSTILE_VERIFY_URL = "https://challenges.cloudflare.com/turnstile/v0/siteverif
_EARTH_SESSION_TOKEN_TYPE = "earth_session"
_MAX_DESKTOP_CLOCK_SKEW_SECONDS = 300
_EARTH_SESSION_RATE_LIMIT_PER_MIN = 600
_EARTH_SESSION_TILE_RATE_LIMIT_PER_MIN = 3000
_RATE_LIMIT_LUA = """
local count = redis.call('INCR', KEYS[1])
if count == 1 or redis.call('TTL', KEYS[1]) < 0 then
redis.call('EXPIRE', KEYS[1], tonumber(ARGV[1]))
end
return count
"""
_LOCAL_SLIDING_WINDOWS: dict[str, deque[float]] = defaultdict(deque)
_LOCAL_NONCES: dict[str, float] = {}
_MAX_LOCAL_ENTRIES = 20_000
@@ -91,15 +99,31 @@ async def check_sliding_rate_limit(
redis_key = f"access_gate:{bucket}"
try:
client = _AsyncRedisClient.get_client()
count = await asyncio.wait_for(
client.incr(redis_key),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
if int(count) == 1:
await asyncio.wait_for(
client.expire(redis_key, window_seconds),
if callable(getattr(client, "eval", None)):
count = await asyncio.wait_for(
client.eval(_RATE_LIMIT_LUA, 1, redis_key, window_seconds),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
else:
count = await asyncio.wait_for(
client.incr(redis_key),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
if int(count) == 1:
await asyncio.wait_for(
client.expire(redis_key, window_seconds),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
elif callable(getattr(client, "ttl", None)):
ttl = await asyncio.wait_for(
client.ttl(redis_key),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
if int(ttl) < 0:
await asyncio.wait_for(
client.expire(redis_key, window_seconds),
timeout=REDIS_OP_TIMEOUT_SECONDS,
)
if int(count) > limit:
raise HTTPException(
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
@@ -386,13 +410,43 @@ async def _validate_bearer_api_user(
return user
EarthRateLimitTier = Literal["default", "tile"]
def _resolve_earth_session_rate_limit(tier: EarthRateLimitTier) -> int:
if tier == "tile":
return max(
1,
int(
getattr(
settings,
"EARTH_SESSION_TILE_RATE_LIMIT_PER_MIN",
_EARTH_SESSION_TILE_RATE_LIMIT_PER_MIN,
)
),
)
return max(
1,
int(
getattr(
settings,
"EARTH_SESSION_RATE_LIMIT_PER_MIN",
_EARTH_SESSION_RATE_LIMIT_PER_MIN,
)
),
)
def require_earth_or_api_access(
scope: str,
*,
allow_query_api_key: bool = False,
rate_limit_tier: EarthRateLimitTier = "default",
):
"""Build a FastAPI dependency allowing API Keys, authorized JWT users, or Earth sessions."""
bucket_suffix = ":tile" if rate_limit_tier == "tile" else ""
async def _dependency(
request: Request,
credentials: HTTPAuthorizationCredentials | None = Depends(optional_bearer),
@@ -425,9 +479,10 @@ def require_earth_or_api_access(
if claims is not None:
channel = "earth_desktop" if claims.get("channel") == "desktop" else "earth_web"
cid = str(claims.get("cid") or "anon")
effective_limit = _resolve_earth_session_rate_limit(rate_limit_tier)
await check_sliding_rate_limit(
f"earth:{channel}:{cid}",
limit=_EARTH_SESSION_RATE_LIMIT_PER_MIN,
f"earth:{channel}:{cid}{bucket_suffix}",
limit=effective_limit,
window_seconds=60,
detail="Earth session rate limit exceeded",
)
+2
View File
@@ -94,6 +94,8 @@ class Settings(BaseSettings):
EARTH_API_AUTH_MODE: str = ""
EARTH_SESSION_TTL_MINUTES: int = 30
EARTH_SESSION_RATE_LIMIT_PER_MIN: int = 600
EARTH_SESSION_TILE_RATE_LIMIT_PER_MIN: int = 3000
EARTH_WEB_ALLOWED_ORIGINS: List[str] = []
EARTH_DESKTOP_HANDSHAKE_SECRET: str = ""
TURNSTILE_SECRET_KEY: str = ""
+22 -21
View File
@@ -12,14 +12,14 @@ COUNTRY_ENTRIES = [
("阿根廷", ["Argentina", "AR", "ARG"]),
("亚美尼亚", ["Armenia", "AM", "ARM"]),
("澳大利亚", ["Australia", "AU", "AUS"]),
("奥地利", ["Austria", "AT", "AUT"]),
("奥地利", ["Austria", "AT", "AUT", "Österreich"]),
("阿塞拜疆", ["Azerbaijan", "AZ", "AZE"]),
("巴哈马", ["Bahamas", "BS", "BHS"]),
("巴林", ["Bahrain", "BH", "BHR"]),
("孟加拉国", ["Bangladesh", "BD", "BGD"]),
("巴巴多斯", ["Barbados", "BB", "BRB"]),
("白俄罗斯", ["Belarus", "BY", "BLR"]),
("比利时", ["Belgium", "BE", "BEL"]),
("比利时", ["Belgium", "BE", "BEL", "België", "Belgique"]),
("伯利兹", ["Belize", "BZ", "BLZ"]),
("贝宁", ["Benin", "BJ", "BEN"]),
("不丹", ["Bhutan", "BT", "BTN"]),
@@ -51,8 +51,8 @@ COUNTRY_ENTRIES = [
("克罗地亚", ["Croatia", "HR", "HRV"]),
("古巴", ["Cuba", "CU", "CUB"]),
("塞浦路斯", ["Cyprus", "CY", "CYP"]),
("捷克", ["Czech Republic", "Czechia", "CZ", "CZE"]),
("丹麦", ["Denmark", "DK", "DNK"]),
("捷克", ["Czech Republic", "Czechia", "CZ", "CZE", "Česko"]),
("丹麦", ["Denmark", "DK", "DNK", "Danmark"]),
("吉布提", ["Djibouti", "DJ", "DJI"]),
("多米尼克", ["Dominica", "DM", "DMA"]),
("多米尼加", ["Dominican Republic", "DO", "DOM"]),
@@ -65,14 +65,14 @@ COUNTRY_ENTRIES = [
("埃斯瓦蒂尼", ["Eswatini", "SZ", "SWZ", "Swaziland"]),
("埃塞俄比亚", ["Ethiopia", "ET", "ETH"]),
("斐济", ["Fiji", "FJ", "FJI"]),
("芬兰", ["Finland", "FI", "FIN"]),
("芬兰", ["Finland", "FI", "FIN", "Suomi"]),
("法国", ["France", "FR", "FRA"]),
("加蓬", ["Gabon", "GA", "GAB"]),
("冈比亚", ["Gambia", "GM", "GMB"]),
("格鲁吉亚", ["Georgia", "GE", "GEO"]),
("德国", ["Germany", "DE", "DEU"]),
("德国", ["Germany", "DE", "DEU", "Deutschland"]),
("加纳", ["Ghana", "GH", "GHA"]),
("希腊", ["Greece", "GR", "GRC"]),
("希腊", ["Greece", "GR", "GRC", "Ελλάς", "Ελλάδα"]),
("格林纳达", ["Grenada", "GD", "GRD"]),
("危地马拉", ["Guatemala", "GT", "GTM"]),
("几内亚", ["Guinea", "GN", "GIN"]),
@@ -80,15 +80,15 @@ COUNTRY_ENTRIES = [
("圭亚那", ["Guyana", "GY", "GUY"]),
("海地", ["Haiti", "HT", "HTI"]),
("洪都拉斯", ["Honduras", "HN", "HND"]),
("匈牙利", ["Hungary", "HU", "HUN"]),
("冰岛", ["Iceland", "IS", "ISL"]),
("匈牙利", ["Hungary", "HU", "HUN", "Magyarország"]),
("冰岛", ["Iceland", "IS", "ISL", "Ísland", "Island"]),
("印度", ["India", "IN", "IND"]),
("印度尼西亚", ["Indonesia", "ID", "IDN"]),
("伊朗", ["Iran", "IR", "IRN", "Iran (Islamic Republic of)"]),
("伊拉克", ["Iraq", "IQ", "IRQ"]),
("爱尔兰", ["Ireland", "IE", "IRL"]),
("以色列", ["Israel", "IL", "ISR"]),
("意大利", ["Italy", "IT", "ITA"]),
("爱尔兰", ["Ireland", "IE", "IRL", "Éire"]),
("以色列", ["Israel", "IL", "ISR", "ישראל"]),
("意大利", ["Italy", "IT", "ITA", "Italia"]),
("牙买加", ["Jamaica", "JM", "JAM"]),
("日本", ["Japan", "JP", "JPN"]),
("约旦", ["Jordan", "JO", "JOR"]),
@@ -96,7 +96,7 @@ COUNTRY_ENTRIES = [
("肯尼亚", ["Kenya", "KE", "KEN"]),
("基里巴斯", ["Kiribati", "KI", "KIR"]),
("朝鲜", ["North Korea", "Korea, DPRK", "Democratic People's Republic of Korea", "KP", "PRK"]),
("韩国", ["South Korea", "Republic of Korea", "Korea", "KR", "KOR"]),
("韩国", ["South Korea", "Republic of Korea", "Korea", "KR", "KOR", "대한민국"]),
("科威特", ["Kuwait", "KW", "KWT"]),
("吉尔吉斯斯坦", ["Kyrgyzstan", "KG", "KGZ"]),
("老挝", ["Laos", "Lao PDR", "Lao People's Democratic Republic", "LA", "LAO"]),
@@ -129,13 +129,13 @@ COUNTRY_ENTRIES = [
("纳米比亚", ["Namibia", "NA", "NAM"]),
("瑙鲁", ["Nauru", "NR", "NRU"]),
("尼泊尔", ["Nepal", "NP", "NPL"]),
("荷兰", ["Netherlands", "NL", "NLD"]),
("荷兰", ["Netherlands", "NL", "NLD", "Nederland"]),
("新西兰", ["New Zealand", "NZ", "NZL"]),
("尼加拉瓜", ["Nicaragua", "NI", "NIC"]),
("尼日尔", ["Niger", "NE", "NER"]),
("尼日利亚", ["Nigeria", "NG", "NGA"]),
("北马其顿", ["North Macedonia", "MK", "MKD", "Macedonia"]),
("挪威", ["Norway", "NO", "NOR"]),
("挪威", ["Norway", "NO", "NOR", "Norge"]),
("阿曼", ["Oman", "OM", "OMN"]),
("巴基斯坦", ["Pakistan", "PK", "PAK"]),
("帕劳", ["Palau", "PW", "PLW"]),
@@ -145,11 +145,11 @@ COUNTRY_ENTRIES = [
("巴拉圭", ["Paraguay", "PY", "PRY"]),
("秘鲁", ["Peru", "PE", "PER"]),
("菲律宾", ["Philippines", "PH", "PHL"]),
("波兰", ["Poland", "PL", "POL"]),
("波兰", ["Poland", "PL", "POL", "Polska"]),
("葡萄牙", ["Portugal", "PT", "PRT"]),
("卡塔尔", ["Qatar", "QA", "QAT"]),
("罗马尼亚", ["Romania", "RO", "ROU"]),
("俄罗斯", ["Russia", "Russian Federation", "RU", "RUS"]),
("俄罗斯", ["Russia", "Russian Federation", "RU", "RUS", "Россия"]),
("卢旺达", ["Rwanda", "RW", "RWA"]),
("圣基茨和尼维斯", ["Saint Kitts and Nevis", "KN", "KNA"]),
("圣卢西亚", ["Saint Lucia", "LC", "LCA"]),
@@ -169,12 +169,12 @@ COUNTRY_ENTRIES = [
("索马里", ["Somalia", "SO", "SOM"]),
("南非", ["South Africa", "ZA", "ZAF"]),
("南苏丹", ["South Sudan", "SS", "SSD"]),
("西班牙", ["Spain", "ES", "ESP"]),
("西班牙", ["Spain", "ES", "ESP", "España"]),
("斯里兰卡", ["Sri Lanka", "LK", "LKA"]),
("苏丹", ["Sudan", "SD", "SDN"]),
("苏里南", ["Suriname", "SR", "SUR"]),
("瑞典", ["Sweden", "SE", "SWE"]),
("瑞士", ["Switzerland", "CH", "CHE"]),
("瑞典", ["Sweden", "SE", "SWE", "Sverige"]),
("瑞士", ["Switzerland", "CH", "CHE", "Schweiz", "Suisse", "Svizzera"]),
("叙利亚", ["Syria", "SY", "SYR", "Syrian Arab Republic"]),
("塔吉克斯坦", ["Tajikistan", "TJ", "TJK"]),
("坦桑尼亚", ["Tanzania", "TZ", "TZA", "United Republic of Tanzania"]),
@@ -188,7 +188,7 @@ COUNTRY_ENTRIES = [
("土库曼斯坦", ["Turkmenistan", "TM", "TKM"]),
("图瓦卢", ["Tuvalu", "TV", "TUV"]),
("乌干达", ["Uganda", "UG", "UGA"]),
("乌克兰", ["Ukraine", "UA", "UKR"]),
("乌克兰", ["Ukraine", "UA", "UKR", "Україна"]),
("阿联酋", ["United Arab Emirates", "AE", "ARE", "UAE"]),
("英国", ["United Kingdom", "UK", "GB", "GBR", "Great Britain", "Britain", "England"]),
("美国", ["United States", "United States of America", "US", "USA", "U.S.", "U.S.A."]),
@@ -292,6 +292,7 @@ def normalize_country(value: Any) -> Optional[str]:
normalized = re.sub(r"\s+", " ", value.strip())
normalized = normalized.replace("(", "(").replace(")", ")")
normalized = re.sub(r"\s*(the)$", "", normalized, flags=re.IGNORECASE).strip()
if not normalized:
return None
+5
View File
@@ -32,6 +32,11 @@ COLLECTOR_URL_KEYS = {
"news_live_streams": "news_live_streams.channels_url",
"barentswatch_vessels": "barentswatch_vessels.url",
"aisstream_vessels": "aisstream_vessels.url",
"global_cloud_map": "global_cloud_map.wms_url",
"cloud_hd_tiles": "cloud_hd_tiles.wmts_url",
"earth_imagery_sentinel2": "earth_imagery_sentinel2.wmts_url",
"earth_imagery_viirs_daily": "earth_imagery_viirs_daily.wmts_url",
"global_wind_gfs": "global_wind_gfs.erddap_url",
}
+26 -4
View File
@@ -14,10 +14,10 @@ fao:
landing_point_url: "https://data.apps.fao.org/catalog/dataset/1b75ff21-92f2-4b96-9b7b-98e8aa65ad5d/resource/b6071077-d1d4-4e97-aa00-42e902847c87/download/landing-point-geo.csv"
telegeography:
# TeleGeography 海缆/系统主数据源,当前使用 GitHub 镜像 JSON
cable_url: "https://raw.githubusercontent.com/lintaojlu/submarine_cable_information/main/cable.json"
# TeleGeography 登陆点主数据源,当前使用 GitHub 镜像 JSON
landing_point_url: "https://raw.githubusercontent.com/lintaojlu/submarine_cable_information/main/landing_point.json"
# TeleGeography 官方海缆/系统 JSON 接口
cable_url: "https://www.submarinecablemap.com/api/v3/cable/all.json"
# TeleGeography 官方登陆点 GeoJSON 接口
landing_point_url: "https://www.submarinecablemap.com/api/v3/landing-point/landing-point-geo.json"
# TeleGeography 历史 API 存档,用于 cable collector 的 fallback
archived_cable_url: "https://web.archive.org/web/2024/https://www.submarinecablemap.com/api/v3/cable"
# TeleGeography 官网页面,用于 cable collector 的最终 HTML 抓取 fallback
@@ -102,3 +102,25 @@ barentswatch_vessels:
aisstream_vessels:
# AISStream realtime WebSocket endpoint. Requires an AISStream API key.
url: "wss://stream.aisstream.io/v0/stream"
global_cloud_map:
# NASA GIBS WMS EPSG:4326 endpoint (multi-satellite IR composite primary)
wms_url: "https://gibs.earthdata.nasa.gov/wms/epsg4326/best/wms.cgi"
# Matt Eason equirectangular cloud map fallback URL
fallback_url: "https://clouds.matteason.co.uk/images/2048x1024/clouds-alpha.png"
cloud_hd_tiles:
# NASA GIBS WMTS EPSG:3857 GeoColor / Band13 tile template
wmts_url: "https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/GOES-East_ABI_GeoColor/default/default/GoogleMapsCompatible_Level7/{z}/{y}/{x}.png"
earth_imagery_sentinel2:
# EOX Sentinel-2 Cloudless 2024 global WMTS template
wmts_url: "https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-2024_3857/default/GoogleMapsCompatible/{z}/{y}/{x}.jpg"
earth_imagery_viirs_daily:
# NASA GIBS VIIRS SNPP Daily TrueColor WMTS template
wmts_url: "https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/VIIRS_SNPP_CorrectedReflectance_TrueColor/default/default/GoogleMapsCompatible_Level9/{z}/{y}/{x}.jpg"
global_wind_gfs:
# PacIOOS ERDDAP NCEP GFS global 0.5-deg 10m wind CSV0 endpoint
erddap_url: "https://pae-paha.pacioos.hawaii.edu/erddap/griddap/ncep_global.csv0"
+51 -1
View File
@@ -161,7 +161,7 @@ DEFAULT_DATASOURCES = {
"is_free": True,
"requires_credentials": True,
"credential_provider": "spacetrack",
"credential_status": "planned",
"credential_status": "supported",
},
"celestrak_tle": {
"id": 20,
@@ -267,6 +267,56 @@ DEFAULT_DATASOURCES = {
"is_free": True,
"requires_credentials": False,
},
"global_cloud_map": {
"id": 34,
"name": "Global Satellite Cloud Map",
"display_name": "全球卫星红外云图",
"module": "L2",
"priority": "P1",
"frequency_minutes": 30,
"is_free": True,
"requires_credentials": False,
},
"cloud_hd_tiles": {
"id": 35,
"name": "HD Satellite Cloud Tiles",
"display_name": "高清云图瓦片金字塔",
"module": "L2",
"priority": "P1",
"frequency_minutes": 60,
"is_free": True,
"requires_credentials": False,
},
"earth_imagery_sentinel2": {
"id": 36,
"name": "Sentinel-2 Cloudless 2024 Imagery",
"display_name": "Sentinel-2 无云高分底图",
"module": "L1",
"priority": "P2",
"frequency_minutes": 1440,
"is_free": True,
"requires_credentials": False,
},
"earth_imagery_viirs_daily": {
"id": 37,
"name": "NASA GIBS Daily TrueColor Imagery",
"display_name": "NASA 每日真彩色卫星底图",
"module": "L1",
"priority": "P2",
"frequency_minutes": 720,
"is_free": True,
"requires_credentials": False,
},
"global_wind_gfs": {
"id": 38,
"name": "NOAA GFS Global 10m Wind Field",
"display_name": "全球 10m 风场 (NOAA GFS)",
"module": "L2",
"priority": "P1",
"frequency_minutes": 180,
"is_free": True,
"requires_credentials": False,
},
}
ID_TO_COLLECTOR = {info["id"]: name for name, info in DEFAULT_DATASOURCES.items()}
+1
View File
@@ -217,6 +217,7 @@ class AuthType(StrEnum):
BEARER = "bearer"
API_KEY = "api_key"
BASIC = "basic"
OAUTH_CLIENT = "oauth_client"
class TVSourceType(StrEnum):
+25 -4
View File
@@ -29,10 +29,30 @@ def _parse_epoch(value: Any) -> Optional[datetime]:
return None
_ALPHA5_PREFIX = "ABCDEFGHJKLMNPQRSTUVWXYZ"
def format_tle_norad_id(norad_cat_id: Any) -> Optional[str]:
"""Encode a NORAD catalog id into a 5-character TLE field (Alpha-5 for >= 100000)."""
try:
norad = int(norad_cat_id)
except (TypeError, ValueError):
return None
if norad <= 0:
return None
if norad < 100000:
return f"{norad:05d}"
lead = norad // 10000
if 10 <= lead <= 33:
return f"{_ALPHA5_PREFIX[lead - 10]}{norad % 10000:04d}"
return f"{norad % 100000:05d}"
def build_tle_line1(norad_cat_id: Any, epoch: Any) -> Optional[str]:
"""Build a valid TLE line 1 from the NORAD id and epoch."""
epoch_date = _parse_epoch(epoch)
if not norad_cat_id or epoch_date is None:
norad_field = format_tle_norad_id(norad_cat_id)
if not norad_field or epoch_date is None:
return None
epoch_year = epoch_date.year % 100
@@ -49,7 +69,7 @@ def build_tle_line1(norad_cat_id: Any, epoch: Any) -> Optional[str]:
epoch_str = f"{epoch_year:02d}{day_of_year:03d}{decimal_fraction}"
core = (
f"1 {int(norad_cat_id):05d}U 00001A {epoch_str}"
f"1 {norad_field}U 00001A {epoch_str}"
" .00000000 00000-0 00000-0 0 999"
)
return core + compute_tle_checksum(core)
@@ -65,8 +85,9 @@ def build_tle_line2(
mean_motion: Any,
) -> Optional[str]:
"""Build a valid TLE line 2 from the standard orbital elements."""
norad_field = format_tle_norad_id(norad_cat_id)
required = [
norad_cat_id,
norad_field,
inclination,
raan,
eccentricity,
@@ -79,7 +100,7 @@ def build_tle_line2(
eccentricity_digits = str(round(float(eccentricity) * 10_000_000)).zfill(7)
core = (
f"2 {int(norad_cat_id):05d}"
f"2 {norad_field}"
f" {float(inclination):8.4f}"
f" {float(raan):8.4f}"
f" {eccentricity_digits}"
+23
View File
@@ -21,6 +21,7 @@ from app.models.user import User
logger = get_logger(__name__, service="security")
oauth2_scheme = HTTPBearer()
optional_oauth2_scheme = HTTPBearer(auto_error=False)
REVOKED_KEY_PREFIX = "revoked_jwt:"
LOCAL_REVOKED_MAX_ENTRIES = 10_000
@@ -297,6 +298,28 @@ async def get_current_user(
return await _load_active_user(user_id, db)
async def get_optional_current_user(
credentials: HTTPAuthorizationCredentials | None = Depends(optional_oauth2_scheme),
db: AsyncSession = Depends(get_db),
) -> User | None:
"""Resolve the active authenticated user when a valid Bearer token is present; otherwise return None."""
if credentials is None or not credentials.credentials:
return None
token = credentials.credentials
if await is_token_blacklisted(token):
return None
payload = decode_token(token)
if payload is None or payload.get("type") != "access":
return None
user_id = payload.get("sub")
if user_id is None:
return None
try:
return await _load_active_user(user_id, db)
except HTTPException:
return None
async def get_current_user_refresh(
credentials: HTTPAuthorizationCredentials = Depends(oauth2_scheme),
db: AsyncSession = Depends(get_db),
+7 -2
View File
@@ -5,15 +5,20 @@ from __future__ import annotations
from datetime import UTC, datetime
def ensure_utc(value: datetime | None) -> datetime | None:
def ensure_utc(value: datetime | str | None) -> datetime | None:
if value is None:
return None
if isinstance(value, str):
stripped = value.strip()
if not stripped:
return None
value = datetime.fromisoformat(stripped.replace("Z", "+00:00"))
if value.tzinfo is None:
return value.replace(tzinfo=UTC)
return value.astimezone(UTC)
def to_iso8601_utc(value: datetime | None) -> str | None:
def to_iso8601_utc(value: datetime | str | None) -> str | None:
normalized = ensure_utc(value)
if normalized is None:
return None
@@ -0,0 +1,177 @@
"""Create compute_configuration_revisions table and extend compute_evidence_candidates columns."""
from __future__ import annotations
from sqlalchemy import text
VERSION = "0007"
NAME = "add_compute_configuration_revisions"
async def upgrade(conn) -> None:
"""Apply compute revision ledger table and candidate review/comparison columns idempotently."""
dialect = getattr(getattr(conn, "dialect", None), "name", "")
if dialect == "postgresql":
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS compute_configuration_revisions (
id SERIAL PRIMARY KEY,
publish_id VARCHAR(64) NOT NULL UNIQUE,
parent_publish_id VARCHAR(64),
action VARCHAR(16) NOT NULL DEFAULT 'publish',
content_fingerprint VARCHAR(64) NOT NULL,
is_default_content BOOLEAN NOT NULL DEFAULT FALSE,
config_payload JSONB NOT NULL DEFAULT '{}'::jsonb,
diff_summary JSONB NOT NULL DEFAULT '[]'::jsonb,
source_candidate_ids JSONB NOT NULL DEFAULT '[]'::jsonb,
publish_note TEXT NOT NULL DEFAULT '',
published_by_id INTEGER,
published_by_name VARCHAR(120),
published_by_role VARCHAR(40),
published_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
presentation_status VARCHAR(16) NOT NULL DEFAULT 'pending',
presentation_attempts INTEGER NOT NULL DEFAULT 0,
presentation_error TEXT NOT NULL DEFAULT '',
presentation_delivered_at TIMESTAMPTZ
)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_published_at
ON compute_configuration_revisions (published_at)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_fingerprint
ON compute_configuration_revisions (content_fingerprint)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_pres_status
ON compute_configuration_revisions (presentation_status, id)
"""
)
)
await conn.execute(
text(
"""
ALTER TABLE compute_evidence_candidates
ADD COLUMN IF NOT EXISTS comparison JSONB NOT NULL DEFAULT '{}'::jsonb,
ADD COLUMN IF NOT EXISTS dedupe_fingerprint VARCHAR(64),
ADD COLUMN IF NOT EXISTS review_reason_code VARCHAR(40),
ADD COLUMN IF NOT EXISTS review_reason TEXT NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS published_publish_id VARCHAR(64)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_dedupe_fp
ON compute_evidence_candidates (dedupe_fingerprint)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_published_pid
ON compute_evidence_candidates (published_publish_id)
"""
)
)
return
# SQLite path
await conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS compute_configuration_revisions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
publish_id VARCHAR(64) NOT NULL UNIQUE,
parent_publish_id VARCHAR(64),
action VARCHAR(16) NOT NULL DEFAULT 'publish',
content_fingerprint VARCHAR(64) NOT NULL,
is_default_content BOOLEAN NOT NULL DEFAULT 0,
config_payload JSON NOT NULL DEFAULT '{}',
diff_summary JSON NOT NULL DEFAULT '[]',
source_candidate_ids JSON NOT NULL DEFAULT '[]',
publish_note TEXT NOT NULL DEFAULT '',
published_by_id INTEGER,
published_by_name VARCHAR(120),
published_by_role VARCHAR(40),
published_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
presentation_status VARCHAR(16) NOT NULL DEFAULT 'pending',
presentation_attempts INTEGER NOT NULL DEFAULT 0,
presentation_error TEXT NOT NULL DEFAULT '',
presentation_delivered_at TIMESTAMP
)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_published_at
ON compute_configuration_revisions (published_at)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_fingerprint
ON compute_configuration_revisions (content_fingerprint)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_config_revisions_pres_status
ON compute_configuration_revisions (presentation_status, id)
"""
)
)
res = await conn.execute(text("PRAGMA table_info(compute_evidence_candidates)"))
columns = {str(row[1]) for row in res.fetchall()}
if columns:
alter_specs = [
("comparison", "JSON NOT NULL DEFAULT '{}'"),
("dedupe_fingerprint", "VARCHAR(64)"),
("review_reason_code", "VARCHAR(40)"),
("review_reason", "TEXT NOT NULL DEFAULT ''"),
("published_publish_id", "VARCHAR(64)"),
]
for col_name, col_ddl in alter_specs:
if col_name not in columns:
await conn.execute(
text(f"ALTER TABLE compute_evidence_candidates ADD COLUMN {col_name} {col_ddl}")
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_dedupe_fp
ON compute_evidence_candidates (dedupe_fingerprint)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_published_pid
ON compute_evidence_candidates (published_publish_id)
"""
)
)
+64
View File
@@ -484,6 +484,7 @@ async def init_db():
import app.models.bgp_observation # noqa: F401
import app.models.collected_data # noqa: F401
import app.models.compute_center_location # noqa: F401
import app.models.compute_configuration_revision # noqa: F401
import app.models.system_setting # noqa: F401
import app.models.playground_session # noqa: F401
import app.models.playground_message # noqa: F401
@@ -919,6 +920,34 @@ async def _init_db_ddl_and_seed():
"""
)
)
await conn.execute(
text(
"""
ALTER TABLE compute_evidence_candidates
ADD COLUMN IF NOT EXISTS comparison JSONB NOT NULL DEFAULT '{}'::jsonb,
ADD COLUMN IF NOT EXISTS dedupe_fingerprint VARCHAR(64),
ADD COLUMN IF NOT EXISTS review_reason_code VARCHAR(40),
ADD COLUMN IF NOT EXISTS review_reason TEXT NOT NULL DEFAULT '',
ADD COLUMN IF NOT EXISTS published_publish_id VARCHAR(64)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_dedupe_fp
ON compute_evidence_candidates (dedupe_fingerprint)
"""
)
)
await conn.execute(
text(
"""
CREATE INDEX IF NOT EXISTS idx_compute_evidence_candidates_published_pid
ON compute_evidence_candidates (published_publish_id)
"""
)
)
await conn.execute(
text(
"""
@@ -1116,6 +1145,28 @@ async def _init_db_ddl_and_seed():
await ensure_baseline_stamped(conn)
if engine.dialect.name == "postgresql":
async with engine.connect() as base_conn:
auto_conn = await base_conn.execution_options(isolation_level="AUTOCOMMIT")
await auto_conn.execute(
text(
"""
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_collected_data_current_collected_at
ON collected_data (collected_at DESC)
WHERE is_current IS TRUE
"""
)
)
await auto_conn.execute(
text(
"""
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_collected_data_current_source_type
ON collected_data (source, data_type)
WHERE is_current IS TRUE
"""
)
)
async with async_session_factory() as session:
from app.services.bgp_collector_locations import (
seed_default_bgp_collector_locations,
@@ -1131,6 +1182,19 @@ async def _init_db_ddl_and_seed():
await purge_legacy_earth_boundary_datasources(session)
await ensure_default_admin_user(session)
await ensure_default_storage_policy(session)
from app.services.ai.proactive_pipeline import retry_pending_compute_presentations
from app.services.ai.workflow_registry import ensure_builtin_workflows
from app.services.compute_configuration import ensure_compute_revision_baseline
await ensure_builtin_workflows(session)
await ensure_compute_revision_baseline(session)
try:
await retry_pending_compute_presentations(session)
await session.commit()
except Exception as exc:
await session.rollback()
logger.warning_event(
"Startup retry of pending compute presentations failed",
event="compute.revision.presentation_failed",
context={"phase": "startup", "error": str(exc)},
)
+4
View File
@@ -201,6 +201,10 @@ class NonStreamingGZipMiddleware:
if path.endswith("/stream") or b"text/event-stream" in accept:
await self.app(scope, receive, send)
return
# PMTiles clients read byte ranges; re-encoding would break Content-Range.
if path.endswith(".pmtiles"):
await self.app(scope, receive, send)
return
await self.gzip_app(scope, receive, send)
+3
View File
@@ -52,6 +52,9 @@ class AIWorkflow(Base):
"published_graph": self.published_graph or {},
"draft_graph": self.draft_graph,
"bindings": self.bindings or {},
"draft_bindings": (
self.draft_graph.get("bindings") if isinstance(self.draft_graph, dict) else None
),
"updated_by": self.updated_by,
"created_at": to_iso8601_utc(self.created_at),
"updated_at": to_iso8601_utc(self.updated_at),
+2 -2
View File
@@ -1,6 +1,6 @@
"""Collected Data model for storing data from all collectors"""
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String, Text, JSON, Index
from sqlalchemy import Boolean, Column, DateTime, ForeignKey, Integer, String, Text, JSON, Index, text
from sqlalchemy.sql import func
from app.core.collected_data_fields import get_record_field
@@ -39,7 +39,7 @@ class CollectedData(Base):
# Status
is_valid = Column(Integer, default=1) # 1=valid, 0=invalid
is_current = Column(Boolean, default=True, index=True)
is_current = Column(Boolean, default=True, nullable=False, server_default=text("true"), index=True)
previous_record_id = Column(Integer, ForeignKey("collected_data.id"), nullable=True, index=True)
change_type = Column(String(20), nullable=True)
change_summary = Column(JSON, default={})
@@ -0,0 +1,62 @@
"""Versioned history table for curated compute comparison configurations."""
from __future__ import annotations
from sqlalchemy import Boolean, Column, DateTime, Index, Integer, JSON, String, Text
from sqlalchemy.sql import func
from app.core.time import to_iso8601_utc
from app.db.session import Base
class ComputeConfigurationRevision(Base):
"""Immutable snapshot ledger of published compute comparison configurations."""
__tablename__ = "compute_configuration_revisions"
id = Column(Integer, primary_key=True, autoincrement=True, index=True)
publish_id = Column(String(64), unique=True, nullable=False, index=True)
parent_publish_id = Column(String(64), nullable=True, index=True)
action = Column(String(16), nullable=False, default="publish")
content_fingerprint = Column(String(64), nullable=False, index=True)
is_default_content = Column(Boolean, nullable=False, default=False)
config_payload = Column(JSON, nullable=False, default=dict)
diff_summary = Column(JSON, nullable=False, default=list)
source_candidate_ids = Column(JSON, nullable=False, default=list)
publish_note = Column(Text, nullable=False, default="")
published_by_id = Column(Integer, nullable=True)
published_by_name = Column(String(120), nullable=True)
published_by_role = Column(String(40), nullable=True)
published_at = Column(
DateTime(timezone=True), server_default=func.now(), nullable=False, index=True
)
presentation_status = Column(String(16), nullable=False, default="pending", index=True)
presentation_attempts = Column(Integer, nullable=False, default=0)
presentation_error = Column(Text, nullable=False, default="")
presentation_delivered_at = Column(DateTime(timezone=True), nullable=True)
__table_args__ = (
Index("idx_compute_config_revisions_published_at", "published_at"),
Index("idx_compute_config_revisions_pres_status", "presentation_status", "id"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"publish_id": self.publish_id,
"parent_publish_id": self.parent_publish_id,
"action": self.action,
"content_fingerprint": self.content_fingerprint,
"is_default_content": bool(self.is_default_content),
"diff_summary": list(self.diff_summary or []),
"source_candidate_ids": list(self.source_candidate_ids or []),
"publish_note": self.publish_note or "",
"published_by_id": self.published_by_id,
"published_by_name": self.published_by_name,
"published_by_role": self.published_by_role,
"published_at": to_iso8601_utc(self.published_at),
"presentation_status": self.presentation_status,
"presentation_attempts": int(self.presentation_attempts or 0),
"presentation_error": self.presentation_error or "",
"presentation_delivered_at": to_iso8601_utc(self.presentation_delivered_at),
}
@@ -235,8 +235,13 @@ class ComputeEvidenceCandidate(Base):
candidate_type = Column(String(40), nullable=False, default="observation")
proposed_payload = Column(JSON, nullable=False, default=dict)
source_payload = Column(JSON, nullable=False, default=dict)
comparison = Column(JSON, nullable=False, default=dict)
dedupe_fingerprint = Column(String(64), nullable=True, index=True)
confidence = Column(Float, nullable=False, default=0.8)
extractor_note = Column(Text, nullable=False, default="")
review_reason_code = Column(String(40), nullable=True)
review_reason = Column(Text, nullable=False, default="")
published_publish_id = Column(String(64), nullable=True, index=True)
reviewed_by = Column(String(120), nullable=True)
reviewed_at = Column(DateTime(timezone=True), nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now(), nullable=False, index=True)
@@ -248,8 +253,13 @@ class ComputeEvidenceCandidate(Base):
"candidate_type": self.candidate_type,
"proposed_payload": self.proposed_payload or {},
"source_payload": self.source_payload or {},
"comparison": self.comparison or {},
"dedupe_fingerprint": self.dedupe_fingerprint,
"confidence": self.confidence,
"extractor_note": self.extractor_note,
"review_reason_code": self.review_reason_code,
"review_reason": self.review_reason or "",
"published_publish_id": self.published_publish_id,
"reviewed_by": self.reviewed_by,
"reviewed_at": to_iso8601_utc(self.reviewed_at),
"created_at": to_iso8601_utc(self.created_at),
+2
View File
@@ -11,6 +11,7 @@ class ChatMessage(BaseModel):
tool_call_id: str | None = Field(default=None, max_length=200)
name: str | None = Field(default=None, max_length=200)
tool_calls: list[dict[str, Any]] | None = None
thinking_blocks: list[dict[str, Any]] | None = None
class ToolCallRecord(BaseModel):
@@ -77,6 +78,7 @@ class SituationalAnalysisResponse(BaseModel):
text_blocks: list[str] = Field(default_factory=list)
thinking_blocks: list[str] = Field(default_factory=list)
tool_calls: list[ToolCallRecord] = Field(default_factory=list)
citation_urls: list[str] = Field(default_factory=list)
stop_reason: str | None = None
raw_response: dict[str, Any] = Field(default_factory=dict)
@@ -56,6 +56,7 @@ class ComputeObservation(ConfigurationModel):
metric: ComputeMetric
source_id: Identifier
values: dict[str, Value] = Field(min_length=1, max_length=250)
value_sources: dict[str, Identifier] | None = None
period_label: PeriodLabel | None = None
global_total: Value | None = None
@@ -65,11 +66,36 @@ class ComputeObservation(ConfigurationModel):
raise ValueError(
"Use countries from the canonical compute catalog, not regional totals"
)
if self.value_sources is not None:
invalid_keys = [code for code in self.value_sources if code not in self.values]
if invalid_keys:
raise ValueError(
"Per-country value_sources keys must be a subset of observation values"
)
if self.metric in SHARE_METRICS and sum(self.values.values()) > 100.000001:
raise ValueError("Global shares for one year must total at most 100 percent")
return self
def source_for(row: ComputeObservation, code: str) -> str:
"""Resolve the authoritative source_id for one country inside an observation row."""
if row.value_sources and code in row.value_sources:
return row.value_sources[code]
return row.source_id
def row_source_ids(row: ComputeObservation) -> list[str]:
"""Return deduplicated source IDs referenced across all countries in an observation row."""
if not row.values:
return [row.source_id]
return list(dict.fromkeys(source_for(row, code) for code in row.values))
def has_mixed_sources(row: ComputeObservation) -> bool:
"""Return True when countries in one observation row cite more than one distinct source."""
return len(row_source_ids(row)) > 1
class ComputeStructureObservation(ConfigurationModel):
scope: str = Field(min_length=2, max_length=16)
year: Year
@@ -176,6 +202,14 @@ class ComputeConfiguration(ConfigurationModel):
raise ValueError(f"Missing report source: {row.source_id}")
if row.year > source.report_year:
raise ValueError("Observation year must not be after its report year")
for obs in self.observations:
if obs.value_sources:
for code, src_id in obs.value_sources.items():
source = sources.get(src_id)
if source is None:
raise ValueError(f"Missing report source: {src_id}")
if obs.year > source.report_year:
raise ValueError("Observation year must not be after its report year")
hub_id_set = set(hub_ids)
for hub in self.national_hubs:
if hub.source_id not in sources:
@@ -190,7 +224,10 @@ class ComputeConfiguration(ConfigurationModel):
class ComputeConfigurationWrite(ConfigurationModel):
revision: str = Field(min_length=1, max_length=80)
config: ComputeConfiguration
publish_note: str = Field(default="", max_length=1000)
source_candidate_ids: list[int] = Field(default_factory=list, max_length=50)
class ComputeConfigurationReset(ConfigurationModel):
revision: str = Field(min_length=1, max_length=80)
publish_note: str = Field(default="", max_length=1000)
+187 -27
View File
@@ -7,7 +7,7 @@ from datetime import UTC, datetime
import hashlib
import json
import re
from typing import Any, Literal
from typing import Any
from fastapi import HTTPException
from pydantic import BaseModel, ConfigDict, Field
@@ -38,6 +38,10 @@ from app.services.ai.thinking_sanitizer import (
)
from app.services.ai.tool_registry import TimeBasis, query_compute_posture_tool
from app.services.ai_client import AIProviderClient
from app.services.compute_lineage import (
build_revision_change_context,
is_revision_question,
)
logger = get_logger(__name__, service="ai_copilot")
@@ -82,6 +86,7 @@ def _deterministic_compute_copilot_reply(
*,
codes: list[str] | None = None,
mode: str = "global_share",
revision_context: dict[str, Any] | None = None,
) -> CopilotInvestigationReply:
evidence = series.get("evidence") or {}
rpi = series.get("bilateral_rpi") or {}
@@ -95,6 +100,7 @@ def _deterministic_compute_copilot_reply(
time_basis = series.get("time_basis") or "retrospective"
cutoff_at = series.get("cutoff_at")
withheld_sources = series.get("withheld_source_ids") or []
publish_id = series.get("publish_id") or series.get("version")
fallback_eid = next(iter(evidence.keys()), "unconfigured")
q_lower = question.lower()
@@ -102,6 +108,19 @@ def _deterministic_compute_copilot_reply(
if entity_id:
highlights.append(entity_id)
if series.get("snapshot_unavailable"):
notice = str(
series.get("notice")
or "当前所选历史发布时间早于版本库基线时间,历史快照不完整,无法恢复当时台账。"
)
return CopilotInvestigationReply(
answer_markdown=f"### 历史快照不完整\n\n- {notice}",
key_points=[],
highlight_entities=list(dict.fromkeys([*(codes or []), *highlights]))[:8],
suggested_followups=["回到当前已发布的最新版本"],
evidence_ids=["unconfigured"],
)
cutoff_note = (
f"\n\n> **历史回放截点**:当前按 `as_known_then`(截至 `{cutoff_at}`)过滤,已隔离 `{len(withheld_sources)}` 份截点后发布报告。"
if time_basis == "as_known_then" and cutoff_at
@@ -121,6 +140,83 @@ def _deterministic_compute_copilot_reply(
evidence_ids=["unconfigured"],
)
if is_revision_question(question) and isinstance(revision_context, dict):
diff_entries = [
entry
for entry in (revision_context.get("diff_summary") or [])
if isinstance(entry, dict) and entry.get("kind") == "observation_value"
]
rev_pid = str(revision_context.get("publish_id") or publish_id or "")
rev_eids: list[str] = []
for entry in diff_entries:
for k in ("new_source_id", "old_source_id"):
sid = entry.get(k)
if isinstance(sid, str) and sid in evidence and sid not in rev_eids:
rev_eids.append(sid)
for cr in revision_context.get("candidate_reasons") or []:
sid = cr.get("source_id") if isinstance(cr, dict) else None
if isinstance(sid, str) and sid in evidence and sid not in rev_eids:
rev_eids.append(sid)
if not rev_eids:
rev_eids = [fallback_eid]
if diff_entries:
has_hist = any(e.get("change_kind") == "historical_revision" for e in diff_entries)
bullet_lines = [f"- {e.get('summary') or ''}" for e in diff_entries[:8] if e.get("summary")]
reason_lines: list[str] = []
for cr in (revision_context.get("candidate_reasons") or [])[:4]:
if not isinstance(cr, dict):
continue
r_label = cr.get("review_reason_label") or cr.get("review_reason_code") or "人工复核采纳"
r_detail = cr.get("review_reason")
if r_detail:
reason_lines.append(f"- **复核理由({r_label})**:{r_detail}")
else:
reason_lines.append(f"- **复核理由类别**:{r_label}")
note_line = (
f"- **发布说明**:{revision_context['publish_note']}"
if revision_context.get("publish_note")
else ""
)
hist_banner = (
"\n\n> **性质说明**:本次变动属于对历史统计观测的修订,不代表当期算力规模跃升。"
if has_hist
else ""
)
changed_codes = [
str(e.get("code"))
for e in diff_entries
if isinstance(e.get("code"), str)
]
highlights.extend(changed_codes or (codes or ["CN", "US"]))
md_parts = [
f"### 算力台账修订说明(版本 `{rev_pid}`)",
"",
*bullet_lines,
*reason_lines,
*([note_line] if note_line else []),
]
return CopilotInvestigationReply(
answer_markdown=("\n".join(md_parts) + hist_banner + cutoff_note).strip(),
key_points=[
CopilotKeyPoint(
claim=str(e.get("summary") or f"版本 {rev_pid} 发生观测值修订"),
evidence_ids=[
e["new_source_id"]
if isinstance(e.get("new_source_id"), str) and e["new_source_id"] in evidence
else rev_eids[0]
],
)
for e in diff_entries[:4]
],
highlight_entities=list(dict.fromkeys(highlights))[:8],
suggested_followups=[
"切回修订前的系统发布版本对比旧值",
"查看该数值的完整血缘与报告原文出处",
],
evidence_ids=rev_eids,
)
if any(kw in q_lower for kw in ("枢纽", "东数西算", "绿电", "pue", "hub", "west")) and hubs:
hub_ids = [h["id"] for h in hubs]
highlights.extend(["CN", *hub_ids[:8]])
@@ -174,11 +270,34 @@ def _deterministic_compute_copilot_reply(
)
highlights.extend(codes or ["CN", "US"])
eids = [
chip_eids = [
eid
for eid in ("caict-2025", "caict-2024", "caict-2023", "epoch-chip-imports-2026", "innovation-2026")
if eid in evidence
] or [fallback_eid]
for eid in (
chip.get("cn_evidence_id"),
chip.get("us_evidence_id"),
chip.get("evidence_id"),
)
if isinstance(eid, str) and eid in evidence
]
eids = list(
dict.fromkeys(
[
*(chip_eids if mode == "chip_inflow_share" else []),
*(
eid
for eid in (
"caict-2025",
"caict-2024",
"caict-2023",
"epoch-chip-imports-2026",
"innovation-2026",
)
if eid in evidence
),
*chip_eids,
]
)
) or [fallback_eid]
if not tot:
# Multilateral or non-CN/US comparison (e.g. JP / EUROPE / DE)
@@ -204,11 +323,18 @@ def _deterministic_compute_copilot_reply(
evidence_ids=eids[:2],
)
mode_banner = (
f"当前聚焦口径:**智能算力全球份额**(中国 `{intel['cn_value']}%` vs 美国 `{intel['us_value']}%`,RPI `{intel['rpi_percent']}%`)。"
if mode == "intelligent_share" and intel
else f"当前聚焦口径:**{tot.get('year')} 年全球总算力份额**(中国 `{tot.get('cn_value')}%` vs 美国 `{tot.get('us_value')}%`,RPI `{tot.get('rpi_percent')}%`)。"
)
if mode == "chip_inflow_share" and chip:
mode_banner = (
f"当前聚焦口径:**{chip.get('year')} 年高端 AI 算力卡新增流向占比**(中国 `{chip['cn_value']}%` vs 美国 `{chip['us_value']}%`,RPI `{chip['rpi_percent']}%`)。"
)
elif mode == "intelligent_share" and intel:
mode_banner = (
f"当前聚焦口径:**智能算力全球份额**(中国 `{intel['cn_value']}%` vs 美国 `{intel['us_value']}%`,RPI `{intel['rpi_percent']}%`)。"
)
else:
mode_banner = (
f"当前聚焦口径:**{tot.get('year')} 年全球总算力份额**(中国 `{tot.get('cn_value')}%` vs 美国 `{tot.get('us_value')}%`,RPI `{tot.get('rpi_percent')}%`)。"
)
denom_line = (
f"- **分母膨胀数学分解**:我国绝对总算力由 `{attr['country_from']:.0f}` 跃升至 `{attr['country_to']:.0f}` EFlops(`+{attr['country_growth_pct']}%`),全球总算力由 `{attr['global_from']:.0f}` 增至 `{attr['global_to']:.0f}` EFlops(`+{attr['global_growth_pct']}%`),相对份额回落源于全球分母扩张更快。\n"
if attr and attr.get("global_to")
@@ -259,9 +385,12 @@ async def run_contextual_copilot(
question: str,
time_basis: TimeBasis = "retrospective",
cutoff_at: str | None = None,
publish_id: str | None = None,
as_of: str | None = None,
allow_drill: bool = False,
series_override: dict[str, Any] | None = None,
posture_override: dict[str, Any] | None = None,
revision_context: dict[str, Any] | None = None,
ai_client: AIProviderClient | None = None,
cancel_event: asyncio.Event | None = None,
) -> dict[str, Any]:
@@ -388,9 +517,26 @@ async def run_contextual_copilot(
}
series = series_override or await query_compute_posture_tool(
db, codes, mode=mode, time_basis=time_basis, cutoff_at=cutoff_at
db,
codes,
mode=mode,
time_basis=time_basis,
cutoff_at=cutoff_at,
as_of=as_of,
publish_id=publish_id,
)
_raise_if_cancelled(cancel_event)
effective_revision_context = revision_context
if (
effective_revision_context is None
and is_revision_question(question)
and not series.get("snapshot_unavailable")
):
effective_revision_context = await build_revision_change_context(
db,
publish_id=series.get("publish_id") or publish_id,
redact=True,
)
posture = posture_override or await generate_or_get_compute_posture(
db,
countries=codes,
@@ -421,6 +567,26 @@ async def run_contextual_copilot(
}
for eid, ev in evidence_map.items()
}
llm_context: dict[str, Any] = {
"domain": domain,
"selected_codes": codes,
"focus_year": focus_year,
"mode": mode,
"publish_id": series.get("publish_id") or series.get("version"),
"published_at": series.get("published_at"),
"as_of": series.get("as_of") or as_of,
"time_basis": time_basis,
"cutoff_at": cutoff_at,
"entity_id": entity_id,
"bilateral_rpi": series.get("bilateral_rpi"),
"denominator_attribution": series.get("denominator_attribution"),
"structures": series.get("structures"),
"innovation_summary": series.get("innovation_summary"),
"national_hubs": series.get("national_hubs"),
"evidence": compact_evidence,
}
if effective_revision_context:
llm_context["revision_context"] = effective_revision_context
llm_resp = await effective_ai_client.analyze(
SituationalAnalysisRequest(
title="地球空间上下文追问",
@@ -432,21 +598,7 @@ async def run_contextual_copilot(
'"highlight_entities": [str], "suggested_followups": [str], "evidence_ids": [str]}'
),
system_prompt=prompt_def.system_prompt,
context={
"domain": domain,
"selected_codes": codes,
"focus_year": focus_year,
"mode": mode,
"time_basis": time_basis,
"cutoff_at": cutoff_at,
"entity_id": entity_id,
"bilateral_rpi": series.get("bilateral_rpi"),
"denominator_attribution": series.get("denominator_attribution"),
"structures": series.get("structures"),
"innovation_summary": series.get("innovation_summary"),
"national_hubs": series.get("national_hubs"),
"evidence": compact_evidence,
},
context=llm_context,
constraints=[
"Return strict JSON matching CopilotInvestigationReply.",
"Every evidence_id must exist in context.evidence.",
@@ -480,7 +632,12 @@ async def run_contextual_copilot(
if reply_obj is None:
reply_obj = _deterministic_compute_copilot_reply(
question, series, entity_id, codes=codes, mode=mode
question,
series,
entity_id,
codes=codes,
mode=mode,
revision_context=effective_revision_context,
)
return {
@@ -488,6 +645,9 @@ async def run_contextual_copilot(
"subject_key": posture["subject_key"],
"revision": posture["revision"],
"config_version": series.get("version"),
"publish_id": series.get("publish_id") or series.get("version"),
"published_at": series.get("published_at"),
"as_of": series.get("as_of") or as_of,
"generation_mode": generation_mode,
"usage": llm_usage,
"reply": reply_obj.model_dump(mode="json"),
+143
View File
@@ -0,0 +1,143 @@
"""Shared URL-normalized evidence ledger for workflow DAG nodes and guardrails."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Sequence
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
_TRACKING_QUERY_PARAMS: frozenset[str] = frozenset({"fbclid", "gclid", "mc_cid", "mc_eid"})
_IGNORED_DOC_EXTENSIONS: tuple[str, ...] = (".csv", ".tsv", ".xlsx", ".xls", ".parquet", ".json")
def normalize_evidence_url(url: Any) -> str:
"""Canonicalize an HTTP(S) URL for deduplication and anti-hallucination matching."""
raw = str(url or "").strip()
if not raw:
return ""
try:
parts = urlsplit(raw)
except ValueError:
return raw.rstrip("/").lower()
scheme = (parts.scheme or "https").lower()
if scheme == "http":
scheme = "https"
netloc = parts.netloc.lower()
path = parts.path.rstrip("/")
kept_query = sorted(
(k, v)
for k, v in parse_qsl(parts.query, keep_blank_values=True)
if not k.lower().startswith("utm_") and k.lower() not in _TRACKING_QUERY_PARAMS
)
return urlunsplit((scheme, netloc, path, urlencode(kept_query), ""))
def is_tabular_dataset_url(url: Any) -> bool:
"""Return True for raw bulk-data files (e.g. Epoch csv exports) unsuitable for webpage fetch."""
raw = str(url or "").strip()
if not raw:
return False
try:
path = urlsplit(raw).path.lower()
except ValueError:
path = raw.lower()
return path.endswith(_IGNORED_DOC_EXTENSIONS)
@dataclass
class EvidenceLedger:
"""Assigns sequential ``E1..En`` IDs to tool-observed URLs and resolves citations safely."""
items: list[dict[str, Any]] = field(default_factory=list)
by_id: dict[str, dict[str, Any]] = field(default_factory=dict)
by_norm_url: dict[str, dict[str, Any]] = field(default_factory=dict)
evidence_calls: int = 0
def record_call(self) -> None:
self.evidence_calls += 1
def add(
self,
*,
url: str,
title: str = "",
snippet: str = "",
tool: str = "",
query: str = "",
) -> str | None:
cleaned_url = str(url or "").strip()
if not cleaned_url:
return None
norm = normalize_evidence_url(cleaned_url)
if not norm:
return None
existing = self.by_norm_url.get(norm)
cleaned_snippet = str(snippet or "").strip()
cleaned_title = str(title or "").strip()
if existing is not None:
if len(cleaned_snippet) > len(str(existing.get("snippet") or "")):
existing["snippet"] = cleaned_snippet[:1500]
if cleaned_title and not existing.get("title"):
existing["title"] = cleaned_title[:200]
return str(existing["id"])
eid = f"E{len(self.items) + 1}"
entry = {
"id": eid,
"url": cleaned_url,
"norm_url": norm,
"title": cleaned_title[:200],
"snippet": cleaned_snippet[:1500],
"tool": tool,
"query": query,
}
self.items.append(entry)
self.by_id[eid] = entry
self.by_norm_url[norm] = entry
return eid
def resolve_refs(self, refs: Sequence[Any]) -> tuple[list[str], list[str]]:
"""Map ``['E1', 'https://...']`` references back to verified IDs and original URLs."""
verified_ids: list[str] = []
verified_urls: list[str] = []
seen_urls: set[str] = set()
for raw in refs:
token = str(raw or "").strip()
if not token:
continue
entry = self.by_id.get(token.upper())
if entry is None:
entry = self.by_norm_url.get(normalize_evidence_url(token))
if entry is None:
continue
eid = str(entry["id"])
url = str(entry["url"])
norm = str(entry["norm_url"])
if eid not in verified_ids:
verified_ids.append(eid)
if norm not in seen_urls:
seen_urls.add(norm)
verified_urls.append(url)
return verified_ids, verified_urls
def to_prompt_items(self, limit: int = 14) -> list[dict[str, str]]:
return [
{
"id": str(item["id"]),
"title": str(item.get("title") or ""),
"url": str(item.get("url") or ""),
"tool": str(item.get("tool") or ""),
"excerpt": str(item.get("snippet") or "")[:900],
}
for item in self.items[:limit]
]
def to_evidence_dict(self) -> dict[str, dict[str, str]]:
return {
str(item["id"]): {
"url": str(item.get("url") or ""),
"title": str(item.get("title") or ""),
"source": str(item.get("tool") or "web"),
}
for item in self.items
}
File diff suppressed because it is too large. Load diff
+81 -5
View File
@@ -116,7 +116,18 @@ def build_deterministic_posture_brief(series_payload: dict[str, Any]) -> Strateg
tot = rpi["latest_total"]
intel = rpi.get("latest_intelligent")
chip = rpi.get("latest_chip_inflow")
tot_ev = tot["evidence_id"]
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 = (
@@ -174,7 +185,8 @@ def build_deterministic_posture_brief(series_payload: dict[str, Any]) -> Strateg
evidence_ids=[eid for eid in (attribution["evidence_ids"] if attribution else [tot_ev]) if eid in evidence] or [tot_ev],
)
]
if intel and intel.get("evidence_id") in evidence:
intel_eids = _pair_eids(intel)
if intel and intel_eids:
causes.append(
PostureBullet(
label="智能算力竞争成为核心分化面",
@@ -184,10 +196,11 @@ def build_deterministic_posture_brief(series_payload: dict[str, Any]) -> Strateg
f"高端训练集群供给差异直接拉开了总算力剪刀差。"
),
detail_en=f"U.S. holds {intel['us_value']}% of global intelligent compute vs China's {intel['cn_value']}%.",
evidence_ids=[intel["evidence_id"]],
evidence_ids=intel_eids,
)
)
if chip and chip.get("evidence_id") in evidence:
chip_eids = _pair_eids(chip)
if chip and chip_eids:
causes.append(
PostureBullet(
label="先进芯片管制重塑新增算力流向",
@@ -196,7 +209,7 @@ def build_deterministic_posture_brief(series_payload: dict[str, Any]) -> Strateg
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["evidence_id"]],
evidence_ids=chip_eids,
)
)
@@ -348,12 +361,56 @@ async def generate_or_get_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,
@@ -410,6 +467,10 @@ async def generate_or_get_compute_posture(
"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]
@@ -424,6 +485,9 @@ async def generate_or_get_compute_posture(
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),
@@ -510,6 +574,10 @@ async def generate_or_get_compute_posture(
"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]
@@ -557,6 +625,10 @@ async def generate_or_get_compute_posture(
"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},
}
@@ -580,6 +652,10 @@ async def generate_or_get_compute_posture(
"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},
}
@@ -15,7 +15,6 @@ from app.models.situational_assessment import StagePresentation
from app.services.ai.domain_catalog import SPATIAL_POSTURE_DOMAINS, SpatialDomain, WorkbenchDomain
from app.services.ai.incident_agent import (
DRILL_INCIDENT_KEY,
HISTORICAL_INCIDENT_SAMPLE,
investigate_infrastructure_incident,
)
from app.services.ai.spatial_domain_agent import investigate_spatial_domain
@@ -84,6 +83,7 @@ class StagePresentationContract(BaseModel):
domain: WorkbenchDomain
time_basis: TimeBasis
cutoff_date: str | None = None
publish_id: str | None = None
is_drill: bool = False
title: str
title_en: str
@@ -515,13 +515,185 @@ def _wrap_ephemeral_contract(contract: StagePresentationContract, cursor: int, r
}
_COUNTRY_CAMERA_ANCHORS: dict[str, tuple[float, float, float]] = {
"CN": (35.0, 105.0, 1.18),
"US": (39.0, -98.0, 1.12),
"JP": (36.2, 138.2, 1.25),
"DE": (51.1, 10.4, 1.25),
"GB": (54.0, -2.0, 1.25),
"FR": (46.6, 2.2, 1.25),
"KR": (36.5, 127.8, 1.28),
"IN": (21.5, 79.0, 1.18),
}
_REVISION_METRIC_LABELS_EN: dict[str, str] = {
"global_share": "Global Compute Share",
"intelligent_share": "Global AI Compute Share",
"absolute": "Total Compute Capacity",
"frontier_cluster_share": "Frontier AI Cluster Share",
"chip_inflow_share": "AI Chip Inflow Share",
}
def compile_compute_revision_presentation(
*,
publish_id: str,
action: str,
series: dict[str, Any],
value_diffs: list[dict[str, Any]],
time_basis: TimeBasis = "retrospective",
) -> StagePresentationContract:
"""Compile a revision-driven stage presentation notice from structured observation diffs."""
from app.services.compute_revision_diff import COUNTRY_ZH_LABELS, METRIC_ZH_LABELS
raw_evidence = series.get("evidence") or {}
evidence = dict(raw_evidence)
historical_diffs = [d for d in value_diffs if d.get("change_kind") == "historical_revision"]
has_historical = bool(historical_diffs)
primary = historical_diffs[0] if has_historical else value_diffs[0]
metric = str(primary.get("metric") or "global_share")
year = int(primary.get("year") or 2024)
metric_zh = METRIC_ZH_LABELS.get(metric, metric)
metric_en = _REVISION_METRIC_LABELS_EN.get(metric, metric)
spotlight_codes = list(
dict.fromkeys(str(d.get("code")) for d in value_diffs if d.get("code"))
) or ["CN", "US"]
first_code = spotlight_codes[0]
cam_lat, cam_lon, cam_zoom = _COUNTRY_CAMERA_ANCHORS.get(first_code, (34.5, 110.0, 1.12))
change_lines_zh: list[str] = []
change_lines_en: list[str] = []
referenced_eids: list[str] = []
for item in value_diffs[:4]:
code = str(item.get("code") or "")
c_zh = COUNTRY_ZH_LABELS.get(code, code)
item_metric = str(item.get("metric") or metric)
item_unit = " EFlops" if item_metric == "absolute" else "%"
item_delta_unit = " EFlops" if item_metric == "absolute" else "pp"
old_val = item.get("old_value")
new_val = item.get("new_value")
delta = float(item.get("delta") or 0.0)
if old_val is not None and new_val is not None:
change_lines_zh.append(
f"{c_zh} {old_val}{item_unit} → {new_val}{item_unit}({delta:+.2g}{item_delta_unit})"
)
change_lines_en.append(
f"{code} {old_val}{item_unit} -> {new_val}{item_unit} ({delta:+.2g}{item_delta_unit})"
)
elif new_val is not None:
change_lines_zh.append(f"{c_zh} 新增 {new_val}{item_unit}")
change_lines_en.append(f"{code} added {new_val}{item_unit}")
elif old_val is not None:
change_lines_zh.append(f"{c_zh} 移除(原 {old_val}{item_unit})")
change_lines_en.append(f"{code} removed (was {old_val}{item_unit})")
for src_key in ("new_source_id", "old_source_id"):
eid = item.get(src_key)
if eid and eid in evidence and eid not in referenced_eids:
referenced_eids.append(str(eid))
if not referenced_eids:
referenced_eids = list(evidence.keys())[:2]
changes_zh = ";".join(change_lines_zh)
changes_en = "; ".join(change_lines_en)
if has_historical:
title_zh = f"{year} 年{metric_zh}数据获修订"
title_en = f"{year} {metric_en} Data Revised"
caption_zh = f"{changes_zh}。这是对历史数据的修订,不代表当期算力跃升。"
caption_en = f"{changes_en}. This is a historical data revision, not a current-period jump."
elif action == "reset":
title_zh = f"{year} 年{metric_zh}已恢复内置版本"
title_en = f"{year} {metric_en} Restored to Bundled Baseline"
caption_zh = f"{changes_zh}。台账已恢复至内置权威报告基线。"
caption_en = f"{changes_en}. Ledger restored to bundled authoritative report baseline."
else:
title_zh = f"{year} 年{metric_zh}台账已更新"
title_en = f"{year} {metric_en} Ledger Updated"
caption_zh = f"{changes_zh}。"
caption_en = f"{changes_en}."
steps = [
StageStepSpec(
step_id="rev-act-1-notice",
stage="overview",
title=title_zh,
title_en=title_en,
caption=caption_zh,
caption_en=caption_en,
dwell_ms=6400,
camera=StageCameraPose(lat=cam_lat, lon=cam_lon, zoom=cam_zoom),
compute_mode=metric,
focus_year=year,
spotlight_Statistic_codes=spotlight_codes,
evidence_ids=referenced_eids,
),
StageStepSpec(
step_id="rev-act-2-lineage",
stage="attribution",
title=f"版本 {publish_id[:8]} · 证据溯源与口径校验",
title_en=f"Revision {publish_id[:8]} · Evidence & Denominator Check",
caption=(
f"当前已生效版本 {publish_id[:8]},共更新 {len(value_diffs)} 项观测值(口径:{metric_zh},{year} 年)。"
"点击卡片数值旁溯源按钮可查看报告原文页码、复核记录与历史对比。"
),
caption_en=(
f"Active revision {publish_id[:8]} updated {len(value_diffs)} observation value(s) "
f"({metric_en}, {year}). Inspect lineage from the compute card for full provenance."
),
dwell_ms=5600,
camera=StageCameraPose(lat=cam_lat, lon=cam_lon, zoom=max(0.95, cam_zoom - 0.1)),
compute_mode=metric,
focus_year=year,
spotlight_Statistic_codes=spotlight_codes,
evidence_ids=referenced_eids,
),
]
return StagePresentationContract(
presentation_key="compute-revision-notice",
domain="compute",
time_basis=time_basis,
publish_id=publish_id,
is_drill=False,
title=title_zh,
title_en=title_en,
summary=caption_zh,
summary_en=caption_en,
steps=steps,
evidence=evidence,
)
async def publish_stage_contract(
db: AsyncSession,
contract: StagePresentationContract,
*,
explicit_revision: int | None = None,
) -> StagePresentation | None:
"""Idempotently persist a `StagePresentation` ONLY on explicit write-side snapshot/config pipelines."""
if not hasattr(db, "execute") or not hasattr(db, "add") or not hasattr(db, "flush"):
return None
if contract.publish_id:
existing_rows = (
(
await db.execute(
select(StagePresentation)
.where(
StagePresentation.presentation_key == contract.presentation_key,
StagePresentation.time_basis == contract.time_basis,
)
.order_by(desc(StagePresentation.revision), desc(StagePresentation.id))
.limit(50)
)
)
.scalars()
.all()
)
for row in existing_rows:
if isinstance(row.contract, dict) and row.contract.get("publish_id") == contract.publish_id:
return row
new_fp = _contract_fingerprint(contract)
existing = (
await db.execute(
@@ -535,7 +707,9 @@ async def publish_stage_contract(
)
).scalar_one_or_none()
if isinstance(existing, StagePresentation) and existing.contract:
if explicit_revision is not None:
next_rev = int(explicit_revision)
elif isinstance(existing, StagePresentation) and existing.contract:
old_fp = hashlib.sha256(
json.dumps(existing.contract, sort_keys=True, ensure_ascii=False).encode("utf-8")
).hexdigest()
+218 -71
View File
@@ -10,6 +10,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.models.bgp_incident import BGPIncident
from app.models.compute_configuration_revision import ComputeConfigurationRevision
from app.models.situational_assessment import (
SituationalAssessment,
StagePresentation,
@@ -19,7 +20,7 @@ from app.models.situational_assessment import (
from app.services.ai.incident_agent import DRILL_INCIDENT_KEY, investigate_infrastructure_incident
from app.services.ai.posture_agent import generate_or_get_compute_posture
from app.services.ai.presentation_compiler import (
compile_compute_posture_presentation,
compile_compute_revision_presentation,
compile_incident_five_act_presentation,
publish_stage_contract,
)
@@ -29,7 +30,6 @@ from app.services.ai.tool_registry import query_compute_posture_tool
logger = get_logger(__name__, service="ai_proactive")
_BGP_STATE_KEY = "situational_bgp_snapshot_state"
_COMPUTE_STATE_KEY = "situational_compute_snapshot_state"
async def _load_state_setting(db: AsyncSession, key: str) -> tuple[SituationalAssessment | None, dict[str, Any] | None]:
@@ -280,80 +280,227 @@ async def process_bgp_snapshot_proactive_delta(
}
async def process_compute_revision_presentation(
db: AsyncSession,
revision_id: int,
*,
countries: list[str] | None = None,
) -> dict[str, Any]:
"""Emit an idempotent StagePresentation driven directly by one `ComputeConfigurationRevision`."""
row = (
await db.execute(
select(ComputeConfigurationRevision).where(
ComputeConfigurationRevision.id == revision_id
)
)
).scalar_one_or_none()
if not isinstance(row, ComputeConfigurationRevision):
return {
"domain": "compute",
"status": "not_found",
"revision_id": revision_id,
"emitted_presentations": [],
"triggered_watches": [],
}
if row.presentation_status in {"delivered", "skipped"}:
return {
"domain": "compute",
"status": row.presentation_status,
"publish_id": row.publish_id,
"revision_id": row.id,
"idempotent": True,
"emitted_presentations": [],
"triggered_watches": [],
}
value_diffs = [
item
for item in (row.diff_summary or [])
if item.get("kind") == "observation_value"
and item.get("delta") is not None
and float(item["delta"]) != 0.0
]
if not value_diffs:
row.presentation_status = "skipped"
row.presentation_error = ""
await db.flush()
return {
"domain": "compute",
"status": "skipped",
"publish_id": row.publish_id,
"revision_id": row.id,
"emitted_presentations": [],
"triggered_watches": [],
}
historical = [d for d in value_diffs if d.get("change_kind") == "historical_revision"]
primary = historical[0] if historical else value_diffs[0]
primary_mode = str(primary.get("metric") or "global_share")
changed_codes = [str(d["code"]) for d in value_diffs if d.get("code")]
codes = list(dict.fromkeys([*(countries or ["CN", "US"]), *changed_codes]))
series = await query_compute_posture_tool(
db, codes, mode=primary_mode, publish_id=row.publish_id
)
posture = await generate_or_get_compute_posture(
db,
countries=codes,
mode=primary_mode,
series_payload=series,
persist=True,
)
existing_stage_rows = (
(
await db.execute(
select(StagePresentation)
.where(
StagePresentation.presentation_key == "compute-revision-notice",
StagePresentation.time_basis == "retrospective",
)
.order_by(desc(StagePresentation.id))
.limit(50)
)
)
.scalars()
.all()
)
existing_for_publish = next(
(
st
for st in existing_stage_rows
if isinstance(st.contract, dict) and st.contract.get("publish_id") == row.publish_id
),
None,
)
if existing_for_publish is not None:
published = existing_for_publish
else:
contract = compile_compute_revision_presentation(
publish_id=row.publish_id,
action=row.action,
series=series,
value_diffs=value_diffs,
time_basis="retrospective",
)
published = await publish_stage_contract(db, contract, explicit_revision=int(row.id))
row.presentation_status = "delivered"
row.presentation_attempts = int(row.presentation_attempts or 0) + 1
row.presentation_error = ""
row.presentation_delivered_at = datetime.now(UTC)
await db.flush()
triggered_watches = await _evaluate_topic_watches(
db,
domain="compute",
target_keys=[posture["subject_key"]],
revision=int(row.id),
)
return {
"domain": "compute",
"status": "delivered",
"publish_id": row.publish_id,
"revision_id": row.id,
"emitted_presentations": [published.to_dict()] if published is not None else [],
"triggered_watches": triggered_watches,
}
async def retry_pending_compute_presentations(
db: AsyncSession,
*,
max_attempts: int = 3,
) -> dict[str, Any]:
"""Retry pending or failed compute revision presentations in ascending revision order."""
if not hasattr(db, "execute"):
return {"domain": "compute", "processed": 0, "delivered": 0, "skipped": 0, "failed": 0, "results": []}
rows = (
(
await db.execute(
select(ComputeConfigurationRevision)
.where(
ComputeConfigurationRevision.presentation_status.in_(["pending", "failed"]),
ComputeConfigurationRevision.presentation_attempts < max_attempts,
)
.order_by(ComputeConfigurationRevision.id.asc())
.limit(20)
)
)
.scalars()
.all()
)
delivered = 0
skipped = 0
failed = 0
results: list[dict[str, Any]] = []
for row in rows:
try:
res = await process_compute_revision_presentation(db, row.id)
results.append(res)
if res.get("status") == "delivered":
delivered += 1
elif res.get("status") == "skipped":
skipped += 1
except Exception as exc:
failed += 1
row.presentation_status = "failed"
row.presentation_attempts = int(row.presentation_attempts or 0) + 1
row.presentation_error = str(exc)[:1000]
await db.flush()
logger.warning_event(
"Compute revision presentation retry failed",
event="compute.revision.presentation_failed",
context={
"revision_id": row.id,
"publish_id": row.publish_id,
"attempts": row.presentation_attempts,
"error": str(exc),
},
)
results.append(
{
"domain": "compute",
"status": "failed",
"publish_id": row.publish_id,
"revision_id": row.id,
"error": str(exc),
}
)
return {
"domain": "compute",
"processed": len(rows),
"delivered": delivered,
"skipped": skipped,
"failed": failed,
"results": results,
}
async def process_compute_config_proactive_delta(
db: AsyncSession,
*,
countries: list[str] | None = None,
publish_id: str | None = None,
) -> dict[str, Any]:
"""Evaluate a newly published compute configuration and emit idempotent stage & watch updates."""
codes = countries or ["CN", "US"]
setting_row, prev_state = await _load_state_setting(db, _COMPUTE_STATE_KEY)
prev_snapshot = prev_state.get("snapshot") if prev_state else None
seen_fps: set[str] = set(prev_state.get("seen_fingerprints") or []) if prev_state else set()
series = await query_compute_posture_tool(db, codes, mode="global_share")
rpi = series.get("bilateral_rpi") or {}
tot = rpi.get("latest_total") or {}
intel = rpi.get("latest_intelligent") or {}
curr_snapshot: dict[str, Any] = {
"status": "success",
"completed_at": datetime.now(UTC).isoformat(),
"record_count": len(series.get("evidence") or {}) or 1,
"active_keys": [f"config:{series.get('version')}"],
"metrics": {
"cn_total_share": float(tot.get("cn_value") or 0.0),
"us_total_share": float(tot.get("us_value") or 0.0),
"cn_intel_share": float(intel.get("cn_value") or 0.0),
},
}
curr_snapshot["fingerprint"] = snapshot_fingerprint(curr_snapshot)
delta = classify_snapshot_delta(
prev_snapshot,
curr_snapshot,
seen_fingerprints=seen_fps,
)
emitted: list[dict[str, Any]] = []
triggered_watches: list[dict[str, Any]] = []
if delta["emit_event"]:
posture = await generate_or_get_compute_posture(
db,
countries=codes,
mode="global_share",
series_payload=series,
persist=True,
)
for tb in ("live", "retrospective"):
contract = compile_compute_posture_presentation(series, time_basis=tb)
published = await publish_stage_contract(db, contract)
if published is not None and tb == "retrospective":
emitted.append(published.to_dict())
triggered_watches = await _evaluate_topic_watches(
db,
domain="compute",
target_keys=[posture["subject_key"]],
revision=int(posture.get("revision") or 1),
)
await _save_state_setting(
db,
setting_row,
_COMPUTE_STATE_KEY,
{
"snapshot": curr_snapshot,
"seen_fingerprints": sorted(seen_fps)[-32:],
"last_verdict": delta["verdict"],
},
)
return {
"domain": "compute",
"delta": delta,
"emitted_presentations": emitted,
"triggered_watches": triggered_watches,
}
"""Compatibility wrapper delegating to `process_compute_revision_presentation` for the target/latest revision."""
stmt = select(ComputeConfigurationRevision)
if publish_id:
stmt = stmt.where(ComputeConfigurationRevision.publish_id == publish_id)
else:
stmt = stmt.order_by(desc(ComputeConfigurationRevision.id))
row = (await db.execute(stmt.limit(1))).scalar_one_or_none()
if not isinstance(row, ComputeConfigurationRevision):
return {
"domain": "compute",
"status": "skipped",
"emitted_presentations": [],
"triggered_watches": [],
}
return await process_compute_revision_presentation(db, row.id, countries=countries)
async def audit_situational_hygiene(db: AsyncSession) -> dict[str, Any]:
+150
View File
@@ -0,0 +1,150 @@
"""Shared `<planet_scene>` prompt guidance and streaming extraction for Earth Influence Zones."""
from __future__ import annotations
import json
import re
from typing import Any
from app.core.logging import get_logger
from app.services.ai.workflow_runtime import validate_influence_zones
logger = get_logger(__name__, service="ai_scene")
PLANET_SCENE_TAG_OPEN = "<planet_scene>"
PLANET_SCENE_RE = re.compile(r"<planet_scene>\s*(.*?)\s*</planet_scene>", re.DOTALL | re.IGNORECASE)
PLANET_SCENE_OPEN_RE = re.compile(r"<\s*planet_scene\b", re.IGNORECASE)
_CODE_FENCE_OPEN_RE = re.compile(r"^\s*```[a-zA-Z0-9_-]*\s*\n?")
_CODE_FENCE_CLOSE_RE = re.compile(r"\n?\s*```\s*$")
_TRAILING_COMMA_RE = re.compile(r",\s*([}\]])")
INFLUENCE_ZONE_GUIDANCE = (
"【地球影响范围联动指令】正文仍用自然 Markdown 输出(绝不在正文解释本标签);"
"只要分析涉及明确地理国家、地区、消费/市场辐射域、基础设施影响区、海域/海峡走廊、峰会/组织或用户询问“影响范围/影响地区/覆盖区域”,"
"就必须在回答**最末尾另起一行**附带一个纯 JSON(禁用 markdown 代码围栏)的系统隐藏标签:\n"
"<planet_scene>{...}</planet_scene>\n"
"分层输出规范(严格遵循):\n"
"- 第一层(必需,直接当事国/核心对象):shape.mode=\"countries\",color=\"#ef4444\",opacity=0.54,edge.style=\"sharp\";必须填全所有直接核心国家且严格使用标准 ISO-3 代码(如朝鲜必须写 \"PRK\",禁用 \"DPRK\";中国 \"CHN\"、韩国 \"KOR\"、日本 \"JPN\"、俄罗斯 \"RUS\"、英国 \"GBR\")。\n"
"- 第二层(若事件存在跨国/区域外溢则必填;纯单一国内消费/内部新闻则不填第二、三层):次级邻近/区域辐射,shape.mode=\"countries\" 或已支持的 \"region_preset\",color=\"#f59e0b\",opacity=0.32,edge.style=\"soft\"。\n"
"- 第三层(仅当明确涉及海峡、海域航道或边境辐射带时可选):shape.mode=\"circle\"(center:[lat,lon], radius_km),color=\"#38bdf8\",opacity=0.28,edge.style=\"soft\"。\n"
"完整单国示例:\n"
"<planet_scene>{\"influence_zones\":[{\"id\":\"chn-core\",\"label\":\"直接影响:中国\",\"color\":\"#ef4444\",\"opacity\":0.54,\"edge\":{\"style\":\"sharp\"},\"animation\":{\"type\":\"sweep\",\"direction\":\"west_to_east\"},\"shape\":{\"mode\":\"countries\",\"countries\":[\"CHN\"]}}],\"camera_hint\":{\"lat\":35.0,\"lon\":104.0}}</planet_scene>\n"
"双国核心+区域外溢+海域辐射示例:\n"
"<planet_scene>{\"influence_zones\":[{\"id\":\"core\",\"label\":\"核心国家\",\"color\":\"#ef4444\",\"opacity\":0.54,\"edge\":{\"style\":\"sharp\"},\"animation\":{\"type\":\"sweep\",\"direction\":\"west_to_east\"},\"shape\":{\"mode\":\"countries\",\"countries\":[\"CHN\",\"PRK\"]}},{\"id\":\"spill\",\"label\":\"东北亚周边外溢\",\"color\":\"#f59e0b\",\"opacity\":0.32,\"edge\":{\"style\":\"soft\"},\"animation\":{\"type\":\"fade\"},\"shape\":{\"mode\":\"countries\",\"countries\":[\"KOR\",\"JPN\",\"RUS\"]}},{\"id\":\"sea\",\"label\":\"黄海—朝鲜海峡航道辐射\",\"color\":\"#38bdf8\",\"opacity\":0.28,\"edge\":{\"style\":\"soft\"},\"animation\":{\"type\":\"radial\"},\"shape\":{\"mode\":\"circle\",\"center\":[36.5,124.5],\"radius_km\":850}}],\"camera_hint\":{\"lat\":38.0,\"lon\":122.0}}</planet_scene>\n"
"可选 region_preset 枚举(仅限此列表,勿自造名称):"
"APEC, ASIA_PACIFIC, NORTHEAST_ASIA, EAST_ASIA, KOREAN_PENINSULA, SOUTHEAST_ASIA, SOUTH_ASIA, CENTRAL_ASIA, ASEAN, INDO_PACIFIC, "
"EU, EUROPE, EASTERN_EUROPE, NORTHERN_EUROPE, WESTERN_EUROPE, G7, BRICS, NATO, MIDDLE_EAST, MENA, AMERICAS, NORTH_AMERICA, SOUTH_AMERICA, AFRICA;"
"animation.type 选 \"sweep\"、\"radial\" 或 \"fade\"。"
)
def sanitize_camera_hint(raw: Any) -> dict[str, float] | None:
if not isinstance(raw, dict):
return None
cleaned: dict[str, float] = {}
for key in ("lat", "lon", "altitude", "zoom"):
val = raw.get(key)
if isinstance(val, (int, float)) and not isinstance(val, bool):
cleaned[key] = float(val)
return cleaned if ("lat" in cleaned and "lon" in cleaned) else None
def _parse_scene_json_candidate(raw_json: str) -> dict[str, Any] | None:
"""Parse JSON inside `<planet_scene>` even if wrapped in code fences or containing trailing commas."""
text = str(raw_json or "").strip()
if not text:
return None
text = _CODE_FENCE_OPEN_RE.sub("", text)
text = _CODE_FENCE_CLOSE_RE.sub("", text).strip()
candidates = [text]
first_brace = text.find("{")
last_brace = text.rfind("}")
if first_brace != -1 and last_brace > first_brace:
sliced = text[first_brace : last_brace + 1]
if sliced != text:
candidates.append(sliced)
for cand in candidates:
for attempt in (cand, _TRAILING_COMMA_RE.sub(r"\1", cand)):
try:
parsed = json.loads(attempt)
except Exception:
continue
if isinstance(parsed, dict):
return parsed
return None
def extract_planet_scene_from_text(text: str) -> tuple[str, dict[str, Any] | None]:
"""Strip `<planet_scene>...</planet_scene>` blocks and return validated scene spec fields."""
if not text:
return "", None
parsed_scene: dict[str, Any] | None = None
matches = PLANET_SCENE_RE.findall(text)
for raw_json in matches:
payload = _parse_scene_json_candidate(raw_json)
if payload is None:
continue
zones = [z.model_dump(mode="json") for z in validate_influence_zones(payload.get("influence_zones"))]
camera_hint = sanitize_camera_hint(payload.get("camera_hint"))
if zones or camera_hint:
parsed_scene = {}
if zones:
parsed_scene["influence_zones"] = zones
if camera_hint:
parsed_scene["camera_hint"] = camera_hint
if matches and parsed_scene is not None:
extracted_zones = parsed_scene.get("influence_zones") or []
logger.info_event(
"Extracted planet scene directives",
event="ai_scene.directive.extracted",
context={
"zones_count": len(extracted_zones),
"zone_ids": [z.get("id") for z in extracted_zones if isinstance(z, dict)],
"has_camera_hint": "camera_hint" in parsed_scene,
},
)
elif matches:
logger.warning_event(
"Planet scene directive ignored after parse/validation failure",
event="ai_scene.directive.dropped",
context={"snippet": str(matches[-1])[:300]},
)
cleaned = PLANET_SCENE_RE.sub("", text)
open_match = PLANET_SCENE_OPEN_RE.search(cleaned)
if open_match:
cleaned = cleaned[: open_match.start()]
return cleaned.rstrip(), parsed_scene
def consume_text_holding_scene_tag(buffer: str, *, flush_all: bool = False) -> tuple[str, str]:
"""Yield visible text before `<planet_scene` while holding back partial tag prefixes."""
stripped_blocks = PLANET_SCENE_RE.sub("", buffer)
open_match = PLANET_SCENE_OPEN_RE.search(stripped_blocks)
if open_match:
return stripped_blocks[: open_match.start()], stripped_blocks[open_match.start() :]
if flush_all:
return stripped_blocks, ""
last_lt = stripped_blocks.rfind("<")
if last_lt != -1:
tail = stripped_blocks[last_lt:]
if len(tail) < len(PLANET_SCENE_TAG_OPEN) and PLANET_SCENE_TAG_OPEN.startswith(tail.lower()):
return stripped_blocks[:last_lt], tail
return stripped_blocks, ""
def merge_scene_specs(
base_scene: dict[str, Any] | None,
parsed_scene: dict[str, Any] | None,
*,
domain: str | None = None,
) -> dict[str, Any] | None:
if not parsed_scene and not isinstance(base_scene, dict):
return None
merged: dict[str, Any] = dict(base_scene) if isinstance(base_scene, dict) else {}
if parsed_scene:
merged.update(parsed_scene)
if domain and not merged.get("domain"):
merged["domain"] = domain
return merged
+56 -8
View File
@@ -174,7 +174,31 @@ def classify_snapshot_delta(
_SHARE_PATTERN = re.compile(
r"(?P<country>美国|中国|日本)\s*(?:全球)?(?P<metric>智能算力|总算力|算力)份额[^\d]{0,10}(?P<value>\d{1,2}(?:\.\d+)?)\s*%"
)
_COUNTRY_MAP = {"美国": "US", "中国": "CN", "日本": "JP"}
_CHIP_INFLOW_ZH_PATTERN = re.compile(
r"(?P<country>美国|中国|日本)\s*(?:高端)?(?:AI)?(?:算力)?芯片(?:新增)?流向(?:算力)?份额[^\d]{0,12}(?P<value>\d{1,2}(?:\.\d+)?)\s*%"
)
_CHIP_INFLOW_CONTEXT_RE = re.compile(
r"\b(?:h100e?|h20|ai\s+chip|chip\s+import|chip\s+inflow|world\s+arrivals|cumulative\s+world\s+arrivals)\b",
re.IGNORECASE,
)
_CHIP_INFLOW_EN_TO_PATTERN = re.compile(
r"\b(?P<country>United States|U\.S\.|US|China|Japan)(?:['’]s|['’])?\s+share\b[^,;]{0,90}?\bto\s+(?P<value>\d{1,2}(?:\.\d+)?)\s*%",
re.IGNORECASE,
)
_CHIP_INFLOW_EN_RECEIVED_PATTERN = re.compile(
r"\b(?P<country>United States|U\.S\.|US|China|Japan)\s+(?:received|accounted for|captured)\s+(?:about\s+|approximately\s+|roughly\s+)?(?P<value>\d{1,2}(?:\.\d+)?)\s*%\s+of\s+(?:that\s+|global\s+|world\s+)?(?:compute|arrivals|inflow)",
re.IGNORECASE,
)
_COUNTRY_MAP = {
"美国": "US",
"中国": "CN",
"日本": "JP",
"united states": "US",
"u.s.": "US",
"us": "US",
"china": "CN",
"japan": "JP",
}
def extract_compute_candidates_deterministic(
@@ -182,10 +206,12 @@ def extract_compute_candidates_deterministic(
*,
year: int,
source_meta: dict[str, Any],
period_label: str | None = None,
) -> list[dict[str, Any]]:
"""Deterministic extractor fallback producing reviewable `ComputeEvidenceCandidate` dicts."""
text = excerpt or ""
by_metric: dict[str, dict[str, float]] = {}
for match in _SHARE_PATTERN.finditer(excerpt or ""):
for match in _SHARE_PATTERN.finditer(text):
code = _COUNTRY_MAP.get(match.group("country"))
if not code:
continue
@@ -194,19 +220,41 @@ def extract_compute_candidates_deterministic(
if 0 <= value <= 100:
by_metric.setdefault(metric_key, {})[code] = value
for match in _CHIP_INFLOW_ZH_PATTERN.finditer(text):
code = _COUNTRY_MAP.get(match.group("country"))
if not code:
continue
value = float(match.group("value"))
if 0 <= value <= 100:
by_metric.setdefault("chip_inflow_share", {})[code] = value
if _CHIP_INFLOW_CONTEXT_RE.search(text):
for pattern in (_CHIP_INFLOW_EN_TO_PATTERN, _CHIP_INFLOW_EN_RECEIVED_PATTERN):
for match in pattern.finditer(text):
code = _COUNTRY_MAP.get(match.group("country").lower())
if not code:
continue
value = float(match.group("value"))
if 0 <= value <= 100 and code not in by_metric.get("chip_inflow_share", {}):
by_metric.setdefault("chip_inflow_share", {})[code] = value
clean_period = (period_label or "").strip() or None
candidates: list[dict[str, Any]] = []
for metric_key, values in by_metric.items():
if sum(values.values()) > 100.0:
continue
proposed: dict[str, Any] = {
"year": year,
"metric": metric_key,
"source_id": source_meta.get("id") or f"candidate-src-{year}",
"values": values,
}
if clean_period is not None:
proposed["period_label"] = clean_period
candidates.append(
{
"candidate_type": "observation",
"proposed_payload": {
"year": year,
"metric": metric_key,
"source_id": source_meta.get("id") or f"candidate-src-{year}",
"values": values,
},
"proposed_payload": proposed,
"source_payload": source_meta,
"confidence": 0.86,
"extractor_note": f"从报告摘录自动提取 {year} 年 {metric_key} 候选值,待管理员人工核验后入库。",
+139 -27
View File
@@ -32,10 +32,25 @@ from app.services.ai.tool_registry import (
query_global_situational_tool,
query_recent_earth_news_tool,
)
from app.services.ai.scene_directives import (
INFLUENCE_ZONE_GUIDANCE as _INFLUENCE_ZONE_GUIDANCE,
consume_text_holding_scene_tag as _consume_text_holding_scene_tag,
extract_planet_scene_from_text,
)
from app.services.ai.workflow_evolver import schedule_post_run_evolution
from app.services.ai.workflow_registry import _fallback_workflow_dict, ensure_builtin_workflows
from app.services.ai.workflow_runtime import classify_turn_intent, execute_session_turn
from app.services.ai.workflow_runtime import (
ActiveRunHandle,
classify_turn_intent,
execute_session_turn,
register_active_run_handle,
unregister_active_run_handle,
)
from app.services.ai_client import AIProviderClient
from app.services.compute_lineage import (
build_revision_change_context,
is_revision_question,
)
logger = get_logger(__name__, service="ai_stream")
@@ -186,6 +201,7 @@ def _build_news_analysis_request(
context["user_memory_notes"] = memory_notes
if pinned_summaries:
context["pinned_comparisons"] = pinned_summaries
context["scene_overlay_guidance"] = _INFLUENCE_ZONE_GUIDANCE
return SituationalAnalysisRequest(
title="Planet 全球新闻与国际局势研判",
objective=(
@@ -194,16 +210,17 @@ def _build_news_analysis_request(
"1. **核心事实与背景脉络**(紧扣聚焦新闻或近期头条);\n"
"2. **地缘、产业与基础设施影响**(可结合海缆/算力/航运/卫星/BGP 背景若相关,无直接关联则勿强行牵连);\n"
"3. **后续重点观察信号与不确定边界**。\n"
"请直接输出面向用户的 Markdown 正文,不要包在 JSON 里。"
"正文直接输出面向用户的 Markdown,不要把正文包在 JSON 里;若存在任何明确的地理国家、地区或海域影响范围,请在正文最末尾附带系统指令要求的 <planet_scene>...</planet_scene>。"
),
system_prompt=(
"你是 Planet(智能星球计划)的全球新闻与国际局势分析参谋。"
"如有前序对话与用户备忘录,请保持指代与口径延续。"
"请严谨区分已报道事实与推演研判,禁止虚构具体伤亡、断缆或未经报道的内部消息。"
"请严谨区分已报道事实与推演研判,禁止虚构具体伤亡、断缆或未经报道的内部消息。\n\n"
f"{_INFLUENCE_ZONE_GUIDANCE}"
),
context=context,
constraints=[
"Output clean user-facing Markdown directly (not JSON).",
"Output clean user-facing Markdown directly (except the optional trailing <planet_scene>...</planet_scene> tag when geographic impact zones apply).",
"Distinguish reported facts from analytical outlook.",
],
thinking=thinking_cfg,
@@ -224,13 +241,19 @@ def _build_telemetry_stream_request(
conversation_summary: str = "",
memory_notes: list[str] | None = None,
pinned_summaries: list[str] | None = None,
revision_context: dict[str, Any] | None = None,
) -> SituationalAnalysisRequest:
context: dict[str, Any] = {
"domain": domain,
"verified_baseline_summary": base_answer_md,
"evidence": evidence,
"view_headline": (view_spec or {}).get("headline"),
"publish_id": (view_spec or {}).get("publish_id"),
"mode": (view_spec or {}).get("mode"),
"focus_year": (view_spec or {}).get("focus_year"),
}
if revision_context:
context["revision_context"] = revision_context
if recent_news and recent_news.get("items"):
context["recent_news_headlines"] = (recent_news.get("items") or [])[:10]
if conversation_summary:
@@ -239,20 +262,23 @@ def _build_telemetry_stream_request(
context["user_memory_notes"] = memory_notes
if pinned_summaries:
context["pinned_comparisons"] = pinned_summaries
context["scene_overlay_guidance"] = _INFLUENCE_ZONE_GUIDANCE
return SituationalAnalysisRequest(
title=f"Planet 态势参谋分析({domain})",
objective=(
f"用户问题:{question}\n\n"
"请严格基于 context 中的已核验内置遥测结论、证据源、前序对话摘要/记忆备忘与关联新闻头条,"
"使用清晰自然的 Markdown 直接回答用户问题,给出结构化洞察与口径边界,不要输出 JSON 对象。"
"使用清晰自然的 Markdown 直接回答用户问题,给出结构化洞察与口径边界,不要把正文包在 JSON 对象里;"
"若涉及明确国家、地区或海域范围,请在正文最末尾附带系统指令要求的 <planet_scene>...</planet_scene>。"
),
system_prompt=(
"你是 Planet 空间与网络基础设施态势参谋。如有前序对话与用户记忆备忘,请延续语境与偏好;"
"所有具体数值必须与 context 一致,不得编造未给出的实时数值或故障原因;直接输出高质量 Markdown 分析正文。"
"所有具体数值必须与 context 一致,不得编造未给出的实时数值或故障原因;直接输出高质量 Markdown 分析正文。\n\n"
f"{_INFLUENCE_ZONE_GUIDANCE}"
),
context=context,
constraints=[
"Output clean Markdown directly (not JSON).",
"Output clean Markdown directly (except the optional trailing <planet_scene>...</planet_scene> tag when geographic impact zones apply).",
"Do not invent telemetry counts or unverified outages outside context.",
],
thinking=thinking_cfg,
@@ -292,6 +318,10 @@ async def stream_session_turn(
for k, v in context_override.items():
if v is not None:
merged_ctx[k] = v
if context_override.get("publish_id") and not context_override.get("as_of"):
merged_ctx["as_of"] = None
elif context_override.get("as_of") and not context_override.get("publish_id"):
merged_ctx["publish_id"] = None
raw_history = history if history else merged_ctx.get("recent_messages")
existing_summary = str(
@@ -322,6 +352,8 @@ async def stream_session_turn(
time_basis: TimeBasis = (context_override or {}).get("time_basis") or merged_ctx.get("time_basis") or "retrospective"
cutoff_at: str | None = (context_override or {}).get("cutoff_at") or merged_ctx.get("cutoff_at")
publish_id: str | None = merged_ctx.get("publish_id")
as_of: str | None = merged_ctx.get("as_of")
codes = list((context_override or {}).get("selected_codes") or merged_ctx.get("selected_codes") or ["CN", "US"])
visible_layers = dict((context_override or {}).get("visible_layers") or merged_ctx.get("visible_layers") or {})
@@ -365,6 +397,18 @@ async def stream_session_turn(
wf_model = str(model_name or "")
wf_provider = str(provider_name or "")
wf_revision = int(wf_dict.get("active_revision") or 1)
wf_scene_zones_count = 0
run_handle = register_active_run_handle(
ActiveRunHandle(
run_id=run_id,
session_id=session_id_val if session is not None else None,
actor_key=getattr(access, "actor_key", "anonymous"),
workflow_id=workflow_id,
access_tier=getattr(access, "access_tier", "public_zero_cost"),
question=question[:500],
started_at=wf_started_at,
)
)
try:
wf_earth_ctx: dict[str, Any] = {
**merged_ctx,
@@ -373,6 +417,8 @@ async def stream_session_turn(
"visible_layers": visible_layers,
"time_basis": time_basis,
"cutoff_at": cutoff_at,
"publish_id": publish_id,
"as_of": as_of,
}
if news_context:
wf_earth_ctx["news_context"] = news_context
@@ -398,6 +444,7 @@ async def stream_session_turn(
request=request,
run_id=run_id,
allow_external_tools=allow_external,
cancel_event=run_handle.cancel_event,
extra_meta={
"session_id": session_id_val,
"domain": domain,
@@ -411,26 +458,42 @@ async def stream_session_turn(
**({"session_token": issued_session_token} if issued_session_token else {}),
},
):
if run_handle.cancel_event.is_set() or (
request is not None and await request.is_disconnected()
):
wf_status = "cancelled"
break
ev_name = str(item.get("event") or "")
ev_data = dict(item.get("data") or {})
if ev_name == "node" and ev_data.get("status") == "completed":
nid = str(ev_data.get("node_id") or "")
if nid and nid not in wf_trace:
wf_trace.append(nid)
elif ev_name == "scene":
s_spec = ev_data.get("scene_spec")
if isinstance(s_spec, dict) and isinstance(s_spec.get("influence_zones"), list):
wf_scene_zones_count = len(s_spec["influence_zones"])
elif ev_name == "done":
if run_handle.cancel_event.is_set():
wf_status = "cancelled"
break
if isinstance(ev_data.get("nodes"), list):
wf_trace = [str(n) for n in ev_data["nodes"] if n]
if ev_data.get("model"):
wf_model = str(ev_data["model"])
if ev_data.get("provider"):
wf_provider = str(ev_data["provider"])
s_spec = ev_data.get("scene_spec")
if isinstance(s_spec, dict) and isinstance(s_spec.get("influence_zones"), list):
wf_scene_zones_count = len(s_spec["influence_zones"])
wf_answer = str(ev_data.get("answer_markdown") or "")
ev_data.setdefault("usage", {})
ev_data["compacted"] = compacted_flag
ev_data["conversation_summary"] = compacted_summary
ev_data["memory_used"] = memory_used_flag
if session is not None and isinstance(session.context_state, dict):
updated_recent = [*recent_history, {"role": "user", "content": question}]
base_recent = list(session.context_state.get("recent_messages") or recent_history)
updated_recent = [*base_recent, {"role": "user", "content": question}]
if wf_answer:
updated_recent.append({"role": "assistant", "content": wf_answer[:1800]})
session.context_state = {
@@ -442,6 +505,8 @@ async def stream_session_turn(
wf_status = "failed"
wf_error = str(ev_data.get("message") or ev_data.get("detail") or "Workflow DAG error")
yield _format_sse(ev_name, ev_data)
if run_handle.cancel_event.is_set():
wf_status = "cancelled"
except asyncio.CancelledError:
wf_status = "cancelled"
raise
@@ -455,6 +520,7 @@ async def stream_session_turn(
)
yield _format_sse("error", {"detail": wf_error, "message": wf_error, "partial": bool(wf_answer)})
finally:
unregister_active_run_handle(run_id)
try:
wf_completed_at = datetime.now(UTC)
wf_latency_ms = max(0, int((wf_completed_at - wf_started_at).total_seconds() * 1000))
@@ -479,6 +545,7 @@ async def stream_session_turn(
"provider": wf_provider,
"latency_ms": wf_latency_ms,
"workflow_revision": wf_revision,
"scene_zones_count": wf_scene_zones_count,
},
error_message=wf_error[:500],
started_at=wf_started_at,
@@ -590,7 +657,8 @@ async def stream_session_turn(
def _persist_session_memory(answer_text: str) -> None:
if session is None or not isinstance(session.context_state, dict):
return
updated_recent = [*recent_history, {"role": "user", "content": question}]
base_recent = list(session.context_state.get("recent_messages") or recent_history)
updated_recent = [*base_recent, {"role": "user", "content": question}]
if answer_text:
updated_recent.append({"role": "assistant", "content": answer_text[:1800]})
session.context_state = {
@@ -629,6 +697,13 @@ async def stream_session_turn(
current_max = int((getattr(ai_client, "llm_config", None) or {}).get("max_tokens") or 0)
if type(ai_client) is AIProviderClient and ai_client.llm_config and current_max < 3200:
effective_client, _ = prepare_situational_ai_call(ai_client, min_max_tokens=3200)
revision_context: dict[str, Any] | None = None
if domain == "compute" and is_revision_question(question):
revision_context = await build_revision_change_context(
db,
publish_id=(view_spec or {}).get("publish_id") or publish_id,
redact=(getattr(access, "tier", "public_zero_cost") != "admin"),
)
analysis_req = (
_build_news_analysis_request(
question=question,
@@ -660,18 +735,33 @@ async def stream_session_turn(
conversation_summary=compacted_summary,
memory_notes=clean_memory_notes,
pinned_summaries=clean_pinned_summaries,
revision_context=revision_context,
)
)
text_chunks: list[str] = []
reasoning_chunks: list[str] = []
pending_scene_tail = ""
resolved_provider = provider_name
resolved_model = model_name
final_usage: dict[str, Any] = {}
direct_run_handle = register_active_run_handle(
ActiveRunHandle(
run_id=run_id,
session_id=session_id_val if session is not None else None,
actor_key=getattr(access, "actor_key", "anonymous"),
workflow_id=f"stream.{domain}",
access_tier=getattr(access, "access_tier", "public_zero_cost"),
question=question[:500],
started_at=datetime.now(UTC),
)
)
try:
async for ev in effective_client.stream_analyze(analysis_req, request_id=run_id):
if request is not None and await request.is_disconnected():
if direct_run_handle.cancel_event.is_set() or (
request is not None and await request.is_disconnected()
):
return
ev_type = str(ev.get("event") or "")
if ev_type == "start":
@@ -688,7 +778,10 @@ async def stream_session_turn(
delta = ev.get("delta")
if isinstance(delta, str) and delta:
text_chunks.append(delta)
yield _format_sse("text", {"delta": delta})
combined_buf = pending_scene_tail + delta
emit_chunk, pending_scene_tail = _consume_text_holding_scene_tag(combined_buf)
if emit_chunk:
yield _format_sse("text", {"delta": emit_chunk})
elif ev_type == "done":
if isinstance(ev.get("provider"), str) and ev["provider"]:
resolved_provider = ev["provider"]
@@ -699,17 +792,30 @@ async def stream_session_turn(
elif ev_type == "error":
raise RuntimeError(str(ev.get("detail") or "AI stream error"))
if direct_run_handle.cancel_event.is_set():
return
if pending_scene_tail:
cleaned_tail, _ = extract_planet_scene_from_text(pending_scene_tail)
if cleaned_tail:
yield _format_sse("text", {"delta": cleaned_tail})
combined_text = "".join(text_chunks).strip()
if not combined_text:
raise RuntimeError("AI provider stream returned empty response")
clean_text, inline_thoughts = strip_thinking_text(combined_text)
clean_text, parsed_scene = extract_planet_scene_from_text(clean_text or combined_text)
combined_reasoning = "".join(reasoning_chunks).strip()
if inline_thoughts:
extra_thought = "\n\n".join(inline_thoughts)
combined_reasoning = f"{combined_reasoning}\n\n{extra_thought}".strip() if combined_reasoning else extra_thought
final_answer_md = clean_text or combined_text
merged_scene_spec: dict[str, Any] | None = dict(scene_spec) if isinstance(scene_spec, dict) else None
if parsed_scene:
merged_scene_spec = {**(merged_scene_spec or {}), "domain": (merged_scene_spec or {}).get("domain") or domain, **parsed_scene}
_persist_session_memory(final_answer_md)
if hasattr(db, "commit"):
try:
@@ -717,22 +823,26 @@ async def stream_session_turn(
except Exception:
pass
yield _format_sse(
"done",
{
"status": "completed",
"generation_mode": "llm_verified",
"zero_token": False,
"provider": resolved_provider,
"model": resolved_model,
"usage": final_usage,
"compacted": compacted_flag,
"conversation_summary": compacted_summary,
"memory_used": memory_used_flag,
"answer_markdown": final_answer_md,
"reasoning_markdown": combined_reasoning,
},
)
if merged_scene_spec is not None and (merged_scene_spec.get("influence_zones") or parsed_scene):
yield _format_sse("scene", {"scene_spec": merged_scene_spec})
done_payload: dict[str, Any] = {
"status": "completed",
"generation_mode": "llm_verified",
"zero_token": False,
"provider": resolved_provider,
"model": resolved_model,
"usage": final_usage,
"compacted": compacted_flag,
"conversation_summary": compacted_summary,
"memory_used": memory_used_flag,
"answer_markdown": final_answer_md,
"reasoning_markdown": combined_reasoning,
}
if merged_scene_spec is not None:
done_payload["scene_spec"] = merged_scene_spec
yield _format_sse("done", done_payload)
except asyncio.CancelledError:
raise
except Exception as exc:
@@ -772,3 +882,5 @@ async def stream_session_turn(
"fallback_reason": str(exc),
},
)
finally:
unregister_active_run_handle(run_id)
+200 -9
View File
@@ -2,7 +2,7 @@
from __future__ import annotations
from datetime import UTC, datetime
from datetime import UTC, date, datetime
import hashlib
import ipaddress
import socket
@@ -18,7 +18,7 @@ from app.core.logging import get_logger
from app.models.bgp_incident import BGPIncident
from app.models.collected_data import CollectedData
from app.models.earth_news import EarthNewsItem
from app.schemas.compute_configuration import ComputeConfiguration
from app.schemas.compute_configuration import ComputeConfiguration, ComputeObservation, source_for
from app.services.ai_tools.schemas import FetchedEvidence
from app.services.compute_configuration import read_configuration
from app.services.compute_history import compute_history
@@ -210,10 +210,42 @@ def filter_compute_config_by_cutoff(
kept_sources.append(src)
kept_source_ids = {s.id for s in kept_sources}
kept_obs = [
obs for obs in config.observations
if obs.year <= cutoff_year and obs.source_id in kept_source_ids
]
kept_obs: list[ComputeObservation] = []
for obs in config.observations:
if obs.year > cutoff_year:
continue
surviving_values = {
code: val
for code, val in obs.values.items()
if source_for(obs, code) in kept_source_ids
}
if not surviving_values:
continue
per_code_sources = {code: source_for(obs, code) for code in surviving_values}
row_src = (
obs.source_id
if obs.source_id in kept_source_ids
else next(iter(per_code_sources.values()))
)
unique_sources = list(dict.fromkeys(per_code_sources.values()))
if len(unique_sources) == 1:
row_src = unique_sources[0]
cleaned_vs = None
else:
cleaned_vs = {
code: src_id
for code, src_id in per_code_sources.items()
if src_id != row_src
} or None
kept_obs.append(
obs.model_copy(
update={
"source_id": row_src,
"values": surviving_values,
"value_sources": cleaned_vs,
}
)
)
kept_innov = [
inn for inn in config.innovation
if inn.year <= cutoff_year and inn.source_id in kept_source_ids
@@ -259,9 +291,28 @@ async def query_compute_posture_tool(
*,
time_basis: TimeBasis = "retrospective",
cutoff_at: str | None = None,
as_of: str | None = None,
publish_id: str | None = None,
) -> dict[str, Any]:
"""Read-only tool returning deterministic multi-metric compute series and provenance."""
envelope = await read_configuration(db)
envelope = await read_configuration(db, as_of=as_of, publish_id=publish_id)
if envelope.get("snapshot_unavailable"):
empty_config = ComputeConfiguration(
reviewed_at=date.today(), sources=[], observations=[], innovation=[]
)
result = compute_history(countries, mode, empty_config)
result["version"] = None
result["publish_id"] = None
result["published_at"] = None
result["as_of"] = envelope.get("as_of")
result["snapshot_unavailable"] = True
result["notice"] = envelope.get("notice")
result["is_default"] = False
result["time_basis"] = time_basis
result["cutoff_at"] = cutoff_at if time_basis == "as_known_then" else None
result["withheld_source_ids"] = []
return result
raw_config = ComputeConfiguration.model_validate(envelope["config"])
effective_config, withheld_sources = filter_compute_config_by_cutoff(
raw_config, time_basis=time_basis, cutoff_at=cutoff_at
@@ -278,7 +329,12 @@ async def query_compute_posture_tool(
result["innovation"] = [
r for r in (result.get("innovation") or []) if int(r.get("year") or 0) <= cutoff_year
]
result["version"] = envelope["revision"]
effective_pid = envelope.get("publish_id") or envelope["revision"]
result["version"] = effective_pid
result["publish_id"] = effective_pid
result["published_at"] = envelope.get("published_at")
result["as_of"] = envelope.get("as_of")
result["snapshot_unavailable"] = False
result["is_default"] = envelope["is_default"]
result["time_basis"] = time_basis
result["cutoff_at"] = cutoff_at if time_basis == "as_known_then" else None
@@ -890,6 +946,119 @@ async def query_vessel_posture_tool(
}
async def query_cloud_posture_tool(
db: AsyncSession,
*,
time_basis: TimeBasis = "live",
cutoff_at: str | None = None,
correlate_domain: str | None = None,
latitude: float | None = None,
longitude: float | None = None,
) -> dict[str, Any]:
"""Read-only meteorological cloud cover, convective cluster, and asset correlation summary."""
from app.services.earth_clouds import (
correlate_cloud_with_assets,
get_cloud_analysis_summary,
query_cloud_point,
)
summary = await get_cloud_analysis_summary(db)
point_info = None
if isinstance(latitude, (int, float)) and isinstance(longitude, (int, float)):
point_info = await query_cloud_point(float(latitude), float(longitude), db=db)
correlation = None
if correlate_domain and hasattr(db, "execute"):
try:
correlation = await correlate_cloud_with_assets(
db, domain=correlate_domain, min_density=55.0, limit=12
)
except Exception:
correlation = None
ev_id = "ev-cloud-1"
return {
"domain": "cloud",
"available": bool(summary.get("available")),
"mode": summary.get("mode"),
"degraded": summary.get("degraded"),
"version": summary.get("version"),
"captured_at": summary.get("captured_at"),
"source": summary.get("source"),
"satellites": summary.get("satellites") or [],
"global_summary": summary.get("global_summary") or {},
"regions": summary.get("regions") or [],
"convective_clusters": (summary.get("convective_clusters") or [])[:12],
"point_query": point_info,
"asset_correlation": correlation,
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"evidence": {
ev_id: {
"id": ev_id,
"title": "Planet 全球静止气象卫星实时红外云图与强对流分析(global_cloud_map)",
"publisher": "NASA GIBS / EUMETSAT / Planet Earth Cloud Analytics",
"url": "/api/v1/data-products/clouds/summary",
"published_at": str(summary.get("captured_at") or datetime.now(UTC).date().isoformat()),
"locator": f"builtin:cloud:{summary.get('version') or 'static'}",
}
},
"limitations": (
[]
if summary.get("available")
else ["尚未采集实时卫星云图快照,当前无可分析的实时云量栅格。"]
),
}
async def query_wind_posture_tool(
db: AsyncSession,
*,
time_basis: TimeBasis = "live",
cutoff_at: str | None = None,
latitude: float | None = None,
longitude: float | None = None,
) -> dict[str, Any]:
"""Read-only NOAA GFS 10m global wind velocity, gale zones, and point vector summary."""
from app.services.earth_wind import get_wind_analysis_summary, query_wind_point
summary = await get_wind_analysis_summary(db)
point_info = None
if isinstance(latitude, (int, float)) and isinstance(longitude, (int, float)):
point_info = await query_wind_point(float(latitude), float(longitude), db=db)
ev_id = "ev-wind-1"
return {
"domain": "wind",
"available": bool(summary.get("available")),
"is_active": bool(summary.get("is_active")),
"version": summary.get("version"),
"captured_at": summary.get("captured_at"),
"forecast_time": summary.get("forecast_time"),
"global_summary": summary.get("global_summary") or {},
"regions": summary.get("regions") or [],
"storm_cores": (summary.get("storm_cores") or [])[:12],
"point_query": point_info,
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"evidence": {
ev_id: {
"id": ev_id,
"title": "NOAA GFS 全球 10m 海表风场与大风核分析(global_wind_gfs)",
"publisher": "NOAA NCEP / PacIOOS ERDDAP",
"url": "/api/v1/data-products/wind/summary",
"published_at": str(summary.get("forecast_time") or summary.get("captured_at") or datetime.now(UTC).date().isoformat()),
"locator": f"builtin:wind:{summary.get('version') or 'static'}",
}
},
"limitations": (
[]
if summary.get("available")
else ["尚未采集全球 10m 风场快照,当前无可分析的 GFS 风速网格。"]
),
}
async def query_global_situational_tool(
db: AsyncSession,
*,
@@ -926,6 +1095,7 @@ async def query_global_situational_tool(
cable_data = await query_cable_posture_tool(db, time_basis=time_basis, cutoff_at=cutoff_at)
sat_data = await query_satellite_posture_tool(db, time_basis=time_basis, cutoff_at=cutoff_at)
vessel_data = await query_vessel_posture_tool(db, time_basis=time_basis, cutoff_at=cutoff_at)
cloud_data = await query_cloud_posture_tool(db, time_basis=time_basis, cutoff_at=cutoff_at)
vis = dict(visible_layers or {})
active_bgp = [it for it in bgp_items if str(it.get("status") or "").lower() == "active"]
@@ -943,7 +1113,7 @@ async def query_global_situational_tool(
"locator": f"builtin:global:codes={','.join(codes)}:basis={time_basis}",
}
}
for sub in (compute_data, cable_data, sat_data, vessel_data):
for sub in (compute_data, cable_data, sat_data, vessel_data, cloud_data):
for k, v in (sub.get("evidence") or {}).items():
if k not in evidence and len(evidence) < 12:
evidence[k] = v
@@ -994,6 +1164,20 @@ async def query_global_situational_tool(
"metric_text": f"{len(bgp_items)} 条(活跃 {len(active_bgp)})",
"status": "incident_active" if active_bgp else ("telemetry_online" if bgp_items else "quiet"),
},
{
"domain": "cloud",
"label": "气象云图",
"layer_visible": bool(vis.get("clouds", True)),
"count": int((cloud_data.get("global_summary") or {}).get("convective_cluster_count") or 0),
"secondary_count": round(float((cloud_data.get("global_summary") or {}).get("global_cloud_cover_pct") or 0.0), 1),
"metric_text": (
f"全球云量 {(cloud_data.get('global_summary') or {}).get('global_cloud_cover_pct', 0)}% · "
f"强对流 {(cloud_data.get('global_summary') or {}).get('convective_cluster_count', 0)} 个"
if cloud_data.get("available")
else "未采集实时云图"
),
"status": "telemetry_online" if cloud_data.get("available") else "standby_or_empty",
},
]
limitations: list[str] = []
@@ -1031,6 +1215,13 @@ async def query_global_situational_tool(
"underway": vessel_data.get("underway", 0),
"by_type": vessel_data.get("by_type") or {},
},
"cloud_summary": {
"available": cloud_data.get("available", False),
"captured_at": cloud_data.get("captured_at"),
"global_cloud_cover_pct": (cloud_data.get("global_summary") or {}).get("global_cloud_cover_pct"),
"convective_cluster_count": (cloud_data.get("global_summary") or {}).get("convective_cluster_count", 0),
"top_clusters": (cloud_data.get("convective_clusters") or [])[:3],
},
"time_basis": time_basis,
"cutoff_at": cutoff_at if time_basis == "as_known_then" else None,
"evidence": evidence,
+428 -60
View File
@@ -21,6 +21,7 @@ import copy
from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
import os
import re
from typing import Any, Protocol
from uuid import uuid4
@@ -38,6 +39,7 @@ from app.services.ai.dag_executor import run_workflow_dag_stream
from app.services.ai.thinking_sanitizer import strip_thinking_text
from app.services.ai.workflow_registry import (
ALLOWED_NODE_PATCH_FIELDS,
DRAFT_BINDINGS_KEY,
TOOL_CATALOG,
VALID_TOOL_IDS,
_apply_validated_node_patches,
@@ -216,6 +218,80 @@ class UnusedToolSignalDetector:
return []
FIXTURE_EXPECT_KEY = "expect"
_UNCERTAINTY_MARKERS = (
"待核实", "待查", "不确定", "证据不足", "无法确认", "尚无法", "有待", "unverified", "uncertain", "insufficient evidence",
)
def normalize_fixture_expect(raw: Any) -> dict[str, Any]:
"""Normalize gradable fixture assertions stored under `context_json["expect"]`."""
if not isinstance(raw, dict):
return {}
def _str_list(key: str) -> list[str]:
vals = raw.get(key)
if not isinstance(vals, list):
return []
return [str(v).strip()[:120] for v in vals if str(v).strip()][:10]
numbers: list[str] = []
for val in raw.get("numbers") or []:
if isinstance(val, bool):
continue
if isinstance(val, (int, float)):
numbers.append(str(int(val)) if float(val).is_integer() else str(val))
elif isinstance(val, str) and re.fullmatch(r"-?\d+(?:\.\d+)?", val.strip()):
numbers.append(val.strip())
expect: dict[str, Any] = {}
if numbers:
expect["numbers"] = numbers[:10]
for key in ("must_include", "must_not_include"):
items = _str_list(key)
if items:
expect[key] = items
if raw.get("require_uncertainty_without_evidence"):
expect["require_uncertainty_without_evidence"] = True
min_evidence = raw.get("min_evidence")
if isinstance(min_evidence, int) and not isinstance(min_evidence, bool) and min_evidence > 0:
expect["min_evidence"] = min(min_evidence, 50)
return expect
def _answer_contains_number(answer: str, number: str) -> bool:
return re.search(rf"(?<![\d.]){re.escape(number)}(?!\d|\.\d)", answer) is not None
def grade_fixture_result(result: dict[str, Any], expect: dict[str, Any]) -> list[str]:
"""Return the failed checks for one sample run (empty list == pass)."""
failures: list[str] = []
answer = str(result.get("answer") or "")
if result.get("error"):
failures.append(f"执行出错:{str(result['error'])[:120]}")
if not answer.strip():
failures.append("没有输出正文")
if result.get("verification_passed") is False:
warns = ";".join(result.get("verification_warnings") or []) or "护栏校验失败"
failures.append(f"护栏校验未通过:{warns}")
for number in expect.get("numbers") or []:
if not _answer_contains_number(answer, number):
failures.append(f"未给出期望数值 {number}")
for phrase in expect.get("must_include") or []:
if phrase not in answer:
failures.append(f"缺少必备表述「{phrase}」")
for phrase in expect.get("must_not_include") or []:
if phrase in answer:
failures.append(f"出现禁用表述「{phrase}」")
evidence_count = int(result.get("evidence_count") or 0)
if expect.get("min_evidence") and evidence_count < int(expect["min_evidence"]):
failures.append(f"证据条目 {evidence_count} 少于要求的 {expect['min_evidence']}")
if expect.get("require_uncertainty_without_evidence") and evidence_count == 0:
lowered = answer.lower()
if not any(marker in lowered for marker in _UNCERTAINTY_MARKERS):
failures.append("证据不足时未保留不确定性(缺少「待核实/证据不足」等表述)")
return failures
class FixtureABEvaluator:
evaluator_id = "fixture_ab"
@@ -255,9 +331,14 @@ class FixtureABEvaluator:
comparisons: list[dict[str, Any]] = []
base_ok = 0
prop_ok = 0
graded = 0
regressions: list[str] = []
for row in rows:
question = str(row.sample_question or "").strip() or f"请分析 {row.name}"
ctx = dict(row.context_json or {})
expect = normalize_fixture_expect(ctx.pop(FIXTURE_EXPECT_KEY, None))
if expect:
graded += 1
base_res = await _run_graph_single_sample(
db=db,
workflow=workflow,
@@ -274,24 +355,32 @@ class FixtureABEvaluator:
earth_context=ctx,
ai_client=ai_client,
)
for res in (base_res, prop_res):
res["failures"] = grade_fixture_result(res, expect)
res["ok"] = not res["failures"]
res["answer_preview"] = str(res.pop("answer", ""))[:280]
if base_res["ok"]:
base_ok += 1
if prop_res["ok"]:
prop_ok += 1
if base_res["ok"] and not prop_res["ok"]:
regressions.append(str(row.name))
comparisons.append(
{
"fixture_id": row.id,
"fixture_name": row.name,
"question": question[:160],
"graded": bool(expect),
"expect": expect,
"base": base_res,
"proposed": prop_res,
}
)
if prop_ok > base_ok:
verdict = "improved"
elif prop_ok < base_ok:
if regressions or prop_ok < base_ok:
verdict = "regressed"
elif prop_ok > base_ok:
verdict = "improved"
else:
avg_base_ms = sum(c["base"]["latency_ms"] for c in comparisons) / len(comparisons)
avg_prop_ms = sum(c["proposed"]["latency_ms"] for c in comparisons) / len(comparisons)
@@ -300,13 +389,19 @@ class FixtureABEvaluator:
else:
verdict = "neutral"
graded_note = "" if graded else "(样本未设置可判对错的断言,仅校验执行成功与护栏)"
return {
"evaluator_id": self.evaluator_id,
"fixture_count": len(comparisons),
"graded_fixture_count": graded,
"base_passed": base_ok,
"proposed_passed": prop_ok,
"regressions": regressions,
"verdict": verdict,
"summary": f"已对照 {len(comparisons)} 组样本:原版通过 {base_ok}/{len(comparisons)},新版通过 {prop_ok}/{len(comparisons)}(判定:{verdict})。",
"summary": (
f"已对照 {len(comparisons)} 组样本(含断言 {graded} 组):原版通过 {base_ok}/{len(comparisons)},"
f"新版通过 {prop_ok}/{len(comparisons)}(判定:{verdict}){graded_note}。"
),
"comparisons": comparisons,
}
@@ -947,6 +1042,20 @@ async def _evaluate_meta_canary(db: AsyncSession) -> None:
)
if meta_canary is None:
return
meta_target = meta_canary.get("target_revision")
meta_live = (
await db.execute(select(AIWorkflow.active_revision).where(AIWorkflow.workflow_id == META_WORKFLOW_ID))
).scalar_one_or_none()
if isinstance(meta_target, int) and meta_live is not None and int(meta_live) != meta_target:
await update_ledger_entry(
db,
str(meta_canary["id"]),
{
"status": "superseded",
"superseded_reason": f"元引擎当前生效版本已变为 v{int(meta_live)}(灰度目标 v{meta_target}),终止灰度且不回滚。",
},
)
return
meta_started = _parse_iso(meta_canary.get("created_at"))
downstream = [
e
@@ -1002,6 +1111,28 @@ async def evaluate_canary_and_maybe_rollback(
if canary is None:
return None
# A manual publish / rollback after this canary started supersedes it: rolling back now would
# overwrite the newer live revision (e.g. revert a hand-published v3 to v1).
target_rev = canary.get("target_revision")
live_rev = (
await db.execute(select(AIWorkflow.active_revision).where(AIWorkflow.workflow_id == workflow_id))
).scalar_one_or_none()
if isinstance(target_rev, int) and live_rev is not None and int(live_rev) != target_rev:
updated = await update_ledger_entry(
db,
str(canary["id"]),
{
"status": "superseded",
"superseded_reason": f"当前生效版本已变为 v{int(live_rev)}(灰度目标 v{target_rev}),终止本轮灰度且不回滚。",
},
)
logger.info_event(
"Workflow canary superseded by a newer live revision",
event="ai_evolver.canary.superseded",
context={"workflow_id": workflow_id, "target_revision": target_rev, "live_revision": int(live_rev)},
)
return {"action": "superseded", "entry": updated}
runs = (
await db.execute(
select(WorkflowRun)
@@ -1155,10 +1286,27 @@ def _deterministic_business_patches(
bad_runs: list[dict[str, Any]],
) -> tuple[str, list[dict[str, Any]]]:
nodes = [n for n in (base_graph.get("nodes") or []) if isinstance(n, dict)]
llm_node = next((n for n in nodes if n.get("node_type") in {"llm_agent", "tool_agent"}), None)
if llm_node is None:
llm_nodes = [n for n in nodes if n.get("node_type") in {"llm_agent", "tool_agent"}]
if not llm_nodes:
return "当前工作流无可扩展推理节点。", []
llm_node = llm_nodes[0]
if bad_runs:
failed_node_counts: dict[str, int] = {}
for br in bad_runs:
traces = (br.get("budget_used") or {}).get("node_traces") if isinstance(br.get("budget_used"), dict) else None
if not isinstance(traces, list):
continue
for item in traces:
if not isinstance(item, dict):
continue
nid = str(item.get("node_id") or "")
if item.get("status") in {"completed", "failed"} and any(n.get("id") == nid for n in llm_nodes):
failed_node_counts[nid] = failed_node_counts.get(nid, 0) + 1
if failed_node_counts:
top_nid = max(failed_node_counts, key=lambda k: failed_node_counts[k])
llm_node = next((n for n in llm_nodes if n.get("id") == top_nid), llm_node)
patches: list[dict[str, Any]] = []
if mode == "model_adapt":
profile = health.get("active_model_profile") or {}
@@ -1204,20 +1352,12 @@ def _deterministic_business_patches(
"reason": f"供应商 {profile.get('provider')} 支持原生联网检索,开启后可协同补充最新一手信源。",
}
)
if not patches:
base_sys = str(llm_node.get("system_prompt") or "").strip()
model_name = str(profile.get("model") or "当前模型").strip()
tag = f"[模型适配 {model_name}] 请优先依据工具返回的实测数值作答,禁止臆测缺失字段。"
if tag not in base_sys and base_sys:
patches.append(
{
"node_id": llm_node["id"],
"field": "system_prompt",
"after": f"{base_sys}\n{tag}",
"reason": f"针对当前模型({model_name})补强事实边界约束。",
}
)
summary = f"针对当前模型 {profile.get('model') or profile.get('provider')} 生成自适应调整方案。"
# No capability mismatch found -> no change (never pad with generic prompt clauses).
summary = (
f"针对当前模型 {profile.get('model') or profile.get('provider')} 生成自适应调整方案。"
if patches
else f"当前模型 {profile.get('model') or profile.get('provider')} 与工作流配置匹配,无需调整。"
)
return summary, patches
inst_lower = instruction.lower()
@@ -1255,20 +1395,21 @@ def _deterministic_business_patches(
"reason": f"精简近期零调用的闲置工具({', '.join(unused[:3])}),减少无效上下文干扰。",
}
)
if not patches:
if not patches and instruction.strip():
# Only an explicit admin instruction justifies a prompt edit without a detected signal.
base_sys = str(llm_node.get("system_prompt") or "").strip()
target_note = instruction.strip() or (
"先明确区分已核验事实与待查证缺口,不确定的数值或来源须直接说明。"
)
target_note = instruction.strip()
if target_note not in base_sys and base_sys:
patches.append(
{
"node_id": llm_node["id"],
"field": "system_prompt",
"after": f"{base_sys}\n[调优约束] {target_note}",
"reason": "基于近期负反馈或调优目标加固提示词护栏。",
"reason": "按管理员调优目标加固提示词护栏。",
}
)
if not patches:
return "未检测到需要调整的信号,本轮无需修改。", []
summary = (
f"已针对「{instruction.strip()}」生成节点调优建议。"
if instruction.strip()
@@ -1277,6 +1418,159 @@ def _deterministic_business_patches(
return summary, patches
# Every (node, field) the meta-evolver may change must measurably alter the business proposal
# request built below; anything else would create versions that change nothing downstream.
META_EVOLVABLE_FIELDS: frozenset[tuple[str, str]] = frozenset(
{
("diag_node", "system_prompt"),
("diag_node", "prompt"),
("patch_node", "system_prompt"),
("patch_node", "prompt"),
("patch_node", "thinking_enabled"),
}
)
_DEFAULT_EVOLVER_SYSTEM_PROMPT = "你是智能星球 AI 工作流架构调优引擎。仅输出严格 JSON:{summary, node_patches}。"
_NO_CHANGE_CLAUSE = "若现有工作流已满足目标、无需调整,请返回空的 node_patches 数组,并在 summary 中说明理由。"
def build_business_evolution_request(
*,
workflow_id: str,
mode: str,
instruction: str,
diag_node: dict[str, Any],
patch_node: dict[str, Any],
schema: dict[str, Any],
context: dict[str, Any],
) -> SituationalAnalysisRequest:
"""Build the business-evolution LLM request from the live meta-evolver nodes."""
diag_sys = str(diag_node.get("system_prompt") or "").strip()
diag_prompt = str(diag_node.get("prompt") or "").strip()
patch_sys = str(patch_node.get("system_prompt") or "").strip()
patch_prompt = str(patch_node.get("prompt") or "").strip()
combined_sys = f"{patch_sys}\n\n[诊断要点]\n{diag_sys}".strip() if (patch_sys or diag_sys) else ""
objective_parts = [
f"进化模式:{mode}(optimize=运行优化 / model_adapt=新模型适配)",
f"工作流 ID:{workflow_id}",
f"管理员指令:{instruction.strip() or '无额外指定,请结合失败/差评样本与健康度指标主动调优。'}",
]
if diag_prompt:
objective_parts.append(f"[诊断任务]\n{diag_prompt}")
if patch_prompt:
objective_parts.append(f"[补丁任务]\n{patch_prompt}")
objective_parts.append(_NO_CHANGE_CLAUSE)
return SituationalAnalysisRequest(
title=f"Evolve workflow {workflow_id}",
objective="\n".join(objective_parts)[:16000],
system_prompt=(combined_sys or _DEFAULT_EVOLVER_SYSTEM_PROMPT)[:8000],
context=context,
thinking={"mode": "auto"} if bool(patch_node.get("thinking_enabled", True)) else {"mode": "off"},
response_format={"type": "json_schema", "json_schema": {"name": "workflow_patch", "schema": schema}},
)
def _full_graph_diff(base_graph: dict[str, Any], proposed_graph: dict[str, Any]) -> list[dict[str, Any]]:
"""All node/edge differences between two graphs (layout positions ignored)."""
try:
base = _validate_graph_payload(base_graph)
proposed = _validate_graph_payload(proposed_graph)
except HTTPException:
return []
base_nodes = {str(n["id"]): n for n in base.get("nodes") or []}
prop_nodes = {str(n["id"]): n for n in proposed.get("nodes") or []}
changes: list[dict[str, Any]] = []
for nid in sorted(set(base_nodes) | set(prop_nodes)):
bnode, pnode = base_nodes.get(nid), prop_nodes.get(nid)
if bnode is None or pnode is None:
changes.append(
{
"node_id": nid,
"node_title": (pnode or bnode or {}).get("title") or nid,
"field": "__node__",
"before": None if bnode is None else "present",
"after": None if pnode is None else "present",
}
)
continue
for key in sorted(set(bnode) | set(pnode)):
if key == "position" or bnode.get(key) == pnode.get(key):
continue
changes.append(
{
"node_id": nid,
"node_title": pnode.get("title") or nid,
"field": key,
"before": copy.deepcopy(bnode.get(key)),
"after": copy.deepcopy(pnode.get(key)),
}
)
def _edge_keys(graph: dict[str, Any]) -> set[tuple[str, str, str]]:
return {
(str(e.get("source")), str(e.get("target")), str(e.get("condition") or "always"))
for e in graph.get("edges") or []
if isinstance(e, dict)
}
base_edges, prop_edges = _edge_keys(base), _edge_keys(proposed)
if base_edges != prop_edges:
changes.append(
{
"node_id": "__edges__",
"node_title": "edges",
"field": "edges",
"before": sorted(list(e) for e in base_edges - prop_edges),
"after": sorted(list(e) for e in prop_edges - base_edges),
}
)
return changes
def _no_change_result(
*,
workflow_id: str,
mode: str,
base_revision: int,
summary: str,
proposed_graph: dict[str, Any],
health: dict[str, Any] | None = None,
meta_revision: int | None = None,
) -> dict[str, Any]:
return {
"workflow_id": workflow_id,
"mode": mode,
"base_revision": base_revision,
"meta_revision": meta_revision,
"summary": summary,
"changes": [],
"changes_vs_live": [],
"proposed_graph": proposed_graph,
"constitution_ok": True,
"violations": [],
"applied_status": "no_change",
"new_revision": None,
"blocked_reason": "",
"ledger_entry": None,
"ab_eval": None,
"health": health,
}
def _ab_gate_allows_auto_publish(ab_eval: dict[str, Any]) -> tuple[bool, str]:
"""Auto-publish only when graded fixtures show the candidate is not worse than live."""
if int(ab_eval.get("fixture_count") or 0) == 0:
return False, "自动发布需先通过 A/B 门禁:当前工作流没有固定样本(Fixtures)。"
if int(ab_eval.get("graded_fixture_count") or 0) == 0:
return False, "自动发布需先通过 A/B 门禁:固定样本均未设置可判对错的断言(expect),无法证明候选版本不退化。"
regressions = list(ab_eval.get("regressions") or [])
if regressions:
return False, f"A/B 门禁未通过:{len(regressions)} 条样本在候选版本上退化({', '.join(regressions[:3])})。"
verdict = str(ab_eval.get("verdict") or "")
if verdict in {"regressed", "slower"}:
return False, f"A/B 门禁未通过(判定:{verdict})。"
return True, ""
async def propose_workflow_evolution(
db: AsyncSession,
workflow_id: str,
@@ -1309,7 +1603,13 @@ async def propose_workflow_evolution(
health = await compute_workflow_health(db, workflow_id, ai_client=ai_client)
parent_revision = int(wf.active_revision or 1)
base_graph = copy.deepcopy(wf.draft_graph or wf.published_graph or {})
live_graph = copy.deepcopy(wf.published_graph or {})
# Only an admin explicitly tuning into a draft may build on their own unpublished draft.
# Background / auto-publish evolution always starts from the live revision so it can never
# smuggle unpublished human edits into production or clear them.
builds_on_human_draft = trigger == "manual" and apply_mode != "auto" and wf.draft_graph is not None
base_graph = copy.deepcopy(wf.draft_graph if builds_on_human_draft else live_graph)
base_graph.pop(DRAFT_BINDINGS_KEY, None)
# Optional DGM archive parent selection
if branch_from_best and health.get("recommended_parent_revision"):
@@ -1323,6 +1623,7 @@ async def propose_workflow_evolution(
).scalar_one_or_none()
if rev_row is not None and isinstance(rev_row.graph_json, dict):
base_graph = copy.deepcopy(rev_row.graph_json)
base_graph.pop(DRAFT_BINDINGS_KEY, None)
parent_revision = best_rev
# Collect bad/selected run context for GEPA diagnosis
@@ -1381,6 +1682,7 @@ async def propose_workflow_evolution(
summary = ""
raw_patches: list[dict[str, Any]] = []
ai_decided = False
if ai_ready and client is not None:
schema = {
"type": "object",
@@ -1402,22 +1704,13 @@ async def propose_workflow_evolution(
},
"required": ["summary", "node_patches"],
}
diag_sys = str(diag_node.get("system_prompt") or "").strip()
patch_sys = str(patch_node.get("system_prompt") or "").strip()
combined_sys = (
f"{patch_sys}\n\n[诊断要点]\n{diag_sys}".strip()
or "你是智能星球 AI 工作流架构调优引擎。仅输出严格 JSON:{summary, node_patches}。"
)
objective = (
f"进化模式:{mode}(optimize=运行优化 / model_adapt=新模型适配)\n"
f"工作流 ID:{workflow_id}\n"
f"管理员指令:{instruction.strip() or '无额外指定,请结合失败/差评样本与健康度指标主动调优。'}\n"
f"{str(patch_node.get('prompt') or '')}"
).strip()
req = SituationalAnalysisRequest(
title=f"Evolve workflow {workflow_id}",
objective=objective[:16000],
system_prompt=combined_sys[:8000],
req = build_business_evolution_request(
workflow_id=workflow_id,
mode=mode,
instruction=instruction,
diag_node=diag_node,
patch_node=patch_node,
schema=schema,
context={
"workflow_id": workflow_id,
"parent_revision": parent_revision,
@@ -1431,7 +1724,6 @@ async def propose_workflow_evolution(
"selected_run": selected_run.to_dict() if selected_run else None,
"aflow_lessons": lessons,
},
response_format={"type": "json_schema", "json_schema": {"name": "workflow_patch", "schema": schema}},
)
try:
resp = await client.analyze(req)
@@ -1441,6 +1733,8 @@ async def propose_workflow_evolution(
summary = str(parsed.get("summary") or "").strip()
if isinstance(parsed.get("node_patches"), list):
raw_patches = parsed["node_patches"]
# A valid, explicitly empty patch list means "no change needed" — honour it.
ai_decided = True
except Exception as exc:
logger.warning_event(
"AI evolution proposal failed; using deterministic fallback",
@@ -1448,7 +1742,7 @@ async def propose_workflow_evolution(
context={"workflow_id": workflow_id, "mode": mode, "error": str(exc)},
)
if not raw_patches:
if not ai_decided:
summary, raw_patches = _deterministic_business_patches(
base_graph,
mode=mode,
@@ -1458,11 +1752,23 @@ async def propose_workflow_evolution(
)
proposed_graph, diffs = _apply_validated_node_patches(base_graph, raw_patches)
if not diffs:
return _no_change_result(
workflow_id=workflow_id,
mode=mode,
base_revision=parent_revision,
summary=summary or "引擎判断当前工作流无需修改。",
proposed_graph=proposed_graph,
health=health,
)
is_auto_apply = apply_mode == "auto"
# Everything that would actually ship, measured against the live revision (not just engine patches).
changes_vs_live = _full_graph_diff(live_graph, proposed_graph)
constitution_ok, violations = validate_evolution_patch(
base_graph,
live_graph if is_auto_apply else base_graph,
proposed_graph,
diffs,
changes_vs_live if is_auto_apply else diffs,
is_meta=False,
is_auto=is_auto_apply,
)
@@ -1471,11 +1777,16 @@ async def propose_workflow_evolution(
new_revision = None
blocked_reason = ""
ledger_entry: dict[str, Any] | None = None
ab_eval: dict[str, Any] | None = None
if apply_mode == "draft":
if not constitution_ok or not diffs:
if trigger != "manual" and wf.draft_graph is not None:
# Never overwrite an admin's unpublished draft from a background run.
applied_status = "skipped"
blocked_reason = "存在未发布的人工草稿,自动进化不覆盖草稿,本轮跳过。"
elif not constitution_ok:
applied_status = "blocked"
blocked_reason = ";".join(violations) if violations else "无可应用的有效节点改动"
blocked_reason = ";".join(violations)
else:
await save_workflow_draft(
db,
@@ -1496,6 +1807,8 @@ async def propose_workflow_evolution(
"meta_revision": meta_revision,
"summary": summary,
"changes": diffs,
"changes_vs_live": changes_vs_live,
"built_on_human_draft": builds_on_human_draft,
},
)
elif apply_mode == "auto":
@@ -1510,10 +1823,17 @@ async def propose_workflow_evolution(
if not budget_ok:
applied_status = "blocked"
blocked_reason = budget_msg
elif not constitution_ok or not diffs:
elif not constitution_ok:
applied_status = "blocked"
blocked_reason = ";".join(violations) if violations else "无可应用的有效节点改动"
blocked_reason = ";".join(violations)
else:
# Auto-publish must prove on graded fixtures that the candidate is not worse than live.
ab_eval = await run_fixture_ab_eval(db, workflow_id, proposed_graph, max_fixtures=5)
gate_ok, gate_msg = _ab_gate_allows_auto_publish(ab_eval)
if not gate_ok:
applied_status = "blocked"
blocked_reason = gate_msg
if applied_status != "blocked":
prev_active_rev = int(wf.active_revision or 1)
published = await publish_workflow(
db,
@@ -1521,6 +1841,7 @@ async def propose_workflow_evolution(
graph=proposed_graph,
change_summary=f"[Auto-Evolve/{mode}] {summary[:120]}",
actor="system:auto_evolver",
keep_draft=True,
)
applied_status = "auto_published"
new_revision = int(published.get("active_revision") or (prev_active_rev + 1))
@@ -1539,6 +1860,8 @@ async def propose_workflow_evolution(
"baseline_failure_rate": health["failure_rate"],
"summary": summary,
"changes": diffs,
"changes_vs_live": changes_vs_live,
"ab_eval_summary": (ab_eval or {}).get("summary"),
},
)
if applied_status == "blocked":
@@ -1554,6 +1877,7 @@ async def propose_workflow_evolution(
"summary": summary or f"{mode} blocked",
"rollback_reason": blocked_reason,
"changes": diffs,
"changes_vs_live": changes_vs_live,
},
)
@@ -1564,6 +1888,7 @@ async def propose_workflow_evolution(
"meta_revision": meta_revision,
"summary": summary or "暂无需要变更的字段。",
"changes": diffs,
"changes_vs_live": changes_vs_live,
"proposed_graph": proposed_graph,
"constitution_ok": constitution_ok,
"violations": violations,
@@ -1571,6 +1896,7 @@ async def propose_workflow_evolution(
"new_revision": new_revision,
"blocked_reason": blocked_reason,
"ledger_entry": ledger_entry,
"ab_eval": ab_eval,
"health": health,
}
@@ -1598,21 +1924,30 @@ async def _run_graph_single_sample(
answer = ""
err = ""
nodes_done: list[str] = []
verification: dict[str, Any] = {}
evidence_count = 0
targets = earth_context.get("targets") if isinstance(earth_context.get("targets"), list) else None
allow_external = bool(earth_context.get("allow_external_tools", False))
try:
async for ev in run_workflow_dag_stream(
db=db,
workflow=test_wf,
question=question,
use_draft=True,
targets=targets,
earth_context=earth_context,
ai_client=ai_client,
allow_external_tools=False,
allow_external_tools=allow_external,
):
ev_name = str(ev.get("event") or "")
ev_data = ev.get("data") if isinstance(ev.get("data"), dict) else {}
if ev_name == "done":
answer = str(ev_data.get("answer_markdown") or "")
nodes_done = [str(x) for x in (ev_data.get("nodes") or [])]
if isinstance(ev_data.get("verification"), dict):
verification = ev_data["verification"]
if isinstance(ev_data.get("evidence"), dict):
evidence_count = len(ev_data["evidence"])
elif ev_name == "error":
err = str(ev_data.get("message") or "DAG error")
except Exception as exc:
@@ -1620,11 +1955,14 @@ async def _run_graph_single_sample(
latency_ms = max(0, int((_utc_now() - started).total_seconds() * 1000))
return {
"ok": bool(answer.strip()) and not err,
"answer": answer,
"latency_ms": latency_ms,
"answer_length": len(answer.strip()),
"nodes": nodes_done,
"error": err,
"verification_passed": bool(verification.get("passed", True)),
"verification_warnings": list(verification.get("warnings") or []),
"evidence_count": evidence_count,
}
@@ -1874,7 +2212,11 @@ async def propose_meta_evolution(
if meta_wf is None:
raise HTTPException(status_code=404, detail=f"Workflow '{META_WORKFLOW_ID}' not found")
base_graph = copy.deepcopy(meta_wf.draft_graph or meta_wf.published_graph or {})
builds_on_human_draft = trigger == "meta_manual" and apply_mode != "auto" and meta_wf.draft_graph is not None
base_graph = copy.deepcopy(
meta_wf.draft_graph if builds_on_human_draft else (meta_wf.published_graph or {})
)
base_graph.pop(DRAFT_BINDINGS_KEY, None)
ledger = await _load_ledger_entries(db)
outcomes = [
e
@@ -1901,6 +2243,7 @@ async def propose_meta_evolution(
summary = ""
raw_patches: list[dict[str, Any]] = []
meta_ai_decided = False
if ai_ready and client is not None:
schema = {
"type": "object",
@@ -1926,8 +2269,9 @@ async def propose_meta_evolution(
title="Meta-evolve workflow evolver",
objective=(
f"管理员指示:{instruction.strip() or '基于进化台账中已验证与被回滚/忽略的案例,优化元引擎诊断与补丁合成精度。'}\n"
"仅允许修改 `diag_node` 或 `patch_node` 的提示词或 thinking_enabled;"
"严禁修改 `verify_output`,且 `patch_node` 必须保留 JSON `node_patches` 输出要求。"
"仅允许修改 `diag_node` 的 system_prompt/prompt,或 `patch_node` 的 system_prompt/prompt/thinking_enabled;"
"严禁修改 `verify_output`,且 `patch_node` 必须保留 JSON `node_patches` 输出要求。\n"
f"{_NO_CHANGE_CLAUSE}"
),
system_prompt="你是智能星球 AI 元进化策略师。仅输出严格 JSON:{summary, node_patches}。",
context={
@@ -1949,6 +2293,7 @@ async def propose_meta_evolution(
summary = str(parsed.get("summary") or "").strip()
if isinstance(parsed.get("node_patches"), list):
raw_patches = parsed["node_patches"]
meta_ai_decided = True
except Exception as exc:
logger.warning_event(
"AI meta-evolution request failed; using deterministic prompt refinement",
@@ -1956,7 +2301,8 @@ async def propose_meta_evolution(
context={"error": str(exc)},
)
if not raw_patches:
if not meta_ai_decided and (instruction.strip() or outcomes):
# Deterministic refinement needs a real basis: an admin instruction or ledger outcomes.
target_node = next(
(n for n in (base_graph.get("nodes") or []) if n.get("id") == "patch_node"),
None,
@@ -1987,7 +2333,25 @@ async def propose_meta_evolution(
f"基于 {len(outcomes)} 条进化台账记录(验证有效 {verified_count},回滚 {rollback_count},忽略 {dismissed_count})生成元引擎自举方案。"
)
# Drop patches to fields that have no downstream effect on the business proposal request.
raw_patches = [
p
for p in raw_patches
if isinstance(p, dict)
and (str(p.get("node_id") or ""), str(p.get("field") or "")) in META_EVOLVABLE_FIELDS
]
proposed_graph, diffs = _apply_validated_node_patches(base_graph, raw_patches)
if not diffs:
return {
**_no_change_result(
workflow_id=META_WORKFLOW_ID,
mode="meta",
base_revision=int(meta_wf.active_revision or 1),
summary=summary or "元引擎判断当前策略无需修改(暂无进化台账结果或明确指示)。",
proposed_graph=proposed_graph,
),
"outcomes_analyzed": len(outcomes),
}
is_auto_apply = apply_mode == "auto"
constitution_ok, violations = validate_evolution_patch(
base_graph,
@@ -2004,9 +2368,12 @@ async def propose_meta_evolution(
policy = await get_evolution_policy(db)
if apply_mode == "draft":
if not constitution_ok or not diffs:
if trigger != "meta_manual" and meta_wf.draft_graph is not None:
applied_status = "skipped"
blocked_reason = "存在未发布的人工元引擎草稿,自动元进化不覆盖草稿,本轮跳过。"
elif not constitution_ok:
applied_status = "blocked"
blocked_reason = ";".join(violations) if violations else "无可应用的元引擎改动"
blocked_reason = ";".join(violations)
else:
await save_workflow_draft(
db,
@@ -2045,9 +2412,9 @@ async def propose_meta_evolution(
if not budget_ok:
applied_status = "blocked"
blocked_reason = budget_msg
elif not constitution_ok or not diffs:
elif not constitution_ok:
applied_status = "blocked"
blocked_reason = ";".join(violations) if violations else "无可应用的元引擎改动"
blocked_reason = ";".join(violations)
else:
prev_rev = int(meta_wf.active_revision or 1)
published = await publish_workflow(
@@ -2056,6 +2423,7 @@ async def propose_meta_evolution(
graph=proposed_graph,
change_summary=f"[Meta-Evolve] {summary[:120]}",
actor="system:meta_evolver" if trigger != "meta_manual" else actor,
keep_draft=True,
)
applied_status = "auto_published"
new_revision = int(published.get("active_revision") or (prev_rev + 1))
+308 -47
View File
@@ -4,14 +4,13 @@ from __future__ import annotations
from collections import deque
import copy
from datetime import UTC, datetime
import inspect
import json
import re
from typing import Any
from uuid import uuid4
from fastapi import HTTPException, status
from fastapi import HTTPException
from sqlalchemy import delete, desc, select
from sqlalchemy.ext.asyncio import AsyncSession
@@ -20,6 +19,10 @@ from app.models.ai_workflow import AIWorkflow, AIWorkflowFixture, AIWorkflowRevi
from app.models.situational_assessment import WorkflowRun
from app.schemas.ai import SituationalAnalysisRequest
from app.services.ai.thinking_sanitizer import strip_thinking_text
from app.services.location.workflow_tools import (
LOCATION_JUDGE_FINAL_SCHEMA,
LOCATION_JUDGE_R1_SCHEMA,
)
logger = get_logger(__name__, service="ai_workflow_registry")
@@ -66,6 +69,20 @@ TOOL_CATALOG: list[dict[str, Any]] = [
"category": "internal_read",
"description": "查询航运密度、关键海峡通道船只态势。",
},
{
"id": "query_cloud_posture",
"name": "全球实时红外云图与强对流分析",
"name_en": "Live Satellite Cloud & Convection Analytics",
"category": "internal_read",
"description": "读取全球与重点航运/算力区域云量、强对流云团与云顶亮温数据。",
},
{
"id": "query_wind_posture",
"name": "全球 10m 风场与大风区态势",
"name_en": "Global 10m Wind Field & Gale Analytics",
"category": "internal_read",
"description": "读取 NOAA GFS 全球 10m 风速、风向、大风核心区域与重点航道风场态势。",
},
{
"id": "query_recent_earth_news",
"name": "Earth 近期新闻动态",
@@ -134,20 +151,64 @@ TOOL_CATALOG: list[dict[str, Any]] = [
"name": "位置结果强约束提交",
"name_en": "Constrained Location Submit",
"category": "location_guardrail",
"description": "通过 Schema 工具提交定位结论或 undisclosed/multi_site 终态。",
"description": "兼容旧版工具式位置提交定义。",
},
{
"id": "location_normalize_context",
"name": "L0 位置上下文归一化与终态检查",
"name_en": "L0 Location Normalize & Terminal Check",
"category": "location_knowledge",
"description": "水合数据库与跨源线索、统一英文国名,并在已确认终态时短路。",
},
{
"id": "location_knowledge_lookup",
"name": "L1 确定性设施知识库查询",
"name_en": "L1 Facility Knowledge Lookup",
"category": "location_knowledge",
"description": "串并行组合查询 builds_upon、ROR、Wikidata(P17) 与 PeeringDB(/api/fac)。",
},
{
"id": "location_web_research",
"name": "L2 并行网页取证与证据编号",
"name_en": "L2 Parallel Web Research",
"category": "external_evidence",
"description": "按轮次并行抓取一手正文并执行结构化英文 WebSearch,为证据编号 E1..En。",
},
{
"id": "location_geocode_verify",
"name": "L3 多粒度级联地理编码校验",
"name_en": "L3 Cascade Geocoder Verify",
"category": "location_guardrail",
"description": "按 街道地址 -> 设施名 -> 城市+省州 -> 城市 级联查 Nominatim 并校验国家与粒度。",
},
{
"id": "location_persist_outcome",
"name": "L4 位置结果输出与终态持久化",
"name_en": "L4 Location Output & Persist",
"category": "location_guardrail",
"description": "输出标准候选坐标载荷与地球联动视角,或在有实证时落库不可定位终态。",
},
]
VALID_TOOL_IDS: frozenset[str] = frozenset(item["id"] for item in TOOL_CATALOG)
MAX_WORKFLOW_NODES = 12
# Graph-level key carrying Earth bindings inside drafts and revision snapshots (no extra column).
DRAFT_BINDINGS_KEY = "bindings"
VALID_NODE_TYPES: frozenset[str] = frozenset(
{"trigger", "deterministic", "llm_agent", "guardrail", "output"}
)
VALID_EDGE_CONDITIONS: frozenset[str] = frozenset(
{"always", "on_empty_or_low_confidence", "on_entity_type"}
{
"always",
"on_empty_or_low_confidence",
"on_entity_type",
"on_field_equals",
"on_guardrail_passed",
"on_guardrail_failed",
}
)
PRESERVED_BUILTIN_EDGE_CONDITIONS: frozenset[str] = frozenset(
{"not_terminal", "high_confidence_hit", "fallback_to_agent", "ingest", "interactive"}
{"not_terminal", "on_terminal", "high_confidence_hit", "fallback_to_agent", "ingest", "interactive"}
)
ALLOWED_EDGE_CONDITIONS: frozenset[str] = VALID_EDGE_CONDITIONS | PRESERVED_BUILTIN_EDGE_CONDITIONS
@@ -427,8 +488,8 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
"name": "算力/设施未知位置定位工作流",
"name_en": "Compute & Facility Location Agent",
"category": "location",
"description": "整合 builds_upon 继承、Wikidata、PeeringDB、可控 Tool-Calling 取证与地理编码硬校验的完整定位管线。",
"description_en": "Tiered facility geolocation combining builds_upon, Wikidata, PeeringDB, controlled tool-calling evidence, and geocoder verification.",
"description": "真正的条件路由 DAG 工作流:L0 归一化与终态短路 → L1 知识库 → 两轮并行联网取证与单轮结构化研判 → 级联地理编码与 3 条硬护栏。",
"description_en": "True conditional DAG workflow: L0 normalize -> L1 knowledge lookup -> 2-round parallel web research & JSON judgment -> cascade geocoder & 3 hard guardrails.",
"is_default": False,
"bindings": {
"enabled": True,
@@ -443,12 +504,13 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
"nodes": [
_node(
"l0_normalize",
"trigger",
"L0:实体归一化与终态短路",
"deterministic",
"L0:实体归一化与终态检查",
"L0: Normalize & Terminal Check",
40,
160,
description="切分 name_short、注入 Epoch Source 1..5/TOP500 一手链接与 builds_upon,若已标记 undisclosed/multi_site 则直接短路。",
180,
description="水合数据库与跨源兄弟线索、转换英文国家名、过滤 .csv 原始表并在已确认终态时直接短路。",
tools=["location_normalize_context"],
params={"short_circuit_terminal_statuses": True},
),
_node(
@@ -456,55 +518,138 @@ BUILTIN_WORKFLOWS: list[dict[str, Any]] = [
"deterministic",
"L1:确定性设施知识库查询",
"L1: Knowledge Resolvers",
420,
160,
description="依次匹配 builds_upon 继承、Wikidata P625、PeeringDB /api/fac 及带商业云过滤的 ROR。",
tools=["builds_upon_inherit", "wikidata_lookup", "peeringdb_fac_lookup", "ror_lookup"],
params={"allow_low_confidence_short_circuit": False, "wikidata_enabled": True, "peeringdb_enabled": True},
380,
80,
description="依次匹配 builds_upon、ROR,并行查询 Wikidata(P625+P17) 与 PeeringDB(/api/fac)。",
tools=["location_knowledge_lookup"],
params={
"builds_upon_enabled": True,
"ror_enabled": True,
"wikidata_enabled": True,
"peeringdb_enabled": True,
},
),
_node(
"l2_agent_research",
"l2_research_r1",
"deterministic",
"L2-R1:并行一手抓取与英文搜索",
"L2-R1: Parallel Web Research",
720,
220,
description="并行抓取一手正文链接与 2 条精简英文搜索,为全部证据分配 E1..En 唯一编号。",
tools=["location_web_research"],
params={"round": 1, "max_search_queries": 2, "max_fetch_urls": 2},
),
_node(
"l2_judge_r1",
"llm_agent",
"L2:多步 Tool-Calling 取证 Agent",
"L2: Tool-Calling Evidence Agent",
800,
300,
description="优先读取一手 source_url/Source 1..5,必要时多轮改写短查询搜索并调用 geocode_verify 落点。",
"L2-J1:首轮证据语义研判",
"L2-J1: Round-1 Judgment",
1060,
220,
description="基于 E1..En 证据输出单轮结构化 JSON:直接定位 / 发起定点补查 / 确认终态。",
prompt_key="location.factcheck.resolve",
system_prompt="你是基础设施物理位置核查 Agent。严禁直接猜测或编造经纬度!必须先通过 fetch_source_url(优先使用元数据自带一手链接)或 web_search 找到物理设施/园区地址证据,再调用 geocode_verify 获取候选坐标 ID,最后调用 submit_location_result 提交结果。若确认为跨地域多站点或未披露地址,提交 multi_site 或 undisclosed。",
prompt="核查给定算力中心或 BGP 观测站的真实物理所在城市与设施位置。",
tools=["fetch_source_url", "web_search", "geocode_verify", "submit_location_result"],
system_prompt=(
"你是基础设施物理位置核查分析师。严格基于输入的 evidence_items(编号 E1..En)和 location_target 进行判断,严禁猜测或编造坐标/URL!\n"
"规则:\n"
"1) 只要证据已明确指出物理所在城市/园区(如数据中心运营商页面、政府规划/新闻稿、HPC 官网),直接设 decision='located' 并填写 city/country(英文国名)/facility_name/address 及引用的 evidence_ids;无需为追门牌号拖延。\n"
"2) 若发现重要线索但还缺关键城市名或正文细节,设 decision='need_followup',给出最多 2 条精准英文 followup_queries 或需全文抓取的 fetch_urls。\n"
"3) 若多条权威证据确认物理机房国与源登记国(总部国)不同,country 填实证物理部署国并在 country_override_reason 说明依据。\n"
"4) 仅当权威证据明确指出未披露、多地分布式、规划中、纯云端无实体时,才选对应终态(undisclosed/multi_site/planned/cloud_only)。\n"
"5) 输出语言规范:reasoning 和 country_override_reason 必须使用简洁的简体中文、不超过 120 字,且严禁出现 E1、E6、E1-E5 等内部证据编号(仅在 evidence_ids 数组填写编号供校验)。"
),
prompt="核查给定设施的真实物理所在城市与园区位置,并按 JSON 契约返回初判结论。",
thinking_enabled=True,
max_steps=4,
timeout_seconds=90,
max_steps=1,
timeout_seconds=60,
native_web_search=False,
params={"output_schema": LOCATION_JUDGE_R1_SCHEMA, "allow_followup": True},
),
_node(
"l2_research_r2",
"deterministic",
"L2-R2:定向补搜与正文全文抓取",
"L2-R2: Targeted Follow-up Research",
1400,
340,
description="仅当 J1 判定需要补查时触发,执行 J1 给出的精准补搜词与候选页全文抓取。",
tools=["location_web_research"],
params={"round": 2, "max_search_queries": 2, "max_fetch_urls": 2},
),
_node(
"l2_judge_r2",
"llm_agent",
"L2-J2:综合全部证据终判",
"L2-J2: Final Evidence Judgment",
1740,
340,
description="结合两轮全部 E1..En 证据给出最终位置研判或明确无法定位原因。",
prompt_key="location.factcheck.resolve",
system_prompt=(
"你是基础设施物理位置终判分析师。严格依据两轮汇总的 evidence_items(E1..En)给出最终判定,禁止继续追问!\n"
"若证据支持某城市或园区,请设 decision='located' 并写明 city、country(英文)、facility_name、evidence_ids 与 confidence;"
"若跨国部署,填写 country_override_reason;若证据仍不足或明确未披露,输出 unresolved 或对应终态。\n"
"输出语言规范:reasoning 和 country_override_reason 必须使用简洁的简体中文、不超过 120 字,直接说明物理部署结论或具体信息缺口,严禁出现 E1、E6、E1-E5 等内部证据编号(evidence_ids 数组照常填写供校验)。"
),
prompt="综合两轮证据完成最终物理位置裁决。",
thinking_enabled=True,
max_steps=1,
timeout_seconds=60,
native_web_search=False,
params={"output_schema": LOCATION_JUDGE_FINAL_SCHEMA, "allow_followup": False},
),
_node(
"l3_geocode",
"deterministic",
"L3:多粒度级联地理编码",
"L3: Cascade Geocoder",
2080,
180,
description="由代码按 街道地址 → 设施+城市 → 城市+省州 → 城市 级联查 Nominatim 落点并校验国家。",
tools=["location_geocode_verify"],
),
_node(
"l3_geo_guardrail",
"guardrail",
"L3:国家边界硬校验与证据核验",
"L3: Geo Boundary Guardrail",
1180,
160,
description="强制校验经纬度范围、国家匹配一致性、引用 URL 真实性及城市级回退降级。",
guardrails={"min_confidence": 0.55, "enforce_country_match": True, "require_tool_cited_urls": True, "downgrade_geocoded_site_to_city": True},
"L3:抗幻觉地理硬护栏",
"L3: Geo Anti-Hallucination Guardrail",
2420,
180,
description="校验证据真实引用(evidence_ids)、坐标>=城市级精度、置信度下限及受控跨国覆写。",
guardrails={
"geo_verification": True,
"min_confidence": 0.55,
"enforce_country_match": True,
"require_tool_cited_urls": True,
"downgrade_geocoded_site_to_city": True,
},
),
_node(
"l4_persist_outcome",
"output",
"L4:候选输出或终态落库",
"L4: Candidate / Terminal State",
1560,
160,
description="返回高可信待确认候选坐标,或写入 undisclosed/multi_site/anonymous 防重复消耗。",
"L4:候选输出与终态落库",
"L4: Persist & Structured Output",
2760,
180,
description="输出标准化候选坐标载荷与地球聚焦视角,或在有实证时落库终态。",
tools=["location_persist_outcome"],
params={"persist_terminal_statuses": True, "fly_to_target": True},
),
],
"edges": [
_edge("loc-e1", "l0_normalize", "l1_knowledge", "未标记终态", "Not terminal", "not_terminal"),
_edge("loc-e2", "l1_knowledge", "l3_geo_guardrail", "高置信度命中", "Verified site hit", "high_confidence_hit"),
_edge("loc-e3", "l1_knowledge", "l2_agent_research", "未命中/需核查", "Miss or unverified", "fallback_to_agent"),
_edge("loc-e4", "l2_agent_research", "l3_geo_guardrail", "提交候选", "Submitted", "always"),
_edge("loc-e5", "l3_geo_guardrail", "l4_persist_outcome", "校验完成", "Validated", "always"),
_edge("loc-e2", "l0_normalize", "l4_persist_outcome", "已有终态缓存", "Cached terminal", "on_terminal"),
_edge("loc-e3", "l1_knowledge", "l4_persist_outcome", "知识库命中", "L1 hit", "high_confidence_hit"),
_edge("loc-e4", "l1_knowledge", "l2_research_r1", "未命中进联网取证", "Miss -> L2 research", "fallback_to_agent"),
_edge("loc-e5", "l2_research_r1", "l2_judge_r1", "首轮证据就绪", "R1 evidence ready", "always"),
_edge("loc-e6", "l2_judge_r1", "l2_research_r2", "需定向补查", "Need followup", "on_field_equals", "decision=need_followup"),
_edge("loc-e7", "l2_research_r2", "l2_judge_r2", "补查证据就绪", "R2 evidence ready", "always"),
_edge("loc-e8", "l2_judge_r1", "l3_geocode", "J1 定位成功", "J1 located", "on_field_equals", "decision=located"),
_edge("loc-e9", "l2_judge_r2", "l3_geocode", "J2 定位成功", "J2 located", "on_field_equals", "decision=located"),
_edge("loc-e10", "l3_geocode", "l3_geo_guardrail", "送入硬护栏", "Verify geo", "always"),
_edge("loc-e11", "l2_judge_r1", "l3_geo_guardrail", "J1 终态/未定论", "J1 non-located", "on_field_equals", "decision=undisclosed,multi_site,planned,cloud_only,anonymous,unresolved"),
_edge("loc-e12", "l2_judge_r2", "l3_geo_guardrail", "J2 终态/未定论", "J2 non-located", "on_field_equals", "decision=undisclosed,multi_site,planned,cloud_only,anonymous,unresolved"),
_edge("loc-e13", "l3_geo_guardrail", "l4_persist_outcome", "输出结论", "Emit outcome", "always"),
],
},
},
@@ -982,6 +1127,100 @@ def _upgrade_untouched_legacy_positions(row: AIWorkflow, spec: dict[str, Any]) -
return True
_LEGACY_LOC_NODE_IDS = frozenset(
{"l0_normalize", "l1_knowledge", "l2_agent_research", "l3_geo_guardrail", "l4_persist_outcome"}
)
def _upgrade_untouched_location_v1(row: AIWorkflow, spec: dict[str, Any]) -> bool:
"""Upgrade retired 5-node `location.resolve_unknown` graphs (and legacy 5-node drafts) to the 9-node DAG."""
if row.workflow_id != "location.resolve_unknown":
return False
changed = False
graph = row.published_graph if isinstance(row.published_graph, dict) else None
if graph:
node_ids = {
str(n.get("id") or "")
for n in (graph.get("nodes") or [])
if isinstance(n, dict) and n.get("id")
}
if node_ids == _LEGACY_LOC_NODE_IDS:
row.published_graph = copy.deepcopy(spec["graph"])
changed = True
draft = row.draft_graph if isinstance(row.draft_graph, dict) else None
if draft:
draft_ids = {
str(n.get("id") or "")
for n in (draft.get("nodes") or [])
if isinstance(n, dict) and n.get("id")
}
if draft_ids == _LEGACY_LOC_NODE_IDS:
row.draft_graph = None
changed = True
return changed
_PREV_LOC_JUDGE_PROMPTS: dict[str, str] = {
"l2_judge_r1": (
"你是基础设施物理位置核查分析师。严格基于输入的 evidence_items(编号 E1..En)和 location_target 进行判断,严禁猜测或编造坐标/URL!\n"
"规则:\n"
"1) 只要证据已明确指出物理所在城市/园区(如数据中心运营商页面、政府规划/新闻稿、HPC 官网),直接设 decision='located' 并填写 city/country(英文国名)/facility_name/address 及引用的 evidence_ids;无需为追门牌号拖延。\n"
"2) 若发现重要线索但还缺关键城市名或正文细节,设 decision='need_followup',给出最多 2 条精准英文 followup_queries 或需全文抓取的 fetch_urls。\n"
"3) 若多条权威证据确认物理机房国与源登记国(总部国)不同,country 填实证物理部署国并在 country_override_reason 说明依据。\n"
"4) 仅当权威证据明确指出未披露、多地分布式、规划中、纯云端无实体时,才选对应终态(undisclosed/multi_site/planned/cloud_only)。"
),
"l2_judge_r2": (
"你是基础设施物理位置终判分析师。严格依据两轮汇总的 evidence_items(E1..En)给出最终判定,禁止继续追问!\n"
"若证据支持某城市或园区,请设 decision='located' 并写明 city、country(英文)、facility_name、evidence_ids 与 confidence;"
"若跨国部署,填写 country_override_reason;若证据仍不足或明确未披露,输出 unresolved 或对应终态,并在 reasoning 说明具体缺口。"
),
}
def _upgrade_untouched_location_judge_prompts(row: AIWorkflow, spec: dict[str, Any]) -> bool:
"""Update untouched stock `l2_judge_r1` / `l2_judge_r2` prompts while preserving user edits."""
if row.workflow_id != "location.resolve_unknown":
return False
target_prompts = {
str(n.get("id") or ""): str(n.get("system_prompt") or "")
for n in spec.get("graph", {}).get("nodes", [])
if isinstance(n, dict) and n.get("id") in _PREV_LOC_JUDGE_PROMPTS
}
if len(target_prompts) != len(_PREV_LOC_JUDGE_PROMPTS):
return False
def _patch_graph(raw_graph: Any) -> tuple[dict[str, Any] | None, bool]:
if not isinstance(raw_graph, dict):
return None, False
nodes = raw_graph.get("nodes")
if not isinstance(nodes, list):
return None, False
cloned = copy.deepcopy(raw_graph)
graph_changed = False
for node in cloned.get("nodes", []):
if not isinstance(node, dict):
continue
nid = str(node.get("id") or "")
if nid not in _PREV_LOC_JUDGE_PROMPTS:
continue
current_prompt = str(node.get("system_prompt") or "")
if current_prompt == _PREV_LOC_JUDGE_PROMPTS[nid]:
node["system_prompt"] = target_prompts[nid]
graph_changed = True
return (cloned, True) if graph_changed else (None, False)
changed = False
new_pub, pub_changed = _patch_graph(row.published_graph)
if pub_changed and new_pub is not None:
row.published_graph = new_pub
changed = True
new_draft, draft_changed = _patch_graph(row.draft_graph)
if draft_changed and new_draft is not None:
row.draft_graph = new_draft
changed = True
return changed
async def ensure_builtin_workflows(db: AsyncSession) -> None:
"""Idempotently seed all 9 built-in workflows into `ai_workflows`."""
if not hasattr(db, "execute"):
@@ -999,6 +1238,10 @@ async def ensure_builtin_workflows(db: AsyncSession) -> None:
existing_row = existing_by_id[wf_id]
if _upgrade_untouched_legacy_positions(existing_row, spec):
changed = True
if _upgrade_untouched_location_v1(existing_row, spec):
changed = True
if _upgrade_untouched_location_judge_prompts(existing_row, spec):
changed = True
if not existing_row.bindings and spec.get("bindings"):
existing_row.bindings = default_bindings
changed = True
@@ -1355,7 +1598,7 @@ async def create_workflow(
workflow_id=wf_id,
revision=1,
status="published",
graph_json=validated_graph,
graph_json={**validated_graph, DRAFT_BINDINGS_KEY: dict(normalized_bindings)},
change_summary="Created custom workflow",
created_by=actor,
)
@@ -1437,7 +1680,11 @@ async def update_workflow_metadata(
if description_en is not None:
row.description_en = description_en.strip()
if bindings is not None:
# Explicit "save bindings now" is a deliberate live change; keep any pending draft in sync
# so a later draft publish does not silently revert it.
row.bindings = normalize_bindings(bindings)
if isinstance(row.draft_graph, dict):
row.draft_graph = {**row.draft_graph, DRAFT_BINDINGS_KEY: dict(row.bindings)}
row.updated_by = actor
await db.commit()
await db.refresh(row)
@@ -1480,9 +1727,17 @@ async def save_workflow_draft(
).scalar_one_or_none()
if row is None:
raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found")
row.draft_graph = _validate_graph_payload(graph)
previous_draft_bindings = (
row.draft_graph.get(DRAFT_BINDINGS_KEY) if isinstance(row.draft_graph, dict) else None
)
staged = _validate_graph_payload(graph)
# Draft bindings stay inside the draft so the public Earth entry only changes on publish
# and is restored by discarding the draft.
if bindings is not None:
row.bindings = normalize_bindings(bindings)
staged[DRAFT_BINDINGS_KEY] = normalize_bindings(bindings)
elif isinstance(previous_draft_bindings, dict):
staged[DRAFT_BINDINGS_KEY] = previous_draft_bindings
row.draft_graph = staged
if name is not None and name.strip():
row.name = name.strip()[:160]
if description is not None:
@@ -1523,6 +1778,7 @@ async def publish_workflow(
description: str | None = None,
change_summary: str = "",
actor: str = "admin",
keep_draft: bool = False,
) -> dict[str, Any]:
await ensure_builtin_workflows(db)
row = (
@@ -1531,13 +1787,17 @@ async def publish_workflow(
if row is None:
raise HTTPException(status_code=404, detail=f"Workflow '{workflow_id}' not found")
target_graph = graph if graph is not None else (row.draft_graph or row.published_graph)
staged_bindings = target_graph.get(DRAFT_BINDINGS_KEY) if isinstance(target_graph, dict) else None
validated = _validate_graph_payload(target_graph)
next_rev = int(row.active_revision or 1) + 1
row.published_graph = validated
row.draft_graph = None
if not keep_draft:
row.draft_graph = None
row.active_revision = next_rev
if bindings is not None:
row.bindings = normalize_bindings(bindings)
elif isinstance(staged_bindings, dict):
row.bindings = normalize_bindings(staged_bindings)
if name is not None and name.strip():
row.name = name.strip()[:160]
if description is not None:
@@ -1548,7 +1808,8 @@ async def publish_workflow(
workflow_id=workflow_id,
revision=next_rev,
status="published",
graph_json=validated,
# Snapshot bindings with the graph so rollback restores the matching Earth entry.
graph_json={**validated, DRAFT_BINDINGS_KEY: dict(row.bindings or {})},
change_summary=change_summary.strip() or f"Published revision v{next_rev}",
created_by=actor,
)
+538 -3
View File
@@ -45,9 +45,13 @@ from app.services.ai.spatial_domain_agent import (
investigate_spatial_domain,
)
from app.services.ai.thinking_sanitizer import merge_usage_dicts
from app.services.ai.tool_registry import TimeBasis, query_bgp_incidents_tool, query_compute_posture_tool
from app.services.ai.tool_registry import TimeBasis, query_compute_posture_tool
from app.services.ai_client import AIProviderClient
from app.services.compute_catalog import PARTICIPANTS
from app.services.compute_lineage import (
build_revision_change_context,
is_revision_question,
)
logger = get_logger(__name__, service="ai_workflow")
@@ -94,6 +98,17 @@ def get_active_run_handle(run_id: str) -> ActiveRunHandle | None:
return _ACTIVE_RUNS.get(run_id)
def register_active_run_handle(handle: ActiveRunHandle) -> ActiveRunHandle:
"""Register an active streaming/execution run handle for explicit cooperative cancellation."""
_ACTIVE_RUNS[handle.run_id] = handle
return handle
def unregister_active_run_handle(run_id: str) -> None:
"""Remove an active run handle once execution finishes or aborts."""
_ACTIVE_RUNS.pop(run_id, None)
def cancel_active_run_handle(run_id: str) -> bool:
"""Signal cancellation event and abort in-flight asyncio task if active."""
handle = _ACTIVE_RUNS.get(run_id)
@@ -136,6 +151,481 @@ class WorkbenchBlockSpec(BaseModel):
data: dict[str, Any] = Field(default_factory=dict)
class InfluenceZoneEdgeSpec(BaseModel):
model_config = ConfigDict(extra="forbid")
style: Literal["soft", "sharp"] = "soft"
feather_px: float = Field(default=22.0, ge=0.0, le=48.0)
border_width: float = Field(default=1.5, ge=0.0, le=6.0)
class InfluenceZoneAnimationSpec(BaseModel):
model_config = ConfigDict(extra="forbid")
type: Literal["sweep", "radial", "fade"] = "sweep"
direction: str = Field(default="west_to_east", max_length=32)
duration_ms: int = Field(default=1800, ge=150, le=8000)
delay_ms: int = Field(default=0, ge=0, le=5000)
class InfluenceZoneShapeSpec(BaseModel):
model_config = ConfigDict(extra="forbid")
mode: Literal["countries", "region_preset", "circle", "polygon"]
countries: list[str] = Field(default_factory=list, max_length=64)
region_preset: str | None = Field(default=None, max_length=32)
center: list[float] | None = Field(default=None, min_length=2, max_length=2)
radius_km: float | None = Field(default=None, ge=20.0, le=15000.0)
coordinates: list[list[list[float]]] = Field(default_factory=list, max_length=16)
class InfluenceZoneSpec(BaseModel):
model_config = ConfigDict(extra="forbid")
id: str = Field(..., min_length=1, max_length=64)
label: str = Field(default="", max_length=80)
color: str = Field(default="#38bdf8", pattern=r"^#[0-9a-fA-F]{6}$")
opacity: float = Field(default=0.42, ge=0.05, le=0.9)
z_index: int = Field(default=0, ge=-50, le=50)
edge: InfluenceZoneEdgeSpec = Field(default_factory=InfluenceZoneEdgeSpec)
animation: InfluenceZoneAnimationSpec = Field(default_factory=InfluenceZoneAnimationSpec)
shape: InfluenceZoneShapeSpec
_SCENE_COLOR_NAMES: dict[str, str] = {
"red": "#ef4444",
"crimson": "#dc2626",
"orange": "#f97316",
"amber": "#f59e0b",
"yellow": "#eab308",
"green": "#22c55e",
"emerald": "#10b981",
"teal": "#14b8a6",
"cyan": "#06b6d4",
"blue": "#38bdf8",
"indigo": "#6366f1",
"purple": "#a855f7",
"violet": "#8b5cf6",
"pink": "#ec4899",
"white": "#f8fafc",
}
SUPPORTED_REGION_PRESETS: frozenset[str] = frozenset(
{
"APEC",
"ASIA_PACIFIC",
"NORTHEAST_ASIA",
"EAST_ASIA",
"KOREAN_PENINSULA",
"SOUTHEAST_ASIA",
"SOUTH_ASIA",
"CENTRAL_ASIA",
"INDO_PACIFIC",
"ASEAN",
"EU",
"EUROPE",
"EASTERN_EUROPE",
"NORTHERN_EUROPE",
"WESTERN_EUROPE",
"G7",
"BRICS",
"NATO",
"MIDDLE_EAST",
"MENA",
"AMERICAS",
"NORTH_AMERICA",
"SOUTH_AMERICA",
"AFRICA",
}
)
_REGION_PRESET_ALIASES: dict[str, str] = {
"东北亚": "NORTHEAST_ASIA",
"NE_ASIA": "NORTHEAST_ASIA",
"东亚": "EAST_ASIA",
"朝鲜半岛": "KOREAN_PENINSULA",
"PENINSULA": "KOREAN_PENINSULA",
"东南": "SOUTHEAST_ASIA",
"东南亚": "SOUTHEAST_ASIA",
"SE_ASIA": "SOUTHEAST_ASIA",
"南亚": "SOUTH_ASIA",
"中亚": "CENTRAL_ASIA",
"亚太": "ASIA_PACIFIC",
"印太": "INDO_PACIFIC",
"欧洲": "EUROPE",
"东欧": "EASTERN_EUROPE",
"北欧": "NORTHERN_EUROPE",
"NORDIC": "NORTHERN_EUROPE",
"BALTIC": "NORTHERN_EUROPE",
"波罗的海": "NORTHERN_EUROPE",
"西欧": "WESTERN_EUROPE",
"欧盟": "EU",
"北约": "NATO",
"东盟": "ASEAN",
"中东": "MIDDLE_EAST",
"中东北非": "MENA",
"MIDDLE_EAST_NORTH_AFRICA": "MENA",
"美洲": "AMERICAS",
"北美": "NORTH_AMERICA",
"南美": "SOUTH_AMERICA",
"拉美": "SOUTH_AMERICA",
"LATIN_AMERICA": "SOUTH_AMERICA",
"非洲": "AFRICA",
}
_COUNTRY_ALIAS_MAP: dict[str, str] = {
"CN": "CHN",
"CHN": "CHN",
"CHINA": "CHN",
"PRC": "CHN",
"中国": "CHN",
"HK": "CHN",
"HKG": "CHN",
"香港": "CHN",
"MO": "CHN",
"MAC": "CHN",
"澳门": "CHN",
"TW": "CHN",
"TWN": "CHN",
"台湾": "CHN",
"KP": "PRK",
"PRK": "PRK",
"DPRK": "PRK",
"NK": "PRK",
"NKR": "PRK",
"NORTH KOREA": "PRK",
"NORTH_KOREA": "PRK",
"朝鲜": "PRK",
"北朝鲜": "PRK",
"朝鲜民主主义人民共和国": "PRK",
"KR": "KOR",
"KOR": "KOR",
"ROK": "KOR",
"KOREA": "KOR",
"SOUTH KOREA": "KOR",
"SOUTH_KOREA": "KOR",
"韩国": "KOR",
"南韩": "KOR",
"大韩民国": "KOR",
"US": "USA",
"USA": "USA",
"AMERICA": "USA",
"美国": "USA",
"RU": "RUS",
"RUS": "RUS",
"RUSSIA": "RUS",
"俄罗斯": "RUS",
"俄国": "RUS",
"JP": "JPN",
"JPN": "JPN",
"JAPAN": "JPN",
"日本": "JPN",
"UK": "GBR",
"GB": "GBR",
"GBR": "GBR",
"BRITAIN": "GBR",
"英国": "GBR",
"FR": "FRA",
"FRA": "FRA",
"FRANCE": "FRA",
"法国": "FRA",
"DE": "DEU",
"DEU": "DEU",
"GERMANY": "DEU",
"德国": "DEU",
"IN": "IND",
"IND": "IND",
"INDIA": "IND",
"印度": "IND",
"AU": "AUS",
"AUS": "AUS",
"AUSTRALIA": "AUS",
"澳大利亚": "AUS",
"CA": "CAN",
"CAN": "CAN",
"CANADA": "CAN",
"加拿大": "CAN",
"BR": "BRA",
"BRA": "BRA",
"BRAZIL": "BRA",
"巴西": "BRA",
"SG": "SGP",
"SGP": "SGP",
"SINGAPORE": "SGP",
"新加坡": "SGP",
"ID": "IDN",
"IDN": "IDN",
"INDONESIA": "IDN",
"印尼": "IDN",
"VN": "VNM",
"VNM": "VNM",
"VIETNAM": "VNM",
"越南": "VNM",
"TH": "THA",
"THA": "THA",
"THAILAND": "THA",
"泰国": "THA",
"MY": "MYS",
"MYS": "MYS",
"MALAYSIA": "MYS",
"马来西亚": "MYS",
"PH": "PHL",
"PHL": "PHL",
"PHILIPPINES": "PHL",
"菲律宾": "PHL",
"UA": "UKR",
"UKR": "UKR",
"UKRAINE": "UKR",
"乌克兰": "UKR",
"IR": "IRN",
"IRN": "IRN",
"IRAN": "IRN",
"伊朗": "IRN",
"SA": "SAU",
"SAU": "SAU",
"沙特": "SAU",
"TR": "TUR",
"TUR": "TUR",
"TURKEY": "TUR",
"土耳其": "TUR",
"IL": "ISR",
"ISR": "ISR",
"ISRAEL": "ISR",
"以色列": "ISR",
"EG": "EGY",
"EGY": "EGY",
"EGYPT": "EGY",
"埃及": "EGY",
"SO": "SOM",
"SOM": "SOM",
"SOMALIA": "SOM",
"索马里": "SOM",
"YE": "YEM",
"YEM": "YEM",
"YEMEN": "YEM",
"也门": "YEM",
"AE": "ARE",
"ARE": "ARE",
"UAE": "ARE",
"阿联酋": "ARE",
"MN": "MNG",
"MNG": "MNG",
"MONGOLIA": "MNG",
"蒙古": "MNG",
"PL": "POL",
"POL": "POL",
"POLAND": "POL",
"波兰": "POL",
}
def _normalize_country_code(raw: Any) -> str:
text = str(raw or "").strip()
if not text:
return ""
upper = text.upper()
return _COUNTRY_ALIAS_MAP.get(text) or _COUNTRY_ALIAS_MAP.get(upper) or upper
def _normalize_region_preset(raw: Any) -> str | None:
text = str(raw or "").strip()
if not text:
return None
normalized = re.sub(r"[\s-]+", "_", text.upper())
canonical = _REGION_PRESET_ALIASES.get(text) or _REGION_PRESET_ALIASES.get(normalized) or normalized
return canonical[:32] if canonical in SUPPORTED_REGION_PRESETS else None
def _coerce_bounded_float(value: Any, low: float, high: float, default: float) -> float:
if isinstance(value, bool) or not isinstance(value, (int, float, str)):
return default
try:
num = float(value)
except Exception:
return default
return max(low, min(high, num))
def _coerce_bounded_int(value: Any, low: int, high: int, default: int) -> int:
if isinstance(value, bool) or not isinstance(value, (int, float, str)):
return default
try:
num = int(float(value))
except Exception:
return default
return max(low, min(high, num))
def _normalize_zone_color(raw: Any) -> str:
text = str(raw or "").strip().lower()
if re.fullmatch(r"#[0-9a-f]{6}", text):
return text
if re.fullmatch(r"#[0-9a-f]{3}", text):
return "#" + "".join(ch * 2 for ch in text[1:])
return _SCENE_COLOR_NAMES.get(text, "#38bdf8")
def _normalize_influence_zone_candidate(item: dict[str, Any], idx: int) -> dict[str, Any]:
"""Sanitize tolerant LLM-authored influence zone fields before strict Pydantic validation."""
raw_edge = item.get("edge")
edge_dict: dict[str, Any] = {}
hoisted_opacity = None
if isinstance(raw_edge, str):
style = raw_edge.strip().lower()
edge_dict["style"] = style if style in {"soft", "sharp"} else "soft"
elif isinstance(raw_edge, dict):
if "opacity" in raw_edge:
hoisted_opacity = raw_edge.get("opacity")
style = str(raw_edge.get("style") or "soft").strip().lower()
edge_dict["style"] = style if style in {"soft", "sharp"} else "soft"
if "feather_px" in raw_edge:
edge_dict["feather_px"] = _coerce_bounded_float(raw_edge.get("feather_px"), 0.0, 48.0, 22.0)
if "border_width" in raw_edge:
edge_dict["border_width"] = _coerce_bounded_float(raw_edge.get("border_width"), 0.0, 6.0, 1.5)
raw_anim = item.get("animation")
anim_dict: dict[str, Any] = {}
if isinstance(raw_anim, str):
atype = raw_anim.strip().lower()
anim_dict["type"] = atype if atype in {"sweep", "radial", "fade"} else "sweep"
elif isinstance(raw_anim, dict):
atype = str(raw_anim.get("type") or "sweep").strip().lower()
anim_dict["type"] = atype if atype in {"sweep", "radial", "fade"} else "sweep"
if raw_anim.get("direction"):
anim_dict["direction"] = str(raw_anim["direction"])[:32]
if "duration_ms" in raw_anim:
anim_dict["duration_ms"] = _coerce_bounded_int(raw_anim.get("duration_ms"), 150, 8000, 1800)
if "delay_ms" in raw_anim:
anim_dict["delay_ms"] = _coerce_bounded_int(raw_anim.get("delay_ms"), 0, 5000, 0)
raw_shape = item.get("shape")
shape_src = dict(raw_shape) if isinstance(raw_shape, dict) else {
k: item[k]
for k in ("mode", "countries", "country", "iso_codes", "region_preset", "region", "center", "radius_km", "coordinates")
if k in item
}
raw_countries = shape_src.get("countries") if "countries" in shape_src else (shape_src.get("country") or shape_src.get("iso_codes"))
if isinstance(raw_countries, str):
raw_country_items = [raw_countries]
elif isinstance(raw_countries, list):
raw_country_items = raw_countries[:64]
else:
raw_country_items = []
countries_list: list[str] = []
seen_countries: set[str] = set()
for raw_c in raw_country_items:
norm_c = _normalize_country_code(raw_c)
if norm_c and norm_c not in seen_countries:
seen_countries.add(norm_c)
countries_list.append(norm_c)
region_preset = shape_src.get("region_preset") or shape_src.get("region")
region_preset_val = _normalize_region_preset(region_preset)
raw_center = shape_src.get("center")
center_val: list[float] | None = None
if isinstance(raw_center, dict) and "lat" in raw_center and "lon" in raw_center:
center_val = [
_coerce_bounded_float(raw_center.get("lat"), -90.0, 90.0, 0.0),
_coerce_bounded_float(raw_center.get("lon"), -180.0, 180.0, 0.0),
]
elif isinstance(raw_center, (list, tuple)) and len(raw_center) >= 2:
center_val = [
_coerce_bounded_float(raw_center[0], -90.0, 90.0, 0.0),
_coerce_bounded_float(raw_center[1], -180.0, 180.0, 0.0),
]
raw_coords = shape_src.get("coordinates")
coords_val: list[list[list[float]]] = []
if isinstance(raw_coords, list) and raw_coords:
first_coord = raw_coords[0]
# Auto-wrap 2D polygon rings ([[lon, lat], ...]) to MultiPolygon ring list ([[[lon, lat], ...]]).
if (
isinstance(first_coord, (list, tuple))
and first_coord
and isinstance(first_coord[0], (int, float))
):
coords_val = [raw_coords] # type: ignore[list-item]
else:
coords_val = raw_coords[:16]
mode = str(shape_src.get("mode") or "").strip().lower()
if mode not in {"countries", "region_preset", "circle", "polygon"}:
if countries_list:
mode = "countries"
elif region_preset_val:
mode = "region_preset"
elif center_val is not None:
mode = "circle"
elif coords_val:
mode = "polygon"
elif mode == "region_preset" and region_preset_val is None and countries_list:
mode = "countries"
shape_clean: dict[str, Any] = {"mode": mode}
if countries_list:
shape_clean["countries"] = countries_list
if region_preset_val:
shape_clean["region_preset"] = region_preset_val
if center_val is not None:
shape_clean["center"] = center_val
if shape_src.get("radius_km") is not None:
shape_clean["radius_km"] = _coerce_bounded_float(shape_src.get("radius_km"), 20.0, 15000.0, 600.0)
if coords_val:
shape_clean["coordinates"] = coords_val
opacity_raw = item.get("opacity", hoisted_opacity)
candidate: dict[str, Any] = {
"id": str(item.get("id") or f"zone-{idx + 1}").strip()[:64] or f"zone-{idx + 1}",
"label": str(item.get("label") or item.get("name") or item.get("title") or "")[:80],
"color": _normalize_zone_color(item.get("color")),
"opacity": _coerce_bounded_float(opacity_raw, 0.05, 0.9, 0.42),
"z_index": _coerce_bounded_int(item.get("z_index"), -50, 50, 0),
"shape": shape_clean,
}
if edge_dict:
candidate["edge"] = edge_dict
if anim_dict:
candidate["animation"] = anim_dict
return candidate
def validate_influence_zones(raw: Any) -> list[InfluenceZoneSpec]:
"""Validate and bound LLM-proposed influence zones without failing the response."""
if not isinstance(raw, list):
return []
validated: list[InfluenceZoneSpec] = []
for idx, item in enumerate(raw[:12]):
if not isinstance(item, dict):
continue
candidate = _normalize_influence_zone_candidate(item, idx)
shape = candidate.get("shape") or {}
mode = shape.get("mode")
has_renderable_shape = (
(mode == "countries" and bool(shape.get("countries")))
or (mode == "region_preset" and bool(shape.get("region_preset")))
or (mode == "circle" and shape.get("center") is not None)
or (mode == "polygon" and bool(shape.get("coordinates")))
)
if not has_renderable_shape:
logger.warning_event(
"Influence zone candidate rejected due to empty/unrenderable shape",
event="ai_scene.zone.rejected",
context={"index": idx, "mode": mode, "id": candidate.get("id")},
)
continue
try:
validated.append(InfluenceZoneSpec.model_validate(candidate))
except Exception as exc:
logger.warning_event(
"Influence zone candidate rejected",
event="ai_scene.zone.rejected",
context={"index": idx, "error": str(exc)},
)
continue
return validated
class SceneSpec(BaseModel):
model_config = ConfigDict(extra="forbid")
@@ -147,6 +637,7 @@ class SceneSpec(BaseModel):
camera_hint: dict[str, float] | None = None
presentation_key: str | None = None
auto_play_presentation: bool = False
influence_zones: list[InfluenceZoneSpec] = Field(default_factory=list, max_length=12)
class ViewSpec(BaseModel):
@@ -161,6 +652,9 @@ class ViewSpec(BaseModel):
is_drill: bool = False
time_basis: TimeBasis = "retrospective"
cutoff_at: str | None = None
publish_id: str | None = None
mode: str | None = None
focus_year: int | None = None
replay_supported: bool = True
replay_status: Literal["frozen", "incomplete_snapshot"] = "frozen"
replay_notice: str | None = None
@@ -394,6 +888,8 @@ def classify_turn_intent(
"incident_focus": focus,
"time_basis": time_basis,
"cutoff_at": cutoff_at,
"publish_id": ctx.get("publish_id"),
"as_of": ctx.get("as_of"),
"include_drill": include_drill,
"visible_layers": visible_layers,
}
@@ -429,6 +925,8 @@ def classify_turn_intent(
"incident_focus": "overview",
"time_basis": time_basis,
"cutoff_at": cutoff_at,
"publish_id": ctx.get("publish_id"),
"as_of": ctx.get("as_of"),
"include_drill": include_drill,
"visible_layers": visible_layers,
}
@@ -472,7 +970,7 @@ def classify_turn_intent(
elif any(kw in q for kw in ("趋势", "走势", "历年", "演变", "走廊", "2020", "trend", "trajectory")):
workflow_id = "compute.compare"
view_preset = "trend"
elif any(kw in q for kw in ("为什么", "成因", "归因", "稀释", "回落", "剪刀差", "创新", "东数西算", "枢纽", "解释", "why", "explain")):
elif any(kw in q for kw in ("为什么", "成因", "归因", "稀释", "回落", "剪刀差", "创新", "东数西算", "枢纽", "解释", "修订", "改了", "变化", "重述", "why", "explain", "revised")):
workflow_id = "compute.explain_gap"
view_preset = "causal"
elif metric_switched or any(kw in q for kw in ("只看", "切换", "改看", "switch")):
@@ -495,6 +993,8 @@ def classify_turn_intent(
"incident_focus": "overview",
"time_basis": time_basis,
"cutoff_at": cutoff_at,
"publish_id": ctx.get("publish_id"),
"as_of": ctx.get("as_of"),
"include_drill": include_drill,
"visible_layers": visible_layers,
}
@@ -528,6 +1028,7 @@ def compile_compute_view_spec(
series: dict[str, Any],
posture: dict[str, Any],
preset: ViewPreset = "default",
focus_year: int | None = None,
enable_hubs: bool = False,
auto_play: bool = False,
replay_supported: bool = True,
@@ -538,6 +1039,10 @@ def compile_compute_view_spec(
evidence_map = series.get("evidence") or {}
time_basis: TimeBasis = series.get("time_basis") or "retrospective"
cutoff_at = series.get("cutoff_at")
effective_publish_id = series.get("publish_id") or series.get("version") or posture.get("publish_id")
if series.get("snapshot_unavailable"):
replay_supported = False
replay_notice = replay_notice or series.get("notice")
metric_zh, metric_en, default_unit = _METRIC_LABELS.get(mode, ("算力指标", "Compute Metric", "%"))
unit = str(series.get("unit") or default_unit)
effective_replay_notice = replay_notice or (_INCOMPLETE_COMPUTE_REPLAY_NOTICE if not replay_supported else None)
@@ -549,6 +1054,7 @@ def compile_compute_view_spec(
if any(r.get("values", {}).get(c) is not None for c in codes)
]
latest_year = int(observed_rows[-1]["year"]) if observed_rows else (years[-1] if years else None)
effective_focus_year = int(focus_year) if focus_year is not None else latest_year
matrix_rows: list[dict[str, Any]] = []
max_numeric = 0.0
@@ -838,6 +1344,9 @@ def compile_compute_view_spec(
is_drill=False,
time_basis=time_basis,
cutoff_at=cutoff_at,
publish_id=effective_publish_id,
mode=mode,
focus_year=effective_focus_year,
replay_supported=replay_supported,
replay_status="frozen" if replay_supported else "incomplete_snapshot",
replay_notice=effective_replay_notice,
@@ -848,7 +1357,7 @@ def compile_compute_view_spec(
domain="compute",
highlight_entities=highlight_ids,
compute_mode=mode,
focus_year=latest_year,
focus_year=effective_focus_year,
enable_national_hubs=enable_hubs,
presentation_key="compute-posture-cn-us",
auto_play_presentation=auto_play,
@@ -1205,6 +1714,10 @@ async def execute_session_turn(
for k, v in context_override.items():
if v is not None:
merged_ctx[k] = v
if context_override.get("publish_id") and not context_override.get("as_of"):
merged_ctx["as_of"] = None
elif context_override.get("as_of") and not context_override.get("publish_id"):
merged_ctx["publish_id"] = None
routed = classify_turn_intent(question, merged_ctx)
workflow_id = routed["workflow_id"]
@@ -1265,6 +1778,8 @@ async def execute_session_turn(
domain = routed["domain"]
time_basis: TimeBasis = routed["time_basis"]
cutoff_at: str | None = routed["cutoff_at"]
publish_id: str | None = routed.get("publish_id")
as_of: str | None = routed.get("as_of")
run_record = WorkflowRun(
id=run_id,
@@ -1326,11 +1841,14 @@ async def execute_session_turn(
and domain == merged_ctx.get("domain")
and time_basis == (merged_ctx.get("time_basis") or time_basis)
and cutoff_at == merged_ctx.get("cutoff_at")
and publish_id == merged_ctx.get("publish_id")
and as_of == merged_ctx.get("as_of")
and (
domain != "compute"
or (
routed["selected_codes"] == (merged_ctx.get("selected_codes") or routed["selected_codes"])
and routed["mode"] == (merged_ctx.get("mode") or routed["mode"])
and routed["focus_year"] == merged_ctx.get("focus_year")
)
)
)
@@ -1480,8 +1998,17 @@ async def execute_session_turn(
mode=mode,
time_basis=time_basis,
cutoff_at=cutoff_at,
as_of=as_of,
publish_id=publish_id,
)
_check_cancelled()
revision_context: dict[str, Any] | None = None
if is_revision_question(question) and not series.get("snapshot_unavailable"):
revision_context = await build_revision_change_context(
db,
publish_id=series.get("publish_id") or publish_id,
redact=(access.tier != "admin"),
)
posture = await generate_or_get_compute_posture(
db,
countries=codes,
@@ -1509,8 +2036,11 @@ async def execute_session_turn(
question=question,
time_basis=time_basis,
cutoff_at=cutoff_at,
publish_id=publish_id,
as_of=as_of,
series_override=series,
posture_override=posture,
revision_context=revision_context,
ai_client=ai_client if (use_paid_llm and access.can_use_paid_llm) else None,
cancel_event=handle.cancel_event,
)
@@ -1525,6 +2055,7 @@ async def execute_session_turn(
series=series,
posture=posture,
preset=preset,
focus_year=routed["focus_year"],
enable_hubs=enable_hubs,
auto_play=routed["auto_play_presentation"],
)
@@ -1625,6 +2156,8 @@ async def execute_session_turn(
"visible_layers": routed.get("visible_layers") or {},
"time_basis": time_basis,
"cutoff_at": cutoff_at,
"publish_id": publish_id,
"as_of": as_of,
"include_drill": routed["include_drill"],
"active_result_id": subject_key,
"active_revision": revision,
@@ -1670,6 +2203,8 @@ async def execute_session_turn(
"generation_mode": generation_mode,
"time_basis": time_basis,
"cutoff_at": cutoff_at,
"publish_id": view_spec.publish_id,
"as_of": as_of,
"context_state": next_context,
"reply": {
"answer_markdown": answer_md,
@@ -38,7 +38,14 @@ from app.services.collectors.nro_delegated import NRODelegatedPrefixGeoCollector
from app.services.collectors.news_live_streams import NewsLiveStreamsCollector
from app.services.collectors.media_news_archive import MediaNewsArchiveCollector
from app.services.collectors.aisstream import AISStreamCollector
from app.services.collectors.cloud_map import EarthCloudMapCollector
from app.services.collectors.earth_tiles import (
CloudHDTilesCollector,
Sentinel2ImageryCollector,
VIIRSDailyImageryCollector,
)
from app.services.collectors.vessel_ais import VesselAISCollector
from app.services.collectors.wind_gfs import EarthWindGFSCollector
collector_registry.register(TOP500Collector())
collector_registry.register(EpochAIGPUCollector())
@@ -69,6 +76,11 @@ collector_registry.register(NewsLiveStreamsCollector())
collector_registry.register(MediaNewsArchiveCollector())
collector_registry.register(VesselAISCollector())
collector_registry.register(AISStreamCollector())
collector_registry.register(EarthCloudMapCollector())
collector_registry.register(CloudHDTilesCollector())
collector_registry.register(Sentinel2ImageryCollector())
collector_registry.register(VIIRSDailyImageryCollector())
collector_registry.register(EarthWindGFSCollector())
__all__ = [
"BaseCollector",
@@ -105,4 +117,9 @@ __all__ = [
"MediaNewsArchiveCollector",
"VesselAISCollector",
"AISStreamCollector",
"EarthCloudMapCollector",
"CloudHDTilesCollector",
"Sentinel2ImageryCollector",
"VIIRSDailyImageryCollector",
"EarthWindGFSCollector",
]
+32 -18
View File
@@ -7,7 +7,7 @@ from datetime import UTC, datetime
from time import perf_counter
from urllib.parse import urlparse
import httpx
from sqlalchemy import delete, insert, select, text, update
from sqlalchemy import delete, insert, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.collected_data_fields import build_dynamic_metadata, get_record_field
@@ -66,6 +66,15 @@ class BaseCollector(ABC):
self._fetch_is_complete: bool = False
self._fetch_is_sample_fallback: bool = False
self._sample_fallback_reason: Optional[str] = None
self._db_commit_lock: Optional[asyncio.Lock] = asyncio.Lock()
def _get_db_commit_lock(self) -> asyncio.Lock:
"""Return the per-collector lock used to serialize DB session commits."""
lock = getattr(self, "_db_commit_lock", None)
if lock is None:
lock = asyncio.Lock()
self._db_commit_lock = lock
return lock
def _mark_fetch_complete(self, complete: bool = True) -> None:
"""Mark the current fetch payload as a verified full-universe snapshot."""
@@ -157,7 +166,9 @@ class BaseCollector(ABC):
async def update_progress(self, records_processed: int, *, commit: bool = False, force: bool = False):
"""Update task progress - call this during data processing"""
if self._current_task and self._db_session:
if not self._current_task or not self._db_session:
return
async with self._get_db_commit_lock():
self._current_task.records_processed = records_processed
if self._current_task.total_records and self._current_task.total_records > 0:
self._current_task.progress = (
@@ -172,7 +183,9 @@ class BaseCollector(ABC):
await self._publish_task_update(force=force)
async def set_phase(self, phase: str, *, message: str | None = None, reset_progress: bool = True):
if self._current_task and self._db_session:
if not self._current_task or not self._db_session:
return
async with self._get_db_commit_lock():
self._current_task.phase = phase
self._current_task.phase_message = message
if reset_progress:
@@ -198,24 +211,25 @@ class BaseCollector(ABC):
if not self._current_task or not self._db_session:
return
if progress is None and current is not None and total and total > 0:
progress = (current / total) * 100
async with self._get_db_commit_lock():
if progress is None and current is not None and total and total > 0:
progress = (current / total) * 100
if progress is not None:
self._current_task.phase_progress = max(0.0, min(float(progress), 100.0))
if current is not None:
self._current_task.phase_current = max(0, int(current))
if total is not None:
self._current_task.phase_total = max(0, int(total))
if unit is not None:
self._current_task.phase_unit = unit
if message is not None:
self._current_task.phase_message = message
if progress is not None:
self._current_task.phase_progress = max(0.0, min(float(progress), 100.0))
if current is not None:
self._current_task.phase_current = max(0, int(current))
if total is not None:
self._current_task.phase_total = max(0, int(total))
if unit is not None:
self._current_task.phase_unit = unit
if message is not None:
self._current_task.phase_message = message
if commit:
await self._db_session.commit()
if commit:
await self._db_session.commit()
await self._publish_task_update(force=force)
await self._publish_task_update(force=force)
@abstractmethod
async def fetch(self) -> List[Dict[str, Any]]:
@@ -0,0 +1,184 @@
"""Built-in collector for global real-time satellite IR cloud imagery and spatial analytics."""
from __future__ import annotations
from typing import Any
from sqlalchemy import select
from app.core.websocket.broadcaster import broadcaster
from app.models.datasource_config import DataSourceConfig
from app.services.collectors.base import BaseCollector
from app.services.earth_clouds import collect_latest_cloud_frame
class EarthCloudMapCollector(BaseCollector):
"""Collect multi-satellite IR cloud map frames and structured atmospheric analytics."""
name = "global_cloud_map"
priority = "P1"
module = "L2"
frequency_hours = 1
data_type = "cloud_map_record"
fail_on_empty = True
preserve_snapshot_on_failure = True
full_snapshot_reconcile = True
async def _load_override_config(self) -> dict[str, Any]:
if not self._db_session or not callable(getattr(self._db_session, "execute", None)):
return {}
try:
result = await self._db_session.execute(
select(DataSourceConfig)
.where(DataSourceConfig.name == self.name)
.where(DataSourceConfig.is_active.is_(True))
.limit(1)
)
record = result.scalar_one_or_none()
if record and isinstance(record.config, dict):
return {
key: value
for key, value in record.config.items()
if key
in {
"enabled",
"primary_source",
"fallback_source",
"resolution",
"ir_threshold",
"contrast_gamma",
"convective_threshold",
"min_cluster_area_km2",
"polar_feather_enabled",
"max_history_frames",
"request_timeout_seconds",
"geocolor_enabled",
"relief_shading_strength",
"optical_flow_enabled",
}
and value is not None
}
except Exception:
return {}
return {}
async def fetch(self) -> list[dict[str, Any]]:
override = await self._load_override_config()
result = await collect_latest_cloud_frame(self._db_session, override_config=override)
return [result]
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
if not raw_data:
return []
bundle = raw_data[0]
frame = bundle.get("frame") or {}
summary = bundle.get("global_summary") or {}
regions = bundle.get("regions") or []
clusters = bundle.get("convective_clusters") or []
version = str(frame.get("version") or "")
captured_at = frame.get("captured_at")
source_used = str(frame.get("source") or "multi_sat_ir")
satellites = list(frame.get("satellites") or [])
degraded = bool(frame.get("degraded", False))
records: list[dict[str, Any]] = [
{
"source_id": "cloud_snapshot:latest",
"name": "全球实时红外云图快照",
"title": f"全球云图 {version}",
"description": (
f"来源={source_used}, 全球平均云量={summary.get('global_cloud_cover_pct')}%, "
f"强对流云团={summary.get('convective_cluster_count', 0)} 个"
),
"latitude": 0.0,
"longitude": 0.0,
"value": summary.get("global_cloud_cover_pct"),
"unit": "%",
"reference_date": captured_at,
"metadata": {
"record_kind": "cloud_map_snapshot",
"version": version,
"captured_at": captured_at,
"cloud_source": source_used,
"satellites": satellites,
"degraded": degraded,
"resolution": frame.get("resolution"),
"image_url": frame.get("image_url"),
"file_size_bytes": frame.get("file_size_bytes"),
"sha256": frame.get("sha256"),
**summary,
},
}
]
for region in regions:
key = str(region.get("key") or "")
records.append(
{
"source_id": f"cloud_region:{key}",
"name": str(region.get("name") or key),
"title": f"区域云量 · {region.get('name') or key}",
"description": (
f"云量 {region.get('cloud_cover_pct')}%, "
f"厚云 {region.get('overcast_coverage_pct')}%, "
f"最低亮温 {region.get('min_brightness_temp_c')}°C"
),
"latitude": region.get("center_lat"),
"longitude": region.get("center_lon"),
"value": region.get("cloud_cover_pct"),
"unit": "%",
"reference_date": captured_at,
"metadata": {
"record_kind": "cloud_region_summary",
"version": version,
"captured_at": captured_at,
**region,
},
}
)
for cluster in clusters:
cid = str(cluster.get("cluster_id") or "")
records.append(
{
"source_id": f"cloud_cluster:{cid}",
"name": f"强对流云团 {cid} ({cluster.get('region') or ''})",
"title": f"强对流核 {cid} · {cluster.get('min_brightness_temp_c')}°C",
"description": (
f"估算面积 {cluster.get('area_km2')} km², "
f"峰值强度 {cluster.get('peak_intensity')}%, "
f"最低亮温 {cluster.get('min_brightness_temp_c')}°C"
),
"latitude": cluster.get("latitude"),
"longitude": cluster.get("longitude"),
"value": cluster.get("area_km2"),
"unit": "km2",
"reference_date": captured_at,
"metadata": {
"record_kind": "cloud_convective_cluster",
"version": version,
"captured_at": captured_at,
**cluster,
},
}
)
return records
async def run(self, db) -> dict[str, Any]:
result = await super().run(db)
if result.get("status") == "success":
try:
await broadcaster.broadcast_earth_update(
{
"event": "earth.layer.changed",
"action": "cloud_map_updated",
"source": self.name,
"layers": ["clouds"],
"refresh_strategy": "reload",
}
)
except Exception:
pass
return result
@@ -0,0 +1,106 @@
"""Collectors for NASA/EOX Earth tile pyramids (`cloud_hd_tiles`, Sentinel-2, VIIRS)."""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from app.core.logging import get_logger
from app.core.time import to_iso8601_utc
from app.core.websocket.broadcaster import broadcaster
from app.services.collectors.base import BaseCollector
from app.services.earth_tiles import TILE_SOURCES, warmup_tile_source
logger = get_logger(__name__, service="collector.earth_tiles")
class _BaseEarthTileCollector(BaseCollector):
"""Base BaseCollector implementation for managed Web-Mercator tile pyramids."""
priority = "P2"
module = "L1"
frequency_hours = 24
data_type = "earth_tile_pyramid"
fail_on_empty = False
preserve_snapshot_on_failure = True
full_snapshot_reconcile = True
broadcast_layer = "basemap"
async def fetch(self) -> list[dict[str, Any]]:
summary = await warmup_tile_source(self.name, db=self._db_session)
return [summary]
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
if not raw_data:
return []
summary = raw_data[0]
cache_stats = summary.get("cache_stats") or {}
tile_count = int(cache_stats.get("tile_count") or 0)
total_mb = float(cache_stats.get("total_mb") or 0.0)
captured_at = to_iso8601_utc(datetime.now(UTC))
return [
{
"source_id": f"tile_pyramid:{self.name}",
"name": self.name,
"title": f"瓦片金字塔预热 · {self.name} (Z0–Z{summary.get('warmup_max_zoom', 3)})",
"description": (
f"新抓取 {summary.get('fetched', 0)} 块,缓存命中 {summary.get('cached_hits', 0)} 块,"
f"累计 {tile_count} 块 ({total_mb} MB)"
),
"latitude": 0.0,
"longitude": 0.0,
"value": tile_count,
"unit": "tiles",
"reference_date": captured_at,
"metadata": {
"record_kind": "earth_tile_pyramid",
"captured_at": captured_at,
**summary,
},
}
]
async def run(self, db) -> dict[str, Any]:
result = await super().run(db)
if result.get("status") == "success":
try:
await broadcaster.broadcast_earth_update(
{
"event": "earth.layer.changed",
"action": "tile_pyramid_warmed",
"source": self.name,
"layers": [self.broadcast_layer],
"refresh_strategy": "reload",
}
)
except Exception:
pass
return result
class CloudHDTilesCollector(_BaseEarthTileCollector):
name = "cloud_hd_tiles"
priority = "P1"
module = "L2"
frequency_hours = 1
broadcast_layer = "clouds"
class Sentinel2ImageryCollector(_BaseEarthTileCollector):
name = "earth_imagery_sentinel2"
frequency_hours = 24
broadcast_layer = "basemap"
class VIIRSDailyImageryCollector(_BaseEarthTileCollector):
name = "earth_imagery_viirs_daily"
frequency_hours = 12
broadcast_layer = "basemap"
__all__ = [
"TILE_SOURCES",
"CloudHDTilesCollector",
"Sentinel2ImageryCollector",
"VIIRSDailyImageryCollector",
]
+26 -25
View File
@@ -116,16 +116,17 @@ class IPtoASNPrefixGeoCollector(BaseCollector):
]
total_expected = sum(expected_sizes) if expected_sizes else 0
if total_expected > 0 and self._current_task and self._db_session:
self._current_task.total_records = total_expected
self._current_task.records_processed = 0
self._current_task.progress = 0.0
self._current_task.phase_progress = 0.0
self._current_task.phase_message = "正在下载 IPtoASN 数据"
self._current_task.phase_current = 0
self._current_task.phase_total = total_expected
self._current_task.phase_unit = "bytes"
await self._db_session.commit()
await self._publish_task_update(force=True)
async with self._get_db_commit_lock():
self._current_task.total_records = total_expected
self._current_task.records_processed = 0
self._current_task.progress = 0.0
self._current_task.phase_progress = 0.0
self._current_task.phase_message = "正在下载 IPtoASN 数据"
self._current_task.phase_current = 0
self._current_task.phase_total = total_expected
self._current_task.phase_unit = "bytes"
await self._db_session.commit()
await self._publish_task_update(force=True)
url_progress: dict[str, int] = {url: 0 for url in dataset_urls}
progress_lock = asyncio.Lock()
@@ -136,29 +137,29 @@ class IPtoASNPrefixGeoCollector(BaseCollector):
if total_expected <= 0:
return
async with progress_lock:
current = max(0, downloaded_bytes)
if current < url_progress[url]:
url_downloaded = max(0, downloaded_bytes)
if url_downloaded < url_progress[url]:
return
url_progress[url] = current
url_progress[url] = url_downloaded
aggregated = sum(url_progress.values())
now = time.monotonic()
current = min(aggregated, total_expected)
should_emit = (
aggregated >= total_expected
or aggregated - last_emit["value"] >= min_emit_bytes
or now - last_emit["t"] >= 2.0
(current >= total_expected and last_emit["value"] < total_expected)
or current - last_emit["value"] >= min_emit_bytes
or (current > last_emit["value"] and now - last_emit["t"] >= 2.0)
)
if not should_emit:
return
last_emit["value"] = aggregated
last_emit["value"] = current
last_emit["t"] = now
current = min(aggregated, total_expected)
await self.update_phase_progress(
current=current,
total=total_expected,
unit="bytes",
message="正在下载 IPtoASN 数据",
)
await self.update_progress(current, commit=True)
await self.update_phase_progress(
current=current,
total=total_expected,
unit="bytes",
message="正在下载 IPtoASN 数据",
)
await self.update_progress(current, commit=True)
dataset_paths = await asyncio.gather(
*(
@@ -52,9 +52,11 @@ class SpaceTrackTLECollector(BaseCollector):
async def fetch(self) -> List[Dict[str, Any]]:
from app.core.config import settings
from app.services.datasource_connectivity import resolve_spacetrack_credentials
username = settings.SPACETRACK_USERNAME
password = settings.SPACETRACK_PASSWORD
username, password, _ = await resolve_spacetrack_credentials(self._db_session)
username = username or settings.SPACETRACK_USERNAME
password = password or settings.SPACETRACK_PASSWORD
if not username or not password:
logger.warning_event(
+144
View File
@@ -0,0 +1,144 @@
"""Collector for NOAA NCEP GFS 10m global wind field (`global_wind_gfs`)."""
from __future__ import annotations
from typing import Any
from app.core.logging import get_logger
from app.core.websocket.broadcaster import broadcaster
from app.services.collectors.base import BaseCollector
from app.services.earth_wind import WIND_REGIONS, collect_latest_wind_grid
logger = get_logger(__name__, service="collector.wind_gfs")
_REGION_COORDS = {
item["key"]: (
(float(item["lat_min"]) + float(item["lat_max"])) / 2.0,
(float(item["lon_min"]) + float(item["lon_max"])) / 2.0,
)
for item in WIND_REGIONS
}
class EarthWindGFSCollector(BaseCollector):
"""Collect NOAA NCEP GFS global 10m wind field grids and regional gale analytics."""
name = "global_wind_gfs"
priority = "P1"
module = "L2"
frequency_hours = 3
data_type = "wind_field_record"
fail_on_empty = True
preserve_snapshot_on_failure = True
full_snapshot_reconcile = True
async def fetch(self) -> list[dict[str, Any]]:
result = await collect_latest_wind_grid(db=self._db_session)
return [result]
def transform(self, raw_data: list[dict[str, Any]]) -> list[dict[str, Any]]:
if not raw_data:
return []
bundle = raw_data[0]
run = bundle.get("run") or {}
summary = bundle.get("global_summary") or {}
regions = bundle.get("regions") or []
cores = bundle.get("storm_cores") or []
version = str(run.get("version") or "")
captured_at = run.get("captured_at")
forecast_time = run.get("forecast_time")
records: list[dict[str, Any]] = [
{
"source_id": "wind_snapshot:latest",
"name": "全球 10m 地面风场快照 (NOAA GFS)",
"title": f"全球风场 {version}",
"description": (
f"全球均速={summary.get('mean_speed_ms')} m/s, 峰值={summary.get('max_speed_ms')} m/s, "
f"大风核心={summary.get('storm_core_count', 0)} 个"
),
"latitude": 0.0,
"longitude": 0.0,
"value": summary.get("mean_speed_ms"),
"unit": "m/s",
"reference_date": captured_at,
"metadata": {
"record_kind": "wind_field_snapshot",
"version": version,
"captured_at": captured_at,
"forecast_time": forecast_time,
**summary,
},
}
]
for reg in regions:
key = str(reg.get("key") or "")
center_lat, center_lon = _REGION_COORDS.get(key, (0.0, 0.0))
records.append(
{
"source_id": f"wind_region:{key}",
"name": str(reg.get("name") or key),
"title": f"区域风场 · {reg.get('name') or key}",
"description": (
f"均速 {reg.get('mean_speed_ms')} m/s, 峰值 {reg.get('max_speed_ms')} m/s, "
f"主导风向 {reg.get('dominant_cardinal')}"
),
"latitude": center_lat,
"longitude": center_lon,
"value": reg.get("mean_speed_ms"),
"unit": "m/s",
"reference_date": captured_at,
"metadata": {
"record_kind": "wind_region_summary",
"version": version,
"captured_at": captured_at,
**reg,
},
}
)
for core in cores:
cid = str(core.get("id") or "")
records.append(
{
"source_id": f"wind_core:{cid}",
"name": f"大风核心 {cid} ({core.get('region') or ''})",
"title": f"大风中心 {cid} · {core.get('max_speed_ms')} m/s",
"description": (
f"估算面积 {core.get('area_km2')} km², "
f"蒲福 {core.get('beaufort')} 级"
),
"latitude": core.get("lat"),
"longitude": core.get("lon"),
"value": core.get("max_speed_ms"),
"unit": "m/s",
"reference_date": captured_at,
"metadata": {
"record_kind": "wind_storm_core",
"version": version,
"captured_at": captured_at,
**core,
},
}
)
return records
async def run(self, db) -> dict[str, Any]:
result = await super().run(db)
if result.get("status") == "success":
try:
await broadcaster.broadcast_earth_update(
{
"event": "earth.layer.changed",
"action": "wind_grid_updated",
"source": self.name,
"layers": ["windField"],
"refresh_strategy": "reload",
}
)
except Exception:
pass
return result
@@ -648,6 +648,7 @@ def _context_to_query(
"sources": list(context.get("sources") or []),
"source_url": context.get("source_url") or "",
"builds_upon": context.get("builds_upon") or "",
"cross_source_hints": list(context.get("cross_source_hints") or []),
},
)
@@ -984,6 +985,50 @@ def resolve_compute_center_location_full(
)
def collect_high_precision_local_candidates(
*,
name: str | None = None,
source: str | None = None,
source_id: str | None = None,
operator: str | None = None,
site: str | None = None,
city: str | None = None,
country: str | None = None,
organization: str | None = None,
sources: list[str] | None = None,
source_url: str | None = None,
builds_upon: str | None = None,
source_raw_country: str | None = None,
include_builds_upon: bool = True,
) -> tuple[list[LocationCandidate], list[str]]:
"""Run high-precision local resolvers (VerifiedSite, BuildsUpon) before external lookups."""
query = build_compute_center_location_query(
name=name,
source=source,
source_id=source_id,
operator=operator,
site=site,
city=city,
country=country,
organization=organization,
sources=sources,
source_url=source_url,
builds_upon=builds_upon,
source_raw_country=source_raw_country,
)
resolvers: list[Any] = [
ComputeCenterSourceCoordinatesResolver(),
VerifiedComputeSiteResolver(),
]
if include_builds_upon:
resolvers.append(BuildsUponComputeCenterResolver())
pipeline = LocationPipeline(
resolvers,
sort_key=_compute_center_candidate_sort_key,
)
return pipeline.collect_candidates(query)
def collect_location_candidates(
*,
name: str | None = None,
@@ -999,6 +1044,9 @@ def collect_location_candidates(
source_url: str | None = None,
builds_upon: str | None = None,
source_raw_country: str | None = None,
include_builds_upon: bool = True,
include_ror: bool = True,
include_nominatim: bool = True,
) -> tuple[list[LocationCandidate], list[str]]:
"""Run the full resolution chain and return ranked candidates with attempted queries."""
query = build_compute_center_location_query(
@@ -1015,7 +1063,30 @@ def collect_location_candidates(
builds_upon=builds_upon,
source_raw_country=source_raw_country,
)
return COMPUTE_CENTER_COLLECTION_PIPELINE.collect_candidates(query)
if include_builds_upon and include_ror and include_nominatim:
return COMPUTE_CENTER_COLLECTION_PIPELINE.collect_candidates(query)
resolvers: list[Any] = [
ComputeCenterSourceCoordinatesResolver(),
VerifiedComputeSiteResolver(),
]
if include_builds_upon:
resolvers.append(BuildsUponComputeCenterResolver())
if include_ror:
resolvers.append(ROROrganizationResolver())
if include_nominatim:
resolvers.append(
NominatimResolver(
query_plan_builder=_compute_center_query_plan,
geocoder=lambda q: _geocode_online(q),
)
)
pipeline = LocationPipeline(
resolvers,
sort_key=_compute_center_candidate_sort_key,
failure_reason=COMPUTE_CENTER_COLLECTION_PIPELINE._failure_reason,
)
return pipeline.collect_candidates(query)
def build_compute_center_location_query(
@@ -1032,6 +1103,7 @@ def build_compute_center_location_query(
source_url: str | None = None,
builds_upon: str | None = None,
source_raw_country: str | None = None,
cross_source_hints: list[dict[str, Any]] | None = None,
) -> LocationQuery:
name_value = coerce_str(name)
context: dict[str, Any] = {
@@ -1048,6 +1120,7 @@ def build_compute_center_location_query(
"source_url": coerce_str(source_url),
"builds_upon": coerce_str(builds_upon),
"source_raw_country": coerce_str(source_raw_country),
"cross_source_hints": list(cross_source_hints or []),
}
return _context_to_query(context)
@@ -1199,4 +1272,12 @@ async def upsert_compute_center_location(
await session.commit()
await session.refresh(record)
await refresh_compute_center_location_cache(session)
try:
from app.core.cache import cache
from app.services.earth_layer_cache import invalidate_earth_layer_cache_for_source
invalidate_earth_layer_cache_for_source("compute_center_locations")
cache.delete_pattern("data_ledger:*")
except Exception:
pass
return record
+482 -40
View File
@@ -1,42 +1,272 @@
"""Database overrides with bundled defaults and atomic, revision-checked publishing."""
"""Database overrides with versioned revision ledger, as-of replay, and atomic publishing."""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
import hashlib
import json
from pathlib import Path
from typing import Any
from uuid import uuid4
from fastapi import HTTPException
from sqlalchemy import desc, select
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.request_context import get_request_id
from app.core.time import to_iso8601_utc
from app.models.compute_configuration_revision import ComputeConfigurationRevision
from app.models.situational_assessment import ComputeEvidenceCandidate
from app.models.system_log import AuditLog
from app.models.system_setting import SystemSetting
from app.models.user import User
from app.schemas.compute_configuration import ComputeConfiguration
from app.schemas.compute_configuration import (
SHARE_METRICS,
ComputeConfiguration,
has_mixed_sources,
)
from app.services.compute_catalog import COUNTRY_CATALOG
from fastapi import HTTPException
from sqlalchemy import select
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from app.services.compute_revision_diff import (
diff_compute_configurations,
has_observation_value_delta,
summarize_diff,
)
CATEGORY = "compute_comparison"
DEFAULT_PATH = Path(__file__).with_name("compute_history_defaults.json")
DEFAULT_CONFIGURATION = ComputeConfiguration.model_validate_json(DEFAULT_PATH.read_text())
DEFAULT_REVISION = hashlib.sha256(DEFAULT_PATH.read_bytes()).hexdigest()
INCOMPLETE_SNAPSHOT_NOTICE = (
"历史快照不完整:所选系统发布时间早于版本库基线时间,无法还原当时的系统台账。"
)
def default_envelope() -> dict:
def compute_content_fingerprint(config: ComputeConfiguration | dict[str, Any]) -> str:
"""Return canonical SHA-256 hex digest of a compute configuration payload."""
payload = (
config.model_dump(mode="json")
if isinstance(config, ComputeConfiguration)
else ComputeConfiguration.model_validate(config).model_dump(mode="json")
)
canonical = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
DEFAULT_CONTENT_FINGERPRINT = compute_content_fingerprint(DEFAULT_CONFIGURATION)
def default_envelope() -> dict[str, Any]:
return {
"config": DEFAULT_CONFIGURATION.model_dump(mode="json"),
"revision": DEFAULT_REVISION,
"publish_id": DEFAULT_REVISION,
"published_at": None,
"action": "baseline",
"is_default": True,
"snapshot_unavailable": False,
}
async def read_configuration(db: AsyncSession) -> dict:
def _dialect_name(db: AsyncSession) -> str:
bind = getattr(db, "bind", None)
name = getattr(getattr(bind, "dialect", None), "name", None)
if isinstance(name, str) and name:
return name
getter = getattr(db, "get_bind", None)
# Avoid invoking AsyncMock attributes as coroutines in unit tests.
if callable(getter) and not hasattr(getter, "assert_awaited"):
try:
resolved = getter()
name = getattr(getattr(resolved, "dialect", None), "name", None)
if isinstance(name, str) and name:
return name
except Exception:
pass
return ""
def _is_relational_session(db: AsyncSession) -> bool:
return _dialect_name(db) in {"postgresql", "sqlite"}
def _parse_as_of(as_of: datetime | str | None) -> datetime | None:
if as_of is None:
return None
if isinstance(as_of, datetime):
return as_of.astimezone(UTC) if as_of.tzinfo else as_of.replace(tzinfo=UTC)
raw = str(as_of).strip()
if not raw:
return None
try:
if len(raw) == 10 and raw[4] == "-" and raw[7] == "-":
return datetime.fromisoformat(f"{raw}T23:59:59.999999+00:00")
normalized = raw.replace("Z", "+00:00")
# Recover '+' decoded as space in unencoded URL query strings (e.g. '...52.97 00:00').
if "T" in normalized and " " in normalized:
date_part, tz_part = normalized.rsplit(" ", 1)
if len(tz_part) == 5 and tz_part[2] == ":" and tz_part[:2].isdigit() and tz_part[3:].isdigit():
normalized = f"{date_part}+{tz_part}"
parsed = datetime.fromisoformat(normalized)
return parsed.astimezone(UTC) if parsed.tzinfo else parsed.replace(tzinfo=UTC)
except ValueError as exc:
raise HTTPException(422, f"Invalid as_of timestamp: {as_of}") from exc
def _db_timestamp(dt: datetime, dialect: str) -> datetime:
utc_dt = dt.astimezone(UTC) if dt.tzinfo else dt.replace(tzinfo=UTC)
if dialect == "sqlite":
return utc_dt.replace(tzinfo=None)
return utc_dt
def _envelope_from_revision(
row: ComputeConfigurationRevision,
*,
as_of_dt: datetime | None = None,
) -> dict[str, Any]:
return {
"config": dict(row.config_payload or {}),
"revision": row.publish_id,
"publish_id": row.publish_id,
"published_at": to_iso8601_utc(row.published_at),
"action": row.action,
"is_default": bool(row.is_default_content),
"as_of": to_iso8601_utc(as_of_dt) if as_of_dt else None,
"snapshot_unavailable": False,
"presentation_status": row.presentation_status,
}
def _normalize_cached_envelope(payload: dict[str, Any]) -> dict[str, Any]:
out = dict(payload)
rev = out.get("revision") or out.get("publish_id") or DEFAULT_REVISION
out["revision"] = rev
out["publish_id"] = rev
out.setdefault("published_at", None)
out.setdefault("action", "baseline" if out.get("is_default") else "publish")
out.setdefault("is_default", False)
out.setdefault("snapshot_unavailable", False)
return out
async def ensure_compute_revision_baseline(
db: AsyncSession,
*,
commit: bool = True,
published_at: datetime | None = None,
) -> ComputeConfigurationRevision | None:
"""Idempotently seal the initial compute configuration baseline into the revision ledger."""
if not _is_relational_session(db):
return None
existing = (
await db.execute(
select(ComputeConfigurationRevision)
.order_by(ComputeConfigurationRevision.id.asc())
.limit(1)
)
).scalar_one_or_none()
if isinstance(existing, ComputeConfigurationRevision):
return existing
setting_row = (
await db.execute(select(SystemSetting).where(SystemSetting.category == CATEGORY))
).scalar_one_or_none()
if setting_row is not None and isinstance(setting_row.payload, dict):
config_dict = dict(setting_row.payload.get("config") or default_envelope()["config"])
publish_id = str(setting_row.payload.get("revision") or DEFAULT_REVISION)
else:
config_dict = default_envelope()["config"]
publish_id = DEFAULT_REVISION
fp = compute_content_fingerprint(config_dict)
now = published_at or datetime.now(UTC)
dialect = _dialect_name(db)
baseline = ComputeConfigurationRevision(
publish_id=publish_id,
parent_publish_id=None,
action="baseline",
content_fingerprint=fp,
is_default_content=(fp == DEFAULT_CONTENT_FINGERPRINT),
config_payload=config_dict,
diff_summary=[],
source_candidate_ids=[],
publish_note="",
published_by_id=None,
published_by_name=None,
published_by_role=None,
published_at=_db_timestamp(now, dialect),
presentation_status="skipped",
presentation_attempts=0,
presentation_error="",
)
db.add(baseline)
await db.flush()
if commit:
await db.commit()
return baseline
async def read_configuration(
db: AsyncSession,
*,
as_of: datetime | str | None = None,
publish_id: str | None = None,
) -> dict[str, Any]:
"""Read current, pinned `publish_id`, or `as_of` historical compute configuration."""
as_of_dt = _parse_as_of(as_of)
pid = (publish_id or "").strip() or None
dialect = _dialect_name(db)
if pid is not None:
row = (
await db.execute(
select(ComputeConfigurationRevision).where(
ComputeConfigurationRevision.publish_id == pid
)
)
).scalar_one_or_none()
if not isinstance(row, ComputeConfigurationRevision):
raise HTTPException(404, f"Compute configuration revision not found: {pid}")
return _envelope_from_revision(row, as_of_dt=as_of_dt)
if as_of_dt is not None:
bound_ts = _db_timestamp(as_of_dt, dialect)
row = (
await db.execute(
select(ComputeConfigurationRevision)
.where(ComputeConfigurationRevision.published_at <= bound_ts)
.order_by(
desc(ComputeConfigurationRevision.published_at),
desc(ComputeConfigurationRevision.id),
)
.limit(1)
)
).scalar_one_or_none()
if not isinstance(row, ComputeConfigurationRevision):
return {
"config": None,
"revision": None,
"publish_id": None,
"published_at": None,
"action": None,
"is_default": False,
"as_of": to_iso8601_utc(as_of_dt),
"snapshot_unavailable": True,
"notice": INCOMPLETE_SNAPSHOT_NOTICE,
}
return _envelope_from_revision(row, as_of_dt=as_of_dt)
record = (
await db.execute(select(SystemSetting).where(SystemSetting.category == CATEGORY))
).scalar_one_or_none()
return dict(record.payload) if record else default_envelope()
if record is not None and isinstance(record.payload, dict):
return _normalize_cached_envelope(record.payload)
return default_envelope()
def configuration_response(envelope: dict) -> dict:
def configuration_response(envelope: dict[str, Any]) -> dict[str, Any]:
return {
**envelope,
"countries": [
@@ -46,6 +276,46 @@ def configuration_response(envelope: dict) -> dict:
}
async def _load_locked_setting(db: AsyncSession, dialect: str) -> SystemSetting:
if dialect == "postgresql":
await db.execute(
pg_insert(SystemSetting)
.values(category=CATEGORY, payload=default_envelope())
.on_conflict_do_nothing(index_elements=[SystemSetting.category])
)
return (
await db.execute(
select(SystemSetting)
.where(SystemSetting.category == CATEGORY)
.with_for_update()
)
).scalar_one()
if dialect == "sqlite":
existing = (
await db.execute(select(SystemSetting).where(SystemSetting.category == CATEGORY))
).scalar_one_or_none()
if existing is None:
existing = SystemSetting(category=CATEGORY, payload=default_envelope())
db.add(existing)
await db.flush()
return existing
# Fallback for mock DB sessions in isolated unit tests.
await db.execute(
pg_insert(SystemSetting)
.values(category=CATEGORY, payload=default_envelope())
.on_conflict_do_nothing(index_elements=[SystemSetting.category])
)
return (
await db.execute(
select(SystemSetting)
.where(SystemSetting.category == CATEGORY)
.with_for_update()
)
).scalar_one()
async def publish_configuration(
db: AsyncSession,
*,
@@ -53,47 +323,219 @@ async def publish_configuration(
config: ComputeConfiguration,
actor: User,
reset: bool = False,
) -> dict:
# The unique category plus row lock also serializes concurrent first writes.
await db.execute(
insert(SystemSetting)
.values(category=CATEGORY, payload=default_envelope())
.on_conflict_do_nothing(index_elements=[SystemSetting.category])
)
record = (
await db.execute(
select(SystemSetting).where(SystemSetting.category == CATEGORY).with_for_update()
)
).scalar_one()
if record.payload["revision"] != revision:
publish_note: str = "",
source_candidate_ids: list[int] | None = None,
) -> dict[str, Any]:
"""Atomically publish or reset compute configuration, writing revision history and cache together."""
dialect = _dialect_name(db)
relational = dialect in {"postgresql", "sqlite"}
record = await _load_locked_setting(db, dialect)
before = _normalize_cached_envelope(record.payload)
current_publish_id = str(before["revision"])
if current_publish_id != revision:
await db.rollback()
raise HTTPException(409, "Configuration changed. Reload before saving your edits.")
envelope = (
default_envelope()
if reset
else {
"config": config.model_dump(mode="json"),
"revision": uuid4().hex,
"is_default": reset,
effective_config = DEFAULT_CONFIGURATION if reset else config
note = (publish_note or "").strip()
candidate_ids = list(dict.fromkeys(int(cid) for cid in (source_candidate_ids or [])))
old_config = ComputeConfiguration.model_validate(before["config"])
old_fp = compute_content_fingerprint(old_config)
new_config_dict = effective_config.model_dump(mode="json")
new_fp = compute_content_fingerprint(effective_config)
if new_fp == old_fp and (not reset or bool(before.get("is_default"))):
return {
**before,
"publish_id": current_publish_id,
"no_changes": True,
"presentation_status": "skipped",
}
)
before = record.payload
if reset:
await db.delete(record)
else:
record.payload = envelope
# Audit and configuration commit together: a published edit must be attributable.
# Share-metric mixed-source guard (M2): require explicit denominator note in publish_note.
if not reset and not note:
for obs in effective_config.observations:
if obs.metric in SHARE_METRICS and has_mixed_sources(obs):
await db.rollback()
raise HTTPException(
422,
"跨报告局部修订份额数据时,必须在发布说明中写明同分母依据。",
)
referenced_candidates: list[ComputeEvidenceCandidate] = []
if candidate_ids and relational:
found = (
(
await db.execute(
select(ComputeEvidenceCandidate).where(
ComputeEvidenceCandidate.id.in_(candidate_ids)
)
)
)
.scalars()
.all()
)
by_id = {c.id: c for c in found}
for cid in candidate_ids:
cand = by_id.get(cid)
if cand is None or cand.status != "approved" or cand.published_publish_id:
await db.rollback()
raise HTTPException(
422,
f"候选证据 #{cid} 不存在、未审核通过或已随其他版本发布。",
)
referenced_candidates.append(cand)
now = datetime.now(UTC)
if relational:
latest_rev = (
await db.execute(
select(ComputeConfigurationRevision)
.order_by(desc(ComputeConfigurationRevision.id))
.limit(1)
)
).scalar_one_or_none()
if not isinstance(latest_rev, ComputeConfigurationRevision):
latest_rev = await ensure_compute_revision_baseline(
db, commit=False, published_at=now - timedelta(milliseconds=1)
)
if latest_rev is not None and latest_rev.published_at is not None:
prev_ts = latest_rev.published_at
prev_utc = prev_ts.astimezone(UTC) if prev_ts.tzinfo else prev_ts.replace(tzinfo=UTC)
if now <= prev_utc:
now = prev_utc + timedelta(milliseconds=1)
diff_summary = diff_compute_configurations(old_config, effective_config)
new_publish_id = uuid4().hex
is_default_content = new_fp == DEFAULT_CONTENT_FINGERPRINT
action = "reset" if reset else "publish"
presentation_status = "pending" if has_observation_value_delta(diff_summary) else "skipped"
envelope: dict[str, Any] = {
"config": new_config_dict,
"revision": new_publish_id,
"publish_id": new_publish_id,
"published_at": to_iso8601_utc(now),
"action": action,
"is_default": is_default_content,
"no_changes": False,
"presentation_status": presentation_status,
"snapshot_unavailable": False,
}
if relational:
revision_row = ComputeConfigurationRevision(
publish_id=new_publish_id,
parent_publish_id=current_publish_id,
action=action,
content_fingerprint=new_fp,
is_default_content=is_default_content,
config_payload=new_config_dict,
diff_summary=diff_summary,
source_candidate_ids=candidate_ids,
publish_note=note,
published_by_id=getattr(actor, "id", None),
published_by_name=getattr(actor, "username", None),
published_by_role=getattr(actor, "role", None),
published_at=_db_timestamp(now, dialect),
presentation_status=presentation_status,
presentation_attempts=0,
presentation_error="",
)
db.add(revision_row)
for cand in referenced_candidates:
cand.published_publish_id = new_publish_id
# Keep SystemSetting as synchronized current-version cache (never delete on reset).
record.payload = {
"config": new_config_dict,
"revision": new_publish_id,
"publish_id": new_publish_id,
"published_at": to_iso8601_utc(now),
"action": action,
"is_default": is_default_content,
}
db.add(
AuditLog(
actor_id=actor.id,
actor_name=actor.username,
actor_id=getattr(actor, "id", None),
actor_name=getattr(actor, "username", None),
action="compute_comparison.reset" if reset else "compute_comparison.update",
target_type="system_setting",
target_id=CATEGORY,
result="success",
request_id=get_request_id(),
details={"before": before, "after": envelope},
details={
"before": before,
"after": envelope,
"publish_id": new_publish_id,
"parent_publish_id": current_publish_id,
"publish_note": note,
"source_candidate_ids": candidate_ids,
"diff_summary": diff_summary[:25],
},
)
)
await db.commit()
return envelope
async def list_configuration_revisions(
db: AsyncSession,
*,
limit: int = 20,
redact: bool = False,
) -> list[dict[str, Any]]:
"""List recent compute configuration revisions newest first."""
bounded = max(1, min(int(limit), 100))
rows = (
(
await db.execute(
select(ComputeConfigurationRevision)
.order_by(desc(ComputeConfigurationRevision.id))
.limit(bounded)
)
)
.scalars()
.all()
)
items: list[dict[str, Any]] = []
for row in rows:
change_count, summary_text = summarize_diff(row.diff_summary or [], action=row.action)
if redact:
items.append(
{
"id": row.id,
"publish_id": row.publish_id,
"action": row.action,
"published_at": to_iso8601_utc(row.published_at),
"is_default_content": bool(row.is_default_content),
"change_count": change_count,
"summary": summary_text,
}
)
else:
items.append(
{
"id": row.id,
"publish_id": row.publish_id,
"parent_publish_id": row.parent_publish_id,
"action": row.action,
"published_at": to_iso8601_utc(row.published_at),
"is_default_content": bool(row.is_default_content),
"change_count": change_count,
"summary": summary_text,
"diff_summary": list(row.diff_summary or []),
"publish_note": row.publish_note or "",
"published_by_name": row.published_by_name,
"published_by_role": row.published_by_role,
"source_candidate_ids": list(row.source_candidate_ids or []),
"presentation_status": row.presentation_status,
"presentation_attempts": int(row.presentation_attempts or 0),
"presentation_error": row.presentation_error or "",
"presentation_delivered_at": to_iso8601_utc(row.presentation_delivered_at),
}
)
return items
+46 -4
View File
@@ -4,7 +4,12 @@ from copy import deepcopy
from datetime import date
from typing import Literal
from app.schemas.compute_configuration import ComputeConfiguration, ComputeObservation
from app.schemas.compute_configuration import (
ComputeConfiguration,
ComputeObservation,
has_mixed_sources,
source_for,
)
from app.services.compute_catalog import (
CATALOG,
DEFAULT_PARTICIPANTS,
@@ -130,6 +135,8 @@ def _latest_bilateral_pair(
"rpi_percent": round(cn_val / us_val * 100, 1),
"gap_pp": round(cn_val - us_val, 2),
"evidence_id": latest.source_id,
"cn_evidence_id": source_for(latest, "CN"),
"us_evidence_id": source_for(latest, "US"),
}
if len(candidates) >= 2:
prev = candidates[-2]
@@ -161,6 +168,8 @@ def _build_bilateral_rpi(config: ComputeConfiguration, enabled: bool) -> dict |
"rpi_percent": round(row.values["CN"] / row.values["US"] * 100, 1),
"gap_pp": round(row.values["CN"] - row.values["US"], 2),
"evidence_id": row.source_id,
"cn_evidence_id": source_for(row, "CN"),
"us_evidence_id": source_for(row, "US"),
}
for row in total_rows
]
@@ -203,7 +212,7 @@ def _build_denominator_attribution(
"latest_value": latest.values[country],
"latest_global_total": latest.global_total,
"unit": "EFlop/s (FP32)",
"evidence_ids": [latest.source_id],
"evidence_ids": [source_for(latest, country)],
}
denom_rows = [row for row in country_rows if row.global_total and row.global_total > 0]
if len(denom_rows) >= 2:
@@ -227,7 +236,9 @@ def _build_denominator_attribution(
"global_to": curr_global,
"global_growth_pct": round(global_growth, 1),
"diluted_by_global_expansion": global_growth > country_growth,
"evidence_ids": list(dict.fromkeys([prev_row.source_id, curr_row.source_id])),
"evidence_ids": list(
dict.fromkeys([source_for(prev_row, country), source_for(curr_row, country)])
),
}
)
elif len(country_rows) >= 2:
@@ -243,7 +254,9 @@ def _build_denominator_attribution(
"country_from": prev_val,
"country_to": curr_val,
"country_growth_pct": round((curr_val - prev_val) / prev_val * 100, 1),
"evidence_ids": list(dict.fromkeys([prev_row.source_id, curr_row.source_id])),
"evidence_ids": list(
dict.fromkeys([source_for(prev_row, country), source_for(curr_row, country)])
),
}
)
result[code] = entry
@@ -294,8 +307,19 @@ def compute_history(
record = annual.get(year)
observations = record.values if record else {}
values, coverage = {}, {}
evidence_by_code: dict[str, list[str]] = {}
for code, members in members_by_participant.items():
values[code], coverage[code] = _participant_value(members, observations, mode)
if record is not None:
evidence_by_code[code] = list(
dict.fromkeys(
source_for(record, member)
for member in members
if member in record.values
)
)
else:
evidence_by_code[code] = []
evidence_id = record.source_id if record else None
rows.append(
{
@@ -305,6 +329,8 @@ def compute_history(
"coverage": coverage,
"global_total": record.global_total if record else None,
"evidence_id": evidence_id,
"evidence_by_code": evidence_by_code,
"mixed_sources": has_mixed_sources(record) if record else False,
}
)
@@ -314,12 +340,28 @@ def compute_history(
code: _participant_value(members, share_obs, "global_share")[0]
for code, members in members_by_participant.items()
}
share_evidence_by_code = {
code: (
list(
dict.fromkeys(
source_for(share_record, member)
for member in members
if member in share_record.values
)
)
if share_record is not None
else []
)
for code, members in members_by_participant.items()
}
divergence_rows.append(
{
"year": year,
"period_label": (share_record.period_label or str(year)) if share_record else None,
"values": share_values,
"evidence_id": share_record.source_id if share_record else None,
"evidence_by_code": share_evidence_by_code,
"mixed_sources": has_mixed_sources(share_record) if share_record else False,
}
)
+430
View File
@@ -0,0 +1,430 @@
"""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,
}
@@ -0,0 +1,311 @@
"""Pure diff utilities for versioned compute comparison configurations."""
from __future__ import annotations
from typing import Any
from app.schemas.compute_configuration import (
ComputeConfiguration,
ComputeObservation,
source_for,
)
METRIC_ZH_LABELS: dict[str, str] = {
"global_share": "全球总算力份额",
"intelligent_share": "全球智能算力份额",
"absolute": "计算设备总规模",
"frontier_cluster_share": "前沿智算集群份额",
"chip_inflow_share": "高端算力芯片流向份额",
}
COUNTRY_ZH_LABELS: dict[str, str] = {
"CN": "中国",
"US": "美国",
"JP": "日本",
"DE": "德国",
"GB": "英国",
"FR": "法国",
"KR": "韩国",
"IN": "印度",
}
def _observation_key(row: ComputeObservation) -> tuple[str, int]:
return (row.metric, row.year)
def _diff_keyed_section(
section: str,
old_items: dict[Any, dict[str, Any]],
new_items: dict[Any, dict[str, Any]],
) -> dict[str, Any] | None:
old_keys = set(old_items)
new_keys = set(new_items)
added = len(new_keys - old_keys)
removed = len(old_keys - new_keys)
modified = sum(1 for key in (old_keys & new_keys) if old_items[key] != new_items[key])
if not (added or removed or modified):
return None
return {
"kind": "section_changed",
"section": section,
"added": added,
"removed": removed,
"modified": modified,
}
def diff_compute_configurations(
old: ComputeConfiguration,
new: ComputeConfiguration,
) -> list[dict[str, Any]]:
"""Compute structured observation-level diffs and section-level counts between two configs."""
diffs: list[dict[str, Any]] = []
old_obs = {_observation_key(row): row for row in old.observations}
new_obs = {_observation_key(row): row for row in new.observations}
all_keys = sorted(set(old_obs) | set(new_obs), key=lambda k: (k[0], k[1]))
for metric, year in all_keys:
old_row = old_obs.get((metric, year))
new_row = new_obs.get((metric, year))
if old_row is None and new_row is not None:
diffs.append(
{
"kind": "observation_row_added",
"metric": metric,
"year": year,
"period_label": new_row.period_label,
}
)
for code in sorted(new_row.values):
new_val = float(new_row.values[code])
diffs.append(
{
"kind": "observation_value",
"metric": metric,
"year": year,
"period_label": new_row.period_label,
"code": code,
"old_value": None,
"new_value": new_val,
"delta": round(new_val, 4),
"change_kind": "new_observation",
"old_source_id": None,
"new_source_id": source_for(new_row, code),
}
)
continue
if old_row is not None and new_row is None:
diffs.append(
{
"kind": "observation_row_removed",
"metric": metric,
"year": year,
"period_label": old_row.period_label,
}
)
for code in sorted(old_row.values):
old_val = float(old_row.values[code])
diffs.append(
{
"kind": "observation_value",
"metric": metric,
"year": year,
"period_label": old_row.period_label,
"code": code,
"old_value": old_val,
"new_value": None,
"delta": round(-old_val, 4),
"change_kind": "observation_removed",
"old_source_id": source_for(old_row, code),
"new_source_id": None,
}
)
continue
assert old_row is not None and new_row is not None
if (old_row.period_label or None) != (new_row.period_label or None):
diffs.append(
{
"kind": "period_label_changed",
"metric": metric,
"year": year,
"old": old_row.period_label,
"new": new_row.period_label,
}
)
for code in sorted(set(old_row.values) | set(new_row.values)):
has_old = code in old_row.values
has_new = code in new_row.values
old_val = float(old_row.values[code]) if has_old else None
new_val = float(new_row.values[code]) if has_new else None
old_src = source_for(old_row, code) if has_old else None
new_src = source_for(new_row, code) if has_new else None
if old_val is None and new_val is not None:
diffs.append(
{
"kind": "observation_value",
"metric": metric,
"year": year,
"period_label": new_row.period_label,
"code": code,
"old_value": None,
"new_value": new_val,
"delta": round(new_val, 4),
"change_kind": "new_observation",
"old_source_id": None,
"new_source_id": new_src,
}
)
elif old_val is not None and new_val is None:
diffs.append(
{
"kind": "observation_value",
"metric": metric,
"year": year,
"period_label": new_row.period_label,
"code": code,
"old_value": old_val,
"new_value": None,
"delta": round(-old_val, 4),
"change_kind": "observation_removed",
"old_source_id": old_src,
"new_source_id": None,
}
)
elif old_val is not None and new_val is not None:
delta = round(new_val - old_val, 4)
if delta != 0:
diffs.append(
{
"kind": "observation_value",
"metric": metric,
"year": year,
"period_label": new_row.period_label,
"code": code,
"old_value": old_val,
"new_value": new_val,
"delta": delta,
"change_kind": "historical_revision",
"old_source_id": old_src,
"new_source_id": new_src,
}
)
elif old_src != new_src:
diffs.append(
{
"kind": "observation_value",
"metric": metric,
"year": year,
"period_label": new_row.period_label,
"code": code,
"old_value": old_val,
"new_value": new_val,
"delta": 0.0,
"change_kind": "source_reattributed",
"old_source_id": old_src,
"new_source_id": new_src,
}
)
section_specs = [
(
"sources",
{s.id: s.model_dump(mode="json") for s in old.sources},
{s.id: s.model_dump(mode="json") for s in new.sources},
),
(
"innovation",
{row.year: row.model_dump(mode="json") for row in old.innovation},
{row.year: row.model_dump(mode="json") for row in new.innovation},
),
(
"structures",
{(row.scope, row.year): row.model_dump(mode="json") for row in old.structures},
{(row.scope, row.year): row.model_dump(mode="json") for row in new.structures},
),
(
"milestones",
{row.id: row.model_dump(mode="json") for row in old.milestones},
{row.id: row.model_dump(mode="json") for row in new.milestones},
),
(
"national_hubs",
{row.id: row.model_dump(mode="json") for row in old.national_hubs},
{row.id: row.model_dump(mode="json") for row in new.national_hubs},
),
]
for section_name, old_map, new_map in section_specs:
entry = _diff_keyed_section(section_name, old_map, new_map)
if entry is not None:
diffs.append(entry)
return diffs
def has_observation_value_delta(diff_summary: list[dict[str, Any]]) -> bool:
"""Return True when diff_summary contains at least one non-zero observation value delta."""
return any(
item.get("kind") == "observation_value"
and item.get("delta") is not None
and float(item["delta"]) != 0.0
for item in (diff_summary or [])
)
def format_diff_entry(entry: dict[str, Any]) -> str:
"""Render a concise Chinese summary string for one diff_summary entry."""
kind = entry.get("kind")
if kind == "observation_value":
metric = METRIC_ZH_LABELS.get(str(entry.get("metric") or ""), str(entry.get("metric") or ""))
year = entry.get("year")
code = str(entry.get("code") or "")
country = COUNTRY_ZH_LABELS.get(code, code)
unit = " EFlops" if entry.get("metric") == "absolute" else "%"
change_kind = entry.get("change_kind")
if change_kind == "historical_revision":
delta = float(entry.get("delta") or 0.0)
delta_unit = " EFlops" if entry.get("metric") == "absolute" else "pp"
return (
f"{year} 年 {metric} {country} "
f"{entry.get('old_value')}{unit} → {entry.get('new_value')}{unit}({delta:+.2g}{delta_unit})"
)
if change_kind == "new_observation":
return f"新增 {year} 年 {metric} {country} {entry.get('new_value')}{unit}"
if change_kind == "observation_removed":
return f"移除 {year} 年 {metric} {country}(原 {entry.get('old_value')}{unit})"
if change_kind == "source_reattributed":
return f"{year} 年 {metric} {country} 来源变更:{entry.get('old_source_id')} → {entry.get('new_source_id')}"
if kind == "period_label_changed":
return f"{entry.get('year')} 年统计周期标签变更:{entry.get('old') or '全年'} → {entry.get('new') or '全年'}"
if kind == "observation_row_added":
return f"新增 {entry.get('year')} 年 {METRIC_ZH_LABELS.get(str(entry.get('metric') or ''), entry.get('metric'))} 观测行"
if kind == "observation_row_removed":
return f"移除 {entry.get('year')} 年 {METRIC_ZH_LABELS.get(str(entry.get('metric') or ''), entry.get('metric'))} 观测行"
if kind == "section_changed":
return (
f"{entry.get('section')} 变更(+{entry.get('added', 0)} / "
f"-{entry.get('removed', 0)} / ~{entry.get('modified', 0)})"
)
return "配置已更新"
def summarize_diff(diff_summary: list[dict[str, Any]], action: str = "publish") -> tuple[int, str]:
"""Return (change_count, first_summary) suitable for revision lists."""
entries = list(diff_summary or [])
if not entries:
if action == "baseline":
return 0, "初始基线封存"
if action == "reset":
return 0, "恢复内置权威报告数据"
return 0, "无观测数值变更"
primary = next(
(item for item in entries if item.get("kind") == "observation_value"),
entries[0],
)
return len(entries), format_diff_entry(primary)
+27
View File
@@ -131,9 +131,36 @@ AISSTREAM_DEFAULT_GUIDE = CredentialGuideDefault(
)
SPACETRACK_DEFAULT_GUIDE = CredentialGuideDefault(
provider="spacetrack",
title="Space-Track TLE 凭证获取教程",
prompt=(
"请生成一份中文教程,指导开发者注册并获取 Space-Track.org 的账号凭证并配置到 Planet。"
"包含注册登录、遵循查询频率限制(如 GP 查询间隔)、在 Planet 采集器配置页填写用户名与密码、"
"测试连通性与常见失败排查。请以 Space-Track 当前官网文档为准。"
),
markdown="""## Space-Track TLE 凭证获取
官方入口:https://www.space-track.org/
1. 前往 Space-Track.org 注册或登录账号。
2. 确认账号已完成邮箱激活且可正常通过网站登录。
3. 回到 Planet 的「采集管理 -> 采集器配置 -> `spacetrack_tle`」。
4. 填写 `用户名` 与 `密码`(或通过环境变量 `SPACETRACK_USERNAME` / `SPACETRACK_PASSWORD` 注入)。
5. 点击「连接测试」验证登录态与 TLE 查询接口后点击「保存」。
### 注意事项
- Space-Track 对 GP 数据接口有严格的限频策略,请避免高频手动重复抓取。
- 本源使用表单会话登录(`/ajaxauth/login`),不要将账号密码当作普通 HTTP Basic Header 暴露。
""",
)
DEFAULT_CREDENTIAL_GUIDES = {
BARENTSWATCH_DEFAULT_GUIDE.provider: BARENTSWATCH_DEFAULT_GUIDE,
AISSTREAM_DEFAULT_GUIDE.provider: AISSTREAM_DEFAULT_GUIDE,
SPACETRACK_DEFAULT_GUIDE.provider: SPACETRACK_DEFAULT_GUIDE,
}
+14
View File
@@ -628,6 +628,18 @@ async def _clear_derived_datasource_data_in_batches(
progress_offset=progress_offset + sum(deleted_counts.values()),
)
return deleted_counts
if source == "global_cloud_map":
from app.services.earth_clouds import clear_all_cloud_map_artifacts
return {"cloud_map_artifacts": clear_all_cloud_map_artifacts()}
if source in {"cloud_hd_tiles", "earth_imagery_sentinel2", "earth_imagery_viirs_daily"}:
from app.services.earth_tiles import clear_tile_source_cache
return {"tile_cache_files": clear_tile_source_cache(source)}
if source == "global_wind_gfs":
from app.services.earth_wind import clear_all_wind_artifacts
return {"wind_artifacts": clear_all_wind_artifacts()}
return await clear_derived_datasource_data(db, source)
@@ -638,6 +650,8 @@ async def _run_clear_cache_job(db: AsyncSession, task: CollectionTask) -> None:
earth_deleted_count = invalidate_earth_layer_cache_for_source(source)
dashboard_deleted_count = int(cache.delete("dashboard:stats")) + int(cache.delete("dashboard:summary"))
cache.delete_pattern("collected:*")
cache.delete_pattern("data_ledger:*")
deleted_count = earth_deleted_count + dashboard_deleted_count
task.records_processed = deleted_count
+299 -36
View File
@@ -3,10 +3,13 @@
from __future__ import annotations
from datetime import UTC, datetime
import csv
import hashlib
import io
import json
import os
from typing import Any
from urllib.parse import urlparse
import httpx
from sqlalchemy import func, select
@@ -17,6 +20,7 @@ from app.core.enums import JobStatus
from app.models.collected_data import CollectedData
from app.models.datasource import DataSource
from app.models.datasource_config import DataSourceConfig
from app.models.earth_news import EarthNewsItem
from app.models.system_setting import SystemSetting
from app.services.barentswatch import (
BarentsWatchConfig,
@@ -29,6 +33,26 @@ from app.services.barentswatch import (
CONNECTIVITY_VALIDATION_KEY = "connectivity_validation"
CONNECTIVITY_STORE_CATEGORY = "datasource_connectivity_validations"
SUPPORTED_CREDENTIAL_PROVIDERS = {"barentswatch", "spacetrack", "aisstream"}
_ARCGIS_SOURCES = frozenset(
{"arcgis_cables", "arcgis_landing_points", "arcgis_cable_landing_relation"}
)
_EPOCH_CSV_URL = "https://epoch.ai/data/gpu_clusters.csv"
def _is_masked_secret(value: Any) -> bool:
if not isinstance(value, str):
return False
stripped = value.strip()
return bool(stripped) and set(stripped) <= {"•", "*"}
def _clean_override_value(override: dict[str, str] | None, key: str, *, secret: bool = False) -> str:
if not isinstance(override, dict):
return ""
raw = str(override.get(key) or "").strip()
if not raw or (secret and _is_masked_secret(raw)):
return ""
return raw
def _sha256_json(payload: Any) -> str:
@@ -46,26 +70,68 @@ def _resolve_spacetrack_credentials() -> tuple[str, str, str]:
return username, password, source or "missing"
def _resolve_spacetrack_credentials_with_override(
async def resolve_spacetrack_credentials(
db=None,
credential_override: dict[str, str] | None = None,
) -> tuple[str, str, str]:
if credential_override and (
credential_override.get("username") or credential_override.get("password")
):
return (
str(credential_override.get("username") or ""),
str(credential_override.get("password") or ""),
"draft",
)
return _resolve_spacetrack_credentials()
"""Resolve Space-Track credentials (`draft override -> DataSourceConfig -> env -> ~/.zshrc`)."""
db_user = ""
db_pass = ""
if db is not None and hasattr(db, "execute"):
try:
result = await db.execute(
select(DataSourceConfig)
.where(DataSourceConfig.name == "spacetrack_tle")
.where(DataSourceConfig.is_active.is_(True))
)
record = result.scalar_one_or_none()
if record is not None:
auth_cfg = record.auth_config or {}
runtime_cfg = record.config or {}
db_user = str(auth_cfg.get("username") or runtime_cfg.get("username") or "").strip()
db_pass = str(auth_cfg.get("password") or runtime_cfg.get("password") or "").strip()
except Exception:
db_user = ""
db_pass = ""
env_user, env_pass, env_source = _resolve_spacetrack_credentials()
username = db_user or env_user
password = db_pass or env_pass
source = "datasource_config" if (db_user or db_pass) else env_source
ov_user = _clean_override_value(credential_override, "username")
ov_pass = _clean_override_value(credential_override, "password", secret=True)
if ov_user or ov_pass:
return ov_user or username, ov_pass or password, "draft"
return username, password, source or "missing"
async def _resolve_barentswatch_with_override(
db,
endpoint: str,
credential_override: dict[str, str] | None = None,
) -> BarentsWatchConfig:
"""Resolve BarentsWatch credentials merging partial draft overrides with saved config."""
saved = await resolve_barentswatch_config(db)
ov_id = _clean_override_value(credential_override, "client_id")
ov_secret = _clean_override_value(credential_override, "client_secret", secret=True)
has_override = bool(ov_id or ov_secret)
return BarentsWatchConfig(
endpoint=str(endpoint or "").strip() or saved.endpoint,
client_id=ov_id or saved.client_id,
client_secret=ov_secret or saved.client_secret,
credential_source="draft" if has_override else saved.credential_source,
endpoint_source="draft" if str(endpoint or "").strip() else saved.endpoint_source,
)
async def _resolve_aisstream_api_key(
db=None,
credential_override: dict[str, str] | None = None,
) -> tuple[str, str]:
if credential_override and credential_override.get("api_key"):
return str(credential_override["api_key"]), "draft"
ov_key = _clean_override_value(credential_override, "api_key", secret=True)
if ov_key:
return ov_key, "draft"
env_key = os.getenv("AISSTREAM_API_KEY")
zshrc_key = _read_zshrc_env().get("AISSTREAM_API_KEY")
@@ -125,15 +191,12 @@ async def build_builtin_connectivity_checksum(
has_credentials = not defaults.get("requires_credentials", False)
if credential_provider == "barentswatch":
if credential_override:
client_id = credential_override.get("client_id", "")
client_secret = credential_override.get("client_secret", "")
credential_source = "draft"
else:
barentswatch_config = await resolve_barentswatch_config(db)
client_id = barentswatch_config.client_id
client_secret = barentswatch_config.client_secret
credential_source = barentswatch_config.credential_source
barentswatch_config = await _resolve_barentswatch_with_override(
db, endpoint, credential_override
)
client_id = barentswatch_config.client_id
client_secret = barentswatch_config.client_secret
credential_source = barentswatch_config.credential_source
has_credentials = bool(client_id and client_secret)
credential_fingerprint = _sha256_json(
{
@@ -142,8 +205,8 @@ async def build_builtin_connectivity_checksum(
}
)
elif credential_provider == "spacetrack":
username, password, credential_source = _resolve_spacetrack_credentials_with_override(
credential_override
username, password, credential_source = await resolve_spacetrack_credentials(
db, credential_override
)
has_credentials = bool(username and password)
credential_fingerprint = _sha256_json(
@@ -176,6 +239,173 @@ async def build_builtin_connectivity_checksum(
}
def _prepare_builtin_http_probe(
source: str,
endpoint: str,
headers: dict[str, str],
) -> tuple[str, Any, dict[str, str]]:
"""Build lightweight protocol-accurate probe URL, params, and headers for a built-in source."""
probe_url = str(endpoint or "").strip()
probe_params: Any = None
probe_headers = dict(headers)
if source == "bgpstream_bgp":
base = probe_url.rstrip("/")
probe_url = base if base.endswith("/data") else f"{base}/data"
end = int(datetime.now(UTC).timestamp()) - 3600
start = end - 3600
probe_params = [
("projects[]", "routeviews"),
("collectors[]", "route-views2"),
("types[]", "updates"),
("intervals[]", f"{start},{end}"),
]
probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)")
elif source == "celestrak_tle":
if "?" not in probe_url:
probe_params = {"CATNR": "25544", "FORMAT": "json"}
elif source in _ARCGIS_SOURCES:
if probe_url.rstrip("/").endswith("/query") and "f=" not in probe_url:
probe_params = {"where": "1=1", "returnCountOnly": "true", "f": "json"}
elif source == "epoch_ai_gpu":
parsed = urlparse(probe_url)
if parsed.hostname == "epoch.ai" and not parsed.path.endswith(".csv"):
probe_url = _EPOCH_CSV_URL
elif source == "ris_live_bgp":
probe_headers.setdefault(
"X-RIS-Subscribe",
json.dumps({"host": "rrc00", "type": "UPDATE", "require": "announcements"}),
)
probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)")
elif source == "global_cloud_map":
if "SERVICE=" not in probe_url.upper():
probe_params = {
"SERVICE": "WMS",
"REQUEST": "GetMap",
"VERSION": "1.1.1",
"LAYERS": "Himawari_AHI_Band13_Clean_Infrared",
"STYLES": "",
"FORMAT": "image/png",
"TRANSPARENT": "true",
"SRS": "EPSG:4326",
"BBOX": "-180,-90,180,90",
"WIDTH": "64",
"HEIGHT": "32",
}
probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)")
elif source in {"cloud_hd_tiles", "earth_imagery_sentinel2", "earth_imagery_viirs_daily"}:
probe_url = (
probe_url.replace("{z}", "0")
.replace("{y}", "0")
.replace("{x}", "0")
)
probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)")
elif source == "global_wind_gfs":
if "?" not in probe_url:
probe_url = (
f"{probe_url}?ugrd10m[(last)][(-10):10:(10)][(0):10:(10)],"
"vgrd10m[(last)][(-10):10:(10)][(0):10:(10)]"
)
probe_headers.setdefault("User-Agent", "Planet-Intelligence-System/1.0 (Python/collector)")
return probe_url, probe_params, probe_headers
async def _read_bounded_probe_bytes(response: httpx.Response, limit: int = 65536) -> bytes:
chunks: list[bytes] = []
size = 0
async for chunk in response.aiter_bytes():
chunks.append(chunk)
size += len(chunk)
if size >= limit:
break
return b"".join(chunks)[:limit]
async def _validate_builtin_probe_response(source: str, response: httpx.Response) -> str | None:
"""Validate response content for sources that return HTTP 200 even on invalid queries."""
if source == "ris_live_bgp":
first_line = ""
async for line in response.aiter_lines():
stripped = line.strip()
if stripped:
first_line = stripped
break
if not first_line:
return "RIS Live 流未返回任何有效消息。"
try:
payload = json.loads(first_line)
except json.JSONDecodeError:
return "RIS Live 返回非 JSON 响应。"
return None if isinstance(payload, dict) else "RIS Live 响应结构异常。"
if source in {
"global_cloud_map",
"cloud_hd_tiles",
"earth_imagery_sentinel2",
"earth_imagery_viirs_daily",
}:
content_type = str(response.headers.get("content-type") or "").lower()
if not content_type.startswith("image/"):
return f"遥感影像上游未返回图像内容(content-type={content_type or 'unknown'})。"
return None
if source == "global_wind_gfs":
raw = await _read_bounded_probe_bytes(response, limit=8192)
text = raw.decode(response.encoding or "utf-8", errors="replace").strip()
if not text:
return "GFS 风场 ERDDAP 响应为空。"
if "ugrd10m" in text and "vgrd10m" in text:
return None
first_row = next(csv.reader(io.StringIO(text)), [])
if len(first_row) >= 5:
try:
float(first_row[1])
float(first_row[2])
float(first_row[3])
float(first_row[4])
return None
except ValueError:
pass
return "GFS 风场 ERDDAP 响应格式异常(缺少有效风矢量列)。"
if source not in _ARCGIS_SOURCES | {"bgpstream_bgp", "celestrak_tle", "epoch_ai_gpu"}:
return None
limit = 4096 if source == "epoch_ai_gpu" else 65536
raw = await _read_bounded_probe_bytes(response, limit=limit)
text = raw.decode(response.encoding or "utf-8", errors="replace").lstrip("\ufeff").strip()
if source == "epoch_ai_gpu":
if text.lower().startswith(("<!doctype", "<html")):
return "Epoch AI 返回了 HTML 页面而非 CSV 数据集。"
first_line = next((line for line in text.splitlines() if line.strip()), "")
headers_row = next(csv.reader(io.StringIO(first_line)), [])
if not {"Name", "Country"}.issubset(set(headers_row)):
return "Epoch AI CSV 表头校验失败(缺少 Name / Country)。"
return None
if source == "celestrak_tle":
if text.lower().startswith("invalid query"):
return f"CelesTrak 参数校验失败:{text[:120]}"
try:
parsed = json.loads(text)
except json.JSONDecodeError:
return "CelesTrak 未返回有效 JSON。"
return None if isinstance(parsed, list) else "CelesTrak 返回格式不是 JSON 数组。"
try:
parsed_obj = json.loads(text)
except json.JSONDecodeError:
return "接口返回了非 JSON 内容(可能是 HTML 错误页)。"
if not isinstance(parsed_obj, dict):
return "接口返回的 JSON 结构无效。"
if parsed_obj.get("error"):
return f"上游接口报错:{str(parsed_obj['error'])[:120]}"
if source == "bgpstream_bgp" and "data" not in parsed_obj:
return "BGPStream Broker 响应缺少 data 字段。"
return None
async def test_builtin_connectivity(
source: str,
endpoint: str,
@@ -223,6 +453,27 @@ async def test_builtin_connectivity(
**credential_context,
}
if source == "media_news_archive":
if db is not None and hasattr(db, "execute"):
try:
await db.execute(select(func.count(EarthNewsItem.id)))
except Exception as exc:
return {
"success": False,
"checksum": checksum,
"stage": "internal",
"message": f"本地新闻归档表检查失败:{exc.__class__.__name__}",
"error": str(exc),
**credential_context,
}
return {
"success": True,
"checksum": checksum,
"stage": "internal",
"message": "内部新闻归档采集器无需外部连接,本地数据源正常。",
**credential_context,
}
request_headers = {str(key): str(value) for key, value in (headers or {}).items()}
request_config = strip_connectivity_validation(config)
timeout = float(request_config.get("timeout") or 30)
@@ -245,19 +496,15 @@ async def test_builtin_connectivity(
**credential_context,
}
probe_url, probe_params, request_headers = _prepare_builtin_http_probe(
source, request_endpoint, request_headers
)
try:
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
if credential_context["credential_provider"] == "barentswatch":
if credential_override:
barentswatch_config = BarentsWatchConfig(
endpoint=str(request_endpoint or ""),
client_id=str(credential_override.get("client_id") or ""),
client_secret=str(credential_override.get("client_secret") or ""),
credential_source="draft",
endpoint_source="draft",
)
else:
barentswatch_config = await resolve_barentswatch_config(db)
barentswatch_config = await _resolve_barentswatch_with_override(
db, request_endpoint, credential_override
)
token = await fetch_barentswatch_access_token(client, barentswatch_config)
if not token:
return {
@@ -270,8 +517,8 @@ async def test_builtin_connectivity(
}
request_headers["Authorization"] = f"Bearer {token}"
elif credential_context["credential_provider"] == "spacetrack":
username, password, _source = _resolve_spacetrack_credentials_with_override(
credential_override
username, password, _source = await resolve_spacetrack_credentials(
db, credential_override
)
login_url = "https://www.space-track.org/ajaxauth/login"
login_response = await client.post(
@@ -284,10 +531,26 @@ async def test_builtin_connectivity(
login_response.raise_for_status()
started = datetime.now(UTC)
async with client.stream("GET", request_endpoint, headers=request_headers) as response:
async with client.stream(
"GET",
probe_url,
params=probe_params,
headers=request_headers,
) as response:
response.raise_for_status()
status_code = response.status_code
body_error = await _validate_builtin_probe_response(source, response)
elapsed_ms = (datetime.now(UTC) - started).total_seconds() * 1000
if body_error:
return {
"success": False,
"checksum": checksum,
"stage": "endpoint",
"message": body_error,
"error": body_error,
"status_code": status_code,
**credential_context,
}
return {
"success": True,
+381 -241
View File
@@ -1,13 +1,22 @@
"""Earth boundary static asset service."""
"""Earth boundary PMTiles artifact service.
Sources are downloaded once per build into the persistent boundary data
directory, the China POV builder (``scripts/build_earth_boundary_pmtiles.py``)
produces a versioned PMTiles archive plus small hover assets, and the API
serves them with HTTP Range support. Web and desktop clients share the same
``/api/v1/earth/boundaries/...`` URLs.
"""
from __future__ import annotations
import asyncio
import hashlib
import json
import os
import shutil
import subprocess
import sys
import tempfile
import zipfile
from datetime import UTC, datetime
from functools import lru_cache
from pathlib import Path
@@ -16,17 +25,21 @@ from uuid import uuid4
import httpx
from app.core.logging import get_logger
logger = get_logger(__name__)
REPO_ROOT = Path(__file__).resolve().parents[3]
SOURCE_OUTPUT_DIR = REPO_ROOT / "data/earth-boundary-sources"
SOURCE_MANIFEST_PATH = SOURCE_OUTPUT_DIR / "manifest.json"
BUILD_RESULT_PATH = SOURCE_OUTPUT_DIR / "build-result.json"
BUILD_JOB_PATH = SOURCE_OUTPUT_DIR / "build-job.json"
BOUNDARY_OUTPUT_DIR = REPO_ROOT / "frontend/public/earth/data/boundaries/v1"
BOUNDARY_MANIFEST_PATH = BOUNDARY_OUTPUT_DIR / "manifest.json"
PMTILES_ARTIFACT_PATH = (
REPO_ROOT / "frontend/public/earth/data/boundaries/earth-boundaries-china-pov-v1.pmtiles"
BOUNDARY_DATA_DIR = Path(
os.environ.get("PLANET_EARTH_BOUNDARY_DIR") or REPO_ROOT / "backend/data/earth-boundaries"
)
SOURCE_OUTPUT_DIR = BOUNDARY_DATA_DIR / "sources"
SOURCE_MANIFEST_PATH = SOURCE_OUTPUT_DIR / "manifest.json"
BUILD_RESULT_PATH = BOUNDARY_DATA_DIR / "build-result.json"
BUILD_JOB_PATH = BOUNDARY_DATA_DIR / "build-job.json"
BOUNDARY_OUTPUT_DIR = BOUNDARY_DATA_DIR / "artifacts"
BOUNDARY_MANIFEST_PATH = BOUNDARY_OUTPUT_DIR / "manifest.json"
POLICY_FALLBACK_PATH = (
REPO_ROOT / "frontend/public/earth/data/countries-admin0.china-pov-v1.geojson"
)
@@ -34,36 +47,78 @@ POV_POLICY_PATH = REPO_ROOT / "config/earth-boundary-pov-policy.china-v1.json"
POV_GEOMETRY_PATH = REPO_ROOT / "resources/earth/boundary-pov-geometry.china-v1.json"
LOCAL_CONFIG_PATH = REPO_ROOT / "config/earth-boundary-sources.local.json"
EXAMPLE_CONFIG_PATH = REPO_ROOT / "config/earth-boundary-sources.example.json"
BUILDER_PATH = REPO_ROOT / "scripts/build_earth_boundary_pmtiles.py"
BUILDER_MODULE_PATHS = (
BUILDER_PATH,
REPO_ROOT / "scripts/earth_boundary_geometry.py",
REPO_ROOT / "scripts/earth_boundary_policy.py",
)
MANIFEST_SCHEMA = "planet-earth-boundaries/v2"
REQUIRED_TOOLS = ("tippecanoe",)
REQUIRED_POLICY_RULES = {"china-taiwan-penghu", "china-hong-kong", "china-macao", "kosovo"}
DOWNLOAD_CHUNK_BYTES = 1024 * 1024
BOUNDARY_SOURCE_KINDS = {
"earth_admin0_boundaries": "admin0-boundaries",
"earth_coastline": "coastline",
"earth_disputed_lines": "disputed-lines",
"earth_claim_lines": "claim-lines",
"earth_admin1_lines": "admin1-lines",
"earth_populated_places": "populated-places",
}
_NE_GEOJSON = "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson"
DEFAULT_PUBLIC_BOUNDARY_SOURCES = {
"earth_admin0_boundaries": {
"displayName": "Natural Earth Admin-0 Countries",
"sourceKind": "admin0-boundaries",
"endpoint": "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_10m_admin_0_countries.geojson",
"endpoint": f"{_NE_GEOJSON}/ne_10m_admin_0_countries.geojson",
"method": "GET",
"headers": {},
"auth_type": "none",
"license": "Natural Earth public domain",
},
"earth_coastline": {
"displayName": "Natural Earth Coastline",
"displayName": "OpenStreetMap Coastlines (osmdata.openstreetmap.de)",
"sourceKind": "coastline",
"endpoint": "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_10m_coastline.geojson",
"endpoint": "https://osmdata.openstreetmap.de/download/coastlines-split-4326.zip",
"method": "GET",
"headers": {},
"auth_type": "none",
"timeout": 1800,
"license": "ODbL 1.0 © OpenStreetMap contributors",
},
"earth_disputed_lines": {
"displayName": "Natural Earth Disputed Boundaries",
"sourceKind": "disputed-lines",
"endpoint": f"{_NE_GEOJSON}/ne_10m_admin_0_boundary_lines_disputed_areas.geojson",
"method": "GET",
"headers": {},
"auth_type": "none",
"license": "Natural Earth public domain",
},
"earth_claim_lines": {
"displayName": "Natural Earth Disputed Boundaries",
"displayName": "Natural Earth China POV Maritime Indicator",
"sourceKind": "claim-lines",
"endpoint": "https://raw.githubusercontent.com/nvkelso/natural-earth-vector/master/geojson/ne_10m_admin_0_boundary_lines_disputed_areas.geojson",
"endpoint": f"{_NE_GEOJSON}/ne_10m_admin_0_boundary_lines_maritime_indicator_chn.geojson",
"method": "GET",
"headers": {},
"auth_type": "none",
"license": "Natural Earth public domain",
},
"earth_admin1_lines": {
"displayName": "Natural Earth Admin-1 Lines",
"sourceKind": "admin1-lines",
"endpoint": f"{_NE_GEOJSON}/ne_10m_admin_1_states_provinces_lines.geojson",
"method": "GET",
"headers": {},
"auth_type": "none",
"license": "Natural Earth public domain",
},
"earth_populated_places": {
"displayName": "Natural Earth Populated Places",
"sourceKind": "populated-places",
"endpoint": f"{_NE_GEOJSON}/ne_10m_populated_places.geojson",
"method": "GET",
"headers": {},
"auth_type": "none",
@@ -73,11 +128,18 @@ DEFAULT_PUBLIC_BOUNDARY_SOURCES = {
BUILD_CONFIG = {
"builder": "scripts/build_earth_boundary_pmtiles.py",
"schema": MANIFEST_SCHEMA,
"format": "pmtiles+mvt",
"production_target": "pmtiles-mvt",
"minZoom": 0,
"maxZoom": 10,
"coastlineMaxZoom": 10,
}
class _NotModified(Exception):
"""Upstream answered 304 for a conditional source download."""
class EarthBoundaryBuildError(RuntimeError):
def __init__(self, message: str, *, code: str = "build_failed", details: Any = None) -> None:
super().__init__(message)
@@ -141,13 +203,11 @@ def _read_json(path: Path) -> dict[str, Any]:
def _write_json(path: Path, payload: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as f:
tmp = path.with_suffix(path.suffix + ".tmp")
with tmp.open("w", encoding="utf-8") as f:
json.dump(payload, f, ensure_ascii=False, indent=2)
f.write("\n")
def _sha256_bytes(payload: bytes) -> str:
return hashlib.sha256(payload).hexdigest()
tmp.replace(path)
def _stable_json_hash(payload: Any) -> str:
@@ -170,69 +230,15 @@ def _versioned_asset(path: Path) -> tuple[dict[str, Any], str]:
return _read_versioned_asset_cached(path, stat.st_mtime_ns, stat.st_size)
def _artifact_extension(endpoint: str, content_type: str, payload: bytes) -> str:
suffix = Path(endpoint.split("?", 1)[0]).suffix.lower()
if suffix in {".json", ".geojson", ".zip", ".pbf"}:
return suffix
if "geo+json" in content_type or b'"FeatureCollection"' in payload[:4096]:
return ".geojson"
if "json" in content_type:
return ".json"
return ".dat"
def _display_path(path: Path) -> str:
try:
return str(path.relative_to(REPO_ROOT))
except ValueError:
return str(path)
def _json_feature_count(payload: Any) -> int:
if isinstance(payload, dict) and isinstance(payload.get("features"), list):
return len(payload["features"])
if isinstance(payload, list):
return len(payload)
return 1 if payload else 0
def _directory_stats(path: Path) -> dict[str, int]:
if not path.exists():
return {"file_count": 0, "size_bytes": 0}
files = [item for item in path.rglob("*") if item.is_file()]
return {"file_count": len(files), "size_bytes": sum(item.stat().st_size for item in files)}
def _write_high_precision_geojson_manifest(
sources: list[dict[str, Any]],
build_input_hash: str,
missing_tools: list[str],
) -> dict[str, Any]:
admin0 = next(source for source in sources if source["kind"] == "admin0-boundaries")
coastline = next(source for source in sources if source["kind"] == "coastline")
claim_lines = next(source for source in sources if source["kind"] == "claim-lines")
result = subprocess.run(
[
sys.executable,
str(Path(__file__).resolve().parents[3] / "scripts/build_earth_boundary_china_pov_geojson.py"),
"--admin0-source", admin0["path"],
"--coastline-source", coastline["path"],
"--claims-source", claim_lines["path"],
"--output-dir", _relative(BOUNDARY_OUTPUT_DIR),
"--build-input-hash", build_input_hash,
"--pov-policy", _relative(POV_POLICY_PATH),
"--pov-geometry", str(POV_GEOMETRY_PATH),
],
cwd=REPO_ROOT,
capture_output=True,
text=True,
)
if result.returncode:
raise EarthBoundaryBuildError(
result.stderr.strip() or "Earth boundary policy build failed",
code="policy_build_failed",
)
manifest = _read_json(BOUNDARY_MANIFEST_PATH)
manifest["missingTools"] = missing_tools
_write_json(BOUNDARY_MANIFEST_PATH, manifest)
return manifest
def _relative(path: Path) -> str:
return str(path.relative_to(REPO_ROOT))
def missing_build_tools() -> list[str]:
return [tool for tool in REQUIRED_TOOLS if shutil.which(tool) is None]
def load_boundary_config() -> tuple[dict[str, Any], str]:
@@ -288,19 +294,19 @@ def _build_input_hash(source_manifest: dict[str, Any]) -> str:
"pov_policy": source_manifest.get("povPolicy"),
"pov_geometry_sha256": _versioned_asset(POV_GEOMETRY_PATH)[1],
"build_config": BUILD_CONFIG,
"builder_sha256": {
path.name: _file_sha256(path) for path in BUILDER_MODULE_PATHS if path.exists()
},
}
)
def _has_current_artifacts(boundary_manifest: dict[str, Any], build_input_hash: str) -> bool:
return (
bool(boundary_manifest)
and boundary_manifest.get("buildInputHash") == build_input_hash
and boundary_manifest.get("tileProvider") == "pmtiles-mvt"
and _policy_verified(boundary_manifest)
and PMTILES_ARTIFACT_PATH.exists()
and _pmtiles_hover_exists(boundary_manifest)
)
def _file_sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(DOWNLOAD_CHUNK_BYTES), b""):
digest.update(chunk)
return digest.hexdigest()
def _policy_verified(manifest: dict[str, Any]) -> bool:
@@ -311,65 +317,86 @@ def _policy_verified(manifest: dict[str, Any]) -> bool:
policy.get("profile") == "china-pov-v1"
and coverage.get("profile") == policy["profile"]
and coverage.get("sha256") == policy_hash
and coverage.get("reviewedGeometrySourceCommit")
== geometry.get("sourceCommit")
and coverage.get("reviewedGeometrySourceCommit") == geometry.get("sourceCommit")
and coverage.get("geometrySha256") == geometry_hash
and coverage.get("applied") is True
and {"china-taiwan-penghu", "china-hong-kong", "china-macao", "kosovo"}
<= set(coverage.get("appliedRuleIds") or [])
and REQUIRED_POLICY_RULES <= set(coverage.get("appliedRuleIds") or [])
)
def _geojson_artifacts_exist(manifest: dict[str, Any]) -> bool:
paths = [manifest.get("base"), manifest.get("hoverIndex")]
if manifest.get("chinaClaims", {}).get("available"):
paths.append(manifest.get("claimLine"))
for asset in paths:
if not isinstance(asset, str) or Path(asset).name != asset:
return False
if not (BOUNDARY_OUTPUT_DIR / asset).is_file():
return False
return True
def _manifest_artifact_names(manifest: dict[str, Any]) -> list[str]:
names = [
(manifest.get("pmtiles") or {}).get("path"),
manifest.get("hoverIndex"),
manifest.get("hoverBorders"),
manifest.get("geoLabels"),
]
return [name for name in names if isinstance(name, str) and name]
def _pmtiles_hover_exists(manifest: dict[str, Any]) -> bool:
hover = manifest.get("hoverIndex")
def _artifacts_exist(manifest: dict[str, Any]) -> bool:
names = _manifest_artifact_names(manifest)
required = [
(manifest.get("pmtiles") or {}).get("path"),
manifest.get("hoverIndex"),
manifest.get("hoverBorders"),
]
if not all(isinstance(name, str) and name for name in required):
return False
return all(Path(name).name == name and (BOUNDARY_OUTPUT_DIR / name).is_file() for name in names)
def _high_precision_ready(manifest: dict[str, Any]) -> bool:
return (
isinstance(hover, str)
and Path(hover).name == hover
and (BOUNDARY_OUTPUT_DIR / hover).is_file()
manifest.get("schema") == MANIFEST_SCHEMA
and manifest.get("tileProvider") == "pmtiles-mvt"
and _policy_verified(manifest)
and _artifacts_exist(manifest)
)
def _has_current_artifacts(boundary_manifest: dict[str, Any], build_input_hash: str) -> bool:
return (
boundary_manifest.get("buildInputHash") == build_input_hash
and _high_precision_ready(boundary_manifest)
)
def get_public_boundary_manifest() -> dict[str, Any] | None:
"""Manifest for Earth clients, or ``None`` when no verified artifact exists."""
manifest = _read_json(BOUNDARY_MANIFEST_PATH)
if not _high_precision_ready(manifest):
return None
return manifest
def resolve_boundary_artifact(name: str) -> Path | None:
"""Only files listed by the current verified manifest are served."""
if not name or Path(name).name != name:
return None
manifest = get_public_boundary_manifest()
if manifest is None or name not in _manifest_artifact_names(manifest):
return None
path = BOUNDARY_OUTPUT_DIR / name
return path if path.is_file() else None
def get_boundary_status() -> dict[str, Any]:
config_payload, config_source = load_boundary_config()
effective_source_configs = _source_configs_with_defaults(config_payload)
boundary_manifest = _read_json(BOUNDARY_MANIFEST_PATH)
pmtiles_exists = PMTILES_ARTIFACT_PATH.exists()
manifest_exists = BOUNDARY_MANIFEST_PATH.exists()
high_precision_ready = (
manifest_exists
and _policy_verified(boundary_manifest)
and (
(
boundary_manifest.get("tileProvider") == "pmtiles-mvt"
and pmtiles_exists
and _pmtiles_hover_exists(boundary_manifest)
)
or (
boundary_manifest.get("tileProvider") == "geojson-high-precision"
and _geojson_artifacts_exist(boundary_manifest)
)
)
)
high_precision_ready = manifest_exists and _high_precision_ready(boundary_manifest)
legacy_exists = POLICY_FALLBACK_PATH.exists() and _policy_verified(
_versioned_asset(POLICY_FALLBACK_PATH)[0]
)
provider = (
boundary_manifest.get("tileProvider")
"pmtiles-mvt"
if high_precision_ready
else "policy-geojson-fallback" if legacy_exists else "missing"
)
pmtiles_info = boundary_manifest.get("pmtiles") or {}
missing_tools = missing_build_tools()
return {
"provider": provider,
"high_precision_ready": high_precision_ready,
@@ -377,8 +404,10 @@ def get_boundary_status() -> dict[str, Any]:
"policy_publishable": bool(
high_precision_ready and boundary_manifest.get("povPolicy", {}).get("publicationReady")
),
"build_tools_ready": not missing_tools,
"missing_tools": missing_tools,
"config_source": config_source,
"config_path": _relative(LOCAL_CONFIG_PATH),
"config_path": _display_path(LOCAL_CONFIG_PATH),
"config_exists": LOCAL_CONFIG_PATH.exists(),
"config": config_payload,
"effective_default_sources": [
@@ -388,8 +417,9 @@ def get_boundary_status() -> dict[str, Any]:
and source_config.get("endpoint") == DEFAULT_PUBLIC_BOUNDARY_SOURCES[source_key]["endpoint"]
],
"manifest": {
"path": _relative(BOUNDARY_MANIFEST_PATH),
"path": _display_path(BOUNDARY_MANIFEST_PATH),
"exists": manifest_exists,
"schema": boundary_manifest.get("schema"),
"tileProvider": boundary_manifest.get("tileProvider"),
"buildInputHash": boundary_manifest.get("buildInputHash"),
"builtAt": boundary_manifest.get("builtAt"),
@@ -397,17 +427,17 @@ def get_boundary_status() -> dict[str, Any]:
"publicationReady": boundary_manifest.get("povPolicy", {}).get("publicationReady", False),
},
"pmtiles": {
"path": _relative(PMTILES_ARTIFACT_PATH),
"exists": pmtiles_exists,
"size_bytes": PMTILES_ARTIFACT_PATH.stat().st_size if pmtiles_exists else 0,
"path": pmtiles_info.get("path"),
"exists": high_precision_ready,
"size_bytes": pmtiles_info.get("sizeBytes", 0) if high_precision_ready else 0,
},
"legacy": {
"path": _relative(POLICY_FALLBACK_PATH),
"path": _display_path(POLICY_FALLBACK_PATH),
"exists": legacy_exists,
"size_bytes": POLICY_FALLBACK_PATH.stat().st_size if legacy_exists else 0,
},
"source_manifest": {
"path": _relative(SOURCE_MANIFEST_PATH),
"path": _display_path(SOURCE_MANIFEST_PATH),
"exists": SOURCE_MANIFEST_PATH.exists(),
},
"last_build": _read_json(BUILD_RESULT_PATH),
@@ -415,6 +445,69 @@ def get_boundary_status() -> dict[str, Any]:
}
def _artifact_extension(endpoint: str, content_type: str, head: bytes) -> str:
suffix = Path(endpoint.split("?", 1)[0]).suffix.lower()
if suffix in {".json", ".geojson", ".zip"}:
return suffix
if head.startswith(b"PK\x03\x04"):
return ".zip"
if "geo+json" in content_type or b'"FeatureCollection"' in head:
return ".geojson"
if "json" in content_type:
return ".json"
return ".dat"
def _zip_shapefile_feature_count(path: Path) -> int:
"""Count shapefile records from the .shx index (100-byte header, 8 bytes per record)."""
try:
with zipfile.ZipFile(path) as archive:
for info in archive.infolist():
if info.filename.endswith("lines.shx"):
return max(0, (info.file_size - 100) // 8)
except zipfile.BadZipFile as exc:
raise EarthBoundaryBuildError(
f"{path.name} is not a valid zip archive", code="invalid_source"
) from exc
return 0
def _source_feature_count(path: Path, extension: str) -> int:
if extension == ".zip":
return _zip_shapefile_feature_count(path)
if extension in {".json", ".geojson"}:
with path.open("r", encoding="utf-8") as f:
payload = json.load(f)
if isinstance(payload, dict) and isinstance(payload.get("features"), list):
return len(payload["features"])
if isinstance(payload, list):
return len(payload)
return 1 if payload else 0
return 0
def _previous_source(source_key: str, endpoint: str) -> dict[str, Any] | None:
"""Last downloaded artifact for this endpoint, if it is still on disk."""
for source in _read_json(SOURCE_MANIFEST_PATH).get("sources") or []:
if source.get("id") != source_key or source.get("endpoint") != endpoint:
continue
path = Path(str(source.get("path") or ""))
if path.is_file() and source.get("sha256") and path.name.startswith(str(source["sha256"])):
return source
return None
def _conditional_headers(previous: dict[str, Any] | None) -> dict[str, str]:
if not previous:
return {}
headers = {}
if previous.get("etag"):
headers["If-None-Match"] = str(previous["etag"])
if previous.get("lastModified"):
headers["If-Modified-Since"] = str(previous["lastModified"])
return headers
async def _download_source(
source_key: str,
source_config: dict[str, Any],
@@ -435,65 +528,108 @@ async def _download_source(
details={"source": source_key, "method": method},
)
if endpoint.startswith("file://") or Path(endpoint).expanduser().exists():
payload = Path(endpoint.removeprefix("file://")).expanduser().read_bytes()
content_type = "application/octet-stream"
if progress_callback:
progress_callback(1, len(payload), len(payload))
else:
timeout = float(source_config.get("timeout") or 120)
headers = source_config.get("headers") if isinstance(source_config.get("headers"), dict) else {}
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
async with client.stream(method, endpoint, headers=headers) as response:
response.raise_for_status()
content_type = response.headers.get("content-type", "")
total = int(response.headers.get("content-length") or 0)
chunks = []
downloaded = 0
async for chunk in response.aiter_bytes():
if not chunk:
continue
chunks.append(chunk)
downloaded += len(chunk)
if progress_callback:
progress_callback(
(downloaded / total) if total else None,
downloaded,
total,
)
payload = b"".join(chunks)
source_dir = SOURCE_OUTPUT_DIR / source_key
source_dir.mkdir(parents=True, exist_ok=True)
previous = _previous_source(source_key, endpoint)
digest = hashlib.sha256()
content_type = ""
head = b""
validators: dict[str, str] = {}
not_modified = False
with tempfile.NamedTemporaryFile(dir=source_dir, prefix=".download-", delete=False) as tmp:
tmp_path = Path(tmp.name)
try:
local_path = Path(endpoint.removeprefix("file://")).expanduser()
if endpoint.startswith("file://") or local_path.exists():
total = local_path.stat().st_size
with local_path.open("rb") as src:
while chunk := src.read(DOWNLOAD_CHUNK_BYTES):
head = head or chunk[:4096]
digest.update(chunk)
tmp.write(chunk)
if progress_callback:
progress_callback(1, total, total)
else:
timeout = float(source_config.get("timeout") or 120)
headers = source_config.get("headers") if isinstance(source_config.get("headers"), dict) else {}
# Re-use the stored artifact when the upstream file is unchanged
# (the OSM coastline archive alone is ~900 MB).
headers = {**headers, **_conditional_headers(previous)}
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True) as client:
async with client.stream(method, endpoint, headers=headers) as response:
if response.status_code == 304 and previous:
not_modified = True
raise _NotModified
response.raise_for_status()
validators = {
key: value
for key, value in (
("etag", response.headers.get("etag")),
("lastModified", response.headers.get("last-modified")),
)
if value
}
content_type = response.headers.get("content-type", "")
# Content-Length counts encoded bytes; aiter_bytes yields decoded ones.
encoded = bool(response.headers.get("content-encoding"))
total = 0 if encoded else int(response.headers.get("content-length") or 0)
downloaded = 0
async for chunk in response.aiter_bytes(DOWNLOAD_CHUNK_BYTES):
if not chunk:
continue
head = head or chunk[:4096]
digest.update(chunk)
tmp.write(chunk)
downloaded += len(chunk)
if progress_callback:
progress_callback((downloaded / total) if total else None, downloaded, total)
except _NotModified:
pass
except BaseException:
tmp_path.unlink(missing_ok=True)
raise
extension = _artifact_extension(endpoint, content_type, payload)
parsed: Any = None
if extension in {".json", ".geojson"}:
parsed = json.loads(payload.decode("utf-8"))
feature_count = _json_feature_count(parsed)
if not_modified and previous:
tmp_path.unlink(missing_ok=True)
if progress_callback:
progress_callback(1, 0, 0)
logger.info("earth_boundary_source_not_modified", extra={"source": source_key})
return {**previous, "notModified": True}
sha256 = digest.hexdigest()
extension = _artifact_extension(endpoint, content_type, head)
artifact_path = source_dir / f"{sha256}{extension}"
tmp_path.replace(artifact_path)
for stale in source_dir.iterdir():
if stale.is_file() and stale != artifact_path:
stale.unlink()
feature_count = _source_feature_count(artifact_path, extension)
if feature_count <= 0:
raise EarthBoundaryBuildError(
f"{source_key} downloaded payload contains no features",
code="empty_source",
details={"source": source_key},
)
sha256 = _sha256_bytes(payload)
source_dir = SOURCE_OUTPUT_DIR / source_key
source_dir.mkdir(parents=True, exist_ok=True)
artifact_path = source_dir / f"{sha256}{extension}"
artifact_path.write_bytes(payload)
return {
"id": source_key,
"kind": source_config.get("sourceKind") or BOUNDARY_SOURCE_KINDS[source_key],
"path": _relative(artifact_path),
"endpoint": endpoint,
"path": str(artifact_path),
"sha256": sha256,
"featureCount": feature_count,
"license": source_config.get("license"),
**validators,
}
async def _run_step(args: list[str]) -> dict[str, Any]:
async def _run_builder(args: list[str]) -> dict[str, Any]:
command = [sys.executable, str(BUILDER_PATH), *args]
nice = shutil.which("nice")
if nice:
# Keep API latency stable while a production rebuild runs in the backend container.
command = [nice, "-n", "10", *command]
process = await asyncio.create_subprocess_exec(
sys.executable,
*args,
*command,
cwd=REPO_ROOT,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
@@ -501,7 +637,7 @@ async def _run_step(args: list[str]) -> dict[str, Any]:
stdout_bytes, stderr_bytes = await process.communicate()
stdout = stdout_bytes.decode("utf-8", errors="replace").strip()
stderr = stderr_bytes.decode("utf-8", errors="replace").strip()
payload: dict[str, Any] = {"stdout": stdout, "stderr": stderr, "returncode": process.returncode}
payload: dict[str, Any] = {"returncode": process.returncode, "stderr_tail": stderr[-4000:]}
last_line = stdout.splitlines()[-1:] or []
if last_line:
try:
@@ -510,7 +646,7 @@ async def _run_step(args: list[str]) -> dict[str, Any]:
payload["result"] = last_line[0]
if process.returncode != 0:
raise EarthBoundaryBuildError(
stderr or stdout or f"command failed: {' '.join(args)}",
(stderr.splitlines()[-1] if stderr else "") or "Earth boundary PMTiles build failed",
code="build_command_failed",
details=payload,
)
@@ -518,8 +654,15 @@ async def _run_step(args: list[str]) -> dict[str, Any]:
async def build_boundary_assets(progress_callback: Any = None) -> dict[str, Any]:
config_payload, config_source = load_boundary_config()
missing_tools = missing_build_tools()
if missing_tools:
raise EarthBoundaryBuildError(
f"PMTiles build tools missing: {', '.join(missing_tools)}",
code="missing_tools",
details={"missing_tools": missing_tools},
)
config_payload, _config_source = load_boundary_config()
source_configs = _source_configs_with_defaults(config_payload)
missing = [source for source in BOUNDARY_SOURCE_KINDS if source not in source_configs]
if missing:
@@ -531,6 +674,7 @@ async def build_boundary_assets(progress_callback: Any = None) -> dict[str, Any]
sources = []
source_keys = list(BOUNDARY_SOURCE_KINDS)
span = 52 / len(source_keys)
for index, source_key in enumerate(source_keys):
source_config = source_configs[source_key]
if not isinstance(source_config, dict):
@@ -539,21 +683,28 @@ async def build_boundary_assets(progress_callback: Any = None) -> dict[str, Any]
code="invalid_config",
details={"source": source_key},
)
source_start = 8 + index * 18
source_end = source_start + 18
source_start = 8 + index * span
source_end = source_start + span
if progress_callback:
progress_callback(source_start, "download", f"正在下载 {source_key}")
def report_download_progress(ratio: float | None, downloaded: int, total: int) -> None:
def report_download_progress(
ratio: float | None,
downloaded: int,
total: int,
_start: float = source_start,
_end: float = source_end,
_key: str = source_key,
) -> None:
if not progress_callback:
return
if ratio is None:
progress_callback(source_start + 8, "download", f"{source_key} 已下载 {downloaded} bytes")
progress_callback(_start + span / 2, "download", f"{_key} 已下载 {downloaded} bytes")
return
progress_callback(
source_start + (source_end - source_start) * ratio,
_start + (_end - _start) * ratio,
"download",
f"{source_key} 下载 {int(ratio * 100)}%",
f"{_key} 下载 {int(ratio * 100)}%",
downloaded_bytes=downloaded,
total_bytes=total,
)
@@ -561,91 +712,71 @@ async def build_boundary_assets(progress_callback: Any = None) -> dict[str, Any]
sources.append(await _download_source(source_key, source_config, report_download_progress))
source_manifest = {
"schema": "planet-earth-boundary-sources/v2",
"schema": "planet-earth-boundary-sources/v3",
"sources": sources,
"povPolicy": _read_json(POV_POLICY_PATH),
}
if progress_callback:
progress_callback(65, "manifest", "正在写入边界源 manifest")
progress_callback(62, "manifest", "正在写入边界源 manifest")
_write_json(SOURCE_MANIFEST_PATH, source_manifest)
build_input_hash = _build_input_hash(source_manifest)
boundary_manifest = _read_json(BOUNDARY_MANIFEST_PATH)
build_skipped = _has_current_artifacts(boundary_manifest, build_input_hash)
missing_tools = [tool for tool in ("tippecanoe", "pmtiles") if shutil.which(tool) is None]
if missing_tools and not build_skipped:
if progress_callback:
progress_callback(82, "build", "缺少 PMTiles 工具,正在生成 GeoJSON 高清包")
boundary_manifest = _write_high_precision_geojson_manifest(
sources,
build_input_hash,
missing_tools,
)
result = {
"status": "built_geojson_fallback",
"code": "missing_tools",
"missing_tools": missing_tools,
"sources": sources,
"boundary_manifest": _relative(BOUNDARY_MANIFEST_PATH),
"manifest": boundary_manifest,
}
_write_json(BUILD_RESULT_PATH, result)
if progress_callback:
progress_callback(96, "finalize", "GeoJSON 高清国界包已生成")
return {**get_boundary_status(), "build": result}
if build_skipped:
if progress_callback:
progress_callback(96, "unchanged", "高精国界已是最新")
build_result = {
build_result: dict[str, Any] = {
"status": "unchanged",
"reason": "source manifest and build config hash unchanged",
"buildInputHash": build_input_hash,
}
else:
if progress_callback:
progress_callback(72, "build", "正在构建 PMTiles/MVT")
admin0 = next(source for source in sources if source["kind"] == "admin0-boundaries")
coastline = next(source for source in sources if source["kind"] == "coastline")
claim_lines = next(source for source in sources if source["kind"] == "claim-lines")
build_result = await _run_step(
[
"scripts/build_earth_boundary_pmtiles.py",
"--admin0-source",
admin0["path"],
"--coastline-source",
coastline["path"],
"--claims-source",
claim_lines["path"],
"--output",
_relative(PMTILES_ARTIFACT_PATH),
"--manifest",
_relative(BOUNDARY_MANIFEST_PATH),
"--build-input-hash",
build_input_hash,
"--pov-policy",
_relative(POV_POLICY_PATH),
"--pov-geometry",
str(POV_GEOMETRY_PATH),
]
)
progress_callback(66, "build", "正在构建 PMTiles/MVT(海岸线 z0–z10)")
by_kind = {source["kind"]: source["path"] for source in sources}
builder_args = [
"--admin0-source", by_kind["admin0-boundaries"],
"--coastline-source", by_kind["coastline"],
"--disputed-source", by_kind["disputed-lines"],
"--claims-source", by_kind["claim-lines"],
"--admin1-source", by_kind["admin1-lines"],
"--output-dir", str(BOUNDARY_OUTPUT_DIR),
"--build-input-hash", build_input_hash,
"--pov-policy", str(POV_POLICY_PATH),
"--pov-geometry", str(POV_GEOMETRY_PATH),
"--min-zoom", str(BUILD_CONFIG["minZoom"]),
"--max-zoom", str(BUILD_CONFIG["maxZoom"]),
"--coastline-max-zoom", str(BUILD_CONFIG["coastlineMaxZoom"]),
"--temp-dir", str(BOUNDARY_DATA_DIR / "tmp"),
]
if "populated-places" in by_kind:
builder_args.extend(["--places-source", by_kind["populated-places"]])
build_result = await _run_builder(builder_args)
if progress_callback:
progress_callback(95, "finalize", "正在校验构建产物")
boundary_manifest = _read_json(BOUNDARY_MANIFEST_PATH)
boundary_stats = _directory_stats(BOUNDARY_OUTPUT_DIR)
if not _high_precision_ready(boundary_manifest):
raise EarthBoundaryBuildError(
"Earth boundary build finished without a verified China POV manifest",
code="unverified_artifact",
details={"manifest": _display_path(BOUNDARY_MANIFEST_PATH)},
)
result = {
"status": "unchanged" if build_skipped else "built",
"sources": sources,
"source_manifest": _relative(SOURCE_MANIFEST_PATH),
"boundary_manifest": _relative(BOUNDARY_MANIFEST_PATH),
"pmtiles_artifact": _relative(PMTILES_ARTIFACT_PATH),
"pmtiles_exists": PMTILES_ARTIFACT_PATH.exists(),
"boundary_stats": boundary_stats,
"source_manifest": _display_path(SOURCE_MANIFEST_PATH),
"boundary_manifest": _display_path(BOUNDARY_MANIFEST_PATH),
"pmtiles": boundary_manifest.get("pmtiles"),
"manifest": boundary_manifest,
"build_result": build_result,
}
_write_json(BUILD_RESULT_PATH, result)
logger.info(
"earth_boundary_build_finished",
extra={"status": result["status"], "pmtiles_bytes": (boundary_manifest.get("pmtiles") or {}).get("sizeBytes")},
)
return {**get_boundary_status(), "build": result}
@@ -674,6 +805,7 @@ async def _run_boundary_build_job(job_id: str) -> None:
)
_append_job_log("高精国界构建完成")
except EarthBoundaryBuildError as exc:
logger.warning("earth_boundary_build_failed", extra={"code": exc.code, "error": str(exc)})
_set_job_state(
id=job_id,
status="failed",
@@ -686,6 +818,7 @@ async def _run_boundary_build_job(job_id: str) -> None:
)
_append_job_log(str(exc))
except Exception as exc: # pragma: no cover - defensive guard for background task
logger.exception("earth_boundary_build_crashed")
_set_job_state(
id=job_id,
status="failed",
@@ -703,6 +836,13 @@ async def start_boundary_build_job() -> dict[str, Any]:
async with _build_job_lock:
if _build_task and not _build_task.done():
return {"accepted": False, "job": _public_job_state()}
missing_tools = missing_build_tools()
if missing_tools:
raise EarthBoundaryBuildError(
f"PMTiles build tools missing: {', '.join(missing_tools)}",
code="missing_tools",
details={"missing_tools": missing_tools},
)
job_id = uuid4().hex
_set_job_state(
id=job_id,
File diff suppressed because it is too large. Load diff
+276
View File
@@ -0,0 +1,276 @@
"""GeoColor daytime visible compositing and DIS optical flow synthesis for cloud maps."""
from __future__ import annotations
from datetime import UTC, datetime
import io
import math
from typing import Any, Sequence
import cv2
import numpy as np
from PIL import Image
def _longitude_weight_vector(width: int, sub_lon_deg: float) -> np.ndarray:
lons = ((np.arange(width, dtype=np.float32) + 0.5) / float(width)) * 360.0 - 180.0
delta = np.abs(((lons - float(sub_lon_deg) + 180.0) % 360.0) - 180.0)
sigma = 46.0
weights = np.exp(-0.5 * (delta / sigma) ** 2).astype(np.float32)
weights[delta > 74.0] = 0.0
return weights
def _decode_rgba_resized(payload_bytes: bytes, width: int, height: int) -> np.ndarray:
with Image.open(io.BytesIO(payload_bytes)) as img:
converted = img.convert("RGBA")
if converted.size != (width, height):
converted = converted.resize((width, height), Image.Resampling.BILINEAR)
return np.asarray(converted, dtype=np.uint8)
def decode_visual_payloads(
visual_payloads: Sequence[tuple[dict[str, Any], bytes | np.ndarray]],
width: int,
height: int,
) -> list[tuple[dict[str, Any], np.ndarray]]:
"""Decode and resize visible satellite payloads once so density & GeoColor share buffers."""
decoded: list[tuple[dict[str, Any], np.ndarray]] = []
for sat, payload in visual_payloads:
if isinstance(payload, np.ndarray):
if payload.shape[:2] == (height, width) and payload.shape[2] == 4:
decoded.append((sat, payload))
continue
try:
rgba = _decode_rgba_resized(payload, width, height)
decoded.append((sat, rgba))
except Exception:
continue
return decoded
def _solar_cosine_grid(width: int, height: int, now_utc: datetime) -> tuple[np.ndarray, np.ndarray]:
"""Return `(cos_sza_2d, lats_deg_1d)` on the equirectangular cloud grid."""
utc = now_utc.astimezone(UTC) if now_utc.tzinfo else now_utc.replace(tzinfo=UTC)
doy = utc.timetuple().tm_yday
decl = math.radians(-23.44 * math.cos(2.0 * math.pi * (doy + 10) / 365.0))
utc_hour = utc.hour + utc.minute / 60.0 + utc.second / 3600.0
subsolar_lon = (12.0 - utc_hour) * 15.0
lats_deg = (90.0 - ((np.arange(height, dtype=np.float32) + 0.5) / float(height)) * 180.0)
lons_deg = (((np.arange(width, dtype=np.float32) + 0.5) / float(width)) * 360.0 - 180.0)
lat_rad = np.deg2rad(lats_deg)[:, None]
ha_rad = np.deg2rad(lons_deg - subsolar_lon)[None, :]
cos_sza = (
np.sin(lat_rad) * math.sin(decl)
+ np.cos(lat_rad) * math.cos(decl) * np.cos(ha_rad)
).astype(np.float32)
return cos_sza, lats_deg
def fuse_daytime_visible_into_density(
density_u8: np.ndarray,
temp_c: np.ndarray,
visual_payloads: Sequence[tuple[dict[str, Any], bytes | np.ndarray]],
*,
width: int,
height: int,
now_utc: datetime | None = None,
) -> np.ndarray:
"""Recover warm daytime low clouds (stratocumulus) from sunlit visible channels."""
if not visual_payloads or density_u8.shape != (height, width) or temp_c.shape != (height, width):
return density_u8
cos_sza, lats_deg = _solar_cosine_grid(width, height, now_utc or datetime.now(UTC))
polar_w = np.clip((76.0 - np.abs(lats_deg)) / 12.0, 0.0, 1.0).astype(np.float32)[:, None]
day_weight = (np.clip((cos_sza - 0.12) / 0.24, 0.0, 1.0) * polar_w).astype(np.float32)
if not np.any(day_weight > 0.01):
return density_u8
decoded_visuals = decode_visual_payloads(visual_payloads, width, height)
if not decoded_visuals:
return density_u8
cos_safe = np.clip(cos_sza, 0.30, 1.0)
safe_temp = np.where(np.isfinite(temp_c), temp_c, 15.0).astype(np.float32)
# Band-pass gate: peaks on -2C..+16C warm low clouds while suppressing hot deserts (>+24C) and sub-zero snow (<-8C).
warm_low_cloud_gate = (
np.clip((24.0 - safe_temp) / 12.0, 0.0, 1.0)
* np.clip((safe_temp + 8.0) / 10.0, 0.0, 1.0)
).astype(np.float32)
vis_accum = np.zeros((height, width), dtype=np.float32)
weight_accum = np.zeros((height, width), dtype=np.float32)
for sat, rgba in decoded_visuals:
rgb = rgba[:, :, :3].astype(np.float32)
alpha = rgba[:, :, 3].astype(np.float32)
luma = 0.299 * rgb[:, :, 0] + 0.587 * rgb[:, :, 1] + 0.114 * rgb[:, :, 2]
not_clipped = ~(
(rgb[:, :, 0] >= 254.0)
& (rgb[:, :, 1] >= 254.0)
& (rgb[:, :, 2] >= 254.0)
& (safe_temp > -10.0)
)
valid = (alpha > 12.0) & (luma > 8.0) & not_clipped
if not np.any(valid):
continue
chroma = (np.max(rgb, axis=2) - np.min(rgb, axis=2)) / 255.0
is_color = float(np.nanpercentile(chroma[valid], 95)) > 0.08
if is_color:
min_rgb = np.min(rgb, axis=2)
albedo = min_rgb / cos_safe
whiteness = np.clip(1.0 - chroma / 0.36, 0.0, 1.0)
sat_cloud = np.clip((albedo - 85.0) / 135.0, 0.0, 1.0) * whiteness * warm_low_cloud_gate
else:
albedo = luma / cos_safe
sat_cloud = np.clip((albedo - 88.0) / 132.0, 0.0, 1.0) * warm_low_cloud_gate
lon_w = _longitude_weight_vector(width, float(sat.get("sub_lon", 0.0)))
pix_w = np.where(valid, lon_w[None, :], 0.0)
vis_accum += sat_cloud * pix_w
weight_accum += pix_w
covered = weight_accum > 0.0
if not np.any(covered):
return density_u8
vis_cloud = np.zeros((height, width), dtype=np.float32)
vis_cloud[covered] = vis_accum[covered] / weight_accum[covered]
vis_cloud *= day_weight
vis_u8 = np.clip(np.round(vis_cloud * 255.0), 0, 255).astype(np.uint8)
vis_u8 = cv2.GaussianBlur(vis_u8, (3, 3), 0.6)
return np.maximum(density_u8, vis_u8)
def synthesize_geocolor_visual_webp(
visual_payloads: Sequence[tuple[dict[str, Any], bytes | np.ndarray]],
density_u8: np.ndarray,
*,
width: int,
height: int,
) -> bytes | None:
"""Composite daytime GeoColor/Visible satellite WMS tiles into an RGBA WebP overlay."""
if not visual_payloads or density_u8.shape != (height, width):
return None
decoded_visuals = decode_visual_payloads(visual_payloads, width, height)
if not decoded_visuals:
return None
rgb_accum = np.zeros((height, width, 3), dtype=np.float32)
weight_accum = np.zeros((height, width), dtype=np.float32)
valid_sources = 0
for sat, rgba in decoded_visuals:
rgb = rgba[:, :, :3].astype(np.float32)
alpha = rgba[:, :, 3].astype(np.float32)
luma = 0.299 * rgb[:, :, 0] + 0.587 * rgb[:, :, 1] + 0.114 * rgb[:, :, 2]
# EUMETView/GIBS return opaque black over night hemispheres or pure-white clipped wedges.
# Mask out dark night pixels and non-dense pure-white [255,255,255] fill artifacts.
not_clipped = ~(
(rgb[:, :, 0] >= 254.0)
& (rgb[:, :, 1] >= 254.0)
& (rgb[:, :, 2] >= 254.0)
& (density_u8 < 180)
)
valid = (alpha > 12.0) & (luma > 22.0) & not_clipped
if not np.any(valid):
continue
lon_w = _longitude_weight_vector(width, float(sat.get("sub_lon", 0.0)))
# Emphasize cloud-rich pixels from daytime channels so dark ocean reflectance doesn't darken clouds.
pix_w = np.where(valid, lon_w[None, :], 0.0)
rgb_accum += rgb * pix_w[:, :, None]
weight_accum += pix_w
valid_sources += 1
if valid_sources == 0 or not np.any(weight_accum > 0.0):
return None
covered = weight_accum > 0.0
comp_rgb = np.full((height, width, 3), 238.0, dtype=np.float32)
comp_rgb[covered] = rgb_accum[covered] / weight_accum[covered, None]
# Purify cloud colors toward clean sunlight white so underlying dark land/ocean never tints thin clouds green/brown
density_f = density_u8.astype(np.float32) / 255.0
comp_luma = (
0.299 * comp_rgb[:, :, 0] + 0.587 * comp_rgb[:, :, 1] + 0.114 * comp_rgb[:, :, 2]
)
daylight_factor = np.where(
covered,
np.clip((comp_luma - 28.0) / 140.0, 0.0, 1.0),
0.0,
).astype(np.float32)
fallback_tone = np.clip(212.0 + density_f * 43.0, 0.0, 255.0)
for ch in range(3):
blended = comp_rgb[:, :, ch] * daylight_factor + fallback_tone * (1.0 - daylight_factor)
comp_rgb[:, :, ch] = blended * 0.65 + fallback_tone * 0.35
out_rgba = np.empty((height, width, 4), dtype=np.uint8)
out_rgba[:, :, :3] = np.clip(np.round(comp_rgb), 0, 255).astype(np.uint8)
# Alpha encodes visible daylight availability multiplied by cloud density.
vis_alpha = np.clip(np.round(density_f * (0.35 + 0.65 * daylight_factor) * 255.0), 0, 255).astype(np.uint8)
out_rgba[:, :, 3] = vis_alpha
img = Image.fromarray(out_rgba, mode="RGBA")
buf = io.BytesIO()
img.save(buf, format="WEBP", quality=86, method=1)
return buf.getvalue()
def compute_dis_optical_flow_webp(
prev_density_u8: np.ndarray,
curr_density_u8: np.ndarray,
*,
flow_width: int = 512,
flow_height: int = 256,
) -> tuple[bytes, float] | None:
"""Compute dense DIS optical flow between consecutive cloud density frames.
Returns `(webp_bytes, max_uv)` where pixels encode normalized UV displacement:
- `R = round((du / max_uv * 0.5 + 0.5) * 255)`
- `G = round((dv / max_uv * 0.5 + 0.5) * 255)`
Using OpenCV's inverted-V orientation converted directly to WebGL UV delta (`v` positive up).
"""
if prev_density_u8 is None or curr_density_u8 is None:
return None
if prev_density_u8.size == 0 or curr_density_u8.size == 0:
return None
prev_small = cv2.resize(prev_density_u8, (flow_width, flow_height), interpolation=cv2.INTER_AREA)
curr_small = cv2.resize(curr_density_u8, (flow_width, flow_height), interpolation=cv2.INTER_AREA)
dis = cv2.DISOpticalFlow_create(cv2.DISOPTICAL_FLOW_PRESET_MEDIUM)
flow_px = dis.calc(prev_small, curr_small, None)
if flow_px is None or flow_px.shape[:2] != (flow_height, flow_width):
return None
# Smooth vector field slightly so advection warps stay coherent without blockiness
flow_px = cv2.GaussianBlur(flow_px, (7, 7), 1.6)
# Convert pixel displacement to normalized equirectangular UV displacement.
# Flip Y sign because image rows increase downward while equirectangular V increases upward in Three.js Canvas/Image unless flipY=true.
# Three.js default Texture.flipY=true puts row 0 (North) at v=1 and row H-1 (South) at v=0, so positive image dy (southward) corresponds to negative dv.
du = flow_px[:, :, 0].astype(np.float32) / float(flow_width)
dv = -flow_px[:, :, 1].astype(np.float32) / float(flow_height)
# Suppress tiny noisy vectors in clear sky regions
max_uv = float(max(np.percentile(np.maximum(np.abs(du), np.abs(dv)), 99.5), 1e-4))
max_uv = min(max_uv, 0.08)
u_norm = np.clip(du / max_uv, -1.0, 1.0) * 0.5 + 0.5
v_norm = np.clip(dv / max_uv, -1.0, 1.0) * 0.5 + 0.5
rgb = np.empty((flow_height, flow_width, 3), dtype=np.uint8)
rgb[:, :, 0] = np.clip(np.round(u_norm * 255.0), 0, 255).astype(np.uint8)
rgb[:, :, 1] = np.clip(np.round(v_norm * 255.0), 0, 255).astype(np.uint8)
rgb[:, :, 2] = 128
img = Image.fromarray(rgb, mode="RGB")
buf = io.BytesIO()
img.save(buf, format="WEBP", quality=92, method=1)
return buf.getvalue(), round(float(max_uv), 6)
@@ -116,6 +116,27 @@ EARTH_LAYER_ADAPTERS: tuple[EarthLayerAdapter, ...] = (
cache_patterns=(),
refresh_strategy="delta",
),
EarthLayerAdapter(
sources=frozenset({"global_cloud_map", "cloud_hd_tiles"}),
tables=frozenset({"collected_data"}),
layers=("clouds",),
cache_patterns=(),
refresh_strategy="reload",
),
EarthLayerAdapter(
sources=frozenset({"global_wind_gfs"}),
tables=frozenset({"collected_data"}),
layers=("windField",),
cache_patterns=(),
refresh_strategy="reload",
),
EarthLayerAdapter(
sources=frozenset({"earth_imagery_sentinel2", "earth_imagery_viirs_daily"}),
tables=frozenset({"collected_data"}),
layers=("basemap",),
cache_patterns=(),
refresh_strategy="reload",
),
)
_ADAPTERS_BY_SOURCE = {
+932
View File
@@ -0,0 +1,932 @@
"""Managed Web-Mercator tile pyramid proxy, warmup collection, LRU cache, and basemap settings."""
from __future__ import annotations
import asyncio
from datetime import UTC, datetime
import hashlib
import io
import math
import os
from pathlib import Path
import time
from typing import Any
from uuid import uuid4
import cv2
import httpx
import numpy as np
from PIL import Image
from pydantic import BaseModel, Field, field_validator
from sqlalchemy import select
from sqlalchemy.dialects.postgresql import insert as pg_insert
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.data_sources import get_data_sources_config
from app.core.datasource_defaults import DEFAULT_DATASOURCES
from app.core.logging import get_logger
from app.core.request_context import get_request_id
from app.models.datasource import DataSource
from app.models.datasource_config import DataSourceConfig
from app.models.system_log import AuditLog
from app.models.system_setting import SystemSetting
from app.models.user import User
from app.services.earth_clouds import (
EUMETVIEW_WMS_URL,
decode_eumetview_ir_to_temp_and_valid,
decode_gibs_band13_to_temp_and_valid,
temperature_to_density,
)
ORIGIN_SHIFT_3857 = 20037508.342789244
logger = get_logger(__name__, service="earth_tiles")
REPO_ROOT = Path(__file__).resolve().parents[3]
TILES_DATA_DIR = REPO_ROOT / "data" / "earth-tiles"
BASEMAP_CONFIG_CATEGORY = "earth_basemap"
CLOUD_HD_TILE_TTL_SECONDS = 1800
TILE_SOURCES: tuple[str, ...] = (
"cloud_hd_tiles",
"earth_imagery_sentinel2",
"earth_imagery_viirs_daily",
)
BASEMAP_TILE_SOURCES: tuple[str, ...] = (
"earth_imagery_sentinel2",
"earth_imagery_viirs_daily",
)
DEFAULT_TILE_TEMPLATES: dict[str, str] = {
"cloud_hd_tiles": (
"https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/"
"GOES-East_ABI_GeoColor/default/default/"
"GoogleMapsCompatible_Level7/{z}/{y}/{x}.png"
),
"earth_imagery_sentinel2": (
"https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-2024_3857/default/"
"GoogleMapsCompatible/{z}/{y}/{x}.jpg"
),
"earth_imagery_viirs_daily": (
"https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/"
"VIIRS_SNPP_CorrectedReflectance_TrueColor/default/default/"
"GoogleMapsCompatible_Level9/{z}/{y}/{x}.jpg"
),
}
class BasemapRevisionConflictError(RuntimeError):
"""Raised when saving basemap configuration with a stale revision."""
class BasemapConfig(BaseModel):
active_source: str = Field(default="earth_imagery_sentinel2")
hd_tiles_enabled: bool = True
cloud_hd_tiles_enabled: bool = False
lod_switch_altitude: float = Field(default=1.85, ge=1.2, le=5.0)
max_zoom: int = Field(default=7, ge=2, le=10)
warmup_max_zoom: int = Field(default=3, ge=1, le=4)
max_cache_mb: int = Field(default=1024, ge=128, le=8192)
request_timeout_seconds: int = Field(default=15, ge=5, le=45)
@field_validator("active_source")
@classmethod
def validate_active_source(cls, value: str) -> str:
normalized = str(value or "earth_imagery_sentinel2").strip()
if normalized not in {"static", *BASEMAP_TILE_SOURCES}:
raise ValueError(
"active_source must be 'static', 'earth_imagery_sentinel2', or 'earth_imagery_viirs_daily'"
)
return normalized
DEFAULT_BASEMAP_CONFIG = BasemapConfig()
DEFAULT_BASEMAP_REVISION = hashlib.sha256(
DEFAULT_BASEMAP_CONFIG.model_dump_json().encode("utf-8")
).hexdigest()[:16]
def _default_basemap_envelope() -> dict[str, Any]:
return {
"config": DEFAULT_BASEMAP_CONFIG.model_dump(mode="json"),
"revision": DEFAULT_BASEMAP_REVISION,
"is_default": True,
}
def _tiles_root() -> Path:
return TILES_DATA_DIR
def _source_dir(source_key: str) -> Path:
if source_key not in TILE_SOURCES:
raise ValueError(f"Unsupported tile source: {source_key}")
return _tiles_root() / source_key
def _tile_path(source_key: str, z: int, x: int, y: int) -> Path:
return _source_dir(source_key) / str(int(z)) / str(int(x)) / f"{int(y)}.webp"
def _atomic_write_bytes(path: Path, content: bytes) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = path.with_name(f".{path.name}.{uuid4().hex[:8]}.tmp")
try:
tmp_path.write_bytes(content)
os.replace(tmp_path, path)
finally:
if tmp_path.exists():
try:
tmp_path.unlink()
except OSError:
pass
def validate_tile_coords(source_key: str, z: int, x: int, y: int, max_zoom: int = 10) -> None:
if source_key not in TILE_SOURCES:
raise ValueError("Unsupported tile source")
if z < 0 or z > max_zoom:
raise ValueError("Zoom level out of range")
limit = 1 << z
if x < 0 or x >= limit or y < 0 or y >= limit:
raise ValueError("Tile coordinates out of range")
def _tile_center_lon(z: int, x: int) -> float:
n = float(1 << max(0, z))
return ((float(x) + 0.5) / n) * 360.0 - 180.0
def _tile_center_lat(z: int, y: int) -> float:
n = float(1 << max(0, z))
merc_y = math.pi * (1.0 - 2.0 * ((float(y) + 0.5) / n))
return math.degrees(math.atan(math.sinh(merc_y)))
def _tile_solar_cosine(z: int, x: int, y: int, now_utc: datetime | None = None) -> float:
utc = now_utc or datetime.now(UTC)
utc = utc.astimezone(UTC) if utc.tzinfo else utc.replace(tzinfo=UTC)
doy = utc.timetuple().tm_yday
decl = math.radians(-23.44 * math.cos(2.0 * math.pi * (doy + 10) / 365.0))
utc_hour = utc.hour + utc.minute / 60.0 + utc.second / 3600.0
subsolar_lon = (12.0 - utc_hour) * 15.0
lat_rad = math.radians(_tile_center_lat(z, y))
ha_rad = math.radians(_tile_center_lon(z, x) - subsolar_lon)
return (
math.sin(lat_rad) * math.sin(decl)
+ math.cos(lat_rad) * math.cos(decl) * math.cos(ha_rad)
)
def _tile_to_3857_bbox(z: int, x: int, y: int) -> str:
n = 1 << max(0, int(z))
tile_span = (2.0 * ORIGIN_SHIFT_3857) / float(n)
minx = -ORIGIN_SHIFT_3857 + float(x) * tile_span
maxx = minx + tile_span
maxy = ORIGIN_SHIFT_3857 - float(y) * tile_span
miny = maxy - tile_span
return f"{minx:.3f},{miny:.3f},{maxx:.3f},{maxy:.3f}"
def _resolve_cloud_hd_ir_fallback(
z: int,
x: int,
y: int,
) -> tuple[str, dict[str, str] | None, str, int]:
"""Return `(url, query_params, provider, src_zoom)` for 5-satellite Band13/IR10.8 cloud tiles."""
lon = _tile_center_lon(z, x)
if 23.0 <= lon < 93.0 or -37.5 <= lon < 23.0:
wms_layer = "msg_fes:ir108" if lon < 23.0 else "msg_iodc:ir108"
params = {
"SERVICE": "WMS",
"REQUEST": "GetMap",
"VERSION": "1.1.1",
"LAYERS": wms_layer,
"STYLES": "",
"FORMAT": "image/png",
"TRANSPARENT": "true",
"SRS": "EPSG:3857",
"BBOX": _tile_to_3857_bbox(z, x, y),
"WIDTH": "256",
"HEIGHT": "256",
}
return EUMETVIEW_WMS_URL, params, "eumetview", int(z)
if lon < -106.0:
layer = "GOES-West_ABI_Band13_Clean_Infrared"
elif lon < -37.5:
layer = "GOES-East_ABI_Band13_Clean_Infrared"
else:
layer = "Himawari_AHI_Band13_Clean_Infrared"
ir_z = min(int(z), 6)
shift = max(0, int(z) - ir_z)
ir_x = int(x) >> shift
ir_y = int(y) >> shift
wmts_url = (
f"https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/"
f"{layer}/default/default/GoogleMapsCompatible_Level6/{ir_z}/{ir_y}/{ir_x}.png"
)
return wmts_url, None, "gibs", ir_z
def _resolve_cloud_hd_request(
default_template: str,
z: int,
x: int,
y: int,
*,
now_utc: datetime | None = None,
daytime: bool | None = None,
) -> tuple[str, dict[str, str] | None, str]:
"""Route HD cloud tiles across 5 geostationary satellites using daytime 1km/2km visible or nighttime IR."""
if "GOES-East_ABI_GeoColor" not in default_template and "GOES-East_ABI_Band13" not in default_template:
url = (
default_template.replace("{z}", str(int(z)))
.replace("{y}", str(int(y)))
.replace("{x}", str(int(x)))
)
return url, None, "gibs"
is_daytime = (
daytime
if daytime is not None
else (_tile_solar_cosine(z, x, y, now_utc) > 0.14)
)
if not is_daytime:
ir_url, ir_params, ir_provider, _ = _resolve_cloud_hd_ir_fallback(z, x, y)
return ir_url, ir_params, ir_provider
lon = _tile_center_lon(z, x)
if lon < -106.0:
layer = "GOES-West_ABI_GeoColor"
provider = "gibs_geocolor"
elif lon < -37.5:
layer = "GOES-East_ABI_GeoColor"
provider = "gibs_geocolor"
elif lon < 93.0:
wms_layer = "msg_fes:rgb_naturalenhncd" if lon < 23.0 else "msg_iodc:rgb_naturalenhncd"
params = {
"SERVICE": "WMS",
"REQUEST": "GetMap",
"VERSION": "1.1.1",
"LAYERS": wms_layer,
"STYLES": "",
"FORMAT": "image/png",
"TRANSPARENT": "true",
"SRS": "EPSG:3857",
"BBOX": _tile_to_3857_bbox(z, x, y),
"WIDTH": "256",
"HEIGHT": "256",
}
return EUMETVIEW_WMS_URL, params, "eumetview_visible"
else:
layer = "Himawari_AHI_Band3_Red_Visible_1km"
provider = "gibs_visible"
wmts_z = min(int(z), 7)
shift = max(0, int(z) - wmts_z)
wmts_x = int(x) >> shift
wmts_y = int(y) >> shift
wmts_url = (
f"https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/"
f"{layer}/default/default/GoogleMapsCompatible_Level7/{wmts_z}/{wmts_y}/{wmts_x}.png"
)
return wmts_url, None, provider
def _crop_subtile_rgba(
raw_bytes: bytes,
z_target: int,
x_target: int,
y_target: int,
z_src: int,
) -> np.ndarray:
with Image.open(io.BytesIO(raw_bytes)) as img:
rgba = np.asarray(img.convert("RGBA"), dtype=np.uint8)
shift = int(z_target) - int(z_src)
if shift <= 0 or rgba.shape[0] < (1 << shift) or rgba.shape[1] < (1 << shift):
if rgba.shape[:2] != (256, 256):
return cv2.resize(rgba, (256, 256), interpolation=cv2.INTER_LINEAR)
return rgba
mask = (1 << shift) - 1
sub_x = int(x_target) & mask
sub_y = int(y_target) & mask
cell_h = max(1, rgba.shape[0] >> shift)
cell_w = max(1, rgba.shape[1] >> shift)
crop = rgba[sub_y * cell_h:(sub_y + 1) * cell_h, sub_x * cell_w:(sub_x + 1) * cell_w]
return cv2.resize(crop, (256, 256), interpolation=cv2.INTER_LINEAR)
def _decode_ir_density_and_temp(
ir_rgba: np.ndarray,
ir_provider: str,
) -> tuple[np.ndarray, np.ndarray]:
if ir_provider == "eumetview":
temp, valid = decode_eumetview_ir_to_temp_and_valid(ir_rgba)
else:
temp, valid = decode_gibs_band13_to_temp_and_valid(ir_rgba)
density = temperature_to_density(temp, ir_threshold=22, contrast_gamma=0.88)
density_u8 = np.where(valid, density, 0).astype(np.uint8)
return density_u8, temp
def _encode_tile_webp(
source_key: str,
raw_bytes: bytes,
*,
provider: str = "gibs",
ir_bytes: bytes | None = None,
ir_provider: str = "gibs",
cos_sza: float = 1.0,
z: int = 0,
x: int = 0,
y: int = 0,
ir_z_src: int | None = None,
) -> bytes:
if source_key == "cloud_hd_tiles":
src_z = min(int(z), 6) if provider == "gibs" else int(z)
rgba = _crop_subtile_rgba(raw_bytes, z, x, y, src_z)
if provider in ("gibs_geocolor", "gibs_visible", "eumetview_visible"):
rgb = rgba[:, :, :3].astype(np.float32)
alpha = rgba[:, :, 3].astype(np.float32)
luma = 0.299 * rgb[:, :, 0] + 0.587 * rgb[:, :, 1] + 0.114 * rgb[:, :, 2]
ir_density = np.zeros(rgba.shape[:2], dtype=np.uint8)
safe_temp = np.full(rgba.shape[:2], 15.0, dtype=np.float32)
cool_gate = np.ones(rgba.shape[:2], dtype=np.float32)
if ir_bytes:
try:
ir_rgba = _crop_subtile_rgba(
ir_bytes, z, x, y, ir_z_src if ir_z_src is not None else min(int(z), 6)
)
ir_density, temp = _decode_ir_density_and_temp(ir_rgba, ir_provider)
safe_temp = np.where(np.isfinite(temp), temp, 15.0).astype(np.float32)
# Band-pass warm low-cloud gate: peaks on -2C..+16C stratocumulus and suppresses freezing snow (<-8C) and hot deserts (>+24C).
cool_gate = (
np.clip((24.0 - safe_temp) / 12.0, 0.0, 1.0)
* np.clip((safe_temp + 8.0) / 10.0, 0.0, 1.0)
).astype(np.float32)
except Exception:
pass
not_clipped = ~(
(rgb[:, :, 0] >= 254.0)
& (rgb[:, :, 1] >= 254.0)
& (rgb[:, :, 2] >= 254.0)
& (safe_temp > -10.0)
)
valid = (alpha > 12.0) & (luma > 8.0) & not_clipped
cos_safe = max(0.30, float(cos_sza))
if provider == "gibs_visible":
albedo = luma / cos_safe
vis = np.clip((albedo - 88.0) / 132.0, 0.0, 1.0) * cool_gate
else:
chroma = (np.max(rgb, axis=2) - np.min(rgb, axis=2)) / 255.0
whiteness = np.clip(1.0 - chroma / 0.36, 0.0, 1.0)
min_rgb = np.min(rgb, axis=2)
albedo = min_rgb / cos_safe
vis = np.clip((albedo - 85.0) / 135.0, 0.0, 1.0) * whiteness * cool_gate
vis_u8 = np.where(valid, np.clip(np.round(vis * 255.0), 0, 255), 0).astype(np.uint8)
density = np.maximum(ir_density, vis_u8)
else:
density, _ = _decode_ir_density_and_temp(rgba, provider)
density = cv2.GaussianBlur(density, (3, 3), 0.5)
out = np.empty_like(rgba)
out[:, :, 0] = density
out[:, :, 1] = density
out[:, :, 2] = density
out[:, :, 3] = density
out_img = Image.fromarray(out, mode="RGBA")
else:
with Image.open(io.BytesIO(raw_bytes)) as img:
out_img = img.convert("RGB")
buf = io.BytesIO()
out_img.save(buf, format="WEBP", quality=84, method=1)
return buf.getvalue()
def summarize_tile_source_cache(source_key: str) -> dict[str, Any]:
root = _source_dir(source_key)
if not root.exists():
return {"tile_count": 0, "total_bytes": 0, "total_mb": 0.0, "zoom_levels": []}
tile_count = 0
total_bytes = 0
zooms: set[int] = set()
for path in root.rglob("*.webp"):
if path.name.startswith(".") or not path.is_file():
continue
tile_count += 1
try:
total_bytes += path.stat().st_size
zoom_dir = path.relative_to(root).parts[0]
if zoom_dir.isdigit():
zooms.add(int(zoom_dir))
except (OSError, IndexError, ValueError):
pass
return {
"tile_count": tile_count,
"total_bytes": total_bytes,
"total_mb": round(total_bytes / (1024 * 1024), 2),
"zoom_levels": sorted(zooms),
}
def prune_tile_source_cache(source_key: str, max_cache_mb: int) -> int:
root = _source_dir(source_key)
if not root.exists():
return 0
limit_bytes = max(16, int(max_cache_mb)) * 1024 * 1024
files: list[tuple[float, int, Path]] = []
total_bytes = 0
for path in root.rglob("*.webp"):
if path.name.startswith(".") or not path.is_file():
continue
try:
st = path.stat()
except OSError:
continue
total_bytes += st.st_size
files.append((st.st_mtime, st.st_size, path))
if total_bytes <= limit_bytes:
return 0
files.sort(key=lambda item: item[0])
removed = 0
for _mtime, size, path in files:
if total_bytes <= limit_bytes:
break
try:
path.unlink()
total_bytes -= size
removed += 1
except OSError:
pass
return removed
def clear_tile_source_cache(source_key: str) -> int:
root = _source_dir(source_key)
if not root.exists():
return 0
removed = 0
for path in root.rglob("*"):
if path.is_file():
try:
path.unlink()
removed += 1
except OSError:
pass
for directory in sorted((p for p in root.rglob("*") if p.is_dir()), reverse=True):
try:
directory.rmdir()
except OSError:
pass
return removed
async def _get_source_runtime_settings(
db: AsyncSession | None,
source_key: str,
) -> tuple[bool, str, dict[str, Any]]:
default_template = DEFAULT_TILE_TEMPLATES[source_key]
ds_active = True
endpoint = default_template
cfg: dict[str, Any] = {
"warmup_max_zoom": 2 if source_key == "cloud_hd_tiles" else 3,
"max_zoom": 7 if source_key == "cloud_hd_tiles" else (10 if source_key == "earth_imagery_sentinel2" else 9),
"max_cache_mb": 512 if source_key == "cloud_hd_tiles" else 1024,
"request_timeout_seconds": 15,
}
if db is None or not hasattr(db, "execute"):
return ds_active, endpoint, cfg
try:
ds_row = (
await db.execute(select(DataSource).where(DataSource.source == source_key))
).scalar_one_or_none()
if ds_row is not None:
ds_active = bool(ds_row.is_active)
except Exception:
pass
try:
cfg_row = (
await db.execute(select(DataSourceConfig).where(DataSourceConfig.name == source_key))
).scalar_one_or_none()
if cfg_row is not None:
if cfg_row.endpoint:
endpoint = str(cfg_row.endpoint).strip()
if isinstance(cfg_row.config, dict):
for key, val in cfg_row.config.items():
if val is not None:
cfg[key] = val
except Exception:
pass
try:
yaml_url = await get_data_sources_config().get_url(source_key, db)
if yaml_url:
endpoint = yaml_url
except Exception:
pass
return ds_active, endpoint, cfg
def _is_cloud_tile_fresh(target: Path) -> bool:
try:
return (time.time() - target.stat().st_mtime) < CLOUD_HD_TILE_TTL_SECONDS
except OSError:
return False
def _is_valid_image_response(resp: Any) -> bool:
if not isinstance(resp, httpx.Response) or resp.status_code != 200:
return False
ctype = str(resp.headers.get("content-type") or "").lower()
return ctype.startswith("image/")
async def _safe_get(
client: httpx.AsyncClient,
url: str,
params: dict[str, str] | None = None,
) -> httpx.Response | Exception:
try:
return await client.get(url, params=params)
except Exception as exc:
return exc
async def _fetch_and_encode_tile(
client: httpx.AsyncClient,
source_key: str,
template: str,
z: int,
x: int,
y: int,
*,
raise_on_error: bool = True,
) -> bytes | None:
if source_key == "cloud_hd_tiles":
cos_sza = _tile_solar_cosine(z, x, y)
is_daytime = cos_sza > 0.14
url, query_params, provider = _resolve_cloud_hd_request(
template, z, x, y, daytime=is_daytime
)
if provider in ("gibs_geocolor", "gibs_visible", "eumetview_visible"):
ir_url, ir_params, ir_provider, ir_z_src = _resolve_cloud_hd_ir_fallback(z, x, y)
primary_res, ir_res = await asyncio.gather(
_safe_get(client, url, query_params),
_safe_get(client, ir_url, ir_params),
)
ir_bytes = ir_res.content if _is_valid_image_response(ir_res) else None
if _is_valid_image_response(primary_res):
return await asyncio.to_thread(
_encode_tile_webp,
source_key,
primary_res.content,
provider=provider,
ir_bytes=ir_bytes,
ir_provider=ir_provider,
cos_sza=cos_sza,
z=z,
x=x,
y=y,
ir_z_src=ir_z_src,
)
if ir_bytes is not None:
return await asyncio.to_thread(
_encode_tile_webp,
source_key,
ir_bytes,
provider=ir_provider,
z=z,
x=x,
y=y,
)
if isinstance(primary_res, Exception) and raise_on_error:
raise primary_res
if isinstance(primary_res, httpx.Response) and primary_res.status_code not in (200, 404) and raise_on_error:
primary_res.raise_for_status()
return None
else:
url = (
template.replace("{z}", str(int(z)))
.replace("{y}", str(int(y)))
.replace("{x}", str(int(x)))
)
query_params = None
provider = "gibs"
response = await client.get(url, params=query_params)
if response.status_code == 404:
return None
response.raise_for_status()
if not _is_valid_image_response(response):
return None
return await asyncio.to_thread(
_encode_tile_webp,
source_key,
response.content,
provider=provider,
z=z,
x=x,
y=y,
)
async def get_or_fetch_tile(
source_key: str,
z: int,
x: int,
y: int,
*,
db: AsyncSession | None = None,
) -> tuple[bytes | None, bool]:
"""Return `(webp_bytes, is_allowed)` enforcing `DataSource.is_active` and caching as WebP."""
ds_active, template, cfg = await _get_source_runtime_settings(db, source_key)
max_zoom = int(cfg.get("max_zoom") or 8)
validate_tile_coords(source_key, z, x, y, max_zoom=max_zoom)
if not ds_active:
return None, False
target = _tile_path(source_key, z, x, y)
if target.exists() and (source_key != "cloud_hd_tiles" or _is_cloud_tile_fresh(target)):
try:
os.utime(target, None)
except OSError:
pass
return target.read_bytes(), True
timeout = httpx.Timeout(float(cfg.get("request_timeout_seconds") or 15))
headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthTileProxy)"}
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client:
webp_bytes = await _fetch_and_encode_tile(client, source_key, template, z, x, y)
if webp_bytes is None:
return None, True
await asyncio.to_thread(_atomic_write_bytes, target, webp_bytes)
return webp_bytes, True
async def warmup_tile_source(
source_key: str,
*,
db: AsyncSession | None = None,
max_zoom_override: int | None = None,
) -> dict[str, Any]:
"""Pre-warm z=0..warmup_max_zoom tile pyramid into managed local WebP storage."""
if source_key not in TILE_SOURCES:
raise ValueError(f"Unsupported tile source: {source_key}")
_ds_active, template, cfg = await _get_source_runtime_settings(db, source_key)
warmup_max = int(
max_zoom_override
if max_zoom_override is not None
else cfg.get("warmup_max_zoom") or (2 if source_key == "cloud_hd_tiles" else 3)
)
warmup_max = max(0, min(4, warmup_max))
max_cache_mb = int(cfg.get("max_cache_mb") or 1024)
timeout = httpx.Timeout(float(cfg.get("request_timeout_seconds") or 15))
headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthTileWarmup)"}
coords: list[tuple[int, int, int]] = []
for z in range(0, warmup_max + 1):
dim = 1 << z
for x in range(dim):
for y in range(dim):
coords.append((z, x, y))
fetched = 0
cached_hits = 0
failed = 0
total_bytes = 0
semaphore = asyncio.Semaphore(8)
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client:
async def _worker(z: int, x: int, y: int) -> None:
nonlocal fetched, cached_hits, failed, total_bytes
target = _tile_path(source_key, z, x, y)
if target.exists() and (source_key != "cloud_hd_tiles" or _is_cloud_tile_fresh(target)):
cached_hits += 1
try:
total_bytes += target.stat().st_size
except OSError:
pass
return
async with semaphore:
try:
webp_bytes = await _fetch_and_encode_tile(
client, source_key, template, z, x, y, raise_on_error=True
)
if webp_bytes is None:
failed += 1
return
await asyncio.to_thread(_atomic_write_bytes, target, webp_bytes)
fetched += 1
total_bytes += len(webp_bytes)
except Exception as exc:
failed += 1
logger.warning_event(
"Tile warmup request failed",
event="earth.tiles.warmup_failed",
context={"source": source_key, "z": z, "x": x, "y": y, "error": str(exc)},
)
await asyncio.gather(*(_worker(z, x, y) for z, x, y in coords))
pruned = await asyncio.to_thread(prune_tile_source_cache, source_key, max_cache_mb)
cache_stats = await asyncio.to_thread(summarize_tile_source_cache, source_key)
return {
"source": source_key,
"warmup_max_zoom": warmup_max,
"total_targets": len(coords),
"fetched": fetched,
"cached_hits": cached_hits,
"failed": failed,
"pruned": pruned,
"written_bytes": total_bytes,
"cache_stats": cache_stats,
}
async def prune_all_tile_caches(db: AsyncSession | None = None) -> int:
removed = 0
for source_key in TILE_SOURCES:
_, _, cfg = await _get_source_runtime_settings(db, source_key)
max_mb = int(cfg.get("max_cache_mb") or 1024)
removed += await asyncio.to_thread(prune_tile_source_cache, source_key, max_mb)
return removed
async def read_basemap_configuration(db: AsyncSession | None) -> dict[str, Any]:
if db is None or not callable(getattr(db, "execute", None)):
return _default_basemap_envelope()
result = await db.execute(
select(SystemSetting).where(SystemSetting.category == BASEMAP_CONFIG_CATEGORY)
)
record = result.scalar_one_or_none()
if not record or not isinstance(record.payload, dict):
return _default_basemap_envelope()
payload = dict(record.payload)
try:
validated = BasemapConfig.model_validate(payload.get("config") or {})
except Exception:
validated = DEFAULT_BASEMAP_CONFIG
return {
"config": validated.model_dump(mode="json"),
"revision": str(payload.get("revision") or DEFAULT_BASEMAP_REVISION),
"is_default": bool(payload.get("is_default", False)),
}
async def save_basemap_configuration(
db: AsyncSession,
*,
revision: str,
config: BasemapConfig,
actor: User,
reset: bool = False,
) -> dict[str, Any]:
dialect_name = ""
try:
bind = db.get_bind()
dialect_name = str(getattr(getattr(bind, "dialect", None), "name", "") or "").lower()
except Exception:
dialect_name = ""
if dialect_name == "postgresql":
await db.execute(
pg_insert(SystemSetting)
.values(category=BASEMAP_CONFIG_CATEGORY, payload=_default_basemap_envelope())
.on_conflict_do_nothing(index_elements=[SystemSetting.category])
)
record = (
await db.execute(
select(SystemSetting)
.where(SystemSetting.category == BASEMAP_CONFIG_CATEGORY)
.with_for_update()
)
).scalar_one()
else:
record = (
await db.execute(
select(SystemSetting).where(SystemSetting.category == BASEMAP_CONFIG_CATEGORY)
)
).scalar_one_or_none()
if record is None:
record = SystemSetting(
category=BASEMAP_CONFIG_CATEGORY,
payload=_default_basemap_envelope(),
)
db.add(record)
current_revision = str((record.payload or {}).get("revision") or DEFAULT_BASEMAP_REVISION)
if current_revision != revision:
await db.rollback()
raise BasemapRevisionConflictError(
"Configuration changed by another editor. Reload and retry."
)
envelope = (
_default_basemap_envelope()
if reset
else {
"config": config.model_dump(mode="json"),
"revision": uuid4().hex[:16],
"is_default": False,
}
)
before = dict(record.payload or {})
if reset:
if getattr(record, "id", None) is not None:
await db.delete(record)
else:
record.payload = envelope
db.add(
AuditLog(
actor_id=actor.id,
actor_name=actor.username,
action="earth_basemap.reset" if reset else "earth_basemap.update",
target_type="system_setting",
target_id=BASEMAP_CONFIG_CATEGORY,
result="success",
request_id=get_request_id(),
details={"before": before, "after": envelope},
)
)
await db.commit()
return envelope
async def get_basemap_runtime_meta(db: AsyncSession | None = None) -> dict[str, Any]:
envelope = await read_basemap_configuration(db)
config = BasemapConfig.model_validate(envelope["config"])
source_items: list[dict[str, Any]] = []
active_map: dict[str, bool] = {}
for source_key in TILE_SOURCES:
is_active, template, cfg = await _get_source_runtime_settings(db, source_key)
cache_stats = await asyncio.to_thread(summarize_tile_source_cache, source_key)
meta_defaults = DEFAULT_DATASOURCES.get(source_key, {})
active_map[source_key] = is_active
source_items.append(
{
"source": source_key,
"display_name": meta_defaults.get("display_name") or source_key,
"is_active": is_active,
"has_data": cache_stats["tile_count"] > 0,
"cached_tiles": cache_stats["tile_count"],
"cache_mb": cache_stats["total_mb"],
"zoom_levels": cache_stats["zoom_levels"],
"max_zoom": int(cfg.get("max_zoom") or config.max_zoom),
"warmup_max_zoom": int(cfg.get("warmup_max_zoom") or config.warmup_max_zoom),
"max_cache_mb": int(cfg.get("max_cache_mb") or config.max_cache_mb),
"tile_url_template": f"/api/v1/earth/tiles/{source_key}/{{z}}/{{x}}/{{y}}.webp",
"upstream_template": template,
}
)
active_source = config.active_source
hd_ready = bool(
config.hd_tiles_enabled
and active_source in BASEMAP_TILE_SOURCES
and active_map.get(active_source, False)
)
cloud_hd_ready = bool(
config.cloud_hd_tiles_enabled and active_map.get("cloud_hd_tiles", False)
)
return {
"active_source": active_source,
"hd_tiles_enabled": config.hd_tiles_enabled,
"cloud_hd_tiles_enabled": config.cloud_hd_tiles_enabled,
"hd_tiles_ready": hd_ready,
"cloud_hd_tiles_ready": cloud_hd_ready,
"lod_switch_altitude": config.lod_switch_altitude,
"max_zoom": config.max_zoom,
"warmup_max_zoom": config.warmup_max_zoom,
"max_cache_mb": config.max_cache_mb,
"tile_url_template": (
f"/api/v1/earth/tiles/{active_source}/{{z}}/{{x}}/{{y}}.webp"
if hd_ready
else None
),
"cloud_tile_url_template": (
"/api/v1/earth/tiles/cloud_hd_tiles/{z}/{x}/{y}.webp"
if cloud_hd_ready
else None
),
"sources": source_items,
}
+735
View File
@@ -0,0 +1,735 @@
"""NOAA NCEP GFS 10m global wind field collector, storage, analytics, and point query engine."""
from __future__ import annotations
import asyncio
import csv
from datetime import UTC, datetime
import io
import json
import math
import os
from pathlib import Path
import re
from typing import Any
from uuid import uuid4
import cv2
import httpx
import numpy as np
from pydantic import BaseModel, Field
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.data_sources import get_data_sources_config
from app.core.logging import get_logger
from app.core.time import to_iso8601_utc
from app.models.datasource import DataSource
from app.models.datasource_config import DataSourceConfig
logger = get_logger(__name__, service="earth_wind")
REPO_ROOT = Path(__file__).resolve().parents[3]
WIND_DATA_DIR = REPO_ROOT / "data" / "earth-wind"
DEFAULT_GFS_ERDDAP_URL = "https://pae-paha.pacioos.hawaii.edu/erddap/griddap/ncep_global.csv0"
VERSION_PATTERN = re.compile(r"^[A-Za-z0-9._-]{4,64}$")
_WIND_WRITE_LOCK = asyncio.Lock()
EARTH_CIRCUMFERENCE_KM = 40075.017
# Reuse consistent maritime / aviation meteorological zones for global posture rollups
WIND_REGIONS: tuple[dict[str, Any], ...] = (
{
"key": "west_pacific",
"name": "西北太平洋",
"name_en": "Western North Pacific",
"lat_min": 5.0,
"lat_max": 35.0,
"lon_min": 120.0,
"lon_max": 165.0,
},
{
"key": "east_asia_coast",
"name": "东亚沿海",
"name_en": "East Asia Coastal Corridor",
"lat_min": 18.0,
"lat_max": 42.0,
"lon_min": 105.0,
"lon_max": 135.0,
},
{
"key": "south_china_sea",
"name": "南海海域",
"name_en": "South China Sea",
"lat_min": 3.0,
"lat_max": 23.0,
"lon_min": 105.0,
"lon_max": 122.0,
},
{
"key": "indian_ocean",
"name": "印度洋航道",
"name_en": "Indian Ocean Corridor",
"lat_min": -20.0,
"lat_max": 20.0,
"lon_min": 50.0,
"lon_max": 98.0,
},
{
"key": "arabian_red_sea",
"name": "阿拉伯海与红海",
"name_en": "Arabian & Red Sea",
"lat_min": 10.0,
"lat_max": 30.0,
"lon_min": 32.0,
"lon_max": 68.0,
},
{
"key": "north_pacific",
"name": "北太平洋航线",
"name_en": "North Pacific Corridor",
"lat_min": 30.0,
"lat_max": 58.0,
"lon_min": 140.0,
"lon_max": -125.0,
},
{
"key": "gulf_caribbean",
"name": "墨西哥湾与加勒比",
"name_en": "Gulf & Caribbean",
"lat_min": 10.0,
"lat_max": 32.0,
"lon_min": -98.0,
"lon_max": -60.0,
},
{
"key": "north_atlantic",
"name": "北大西洋航道",
"name_en": "North Atlantic Corridor",
"lat_min": 35.0,
"lat_max": 62.0,
"lon_min": -60.0,
"lon_max": -10.0,
},
)
class WindFieldConfig(BaseModel):
grid_step_deg: float = Field(default=2.0, ge=1.0, le=5.0)
gale_threshold_ms: float = Field(default=17.2, ge=10.0, le=35.0)
request_timeout_seconds: int = Field(default=25, ge=5, le=60)
max_history_runs: int = Field(default=12, ge=2, le=48)
DEFAULT_WIND_CONFIG = WindFieldConfig()
def _wind_dir() -> Path:
return WIND_DATA_DIR
def _manifest_path() -> Path:
return _wind_dir() / "manifest.json"
def _grids_dir() -> Path:
return _wind_dir() / "grids"
def _ensure_wind_dirs() -> None:
_grids_dir().mkdir(parents=True, exist_ok=True)
def _atomic_write_bytes(path: Path, content: bytes) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = path.with_name(f".{path.name}.{uuid4().hex[:8]}.tmp")
try:
tmp_path.write_bytes(content)
os.replace(tmp_path, path)
finally:
if tmp_path.exists():
try:
tmp_path.unlink()
except OSError:
pass
def _atomic_write_json(path: Path, payload: Any) -> None:
encoded = json.dumps(payload, ensure_ascii=False, indent=2).encode("utf-8")
_atomic_write_bytes(path, encoded)
def _read_manifest() -> dict[str, Any]:
path = _manifest_path()
if not path.exists():
return {"latest_version": None, "updated_at": None, "runs": []}
try:
parsed = json.loads(path.read_text(encoding="utf-8"))
if isinstance(parsed, dict) and isinstance(parsed.get("runs"), list):
return parsed
except Exception:
pass
return {"latest_version": None, "updated_at": None, "runs": []}
def _wind_vector_to_bearing_deg(u_ms: float, v_ms: float) -> float:
"""Meteorological heading TO which wind blows (0=N, 90=E, 180=S, 270=W)."""
return (math.degrees(math.atan2(u_ms, v_ms)) + 360.0) % 360.0
def _bearing_to_cardinal(deg: float) -> str:
dirs = ("N", "NE", "E", "SE", "S", "SW", "W", "NW")
idx = int(round((deg % 360.0) / 45.0)) % 8
return dirs[idx]
def _speed_to_beaufort(speed_ms: float) -> int:
thresholds = (0.3, 1.6, 3.4, 5.5, 8.0, 10.8, 13.9, 17.2, 20.8, 24.5, 28.5, 32.7)
for force, limit in enumerate(thresholds):
if speed_ms < limit:
return force
return 12
def _match_region_name(lat: float, lon: float) -> tuple[str, str]:
wrapped = ((float(lon) + 180.0) % 360.0) - 180.0
for reg in WIND_REGIONS:
if not (reg["lat_min"] <= lat <= reg["lat_max"]):
continue
lon_min, lon_max = reg["lon_min"], reg["lon_max"]
if lon_min <= lon_max:
in_lon = lon_min <= wrapped <= lon_max
else:
in_lon = wrapped >= lon_min or wrapped <= lon_max
if in_lon:
return reg["name"], reg["name_en"]
return "公海全球风场", "Global High Seas"
async def read_wind_configuration(db: AsyncSession | None = None) -> dict[str, Any]:
endpoint = DEFAULT_GFS_ERDDAP_URL
raw_cfg: dict[str, Any] = {}
if db is not None and hasattr(db, "execute"):
try:
row = (
await db.execute(
select(DataSourceConfig).where(DataSourceConfig.name == "global_wind_gfs")
)
).scalar_one_or_none()
if row is not None:
if row.endpoint:
endpoint = str(row.endpoint).strip()
if isinstance(row.config, dict):
raw_cfg = dict(row.config)
except Exception:
pass
try:
yaml_url = await get_data_sources_config().get_url("global_wind_gfs", db)
if yaml_url:
endpoint = yaml_url
except Exception:
pass
try:
validated = WindFieldConfig.model_validate(raw_cfg)
except Exception:
validated = DEFAULT_WIND_CONFIG
return {
"endpoint": endpoint,
"config": validated.model_dump(mode="json"),
}
def parse_erddap_csv0_wind(csv_text: str) -> dict[str, Any]:
"""Parse PacIOOS ERDDAP `ncep_global.csv0` `ugrd10m,vgrd10m` into `[-180..180]` grids."""
rows: list[tuple[float, float, float, float]] = []
forecast_time: str | None = None
reader = csv.reader(io.StringIO(csv_text))
for line in reader:
if len(line) < 5:
continue
t_raw, lat_s, lon_s, u_s, v_s = line[0].strip(), line[1].strip(), line[2].strip(), line[3].strip(), line[4].strip()
if t_raw.lower() == "time" or lat_s.lower() == "latitude":
continue
try:
lat = float(lat_s)
lon_raw = float(lon_s)
u_val = float(u_s)
v_val = float(v_s)
except ValueError:
continue
if not (math.isfinite(lat) and math.isfinite(lon_raw) and math.isfinite(u_val) and math.isfinite(v_val)):
continue
if forecast_time is None and t_raw:
forecast_time = t_raw
# Shift 0..360 longitude to [-180, 180)
lon_norm = ((lon_raw + 180.0) % 360.0) - 180.0
rows.append((round(lat, 3), round(lon_norm, 3), u_val, v_val))
if not rows:
raise RuntimeError("GFS wind ERDDAP payload contained zero valid grid samples")
lats = sorted({item[0] for item in rows})
lons = sorted({item[1] for item in rows})
lat_idx = {val: i for i, val in enumerate(lats)}
lon_idx = {val: i for i, val in enumerate(lons)}
height = len(lats)
width = len(lons)
u_grid = np.zeros((height, width), dtype=np.float32)
v_grid = np.zeros((height, width), dtype=np.float32)
for lat, lon, u_val, v_val in rows:
u_grid[lat_idx[lat], lon_idx[lon]] = u_val
v_grid[lat_idx[lat], lon_idx[lon]] = v_val
return {
"forecast_time": forecast_time,
"lats": np.asarray(lats, dtype=np.float32),
"lons": np.asarray(lons, dtype=np.float32),
"u": u_grid,
"v": v_grid,
}
def analyze_wind_grid(
parsed: dict[str, Any],
*,
config: WindFieldConfig,
) -> dict[str, Any]:
lats = parsed["lats"]
lons = parsed["lons"]
u_grid = parsed["u"]
v_grid = parsed["v"]
speed = np.sqrt(u_grid * u_grid + v_grid * v_grid).astype(np.float32)
lat_weights = np.maximum(np.cos(np.deg2rad(lats)), 0.05).astype(np.float32)[:, None]
weight_sum = float(np.sum(lat_weights) * speed.shape[1])
mean_speed = float(np.sum(speed * lat_weights) / max(weight_sum, 1e-6))
max_speed = float(np.max(speed))
gale_mask = speed >= float(config.gale_threshold_ms)
gale_cov_pct = float(np.sum(gale_mask.astype(np.float32) * lat_weights) / max(weight_sum, 1e-6) * 100.0)
# Identify coherent gale/storm cores via connected components
gale_u8 = (gale_mask.astype(np.uint8) * 255)
num_labels, labels, stats, _centroids = cv2.connectedComponentsWithStats(gale_u8, connectivity=8)
dlat = abs(float(lats[1] - lats[0])) if len(lats) > 1 else config.grid_step_deg
dlon = abs(float(lons[1] - lons[0])) if len(lons) > 1 else config.grid_step_deg
storm_cores: list[dict[str, Any]] = []
for label_id in range(1, num_labels):
pixel_count = int(stats[label_id, cv2.CC_STAT_AREA])
if pixel_count < 3:
continue
comp_mask = labels == label_id
comp_lats = lats[np.where(comp_mask)[0]]
comp_lons = lons[np.where(comp_mask)[1]]
center_lat = float(np.mean(comp_lats))
center_lon = float(np.mean(comp_lons))
comp_speeds = speed[comp_mask]
peak_ms = float(np.max(comp_speeds))
avg_ms = float(np.mean(comp_speeds))
cell_area = (
(dlat / 360.0) * EARTH_CIRCUMFERENCE_KM
* ((dlon / 360.0) * EARTH_CIRCUMFERENCE_KM * max(math.cos(math.radians(center_lat)), 0.1))
)
area_km2 = round(pixel_count * cell_area)
region_zh, region_en = _match_region_name(center_lat, center_lon)
storm_cores.append(
{
"id": f"gale-{label_id}",
"lat": round(center_lat, 2),
"lon": round(center_lon, 2),
"max_speed_ms": round(peak_ms, 1),
"mean_speed_ms": round(avg_ms, 1),
"beaufort": _speed_to_beaufort(peak_ms),
"area_km2": area_km2,
"region": region_zh,
"region_en": region_en,
"severity": "storm" if peak_ms >= 24.5 else "gale",
}
)
storm_cores.sort(key=lambda item: item["max_speed_ms"], reverse=True)
storm_cores = storm_cores[:24]
region_summaries: list[dict[str, Any]] = []
for reg in WIND_REGIONS:
lat_mask = (lats >= reg["lat_min"]) & (lats <= reg["lat_max"])
if reg["lon_min"] <= reg["lon_max"]:
lon_mask = (lons >= reg["lon_min"]) & (lons <= reg["lon_max"])
else:
lon_mask = (lons >= reg["lon_min"]) | (lons <= reg["lon_max"])
sub_mask = np.outer(lat_mask, lon_mask)
if not np.any(sub_mask):
continue
sub_speed = speed[sub_mask]
sub_u = u_grid[sub_mask]
sub_v = v_grid[sub_mask]
mean_reg = float(np.mean(sub_speed))
max_reg = float(np.max(sub_speed))
gale_reg = float(np.mean(sub_speed >= float(config.gale_threshold_ms)) * 100.0)
dom_u = float(np.mean(sub_u))
dom_v = float(np.mean(sub_v))
dom_deg = _wind_vector_to_bearing_deg(dom_u, dom_v)
posture = "gale_warning" if gale_reg >= 12.0 or max_reg >= 20.8 else ("breezy" if mean_reg >= 10.8 else "moderate")
region_summaries.append(
{
"key": reg["key"],
"name": reg["name"],
"name_en": reg["name_en"],
"mean_speed_ms": round(mean_reg, 1),
"max_speed_ms": round(max_reg, 1),
"gale_coverage_pct": round(gale_reg, 1),
"dominant_direction_deg": round(dom_deg, 1),
"dominant_cardinal": _bearing_to_cardinal(dom_deg),
"posture": posture,
}
)
return {
"global_summary": {
"mean_speed_ms": round(mean_speed, 2),
"max_speed_ms": round(max_speed, 2),
"gale_coverage_pct": round(gale_cov_pct, 2),
"storm_core_count": len(storm_cores),
"grid_width": int(u_grid.shape[1]),
"grid_height": int(u_grid.shape[0]),
"step_deg": round(float(config.grid_step_deg), 2),
"forecast_time": parsed.get("forecast_time"),
},
"regions": region_summaries,
"storm_cores": storm_cores,
}
def _remove_wind_run_files(version: str) -> int:
if not VERSION_PATTERN.match(version):
return 0
target = _grids_dir() / f"{version}.npz"
if target.exists():
try:
target.unlink()
return 1
except OSError:
pass
return 0
def prune_wind_artifacts(max_runs: int = 12) -> int:
if not _wind_dir().exists():
return 0
manifest = _read_manifest()
runs = manifest.get("runs", [])
kept = runs[: max(1, int(max_runs))]
kept_versions = {str(item.get("version")) for item in kept if item.get("version")}
removed = 0
for item in runs[max(1, int(max_runs)) :]:
ver = str(item.get("version") or "")
if ver:
removed += _remove_wind_run_files(ver)
if _grids_dir().exists():
for file_path in _grids_dir().iterdir():
if file_path.name.startswith(".") or file_path.stem not in kept_versions:
try:
file_path.unlink()
removed += 1
except OSError:
pass
if len(kept) != len(runs):
_atomic_write_json(
_manifest_path(),
{
"latest_version": kept[0].get("version") if kept else None,
"updated_at": manifest.get("updated_at"),
"runs": kept,
},
)
return removed
def clear_all_wind_artifacts() -> int:
removed = 0
if _grids_dir().exists():
for file_path in _grids_dir().iterdir():
if file_path.is_file():
try:
file_path.unlink()
removed += 1
except OSError:
pass
manifest_file = _manifest_path()
if manifest_file.exists():
try:
manifest_file.unlink()
removed += 1
except OSError:
pass
return removed
def _save_wind_run_sync(
*,
version: str,
captured_at: str,
parsed: dict[str, Any],
analysis: dict[str, Any],
max_history_runs: int,
) -> dict[str, Any]:
_ensure_wind_dirs()
grid_path = _grids_dir() / f"{version}.npz"
tmp_path = grid_path.with_name(f".{version}.{uuid4().hex[:8]}.npz")
try:
np.savez_compressed(
tmp_path,
lats=parsed["lats"],
lons=parsed["lons"],
u=parsed["u"],
v=parsed["v"],
)
os.replace(tmp_path, grid_path)
finally:
if tmp_path.exists():
try:
tmp_path.unlink()
except OSError:
pass
entry = {
"version": version,
"captured_at": captured_at,
"forecast_time": parsed.get("forecast_time"),
"source": "global_wind_gfs",
"grid_url": f"/api/v1/earth/wind/grid/{version}",
"file_size_bytes": grid_path.stat().st_size if grid_path.exists() else 0,
"global_summary": analysis["global_summary"],
"regions": analysis["regions"],
"storm_cores": analysis["storm_cores"],
}
manifest = _read_manifest()
runs = [item for item in manifest.get("runs", []) if item.get("version") != version]
runs.insert(0, entry)
kept_runs = runs[: max(1, int(max_history_runs))]
dropped = [str(item.get("version") or "") for item in runs[max(1, int(max_history_runs)) :]]
_atomic_write_json(
_manifest_path(),
{
"latest_version": version,
"updated_at": captured_at,
"runs": kept_runs,
},
)
for old_ver in dropped:
_remove_wind_run_files(old_ver)
return entry
async def collect_latest_wind_grid(db: AsyncSession | None = None) -> dict[str, Any]:
env = await read_wind_configuration(db)
config = WindFieldConfig.model_validate(env["config"])
endpoint = str(env["endpoint"] or DEFAULT_GFS_ERDDAP_URL).rstrip("/")
stride = max(1, int(round(float(config.grid_step_deg) * 2.0)))
query_url = (
f"{endpoint}?ugrd10m[(last)][(-90):{stride}:(90)][(0):{stride}:(359.5)],"
f"vgrd10m[(last)][(-90):{stride}:(90)][(0):{stride}:(359.5)]"
)
timeout = httpx.Timeout(float(config.request_timeout_seconds))
headers = {"User-Agent": "Planet-Intelligence-System/1.0 (EarthWindCollector)"}
async with httpx.AsyncClient(timeout=timeout, follow_redirects=True, headers=headers) as client:
response = await client.get(query_url)
response.raise_for_status()
csv_text = response.text
parsed = await asyncio.to_thread(parse_erddap_csv0_wind, csv_text)
analysis = await asyncio.to_thread(analyze_wind_grid, parsed, config=config)
now_utc = datetime.now(UTC)
version = now_utc.strftime("%Y%m%dT%H%M%SZ")
captured_at = to_iso8601_utc(now_utc) or now_utc.isoformat()
async with _WIND_WRITE_LOCK:
entry = await asyncio.to_thread(
_save_wind_run_sync,
version=version,
captured_at=captured_at,
parsed=parsed,
analysis=analysis,
max_history_runs=config.max_history_runs,
)
return {
"run": entry,
"global_summary": analysis["global_summary"],
"regions": analysis["regions"],
"storm_cores": analysis["storm_cores"],
"config": config.model_dump(mode="json"),
}
def _load_wind_npz(version: str) -> dict[str, np.ndarray] | None:
if not VERSION_PATTERN.match(version):
return None
path = (_grids_dir() / f"{version}.npz").resolve()
root = _grids_dir().resolve()
if path.parent != root or not path.exists():
return None
with np.load(path, allow_pickle=False) as archive:
return {
"lats": archive["lats"].copy(),
"lons": archive["lons"].copy(),
"u": archive["u"].copy(),
"v": archive["v"].copy(),
}
async def get_wind_runtime_meta(db: AsyncSession | None = None) -> dict[str, Any]:
ds_active = True
if db is not None and hasattr(db, "execute"):
try:
row = (
await db.execute(select(DataSource).where(DataSource.source == "global_wind_gfs"))
).scalar_one_or_none()
if row is not None:
ds_active = bool(row.is_active)
except Exception:
pass
manifest = _read_manifest()
runs = manifest.get("runs", [])
latest = runs[0] if runs else None
latest_version = str(latest.get("version")) if isinstance(latest, dict) and latest.get("version") else None
exists = bool(latest_version and (_grids_dir() / f"{latest_version}.npz").exists())
available = bool(ds_active and exists)
return {
"available": available,
"is_active": ds_active,
"version": latest_version if exists else None,
"captured_at": latest.get("captured_at") if exists and latest else None,
"forecast_time": latest.get("forecast_time") if exists and latest else None,
"grid_url": f"/api/v1/earth/wind/grid/{latest_version}" if available else None,
"global_summary": (latest.get("global_summary") or {}) if exists and latest else {},
"regions": (latest.get("regions") or []) if exists and latest else [],
"storm_cores": (latest.get("storm_cores") or []) if exists and latest else [],
"has_data": exists,
}
def read_wind_grid_payload(version: str) -> dict[str, Any] | None:
manifest = _read_manifest()
entry = next(
(item for item in manifest.get("runs", []) if item.get("version") == version),
None,
)
arrays = _load_wind_npz(version)
if arrays is None:
return None
lats = arrays["lats"]
lons = arrays["lons"]
u = arrays["u"]
v = arrays["v"]
speed = np.sqrt(u * u + v * v)
return {
"version": version,
"captured_at": entry.get("captured_at") if entry else None,
"forecast_time": entry.get("forecast_time") if entry else None,
"width": int(u.shape[1]),
"height": int(u.shape[0]),
"lat_min": float(lats[0]),
"lat_max": float(lats[-1]),
"lon_min": float(lons[0]),
"lon_max": float(lons[-1]),
"max_speed_ms": round(float(np.max(speed)), 2),
"u": [round(float(val), 2) for val in u.ravel().tolist()],
"v": [round(float(val), 2) for val in v.ravel().tolist()],
}
async def query_wind_point(
lat: float,
lon: float,
db: AsyncSession | None = None,
) -> dict[str, Any]:
env = await read_wind_configuration(db)
config = WindFieldConfig.model_validate(env["config"])
manifest = _read_manifest()
runs = manifest.get("runs", [])
latest = runs[0] if runs else None
version = str(latest.get("version") or "") if isinstance(latest, dict) else ""
arrays = _load_wind_npz(version) if version else None
if arrays is None:
return {
"available": False,
"latitude": round(float(lat), 4),
"longitude": round(float(lon), 4),
"u_ms": None,
"v_ms": None,
"speed_ms": None,
"direction_deg": None,
"direction_cardinal": None,
"beaufort": None,
}
lats = arrays["lats"]
lons = arrays["lons"]
u_arr = arrays["u"]
v_arr = arrays["v"]
clamped_lat = max(float(lats[0]), min(float(lats[-1]), float(lat)))
wrapped_lon = ((float(lon) + 180.0) % 360.0) - 180.0
# Bilinear interpolation across grid
lat_pos = float(np.interp(clamped_lat, lats, np.arange(len(lats), dtype=np.float32)))
lon_pos = float(np.interp(wrapped_lon, lons, np.arange(len(lons), dtype=np.float32)))
r0 = min(int(math.floor(lat_pos)), len(lats) - 1)
r1 = min(r0 + 1, len(lats) - 1)
c0 = min(int(math.floor(lon_pos)), len(lons) - 1)
c1 = min(c0 + 1, len(lons) - 1)
dr = lat_pos - r0
dc = lon_pos - c0
def _bilerp(grid: np.ndarray) -> float:
top = float(grid[r0, c0]) * (1.0 - dc) + float(grid[r0, c1]) * dc
bot = float(grid[r1, c0]) * (1.0 - dc) + float(grid[r1, c1]) * dc
return top * (1.0 - dr) + bot * dr
u_val = _bilerp(u_arr)
v_val = _bilerp(v_arr)
speed = math.hypot(u_val, v_val)
bearing = _wind_vector_to_bearing_deg(u_val, v_val)
region_zh, region_en = _match_region_name(lat, lon)
return {
"available": True,
"latitude": round(float(lat), 4),
"longitude": round(float(lon), 4),
"u_ms": round(u_val, 2),
"v_ms": round(v_val, 2),
"speed_ms": round(speed, 2),
"direction_deg": round(bearing, 1),
"direction_cardinal": _bearing_to_cardinal(bearing),
"beaufort": _speed_to_beaufort(speed),
"is_gale": speed >= float(config.gale_threshold_ms),
"region": region_zh,
"region_en": region_en,
"version": version,
"captured_at": latest.get("captured_at") if latest else None,
"forecast_time": latest.get("forecast_time") if latest else None,
}
async def get_wind_analysis_summary(db: AsyncSession | None = None) -> dict[str, Any]:
meta = await get_wind_runtime_meta(db)
return {
"available": meta["available"],
"is_active": meta["is_active"],
"version": meta["version"],
"captured_at": meta["captured_at"],
"forecast_time": meta["forecast_time"],
"global_summary": meta["global_summary"],
"regions": meta["regions"],
"storm_cores": meta["storm_cores"],
}
@@ -1,664 +0,0 @@
"""Controlled multi-step Tool-Calling agent & L1 resolvers for unknown facility locations."""
from __future__ import annotations
import asyncio
from datetime import UTC, datetime
import json
from typing import Any
from uuid import uuid4
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.logging import get_logger
from app.models.compute_center_location import ComputeCenterLocationRecord
from app.models.situational_assessment import WorkflowRun
from app.schemas.ai import SituationalAnalysisRequest
from app.services.ai.tool_registry import isolate_untrusted_external_text, safe_web_fetch
from app.services.ai.workflow_registry import resolve_runtime_workflow_node
from app.services.location.llm_fallback import (
DEFAULT_MIN_CONFIDENCE,
LocationLLMFallbackResult,
collect_llm_location_fallback_candidate,
)
from app.services.location.models import LocationCandidate, LocationQuery
from app.services.location.resolvers.nominatim import build_default_nominatim_geocoder
from app.services.location.resolvers.peeringdb_facility import lookup_peeringdb_facility
from app.services.location.resolvers.wikidata import lookup_wikidata_facility
from app.services.location.text import coerce_str, normalize_country_text, normalize_text, parse_float
logger = get_logger(__name__, service="location_agent")
TERMINAL_UNLOCATABLE_STATUSES: frozenset[str] = frozenset({"undisclosed", "multi_site", "anonymous"})
_agent_geocoder = build_default_nominatim_geocoder()
LOCATION_AGENT_TOOLS: list[dict[str, Any]] = [
{
"name": "fetch_source_url",
"description": "Fetch and read a primary source webpage (especially Epoch Source 1..5 or TOP500 detail URL) cleanly with prompt-injection isolation.",
"parameters": {
"type": "object",
"properties": {"url": {"type": "string", "description": "Public http/https URL"}},
"required": ["url"],
},
},
{
"name": "web_search",
"description": "Search the web using concise English or local-language queries (do not chain long hardware suffixes).",
"parameters": {
"type": "object",
"properties": {"query": {"type": "string", "description": "Concise search query"}},
"required": ["query"],
},
},
{
"name": "geocode_verify",
"description": "Verify a physical facility address or city via geocoder and receive a verified geocode_candidate_id with coordinates and country.",
"parameters": {
"type": "object",
"properties": {
"place_query": {"type": "string", "description": "Address, campus, or city + country"},
"country": {"type": "string", "description": "Expected country name"},
},
"required": ["place_query"],
},
},
{
"name": "submit_location_result",
"description": "Finalize location verification using a geocode_candidate_id from geocode_verify, or report a terminal status (undisclosed/multi_site/anonymous/unresolved).",
"parameters": {
"type": "object",
"properties": {
"status": {
"type": "string",
"enum": ["located", "undisclosed", "multi_site", "anonymous", "unresolved"],
},
"facility_name": {"type": "string"},
"address": {"type": "string"},
"city": {"type": "string"},
"region": {"type": "string"},
"country": {"type": "string"},
"precision": {"type": "string", "enum": ["precise", "site", "city"]},
"geocode_candidate_id": {"type": "string"},
"citations": {
"type": "array",
"items": {"type": "string"},
"description": "URLs directly observed in fetch_source_url or web_search outputs",
},
"confidence": {"type": "number"},
"reasoning": {"type": "string"},
},
"required": ["status", "reasoning"],
},
},
]
async def run_l1_structured_facility_resolvers(
query: LocationQuery,
*,
db: AsyncSession | None = None,
) -> tuple[list[LocationCandidate], list[str], bool]:
"""Run async L1 Wikidata & PeeringDB lookups respecting `location.resolve_unknown` config."""
l1_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l1_knowledge")
params = (l1_node or {}).get("params") or {}
enabled_tools = set((l1_node or {}).get("tools") or [])
allow_low_short_circuit = bool(params.get("allow_low_confidence_short_circuit", False))
tasks = []
if params.get("wikidata_enabled", True) and (not enabled_tools or "wikidata_lookup" in enabled_tools):
tasks.append(lookup_wikidata_facility(query))
if params.get("peeringdb_enabled", True) and (not enabled_tools or "peeringdb_fac_lookup" in enabled_tools):
tasks.append(lookup_peeringdb_facility(query))
candidates: list[LocationCandidate] = []
attempted: list[str] = []
if tasks:
results = await asyncio.gather(*tasks, return_exceptions=True)
for out in results:
if isinstance(out, Exception):
continue
attempted.extend(out.attempted_queries)
candidates.extend(out.candidates)
return candidates, attempted, allow_low_short_circuit
async def _persist_terminal_location_status(
db: AsyncSession | None,
*,
query: LocationQuery,
terminal_status: str,
reasoning: str,
) -> None:
if db is None or not hasattr(db, "execute"):
return
extra = query.extra or {}
source = coerce_str(extra.get("source"))
source_id = coerce_str(extra.get("source_id"))
if not source or not source_id:
return
try:
from app.services.compute_center_locations import refresh_compute_center_location_cache
existing = await db.scalar(
select(ComputeCenterLocationRecord)
.where(ComputeCenterLocationRecord.source == source)
.where(ComputeCenterLocationRecord.source_id == source_id)
)
if existing is None:
existing = ComputeCenterLocationRecord(
source=source,
source_id=source_id,
name=query.name,
operator=coerce_str(extra.get("operator")) or None,
site=coerce_str(extra.get("site")) or None,
city=query.city,
country=query.country,
latitude=None,
longitude=None,
precision="unknown",
confidence=0.0,
location_source=f"agent_terminal_{terminal_status}",
source_note=reasoning[:500] or f"Marked {terminal_status} by location agent",
needs_confirmation=False,
verification_status=terminal_status,
verified_at=datetime.now(UTC),
)
db.add(existing)
else:
existing.precision = "unknown"
existing.latitude = None
existing.longitude = None
existing.verification_status = terminal_status
existing.location_source = f"agent_terminal_{terminal_status}"
existing.source_note = reasoning[:500] or existing.source_note
existing.verified_at = datetime.now(UTC)
await db.commit()
await refresh_compute_center_location_cache(db)
except Exception as exc:
logger.warning_event(
"Failed to persist terminal unlocatable status",
event="location.agent.persist_terminal_failed",
context={"source_id": source_id, "status": terminal_status, "error": str(exc)},
)
async def _record_location_workflow_run(
db: AsyncSession | None,
*,
question: str,
status_value: str,
tool_trace: list[str],
steps_used: int,
error_message: str = "",
) -> None:
if db is None or not hasattr(db, "add"):
return
try:
db.add(
WorkflowRun(
id=f"run_{uuid4().hex[:16]}",
workflow_id="location.resolve_unknown",
status=status_value,
access_tier="admin",
actor_key="admin:collect-location",
question=question[:500],
tool_trace=tool_trace,
budget_used={"steps": steps_used},
error_message=error_message[:500],
completed_at=datetime.now(UTC),
)
)
await db.commit()
except Exception:
try:
await db.rollback()
except Exception:
pass
async def run_controlled_location_agent(
*,
provider_client: Any,
web_search_client: Any | None,
query: LocationQuery,
entity_type: str = "compute_center",
db: AsyncSession | None = None,
attempted_queries: list[str] | None = None,
) -> tuple[LocationLLMFallbackResult, str | None]:
"""Run the 3-4 step Tool-Calling location agent and return `(result, terminal_status)`."""
extra = query.extra or {}
l2_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l2_agent_research")
l3_node = await resolve_runtime_workflow_node(db, "location.resolve_unknown", "l3_geo_guardrail")
if l2_node and not l2_node.get("enabled", True):
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=list(attempted_queries or []),
failure_reason="Location agent node is disabled by workflow configuration.",
),
None,
)
max_steps = max(1, min(int((l2_node or {}).get("max_steps") or 4), 6))
allowed_tool_names = set((l2_node or {}).get("tools") or [t["name"] for t in LOCATION_AGENT_TOOLS])
min_confidence = float(((l3_node or {}).get("guardrails") or {}).get("min_confidence") or DEFAULT_MIN_CONFIDENCE)
require_tool_urls = bool(((l3_node or {}).get("guardrails") or {}).get("require_tool_cited_urls", True))
active_tools = [t for t in LOCATION_AGENT_TOOLS if t["name"] in allowed_tool_names]
if not any(t["name"] == "submit_location_result" for t in active_tools):
active_tools.append(LOCATION_AGENT_TOOLS[-1])
observed_urls: set[str] = set()
geocode_candidates: dict[str, dict[str, Any]] = {}
tool_trace: list[str] = ["l0_normalize", "l1_knowledge"]
agent_attempts: list[str] = []
source_urls = [
str(u).strip()
for u in [*([extra.get("source_url")] if extra.get("source_url") else []), *(extra.get("sources") or [])]
if str(u or "").strip().startswith(("http://", "https://"))
]
system_prompt = (l2_node or {}).get("system_prompt") or (
"你是算力与网络基础设施物理位置查证 Agent。严禁编造经纬度!"
"1) 若存在 primary_source_urls,优先调用 fetch_source_url;"
"2) 否则调用 web_search 查询物理地址;"
"3) 将查到的物理地址/城市传入 geocode_verify 获取 candidate_id;"
"4) 最后调用 submit_location_result 提交结果。"
)
user_objective = (l2_node or {}).get("prompt") or (
f"请查证目标设施 {query.name or extra.get('source_id')} 的物理所在城市或园区。"
)
context_payload = {
"name": query.name,
"name_short": query.aliases[0] if query.aliases else query.name,
"operator": extra.get("operator") or None,
"site": extra.get("site") or None,
"city": query.city,
"country": query.country,
"raw_country": extra.get("source_raw_country"),
"primary_source_urls": source_urls[:5],
}
messages: list[dict[str, Any]] = [
{
"role": "user",
"content": (
f"{user_objective}\n\n目标上下文 JSON:\n"
f"{json.dumps(context_payload, ensure_ascii=False)}"
),
}
]
submitted_payload: dict[str, Any] | None = None
last_text_response = ""
steps_taken = 0
for step in range(1, max_steps + 1):
steps_taken = step
req = SituationalAnalysisRequest(
title=f"Location agent step {step}",
objective=user_objective,
system_prompt=system_prompt,
context=context_payload,
preferred_model=(l2_node or {}).get("model_override"),
messages=messages,
tools=active_tools,
tool_choice="auto" if step < max_steps else {"type": "function", "name": "submit_location_result"},
native_web_search=bool((l2_node or {}).get("native_web_search", False)),
)
try:
resp = await provider_client.analyze(req)
except Exception as exc:
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="failed",
tool_trace=tool_trace,
steps_used=steps_taken,
error_message=str(exc),
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=f"Location agent failed: {exc}",
),
None,
)
last_text_response = str(getattr(resp, "content", "") or "")
tool_calls = list(getattr(resp, "tool_calls", None) or [])
if not tool_calls:
# Provider returned plain text (no tool calling support); break cleanly into deterministic fallback.
break
messages.append(
{
"role": "assistant",
"content": last_text_response,
"tool_calls": [
{"id": tc.id, "name": tc.name, "arguments": tc.arguments}
for tc in tool_calls
],
}
)
for tc in tool_calls:
raw_args = tc.arguments
if isinstance(raw_args, str):
try:
raw_args = json.loads(raw_args)
except json.JSONDecodeError:
raw_args = {}
args = raw_args if isinstance(raw_args, dict) else {}
tool_trace.append(f"l2_agent_research:{tc.name}")
if tc.name == "fetch_source_url":
target_url = coerce_str(args.get("url"))
agent_attempts.append(f"fetch_url:{target_url}")
try:
fetched = await asyncio.wait_for(safe_web_fetch(target_url, timeout_seconds=8), timeout=10.0)
final_url = (
coerce_str(fetched.get("final_url") or fetched.get("url"))
if isinstance(fetched, dict)
else coerce_str(getattr(fetched, "final_url", None) or getattr(fetched, "url", None))
) or target_url
title = fetched.get("title", "") if isinstance(fetched, dict) else getattr(fetched, "title", "")
text = fetched.get("content", "") if isinstance(fetched, dict) else getattr(fetched, "text", "")
observed_urls.add(target_url)
observed_urls.add(final_url)
tool_output = isolate_untrusted_external_text(final_url, title, text, max_chars=2400)
except Exception as exc:
tool_output = {"error": f"fetch failed: {exc}", "url": target_url}
messages.append(
{
"role": "tool",
"tool_call_id": tc.id,
"name": tc.name,
"content": json.dumps(tool_output, ensure_ascii=False),
}
)
elif tc.name == "web_search":
q_str = coerce_str(args.get("query"))
agent_attempts.append(f"web_search:{q_str}")
if web_search_client is None:
tool_output = {"error": "WebSearch is not enabled or missing API key"}
else:
try:
evidences = await web_search_client.search(q_str, max_results=5)
items = []
for ev in evidences:
u = coerce_str(getattr(ev, "url", ""))
if u:
observed_urls.add(u)
items.append(
{
"title": getattr(ev, "title", ""),
"url": u,
"snippet": getattr(ev, "snippet", "")[:400],
}
)
tool_output = {"results": items}
except Exception as exc:
tool_output = {"error": str(exc)}
messages.append(
{
"role": "tool",
"tool_call_id": tc.id,
"name": tc.name,
"content": json.dumps(tool_output, ensure_ascii=False),
}
)
elif tc.name == "geocode_verify":
place_q = coerce_str(args.get("place_query"))
expected_c = normalize_country_text(args.get("country") or query.country)
agent_attempts.append(f"geocode_verify:{place_q}")
try:
geo_res = await asyncio.to_thread(_agent_geocoder, place_q)
except Exception as exc:
logger.warning_event(
"Location agent geocode_verify failed",
event="location_agent.geocode_verify.failed",
context={"place_query": place_q, "error": str(exc)},
)
geo_res = None
geocode_error = f"geocoder request failed: {exc}"
else:
geocode_error = ""
if geocode_error:
tool_output = {"found": False, "error": geocode_error, "retryable": True}
elif not isinstance(geo_res, dict):
tool_output = {"found": False, "reason": "No geocoder match"}
else:
lat = parse_float(geo_res.get("lat") if geo_res.get("lat") is not None else geo_res.get("latitude"))
lon = parse_float(geo_res.get("lon") if geo_res.get("lon") is not None else geo_res.get("longitude"))
addr = geo_res.get("address") if isinstance(geo_res.get("address"), dict) else {}
res_country = normalize_country_text(addr.get("country") or geo_res.get("country"))
if (
lat in (None, 0.0)
or lon in (None, 0.0)
or not (-90.0 <= lat <= 90.0)
or not (-180.0 <= lon <= 180.0)
):
tool_output = {"found": False, "reason": "Invalid geocoder coordinates"}
elif expected_c and res_country and normalize_text(res_country) != normalize_text(expected_c):
tool_output = {
"found": False,
"reason": f"Country mismatch: got {res_country}, expected {expected_c}",
}
else:
cid = f"geo_{len(geocode_candidates) + 1}"
geocode_candidates[cid] = {
"latitude": lat,
"longitude": lon,
"display_name": coerce_str(geo_res.get("display_name")) or place_q,
"city": coerce_str(
addr.get("city")
or addr.get("town")
or addr.get("village")
or addr.get("municipality")
or geo_res.get("city")
),
"region": coerce_str(addr.get("state") or addr.get("region") or geo_res.get("region")),
"country": res_country or expected_c or query.country,
}
tool_output = {"found": True, "geocode_candidate_id": cid, **geocode_candidates[cid]}
messages.append(
{
"role": "tool",
"tool_call_id": tc.id,
"name": tc.name,
"content": json.dumps(tool_output, ensure_ascii=False),
}
)
elif tc.name == "submit_location_result":
submitted_payload = dict(args)
tool_trace.append("l3_geo_guardrail")
messages.append(
{
"role": "tool",
"tool_call_id": tc.id,
"name": tc.name,
"content": json.dumps({"accepted": True}),
}
)
if submitted_payload is not None:
break
if submitted_payload is None:
# Fallback for providers/mocks without tool_calls support
evidence_list = []
if web_search_client is not None:
from app.services.location.llm_fallback import collect_location_search_evidence
search_res = await collect_location_search_evidence(
web_search_client=web_search_client,
query=query,
entity_type=entity_type,
)
agent_attempts.extend(search_res.attempted_queries)
evidence_list = search_res.evidence
if evidence_list or last_text_response:
fallback_res = await collect_llm_location_fallback_candidate(
provider_client=provider_client,
query=query,
entity_type=entity_type,
db=db,
attempted_queries=[*(attempted_queries or []), *agent_attempts],
search_evidence=evidence_list,
min_confidence=min_confidence,
)
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="completed" if fallback_res.candidates else "failed",
tool_trace=[*tool_trace, "llm_fallback"],
steps_used=steps_taken,
error_message=fallback_res.failure_reason or "",
)
return fallback_res, None
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="failed",
tool_trace=tool_trace,
steps_used=steps_taken,
error_message="Agent did not submit location result",
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason="Location agent reached step budget without submitting a verified location.",
),
None,
)
sub_status = str(submitted_payload.get("status") or "unresolved").strip().lower()
reasoning = coerce_str(submitted_payload.get("reasoning"))
if sub_status in TERMINAL_UNLOCATABLE_STATUSES:
await _persist_terminal_location_status(
db,
query=query,
terminal_status=sub_status,
reasoning=reasoning,
)
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="completed",
tool_trace=[*tool_trace, f"l4_persist_outcome:{sub_status}"],
steps_used=steps_taken,
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=reasoning or f"Facility confirmed as {sub_status}.",
),
sub_status,
)
geo_cid = coerce_str(submitted_payload.get("geocode_candidate_id"))
geo_entry = geocode_candidates.get(geo_cid)
if sub_status != "located" or geo_entry is None:
reason = reasoning or "Submitted result missing verified geocode_candidate_id"
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="failed",
tool_trace=tool_trace,
steps_used=steps_taken,
error_message=reason,
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=reason,
),
None,
)
citations = [
str(c).strip()
for c in (submitted_payload.get("citations") or [])
if str(c or "").strip()
]
verified_citations = [c for c in citations if c in observed_urls]
if require_tool_urls and not verified_citations:
reason = "No verified citation URLs observed in tool outputs"
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="failed",
tool_trace=tool_trace,
steps_used=steps_taken,
error_message=reason,
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=reason,
),
None,
)
expected_country = normalize_country_text(query.country)
resolved_country = normalize_country_text(submitted_payload.get("country") or geo_entry.get("country"))
if expected_country and resolved_country and normalize_text(resolved_country) != normalize_text(expected_country):
reason = f"Country mismatch ({resolved_country} != {expected_country})"
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="failed",
tool_trace=tool_trace,
steps_used=steps_taken,
error_message=reason,
)
return (
LocationLLMFallbackResult(
candidates=[],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=reason,
),
None,
)
confidence = min(max(parse_float(submitted_payload.get("confidence")) or 0.78, 0.0), 1.0)
raw_precision = coerce_str(submitted_payload.get("precision")).lower()
precision = raw_precision if raw_precision in {"precise", "site", "city"} else "city"
facility_label = coerce_str(submitted_payload.get("facility_name")) or coerce_str(geo_entry.get("display_name")) or coerce_str(query.name)
candidate = LocationCandidate(
latitude=float(geo_entry["latitude"]),
longitude=float(geo_entry["longitude"]),
display_name=facility_label,
precision=precision,
confidence=max(confidence, min_confidence),
query=f"location_agent:{entity_type}:{query.name or extra.get('source_id') or 'unknown'}",
source="llm_location_factcheck",
source_note=reasoning or f"Verified via tool-calling agent ({len(verified_citations)} citations)",
matched_fields=("name", "tool_calling_agent"),
needs_confirmation=True,
city=coerce_str(submitted_payload.get("city")) or geo_entry.get("city") or query.city or None,
region=coerce_str(submitted_payload.get("region")) or geo_entry.get("region") or query.region or None,
country=resolved_country or expected_country or query.country,
matched_location_name=facility_label,
raw_payload={"citations": verified_citations or citations, "geocode_candidate_id": geo_cid},
)
await _record_location_workflow_run(
db,
question=str(query.name or ""),
status_value="completed",
tool_trace=[*tool_trace, "l4_persist_outcome:located"],
steps_used=steps_taken,
)
return (
LocationLLMFallbackResult(
candidates=[candidate],
attempted_queries=[*(attempted_queries or []), *agent_attempts],
failure_reason=None,
),
None,
)
File diff suppressed because it is too large. Load diff
@@ -21,6 +21,7 @@ from typing import Any, Callable
import httpx
from app.core.countries import normalize_country
from app.core.logging import get_logger
from ..models import LocationCandidate, LocationQuery, ResolverOutput
@@ -71,8 +72,12 @@ def build_default_nominatim_geocoder(
"format": "jsonv2",
"limit": 1,
"addressdetails": 1,
"accept-language": "en",
},
headers={
"User-Agent": user_agent,
"Accept-Language": "en",
},
headers={"User-Agent": user_agent},
timeout=timeout_seconds,
)
response.raise_for_status()
@@ -125,6 +130,42 @@ _DEFAULT_SITE_CATEGORIES = frozenset(
)
def resolve_geocoder_country(
address: dict[str, Any] | None,
raw_result: dict[str, Any] | None = None,
) -> str:
"""Resolve canonical country from explicit name/multilingual parts first, then ISO country_code."""
addr = address if isinstance(address, dict) else {}
raw = raw_result if isinstance(raw_result, dict) else {}
for candidate in (addr.get("country"), raw.get("country")):
text = coerce_str(candidate)
if not text:
continue
direct = normalize_country(text)
if direct:
return direct
if "/" in text:
for part in text.split("/"):
part_canonical = normalize_country(part.strip())
if part_canonical:
return part_canonical
for code in (addr.get("country_code"), raw.get("country_code")):
code_text = coerce_str(code)
if code_text:
code_canonical = normalize_country(code_text)
if code_canonical:
return code_canonical
return normalize_country_text(
addr.get("country")
or raw.get("country")
or addr.get("country_code")
or raw.get("country_code")
)
def interpret_geocode_result(
result: dict[str, Any],
*,
@@ -161,9 +202,7 @@ def interpret_geocode_result(
if context_country:
normalized_context = normalize_text(normalize_country_text(context_country))
normalized_result = normalize_text(
normalize_country_text(address.get("country"))
)
normalized_result = normalize_text(resolve_geocoder_country(address, result))
if (
normalized_context
and normalized_result
@@ -211,7 +250,7 @@ def _candidate_from_geocode(
or None
)
region = address.get("state") or address.get("region")
country = address.get("country") or query.country or None
country = resolve_geocoder_country(address, raw_result) or query.country or None
display_name = raw_result.get("display_name") or geocode_query
confidence = city_confidence if classification == "city" else site_confidence
@@ -15,22 +15,51 @@ PEERINGDB_USER_AGENT = "Planet-Intelligence-System/1.0"
PEERINGDB_TIMEOUT_SECONDS = 6.0
_GENERIC_OPERATOR_NAMES = frozenset(
{
"google",
"ibm",
"microsoft",
"amazon",
"aws",
"meta",
"facebook",
"nebius",
"nebius ai",
"oracle",
"alibaba",
"tencent",
"bytedance",
"nvidia",
"apple",
"openai",
"xai",
"equinix",
"digital realty",
"coreweave",
"lambda",
}
)
async def lookup_peeringdb_facility(
query: LocationQuery,
*,
timeout_seconds: float = PEERINGDB_TIMEOUT_SECONDS,
) -> ResolverOutput:
"""Query PeeringDB facilities matching the target site/operator/name."""
"""Query PeeringDB facilities matching the target site/name (never generic operator alone)."""
extra = query.extra or {}
search_terms: list[str] = []
for raw in [
extra.get("site"),
extra.get("operator"),
*(query.aliases or ()),
query.name,
]:
cleaned = coerce_str(raw)
if cleaned and len(cleaned) >= 3 and cleaned not in search_terms:
norm = normalize_text(cleaned)
if not cleaned or len(cleaned) < 3 or norm in _GENERIC_OPERATOR_NAMES:
continue
if cleaned not in search_terms:
search_terms.append(cleaned)
if not search_terms:
return ResolverOutput()
@@ -2,8 +2,6 @@
from __future__ import annotations
from typing import Any
import httpx
from ..models import LocationCandidate, LocationQuery, ResolverOutput
@@ -82,6 +80,44 @@ async def lookup_wikidata_facility(
continue
term_tokens = set(normalize_text(term).split())
expected_country = normalize_text(normalize_country_text(query.country))
country_qids: set[str] = set()
if expected_country:
for entity in entities.values():
if not isinstance(entity, dict):
continue
for p17 in (entity.get("claims") or {}).get("P17") or []:
dataval = (((p17.get("mainsnak") or {}).get("datavalue") or {}).get("value") if isinstance(p17, dict) else None)
if isinstance(dataval, dict) and dataval.get("id"):
country_qids.add(str(dataval["id"]))
country_labels: dict[str, list[str]] = {}
if country_qids:
try:
c_resp = await client.get(
WIKIDATA_API_URL,
params={
"action": "wbgetentities",
"ids": "|".join(sorted(country_qids)[:12]),
"props": "labels",
"languages": "en|zh",
"format": "json",
},
)
c_resp.raise_for_status()
for c_qid, c_ent in ((c_resp.json() or {}).get("entities") or {}).items():
if not isinstance(c_ent, dict):
continue
c_labels = c_ent.get("labels") or {}
vals = [
coerce_str((c_labels.get(lang) or {}).get("value"))
for lang in ("en", "zh")
if coerce_str((c_labels.get(lang) or {}).get("value"))
]
if vals:
country_labels[c_qid] = vals
except Exception:
country_labels = {}
for qid, entity in entities.items():
if not isinstance(entity, dict):
continue
@@ -99,6 +135,18 @@ async def lookup_wikidata_facility(
continue
claims = entity.get("claims") or {}
resolved_p17_countries: list[str] = []
for p17 in claims.get("P17") or []:
dataval = (((p17.get("mainsnak") or {}).get("datavalue") or {}).get("value") if isinstance(p17, dict) else None)
c_qid = str(dataval.get("id") or "") if isinstance(dataval, dict) else ""
for raw_label in country_labels.get(c_qid, []):
norm_c = normalize_country_text(raw_label) or raw_label
if norm_c and norm_c not in resolved_p17_countries:
resolved_p17_countries.append(norm_c)
if expected_country and resolved_p17_countries:
if not any(normalize_text(c) == expected_country for c in resolved_p17_countries):
continue
coord_claims = claims.get("P625") or []
for claim in coord_claims:
mainsnak = claim.get("mainsnak") if isinstance(claim, dict) else None
@@ -115,7 +163,11 @@ async def lookup_wikidata_facility(
or not (-180.0 <= lon <= 180.0)
):
continue
country = normalize_country_text(query.country)
country = (
resolved_p17_countries[0]
if resolved_p17_countries
else normalize_country_text(query.country)
)
candidates.append(
LocationCandidate(
latitude=lat,
@@ -131,7 +183,11 @@ async def lookup_wikidata_facility(
city=query.city or None,
country=country or query.country,
matched_location_name=label or term,
raw_payload={"wikidata_qid": qid, "description": desc},
raw_payload={
"wikidata_qid": qid,
"description": desc,
**({"wikidata_country": resolved_p17_countries[0]} if resolved_p17_countries else {}),
},
)
)
break
File diff suppressed because it is too large. Load diff
+30
View File
@@ -60,6 +60,8 @@ _HEAVY_COLLECTOR_SEMAPHORES: weakref.WeakKeyDictionary[
EARTH_NEWS_REFRESH_JOB_ID = "earth_news_rss_refresh"
STORAGE_RETENTION_JOB_ID = "storage_retention_maintenance"
STORAGE_RETENTION_INTERVAL_HOURS = 6
COMPUTE_PRESENTATION_RETRY_JOB_ID = "compute_revision_presentation_retry"
COMPUTE_PRESENTATION_RETRY_INTERVAL_MINUTES = 5
SCHEDULER_LEADER_LOCK_KEY = (17001613, 3)
_leader_lock_conn: Optional[asyncpg.Connection] = None
_pending_earth_news_refreshes: dict[str, dict[str, Any]] = {}
@@ -531,6 +533,23 @@ async def release_scheduler_leader_lock() -> None:
await conn.close()
async def run_compute_presentation_retry_job() -> None:
"""Retry pending or failed compute revision stage presentations."""
from app.services.ai.proactive_pipeline import retry_pending_compute_presentations
async with async_session_factory() as db:
try:
await retry_pending_compute_presentations(db)
await db.commit()
except Exception as exc:
await db.rollback()
logger.warning_event(
"Scheduled compute presentation retry failed",
event="compute.revision.presentation_failed",
context={"phase": "scheduler", "error": str(exc)},
)
def start_scheduler() -> None:
"""Start the scheduler."""
if not scheduler.running:
@@ -555,6 +574,16 @@ def start_scheduler() -> None:
coalesce=True,
misfire_grace_time=300,
)
scheduler.add_job(
run_compute_presentation_retry_job,
trigger=IntervalTrigger(minutes=COMPUTE_PRESENTATION_RETRY_INTERVAL_MINUTES),
id=COMPUTE_PRESENTATION_RETRY_JOB_ID,
name="Compute revision presentation retry",
replace_existing=True,
max_instances=1,
coalesce=True,
misfire_grace_time=120,
)
scheduler.start()
logger.info_event("Scheduler started", event="scheduler.started")
@@ -780,6 +809,7 @@ async def sync_scheduler_with_datasources() -> None:
job.id not in configured_sources
and not is_earth_news_refresh
and job.id != STORAGE_RETENTION_JOB_ID
and job.id != COMPUTE_PRESENTATION_RETRY_JOB_ID
):
scheduler.remove_job(job.id)
@@ -302,6 +302,17 @@ async def _run_maintenance_with_session(
where_clause=[ObservabilityEvent.occurred_at < history_cutoff],
batch_size=batch_size,
)
from app.services.earth_clouds import prune_cloud_map_artifacts, read_cloud_map_configuration
from app.services.earth_tiles import prune_all_tile_caches
from app.services.earth_wind import prune_wind_artifacts, read_wind_configuration
cloud_env = await read_cloud_map_configuration(db)
max_cloud_frames = int((cloud_env.get("config") or {}).get("max_history_frames") or 24)
pruned_cloud_artifacts = prune_cloud_map_artifacts(max_frames=max_cloud_frames)
pruned_tile_files = await prune_all_tile_caches(db)
wind_env = await read_wind_configuration(db)
max_wind_runs = int((wind_env.get("config") or {}).get("max_history_runs") or 12)
pruned_wind_artifacts = prune_wind_artifacts(max_runs=max_wind_runs)
deleted_counts = {
"collected_data": deleted_collected,
@@ -312,6 +323,9 @@ async def _run_maintenance_with_session(
"earth_news_items": deleted_news_items,
"system_logs": deleted_system_logs,
"observability_events": deleted_observability_events,
"cloud_map_artifacts": pruned_cloud_artifacts,
"tile_cache_files": pruned_tile_files,
"wind_artifacts": pruned_wind_artifacts,
}
logger.info_event(
"Completed storage retention maintenance",
+31
View File
@@ -0,0 +1,31 @@
{
"case_id": "epoch-ai-2026-11-restates-2025-chip-inflow-cn",
"metric": "chip_inflow_share",
"year": 2025,
"period_label": null,
"old": {
"source_id": "epoch-chip-imports-2026",
"values": {
"US": 72,
"CN": 11
},
"locator": "Regional H100-equivalent AI Accelerator Inflow(2022.10 先进芯片管制及北美云厂商每年超 2000 亿美元 CapEx 驱动下,高端 AI 算力芯片新增流向美国约 72%、中国约 10%–12%)"
},
"new": {
"source_id": "epoch-chip-imports-2026-11",
"title": "Epoch AI: Data on AI Chip Imports (2026-11-12 Revision)",
"url": "https://epoch.ai/data/ai-chip-imports-documentation/changelog",
"publisher": "Epoch AI",
"report_year": 2026,
"published_at": "2026-11-12",
"locator": "AI chip imports documentation — Changelog (2026-11-12) & Overview (Key takeaways); ai_chip_trade_by_country.csv",
"excerpt": "2026-11-12: We now assume Nvidia's H20 arrived in the quarter it was sold. Other chips are still assumed to arrive two months after sale. This moves about 216,000 H20s in China from 2025 to 2024. It also raises China's share of cumulative world arrivals through June 2026 from 9.6% to 9.9% (69,000 H100e).",
"values": {
"CN": 9.9
}
},
"unchanged_codes": [
"US"
],
"notes": "真实公开修订案例(非演练)。同一机构(Epoch AI)、同一口径(全球 H100e 等效 AI 加速芯片新增/累计流向份额,分母 ai_chip_inflow):内置台账 epoch-chip-imports-2026(2026-04-10)记录美国 72%、中国约 10%–12%(取中值 11%);Epoch AI 官方 AI Chip Imports 数据集于 2026-10-27 正式发布并于 2026-11-12 修订,在 Changelog 中明确因将约 216,000 颗中国 H20 芯片到货时点由 2025 年调回 2024 年并结合海关/国产产量核算,将中国全球累计到货算力份额更新为 9.9%(相对原台账 11% 为 -1.1 个百分点),同期同句给出美国份额 72.0%(与原台账 72% 持平,故只修订中国时美国保留原来源 epoch-chip-imports-2026)。附注:已核查 CAICT 2021–2025 五版白皮书/蓝皮书原件 PDF(含正文与图表),CAICT 2025 未对 2023 年全球总份额(美 41%/中 31%)与总规模(1397/435 EFlops)做修订。"
}
+327
View File
@@ -277,3 +277,330 @@ async def test_stream_turn_forwards_history_compaction_and_memory(monkeypatch):
assert sent_payload.context["conversation_summary"] == meta_ev["conversation_summary"]
assert sent_payload.context["user_memory_notes"] == ["优先给出亚太海缆冗余与算力口径边界"]
assert sent_payload.context["pinned_comparisons"] == ["GLOBAL · Rev.1: 全球综合态势"]
@pytest.mark.asyncio
async def test_stream_turn_extracts_planet_scene_and_emits_scene_event(monkeypatch):
from app.services.ai.workflow_runtime import SceneSpec
reset_stream_quota_ledger()
async def fake_global_tool(*_args, **_kwargs):
return {
"domain": "global",
"domain_summaries": [{"domain": "cable", "label": "海底光缆", "metric_text": "343 条"}],
"evidence": {"ev-global-1": {"id": "ev-global-1", "title": "Global Telemetry"}},
}
async def fake_recent_news(*_args, **_kwargs):
return {"domain": "news", "available": True, "count": 0, "items": [], "evidence": {}}
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
class _SceneStreamingClient(AIProviderClient):
def __init__(self):
super().__init__(
service_url="http://aiprovider.test",
llm_config={
"provider": "minimax",
"provider_api": "anthropic-messages",
"base_url": "https://api.minimaxi.com/anthropic",
"api_key": "secret-key",
"model": "MiniMax-M2.7",
},
)
async def stream_analyze(self, payload, request_id=None):
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M2.7"}
yield {"event": "text", "delta": "APEC 峰会影响聚焦中美俄及亚太经济体。"}
yield {"event": "text", "delta": "\n<planet_"}
yield {
"event": "text",
"delta": (
'scene>{"camera_hint":{"lat":28.0,"lon":128.0},'
'"influence_zones":[{"id":"apec-core","label":"核心与会国","color":"#ef4444",'
'"opacity":0.62,"edge":{"style":"sharp"},"animation":{"type":"sweep","direction":"west_to_east"},'
'"shape":{"mode":"countries","countries":["CHN","USA","RUS"]}}]}</planet_scene>'
),
}
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M2.7", "usage": {"total_tokens": 64}}
app = FastAPI()
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
app.dependency_overrides[situational_awareness.get_db] = lambda: _StubDb()
app.dependency_overrides[get_ai_provider_client] = lambda: _SceneStreamingClient()
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
res = await client.post(
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
json={
"question": "请分析这条国际新闻:「APEC 中美俄元首会晤」在地缘上的影响范围",
"domain": "news",
"news_context": {
"id": "apec-1",
"title": "APEC 中美俄元首会晤",
"summary": "中美俄三方会晤与亚太经济体协同",
"source": "Reuters",
"region": "亚太",
},
},
)
assert res.status_code == 200
events = _parse_sse_text(res.text)
text_deltas = "".join(data["delta"] for name, data in events if name == "text")
assert "<planet_scene>" not in text_deltas
assert "APEC 峰会影响聚焦中美俄及亚太经济体" in text_deltas
scene_events = [data for name, data in events if name == "scene"]
assert len(scene_events) == 1
zones = scene_events[0]["scene_spec"]["influence_zones"]
assert len(zones) == 1
assert zones[0]["id"] == "apec-core"
assert zones[0]["shape"]["countries"] == ["CHN", "USA", "RUS"]
done_ev = events[-1][1]
assert "<planet_scene>" not in done_ev["answer_markdown"]
assert done_ev["scene_spec"]["camera_hint"]["lat"] == 28.0
validated = SceneSpec.model_validate({
"domain": "global",
"influence_zones": zones,
})
assert validated.influence_zones[0].edge.style == "sharp"
@pytest.mark.asyncio
async def test_workflow_dag_stream_emits_influence_zones_for_red_sea_news(monkeypatch):
reset_stream_quota_ledger()
class _EmptyScalarResult:
def scalar_one_or_none(self):
return None
class _DagStubDb(_StubDb):
async def execute(self, *_args, **_kwargs):
return _EmptyScalarResult()
async def fake_global_tool(*_args, **_kwargs):
return {"domain": "global", "domain_summaries": [], "evidence": {}}
async def fake_recent_news(*_args, **_kwargs):
return {
"domain": "news",
"available": True,
"count": 1,
"items": [{"id": "n-redsea", "title": "红海安全成为埃及与索马里军方会谈重点"}],
"evidence": {"ev-news-1": {"id": "ev-news-1", "title": "Red Sea News"}},
}
monkeypatch.setattr("app.services.ai.dag_executor.query_global_situational_tool", fake_global_tool)
monkeypatch.setattr("app.services.ai.dag_executor.query_recent_earth_news_tool", fake_recent_news)
monkeypatch.setattr("app.services.ai.stream_turn.query_global_situational_tool", fake_global_tool)
monkeypatch.setattr("app.services.ai.stream_turn.query_recent_earth_news_tool", fake_recent_news)
captured_requests = []
class _DagSceneClient(AIProviderClient):
def __init__(self):
super().__init__(
service_url="http://aiprovider.test",
llm_config={
"provider": "minimax",
"provider_api": "anthropic-messages",
"base_url": "https://api.minimaxi.com/anthropic",
"api_key": "secret-key",
"model": "MiniMax-M3.1-Flash",
},
)
async def stream_analyze(self, payload, request_id=None):
captured_requests.append(payload)
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M3.1-Flash"}
yield {"event": "text", "delta": "红海安全会谈核心涉及埃及与索马里及曼德海峡航道。\n<planet_sce"}
yield {
"event": "text",
"delta": (
'ne>{"camera_hint":{"lat":18.0,"lon":39.0},"influence_zones":['
'{"id":"redsea-corridor","label":"红海—曼德海峡走廊","color":"#38bdf8","opacity":0.28,'
'"edge":{"style":"soft"},"animation":{"type":"radial"},'
'"shape":{"mode":"circle","center":[15.5,42.5],"radius_km":950}},'
'{"id":"egy-som","label":"埃及与索马里","color":"#f59e0b","opacity":0.55,'
'"edge":{"style":"sharp"},"animation":{"type":"sweep","direction":"north_to_south"},'
'"shape":{"mode":"countries","countries":["EGY","SOM"]}}]}</planet_scene>'
),
}
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M3.1-Flash"}
app = FastAPI()
app.include_router(situational_awareness.router, prefix="/api/v1/situational-awareness")
app.dependency_overrides[situational_awareness.get_db] = lambda: _DagStubDb()
app.dependency_overrides[get_ai_provider_client] = lambda: _DagSceneClient()
async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
res = await client.post(
"/api/v1/situational-awareness/sessions/stateless/turns/stream",
json={
"question": "该事件影响范围?",
"domain": "news",
"workflow_id": "earth.news.analysis",
},
)
assert res.status_code == 200
events = _parse_sse_text(res.text)
text_deltas = "".join(data["delta"] for name, data in events if name == "text")
assert "<planet_scene>" not in text_deltas
assert "红海安全会谈核心涉及埃及与索马里" in text_deltas
scene_events = [data for name, data in events if name == "scene"]
assert len(scene_events) == 1
zones = scene_events[0]["scene_spec"]["influence_zones"]
assert [z["id"] for z in zones] == ["redsea-corridor", "egy-som"]
done_ev = events[-1][1]
assert "<planet_scene>" not in done_ev["answer_markdown"]
assert len(done_ev["scene_spec"]["influence_zones"]) == 2
assert captured_requests and "scene_overlay_guidance" in captured_requests[0].context
assert "<planet_scene>" in (captured_requests[0].system_prompt or "")
def test_scene_directives_tolerate_code_fences_and_llm_field_quirks():
from app.services.ai.scene_directives import extract_planet_scene_from_text
from app.services.ai.workflow_runtime import validate_influence_zones
raw = (
"直接影响地区为中国市场。\n"
"<planet_scene>\n"
"```json\n"
"{\n"
' "influence_zones": [\n'
" {\n"
' "name": "直接影响:中国",\n'
' "color": "red",\n'
' "edge": {"style": "sharp", "opacity": 0.55, "extra_ignored": true},\n'
' "animation": "sweep",\n'
' "countries": "CHN",\n'
' "extra_note": "ignore me",\n'
" },\n"
" {\n"
' "id": "corridor",\n'
' "color": "#38b",\n'
' "opacity": 1.4,\n'
' "shape": {"mode": "circle", "center": {"lat": 15.5, "lon": 42.5}, "radius_km": 5}\n'
" },\n"
" ],\n"
' "camera_hint": {"lat": 35.0, "lon": 104.0}\n'
"}\n"
"```\n"
"</planet_scene>"
)
cleaned, parsed = extract_planet_scene_from_text(raw)
assert cleaned == "直接影响地区为中国市场。"
assert parsed is not None
assert parsed["camera_hint"] == {"lat": 35.0, "lon": 104.0}
zones = parsed["influence_zones"]
assert len(zones) == 2
assert zones[0]["label"] == "直接影响:中国"
assert zones[0]["color"] == "#ef4444"
assert zones[0]["opacity"] == pytest.approx(0.55)
assert zones[0]["edge"]["style"] == "sharp"
assert zones[0]["animation"]["type"] == "sweep"
assert zones[0]["shape"]["mode"] == "countries"
assert zones[0]["shape"]["countries"] == ["CHN"]
assert zones[1]["color"] == "#3388bb"
assert zones[1]["opacity"] == pytest.approx(0.9)
assert zones[1]["shape"]["center"] == [15.5, 42.5]
assert zones[1]["shape"]["radius_km"] == pytest.approx(20.0)
# Also test validate_influence_zones directly with edge string + flat region_preset
direct = validate_influence_zones(
[{"id": "apec", "color": "#f59e0b", "edge": "soft", "region_preset": "APEC"}]
)
assert len(direct) == 1
assert direct[0].edge.style == "soft"
assert direct[0].shape.mode == "region_preset"
assert direct[0].shape.region_preset == "APEC"
def test_validate_influence_zones_normalizes_dprk_presets_polygons_and_rejects_empty():
from app.services.ai.workflow_runtime import validate_influence_zones
zones = validate_influence_zones(
[
{"id": "core", "color": "red", "countries": ["CHN", "DPRK", "朝鲜", "KP"]},
{"id": "ne-asia", "color": "amber", "region_preset": "东北亚"},
{"id": "ne-asia-en", "color": "amber", "shape": {"mode": "region_preset", "region_preset": "northeast-asia"}},
{"id": "poly2d", "color": "#38bdf8", "coordinates": [[120.0, 35.0], [126.0, 35.0], [126.0, 40.0]]},
{"id": "unknown-preset", "color": "#38bdf8", "shape": {"mode": "region_preset", "region_preset": "MARS_BELT"}},
{"id": "empty-countries", "color": "#ef4444", "shape": {"mode": "countries", "countries": []}},
]
)
assert [z.id for z in zones] == ["core", "ne-asia", "ne-asia-en", "poly2d"]
assert zones[0].shape.countries == ["CHN", "PRK"]
assert zones[1].shape.mode == "region_preset"
assert zones[1].shape.region_preset == "NORTHEAST_ASIA"
assert zones[2].shape.region_preset == "NORTHEAST_ASIA"
assert zones[3].shape.mode == "polygon"
assert len(zones[3].shape.coordinates) == 1
assert len(zones[3].shape.coordinates[0]) == 3
@pytest.mark.asyncio
async def test_stream_turn_cooperative_cancel_stops_stream_and_preserves_session_memory(monkeypatch):
from types import SimpleNamespace
import app.services.ai.stream_turn as st_mod
from app.services.ai.workflow_runtime import cancel_active_run_handle
from app.services.ai.access_policy import AccessContext
async def _fake_recent_news(*_args, **_kwargs):
return {"items": [], "evidence": {}}
async def _fake_global_tool(*_args, **_kwargs):
return {"domain_summaries": [], "evidence": {}}
monkeypatch.setattr(st_mod, "query_recent_earth_news_tool", _fake_recent_news)
monkeypatch.setattr(st_mod, "query_global_situational_tool", _fake_global_tool)
class FakeSlowClient:
llm_config = {"provider": "minimax", "model": "MiniMax-M3.1-Flash", "max_tokens": 4096}
async def is_ready(self):
return True, "minimax", "MiniMax-M3.1-Flash"
async def stream_analyze(self, req, request_id=None):
yield {"event": "start", "provider": "minimax", "model": "MiniMax-M3.1-Flash"}
yield {"event": "text", "delta": "first chunk "}
# Simulate cooperative cancel triggered by overlapping turn before finishing
assert cancel_active_run_handle(request_id) is True
yield {"event": "text", "delta": "should not appear"}
yield {"event": "done", "provider": "minimax", "model": "MiniMax-M3.1-Flash", "usage": {}}
class DummyDb:
async def commit(self):
return None
session = SimpleNamespace(
id="sess-cancel-test",
context_state={"recent_messages": [{"role": "user", "content": "keep me"}], "domain": "news"},
pinned_items=[],
)
access = AccessContext(tier="public_zero_cost", actor_key="test-actor", hourly_paid_quota=100)
events = []
async for raw_ev in st_mod.stream_session_turn(
DummyDb(),
request=None,
session=session,
question="旧提问",
context_override={"domain": "news"},
news_context={"id": "n1", "title": "中朝关系", "source": "BBC World"},
access=access,
ai_client=FakeSlowClient(),
client_run_id="run-cancel-1",
):
events.append(raw_ev)
joined = "".join(events)
assert "should not appear" not in joined
assert "event: done" not in joined
assert session.context_state["recent_messages"] == [{"role": "user", "content": "keep me"}]
+48 -8
View File
@@ -197,13 +197,13 @@ async def test_ai_workflow_optimize_whitelist_and_playground_sse_runs(monkeypatc
"summary": "Add fetch tool & block bad tool",
"node_patches": [
{
"node_id": "l2_agent_research",
"node_id": "l2_judge_r1",
"field": "tools",
"after": ["fetch_source_url", "evil_rm_rf_tool"],
"reason": "Keep only whitelisted tool",
},
{
"node_id": "l2_agent_research",
"node_id": "l2_judge_r1",
"field": "max_steps",
"after": 5,
"reason": "Allow 5 steps",
@@ -306,9 +306,23 @@ async def test_ensure_builtin_workflows_upgrades_untouched_legacy_positions_only
loc_spec = next(
item for item in BUILTIN_WORKFLOWS if item["workflow_id"] == "location.resolve_unknown"
)
legacy_loc_graph = copy.deepcopy(loc_spec["graph"])
for node in legacy_loc_graph["nodes"]:
lx, ly = _LEGACY_BUILTIN_POSITIONS["location.resolve_unknown"][node["id"]]
legacy_loc_graph = {
"nodes": [
{"id": "l0_normalize", "node_type": "trigger", "position": {"x": 40, "y": 140}},
{"id": "l1_knowledge", "node_type": "deterministic", "position": {"x": 320, "y": 60}},
{"id": "l2_agent_research", "node_type": "llm_agent", "position": {"x": 320, "y": 250}},
{"id": "l3_geo_guardrail", "node_type": "guardrail", "position": {"x": 640, "y": 140}},
{"id": "l4_persist_outcome", "node_type": "output", "position": {"x": 940, "y": 140}},
],
"edges": [],
}
wg_spec = next(
item for item in BUILTIN_WORKFLOWS if item["workflow_id"] == "wargame.infrastructure"
)
legacy_wg_graph = copy.deepcopy(wg_spec["graph"])
for node in legacy_wg_graph["nodes"]:
lx, ly = _LEGACY_BUILTIN_POSITIONS["wargame.infrastructure"][node["id"]]
node["position"] = {"x": lx, "y": ly}
gen_spec = next(
@@ -333,6 +347,22 @@ async def test_ensure_builtin_workflows_upgrades_untouched_legacy_positions_only
updated_by="system",
)
)
session.add(
AIWorkflow(
workflow_id="wargame.infrastructure",
name=wg_spec["name"],
name_en=wg_spec["name_en"],
category=wg_spec["category"],
description=wg_spec["description"],
description_en=wg_spec["description_en"],
is_default=False,
is_builtin=True,
active_revision=1,
published_graph=legacy_wg_graph,
draft_graph=None,
updated_by="system",
)
)
session.add(
AIWorkflow(
workflow_id="default.general",
@@ -360,9 +390,19 @@ async def test_ensure_builtin_workflows_upgrades_untouched_legacy_positions_only
select(AIWorkflow).where(AIWorkflow.workflow_id == "location.resolve_unknown")
)
).scalar_one()
l1 = next(n for n in upgraded_loc.published_graph["nodes"] if n["id"] == "l1_knowledge")
l2 = next(n for n in upgraded_loc.published_graph["nodes"] if n["id"] == "l2_agent_research")
assert l2["position"]["x"] > l1["position"]["x"]
loc_ids = [n["id"] for n in upgraded_loc.published_graph["nodes"]]
assert "l2_research_r1" in loc_ids
assert "l2_judge_r1" in loc_ids
assert "l3_geocode" in loc_ids
upgraded_wg = (
await session.execute(
select(AIWorkflow).where(AIWorkflow.workflow_id == "wargame.infrastructure")
)
).scalar_one()
wg_trig = next(n for n in upgraded_wg.published_graph["nodes"] if n["id"] == "wg_trigger")
wg_inv = next(n for n in upgraded_wg.published_graph["nodes"] if n["id"] == "wg_investigator")
assert wg_inv["position"]["x"] - wg_trig["position"]["x"] >= 700
untouched_gen = (
await session.execute(
+16 -32
View File
@@ -8,7 +8,6 @@ import pytest
from app.api.v1 import bgp as bgp_api
from app.services import bgp_collector_locations
from app.services.location.llm_fallback import LocationLLMFallbackResult
from app.services.bgp_collector_locations import (
RIPE_RIS_COLLECTOR_COORDS,
collect_bgp_collector_location_candidates,
@@ -118,9 +117,9 @@ async def test_collect_bgp_collector_location_uses_llm_when_candidates_empty(mon
display_name="Lyon, France",
precision="city",
confidence=0.74,
query="llm_factcheck:bgp_collector:rrc-mystery",
query="location_workflow:bgp_collector:rrc-mystery",
source="llm_location_factcheck",
source_note="LLM location factcheck fallback",
source_note="Controlled workflow factcheck",
matched_fields=("collector",),
needs_confirmation=True,
city="Lyon",
@@ -131,36 +130,21 @@ async def test_collect_bgp_collector_location_uses_llm_when_candidates_empty(mon
"get_bgp_collector_location_dict",
lambda _collector: {},
)
monkeypatch.setattr(
bgp_api,
"collect_bgp_collector_location_candidates",
lambda **_kwargs: ([], ["Lyon, France"]),
)
from app.services.location.llm_fallback import LocationSearchEvidenceResult
async def _search_evidence(**_kwargs):
return LocationSearchEvidenceResult(
evidence=[
{
"title": "RRC source",
"url": "https://example.test/rrc",
"snippet": "rrc-mystery is in Lyon.",
}
async def _run_wf(**kwargs):
assert kwargs.get("entity_type") == "bgp_collector"
assert kwargs.get("query").name == "rrc-mystery"
return {
"candidates": [llm_candidate],
"attempted_queries": [
"Lyon, France",
"web_search:rrc-mystery Lyon France",
],
attempted_queries=["web_search:bgp_collector:rrc-mystery Lyon France physical location route collector city"],
)
"workflow_run_id": "run_bgp_1",
"failure_reason": None,
}
async def _fallback(**_kwargs):
return LocationLLMFallbackResult(
candidates=[llm_candidate],
attempted_queries=["llm_factcheck:bgp_collector:rrc-mystery"],
)
monkeypatch.setattr(bgp_api, "get_ai_provider_client", AsyncMock(return_value=object()))
monkeypatch.setattr(bgp_api, "get_web_search_client", AsyncMock(return_value=object()))
monkeypatch.setattr(bgp_api, "collect_location_search_evidence", _search_evidence)
monkeypatch.setattr(bgp_api, "collect_llm_location_fallback_candidate", _fallback)
monkeypatch.setattr(bgp_api, "run_location_workflow", _run_wf)
response = await bgp_api.collect_bgp_collector_location(
"rrc-mystery",
@@ -172,10 +156,10 @@ async def test_collect_bgp_collector_location_uses_llm_when_candidates_empty(mon
assert response["success"] is True
assert response["best_candidate"]["source"] == "llm_location_factcheck"
assert response["best_candidate"]["needs_confirmation"] is True
assert response["workflow_run_id"] == "run_bgp_1"
assert response["attempted_queries"] == [
"Lyon, France",
"web_search:bgp_collector:rrc-mystery Lyon France physical location route collector city",
"llm_factcheck:bgp_collector:rrc-mystery",
"web_search:rrc-mystery Lyon France",
]
+245
View File
@@ -0,0 +1,245 @@
"""Unit tests for optimized /api/v1/collected endpoints, summary facets, and Redis cache."""
from __future__ import annotations
from datetime import UTC, datetime
from httpx import ASGITransport, AsyncClient
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.api.v1 import collected_data as collected_api
from app.core.security import get_current_user
from app.db.session import Base, get_db
from app.main import app
from app.models.collected_data import CollectedData
from app.models.data_snapshot import DataSnapshot
from app.models.datasource import DataSource
from app.models.task import CollectionTask
from app.models.user import User, UserRole
class _MemoryCache:
def __init__(self) -> None:
self.store: dict[str, object] = {}
self.gets: list[str] = []
self.sets: list[str] = []
def get(self, key: str):
self.gets.append(key)
return self.store.get(key)
def set(self, key: str, value, expire_seconds: int = 300) -> bool:
self.sets.append(key)
self.store[key] = value
return True
class _SyncAsAsyncSession:
def __init__(self, sync_session):
self._s = sync_session
def add_all(self, objs):
return self._s.add_all(objs)
async def execute(self, stmt, *args, **kwargs):
return self._s.execute(stmt, *args, **kwargs)
async def commit(self):
return self._s.commit()
async def close(self):
return self._s.close()
def _make_test_session():
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(
engine,
tables=[
DataSource.__table__,
DataSnapshot.__table__,
CollectionTask.__table__,
CollectedData.__table__,
],
)
sync_factory = sessionmaker(engine, expire_on_commit=False)
with sync_factory() as session:
session.add_all(
[
DataSource(name="TOP500", source="top500", module="L4", collector_class="Top500Collector"),
DataSource(name="IPtoASN", source="iptoasn_prefix_geo", module="L1", collector_class="IPtoASNCollector"),
]
)
now = datetime.now(UTC)
session.add_all(
[
CollectedData(
source="top500",
source_id="t1",
entity_key="top500:t1",
data_type="supercomputer",
name="Frontier",
extra_data={"country": "美国"},
collected_at=now,
is_current=True,
),
CollectedData(
source="top500",
source_id="t2",
entity_key="top500:t2",
data_type="supercomputer",
name="Aurora",
extra_data={"country": "美国"},
collected_at=now,
is_current=True,
),
CollectedData(
source="top500",
source_id="t1_old",
entity_key="top500:t1_old",
data_type="supercomputer",
name="Old Frontier",
extra_data={"country": "美国"},
collected_at=now,
is_current=False,
),
CollectedData(
source="iptoasn_prefix_geo",
source_id="p1",
entity_key="iptoasn_prefix_geo:p1",
data_type="prefix_geography",
name="1.1.1.0/24",
extra_data={"country": "澳大利亚"},
collected_at=now,
is_current=True,
),
]
)
session.commit()
class _Ctx:
def __call__(self):
return self
async def __aenter__(self):
self._s = sync_factory()
return _SyncAsAsyncSession(self._s)
async def __aexit__(self, exc_type, exc, tb):
self._s.close()
return False
return engine, _Ctx()
def _fake_admin_user() -> User:
return User(
id=1,
username="collected_tester",
email="collected_tester@example.com",
role=UserRole.ADMIN,
is_active=True,
)
@pytest.mark.asyncio
async def test_collected_summary_excludes_prefix_geography_by_default_and_includes_explicitly(
monkeypatch,
):
engine, session_factory = _make_test_session()
mem_cache = _MemoryCache()
monkeypatch.setattr(collected_api, "cache", mem_cache)
async def override_get_db():
async with session_factory() as session:
yield session
app.dependency_overrides.update({get_db: override_get_db, get_current_user: _fake_admin_user})
try:
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
list_res = await client.get("/api/v1/collected?page=1&page_size=20&include_metadata=false")
assert list_res.status_code == 200
list_body = list_res.json()
assert list_body["total"] == 2
assert {item["source"] for item in list_body["data"]} == {"top500"}
explicit_res = await client.get("/api/v1/collected?data_type=prefix_geography&include_metadata=false")
assert explicit_res.status_code == 200
explicit_body = explicit_res.json()
assert explicit_body["total"] == 1
assert explicit_body["data"][0]["source"] == "iptoasn_prefix_geo"
summary_res = await client.get("/api/v1/collected/summary")
assert summary_res.status_code == 200
summary = summary_res.json()
assert summary["total_records"] == 2
assert summary["overall_total_records"] == 2
assert summary["by_source"] == {"TOP500": {"supercomputer": 2}}
assert summary["source_totals"] == [{"source": "top500", "source_name": "TOP500", "count": 2}]
assert summary["type_totals"] == [{"data_type": "supercomputer", "count": 2}]
explicit_summary_res = await client.get("/api/v1/collected/summary?data_type=prefix_geography")
assert explicit_summary_res.status_code == 200
explicit_summary = explicit_summary_res.json()
assert explicit_summary["total_records"] == 1
assert explicit_summary["overall_total_records"] == 3
assert explicit_summary["source_totals"] == [
{"source": "iptoasn_prefix_geo", "source_name": "IPtoASN", "count": 1}
]
sources_res = await client.get("/api/v1/collected/sources")
assert sources_res.status_code == 200
assert {s["source"] for s in sources_res.json()["sources"]} == {"iptoasn_prefix_geo", "top500"}
types_res = await client.get("/api/v1/collected/types")
assert types_res.status_code == 200
assert set(types_res.json()["data_types"]) == {"prefix_geography", "supercomputer"}
finally:
app.dependency_overrides.clear()
engine.dispose()
@pytest.mark.asyncio
async def test_collected_summary_and_facets_use_redis_cache_without_hitting_db_on_repeat(
monkeypatch,
):
engine, session_factory = _make_test_session()
mem_cache = _MemoryCache()
monkeypatch.setattr(collected_api, "cache", mem_cache)
fail_db = {"enabled": False}
async def override_get_db():
async with session_factory() as session:
if fail_db["enabled"]:
async def _boom(*_args, **_kwargs):
raise AssertionError("DB should not be queried on cache hit")
monkeypatch.setattr(session, "execute", _boom)
yield session
app.dependency_overrides.update({get_db: override_get_db, get_current_user: _fake_admin_user})
try:
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
r1 = await client.get("/api/v1/collected/summary")
assert r1.status_code == 200
assert "collected:facets:v1" in mem_cache.sets
assert any(k.startswith("collected:summary:v1:") for k in mem_cache.sets)
fail_db["enabled"] = True
r2 = await client.get("/api/v1/collected/summary")
assert r2.status_code == 200
assert r2.json() == r1.json()
s_res = await client.get("/api/v1/collected/sources")
assert s_res.status_code == 200
assert len(s_res.json()["sources"]) == 2
t_res = await client.get("/api/v1/collected/types")
assert t_res.status_code == 200
assert len(t_res.json()["data_types"]) == 2
finally:
app.dependency_overrides.clear()
engine.dispose()
+58
View File
@@ -345,3 +345,61 @@ def test_supported_credential_collectors_have_guides_and_connectivity_provider()
missing.append(f"{source}: missing connectivity provider for {provider}")
assert missing == []
def test_app_main_imports_and_all_collectors_satisfy_base_contract():
import importlib
import inspect
import pkgutil
import app.main # noqa: F401
import app.services.collectors as collectors_pkg
from app.services.collectors import BaseCollector, HTTPCollector, IntervalCollector
from app.services.collectors.compute_base import ComputeCollector
abstract_bases = (BaseCollector, HTTPCollector, IntervalCollector, ComputeCollector)
checked = 0
for mod in pkgutil.iter_modules(collectors_pkg.__path__, collectors_pkg.__name__ + "."):
module = importlib.import_module(mod.name)
for attr_name, obj in inspect.getmembers(module, inspect.isclass):
if obj.__module__ != mod.name or not issubclass(obj, BaseCollector):
continue
if obj in abstract_bases or attr_name.startswith("_"):
continue
assert not inspect.isabstract(obj), (
f"{mod.name}.{attr_name} still has abstract methods: {sorted(obj.__abstractmethods__)}"
)
inst = obj()
assert str(getattr(inst, "name", "") or "").strip(), f"{mod.name}.{attr_name} missing name"
assert callable(getattr(inst, "fetch", None)), f"{mod.name}.{attr_name} missing fetch()"
run_fn = getattr(inst, "run", None)
assert callable(run_fn) and "db" in inspect.signature(run_fn).parameters
checked += 1
assert checked > 0
registered = collector_registry.all()
assert len(registered) > 0
for key, col in registered.items():
assert isinstance(col, BaseCollector)
assert col.name == key
assert callable(getattr(col, "fetch", None))
assert "db" in inspect.signature(col.run).parameters
def test_earth_tile_collectors_registered_and_transform():
sample_summary = {
"warmup_max_zoom": 2,
"fetched": 3,
"cached_hits": 2,
"cache_stats": {"tile_count": 5, "total_mb": 1.25},
}
for source in ("cloud_hd_tiles", "earth_imagery_sentinel2", "earth_imagery_viirs_daily"):
collector = collector_registry.get(source)
assert collector is not None, f"Missing collector for {source}"
records = collector.transform([sample_summary])
assert len(records) == 1
record = records[0]
assert record["source_id"] == f"tile_pyramid:{source}"
assert record["value"] == 5
assert record["unit"] == "tiles"
assert record["metadata"]["record_kind"] == "earth_tile_pyramid"
+16 -5
View File
@@ -133,24 +133,32 @@ async def test_publish_and_audit_are_one_transaction_and_conflicts_do_not_overwr
db = fake_db(record)
actor = SimpleNamespace(id=1, username="admin")
old = deepcopy(record.payload)
edited_payload = default_config()
edited_payload["observations"][4]["values"]["CN"] = 24.5
edited_config = ComputeConfiguration.model_validate(edited_payload)
result = await publish_configuration(
db,
revision=old["revision"],
config=DEFAULT_CONFIGURATION,
config=edited_config,
actor=actor,
)
assert result["revision"] != old["revision"]
assert result["publish_id"] == result["revision"]
assert result["no_changes"] is False
audit = db.add.call_args.args[0]
assert isinstance(audit, AuditLog)
assert audit.details == {"before": old, "after": result}
assert audit.details["before"] == old
assert audit.details["after"] == result
assert audit.details["publish_id"] == result["publish_id"]
assert audit.details["parent_publish_id"] == old["revision"]
assert audit.actor_id == actor.id
db.commit.assert_awaited_once()
with pytest.raises(HTTPException) as failure:
await publish_configuration(
db, revision=old["revision"], config=DEFAULT_CONFIGURATION, actor=actor
db, revision=old["revision"], config=edited_config, actor=actor
)
assert failure.value.status_code == 409
assert record.payload == result
assert record.payload["revision"] == result["revision"]
db.rollback.assert_awaited_once()
db.commit.assert_awaited_once()
@@ -207,15 +215,18 @@ async def test_http_configuration_auth_validation_and_public_series():
)
assert response.status_code == 422
db.commit.assert_not_awaited()
edited = deepcopy(loaded["config"])
edited["observations"][4]["values"]["CN"] = 24.5
response = await client.put(
"/configuration",
json={
"revision": loaded["revision"],
"config": loaded["config"],
"config": edited,
},
)
assert response.status_code == 200
assert response.json()["revision"] != loaded["revision"]
assert response.json()["no_changes"] is False
assert (
await client.post(
"/configuration/reset",
@@ -0,0 +1,343 @@
"""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()
@@ -0,0 +1,231 @@
"""Tests for M3 revision-driven compute stage presentations, failure retry, idempotency, B->A reset, and small revisions."""
from __future__ import annotations
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
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,
StagePresentation,
TopicWatch,
)
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 import proactive_pipeline
from app.services.ai.proactive_pipeline import (
process_compute_revision_presentation,
retry_pending_compute_presentations,
)
from app.services.compute_configuration import (
DEFAULT_CONFIGURATION,
ensure_compute_revision_baseline,
publish_configuration,
)
def _make_sqlite_db():
engine = create_engine("sqlite://")
for model in (
SystemSetting,
AuditLog,
ComputeConfigurationRevision,
ComputeEvidenceCandidate,
EvidenceRecord,
SituationalAssessment,
StagePresentation,
TopicWatch,
):
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 _edit_cn_2024(value: float) -> 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"] = value
break
return ComputeConfiguration.model_validate(payload)
@pytest.mark.asyncio
async def test_failure_during_publish_marks_failed_and_retry_delivers_exactly_once(monkeypatch):
engine, raw, db = _make_sqlite_db()
try:
baseline = await ensure_compute_revision_baseline(db)
assert baseline is not None
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
# Force presentation delivery to fail during PUT /configuration
real_fn = proactive_pipeline.process_compute_revision_presentation
async def _boom(*_args, **_kwargs):
raise RuntimeError("Simulated presentation failure")
monkeypatch.setattr(proactive_pipeline, "process_compute_revision_presentation", _boom)
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
put_res = await client.put(
"/data-products/compute/configuration",
json={
"revision": baseline.publish_id,
"config": _edit_cn_2024(24.5).model_dump(mode="json"),
"publish_note": "1.5pp historical revision",
},
)
# Publish itself still returns 200 with presentation_status='failed'
assert put_res.status_code == 200
body = put_res.json()
assert body["presentation_status"] == "failed"
pid = body["publish_id"]
rev_row = raw.execute(
select(ComputeConfigurationRevision).where(
ComputeConfigurationRevision.publish_id == pid
)
).scalar_one()
assert rev_row.presentation_status == "failed"
assert rev_row.presentation_attempts == 1
assert "Simulated presentation failure" in rev_row.presentation_error
assert len(raw.execute(select(StagePresentation)).scalars().all()) == 0
# Restore real function and trigger retry via /proactive/evaluate
monkeypatch.setattr(proactive_pipeline, "process_compute_revision_presentation", real_fn)
eval_res = await client.post(
"/situational-awareness/proactive/evaluate",
json={"domain": "compute"},
)
assert eval_res.status_code == 200
assert eval_res.json()["delivered"] == 1
raw.refresh(rev_row)
assert rev_row.presentation_status == "delivered"
assert rev_row.presentation_delivered_at is not None
assert rev_row.presentation_error == ""
presentations = raw.execute(select(StagePresentation)).scalars().all()
assert len(presentations) == 1
pres = presentations[0]
assert pres.presentation_key == "compute-revision-notice"
assert pres.revision == rev_row.id
assert pres.contract["publish_id"] == pid
assert "2024 年全球总算力份额数据获修订" in pres.title
assert "这是对历史数据的修订,不代表当期算力跃升" in pres.summary
step1 = pres.contract["steps"][0]
assert step1["compute_mode"] == "global_share"
assert step1["focus_year"] == 2024
assert step1["spotlight_Statistic_codes"] == ["CN"]
# Re-running presentation for the same revision is strictly idempotent (no duplicate row)
dup_res = await process_compute_revision_presentation(db, rev_row.id)
assert dup_res["idempotent"] is True
retry_again = await retry_pending_compute_presentations(db)
assert retry_again["processed"] == 0
assert len(raw.execute(select(StagePresentation)).scalars().all()) == 1
finally:
raw.close()
engine.dispose()
@pytest.mark.asyncio
async def test_aba_reset_emits_new_presentation_and_milestone_only_edit_is_skipped():
engine, raw, db = _make_sqlite_db()
try:
baseline = await ensure_compute_revision_baseline(db)
assert baseline is not None
actor = SimpleNamespace(id=1, username="admin", role="admin")
# 1. Publish B (+1.5pp small revision)
env_b = await publish_configuration(
db,
revision=baseline.publish_id,
config=_edit_cn_2024(24.5),
actor=actor,
)
rev_b = raw.execute(
select(ComputeConfigurationRevision).where(
ComputeConfigurationRevision.publish_id == env_b["publish_id"]
)
).scalar_one()
res_b = await process_compute_revision_presentation(db, rev_b.id)
await db.commit()
assert res_b["status"] == "delivered"
# 2. Reset B -> A must ALSO emit a new presentation (no seen_fingerprints suppression!)
env_a2 = await publish_configuration(
db,
revision=env_b["publish_id"],
config=DEFAULT_CONFIGURATION,
actor=actor,
reset=True,
)
rev_a2 = raw.execute(
select(ComputeConfigurationRevision).where(
ComputeConfigurationRevision.publish_id == env_a2["publish_id"]
)
).scalar_one()
res_a2 = await process_compute_revision_presentation(db, rev_a2.id)
await db.commit()
assert res_a2["status"] == "delivered"
presentations = raw.execute(
select(StagePresentation).order_by(StagePresentation.id.asc())
).scalars().all()
assert len(presentations) == 2
assert presentations[0].contract["publish_id"] == env_b["publish_id"]
assert presentations[1].contract["publish_id"] == env_a2["publish_id"]
assert presentations[1].revision > presentations[0].revision
# 3. Milestone-only edit has no observation delta -> presentation_status='skipped', no presentation added
ms_payload = DEFAULT_CONFIGURATION.model_dump(mode="json")
ms_payload["milestones"][0]["title"] = "修订里程碑文案"
env_ms = await publish_configuration(
db,
revision=env_a2["publish_id"],
config=ComputeConfiguration.model_validate(ms_payload),
actor=actor,
)
assert env_ms["presentation_status"] == "skipped"
rev_ms = raw.execute(
select(ComputeConfigurationRevision).where(
ComputeConfigurationRevision.publish_id == env_ms["publish_id"]
)
).scalar_one()
res_ms = await process_compute_revision_presentation(db, rev_ms.id)
assert res_ms["status"] == "skipped"
assert len(raw.execute(select(StagePresentation)).scalars().all()) == 2
finally:
raw.close()
engine.dispose()
@@ -0,0 +1,758 @@
"""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()
+440
View File
@@ -0,0 +1,440 @@
"""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)
+210
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
import copy
import json
from types import SimpleNamespace
@@ -362,3 +363,212 @@ async def test_earth_stateless_stream_executes_published_custom_workflow_and_blo
finally:
app.dependency_overrides.clear()
engine.dispose()
@pytest.mark.asyncio
async def test_generic_dag_supports_output_schema_field_routing_and_guardrail_edges():
from app.services.ai import dag_executor
class _RepairAI:
def __init__(self):
self.calls = 0
async def analyze(self, _req):
self.calls += 1
if self.calls == 1:
return SimpleNamespace(content="暂时分析完成,结论是需要补查 need_followup。", model="m1", provider="p1")
return SimpleNamespace(
content=json.dumps({"decision": "need_followup", "reason": "need extra proof"}),
model="m1",
provider="p1",
)
workflow = {
"workflow_id": "custom.routing_test",
"name": "Generic Routing Test",
"published_graph": {
"nodes": [
{"id": "t", "node_type": "trigger", "title": "Start"},
{
"id": "judge",
"node_type": "llm_agent",
"title": "Judge",
"params": {
"output_schema": {
"type": "object",
"properties": {
"decision": {"type": "string", "enum": ["direct", "need_followup"]},
"reason": {"type": "string"},
},
"required": ["decision", "reason"],
}
},
},
{"id": "branch_direct", "node_type": "output", "title": "Direct Branch"},
{"id": "branch_followup", "node_type": "output", "title": "Followup Branch"},
],
"edges": [
{"id": "e1", "source": "t", "target": "judge", "condition": "always"},
{
"id": "e2",
"source": "judge",
"target": "branch_direct",
"condition": "on_field_equals",
"condition_value": "decision=direct",
},
{
"id": "e3",
"source": "judge",
"target": "branch_followup",
"condition": "on_field_equals",
"condition_value": "decision=need_followup",
},
],
},
"bindings": {},
}
ai = _RepairAI()
events = []
async for evt in dag_executor.run_workflow_dag_stream(
db=None,
workflow=workflow,
question="Route test",
ai_client=ai,
):
events.append(evt)
assert ai.calls == 2
node_statuses = {
e["data"]["node_id"]: e["data"]["status"]
for e in events
if e.get("event") == "node" and e["data"]["status"] in {"completed", "skipped"}
}
assert node_statuses["branch_direct"] == "skipped"
assert node_statuses["branch_followup"] == "completed"
@pytest.mark.asyncio
async def test_location_resolve_unknown_runs_real_generic_dag(monkeypatch):
from app.services.ai import dag_executor
from app.services.ai.workflow_registry import BUILTIN_WORKFLOWS
from app.services.location import workflow_tools
monkeypatch.setattr(
workflow_tools,
"lookup_wikidata_facility",
lambda _q: _async_val(SimpleNamespace(candidates=(), attempted_queries=())),
)
monkeypatch.setattr(
workflow_tools,
"lookup_peeringdb_facility",
lambda _q: _async_val(SimpleNamespace(candidates=(), attempted_queries=())),
)
monkeypatch.setattr(
"app.services.compute_center_locations._lookup_ror_organization",
lambda _q: None,
)
monkeypatch.setattr(
workflow_tools,
"_agent_geocoder",
lambda _q: {
"lat": "64.0025",
"lon": "-22.5594",
"display_name": "Keflavik, Iceland",
"address": {"city": "Keflavik", "country": "Iceland"},
},
)
class _Search:
async def search(self, _q, max_results=5):
return [
SimpleNamespace(
title="ISEG2 Verne Global",
url="https://verneglobal.com/iseg2",
snippet="Nebius ISEG2 sits in Keflavik, Iceland.",
source_provider="tavily",
)
]
class _JudgeAI:
def __init__(self):
self.calls = 0
async def is_ready(self):
return True, "minimax", "MiniMax-M3.1-Flash"
async def analyze(self, req):
self.calls += 1
items = (req.context or {}).get("evidence_items") or []
assert items and items[0]["id"] == "E1"
return SimpleNamespace(
content=json.dumps(
{
"decision": "located",
"facility_name": "Verne Global",
"city": "Keflavik",
"country": "Iceland",
"precision": "city",
"confidence": 0.92,
"evidence_ids": ["E1"],
"country_override_reason": "Nebius HQ is NL while cluster sits in Iceland.",
"reasoning": "E1 confirms Keflavik, Iceland.",
}
),
model="MiniMax-M3.1-Flash",
provider="minimax",
)
builtin_loc = copy.deepcopy(next(w for w in BUILTIN_WORKFLOWS if w["workflow_id"] == "location.resolve_unknown"))
workflow = {
"workflow_id": builtin_loc["workflow_id"],
"name": builtin_loc["name"],
"published_graph": builtin_loc["graph"],
"bindings": builtin_loc["bindings"],
}
ai = _JudgeAI()
events = []
async for evt in dag_executor.run_workflow_dag_stream(
db=None,
workflow=workflow,
question="定位 ISEG2",
targets=[{"entity_type": "compute_center", "entity_id": "top500_13", "label": "ISEG2"}],
earth_context={
"name": "ISEG2",
"operator": "Nebius",
"country": "荷兰",
"_location_runtime": {"web_search_client": _Search()},
},
ai_client=ai,
allow_external_tools=True,
):
events.append(evt)
assert ai.calls == 1
statuses = {
e["data"]["node_id"]: e["data"]["status"]
for e in events
if e.get("event") == "node" and e["data"]["status"] in {"completed", "skipped"}
}
assert statuses["l0_normalize"] == "completed"
assert statuses["l1_knowledge"] == "completed"
assert statuses["l2_research_r1"] == "completed"
assert statuses["l2_judge_r1"] == "completed"
assert statuses["l2_research_r2"] == "skipped"
assert statuses["l2_judge_r2"] == "skipped"
assert statuses["l3_geocode"] == "completed"
assert statuses["l3_geo_guardrail"] == "completed"
assert statuses["l4_persist_outcome"] == "completed"
done_ev = next(e["data"] for e in events if e.get("event") == "done")
so = done_ev["structured_output"]
assert so["success"] is True
assert so["best_candidate"]["city"] == "Keflavik"
assert so["best_candidate"]["country"] == "冰岛"
assert so["best_candidate"]["raw_payload"]["citations"] == ["https://verneglobal.com/iseg2"]
assert done_ev["scene_spec"]["fly_to"]["lat"] == pytest.approx(64.0025)
async def _async_val(v):
return v
+468
View File
@@ -0,0 +1,468 @@
"""Tests for admin layer-based data ledger endpoints."""
from datetime import UTC, datetime
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.api.v1 import data_ledger as ledger_api
from app.core.security import get_current_user
from app.db.session import get_db
from app.main import app
from app.models.bgp_collector_location import BGPCollectorLocation
from app.models.bgp_incident import BGPIncident
from app.models.collected_data import CollectedData
from app.models.compute_center_location import ComputeCenterLocationRecord
from app.models.data_snapshot import DataSnapshot
from app.models.datasource import DataSource
from app.models.earth_news import EarthNewsItem
from app.models.situational_assessment import WorkflowRun
from app.models.task import CollectionTask
from app.models.user import User, UserRole
from app.models.vessel import VesselCurrentState
class _MemoryCache:
def __init__(self):
self.store = {}
def get(self, key):
return self.store.get(key)
def set(self, key, value, expire_seconds=300):
self.store[key] = value
return True
class _SyncAsAsyncSession:
def __init__(self, session):
self._session = session
async def execute(self, stmt, params=None):
return self._session.execute(stmt, params or {})
async def scalar(self, stmt):
return self._session.scalar(stmt)
def _fake_admin_user() -> User:
return User(
id=1,
username="ledger_admin",
email="ledger@example.com",
role=UserRole.ADMIN,
is_active=True,
)
def _seed_ledger_db():
engine = create_engine("sqlite:///:memory:", future=True)
CollectedData.metadata.create_all(
engine,
tables=[
DataSource.__table__,
DataSnapshot.__table__,
CollectionTask.__table__,
CollectedData.__table__,
ComputeCenterLocationRecord.__table__,
VesselCurrentState.__table__,
BGPCollectorLocation.__table__,
BGPIncident.__table__,
EarthNewsItem.__table__,
WorkflowRun.__table__,
],
)
sync_factory = sessionmaker(engine, expire_on_commit=False)
now = datetime(2026, 12, 3, 12, 0, tzinfo=UTC)
with sync_factory() as s:
s.add_all(
[
DataSource(
name="CelesTrak TLE",
source="celestrak_tle",
module="L1",
collector_class="celestrak_tle",
),
CollectedData(
source="top500",
source_id="top500_1",
entity_key="top500:top500_1",
data_type="supercomputer",
name="Frontier",
extra_data={"country": "美国", "city": "Oak Ridge", "organization": "ORNL"},
collected_at=now,
is_current=True,
),
CollectedData(
source="epoch_ai_gpu",
source_id="epoch_gpu_unverified",
entity_key="epoch_ai_gpu:epoch_gpu_unverified",
data_type="gpu_cluster",
name="Candidate Cluster",
extra_data={"country": "United States", "operator": "Acme"},
collected_at=now,
is_current=True,
),
CollectedData(
source="epoch_ai_gpu",
source_id="epoch_ibm_dyeus",
entity_key="epoch_ai_gpu:epoch_ibm_dyeus",
data_type="gpu_cluster",
name="IBM DYEUS",
extra_data={
"country": "Россия",
"site_type": "data_center",
"location": "3231 Riverport Rd, Memphis, TN 38109",
},
collected_at=now,
is_current=True,
),
CollectedData(
source="epoch_ai_gpu",
source_id="epoch_pending_edge",
entity_key="epoch_ai_gpu:epoch_pending_edge",
data_type="edge_node",
name="Edge Node One",
extra_data={"country": "ישראל", "location": "Jülich Supercomputing Centre\n52428 Jülich, Germany"},
collected_at=now,
is_current=True,
),
CollectedData(
source="epoch_ai_gpu",
source_id="epoch_cloud_known",
entity_key="epoch_ai_gpu:epoch_cloud_known",
data_type="cloud_center",
name="Cloud Region Alpha",
extra_data={"country": "日本", "city": "Tokyo", "latitude": 35.68, "longitude": 139.76},
collected_at=now,
is_current=True,
),
CollectedData(
source="epoch_ai_gpu",
source_id="epoch_anon_placeholder",
entity_key="epoch_ai_gpu:epoch_anon_placeholder",
data_type="gpu_cluster",
name="Anonymized Chinese System",
extra_data={
"compute_contract": "v1",
"anonymous": True,
"country": "中国",
"location": "China",
"sources": [],
},
collected_at=now,
is_current=True,
),
ComputeCenterLocationRecord(
source="top500",
source_id="top500_1",
name="Frontier",
city="Oak Ridge",
country="美国",
latitude=35.93,
longitude=-84.31,
precision="site",
location_source="official_facility_registry",
verification_status="verified",
source_note="ORNL 官方页面确认。",
),
ComputeCenterLocationRecord(
source="epoch_ai_gpu",
source_id="epoch_cloud_known",
name="Cloud Region Alpha",
city="Tokyo",
country="日本",
latitude=35.68,
longitude=139.76,
precision="city",
location_source="source_coordinates",
verification_status="source_provided",
source_note="源数据自带城市级坐标。",
),
ComputeCenterLocationRecord(
source="epoch_ai_gpu",
source_id="epoch_gpu_unverified",
name="Candidate Cluster",
city="Dallas",
country="美国",
latitude=32.77,
longitude=-96.79,
precision="city",
location_source="llm_location_factcheck",
verification_status="unverified",
needs_confirmation=True,
source_note="待人工确认候选取样(E1)。",
),
ComputeCenterLocationRecord(
source="epoch_ai_gpu",
source_id="epoch_ibm_dyeus",
name="IBM DYEUS",
country="Россия",
precision="unknown",
location_source="agent_terminal_undisclosed",
verification_status="undisclosed",
needs_confirmation=False,
source_note="E6 confirms DYEUS location is undisclosed (E1-E5).",
raw_payload={"workflow_run_id": "run_dyeus_99"},
),
CollectedData(
source="celestrak_tle",
source_id="25544",
entity_key="celestrak_tle:25544",
data_type="satellite_tle",
name="ISS (ZARYA)",
extra_data={
"international_designator": "1998-067A",
"constellation_group": "stations",
"inclination": 51.6416,
},
collected_at=now,
is_current=True,
),
CollectedData(
source="spacetrack_tle",
source_id="",
entity_key="spacetrack_tle:",
data_type="satellite_tle",
name="Unknown",
extra_data={},
collected_at=now,
is_current=True,
),
CollectedData(
source="arcgis_cables",
source_id="cable_1",
entity_key="arcgis_cables:cable_1",
data_type="submarine_cable",
name="Asia-America Gateway",
extra_data={"country": "国际"},
collected_at=now,
is_current=True,
),
CollectedData(
source="arcgis_landing_points",
source_id="lp_1",
entity_key="arcgis_landing_points:lp_1",
data_type="landing_point",
name="Changi",
extra_data={"country": "新加坡"},
collected_at=now,
is_current=True,
),
CollectedData(
source="news_live_streams",
source_id="stream_1",
entity_key="news_live_streams:stream_1",
data_type="news_live_stream",
name="ABC News",
extra_data={"region": "全球", "language": "en"},
collected_at=now,
is_current=True,
),
CollectedData(
source="global_cloud_map",
source_id="cloud_1",
entity_key="global_cloud_map:cloud_1",
data_type="cloud_map_record",
name="Global Cloud Frame",
extra_data={},
collected_at=now,
is_current=True,
),
CollectedData(
source="earth_imagery_sentinel2",
source_id="tile_1",
entity_key="earth_imagery_sentinel2:tile_1",
data_type="earth_tile_pyramid",
name="Sentinel-2 Global",
extra_data={},
collected_at=now,
is_current=True,
),
VesselCurrentState(
mmsi=413000001,
lat=31.2,
lon=121.5,
sog=12.4,
name="COSCO STAR",
vessel_type_name="Cargo",
flag="CN",
source="aisstream_vessels",
observed_at=now,
),
BGPCollectorLocation(
collector_id="rrc00",
operator="RIPE NCC",
city="Amsterdam",
country="荷兰",
verification_status="verified",
updated_at=now,
),
BGPIncident(
source="ris_live_bgp",
incident_key="inc_1",
incident_type="route_leak",
title="Test Route Leak",
summary="Summary",
severity="high",
status="active",
started_at=now,
created_at=now,
),
EarthNewsItem(
id="news_1",
title="海底光缆维护通告",
url="https://example.com/news/1",
source="Reuters",
region="亚太",
latitude=1.35,
longitude=103.82,
location_label="Singapore",
published_at=now,
),
]
)
s.commit()
class _Ctx:
def __call__(self):
return self
async def __aenter__(self):
self._s = sync_factory()
return _SyncAsAsyncSession(self._s)
async def __aexit__(self, exc_type, exc, tb):
self._s.close()
return False
return engine, _Ctx()
@pytest.mark.asyncio
async def test_data_ledger_layers_compute_buckets_sanitization_and_layer_items(monkeypatch):
engine, session_factory = _seed_ledger_db()
mem_cache = _MemoryCache()
monkeypatch.setattr(ledger_api, "cache", mem_cache)
monkeypatch.setattr("app.api.v1.collected_data.cache", mem_cache)
async def override_get_db():
async with session_factory() as session:
yield session
app.dependency_overrides.update({get_db: override_get_db, get_current_user: _fake_admin_user})
try:
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
layers_res = await client.get("/api/v1/data-ledger/layers")
assert layers_res.status_code == 200
layers = {item["id"]: item for item in layers_res.json()["layers"]}
assert set(["compute", "satellites", "cables", "vessels", "bgp", "news", "weather", "geo", "raw"]).issubset(layers.keys())
assert layers["compute"]["count"] == 6
assert layers["vessels"]["count"] == 1
assert layers["news"]["name"] == "新闻与直播"
assert layers["news"]["count"] == 2
cc_res = await client.get("/api/v1/data-ledger/compute-centers")
assert cc_res.status_code == 200
cc = cc_res.json()
assert cc["total"] == 6
assert cc["counts"]["by_status"] == {
"located": 2,
"needs_confirmation": 1,
"terminal": 2,
"pending": 1,
}
assert cc["counts"]["by_site_type"] == {
"supercomputer": 1,
"gpu_cluster": 2,
"data_center": 1,
"cloud_center": 1,
"edge_node": 1,
}
ordered_ids = [row["source_id"] for row in cc["items"]]
assert ordered_ids[0] == "epoch_pending_edge"
assert ordered_ids[1] == "epoch_gpu_unverified"
assert ordered_ids[-2:] == ["epoch_ibm_dyeus", "epoch_anon_placeholder"]
by_sid = {row["source_id"]: row for row in cc["items"]}
assert by_sid["epoch_anon_placeholder"]["is_anonymous_placeholder"] is True
assert by_sid["epoch_anon_placeholder"]["city"] is None
assert by_sid["epoch_gpu_unverified"]["city"] == "Dallas"
assert by_sid["epoch_gpu_unverified"]["country"] == "美国"
assert by_sid["epoch_ibm_dyeus"]["city"] == "Memphis"
assert by_sid["epoch_pending_edge"]["city"] == "Jülich"
assert by_sid["epoch_pending_edge"]["country"] == "以色列"
assert by_sid["epoch_ibm_dyeus"]["country"] == "俄罗斯"
assert layers["satellites"]["count"] == 1
assert by_sid["epoch_ibm_dyeus"]["is_anonymous_placeholder"] is False
assert by_sid["epoch_ibm_dyeus"]["terminal_status"] == "undisclosed"
assert by_sid["epoch_ibm_dyeus"]["workflow_run_id"] == "run_dyeus_99"
assert "E6" not in (by_sid["epoch_ibm_dyeus"]["source_note"] or "")
assert "E1" not in (by_sid["epoch_gpu_unverified"]["source_note"] or "")
sat_res = await client.get("/api/v1/data-ledger/satellites/items?page=1&page_size=10")
assert sat_res.status_code == 200
sat_body = sat_res.json()
assert sat_body["total"] == 1
assert sat_body["rows"][0]["source"] == "CelesTrak TLE"
assert sat_body["rows"][0]["international_designator"] == "1998-067A"
assert sat_body["rows"][0]["constellation_group"] == "stations"
assert sat_body["rows"][0]["inclination"] == "51.64°"
status_res = await client.get("/api/v1/data-ledger/compute-centers?status=terminal")
assert status_res.status_code == 200
assert status_res.json()["total"] == 2
assert [r["source_id"] for r in status_res.json()["items"]] == [
"epoch_ibm_dyeus",
"epoch_anon_placeholder",
]
for path in (
"/api/v1/data-ledger/satellites/items?page=1&page_size=1",
"/api/v1/data-ledger/cables/items?kind=landing_point",
"/api/v1/data-ledger/vessels/items?page=1&page_size=1",
"/api/v1/data-ledger/bgp/items?kind=incidents",
"/api/v1/data-ledger/news/items?kind=items",
"/api/v1/data-ledger/news/items?kind=live_streams",
"/api/v1/data-ledger/weather/items",
"/api/v1/data-ledger/geo/items",
):
r = await client.get(path)
assert r.status_code == 200, f"{path} failed: {r.text}"
body = r.json()
assert body["total"] == 1
assert len(body["rows"]) == 1
assert len(body["columns"]) >= 4
missing = await client.get("/api/v1/data-ledger/nonexistent/items")
assert missing.status_code == 404
finally:
app.dependency_overrides.clear()
engine.dispose()
def test_extract_city_from_location_cases():
assert ledger_api._normalize_ledger_country("Philippines (the)") == "菲律宾"
assert ledger_api._extract_city_from_location("Tsukuba, Japan", "日本") == "Tsukuba"
assert ledger_api._extract_city_from_location("3231 Riverport Rd, Memphis, TN 38109", "美国") == "Memphis"
assert (
ledger_api._extract_city_from_location(
"33°24'28.7\"N 112°21'54.3\"W\nGoodyear, Arizona, USA",
"美国",
)
== "Goodyear"
)
assert (
ledger_api._extract_city_from_location(
"Jülich Supercomputing Centre (JSC)\n52428 Jülich, Germany",
"德国",
)
== "Jülich"
)
assert ledger_api._extract_city_from_location("Follummoveien 94, 3516 Hønefoss, Norway", "挪威") == "Hønefoss"
assert ledger_api._extract_city_from_location("United States of America", "美国") is None
assert ledger_api._extract_city_from_location('"on prem" for Tesla', "美国") is None
assert ledger_api._extract_city_from_location("The Nordics", None) is None
@@ -0,0 +1,414 @@
"""Regression tests for collector auth_type, secret persistence, Space-Track config, and probes."""
from __future__ import annotations
import asyncio
import gzip
from types import SimpleNamespace
import httpx
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy import create_engine, select
from sqlalchemy.orm import sessionmaker
from app.core.enums import AuthType
from app.core.security import get_current_user
from app.core.websocket.broadcaster import broadcaster
from app.db.session import Base, get_db
from app.main import app
from app.models.collected_data import CollectedData
from app.models.datasource import DataSource
from app.models.datasource_config import DataSourceConfig
from app.models.earth_news import EarthNewsItem
from app.models.system_setting import SystemSetting
from app.services import datasource_connectivity
from app.services.collectors.base import BaseCollector
from app.services.collectors.iptoasn import IPtoASNPrefixGeoCollector
from app.services.collectors.spacetrack import SpaceTrackTLECollector
class _SyncAsAsyncSession:
def __init__(self, sync_session):
self._s = sync_session
def add(self, obj):
return self._s.add(obj)
async def execute(self, stmt, *args, **kwargs):
return self._s.execute(stmt, *args, **kwargs)
async def scalar(self, stmt, *args, **kwargs):
return self._s.scalar(stmt, *args, **kwargs)
async def get(self, model, ident):
return self._s.get(model, ident)
async def delete(self, obj):
return self._s.delete(obj)
async def commit(self):
return self._s.commit()
async def rollback(self):
return self._s.rollback()
async def refresh(self, obj):
return self._s.refresh(obj)
async def close(self):
return self._s.close()
def _make_db():
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(
engine,
tables=[
DataSourceConfig.__table__,
DataSource.__table__,
CollectedData.__table__,
SystemSetting.__table__,
EarthNewsItem.__table__,
],
)
sync_factory = sessionmaker(engine, expire_on_commit=False)
class _Ctx:
def __call__(self):
return self
async def __aenter__(self):
self._sess = _SyncAsAsyncSession(sync_factory())
return self._sess
async def __aexit__(self, *_args):
await self._sess.close()
return engine, _Ctx()
def _mock_httpx_factory(handler):
real_async_client = httpx.AsyncClient
transport = httpx.MockTransport(handler)
def _factory(*_args, **kwargs):
kwargs.pop("follow_redirects", None)
kwargs["transport"] = transport
return real_async_client(**kwargs)
return _factory
@pytest.mark.asyncio
async def test_barentswatch_oauth_client_accepted_and_partial_update_preserves_secret(monkeypatch):
assert AuthType.OAUTH_CLIENT.value == "oauth_client"
engine, factory = _make_db()
captured: dict = {}
def handler(request: httpx.Request) -> httpx.Response:
captured["urls"] = [*captured.get("urls", []), str(request.url)]
if "barentswatch.no/connect/token" in str(request.url):
captured["token_body"] = request.content.decode()
return httpx.Response(200, json={"access_token": "tok_test_123"})
captured["auth_header"] = request.headers.get("Authorization")
return httpx.Response(200, json=[])
monkeypatch.setattr(datasource_connectivity.httpx, "AsyncClient", _mock_httpx_factory(handler))
async def override_db():
async with factory() as session:
yield session
def override_user():
return SimpleNamespace(id=1, username="admin", role="admin", email="admin@test")
app.dependency_overrides[get_db] = override_db
app.dependency_overrides[get_current_user] = override_user
try:
async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:
# 1. Create BarentsWatch config with auth_type=oauth_client (previously 422)
create_resp = await client.post(
"/api/v1/datasources/configs",
json={
"name": "barentswatch_vessels",
"source_type": "api",
"endpoint": "https://live.ais.barentswatch.no/v1/latest/combined",
"auth_type": "oauth_client",
"auth_config": {"client_id": "id-1", "client_secret": "real-secret-1"},
},
)
assert create_resp.status_code == 200, create_resp.text
cfg_id = create_resp.json()["id"]
# 2. Partial PUT updating client_id (omitting masked client_secret) preserves real-secret-1
put_resp = await client.put(
f"/api/v1/datasources/configs/{cfg_id}",
json={
"endpoint": "https://live.ais.barentswatch.no/v1/latest/combined",
"auth_type": "oauth_client",
"auth_config": {"client_id": "id-2", "client_secret": "••••••••"},
},
)
assert put_resp.status_code == 200, put_resp.text
async with factory() as db:
row = (await db.execute(select(DataSourceConfig).where(DataSourceConfig.id == cfg_id))).scalar_one()
assert row.auth_config["client_id"] == "id-2"
assert row.auth_config["client_secret"] == "real-secret-1"
# 3. Builtin connect with partial auth_config uses merged saved secret
conn_resp = await client.post(
"/api/v1/datasources/configs/builtin/connect",
json={
"name": "barentswatch_vessels",
"source_type": "api",
"endpoint": "https://live.ais.barentswatch.no/v1/latest/combined",
"auth_type": "oauth_client",
"auth_config": {"client_id": "id-2"},
},
)
assert conn_resp.status_code == 200, conn_resp.text
assert conn_resp.json()["success"] is True
assert "client_secret=real-secret-1" in captured["token_body"]
assert captured["auth_header"] == "Bearer tok_test_123"
finally:
app.dependency_overrides.clear()
engine.dispose()
@pytest.mark.asyncio
async def test_spacetrack_collector_uses_saved_database_credentials(monkeypatch):
engine, factory = _make_db()
monkeypatch.delenv("SPACETRACK_USERNAME", raising=False)
monkeypatch.delenv("SPACETRACK_PASSWORD", raising=False)
monkeypatch.setattr(datasource_connectivity, "_read_zshrc_env", lambda: {})
posted: list[str] = []
def handler(request: httpx.Request) -> httpx.Response:
if request.method == "POST" and "ajaxauth/login" in str(request.url):
posted.append(request.content.decode())
return httpx.Response(200, text="{}")
if request.method == "GET" and str(request.url).rstrip("/").endswith("space-track.org"):
return httpx.Response(200, text="ok")
return httpx.Response(200, json=[{"NORAD_CAT_ID": 25544, "OBJECT_NAME": "ISS"}])
monkeypatch.setattr("app.services.collectors.spacetrack.httpx.AsyncClient", _mock_httpx_factory(handler))
try:
async with factory() as db:
db.add(
DataSourceConfig(
name="spacetrack_tle",
source_type="api",
endpoint="https://www.space-track.org/basicspacedata/query/class/gp/limit/10/format/json",
auth_type="basic",
auth_config={"username": "db-user", "password": "db-password"},
is_active=True,
)
)
await db.commit()
collector = SpaceTrackTLECollector()
collector._db_session = db
collector._resolved_url = "https://www.space-track.org/basicspacedata/query/class/gp/limit/10/format/json"
rows = await collector.fetch()
assert rows == [{"NORAD_CAT_ID": 25544, "OBJECT_NAME": "ISS"}]
assert posted and "identity=db-user" in posted[0] and "password=db-password" in posted[0]
finally:
engine.dispose()
@pytest.mark.asyncio
async def test_builtin_connectivity_probes_match_collector_protocols(monkeypatch):
seen_requests: list[tuple[str, dict[str, str]]] = []
def handler(request: httpx.Request) -> httpx.Response:
url = str(request.url)
seen_requests.append((url, dict(request.headers)))
if "broker.bgpstream.caida.org" in url:
if url.endswith("/v2"):
return httpx.Response(404)
return httpx.Response(200, json={"error": None, "data": {"resources": []}})
if "celestrak.org" in url:
if "CATNR=25544" not in url:
return httpx.Response(200, text='Invalid query: ""')
return httpx.Response(200, json=[{"NORAD_CAT_ID": 25544}])
if "services.arcgis.com" in url:
if "f=json" not in url:
return httpx.Response(200, text="<html>ArcGIS HTML</html>")
return httpx.Response(200, json={"count": 42})
if "epoch.ai" in url:
if url.endswith("gpu-clusters"):
return httpx.Response(200, text="<!doctype html><html></html>", headers={"content-type": "text/html"})
return httpx.Response(200, text="Name,Country,Status\nFrontier,USA,Active\n", headers={"content-type": "text/csv"})
if "ris-live.ripe.net" in url:
assert "x-ris-subscribe" in request.headers
return httpx.Response(200, text='{"type":"ris_message","data":{}}\n', headers={"content-type": "application/x-ndjson"})
return httpx.Response(404)
monkeypatch.setattr(datasource_connectivity.httpx, "AsyncClient", _mock_httpx_factory(handler))
engine, factory = _make_db()
try:
async with factory() as db:
for source, endpoint in [
("bgpstream_bgp", "https://broker.bgpstream.caida.org/v2"),
("celestrak_tle", "https://celestrak.org/NORAD/elements/gp.php"),
("arcgis_cables", "https://services.arcgis.com/org/ArcGIS/rest/services/Cables/FeatureServer/2/query"),
("epoch_ai_gpu", "https://epoch.ai/data/gpu-clusters"),
("ris_live_bgp", "https://ris-live.ripe.net/v1/stream/?format=json&client=planet-ris-live"),
("media_news_archive", ""),
]:
res = await datasource_connectivity.test_builtin_connectivity(
source, endpoint, "none", {}, {"timeout": 10}, db=db
)
assert res["success"] is True, (source, res)
assert any("/v2/data?" in url and "intervals%5B%5D=" in url for url, _ in seen_requests)
# Reject fake HTTP 200 responses when content fails validation (e.g., ArcGIS/CelesTrak bad params)
bad_arcgis = await datasource_connectivity.test_builtin_connectivity(
"arcgis_cables",
"https://services.arcgis.com/org/ArcGIS/rest/services/Cables/FeatureServer/2/query?f=html",
"none",
{},
{"timeout": 10},
)
assert bad_arcgis["success"] is False
bad_celestrak = await datasource_connectivity.test_builtin_connectivity(
"celestrak_tle",
"https://celestrak.org/NORAD/elements/gp.php?BAD=1",
"none",
{},
{"timeout": 10},
)
assert bad_celestrak["success"] is False
finally:
engine.dispose()
class _StrictNonConcurrentSession:
"""Fake AsyncSession that fails immediately if commit() is entered concurrently."""
def __init__(self, task: SimpleNamespace) -> None:
self.task = task
self._in_commit = False
self.active_commits = 0
self.max_concurrent_commits = 0
self.commit_count = 0
self.committed_progress: list[int] = []
async def commit(self) -> None:
if self._in_commit:
raise RuntimeError("concurrent operations are not permitted")
self._in_commit = True
self.active_commits += 1
self.max_concurrent_commits = max(self.max_concurrent_commits, self.active_commits)
try:
self.committed_progress.append(int(self.task.records_processed or 0))
await asyncio.sleep(0.01)
self.commit_count += 1
finally:
self.active_commits -= 1
self._in_commit = False
def _make_task_stub(task_id: int = 29) -> SimpleNamespace:
return SimpleNamespace(
id=task_id,
status="running",
phase="downloading",
phase_progress=0.0,
phase_message="",
phase_current=0,
phase_total=0,
phase_unit="bytes",
progress=0.0,
records_processed=0,
total_records=0,
started_at=None,
completed_at=None,
error_message=None,
)
@pytest.mark.asyncio
async def test_iptoasn_parallel_download_progress_serializes_db_commits(tmp_path, monkeypatch):
v4_path = tmp_path / "ip2asn-v4.tsv.gz"
v6_path = tmp_path / "ip2asn-v6.tsv.gz"
with gzip.open(v4_path, "wt", encoding="utf-8") as f:
f.write("1.0.0.0\t1.0.0.255\t13335\tAU\tCLOUDFLARENET\n")
with gzip.open(v6_path, "wt", encoding="utf-8") as f:
f.write("2606:4700::\t2606:4700::ffff\t13335\tUS\tCLOUDFLARENET\n")
async def _noop_broadcast(_payload):
return None
monkeypatch.setattr(broadcaster, "broadcast_datasource_task_update", _noop_broadcast)
collector = IPtoASNPrefixGeoCollector()
task = _make_task_stub(task_id=29)
strict_session = _StrictNonConcurrentSession(task)
collector._resolved_url = "https://iptoasn.com/data/ip2asn-combined.tsv.gz"
collector._db_session = strict_session
collector._current_task = task
async def _fake_fetch_remote_info(_client, _url):
return {"content_length": 10_000_000}
async def _fake_download_dataset_file(_client, url, *, progress_callback=None):
for step in (2_500_000, 5_000_000, 7_500_000, 10_000_000, 10_000_000):
if progress_callback:
await progress_callback(step, 10_000_000)
await asyncio.sleep(0)
return v4_path if "v4" in url else v6_path
async def _no_short_circuit(_db, *, file_sha256):
return None
monkeypatch.setattr(collector._downloader, "fetch_remote_info", _fake_fetch_remote_info)
monkeypatch.setattr(collector, "_download_dataset_file", _fake_download_dataset_file)
monkeypatch.setattr(collector, "_can_short_circuit_unchanged_file", _no_short_circuit)
rows = await collector.fetch()
assert len(rows) == 2
assert {row["asn"] for row in rows} == {"13335"}
assert strict_session.max_concurrent_commits == 1
assert strict_session.commit_count >= 2
assert strict_session.committed_progress == sorted(strict_session.committed_progress)
assert collector._current_task.records_processed == 20_000_000
@pytest.mark.asyncio
async def test_base_collector_serializes_concurrent_progress_and_phase_commits(monkeypatch):
class _DummyCollector(BaseCollector):
name = "dummy_concurrent_collector"
async def fetch(self):
return []
async def _noop_broadcast(_payload):
return None
monkeypatch.setattr(broadcaster, "broadcast_datasource_task_update", _noop_broadcast)
collector = _DummyCollector()
task = _make_task_stub(task_id=30)
task.total_records = 10
strict_session = _StrictNonConcurrentSession(task)
collector._current_task = task
collector._db_session = strict_session
await asyncio.gather(
collector.update_progress(1, commit=True, force=True),
collector.update_phase_progress(current=2, total=10, unit="rows", message="step 2", commit=True, force=True),
collector.set_phase("downloading", message="step 3"),
collector.update_progress(4, commit=True, force=True),
collector.update_phase_progress(current=5, total=10, unit="rows", message="step 5", commit=True, force=True),
collector.set_phase("parsing", message="step 6"),
)
assert strict_session.max_concurrent_commits == 1
assert strict_session.commit_count == 6
@@ -0,0 +1,65 @@
"""Unit tests for masked collector credential previews on dashboard config summaries."""
from __future__ import annotations
from app.api.v1.datasource_config import (
build_masked_credential_preview,
mask_credential_value,
)
def test_mask_credential_value_never_leaks_secrets() -> None:
assert mask_credential_value("") == ""
assert mask_credential_value("secret-pass", secret=True) == "••••••"
assert mask_credential_value("short", secret=True, reveal_edges=True) == "••••••"
assert mask_credential_value("tvly-dev-123456789a4f", secret=True, reveal_edges=True) == "tvl••••9a4f"
assert mask_credential_value("bw_client_82", secret=False) == "bw•••82"
assert mask_credential_value("ops", secret=False) == "•••"
def test_build_masked_credential_preview_variants() -> None:
assert build_masked_credential_preview(
requires_credentials=False,
auth_type="none",
auth_config={},
) == (True, "")
has_creds, preview = build_masked_credential_preview(
requires_credentials=True,
auth_type="oauth2",
auth_config={},
resolved_provider="barentswatch",
resolved_values={"client_id": "bw_client_82", "client_secret": "super-secret-xyz"},
)
assert has_creds is True
assert preview == "bw•••82 · ••••••"
assert "super-secret" not in preview
has_creds, preview = build_masked_credential_preview(
requires_credentials=True,
auth_type="basic",
auth_config={"username": "ops_user_1", "password": "top_password"},
resolved_provider="spacetrack",
)
assert has_creds is True
assert preview == "op•••_1 · ••••••"
assert "top_password" not in preview
has_creds, preview = build_masked_credential_preview(
requires_credentials=True,
auth_type="api_key",
auth_config={"api_key": "ais_key_abcdef12"},
resolved_provider="aisstream",
)
assert has_creds is True
assert preview == "ais••••ef12"
assert "abcdef" not in preview
has_creds, preview = build_masked_credential_preview(
requires_credentials=True,
auth_type="api_key",
auth_config={},
resolved_provider="aisstream",
)
assert has_creds is False
assert preview == ""
+164
View File
@@ -212,6 +212,8 @@ async def test_enforce_mode_blocks_anonymous_endpoints_and_allows_public_exempti
"/api/v1/news/earth-feed",
"/api/v1/data-products/compute/configuration",
"/api/v1/earth/brand",
"/api/v1/earth/boundaries/manifest",
"/api/v1/earth/boundaries/files/earth-boundaries.test.pmtiles",
"/api/v1/tv/streams",
]:
resp = await client.get(protected_path)
@@ -616,3 +618,165 @@ async def test_controlled_openapi_and_production_mode_defaults(monkeypatch, acce
assert "/api/v1/visualization/geo/summary" in ext["paths"]
assert "/api/v1/users" not in ext["paths"]
assert "/api/v1/settings/integrations" not in ext["paths"]
@pytest.mark.asyncio
async def test_tile_rate_limit_tier_isolated_from_business_apis(monkeypatch, access_db):
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
monkeypatch.setattr(settings, "TURNSTILE_SECRET_KEY", "")
monkeypatch.setattr(settings, "EARTH_SESSION_RATE_LIMIT_PER_MIN", 2)
monkeypatch.setattr(settings, "EARTH_SESSION_TILE_RATE_LIMIT_PER_MIN", 3)
from app.api.v1 import earth as earth_api
from app.api.v1 import visualization as visualization_api
async def _mock_fetch_terrain_tile(_client, _z: int, _x: int, _y: int):
return b"png", "image/png", {}
async def _mock_get_or_fetch_tile(_source_key: str, _z: int, _x: int, _y: int, **_kwargs):
return b"webp", True
monkeypatch.setattr(visualization_api, "_fetch_terrain_tile", _mock_fetch_terrain_tile)
monkeypatch.setattr(earth_api, "resolve_boundary_artifact", lambda _name: None)
import app.services.earth_tiles as earth_tiles_service
monkeypatch.setattr(earth_tiles_service, "get_or_fetch_tile", _mock_get_or_fetch_tile)
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
session_resp = await client.post(
"/api/v1/auth/earth-session",
json={"client_type": "web"},
headers={"Origin": "http://test", "Sec-Fetch-Site": "same-origin"},
)
assert session_resp.status_code == 200
# Exhaust the tile bucket across boundaries, basemap tiles, and terrarium tiles (3 total).
assert (
await client.get("/api/v1/earth/boundaries/files/missing.pmtiles")
).status_code == 404
assert (
await client.get("/api/v1/earth/tiles/sentinel2_hd/2/1/1.webp")
).status_code == 200
assert (
await client.get("/api/v1/visualization/terrain/terrarium/2/1/1.png")
).status_code == 200
assert (
await client.get("/api/v1/earth/boundaries/files/missing.pmtiles")
).status_code == 429
# Business API bucket remains completely unaffected until its own limit (2).
assert (await client.get("/api/v1/earth/brand")).status_code == 200
assert (await client.get("/api/v1/earth/boundaries/status")).status_code == 200
assert (await client.get("/api/v1/earth/brand")).status_code == 429
@pytest.mark.asyncio
async def test_desktop_earth_session_rate_limit_isolated_by_client_ip(monkeypatch, access_db):
monkeypatch.setattr(settings, "EARTH_API_AUTH_MODE", "enforce")
secret = "desktop-shared-hmac-secret"
monkeypatch.setattr(settings, "EARTH_DESKTOP_HANDSHAKE_SECRET", secret)
monkeypatch.setattr(settings, "EARTH_SESSION_RATE_LIMIT_PER_MIN", 1)
client_header = "planet-earth-desktop/0.82.0"
def _signed_headers(nonce: str, client_ip: str) -> dict[str, str]:
ts = str(int(time.time()))
sig = hmac.new(
secret.encode("utf-8"),
f"{ts}.{nonce}.{client_header}".encode("utf-8"),
hashlib.sha256,
).hexdigest()
return {
"X-Forwarded-For": client_ip,
"X-Planet-Client": client_header,
"X-Planet-Client-Timestamp": ts,
"X-Planet-Client-Nonce": nonce,
"X-Planet-Client-Signature": sig,
}
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
r1 = await client.post(
"/api/v1/auth/earth-session",
json={"client_type": "desktop"},
headers=_signed_headers("nonce-ip-1", "10.0.0.1"),
)
r2 = await client.post(
"/api/v1/auth/earth-session",
json={"client_type": "desktop"},
headers=_signed_headers("nonce-ip-2", "10.0.0.2"),
)
assert r1.status_code == 200 and r2.status_code == 200
tok1 = r1.json()["token"]
tok2 = r2.json()["token"]
c1 = access_gate.verify_earth_session_token(tok1)
c2 = access_gate.verify_earth_session_token(tok2)
assert c1 is not None and c2 is not None
assert c1["cid"] != c2["cid"]
assert c1["cid"].startswith("10.0.0.1:")
assert c2["cid"].startswith("10.0.0.2:")
assert (
await client.get("/api/v1/earth/brand", headers={EARTH_TOKEN_HEADER: tok1})
).status_code == 200
assert (
await client.get("/api/v1/earth/brand", headers={EARTH_TOKEN_HEADER: tok1})
).status_code == 429
# Second desktop client IP still has its own fresh quota.
assert (
await client.get("/api/v1/earth/brand", headers={EARTH_TOKEN_HEADER: tok2})
).status_code == 200
@pytest.mark.asyncio
async def test_redis_rate_limit_atomic_lua_and_negative_ttl_recovery(monkeypatch):
class _FakeLuaRedis:
def __init__(self):
self.counts: dict[str, int] = {}
self.ttls: dict[str, int] = {}
self.eval_calls = 0
async def eval(self, script: str, numkeys: int, key: str, window_seconds: int):
self.eval_calls += 1
assert numkeys == 1
assert "TTL" in script and "EXPIRE" in script
count = self.counts.get(key, 0) + 1
self.counts[key] = count
if count == 1 or self.ttls.get(key, -1) < 0:
self.ttls[key] = int(window_seconds)
return count
lua_redis = _FakeLuaRedis()
monkeypatch.setattr(access_gate, "_AsyncRedisClient", type("R", (), {"get_client": staticmethod(lambda: lua_redis)}))
await access_gate.check_sliding_rate_limit("earth:earth_web:1.2.3.4", limit=2, window_seconds=60)
assert lua_redis.eval_calls == 1
assert lua_redis.ttls["access_gate:earth:earth_web:1.2.3.4"] == 60
class _LegacyRedisWithNegativeTtl:
def __init__(self):
self.counts = {"access_gate:stuck": 1}
self.ttls = {"access_gate:stuck": -1}
self.expired_with: list[int] = []
async def incr(self, key: str) -> int:
self.counts[key] = self.counts.get(key, 0) + 1
return self.counts[key]
async def ttl(self, key: str) -> int:
return self.ttls.get(key, -1)
async def expire(self, key: str, seconds: int) -> bool:
self.ttls[key] = seconds
self.expired_with.append(seconds)
return True
legacy_redis = _LegacyRedisWithNegativeTtl()
monkeypatch.setattr(
access_gate,
"_AsyncRedisClient",
type("R2", (), {"get_client": staticmethod(lambda: legacy_redis)}),
)
await access_gate.check_sliding_rate_limit("stuck", limit=5, window_seconds=60)
assert legacy_redis.ttls["access_gate:stuck"] == 60
assert legacy_redis.expired_with == [60]
Loaded 100 of 289 files, more files were not shown because too many files have changed in this diff. Show more