🌊 Волна 17: backend #8 — баги + N+1 (16 багов)
Продуктовые: - hint_consumed_before_word_check: сначала проверка слов, потом инкремент (hints.py) - hint_fake_first_cell: 404 вместо [0,0] (hints.py) - leaderboard_rank_wrong_for_uncached_user: корректный rank (leaderboard.py) - teacher_ai_explanation_empty_on_failure: fallback-текст (teacher.py) Данные: - duplicate_delete_keeps_wrong_row: оставляем лучшую строку (database.py) Security: - fastapi_docs_exposed: /docs скрыт в проде (main.py) - cf_ip_check_per_request: предкомпиляция CF_IPS (main.py) N+1: - admin_content_lesson_levels_n_plus_1: 3 GROUP BY (admin_content.py) - admin_content_lesson_topics_n_plus_1: 2 GROUP BY (admin_content.py) - admin_content_get_lesson_n_plus_1: ANY + группировка (admin_content.py) - teacher_progress_n_plus_1: 2 GROUP BY (teacher.py) - teacher_diagnostic_test_n_plus_1: ANY + группировка (teacher.py) - orchestrator_n_plus_1_options: ANY + группировка (orchestrator.py) Качество: - cleanup_task_leak_on_startup_failure: cleanup после init (main.py) - unused_first_name: удалена мёртвая переменная (auth.py) Пропущено осознанно: - initdata_in_query_param (fallback deleteFeedPost) - init_db_slow_startup (Alembic, отдельная задача) Аудит v5: Issue #8, backend 16/17 задач
This commit is contained in:
+63
-25
@@ -288,7 +288,20 @@ async def get_wrong_answer_ai_explanation(telegram_id: int, lang: str, prompt_te
|
||||
async with pool.acquire() as conn:
|
||||
await increment_teacher_ai_usage(conn, telegram_id)
|
||||
else:
|
||||
ai_response = get_ai_limit_message(lang) if not await _check_ai_limit_for_fallback(telegram_id, lang) else ""
|
||||
# 🔧 ФИКС (25.09.2026): teacher_ai_explanation_empty_on_failure —
|
||||
# если AI упал и лимит НЕ исчерпан, возвращаем нейтральный fallback,
|
||||
# а не пустую строку (иначе ученик не понимает, почему ошибся).
|
||||
if not await _check_ai_limit_for_fallback(telegram_id, lang):
|
||||
ai_response = get_ai_limit_message(lang)
|
||||
else:
|
||||
# Нейтральный fallback на 4 языках
|
||||
fallbacks = {
|
||||
"pl": "Zastanów się nad tym pytaniem jeszcze raz.",
|
||||
"ru": "Подумай над этим вопросом ещё раз.",
|
||||
"uk": "Поміркуй над цим питанням ще раз.",
|
||||
"en": "Think about this question again.",
|
||||
}
|
||||
ai_response = fallbacks.get(lang, fallbacks["en"])
|
||||
|
||||
return ai_response
|
||||
|
||||
@@ -1028,17 +1041,29 @@ async def teacher_diagnostic_test(request: Request):
|
||||
"SELECT current_level FROM users WHERE telegram_id = $1", telegram_id
|
||||
) or "A1"
|
||||
session_id = await start_learning_session(conn, telegram_id, user_level, "", "diagnostic_test")
|
||||
|
||||
|
||||
# 🔧 ФИКС (25.09.2026): teacher_diagnostic_test_n_plus_1 —
|
||||
# один запрос ANY + группировка в Python.
|
||||
question_ids = [q["question_id"] for q in questions]
|
||||
|
||||
all_options = []
|
||||
if question_ids:
|
||||
all_options = await conn.fetch("""
|
||||
SELECT * FROM question_options
|
||||
WHERE question_id = ANY($1::text[])
|
||||
""", question_ids)
|
||||
|
||||
options_by_q: dict = {}
|
||||
for o in all_options:
|
||||
options_by_q.setdefault(o["question_id"], []).append(dict(o))
|
||||
|
||||
questions_data = []
|
||||
for q in questions:
|
||||
options = await conn.fetch("""
|
||||
SELECT * FROM question_options WHERE question_id = $1
|
||||
""", q["question_id"])
|
||||
questions_data.append({
|
||||
"question": dict(q),
|
||||
"options": [dict(o) for o in options],
|
||||
"options": options_by_q.get(q["question_id"], []),
|
||||
})
|
||||
|
||||
|
||||
return {
|
||||
"session_id": session_id,
|
||||
"questions": questions_data,
|
||||
@@ -1103,34 +1128,47 @@ async def teacher_progress(request: Request):
|
||||
WHERE is_active = TRUE
|
||||
ORDER BY sort_order
|
||||
""")
|
||||
|
||||
|
||||
if not levels:
|
||||
return {"levels": []}
|
||||
|
||||
level_codes = [lvl["code"] for lvl in levels]
|
||||
|
||||
# 🔧 ФИКС (25.09.2026): teacher_progress_n_plus_1 —
|
||||
# 2 запроса вместо 2×N.
|
||||
topics_total_rows = await conn.fetch("""
|
||||
SELECT level_code, COUNT(*) as cnt
|
||||
FROM learning_topics
|
||||
WHERE level_code = ANY($1::text[]) AND is_active = TRUE
|
||||
GROUP BY level_code
|
||||
""", level_codes)
|
||||
topics_total_map = {r["level_code"]: r["cnt"] for r in topics_total_rows}
|
||||
|
||||
topics_completed_rows = await conn.fetch("""
|
||||
SELECT t.level_code, COUNT(*) as cnt
|
||||
FROM user_topic_progress utp
|
||||
JOIN learning_topics t ON utp.topic_id = t.topic_id
|
||||
WHERE utp.user_id = $1
|
||||
AND utp.test_completed = TRUE
|
||||
AND t.is_active = TRUE
|
||||
AND t.level_code = ANY($2::text[])
|
||||
GROUP BY t.level_code
|
||||
""", telegram_id, level_codes)
|
||||
topics_completed_map = {r["level_code"]: r["cnt"] for r in topics_completed_rows}
|
||||
|
||||
result = []
|
||||
|
||||
for level in levels:
|
||||
code = level["code"]
|
||||
|
||||
topics_total = await conn.fetchval("""
|
||||
SELECT COUNT(*) FROM learning_topics
|
||||
WHERE level_code = $1 AND is_active = TRUE
|
||||
""", code) or 0
|
||||
|
||||
topics_completed = await conn.fetchval("""
|
||||
SELECT COUNT(*) FROM user_topic_progress
|
||||
WHERE user_id = $1 AND topic_id IN (
|
||||
SELECT topic_id FROM learning_topics WHERE level_code = $2 AND is_active = TRUE
|
||||
) AND test_completed = TRUE
|
||||
""", telegram_id, code) or 0
|
||||
|
||||
result.append({
|
||||
"code": code,
|
||||
"name_pl": level["name_pl"],
|
||||
"name_ru": level["name_ru"],
|
||||
"name_uk": level["name_uk"],
|
||||
"name_en": level["name_en"],
|
||||
"topics_total": topics_total,
|
||||
"topics_completed": topics_completed,
|
||||
"topics_total": topics_total_map.get(code, 0),
|
||||
"topics_completed": topics_completed_map.get(code, 0),
|
||||
})
|
||||
|
||||
|
||||
return {"levels": result}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user