Files
live-hub-py/tests/test_migrations.py
T
yml2213 5ae5d92978 feat(account): 兑换记录列 + 修掉 source_ref NOT NULL 导致的事件静默丢失
三件事合成一次提交(按反馈不再一改一提交)。

## ① 账号列表加「兑换记录」列

次数 + 最近一次(商品名 + 日期),填上列表右侧的空档。

数据源是**账号自己的事件流**(`account_events` 的 `exchange`),不是 `douyu_tasks`
的 JSON —— 后者是执行日志,S5 起业务事实已经在事件里了。

性能上刻意**每页只跑两条聚合查询**(不是每行一条 N+1):
一条分组算 `count` + `max(occurred_at)`(走 `(account_id, event_type, occurred_at)`
复合索引),一条用窗口函数 `ROW_NUMBER()` 取每个账号最新那条的商品名。
实测 6 个账号 3 条兑换事件,聚合与「最近」都正确。

「兑换 」前缀在前端剥掉(列头已经叫「兑换记录」,再带前缀是重复)。

## ② 修掉一个静默丢事件的 bug(排查中发现的)

**现象**:开发库上「状态变迁 / 分配 / 标签 / 备注 / CK 清除」这些事件**一条都没有**,
而带幂等键的事件(业务事实、`ck_invalid`、`relogin_*`)照常写入 ——
时间线看起来有数据,只是恰好缺了某一类,**极难发现**。

**根因**:`source_ref` 是**可选**幂等键(模型与迁移文件都是 `nullable=True`,
`emit()` 对没有天然幂等键的事件就传 `None`)。但早期那版迁移
(重编号成 `0041` 之前的 `0040`)建的是 **NOT NULL**,而我后来只改了
**迁移文件**、没管**已建好的库** —— Alembic 只记版本号,不会重放已应用的脚本。
`__pycache__` 里那个 `20261002_0040_*.pyc` 就是旧版留下的痕迹。

**为什么静默**:`emit()` 按设计吞掉任何异常(事件是旁路,不能影响主流程),
只记一条 warning,调用方也从不检查返回值。已实测复现:
`emit(...)` 返回 `False` + warning,实际落库 `0` 条。

**修法**:迁移 `20261004_0045` 改回可空(`MODIFY`,**唯一索引保留**,幂等,
生产若跑过旧版也一并修好)。修复后实测:`emit` 返回 `True`、落库 1 条。

## ③ 补一条能防「未来」同类问题的守卫

`tests/test_migrations.py` 原本只比对「表/列/索引在不在」,**不比对可空性**。
已加:迁移建出的列**不允许比模型更严**(模型说可空、库里 NOT NULL)。

只查这个**危险方向**:反方向(模型 NOT NULL、库里允许 NULL)是无害的宽松,
历史遗留里有 28 处,一并报出来只会制造噪声、逼人修没收益的东西。

> 这条守卫**有边界**,已在代码注释与设计文档 §3.5.1 写明:
> 它在**全新库**上跑整链,只能防「未来的迁移建错」,**防不了已有库的历史漂移**。
> 已验证:临时禁用 `0045`,该用例仍通过(全新链本来就是对的)。

## 验证

- `TZ=Asia/Shanghai`:**503 passed / 6 skipped**(+3 条兑换列用例)
- `TZ=UTC`(迁移 + 列表相关)45 passed;ruff 全绿;前端 build 通过、lint 0 errors
- 真实开发库:迁移已应用(head `20261004_0045`),
  `source_ref` 现在 `IS_NULLABLE=YES` 且唯一索引仍在;
  不带幂等键的事件确实能落库;兑换聚合返回值正确

注:验证时在开发库那个有 CK 的账号上留了 3 条 `exchange` 演示事件
(兔兔白日梦 / 冠军鸡腿 / 烟花),是为了让列有数据可看,随时可删。
2026-10-04 17:25:40 +08:00

156 lines
7.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Alembic 迁移链冒烟测试(在真实 MySQL 临时库上执行)。
覆盖三件事:
1. 链完整性:只有一个头版本、头与最新迁移一致、每个修订的
down_revision 都能回溯到根(无悬挂引用、无分叉链)。
2. 全部迁移脚本可编译:防止迁移文件被改坏后部署流程才暴露。
3. 空库整链执行:迁移脚本在真实 MySQL 临时库上执行 `upgrade head`,
随后校验表/列/索引与 Base.metadata 模型元数据对齐(模型要求的不允许缺失),
并确认迁移新增的复合查询索引确实落库。
"""
import secrets
from pathlib import Path
from urllib.parse import quote_plus
from alembic import command
from alembic.config import Config
from alembic.script import ScriptDirectory
from sqlalchemy import create_engine, inspect, text
import web.backend.database as database_module
from tests.support.db import get_mysql_credentials, get_test_engine
from web.backend.database import Base
TESTS_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = TESTS_DIR.parent
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
HEAD_REVISION = "20261004_0045"
# 迁移新增、但不声明在模型里的复合查询索引。
EXTRA_INDEXES = (
"ix_douyu_tasks_handbook_scope_id",
"ix_douyu_tasks_handbook_scope_task_type_id",
"ix_douyu_tasks_status_finished_at_id",
"ix_login_tasks_status_finished_at_id",
# 账号时间线按「账号 + 时间倒序」查,模型里不声明这个复合索引。
"ix_account_events_account_occurred",
# CK 搬到账号后,「在途尝试」只能留在登录记录上,巡检/重登每轮按
# (account_id, attempt_status) 过滤 —— 模型里不声明这个索引。
"ix_login_tasks_account_attempt_status",
)
def _migration_config() -> Config:
config = Config(str(PROJECT_ROOT / "alembic.ini"))
config.set_main_option(
"script_location", str(PROJECT_ROOT / "web" / "backend" / "migrations")
)
return config
class TestMigrationSmoke:
def test_chain_is_linear_and_head_matches_latest_file(self):
directory = ScriptDirectory.from_config(_migration_config())
heads = directory.get_heads()
assert len(heads) == 1, f"迁移链出现多个头版本(存在分叉): {heads}"
assert heads[0] == HEAD_REVISION, f"头版本 {heads[0]} 与最新迁移不一致"
version_files = sorted(path.name for path in VERSIONS_DIR.glob("*.py"))
revisions = list(directory.walk_revisions())
revision_ids = {revision.revision for revision in revisions}
assert len(revision_ids) == len(version_files), (
"迁移文件数量与已加载修订数量不一致(存在无法加载的脚本)"
)
for revision in revisions:
if revision.down_revision is not None:
assert revision.down_revision in revision_ids, (
f"{revision.revision} 引用了不存在的父版本 {revision.down_revision}"
)
def test_all_migration_scripts_compile(self):
for path in sorted(VERSIONS_DIR.glob("*.py")):
source = path.read_text(encoding="utf-8")
compile(source, str(path), "exec") # 语法/缩进等编译错误会在此抛出
def test_full_chain_applies_on_fresh_mysql_and_matches_models(self):
"""空库执行整条迁移链,校验表/列/索引与模型元数据对齐。"""
creds = get_mysql_credentials()
mig_db = f"douyu_login_mig_{secrets.token_hex(4)}"
mig_url = f"mysql+pymysql://{quote_plus(creds['user'])}:{quote_plus(creds['password'])}@{creds['host']}:{creds['port']}/{mig_db}?charset=utf8mb4"
admin_engine = get_test_engine()
with admin_engine.begin() as conn:
conn.execute(
text(
f"CREATE DATABASE `{mig_db}` CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;"
)
)
original_url = database_module.DATABASE_URL
try:
database_module.DATABASE_URL = mig_url
cfg = _migration_config()
cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "head")
inspector = inspect(create_engine(mig_url))
db_tables = set(inspector.get_table_names())
assert db_tables
model_tables = Base.metadata.tables
missing_tables = set(model_tables) - db_tables
assert not missing_tables
all_db_indexes = set()
nullability_mismatches: list[str] = []
for name, table in model_tables.items():
db_cols = inspector.get_columns(name)
db_columns = {column["name"] for column in db_cols}
model_columns = set(table.columns.keys())
missing_columns = model_columns - db_columns
assert not missing_columns
# 可空性只查**危险的那个方向**:模型说可空、库里却是 NOT NULL。
# 那样带 NULL 的写入会**在运行时静默失败**(`emit()` 按设计吞异常),
# 正是 `account_events.source_ref` 那次事故的形态 ——
# 只比对「列在不在」是抓不到的。
#
# 反方向(模型 NOT NULL、库里允许 NULL)是**无害的宽松**:
# SQLAlchemy 总会写值,库里宽松一点不会丢数据。历史遗留里有不少,
# 一并报出来只会制造噪声、逼人去修没有收益的东西。
db_nullable = {c["name"]: c["nullable"] for c in db_cols}
for column in table.columns:
if column.name not in db_nullable:
continue
if bool(column.nullable) and not bool(db_nullable[column.name]):
nullability_mismatches.append(
f"{name}.{column.name}: 模型说可空,"
f"但迁移建成了 NOT NULL(带 NULL 的写入会静默丢失)"
)
db_indexes = set()
for index in inspector.get_indexes(name):
index_name = index["name"]
if index_name:
db_indexes.add(index_name)
all_db_indexes |= db_indexes
model_indexes = {index.name for index in table.indexes if index.name}
missing_indexes = model_indexes - db_indexes
assert not missing_indexes
assert not nullability_mismatches, (
"迁移建出的列比模型更严(会在运行期静默丢数据):\n"
+ "\n".join(nullability_mismatches)
)
# 迁移新增的复合查询索引(不入模型,但应存在)。
for index_name in EXTRA_INDEXES:
assert index_name in all_db_indexes, f"迁移链未创建索引 {index_name}"
finally:
database_module.DATABASE_URL = original_url
with admin_engine.begin() as conn:
conn.execute(text(f"DROP DATABASE IF EXISTS `{mig_db}`;"))