db.py
16.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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
"""MySQL 状态管理(otlg_ 前缀)。仅存文件/任务/检索/配置元数据;图与向量存文件。
v2 变化:
- Document 增加 stored_name / encoding / parse_warning,显示名与磁盘名彻底解耦(修乱码)。
- Job 增加 stage/current/total/detail,进度落库 —— 刷新页面不再丢进度。
- QueryLog 增加 mode/duration_ms,便于后续做检索质量分析。
"""
from __future__ import annotations
import json
import logging
import datetime as dt
from typing import Any, Optional
from sqlalchemy import (
create_engine, String, Integer, Text, DateTime, BigInteger,
func, select, update, delete, inspect, text as sa_text,
)
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
from .config import get_settings, DEFAULT_RUNTIME
from .reqcache import per_request
log = logging.getLogger(__name__)
_settings = get_settings()
engine = create_engine(_settings.sqlalchemy_url, pool_pre_ping=True, pool_recycle=1800, future=True)
_LONGTEXT = Text().with_variant(Text(length=4_000_000), "mysql")
# 必须用原生 CURRENT_TIMESTAMP,不能用 func.now()。
# SQLAlchemy 会把 func.now() 渲染成 `DEFAULT (now())` —— 这是"函数式默认值",
# MySQL 8.0.23 在对这种表做 ALTER TABLE ADD COLUMN 时会报
# "Invalid default value for 'created_at'",导致老库升不上来。
_NOW = sa_text("CURRENT_TIMESTAMP")
class Base(DeclarativeBase):
pass
class Document(Base):
__tablename__ = "otlg_document"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
filename: Mapped[str] = mapped_column(String(512)) # 显示名(已做编码修复)
stored_name: Mapped[str] = mapped_column(String(255), default="") # 磁盘名,纯 ascii
stored_path: Mapped[str] = mapped_column(String(1024))
file_hash: Mapped[str] = mapped_column(String(64), default="")
size_bytes: Mapped[int] = mapped_column(BigInteger, default=0)
encoding: Mapped[str] = mapped_column(String(32), default="") # 实际探测到的编码
parse_warning: Mapped[str] = mapped_column(Text, default="") # 如"疑似扫描件"
status: Mapped[str] = mapped_column(String(32), default="uploaded")
chunk_count: Mapped[int] = mapped_column(Integer, default=0)
entity_count: Mapped[int] = mapped_column(Integer, default=0)
relation_count: Mapped[int] = mapped_column(Integer, default=0)
error: Mapped[str] = mapped_column(Text, default="")
# 属于哪个本体空间;空 = 各空间共用(这一列出现之前上传的文档都是共用的)
workspace: Mapped[str] = mapped_column(String(64), default="")
created_at: Mapped[dt.datetime] = mapped_column(DateTime, server_default=_NOW)
updated_at: Mapped[dt.datetime] = mapped_column(DateTime, server_default=_NOW, onupdate=func.now())
class Job(Base):
__tablename__ = "otlg_job"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
doc_id: Mapped[int] = mapped_column(Integer, default=0)
job_type: Mapped[str] = mapped_column(String(32), default="extract")
status: Mapped[str] = mapped_column(String(32), default="queued") # queued/running/done/failed/cancelled
stage: Mapped[str] = mapped_column(String(32), default="")
progress: Mapped[int] = mapped_column(Integer, default=0)
current: Mapped[int] = mapped_column(Integer, default=0)
total: Mapped[int] = mapped_column(Integer, default=0)
message: Mapped[str] = mapped_column(Text, default="")
detail: Mapped[str] = mapped_column(_LONGTEXT, default="[]") # 事件日志快照(JSON)
started_at: Mapped[dt.datetime] = mapped_column(DateTime, server_default=_NOW)
finished_at: Mapped[Optional[dt.datetime]] = mapped_column(DateTime, nullable=True)
class QueryLog(Base):
__tablename__ = "otlg_query_log"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
question: Mapped[str] = mapped_column(Text)
mode: Mapped[str] = mapped_column(String(24), default="agentic")
params_json: Mapped[str] = mapped_column(Text, default="{}")
trace_json: Mapped[str] = mapped_column(_LONGTEXT, default="[]")
answer: Mapped[str] = mapped_column(_LONGTEXT, default="")
subgraph_json: Mapped[str] = mapped_column(_LONGTEXT, default="{}")
duration_ms: Mapped[int] = mapped_column(Integer, default=0)
created_at: Mapped[dt.datetime] = mapped_column(DateTime, server_default=_NOW)
class Config(Base):
__tablename__ = "otlg_config"
cfg_key: Mapped[str] = mapped_column(String(64), primary_key=True)
cfg_value: Mapped[str] = mapped_column(Text().with_variant(Text(length=1_000_000), "mysql"))
updated_at: Mapped[dt.datetime] = mapped_column(DateTime, server_default=_NOW, onupdate=func.now())
# create_all 不会给已存在的表补列。以后给模型加列时,在这里登记一条,
# 已经建好的库(包括演示版本的快照库)启动时会自动补上。例:
# "otlg_job": {"stage": "VARCHAR(32) NOT NULL DEFAULT ''"},
_ADD_COLUMNS: dict[str, dict[str, str]] = {
"otlg_sm_model": {"db_comment": "TEXT NULL"},
"otlg_sm_column": {"db_comment": "TEXT NULL"},
"otlg_sop_run": {"kind": "VARCHAR(16) NOT NULL DEFAULT 'main'",
"row_index": "INT NOT NULL DEFAULT 0",
"parent_run_id": "VARCHAR(64) NOT NULL DEFAULT ''"},
"otlg_mem_case": {"voters_json": "TEXT"},
"otlg_document": {"workspace": "VARCHAR(64) NOT NULL DEFAULT ''"},
"otlg_approval": {"stage": "INT NOT NULL DEFAULT 0", "stage_name": "VARCHAR(64) NOT NULL DEFAULT ''"},
"otlg_watch_state": {"label": "VARCHAR(255) NOT NULL DEFAULT ''", "first_seen_at": "DATETIME NULL",
"recovered_at": "DATETIME NULL", "detail_json": "LONGTEXT"},
}
def get_engine():
"""当前请求所在环境(开发 / 某个演示版本)的元数据库引擎。
开发环境就是 `engine` 本身(测试里 patch 它就够了);演示版本各有一个独立的库,见 core/envs.py。
"""
from . import envs
return envs.engine_for_current()
def _register_models() -> None:
# 各子系统的表定义在各自的 models.py。必须在 create_all 之前 import
# 才会注册到 Base.metadata;放在函数体里 import 是为了绕开循环依赖
# (那些模块要从这里拿 Base / _LONGTEXT / _NOW)。
from ..text2sql import models as _t2s_models # noqa: F401
from ..governance import models as _gov_models # noqa: F401
from ..kernel import models as _kernel_models # noqa: F401
from ..capability import models as _cap_models # noqa: F401
from ..sop import models as _sop_models # noqa: F401
from ..agents import models as _ask_models # noqa: F401
from ..evals import models as _eval_models # noqa: F401
from ..memory import models as _mem_models # noqa: F401
from ..watch import models as _watch_models # noqa: F401
from . import envs as _envs # noqa: F401
def init_schema(eng) -> None:
"""建表(IF NOT EXISTS)→ 补列。主库和演示快照库共用,老快照也能跟上新代码的表结构。"""
_register_models()
Base.metadata.create_all(eng)
if not _ADD_COLUMNS:
return
insp = inspect(eng)
with eng.begin() as conn:
for table, cols in _ADD_COLUMNS.items():
try:
existing_cols = {c["name"] for c in insp.get_columns(table)}
except Exception:
continue
for name, ddl in cols.items():
if name not in existing_cols:
conn.execute(sa_text("ALTER TABLE `%s` ADD COLUMN `%s` %s" % (table, name, ddl)))
def init_db() -> None:
"""主库:建表 / 补列 → seed 默认运行时配置。"""
init_schema(engine)
with Session(engine) as s:
existing = {c.cfg_key for c in s.scalars(select(Config)).all()}
for k, v in DEFAULT_RUNTIME.items():
if k not in existing:
s.add(Config(cfg_key=k, cfg_value=v))
# v1 遗留的、v2 已删除的配置键清理掉,免得设置页显示僵尸项
for k in existing - set(DEFAULT_RUNTIME):
s.execute(delete(Config).where(Config.cfg_key == k))
s.commit()
# ---------- 运行时配置 ----------
@per_request
def get_all_config() -> dict[str, str]:
with Session(get_engine()) as s:
rows = s.scalars(select(Config)).all()
cfg = {**DEFAULT_RUNTIME}
cfg.update({r.cfg_key: r.cfg_value for r in rows})
return cfg
@per_request
def get_config(key: str, default: str | None = None) -> str:
with Session(get_engine()) as s:
row = s.get(Config, key)
if row is not None:
return row.cfg_value
return DEFAULT_RUNTIME.get(key, default if default is not None else "")
def set_config(items: dict[str, str]) -> None:
with Session(get_engine()) as s:
for k, v in items.items():
row = s.get(Config, k)
if row is None:
s.add(Config(cfg_key=k, cfg_value=str(v)))
else:
row.cfg_value = str(v)
s.commit()
# ---------- 文档 ----------
def create_document(filename: str, stored_path: str, size_bytes: int, file_hash: str = "",
stored_name: str = "", workspace: str = "") -> int:
with Session(get_engine()) as s:
d = Document(filename=filename, stored_path=stored_path, size_bytes=size_bytes,
file_hash=file_hash, stored_name=stored_name, status="uploaded", workspace=workspace)
s.add(d)
s.commit()
return d.id
def find_document_by_hash(file_hash: str, workspace: str | None = None) -> Optional[dict]:
"""同一个文件只存一份 —— 按本体空间算:别的空间传过同一份文件,这里看不到它,要能再传一次。"""
with Session(get_engine()) as s:
q = select(Document).where(Document.file_hash == file_hash)
if workspace is not None:
q = q.where(Document.workspace.in_(["", workspace]))
r = s.scalars(q).first()
return _doc_dict(r) if r else None
def update_document(doc_id: int, **fields: Any) -> None:
if not fields:
return
with Session(get_engine()) as s:
s.execute(update(Document).where(Document.id == doc_id).values(**fields))
s.commit()
def _doc_dict(r: "Document") -> dict:
return {
"id": r.id, "filename": r.filename, "stored_name": r.stored_name or "",
"stored_path": r.stored_path, "status": r.status, "size_bytes": r.size_bytes,
"encoding": r.encoding or "", "parse_warning": r.parse_warning or "",
"chunk_count": r.chunk_count, "entity_count": r.entity_count,
"relation_count": r.relation_count, "error": r.error or "", "workspace": r.workspace or "",
"created_at": r.created_at.isoformat() if r.created_at else None,
"updated_at": r.updated_at.isoformat() if r.updated_at else None,
}
def list_documents(workspace: str | None = None) -> list[dict]:
"""workspace 给了:只列这个本体空间的文档,加上各空间共用的(workspace 为空的老文档)。"""
with Session(get_engine()) as s:
stmt = select(Document).order_by(Document.id.desc())
if workspace is not None:
stmt = stmt.where(Document.workspace.in_(["", workspace]))
return [_doc_dict(r) for r in s.scalars(stmt).all()]
def document_ids(workspace: str) -> set[int]:
"""这个本体空间看得到的文档 id(知识检索按它过滤原文片段)。"""
with Session(get_engine()) as s:
return set(s.scalars(select(Document.id).where(Document.workspace.in_(["", workspace]))).all())
def get_document(doc_id: int) -> Optional[dict]:
with Session(get_engine()) as s:
r = s.get(Document, doc_id)
return _doc_dict(r) if r else None
def delete_document(doc_id: int) -> None:
with Session(get_engine()) as s:
s.execute(delete(Document).where(Document.id == doc_id))
s.commit()
# ---------- 任务 ----------
def create_job(doc_id: int, job_type: str = "extract") -> int:
with Session(get_engine()) as s:
j = Job(doc_id=doc_id, job_type=job_type, status="queued")
s.add(j)
s.commit()
return j.id
def update_job(job_id: int, **fields: Any) -> None:
if not fields:
return
if "detail" in fields and not isinstance(fields["detail"], str):
fields["detail"] = json.dumps(fields["detail"], ensure_ascii=False)[:3_000_000]
with Session(get_engine()) as s:
s.execute(update(Job).where(Job.id == job_id).values(**fields))
s.commit()
def finish_job(job_id: int, status: str, message: str = "") -> None:
values: dict[str, Any] = {"status": status, "message": (message or "")[:60000],
"finished_at": func.now()}
if status == "done":
values["progress"] = 100
with Session(get_engine()) as s:
s.execute(update(Job).where(Job.id == job_id).values(**values))
s.commit()
def _job_dict(r: "Job") -> dict:
try:
detail = json.loads(r.detail) if r.detail else []
except Exception:
detail = []
return {"id": r.id, "doc_id": r.doc_id, "job_type": r.job_type, "status": r.status,
"stage": r.stage or "", "progress": r.progress, "current": r.current, "total": r.total,
"message": r.message or "", "detail": detail,
"started_at": r.started_at.isoformat() if r.started_at else None,
"finished_at": r.finished_at.isoformat() if r.finished_at else None}
def get_job(job_id: int) -> Optional[dict]:
with Session(get_engine()) as s:
r = s.get(Job, job_id)
return _job_dict(r) if r else None
def list_jobs(limit: int = 20) -> list[dict]:
with Session(get_engine()) as s:
rows = s.scalars(select(Job).order_by(Job.id.desc()).limit(limit)).all()
return [_job_dict(r) for r in rows]
def active_job_for_doc(doc_id: int) -> Optional[dict]:
with Session(get_engine()) as s:
r = s.scalars(
select(Job).where(Job.doc_id == doc_id, Job.status.in_(["queued", "running"]))
.order_by(Job.id.desc())
).first()
return _job_dict(r) if r else None
def reap_stale_jobs() -> int:
"""进程重启后,把库里残留的 running/queued 标记为 failed,避免 UI 永远转圈。"""
with Session(get_engine()) as s:
res = s.execute(update(Job).where(Job.status.in_(["queued", "running"])).values(
status="failed", message="服务重启,任务中断", finished_at=func.now()))
s.commit()
return res.rowcount or 0
# ---------- 检索留痕 ----------
def log_query(question: str, mode: str, params: dict, trace: list, answer: str,
subgraph: dict, duration_ms: int = 0) -> int:
with Session(get_engine()) as s:
q = QueryLog(
question=question, mode=mode,
params_json=json.dumps(params, ensure_ascii=False)[:60000],
trace_json=json.dumps(trace, ensure_ascii=False)[:3_000_000],
answer=(answer or "")[:3_000_000],
subgraph_json=json.dumps(subgraph, ensure_ascii=False)[:3_000_000],
duration_ms=duration_ms,
)
s.add(q)
s.commit()
return q.id
def list_queries(limit: int = 20) -> list[dict]:
with Session(get_engine()) as s:
rows = s.scalars(select(QueryLog).order_by(QueryLog.id.desc()).limit(limit)).all()
return [{"id": r.id, "question": r.question, "mode": r.mode,
"duration_ms": r.duration_ms,
"answer_preview": (r.answer or "")[:160],
"created_at": r.created_at.isoformat() if r.created_at else None} for r in rows]
def get_query(qid: int) -> Optional[dict]:
with Session(get_engine()) as s:
r = s.get(QueryLog, qid)
if not r:
return None
def _j(v, d):
try:
return json.loads(v)
except Exception:
return d
return {"id": r.id, "question": r.question, "mode": r.mode,
"trace": _j(r.trace_json, []), "answer": r.answer,
"subgraph": _j(r.subgraph_json, {}),
"duration_ms": r.duration_ms,
"created_at": r.created_at.isoformat() if r.created_at else None}