feat: 新增单位工程级工料机汇总(lme_uw)并将项目工料机数据源切换为项目级汇总

This commit is contained in:
lianjianwei2024
2026-10-12 08:32:34 +08:00
parent ced87bde6f
commit fb1875e8b2
25 changed files with 1775 additions and 190 deletions

4
release/testdata/bench_history.jsonl vendored Normal file
View File

@@ -0,0 +1,4 @@
{"ts": "2026-10-11 15:32:14", "db": "history-test.db", "rows": {"batches": 1744, "bills": 989798, "norms": 3959062, "norm_res": 16233720, "lmes": 78384, "prices": 1840, "sessions": 500, "s_bills": 138181}, "db_mb": 1988.7, "q_ms": {"批次列表·首页50": 0.1, "批次列表·深翻页50": 1.1, "批次筛选·project计数": 0.3, "打开项目·清单树全拉": 1.9, "工料机列表·统一过滤": 37.3, "工料机检索·LIKE%混凝土%": 458.1, "单批次·定额消耗链计数": 5.1, "类似清单·精确命中x20": 79.0, "价格命中x20": 107.6, "最近审核·列表聚合": 3637.3, "工作台打开·清单全拉": 1.6, "工作台·工料机过滤列表": 10.8}, "s_db_mb": 254.5}
{"ts": "2026-10-11 15:47:16", "db": "history-test.db", "rows": {"batches": 1736, "bills": 985181, "norms": 3940597, "norm_res": 16157921, "lmes": 78016, "prices": 1840, "sessions": 500, "s_bills": 138181}, "db_mb": 1996.0, "q_ms": {"批次列表·首页50": 0.3, "批次列表·深翻页50": 1.4, "批次筛选·project计数": 0.3, "打开项目·清单树全拉": 2.5, "工料机列表·统一过滤": 0.2, "工料机检索·LIKE%混凝土%": 1.3, "单批次·定额消耗链计数": 2.5, "类似清单·精确命中x20": 126.6, "价格命中x20": 23.0, "最近审核·列表聚合": 1859.7, "工作台打开·清单全拉": 1.5, "工作台·工料机过滤列表": 0.4}, "s_db_mb": 254.5}
{"ts": "2026-10-11 17:11:35", "db": "history-test.db", "rows": {"batches": 6036, "bills": 1893356, "norms": 7573409, "norm_res": 31056407, "lmes": 137816, "prices": 139840, "sessions": 2000, "s_bills": 1868365}, "db_mb": 3859.3, "q_ms": {"批次列表·首页50": 0.3, "批次列表·深翻页50": 4.9, "批次筛选·project计数": 2.1, "打开项目·清单树全拉": 63.7, "工料机列表·统一过滤": 13.0, "工料机检索·LIKE%混凝土%": 459.3, "单批次·定额消耗链计数": 3.1, "类似清单·精确命中x20": 6762.7, "价格命中x20": 154.0, "最近审核·列表聚合": 65108.2, "工作台打开·清单全拉": 2.4, "工作台·工料机过滤列表": 0.2}, "s_db_mb": 3436.8}
{"ts": "2026-10-12 07:40:22", "db": "history-test.db", "rows": {"batches": 27036, "bills": 6799351, "norms": 27195683, "norm_res": 111506219, "lmes": 459816, "prices": 783840, "sessions": 10000, "s_bills": 11057380}, "db_mb": 14162.3, "q_ms": {"批次列表·首页50": 0.4, "批次列表·深翻页50": 26.7, "批次筛选·project计数": 9.3, "打开项目·清单树全拉": 68.4, "工料机列表·统一过滤": 2.3, "工料机检索·LIKE%混凝土%": 461.4, "单批次·定额消耗链计数": 1.6, "类似清单·精确命中x20": 8146.3, "价格命中x20": 159.1, "最近审核·列表聚合": 442676.3, "工作台打开·清单全拉": 9.8, "工作台·工料机过滤列表": 32.1}, "s_db_mb": 20816.2}

View File

@@ -1,15 +1,25 @@
# -*- coding: utf-8 -*-
"""一次性核查:lmes / norm_res 在测试库里的真实行数(只读,不写任何东西)。"""
import glob
"""核查:lmes / norm_res 在测试库里的真实行数(只读,不写任何东西)。
2026-10-11:路径改走 gen_testdata.find_data_dir()(旧 glob 指向改名前的目录必 IndexError)。"""
import os
import sqlite3
import sys
sys.stdout.reconfigure(errors="replace")
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import gen_testdata as G
h = glob.glob("D:/Pricing review*/\u9020\u4ef7\u5ba1\u6838/data/history-test.db")[0]
s = glob.glob("D:/Pricing review*/\u9020\u4ef7\u5ba1\u6838/data/session-test.db")[0]
dd = G.find_data_dir()
if not dd:
print("!! 找不到数据目录(history.db)")
sys.exit(1)
h, s = G.db_paths(dd)[1], G.db_paths(dd)[3]
print("数据目录:", dd)
if not os.path.exists(h):
print("测试库 history-test.db 不存在——先在控制台生成一批。")
sys.exit(1)
print("history-test:", h)
print("session-test:", s)
hc = sqlite3.connect(h, timeout=10)
q = "FROM batches WHERE is_mock=1 AND Name LIKE '\u6d4b\u8bd5%'"
@@ -46,6 +56,10 @@ if bid:
print(" norm_res 行数:", row[0])
hc.close()
if not os.path.exists(s):
print("\nsession-test.db 不存在(工作台侧未生成),跳过。")
sys.exit(0)
print("\nsession-test:", s)
sc = sqlite3.connect(s, timeout=10)
print("\n== session-test.db 真实行数 ==")
for name, sql in {

View File

@@ -17,8 +17,13 @@ SQLite 变量上限(32766)会直接报错。
命令行:
python gen_testdata.py --check # 统计现有测试数据
python gen_testdata.py --run run_cfg.json # 按参数生成(控制台写这份 json)
python gen_testdata.py --bench # 性能体检:只读实测母体热点查询耗时
python gen_testdata.py --delete --yes # 分块删除全部测试数据(含附件文件)
python gen_testdata.py --delete --yes --keep-files # 只删库行不删附件文件
测「数据库上限」的方法(2026-10-11):从小到大逐级生成(如 1千 → 5千 → 1万 → 5万
项目),每级跑一次 --bench,哪条查询突破可接受阈值(如 1 秒),哪里就是软件的实际
容量上限。体检结果自动追加存档 bench_history.jsonl,逐级对比即可画曲线。
"""
import argparse
import glob
@@ -27,6 +32,7 @@ import json
import os
import random
import re
import shutil
import sqlite3
import sys
import time
@@ -389,6 +395,46 @@ def gen_builder(rng):
nm += rng.choice(_TAIL)
return nm
# 语义匹配词表:清单名关键词 → 同族定额;定额名 → 人工/材料/机械构成
NKEYS = ["土方", "土", "混凝土", "钢筋", "砌", "防水", "卷材", "抹灰", "油漆", "涂料",
"窗", "门", "脚手", "道路", "沥青", "人行", "井", "给水", "排水", "电缆",
"桥架", "灯", "管", "乔木", "灌木", "草", "绿地", "面层", "基层", "钢结构"]
MKEYS = ["挖掘", "运输", "汽车", "泵", "压路", "起重", "搅拌", "切断", "装载", "吊装",
"夯实", "打桩", "机械"]
# 点名映射:内置池语料有限,专有清单直接指族(命中不了再走通用关键词)
HINTS = [("措施项目费", ["脚手", "安全文明"]), ("安全文明", ["脚手", "安全文明"]),
("综合脚手架", ["脚手"]), ("栽植", ["乔木", "灌木"]), ("棕榈", ["乔木", "灌木"]),
("绿地", ["绿地"]), ("喷播", ["草", "喷播"]), ("路灯", ["灯", "路灯"]),
("灯具", ["灯"]), ("变压器", ["电缆", "变压器"]), ("检查井", ["井"]),
("桥架", ["桥架"]), ("电缆", ["电缆"]), ("井盖", ["井"])]
def build_norm_index(norms):
"""关键词 → 定额 倒排索引(一次构建,整个生成期复用)。
旧实现每条清单都对全定额池逐条做子串匹配(真实词料池可达 4000 条 × 30 个关键词),
1 万项目 × 800 清单就是上千亿次子串扫描——生成期最大 CPU 热点,动辄数十小时。
索引后每条清单只合并命中的几个桶,与旧口径逐字等价(命中集相同)。"""
kws = set(NKEYS)
for _h, hs in HINTS:
kws.update(hs)
ix = {}
for n in norms:
nm = n[1] or ""
for k in kws:
if k in nm:
ix.setdefault(k, []).append(n)
hint_ix = {}
for h, hs in HINTS:
merged, seen = [], set()
for kk in hs:
for n in ix.get(kk, ()):
if id(n) not in seen:
seen.add(id(n))
merged.append(n)
hint_ix[h] = merged
return ix, hint_ix
# ---------------- 词料采集(优先用库里的真实词料,增强真实感) ----------------
def harvest(con):
@@ -441,6 +487,7 @@ class Words:
self.norms = (h["norms"] if len(h["norms"]) >= 12 else []) or NORM_ITEMS
self.lmes = (h["lmes"] if len(h["lmes"]) >= 60 else []) or LME_BUILTIN
self.builders = h["builders"] or [gen_builder(random.Random(i)) for i in range(80)]
self.norm_ix, self.hint_ix = build_norm_index(self.norms)
# ---------------- 附件文件(名字确定性 → 重跑原地覆盖,不累积孤儿文件) ----------------
@@ -567,9 +614,23 @@ def _paused():
return os.path.exists(PAUSE_FLAG)
def _open_db(path):
def _open_db(path, bulk=False):
"""bulk=False:常规读写(版本对齐等小批量写,含可能打开真实库)——保守参数。
bulk=True:仅用于测试库批量生成——synchronous=OFF(测试数据可再生,断电大不了重来)
+ 关自动 checkpoint(实测 2GB 库上每次 commit 触发 checkpoint 要 7s,百兆脏页随机
回拷是生成最大拖累;关掉后 commit 0.1s,WAL 增长由 _ckpt 每 10 份做一次 PASSIVE
兜底,收尾 run() 再 TRUNCATE 清干净)。"""
con = sqlite3.connect(path, timeout=60)
con.execute("PRAGMA busy_timeout=30000")
con.execute("PRAGMA cache_size=-65536")
con.execute("PRAGMA temp_store=MEMORY")
if bulk:
con.execute("PRAGMA synchronous=OFF")
con.execute("PRAGMA wal_autocheckpoint=0")
con.execute("PRAGMA cache_size=-262144") # 256MB:索引页散布全库,缓存大些少读盘
else:
# WAL 下 NORMAL 进程崩溃不丢数据(仅断电才可能丢最后一笔),大批量插入也明显提速
con.execute("PRAGMA synchronous=NORMAL")
return con
@@ -608,6 +669,17 @@ def _merge(st, add):
st[k] = st.get(k, 0) + v
return st
def _db_mb(p):
"""库文件体积(含 -wal/-shm),MB。"""
n = 0.0
for e in ("", "-wal", "-shm"):
try:
n += os.path.getsize(p + e)
except OSError:
pass
return n / 1048576.0
# ---------------- 结构级插入(history 与 session 两库共用一份逻辑数据) ----------------
# 逻辑行里的 owner 索引是本地序号,插入时映射为真实 id。
@@ -727,21 +799,29 @@ def insert_tree(con, sqls, owner_id, data, ym=None):
cur.execute(bill_sql, vals)
bill_ids.append(cur.lastrowid)
data["bill_ids"] = bill_ids
# 定额逐条插(要 lastrowid 挂消耗),消耗行攒齐一个项目一次 executemany——
# 万级项目下 norm_res 有上亿行,逐条 execute 光 Python 调用开销就要数小时
res_rows = []
for bi, norms in enumerate(data["norms"]):
for nrow in norms:
cur.execute(sqls["norm"], (bill_ids[bi],) + tuple(nrow[:6]))
nid = cur.lastrowid
for (res_code, rq) in nrow[6]:
cur.execute(sqls["res"], (nid, res_code, rq))
res_rows.append((nid, res_code, rq))
if res_rows:
cur.executemany(sqls["res"], res_rows)
lme_vals = []
for row in data["lmes"]:
vals = [owner_id] + list(row[:13])
if pdl:
vals += [ym, ym]
cur.execute(lme_sql, vals)
for row in data["lib"]:
cur.execute(sqls["lib"], [owner_id] + list(row))
for row in data["proj"]:
cur.execute(sqls["proj"], [owner_id] + list(row))
lme_vals.append(vals)
if lme_vals:
cur.executemany(lme_sql, lme_vals)
if data["lib"]:
cur.executemany(sqls["lib"], [[owner_id] + list(r) for r in data["lib"]])
if data["proj"]:
cur.executemany(sqls["proj"], [[owner_id] + list(r) for r in data["proj"]])
return {"sec": sec_map, "uw": uw_map, "div": div_map}
@@ -774,10 +854,13 @@ def build_project_data(rng, cfg, words, m_idx, bid_local=True):
# 清单
bill_target = rng.randint(int(cfg["bill_lo"]), max(int(cfg["bill_lo"]), int(cfg["bill_hi"])))
uw_ids = [u[0] for u in uws]
divs_by_uw = {}
for d in divs:
divs_by_uw.setdefault(d[0], []).append(d)
seq = 0
for i in range(bill_target):
uw_l = rng.choice(uw_ids)
ds = [d for d in divs if d[0] == uw_l]
ds = divs_by_uw.get(uw_l)
if not ds:
continue
d = rng.choice(ds)
@@ -812,33 +895,44 @@ def build_project_data(rng, cfg, words, m_idx, bid_local=True):
lme_by_kind = {1: [], 2: [], 3: []}
for it in lme_pool:
lme_by_kind.setdefault(it[4] or 2, []).append(it)
# 语义匹配:清单名关键词 → 同族定额;定额名 → 人工/材料/机械构成
NKEYS = ["土方", "土", "混凝土", "钢筋", "砌", "防水", "卷材", "抹灰", "油漆", "涂料",
"窗", "门", "脚手", "道路", "沥青", "人行", "井", "给水", "排水", "电缆",
"桥架", "灯", "管", "乔木", "灌木", "草", "绿地", "面层", "基层", "钢结构"]
MKEYS = ["挖掘", "运输", "汽车", "泵", "压路", "起重", "搅拌", "切断", "装载", "吊装",
"夯实", "打桩", "机械"]
# 点名映射:内置池语料有限,专有清单直接指族(命中不了再走通用关键词)
HINTS = [("措施项目费", ["脚手", "安全文明"]), ("安全文明", ["脚手", "安全文明"]),
("综合脚手架", ["脚手"]), ("栽植", ["乔木", "灌木"]), ("棕榈", ["乔木", "灌木"]),
("绿地", ["绿地"]), ("喷播", ["草", "喷播"]), ("路灯", ["灯", "路灯"]),
("灯具", ["灯"]), ("变压器", ["电缆", "变压器"]), ("检查井", ["井"]),
("桥架", ["桥架"]), ("电缆", ["电缆"]), ("井盖", ["井"])]
# 语义匹配走倒排索引(words.norm_ix / words.hint_ix,Words 里一次构建)
for b in bills:
cand = None
for hint, hs in HINTS:
for hint, _hs in HINTS:
if hint in b[3]:
cand = [n for n in words.norms if any(h in n[1] for h in hs)]
break
cand = words.hint_ix.get(hint) or None
if cand:
break
if not cand:
keys = [kk for kk in NKEYS if kk in b[3]]
cand = [n for n in words.norms if any(kk in n[1] for kk in keys)] or list(words.norms)
if keys:
merged, seen = [], set()
for kk in keys:
for n in words.norm_ix.get(kk, ()):
if id(n) not in seen:
seen.add(id(n))
merged.append(n)
cand = merged
cand = cand or words.norms
k = rng.randint(nrm_lo, nrm_hi)
bl = []
used = set()
big = len(cand) > 12
for _ in range(k):
pickable = [n for n in cand if n[0] not in used] or cand
ncode, nname, nunit = rng.choice(pickable)
if big:
# 池大时随机试探替代「全池过滤重建」:同是优先未用定额,免去每次 k×全池扫描
pick = None
for _t in range(10):
n_ = rng.choice(cand)
if n_[0] not in used:
pick = n_
break
if pick is None:
pick = rng.choice(cand)
else:
pickable = [n for n in cand if n[0] not in used] or cand
pick = rng.choice(pickable)
ncode, nname, nunit = pick
used.add(ncode)
nqty = max(round(b[6] * rng.uniform(0.05, 0.6), 2), 0.01)
nprice = guess_price(nname, nunit, m_idx)
@@ -915,6 +1009,7 @@ def gen_projects(hc, sc, dd, cfg, rng, words, log, start=0):
pver = _parser_vers(dd)[0] # 工程线版本
n = int(cfg["n_project"])
linked = bool(cfg.get("session_linked"))
t0 = time.time()
stats = {"project": 0, "bills": 0, "norms": 0, "res": 0, "lmes": 0,
"inq": 0, "binds": 0, "sessions": 0}
for i in range(n):
@@ -1012,15 +1107,23 @@ def gen_projects(hc, sc, dd, cfg, rng, words, log, start=0):
i + 1, n, name, len(data["bills"]), sum(len(x) for x in data["norms"]),
len(data["lmes"]), len(inq_ids),
"(+镜像会话)" if linked else ""))
# 量级进度:上限测试跑的是万级项目,光看逐条日志没有体积/速率概念
if (i + 1) % 25 == 0 or i + 1 == n:
el = time.time() - t0
log(" …进度 %d/%d | %.0fs | 累计清单 %d(%.0f 行/s)| history %.0f MB%s" % (
i + 1, n, el, stats["bills"], stats["bills"] / max(el, 0.001),
_db_mb(db_paths(dd)[1]),
(" + session %.0f MB" % _db_mb(db_paths(dd)[3])) if sc is not None else ""))
return stats
# ---------------- 独立工作台会话 ----------------
def gen_sessions_standalone(sc, cfg, rng, words, log):
def gen_sessions_standalone(sc, dd, cfg, rng, words, log):
y_a, y_b = _ym_range(cfg)
n = int(cfg.get("n_session", 0))
sub = dict(cfg)
sub["bill_lo"], sub["bill_hi"] = cfg.get("sbill_lo", 150), cfg.get("sbill_hi", 400)
t0 = time.time()
stats = {"sessions": 0, "bills": 0, "norms": 0, "res": 0, "lmes": 0}
for i in range(n):
if _paused():
@@ -1053,6 +1156,11 @@ def gen_sessions_standalone(sc, cfg, rng, words, log):
stats["res"] += sum(len(n2[6]) for x in data["norms"] for n2 in x)
stats["lmes"] += len(data["lmes"])
log(" [%d/%d] %s:清单 %d(独立会话)" % (i + 1, n, name, len(data["bills"])))
if (i + 1) % 25 == 0 or i + 1 == n:
el = time.time() - t0
log(" …进度 %d/%d | %.0fs | 累计清单 %d(%.0f 行/s)| session %.0f MB" % (
i + 1, n, el, stats["bills"], stats["bills"] / max(el, 0.001),
_db_mb(db_paths(dd)[3])))
return stats
# ---------------- 市场价 / 信息价 ----------------
@@ -1135,6 +1243,9 @@ def gen_prices(hc, dd, cfg, rng, words, log):
_ckpt(hc)
stats[kind] += 1
stats["price_rows"] += n_rows
if (i + 1) % 200 == 0 or i + 1 == cnt:
log(" …%s 进度 %d/%d | history %.0f MB" % (
prefix, i + 1, cnt, _db_mb(db_paths(dd)[1])))
log(" %s:%d 份完成(每份 %d~%d 条,附件率 %d%%)" % (prefix, cnt, lo, hi, rate))
return stats
@@ -1428,6 +1539,173 @@ def delete_testdata(dd, keep_files=False, log=print):
st["_remaining"] = stats_of(dd)
return st
# ---------------- 性能体检(测「数据库上限」用,全程只读) ----------------
# 复刻母体 match.lme_list_where() 的过滤口径(2026-10-11 版)——体检查询与工作台/后台
# 「项目工料机」完全同形;不 import 母体代码,母体口径若变以那边为准。
LME_WHERE = ("CAST(IFNULL(%sKind,'') AS TEXT) NOT IN ('6','7') "
"AND TRIM(IFNULL(%sUnit,'')) NOT IN ('元','工日','台班')")
BENCH_HIST = os.path.join(HERE, "bench_history.jsonl")
class _BenchAbort(Exception):
pass
def bench_testdata(dd, log=print):
"""按母体真实热点查询做一次只读体检:输出当前库规模 + 各查询毫秒数,并追加存档
bench_history.jsonl。测上限用法:从小到大逐级生成(1千→5千→1万→…项目),每级跑
一次体检,哪条查询突破可接受阈值(如 1 秒),哪里就是软件的实际容量上限。
测试库不存在时退而测参考库(只读),并在输出里注明。"""
rh, th, rs, ts = db_paths(dd)
hp = th if os.path.exists(th) else rh
if not os.path.exists(hp):
log("!! 没有 history.db / history-test.db 可测(数据目录:%s)" % _disp(dd))
return None
res = {"ts": time.strftime("%Y-%m-%d %H:%M:%S"), "db": os.path.basename(hp),
"rows": {}, "db_mb": round(_db_mb(hp), 1), "q_ms": {}}
log("== 性能体检(只读)==")
log("被测库:%s(%.1f MB 含 WAL)%s" % (
res["db"], res["db_mb"],
"〔测试库〕" if hp == th else "〔参考库——测试库尚未生成,测的是真实库,只读不写〕"))
con = _open_ro(hp, timeout=15)
if con is None:
log("!! 库被占用(生成中或造价审核软件打开中),稍后再试。")
return None
def timed(name, sql, args=(), con_=None):
if _paused():
raise _BenchAbort
c = con_ or con
t0 = time.perf_counter()
try:
rows = c.execute(sql, args).fetchall()
except Exception as e:
log(" %-28s —— 跳过(%s)" % (name, str(e).split("\n")[0][:60]))
return []
ms = (time.perf_counter() - t0) * 1000.0
res["q_ms"][name] = round(ms, 1)
log(" %-28s %10.1f ms 返回 %s 行" % (name, ms, format(len(rows), ",")))
return rows
try:
# —— 规模 ——
log("-- 数据规模 --")
for t, label in (("batches", "批次"), ("bills", "清单"), ("norms", "定额"),
("norm_res", "定额消耗"), ("lmes", "工料机"), ("prices", "价格明细")):
try:
n = con.execute("SELECT COUNT(*) FROM %s" % t).fetchone()[0]
res["rows"][t] = n
log(" %-8s %15s 行" % (label, format(n, ",")))
except Exception:
pass
n_bat = res["rows"].get("batches", 0)
# —— 后台(history)热点 ——
log("-- 后台热点查询 --")
timed("批次列表·首页50", "SELECT id,Name,kind FROM batches ORDER BY id DESC LIMIT 50")
timed("批次列表·深翻页50", "SELECT id,Name,kind FROM batches ORDER BY id DESC LIMIT 50 OFFSET %d"
% max(0, n_bat - 50))
timed("批次筛选·project计数", "SELECT COUNT(*) FROM batches WHERE kind='project'")
row = con.execute(
"SELECT id FROM batches WHERE kind='project' ORDER BY id DESC LIMIT 1").fetchone()
bid = row[0] if row else 0
timed("打开项目·清单树全拉", "SELECT id,Number,Name,Attr,Unit,Quantity,Price,Total,Kind"
" FROM bills WHERE batch_id=? ORDER BY id", (bid,))
timed("工料机列表·统一过滤", "SELECT id FROM lmes WHERE batch_id=? AND %s ORDER BY id"
% (LME_WHERE % ("", "")), (bid,))
timed("工料机检索·LIKE%混凝土%",
"SELECT l.id FROM lmes l JOIN batches bt ON bt.id=l.batch_id"
" WHERE bt.kind='project' AND l.x_name_norm LIKE '%混凝土%' LIMIT 200")
timed("单批次·定额消耗链计数",
"SELECT COUNT(*) FROM norm_res r JOIN norms n ON n.id=r.norm_id"
" JOIN bills b ON b.id=n.bill_id WHERE b.batch_id=?", (bid,))
# 类似清单命中:与 match.py 一致,按哈希逐条查询,这里实测 20 次合计
hashes = [r[0] for r in con.execute(
"SELECT x_hash_exact FROM bills WHERE batch_id=? LIMIT 20", (bid,))]
if hashes:
t0 = time.perf_counter()
n_hit = 0
for h in hashes:
n_hit += len(con.execute(
"SELECT b.id FROM bills b JOIN batches bt ON bt.id=b.batch_id"
" WHERE b.x_hash_exact=? AND bt.kind='project' LIMIT 20", (h,)).fetchall())
ms = (time.perf_counter() - t0) * 1000.0
res["q_ms"]["类似清单·精确命中x20"] = round(ms, 1)
log(" %-28s %10.1f ms 20次合计,命中 %d" % ("类似清单·精确命中x20", ms, n_hit))
hashes = [r[0] for r in con.execute(
"SELECT x_hash_exact FROM lmes WHERE batch_id=? LIMIT 20", (bid,))]
if hashes and res["rows"].get("prices"):
t0 = time.perf_counter()
n_hit = 0
for h in hashes:
n_hit += len(con.execute(
"SELECT p.id FROM prices p JOIN batches bt ON bt.id=p.batch_id"
" WHERE p.x_hash_exact=? AND bt.kind IN ('market','info') LIMIT 20",
(h,)).fetchall())
ms = (time.perf_counter() - t0) * 1000.0
res["q_ms"]["价格命中x20"] = round(ms, 1)
log(" %-28s %10.1f ms 20次合计,命中 %d" % ("价格命中x20", ms, n_hit))
con.close()
con = None
# —— 工作台(session)热点 ——
sp = ts if os.path.exists(ts) else rs
if os.path.exists(sp):
scon = _open_ro(sp, timeout=15)
if scon is not None:
res["s_db_mb"] = round(_db_mb(sp), 1)
log("-- 工作台热点查询(%s,%.1f MB)--" % (os.path.basename(sp), res["s_db_mb"]))
try:
n_sess = scon.execute("SELECT COUNT(*) FROM sessions").fetchone()[0]
res["rows"]["sessions"] = n_sess
res["rows"]["s_bills"] = scon.execute(
"SELECT COUNT(*) FROM s_bills").fetchone()[0]
log(" 会话 %s 份 / 清单 %s 行" % (
format(n_sess, ","), format(res["rows"]["s_bills"], ",")))
# 最近审核页核心 SQL(api_sessions 原样复刻:3 个关联子查询聚合)
timed("最近审核·列表聚合", "SELECT b.session_id, COUNT(DISTINCT b.id),"
" (SELECT COUNT(*) FROM s_norms n WHERE n.bill_id IN"
" (SELECT id FROM s_bills WHERE session_id=b.session_id)),"
" (SELECT COUNT(*) FROM s_lmes l WHERE l.session_id=b.session_id),"
" (SELECT COUNT(*) FROM s_unit_works u WHERE u.session_id=b.session_id),"
" SUM(CASE WHEN b.x_remark IS NOT NULL AND TRIM(b.x_remark)<>''"
" THEN 1 ELSE 0 END)"
" FROM s_bills b GROUP BY b.session_id", con_=scon)
row = scon.execute(
"SELECT id FROM sessions ORDER BY id DESC LIMIT 1").fetchone()
sid = row[0] if row else 0
timed("工作台打开·清单全拉",
"SELECT id,Number,Name,Attr,Unit,Quantity,Price,Total"
" FROM s_bills WHERE session_id=? ORDER BY id", (sid,), con_=scon)
timed("工作台·工料机过滤列表",
"SELECT id FROM s_lmes WHERE session_id=? AND %s ORDER BY id"
% (LME_WHERE % ("", "")), (sid,), con_=scon)
finally:
scon.close()
except _BenchAbort:
log("软暂停:体检中止(只读操作,无残留)。")
try:
con.close()
except Exception:
pass
return None
finally:
if con is not None:
try:
con.close()
except Exception:
pass
try:
with open(BENCH_HIST, "a", encoding="utf-8") as f:
f.write(json.dumps(res, ensure_ascii=False) + "\n")
log("体检结果已追加存档 %s——逐级加量各跑一次,即可对比画出「容量-耗时」曲线。"
% os.path.basename(BENCH_HIST))
except Exception:
pass
log("== 体检完成。判读:哪条查询突破可接受阈值(如 1 秒),哪里就是当前规模下的瓶颈;")
log(" 逐级加量(1千→5千→1万→5万项目)重复「生成→体检」,阈值 Crossing 点即数据库上限。")
return res
# ---------------- 编排入口 ----------------
def _has_col(con, table, col):
@@ -1472,6 +1750,28 @@ def _clean_orphans(con, parent="batches", pcol="batch_id"):
raise
def _estimate_run(cfg):
"""按行宽×行数粗估本次生成的库体积(GB)与附件文件个数,供磁盘空间预警。
系数为经验值:bills≈340B/行、norms≈180B、norm_res≈48B、工料机三表≈390 种×730B、
prices≈220B,再乘 1.7 覆盖索引与表结构冗余;文件按 8KB/个(内容 1~6KB + NTFS 簇)。"""
def _avg(a, b):
return (float(a or 0) + float(b or 0)) / 2.0
np_ = float(cfg.get("n_project", 0) or 0)
nb = _avg(cfg.get("bill_lo", 0), cfg.get("bill_hi", 0))
nn = nb * _avg(cfg.get("norm_lo", 0), cfg.get("norm_hi", 0))
nr = nn * _avg(cfg.get("res_lo", 0), cfg.get("res_hi", 0))
rows = np_ * (nb * 340 + nn * 180 + nr * 48 + 390 * 730 + 400)
ns = np_ if cfg.get("session_linked") else float(cfg.get("n_session", 0) or 0)
sb = _avg(cfg.get("sbill_lo", 0), cfg.get("sbill_hi", 0))
rows += ns * (sb * 340 + sb * 4 * 180 + sb * 4 * 4 * 48 + 390 * 730 + 400)
rows += float(cfg.get("n_market", 0) or 0) * _avg(cfg.get("market_lo", 0), cfg.get("market_hi", 0))
rows += float(cfg.get("n_info", 0) or 0) * _avg(cfg.get("info_lo", 0), cfg.get("info_hi", 0))
gb = rows * 1.7 / 1e9
nfiles = np_ * float(cfg.get("inq_per_project", 0) or 0) + ns + np_
return gb, int(nfiles), nfiles * 8192 / 1e9
def run(cfg, log=print):
global REF_DIR
REF_DIR = (cfg.get("ref_dir") or "").strip() or None
@@ -1480,9 +1780,9 @@ def run(cfg, log=print):
log("!! 找不到数据目录(history.db)。请在控制台里手动指定数据目录。")
return False
th, ts = ensure_test_dbs(dd, log)
hc = _open_db(th)
hc = _open_db(th, bulk=True)
_clean_orphans(hc, "batches", "batch_id")
sc = _open_db(ts) if os.path.exists(ts) else None
sc = _open_db(ts, bulk=True) if os.path.exists(ts) else None
if sc is not None:
_clean_orphans(sc, "sessions", "session_id")
rng = random.Random() # 每次运行真随机(不固定种子)
@@ -1491,6 +1791,17 @@ def run(cfg, log=print):
log("测试库目录:%s" % _disp(dd))
log("词料:项目名 %d / 定额 %d / 工料机 %d / 建设单位 %d" % (
len(words.stems), len(words.norms), len(words.lmes), len(words.builders)))
# 磁盘空间预警:上限测试动辄几十上百 GB,写满中途失败虽然已提交数据保留,但白跑几小时
est_gb, est_files, est_fgb = _estimate_run(cfg)
try:
free_gb = shutil.disk_usage(dd).free / 1e9
except Exception:
free_gb = None
log("规模预估:库 ≈ %.1f GB + 附件文件 %d 个(≈ %.1f GB)%s" % (
est_gb, est_files, est_fgb,
(";数据盘剩余 %.0f GB" % free_gb) if free_gb is not None else ""))
if free_gb is not None and est_gb + est_fgb > 0.5 and free_gb < (est_gb + est_fgb) * 1.1:
log("⚠ 剩余空间低于预估——中途磁盘写满会报错停止(已提交数据保留),请减小规模或换盘。")
t0 = time.time()
st = {}
if int(cfg.get("n_project", 0)) > 0:
@@ -1513,7 +1824,7 @@ def run(cfg, log=print):
if sc is not None and not cfg.get("session_linked") and int(cfg.get("n_session", 0)) > 0:
log("== 独立工作台会话(%d 份,清单 %d~%d/份)==" % (
cfg["n_session"], cfg.get("sbill_lo", 150), cfg.get("sbill_hi", 400)))
_merge(st, gen_sessions_standalone(sc, cfg, rng, words, log))
_merge(st, gen_sessions_standalone(sc, dd, cfg, rng, words, log))
# 收尾 checkpoint:全部读连接断开时把 WAL 收干净,不留巨型 WAL 给下次恢复
for c in (hc, sc):
if c is not None:
@@ -1535,6 +1846,8 @@ def main():
ap = argparse.ArgumentParser(description="testdata 测试数据生成器")
ap.add_argument("--check", action="store_true", help="统计现有测试数据")
ap.add_argument("--run", metavar="CFG_JSON", help="按参数 json 生成")
ap.add_argument("--bench", action="store_true",
help="性能体检:只读实测母体热点查询耗时(测数据库上限用)")
ap.add_argument("--align-ver", action="store_true",
help="把测试批次的解析器版本对齐到本母体当前版本(换母体使用后跑一次)")
ap.add_argument("--delete", action="store_true", help="分块删除全部测试数据")
@@ -1551,6 +1864,12 @@ def main():
for k, v in s.items():
print(" %s: %s" % (k, v))
return
if args.bench:
if not dd:
print("!! 找不到数据目录(history.db)")
sys.exit(1)
bench_testdata(dd)
return
if args.delete:
if not dd:
print("!! 找不到数据目录(history.db)")

View File

@@ -4,6 +4,8 @@
双击「启动testdata.bat」自动打开浏览器:http://127.0.0.1:8412
填参数 → 开始生成 → 实时日志;停止 = 软暂停;删除 = 分块删除全部测试数据;
版本对齐 = 测试库换到别的母体后,把测试批次解析器版本对齐到该母体当前版本。
性能体检 = 只读实测母体热点查询耗时(结果存档 bench_history.jsonl)——
测数据库容量上限用:逐级加量生成,每级体检一次,查询突破阈值处即上限。
生成写入独立测试库 history-test.db / session-test.db,真实库零污染。
只在本机 127.0.0.1 监听。不改任何软件代码。
"""
@@ -74,6 +76,8 @@ def start_sub(mode, cfg):
args += ["--run", cfgpath]
elif mode == "delete":
args += ["--delete", "--yes"]
elif mode == "bench":
args += ["--bench"]
else:
return False, "未知操作"
try:
@@ -200,6 +204,9 @@ class H(BaseHTTPRequestHandler):
"msg": "换库完成!现在点「启动造价审核.bat」即可查看测试数据。"})
except Exception as e:
self._send(200, {"ok": False, "msg": str(e)})
elif self.path == "/api/bench":
ok, msg = start_sub("bench", {})
self._send(200, {"ok": ok, "msg": msg})
elif self.path == "/api/delete":
ok, msg = start_sub("delete", {})
self._send(200, {"ok": ok, "msg": msg})
@@ -350,6 +357,7 @@ history-test.db / session-test.db(首次自动从真实库克隆底子),<b
<button style="background:var(--ok)" onclick="doSwitch()">一键换库</button>
<button class="red" onclick="doDel()">删除全部测试数据</button>
<button class="gray" onclick="doAlign()">版本对齐</button>
<button class="gray" onclick="doBench()">性能体检</button>
<button class="gray" onclick="loadStats()">刷新统计</button>
</div>
<div class="kpis" id="kpis"></div></div>
@@ -393,6 +401,9 @@ async function doStop(){try{const r=await post("/api/stop",{});banner(r.msg||"
async function doDel(){if(!confirm("确认真删除全部「测试」前缀的模拟数据?此操作不可恢复!"))return;
try{await post("/api/delete",{});banner("删除任务已提交,请观察日志。","");poll();}catch(e){banner("删除失败:"+e.message,"err");}}
async function doAlign(){try{const r=await post("/api/align",{});banner(r.msg||"完成","");}catch(e){banner("对齐失败:"+e.message,"err");}}
async function doBench(){try{const r=await post("/api/bench",{});
banner(r.ok?"性能体检已开始(只读,不写任何数据),结果看下方日志。":("性能体检失败:"+(r.msg||"未知错误")),r.ok?"":"err");
if(r.ok)poll();}catch(e){banner("性能体检失败:"+e.message,"err");}}
async function doSwitch(){
if(!confirm("一键换库:测试库换上(history-test.db→history.db),原库留底为 history-y.db / session-y.db。\\n\\n请先关闭造价审核软件,否则文件占用会失败。继续?"))return;
try{const r=await post("/api/switch",{});banner(r.msg||"完成","");loadStats();}catch(e){banner("换库失败:"+e.message,"err");}}

View File

@@ -1,22 +1,34 @@
# -*- coding: utf-8 -*-
"""最小探针:定位哪个库、哪种打开方式能读。只读 SELECT。"""
import glob
"""最小探针:定位哪个库、哪种打开方式能读。只读 SELECT。
2026-10-11:路径改走 gen_testdata.find_data_dir()(旧 glob 指向改名前的目录必 IndexError)。"""
import os
import sqlite3
import sys
sys.stdout.reconfigure(errors="replace")
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import gen_testdata as G
base = glob.glob("D:/Pricing review*/\u9020\u4ef7\u5ba1\u6838/data")[0]
dd = G.find_data_dir()
if not dd:
print("!! 找不到数据目录(history.db)。请先在控制台里指定,或放到母体旁。")
sys.exit(1)
rh, th, rs, ts = G.db_paths(dd)
targets = {
"history.db(真实)": base + "/history.db",
"history-test.db": base + "/history-test.db",
"session.db(真实)": base + "/session.db",
"session-test.db": base + "/session-test.db",
"history.db(真实)": rh,
"history-test.db": th,
"session.db(真实)": rs,
"session-test.db": ts,
}
for name, p in targets.items():
if not os.path.exists(p):
print("%-18s 缺文件" % name)
continue
for mode, uri in (("普通", False), ("ro", True)):
try:
con = sqlite3.connect(p if not uri else "file:" + p.replace("\\", "/") + "?mode=ro", uri=uri, timeout=5)
con = sqlite3.connect(p if not uri else "file:" + p.replace("\\", "/") + "?mode=ro",
uri=uri, timeout=5)
n = con.execute("SELECT COUNT(*) FROM sqlite_master").fetchone()[0]
con.close()
print("%-18s %-4s OK, sqlite_master=%d" % (name, mode, n))

28
release/testdata/step1_3k.json vendored Normal file
View File

@@ -0,0 +1,28 @@
{
"n_project": 1300,
"bill_lo": 600,
"bill_hi": 800,
"norm_lo": 3,
"norm_hi": 5,
"res_lo": 3,
"res_hi": 5,
"inq_per_project": 35,
"bind_rate": 50,
"n_market": 1500,
"market_lo": 500,
"market_hi": 800,
"market_attach_rate": 80,
"n_info": 1500,
"info_lo": 500,
"info_hi": 800,
"info_attach_rate": 90,
"session_linked": false,
"n_session": 1500,
"sbill_lo": 800,
"sbill_hi": 1500,
"from_ym": "2018-01",
"to_ym": "2026-10",
"chunk": 500,
"data_dir": "D:/PricingReview/CostReview/data",
"ref_dir": "D:/PricingReview/CostReview/data"
}

28
release/testdata/step2_10k.json vendored Normal file
View File

@@ -0,0 +1,28 @@
{
"n_project": 7000,
"bill_lo": 600,
"bill_hi": 800,
"norm_lo": 3,
"norm_hi": 5,
"res_lo": 3,
"res_hi": 5,
"inq_per_project": 35,
"bind_rate": 50,
"n_market": 7000,
"market_lo": 500,
"market_hi": 800,
"market_attach_rate": 80,
"n_info": 7000,
"info_lo": 500,
"info_hi": 800,
"info_attach_rate": 90,
"session_linked": false,
"n_session": 8000,
"sbill_lo": 800,
"sbill_hi": 1500,
"from_ym": "2018-01",
"to_ym": "2026-10",
"chunk": 500,
"data_dir": "D:/PricingReview/CostReview/data",
"ref_dir": "D:/PricingReview/CostReview/data"
}