feat(safety-sell): dcy-010 BAT-014 — 영속 거부 재시도 쿨다운 (REQ-052~054)
dcy-010(safety-sell 영속 거부 재시도 백오프) 전체 SDLC: draft-req → confirm-req → draft-batch(BAT-014 batch-lite) → run-batch-delivery → confirm-req-implemented. 2026-06-07 실 KIS LIVE SL/TP e2e에서 발견한 KIS 주문 spam 위험(영속 거부 시 매도 무한 재제출) 차단. - REQ-052 (Integration): SafetySellService per-slot 인메모리 쿨다운 (_in_cooldown/_attempt_sell/_prune_cooldown) — forced_close·stop-loss·take-profit 트리거에 min_retry_interval_sec(600s) 이내 재시도 skip(가격 poll 포함) + max_retry_warn_count(3) 도달 시 WARNING + holding 이탈 정리. market_close 제외. - REQ-053 (Configuration): SafetySellConfig min_retry_interval_sec/max_retry_warn_count + TREX_SAFETY_SELL_MIN_RETRY_INTERVAL/MAX_RETRY_WARN_COUNT env (additive) - REQ-054 (Documentation): runtime-flows 쿨다운 flow + 가격체크 tr_id(FHKST01010100) 정정 인메모리 only(DB/스레드/인터페이스 변경 없음), default 미설정 시 기존 동작 불변. 검증: 신규 8 단위(쿨다운 6 + config 2), 전체 278 passed, ruff clean. REQ-052~054 Implemented, BAT-014 release-candidate. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -294,3 +294,92 @@ class TestRunOnce:
|
||||
s = _svc(repo, service, broker, watchdog,
|
||||
_cfg(forced_close_check_interval_sec=60, stop_loss_poll_interval_sec=30))
|
||||
assert s.base_tick_sec == 30.0
|
||||
|
||||
|
||||
# ------------------------------------------------ REQ-052 retry cooldown (BAT-014)
|
||||
class _StubSell:
|
||||
"""slot_service.sell() that records calls but does NOT transition the slot —
|
||||
simulates a broker rejection (slot rolled back to holding) so the same slot
|
||||
keeps re-qualifying for the trigger across ticks."""
|
||||
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
def sell(self, slot_id, *, actor, reason):
|
||||
self.calls.append((slot_id, reason))
|
||||
|
||||
|
||||
def _cooldown_svc(repo, broker, watchdog, cfg):
|
||||
stub = _StubSell()
|
||||
svc = SafetySellService(slot_repo=repo, slot_service=stub, broker=broker,
|
||||
watchdog=watchdog, config=cfg)
|
||||
return svc, stub
|
||||
|
||||
|
||||
class TestRetryCooldown:
|
||||
def test_skips_retry_within_interval(self, repo, service, broker, watchdog):
|
||||
"""FR-1 / S-1: within min_retry_interval_sec, no second attempt."""
|
||||
slot = _make_holding(service, repo, stop_loss_price=Decimal("50000"))
|
||||
broker.prices["005930"] = Decimal("49000")
|
||||
svc, stub = _cooldown_svc(repo, broker, watchdog, _cfg(min_retry_interval_sec=600))
|
||||
svc.check_prices(_NOW)
|
||||
svc.check_prices(_NOW) # same time → cooldown
|
||||
assert len(stub.calls) == 1
|
||||
assert stub.calls[0] == (slot.slot_id, "stop_loss")
|
||||
|
||||
def test_retries_after_cooldown_expiry(self, repo, service, broker, watchdog):
|
||||
"""FR-2 / S-2: after the interval, retry once more."""
|
||||
_make_holding(service, repo, stop_loss_price=Decimal("50000"))
|
||||
broker.prices["005930"] = Decimal("49000")
|
||||
svc, stub = _cooldown_svc(repo, broker, watchdog, _cfg(min_retry_interval_sec=600))
|
||||
svc.check_prices(_NOW)
|
||||
svc.check_prices(_NOW + timedelta(seconds=601))
|
||||
assert len(stub.calls) == 2
|
||||
|
||||
def test_warning_after_max_count(self, repo, service, broker, watchdog, caplog):
|
||||
"""FR-3 / S-3: WARNING once attempt_count reaches max_retry_warn_count."""
|
||||
slot = _make_holding(service, repo, stop_loss_price=Decimal("50000"))
|
||||
broker.prices["005930"] = Decimal("49000")
|
||||
svc, stub = _cooldown_svc(repo, broker, watchdog,
|
||||
_cfg(min_retry_interval_sec=600, max_retry_warn_count=3))
|
||||
import logging
|
||||
with caplog.at_level(logging.WARNING, logger="trex_core.application.safety_sell"):
|
||||
svc.check_prices(_NOW) # count 1
|
||||
svc.check_prices(_NOW + timedelta(seconds=601)) # count 2
|
||||
svc.check_prices(_NOW + timedelta(seconds=1202)) # count 3 → WARN
|
||||
assert len(stub.calls) == 3
|
||||
warns = [r for r in caplog.records if "repeated rejection" in r.getMessage()]
|
||||
assert warns and str(slot.slot_id) in warns[-1].getMessage()
|
||||
|
||||
def test_prune_on_non_holding(self, repo, service, broker, watchdog):
|
||||
"""FR-4 / S-4: cooldown state dropped when slot leaves holding."""
|
||||
slot = _make_holding(service, repo, stop_loss_price=Decimal("50000"))
|
||||
broker.prices["005930"] = Decimal("49000")
|
||||
svc, _ = _cooldown_svc(repo, broker, watchdog, _cfg(min_retry_interval_sec=600))
|
||||
svc.check_prices(_NOW)
|
||||
assert slot.slot_id in svc._last_attempt
|
||||
# slot leaves holding (e.g. sell fills → closed; here transit to pending_sell)
|
||||
service.sell(slot.slot_id, actor="test", reason="x")
|
||||
svc.run_once(_NOW)
|
||||
assert slot.slot_id not in svc._last_attempt
|
||||
assert slot.slot_id not in svc._attempt_count
|
||||
|
||||
def test_market_close_not_gated_by_cooldown(self, repo, service, broker, watchdog):
|
||||
"""AC-5: market_close ignores per-slot cooldown."""
|
||||
slot = _make_holding(service, repo)
|
||||
now = datetime(2026, 6, 7, 6, 10, tzinfo=timezone.utc) # 15:10 KST
|
||||
svc, stub = _cooldown_svc(repo, broker, watchdog,
|
||||
_cfg(market_close_liquidation_time="15:10", min_retry_interval_sec=600))
|
||||
svc._last_attempt[slot.slot_id] = now # slot is "in cooldown"
|
||||
fired = svc.check_market_close(now)
|
||||
assert slot.slot_id in fired # still liquidated despite cooldown
|
||||
assert (slot.slot_id, "market_close_liquidation") in stub.calls
|
||||
|
||||
def test_trigger_resolved_no_increment(self, repo, service, broker, watchdog):
|
||||
"""R-1 / AC-6: price recovered → no sell, no attempt_count increment."""
|
||||
slot = _make_holding(service, repo, stop_loss_price=Decimal("50000"))
|
||||
broker.prices["005930"] = Decimal("65000") # above stop_loss → no trigger
|
||||
svc, stub = _cooldown_svc(repo, broker, watchdog, _cfg())
|
||||
svc.check_prices(_NOW)
|
||||
assert stub.calls == []
|
||||
assert slot.slot_id not in svc._attempt_count
|
||||
|
||||
@@ -11,6 +11,8 @@ _SAFETY_KEYS = (
|
||||
"TREX_FORCED_CLOSE_CHECK_INTERVAL",
|
||||
"TREX_STOP_LOSS_POLL_INTERVAL",
|
||||
"TREX_MARKET_CLOSE_LIQUIDATION_TIME",
|
||||
"TREX_SAFETY_SELL_MIN_RETRY_INTERVAL",
|
||||
"TREX_SAFETY_SELL_MAX_RETRY_WARN_COUNT",
|
||||
)
|
||||
|
||||
|
||||
@@ -35,6 +37,19 @@ def test_safety_sell_config_defaults(tmp_path, monkeypatch, _base_env):
|
||||
assert ss.forced_close_check_interval_sec == 60
|
||||
assert ss.stop_loss_poll_interval_sec == 30
|
||||
assert ss.market_close_liquidation_time is None
|
||||
# BAT-014 / REQ-053
|
||||
assert ss.min_retry_interval_sec == 600
|
||||
assert ss.max_retry_warn_count == 3
|
||||
|
||||
|
||||
def test_retry_cooldown_env_tuning(tmp_path, monkeypatch, _base_env):
|
||||
"""REQ-053 AC-2: retry cooldown env vars are parsed."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
monkeypatch.setenv("TREX_SAFETY_SELL_MIN_RETRY_INTERVAL", "300")
|
||||
monkeypatch.setenv("TREX_SAFETY_SELL_MAX_RETRY_WARN_COUNT", "5")
|
||||
ss = DaemonConfig.from_env().safety_sell
|
||||
assert ss.min_retry_interval_sec == 300
|
||||
assert ss.max_retry_warn_count == 5
|
||||
|
||||
|
||||
def test_safety_sell_config_env_tuning(tmp_path, monkeypatch, _base_env):
|
||||
|
||||
Reference in New Issue
Block a user