fix(broker): dcy-013 KIS 외부 취소 감지 + 부분 체결 회계 + stale 워치독 (BAT-017)

KIS 계좌에서 직접 매도 주문을 취소하면 poll_fill 이 cncl_yn 을 파싱하지 않아
슬롯이 pending_sell 에 영구히 갇히고 죽은 주문을 무한 폴링하던 버그(issue #9)
정정.

거버넌스: 전부 change-req (신규 REQ 없음, dcy-013 OQ-3).
- REQ-012: KIS poll_fill cncl_yn 파싱 → 외부 취소 감지. FillStatus.cancelled
  /is_partial_cancel 추가. 체결 0 취소→cancelled, 부분 체결 후 취소→partial+cancelled
- REQ-013: 집행 _on_partial_cancel — 체결분 원장 1회 + qty 차감(매도 잔여/매수 체결분)
  + holding 복귀 (OQ-1 A안). 전량 취소는 기존 롤백 경로 재사용
- REQ-018: 부분 체결분 원장 1회 기록 (_record_ledger 재사용)
- REQ-031: 잔여 포지션 정합 연계 (slot.qty ↔ 실 잔고, 과매도 방지)
- REQ-014: pending stale 워치독 Alert-only (TREX_PENDING_STALE_THRESHOLD,
  WARN+카운터, 상태 미변경) — 취소 감지 누락 backstop
- REQ-015: interface-contract/runtime-flows 정합

전량 취소는 holding 자동 복구(limit_price clear→재매도 시장가, dcy-012 연계).
KIS cncl_yn 실 규약은 운영 검증(미지 값 보수 처리 + 워치독 backstop).

검증: 단위 294 passed/32 skipped, 인프라 게이트(PG+RabbitMQ) 326 passed, ruff clean.
신규 test_kis_cancel(httpx stub) + test_execution_cancel(programmable broker).
BAT-017 release-candidate.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-08 14:11:49 +09:00
co-authored by Claude Opus 4.8
parent cc28e1fba5
commit 4746f74aae
24 changed files with 1063 additions and 6 deletions
@@ -185,3 +185,41 @@
#### Validation Plan
- BAT-016: 코드-문서 diff 대조(S-4).
### CHG-20260608-02
- Date: 2026-06-08
- Author: Justin Ko
#### Change Summary
- (change-req, dcy-013) baseline 문서를 외부 취소 감지·부분 체결 회계·pending stale 워치독에 맞춰 정합: `docs/interface-contract.md`(FillStatus.cancelled/is_partial_cancel + state별 집행 처리 + KIS cncl_yn 매핑), `docs/runtime-flows.md`(poll 단계 외부 취소 → 롤백/부분 회계 + Alert-only stale 워치독). BAT-017 정합 완료 → Implemented 유지.
#### Intent
- 코드(kis/broker_port/execution/config) 변경과 baseline 문서를 일치(S 기준)시켜 운영자 참조 정합 유지.
#### Acceptance Criteria Delta
- Updated:
- interface-contract/runtime-flows 의 취소 감지·부분 회계·stale 워치독 기술 정합.
#### Impacted Area Delta
- Docs: docs/interface-contract.md, docs/runtime-flows.md
#### Delivery Trace Delta
- Batches: BAT-017
- Releases: none
#### Revalidation Impact
- Reverification Needed: no (문서 정합)
- Existing Implementation Invalidated: no
- Status Recommendation: Implemented (change-req → BAT-017 정합)
- Follow-up Action: confirm-req-implemented(BAT-017).
#### Validation Plan
- BAT-017: 코드-문서 diff 대조.
@@ -148,3 +148,42 @@
#### Validation Plan
- BAT-004 verification evidence 재참조로 충분.
### CHG-20260608-01
- Date: 2026-06-08
- Author: Justin Ko
#### Change Summary
- (change-req, dcy-013/issue #9, OQ-2 Alert-only) pending 주문 stale 워치독 추가: dispatched-pending 슬롯이 `TREX_PENDING_STALE_THRESHOLD`(초, 0=비활성) 초과로 머물면 WARN 로그 + `ExecutionResult.stale_pending` 카운터로 가시화한다. **슬롯/주문 상태는 변경하지 않는다**(auto-remediation 후속). 취소 감지 누락(R-1) 등 미지 원인 무한 갇힘이 silent 로 남지 않게 하는 reconciliation 안전망. BAT-017 재구현·재검증 완료 → Implemented 유지.
#### Intent
- 자동 취소 감지(REQ-012)가 놓치는 케이스까지 포함해, 비정상적으로 오래 pending 인 주문을 운영자에게 노출하는 durability 안전망 제공.
#### Acceptance Criteria Delta
- Added:
- pending stale 임계 초과 시 WARN+카운터 가시화(상태 미변경, Alert-only). 임계 env `TREX_PENDING_STALE_THRESHOLD`(0=비활성).
#### Impacted Area Delta
- Modules: `trex_core/application/execution.py`(`_check_stale_pending`, ExecutionService threshold), `trex_core/runtime/config.py`(`pending_stale_threshold_sec`/env), `trex_core/runtime/daemon.py`(배선)
- Tests: tests/application/test_execution_cancel.py(stale WARN + 비활성)
#### Delivery Trace Delta
- Batches: BAT-017
- Releases: none
#### Revalidation Impact
- Reverification Needed: yes (BAT-017 에서 완료)
- Existing Implementation Invalidated: no (관측만 추가, 기존 reconcile/poll 동작 불변)
- Status Recommendation: Implemented (change-req → BAT-017 재검증)
- Follow-up Action: confirm-req-implemented(BAT-017).
#### Validation Plan
- BAT-017: 임계 초과 pending 주입 → WARN+카운터, 상태 미변경 / 비활성(default) → 무경고 단위.
@@ -133,3 +133,41 @@
- AC-1: tests/application/test_reconciliation.py::test_mismatch_raises_warning_and_masks_asset.
- AC-2: ::test_subsequent_match_auto_clears_warning.
- AC-3: ::test_paper_broker_returns_deterministic_balance.
### CHG-20260608-01
- Date: 2026-06-08
- Author: Justin Ko
#### Change Summary
- (change-req, dcy-013/issue #9) 부분 체결 후 외부 취소 처리(REQ-013)가 슬롯 qty 를 체결분만큼 차감하고 잔여를 holding 으로 복귀시켜, 슬롯 잔여 수량이 실 브로커 잔고와 정합하도록 보장한다(과매도 방지). 포지션 정합 검증 로직 자체(`reconcile_positions`)는 코드 변경 없음 — 본 change-req 는 정합 불변식이 유지됨을 명시하는 연계 기록. BAT-017 검증 완료 → Implemented 유지.
#### Intent
- 부분 체결+취소에서 slot.qty ↔ 실제 held 수량 정합을 보장해 REQ-031 의 포지션 정합 불변식이 깨지지 않게 한다.
#### Acceptance Criteria Delta
- (변경 없음 — reconcile 로직 불변. 부분 취소 회계가 정합 입력을 정확히 유지)
#### Impacted Area Delta
- Modules: (없음 — REQ-013 `_on_partial_cancel` 이 잔여 qty 를 정확히 갱신)
- Tests: tests/application/test_execution_cancel.py(잔여 qty=6 정합)
#### Delivery Trace Delta
- Batches: BAT-017
- Releases: none
#### Revalidation Impact
- Reverification Needed: no (reconcile 코드 불변, 회계 정확성은 REQ-013 테스트로 커버)
- Existing Implementation Invalidated: no
- Status Recommendation: Implemented (연계 change-req)
- Follow-up Action: confirm-req-implemented(BAT-017).
#### Validation Plan
- BAT-017: 부분 취소 후 slot.qty 가 잔여 held 와 일치(과매도 0).
@@ -150,3 +150,42 @@
#### Validation Plan
- BAT-004 verification evidence 재참조로 충분.
### CHG-20260608-01
- Date: 2026-06-08
- Author: Justin Ko
#### Change Summary
- (change-req, dcy-013/issue #9) KIS `poll_fill` 이 `inquire-daily-ccld` 응답의 `cncl_yn="Y"` 를 파싱해 외부 취소를 감지한다. 체결 0 취소 → `FillStatus(state="cancelled")`, 부분 체결 후 취소 → `state="partially_filled" + cancelled=True`(execution_id/fee 운반). 미지/부재 값은 보수적 비취소. BAT-017 재구현·재검증 완료 → Implemented 유지.
#### Intent
- 계좌 직접 취소가 `accepted` 로 오판되어 슬롯이 pending_sell 에 영구 갇히던 갭(issue #9) 제거 — KIS 어댑터가 취소를 종료 상태로 정확히 매핑.
#### Acceptance Criteria Delta
- Added:
- poll_fill 이 cncl_yn 을 파싱: 체결 0 취소 → cancelled, 부분 체결 후 취소 → partially_filled+cancelled.
#### Impacted Area Delta
- Modules: `trex_core/adapters/broker/kis.py`(poll_fill), `trex_core/application/broker_port.py`(FillStatus.cancelled/is_partial_cancel)
- Tests: tests/adapters/broker/test_kis_cancel.py
#### Delivery Trace Delta
- Batches: BAT-017
- Releases: none
#### Revalidation Impact
- Reverification Needed: yes (BAT-017 에서 완료)
- Existing Implementation Invalidated: yes (취소를 accepted 로 오판하던 poll_fill)
- Status Recommendation: Implemented (change-req → BAT-017 재검증)
- Follow-up Action: confirm-req-implemented(BAT-017).
#### Validation Plan
- BAT-017: 취소 fixture(full/partial/non-cancel/full-fill) → FillStatus 매핑 단위.
@@ -189,3 +189,42 @@
#### Validation Plan
- BAT-016: 지정가 매수 슬롯 + 가격 미전달 매도 → 시장가(entry_price 미사용 증명), + 가격 전달 매도 → 그 지정가, 시장가 매수 슬롯 회귀.
### CHG-20260608-02
- Date: 2026-06-08
- Author: Justin Ko
#### Change Summary
- (change-req, dcy-013/issue #9) 집행 루프에 외부 취소 처리 추가: 전량 취소(`is_terminal_reject`)는 기존 롤백 경로 재사용, 부분 체결 후 취소(`is_partial_cancel`)는 신규 `_on_partial_cancel` — 체결분 원장 1회 기록 + 슬롯 qty 차감(매도 잔여 held / 매수 체결분) + holding 복귀(OQ-1 A안). BAT-017 재구현·재검증 완료 → Implemented 유지.
#### Intent
- 부분 체결 후 취소에서 과매도·이중기록 없이 잔여 포지션만 재매도 가능하게(NFR-3). 전량 취소는 자동 holding 복귀.
#### Acceptance Criteria Delta
- Added:
- `_poll` 이 is_partial_cancel 분기로 부분 체결 회계 수행(원장 1회 + qty 차감 + holding 복귀). 전량 취소는 롤백.
#### Impacted Area Delta
- Modules: `trex_core/application/execution.py`(`_poll`, `_on_partial_cancel`, ExecutionResult.stale_pending)
- Tests: tests/application/test_execution_cancel.py
#### Delivery Trace Delta
- Batches: BAT-017
- Releases: none
#### Revalidation Impact
- Reverification Needed: yes (BAT-017 에서 완료)
- Existing Implementation Invalidated: no (신규 분기 추가, 기존 filled/reject 경로 불변)
- Status Recommendation: Implemented (change-req → BAT-017 재검증)
- Follow-up Action: confirm-req-implemented(BAT-017).
#### Validation Plan
- BAT-017: 전량 취소 → holding 복귀, 부분 취소 → 원장 1건 + qty 차감 + cost basis 유지 단위.
@@ -189,3 +189,42 @@
#### Validation Plan
- BAT-015: ledger skip WARN 로그 단위(caplog) + 회귀.
### CHG-20260608-02
- Date: 2026-06-08
- Author: Justin Ko
#### Change Summary
- (change-req, dcy-013/issue #9) 부분 체결 후 외부 취소 시 체결분(`ccld_qty`)을 원장에 **1회** 기록한다. `_on_partial_cancel` 이 `_record_ledger`(기존)를 재사용해 partial fill 의 execution_id/fee/qty 를 정확히 운반. BAT-017 재구현·재검증 완료 → Implemented 유지.
#### Intent
- 전량 체결만 다루던 원장 기록을 부분 체결+취소에도 확장해 체결분 누락/이중기록을 방지(정확 회계, OQ-1 A안).
#### Acceptance Criteria Delta
- Updated:
- AC-1/2 의 fill→원장 기록을 부분 체결 후 취소(체결분 1회)에도 적용.
#### Impacted Area Delta
- Modules: `trex_core/application/execution.py`(`_on_partial_cancel` → `_record_ledger` 재사용)
- Tests: tests/application/test_execution_cancel.py::test_partial_fill_then_cancel_records_and_keeps_remainder
#### Delivery Trace Delta
- Batches: BAT-017
- Releases: none
#### Revalidation Impact
- Reverification Needed: yes (BAT-017 에서 완료)
- Existing Implementation Invalidated: no (기록 경로 재사용, 호출 지점만 확장)
- Status Recommendation: Implemented (change-req → BAT-017 재검증)
- Follow-up Action: confirm-req-implemented(BAT-017).
#### Validation Plan
- BAT-017: 부분 취소 시 sell 원장 1건(qty=체결분, price=체결가) 단위.
+1 -1
View File
@@ -139,8 +139,8 @@
## Recent Change Log Summary
- 2026-06-08 :: REQ-012/013/018/031/014/015 change-req (dcy-013, BAT-017): KIS 외부 주문 취소 시 슬롯이 pending_sell 에 영구 갇히던 버그(issue #9) 정정. KIS `poll_fill` 이 `cncl_yn` 파싱해 외부 취소 감지 — 체결 0 취소→`cancelled`(롤백 자동 복구), 부분 체결 후 취소→`is_partial_cancel`(체결분 원장 1회+qty 차감+holding 복귀, OQ-1 A안)(REQ-012/013/018), 잔여 포지션 정합 연계(REQ-031), pending stale 워치독 Alert-only(`TREX_PENDING_STALE_THRESHOLD`, WARN+카운터, 상태 미변경)(REQ-014), baseline 2문서 정합(REQ-015). 전부 change-req(신규 REQ 없음, OQ-3). 단위 294 passed, 인프라 게이트 326 passed, ruff clean. (change-req/confirm-req-implemented)
- 2026-06-08 :: REQ-013/007/036/002/006/003/015 change-req (dcy-012, BAT-016): 매도 주문이 매수가(entry_price) 지정가로 나가던 버그(issue #10) 정정. 슬롯 `entry_price`→`limit_price`(side 무관 pending 지정가) rename + pending 이탈 clear(REQ-002), 컬럼 rename 마이그레이션 006(REQ-006), `_dispatch` 가 slot.limit_price 단일 필드로 가격/주문유형 결정(REQ-013), SellIntent/sell payload optional limit_price·_admit_sell 운반(REQ-007), SlotService.sell optional 가격→자율 매도 시장가(REQ-036), 컬럼 계약 가드(REQ-003), baseline 3문서 정합(REQ-015). 전부 change-req(신규 REQ 없음, OQ-3). 단위 286 passed, 인프라 게이트 318 passed, ruff clean. (change-req/confirm-req-implemented)
- 2026-06-08 :: REQ-007/018/021 change-req + REQ-055 생성·Implemented (dcy-011, BAT-015): buy intent 계약 hard cutover — portfolio_id 필수화 + symbol 서버 resolve(SnapshotStore) + unknown_portfolio/portfolio_id_required 거부(REQ-007), buy payload symbol 제거(REQ-021), ledger skip 가시화(WARN+ledger_skipped 카운터, REQ-018), closed↔outbox anti-join 운영 점검 `find_ledger_gap_slots` 신규(REQ-055). 전체 인프라 게이트 314 passed, ruff clean. (change-req/draft-req/confirm-req-implemented)
- 2026-06-08 :: REQ-052~054 Approved → Implemented (confirm-req-implemented): BAT-014(batch-lite) verify 완료(신규 8 단위, 전체 278 passed, ruff clean). SafetySellService per-slot 쿨다운(skip/만료재시도/경고/prune, market_close 제외), SafetySellConfig env 2종(min_retry_interval_sec 600/max_retry_warn_count 3), runtime-flows 정합. (confirm-req-implemented)
- 2026-06-08 :: REQ-052~054 Proposed → Approved (confirm-req): dcy-010 safety-sell 쿨다운 3개 전원 승인 게이트 통과. dcy-010(confirmed) FR/OQ 와 모순 없음, 필수 필드·구체 AC 완비. 피드백 채널·DB 영속은 Out of Scope 비핵심. (confirm-req)
- 2026-06-08 :: REQ-052~054 생성 (draft-req): dcy-010(safety-sell 영속 거부 재시도 백오프, confirmed) → 3개 REQ 초안. per-slot 쿨다운+경고(052), 쿨다운 env 2종(053), runtime-flows 정합(054). OQ-1(600s)/OQ-2(3회 경고)/OQ-3(단일 per-slot) Answered. (draft-req)