全量修复:预测系统正确性、安全性与部署问题
P0 严重问题修复: - 修复 form_slice/stats_slice 主客身份反转(历史比赛视角错误) - 修复 understat.py httpx 未导入导致的 NameError - 修复 LLM 解析失败时静默产生假成功预测(0-0 平局+置信度0.5) 预测路径修复: - multi-agent 路径增加 backtest cutoff 透传,回测防泄漏生效 - H2H 切片汇总统计改为从当前主队视角计数 - 预测唯一约束增加 mode+run_type 维度,防止回测覆盖实盘预测 伤停管线修复: - IntegrityError 后不再整批回滚丢数据(改用逐条 flush) - return_date 正确解析并写入 - retrieved_at 比较统一用 date() 避免当天数据不可见 - 唯一索引改为 partial unique index(排除 NULL 重复) - HTTP 缓存 TTL 从 7 天改为 6 小时 安全与连接管理: - /api/v1/predict 增加内存滑动窗口限流(10次/分钟/IP) - 预测路由改用短 session 模式,LLM 调用期间不持有 DB 连接 Docker 部署修复: - 修复 .dockerignore 排除 *.md 导致 COPY README.md 失败 - 容器内 DATABASE_URL 使用 postgres 服务名(非 localhost) - 启动时自动执行 alembic upgrade head - 前端改用多阶段构建(Dockerfile.frontend) 新增测试(5个文件,24+用例): - test_p0_home_away.py: 主客身份反转回归测试 - test_p0_parse_failure.py: LLM 解析失败回归测试 - test_multi_agent_cutoff.py: multi-agent cutoff 透传测试 - test_h2h_perspective.py: H2H 视角测试 - test_injuries_pipeline.py: 伤停管线 5 项修复测试 - test_predict_protection.py: 限流+短 session 测试 - test_prediction_unique_constraint.py: 唯一约束测试 迁移: - 0012_injuries_partial_unique_and_return_date.py - 0013_predictions_unique_constraint_mode_run_type.py
This commit is contained in:
+57
-26
@@ -71,6 +71,7 @@ class MatchContext:
|
||||
has_stats: bool
|
||||
has_injuries: bool
|
||||
match_dt: object | None = None # 比赛时间(回测防泄漏 + 快照用)
|
||||
cutoff: object | None = None # 实际使用的数据截止时间(用于落库记录)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -144,20 +145,38 @@ async def h2h_slice(header: MatchHeader, *, limit: int = 8, before=None, db: Asy
|
||||
lines = [f"── 历史交锋(近 {limit} 次) ──"]
|
||||
n_with_score = 0
|
||||
if h2h:
|
||||
home_wins = draws = away_wins = 0
|
||||
# 从当前主队视角统计:判断当前主队在每场交锋中是主是客
|
||||
current_home_wins = current_home_draws = current_home_losses = 0
|
||||
for hm in h2h:
|
||||
d = hm.match_date.strftime("%Y-%m") if hm.match_date else "?"
|
||||
if hm.home_goals is not None:
|
||||
n_with_score += 1
|
||||
if hm.home_goals > hm.away_goals: home_wins += 1
|
||||
elif hm.home_goals == hm.away_goals: draws += 1
|
||||
else: away_wins += 1
|
||||
# 判断当前主队当时是主队还是客队
|
||||
if hm.home_team_id == header.home_team_id:
|
||||
# 当前主队当时是主队
|
||||
if hm.home_goals > hm.away_goals:
|
||||
current_home_wins += 1
|
||||
elif hm.home_goals == hm.away_goals:
|
||||
current_home_draws += 1
|
||||
else:
|
||||
current_home_losses += 1
|
||||
else:
|
||||
# 当前主队当时是客队(从客队视角看赛果)
|
||||
if hm.away_goals > hm.home_goals:
|
||||
current_home_wins += 1
|
||||
elif hm.away_goals == hm.home_goals:
|
||||
current_home_draws += 1
|
||||
else:
|
||||
current_home_losses += 1
|
||||
lines.append(f" {d}: {hm.home_team.name} {hm.home_goals}-{hm.away_goals} {hm.away_team.name}")
|
||||
else:
|
||||
lines.append(f" {d}: {hm.home_team.name} vs {hm.away_team.name} (无比分)")
|
||||
total = home_wins + draws + away_wins
|
||||
total = current_home_wins + current_home_draws + current_home_losses
|
||||
if total:
|
||||
lines.append(f" 总计 {total} 场: 主队 {home_wins}胜 {draws}平 {away_wins}负")
|
||||
lines.append(
|
||||
f" 总计 {total} 场(从当前主队 {header.home_name} 视角): "
|
||||
f"{current_home_wins}胜 {current_home_draws}平 {current_home_losses}负"
|
||||
)
|
||||
else:
|
||||
lines.append(" 无数据")
|
||||
# has_data 以「有比分的交锋」为准:仅有对阵无比分时不足以支撑分析
|
||||
@@ -178,14 +197,18 @@ async def form_slice(header: MatchHeader, *, limit: int = 5, before=None, db: As
|
||||
away_form = await _get_form(new_db, header.away_team_id, before=before, limit=limit)
|
||||
lines = []
|
||||
n_scored = 0
|
||||
for label, name, form, side in (
|
||||
("主队", header.home_name, home_form, "home"),
|
||||
("客队", header.away_name, away_form, "away"),
|
||||
# P0-1 修复:每场历史比赛必须根据「该队当时是主是客」判断 side,
|
||||
# 不能用本场 side 硬套 —— 否则客场输球会被算成主场赢球。
|
||||
for label, name, form, team_id in (
|
||||
("主队", header.home_name, home_form, header.home_team_id),
|
||||
("客队", header.away_name, away_form, header.away_team_id),
|
||||
):
|
||||
lines.append(f"── {label}近况({name},近 {limit} 场) ──")
|
||||
if form:
|
||||
wins = draws = losses = 0
|
||||
for fm in form:
|
||||
is_home = (fm.home_team_id == team_id)
|
||||
side = "home" if is_home else "away"
|
||||
o = _outcome(fm.home_goals, fm.away_goals, side)
|
||||
if o == "W": wins += 1
|
||||
elif o == "D": draws += 1
|
||||
@@ -195,9 +218,9 @@ async def form_slice(header: MatchHeader, *, limit: int = 5, before=None, db: As
|
||||
score = f"{fm.home_goals}-{fm.away_goals}" if fm.home_goals is not None else "vs"
|
||||
xg = ""
|
||||
if fm.stats and _is_stats_available(fm.stats, before) and fm.stats.home_xg is not None:
|
||||
own = fm.stats.home_xg if side == "home" else fm.stats.away_xg
|
||||
own = fm.stats.home_xg if is_home else fm.stats.away_xg
|
||||
xg = f" (xG {own:.1f})"
|
||||
opp = fm.away_team.name if side == "home" else fm.home_team.name
|
||||
opp = fm.away_team.name if is_home else fm.home_team.name
|
||||
lines.append(f" {o} {score} vs {opp}{xg}")
|
||||
lines.append(f" 近 {len(form)} 场: {wins}胜 {draws}平 {losses}负")
|
||||
else:
|
||||
@@ -219,30 +242,33 @@ async def stats_slice(header: MatchHeader, *, limit: int = 10, before=None, db:
|
||||
away_form = await _get_form(new_db, header.away_team_id, before=before, limit=limit)
|
||||
lines = [f"── 攻防数据(近 {limit} 场) ──"]
|
||||
n_total = 0
|
||||
for label, name, form, side in (
|
||||
("主队", header.home_name, home_form, "home"),
|
||||
("客队", header.away_name, away_form, "away"),
|
||||
# P0-1 修复:每场历史比赛必须根据「该队当时是主是客」判断 side,
|
||||
# 不能用本场 side 硬套 —— 否则进球/失球/xG 全部算反。
|
||||
for label, name, form, team_id in (
|
||||
("主队", header.home_name, home_form, header.home_team_id),
|
||||
("客队", header.away_name, away_form, header.away_team_id),
|
||||
):
|
||||
if form:
|
||||
gf = ga = shots = sot = poss = xg = xga = 0
|
||||
n = n_shots = n_poss = n_xg = 0
|
||||
for fm in form:
|
||||
if fm.home_goals is None: continue
|
||||
gf += fm.home_goals if side == "home" else fm.away_goals
|
||||
ga += fm.away_goals if side == "home" else fm.home_goals
|
||||
is_home = (fm.home_team_id == team_id)
|
||||
gf += fm.home_goals if is_home else fm.away_goals
|
||||
ga += fm.away_goals if is_home else fm.home_goals
|
||||
n += 1
|
||||
# 只使用 cutoff 之前已可用的统计数据
|
||||
if fm.stats and _is_stats_available(fm.stats, before):
|
||||
if fm.stats.home_shots is not None:
|
||||
shots += fm.stats.home_shots if side == "home" else fm.stats.away_shots
|
||||
sot += fm.stats.home_shots_on_target if side == "home" else fm.stats.away_shots_on_target
|
||||
shots += fm.stats.home_shots if is_home else fm.stats.away_shots
|
||||
sot += fm.stats.home_shots_on_target if is_home else fm.stats.away_shots_on_target
|
||||
n_shots += 1
|
||||
if fm.stats.home_possession is not None:
|
||||
poss += fm.stats.home_possession if side == "home" else (100 - fm.stats.home_possession)
|
||||
poss += fm.stats.home_possession if is_home else (100 - fm.stats.home_possession)
|
||||
n_poss += 1
|
||||
if fm.stats.home_xg is not None:
|
||||
xg += fm.stats.home_xg if side == "home" else fm.stats.away_xg
|
||||
xga += fm.stats.away_xg if side == "home" else fm.stats.home_xg
|
||||
xg += fm.stats.home_xg if is_home else fm.stats.away_xg
|
||||
xga += fm.stats.away_xg if is_home else fm.stats.home_xg
|
||||
n_xg += 1
|
||||
n_total += n
|
||||
if n > 0:
|
||||
@@ -340,23 +366,27 @@ async def injuries_slice(header: MatchHeader, *, before=None, db: AsyncSession |
|
||||
# 单 agent 路径: 拼接全部切片(行为与旧版一致)
|
||||
# ============================================================
|
||||
|
||||
async def build_context(match_id: int, *, form_last: int = 5, h2h_last: int = 5, backtest: bool = False) -> MatchContext:
|
||||
"""单 agent 路径的完整上下文: 拼接全部切片(before=比赛时间,防未来信息)。
|
||||
async def build_context(match_id: int, *, form_last: int = 5, h2h_last: int = 5, backtest: bool = False, cutoff_at=None) -> MatchContext:
|
||||
"""单 agent 路径的完整上下文: 拼接全部切片(before=cutoff,防未来信息)。
|
||||
|
||||
has_stats / has_injuries 直接取切片显式声明的 has_data,
|
||||
不再靠文案子串匹配(见审查报告 P2-1)。
|
||||
|
||||
P2-6: backtest=True 时 cutoff = match_date - 1天,确保只用赛前数据。
|
||||
cutoff_at: 显式截止时间(优先于 backtest 自动计算)。
|
||||
|
||||
P1-1: 使用单个共享 session 贯穿所有切片查询,避免连接池耗尽。
|
||||
"""
|
||||
async with AsyncSessionLocal() as db:
|
||||
header = await load_match_header(match_id, db=db)
|
||||
# P2-6: 回测模式下 cutoff 提前 1 天,防止比赛日数据泄漏
|
||||
cutoff = header.match_dt
|
||||
if backtest and header.match_dt:
|
||||
# 计算数据截止时间: 显式 > backtest 自动计算 > 默认(比赛时间)
|
||||
if cutoff_at is not None:
|
||||
cutoff = cutoff_at
|
||||
elif backtest and header.match_dt:
|
||||
from datetime import timedelta
|
||||
cutoff = header.match_dt - timedelta(days=1)
|
||||
else:
|
||||
cutoff = header.match_dt
|
||||
parts = [header_text(header), ""]
|
||||
|
||||
form_res = await form_slice(header, limit=form_last, before=cutoff, db=db)
|
||||
@@ -384,6 +414,7 @@ async def build_context(match_id: int, *, form_last: int = 5, h2h_last: int = 5,
|
||||
has_stats=form_res.has_data or stats_res.has_data,
|
||||
has_injuries=injuries_res.has_data,
|
||||
match_dt=header.match_dt,
|
||||
cutoff=cutoff,
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user