dcy-019/issue #18: slot 자원을 진입 횟수 기준으로 고르게 재사용하고 idle 소진 시 closed 슬롯을 직접 재할당한다. 거버넌스는 전부 change-req(신규 REQ 없음). - 도메인(REQ-002): Slot.entry_count(기본 0) + EXPECTED_SLOT_FIELDS, 상태 머신 closed→pending_buy 신규 전이(base 8→9, ALLOWED_TRANSITIONS 14→15), _apply_transition_fields closed→pending_buy clean-slate + →pending_buy 시 +1 - 영속화(REQ-006): 멱등 마이그레이션 008(entry_count), flat 매핑, find_allocatable_slot(idle∪closed, entry_count→updated_at→slot_id) + in-memory 동등 - admission(REQ-007): _admit_buy find_idle_slot→find_allocatable_slot + from_state=slot.status - 테스트(REQ-003): 전이 카운트/계약 가드 정합 + test_slot_entry_count.py / test_buy_admission_reallocation.py - 문서(REQ-009): data-model.md / runtime-flows.md 정합 - 기존 daily_symbol_entries(symbol-scoped) 분리·미변경 BAT-025(release-candidate) delivery + change-req REQ-002/003/006/007/009(CHG-20260609-01). REL-005(confirmed, app-service): BAT-024+BAT-025 묶음. operator-facing run-the-app 스모크로 enter --forced-close-at(BAT-024)·closed 재할당(BAT-025) 실 데몬 검증 (실 PG 마이그레이션 008 round-trip 포함). 검증: 단위 366 passed / 35 skipped(KIS sandbox 1건 deselect — live .env 환경 의존), ruff clean. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
4.3 KiB
4.3 KiB
BAT-025 Design
- Status: confirmed
- Batch: BAT-025
설계 목표
- 슬롯 자원을 진입 횟수 기준으로 고르게 재사용하고 idle 소진 시 closed 슬롯을 재할당하도록, slot-scoped
entry_count를 도메인 정본에 영속하고 buy admission 후보를 idle∪closed 로 확장한다. 동시성·계약·기존 동작(회귀) 안전을 보장한다.
1. 슬롯 도메인 필드 (REQ-002)
Slot.entry_count: int = 0(take_profit_price 뒤, created_at 앞).EXPECTED_SLOT_FIELDS에"entry_count"추가(같은 위치).- slot-scoped 누적 진입 횟수.
daily_symbol_entries(symbol-scoped, AC-3)와 무관 — 본 batch 에서 후자 미변경.
2. 상태 머신 전이 (REQ-002)
_BASE_TRANSITIONS에(CLOSED, PENDING_BUY)추가(#9). base 7→8 tuple,ALLOWED_TRANSITIONS14→15.- docstring "6 states + 9 base allowed transitions" 갱신(
* → errorfamily 는 별도 집합이므로 base 카운트는 tuple 8 + 주석 #9).
3. 전이 필드 계산 (REQ-002 / _apply_transition_fields)
- closed→pending_buy clean-slate(limit_price lifecycle 분기 앞):
to_state is PENDING_BUY and slot.status is CLOSED면 점유 필드(symbol/qty/avg_price/limit_price/allocated_capital/order_id/strategy_id/broker_order_id/portfolio_id/sell_strategy_id/forced_close_at/stop_loss_price/take_profit_price)를 None 으로 리셋한slot으로 교체 → 이전 사이클 점유가 새 진입에 누수되지 않음.entry_count는 리셋 대상 제외(누적 보존). - 이후 generic
replace에서 caller-supplied 값으로 새 진입 필드 적용(None 이면 keep — clean-slate 후이므로 None 유지). - entry_count +1:
new_entry_count = slot.entry_count + (1 if to_state is PENDING_BUY else 0)→ idle→ 와 closed→ 모두 +1. 그 외 전이·closed→idle 복구는 보존.replace(..., entry_count=new_entry_count).
4. 후보 selector (REQ-006)
SlotRepository.find_allocatable_slot(trading_date)Protocol 추가: idle∪closed 후보를entry_count asc → updated_at asc → slot_id정렬로 1건(없으면 None). caller 가 advisory lock+재시도로 마지막 후보 경합 처리.- PG:
SELECT {_SLOT_COLUMNS} FROM daily_slot WHERE trading_date=%s AND status IN ('idle','closed') ORDER BY entry_count ASC, updated_at ASC, slot_id ASC LIMIT 1. 기존find_idle_slot와 동일하게 FOR UPDATE 미사용(동시성은 transit advisory lock). - in-memory: idle/closed 후보 중
min(key=(entry_count, updated_at or min, str(slot_id))).
5. persistence flat 매핑 (REQ-006)
_SLOT_COLUMNS끝에entry_count(인덱스 18, 총 19컬럼).update_slotSET 에entry_count=%s+ params._row_to_slot에entry_count=int(row[18]) if row[18] is not None else 0.- 마이그레이션
008_add_slot_entry_count.sql:ALTER TABLE daily_slot ADD COLUMN IF NOT EXISTS entry_count INTEGER NOT NULL DEFAULT 0(additive·멱등, 004 패턴).
6. admission (REQ-007)
_admit_buy재시도 루프:find_idle_slot→find_allocatable_slot. transit from_state 하드코딩IDLE→slot.status(후보가 idle 이면 idle→, closed 면 closed→ 직접 재할당). 후보 없으면no_idle_slot거부.SlotStateMismatchError시 다음 후보 재시도(경합 보존). 멱등(intent_log dedup) 불변.
7. baseline 문서 (REQ-009)
data-model.md: daily_slotentry_count필드, Lifecycleclosed→pending_buy, State Rules(전이 패밀리 8 base + clean-slate). 두 카운터 구분.runtime-flows.md: buy admissionfind_allocatable_slot(idle∪closed, entry_count 정렬)·closed 재할당, transit_slot 흐름에→pending_buy 시 entry_count +1단계.
테스트 설계
- domain: 전이 카운트(14→15, closed→pending_buy allowed/disallowed 재배치); 계약 가드(EXPECTED_SLOT_FIELDS); entry_count 증분(idle→/non-buy 미증가)·closed→idle 복구 보존; closed→pending_buy clean-slate(미공급 필드 클리어)·+1; selector(none/idle-only/closed 포함/entry_count 오름차순).
- application: closed 재할당 admit(idle 소진 시), idle 우선(closed 보다), 양쪽 소진 reject; 동시성 경합 회귀(test_intent_concurrency).
- PG 게이트: 마이그레이션/드리프트(
EXPECTED_SLOT_FIELDS↔information_schema) — entry_count 자동 반영. - 회귀: 전체 단위(flat 매핑 추가로 인한 slot read/write 무누락) green.