fix(audit): run_in_threadpool для write_audit_row в async middleware (#1202) #1252
No reviewers
Labels
No labels
admin
analytics
auth
automation
bug
business
chore
ci
compliance
data
data-moat
docs
duplicate
dx
enhancement
Fable 5 ревью
feedback/max
generative
GG-форсайт
needs-discussion
needs-human
observability
pause-bots
performance
priority/p0
priority/p1
priority/p2
priority/p3
scope/backend
scope/db
scope/devops
scope/frontend
scope/qa
scrapers
security
site-finder
stage/1
stage/2
status/blocked
status/done
status/needs-analysis
status/needs-fix
status/qa
status/ready
status/review
status/wip
tech-debt
tradein
ux
week ревью 1
wontfix
вторичка
ИРД
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference: lekss361/gendesign#1252
Loading…
Add table
Reference in a new issue
No description provided.
Delete branch "fix/audit-middleware-run-in-threadpool"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Summary
Closes #1202 (P2 concurrency).
write_audit_row(syncSessionLocal/execute/commit) выполняется напрямую вasync audit_log_middleware→ блокирует event loop на каждом аудируемом запросе.Bug
audit_log_middlewareзарегистрирован черезapp.middleware("http")(main.py:92) → async dispatch на event loop. Послеawait call_next(...)response уже отдан, ноwrite_audit_row(syncSessionLocal()+execute(INSERT)+commit()) блокирует event loop на полный DB round-trip.Под нагрузкой:
GET /forecast(раз в 2 сек), каждый /analyze, /export, /insight-write.pool_timeout=30сНА loop'е → весь API замирает, включая/health.Комментарий в коде «off the critical path» закрывал только латентность для самого клиента, но НЕ блокировку loop'а для других запросов.
Fix
Sync IO в worker-потоке (FastAPI threadpool), event loop свободен. Никаких изменений в самой
write_audit_row— остаётся sync def с собственным try/except + rollback.Test plan
pytest tests/test_audit_middleware.py→ 16/16 passed (поведение для caller'а не изменилось —awaitoverrun_in_threadpoolсинхронно с точки зрения dispatch).ruff check→ clean.Closes #1202
audit_log_middleware зарегистрирован через app.middleware("http") (main.py:92) → async dispatch на event loop. После `await call_next(...)` response уже отдан, но БЛОКИРУЕТ event loop пока идёт sync DB round-trip (SessionLocal/ execute/commit). Это останавливает ВСЕ другие запросы на loop'е до завершения INSERT'а. При исчерпании connection pool (default 5+10, sync analyze держит сессию ~15с inline-wait) checkout ждёт pool_timeout=30с НА loop'е → весь API, включая /health, замирает. Каждый аудируемый запрос: analyze, КАЖДЫЙ 2с-poll GET /forecast, export, insight-write. На активной демо-сессии — десятки таких в минуту. Fix: write_audit_row выполняется через fastapi.concurrency.run_in_threadpool — sync IO в worker-потоке, event loop свободен для других запросов. Никаких изменений в самой write_audit_row — она остаётся sync def с собственным try/except + rollback. 16/16 audit-middleware тестов зелёные (поведение для caller'а не изменилось). Closes #1202