metrics.py 21.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
"""指标取数:把「指标 + 维度 + 过滤 + 时间」**确定性地**编译成 SQL。

已发布的指标不让 LLM 写 SQL —— 口径由绑定定义,每次问都是同一条逻辑,
数字才可信、可复现、可审计。LLM 只负责从问题里挑出指标、维度和时间(编排层做)。
编译出的 SQL 仍走 executor(guard + 行数上限 + 超时),并落 SqlRun 作为数据引用。

统计周期是指标自己的口径(spec.period:自然月、「上月 26 日到本月 25 日」的业务月……),问「本期 / 上期」按它解析。
统计的是哪一批:一张表、一类对象(含计算属性),或一个对象集。
历史(history):有时间列的按周期分桶直接算;没有时间列的(库存这类时点数)读快照序列。
"""
from __future__ import annotations

from typing import Any

from fastapi import HTTPException

from ..core import identity
from . import calendar as cal
from . import service
from .sqlutil import ident, jsonable, lit, to_dialect


def metric(ref: str) -> dict:
    m = service.rt_fn(ref, "aggregate")
    if m is None:
        raise HTTPException(404, f"找不到已发布的聚合函数(指标)「{ref}」")
    return m


def resolve_time(m: dict, time: Any) -> dict | None:
    """time 可以是 {start,end} / {ref} / 'last' / '2026-08'。按指标自己的统计周期口径解析。

    'none' / '' 表示显式不按时间过滤 —— 像「库存缺口」这种快照指标本来就没有时间列,
    强行塞一个 'current' 会让它取不了数。
    """
    if not time or (isinstance(time, str) and time.strip().lower() in ("none", "不限")):
        return None
    if isinstance(time, dict) and str(time.get("ref") or "").strip().lower() in ("none", "不限"):
        return None
    if isinstance(time, str):
        time = {"ref": time}
    if time.get("start") and time.get("end"):
        return {"start": str(time["start"])[:10], "end": str(time["end"])[:10],
                "period": time.get("period") or "", "calendar": ""}
    period = (m.get("spec") or {}).get("period") or {}
    spec = {**cal.NATURAL_MONTH, **period} if period else cal.NATURAL_MONTH
    out = cal.resolve(spec, str(time.get("ref") or "current"))
    out["calendar"] = period_label(period)
    return out


def period_label(period: dict) -> str:
    """统计周期口径的叫法:写了 label 用 label,否则按规则说一句。"""
    if not period:
        return "自然月"
    if period.get("label"):
        return period["label"]
    grain = period.get("grain") or "month"
    if grain != "month":
        return {"day": "自然日", "week": "自然周", "quarter": "自然季度", "year": "自然年"}.get(grain, grain)
    if int(period.get("start_day") or 1) == 1 and str(period.get("end_day") or "last") == "last":
        return "自然月"
    return f"业务月({period.get('start_day')} 日起)"


_BUCKET_LEN = {"day": 10, "month": 7, "year": 4}


def compile_sql(m: dict, *, dimensions: list[str] | None = None, filters: dict | None = None,
                time: Any = None, object_key: str = "", order: str = "desc", limit: int = 200,
                bucket: str = "", set_inputs: dict | None = None) -> dict:
    """bucket:按时间分桶(day / month / year),结果多一列 __period,历史用。"""
    b = service.rt_binding(m, "metric_expr")
    if b is None:
        raise HTTPException(422, f"指标「{m['name']}」还没有绑定取数表达式")
    ref = b["ref"]
    dim_map: dict[str, str] = dict(ref.get("dimensions") or {})
    ds_id = b["ds_id"]
    source = ident(ref["base_table"]) if ref.get("base_table") else ""
    base_ot = None
    if ref.get("base_set"):
        # 指标统计一个对象集:把这批对象(含算出来的属性)当成一张表来聚合
        from . import objectset
        ds_id, sub, base_ot = objectset.sql_base(ref["base_set"], set_inputs)
        source = f"{sub} AS t"
        tcols = (objects_eff(base_ot).get("columns") or {})
        for p in (base_ot.get("spec") or {}).get("properties") or []:
            dim_map.setdefault(p["name"], p["name"] if p.get("expression") else tcols.get(p["name"], p["name"]))
    elif ref.get("base_object"):
        # 指标建在对象上:把对象(含算出来的属性)当成一张表来聚合,对象的每个属性都能当维度
        from . import objects
        base_ot = service.rt_find(ref["base_object"], "object_type")
        if base_ot is None:
            raise HTTPException(422, f"指标「{m['name']}」统计的对象「{ref['base_object']}」还没有发布")
        ds_id, sub = objects.source_sql(base_ot)
        source = f"{sub} AS t"
        tcols = (objects.table_binding(base_ot)["ref"].get("columns") or {})
        for p in (base_ot.get("spec") or {}).get("properties") or []:
            dim_map.setdefault(p["name"], p["name"] if p.get("expression") else tcols.get(p["name"], p["name"]))
    if not source:
        raise HTTPException(422, f"指标「{m['name']}」还没有选统计哪张表或哪个对象")

    # 维度就是对象的属性:属性的显示名也能用来拆分(「按大区」→ 属性「区域」显示名「大区」)
    alias: dict[str, str] = {}
    ot = base_ot or service.rt_find((m.get("spec") or {}).get("object_type") or "", "object_type") or {}
    for p in (ot.get("spec") or {}).get("properties") or []:
        if p.get("display_name"):
            alias[p["display_name"]] = p["name"]

    def dim_col(name: str) -> str:
        if name in dim_map:
            return dim_map[name]
        if alias.get(name) in dim_map:
            return dim_map[alias[name]]
        low = name.lower()
        for k in dim_map:
            if k.lower() == low:
                return dim_map[k]
        raise HTTPException(422, f"指标「{m['name']}」不支持按「{name}」拆分,"
                                 f"可用维度:{'、'.join(dim_map) or '无'}")

    dims = [d for d in (dimensions or []) if d]
    select_parts = [f"{ident(dim_col(d))} AS {ident(d)}" for d in dims]
    if bucket:
        if not ref.get("time_column"):
            raise HTTPException(422, f"指标「{m['name']}」没有时间列,历史要读快照")
        n = _BUCKET_LEN.get(bucket)
        if not n:
            raise HTTPException(422, f"历史只能按 {'/'.join(_BUCKET_LEN)} 分桶")
        select_parts.insert(0, f"SUBSTR(CAST({ident(_tcol(ref, base_ot, dim_map))} AS CHAR), 1, {n}) AS `__period`")
    select_parts.append(f"{ref['expression']} AS `value`")
    where = list(ref.get("filters") or [])
    for name, val in (filters or {}).items():
        if val in (None, "", []):
            continue
        col = ident(dim_col(name))
        if isinstance(val, (list, tuple)):
            where.append(f"{col} IN ({', '.join(lit(v) for v in val)})")
        else:
            where.append(f"{col} = {lit(val)}")
    if object_key:
        if not ref.get("object_key_column"):
            raise HTTPException(422, f"指标「{m['name']}」没有配置对象键列,不能按单个对象取数")
        where.append(f"{ident(ref['object_key_column'])} = {lit(object_key)}")
    period = resolve_time(m, time)
    if period:
        if not ref.get("time_column"):
            raise HTTPException(422, f"指标「{m['name']}」没有配置时间列,不能按时间过滤")
        tc = ident(_tcol(ref, base_ot, dim_map))
        import datetime as _dt
        nxt = (_dt.date.fromisoformat(str(period["end"])[:10]) + _dt.timedelta(days=1)).isoformat()
        where.append(f"{tc} >= {lit(period['start'])} AND {tc} < {lit(nxt)}")     # 含首尾:截止日的第二天之前
    # 数据范围:对象键列 / 同名维度上的限制(建在对象上的指标,范围已经在对象那一层过滤了)
    ot_id = ot.get("id") if ot and not base_ot else None
    scope = (identity.current().scope or {}).get(ot_id) if ot_id else None
    for prop, vals in (scope or {}).items():
        col = dim_map.get(prop)
        if not col and ref.get("object_key_column"):
            ot = service.rt_get(ot_id) or {}
            if prop == (ot.get("spec") or {}).get("key_property"):
                col = ref["object_key_column"]
        if col and vals:
            where.append(f"{ident(col)} IN ({', '.join(lit(v) for v in vals)})")
    sql = f"SELECT {', '.join(select_parts)} FROM {source}"
    if where:
        sql += " WHERE " + " AND ".join(f"({w})" for w in where)
    direction = "ASC" if order == "asc" else "DESC"
    cap = int(max(1, min(limit, 5000)))
    named: dict[str, str] = {}          # 维度 → 名称列的列名(SQL 里已经带出来的)
    types: dict[str, dict] = {}         # 维度 → 它是哪类对象
    dim_types: dict[str, dict] = {}
    if base_ot:
        from . import objects
        b_ref = objects.table_binding(base_ot)["ref"]
        c2p = {v: k for k, v in (b_ref.get("columns") or {}).items()}
        for par in objects.parents(base_ot):
            prop = c2p.get(par["my_col"], par["my_col"])
            dim_types[prop] = par["other"]
            dim_types.setdefault(prop_label(base_ot, prop), par["other"])
    unnamed: dict[str, str] = {}        # 维度 → 对象类型名(是对象,但名称要查完再补)
    if dims or bucket:
        groups = ([f"SUBSTR(CAST({ident(_tcol(ref, base_ot, dim_map))} AS CHAR), 1, {_BUCKET_LEN[bucket]})"]
                  if bucket else []) + [ident(dim_col(d)) for d in dims]
        sql += " GROUP BY " + ", ".join(groups)
        joins, outer = [], (["m.`__period`"] if bucket else [])
        for i, d in enumerate(dims):
            outer.append(f"m.{ident(d)}")
            ot_d = dim_types.get(d) or dim_object_type(ref, d)
            if not ot_d:
                continue
            types[d] = {"type_id": ot_d["id"], "type_name": ot_d["name"]}
            from . import objects
            tb = objects.binding(ot_d) or {}
            tref = tb.get("ref") or {}
            if tb.get("ds_id") == ds_id and tref.get("label_column") and tref.get("key_column"):
                # 维度本身是对象(仓库、商品):同一个数据源里直接关联对象表带出名称,
                # 「查看 SQL」拿去重跑能得到一模一样的结果
                named[d] = f"{d}名称"
                outer.append(f"d{i}.{ident(tref['label_column'])} AS {ident(named[d])}")
                joins.append(f"LEFT JOIN {tref['from']} AS d{i} "
                             f"ON m.{ident(d)} = d{i}.{ident(tref['key_column'])}")
            else:
                unnamed[d] = ot_d["name"]
        order_by = "`__period` ASC" if bucket else f"`value` {direction}"
        if joins:
            sql = (f"SELECT {', '.join(outer)}, m.`value` FROM ({sql}) AS m {' '.join(joins)} "
                   f"ORDER BY m.{order_by}")
        else:
            sql += f" ORDER BY {order_by}"
    sql += f" LIMIT {cap}"
    return {"sql": sql, "ds_id": ds_id, "period": period, "dimensions": dims,
            "named": named, "unnamed": unnamed, "types": types}


def prop_label(ot: dict, prop: str) -> str:
    for p in (ot.get("spec") or {}).get("properties") or []:
        if p["name"] == prop:
            return p.get("display_name") or prop
    return prop


def value_label(m: dict) -> str:
    unit = (m.get("spec") or {}).get("unit") or ""
    name = m.get("display_name") or m["name"]
    return f"{name}({unit})" if unit and unit not in name else name


def col_meta(m: dict, compiled: dict, columns: list[str]) -> list[dict]:
    """结果的每一列怎么显示:数值列叫指标的名字;对象维度的编号列和名称列合成一列。"""
    ot = service.rt_find((m.get("spec") or {}).get("object_type") or "", "object_type") or {}
    spec = m.get("spec") or {}
    out = []
    for c in columns:
        if c == "__period":
            out.append({"name": c, "label": "统计时间", "role": "period"})
            continue
        if c == "value":
            out.append({"name": c, "label": value_label(m), "role": "value", "unit": spec.get("unit") or "",
                        "format": spec.get("format") or ""})
            continue
        base = c[:-2] if c.endswith("名称") and c[:-2] in compiled["dimensions"] else ""
        if base:
            out.append({"name": c, "label": prop_label(ot, base) if ot else base, "role": "name", "of": base})
            continue
        meta = {"name": c, "label": prop_label(ot, c) if ot else c, "role": "dim"}
        if c in (compiled.get("types") or {}):
            meta.update(compiled["types"][c])
            meta["name_col"] = f"{c}名称" if f"{c}名称" in columns else ""
        out.append(meta)
    return out


def dim_object_type(ref: dict, dim: str) -> dict | None:
    """这个维度对应哪个对象类型(已发布)。绑定里声明了 dimension_types 就按声明,
    没声明时按「维度名就是对象类型名」认(「按仓库拆分」的仓库通常就是对象「仓库」)。"""
    declared = str((ref.get("dimension_types") or {}).get(dim) or "")
    if declared:
        return service.rt_get(declared) or service.rt_find(declared, "object_type")
    return service.rt_find(dim, "object_type")


def _fill_names(compiled: dict, columns: list[str], rows: list[list[Any]]) -> list[str]:
    """SQL 里带不出名称的对象维度(对象表在别的数据源),查完按主键补一列名称。返回补不上的维度。"""
    from . import objects
    missing = []
    for dim, type_name in (compiled.get("unnamed") or {}).items():
        if dim not in columns:
            continue
        i = columns.index(dim)
        names = objects.labels(type_name, [r[i] for r in rows])
        if not names:
            missing.append(dim)
            continue
        columns.insert(i + 1, f"{dim}名称")
        for r in rows:
            r.insert(i + 1, names.get(str(r[i]), ""))
    return missing


def query(ref: str | dict, *, dimensions: list[str] | None = None, filters: dict | None = None,
          time: Any = None, object_key: str = "", order: str = "desc",
          limit: int = 200, question: str = "", bucket: str = "", set_inputs: dict | None = None) -> dict:
    """ref 是名称 / id(取已发布定义),或直接给一份函数定义 dict(试跑工作副本用)。"""
    from ..text2sql import executor, semantic
    m = ref if isinstance(ref, dict) else metric(ref)
    compiled = compile_sql(m, dimensions=dimensions, filters=filters, time=time,
                           object_key=object_key, order=order, limit=limit, bucket=bucket,
                           set_inputs=set_inputs)
    ds = semantic.get_datasource(compiled["ds_id"])
    if ds is None:
        raise HTTPException(422, f"数据源 {compiled['ds_id']} 不存在")
    out = executor.execute(compiled["ds_id"], to_dialect(compiled["sql"], ds["ds_type"]), ds["ds_type"],
                           policy="catalog")
    status = "ok" if out.ok else "failed"
    rows = [[jsonable(v) for v in r] for r in (out.result.rows if out.result else [])]
    run_id = executor.log_run(
        compiled["ds_id"], question or f"[指标] {m['name']}", compiled["sql"],
        out.guard.sql if out.guard and out.guard.sql else compiled["sql"], status,
        plan={"metric": m["name"], "dimensions": compiled["dimensions"], "filters": filters,
              "time": compiled["period"], "object_key": object_key},
        error=out.error, row_count=len(rows),
        duration_ms=out.result.duration_ms if out.result else 0)
    if not out.ok:
        raise HTTPException(422, f"指标取数失败:{out.error}")
    columns = list(out.result.columns) if out.result else []
    notes = [f"「{d}」是对象,但取不到它的名称(对象没有名称列或查不到),结果里只有编号"
             for d in _fill_names(compiled, columns, rows)]
    calibre = None
    cr = (m.get("spec") or {}).get("calibre_rule")
    if cr:
        rc = service.rt_fn(cr, "rule")
        if rc:
            calibre = {"id": rc["id"], "name": rc["name"],
                       "text": (rc.get("spec") or {}).get("text") or rc.get("description", "")}
    value = rows[0][-1] if rows and not compiled["dimensions"] else None
    return {"metric": {"id": m["id"], "name": m["name"], "unit": (m.get("spec") or {}).get("unit", ""),
                       "direction": (m.get("spec") or {}).get("direction", "neutral")},
            "sql": out.guard.sql or compiled["sql"], "run_id": run_id,
            "columns": columns, "rows": rows, "col_meta": col_meta(m, compiled, columns),
            "value_label": value_label(m), "value": value, "period": compiled["period"], "calibre": calibre, "notes": notes,
            "truncated": bool(out.result and out.result.truncated)}


def query_many(calls: list[dict], workers: int = 6) -> list[dict | Exception]:
    """几个指标一起取(工作台的关键数字、对象页上这个对象的各项指标):并行发出去,按原顺序返回。
    每一项是 query() 的参数;某一项失败不影响别的,对应位置放的是那个异常。"""
    import contextvars
    from concurrent.futures import ThreadPoolExecutor
    if not calls:
        return []

    def one(kw: dict):
        try:
            return query(**kw)
        except Exception as e:  # noqa: BLE001
            return e
    if len(calls) == 1:
        return [one(calls[0])]
    with ThreadPoolExecutor(max_workers=min(workers, len(calls))) as pool:
        # 每个线程带上当前请求的身份 / 环境 / 预演状态
        futs = [pool.submit(contextvars.copy_context().run, one, kw) for kw in calls]
        return [f.result() for f in futs]


def objects_eff(ot: dict) -> dict:
    from . import objects
    return objects.table_binding(ot)["ref"]


def _tcol(ref: dict, base_ot: dict | None, dim_map: dict[str, str]) -> str:
    """时间列:建在对象 / 对象集上的指标,时间列写的可以是属性名(对象读取方案里的列)。"""
    tc = ref.get("time_column") or ""
    return dim_map.get(tc, tc) if base_ot else tc


def history(ref: str | dict, *, grain: str = "day", n: int = 30, dimensions: list[str] | None = None,
            filters: dict | None = None, object_key: str = "", end: Any = None) -> dict:
    """指标的历史:{metric, grain, source, dimensions, series: {维度键: [{period, value}]}}(旧的在前)。

    有时间列:按 grain 分桶在业务库里算最近 n 个桶(SUM / COUNT 类的指标没有数的桶补 0);
    没有时间列:读快照序列(series.metric_series),每个桶取最后一个点。"""
    import datetime as dt

    from . import series as ser
    m = ref if isinstance(ref, dict) else metric(ref)
    b = service.rt_binding(m, "metric_expr")
    if b is None:
        raise HTTPException(422, f"指标「{m['name']}」还没有绑定取数表达式")
    dims = [d for d in (dimensions or []) if d]
    n = max(1, min(int(n or 30), 400))
    end_d = (dt.date.fromisoformat(str(end)[:10]) if end else dt.date.today())
    if grain == "day":
        start = end_d - dt.timedelta(days=n - 1)
    elif grain == "month":
        y, mo = divmod(end_d.year * 12 + end_d.month - 1 - (n - 1), 12)
        start = dt.date(y, mo + 1, 1)
    elif grain == "year":
        start = dt.date(end_d.year - n + 1, 1, 1)
    else:
        raise HTTPException(422, f"历史只能按 {'/'.join(_BUCKET_LEN)} 看")
    buckets = _buckets(start, end_d, grain)
    out: dict[str, list[dict]] = {}
    expr = str((b.get("ref") or {}).get("expression") or "").strip().upper()
    fill = 0 if expr.startswith(("SUM", "COUNT")) else None
    if (b.get("ref") or {}).get("time_column"):
        res = query(m, dimensions=dims, filters=filters, object_key=object_key, bucket=grain, limit=5000,
                    time={"start": start.isoformat(), "end": end_d.isoformat()}, question=f"[历史] {m['name']}")
        cols = [str(c) for c in res["columns"]]
        got: dict[str, dict[str, Any]] = {}
        for row in res["rows"]:
            rec = dict(zip(cols, row))
            got.setdefault(ser.dims_key(rec, dims) if dims else "", {})[str(rec.get("__period"))] = rec.get("value")
        for k, by_p in (got or {"": {}}).items():
            out[k] = [{"period": p, "value": by_p.get(p, fill)} for p in buckets]
        source = "time_column"
    else:
        pts = ser.query(ser.metric_series(m["id"]), since=dt.datetime.combine(start, dt.time.min), limit=20000)
        by_key: dict[str, dict[str, Any]] = {}
        for pt in pts:
            p = str(pt["at"])[:_BUCKET_LEN[grain]]
            by_key.setdefault(pt["skey"], {})[p] = pt["value"]      # 后来的点覆盖:每个桶取最后一个
        for k, by_p in by_key.items():
            out[k] = [{"period": p, "value": by_p.get(p)} for p in buckets]
        source = "snapshot"
    return {"metric": {"id": m["id"], "name": m["name"], "unit": (m.get("spec") or {}).get("unit", "")},
            "grain": grain, "source": source, "dimensions": dims, "series": out}


def _buckets(start, end, grain: str) -> list[str]:
    import datetime as dt
    out = []
    cur = start
    while cur <= end:
        out.append(cur.isoformat()[:_BUCKET_LEN[grain]])
        if grain == "day":
            cur += dt.timedelta(days=1)
        elif grain == "month":
            cur = (cur.replace(day=28) + dt.timedelta(days=4)).replace(day=1)
        else:
            cur = dt.date(cur.year + 1, 1, 1)
    return list(dict.fromkeys(out))