feat(rel-006): dcy-022/023 + BAT-032~034 — 실행 정책·qty 검증·allocated_capital 제거 통합

BAT-032 (dcy-022): timeout_sec/slippage_pct 실행 정책, 미체결 자동 취소,
보호 지정가, `trex-core cancel` 백스톱. 마이그레이션 012.
BAT-033: `trex-core enter --qty` 필수 검증 — 미지정 시 RPC 전 즉시 오류.
BAT-034 (dcy-023): allocated_capital 죽은 필드 전 경로 제거 (domain·intent·
persistence·snapshot·CLI). 마이그레이션 013(비가역 DROP). 외부 발신자
unknown key 무시 수신 의미론 적용.
REL-006 confirmed: BAT-026~034 통합 릴리즈, pre-release smoke 증거 포함.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-06-11 07:42:03 +09:00
co-authored by Claude Sonnet 4.6
parent 5ee5f7f4e2
commit fb05a73130
56 changed files with 3151 additions and 103 deletions
@@ -0,0 +1,50 @@
# BAT-032 Design
- Status: approved
- Batch: BAT-032
## 설계 결정
### D1: 실행 정책 필드를 슬롯 컬럼으로 저장 (timeout_sec, slippage_pct)
- 결정: `Slot` 모델에 `timeout_sec: Optional[int]`, `slippage_pct: Optional[float]` 컬럼 추가. PENDING_* 진입 시 set, 탈출(→HOLDING/→INACTIVE) 시 clear.
- 근거: 집행 루프가 dispatch/poll 시 슬롯만 읽으면 되어 별도 캐시/in-memory 구조 불필요. limit_price 와 동일한 패턴(set on pending entry, cleared on exit).
- 대안: in-memory dict 에 별도 저장 → 재시작 시 유실, 재기동 reconciliation 에서 timeout 추적 불가. 기각.
### D2: updated_at 을 dispatch 시각 proxy 로 사용 (기존 stale watchdog 방법 계승)
- 결정: timeout 경과 시간 = `(now - slot.updated_at).total_seconds()`. mark_dispatched 가 updated_at 을 갱신하므로 dispatch 시각과 일치.
- 근거: `_check_stale_pending`(REQ-014) 이 이미 동일 방법 사용 → 일관성, 추가 필드 불필요.
- 한계: PENDING_* 상태에서 `update_thresholds` 가 호출되면 updated_at 이 리셋될 수 있으나, `update_thresholds`는 HOLDING 슬롯에만 작동(REQ-040) → 실질적 충돌 없음.
### D3: cancel_order best-effort, 즉시 롤백 없음 (race 안전)
- 결정: `_try_timeout_cancel` 에서 cancel_order 송신만 하고 슬롯 상태를 변경하지 않는다. 다음 poll 틱에서 is_terminal_reject/is_partial_cancel 로 수렴.
- 근거: 취소-체결 race(cancel 수락 직전 체결) 시 다음 poll 이 is_filled 경로로 정상 수렴 → 임의 롤백 없음. dcy-013 부분 취소 선례 재사용.
### D4: cancel CLI → control RPC → ExecutionService.cancel_pending_slot
- 결정: CLI는 `trex.control.req` 채널로 `{"action": "cancel_pending", "slot_id": ...}` 를 전송. 제어 핸들러가 `ExecutionService.cancel_pending_slot(slot_id)` 를 호출해 cancel_order 를 송신. 슬롯 전이 없음.
- 근거: 기존 kill_switch·pause 와 동일한 경로(단일 writer 불변식 보존). execution_service 를 control 핸들러에 주입하는 방식으로 커플링 최소화.
- 대안: intent RPC 채널 재사용 → intent 계약(buy/sell)과 의미 혼용. 기각.
## 컴포넌트 다이어그램 (텍스트)
```
CLI: trex-core cancel <slot_id>
→ control RPC (trex.control.req) cancel_pending
→ make_control_rpc_handler (execution_service.cancel_pending_slot)
→ broker.cancel_order(broker_order_id)
→ [다음 tick _poll] is_terminal_reject / is_partial_cancel
→ rollback / partial-preserve (기존 경로)
```
```
Intent: {intent_type: "buy", timeout_sec: 60, slippage_pct: 0.1}
→ messaging_handlers (파싱 → BuyIntent)
→ IntentService._admit_buy (effective_timeout 해결 → transit_slot)
→ SlotService (slot.timeout_sec=60, slot.slippage_pct=0.1 set)
→ [_dispatch] slippage 실효 지정가 → OrderRequest.limit_price
→ [_poll] timeout 초과 → _try_timeout_cancel → cancel_order
→ [다음 tick] is_terminal_reject → rollback
```
@@ -0,0 +1,62 @@
# BAT-032 Implementation
- Status: done
- Batch: BAT-032
## M1 — 실행 정책 계약·파싱·슬롯 저장 (REQ-068, REQ-061 CHG-05)
**변경 파일**
| 파일 | 내용 |
|---|---|
| `trex_core/domain/slot/models.py` | `Slot` dataclass 에 `timeout_sec: Optional[int]`, `slippage_pct: Optional[float]` 추가. `EXPECTED_SLOT_FIELDS` 갱신. |
| `trex_core/adapters/persistence/sql/012_add_execution_policy_fields.sql` | `ALTER TABLE daily_slot ADD COLUMN IF NOT EXISTS timeout_sec INTEGER; … slippage_pct FLOAT;` |
| `trex_core/domain/slot/service.py` | `transit_slot`·`_apply_transition_fields` kwargs 확장. PENDING_* 진입 시 set, HOLDING/INACTIVE/ERROR 진입 시 clear (limit_price 동일 생애주기). |
| `trex_core/adapters/persistence/postgresql.py` | `_SLOT_COLUMNS`에 col 19·20 추가. `update_slot` SQL 갱신. `_row_to_slot` 인덱스 추가. |
| `trex_core/application/intents.py` | `BuyIntent`·`SellIntent` 에 `timeout_sec`·`slippage_pct` 추가. `IntentService.__init__` 에 `default_order_timeout_sec`. `_admit_buy`·`_admit_sell` 에서 effective_timeout 해석. |
| `trex_core/application/messaging_handlers.py` | buy/sell 핸들러에서 `_opt_int`·`_opt_float` 파싱 추가. |
| `trex_core/runtime/config.py` | `DaemonInstanceConfig.default_order_timeout_sec`. |
| `trex_core/runtime/daemon.py` | `IntentService` wiring 에 `default_order_timeout_sec` 전달. |
## M2 — slippage 보호 지정가 dispatch (REQ-070, REQ-013 CHG-03 partial)
**변경 파일**
| 파일 | 내용 |
|---|---|
| `trex_core/application/execution.py` | `_dispatch`: limit 계산 후 slippage 블록 추가. buy: `ceil(limit*(1+pct/100))`, sell: `floor(limit*(1-pct/100))`. `import math` 추가. |
## M3 — timeout 집행 + race 처리 (REQ-069, REQ-013 CHG-03 partial)
**변경 파일**
| 파일 | 내용 |
|---|---|
| `trex_core/application/execution.py` | `ExecutionResult.timeout_cancelled` 추가. `_poll` else branch에 `_try_timeout_cancel` 추가. `_try_timeout_cancel` 구현: `slot.updated_at` proxy로 경과 체크 → `cancel_order` best-effort → `r.timeout_cancelled += 1`. |
## M4 — 운영자 cancel 백스톱 (REQ-071)
**변경 파일**
| 파일 | 내용 |
|---|---|
| `trex_core/application/execution.py` | `cancel_pending_slot(slot_id)` 메서드: PENDING_* slot → `cancel_order` 송신 → "ok"/"not_pending"/"slot_not_found"/"not_dispatched"/"cancel_failed" 반환. 슬롯 전이 없음 (단일 writer 보존). |
| `trex_core/application/messaging_handlers.py` | `make_control_rpc_handler` 에 `cancel_pending_fn` 파라미터. `cancel_pending` 액션 라우팅. `_handle_cancel_pending` 구현. |
| `trex_core/runtime/cli.py` | `cancel <slot_id>` 서브커맨드. `_cmd_cancel`. `_add_intent_guards` (--yes/--dry-run/--live). control RPC 경유. |
| `trex_core/runtime/daemon.py` | `make_control_rpc_handler(cancel_pending_fn=self.execution.cancel_pending_slot)` 배선. |
## M5 — baseline 문서 정합 (REQ-072)
**변경 파일**
| 파일 | 내용 |
|---|---|
| `docs/interface-contract.md` | buy/sell payload에 `timeout_sec`·`slippage_pct` 필드 기술. 하위 호환 주석 추가. cancel CLI 참조. |
| `docs/runtime-flows.md` | dispatch 스텝: slippage 지정가 주석. poll 스텝: timeout 자동 취소 흐름. 실행 정책 생애주기. "운영자 cancel 백스톱" 섹션 추가. |
## 설계 결정 근거 (design.md 요약)
- **D1**: `timeout_sec`/`slippage_pct` 를 slot 컬럼으로 저장 — `limit_price` 와 동일 생애주기(PENDING 진입 시 set, 탈출 시 clear).
- **D2**: `slot.updated_at` 을 dispatch 시각 proxy로 사용 — 기존 stale watchdog(REQ-014)과 동일 방법, 별도 컬럼 불필요.
- **D3**: `cancel_order` 송신만, 즉시 롤백 없음 — cancel-fill race 안전. 다음 poll의 `is_terminal_reject`/`is_partial_cancel` 경로 재사용.
- **D4**: cancel CLI → control RPC → `ExecutionService.cancel_pending_slot` — 단일 writer 불변식(A) 보존.
@@ -0,0 +1,23 @@
# BAT-032: 주문 실행 정책 — timeout·slippage·운영자 cancel (dcy-022)
- Status: release-candidate
- Profile: standard
- Source Discovery: dcy-022
- Included REQ: REQ-068 (실행 정책 계약), REQ-069 (timeout 집행·race), REQ-070 (slippage dispatch), REQ-071 (운영자 cancel 백스톱), REQ-072 (baseline 정합), REQ-061 (CHG-05), REQ-013 (CHG-03)
## Summary
- dcy-022: dcy-021(포지션 사이징) 전제 위에 **주문 실행 정책**(timeout_sec·slippage_pct)을 intent 계약에 추가하고 집행 루프에 배선한다. 미체결 주문은 timeout 초과 시 자동 취소·롤백(고착 예방), slippage 보호 지정가로 과도한 불리 체결을 방지. 잔여 고착 백스톱으로 운영자 cancel CLI 를 추가한다.
## Scope
- In: timeout_sec/slippage_pct intent 계약·파싱·슬롯 저장, timeout 집행 (cancel_order 배선·race 처리·부분 보존), slippage 실효 지정가 dispatch, 운영자 cancel 백스톱(trex-core cancel), per-instance TOML default_order_timeout_sec, baseline 2문서.
- Out: IOC/FOK 네이티브 TIF, 자동 리밸런싱, 전략 모듈(orb-v1) 발신 계약 전환(외부 repo, 별도 합의).
## Documents
- Planning: [planning.md](./planning.md)
- Design: [design.md](./design.md)
- Implementation: [implementation.md](./implementation.md)
- Verification: [verification.md](./verification.md)
## Notes
- 집행 핫패스(라이브 주문) 확장 — additive(기존 경로 보존). design.md D1~D4 확정 후 구현.
- 본 배치 완료 후 REQ-013/061/068/069/070/071/072 confirm-req-implemented.
@@ -0,0 +1,64 @@
# BAT-032 Planning
- Status: done
- Batch: BAT-032
## Milestones
| ID | 목표 | 연결 REQ |
|---|---|---|
| M1 | 실행 정책 계약·파싱·슬롯 저장 | REQ-068, REQ-061(CHG-05) |
| M2 | slippage 보호 지정가 dispatch | REQ-070, REQ-013(CHG-03 partial) |
| M3 | timeout 집행 + race 처리 | REQ-069, REQ-013(CHG-03 partial) |
| M4 | 운영자 cancel 백스톱 CLI + control RPC | REQ-071 |
| M5 | baseline 문서 정합 | REQ-072 |
## M1 상세 (실행 정책 계약·파싱·슬롯 저장)
- `Slot` 모델: `timeout_sec: Optional[int]`, `slippage_pct: Optional[float]` 필드 추가. `EXPECTED_SLOT_FIELDS` 갱신.
- Migration 012: `ALTER TABLE daily_slot ADD COLUMN IF NOT EXISTS timeout_sec INTEGER; ADD COLUMN IF NOT EXISTS slippage_pct FLOAT;`
- `BuyIntent`/`SellIntent`: `timeout_sec`/`slippage_pct` 추가.
- `IntentService`: `__init__` 에 `default_order_timeout_sec: Optional[int] = None` 추가. `_admit_buy`/`_admit_sell` 에서 effective_timeout = intent.timeout_sec ?? config_default → transit_slot 에 전달.
- `SlotService.transit_slot` kwargs: `timeout_sec`/`slippage_pct` 전달. `_apply_transition_fields` 에서 PENDING_* 진입 시 set, 탈출(→HOLDING/→INACTIVE) 시 clear.
- `messaging_handlers.py`: `timeout_sec=_opt_int(body.get("timeout_sec"))`, `slippage_pct=_opt_float(body.get("slippage_pct"))` 파싱 추가.
- `DaemonInstanceConfig`: `default_order_timeout_sec: Optional[int] = None` 추가, from_toml 파싱.
- `DaemonConfig` + daemon runtime 배선: IntentService 에 default_order_timeout_sec 전달.
## M2 상세 (slippage 보호 지정가 dispatch)
- `execution._dispatch`: limit 계산 후 slippage 적용:
```python
import math
if limit is not None and slot.slippage_pct:
factor = 1 + slot.slippage_pct/100 if side == "buy" else 1 - slot.slippage_pct/100
limit = int(math.ceil(limit * factor)) if side == "buy" else int(math.floor(limit * factor))
```
- `_log.debug(...)` 로 slippage 적용 기록.
## M3 상세 (timeout 집행)
- `ExecutionResult`: `timeout_cancelled: int = 0` 추가.
- `_poll` 의 else branch(`_check_stale_pending` 호출)에서 timeout 체크 추가:
```python
self._check_stale_pending(slot, now, r) # Alert-only (REQ-014, no change)
self._try_timeout_cancel(slot, now, r) # NEW: cancel if timeout_sec exceeded
```
- `_try_timeout_cancel`: `slot.timeout_sec` 있고 경과 시간 초과 시 → `broker.cancel_order(...)` best-effort → `r.timeout_cancelled += 1` → WARNING 로그. 실패 시 WARNING, 상태 불변.
## M4 상세 (운영자 cancel 백스톱)
- `messaging_handlers.make_control_rpc_handler`: `cancel_pending` 액션 추가. `cancel_pending_fn` 콜백(slot_id → bool) 주입.
- `execution.ExecutionService.cancel_pending_slot(slot_id)`: 슬롯 조회 → PENDING_* 이면 `broker.cancel_order` 송신. 슬롯 직접 전이 없음.
- `cli.py`: `cancel <slot_id>` 서브커맨드 추가. `--dry-run`/`--yes`/`--live` 안전장치. control RPC 경유.
- daemon.py 배선: make_control_rpc_handler 에 cancel_pending_fn 전달.
## M5 상세 (baseline 문서)
- `docs/interface-contract.md`: buy/sell payload 에 `timeout_sec`/`slippage_pct` 추가.
- `docs/runtime-flows.md`: 집행 루프·dispatch 섹션에 timeout 취소·slippage·cancel 백스톱 흐름 추가.
## 위험 요소
- **R-1 (취소-체결 race)**: cancel_order 송신 후 즉시 롤백하지 않고 다음 poll 수렴 → 기존 is_terminal_reject/is_partial_cancel 경로 재사용 완화.
- **R-2 (부분 체결 보존)**: timeout cancel → is_partial_cancel → 기존 `_on_partial_cancel` 선례(dcy-013) 재사용.
- **R-3 (단일 writer)**: cancel CLI 는 cancel_order 만 송신; 슬롯 전이는 집행 루프 단독 → 불변식 보존.
@@ -0,0 +1,69 @@
# BAT-032 Verification
- Status: approved
- Batch: BAT-032
## Test Evidence
단위 테스트 425 passed, 45 skipped (통합 제외). 신규 71 tests.
```
.venv/bin/python -m pytest tests/ -q --ignore=tests/integration
425 passed, 45 skipped in 1.18s
```
## 신규 테스트 파일
| 파일 | 커버리지 |
|---|---|
| `tests/domain/slot/test_execution_policy_lifecycle.py` | REQ-068: PENDING 진입 시 set, HOLDING/INACTIVE 탈출 시 clear (10 cases) |
| `tests/application/test_execution_policy.py` | REQ-069/070/071: slippage dispatch (buy ceil, sell floor, market=skip, no-slippage=unchanged, zero) + timeout cancel (exceeded→cancel sent, not exceeded→no cancel, no timeout_sec→no cancel, exception best-effort, state unchanged, cancel-fill race) + cancel_pending_slot (ok, not_pending, slot_not_found, not_dispatched, cancel_failed, state unchanged) |
| `tests/application/test_execution_policy_handler.py` | REQ-068/071 핸들러: buy/sell intent payload 파싱 (timeout_sec/slippage_pct), default_order_timeout_sec 계층적 해석, control cancel_pending 액션 (ok/not_pending/slot_not_found/no-fn/cancel_failed/missing-slot_id) |
| `tests/runtime/test_cli_operator.py` (기존 확장) | REQ-071 cancel CLI: 확인 없이 중단, --yes 제출, --dry-run 스킵, --json 출력, ignored/not_found 응답 처리 |
## REQ 별 AC 검증
### REQ-068 (실행 정책 계약)
- AC-1 (timeout_sec 파싱·저장): `test_buy_timeout_sec_parsed_and_stored_on_slot`, `test_timeout_sec_set_on_pending_buy_entry`
- AC-2 (slippage_pct 파싱·저장): `test_buy_slippage_pct_parsed_and_stored_on_slot`, `test_slippage_pct_set_on_pending_buy_entry`
- AC-3 (config default): `test_config_default_applied_when_intent_has_no_timeout`
- AC-4 (하위 호환): `test_buy_policy_fields_absent_means_none`, `test_policy_fields_default_to_none_when_not_given`
- AC-5 (per-intent override): `test_per_intent_timeout_overrides_config_default`
- AC-6 (cleared on exit): `test_policy_cleared_on_transition_to_holding`, `test_policy_cleared_on_transition_to_inactive`
### REQ-069 (timeout 집행·race)
- AC-1 (timeout 초과 → cancel_order): `test_timeout_exceeded_sends_cancel_order`
- AC-2 (is_terminal_reject → rollback): race 수렴은 기존 `test_full_external_cancel_returns_slot_to_holding` 재사용
- AC-3 (is_partial_cancel → 부분 보존): 기존 `test_partial_fill_then_cancel_records_and_keeps_remainder` 재사용
- AC-4 (cancel 후 fill race → is_filled 경로): `test_timeout_cancel_then_fill_race_handled`
- AC-5 (timeout_sec 없으면 cancel 없음): `test_no_timeout_sec_no_cancel`
- AC-6 (exception best-effort): `test_timeout_cancel_best_effort_on_exception`
### REQ-070 (slippage 지정가)
- AC-1 (buy ceil): `test_buy_slippage_ceil_applied_to_limit`
- AC-2 (sell floor): `test_sell_slippage_floor_applied_to_limit`
- AC-3 (market = ignore): `test_no_slippage_when_market_order_no_entry_price`
- AC-4 (slippage 없으면 기존 동작): `test_no_slippage_when_slippage_pct_is_none`
- AC-5 (0% = 기본 가격): `test_zero_slippage_uses_base_price`
- AC-6 (분수 입력 ceil/floor): `test_buy_slippage_fractional_ceil`
### REQ-071 (운영자 cancel 백스톱)
- AC-1 (PENDING_BUY cancel): `test_ok_sends_cancel_and_returns_ok`
- AC-2 (루프 수렴): 단일 writer 설계로 execution loop 수렴 보장 (`test_cancel_does_not_change_slot_state`)
- AC-3 (PENDING_SELL same): cancel_pending_slot 구현에 PENDING_SELL 포함 (코드 검증)
- AC-4 (HOLDING ignored): `test_not_pending_returns_not_pending`
- AC-5 (not_found): `test_slot_not_found_returns_slot_not_found`
- AC-6 (--dry-run): `test_cancel_dry_run_does_not_submit`
### REQ-072 (baseline 정합)
- AC-1~4: docs/interface-contract.md, docs/runtime-flows.md 수동 확인 완료 (M5).
## 기존 테스트 회귀 없음
전체 425 passed — REQ-013/061 기존 AC 포함 회귀 없음.
| 항목 | 결과 |
|---|---|
| 단위 테스트 (non-integration) | 425 passed, 45 skipped |
| 신규 tests | 71 |
| 회귀 | 없음 |