pipeline.py 26 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 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571
"""数据管道:把对象索引从后备数据源同步进来,和上一次对比出变化,并按关系物化出关系边。

业务数据永远实时查业务库 —— 这里只同步「索引」:
- 主键、显示名:问句里点名具体对象时做链接、全局搜对象;
- 关系键列:按关系的外键 / 中间表物化成 `otlg_link_edge`,多跳遍历 / 影响分析只走这张表;
- 维度属性:遍历结果按数据范围过滤、按维度分组;
- 状态属性和标了「记录历史」的属性:和上一次同步对比,变了就记进变化记录(otlg_object_change),
  每次同步记一个时间序列点(otlg_series_point)—— 这就是本体的「时间层」:
  状态变化的触发、某个时点的样子、指标的历史波动都从这里来。

跨表多跳 JOIN 在业务库上实时做既慢、跨数据源还做不了;索引表上 BFS 很便宜。
代价是有同步延迟,所以每个结果都带「数据截至」时间。
"""
from __future__ import annotations

import datetime as dt
import hashlib
import logging
import time
from typing import Any

from fastapi import HTTPException
from sqlalchemy import delete, func, insert, select

from ..core import db as core_db
from ..core import identity
from ..core.dbx import iso, jdump, jload, new_id, now, session
from ..governance import audit
from . import objects, service
from .models import LinkEdge, ObjectIndex, Pipeline
from .sqlutil import ident

log = logging.getLogger(__name__)

SCHEDULES = ("manual", "hourly", "daily")
MAX_EDGES = 500_000
_BATCH = 2000          # 批量写入:远程元数据库上逐行 INSERT 太慢


def _ws() -> str:
    return identity.current().workspace


def _type_id(ref: str) -> str:
    try:
        return objects.object_type(ref)["id"]
    except HTTPException:
        return ""


def _links_of(ot_id: str) -> list[tuple[dict, dict, str, str]]:
    """涉及这个对象类型的已发布关系:(关系, join 绑定(带 _ds_id), from 类型 id, to 类型 id)。"""
    out = []
    for lt in service.rt_by_kind("link_type"):
        jb = service.rt_binding(lt, "join")
        if not jb:
            continue
        spec = lt.get("spec") or {}
        f, t = _type_id(spec.get("from_type") or ""), _type_id(spec.get("to_type") or "")
        if f and t and ot_id in (f, t):
            out.append((lt, {**jb["ref"], "_ds_id": jb["ds_id"]}, f, t))
    return out


def _end_column(j: dict, side: str, ref: dict) -> str:
    """关系一端在这类对象上用的列:外键关系就是 from_column / to_column;中间表关系没写就是主键。"""
    return j.get(f"{side}_column") or ref["key_column"]


def _tracked(ot: dict) -> list[dict]:
    """要记历史的属性:标了 track 的(计算属性也行,同步时按对象的读取方案算出来)和带状态机的。"""
    return [p for p in (ot.get("spec") or {}).get("properties") or [] if p.get("track") or p.get("lifecycle")]


def _skeleton_columns(ot: dict, ref: dict) -> tuple[list[str], dict[str, str]]:
    """要同步的列:主键、显示列、所有关系键列、维度属性、状态与记录历史的属性。返回 (列, 列→属性名)。"""
    cols = [ref["key_column"]]
    if ref.get("label_column"):
        cols.append(ref["label_column"])
    for _, j, f, t in _links_of(ot["id"]):
        if f == ot["id"]:
            cols.append(_end_column(j, "from", ref))
        if t == ot["id"]:
            cols.append(_end_column(j, "to", ref))
    prop_cols: dict[str, str] = {}
    want = {p["name"] for p in _tracked(ot)}
    for p in (ot.get("spec") or {}).get("properties") or []:
        if p.get("is_dimension") or p.get("is_key") or p["name"] in want:
            if p.get("expression"):
                col = p["name"]                    # 计算属性:读取方案里的列名就是属性名
            else:
                col = (ref.get("columns") or {}).get(p["name"]) or (ref["key_column"] if p.get("is_key") else "")
            if col:
                prop_cols[col] = p["name"]
                cols.append(col)
    return list(dict.fromkeys(cols)), prop_cols


def _parent_labels(ot_id: str, ws: str) -> list[tuple[str, dict[str, str]]]:
    """这个对象通过外键指向的上级对象:[(外键列, {上级主键: 上级显示名})](上级要先同步过)。"""
    out = []
    with session() as s:
        for _, j, f, t in _links_of(ot_id):
            if f != ot_id or t == ot_id or j.get("via_table"):
                continue
            labels = {r.obj_key: r.label for r in s.scalars(select(ObjectIndex).where(
                ObjectIndex.workspace == ws, ObjectIndex.concept_id == t)).all()}
            out.append((j["from_column"], labels))
    return out


def _hash(props: dict) -> str:
    return hashlib.sha1(jdump(props).encode("utf-8")).hexdigest()


def _same_value(a: Any, b: Any) -> bool:
    if a == b:
        return True
    try:
        return float(a) == float(b)
    except (TypeError, ValueError):
        return str(a) == str(b)


def sync_type(type_ref: str, limit: int | None = None) -> dict:
    """同步一个对象类型的索引:对比上一次 → 变化记录 + 序列点 → 重建和它有关的关系边。"""
    from . import series
    ot = objects.object_type(type_ref)
    if objects.is_interface(ot):
        raise HTTPException(422, f"「{ot['name']}」是接口,数据在实现它的对象里,同步那些对象即可")
    b = objects.table_binding(ot)
    ref = b["ref"]
    limit = int(limit or core_db.get_config("PIPELINE_ROW_LIMIT", "20000") or 20000)
    cols, prop_cols = _skeleton_columns(ot, ref)
    # 执行器对每条查询都有行数上限(SQL_ROW_LIMIT),按主键排序分页拉,直到拉满 limit 或拉完
    from ..text2sql import executor
    page = max(1, min(int(executor.limits()[0] or 1000), limit))
    names: list[str] = []
    rows: list[list[Any]] = []
    plan = objects._plan(ot, ref)
    source = f"(SELECT {plan['select']} FROM {plan['from']})"
    while len(rows) < limit:
        sql = (f"SELECT {', '.join('t.' + ident(c) for c in cols)} FROM {source} AS t "
               f"ORDER BY t.{ident(ref['key_column'])} LIMIT {page} OFFSET {len(rows)}")
        names, chunk = objects._run(b["ds_id"], sql)
        rows += chunk
        if len(chunk) < page:
            break
    truncated = len(rows) >= limit
    rows = rows[:limit]
    ws = _ws()
    at = now()
    key_col, label_col = ref["key_column"], ref.get("label_column") or ref["key_column"]
    parents = [] if ref.get("label_column") else _parent_labels(ot["id"], ws)
    tracked = {p["name"]: p for p in _tracked(ot)}
    with session() as s:
        old = {r.obj_key: (r.props_json, r.gone, r.first_seen, r.last_changed, r.label, r.props_hash)
               for r in s.scalars(select(ObjectIndex).where(
                   ObjectIndex.workspace == ws, ObjectIndex.concept_id == ot["id"])).all()}
    first_sync = not old
    seen: set[str] = set()
    batch: list[dict] = []
    changes: list[dict] = []
    points: list[dict] = []
    for row in rows:
        raw = dict(zip(names, row))
        k = raw.get(key_col)
        if k is None or str(k)[:255] in seen:
            continue
        k = str(k)[:255]
        seen.add(k)
        lab = raw.get(label_col)
        if parents:
            # 没有名称列的对象(如「仓库 × 商品」的库存行):用它指向的上级对象名称拼一个人看得懂的名字
            lab = " · ".join(labels.get(str(raw.get(col)), str(raw.get(col)))
                             for col, labels in parents if raw.get(col) is not None) or lab
        props = {prop_cols[c]: raw.get(c) for c in prop_cols if c in raw}
        joins = {c: raw.get(c) for c in cols if c not in (key_col,)}
        prev = old.get(k)
        prev_p = ((jload(prev[0], {}) or {}).get("p") or {}) if prev else {}
        alive_before = prev is not None and not prev[1]
        changed = False
        if not alive_before and not first_sync:
            changes.append({"type_id": ot["id"], "key": k, "property": "*", "old": None, "new": "created",
                            "source": "sync", "at": at})
        for name in tracked:
            if alive_before and name in prev_p and not _same_value(prev_p.get(name), props.get(name)):
                changes.append({"type_id": ot["id"], "key": k, "property": name, "old": prev_p.get(name),
                                "new": props.get(name), "source": "sync", "at": at})
                changed = True
            if name in props:
                points.append(series.point_of(f"prop:{ot['id']}:{name}", k, props.get(name), at))
        batch.append({"workspace": ws, "concept_id": ot["id"], "obj_key": k,
                      "label": str(lab if lab not in (None, "") else k)[:255],
                      "props_json": jdump({"p": props, "j": joins}), "props_hash": _hash({"p": props, "j": joins}),
                      "gone": 0, "first_seen": prev[2] if prev and prev[2] else at,
                      "last_changed": at if (changed or not alive_before) else (prev[3] or at), "synced_at": at})
    gone = [] if truncated else [k for k, r in old.items() if k not in seen and not r[1]]
    for k in gone:
        r = old[k]
        changes.append({"type_id": ot["id"], "key": k, "property": "*", "old": "existed", "new": "removed",
                        "source": "sync", "at": at})
    for k, r in old.items():                     # 消失的对象留在索引里标 gone:变化记录、as_of 还要用到它
        if k not in seen:
            batch.append({"workspace": ws, "concept_id": ot["id"], "obj_key": k, "label": r[4],
                          "props_json": r[0], "props_hash": r[5], "gone": 1, "first_seen": r[2],
                          "last_changed": at if k in gone else r[3], "synced_at": at})
    with session() as s:
        s.execute(delete(ObjectIndex).where(ObjectIndex.workspace == ws, ObjectIndex.concept_id == ot["id"]))
        for i in range(0, len(batch), _BATCH):
            s.execute(insert(ObjectIndex), batch[i:i + _BATCH])
        s.commit()
    series.write_points([p for p in points if p])
    objects.record_changes(changes)
    edges = sum(rebuild_edges(lt, j, f, t) for lt, j, f, t in _links_of(ot["id"]))
    from . import linker
    linker.invalidate()
    return {"object_type": ot["name"], "rows": len(seen), "edges": edges, "changes": len(changes),
            "removed": len(gone), "truncated": truncated, "synced_at": iso(at)}


def touch(pending: list[dict]) -> None:
    """动作写完:把索引里这几个对象改成新值(新建的先放进索引),下一次同步就不会把同一个变化再记一遍。"""
    if not pending:
        return
    ws = _ws()
    at = now()
    with session() as s:
        for p in pending:
            r = s.scalars(select(ObjectIndex).where(ObjectIndex.workspace == ws, ObjectIndex.concept_id == p["type_id"],
                                                    ObjectIndex.obj_key == str(p["key"]))).first()
            if p["mode"] == "delete":
                if r is not None:
                    r.gone, r.last_changed = 1, at
                continue
            if p["mode"] == "create":
                if r is None and p["key"]:
                    vals = p["value"] if isinstance(p["value"], dict) else {}
                    s.add(ObjectIndex(workspace=ws, concept_id=p["type_id"], obj_key=str(p["key"])[:255],
                                      label=str(p["key"])[:255], props_json=jdump({"p": vals, "j": {}}),
                                      first_seen=at, last_changed=at, synced_at=at))
                continue
            if r is None:
                continue
            d = jload(r.props_json, {}) or {}
            pp = d.get("p") or {}
            if p["property"] in pp:
                pp[p["property"]] = p["value"]
                d["p"] = pp
                r.props_json = jdump(d)
                r.last_changed = at
        s.commit()


def _cache_rows(ws: str, type_id: str) -> list[tuple[str, dict]]:
    with session() as s:
        return [(r.obj_key, jload(r.props_json, {}) or {}) for r in s.scalars(select(ObjectIndex).where(
            ObjectIndex.workspace == ws, ObjectIndex.concept_id == type_id, ObjectIndex.gone == 0)).all()]


def _val(v: Any) -> str | None:
    if v is None or v == "":
        return None
    if isinstance(v, float) and v.is_integer():
        v = int(v)
    return str(v)


def rebuild_edges(lt: dict, join: dict, from_type: str, to_type: str) -> int:
    """按绑定物化一条关系的所有边。外键:from 的 from_column = to 的 to_column;
    中间表:中间表每一行连起 from(via_from 对上 from_column,默认主键)和 to(via_to 对上 to_column)。"""
    ws = _ws()

    def col_value(key: str, props: dict, col: str) -> str | None:
        j = props.get("j") or {}
        return _val(j[col]) if col in j else key        # 不在关系键里的就是主键列本身
    edges: list[dict] = []
    if join.get("via_table"):
        f_ref = objects.table_binding(service.rt_get(from_type))["ref"]
        t_ref = objects.table_binding(service.rt_get(to_type))["ref"]
        f_col, t_col = _end_column(join, "from", f_ref), _end_column(join, "to", t_ref)
        f_index: dict[str, list[str]] = {}
        for k, p in _cache_rows(ws, from_type):
            v = k if f_col == f_ref["key_column"] else col_value(k, p, f_col)
            if v is not None:
                f_index.setdefault(v, []).append(k)
        t_index: dict[str, list[str]] = {}
        for k, p in _cache_rows(ws, to_type):
            v = k if t_col == t_ref["key_column"] else col_value(k, p, t_col)
            if v is not None:
                t_index.setdefault(v, []).append(k)
        props = join.get("props") or {}
        sel = [join["via_from"], join["via_to"], *props.values()]
        try:
            names, rows = objects._run(int(join.get("_ds_id") or 0),
                                       f"SELECT {', '.join(ident(c) for c in dict.fromkeys(sel))} "
                                       f"FROM {ident(join['via_table'])}")
        except HTTPException as e:
            log.warning("关系「%s」读中间表失败:%s", lt["name"], e.detail)
            rows, names = [], []
        for r in rows:
            d = dict(zip(names, r))
            lp = {p: d.get(c) for p, c in props.items()}
            for fk in f_index.get(_val(d.get(join["via_from"])) or "", []):
                for tk in t_index.get(_val(d.get(join["via_to"])) or "", []):
                    edges.append({"workspace": ws, "link_id": lt["id"], "from_type": from_type, "from_key": fk,
                                  "to_type": to_type, "to_key": tk, "props_json": jdump(lp) if lp else ""})
            if len(edges) >= MAX_EDGES:
                break
    else:
        to_index: dict[str, list[str]] = {}
        for k, p in _cache_rows(ws, to_type):
            v = col_value(k, p, join["to_column"])
            if v is not None:
                to_index.setdefault(v, []).append(k)
        if to_index:
            for k, p in _cache_rows(ws, from_type):
                v = col_value(k, p, join["from_column"])
                if v is None:
                    continue
                for tk in to_index.get(v, []):
                    if from_type == to_type and tk == k:
                        continue
                    edges.append({"workspace": ws, "link_id": lt["id"], "from_type": from_type, "from_key": k,
                                  "to_type": to_type, "to_key": tk, "props_json": ""})
                if len(edges) >= MAX_EDGES:
                    break
    if len(edges) >= MAX_EDGES:
        log.warning("关系「%s」的边超过 %d 条,已截断", lt["name"], MAX_EDGES)
        edges = edges[:MAX_EDGES]
    with session() as s:
        s.execute(delete(LinkEdge).where(LinkEdge.workspace == ws, LinkEdge.link_id == lt["id"]))
        for i in range(0, len(edges), _BATCH):
            s.execute(insert(LinkEdge), edges[i:i + _BATCH])
        s.commit()
    return len(edges)


def rebuild_system_edges() -> int:
    """系统对象(预警事件 / 动作记录 / 流程运行)到业务对象的边。"""
    from . import sysobjects
    ws = _ws()
    edges = sysobjects.edges(ws)
    with session() as s:
        s.execute(delete(LinkEdge).where(LinkEdge.workspace == ws, LinkEdge.link_id.in_(list(sysobjects.LINKS))))
        for i in range(0, len(edges), _BATCH):
            s.execute(insert(LinkEdge), edges[i:i + _BATCH])
        s.commit()
    return len(edges)


# ---------------- 管道的登记与运行 ----------------
def _dict(p: Pipeline, names: dict[str, str] | None = None) -> dict:
    return {"id": p.id, "object_type_id": p.object_type_id,
            "object_type": (names or {}).get(p.object_type_id, p.object_type_id),
            "schedule": p.schedule, "row_limit": p.row_limit, "enabled": bool(p.enabled),
            "status": p.status, "last_rows": p.last_rows, "last_edges": p.last_edges,
            "last_error": p.last_error or "", "last_run_at": iso(p.last_run_at),
            "last_duration_ms": p.last_duration_ms, "created_at": iso(p.created_at)}


def _type_names() -> dict[str, str]:
    return {c["id"]: c["name"] for c in service.list_concepts(kind="object_type")}


def list_pipelines() -> list[dict]:
    names = _type_names()
    with session() as s:
        rows = s.scalars(select(Pipeline).where(Pipeline.workspace == _ws())
                         .order_by(Pipeline.created_at)).all()
        return [_dict(p, names) for p in rows]


def get(pid: str) -> Pipeline:
    with session() as s:
        p = s.get(Pipeline, pid)
        if p is None or p.workspace != _ws():
            raise HTTPException(404, "数据管道不存在")
        s.expunge(p)
        return p


def create(object_type: str, schedule: str = "manual", row_limit: int = 0) -> dict:
    ot = objects.object_type(object_type)
    objects.table_binding(ot)
    if schedule not in SCHEDULES:
        raise HTTPException(422, f"调度只能是 {'/'.join(SCHEDULES)}")
    with session() as s:
        dup = s.scalars(select(Pipeline).where(Pipeline.workspace == _ws(),
                                               Pipeline.object_type_id == ot["id"])).first()
        if dup:
            raise HTTPException(409, f"「{ot['name']}」已经有数据管道了")
        p = Pipeline(id=new_id("pl"), workspace=_ws(), object_type_id=ot["id"], schedule=schedule,
                     row_limit=int(row_limit or 0), created_by=identity.current().id)
        s.add(p)
        s.commit()
        out = _dict(p, {ot["id"]: ot["name"]})
    audit.record("pipeline.create", "pipeline", out["id"], f"新建数据管道「{ot['name']}」({schedule})")
    return out


def update(pid: str, *, schedule: str | None = None, row_limit: int | None = None,
           enabled: bool | None = None) -> dict:
    get(pid)
    with session() as s:
        p = s.get(Pipeline, pid)
        if schedule is not None:
            if schedule not in SCHEDULES:
                raise HTTPException(422, f"调度只能是 {'/'.join(SCHEDULES)}")
            p.schedule = schedule
        if row_limit is not None:
            p.row_limit = max(0, int(row_limit))
        if enabled is not None:
            p.enabled = 1 if enabled else 0
        s.commit()
        return _dict(p, _type_names())


def delete_pipeline(pid: str) -> None:
    p = get(pid)
    with session() as s:
        s.execute(delete(Pipeline).where(Pipeline.id == pid))
        s.execute(delete(ObjectIndex).where(ObjectIndex.workspace == p.workspace,
                                              ObjectIndex.concept_id == p.object_type_id))
        s.execute(delete(LinkEdge).where(LinkEdge.workspace == p.workspace,
                                         (LinkEdge.from_type == p.object_type_id)
                                         | (LinkEdge.to_type == p.object_type_id)))
        s.commit()
    audit.record("pipeline.delete", "pipeline", pid, "删除数据管道(骨架与关系边一并清除)")


def run(pid: str) -> dict:
    p = get(pid)
    started = time.time()
    with session() as s:
        row = s.get(Pipeline, pid)
        row.status = "running"
        s.commit()
    try:
        out = sync_type(p.object_type_id, p.row_limit or None)
        status, err = "ok", ""
    except HTTPException as e:
        out, status, err = {}, "failed", str(e.detail)
    except Exception as e:  # noqa: BLE001
        log.exception("数据管道 %s 运行失败", pid)
        out, status, err = {}, "failed", str(e)[:500]
    ms = int((time.time() - started) * 1000)
    with session() as s:
        row = s.get(Pipeline, pid)
        row.status = status
        row.last_error = err
        row.last_run_at = now()
        row.last_duration_ms = ms
        if status == "ok":
            row.last_rows = out["rows"]
            row.last_edges = out["edges"]
        s.commit()
        res = _dict(row, _type_names())
    audit.record("pipeline.run", "pipeline", pid,
                 f"数据管道同步「{res['object_type']}」:"
                 + (f"{out['rows']} 个对象、{out['edges']} 条关系边,{ms} ms" if status == "ok" else f"失败:{err}"),
                 after=out or {"error": err})
    return {**res, "result": out}


def ensure_all(schedule: str = "manual") -> dict:
    """给所有已映射、还没有管道的对象类型建管道。"""
    have = {p["object_type_id"] for p in list_pipelines()}
    created = []
    for c in service.list_concepts(kind="object_type"):
        if c["id"] in have or not c.get("mapped") or c.get("abstract") or not service.rt_get(c["id"]):
            continue
        try:
            created.append(create(c["id"], schedule)["id"])
        except HTTPException:
            continue
    return {"created": created}


def run_all_events():
    """后台任务:逐条同步,yield 进度。每条都会重建相关的边,所以跑完一轮两端都在的边都齐了。"""
    items = [p for p in list_pipelines() if p["enabled"]]
    # 上级对象先同步(外键指向别人的少的排前面),下级拼显示名时才取得到上级的名称
    ups = {p["object_type_id"]: sum(1 for _, _, f, t in _links_of(p["object_type_id"])
                                    if f == p["object_type_id"] and t != f) for p in items}
    items.sort(key=lambda p: ups.get(p["object_type_id"], 0))
    ok = 0
    for i, p in enumerate(items, 1):
        r = run(p["id"])
        ok += r["status"] == "ok"
        yield {"stage": "pipeline", "progress": int(i / max(1, len(items)) * 100),
               "message": f"{r['object_type']}:{'%d 个对象、%d 条边' % (r['last_rows'], r['last_edges']) if r['status'] == 'ok' else r['last_error']}"}
    try:
        sys_edges = rebuild_system_edges()
    except Exception:  # noqa: BLE001  系统对象的边补不上不影响业务对象的同步
        log.exception("重建系统对象的关系边失败")
        sys_edges = 0
    yield {"stage": "done", "progress": 100, "message": f"同步完成 {ok}/{len(items)}",
           "result": {"ok": ok, "total": len(items), "system_edges": sys_edges}}


def run_all() -> dict:
    out = list(run_all_events())
    return out[-1]["result"]


def status() -> dict:
    ws = _ws()
    with session() as s:
        objs = s.scalar(select(func.count(ObjectIndex.id)).where(ObjectIndex.workspace == ws,
                                                                 ObjectIndex.gone == 0)) or 0
        edges = s.scalar(select(func.count(LinkEdge.id)).where(LinkEdge.workspace == ws)) or 0
        last = s.scalar(select(func.max(ObjectIndex.synced_at)).where(ObjectIndex.workspace == ws))
    return {"objects": int(objs), "edges": int(edges), "synced_at": iso(last)}


def dataset(type_ref: str, q: str = "", limit: int = 50, offset: int = 0) -> dict:
    """本体数据集:浏览某个对象类型已同步的骨架。"""
    ot = objects.object_type(type_ref)
    ws = _ws()
    with session() as s:
        stmt = select(ObjectIndex).where(ObjectIndex.workspace == ws, ObjectIndex.gone == 0,
                                         ObjectIndex.concept_id == ot["id"])
        if q:
            stmt = stmt.where(ObjectIndex.label.like(f"%{q}%") | (ObjectIndex.obj_key == q))
        total = s.scalar(select(func.count()).select_from(stmt.subquery())) or 0
        rows = s.scalars(stmt.order_by(ObjectIndex.id).offset(offset).limit(min(limit, 500))).all()
        items = [{"key": r.obj_key, "label": r.label, "properties": (jload(r.props_json, {}) or {}).get("p") or {},
                  "synced_at": iso(r.synced_at)} for r in rows]
    return {"object_type": {"id": ot["id"], "name": ot["name"]}, "total": int(total), "items": items}


def reap_stale() -> int:
    """进程重启后,上次没跑完的管道 / 业务建模还标着 running:改成失败,免得界面永远转圈、定时永远跳过。"""
    from sqlalchemy import update
    from .models import ModelRun
    with session() as s:
        n = s.execute(update(Pipeline).where(Pipeline.status == "running").values(
            status="failed", last_error="服务重启,同步中断")).rowcount or 0
        n += s.execute(update(ModelRun).where(ModelRun.status == "running").values(
            status="failed", error="服务重启,建模中断,可以重新运行")).rowcount or 0
        s.commit()
    return n


# ---------------- 定时 ----------------
def _due(p: Pipeline, at: dt.datetime) -> bool:
    if not p.enabled or p.schedule == "manual" or p.status == "running":
        return False
    if p.last_run_at is None:
        return True
    gap = dt.timedelta(hours=1) if p.schedule == "hourly" else dt.timedelta(days=1)
    return at - p.last_run_at >= gap


def tick(at: dt.datetime | None = None) -> list[str]:
    at = at or dt.datetime.now()
    with session() as s:
        items = [(p.id, p.workspace) for p in s.scalars(select(Pipeline)).all() if _due(p, at)]
    fired = []
    for pid, ws in items:
        tok = identity.set_current(identity.Actor(id="system", name="系统 · 数据管道", kind="system",
                                                  roles=["admin"], workspace=ws))
        try:
            run(pid)
            fired.append(pid)
        except Exception:  # noqa: BLE001
            log.exception("定时数据管道失败 %s", pid)
        finally:
            identity.reset(tok)
    return fired