From b5a59622a18604c4dc548496751a2c46f4762b9e Mon Sep 17 00:00:00 2001 From: Nixevol Date: Wed, 11 Nov 2026 01:57:28 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=B7=A5=E5=8F=82=E6=8C=89=E5=9C=B0?= =?UTF-8?q?=E5=B8=82=E5=92=8C=E6=97=A5=E6=9C=9F=E5=85=A5=E5=BA=93=EF=BC=8C?= =?UTF-8?q?=E5=85=88=E6=9F=A5=E5=BA=93=E5=86=8D=E4=BB=8E=E5=A4=A7=E6=95=B0?= =?UTF-8?q?=E6=8D=AE=E5=B9=B3=E5=8F=B0=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 即席查询取工参属性,OpenCode 导出当天全市 CGI 和经纬度,按 CGI 合并后存成快照;即席查询失败或 CGI 对不上时改由 OpenCode 一并导出属性。拆除前后的工参日期按库优先、逐月回溯的规则选取,多个任务取同一天时只取一次。即席查询 getTableCount 出错不再被当成 0 行。 --- .../alembic/versions/0007_gongcan_snapshot.py | 56 +++ backend/app/collect/gongcan.py | 437 +++++++++++++++++ backend/app/collect/store.py | 2 + backend/app/models.py | 50 +- backend/app/nqi/adhoc.py | 88 +++- backend/app/nqi/opencode.py | 446 ++++++++++++++++++ backend/tests/test_gongcan.py | 329 +++++++++++++ backend/tests/test_opencode.py | 224 +++++++++ docs/gongcan-source.md | 138 ++++++ 9 files changed, 1765 insertions(+), 5 deletions(-) create mode 100644 backend/alembic/versions/0007_gongcan_snapshot.py create mode 100644 backend/app/collect/gongcan.py create mode 100644 backend/app/nqi/opencode.py create mode 100644 backend/tests/test_gongcan.py create mode 100644 backend/tests/test_opencode.py create mode 100644 docs/gongcan-source.md diff --git a/backend/alembic/versions/0007_gongcan_snapshot.py b/backend/alembic/versions/0007_gongcan_snapshot.py new file mode 100644 index 0000000..a846520 --- /dev/null +++ b/backend/alembic/versions/0007_gongcan_snapshot.py @@ -0,0 +1,56 @@ +"""按地市、日期保存全量 4G/5G 小区工参,评估任务先查这里,没有再去大数据平台取。""" + +from alembic import op +import sqlalchemy as sa + +revision = "0007_gongcan_snapshot" +down_revision = "0006_account_task_load" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + "gongcan_snapshot", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("city", sa.String(32), nullable=False), + sa.Column("snapshot_date", sa.Date(), nullable=False), + sa.Column("status", sa.String(16), nullable=False, server_default="loading"), + sa.Column("attr_source", sa.String(16), nullable=False, server_default=""), + sa.Column("lte_cells", sa.Integer(), nullable=False, server_default="0"), + sa.Column("nr_cells", sa.Integer(), nullable=False, server_default="0"), + sa.Column("located_cells", sa.Integer(), nullable=False, server_default="0"), + sa.Column("error", sa.Text(), nullable=False, server_default=""), + sa.Column("created_at", sa.DateTime(timezone=True), nullable=False), + sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False), + sa.UniqueConstraint("city", "snapshot_date", name="uq_gongcan_city_date"), + ) + op.create_table( + "gongcan_cell", + sa.Column("id", sa.BigInteger().with_variant(sa.Integer(), "sqlite"), primary_key=True), + sa.Column("snapshot_id", sa.Integer(), sa.ForeignKey("gongcan_snapshot.id", ondelete="CASCADE"), nullable=False), + sa.Column("tech", sa.String(4), nullable=False), + sa.Column("cgi", sa.String(64), nullable=False), + sa.Column("cell_name", sa.Text(), nullable=False, server_default=""), + sa.Column("site_name", sa.Text(), nullable=False, server_default=""), + sa.Column("latitude", sa.Float(), nullable=True), + sa.Column("longitude", sa.Float(), nullable=True), + sa.Column("network_type", sa.Text(), nullable=False, server_default=""), + sa.Column("node_id", sa.Text(), nullable=False, server_default=""), + sa.Column("node_name", sa.Text(), nullable=False, server_default=""), + sa.Column("area", sa.Text(), nullable=False, server_default=""), + sa.Column("town", sa.Text(), nullable=False, server_default=""), + sa.Column("state", sa.Text(), nullable=False, server_default=""), + sa.Column("cover_type", sa.Text(), nullable=False, server_default=""), + sa.Column("frequency_band", sa.Text(), nullable=False, server_default=""), + sa.Column("vendor", sa.Text(), nullable=False, server_default=""), + sa.Column("azimuth", sa.Text(), nullable=False, server_default=""), + sa.UniqueConstraint("snapshot_id", "cgi", "tech", name="uq_gongcan_cell"), + ) + op.create_index("ix_gongcan_cell_site", "gongcan_cell", ["snapshot_id", "site_name"]) + + +def downgrade() -> None: + op.drop_index("ix_gongcan_cell_site", table_name="gongcan_cell") + op.drop_table("gongcan_cell") + op.drop_table("gongcan_snapshot") diff --git a/backend/app/collect/gongcan.py b/backend/app/collect/gongcan.py new file mode 100644 index 0000000..cd3715b --- /dev/null +++ b/backend/app/collect/gongcan.py @@ -0,0 +1,437 @@ +"""评估用的 4G/5G 小区工参:按地市、日期整份保存,任务先查库,没有再去大数据平台取。 + +一份快照 = 即席查询当天的工参(经纬度是脱敏的)+ OpenCode 导出的当天 CGI 与经纬度,按 CGI 合并, +OpenCode 里没有坐标的小区经纬度留空。即席查询取不到,或者它给的 CGI 和 OpenCode 那份对不上时, +改由 OpenCode 把属性列一起导出。OpenCode 那份按 eff_from_date/eff_to_date 取当天有效的记录,是日期口径的基准。 +""" + +from __future__ import annotations + +import asyncio +import hashlib +import logging +import math +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from datetime import date, datetime, timedelta, timezone + +from sqlalchemy import delete, exists, insert, select, update +from sqlalchemy.engine import Engine +from sqlalchemy.exc import IntegrityError + +from app.models import GongcanCell, GongcanSnapshot, utcnow +from app.nqi import adhoc +from app.nqi.client import NqiClient, NqiError +from app.nqi.opencode import EFFECTIVE, ExportFile, OpenCode, snapshot_where, task_session + +logger = logging.getLogger("decom") + +TECHS = ("4G", "5G") +ADHOC_TABLES = {"4G": "appdbv3.v_a_common_cfg_lte_cellant_d", "5G": "appdbv3.a_common_cfg_nr_cellant_d"} +PLATFORM_TABLES = {"4G": "appdbv3.a_common_cfg_lte_cellant_d", "5G": "appdbv3.a_common_cfg_nr_cellant_d"} +KEYS = {"4G": ("cgi",), "5G": ("ncgi", "cgi")} +NAMED_FIELDS = { + "4G": {"cell_name": "cell_name", "site_name": "station_name", "node_id": "enodeb_id", "node_name": "enodeb_name"}, + "5G": {"cell_name": "nrcell_name", "site_name": "station_name", "node_id": "gnodeb_id", "node_name": "gnodeb_name"}, +} +SHARED_FIELDS = ("network_type", "area", "town", "state", "cover_type", "frequency_band", "vendor", "azimuth") +COORDS = ("longitude", "latitude") +MATCH_RATIO = 0.98 +FAILED_COOLDOWN = timedelta(minutes=10) +STALE_LOADING = timedelta(minutes=40) + + +class GongcanError(Exception): + pass + + +class GongcanMissing(GongcanError): + pass + + +@dataclass(frozen=True) +class Target: + """一个评估任务的对象:一个或几个 CGI,或者一个站点名。""" + + cgis: tuple[str, ...] = () + site: str = "" + + def __post_init__(self) -> None: + if bool(self.cgis) == bool(self.site): + raise ValueError("目标要么给 CGI,要么给站点名称") + + @property + def label(self) -> str: + return f"站点 {self.site}" if self.site else f"小区 {'、'.join(self.cgis)}" + + +def attribute_columns(tech: str) -> tuple[str, ...]: + return tuple(NAMED_FIELDS[tech].values()) + SHARED_FIELDS + + +def adhoc_fields(tech: str) -> tuple[str, ...]: + return KEYS[tech] + attribute_columns(tech) + + +def snapshot_task_name(city: str, day: date) -> str: + """OpenCode 目录名不带日期样式的数字,平台的脱敏会把它当日期改掉。""" + return "gc_" + hashlib.sha1(f"{city}|{day.isoformat()}".encode("utf-8")).hexdigest()[:12] + + +def platform_files(task: str, city: str, day: date, *, attributes: bool) -> list[ExportFile]: + """全市当天有效的工参。只要坐标时三四列;要属性时文字列把英文逗号换成中文逗号,避免 CSV 错列。""" + files = [] + for tech, name in (("4G", "lte"), ("5G", "nr")): + columns = KEYS[tech] + COORDS + EFFECTIVE + select_list = list(columns) + if attributes: + columns += attribute_columns(tech) + select_list += [f"replace({column}::text, ',', ',') as {column}" for column in attribute_columns(tech)] + sql = f"select {', '.join(select_list)} from {PLATFORM_TABLES[tech]} where {snapshot_where(city, day)}" + files.append(ExportFile(task, "attr" if attributes else "xy", f"{name}.csv", sql, day, columns)) + return files + + +def key_of(row: dict, tech: str) -> str: + for name in KEYS[tech]: + value = str(row.get(name) or "").strip() + if value: + return value + return "" + + +def valid_coordinate(lon: object, lat: object) -> tuple[float | None, float | None]: + try: + lon_value, lat_value = float(lon), float(lat) + except (TypeError, ValueError): + return None, None + if 70 <= lon_value <= 140 and 15 <= lat_value <= 55: + return lon_value, lat_value + return None, None + + +def coordinates(rows: list[dict], tech: str) -> dict[str, tuple[float, float]]: + """4G 表一行一个天线,同一 CGI 会有多行,取第一条有效坐标。""" + found: dict[str, tuple[float, float]] = {} + for row in rows: + key = key_of(row, tech) + if not key or key in found: + continue + lon, lat = valid_coordinate(row.get("longitude"), row.get("latitude")) + if lon is not None: + found[key] = (lat, lon) + return found + + +def build_cells(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> list[dict]: + coords = coordinates(coord_rows, tech) + mapping = {**NAMED_FIELDS[tech], **{name: name for name in SHARED_FIELDS}} + cells: dict[str, dict] = {} + for row in attr_rows: + key = key_of(row, tech) + if not key or key in cells: + continue + lat, lon = coords.get(key, (None, None)) + cell = {"tech": tech, "cgi": key, "latitude": lat, "longitude": lon} + for target, source in mapping.items(): + cell[target] = str(row.get(source) or "").strip() + cells[key] = cell + return list(cells.values()) + + +def key_overlap(attr_rows: list[dict], coord_rows: list[dict], tech: str) -> float: + left = {key_of(row, tech) for row in attr_rows} - {""} + right = {key_of(row, tech) for row in coord_rows} - {""} + if not left or not right: + return 0.0 + return len(left & right) / len(left | right) + + +async def fetch_snapshot(nqi: NqiClient, oc: OpenCode, city: str, day: date, *, use_adhoc: bool = True) -> tuple[list[dict], str]: + """从大数据平台取一份快照,返回小区列表和属性来源(adhoc / opencode)。""" + attrs: dict[str, list[dict]] | None = None + if use_adhoc: + try: + attrs = {tech: await adhoc.export_day(nqi, ADHOC_TABLES[tech], day, city, adhoc_fields(tech)) for tech in TECHS} + except NqiError as exc: + logger.info("即席查询取 %s %s 工参未成功,改由 OpenCode 导出属性: %s", city, day, exc) + attrs = None + task = snapshot_task_name(city, day) + async with task_session(oc, task) as session_id: + files = platform_files(task, city, day, attributes=attrs is None) + tables = await oc.export(session_id, files) + rows = {tech: tables[item.key].rows for tech, item in zip(TECHS, files)} + if attrs is not None: + ratios = {tech: key_overlap(attrs[tech], rows[tech], tech) for tech in TECHS} + if min(ratios.values()) < MATCH_RATIO: + logger.info("即席查询的 CGI 与 OpenCode 当天快照重合 %s,改用 OpenCode 的属性", ratios) + attrs = None + files = platform_files(task, city, day, attributes=True) + tables = await oc.export(session_id, files) + rows = {tech: tables[item.key].rows for tech, item in zip(TECHS, files)} + source = "adhoc" if attrs is not None else "opencode" + attrs = attrs if attrs is not None else rows + cells = [cell for tech in TECHS for cell in build_cells(attrs[tech], rows[tech], tech)] + if not any(cell["tech"] == "4G" for cell in cells) or not any(cell["tech"] == "5G" for cell in cells): + raise GongcanError(f"{city} {day} 的工参是空的") + return cells, source + + +_SNAPSHOT = GongcanSnapshot.__table__ +_CELL = GongcanCell.__table__ + + +def _aware(value: datetime) -> datetime: + return value if value.tzinfo else value.replace(tzinfo=timezone.utc) + + +def claim_snapshot(engine: Engine, city: str, day: date, now: datetime) -> int | None: + """抢到取数权返回快照 id;已就绪、别人正在取、或刚失败还在冷却时返回 None。""" + try: + with engine.begin() as connection: + result = connection.execute( + insert(_SNAPSHOT).values(city=city, snapshot_date=day, status="loading", error="", created_at=now, updated_at=now) + ) + return int(result.inserted_primary_key[0]) + except IntegrityError: + pass + with engine.begin() as connection: + row = connection.execute( + select(_SNAPSHOT.c.id, _SNAPSHOT.c.status, _SNAPSHOT.c.updated_at).where(_SNAPSHOT.c.city == city, _SNAPSHOT.c.snapshot_date == day) + ).first() + if row is None or row.status == "ready": + return None + wait = FAILED_COOLDOWN if row.status == "failed" else STALE_LOADING + if _aware(row.updated_at) > now - wait: + return None + taken = connection.execute( + update(_SNAPSHOT) + .where(_SNAPSHOT.c.id == row.id, _SNAPSHOT.c.status == row.status, _SNAPSHOT.c.updated_at <= now - wait) + .values(status="loading", error="", updated_at=now) + ) + return int(row.id) if taken.rowcount == 1 else None + + +def save_snapshot(engine: Engine, snapshot_id: int, cells: list[dict], source: str, now: datetime) -> None: + with engine.begin() as connection: + connection.execute(delete(_CELL).where(_CELL.c.snapshot_id == snapshot_id)) + for start in range(0, len(cells), 2000): + connection.execute(insert(_CELL), [{**cell, "snapshot_id": snapshot_id} for cell in cells[start:start + 2000]]) + connection.execute( + update(_SNAPSHOT) + .where(_SNAPSHOT.c.id == snapshot_id) + .values( + status="ready", + attr_source=source, + lte_cells=sum(1 for cell in cells if cell["tech"] == "4G"), + nr_cells=sum(1 for cell in cells if cell["tech"] == "5G"), + located_cells=sum(1 for cell in cells if cell["latitude"] is not None), + error="", + updated_at=now, + ) + ) + + +def fail_snapshot(engine: Engine, snapshot_id: int, error: str, now: datetime) -> None: + with engine.begin() as connection: + connection.execute(update(_SNAPSHOT).where(_SNAPSHOT.c.id == snapshot_id).values(status="failed", error=error[:500], updated_at=now)) + + +def _has_target(target: Target): + condition = _CELL.c.site_name == target.site if target.site else _CELL.c.cgi.in_(target.cgis) + return exists(select(_CELL.c.id).where(_CELL.c.snapshot_id == _SNAPSHOT.c.id, condition)) + + +def _ready(city: str, start: date, end: date): + return (_SNAPSHOT.c.city == city, _SNAPSHOT.c.status == "ready", _SNAPSHOT.c.snapshot_date >= start, _SNAPSHOT.c.snapshot_date < end) + + +class GongcanStore: + """快照的读写和按需取数。loader 负责从平台取一份快照,测试里可以换成假的。""" + + def __init__( + self, + engine: Engine, + loader: Callable[[str, date], Awaitable[tuple[list[dict], str]]], + *, + poll_seconds: float = 10.0, + wait_timeout: timedelta = timedelta(minutes=45), + clock: Callable[[], datetime] = utcnow, + ): + self.engine = engine + self.loader = loader + self.poll_seconds = poll_seconds + self.wait_timeout = wait_timeout + self.clock = clock + + def ready_dates(self, city: str, start: date, end: date) -> list[date]: + """start <= 日期 < end 的已就绪快照。""" + with self.engine.connect() as connection: + return sorted(connection.execute(select(_SNAPSHOT.c.snapshot_date).where(*_ready(city, start, end))).scalars()) + + def dates_with_target(self, city: str, target: Target, start: date, end: date) -> list[date]: + with self.engine.connect() as connection: + query = select(_SNAPSHOT.c.snapshot_date).where(*_ready(city, start, end), _has_target(target)) + return sorted(connection.execute(query).scalars()) + + def has_target(self, city: str, day: date, target: Target) -> bool: + return bool(self.dates_with_target(city, target, day, day + timedelta(days=1))) + + def cells(self, city: str, day: date) -> list[dict]: + columns = [column for column in _CELL.c if column.name not in ("id", "snapshot_id")] + with self.engine.connect() as connection: + query = select(*columns).join(_SNAPSHOT, _SNAPSHOT.c.id == _CELL.c.snapshot_id).where(*_ready(city, day, day + timedelta(days=1))) + return [dict(row._mapping) for row in connection.execute(query)] + + def _state(self, city: str, day: date): + with self.engine.connect() as connection: + return connection.execute( + select(_SNAPSHOT.c.status, _SNAPSHOT.c.error).where(_SNAPSHOT.c.city == city, _SNAPSHOT.c.snapshot_date == day) + ).first() + + async def ensure(self, city: str, day: date) -> None: + """库里没有这一天就去平台取。别的任务正在取同一天时等它,不重复取。""" + deadline = self.clock() + self.wait_timeout + while True: + state = self._state(city, day) + if state is not None and state.status == "ready": + return + snapshot_id = claim_snapshot(self.engine, city, day, self.clock()) + if snapshot_id is not None: + await self._load(snapshot_id, city, day) + return + state = self._state(city, day) + if state is not None and state.status == "failed": + raise GongcanError(f"{city} {day} 的工参刚取失败,稍后再试:{state.error}") + if self.clock() > deadline: + raise GongcanError(f"等待 {city} {day} 的工参超时") + await asyncio.sleep(self.poll_seconds) + + async def _load(self, snapshot_id: int, city: str, day: date) -> None: + try: + cells, source = await self.loader(city, day) + save_snapshot(self.engine, snapshot_id, cells, source, self.clock()) + except BaseException as exc: + fail_snapshot(self.engine, snapshot_id, f"{type(exc).__name__}: {exc}", self.clock()) + raise + logger.info("工参快照 %s %s 已入库:%s 个小区,属性来自 %s", city, day, len(cells), source) + + +def platform_loader(nqi: NqiClient, *, use_adhoc: bool = True) -> Callable[[str, date], Awaitable[tuple[list[dict], str]]]: + oc = OpenCode(nqi) + + async def load(city: str, day: date) -> tuple[list[dict], str]: + return await fetch_snapshot(nqi, oc, city, day, use_adhoc=use_adhoc) + + return load + + +def china_today() -> date: + return (datetime.now(timezone.utc) + timedelta(hours=8)).date() + + +def month_start(day: date, offset: int = 0) -> date: + index = day.year * 12 + day.month - 1 + offset + return date(index // 12, index % 12 + 1, 1) + + +@dataclass(frozen=True) +class AfterPick: + day: date + target_present: bool + + +async def pick_before(store: GongcanStore, city: str, target: Target, removal: date, months: int = 3) -> date: + """拆除前用的工参日期。 + + 库里拆除日前、近 months 个月(从 months 个月前的 1 号算起)有目标的快照,取最晚的一份; + 没有就从拆除日上个月 1 号起逐月往前,库里没有的那天才去平台取,取到有目标的为止。 + """ + earliest = month_start(removal, -months) + found = store.dates_with_target(city, target, earliest, removal) + if found: + return found[-1] + stored = set(store.ready_dates(city, earliest, removal)) + for back in range(1, months + 1): + day = month_start(removal, -back) + if day in stored: + continue + await store.ensure(city, day) + if store.has_target(city, day, target): + return day + raise GongcanMissing(f"拆除前 {months} 个月的工参里都没有{target.label}") + + +async def pick_after(store: GongcanStore, city: str, target: Target, removal: date, today: date) -> AfterPick | None: + """拆除后用的工参日期,越接近今天越好。 + + 库里拆除日之后、目标已经不在的快照取最晚的一份;都还在时,最晚那份是昨天就直接用, + 不是就去平台取昨天的。目标仍在只做标记,不算失败。拆除日还没过去时返回 None。 + """ + yesterday = today - timedelta(days=1) + if yesterday <= removal: + return None + start = removal + timedelta(days=1) + stored = store.ready_dates(city, start, today) + present = set(store.dates_with_target(city, target, start, today)) + absent = [day for day in stored if day not in present] + if absent: + return AfterPick(absent[-1], False) + if stored and stored[-1] == yesterday: + return AfterPick(yesterday, True) + await store.ensure(city, yesterday) + return AfterPick(yesterday, store.has_target(city, yesterday, target)) + + +def is_indoor(cell: dict) -> bool: + return "W-" in (cell.get("cell_name") or "") + + +def evaluable(cell: dict) -> bool: + """与模板工具入库规则一致:去室分(小区名含 W-)和 4G 的 NB-IoT。""" + return not is_indoor(cell) and not (cell.get("tech") == "4G" and (cell.get("network_type") or "").upper() == "NB-IOT") + + +def haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float: + p1, p2 = math.radians(lat1), math.radians(lat2) + a = math.sin((p2 - p1) / 2) ** 2 + math.cos(p1) * math.cos(p2) * math.sin(math.radians(lon2 - lon1) / 2) ** 2 + return 2 * 6371000.0 * math.asin(math.sqrt(a)) + + +def target_center(cells: list[dict]) -> tuple[float, float] | None: + """目标坐标取室外小区的平均;全是室分时用全部有坐标的小区。""" + located = [cell for cell in cells if cell.get("latitude") is not None] + chosen = [cell for cell in located if evaluable(cell)] or located + if not chosen: + return None + return sum(cell["latitude"] for cell in chosen) / len(chosen), sum(cell["longitude"] for cell in chosen) / len(chosen) + + +def nearest_sites( + cells: list[dict], + lat: float, + lon: float, + *, + exclude: set[str], + k: int = 3, + exclude_keywords: tuple[str, ...] = ("微小",), +) -> list[tuple[str, float]]: + """站点坐标取其可评估小区坐标的平均,按到目标的距离取最近 k 个,1 米内的视为同址不算。""" + sums: dict[str, list[float]] = {} + for cell in cells: + site = cell.get("site_name") or "" + if cell.get("latitude") is None or not site or site in exclude or not evaluable(cell): + continue + if any(word in (cell.get("cell_name") or "") for word in exclude_keywords): + continue + acc = sums.setdefault(site, [0.0, 0.0, 0.0]) + acc[0] += cell["latitude"] + acc[1] += cell["longitude"] + acc[2] += 1 + found = [] + for site, (lat_sum, lon_sum, count) in sums.items(): + dist = haversine(lat, lon, lat_sum / count, lon_sum / count) + if dist >= 1.0: + found.append((site, round(dist, 1))) + found.sort(key=lambda item: item[1]) + return found[:k] diff --git a/backend/app/collect/store.py b/backend/app/collect/store.py index 1038cae..3f183d2 100644 --- a/backend/app/collect/store.py +++ b/backend/app/collect/store.py @@ -32,6 +32,8 @@ APP_TABLES = { "celldata", "collection_source", "export_task", + "gongcan_snapshot", + "gongcan_cell", } _UNSAFE = re.compile(r"[^0-9A-Za-z_]+") _CHUNK = 300 diff --git a/backend/app/models.py b/backend/app/models.py index 5451a20..d31f726 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -1,8 +1,8 @@ from __future__ import annotations -from datetime import datetime, timezone +from datetime import date, datetime, timezone -from sqlalchemy import JSON, Boolean, DateTime, Integer, String, Text, UniqueConstraint +from sqlalchemy import JSON, BigInteger, Boolean, Date, DateTime, Float, ForeignKey, Index, Integer, String, Text, UniqueConstraint from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column @@ -82,6 +82,52 @@ class CollectionSource(Base): last_error: Mapped[str] = mapped_column(Text, default="") +class GongcanSnapshot(Base): + """某地市某一天的全量 4G/5G 小区工参。status 兼作取数锁:loading 时别的任务等它。""" + + __tablename__ = "gongcan_snapshot" + __table_args__ = (UniqueConstraint("city", "snapshot_date", name="uq_gongcan_city_date"),) + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + city: Mapped[str] = mapped_column(String(32)) + snapshot_date: Mapped[date] = mapped_column(Date) + status: Mapped[str] = mapped_column(String(16), default="loading") + attr_source: Mapped[str] = mapped_column(String(16), default="") + lte_cells: Mapped[int] = mapped_column(Integer, default=0) + nr_cells: Mapped[int] = mapped_column(Integer, default=0) + located_cells: Mapped[int] = mapped_column(Integer, default=0) + error: Mapped[str] = mapped_column(Text, default="") + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + +class GongcanCell(Base): + __tablename__ = "gongcan_cell" + __table_args__ = ( + UniqueConstraint("snapshot_id", "cgi", "tech", name="uq_gongcan_cell"), + Index("ix_gongcan_cell_site", "snapshot_id", "site_name"), + ) + + id: Mapped[int] = mapped_column(BigInteger().with_variant(Integer, "sqlite"), primary_key=True) + snapshot_id: Mapped[int] = mapped_column(ForeignKey("gongcan_snapshot.id", ondelete="CASCADE")) + tech: Mapped[str] = mapped_column(String(4)) + cgi: Mapped[str] = mapped_column(String(64)) + cell_name: Mapped[str] = mapped_column(Text, default="") + site_name: Mapped[str] = mapped_column(Text, default="") + latitude: Mapped[float | None] = mapped_column(Float, nullable=True) + longitude: Mapped[float | None] = mapped_column(Float, nullable=True) + network_type: Mapped[str] = mapped_column(Text, default="") + node_id: Mapped[str] = mapped_column(Text, default="") + node_name: Mapped[str] = mapped_column(Text, default="") + area: Mapped[str] = mapped_column(Text, default="") + town: Mapped[str] = mapped_column(Text, default="") + state: Mapped[str] = mapped_column(Text, default="") + cover_type: Mapped[str] = mapped_column(Text, default="") + frequency_band: Mapped[str] = mapped_column(Text, default="") + vendor: Mapped[str] = mapped_column(Text, default="") + azimuth: Mapped[str] = mapped_column(Text, default="") + + class ExportTask(Base): __tablename__ = "export_task" diff --git a/backend/app/nqi/adhoc.py b/backend/app/nqi/adhoc.py index d744557..797249e 100644 --- a/backend/app/nqi/adhoc.py +++ b/backend/app/nqi/adhoc.py @@ -2,7 +2,9 @@ from __future__ import annotations +import asyncio import json +import re from datetime import date, datetime, timedelta from urllib.parse import urlencode @@ -156,9 +158,7 @@ async def export_table( "result": json.dumps({"result": selected}, ensure_ascii=False), "where": json.dumps(where, ensure_ascii=False), } - counted = await _post_json(client, f"{PAGE}/getTableCount", common) - total = int(counted.get("count") or 0) if isinstance(counted, dict) else 0 - index_count = str(counted.get("indexcount") or "0") if isinstance(counted, dict) else "0" + total, index_count = await _count(client, common) rows: list[dict] = [] start_at = 0 pages = 0 @@ -192,6 +192,88 @@ async def export_table( return title, columns, rows +async def export_day( + client: NqiClient, + tablename: str, + day: date, + city: str, + fields: tuple[str, ...], + *, + page_size: int = PAGE_SIZE, + pause_seconds: float = 0.3, +) -> list[dict]: + """取一张表某一天、某个地市的指定几列。 + + 维度有多个可选值时(如“小区,网格,地市,分公司”“天粒度”),按页面默认取第一个并去掉“粒度”。 + 翻页按实际返回的行数推进,平台把每页压到更少时也不会漏行;取不全就报错。 + """ + await ensure_session(client) + columns = await _columns(client, tablename) + selected = [column for column in columns if column.get("columnname") in fields] + missing = set(fields) - {str(column.get("columnname")) for column in selected} + if missing: + raise NqiError(f"{tablename} 缺少字段:{'、'.join(sorted(missing))}") + head = columns[0] + common = { + "geographicdimension": _first_choice(head.get("geographicdimension")), + "timedimension": _first_choice(head.get("timedimension")).removesuffix("粒度"), + "enodebField": head.get("enodeb_field") or "", + "cgiField": head.get("cgi_field") or "", + "timeField": head.get("time_field") or "starttime", + "cellField": head.get("cell_field") or "", + "cityField": head.get("city_field") or "city", + "result": json.dumps({"result": [_field(column) for column in selected]}, ensure_ascii=False), + "where": json.dumps(_where(head, _start(day), _end(day), city), ensure_ascii=False), + } + total, index_count = await _count(client, common) + rows: list[dict] = [] + pages = 0 + while len(rows) < total: + pages += 1 + if pages > MAX_PAGES: + raise NqiError("数据行数超出单次导出上限") + page = await _post_json( + client, + f"{PAGE}/getTable", + { + **common, + **_column_form(selected), + "draw": pages, + "start": len(rows), + "length": page_size, + "indexcount": index_count, + "total": total, + "order[0][column]": 0, + "order[0][dir]": "desc", + "search[value]": "", + "search[regex]": "false", + }, + ) + data = page.get("data") if isinstance(page, dict) else None + batch = [item for item in data if isinstance(item, dict)] if isinstance(data, list) else [] + if not batch: + break + rows.extend(batch) + if pause_seconds: + await asyncio.sleep(pause_seconds) + if len(rows) < total: + raise NqiError(f"{tablename} 只取到 {len(rows)} 行,应有 {total} 行") + return rows + + +def _first_choice(value: object) -> str: + return re.split(r"[,,.、]", str(value or ""))[0].strip() + + +async def _count(client: NqiClient, common: dict) -> tuple[int, str]: + """平台出错时返回 {"stat":"0"},没有 count。不能当成 0 行。""" + counted = await _post_json(client, f"{PAGE}/getTableCount", common) + if not isinstance(counted, dict) or "count" not in counted: + message = counted.get("message") if isinstance(counted, dict) else "" + raise NqiError(f"即席查询没有返回行数{f':{message}' if message and message != 'null' else ''}") + return int(counted.get("count") or 0), str(counted.get("indexcount") or "0") + + def _field(column: dict) -> dict: return { "feildtype": column.get("fieldtype") or "", diff --git a/backend/app/nqi/opencode.py b/backend/app/nqi/opencode.py new file mode 100644 index 0000000..3e963b7 --- /dev/null +++ b/backend/app/nqi/opencode.py @@ -0,0 +1,446 @@ +"""大数据平台 OpenCode 取数。 + +平台 AI 只能用 adhoc_query 技能把 SQL 结果导出成 CSV。程序给它写死的导出命令, +再按导出脚本的输出、实际执行的 SQL 和文件内容核对结果,AI 回复的文字只记录不采信。 +一个任务一个会话、一个 /workspace/tasks/<任务> 目录,取完先让 AI 删目录,再删会话。 +""" + +from __future__ import annotations + +import asyncio +import csv +import hashlib +import io +import json +import logging +import posixpath +import random +import re +import shlex +import string +import time +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from dataclasses import dataclass, field +from datetime import date + +import httpx + +from app.nqi.client import NqiAuthError, NqiClient, NqiError +from app.nqi.constants import ORIGIN + +logger = logging.getLogger("decom") + +OPENCODE = f"{ORIGIN}/pro-opencode" +PROVISION_PID = "LXWXYWGZT" +WORKSPACE = "/workspace" +TASKS_DIR = "tasks" +MODEL_ID = "DeepSeek-V4-Flash-0731-w8a8" +EXPORT_SCRIPT = "script/download-file-all-async.py" +SAVED = re.compile(r"文件已保存至[::]\s*(\S+)") +EMPTY_RESULT = "服务端响应体为空" +EFFECTIVE = ("eff_from_date", "eff_to_date") +_NAME = re.compile(r"^[0-9A-Za-z_]{1,80}$") +_FILENAME = re.compile(r"^[0-9A-Za-z_]{1,60}\.csv$") +_SHELL_UNSAFE = ('"', "`", "$", "\\", "\n", "\r") +_BASE62 = string.digits + string.ascii_letters + + +class OpenCodeError(NqiError): + pass + + +def task_dir_name(key: str) -> str: + """目录名只留字母、数字和下划线。CGI 的横线也换掉,带中文的另加摘要避免重名。""" + text = (key or "").strip() + if not text: + raise ValueError("任务名称为空") + name = re.sub(r"_+", "_", re.sub(r"[^0-9A-Za-z]+", "_", text)).strip("_") + if not name or re.search(r"[^\x00-\x7f]", text): + digest = hashlib.sha1(text.encode("utf-8")).hexdigest()[:10] + name = f"{name[:60]}_{digest}".strip("_") + return name[:80] + + +def sql_text(value: str) -> str: + text = str(value) + if any(char in text for char in _SHELL_UNSAFE): + raise ValueError("取值里有不能放进导出命令的字符") + return "'" + text.replace("'", "''") + "'" + + +def day_sql(day: date) -> str: + """平台在 AI 前面会把 YYYY-MM-DD 换成占位符,还原时会串号,所以日期不写成这种字面量。""" + return f"make_date({day.year}, {day.month}, {day.day})" + + +def snapshot_where(city: str, day: date) -> str: + expr = day_sql(day) + return f"city = {sql_text(city)} and eff_from_date <= {expr} and eff_to_date > {expr}" + + +@dataclass(frozen=True) +class ExportFile: + task: str + phase: str + filename: str + sql: str + day: date + required: tuple[str, ...] + key: str = "" + + def __post_init__(self) -> None: + if not _NAME.match(self.task) or not _NAME.match(self.phase): + raise ValueError("任务或阶段名称不合法") + if not _FILENAME.match(self.filename): + raise ValueError("文件名不合法") + if any(char in self.sql for char in _SHELL_UNSAFE): + raise ValueError("SQL 里有不能放进导出命令的字符") + if not self.required: + raise ValueError("没有指定必需的列") + if not self.key: + object.__setattr__(self, "key", f"{self.phase}/{self.filename.rsplit('.', 1)[0]}") + + @property + def save_dir(self) -> str: + return f"{WORKSPACE}/{TASKS_DIR}/{self.task}/{self.phase}" + + @property + def path(self) -> str: + return f"{self.save_dir}/{self.filename}" + + def command(self) -> str: + return f'python {EXPORT_SCRIPT} --sql "{self.sql}" --save-dir "{self.save_dir}" --filename "{self.filename}"' + + def retry(self, attempt: int) -> "ExportFile": + stem = re.sub(r"_r\d+$", "", self.filename.rsplit(".", 1)[0]) + return ExportFile(self.task, self.phase, f"{stem}_r{attempt}.csv", self.sql, self.day, self.required, self.key) + + +def export_prompt(files: list[ExportFile]) -> str: + lines = [ + "请加载并严格遵循 adhoc_query 技能完成数据导出。这是程序发起的自动任务,没有人会回答问题:", + f"不要询问、不要确认、不要预览数据,直接在 adhoc_query 技能目录下按顺序执行下面 {len(files)} 条命令,每条单独执行。", + "SQL 已经过校验,一个字符都不能改,也不要按技能规范重写。", + "", + ] + lines += _numbered_commands(files) + lines += [ + "", + "要求:", + "1. 导出脚本会自己创建保存目录;不得使用其他目录,不得改文件名。", + "2. 只执行这些导出命令,不要额外查询或统计。某条失败时继续执行后面的命令。", + "3. 全部执行完后,每条命令输出一行结果,成功写 DONE <序号> <保存的绝对路径>,失败写 FAIL <序号> <错误原因>。", + ] + return "\n".join(lines) + + +def redo_prompt(files: list[ExportFile]) -> str: + lines = ["刚才有命令执行时 SQL 被改动了,导出的数据不能用。", "请原样执行下面的命令,SQL、目录、文件名都不能做任何修改:", ""] + lines += _numbered_commands(files) + lines += ["", "全部执行完后,每条命令输出一行结果,成功写 DONE <序号> <保存的绝对路径>,失败写 FAIL <序号> <错误原因>。"] + return "\n".join(lines) + + +def cleanup_prompt(task: str) -> str: + """直接给出删除命令会被平台的安全规则拒绝,用自然语言说明要删的目录。""" + folder = f"{WORKSPACE}/{TASKS_DIR}/{task}" + return ( + f"现在清理掉这个任务下载的数据:删除 {folder} 目录及其中的全部文件。" + f"只删除这一个目录,不要动 {WORKSPACE} 下的其他内容。" + f"删除后确认该目录已不存在,最后单独输出一行:CLEANED {task}" + ) + + +def _numbered_commands(files: list[ExportFile]) -> list[str]: + lines = [] + for index, item in enumerate(files, 1): + lines += [f"[{index}]", "```bash", item.command(), "```"] + return lines + + +@dataclass +class FileEvidence: + saved: bool = False + empty: bool = False + sql_same: bool | None = None + commands: int = 0 + + +def reply_parts(messages: list[dict], message_id: str): + for message in messages: + info = message.get("info") or {} + if info.get("role") == "assistant" and info.get("parentID") == message_id: + yield from message.get("parts") or [] + + +def judge_export(messages: list[dict], message_id: str, files: list[ExportFile]) -> dict[str, FileEvidence]: + """只认 bash 工具里实际执行的命令和导出脚本的输出。""" + by_path = {item.path: item for item in files} + evidence = {item.key: FileEvidence() for item in files} + for part in reply_parts(messages, message_id): + if part.get("type") != "tool" or part.get("tool") != "bash": + continue + state = part.get("state") or {} + command = str((state.get("input") or {}).get("command") or "") + output = str(state.get("output") or (state.get("metadata") or {}).get("output") or "") + segments = [s for s in re.split(r"\s*(?:&&|;|\n)\s*", command) if EXPORT_SCRIPT.rsplit("/", 1)[-1] in s] + for segment in segments: + options = _options(segment) + for item in files: + if posixpath.normpath(options.get("--save-dir", "")) != item.save_dir or options.get("--filename") != item.filename: + continue + found = evidence[item.key] + found.commands += 1 + found.sql_same = options.get("--sql") == item.sql + if len(segments) == 1 and EMPTY_RESULT in output and not SAVED.search(output): + found.empty = True + for saved in SAVED.findall(output): + item = by_path.get(posixpath.normpath(saved)) + if item: + evidence[item.key].saved = True + return evidence + + +def _options(command: str) -> dict[str, str]: + try: + tokens = shlex.split(command) + except ValueError: + return {} + found = {} + for index, token in enumerate(tokens[:-1]): + if token in ("--sql", "--save-dir", "--filename"): + found[token] = tokens[index + 1] + return found + + +@dataclass +class CsvTable: + header: list[str] = field(default_factory=list) + rows: list[dict[str, str]] = field(default_factory=list) + bad_rows: int = 0 + outside_day: int = 0 + missing: list[str] = field(default_factory=list) + empty: bool = False + + @property + def ok(self) -> bool: + return self.empty or (not self.missing and not self.outside_day) + + +def parse_export_csv(content: str, required: tuple[str, ...], day: date) -> CsvTable: + """列顺序和 SQL 里写的不一样,一律按表头名取值。列数不对的行是逗号错列,直接丢弃。 + + 带有效期两列时,逐行核对 day 落在 [eff_from_date, eff_to_date) 里,防止 SQL 里的日期被换掉。 + """ + rows = list(csv.reader(io.StringIO(content.lstrip("\ufeff")))) + if not rows: + return CsvTable(missing=list(required)) + header = [name.strip().lower() for name in rows[0]] + good = [dict(zip(header, row)) for row in rows[1:] if len(row) == len(header)] + outside = 0 + if all(name in header for name in EFFECTIVE): + target = day.isoformat() + outside = sum(1 for row in good if not (row["eff_from_date"][:10] <= target < row["eff_to_date"][:10])) + return CsvTable( + header=header, + rows=good, + bad_rows=len(rows) - 1 - len(good), + outside_day=outside, + missing=[name for name in required if name not in header], + ) + + +_last_ms = 0 +_counter = 0 + + +def ascending_id(prefix: str) -> str: + """与平台前端相同的编号:毫秒时间戳乘 4096 加序号取 48 位,再接 14 位随机字符。""" + global _last_ms, _counter + now_ms = int(time.time() * 1000) + if now_ms != _last_ms: + _last_ms, _counter = now_ms, 0 + _counter += 1 + value = (now_ms * 0x1000 + _counter) & ((1 << 48) - 1) + return f"{prefix}_{value.to_bytes(6, 'big').hex()}{''.join(random.choice(_BASE62) for _ in range(14))}" + + +class OpenCode: + def __init__(self, nqi: NqiClient, *, model: str = MODEL_ID, poll_seconds: float = 3.0): + self.nqi = nqi + self.model = model + self.poll_seconds = poll_seconds + self.ticket = nqi.ticket() + self.base = "" + self.headers = {"Accept": "*/*", "Origin": ORIGIN, "x-opencode-directory": "%2Fworkspace"} + + async def provision(self) -> str: + """provision 会下发 opencode_route,会话页会下发 oc_castgc,之后接口才认。""" + if not self.ticket: + raise NqiAuthError("登录已失效,请重新登录") + page = {"Accept": "text/html,application/xhtml+xml,*/*;q=0.8", "Referer": f"{ORIGIN}/pro-portal/struts/portal/index.html"} + response = await self.nqi._request( + "GET", + f"{OPENCODE}/api/provision", + params={"random": str(random.random()), "__PID": PROVISION_PID, "token": self.ticket}, + headers=page, + follow_redirects=False, + ) + location = response.headers.get("location", "") + if "/cas/login" in location: + raise NqiAuthError("登录已失效,请重新登录") + found = re.match(r"^/pro-opencode/([^/]+)/", location) + if response.status_code not in (301, 302, 303, 307, 308) or not found: + raise OpenCodeError("没有打开大数据平台的 AI 工作区") + self.base = f"{OPENCODE}/{found.group(1)}" + self.headers["Referer"] = f"{self.base}/L3dvcmtzcGFjZQ/session" + response = await self.nqi._request("GET", f"{ORIGIN}{location}", headers=page, follow_redirects=False) + if response.status_code != 200: + raise OpenCodeError("没有打开大数据平台的 AI 工作区") + return found.group(1) + + async def _call(self, method: str, path: str, *, params: dict | None = None, body: dict | None = None, tickets: bool = True) -> httpx.Response: + if not self.base: + raise OpenCodeError("还没有打开 AI 工作区") + query = dict(params or {}) + if tickets: + query["tickets"] = self.ticket + headers = dict(self.headers) + kwargs: dict = {"params": query, "headers": headers, "follow_redirects": False, "timeout": httpx.Timeout(60.0, connect=15.0)} + if body is not None: + headers["Content-Type"] = "application/json" + kwargs["content"] = json.dumps(body, ensure_ascii=False).encode("utf-8") + response = await self.nqi._request(method, f"{self.base}/{path}", **kwargs) + if response.status_code in (301, 302, 303, 307, 308) and "/cas/login" in response.headers.get("location", ""): + raise NqiAuthError("登录已失效,请重新登录") + return response + + async def _json(self, method: str, path: str, **kwargs): + response = await self._call(method, path, **kwargs) + if response.status_code >= 400: + raise OpenCodeError(f"AI 工作区接口返回 {response.status_code}") + if not response.content: + return None + try: + return response.json() + except json.JSONDecodeError as exc: + raise OpenCodeError("AI 工作区返回的内容无法识别") from exc + + async def create_session(self) -> str: + data = await self._json( + "POST", + "session", + params={"directory": WORKSPACE}, + body={"agent": "build", "model": {"id": self.model, "providerID": self.model}}, + ) + if not isinstance(data, dict) or not data.get("id"): + raise OpenCodeError("没有建立 AI 会话") + return str(data["id"]) + + async def prompt(self, session_id: str, text: str) -> str: + message_id = ascending_id("msg") + body = { + "messageID": message_id, + "agent": "build", + "model": {"modelID": self.model, "providerID": self.model}, + "parts": [{"id": ascending_id("prt"), "type": "text", "text": text}], + } + response = await self._call("POST", f"session/{session_id}/prompt_async", body=body) + if response.status_code >= 400: + raise OpenCodeError(f"发送指令失败 {response.status_code}") + return message_id + + async def wait_reply(self, session_id: str, message_id: str, timeout: float = 1200) -> list[dict]: + """会话回到空闲,且这条指令的最后一步正常结束或出错,才算回复完成。""" + started = time.monotonic() + while True: + status = await self._json("GET", "session/status") or {} + busy = (status.get(session_id) or {}).get("type", "idle") != "idle" + for kind in ("permission", "question"): + waiting = [item for item in await self._json("GET", kind, params={"directory": WORKSPACE}) or [] if item.get("sessionID") == session_id] + if waiting: + raise OpenCodeError("平台 AI 在等人工确认,自动任务无法继续") + messages = await self._json("GET", f"session/{session_id}/message") or [] + steps = [m.get("info") or {} for m in messages if (m.get("info") or {}).get("role") == "assistant" and (m.get("info") or {}).get("parentID") == message_id] + last = steps[-1] if steps else {} + finished = bool(last) and (last.get("time") or {}).get("completed") and last.get("finish") not in (None, "tool-calls", "unknown") + if not busy and (finished or last.get("error")): + if last.get("error"): + logger.info("OpenCode 回复出错: %s", json.dumps(last["error"], ensure_ascii=False)[:300]) + return messages + if time.monotonic() - started > timeout: + raise OpenCodeError("平台 AI 回复超时") + await asyncio.sleep(self.poll_seconds) + + async def list_dir(self, path: str) -> list[dict]: + return await self._json("GET", "file", params={"path": path, "directory": WORKSPACE}) or [] + + async def read_text(self, path: str) -> str: + data = await self._json("GET", "file/content", params={"path": path, "directory": WORKSPACE}, tickets=False) + if not isinstance(data, dict) or data.get("type") != "text": + raise OpenCodeError("导出文件不是文本") + return str(data.get("content") or "") + + async def delete_session(self, session_id: str) -> bool: + response = await self._call("DELETE", f"session/{session_id}") + return response.status_code < 400 + + async def export(self, session_id: str, files: list[ExportFile], retries: int = 2) -> dict[str, CsvTable]: + """SQL 被改、没有落盘或文件不合格的,换新文件名重做,最多 retries 次。""" + results: dict[str, CsvTable] = {} + todo = list(files) + for attempt in range(retries + 1): + message_id = await self.prompt(session_id, export_prompt(todo) if attempt == 0 else redo_prompt(todo)) + messages = await self.wait_reply(session_id, message_id) + evidence = judge_export(messages, message_id, todo) + failed = [] + for item in todo: + found = evidence[item.key] + if found.sql_same is not True: + logger.info("OpenCode 导出 %s 没有按原 SQL 执行", item.key) + failed.append(item) + elif found.empty: + results[item.key] = CsvTable(empty=True) + elif not found.saved: + logger.info("OpenCode 导出 %s 没有保存文件", item.key) + failed.append(item) + else: + table = parse_export_csv(await self.read_text(posixpath.relpath(item.path, WORKSPACE)), item.required, item.day) + if table.ok: + results[item.key] = table + else: + logger.info("OpenCode 导出 %s 内容不合格: 缺列 %s,日期不符 %s 行", item.key, table.missing, table.outside_day) + failed.append(item) + if not failed: + return results + todo = [item.retry(attempt + 1) for item in failed] + raise OpenCodeError("导出失败:" + "、".join(item.key for item in todo)) + + async def cleanup(self, session_id: str, task: str) -> bool: + if not _NAME.match(task): + raise ValueError("任务名称不合法") + message_id = await self.prompt(session_id, cleanup_prompt(task)) + await self.wait_reply(session_id, message_id, timeout=300) + names = {entry.get("name") for entry in await self.list_dir(TASKS_DIR)} + return task not in names + + +@asynccontextmanager +async def task_session(oc: OpenCode, task: str) -> AsyncIterator[str]: + """建会话给一个任务用,结束时不论成败都清目录、删会话。清理失败只记日志,不盖掉原来的错误。""" + if not oc.base: + await oc.provision() + session_id = await oc.create_session() + try: + yield session_id + finally: + try: + if not await oc.cleanup(session_id, task): + logger.info("OpenCode 任务目录 %s 没有删掉", task) + except NqiError as exc: + logger.info("OpenCode 任务 %s 清理未完成: %s", task, exc) + try: + await oc.delete_session(session_id) + except NqiError as exc: + logger.info("OpenCode 会话 %s 删除未完成: %s", session_id, exc) diff --git a/backend/tests/test_gongcan.py b/backend/tests/test_gongcan.py new file mode 100644 index 0000000..b4dbbdf --- /dev/null +++ b/backend/tests/test_gongcan.py @@ -0,0 +1,329 @@ +import asyncio +import re +from datetime import date, datetime, timedelta, timezone + +import pytest +from sqlalchemy import create_engine + +from app.collect import gongcan +from app.collect.gongcan import ( + AfterPick, + GongcanError, + GongcanMissing, + GongcanStore, + Target, + build_cells, + claim_snapshot, + fetch_snapshot, + key_overlap, + month_start, + nearest_sites, + pick_after, + pick_before, + platform_files, + save_snapshot, + snapshot_task_name, + target_center, +) +from app.models import Base, GongcanCell, GongcanSnapshot +from app.nqi.client import NqiError +from app.nqi.opencode import CsvTable, OpenCode + +CITY = "江门" +SITE = Target(site="T") + + +def cell(cgi, site, tech="4G", lat=22.0, lon=113.0, name="A", network_type="LTE"): + return {"tech": tech, "cgi": cgi, "cell_name": name, "site_name": site, "latitude": lat, "longitude": lon, "network_type": network_type} + + +def with_target(*others): + return [cell("t1", "T"), cell("n1", "N", tech="5G")] + [cell(f"x{i}", name) for i, name in enumerate(others)] + + +def without_target(): + return [cell("n1", "N", tech="5G"), cell("o1", "O")] + + +class Clock: + def __init__(self): + self.now = datetime(2026, 11, 11, 2, 0, tzinfo=timezone.utc) + + def __call__(self): + return self.now + + +class Platform: + def __init__(self, days, delay=0.0): + self.days = days + self.delay = delay + self.fetched = [] + + async def __call__(self, city, day): + self.fetched.append(day) + if self.delay: + await asyncio.sleep(self.delay) + if day not in self.days: + raise GongcanError("平台没有这一天") + return self.days[day], "opencode" + + +def make_store(platform, stored=None, clock=None): + db = create_engine("sqlite://") + Base.metadata.create_all(db, tables=[GongcanSnapshot.__table__, GongcanCell.__table__]) + clock = clock or Clock() + for day, cells in (stored or {}).items(): + snapshot_id = claim_snapshot(db, CITY, day, clock()) + save_snapshot(db, snapshot_id, cells, "adhoc", clock()) + return GongcanStore(db, platform, poll_seconds=0.01, clock=clock) + + +def test_month_start_crosses_year(): + assert month_start(date(2026, 1, 10), -1) == date(2025, 12, 1) + assert month_start(date(2026, 1, 10), -3) == date(2025, 10, 1) + assert month_start(date(2026, 11, 30)) == date(2026, 11, 1) + + +def test_platform_files_use_make_date_and_keep_commas_out_of_text_columns(): + task = snapshot_task_name(CITY, date(2026, 11, 1)) + assert re.fullmatch(r"gc_[0-9a-f]{12}", task) and task != snapshot_task_name(CITY, date(2026, 10, 1)) + lte, nr = platform_files(task, CITY, date(2026, 11, 1), attributes=False) + assert lte.sql.startswith("select cgi, longitude, latitude, eff_from_date, eff_to_date from appdbv3.a_common_cfg_lte_cellant_d where city = '江门'") + assert nr.sql.startswith("select ncgi, cgi, longitude, latitude,") + assert "make_date(2026, 11, 1)" in lte.sql and not re.search(r"\d{4}-\d{2}-\d{2}", lte.sql + nr.sql) + assert (lte.phase, lte.key, nr.key) == ("xy", "xy/lte", "xy/nr") + lte_attr, nr_attr = platform_files(task, CITY, date(2026, 11, 1), attributes=True) + assert "replace(station_name::text, ',', ',') as station_name" in lte_attr.sql + assert "replace(gnodeb_name::text, ',', ',') as gnodeb_name" in nr_attr.sql + assert {"station_name", "enodeb_id", "azimuth"} <= set(lte_attr.required) and lte_attr.phase == "attr" + + +def test_build_cells_merges_coordinates_by_cgi(): + attrs = [ + {"cgi": "c1", "cell_name": "A", "station_name": "S1", "enodeb_id": "1", "network_type": "LTE"}, + {"cgi": "c1", "cell_name": "A-dup", "station_name": "S1"}, + {"cgi": "c2", "cell_name": "B", "station_name": "S2"}, + {"cgi": "", "cell_name": "no key"}, + ] + coords = [ + {"cgi": "c1", "longitude": "", "latitude": ""}, + {"cgi": "c1", "longitude": "113.1", "latitude": "22.5"}, + {"cgi": "c2", "longitude": "0", "latitude": "0"}, + ] + cells = build_cells(attrs, coords, "4G") + assert [(item["cgi"], item["cell_name"], item["site_name"], item["latitude"], item["longitude"]) for item in cells] == [ + ("c1", "A", "S1", 22.5, 113.1), + ("c2", "B", "S2", None, None), + ] + assert cells[0]["node_id"] == "1" and cells[0]["tech"] == "4G" and cells[1]["network_type"] == "" + nr = build_cells([{"ncgi": "", "cgi": "n1", "nrcell_name": "N", "gnodeb_id": "9"}], [{"ncgi": "n1", "longitude": "113", "latitude": "22"}], "5G") + assert nr == [{**nr[0], "cgi": "n1", "cell_name": "N", "node_id": "9", "latitude": 22.0, "longitude": 113.0}] + + +def test_key_overlap(): + assert key_overlap([{"cgi": "a"}, {"cgi": "b"}, {"cgi": "c"}], [{"cgi": "a"}, {"cgi": "b"}, {"cgi": "d"}], "4G") == 0.5 + assert key_overlap([], [{"cgi": "a"}], "4G") == 0.0 + + +class SnapshotOpenCode(OpenCode): + def __init__(self, rows): + self.base = "provisioned" + self.rows = rows + self.phases = [] + self.cleaned = [] + + async def create_session(self): + return "s1" + + async def export(self, session_id, files, retries=2): + self.phases.append(files[0].phase) + return {item.key: CsvTable(header=list(item.required), rows=self.rows["4G" if item.filename.startswith("lte") else "5G"]) for item in files} + + async def cleanup(self, session_id, task): + self.cleaned.append(task) + return True + + async def delete_session(self, session_id): + return True + + +PLATFORM_ROWS = { + "4G": [{"cgi": "c1", "station_name": "OC站", "longitude": "113", "latitude": "22"}], + "5G": [{"ncgi": "n1", "cgi": "n1", "station_name": "OC站", "longitude": "113", "latitude": "22"}], +} + + +def adhoc_returns(monkeypatch, result): + async def export_day(client, tablename, day, city, fields, **kwargs): + if isinstance(result, Exception): + raise result + return result["4G" if "lte" in tablename else "5G"] + + monkeypatch.setattr(gongcan.adhoc, "export_day", export_day) + + +def test_snapshot_takes_attributes_from_adhoc_and_coordinates_from_opencode(monkeypatch): + adhoc_returns(monkeypatch, {"4G": [{"cgi": "c1", "station_name": "即席站"}], "5G": [{"ncgi": "n1", "station_name": "即席站"}]}) + oc = SnapshotOpenCode(PLATFORM_ROWS) + cells, source = asyncio.run(fetch_snapshot(None, oc, CITY, date(2026, 11, 1))) + assert source == "adhoc" and oc.phases == ["xy"] and oc.cleaned == [snapshot_task_name(CITY, date(2026, 11, 1))] + assert [(item["tech"], item["site_name"], item["latitude"]) for item in cells] == [("4G", "即席站", 22.0), ("5G", "即席站", 22.0)] + + +def test_snapshot_falls_back_to_opencode_attributes(monkeypatch): + adhoc_returns(monkeypatch, NqiError("即席查询没有返回行数")) + oc = SnapshotOpenCode(PLATFORM_ROWS) + cells, source = asyncio.run(fetch_snapshot(None, oc, CITY, date(2026, 11, 1))) + assert source == "opencode" and oc.phases == ["attr"] and cells[0]["site_name"] == "OC站" + + adhoc_returns(monkeypatch, {"4G": [{"cgi": "other"}], "5G": [{"ncgi": "n1"}]}) + mismatch = SnapshotOpenCode(PLATFORM_ROWS) + cells, source = asyncio.run(fetch_snapshot(None, mismatch, CITY, date(2026, 11, 1))) + assert source == "opencode" and mismatch.phases == ["xy", "attr"] and cells[0]["cgi"] == "c1" + + +def test_snapshot_rejects_empty_city(monkeypatch): + adhoc_returns(monkeypatch, NqiError("x")) + with pytest.raises(GongcanError): + asyncio.run(fetch_snapshot(None, SnapshotOpenCode({"4G": [], "5G": []}), CITY, date(2026, 11, 1))) + + +def test_store_answers_presence_queries(): + store = make_store(Platform({}), {date(2026, 10, 1): with_target(), date(2026, 11, 1): without_target()}) + assert store.ready_dates(CITY, date(2026, 10, 1), date(2026, 11, 2)) == [date(2026, 10, 1), date(2026, 11, 1)] + assert store.ready_dates(CITY, date(2026, 10, 1), date(2026, 11, 1)) == [date(2026, 10, 1)] + assert store.dates_with_target(CITY, SITE, date(2026, 1, 1), date(2027, 1, 1)) == [date(2026, 10, 1)] + assert store.has_target(CITY, date(2026, 10, 1), Target(cgis=("zz", "t1"))) + assert not store.has_target(CITY, date(2026, 11, 1), Target(cgis=("t1",))) + assert not store.has_target("广州", date(2026, 10, 1), SITE) + loaded = store.cells(CITY, date(2026, 10, 1)) + assert {item["cgi"] for item in loaded} == {"t1", "n1"} and loaded[0]["area"] == "" + + +def test_ensure_loads_once_even_when_tasks_race(): + platform = Platform({date(2026, 11, 1): with_target()}, delay=0.05) + store = make_store(platform) + + async def race(): + await asyncio.gather(store.ensure(CITY, date(2026, 11, 1)), store.ensure(CITY, date(2026, 11, 1))) + + asyncio.run(race()) + asyncio.run(store.ensure(CITY, date(2026, 11, 1))) + assert platform.fetched == [date(2026, 11, 1)] + + +def test_failed_snapshot_cools_down_then_retries(): + clock = Clock() + platform = Platform({}) + store = make_store(platform, clock=clock) + with pytest.raises(GongcanError, match="平台没有这一天"): + asyncio.run(store.ensure(CITY, date(2026, 11, 1))) + with pytest.raises(GongcanError, match="刚取失败"): + asyncio.run(store.ensure(CITY, date(2026, 11, 1))) + assert platform.fetched == [date(2026, 11, 1)] + clock.now += timedelta(minutes=11) + platform.days[date(2026, 11, 1)] = with_target() + asyncio.run(store.ensure(CITY, date(2026, 11, 1))) + assert platform.fetched == [date(2026, 11, 1)] * 2 and store.has_target(CITY, date(2026, 11, 1), SITE) + + +def test_stale_loading_is_taken_over(): + clock = Clock() + store = make_store(Platform({}), clock=clock) + assert claim_snapshot(store.engine, CITY, date(2026, 11, 1), clock()) is not None + assert claim_snapshot(store.engine, CITY, date(2026, 11, 1), clock() + timedelta(minutes=5)) is None + assert claim_snapshot(store.engine, CITY, date(2026, 11, 1), clock() + timedelta(minutes=41)) is not None + + +REMOVAL = date(2026, 11, 15) + + +def test_before_uses_latest_stored_snapshot_with_target(): + platform = Platform({}) + store = make_store(platform, {date(2026, 9, 1): with_target(), date(2026, 10, 20): with_target(), date(2026, 11, 14): without_target()}) + assert asyncio.run(pick_before(store, CITY, SITE, REMOVAL)) == date(2026, 10, 20) + assert platform.fetched == [] + + +def test_before_fetches_previous_month_when_stored_data_is_too_old(): + platform = Platform({date(2026, 10, 1): with_target()}) + store = make_store(platform, {date(2026, 7, 1): with_target()}) + assert asyncio.run(pick_before(store, CITY, SITE, REMOVAL)) == date(2026, 10, 1) + assert platform.fetched == [date(2026, 10, 1)] + + +def test_before_walks_back_month_by_month(): + platform = Platform({date(2026, 10, 1): without_target(), date(2026, 9, 1): with_target()}) + store = make_store(platform) + assert asyncio.run(pick_before(store, CITY, SITE, REMOVAL)) == date(2026, 9, 1) + assert platform.fetched == [date(2026, 10, 1), date(2026, 9, 1)] + + +def test_before_fails_after_three_months_and_skips_stored_months(): + platform = Platform({date(2026, 9, 1): without_target(), date(2026, 8, 1): without_target()}) + store = make_store(platform, {date(2026, 10, 1): without_target()}) + with pytest.raises(GongcanMissing, match="站点 T"): + asyncio.run(pick_before(store, CITY, SITE, REMOVAL)) + assert platform.fetched == [date(2026, 9, 1), date(2026, 8, 1)] + + +AFTER_REMOVAL = date(2026, 11, 1) +TODAY = date(2026, 11, 11) + + +def test_after_prefers_latest_snapshot_without_target(): + platform = Platform({}) + stored = {date(2026, 11, 3): without_target(), date(2026, 11, 5): with_target(), date(2026, 11, 8): without_target(), date(2026, 10, 30): without_target()} + store = make_store(platform, stored) + assert asyncio.run(pick_after(store, CITY, SITE, AFTER_REMOVAL, TODAY)) == AfterPick(date(2026, 11, 8), False) + assert platform.fetched == [] + + +def test_after_uses_yesterday_when_target_is_still_there(): + platform = Platform({}) + store = make_store(platform, {date(2026, 11, 5): with_target(), date(2026, 11, 10): with_target()}) + assert asyncio.run(pick_after(store, CITY, SITE, AFTER_REMOVAL, TODAY)) == AfterPick(date(2026, 11, 10), True) + assert platform.fetched == [] + + +def test_after_fetches_yesterday_when_stored_data_still_has_target(): + platform = Platform({date(2026, 11, 10): without_target()}) + store = make_store(platform, {date(2026, 11, 5): with_target(), date(2026, 10, 1): without_target()}) + assert asyncio.run(pick_after(store, CITY, SITE, AFTER_REMOVAL, TODAY)) == AfterPick(date(2026, 11, 10), False) + assert platform.fetched == [date(2026, 11, 10)] + + +def test_after_is_empty_until_removal_day_has_passed(): + store = make_store(Platform({})) + assert asyncio.run(pick_after(store, CITY, SITE, date(2026, 11, 10), TODAY)) is None + + +def test_target_needs_cgis_or_site(): + with pytest.raises(ValueError): + Target() + with pytest.raises(ValueError): + Target(cgis=("a",), site="b") + + +def test_nearest_sites_uses_template_rules(): + pool = [ + cell("t", "target"), + cell("a", "near", lat=22.001), + cell("b", "near", lat=22.003), + cell("c", "indoor", lat=22.0005, name="W-室分"), + cell("d", "iot", lat=22.0005, network_type="NB-IoT"), + cell("e", "small", lat=22.0005, name="微小站"), + cell("f", "same_spot"), + cell("g", "nr", lat=22.004, tech="5G", network_type="NR"), + cell("h", "unknown", lat=None, lon=None), + cell("i", "far", lat=22.2), + ] + found = nearest_sites(pool, 22.0, 113.0, exclude={"target"}, k=3) + assert [site for site, _ in found] == ["near", "nr", "far"] + assert 210 < found[0][1] < 235 + + +def test_target_center_falls_back_to_indoor_cells(): + assert target_center([cell("a", "T", lat=22.0), cell("b", "T", lat=22.002), cell("c", "T", lat=23.0, name="W-x")]) == pytest.approx((22.001, 113.0)) + assert target_center([cell("c", "T", lat=23.0, name="W-x")]) == (23.0, 113.0) + assert target_center([cell("c", "T", lat=None, lon=None)]) is None diff --git a/backend/tests/test_opencode.py b/backend/tests/test_opencode.py new file mode 100644 index 0000000..cd791e2 --- /dev/null +++ b/backend/tests/test_opencode.py @@ -0,0 +1,224 @@ +import asyncio +import re +from datetime import date + +import pytest + +from app.nqi.opencode import ( + ExportFile, + OpenCode, + OpenCodeError, + ascending_id, + cleanup_prompt, + export_prompt, + judge_export, + parse_export_csv, + redo_prompt, + snapshot_where, + sql_text, + task_dir_name, + task_session, +) + +BEFORE = date(2026, 11, 9) +REQUIRED = ("cgi", "longitude", "latitude", "eff_from_date", "eff_to_date") + + +def lte_file(name="lte_target.csv", phase="before"): + sql = f"select {', '.join(REQUIRED)} from appdbv3.a_common_cfg_lte_cellant_d where {snapshot_where('江门', BEFORE)}" + return ExportFile("t1", phase, name, sql, BEFORE, REQUIRED) + + +def bash(message_id, command, output): + part = {"type": "tool", "tool": "bash", "state": {"status": "completed", "input": {"command": command}, "output": output}} + return {"info": {"role": "assistant", "parentID": message_id}, "parts": [part]} + + +def ran(item, sql=None): + command = item.command() if sql is None else item.command().replace(item.sql, sql) + return "cd /home/opencode/.config/opencode/skills/adhoc_query && " + command + + +def test_task_dir_name_keeps_only_ascii_word_characters(): + assert task_dir_name("460-00-374730-86") == "460_00_374730_86" + site = task_dir_name("江门台山市现代技术学校") + assert re.fullmatch(r"[0-9a-f]{10}", site) + assert site != task_dir_name("江门台山市东门商业街") + assert re.fullmatch(r"job7_[0-9a-f]{10}", task_dir_name("job7 江门某站")) + with pytest.raises(ValueError): + task_dir_name(" ") + + +def test_sql_text_quotes_and_rejects_shell_characters(): + assert sql_text("O'Neil") == "'O''Neil'" + for value in ('a"b', "a$b", "a`b", "a\\b"): + with pytest.raises(ValueError): + sql_text(value) + + +def test_sql_and_prompt_never_carry_iso_dates(): + item = lte_file() + assert "city = '江门' and eff_from_date <= make_date(2026, 11, 9) and eff_to_date > make_date(2026, 11, 9)" in item.sql + for text in (export_prompt([item]), redo_prompt([item]), cleanup_prompt("t1")): + assert not re.search(r"\d{4}-\d{2}-\d{2}", text) + assert item.command() in export_prompt([item]) + + +def test_export_file_paths_and_retry_names(): + item = lte_file("lte_nbr_x1.csv", phase="after") + assert item.path == "/workspace/tasks/t1/after/lte_nbr_x1.csv" + first = item.retry(1) + second = first.retry(2) + assert (first.filename, second.filename) == ("lte_nbr_x1_r1.csv", "lte_nbr_x1_r2.csv") + assert item.key == first.key == second.key == "after/lte_nbr_x1" + assert second.required == REQUIRED + with pytest.raises(ValueError): + ExportFile("../x", "before", "a.csv", "select 1", BEFORE, REQUIRED) + with pytest.raises(ValueError): + ExportFile("t1", "before", "a.csv", 'select "x"', BEFORE, REQUIRED) + with pytest.raises(ValueError): + ExportFile("t1", "before", "a.csv", "select 1", BEFORE, ()) + + +def test_judge_accepts_only_script_evidence(): + item = lte_file() + saved = f"文件已保存至:{item.path}" + messages = [ + bash("m1", ran(item), saved), + {"info": {"role": "assistant", "parentID": "m1"}, "parts": [{"type": "text", "text": "DONE 1 /workspace/x.csv"}]}, + ] + found = judge_export(messages, "m1", [item])[item.key] + assert found.saved and found.sql_same and not found.empty + assert not judge_export(messages, "other", [item])[item.key].saved + + +def test_judge_flags_changed_sql_and_empty_result(): + item = lte_file() + changed = judge_export([bash("m1", ran(item, item.sql.replace("make_date(2026, 11, 9)", "'2025-11-11'")), f"文件已保存至:{item.path}")], "m1", [item]) + assert changed[item.key].saved and changed[item.key].sql_same is False + empty = judge_export([bash("m1", ran(item), "文件写入失败:服务端响应体为空,未写入任何数据")], "m1", [item]) + assert empty[item.key].empty and empty[item.key].sql_same and not empty[item.key].saved + + +def test_judge_splits_chained_commands(): + first, second = lte_file("lte_a.csv"), lte_file("lte_b.csv") + output = f"文件写入失败:服务端响应体为空\n文件已保存至:{second.path}" + found = judge_export([bash("m1", f"{first.command()} && {second.command()}", output)], "m1", [first, second]) + assert found[first.key].sql_same and not found[first.key].saved and not found[first.key].empty + assert found[second.key].saved and found[second.key].sql_same + + +def test_parse_csv_maps_by_header_and_checks_snapshot_day(): + content = ( + "\ufefflatitude,cgi,eff_to_date,cell_name,station_name,longitude,eff_from_date\n" + "22.5,460-00-1-1,2026-11-10 00:00:00,A,S,113.1,2026-11-01 00:00:00\n" + "22.5,460-00-1-2,broken\n" + "22.5,460-00-1-3,2026-11-09 00:00:00,B,S,113.1,2026-11-01 00:00:00\n" + ) + table = parse_export_csv(content, REQUIRED, BEFORE) + assert table.header[0] == "latitude" + assert [row["cgi"] for row in table.rows] == ["460-00-1-1", "460-00-1-3"] + assert (table.bad_rows, table.outside_day, table.missing) == (1, 1, []) + assert not table.ok + missing = parse_export_csv("cgi,cell_name\n1,A\n", REQUIRED, BEFORE) + assert "latitude" in missing.missing and not missing.ok + + +def test_ascending_id_format_and_order(): + ids = [ascending_id("msg") for _ in range(50)] + assert all(re.fullmatch(r"msg_[0-9a-f]{12}[0-9A-Za-z]{14}", value) for value in ids) + stamps = [value[4:16] for value in ids] + assert stamps == sorted(stamps) and len(set(stamps)) == len(stamps) + + +class FakeOpenCode(OpenCode): + def __init__(self, replies, files): + self.replies = replies + self.files = files + self.prompts = [] + + async def prompt(self, session_id, text): + self.prompts.append(text) + return f"m{len(self.prompts)}" + + async def wait_reply(self, session_id, message_id, timeout=1200): + return self.replies[len(self.prompts) - 1](message_id) + + async def read_text(self, path): + return self.files["/workspace/" + path] + + +GOOD_CSV = ( + "cgi,cell_name,station_name,longitude,latitude,eff_from_date,eff_to_date\n" + "460-00-1-1,A,S,113.1,22.5,2026-11-01 00:00:00,2026-11-10 00:00:00\n" +) + + +def test_export_retries_changed_sql_with_new_filename(): + good, wrong = lte_file("lte_a.csv"), lte_file("lte_b.csv") + retried = wrong.retry(1) + replies = [ + lambda mid: [ + bash(mid, ran(good), f"文件已保存至:{good.path}"), + bash(mid, ran(wrong, wrong.sql + " limit 10"), f"文件已保存至:{wrong.path}"), + ], + lambda mid: [bash(mid, ran(retried), f"文件已保存至:{retried.path}")], + ] + oc = FakeOpenCode(replies, {good.path: GOOD_CSV, retried.path: GOOD_CSV}) + tables = asyncio.run(oc.export("s1", [good, wrong])) + assert set(tables) == {good.key, wrong.key} + assert "SQL 被改动" in oc.prompts[1] and "lte_b_r1.csv" in oc.prompts[1] and "lte_a.csv" not in oc.prompts[1] + + +def test_export_accepts_empty_result_and_gives_up_after_retries(): + item = lte_file() + empty = FakeOpenCode([lambda mid: [bash(mid, ran(item), "服务端响应体为空")]], {}) + assert asyncio.run(empty.export("s1", [item]))[item.key].empty + never = FakeOpenCode([lambda mid: []] * 3, {}) + with pytest.raises(OpenCodeError): + asyncio.run(never.export("s1", [item], retries=2)) + assert len(never.prompts) == 3 + + +class FakeSession(OpenCode): + def __init__(self, base=""): + self.base = base + self.calls = [] + + async def provision(self): + self.calls.append("provision") + self.base = "provisioned" + + async def create_session(self): + self.calls.append("create") + return "s1" + + async def cleanup(self, session_id, task): + self.calls.append(f"cleanup {task}") + raise OpenCodeError("平台没回") + + async def delete_session(self, session_id): + self.calls.append(f"delete {session_id}") + return True + + +def test_task_session_always_cleans_up_without_hiding_the_error(): + oc = FakeSession() + + async def run(): + async with task_session(oc, "gc_x") as session_id: + assert session_id == "s1" + raise RuntimeError("导出出错") + + with pytest.raises(RuntimeError, match="导出出错"): + asyncio.run(run()) + assert oc.calls == ["provision", "create", "cleanup gc_x", "delete s1"] + + ready = FakeSession(base="provisioned") + + async def quiet(): + async with task_session(ready, "gc_y"): + pass + + asyncio.run(quiet()) + assert ready.calls == ["create", "cleanup gc_y", "delete s1"] diff --git a/docs/gongcan-source.md b/docs/gongcan-source.md new file mode 100644 index 0000000..56a03f0 --- /dev/null +++ b/docs/gongcan-source.md @@ -0,0 +1,138 @@ +# 评估工参的数据来源 + +退服评估要用拆除前、拆除后的 4G/5G 小区工参(含经纬度)。除工参外的其他数据(话务、流量等)都走即席查询, +不经过 OpenCode。工参按“地市 + 日期”整份存进本系统的 PostgreSQL,任务先查库,库里没有才去大数据平台取。 + +代码位置: + +| 内容 | 文件 | +| --- | --- | +| OpenCode 接口、提示词、导出核对 | `backend/app/nqi/opencode.py` | +| 即席查询按天取指定列 | `backend/app/nqi/adhoc.py` 的 `export_day` | +| 快照合并、入库、日期规则、邻站 | `backend/app/collect/gongcan.py` | +| 表结构 | `backend/app/models.py` 的 `GongcanSnapshot`、`GongcanCell`,迁移 `0007_gongcan_snapshot` | + +## 一份快照怎么来 + +1. 即席查询取当天全市工参(经纬度是脱敏的,不取): + - 4G `appdbv3.v_a_common_cfg_lte_cellant_d`,主键 `cgi` + - 5G `appdbv3.a_common_cfg_nr_cellant_d`,主键 `ncgi` + - 列:小区名、站点名 `station_name`、基站 ID/名称、`network_type`、`area`、`town`、`state`、`cover_type`、`frequency_band`、`vendor`、`azimuth` +2. OpenCode 在一个会话、一条提示词里导出全市当天有效的 CGI 和经纬度(4G/5G 各一个文件), + 原表是 `appdbv3.a_common_cfg_lte_cellant_d` / `a_common_cfg_nr_cellant_d`,按 `eff_from_date <= 当天 < eff_to_date` 取。 +3. 按 CGI 把经纬度合并回去。OpenCode 里没有的小区经纬度留空。坐标不在经度 70–140、纬度 15–55 之内的视为无效,也留空。 +4. 自动校验:即席查询给的 CGI 集合和 OpenCode 当天快照的 CGI 集合重合度(交集/并集)低于 98%, + 或者即席查询本身失败,就在同一个会话里让 OpenCode 把属性列一起导出,属性改用 OpenCode 的。 + 快照表的 `attr_source` 记录属性来自 `adhoc` 还是 `opencode`。 +5. 4G 或 5G 任何一边是空的,整份快照算失败。 + +OpenCode 那份按生效日期严格截取,是日期口径的基准;即席查询的日期口径(视图上的 `starttime`)还没在页面上抓包确认过, +所以靠第 4 步兜底。 + +### 实测(2026-11-01,江门) + +| | 行数 | 文件 | 有效坐标 | 说明 | +| --- | --- | --- | --- | --- | +| 4G | 40,816 | 3.35 MB | 40,741 | 一行一个天线,去重后 38,038 个 CGI,2,731 个 CGI 有多行 | +| 5G | 23,814 | 2.4 MB | 23,811 | 每行 `cgi == ncgi` | + +一条提示词 4 条导出命令约 138 秒、约 22 万输入 token;读文件每个 0.1–0.2 秒;清理约 10 秒。 +一份快照的 OpenCode 开销约 2.5 分钟。属性改由 OpenCode 导出时不额外增加 AI 调用(同样一条提示词,只是 SQL 多几列)。 +即席查询按每页 200 行要翻约 320 页,翻页之间停 0.3 秒。 + +## 存储与并发 + +- `gongcan_snapshot`:每个(地市,日期)一行,唯一约束。`status` 为 `loading` / `ready` / `failed`,兼作取数锁。 +- `gongcan_cell`:快照下的小区,唯一(快照,CGI,制式),另有(快照,站点名)索引。 +- 取数前先插入 `loading` 行,插入成功的任务负责取数;插不进的说明别人在取,每 10 秒查一次,最多等 45 分钟。 +- `loading` 超过 40 分钟没更新视为取数进程已死,下一个任务接手。 +- `failed` 冷却 10 分钟,期间别的任务直接报“刚取失败”,不反复打平台。 +- 邻站直接用库里全市快照算,不再按方框扩大范围多次导出。 + +## 拆除前后用哪天的工参 + +目标是一个或几个 CGI,或者一个站点名(按 `site_name` 匹配)。“今天”按北京时间。 + +**拆除前**(取不到则该小区/站点的评估任务失败): + +1. 库里“拆除日前 3 个月的 1 号”到“拆除日前一天”之间、包含目标的快照,取最晚的一份。 +2. 没有就从拆除日上个月 1 号开始逐月往前,最多 3 个月:库里已有这天但不含目标的跳过;库里没有的去平台取,取完含目标就用它。 +3. 三个月都没有,报 `GongcanMissing`。 + +例:拆除日 11-15,库里范围是 08-01 到 11-14;平台取数顺序 10-01、09-01、08-01。 + +**拆除后**(不报错,越接近今天越好): + +1. 拆除日已经是昨天或之后:没有拆除后的工参,返回空。 +2. 库里拆除日之后、目标已不在的快照,取最晚的一份。 +3. 都还有目标时,最晚那份是昨天就直接用;不是就从平台取昨天的。目标仍在只标记 `target_present=True`。 + +注意第 2 步可能选到较早的快照,例如拆除后第三天的快照里目标已不在,而之后没再入过库,就会用那份。 + +## OpenCode 接口 + +基础地址 `https://nqi.gmcc.net:20443/pro-opencode/`,账号要先登录 NQI 门户拿到 CASTGC。 + +1. 开通:`GET /pro-opencode/api/provision?random=<随机数>&__PID=LXWXYWGZT&token=`,返回 307 到 + `/pro-opencode/<用户>/L3dvcmtzcGFjZQ/session?...`;再 GET 这个地址,服务端种下 `oc_castgc`。 + 之后接口前缀是 `/pro-opencode/<用户>/`。 +2. 除 `file/content` 外的请求都带查询参数 `tickets=`,头 `x-opencode-directory: %2Fworkspace`。 +3. 用到的接口:`session`(建、查、删)、`session//prompt_async`、`session/status`、`session//message`、 + `permission`、`question`、`file`、`file/content`、`global/health`。 +4. 模型 `DeepSeek-V4-Flash-0731-w8a8`。消息 ID 用 `msg_` + 12 位十六进制毫秒时间 + 14 位随机字符,保证递增。 + +一个快照一个会话、一个目录 `/workspace/tasks/gc_/`。导出、读取、删除都只在 `/workspace` 里。 +会话结束时不论成败都先让 AI 删目录,再删会话;清理失败只记日志,不盖掉原来的错误。多个快照可以各开会话并行。 + +## 提示词与核对 + +导出提示词(`export_prompt`)要点:加载 `adhoc_query` 技能;程序发起、没人回答,不询问不确认不预览; +在技能目录下逐条执行给定命令;SQL 一个字符都不能改,也不要按技能规范重写;不得换目录和文件名; +最后每条输出 `DONE <序号> <路径>` 或 `FAIL <序号> <原因>`。命令形如: + +```bash +python script/download-file-all-async.py --sql "select cgi, longitude, latitude, eff_from_date, eff_to_date from appdbv3.a_common_cfg_lte_cellant_d where city = '江门' and eff_from_date <= make_date(2026, 11, 1) and eff_to_date > make_date(2026, 11, 1)" --save-dir "/workspace/tasks/gc_xxx/xy" --filename "lte.csv" +``` + +程序只认工具证据,AI 回复的文字只记录不采信: + +- 只看 bash 工具里实际执行的命令,按 `--save-dir`、`--filename` 对上文件,`--sql` 必须与下发的逐字节相同。 +- 导出脚本输出 `文件已保存至:<路径>` 才算落盘;输出 `服务端响应体为空` 视为查询结果为空。 +- 读回 CSV 后按表头取列(脚本输出的列顺序和 SELECT 不一致),必需列要齐,列数不对的行丢弃, + 有生效日期列时每行都要满足 `eff_from_date <= 当天 < eff_to_date`。 +- 不合格的换新文件名(`_r1`、`_r2`)重做,最多重做 2 次。 + +属性列导出时文字列写成 `replace(列::text, ',', ',') as 列`,避免字段里的英文逗号让 CSV 错列。 + +清理提示词用自然语言说明要删除的目录并要求只删这一个;直接给 `rm -rf` 命令会被平台安全规则拒绝。 + +## 已知的坑 + +- **日期字面量会被改**:平台在把提示词交给 AI 前会把 `YYYY-MM-DD` 换成占位符,还原时会串号, + 导致 SQL 里的日期被换成别的日期。SQL 里一律写 `make_date(年, 月, 日)`,提示词、路径、阶段名里都不出现日期样式的数字。 +- **4G 原表没有 `starttime`**,只能按 `eff_from_date` / `eff_to_date` 取某天的状态。 +- **4G 一个 CGI 多行**(天线粒度),入库按 CGI 去重,优先保留有有效坐标的那条。 +- **即席查询数据接口暂时不可用**(2026-11-11 起):`getTableCount`、`getTable`、`searchMap` 都返回 + `{"stat":"0","message":"null"}`,按抓包的完整页面请求顺序重放、重新走 CAS 也一样;`indexSearchMap`、`getPage` 正常。 + 这时快照自动改用 OpenCode 的属性。以前 `getTableCount` 出错会被当成 0 行静默返回,已改为报错。 +- 即席查询多选的维度(如“小区,网格,地市,分公司”“天粒度”)取第一个值并去掉“粒度”,这是推断,要等页面抓包确认。 + +## 迁移模板工具时的字段对照 + +| 模板工具 | 快照列 | +| --- | --- | +| CGI | `cgi`(5G 为 NCGI) | +| 小区名 | `cell_name` | +| 站点名 | `site_name` | +| 纬度 / 经度 | `latitude` / `longitude`(可能为空) | +| 制式 | `tech`(`4G` / `5G`) | + +入库筛选沿用模板工具规则:小区名含 `W-` 的室分小区、4G 的 NB-IoT 不参与邻站计算,邻站另外排除名称含“微小”的小区。 +目标自身是室分(`W-`)时仍然要能找到,所以快照里保留全部小区,筛选只在计算时做。 + +## 还没验证的 + +- OpenCode 弹出权限确认(`permission`)或提问(`question`)时的处理。 +- 会话异常后换新会话重试。 +- 即席查询恢复后,它的 CGI 与 OpenCode 快照的实际重合度,98% 的阈值要按实测调整。 +- 快照保留多久、何时清理旧快照(目前不自动删除,一份约 6.4 万行)。