fix: 하드닝 루프 8회차 — 체결 보정·고아 감지·청산 경보·실시간/차트·리스크 가드 일괄 수정

- 스윙 체결가 확인 전 executed_price NULL + fill_sweep, 진입가 resolve(ActiveTrade↔Portfolio), 0체결/부분체결 매수 장부 원복
- DT 고아 감지(근거 한정)·0체결 매도 복원·stale 점검 확대, 시간손절 -0.3% 원복
- 폴백 손절 ATR 캐시, 거래량부족-차단 신호 매수 차단, 현금 5% 유보 재적용, MDD peak/reset 수정
- KIS 서킷브레이커 청산 우회·경보, db_worker 재큐잉 순서, heartbeat·health-watch 사이드카
- 실시간 WS 재구독·41건 우선순위·다건 프레임 분할, 차트 샘플 제거·당일봉 합성, WS 서브프로토콜 인증
- 프론트: 미관리 그룹·확인 모달·차트 실시간 반영·예수금 표시 정정
- 전문가 에이전트 6종 추가(.claude/agents)
- 유닛 스위트 2667 passed (소켓 차단 하), tsc OK

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y83Za98XsNw9zuA4FTUytN
This commit is contained in:
2026-10-10 12:17:49 +09:00
parent 5c4803b339
commit a264561576
230 changed files with 41160 additions and 2334 deletions

View File

@@ -0,0 +1,146 @@
"""하드닝 R6: DB alembic_version ↔ 코드 head 대조가 /health 에 노출된다."""
import pytest
from app import main as m
class _Res:
def __init__(self, rows):
self._rows = rows
def fetchall(self):
return self._rows
class _Conn:
def __init__(self, rows=None, exc=None):
self.rows, self.exc = rows, exc
async def execute(self, *_a, **_k):
if self.exc:
raise self.exc
return _Res(self.rows)
@pytest.fixture(autouse=True)
def _reset_state(monkeypatch):
monkeypatch.setattr(m, "_migration_state", {"checked": False, "db": None, "head": None, "mismatch": False})
def test_code_head_readable():
assert len(m._code_alembic_heads_v2()) >= 1
@pytest.mark.asyncio
async def test_match_is_not_mismatch():
heads = m._code_alembic_heads_v2()
st = await m._check_migration_head_v2(_Conn([(h,) for h in heads]))
assert st["mismatch"] is False and st["checked"] is True
@pytest.mark.asyncio
async def test_old_db_version_is_mismatch():
st = await m._check_migration_head_v2(_Conn([("0011",)]))
assert st["mismatch"] is True and st["db"] == "0011"
@pytest.mark.asyncio
async def test_missing_table_raises_not_silent():
with pytest.raises(RuntimeError):
await m._check_migration_head_v2(_Conn(exc=RuntimeError("no alembic_version")))
assert m._migration_state["mismatch"] is False # 불일치로 단정하지 않는다
@pytest.mark.asyncio
async def test_health_degraded_reason_on_mismatch(monkeypatch):
from app.services import db_worker as w
from app.core import redis as _redis
class _NoDb:
def connect(self):
raise RuntimeError("test: real DB access blocked")
monkeypatch.setattr(m, "engine", _NoDb())
monkeypatch.setattr(_redis, "get_redis", lambda: None)
async def dlq():
return {"pending": 0, "manual": 0, "expired": 0}
monkeypatch.setattr(w, "dlq_status_counts", dlq)
monkeypatch.setattr(m, "_runtime_health_v2", lambda market_open=None: ({}, []))
m._migration_state["mismatch"] = True
out = await m._health_check_impl()
assert "migration_mismatch" in out["degraded_reasons"] and out["status"] == "degraded"
@pytest.mark.asyncio
async def test_mismatch_blocks_entry_independent_of_fail_closed(monkeypatch):
"""R8: SECURITY_FAIL_CLOSED=False 여도 불일치면 can_open_new_position 이 False."""
from app.core.config import settings
monkeypatch.setattr(settings, "SECURITY_FAIL_CLOSED", False)
class _Mgr:
async def can_open_new_position(self):
return True
mgr = _Mgr()
m._install_migration_entry_guard_v2(mgr)
m._migration_state["mismatch"] = False
assert await mgr.can_open_new_position() is True
m._migration_state["mismatch"] = True
assert await mgr.can_open_new_position() is False
m._migration_state["mismatch"] = False # 복구 시 자동 해제
assert await mgr.can_open_new_position() is True
@pytest.mark.asyncio
async def test_guard_install_is_idempotent():
class _Mgr:
async def can_open_new_position(self):
return True
mgr = _Mgr()
m._install_migration_entry_guard_v2(mgr)
first = mgr.can_open_new_position
m._install_migration_entry_guard_v2(mgr)
assert mgr.can_open_new_position is first
@pytest.mark.asyncio
async def test_recheck_loop_repeats_warning_and_recovers(monkeypatch):
sent = []
monkeypatch.setattr(m, "_notify_system_warning_bg", lambda c, msg: sent.append(c))
states = iter([True, True, False])
async def _fake_check(_conn):
m._migration_state.update(checked=True, db="0011", head="0012", mismatch=next(states))
return dict(m._migration_state)
class _Ctx:
async def __aenter__(self):
return object()
async def __aexit__(self, *a):
return False
class _Eng:
def connect(self):
return _Ctx()
monkeypatch.setattr(m, "engine", _Eng())
monkeypatch.setattr(m, "_check_migration_head_v2", _fake_check)
m._migration_state["mismatch"] = True
await m._migration_recheck_loop_v2(interval_sec=0, iterations=3)
assert sent == ["migration_mismatch", "migration_mismatch"]
assert m._migration_state["mismatch"] is False
@pytest.mark.asyncio
async def test_recheck_failure_keeps_mismatch(monkeypatch):
class _Eng:
def connect(self):
raise RuntimeError("db down")
monkeypatch.setattr(m, "engine", _Eng())
m._migration_state["mismatch"] = True
await m._migration_recheck_loop_v2(interval_sec=0, iterations=1)
assert m._migration_state["mismatch"] is True