Files
auto-stock/backend/tests/test_swing_scheduler_r9_20261012.py
shuim d140055e64 fix: 하드닝 루프 9회차 — 매수 원복·잔고 연속조회·결과 불명 매도·브레이커·경보 보강
- 8회차 HIGH 수정 16건 레드팀 재검증: 12 확인·3 부분·1 미수정 → 전부 보강
- trade_executor/fill_sweep: 늦게 확정된 0체결 BUY → CANCELLED + ActiveTrade close, 부분체결 → 수량 축소(멱등, 재기동 후 TH 재구성)
- korea_investment_api: get_balance_all_v2(tr_cont 연속조회, _partial), get_todays_orders_v2(실패 None), 브레이커 청산용 조회 면제(OPEN 중 미집계)
- swing/exit_service·mdd_manager: 매도 직전 상한·MDD 축소가 전체 잔고 페이지 사용(§8.5-37), 불명 대기 중 부분익절 skip·쿨다운·pre_hldg 차감, 대기 TTL 15:30+재매수 폐기(대조 1회 선행)(§8.5-38 해소)
- swing/scheduler: 청산 TIMED_OUT/SKIPPED/in-flight 시 MDD 축소·진입 보류(예외는 진입만), 3사이클 연속 시 error+텔레그램
- daytrading: 결과 불명 매도 재판정 v3(주문조회 v2 None→보류, 등록 이후 일치 행→accepted, 원장≤0→보류), 재기동 복원 min(주문가능,보유), 잔고 조회 후 일일손실한도 재확인, 단독 실행 Redis 접속 제거
- main: 스트림 무수신 경보 v4(희망 구독 기준), 첫 하트비트 없음 stale(HB_FIRST_BEAT_GRACE_SEC)
- 운영: Jenkinsfile health_watch.py 디렉터리 잔존 복구, prod_smoke 사이드카 확인, config 키 12개 선언(동작 무변경)
- 진입가 v3(max(AT,PA))는 KIS 이동평균 평단 전제 오류로 레드팀 반증 → 폐기
- CLAUDE.md §3.2 ③-d, §8.5-37/38 갱신, §8.5-39~48 신규(Crisis 손절 소급 §8.5-39 는 사용자 결정 대기)
- 유닛 스위트 2781 passed / 0 failed (소켓 차단), 네트워크 시도 0건

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-12 15:37:16 +09:00

145 lines
5.6 KiB
Python

"""하드닝 R9 A-2 — 청산 단계 미종결(TIMED_OUT/SKIPPED/예외) 사이클의 MDD 축소·진입 생략 (redteam #8).
루프 하네스·상태 초기화는 test_swing_scheduler_hardening_r1 의 것을 그대로 쓴다(autouse _reset_state).
"""
import asyncio
from unittest.mock import AsyncMock
import pytest
from tests.test_swing_scheduler_hardening_r1 import ( # noqa: F401 (_reset_state: autouse 픽스처)
_drain, _loop_env, _messages, _one_cycle, _reset_state,
)
@pytest.mark.asyncio
async def test_timed_out_exit_skips_mdd_reduction_then_resumes(monkeypatch, _reset_state):
release = asyncio.Event()
async def _exit(db):
await release.wait()
return []
sch, _api, _calls = _loop_env(monkeypatch, exit_mock=AsyncMock(side_effect=_exit), can_open=False)
reduce_mock = AsyncMock(return_value=[])
monkeypatch.setattr(sch.mdd_manager, "execute_reduction", reduce_mock)
monkeypatch.setattr(sch.mdd_manager, "reduction_applied", "10pct")
monkeypatch.setattr(sch, "_DEFAULT_EXIT_STEP_TIMEOUT_SEC", 0.05)
await _one_cycle(sch) # 청산 TIMED_OUT
reduce_mock.assert_not_awaited()
await _one_cycle(sch) # 이전 청산 진행 중 → SKIPPED
reduce_mock.assert_not_awaited()
release.set()
await _drain()
await _one_cycle(sch) # 청산 정상 완료 → 축소 재개
reduce_mock.assert_awaited_once()
@pytest.mark.asyncio
async def test_timed_out_exit_skips_entry_then_resumes(monkeypatch, _reset_state):
release = asyncio.Event()
async def _exit(db):
await release.wait()
return []
sch, _api, calls = _loop_env(monkeypatch, exit_mock=AsyncMock(side_effect=_exit))
monkeypatch.setattr(sch, "_DEFAULT_EXIT_STEP_TIMEOUT_SEC", 0.05)
await _one_cycle(sch)
assert calls["entry"] == 0
await _one_cycle(sch)
assert calls["entry"] == 0
release.set()
await _drain()
await _one_cycle(sch)
assert calls["entry"] == 1
@pytest.mark.asyncio
async def test_exit_exception_skips_entry_this_cycle_only(monkeypatch, _reset_state):
sch, _api, calls = _loop_env(monkeypatch)
monkeypatch.setattr(sch, "_run_exit_phase_v2", AsyncMock(side_effect=RuntimeError("boom")))
await _one_cycle(sch)
assert calls["entry"] == 0
monkeypatch.setattr(sch, "_run_exit_phase_v2", AsyncMock(return_value=None))
await _one_cycle(sch)
assert calls["entry"] == 1
def test_unsettled_reason_classification(_reset_state):
sch = _reset_state.sch
assert sch._exit_phase_unsettled_reason_v2(sch._STEP_TIMED_OUT, False)
assert sch._exit_phase_unsettled_reason_v2(sch._STEP_SKIPPED, False)
assert sch._exit_phase_unsettled_reason_v2([], True)
assert sch._exit_phase_unsettled_reason_v2([], False) is None
@pytest.fixture
def _fresh_escalation(monkeypatch, _reset_state):
monkeypatch.setattr(_reset_state.sch, "_mdd_unsettled_skip_state", {"count": 0, "escalated": False})
return _reset_state.sch
@pytest.mark.asyncio
async def test_exit_exception_still_runs_mdd_reduction(monkeypatch, _reset_state, _fresh_escalation):
sch, _api, calls = _loop_env(monkeypatch, can_open=False)
monkeypatch.setattr(sch, "_run_exit_phase_v2", AsyncMock(side_effect=RuntimeError("boom")))
reduce_mock = AsyncMock(return_value=[])
monkeypatch.setattr(sch.mdd_manager, "execute_reduction", reduce_mock)
monkeypatch.setattr(sch.mdd_manager, "reduction_applied", "10pct")
await _one_cycle(sch)
reduce_mock.assert_awaited_once() # 예외(태스크 종료) — 축소는 실행
assert calls["entry"] == 0
assert sch._mdd_unsettled_skip_state["count"] == 0
def test_exception_reason_blocks_entry_but_not_reduction(_reset_state):
sch = _reset_state.sch
assert sch._exit_phase_unsettled_reason_v2([], True)
assert sch._exit_inflight_reason_v2([]) is None
assert sch._exit_inflight_reason_v2(sch._STEP_TIMED_OUT)
assert sch._exit_inflight_reason_v2(sch._STEP_SKIPPED)
@pytest.mark.asyncio
async def test_mdd_reduction_skip_escalates_once_then_resets(monkeypatch, caplog, _reset_state, _fresh_escalation):
release = asyncio.Event()
async def _exit(db):
await release.wait()
return []
sch, _api, _calls = _loop_env(monkeypatch, exit_mock=AsyncMock(side_effect=_exit), can_open=False)
reduce_mock = AsyncMock(return_value=[])
monkeypatch.setattr(sch.mdd_manager, "execute_reduction", reduce_mock)
monkeypatch.setattr(sch.mdd_manager, "reduction_applied", "10pct")
monkeypatch.setattr(sch, "_DEFAULT_EXIT_STEP_TIMEOUT_SEC", 0.05)
limit = sch._DEFAULT_SWING_EXIT_UNSETTLED_ESCALATE_CYCLES
def _escalations():
return [r for r in caplog.records
if r.levelname == "ERROR" and "연속 미실행" in r.getMessage()]
for _ in range(limit - 1):
await _one_cycle(sch)
assert _escalations() == []
await _one_cycle(sch) # limit 번째 → error 1회
assert len(_escalations()) == 1
await _drain() # 텔레그램 전송은 태스크로 스폰된다
assert any("연속 미실행" in m for m in _messages(_reset_state.notify))
await _one_cycle(sch) # 같은 스트릭 — 반복 안 함
assert len(_escalations()) == 1
reduce_mock.assert_not_awaited() # 강제 실행 안 함
release.set()
await _drain()
await _one_cycle(sch) # 정상 청산 → 축소 재개 + 리셋
reduce_mock.assert_awaited_once()
assert sch._mdd_unsettled_skip_state == {"count": 0, "escalated": False}
from _swing_redis_guard import _swing_redis_guard # noqa: E402,F401 (R9: 단독 실행 시 Redis 실접속 방지)