service.py 26.2 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 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
"""本体内核的读写:概念、绑定、证据、发布与回滚、引用与血缘。

两份数据:
- **工作副本**(Concept 的各列 + Binding 表):建设台编辑的就是它;
- **已发布副本**(`published_json`):运行时唯一读取来源。发布时把工作副本冻结进去。
这样改到一半的指标口径不会影响正在被问的问题,发布前还能跑评测把关。
"""
from __future__ import annotations

import contextlib
import contextvars
import logging
import threading
import time
from typing import Any, Callable

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

from ..core import identity
from ..core.dbx import iso, jdump, jload, new_id, now, session
from ..governance import audit
from . import schema
from .models import Binding, Concept, Evidence, Revision

log = logging.getLogger(__name__)


# ---------------- 序列化 ----------------
def _binding_dict(b: Binding) -> dict:
    return {"id": b.id, "concept_id": b.concept_id, "ds_id": b.ds_id,
            "target_kind": b.target_kind, "ref": jload(b.ref_json, {}),
            "updated_at": iso(b.updated_at)}


def _concept_dict(c: Concept, brief: bool = False) -> dict:
    out = {"id": c.id, "kind": c.kind, "kind_label": schema.KINDS.get(c.kind, {}).get("label", c.kind),
           "name": c.name, "display_name": c.display_name or "",
           "description": c.description or "", "synonyms": jload(c.synonyms_json, []),
           "parent_id": c.parent_id or "", "status": c.status, "dirty": bool(c.dirty),
           "version": c.version, "origin": c.origin, "published": bool(c.published_json),
           "created_by": c.created_by, "created_at": iso(c.created_at),
           "updated_at": iso(c.updated_at)}
    if not brief:
        out["spec"] = jload(c.spec_json, {})
    return out


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


# ---------------- 运行时视图(已发布) ----------------
_rt_cache: dict[str, tuple[float, dict[str, dict]]] = {}
_rt_lock = threading.Lock()
_RT_TTL = 30.0


# 评测「待发布版本」时,运行时临时改读工作副本(含未发布的修改)
_draft_mode: contextvars.ContextVar[bool] = contextvars.ContextVar("onto_draft_mode", default=False)


@contextlib.contextmanager
def draft_runtime():
    tok = _draft_mode.set(True)
    try:
        yield
    finally:
        _draft_mode.reset(tok)


def invalidate_runtime() -> None:
    with _rt_lock:
        _rt_cache.clear()


def runtime(workspace: str | None = None) -> dict[str, dict]:
    """已发布、未废弃的概念:id → 概念 dict(含 spec 与 bindings)。"""
    ws = workspace or _ws()
    if _draft_mode.get():
        with session() as s:
            return {c.id: _publish_copy(s, c) for c in s.scalars(select(Concept).where(
                Concept.workspace == ws, Concept.status != "deprecated")).all()}
    with _rt_lock:
        hit = _rt_cache.get(ws)
        if hit and time.time() - hit[0] < _RT_TTL:
            return hit[1]
    with session() as s:
        rows = s.scalars(select(Concept).where(
            Concept.workspace == ws, Concept.status == "published",
            Concept.published_json != "")).all()
        out = {}
        for c in rows:
            d = jload(c.published_json, None)
            if isinstance(d, dict):
                out[c.id] = d
    with _rt_lock:
        _rt_cache[ws] = (time.time(), out)
    return out


def rt_get(cid: str) -> dict | None:
    return runtime().get(cid)


def rt_find(name: str, kind: str | None = None) -> dict | None:
    """按名称 / 显示名 / 同义词在已发布概念里找。也接受直接传 id。"""
    if not name:
        return None
    rt = runtime()
    if name in rt and (kind is None or rt[name]["kind"] == kind):
        return rt[name]
    n = name.strip().lower()
    for c in rt.values():
        if kind and c["kind"] != kind:
            continue
        names = [c["name"], c.get("display_name") or ""] + list(c.get("synonyms") or [])
        if any(n == x.strip().lower() for x in names if x):
            return c
    return None


def rt_by_kind(kind: str) -> list[dict]:
    return [c for c in runtime().values() if c["kind"] == kind]


def rt_binding(concept: dict, target_kind: str, ds_id: int | None = None) -> dict | None:
    for b in concept.get("bindings") or []:
        if b["target_kind"] == target_kind and (ds_id is None or b["ds_id"] == ds_id):
            return b
    return None


# ---------------- 查询 ----------------
def list_concepts(kind: str = "", status: str = "", q: str = "", limit: int = 1000) -> list[dict]:
    with session() as s:
        stmt = select(Concept).where(Concept.workspace == _ws())
        if kind:
            stmt = stmt.where(Concept.kind == kind)
        if status == "dirty":
            stmt = stmt.where(Concept.dirty == 1)
        elif status:
            stmt = stmt.where(Concept.status == status)
        else:
            stmt = stmt.where(Concept.status != "deprecated")
        if q:
            like = f"%{q}%"
            stmt = stmt.where(or_(Concept.name.like(like), Concept.display_name.like(like),
                                  Concept.synonyms_json.like(like), Concept.description.like(like)))
        rows = s.scalars(stmt.order_by(Concept.kind, Concept.name).limit(limit)).all()
        return [_concept_dict(c, brief=True) for c in rows]


def stats() -> dict:
    with session() as s:
        rows = s.execute(select(Concept.kind, Concept.status, func.count(Concept.id))
                         .where(Concept.workspace == _ws())
                         .group_by(Concept.kind, Concept.status)).all()
        dirty = s.scalar(select(func.count(Concept.id)).where(
            Concept.workspace == _ws(), Concept.dirty == 1)) or 0
        rev = s.scalar(select(func.max(Revision.revision)).where(Revision.workspace == _ws())) or 0
    by_kind: dict[str, dict] = {}
    for k, st, n in rows:
        by_kind.setdefault(k, {"total": 0})
        by_kind[k][st] = int(n)
        if st != "deprecated":
            by_kind[k]["total"] += int(n)
    return {"by_kind": by_kind, "dirty": int(dirty), "revision": int(rev),
            "kinds": [{"kind": k, **v} for k, v in schema.KINDS.items()]}


def _load(s, cid: str) -> Concept:
    c = s.get(Concept, cid)
    if c is None or c.workspace != _ws():
        raise HTTPException(404, "概念不存在")
    return c


def get_concept(cid: str) -> dict:
    with session() as s:
        c = _load(s, cid)
        out = _concept_dict(c)
        out["bindings"] = [_binding_dict(b) for b in s.scalars(
            select(Binding).where(Binding.concept_id == cid)).all()]
        out["evidence"] = [{"id": e.id, "doc_id": e.doc_id, "chunk_id": e.chunk_id,
                            "heading": e.heading, "snippet": e.snippet,
                            "graph_entity_id": e.graph_entity_id}
                           for e in s.scalars(select(Evidence).where(
                               Evidence.concept_id == cid).order_by(Evidence.id)).all()]
        out["published_copy"] = jload(c.published_json, None)
    return out


def find(name: str, kind: str | None = None) -> dict | None:
    """在工作副本里按名称 / 同义词找(建设期用;运行时请用 rt_find)。"""
    n = (name or "").strip()
    if not n:
        return None
    with session() as s:
        stmt = select(Concept).where(Concept.workspace == _ws(), Concept.status != "deprecated")
        if kind:
            stmt = stmt.where(Concept.kind == kind)
        exact = s.scalars(stmt.where(or_(Concept.name == n, Concept.display_name == n))).first()
        if exact:
            return _concept_dict(exact)
        for c in s.scalars(stmt.where(Concept.synonyms_json.like(f"%{n}%"))).all():
            if n in jload(c.synonyms_json, []):
                return _concept_dict(c)
    return None


# ---------------- 写入 ----------------
def _clean_synonyms(v: Any, name: str) -> list[str]:
    items = schema._list_str(v)
    out: list[str] = []
    for x in items:
        if x != name and x not in out:
            out.append(x)
    return out[:50]


def create_concept(kind: str, name: str, *, display_name: str = "", description: str = "",
                   synonyms: Any = None, spec: dict | None = None, parent_id: str = "",
                   origin: str = "user", evidence: list[dict] | None = None,
                   bindings: list[dict] | None = None) -> dict:
    name = (name or "").strip()
    if not name:
        raise HTTPException(422, "概念名称不能为空")
    try:
        spec = schema.normalize_spec(kind, spec)
    except schema.SpecError as e:
        raise HTTPException(422, str(e)) from e
    if find(name, kind):
        raise HTTPException(409, f"已存在同名的{schema.KINDS[kind]['label']}「{name}」")
    actor = identity.current()
    cid = new_id(kind[:3])
    with session() as s:
        c = Concept(id=cid, workspace=actor.workspace, kind=kind, name=name[:255],
                    display_name=(display_name or "")[:255], description=description or "",
                    synonyms_json=jdump(_clean_synonyms(synonyms, name)),
                    parent_id=parent_id or "", spec_json=jdump(spec), status="draft",
                    dirty=1, origin=origin, created_by=actor.id)
        s.add(c)
        s.commit()
    for b in bindings or []:
        set_binding(cid, int(b.get("ds_id") or 0), b.get("target_kind") or
                    schema.BINDING_KINDS.get(kind, ""), b.get("ref") or {}, _audit=False)
    if evidence:
        add_evidence(cid, evidence)
    out = get_concept(cid)
    audit.record("concept.create", "concept", cid, f"新建{out['kind_label']}「{name}」",
                 after=out)
    return out


def update_concept(cid: str, **fields: Any) -> dict:
    before = get_concept(cid)
    with session() as s:
        c = _load(s, cid)
        if "name" in fields and fields["name"] is not None:
            nm = str(fields["name"]).strip()
            if not nm:
                raise HTTPException(422, "概念名称不能为空")
            other = find(nm, c.kind)
            if other and other["id"] != cid:
                raise HTTPException(409, f"已存在同名概念「{nm}」")
            c.name = nm[:255]
        for key in ("display_name", "description", "parent_id"):
            if key in fields and fields[key] is not None:
                setattr(c, key, str(fields[key]))
        if "synonyms" in fields and fields["synonyms"] is not None:
            c.synonyms_json = jdump(_clean_synonyms(fields["synonyms"], c.name))
        if "spec" in fields and fields["spec"] is not None:
            try:
                c.spec_json = jdump(schema.normalize_spec(c.kind, fields["spec"]))
            except schema.SpecError as e:
                raise HTTPException(422, str(e)) from e
        c.version += 1
        c.dirty = 1
        if c.status == "deprecated" and fields.get("restore"):
            c.status = "draft"
        s.commit()
    after = get_concept(cid)
    audit.record("concept.update", "concept", cid, f"修改{after['kind_label']}「{after['name']}」",
                 before=before, after=after)
    return after


def deprecate_concept(cid: str, reason: str = "") -> dict:
    before = get_concept(cid)
    with session() as s:
        c = _load(s, cid)
        c.status = "deprecated"
        c.dirty = 1
        s.commit()
    invalidate_runtime()
    audit.record("concept.deprecate", "concept", cid,
                 f"废弃「{before['name']}」" + (f":{reason}" if reason else ""), before=before)
    return get_concept(cid)


def delete_concept(cid: str) -> None:
    with session() as s:
        c = _load(s, cid)
        if c.published_json:
            raise HTTPException(409, "已发布过的概念不能删除,只能废弃(保证历史答案仍可追溯)")
        snap = _concept_dict(c)
        s.execute(delete(Binding).where(Binding.concept_id == cid))
        s.execute(delete(Evidence).where(Evidence.concept_id == cid))
        s.delete(c)
        s.commit()
    audit.record("concept.delete", "concept", cid, f"删除草稿「{snap['name']}」", before=snap)


def _touch(cid: str) -> None:
    with session() as s:
        c = s.get(Concept, cid)
        if c is not None:
            c.dirty = 1
            c.version += 1
            s.commit()


# ---------------- 绑定 ----------------
def list_bindings(cid: str) -> list[dict]:
    with session() as s:
        return [_binding_dict(b) for b in s.scalars(
            select(Binding).where(Binding.concept_id == cid)).all()]


def set_binding(cid: str, ds_id: int, target_kind: str, ref: dict, _audit: bool = True) -> dict:
    try:
        ref = schema.normalize_binding(target_kind, ref)
    except schema.SpecError as e:
        raise HTTPException(422, str(e)) from e
    with session() as s:
        _load(s, cid)
        b = s.scalars(select(Binding).where(Binding.concept_id == cid, Binding.ds_id == ds_id,
                                            Binding.target_kind == target_kind)).first()
        before = _binding_dict(b) if b else None
        if b is None:
            b = Binding(id=new_id("bd"), workspace=_ws(), concept_id=cid, ds_id=ds_id,
                        target_kind=target_kind)
            s.add(b)
        b.ref_json = jdump(ref)
        s.commit()
        out = _binding_dict(b)
    _touch(cid)
    if _audit:
        audit.record("binding.set", "concept", cid, f"设置数据绑定(数据源 {ds_id})",
                     before=before, after=out)
    return out


def delete_binding(binding_id: str) -> None:
    with session() as s:
        b = s.get(Binding, binding_id)
        if b is None:
            raise HTTPException(404, "绑定不存在")
        snap, cid = _binding_dict(b), b.concept_id
        s.delete(b)
        s.commit()
    _touch(cid)
    audit.record("binding.delete", "concept", cid, "删除数据绑定", before=snap)


# ---------------- 证据 ----------------
def add_evidence(cid: str, items: list[dict]) -> int:
    n = 0
    with session() as s:
        have = {(e.chunk_id, e.graph_entity_id) for e in s.scalars(
            select(Evidence).where(Evidence.concept_id == cid)).all()}
        for it in items or []:
            key = (str(it.get("chunk_id") or ""), str(it.get("graph_entity_id") or ""))
            if key in have or key == ("", ""):
                continue
            have.add(key)
            s.add(Evidence(workspace=_ws(), concept_id=cid, doc_id=int(it.get("doc_id") or 0),
                           chunk_id=key[0], heading=str(it.get("heading") or "")[:500],
                           snippet=str(it.get("snippet") or "")[:2000], graph_entity_id=key[1]))
            n += 1
        s.commit()
    return n


def evidence_for(cids: list[str]) -> dict[str, list[dict]]:
    if not cids:
        return {}
    with session() as s:
        out: dict[str, list[dict]] = {}
        for e in s.scalars(select(Evidence).where(Evidence.concept_id.in_(cids))).all():
            out.setdefault(e.concept_id, []).append(
                {"doc_id": e.doc_id, "chunk_id": e.chunk_id, "heading": e.heading,
                 "snippet": e.snippet})
        return out


# ---------------- 发布 / 回滚 ----------------
# 发布闸门:fn(diff) -> (ok, message)。评测模块会注册一个「回归不能掉点」的闸门。
_gates: list[Callable[[dict], tuple[bool, str]]] = []


def register_publish_gate(fn: Callable[[dict], tuple[bool, str]]) -> None:
    _gates.append(fn)


def _publish_copy(s, c: Concept) -> dict:
    d = _concept_dict(c)
    d["bindings"] = [_binding_dict(b) for b in s.scalars(
        select(Binding).where(Binding.concept_id == c.id)).all()]
    d.pop("published", None)
    d.pop("dirty", None)
    return d


def _last_snapshot(s) -> tuple[int, dict]:
    r = s.scalars(select(Revision).where(Revision.workspace == _ws())
                  .order_by(Revision.revision.desc())).first()
    return (r.revision, jload(r.snapshot_json, {})) if r else (0, {})


def _diff(prev: dict, cur: dict) -> dict:
    added = [{"id": k, "name": v["name"], "kind": v["kind"]} for k, v in cur.items() if k not in prev]
    removed = [{"id": k, "name": v["name"], "kind": v["kind"]} for k, v in prev.items() if k not in cur]
    changed = []
    for k, v in cur.items():
        if k in prev:
            fields = [f for f in ("name", "display_name", "description", "synonyms", "spec", "bindings")
                      if jdump(prev[k].get(f)) != jdump(v.get(f))]
            if fields:
                changed.append({"id": k, "name": v["name"], "kind": v["kind"], "fields": fields})
    return {"added": added, "removed": removed, "changed": changed}


def pending_diff() -> dict:
    """如果现在发布,会变什么。"""
    with session() as s:
        _, prev = _last_snapshot(s)
        cur = dict(prev)
        for c in s.scalars(select(Concept).where(Concept.workspace == _ws(),
                                                 Concept.dirty == 1)).all():
            if c.status == "deprecated":
                cur.pop(c.id, None)
            else:
                cur[c.id] = _publish_copy(s, c)
    return _diff(prev, cur)


def publish(note: str = "", concept_ids: list[str] | None = None, force: bool = False) -> dict:
    actor = identity.current()
    diff = pending_diff()
    if not (diff["added"] or diff["removed"] or diff["changed"]):
        raise HTTPException(409, "没有待发布的变更")
    if not force:
        for gate in _gates:
            ok, msg = gate(diff)
            if not ok:
                raise HTTPException(412, f"发布被闸门拦下:{msg}")
    with session() as s:
        rev, prev = _last_snapshot(s)
        stmt = select(Concept).where(Concept.workspace == actor.workspace, Concept.dirty == 1)
        if concept_ids:
            stmt = stmt.where(Concept.id.in_(concept_ids))
        snapshot = dict(prev)
        for c in s.scalars(stmt).all():
            if c.status == "deprecated":
                snapshot.pop(c.id, None)
                c.published_json = ""
            else:
                copy = _publish_copy(s, c)
                copy["status"] = "published"
                c.status = "published"
                c.published_json = jdump(copy)
                snapshot[c.id] = copy
            c.dirty = 0
        real_diff = _diff(prev, snapshot)
        r = Revision(workspace=actor.workspace, revision=rev + 1, note=note or "",
                     snapshot_json=jdump(snapshot), diff_json=jdump(real_diff),
                     published_by=actor.id)
        s.add(r)
        s.commit()
        out = {"revision": r.revision, "note": r.note, "diff": real_diff,
               "concepts": len(snapshot)}
    invalidate_runtime()
    audit.record("ontology.publish", "revision", str(out["revision"]),
                 f"发布本体第 {out['revision']} 版:新增 {len(real_diff['added'])},"
                 f"修改 {len(real_diff['changed'])},移除 {len(real_diff['removed'])}"
                 + (f"({note})" if note else ""), after=real_diff)
    return out


def list_revisions() -> list[dict]:
    with session() as s:
        rows = s.scalars(select(Revision).where(Revision.workspace == _ws())
                         .order_by(Revision.revision.desc())).all()
        return [{"revision": r.revision, "note": r.note, "diff": jload(r.diff_json, {}),
                 "published_by": r.published_by, "created_at": iso(r.created_at),
                 "concepts": len(jload(r.snapshot_json, {}))} for r in rows]


def get_revision(rev: int) -> dict:
    with session() as s:
        r = s.scalars(select(Revision).where(Revision.workspace == _ws(),
                                             Revision.revision == rev)).first()
        if r is None:
            raise HTTPException(404, "版本不存在")
        return {"revision": r.revision, "note": r.note, "snapshot": jload(r.snapshot_json, {}),
                "diff": jload(r.diff_json, {}), "published_by": r.published_by,
                "created_at": iso(r.created_at)}


def rollback(rev: int) -> dict:
    """回滚到某个版本:工作副本与发布副本都恢复成那一版,然后记为一个新版本。"""
    target = get_revision(rev)["snapshot"]
    actor = identity.current()
    with session() as s:
        cur_rev, prev = _last_snapshot(s)
        for cid, d in target.items():
            c = s.get(Concept, cid)
            if c is None:
                c = Concept(id=cid, workspace=actor.workspace, kind=d["kind"],
                            origin=d.get("origin") or "user", created_by=actor.id)
                s.add(c)
            c.name = d["name"]
            c.display_name = d.get("display_name") or ""
            c.description = d.get("description") or ""
            c.synonyms_json = jdump(d.get("synonyms") or [])
            c.parent_id = d.get("parent_id") or ""
            c.spec_json = jdump(d.get("spec") or {})
            c.status = "published"
            c.dirty = 0
            c.version = (c.version or 0) + 1
            c.published_json = jdump(d)
            s.execute(delete(Binding).where(Binding.concept_id == cid))
            for b in d.get("bindings") or []:
                s.add(Binding(id=b.get("id") or new_id("bd"), workspace=actor.workspace,
                              concept_id=cid, ds_id=int(b.get("ds_id") or 0),
                              target_kind=b["target_kind"], ref_json=jdump(b.get("ref") or {})))
        for cid in set(prev) - set(target):
            c = s.get(Concept, cid)
            if c is not None:
                c.status = "deprecated"
                c.published_json = ""
                c.dirty = 0
        diff = _diff(prev, target)
        r = Revision(workspace=actor.workspace, revision=cur_rev + 1,
                     note=f"回滚到第 {rev} 版", snapshot_json=jdump(target),
                     diff_json=jdump(diff), published_by=actor.id)
        s.add(r)
        s.commit()
        new_rev = r.revision
    invalidate_runtime()
    audit.record("ontology.rollback", "revision", str(new_rev), f"回滚到第 {rev} 版", after=diff)
    return {"revision": new_rev, "diff": diff}


# ---------------- 引用 / 影响 / 血缘 ----------------
# 其他模块(能力、SOP、编排)注册自己的引用查找:fn(concept_id, names) -> [{type,id,name}]
_usage_providers: list[Callable[[str, list[str]], list[dict]]] = []


def register_usage_provider(fn: Callable[[str, list[str]], list[dict]]) -> None:
    _usage_providers.append(fn)


def usage(cid: str) -> list[dict]:
    c = get_concept(cid)
    out: list[dict] = []
    with session() as s:
        for other in s.scalars(select(Concept).where(
                Concept.workspace == _ws(), Concept.id != cid,
                Concept.spec_json.like(f"%{cid}%"))).all():
            out.append({"type": "concept", "id": other.id, "name": other.name,
                        "kind": other.kind})
    names = [c["name"]] + list(c.get("synonyms") or [])
    for fn in _usage_providers:
        try:
            out.extend(fn(cid, names))
        except Exception:  # noqa: BLE001
            log.debug("引用查找失败", exc_info=True)
    return out


def lineage(cid: str) -> dict:
    """血缘图:概念 → 引用的概念 → 绑定的表/列 → 数据源;概念 → 文档出处。"""
    from ..text2sql import semantic
    nodes: dict[str, dict] = {}
    edges: list[dict] = []

    def node(nid: str, label: str, kind: str) -> None:
        nodes.setdefault(nid, {"id": nid, "label": label, "kind": kind})

    def walk(concept_id: str, depth: int) -> None:
        try:
            c = get_concept(concept_id)
        except HTTPException:
            return
        node(concept_id, c["name"], c["kind"])
        if depth > 2:
            return
        for key, val in (c.get("spec") or {}).items():
            if isinstance(val, str) and val and val != concept_id:
                with session() as s:
                    ref = s.get(Concept, val)
                if ref is not None:
                    walk(val, depth + 1)
                    edges.append({"from": concept_id, "to": val, "label": key})
        for b in c.get("bindings") or []:
            ref = b["ref"]
            table = ref.get("table") or ref.get("base_table")
            ds = semantic.get_datasource(b["ds_id"]) if b["ds_id"] else None
            ds_node = f"ds:{b['ds_id']}"
            node(ds_node, ds["name"] if ds else f"数据源 {b['ds_id']}", "datasource")
            if table:
                tnode = f"table:{b['ds_id']}:{table}"
                node(tnode, table, "table")
                edges.append({"from": concept_id, "to": tnode, "label": "绑定"})
                edges.append({"from": tnode, "to": ds_node, "label": "位于"})
                cols = [ref.get("key_column"), ref.get("label_column"), ref.get("time_column"),
                        ref.get("object_key_column"), *(ref.get("columns") or {}).values(),
                        *(ref.get("dimensions") or {}).values()]
                for col in _expr_columns(ref.get("expression") or "") + [x for x in cols if x]:
                    cnode = f"col:{b['ds_id']}:{table}.{col}"
                    node(cnode, f"{table}.{col}", "column")
                    edges.append({"from": tnode, "to": cnode, "label": "列"})
        for e in (c.get("evidence") or [])[:8]:
            dnode = f"doc:{e['doc_id']}"
            node(dnode, e.get("heading") or f"文档 {e['doc_id']}", "document")
            edges.append({"from": concept_id, "to": dnode, "label": "出处"})

    walk(cid, 0)
    uniq = {(e["from"], e["to"], e["label"]): e for e in edges}
    return {"nodes": list(nodes.values()), "edges": list(uniq.values())}


def _expr_columns(expr: str) -> list[str]:
    if not expr:
        return []
    try:
        import sqlglot
        from sqlglot import exp
        tree = sqlglot.parse_one(f"SELECT {expr}", read="mysql")
        return sorted({c.name for c in tree.find_all(exp.Column) if c.name})
    except Exception:  # noqa: BLE001
        return []


def impact(cid: str) -> dict:
    """改这个概念会波及什么:直接引用它的一切 + 已发布状态 + 绑定。"""
    c = get_concept(cid)
    refs = usage(cid)
    by_type: dict[str, int] = {}
    for r in refs:
        by_type[r["type"]] = by_type.get(r["type"], 0) + 1
    return {"concept": {"id": cid, "name": c["name"], "kind": c["kind"],
                        "status": c["status"]},
            "references": refs, "by_type": by_type,
            "bindings": c.get("bindings") or [],
            "risk": "high" if len(refs) >= 5 else "medium" if refs else "low"}