test_kernel_v10.py
20.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
"""v10 本体内核:语义层、映射与存储、逻辑层、动作层、时间层、动态层。
每个用例对应 docs/ontology_kernel_roadmap.md 里的一项(A1~F5)。元数据库和业务库都是 SQLite。
"""
from __future__ import annotations
import datetime as dt
import sys
from pathlib import Path
import pytest
from fastapi import HTTPException
sys.path.insert(0, str(Path(__file__).parent))
from kernel_env import TODAY, biz_exec, build_inventory, make_env # noqa: E402
@pytest.fixture()
def env(tmp_path, monkeypatch):
from app.core import identity
e = make_env(tmp_path, monkeypatch)
e["o"] = build_inventory(e["ds"])
yield e
identity.reset(e["tok"])
def _sync(*names):
from app.kernel import pipeline
return [pipeline.sync_type(n) for n in names]
# =========================== A 语义层 ===========================
def test_A3_值类型_内置与本体里建的都认_写入时统一校验(env):
from app.kernel import objects, valuetypes
assert valuetypes.resolve("金额")["format"] == "money"
assert valuetypes.resolve("件数")["base_type"] == "integer" # 本体里建的
names = {v["name"] for v in valuetypes.catalog()}
assert {"金额", "数量", "手机号", "件数"} <= names
with pytest.raises(HTTPException) as e:
objects.plan_ops([{"op": "update", "object_type": "库存位", "key": "1", "values": {"在库": -3}}])
assert "不能小于 0" in e.value.detail
with pytest.raises(HTTPException):
objects.plan_ops([{"op": "update", "object_type": "库存位", "key": "1", "values": {"在库": 2.5}}])
cols = {c["name"]: c for c in objects.columns(objects.object_type("配件"))}
assert cols["单价"]["format"] == "money" and cols["单价"]["unit"] == "元"
def test_A2_接口_合并所有实现_主键带类型前缀_按接口属性筛选(env):
from app.kernel import objects
r = objects.query("网点")
assert r["total"] == 4
assert all(":" in o["key"] and o.get("impl_type") for o in r["items"])
hz = objects.query("网点", filters=[{"property": "城市", "op": "eq", "value": "杭州"}])
assert hz["total"] == 3 and {o["label"] for o in hz["items"]} == {"杭州店", "西湖店", "滨江店"}
key = next(o["key"] for o in r["items"] if o["label"] == "西湖店")
one = objects.get("网点", key)
assert one["properties"]["名称"] == "西湖店"
impl, k = objects.concrete("网点", key)
assert impl["name"] == "乙门店" and k == "1"
def test_A5_状态机_状态只能经由声明了流转的动作改变(env):
from app.capability import actions
from app.kernel import objects
with pytest.raises(HTTPException) as e:
objects.plan_ops([{"op": "update", "object_type": "采购单", "key": "PO1", "values": {"状态": "运输中"}}])
assert "状态机" in e.value.detail
# 不在任何流转里:已下单 → 已到货
with pytest.raises(HTTPException) as e:
objects.apply_ops([{"op": "transition", "object_type": "采购单", "key": "PO1", "property": "状态", "to": "已到货"}])
assert "不能从「已下单」流转到「已到货」" in e.value.detail
# 流转点名了动作「发货」:别的动作 / 直接写都不行
with pytest.raises(HTTPException) as e:
objects.apply_ops([{"op": "transition", "object_type": "采购单", "key": "PO1", "property": "状态", "to": "运输中"}])
assert "要由动作「发货」完成" in e.value.detail
run = actions.propose("发货", {}, object_key="PO1")
assert run["status"] == "done", run
assert objects.get("采购单", "PO1")["properties"]["状态"] == "运输中"
# 当前状态不对:前置校验当场拦下
with pytest.raises(HTTPException) as e:
actions.propose("发货", {}, object_key="PO1")
assert "只有状态是已下单时才能做" in e.value.detail
run = actions.propose("到货入库", {}, object_key="PO1")
assert run["status"] == "done" and objects.get("采购单", "PO1")["properties"]["状态"] == "已到货"
# 撤销:状态回到运输中
rv = actions.propose_revert(run["id"], "点错了")
actions.decide(rv["id"], True, "")
assert objects.get("采购单", "PO1")["properties"]["状态"] == "运输中"
def test_A6_系统对象_动作记录进本体_能查_能统计_连着业务对象(env):
from app.capability import actions
from app.kernel import metrics, objects, pipeline, traverse
actions.propose("调整在库", {"qty": 90}, object_key="1")
recs = objects.query("动作记录")
assert recs["total"] >= 1
rec = recs["items"][0]["properties"]
assert rec["动作"] == "调整在库" and rec["状态"] == "已完成" and rec["对象主键"] == "1"
r = metrics.query("动作执行数", dimensions=["动作"])
assert dict((row[0], row[-1]) for row in r["rows"])["调整在库"] == 1
_sync("仓库", "配件", "库存位")
pipeline.rebuild_system_edges()
t = traverse.traverse("库存位", "1", depth=1)
assert any(n["type_name"] == "动作记录" for n in t["nodes"])
# =========================== B 映射与存储 ===========================
def test_B1_多表组合_计算属性跨表_只能写主表的列(env):
from app.kernel import objects
o = objects.get("库存位", "1")
assert o["properties"]["配件名"] == "火花塞" and o["properties"]["库存金额"] == 3000
assert o["label"] == "华东仓·火花塞" # 外键属性在标题里显示成对方的名称
objects.apply_ops([{"op": "update", "object_type": "库存位", "key": "1", "values": {"在库": 99}}])
assert objects.get("库存位", "1")["properties"]["在库"] == 99
def test_B1_表的一部分_多源合并_多源只读(env):
from app.kernel import objects
r = objects.query("在途采购单")
assert {o["key"] for o in r["items"]} == {"PO1", "PO2"}
u = objects.query("全部门店")
assert {o["key"] for o in u["items"]} == {"A-1", "A-2", "B-1", "B-2"}
with pytest.raises(HTTPException) as e:
objects.plan_ops([{"op": "update", "object_type": "全部门店", "key": "A-1", "values": {"名称": "x"}}])
assert "只读" in e.value.detail
def test_B3_本体自建对象_发布即建表_能新建修改删除_撤销(env):
from app.capability import actions
from app.kernel import objects
run = actions.propose("生成补货建议", {"qty": 30}, object_key="2")
assert run["status"] == "done", run
items = objects.query("补货建议")["items"]
assert len(items) == 1 and items[0]["properties"]["状态"] == "待审" # 状态机属性自动取初始状态
key = items[0]["key"]
assert items[0]["properties"]["库存位"] == "华东仓·机油滤清器"
objects.apply_ops([{"op": "delete", "object_type": "补货建议", "key": key}])
assert objects.query("补货建议")["total"] == 0
# 撤销「生成补货建议」:新建的那条也删掉(这里已经删了,撤销删除再撤销新建)
with pytest.raises(HTTPException):
objects.apply_ops([{"op": "update", "object_type": "补货建议", "key": key, "values": {"状态": "已批准"}}])
def test_B4_写入都记进变化记录_动作写完索引跟着改(env):
from app.capability import actions
from app.kernel import objects
_sync("库存位")
actions.propose("调整在库", {"qty": 77}, object_key="1")
h = objects.history(objects.object_type("库存位")["id"], "1")
assert h[0]["property"] == "在库" and h[0]["old"] == 100 and h[0]["new"] == 77 and h[0]["source"] == "action"
# 再同步一次:索引已经是 77,不会把同一个变化再记一遍
_sync("库存位")
h2 = objects.history(objects.object_type("库存位")["id"], "1")
assert len([x for x in h2 if x["property"] == "在库"]) == 1
# =========================== C 逻辑层 ===========================
def test_C2_对象集_条件带参数_沿关系走_集合运算_当指标的统计口径(env):
from app.kernel import metrics, objectset, service
r = objectset.evaluate("低库存位")
assert set(r["keys"]) == {"2", "3"} # 可用 5、6 < 15
assert set(objectset.evaluate("低库存位", {"门槛": 7})["keys"]) == {"2", "3"}
assert set(objectset.evaluate("低库存位", {"门槛": 6})["keys"]) == {"2"}
parts = objectset.evaluate("低库存的配件")
assert parts["type_name"] == "配件" and set(parts["keys"]) == {"P1", "P2"}
c = service.create_concept("function", "低库存但不是火花塞", spec={
"category": "object_set", "base": "库存位", "combine": [{"op": "intersect", "set": "低库存位"}],
"where": {"mode": "all", "items": [{"left": "配件", "op": "ne", "right": "P1"}]}})
service.publish("加对象集")
assert set(objectset.evaluate(c["name"])["keys"]) == {"2"}
m = metrics.query("低库存位数", dimensions=["仓库"])
assert dict((row[0], row[-1]) for row in m["rows"]) == {"W1": 1, "W2": 1}
def test_C1_指标周期口径与历史(env):
from app.kernel import metrics, service
h = metrics.history("日出库量", grain="day", n=7, filters={"配件": "P1"})
pts = h["series"][""]
assert h["source"] == "time_column" and len(pts) == 7 and pts[-1]["value"] == 60
m = service.create_concept("function", "业务月出库", spec={
"category": "aggregate", "period": {"start_day": 26, "start_month_offset": -1, "end_day": 25}})
service.set_binding(m["id"], service.list_bindings(service.find("日出库量")["id"])[0]["ds_id"], "metric_expr",
{"base_table": "outbound", "expression": "SUM(qty)", "time_column": "day"})
service.publish("业务月")
period = metrics.resolve_time(service.rt_find("业务月出库"), "current")
assert period["start"].endswith("-26") or period["start"][8:] == "26"
assert period["calendar"].startswith("业务月")
def test_A4_中间表关系_带属性_汇总_遍历_建立与解除(env):
from app.kernel import objects, pipeline, traverse
links = objects.linked("配件", "P1")
fit = next(g for g in links if g["link_type"] == "适配")
assert {o["label"] for o in fit["items"]} == {"轿车A", "SUV B"}
assert {o["link_props"]["备注"] for o in fit["items"]} == {"原厂", "通用"}
assert objects.get("配件", "P1")["properties"]["适配车型数"] == 2
f = objects.fetch("配件", include=[{"link": "适配", "fields": ["名称"]}], keys=["P1"])
assert {x["名称"] for x in f["items"][0]["适配"]} == {"轿车A", "SUV B"}
objects.apply_ops([{"op": "link", "link": "适配", "from_key": "P3", "to_key": "M2", "values": {"备注": "加装"}}])
assert objects.get("配件", "P3")["properties"]["适配车型数"] == 1
objects.apply_ops([{"op": "link", "link": "适配", "from_key": "P3", "to_key": "M2"}]) # 重复建立:不报错也不多一条
assert objects.get("配件", "P3")["properties"]["适配车型数"] == 1
res = objects.apply_ops([{"op": "unlink", "link": "适配", "from_key": "P3", "to_key": "M2"}])
assert objects.get("配件", "P3")["properties"]["适配车型数"] == 0
objects.revert_edits(res["edit_ids"])
assert objects.get("配件", "P3")["properties"]["适配车型数"] == 1
_sync("配件", "车型")
t = traverse.traverse("车型", "M2", depth=1)
assert {n["key"] for n in t["nodes"] if n["type_name"] == "配件"} == {"P1", "P3"}
# =========================== E 时间层 ===========================
def test_E1_E2_同步对比出变化_记序列点_回到过去的样子(env):
from app.kernel import objects, series
ot = objects.object_type("库存位")
import time
_sync("库存位")
time.sleep(1.1) # 变化记录按秒记时间:隔开一秒再取「过去」的时点
first = dt.datetime.now()
time.sleep(1.1)
biz_exec(env, "UPDATE stock SET on_hand = 3 WHERE id = 1")
biz_exec(env, "INSERT INTO stock VALUES (5, 'W2', 'P2', 40, 0, 5, '否')")
biz_exec(env, "DELETE FROM stock WHERE id = 4")
r = _sync("库存位")[0]
assert r["changes"] >= 3 and r["removed"] == 1
h = objects.history(ot["id"], "1")
assert any(x["property"] == "在库" and x["old"] == 100 and x["new"] == 3 for x in h)
assert any(x["property"] == "可用" and x["old"] == 90 and x["new"] == -7 for x in h) # 计算属性也记历史
assert any(x["property"] == "*" and x["new"] == "created" for x in objects.history(ot["id"], "5"))
pts = series.query(series.prop_series(ot["id"], "在库"), "1")
assert [p["value"] for p in pts] == [100, 3]
old = series.as_of(ot["id"], "1", first)
assert old["properties"]["在库"] == 100
assert series.as_of(ot["id"], "4", first)["existed"] is True
def test_E3_快照指标的环比读快照序列(env):
from app.capability import builtins
from app.kernel import series, service
m = service.rt_find("低库存位数")
series.backfill(series.metric_series(m["id"]), [("", 5, dt.datetime.now() - dt.timedelta(days=31))])
spec = dict(m["spec"])
spec["compare"] = "mom"
r = builtins.eval_function({**m, "spec": spec}, {})
assert r["value"] == 2 and r["previous"] == 5 and r["change"] == -3
# =========================== F 动态层 ===========================
def test_F2_检测器纯函数():
from app.watch import detectors as d
now = dt.datetime.now()
z = d.normalize([{"name": "z", "fn": "zscore", "field": "value", "window": 5}])[0]
assert d.compute(z, 60, [10, 11, 12, 10, 11]) > 3
assert d.compute({"fn": "pct_change"}, 15, [10]) == 0.5
assert d.compute({"fn": "delta"}, 7, [10]) == -3
assert d.compute({"fn": "streak_up", "window": 5}, 5, [1, 2, 3, 4]) == 4
assert d.compute({"fn": "streak_down", "window": 5}, 1, [3, 2]) == 2
assert d.compute({"fn": "changed", "from": ["正常"], "to": ["冻结"]}, "冻结", ["正常"]) is True
assert d.compute({"fn": "changed", "from": ["正常"], "to": ["冻结"]}, "正常", ["冻结"]) is False
assert d.compute({"fn": "stale"}, 5, [5, 5, 5], times=[now - dt.timedelta(days=9), now - dt.timedelta(days=5),
now - dt.timedelta(days=1)], now=now) == 9
assert d.compute({"fn": "avg", "window": 3}, 0, [1, 2, 3, 6]) == pytest.approx(11 / 3, 0.01)
with pytest.raises(d.DetectorError):
d.normalize([{"fn": "nope"}])
def _watch(**kw):
from app.watch import service as wsvc
body = {"title": "低库存预警", "schedule": {"kind": "interval", "every_minutes": 60},
"source": {"kind": "object_set", "set": "低库存位"}, "condition": "可用 < 安全库存",
"strategies": [{"kind": "propose_action", "action": "生成补货建议", "params": {"qty": "=安全库存 * 2 - 可用"}}],
"severity": {"mode": "rules", "level": "中", "rules": [{"when": "可用 <= 5", "level": "高"}]},
"recovery": {"mode": "auto", "reopen_days": 7}, "dedup": {"cooldown_hours": 24}}
body.update(kw)
return wsvc.create(body)
def test_F3_F4_预警事件全生命周期_处置_验证_恢复_复发_忽略静默_效果统计(env):
from app.kernel import metrics, objects
from app.watch import engine, events
w = _watch()
r = engine.scan(w["id"])
assert r["opened"] == 2 and r["hit_count"] == 2
evs = {e["object"]["key"]: e for e in events.list_events(status="open")}
assert set(evs) == {"2", "3"}
assert evs["2"]["severity"] == "高" and evs["3"]["severity"] == "中"
# 处置用的动作是自动执行的:单据结束 → 待验证,而且是自动处理
assert evs["2"]["status"] == "待验证" and evs["2"]["auto_handled"]
assert objects.query("补货建议")["total"] == 2
# 再扫一次:事件开着、冷却期内,不重复处置
r2 = engine.scan(w["id"])
assert r2["opened"] == 0 and r2["suppressed"] == 2 and objects.query("补货建议")["total"] == 2
# 3 号恢复了
biz_exec(env, "UPDATE stock SET on_hand = 50 WHERE id = 3")
r3 = engine.scan(w["id"])
assert r3["recovered"] == 1
e3 = events.get(evs["3"]["id"])
assert e3["status"] == "已恢复" and e3["recover_hours"] is not None
# 复发:恢复后 7 天内再命中
biz_exec(env, "UPDATE stock SET on_hand = 9 WHERE id = 3")
engine.scan(w["id"])
again = [e for e in events.list_events(status="open") if e["object"]["key"] == "3"]
assert len(again) == 1 and again[0]["is_recurrence"] and again[0]["recurrence_of"] == evs["3"]["id"]
# 误报:忽略并静默 3 天,恢复再坏也不开新事件
events.ignore(again[0]["id"], "数据录错了", silence_days=3)
biz_exec(env, "UPDATE stock SET on_hand = 50 WHERE id = 3")
engine.scan(w["id"])
biz_exec(env, "UPDATE stock SET on_hand = 9 WHERE id = 3")
r4 = engine.scan(w["id"])
assert not [e for e in events.list_events(status="open") if e["object"]["key"] == "3"] and r4["suppressed"] >= 1
st = events.stats()
assert st["total"] == 3 and st["ignored"] == 1 and st["recurrence_rate"] == pytest.approx(1 / 3, 0.01)
# 同一个口径的系统对象指标
m = metrics.query("预警数", dimensions=["状态"])
by = dict((row[0], row[-1]) for row in m["rows"])
assert by.get("已忽略") == 1 and by.get("已恢复") == 1
assert objects.query("预警事件", filters=[{"property": "严重度", "op": "eq", "value": "高"}])["total"] >= 1
def test_F1_对象一变化就触发_不等排程(env):
from app.capability import actions
from app.watch import events
_watch(title="在库骤降", trigger={"kind": "change", "properties": ["在库"]},
source={"kind": "object", "object_type": "库存位"},
detectors=[{"name": "降幅", "fn": "delta", "field": "在库"}], condition="可用 < 安全库存",
strategies=[{"kind": "notify", "role": "admin", "subject": "在库不足:$label"}])
assert not events.list_events(status="open")
actions.propose("调整在库", {"qty": 12}, object_key="1") # 可用 2 < 20:动作一写完就命中
evs = events.list_events(status="open")
assert len(evs) == 1 and evs[0]["object"]["key"] == "1" and evs[0]["rule"] == "在库骤降"
def test_F2_检测量进条件_偏离基线的出库突增(env):
from app.watch import engine, events, service as wsvc
w = wsvc.create({"title": "出库突增", "schedule": {"kind": "daily", "at": "08:00"},
"source": {"kind": "metric", "metric": "日出库量", "dimensions": ["配件"], "time": "today"},
"detectors": [{"name": "z", "fn": "zscore", "field": "value", "window": 14},
{"name": "基线", "fn": "avg", "field": "value", "window": 14}],
"condition": "z > 3", "strategies": [{"kind": "notify", "role": "admin"}]})
dry = engine.scan(w["id"], dry=True)
assert [h["key"] for h in dry["hits"]] == ["P1"]
assert dry["hits"][0]["z"] > 3 and 10 <= dry["hits"][0]["基线"] <= 12
engine.scan(w["id"])
ev = events.list_events(status="open")[0]
assert ev["object"]["type_name"] == "配件" and ev["object"]["key"] == "P1"
assert ev["baseline"] and ev["deviation"] > 3 and ev["value"] == 60
def test_G1_流程卡由预警拉起_运行挂到事件和对象上_走完事件进入待验证(env):
from app.sop import engine as sop_engine, service as sop_service
from app.watch import engine, events
spec = {"params": [{"name": "spot", "label": "库存位", "type": "object", "object_type": "库存位", "required": True}],
"start": "s1", "steps": [
{"id": "s1", "type": "notify", "title": "告诉采购", "role": "admin",
"subject": "处置预警:$event.title", "next": "end"},
{"id": "end", "type": "end", "title": "结束"}]}
d = sop_service.create("缺货处置", "预警拉起的处置流程", spec)
sop_service.publish(d["id"], "上线")
w = _watch(title="缺货处置预警", strategies=[{"kind": "run_sop", "sop": "缺货处置", "params": {"spot": "$key"}}])
engine.scan(w["id"])
ev = next(e for e in events.list_events(status="open") if e["object"]["key"] == "2")
run_id = next(f["ref"] for f in ev["fired"] if f["ref_kind"] == "sop_run")
run = sop_engine.get_run(run_id)
assert run["event_id"] == ev["id"] and run["subject"]["key"] == "2" and run["status"] == "done"
assert events.get(ev["id"])["status"] == "待验证"