# 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_TRANSITIONS` 14→15. - docstring "6 states + 9 base allowed transitions" 갱신(`* → error` family 는 별도 집합이므로 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_slot` SET 에 `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_slot `entry_count` 필드, Lifecycle `closed→pending_buy`, State Rules(전이 패밀리 8 base + clean-slate). 두 카운터 구분. - `runtime-flows.md`: buy admission `find_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.