feat: 工参每周一一份并提前缓存,登录后自动补缺;评估按周一取工参,指标等平台同步三天后再查

- 工参从 2024-01-01 起每周一一份,排队任务一次补一份,新的周先补;一个地市同时只取一份
- 大数据平台账号登录成功后排补取,排队进程每 10 分钟检查缺的周;排队进程重启时放开没取完的快照
- 拆除前工参用拆除日上一周的周一,拆除后用当周的周一;待拆小区不参与周边站和指标匹配
- 一周的指标等周日过后第 3 天才查,没到时间在结果说明里写明哪天之后有数据
- AI 工作区没就绪时开通接口返回 200,改为等待重试,最多 150 秒
- 排任务加锁,避免多个线程同时排时用到已关闭的连接池
- 运行面板显示各地市工参缓存进度
This commit is contained in:
2026-11-12 12:31:03 +08:00
parent 452b01498f
commit 3a7a5b39b4
20 changed files with 814 additions and 180 deletions
+29 -12
View File
@@ -10,7 +10,7 @@ from collections.abc import Callable
from dataclasses import replace
from datetime import date, timedelta
from app.collect.gongcan import GongcanMissing, Target, evaluable, nearest_sites, target_center
from app.collect.gongcan import SYNC_LAG_DAYS, GongcanMissing, Target, after_monday, evaluable, monday_of, nearest_sites, target_center
from app.evaluate.demand import DemandRow, SiteGroup
from app.evaluate.sources import GongcanSource, MetricSource
@@ -24,15 +24,20 @@ class EvalFailure(Exception):
def week_of(day: date) -> tuple[date, date]:
"""拆除日所在的自然周,周一到周日。"""
monday = day - timedelta(days=day.weekday())
monday = monday_of(day)
return monday, monday + timedelta(days=6)
def ready_day(week_end: date) -> date:
"""这一周的指标从哪天起可以查:平台数据约三天同步好,周日之后再等 SYNC_LAG_DAYS 天。"""
return week_end + timedelta(days=SYNC_LAG_DAYS)
def windows(removal: date, today: date) -> tuple[tuple[date, date], tuple[date, date] | None]:
"""停闭前是拆除日所在周的上一周,停闭后是拆除日所在的那一周。当周周日还没过就没有停闭后。"""
"""停闭前是拆除日所在周的上一周,停闭后是拆除日所在的那一周。当周的数据平台还没同步好时没有停闭后。"""
after_start, after_end = week_of(removal)
before = (after_start - timedelta(days=7), after_end - timedelta(days=7))
if today <= after_end:
if today < ready_day(after_end):
return before, None
return before, (after_start, after_end)
@@ -91,7 +96,7 @@ def evaluate_site(
target = Target(site=group.site) if group.site else Target(cgis=tuple(group.cgis))
stage("确定拆除前工参")
try:
before_day = gongcan.before_day(city, target, group.removal)
before_day = gongcan.before_day(city, target, group.removal, today)
except GongcanMissing as exc:
raise EvalFailure(str(exc)) from exc
stage("确定拆除后工参")
@@ -112,7 +117,12 @@ def evaluate_site(
missing = [cgi for cgi in group.cgis if cgi not in {cell["cgi"] for cell in targets}]
if missing:
notes.append(f"{before_day} 的工参里没有 {'、'.join(missing)}")
pool = gongcan.cells(city, after.day) if after is not None and after.day != before_day else before_cells
wanted_after = after_monday(group.removal, today)
if after is None and wanted_after is not None:
notes.append(f"{wanted_after} 的工参没取到,周边站按拆除前工参算")
# 拆除后工参是拆除当周周一的,待拆小区通常还在里面;算周边站和取指标时去掉它们。
own = {cell["cgi"] for cell in targets} | set(group.cgis)
pool = [cell for cell in (gongcan.cells(city, after.day) if after is not None and after.day != before_day else before_cells) if cell["cgi"] not in own]
center = target_center(targets)
neighbors: list[tuple[str, float]] = []
if center is None:
@@ -125,8 +135,12 @@ def evaluate_site(
stage("查询停闭前后指标")
before_window, after_window = windows(group.removal, today)
if after_window is None:
notes.append("拆除当周还没结束,没有停闭后的指标")
before_ready = today >= ready_day(before_window[1])
if not before_ready:
notes.append(f"停闭前一周({before_window[0]} 至 {before_window[1]})的指标平台要到 {ready_day(before_window[1])} 才同步好,现在没有停闭前后的指标")
elif after_window is None:
after_week = week_of(group.removal)
notes.append(f"停闭后一周({after_week[0]} 至 {after_week[1]})的指标平台要到 {ready_day(after_week[1])} 才同步好,现在没有停闭后的指标")
by_site: dict[str, list[dict]] = {}
for cell in pool:
name = cell.get("cell_name") or ""
@@ -137,7 +151,7 @@ def evaluate_site(
for cell in sorted(by_site.get(site, []), key=lambda item: (item.get("tech") != "4G", item.get("cell_name") or "")):
picked.append((site, distance, cell))
picked_cells = [cell for _site, _distance, cell in picked]
before_metrics = metrics.window(picked_cells, *before_window) if picked_cells else {}
before_metrics = metrics.window(picked_cells, *before_window) if picked_cells and before_ready else {}
after_metrics = metrics.window(picked_cells, *after_window) if picked_cells and after_window else {}
item2 = [
{
@@ -173,7 +187,7 @@ def evaluate_site(
}
if group.kind == "dixiao":
stage("查询扇区指标")
section1, sectors, sector_notes = _dixiao_sections(rows, targets, before_cells, metrics, before_window, after_window)
section1, sectors, sector_notes = _dixiao_sections(rows, targets, before_cells, metrics, before_window if before_ready else None, after_window)
payload["section1"] = section1
payload["sectors"] = sectors
notes.extend(sector_notes)
@@ -199,11 +213,12 @@ def _dixiao_sections(
targets: list[dict],
pool: list[dict],
metrics: MetricSource,
before_window: tuple[date, date],
before_window: tuple[date, date] | None,
after_window: tuple[date, date] | None,
) -> tuple[list[dict], list[dict], list[str]]:
"""before_window 为空表示停闭前一周的指标还没同步好:第 1 节只留名称,第 2 节不出。"""
notes: list[str] = []
own = metrics.profile(targets, *before_window)
own = metrics.profile(targets, *before_window) if before_window else {}
section1 = []
for row in rows:
item = own.get(row.cgi, {})
@@ -239,6 +254,8 @@ def _dixiao_sections(
"评估结果": "通过",
}
)
if before_window is None:
return section1, [], notes
own_cgis = {row.cgi for row in rows}
by_sector: dict[str, list[DemandRow]] = {}
+33 -14
View File
@@ -1,7 +1,7 @@
"""评估取数。
工参:本系统的工参快照(CellData_4G/5G),拆除前后按 pick_before / pick_after 选日期,库里没有的日期
用提交人的大数据平台凭证经 OpenCode 补取;本系统账号没有凭证时借号池里的账号。
工参:本系统的工参快照(CellData_4G/5G),每周一一份。拆除前用拆除日上一周的周一,拆除后用拆除日当周的周一;
库里还没有的周一用提交人的大数据平台凭证经 OpenCode 补取,本系统账号没有凭证时借号池里的账号。
指标按周(周一到周日)取。4G 小区的流量、质量、扇区和频段取即席查询「[管理视图]重要场景-小区周粒度」;
MR 覆盖、竞对和 5G 小区还没接,先用模拟数据,同一小区同一时间段每次结果相同。
环境变量 DECOM_EVAL_SOURCE=mock 时工参和指标都用模拟数据,便于本地演示。
@@ -11,23 +11,35 @@ from __future__ import annotations
import asyncio
import hashlib
import logging
import math
import os
from collections.abc import Callable, Iterator
from contextlib import contextmanager
from datetime import date, datetime, time, timedelta
from datetime import date, datetime, time
from typing import Protocol
from sqlalchemy import select
from app.collect.accounts import borrow_account, release_account
from app.collect.gongcan import AfterPick, GongcanError, GongcanStore, Target, fetch_snapshot, month_start, pick_after, pick_before
from app.collect.gongcan import (
AfterPick,
GongcanError,
GongcanStore,
Target,
after_monday,
before_monday,
fetch_snapshot,
pick_after,
pick_before,
)
from app.db import engine, session_scope
from app.models import NqiAccount
from app.nqi import adhoc
from app.nqi.client import NqiAuthError, NqiClient, NqiError
from app.nqi.opencode import OpenCode
logger = logging.getLogger("decom")
METRIC_KEYS = ("traffic_gb", "rrc_max", "high_load", "mr_weak_pct", "access_rate", "drop_rate", "util_peak")
MR_PROFILE_KEYS = ("mr_total", "mr_good_cnt", "mr_cover_pct", "unicom_cov", "telecom_cov", "weak_cell", "worse_unicom", "worse_telecom")
WEEK_TABLE = "appdbv3.a_overview_ispm_lte_cell_w"
@@ -44,9 +56,11 @@ class MetricError(Exception):
class GongcanSource(Protocol):
def before_day(self, city: str, target: Target, removal: date) -> date: ...
def before_day(self, city: str, target: Target, removal: date, today: date) -> date:
"""拆除前工参的日期。里面必须有目标,找不到时抛 GongcanMissing。"""
def after_pick(self, city: str, target: Target, removal: date, today: date) -> AfterPick | None: ...
def after_pick(self, city: str, target: Target, removal: date, today: date) -> AfterPick | None:
"""拆除后工参的日期,以及目标是否还在里面;还没有这份工参时返回 None。"""
def cells(self, city: str, day: date) -> list[dict]: ...
@@ -123,11 +137,16 @@ class StoreGongcan:
finally:
await client.aclose()
def before_day(self, city: str, target: Target, removal: date) -> date:
return asyncio.run(pick_before(self.store, city, target, removal))
def before_day(self, city: str, target: Target, removal: date, today: date) -> date:
return asyncio.run(pick_before(self.store, city, target, removal, today))
def after_pick(self, city: str, target: Target, removal: date, today: date) -> AfterPick | None:
return asyncio.run(pick_after(self.store, city, target, removal, today))
"""拆除后工参取不到不算失败,周边站改用拆除前工参。"""
try:
return asyncio.run(pick_after(self.store, city, target, removal, today))
except GongcanError as exc:
logger.info("%s 拆除后工参没取到,改用拆除前工参:%s", city, exc)
return None
def cells(self, city: str, day: date) -> list[dict]:
return self.store.cells(city, day)
@@ -143,23 +162,23 @@ def _between(low: float, high: float, *parts: object) -> float:
class MockGongcan:
"""演示用工参:待拆小区放在一处,周围散布模拟站点,拆除前取上个月 1 号、拆除后取昨天。"""
"""演示用工参:待拆小区放在一处,周围散布模拟站点。日期和实际规则一样取周一。"""
SITES = 24
def __init__(self):
self.targets: dict[str, str] = {}
def before_day(self, city: str, target: Target, removal: date) -> date:
def before_day(self, city: str, target: Target, removal: date, today: date) -> date:
for cgi in target.cgis:
self.targets.setdefault(cgi, target.site)
if target.site:
self.targets.setdefault(f"site:{target.site}", target.site)
return month_start(removal, -1)
return before_monday(removal, today)
def after_pick(self, city: str, target: Target, removal: date, today: date) -> AfterPick | None:
yesterday = today - timedelta(days=1)
return None if yesterday <= removal else AfterPick(yesterday, False)
day = after_monday(removal, today)
return None if day is None else AfterPick(day, True)
def cells(self, city: str, day: date) -> list[dict]:
seed = sorted(self.targets)[0] if self.targets else city