kernel_env.py
19.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
"""v10 内核测试的公共环境:元数据库(也是「本体存储」)和业务库都用 SQLite,LLM 不参与。
业务库是一个小型库存场景:仓库、配件、库存位、车型、适配(中间表)、采购单、出库流水、两张门店表。
连接器按数据源路由:本体存储 → 元数据库,其余 → 业务库;内省按 SQLite 的真实表结构来。
"""
from __future__ import annotations
import datetime as dt
import sys
import time
from pathlib import Path
from sqlalchemy import create_engine, inspect, text as sa_text
from sqlalchemy.orm import Session
sys.path.insert(0, str(Path(__file__).parent.parent))
from app.core import db as core_db, identity # noqa: E402
from app.core.config import DEFAULT_RUNTIME # noqa: E402
from app.text2sql import introspect, semantic # noqa: E402
from app.text2sql.connectors.base import ( # noqa: E402
ColumnInfo, Connector, Introspection, QueryFailed, QueryResult, TableInfo,
)
TODAY = dt.date.today()
class SqliteConnector(Connector):
dialect = "mysql"
def __init__(self, engine):
super().__init__({"id": 1, "ds_type": "mysql"}, "")
self.engine = engine
self.executed: list[str] = []
def test(self) -> dict:
return {"version": "sqlite", "database": "biz", "table_count": 0, "account_writable": True}
def introspect(self) -> Introspection:
insp = inspect(self.engine)
tables = []
for t in insp.get_table_names():
if t.startswith("otlg_"):
continue
pk = (insp.get_pk_constraint(t) or {}).get("constrained_columns") or []
tables.append(TableInfo(name=t, primary_key=pk, row_count_est=10, columns=[
ColumnInfo(c["name"], str(c["type"]).lower(), bool(c.get("nullable", True))) for c in insp.get_columns(t)]))
return Introspection(tables=tables, foreign_keys=[])
def sample_values(self, table, column, limit, max_distinct):
with self.engine.connect() as c:
rows = c.execute(sa_text(f'SELECT DISTINCT "{column}" FROM "{table}" LIMIT {int(limit)}')).fetchall()
return [str(r[0]) for r in rows if r[0] is not None], len(rows)
def null_ratios(self, table, columns, sample=50000):
return {}
def run_sql(self, sql: str, row_limit: int, timeout_ms: int) -> QueryResult:
self.executed.append(sql)
started = time.time()
try:
with self.engine.connect() as c:
cur = c.execute(sa_text(sql))
cols = list(cur.keys())
rows = cur.fetchmany(row_limit + 1)
except Exception as e: # noqa: BLE001
raise QueryFailed(str(e)) from e
return QueryResult(columns=cols, rows=[list(r) for r in rows[:row_limit]], row_count=min(len(rows), row_limit),
duration_ms=int((time.time() - started) * 1000), truncated=len(rows) > row_limit)
def seed_biz(eng) -> None:
stmts = [
"CREATE TABLE warehouse (code TEXT PRIMARY KEY, wname TEXT, region TEXT)",
"CREATE TABLE part (sku TEXT PRIMARY KEY, pname TEXT, price REAL, category TEXT)",
"CREATE TABLE stock (id INTEGER PRIMARY KEY, wh TEXT, sku TEXT, on_hand INTEGER, locked INTEGER, "
"safety INTEGER, frozen TEXT)",
"CREATE TABLE car_model (mid TEXT PRIMARY KEY, mname TEXT)",
"CREATE TABLE fit (sku TEXT, mid TEXT, note TEXT)",
"CREATE TABLE po (po_no TEXT PRIMARY KEY, sku TEXT, qty INTEGER, status TEXT)",
"CREATE TABLE outbound (id INTEGER PRIMARY KEY, wh TEXT, sku TEXT, qty INTEGER, day TEXT)",
"CREATE TABLE store_a (id INTEGER PRIMARY KEY, name TEXT, city TEXT)",
"CREATE TABLE store_b (id INTEGER PRIMARY KEY, name TEXT, city TEXT)",
]
with eng.begin() as c:
for st in stmts:
c.execute(sa_text(st))
for code, name, region in [("W1", "华东仓", "华东"), ("W2", "华北仓", "华北")]:
c.execute(sa_text("INSERT INTO warehouse VALUES (:a,:b,:c)"), {"a": code, "b": name, "c": region})
for sku, name, price, cat in [("P1", "火花塞", 30.0, "点火"), ("P2", "机油滤清器", 45.0, "滤清"),
("P3", "刹车片", 120.0, "制动")]:
c.execute(sa_text("INSERT INTO part VALUES (:a,:b,:c,:d)"), {"a": sku, "b": name, "c": price, "d": cat})
for i, (wh, sku, oh, lk, sf) in enumerate([("W1", "P1", 100, 10, 20), ("W1", "P2", 5, 0, 20),
("W2", "P1", 8, 2, 10), ("W2", "P3", 50, 0, 10)], 1):
c.execute(sa_text("INSERT INTO stock VALUES (:i,:w,:s,:o,:l,:f,'否')"),
{"i": i, "w": wh, "s": sku, "o": oh, "l": lk, "f": sf})
for mid, name in [("M1", "轿车A"), ("M2", "SUV B")]:
c.execute(sa_text("INSERT INTO car_model VALUES (:a,:b)"), {"a": mid, "b": name})
for sku, mid, note in [("P1", "M1", "原厂"), ("P1", "M2", "通用"), ("P2", "M1", "原厂")]:
c.execute(sa_text("INSERT INTO fit VALUES (:a,:b,:c)"), {"a": sku, "b": mid, "c": note})
for no, sku, qty, st in [("PO1", "P1", 50, "已下单"), ("PO2", "P2", 30, "运输中"), ("PO3", "P3", 10, "已到货")]:
c.execute(sa_text("INSERT INTO po VALUES (:a,:b,:c,:d)"), {"a": no, "b": sku, "c": qty, "d": st})
n = 1
for back in range(20, -1, -1): # 20 天的出库流水:P1 平时每天 10 个,今天突然 60 个
day = (TODAY - dt.timedelta(days=back)).isoformat()
for wh, sku, qty in [("W1", "P1", 60 if back == 0 else 10 + back % 3), ("W1", "P2", 4)]:
c.execute(sa_text("INSERT INTO outbound VALUES (:i,:w,:s,:q,:d)"),
{"i": n, "w": wh, "s": sku, "q": qty, "d": day})
n += 1
for t, rows in (("store_a", [(1, "杭州店", "杭州"), (2, "宁波店", "宁波")]),
("store_b", [(1, "西湖店", "杭州"), (2, "滨江店", "杭州")])):
for i, name, city in rows:
c.execute(sa_text(f"INSERT INTO {t} VALUES (:i,:n,:c)"), {"i": i, "n": name, "c": city})
def make_env(tmp_path, monkeypatch) -> dict:
from app import bootstrap
from app.capability import models as _m1 # noqa: F401
from app.evals import models as _m2 # noqa: F401
from app.governance import models as _m3 # noqa: F401
from app.kernel import models as _m4 # noqa: F401
from app.agents import models as _m5 # noqa: F401
from app.sop import models as _m6 # noqa: F401
from app.text2sql import models as _m7 # noqa: F401
from app.memory import models as _m8 # noqa: F401
from app.watch import models as _m9 # noqa: F401
meta = create_engine(f"sqlite:///{tmp_path / 'meta.db'}", future=True)
core_db.Base.metadata.create_all(meta)
with Session(meta) as s:
for k, v in DEFAULT_RUNTIME.items():
s.add(core_db.Config(cfg_key=k, cfg_value="0" if k == "PIPELINE_AUTO_SYNC" else v))
s.commit()
monkeypatch.setattr(core_db, "engine", meta)
biz_eng = create_engine(f"sqlite:///{tmp_path / 'biz.db'}", future=True)
seed_biz(biz_eng)
biz, store = SqliteConnector(biz_eng), SqliteConnector(meta)
from app.kernel import storage
storage.reset_cache()
monkeypatch.setattr(semantic, "connector_for",
lambda ds_id, fresh=False: store if storage.is_storage(ds_id) else biz)
monkeypatch.setattr(semantic.crypto, "encrypt", lambda p: f"enc:{p}")
monkeypatch.setattr(semantic.crypto, "decrypt", lambda t: t[4:] if t.startswith("enc:") else "")
bootstrap.setup()
from app.governance import users
from app.kernel import linker, service
from app.sop import engine
from app.watch import engine as watch_engine
users.seed()
users.invalidate()
service.invalidate_runtime()
linker.invalidate()
monkeypatch.setattr(engine, "_submit", lambda rid: engine._safe_advance(rid))
monkeypatch.setattr(watch_engine, "SYNC_CHANGES", True)
tok = identity.set_current(identity.Actor())
ds_id = semantic.create_datasource(name="业务库", ds_type="mysql", host="h", port=3306, db_name="biz",
username="rw", password="pw", extra={"writeback": True})
events = list(introspect.run_introspection(ds_id))
assert events[-1]["stage"] == "done", events[-1]
semantic.set_models_enabled(ds_id, [m["id"] for m in semantic.list_models(ds_id)], True)
storage.datasource_id() # 本体存储数据源先建好(系统对象、自建对象都要用)
service.invalidate_runtime()
return {"ds": ds_id, "biz": biz, "biz_eng": biz_eng, "meta": meta, "store": store, "tok": tok}
def biz_exec(env: dict, sql: str, **args) -> None:
with env["biz_eng"].begin() as c:
c.execute(sa_text(sql), args)
from app.core import reqcache
reqcache.clear()
def build_inventory(ds: int) -> dict:
"""一套最小的库存本体:值类型、接口、几种数据来源、中间表关系、状态机、动作、对象集、指标。发布。"""
from app.kernel import service
out: dict = {}
out["vt"] = service.create_concept("value_type", "件数", spec={"base_type": "integer", "min": 0, "unit": "件",
"format": "quantity"})
out["wh"] = service.create_concept("object_type", "仓库", spec={"properties": [
{"name": "编码", "is_key": True}, {"name": "名称"}, {"name": "区域", "is_dimension": True}],
"label_property": "名称"})
service.set_binding(out["wh"]["id"], ds, "table", {"table": "warehouse", "key_column": "code", "label_column": "wname",
"columns": {"编码": "code", "名称": "wname", "区域": "region"}})
out["part"] = service.create_concept("object_type", "配件", spec={"properties": [
{"name": "SKU", "is_key": True}, {"name": "名称"}, {"name": "单价", "data_type": "number", "value_type": "金额"},
{"name": "品类", "is_dimension": True},
{"name": "适配车型数", "data_type": "integer", "expression": "count_of(适配)"}], "label_property": "名称"})
service.set_binding(out["part"]["id"], ds, "table", {"table": "part", "key_column": "sku", "label_column": "pname",
"columns": {"SKU": "sku", "名称": "pname", "单价": "price", "品类": "category"}})
# 库存位:多表组合(主表 stock 关联 part 带出配件名、单价),计算属性 + 记录历史
out["stock"] = service.create_concept("object_type", "库存位", spec={"properties": [
{"name": "编号", "data_type": "integer", "is_key": True}, {"name": "仓库", "is_dimension": True},
{"name": "配件", "is_dimension": True}, {"name": "配件名"}, {"name": "单价", "data_type": "number"},
{"name": "在库", "data_type": "integer", "value_type": "件数", "is_writable": True, "track": True},
{"name": "锁定", "data_type": "integer", "is_writable": True},
{"name": "安全库存", "data_type": "integer", "is_writable": True},
{"name": "可用", "data_type": "integer", "expression": "在库 - 锁定", "track": True},
{"name": "库存金额", "data_type": "number", "expression": "在库 * 单价"}],
"title_template": "{仓库}·{配件名}"})
service.set_binding(out["stock"]["id"], ds, "table", {
"kind": "view", "table": "stock", "key_column": "id",
"joins": [{"alias": "p", "table": "part", "from_column": "sku", "to_column": "sku"}],
"columns": {"编号": "id", "仓库": "wh", "配件": "sku", "配件名": "p.pname", "单价": "p.price",
"在库": "on_hand", "锁定": "locked", "安全库存": "safety"}})
out["car"] = service.create_concept("object_type", "车型", spec={"properties": [
{"name": "编码", "is_key": True}, {"name": "名称"}], "label_property": "名称"})
service.set_binding(out["car"]["id"], ds, "table", {"table": "car_model", "key_column": "mid",
"label_column": "mname", "columns": {"编码": "mid", "名称": "mname"}})
# 采购单:带状态机
out["po"] = service.create_concept("object_type", "采购单", spec={"properties": [
{"name": "单号", "is_key": True}, {"name": "配件"}, {"name": "数量", "data_type": "integer"},
{"name": "状态", "lifecycle": {"states": [{"value": "已下单"}, {"value": "运输中"},
{"value": "已到货", "terminal": True}, {"value": "已取消", "terminal": True}],
"transitions": [{"from": ["已下单"], "to": "运输中", "action": "发货"},
{"from": ["运输中"], "to": "已到货", "action": "到货入库"},
{"from": ["已下单", "运输中"], "to": "已取消"}]}}]})
service.set_binding(out["po"]["id"], ds, "table", {"table": "po", "key_column": "po_no",
"columns": {"单号": "po_no", "配件": "sku", "数量": "qty", "状态": "status"}})
# 在途采购单:表的一部分
out["intransit"] = service.create_concept("object_type", "在途采购单", spec={"properties": [
{"name": "单号", "is_key": True}, {"name": "数量", "data_type": "integer"}]})
service.set_binding(out["intransit"]["id"], ds, "table", {"kind": "filtered", "table": "po", "key_column": "po_no",
"where": "status in ['已下单', '运输中']",
"columns": {"单号": "po_no", "数量": "qty"}})
# 接口:网点;两张门店表各是一类对象,都实现它
out["iface"] = service.create_concept("object_type", "网点", spec={"abstract": True, "properties": [
{"name": "名称"}, {"name": "城市", "is_dimension": True}]})
for nm, t in (("甲门店", "store_a"), ("乙门店", "store_b")):
c = service.create_concept("object_type", nm, spec={"properties": [
{"name": "编号", "data_type": "integer", "is_key": True}, {"name": "店名"}, {"name": "所在城市"}],
"label_property": "店名", "implements": [{"interface": "网点", "mapping": {"名称": "店名", "城市": "所在城市"}}]})
service.set_binding(c["id"], ds, "table", {"table": t, "key_column": "id", "label_column": "name",
"columns": {"编号": "id", "店名": "name", "所在城市": "city"}})
out[t] = c
# 多源合并
out["allstore"] = service.create_concept("object_type", "全部门店", spec={"properties": [
{"name": "编号", "is_key": True}, {"name": "名称"}, {"name": "城市"}], "label_property": "名称"})
service.set_binding(out["allstore"]["id"], ds, "table", {"kind": "union", "branches": [
{"table": "store_a", "key_column": "id", "label_column": "name", "prefix": "A-", "columns": {"名称": "name", "城市": "city"}},
{"table": "store_b", "key_column": "id", "label_column": "name", "prefix": "B-", "columns": {"名称": "name", "城市": "city"}}]})
# 本体自建:补货建议
out["sugg"] = service.create_concept("object_type", "补货建议", spec={"properties": [
{"name": "库存位"}, {"name": "建议数量", "data_type": "integer", "value_type": "件数"},
{"name": "状态", "lifecycle": {"states": [{"value": "待审"}, {"value": "已批准"}, {"value": "已驳回"}],
"transitions": [{"from": ["待审"], "to": "已批准", "action": "批准补货"},
{"from": ["待审"], "to": "已驳回"}]}}],
"label_property": "库存位"})
service.set_binding(out["sugg"]["id"], 0, "table", {"kind": "managed"})
# 关系:库存位 → 仓库(外键)、库存位 → 配件(外键)、配件 ↔ 车型(中间表,带属性)
for name, f, t, fc, tc in (("所在仓库", "库存位", "仓库", "wh", "code"), ("存放配件", "库存位", "配件", "sku", "sku")):
lt = service.create_concept("link_type", name, spec={"from_type": f, "to_type": t, "cardinality": "n:1"})
service.set_binding(lt["id"], ds, "join", {"from_column": fc, "to_column": tc})
out["fit"] = service.create_concept("link_type", "适配", spec={"from_type": "配件", "to_type": "车型",
"cardinality": "n:n", "inverse_name": "适用配件"})
service.set_binding(out["fit"]["id"], ds, "join", {"via_table": "fit", "via_from": "sku", "via_to": "mid",
"props": {"备注": "note"}})
# 动作:发货 / 到货入库(状态流转)、调整在库、生成补货建议
out["ship"] = service.create_concept("action", "发货", spec={
"target_type": "采购单", "transition": {"property": "状态", "from": ["已下单"], "to": "运输中"},
"approval": {"mode": "auto"}})
out["arrive"] = service.create_concept("action", "到货入库", spec={
"target_type": "采购单", "transition": {"property": "状态", "to": "已到货"}, "approval": {"mode": "auto"}})
out["adjust"] = service.create_concept("action", "调整在库", spec={
"target_type": "库存位", "params": [{"name": "qty", "label": "在库", "type": "integer", "required": True}],
"effects": [{"tool": "object.write", "args": {"object_type": "库存位", "key": "$obj_key", "values": {"在库": "$qty"}}}],
"approval": {"mode": "auto"}})
out["suggest"] = service.create_concept("action", "生成补货建议", spec={
"target_type": "库存位", "params": [{"name": "qty", "label": "数量", "type": "integer", "required": True}],
"effects": [{"tool": "object.create", "args": {"object_type": "补货建议",
"values": {"库存位": "$obj.label", "建议数量": "$qty"}}}],
"approval": {"mode": "auto"}})
# 对象集与指标
out["low"] = service.create_concept("function", "低库存位", spec={
"category": "object_set", "base": "库存位", "where": {"mode": "all", "items": [{"left": "可用", "op": "lt", "right": "$门槛"}]},
"inputs": [{"name": "门槛", "type": "number", "default": 15}]})
out["lowparts"] = service.create_concept("function", "低库存的配件", spec={
"category": "object_set", "base": "低库存位", "around": [{"link": "存放配件"}]})
out["out_qty"] = service.create_concept("function", "日出库量", spec={
"category": "aggregate", "unit": "件", "period": {"grain": "day"}})
service.set_binding(out["out_qty"]["id"], ds, "metric_expr", {
"base_table": "outbound", "expression": "SUM(qty)", "time_column": "day",
"dimensions": {"仓库": "wh", "配件": "sku"}, "dimension_types": {"配件": "配件"}})
out["low_count"] = service.create_concept("function", "低库存位数", spec={"category": "aggregate", "unit": "个"})
service.set_binding(out["low_count"]["id"], ds, "metric_expr", {"base_set": "低库存位", "expression": "COUNT(*)",
"dimensions": {"仓库": "wh"}})
service.publish("v10 内核测试")
return out