service.py
38.3 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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
"""本体内核的读写:概念、绑定、证据、发布与回滚、引用与血缘。
两份数据:
- **工作副本**(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 envs, 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:
spec = jload(c.spec_json, {})
out = {"id": c.id, "kind": c.kind, "kind_label": schema.kind_label(c.kind, spec),
"category": spec.get("category", "") if c.kind == "function" else "",
"object_type": (spec.get("object_type") or spec.get("target_type") or "")
if c.kind in ("function", "action") else "",
"domain": spec.get("domain", ""),
"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"] = spec
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
# 预演(SOP 试运行、单步试跑、监控试扫描、动作预览、评测「待发布版本」)时,运行时改读工作副本(含草稿)。
# 值是这次预演自己的缓存 {workspace: {id: 概念}},None 表示正常模式;正式运行永远只认已发布的。
_draft_mode: contextvars.ContextVar[dict | None] = contextvars.ContextVar("onto_draft_mode", default=None)
@contextlib.contextmanager
def draft_runtime():
if _draft_mode.get() is not None: # 已在预演里(如子流程):沿用同一份缓存
yield
return
tok = _draft_mode.set({})
try:
yield
finally:
_draft_mode.reset(tok)
def in_draft_mode() -> bool:
return _draft_mode.get() is not None
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()
draft_cache = _draft_mode.get()
if draft_cache is not None:
if ws not in draft_cache:
with session() as s:
out = {}
for c in s.scalars(select(Concept).where(Concept.workspace == ws,
Concept.status != "deprecated")).all():
try:
out[c.id] = _publish_copy(s, c)
except Exception: # noqa: BLE001 坏草稿不拖垮整次预演
log.warning("预演时读取草稿 %s 失败", c.id, exc_info=True)
draft_cache[ws] = out
return draft_cache[ws]
with _rt_lock:
hit = _rt_cache.get(f"{envs.current()}:{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[f"{envs.current()}:{ws}"] = (time.time(), out)
return out
def rt_get(cid: str) -> dict | None:
return runtime().get(cid)
def _match_kind(c: dict, kind: str | None, category: str | None) -> bool:
if kind and c["kind"] != kind:
return False
if category and (c.get("spec") or {}).get("category") != category:
return False
return True
def rt_find(name: str, kind: str | None = None, category: str | None = None) -> dict | None:
"""按名称 / 显示名 / 同义词在已发布概念里找。也接受直接传 id。
函数再按 category 细分:rt_find("销售额", "function", "aggregate"),简写 rt_fn(name, category)。
"""
if not name:
return None
rt = runtime()
if name in rt and _match_kind(rt[name], kind, category):
return rt[name]
n = str(name).strip().lower()
for c in rt.values():
if not _match_kind(c, kind, category):
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_fn(name: str, category: str) -> dict | None:
return rt_find(name, "function", category)
def rt_by_kind(kind: str, category: str | None = None) -> list[dict]:
return [c for c in runtime().values() if _match_kind(c, kind, category)]
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()
bound: dict[str, set[str]] = {}
for cid, tk in s.execute(select(Binding.concept_id, Binding.target_kind).where(
Binding.workspace == _ws())).all():
bound.setdefault(cid, set()).add(tk)
out = []
for c in rows:
d = _concept_dict(c, brief=True)
d["mapped"] = is_mapped(d, bound.get(c.id, set()))
out.append(d)
return out
def is_mapped(c: dict, target_kinds: set[str]) -> bool | None:
"""这块积木是否已落到真实数据。不需要绑定的积木(规则、决策表、动作……)返回 None。"""
if c["kind"] == "object_type":
return "table" in target_kinds
if c["kind"] == "link_type":
return "join" in target_kinds
if c["kind"] == "function" and c.get("category") == "aggregate":
return "metric_expr" in target_kinds
return None
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)
by_cat: dict[str, int] = {}
with session() as s:
for (sj,) in s.execute(select(Concept.spec_json).where(
Concept.workspace == _ws(), Concept.kind == "function",
Concept.status != "deprecated")).all():
cat = jload(sj, {}).get("category") or "rule"
by_cat[cat] = by_cat.get(cat, 0) + 1
return {"by_kind": by_kind, "by_category": by_cat, "dirty": int(dirty), "revision": int(rev),
"kinds": [{"kind": k, **v} for k, v in schema.KINDS.items()],
"categories": [{"category": k, **v} for k, v in schema.FN_CATEGORIES.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.id == n, 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, "名称不能为空")
up = schema.upgrade(kind, spec) # 旧类别(metric/rule/…)自动换成四元组
if up is None:
raise HTTPException(422, f"「{kind}」不再是本体积木:角色请在「成员与角色」维护,"
f"流程请建流程卡,术语写成同义词")
kind, spec = up
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}」")
if kind != "function" or spec.get("category") != "aggregate":
bindings = [b for b in bindings or []
if (b.get("target_kind") or schema.BINDING_KINDS.get(kind)) != "metric_expr"]
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:
new_spec = dict(fields["spec"])
old_ui = jload(c.spec_json, {}).get("ui")
if old_ui and "ui" not in new_spec:
new_spec["ui"] = old_ui # 表单编辑不带画布位置,别把它冲掉
try:
c.spec_json = jdump(schema.normalize_spec(c.kind, new_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 save_layout(positions: dict[str, dict]) -> int:
"""画布拖动后的位置。纯展示信息:不算修改、不进发布、不写审计。"""
n = 0
with session() as s:
for cid, pos in (positions or {}).items():
c = s.get(Concept, cid)
if c is None or c.workspace != _ws() or not isinstance(pos, dict):
continue
spec = jload(c.spec_json, {})
try:
spec["ui"] = {"pos": {"x": float(pos.get("x") or 0), "y": float(pos.get("y") or 0)}}
except (TypeError, ValueError):
continue
c.spec_json = jdump(spec)
n += 1
s.commit()
return n
def deprecate_concept(cid: str, reason: str = "", force: bool = False) -> dict:
"""废弃一块积木。被别的积木或流程卡引用时默认拦住 —— 以前不拦,废弃「商品」不会有
任何提示,但「库存→记录→商品」这条关系和「库存缺口」这个指标当场就哑了。"""
before = get_concept(cid)
if not force:
refs = usage(cid)
if refs:
names = "、".join(f"「{r['name']}」" for r in refs[:5])
raise HTTPException(409, f"「{before['name']}」还被 {len(refs)} 处引用({names}"
f"{' 等' if len(refs) > 5 else ''}),"
"确认要废弃就勾选「仍然废弃」,否则先改掉这些引用")
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]]] = []
# 发布监听:新版本生效后通知运行时各部分刷新(链接器、MCP 目录……)。进程内事件,不需要消息队列。
_listeners: list[Callable[[int], None]] = []
def register_publish_gate(fn: Callable[[dict], tuple[bool, str]]) -> None:
_gates.append(fn)
def on_publish(fn: Callable[[int], None]) -> None:
_listeners.append(fn)
def _released(revision: int) -> None:
invalidate_runtime()
for fn in _listeners:
try:
fn(revision)
except Exception: # noqa: BLE001
log.exception("发布监听处理失败")
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(_cmp(prev[k].get(f), f)) != jdump(_cmp(v.get(f), f))]
if fields:
changed.append({"id": k, "name": v["name"], "kind": v["kind"], "fields": fields})
return {"added": added, "removed": removed, "changed": changed}
def _cmp(v: Any, field: str) -> Any:
if field == "spec" and isinstance(v, dict) and "ui" in v:
return {k: x for k, x in v.items() if k != "ui"}
return v
def _field_changes(a: dict, b: dict) -> list[dict]:
"""两份概念快照之间逐字段的前后值(给版本对比页看)。"""
out = []
for f in ("name", "display_name", "description", "synonyms"):
if jdump(a.get(f)) != jdump(b.get(f)):
out.append({"field": f, "before": a.get(f), "after": b.get(f)})
sa, sb = _cmp(a.get("spec") or {}, "spec"), _cmp(b.get("spec") or {}, "spec")
for k in sorted(set(sa) | set(sb)):
if jdump(sa.get(k)) != jdump(sb.get(k)):
out.append({"field": f"spec.{k}", "before": sa.get(k), "after": sb.get(k)})
def _bind(c: dict) -> list[dict]:
return [{"ds_id": x.get("ds_id"), "target_kind": x.get("target_kind"), "ref": x.get("ref")}
for x in c.get("bindings") or []]
if jdump(_bind(a)) != jdump(_bind(b)):
out.append({"field": "bindings", "before": _bind(a), "after": _bind(b)})
return out
def compare_revisions(rev_from: int, rev_to: int) -> dict:
"""任意两个版本之间的差异(rev=0 表示空本体),含每个修改概念的逐字段前后值。"""
a = get_revision(rev_from)["snapshot"] if rev_from else {}
b = get_revision(rev_to)["snapshot"] if rev_to else {}
d = _diff(a, b)
names = {k: v["name"] for k, v in {**a, **b}.items()}
def readable(v: Any) -> Any: # 引用别的积木时显示名称而不是 id
if isinstance(v, str) and v in names:
return names[v]
if isinstance(v, list):
return [readable(x) for x in v]
return v
for ch in d["changed"]:
ch["changes"] = [{**x, "before": readable(x["before"]), "after": readable(x["after"])}
for x in _field_changes(a[ch["id"]], b[ch["id"]])]
for x in d["added"]:
x["type_key"] = schema.type_key(b[x["id"]])
for x in d["removed"]:
x["type_key"] = schema.type_key(a[x["id"]])
return {"from": rev_from, "to": rev_to, **d}
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)}
_released(out["revision"])
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
_released(new_rev)
audit.record("ontology.rollback", "revision", str(new_rev), f"回滚到第 {rev} 版", after=diff)
return {"revision": new_rev, "diff": diff}
# ---------------- 变更提案(发布与回滚都要人审) ----------------
# 规则:提交人不能审批自己的提案;AI / 外部 Agent 不能审批;审批时如果草稿又被改过,要重新提交。
def _dirty_fingerprint(concept_ids: list[str] | None = None) -> list[list]:
with session() as s:
stmt = select(Concept.id, Concept.version).where(Concept.workspace == _ws(), Concept.dirty == 1)
if concept_ids:
stmt = stmt.where(Concept.id.in_(concept_ids))
return sorted([cid, int(v)] for cid, v in s.execute(stmt).all())
def _pending_release() -> dict | None:
from ..governance import review
items = review.list_items(status="pending", kind="release", limit=1)["items"]
return items[0] if items else None
def propose_release(note: str = "", concept_ids: list[str] | None = None) -> dict:
from ..governance import review
diff = pending_diff()
if not (diff["added"] or diff["removed"] or diff["changed"]):
raise HTTPException(409, "没有待发布的变更")
if _pending_release():
raise HTTPException(409, "已有一份待审批的变更提案,请先处理它(或撤回后重新提交)")
with session() as s:
rev, _ = _last_snapshot(s)
title = f"发布第 {rev + 1} 版:新增 {len(diff['added'])},修改 {len(diff['changed'])},移除 {len(diff['removed'])}"
return review.propose("release", title, {
"op": "publish", "note": note or "", "concept_ids": concept_ids or [], "diff": diff,
"fingerprint": _dirty_fingerprint(concept_ids), "base_revision": rev},
source="user", target_ref="release", assignee_role="builder", dedupe=False)
def propose_rollback(rev: int, note: str = "") -> dict:
from ..governance import review
get_revision(rev)
if _pending_release():
raise HTTPException(409, "已有一份待审批的变更提案,请先处理它")
with session() as s:
cur, _ = _last_snapshot(s)
diff = compare_revisions(cur, rev) if cur else {}
return review.propose("release", f"回滚到第 {rev} 版", {
"op": "rollback", "rev": rev, "note": note or "", "diff": diff, "base_revision": cur},
source="user", target_ref="release", assignee_role="builder", dedupe=False)
def can_decide_release(actor: identity.Actor, item: dict) -> str:
"""返回不能审批的原因;空串表示可以。管理员什么都能批(含自己提交的,审计里注明);
其他人不能批自己的,单人团队可在系统设置里放开(RELEASE_SELF_APPROVE)。"""
from ..core import db as core_db
from ..governance import permissions
self_ok = core_db.get_config("RELEASE_SELF_APPROVE", "0").lower() in ("1", "true", "yes")
why = permissions.can_decide(actor, perm="review", submitters=[item.get("created_by") or ""],
allow_self=self_ok, what="变更提案")
if why.startswith("不能审批自己"):
why += ";单人团队可在「系统设置 → 治理」里打开「允许自审变更提案」"
return why
def _accept_release(payload: dict, item: dict) -> dict:
why = can_decide_release(identity.current(), item)
if why:
raise HTTPException(403, why)
with session() as s:
cur, _ = _last_snapshot(s)
if int(payload.get("base_revision") or 0) != cur:
raise HTTPException(409, "提交之后本体已经发布过新版本,请重新提交变更提案")
if payload.get("op") == "rollback":
return rollback(int(payload["rev"]))
if _dirty_fingerprint(payload.get("concept_ids") or None) != payload.get("fingerprint"):
raise HTTPException(409, "提交之后草稿又被修改过,请重新提交变更提案")
return publish(payload.get("note") or item["title"], payload.get("concept_ids") or None)
def list_releases(status: str = "", limit: int = 50) -> list[dict]:
from ..governance import review
items = review.list_items(status=status, kind="release", limit=limit)["items"]
actor = identity.current()
for it in items:
why = can_decide_release(actor, it) if it["status"] == "pending" else ""
it["can_decide"] = it["status"] == "pending" and not why
it["cannot_reason"] = why
return items
def _register_release_handler() -> None:
from ..governance import review
review.register_handler("release", _accept_release)
_register_release_handler()
# ---------------- 引用 / 影响 / 血缘 ----------------
# 其他模块(能力、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"}