perf(match): 模糊档改前缀键+扫描护栏,大库点清单提速

- 新增 x_name_pre 前缀键(决策 339),前置通配 LIKE 改前缀等值,并补建次精确档索引(决策 338)
- 启动迁移回填老库前缀键与索引
- 检索加独立扫描预算哨,超时中断降级,宁少结果不白等
- 采纳链路加分段计时日志,定位慢段
This commit is contained in:
lianjianwei2024
2026-11-15 09:04:53 +08:00
parent b400454f74
commit 935c830135
10 changed files with 274 additions and 206 deletions

View File

@@ -1243,6 +1243,9 @@ def api_bill_adopt(sc, hc, body):
都没有才用后台源码补本单位。项目级 `s_lme_proj` 是计算结果,不参与匹配、不补行;
目标已有三同(含一级叶子)时源子级不写,先到先占。
9.2 临删状态不可采纳。"""
_t0a = time.perf_counter() # 2026-11-14 性能排查(主人报「采纳按钮半天没反应」):分段累计耗时,定位慢段后可拆
def _lap(_w):
print("[采纳计时] %-14s 累计 %6dms bill=%s src=%s" % (_w, int((time.perf_counter() - _t0a) * 1000), bid, src_id), flush=True)
sid = int(body.get("session_id", 0) or 0)
bid = int(body.get("bill_id", 0) or 0)
src_id = int(body.get("src_bill_id", 0) or 0)
@@ -1429,6 +1432,7 @@ def api_bill_adopt(sc, hc, body):
if not _new:
return mo.group(0)
return mo.group(0).replace('Number="%s"' % mo.group(1), 'Number="%s"' % _new, 1)
_adopted = []
for nn in bnorms:
# 决策322(2026-11-14 主人拍板):锚四列落地——差额法不变式的起点
# (Price=锚价+(现合计−锚合计);改价/含量编辑按 Δ=差额×含量 增量维护,见 _norm_price_cascade)。
@@ -1482,28 +1486,46 @@ def api_bill_adopt(sc, hc, body):
# 采纳外部的以本项目为准(9.4 本地匹配),不落锚走原链。合并工料机只动汇总现值,
# 不碰行级锚——上下游各自生效不冲突(主人 2026-10-27 拍板)。
a = _lme_ntp_of(sc, sid, bb["uw_id"], rr["res_code"]) if src_self else (None, None)
sc.execute("INSERT INTO s_norm_res(norm_id, res_code, qty, express, x_ntp, x_taxp) VALUES(?,?,?,?,?,?)",
sc.execute("""INSERT INTO s_norm_res(norm_id, res_code, qty, express, x_ntp, x_taxp)
VALUES(?,?,?,?,?,?)""",
(cur.lastrowid, rr["res_code"], rr["qty"], rr["express"], a[0], a[1]))
# 决策 333(2026-11-14 主人拍板 B,取代决策 19「采纳单价恒跟源」):
# 清单价=Σ(定额量×定额价)÷清单量(2 位半升);定额量按来源清单量→当前清单量等比缩放
# (x_qty_coef 优先,缺则 源定额量/源清单量),与导出/显示的 GCL 求值同一把尺。
# 决策 322 差额法(采纳落库尾):**同项目采纳**才按“目标单位现价”算差;
# 跨项目采纳(2026-11-14 主人拍板 B)现合计取来源批次价 → 差额=0,
# 定额价=来源定额价(insert 已写锚价),目标改价后再由 322 级联增量反映。
if src_self:
_cur_total = 0.0
for rr in _norm_res(nn["id"]):
_np2, _tp2 = _lme_ntp_of(sc, sid, sb["uw_id"], rr["res_code"])
_pr2 = _tp2 if _vb == "taxp" else _np2
if _pr2 is None:
_pr2 = _np2 if _np2 is not None else _tp2
_cur_total += float(rr["qty"] or 0) * float(_pr2 or 0)
if _va is not None and _vt is not None:
sc.execute("UPDATE s_norms SET Price=?, x_lme_total=? WHERE id=?",
(_r2(float(_va) + (_cur_total - float(_vt))), _cur_total, cur.lastrowid))
_cf0 = nn["x_qty_coef"] if "x_qty_coef" in nn.keys() else None
if _cf0 in (None, 0) and bb["Quantity"] not in (None, 0):
try:
_uf = unit_factor(nn["Unit"])
except Exception:
_uf = 1.0
_cf0 = float(nn["Quantity"] or 0) * float(_uf or 1.0) / float(bb["Quantity"])
_adopted.append((cur.lastrowid, float(_cf0 or 0)))
# 决策 333(2026-11-14 斗门莲洲实证):清单价=Σ(定额单位含量×定额价),定额价=
# 322 差额法价(上段已写);合价=清单价×清单量,量空/0→价、合价留空。
_qb = _pre["Quantity"]
_qs = bb["Quantity"]
_sum333, _ok333 = 0.0, False
for nn in bnorms:
try:
_coef = (float(nn["Quantity"] or 0) / float(_qs)) if _qs not in (None, 0) else 1.0
_sum333 += float(_coef) * float(_qb or 0) * float(nn["Price"] or 0)
_sp333, _ok333 = 0.0, False
for _nid2, _cf2 in _adopted:
_prow = sc.execute("SELECT Price FROM s_norms WHERE id=?", (_nid2,)).fetchone()
if _prow and _prow[0] is not None:
_sp333 += _cf2 * float(_prow[0])
_ok333 = True
except Exception:
pass
if _ok333 and _qb not in (None, 0) and float(_qb) != 0:
new_price = _r2(_sum333 / float(_qb))
if _ok333 and _qb not in (None, 0):
new_price = _r2(_sp333)
else:
new_price = None
# —— 清单字段统一口径(2026-11-07 主人定):编码/名称/项目特征/单位/工程量
# **空则引入、非空利旧**;新清单工程量恒清 0 待填;
# 单价按决策 333=Σ定额合价÷清单量(取代 19 的“恒跟源”);合价=量×价现算。
# **空则引入、非空利旧**;新清单工程量恒清 0 待填;合价=量×价现算。
sets, vals = [], []
for col in ("Number", "Name", "Attr", "Unit"):
_sv = bb[col]
@@ -1566,6 +1588,7 @@ def api_bill_adopt(sc, hc, body):
# 2026-11-04 主人定「数据只来源原数据」:只从**本次采纳来源批次**取。此前这条 SQL 漏了
# batch_id,实测把历史库 12 个批次的同码组成全灌进一个会话(耗弹框 60 行重复、汇总数量翻倍);
# 来源=本会话清单(src_self)时一律不补——本会话的组成只能来自它自己的原件。
_lap("②333求值+清单字段") # 覆盖:决策333 清单价求值、清单五字段空则引入、汇总补品类落行
try:
if not src_self and src_id:
# 决策 294:源 lme_res 递归闭包——子工料机的子工料机也是父码,逐层补组成;
@@ -1631,6 +1654,7 @@ def api_bill_adopt(sc, hc, body):
# 决策 297 补记三(2026-11-11 主人定「只要有定额耗的编码存活,对应的数据链必须完整」):
# 采纳收尾自愈——新链闭包内缺源行从**来源批次库**兜底补齐(实在命不中登记 chain_problems,
# 导出闸 292/295 照拦)。失败不挡采纳本身。
_lap("③工料机链") # 覆盖:决策295/296 三同匹配补子级、汇总补品类、附件收进
try:
_chain_survey_repair(sc, sid, hc=hc)
sc.commit()
@@ -1642,6 +1666,7 @@ def api_bill_adopt(sc, hc, body):
print("采纳收尾数据链自愈失败(不挡采纳):%s" % _e, flush=True)
# 决策 323(2026-11-14 主人定,取代 316 补记九):采纳收尾同口径全层级母随子动——
# 采纳落库/换码后全库带子级行按 Σ(边含量×子价) 回算(与导入收尾同一函数),失败不挡采纳。
_lap("④297链自愈") # 覆盖:_chain_survey_repair 全链勘察补源
try:
reprice_all_lme(sc, sid)
sc.commit()
@@ -1651,6 +1676,7 @@ def api_bill_adopt(sc, hc, body):
except Exception:
pass
print("采纳收尾全层级回算失败(不挡采纳):%s" % _e, flush=True)
_lap("⑤323全层级回算") # 覆盖:reprice_all_lme 全库母随子动回算
return {"ok": True, "sid": sid, "price0": _price0,
"n_norm": len(bnorms), "n_sum": n_sum, "n_recode": n_recode, "n_att": _n_att,
"mode": "覆盖" if is_new else "追加", "price": new_price}
@@ -1957,7 +1983,10 @@ def _ensure_batch_schema():
_ensure_cols(c, "bills", [("uw_id", "INTEGER"), ("div_id", "INTEGER"),
("Quantity", "REAL"), ("Total", "REAL"),
# 源文件备注(清单节点 Remark 属性,2026-10-08;只显示在「原数据」)
("src_remark", "TEXT")])
("src_remark", "TEXT"),
# 决策 339:模糊档前缀键(match.name_pre(Name))——老库补列,
# 回填+建索引在 api_server.migrate_name_pre(schema.sql 之后跑才安全)
("x_name_pre", "TEXT")])
_ensure_cols(c, "norms", [("Quantity", "REAL"), ("Total", "REAL"),
# 规格 19:定额工程量系数(**GCL 口径** = 定额量÷历史GCL,
# 导入时算好存库,采纳时直接取用生成 GCL*系数 公式;主人 2026-10-17 定)

View File

@@ -308,10 +308,22 @@ def migrate_match_keys():
con.execute("SELECT id, Name, Specification, Unit FROM lmes WHERE x_setkey IS NULL")])
print("迁移:lmes 字集键回填 %d 行" % nl)
con.execute("CREATE INDEX IF NOT EXISTS ix_bill_setkey ON bills(x_setkey)")
con.execute("CREATE INDEX IF NOT EXISTS ix_bill_semi ON bills(x_hash_semi)") # 决策 338:次精确档索引(老库启动补齐;schema.sql 已带,这里保旧库不漏)
con.execute("CREATE INDEX IF NOT EXISTS ix_lme_setkey ON lmes(x_setkey)")
con.commit()
finally:
con.close()
# 决策 339:模糊档前缀键回填+建索引(列由 _ensure_batch_schema 补;回填要 match.name_pre 现算,
# 必须在该列存在后跑——放 migrate_match_keys 之后,与 setkey 回填同一启动序列)
con = sqlite3.connect(DB)
try:
nb = match.backfill_name_pre(con)
if nb:
print("迁移:bills 模糊档前缀键回填 %d 行(决策 339)" % nb, flush=True)
con.execute("CREATE INDEX IF NOT EXISTS ix_bill_namepre ON bills(x_name_pre)")
con.commit()
finally:
con.close()
scon = sess.connect()
try:
if not _hash9_current(scon, "s_bills"):
@@ -1594,6 +1606,9 @@ def api_sessions():
# 决策 213 补记七:五个统计数取消(不再逐会话 COUNT)
"total": g.get("x_total"), # 工程总造价(原文件口径,不是清单合价求和)
"dir": _dir_path(_dmap.get((g["name"] or "").strip(), 0)), # 所属目录全路径(未归类=空串)
# 决策 334(2026-11-14 主人定 A 案):创建时间=该名称下最早一次打开时间(取 all 里最早 imported_at,
# 字符串即时间序,格式 YYYY-MM-DD HH:MM:SS 直接比大小;老项目立即可显,不改表结构)
"created_at": min([s["at"] for s in g["all"] if s["at"]], default=None),
"all": g["all"], "dup": len(g["all"]),
"manual": _manual,
"can_reparse": bool(g["src_name"]) and (source_names is None or _src_exists_in_names(g["src_name"], source_names)) and not _manual,
@@ -6593,7 +6608,8 @@ def api_search(body):
pmin=_num_or_none(body.get("pmin")),
pmax=_num_or_none(body.get("pmax")),
att=body.get("att") or "all", # 决策 208:价格范围/附件清单侧同生效
only_batch_ids=only_ids) # 决策 277:同后缀硬过滤
only_batch_ids=only_ids, # 决策 277:同后缀硬过滤
self_unit=(s["bulid_unit"] if "bulid_unit" in s.keys() else "") or "") # 决策 337:同档内建设单位一致优先(空不加分)
# 规格 20:本组其他清单的批次记录(bill_id 集合)——组价不一致对比按它过滤
allowed = None
if scope_self and members is not None:
@@ -6847,40 +6863,49 @@ def api_hist_search(body):
(a.get("district") or "").strip())
if t[0]:
area.append(t)
if body.get("target") == "lme":
# 工料机标签:查全部入库项目工料机 + 信息价/市场价明细;
# 筛选=来源(srcs)/单位(orgs 跨来源联查)/地区/期次/价格范围/附件(单价类型/类别不参与)
res = match.hist_search_lme(hist,
orgs=body.get("orgs") or [],
area=area,
pfrom=body.get("period_from"), pto=body.get("period_to"),
kw=body.get("kw") or "",
pmin=_num_or_none(body.get("pmin")),
pmax=_num_or_none(body.get("pmax")),
att=body.get("att") or "all",
kinds=body.get("file_kinds") or [],
srcs=body.get("srcs") or ["project", "info", "market"],
limit=min(int(body.get("limit", 200)), 500),
_restore = match.search_deadline(hist) # 决策 339 ③:独立检索扫描护栏——超预算中断,宁少结果不白等
try:
if body.get("target") == "lme":
# 工料机标签:查全部入库项目工料机 + 信息价/市场价明细;
# 筛选=来源(srcs)/单位(orgs 跨来源联查)/地区/期次/价格范围/附件(单价类型/类别不参与)
res = match.hist_search_lme(hist,
orgs=body.get("orgs") or [],
area=area,
pfrom=body.get("period_from"), pto=body.get("period_to"),
kw=body.get("kw") or "",
pmin=_num_or_none(body.get("pmin")),
pmax=_num_or_none(body.get("pmax")),
att=body.get("att") or "all",
kinds=body.get("file_kinds") or [],
srcs=body.get("srcs") or ["project", "info", "market"],
limit=min(int(body.get("limit", 200)), 500),
self_name=self_name, self_src=self_src,
page=int(body.get("page", 1) or 1),
projs=body.get("projs") or [],
stop=match.stop_words(body.get("stop")))
else:
res = match.hist_search(hist,
body.get("file_kinds") or [],
body.get("bulid_units") or [],
area,
body.get("period_from"), body.get("period_to"),
body.get("kw") or "",
min(int(body.get("limit", 200)), 500),
self_name=self_name, self_src=self_src,
page=int(body.get("page", 1) or 1),
projs=body.get("projs") or [],
stop=match.stop_words(body.get("stop")))
else:
res = match.hist_search(hist,
body.get("file_kinds") or [],
body.get("bulid_units") or [],
area,
body.get("period_from"), body.get("period_to"),
body.get("kw") or "",
min(int(body.get("limit", 200)), 500),
self_name=self_name, self_src=self_src,
page=int(body.get("page", 1) or 1),
projs=body.get("projs") or [],
stop=match.stop_words(body.get("stop")),
only_batch_ids=_bill_search_batch_ids(hist, sess_src_name), # 决策 277:同后缀硬过滤(工料机分支不受限)
pmin=_num_or_none(body.get("pmin")),
pmax=_num_or_none(body.get("pmax")),
att=body.get("att") or "all") # 决策 208:价格范围/附件清单侧同生效)
stop=match.stop_words(body.get("stop")),
only_batch_ids=_bill_search_batch_ids(hist, sess_src_name), # 决策 277:同后缀硬过滤(工料机分支不受限)
pmin=_num_or_none(body.get("pmin")),
pmax=_num_or_none(body.get("pmax")),
att=body.get("att") or "all") # 决策 208:价格范围/附件清单侧同生效)
except sqlite3.OperationalError as _e:
if "interrupt" not in str(_e).lower():
raise
return {"ok": False, "msg": "检索超时(%g 秒预算内没扫完):关键词太泛或库太大,"
"请加条件缩小范围后再搜" % match.SEARCH_BUDGET_S}
finally:
_restore()
finally:
hist.close()
for r in res: # 单价类型码 → 名称(0/空=未标注 → 前端显示 —)