modeling_schedule.py 22.3 KB
"""AI 建模 ⑦ 预警与定时:文档里写了「每天几点做」「低于多少就通知」「突然暴增要预警」的,直接配成预警规则与定时任务的草稿。

- 流程写了执行时间(「每天 9:00 做巡检」)→ 按点跑这张流程卡(source=sop + run_sop);
- 规则写了要盯着的条件(「某类记录低于某个数就通知某角色」)→ 盯对象或指标,命中就通知 / 派任务 / 提交审批;
- 流程卡里已经逐条处理的检查不再另建监控,免得同一件事一天被提醒两遍。

草稿的格式就是监控模块认的那套(watch.service.normalize),先在这里校一遍:引用的流程卡、指标、对象、动作
必须在这次草案或本体里,条件只能用对象 / 指标拆出来的字段;不过的按错误让 AI 改一次。
采纳时在元素和流程卡上线之后调 watch.service.create 建好并启用。
"""
from __future__ import annotations

import copy
from typing import Any, Iterator

from fastapi import HTTPException

from ..core import llm
from ..core.dbx import jdump, new_id
from ..governance import llmlog
from . import modeling, rules, service

SCHEDULE_PROMPT = """下面是一份业务文档,以及这次从里面建出来的流程卡、对象、指标、规则和动作。
把文档里**写明了要定时做、或者要持续盯着**的事配成监控 / 定时任务。

【文档】
{doc}

【流程卡】(名称|负责角色|文档写的执行时间|步骤)
{sops}

【对象及属性】
{objects}

【指标】(名称:可拆分的维度)
{metrics}

【判定类规则】
{rules}

【动作】(名称:作用对象,参数)
{actions}

【业务角色】{roles}

【文档里的定时 / 盯数条目】
{reqs}

每条监控的写法:
{{"title":"监控名","description":"一句话说明","owner_role":"负责角色",
  "schedule":{{"kind":"daily","at":"09:00"}}(也可以 {{"kind":"weekly","weekday":1,"at":"09:00"}}、
             {{"kind":"monthly","day":1,"at":"09:00"}}、{{"kind":"interval","every_minutes":60}}),
  "source": 三选一 ——
     {{"kind":"sop","sop":"流程卡名"}}:不看数据,到点跑流程卡;
     {{"kind":"object","object_type":"对象名"}}:逐个看这类对象,condition 里用它的属性名(含计算属性);
     {{"kind":"metric","metric":"指标名","dimensions":["维度名"]}}:按维度拆开逐行看,condition 里用维度名和 value(指标值),
  "detectors":[ 文档写了「突然暴增 / 骤降 / 比上周多了 X% / 连续 N 天下降 / 状态变成 X / 超过 N 天没动」这类和历史比的条件时才写 ——
     {{"name":"z","fn":"zscore","field":"value","window":14}}(偏离近 N 期均值几个标准差)、
     {{"name":"增幅","fn":"pct_change","field":"value"}}(比上一期变了百分之多少,0.3 = 30%)、
     {{"name":"连跌","fn":"streak_down","field":"属性或 value"}}、{{"name":"变冻结","fn":"changed","field":"状态属性","to":["冻结"]}}、
     {{"name":"呆滞天数","fn":"stale","field":"属性"}}(多少天没变过);对象上的属性要和历史比,那个属性要标了「记录历史」 ],
  "condition":"对每一行求值的表达式,可以用检测量的名字,如 value < 20、is_overdue、z > 3、增幅 > 0.3(source=sop 时留空)",
  "severity": 文档写了分级(「超过 X 为严重」)时用 {{"mode":"rules","level":"中","rules":[{{"when":"条件","level":"高"}}]}},否则 {{"mode":"fixed","level":"中"}},
  "strategies":[ 命中后做什么,可以多条 ——
     {{"kind":"run_sop","sop":"流程卡名","params":{{}}}}、
     {{"kind":"notify","role":"角色","subject":"标题,可嵌 $字段","body":"内容,可嵌 $字段"}}、
     {{"kind":"task","role":"角色","title":"待办标题","instructions":"要做什么"}}、
     {{"kind":"propose_action","action":"动作名","params":{{"参数名":"$字段"}},"reason":"为什么"}} ],
  "dedup":{{"key":"$key","cooldown_hours":24}},
  "basis":"文档里的依据(照抄原句)","req_ids":["落实了上面哪几条"]}}

要求:
- 只配文档里写了的:流程写了执行时间的,按那个时间跑这张流程卡;规则写了「低于 / 超过 / 存在…就通知 / 处理」的,配成盯数据的监控。
- 流程卡里已经逐条处理的检查(巡检流程里已经查过、处理过的)不要再单独建监控。
- 条件优先用对象上的计算属性(是 / 否状态、算出来的量),口径和别处一致;表里有现成的列和指标口径重复时用指标。
- 文字匹配用 contains(字段, '关键字'),不要写 SQL 的 like。
- 盯数据的监控文档没写时间的,默认每天 08:00 看一次。
- 只能用上面列出的流程卡、对象、指标、动作和角色,名字照抄。
只输出 JSON:{{"watches":[...]}},没有可配的就输出 {{"watches":[]}}。"""


def _context(run_id: str, ctx: dict) -> dict[str, Any]:
    """这次建模里能被监控引用的东西:流程卡标题、对象(含草案)、指标及维度、动作、规则。"""
    from ..capability import defs
    from ..governance import roles
    from ..sop import service as sop_service
    from ..sop import spec as sop_spec
    inp = modeling._inputs(run_id)
    hints = inp.get("sop_hints") or {}
    sops, sop_lines = {}, []
    for sid in inp.get("sop_ids") or []:
        try:
            d = sop_service.get(sid)
        except HTTPException:
            continue
        h = hints.get(sid) or {}
        sops[d["title"]] = sid
        steps = "→".join(o["title"] for o in sop_spec.outline(d["spec"]) if o["kind"] not in ("case", "end"))[:300]
        sop_lines.append(f"- {d['title']}|{d.get('owner_role') or h.get('owner_role') or ''}|{h.get('schedule') or '(没写)'}|{steps}")
    for d in sop_service.list_defs(status="published"):
        sops.setdefault(d["title"], d["id"])
    objs = modeling._run_objects(run_id)
    metrics: dict[str, list[str]] = {}
    actions: dict[str, dict] = {}
    rule_lines = []
    for it in modeling._pending(run_id):
        pl = it["payload"] or {}
        sp = pl.get("spec") or {}
        if pl.get("kind") == "function" and sp.get("category") == "aggregate":
            b = next((x for x in pl.get("bindings") or [] if x.get("target_kind") == "metric_expr"), None)
            metrics[pl["name"]] = list(((b or {}).get("ref") or {}).get("dimensions") or {})
        elif pl.get("kind") == "function" and sp.get("category") == "rule" and sp.get("rule_kind") == "judgement":
            rule_lines.append(f"- {pl['name']}({sp.get('object_type') or ''}):{sp.get('expression') or ''};{sp.get('text') or ''}")
        elif pl.get("kind") == "action":
            actions[pl["name"]] = sp
    for c in service.list_concepts(kind="function", limit=300):
        if c.get("category") == "aggregate" and c["name"] not in metrics:
            full = service.get_concept(c["id"])
            b = next((x for x in full.get("bindings") or [] if x["target_kind"] == "metric_expr"), None)
            metrics[c["name"]] = list(((b or {}).get("ref") or {}).get("dimensions") or {})
    for a in defs.list_defs("action"):
        actions.setdefault(a["name"], a.get("spec") or {})
    return {"sops": sops, "sop_lines": sop_lines, "objs": objs, "metrics": metrics, "actions": actions,
            "rule_lines": rule_lines, "roles": roles.names(),
            "objects_text": modeling._objects_text(objs, modeling._run_links(run_id))}


def _problems(w: dict, c: dict) -> list[str]:
    """一条监控草稿的问题(格式 + 引用 + 条件里用到的字段)。空列表 = 能直接建。"""
    from ..watch import service as watch_service
    errs: list[str] = []
    title = str(w.get("title") or "未命名")
    try:
        watch_service.normalize(w)
    except HTTPException as e:
        return [f"「{title}」:{e.detail}"]
    except Exception as e:  # noqa: BLE001 —— 排程写错是 CronError
        return [f"「{title}」:{e}"]
    src = w.get("source") or {}
    fields: set[str] = {"key", "label", "value"}
    if src.get("kind") == "sop" and src.get("sop") not in c["sops"]:
        errs.append(f"「{title}」:没有叫「{src.get('sop')}」的流程卡,只能用:{'、'.join(c['sops']) or '(无)'}")
    if src.get("kind") == "object":
        rec = modeling._resolve_obj(str(src.get("object_type") or ""), c["objs"])
        if rec is None:
            errs.append(f"「{title}」:没有对象「{src.get('object_type')}」")
        else:
            src["object_type"] = rec["name"]
            fields |= {p["name"] for p in rec["properties"]}
    if src.get("kind") == "metric":
        if src.get("metric") not in c["metrics"]:
            errs.append(f"「{title}」:没有指标「{src.get('metric')}」,只能用:{'、'.join(c['metrics']) or '(无)'}")
        else:
            dims = c["metrics"][src["metric"]]
            bad = [d for d in src.get("dimensions") or [] if d not in dims]
            if bad:
                errs.append(f"「{title}」:指标「{src['metric']}」不能按 {'、'.join(bad)} 拆,可用维度:{'、'.join(dims) or '无'}")
            fields |= set(src.get("dimensions") or [])
    fields |= {str(d.get("name") or d.get("fn") or "") for d in w.get("detectors") or [] if isinstance(d, dict)}
    cond = str(w.get("condition") or "").strip()
    if cond and src.get("kind") != "sop":
        try:
            ghost = sorted(n for n in rules.free_names(cond) if n not in fields and n not in ("today",))
        except rules.RuleError as e:
            ghost = []
            errs.append(f"「{title}」:条件写法有误:{e}")
        if ghost:
            errs.append(f"「{title}」:条件里的 {'、'.join(ghost)} 不是这一行有的字段(可用:{'、'.join(sorted(fields))})")
    for st in w.get("strategies") or []:
        k = st.get("kind")
        if k == "run_sop" and st.get("sop") not in c["sops"]:
            errs.append(f"「{title}」:要启动的流程卡「{st.get('sop')}」不存在")
        if k == "propose_action" and st.get("action") not in c["actions"]:
            errs.append(f"「{title}」:动作「{st.get('action')}」不存在,只能用:{'、'.join(c['actions']) or '(无)'}")
        if k in ("notify", "task") and st.get("role") and st["role"] not in c["roles"]:
            errs.append(f"「{title}」:角色「{st['role']}」不在业务角色里:{'、'.join(c['roles'])}")
    return errs


def add_one(run_id: str, req: dict, note) -> str:
    """按对账补一条漏掉的监控:只按这一条要求配。返回建好的草稿标题(空串 = 没配成)。"""
    c = _context(run_id, {})
    msg = SCHEDULE_PROMPT.format(
        doc=f"【{req.get('section') or '要求'}】\n{req.get('quote') or req['text']}\n(要做到:{(req.get('fix') or {}).get('instruction') or req['text']})",
        sops="\n".join(c["sop_lines"]) or "(无)", objects=c["objects_text"],
        metrics="\n".join(f"- {m}:{'、'.join(d) or '不拆'}" for m, d in c["metrics"].items()) or "(无)",
        rules="\n".join(c["rule_lines"]) or "(无)",
        actions="\n".join(f"- {n}:{sp.get('target_type') or ''},{[x.get('name') for x in sp.get('params') or []]}"
                          for n, sp in c["actions"].items()) or "(无)",
        roles="、".join(c["roles"]) or "(无)", reqs=f"{req['id']}:{req['text']}")
    try:
        with llmlog.feature("modeling_schedule"), llm.trace_label(f"按对账补监控:{req['id']}"):
            res = llm.chat_json([{"role": "user", "content": msg}], temperature=0.1)
    except Exception as e:  # noqa: BLE001
        note(f"补监控没成:{str(e)[:100]}")
        return ""
    ws = [w for w in (res.get("watches") or []) if isinstance(w, dict)] if isinstance(res, dict) else []
    if not ws:
        return ""
    w = ws[0]
    _lift_fields(run_id, w, c, note)
    probs = _problems(w, c)
    d = {"id": new_id("wd"), "title": str(w.get("title") or "未命名监控")[:120], "body": _body(w),
         "basis": str(w.get("basis") or req.get("quote") or "")[:300], "status": "pending", "req_ids": [req["id"]],
         "issue": ";".join(probs), "weak": bool(probs)}
    from . import modeling_world
    if not probs:
        with modeling_world.world(modeling._pending(run_id)):
            d["trial"] = modeling_world.watch_trial(d["body"])
    modeling._patch_inputs(run_id, lambda inp: inp.update(watch_drafts=[*(inp.get("watch_drafts") or []), d]))
    return d["title"]


def _lift_fields(run_id: str, w: dict, c: dict, note) -> None:
    """条件里用了对象「指向的那个对象」的属性(盯明细却按名称筛):逐行看的时候这一行里没有它。
    意思是确定的,就在这次草案的对象上加一个计算属性(= 关系名.属性),条件照原样就能用。"""
    src = w.get("source") or {}
    cond = rules.normalize_text(str(w.get("condition") or "").strip())
    if src.get("kind") != "object" or not cond:
        return
    w["condition"] = cond
    rec = modeling._resolve_obj(str(src.get("object_type") or ""), c["objs"])
    if rec is None or rec["item"] is None:
        return
    try:
        names = rules.free_names(cond)
    except rules.RuleError:
        return
    have = {p["name"] for p in rec["properties"]}
    links = modeling._run_links(run_id)
    for n in names:
        if n in have or n in ("key", "label", "value", "today"):
            continue
        for l in links:
            if l["from"] != rec["name"] or not l["n1"]:
                continue
            other = modeling._resolve_obj(str(l["to"] or ""), c["objs"])
            hit = next((p for p in (other or {}).get("properties") or [] if p["name"] == n), None)
            if hit is None:
                continue
            why = modeling._attach_property(c["objs"], links, rec["name"],
                                            {"name": n, "display_name": hit.get("display_name") or n,
                                             "data_type": hit.get("data_type") or "string", "expression": f"{l['name']}.{n}"},
                                            {"name": hit.get("display_name") or n, "description": f"取自{l['to']}"})
            if not why:
                have.add(n)
                note(f"「{w.get('title')}」的条件用到了{l['to']}的「{hit.get('display_name') or n}」:给{rec['name']}加了计算属性 {n} = {l['name']}.{n}")
            break


def _body(w: dict) -> dict:
    return {k: w.get(k) for k in ("title", "description", "owner_role", "schedule", "source", "condition",
                                  "strategies", "dedup") if w.get(k) not in (None, "")}


def stage(run_id: str, st: Any, ctx: dict) -> Iterator[dict]:
    note = st.note("schedule")
    c = _context(run_id, ctx)
    if not (c["sop_lines"] or c["rule_lines"] or c["metrics"]):
        st.set("schedule", "done", "这次没有流程卡、判定规则或指标,没有可配的定时任务", watches=0)
        yield {"stage": "schedule", "progress": 94, "message": "定时与监控:0 条"}
        return
    doc = "\n\n".join(f"【{x.get('heading') or '正文'}】\n{x['text']}" for x in ctx.get("chunks") or [])
    msgs = [{"role": "user", "content": SCHEDULE_PROMPT.format(
        doc=llm.truncate_to_tokens(doc, 9000), sops="\n".join(c["sop_lines"]) or "(无)",
        objects=c["objects_text"],
        metrics="\n".join(f"- {m}:{'、'.join(d) or '不拆'}" for m, d in c["metrics"].items()) or "(无)",
        rules="\n".join(c["rule_lines"]) or "(无)",
        actions="\n".join(f"- {n}:{sp.get('target_type') or ''},{[x.get('name') for x in sp.get('params') or []]}"
                          for n, sp in c["actions"].items()) or "(无)",
        roles="、".join(c["roles"]) or "(无)",
        reqs="\n".join(f"{r['id']}:{r['text']}" for r in ctx.get("reqs") or [] if r["kind"] == "schedule") or "(没有拆出条目)")}]
    try:
        with llmlog.feature("modeling_schedule"), llm.trace_label("配定时任务和监控"):
            res = llm.chat_json(msgs, temperature=0.1)
    except Exception as e:  # noqa: BLE001
        st.set("schedule", "done", f"没配成:{str(e)[:120]}", watches=0)
        yield {"stage": "schedule", "progress": 94, "message": "定时与监控:0 条"}
        return
    watches = [w for w in (res.get("watches") or []) if isinstance(w, dict)] if isinstance(res, dict) else []
    for w in watches:
        _lift_fields(run_id, w, c, note)
    errs = [e for w in watches for e in _problems(w, c)]
    if errs:
        note(f"{len(errs)} 处要改:{errs[0]}" + (" 等" if len(errs) > 1 else "") + ",按错误改一次")
        msgs += [{"role": "assistant", "content": jdump(res)},
                 {"role": "user", "content": "校验发现这些问题,请修正后输出完整 JSON:\n- " + "\n- ".join(errs[:15])}]
        try:
            with llmlog.feature("modeling_schedule_fix"), llm.trace_label("配定时任务和监控(按校验错误改)"):
                res2 = llm.chat_json(msgs, temperature=0)
            w2 = [w for w in (res2.get("watches") or []) if isinstance(w, dict)] if isinstance(res2, dict) else []
            for w in w2:
                _lift_fields(run_id, w, c, note)
            e2 = [e for w in w2 for e in _problems(w, c)]
            if w2 and len(e2) <= len(errs):
                watches = w2
        except Exception as e:  # noqa: BLE001
            note(f"改的时候出错:{str(e)[:80]},保留原稿")
    drafts = []
    for w in watches[:12]:
        probs = _problems(w, c)
        drafts.append({"id": new_id("wd"), "title": str(w.get("title") or "未命名监控")[:120], "body": _body(w),
                       "basis": str(w.get("basis") or "")[:300], "status": "pending",
                       "req_ids": [str(x) for x in w.get("req_ids") or [] if x][:8],
                       "issue": ";".join(probs), "weak": bool(probs)})
    from . import modeling_world
    with modeling_world.world(modeling._pending(run_id)):
        for d in drafts:
            if not d["weak"]:
                d["trial"] = modeling_world.watch_trial(d["body"])
    modeling._patch_inputs(run_id, lambda inp: inp.update(
        watch_drafts=[x for x in inp.get("watch_drafts") or [] if x.get("status") == "accepted"] + drafts))
    for d in drafts:
        note(f"「{d['title']}」:{describe(d)}" + (f"(还有问题:{d['issue']})" if d["issue"] else "")
             + (f";{d['trial'].get('summary') or d['trial'].get('error')}" if d.get("trial") else ""))
    ok = sum(1 for d in drafts if not d["weak"])
    st.set("schedule", "done", f"配了 {len(drafts)} 条定时任务 / 监控" + (f",{len(drafts) - ok} 条有问题默认不勾选" if ok < len(drafts) else ""),
           watches=len(drafts), weak=len(drafts) - ok)
    yield {"stage": "schedule", "progress": 94, "message": f"定时与监控:{len(drafts)} 条"}


def describe(d: dict) -> str:
    """一句话说清这条监控:什么时候、看什么、命中了做什么。"""
    from ..watch import cron
    b = d.get("body") or {}
    try:
        when = cron.describe(cron.normalize(b.get("schedule")))
    except Exception:  # noqa: BLE001
        when = "排程待定"
    src = b.get("source") or {}
    what = {"sop": f"跑流程卡「{src.get('sop')}」", "object": f"看「{src.get('object_type')}」",
            "metric": f"看指标「{src.get('metric')}」" + (f"(按{'、'.join(src.get('dimensions') or [])})" if src.get("dimensions") else "")
            }.get(src.get("kind"), "")
    cond = f",{b['condition']} 时" if b.get("condition") and src.get("kind") != "sop" else ""
    acts = []
    for s in b.get("strategies") or []:
        k = s.get("kind")
        acts.append({"run_sop": f"启动「{s.get('sop')}」", "notify": f"通知{s.get('role')}", "task": f"派待办给{s.get('role')}",
                     "propose_action": f"提交「{s.get('action')}」"}.get(k, k or ""))
    if src.get("kind") == "sop" and all(s.get("kind") == "run_sop" for s in b.get("strategies") or []):
        acts = []
    return f"{when}{what}{cond}" + (f",{'、'.join(acts)}" if acts else "")


def adopt(run_id: str, watch_ids: list[str]) -> dict[str, str]:
    """把勾选的草稿建成监控并启用(元素和流程卡已经先上线了)。返回 {草稿 id: 失败原因(空 = 建好了)}。"""
    from ..sop import service as sop_service
    from ..watch import service as watch_service
    want = set(watch_ids)
    out: dict[str, str] = {}
    drafts = modeling._inputs(run_id).get("watch_drafts") or []
    made: dict[str, str] = {}
    for d in drafts:
        if d["id"] not in want or d.get("status") != "pending":
            continue
        b = copy.deepcopy(d["body"])

        def sop_id(ref: str) -> str:
            hit = sop_service.resolve_published(ref)
            if hit is None:
                raise HTTPException(422, f"流程卡「{ref}」还没上线,先采纳它")
            return hit["id"]
        try:
            src = dict(b.get("source") or {})
            if src.get("kind") == "sop":
                src["sop"] = sop_id(str(src.get("sop") or ""))
            b["source"] = src
            b["strategies"] = [{**s, "sop": sop_id(str(s.get("sop") or ""))} if s.get("kind") == "run_sop" else s
                               for s in b.get("strategies") or []]
            if src.get("kind") == "metric" and service.rt_find(str(src.get("metric") or ""), "function") is None:
                raise HTTPException(422, f"指标「{src.get('metric')}」还没上线,先采纳它")
            if src.get("kind") == "object" and service.rt_find(str(src.get("object_type") or ""), "object_type") is None:
                raise HTTPException(422, f"对象「{src.get('object_type')}」还没上线,先采纳它")
            w = watch_service.create({**b, "enabled": True,
                                      "description": (b.get("description") or "") + (f"(依据:{d['basis']})" if d.get("basis") else "")})
        except HTTPException as e:
            out[d["id"]] = str(e.detail)
            continue
        except Exception as e:  # noqa: BLE001
            out[d["id"]] = str(e)[:300]
            continue
        made[d["id"]] = w["id"]
        out[d["id"]] = ""

    def keep(inp: dict) -> None:
        for d in inp.get("watch_drafts") or []:
            if d["id"] in made:
                d.update(status="accepted", watch_id=made[d["id"]], issue="")
            elif out.get(d["id"]):
                d["issue"] = out[d["id"]]
    modeling._patch_inputs(run_id, keep)
    return out