"""하드닝 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 실접속 방지)