unis-oa/backend/scripts/check_index_gaps.py

399 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#!/usr/bin/env python3
"""会长大的表上,代码里的等值过滤列有没有索引可用(跑在 backend 目录下)::
PYTHONPATH=. python3 scripts/check_index_gaps.py # 认库里实际的索引
PYTHONPATH=. python3 scripts/check_index_gaps.py --models # 认模型声明(新建库会得到什么)
PYTHONPATH=. python3 scripts/check_index_gaps.py --all # 连"看着可疑其实没事"的也列出来
为什么要这一条:加索引这件事从来不是写错了才发现的,是列表页变慢了才想起来的——
一条 ``WHERE form = ?`` 落在只长不删的归档表上,今天 1ms、两年后几百 ms,**一声不响**。
前面几轮就是这么捡到六条索引的(``users.display_name``、``oa_read.work``、
``oa_attachment.work``、``oa_work_completed.(form, finish_time)``、
``oa_outbound_message.(integration, create_time)``、``oa_quota_ledger.work``),
这个脚本把那一次性的体检变成常驻门。
判据三条,缺一条就是假警报(本部署第一轮扫出 32 处,真缺口只有三处):
1. **只看会长大的表**(``GROWS``):运行态、日志、台账这类一直 INSERT 的表。
``oa_role`` / ``oa_unit`` / ``oa_process`` / ``oa_dict_item`` 这种几十行的编目表不在其列——
给十行表的某一列建索引,MySQL 自己都懒得走。
2. **只看没有打头索引可用的列**:``(a, b)`` 那种复合索引只有 ``a`` 对等值查找有用,
``b`` 单看是"没索引",但它跟着 ``a`` 一起被筛,不亏;主键与聚簇扫等价,也算有用。
这一档只在 ``--all`` 里列全。
3. **只看没人收窄的那一条**:同一个函数里如果还有别处把**打头索引列**当等值条件用,
MySQL 就有一条走得通的路,这一列跟着被筛一下不贵(``oa_read.read_type`` 永远跟着
``identity`` 或 ``work`` 一起问,就是这一档)。
两处判不出来、写豁免理由的人要自己看一眼:
* ``or_(indexed = a, unguarded = b)``:索引只救得了 ``a`` 那一边,``b`` 那一边照样扫,
所以 ``or_`` / ``|`` 里的条件**不算**收窄别人的那一把(``oa_quota_ledger`` 那条
``(work = ? OR job = ?)`` 就是这么被抓到的:``job`` 有索引、``work`` 没有,
index_merge 凑不齐两边,退化成整表扫)。但同一条 ``or_`` 里两边都缺索引时,
脚本只会各报一次,不会提示"这两条该合起来建一个复合索引";
* 一个函数里两条互不相干的查询:按**函数**归堆,另一条查询收窄了,这一条也可能被
当成收窄(少报的方向)。
不写库:只反射索引。退出码非 0 只有一种意思——**有个新的等值过滤落在会长大的表上、
没有索引可用、也没在下面 ``EXEMPT`` 里写下不建的理由**。写理由不算输:不建索引常常
是对的(写热点表、低基数列、有界表),不写理由才是。
"""
from __future__ import annotations
import argparse
import ast
import pathlib
import sys
from sqlalchemy import inspect as sa_inspect
from app import models
from app.db import engine
#: 一直在长的表。判据是"这张表只 INSERT,或者跟着人头/时间一直加行",
#: 与它现在有多少行无关(``oa_outbound_message`` 现在 0 行,接了外部写回就是每发一次一行)。
#: 有界的表(``oa_task`` / ``oa_read`` 只存在途、办结就搬走)也留在名单里:判错了无非是
#: 多写一条理由,漏了一张真会长的表才是亏。
GROWS = {
"oa_work", "oa_work_completed", "oa_task", "oa_task_completed", "oa_read",
"oa_read_completed", "oa_work_log", "oa_work_comment", "oa_attachment",
"oa_notification", "oa_draft", "oa_handover", "oa_meeting", "oa_meeting_attendee",
"oa_operation_log", "oa_data_source_log", "oa_hub_sync_run", "oa_open_call",
"oa_outbound_message", "oa_notify_delivery", "oa_quota_ledger", "oa_sso_handoff",
"oa_refresh_token", "oa_embed_ticket", "oa_storage_pending_delete",
"oa_person_auth_role", "oa_bank_account", "oa_file", "oa_cms_document", "users",
}
#: 没有打头索引可用、又没人收窄的列,**必须**在这里留下一条理由。
#: 理由要经得起下一次有人翻到它时追问"现在还成立吗":写清是哪一处调用、为什么不建、
#: 什么条件下该回来补索引。索引补上之后这条会自动过期,脚本会催着删。
EXEMPT: dict[tuple[str, str], str] = {
("oa_file", "owner_person"):
"网盘文件「我能看的」是一支三分支的 or_:owner、owner_person、"
"json_contains(shared_identities)。第三支是 JSON 函数,index_merge 两边都凑不齐,"
"给 owner_person 补索引也救不了这条查询。真要提速是给共享名单上生成列(虚列 + 索引)"
"那道题,不是这里补一条索引的事——见 docs/ 里没有这一篇,做之前先立项。",
("oa_meeting", "creator"):
"门户「我发起的会议」是 or_(id IN (参会人子查询), creator = ?, creator_identity = ?)。"
"会议模块本部署 4 行,加两条索引今天也不会被优化器选中(表小到全表扫更便宜)。"
"回来的条件:会议数上万、门户首页这一问进慢查询榜。",
("oa_meeting", "creator_identity"):
"同 oa_meeting.creator:同一个 or_ 的另一半,要么一起补、要么都别补。",
("oa_handover", "person"):
"移交列表是 or_(from_person = ?, person = ?),from_person 有索引、这一列没有,"
"所以 index_merge 凑不齐(这一条与 oa_quota_ledger.work 是同一个形状,那边补了)。"
"没补的理由只有一个:oa_handover 现在 0 行、这个功能没人用。补法就一条 "
"Index('ix_oa_handover_person', 'person'),等人用起来再补,一次 ALTER 的事。",
("oa_operation_log", "action"):
"操作日志列表按动作筛是**可选**条件:不筛时走 create_time、限定到人时走 "
"(person, create_time),那两路才是默认口径。action 只有几十个取值,基数低到 "
"优化器多半不走。真要治的是这张表只长不删——和 docs 里「操作日志保留期」那条一起拍板。",
("oa_quota_ledger", "quota_def"):
"被 (work = ? OR job = ?) 收窄:两支现在都有索引(work 那条是这一轮补的),"
"index_merge 把并集拿出来之后再筛 quota_def,筛的是几十行。单建索引反而是多余的一列。",
("oa_task", "person"):
"删人之前数一次他名下还有没有待办(api/org.py::delete_person),一次管理动作一趟。"
"oa_task 只存在途待办、办结即搬去 oa_task_completed,是有界表;而它是全站最热的"
"写表之一(派工、办理、加签、转办都写它),不给它加一条只在管理动作里用的索引。"
"回来的条件:在途待办量级上万。",
("oa_work", "form"):
"集成模板预览那两条查询的在途那一半(api/integrations.py::template_samples)。"
"已办结那一半这一轮补了 (form, finish_time)——归档表只长不删,实测 65.1ms → 17.7ms。"
"这一半落在 oa_work:办结就搬走、只存在途单,是有界表,同一份形状在小表上不值得"
"多一条索引。回来的条件:在途单量级上千。",
("oa_work", "parent_job"):
"子流程办结时回找还在跑的兄弟子单(engine._finish_work:parent_job = ? AND "
"status = 'running')。同样是 oa_work 这张有界的在途表;而且这是**办结路径**上的"
"查询,写热点表上加索引要先算写入那本账。",
("oa_work", "status"):
"与上一条同一条查询:status 在 (creator_identity, status) 里是非打头位,单独筛它"
"没人收窄。等 oa_work 真成大表,要建的也是 (parent_job, status) 这一条复合索引,"
"不是给 status 单独立一条。",
("users", "source"):
"同步的离职判定:select(User).where(source == 'hub') 然后整批比 hub_user_id。"
"这一问的口径就是「把 Hub 同步来的号全拿回来」,加索引省不了搬多少行,"
"而且 users 只有人头那么多行(本部署 108)。",
("users", "wecom_user_id"):
"「这个企微号挂在谁身上」只在增量事件里一次一问,全量同步本来就整表读进内存。"
"这一列不建索引是 models.py 里明写的决定(注释在 User.wecom_user_id 上方),"
"改之前先改那边。",
}
#: ``case(...)`` / ``order_by(...)`` 这些调用子树里的 ``==`` 是表达式或排序键,不是过滤条件;
#: 它们出现在 ``or_`` 之外也不该被当成收窄,所以与 ``or_`` 一样压一层深度。
_OR_LIKE_CALLS = {"or_", "case", "when", "order_by", "group_by", "label"}
def mapped_tables() -> tuple[dict[str, str], dict[str, set[str]]]:
"""``表名 -> 模型类名`` 与 ``表名 -> 列名集合``(只认 SQLAlchemy 映射出来的类)。"""
by_name: dict[str, str] = {}
columns: dict[str, set[str]] = {}
for attr in dir(models):
obj = getattr(models, attr)
if not (isinstance(obj, type) and hasattr(obj, "__tablename__")):
continue
try:
mapper = sa_inspect(obj)
except Exception: # noqa: BLE001 - 非映射类
continue
by_name[obj.__tablename__] = attr
columns[obj.__tablename__] = {c.key for c in mapper.columns}
return by_name, columns
def index_columns(tables: list[str], use_models: bool) -> dict[str, tuple[set[str], set[str]]]:
"""每张表:``(打头可用的列, 被任何索引提到的列)``。
打头可用 = 主键(聚簇扫,等值本来就快)或某个二级索引的第一列。
"""
out: dict[str, tuple[set[str], set[str]]] = {}
if use_models:
from app.db import Base
for name in tables:
table = Base.metadata.tables[name]
leading = {c.name for c in table.primary_key.columns}
mentioned = set(leading)
# 唯一**约束**不是 Index 对象,但 MySQL 会给它建一条唯一索引,等值查找用得上的;
# 外键列上的那条(MySQL 自动建的)不在模型里,所以 --models 会多报几条——
# 真要对着新建库判,就把这些列一起当"有索引"。
from sqlalchemy import UniqueConstraint
for column in table.columns:
for fk in column.foreign_keys:
# 单列外键:MySQL 会自动建一条以它打头的索引(名字是列名,
# ``sql/schema.sql`` 快照里有它)。模型里没有这条 Index 对象。
if len(fk.constraint.columns) == 1:
leading.add(column.name)
mentioned.add(column.name)
for constraint in table.constraints:
if isinstance(constraint, UniqueConstraint):
names = [c.name for c in constraint.columns]
if names:
leading.add(names[0])
mentioned.update(names)
for index in table.indexes:
names = [c.name for c in index.columns]
if names:
leading.add(names[0])
mentioned.update(names)
out[name] = (leading, mentioned)
return out
inspector = sa_inspect(engine)
for name in tables:
leading = set(inspector.get_pk_constraint(name).get("constrained_columns") or [])
mentioned = set(leading)
for index in inspector.get_indexes(name):
cols = [c for c in index["column_names"] if c]
if cols:
leading.add(cols[0])
mentioned.update(cols)
out[name] = (leading, mentioned)
return out
def _brief(reason: str, limit: int = 72) -> str:
"""把豁免理由压成一行:首句 + 那句"回来的条件"(完整理由留在源码里)。"""
text = " ".join(reason.split())
sentences = [part for part in text.split("。") if part.strip()]
first = sentences[0][:limit] + ("…" if len(sentences[0]) > limit else "")
back = next((f" {part.strip()}。" for part in sentences if "回来的条件" in part), "")
return f"{first}。{back}".strip()
def _call_name(node: ast.AST | None) -> str:
if isinstance(node, ast.Name):
return node.id
if isinstance(node, ast.Attribute):
return node.attr
return ""
class Predicate:
"""一处等值过滤:``哪张表的哪一列``、``在不在 or_ 里``、``在哪一个文件第几行``。"""
__slots__ = ("table", "column", "in_or", "file", "line")
def __init__(self, table: str, column: str, in_or: bool, file: str, line: int) -> None:
self.table, self.column, self.in_or = table, column, in_or
self.file, self.line = file, line
def where(self) -> str:
return f"{self.file}:{self.line}"
class Collector(ast.NodeVisitor):
"""按**函数**归堆收集等值过滤;``or_(...)`` / ``a | b`` 里面的条件打上 ``in_or``。"""
def __init__(self, classes: dict[str, str], columns: dict[str, set[str]], path: str) -> None:
self.classes = classes # 模型类名 -> 表名
self.columns = columns # 表名 -> 列名集合
self.path = path
self.scopes: dict[str, list[Predicate]] = {}
self._scope = "<module>"
self._or_depth = 0
# --- 作用域:一个函数算一堆(条件常常是 stmt = stmt.where(...) 一句句拼的) ---
def _visit_scope(self, node: ast.AST, key: str) -> None:
full = f"{self.path}:{key}"
outer, self._scope = self._scope, full
self.scopes.setdefault(full, [])
self.generic_visit(node)
self._scope = outer
def visit_FunctionDef(self, node: ast.FunctionDef) -> None:
self._visit_scope(node, node.name)
visit_AsyncFunctionDef = visit_FunctionDef
# --- or_ / | :里面的条件不算收窄别人的那一把 ---------------------------
def visit_Call(self, node: ast.Call) -> None:
name = _call_name(node.func)
if name in _OR_LIKE_CALLS:
# 只对**参数**压深度:``or_(a, b)`` 的分支就是参数。链式写法里
# ``.where(a).order_by(b)`` 的 ``.where(a)`` 挂在 ``func`` 那一侧,
# 连它一起压就会把正常的过滤条件误标成"在 or_ 里"(第一版就栽在这)。
self._or_depth += 1
for child in (*node.args, *(kw.value for kw in node.keywords)):
self.visit(child)
self._or_depth -= 1
self.visit(node.func)
return
if name == "in_":
self._add(getattr(node.func, "value", None))
self.generic_visit(node)
def visit_BinOp(self, node: ast.BinOp) -> None:
if isinstance(node.op, ast.BitOr):
self._or_depth += 1
self.visit(node.left)
self.visit(node.right)
self._or_depth -= 1
return
self.generic_visit(node)
# --- 等值过滤 ---------------------------------------------------------
def visit_Compare(self, node: ast.Compare) -> None:
if any(isinstance(op, (ast.Eq, ast.In)) for op in node.ops):
for side in (node.left, *node.comparators):
self._add(side)
self.generic_visit(node)
def _add(self, node: ast.AST | None) -> None:
found = self._column(node)
if found is None:
return
table, column = found
self.scopes[self._scope].append(
Predicate(table, column, self._or_depth > 0, self.path, getattr(node, "lineno", 0))
)
def _column(self, node: ast.AST | None) -> tuple[str, str] | None:
"""认出 ``models.<类名>.<列名>``;列名必须真是那张表的列(排除关系属性)。"""
if not isinstance(node, ast.Attribute):
return None
inner = node.value
if not isinstance(inner, ast.Attribute) or not isinstance(inner.value, ast.Name):
return None
if inner.value.id != "models":
return None
table = self.classes.get(inner.attr)
if table is None or node.attr not in self.columns.get(table, set()):
return None
return table, node.attr
def scan(classes: dict[str, str], columns: dict[str, set[str]]) -> dict[str, list[Predicate]]:
"""``作用域 -> 这一堆等值过滤``。只看 ``app/``:脚本与探针里的查询不是线上口径。"""
scopes: dict[str, list[Predicate]] = {}
for path in sorted(pathlib.Path("app").rglob("*.py")):
rel = str(path)
tree = ast.parse(path.read_text(encoding="utf-8"), filename=rel)
collector = Collector(classes, columns, rel)
collector.visit(tree)
for key, items in collector.scopes.items():
scopes.setdefault(key, []).extend(items)
return scopes
def main() -> int:
parser = argparse.ArgumentParser(description="会长大的表上的等值过滤有没有索引可用")
parser.add_argument("--models", action="store_true",
help="按模型声明判(新建库会得到什么),不按库里实际的索引")
parser.add_argument("--all", action="store_true", dest="show_all",
help="连同一函数里已被打头索引列收窄的那些也一起列出来")
args = parser.parse_args()
tables_by_name, columns = mapped_tables()
growing = sorted(name for name in tables_by_name if name in GROWS)
gone = sorted(GROWS - set(tables_by_name))
index_info = index_columns(growing, args.models)
scopes = scan({cls: table for table, cls in tables_by_name.items()}, columns)
flags: dict[tuple[str, str], list[Predicate]] = {}
loose: dict[tuple[str, str], list[Predicate]] = {}
for items in scopes.values():
# 这一堆里"能收窄别人的列":同一张表、打头可用、且不在 or_ 里面
narrowing = {
item.table for item in items
if not item.in_or and item.table in index_info
and item.column in index_info[item.table][0]
}
for item in items:
if item.table not in index_info or item.column in index_info[item.table][0]:
continue # 有打头索引可用,或者这张表不会长大
bucket = loose if item.table in narrowing else flags
bucket.setdefault((item.table, item.column), []).append(item)
fails: list[str] = []
print(f"会长大的表 {len(growing)} 张、{len(scopes)} 个函数,"
f"按{'模型声明' if args.models else '库里实际'}的索引判\n")
print("■ 没有索引可用、也没写下理由")
unexplained = {k: v for k, v in flags.items() if k not in EXEMPT}
if not unexplained:
print(" (无)")
for (table, column), hits in sorted(unexplained.items()):
where = " ".join(sorted({h.where() for h in hits})[:3])
print(f" {table}.{column} <- {where}")
fails.append(f"{table}.{column}")
print("\n■ 已写下理由的(复核一眼还成立吗)")
shown = 0
for (table, column), reason in sorted(EXEMPT.items()):
if table not in index_info:
fails.append(f"{table}.{column}:表不在会长大的名单里或不在了,删掉这条理由")
continue
if column in index_info[table][0] or (table, column) not in flags:
fails.append(f"{table}.{column}:现在有打头索引了(或已不再被单独等值过滤),这条理由过期了")
continue
shown += 1
print(f" {table}.{column}:{_brief(reason)}")
if not shown:
print(" (无)")
if gone:
fails.append(f"GROWS 里有两张对不上的表:{', '.join(gone)}")
if args.show_all:
print("\nℹ 同一函数内有打头索引列收窄(假警报多数在这一档,抽查即可)")
if not loose:
print(" (无)")
for (table, column), hits in sorted(loose.items()):
print(f" {table}.{column} <- {len(hits)} 处")
print()
if fails:
for item in fails:
print(f"!! {item}")
print(f"\n未通过:{len(fails)} 项")
return 1
print(f"通过:会长大的表上每一个单独出现的等值过滤列,要么有打头索引可用,"
f"要么写下了不建的理由(已记录 {len(EXEMPT)} 条)")
return 0
if __name__ == "__main__":
sys.exit(main())