Merge pull request #31 from fourblocks2020/feat/dcy-034-core-a-reconcile-warning

feat(core-A): 차단형 reconcile — reconcile-warning durable store + 전략 차단 게이트 (BAT-050, REQ-102/103/104/107/108)
This commit is contained in:
2026-06-26 06:58:27 +09:00
committed by GitHub
28 changed files with 2434 additions and 29 deletions
+3
View File
@@ -12,3 +12,6 @@ __pycache__/
/config/*
!/config/*.example.toml
!/config/.env.example
# git-ops worktree metadata (ephemerally scoped per batch runner; never commit)
.claude/worktrees/
@@ -0,0 +1,145 @@
# BAT-050 Design
- Status: confirmed
- Batch: BAT-050
## 1. ReconcileWarningStore 포트 위치 결정
**결정: `application/portfolio.py` 내에 Protocol + InMemory 통합.** pause_store 선례와 동형으로, 포트와 인메모리 구현을 `portfolio.py`에 함께 둔다. PostgreSQL 어댑터는 `adapters/portfolio/reconcile_warning_store.py`에 별도 파일.
이유: `PauseStore Protocol`과 `InMemoryPauseStore`가 `portfolio.py`에 있는 패턴을 그대로 따른다. 파일 분산 없이 선례 일관성 유지.
## 2. ReconcileWarningStore 인터페이스 설계
```python
class ReconcileWarningStore(Protocol):
def set_warned(self, slot_id: str, *, portfolio_id: str, case_code: str,
actor: str = "reconcile", reason: str = "") -> None: ...
def clear_warned(self, slot_id: str) -> None: ...
def is_warned(self, slot_id: str) -> bool: ...
def list_warned(self) -> set[str]: ... # set of slot_id strings
```
- PK: `slot_id` (문자열 UUID)
- `case_code`: `'B'` (슬롯↔브로커 qty 불일치) 또는 `'C'` (원장↔브로커 불일치)
- `list_warned()`: set[str] 반환 — bulk 조회 후 `slot_to_dict`에서 in-operator 체크
## 3. SQL 마이그레이션 스키마
```sql
CREATE TABLE IF NOT EXISTS slot_reconcile_warning (
slot_id TEXT PRIMARY KEY,
portfolio_id TEXT NOT NULL,
case_code TEXT NOT NULL,
actor TEXT NOT NULL DEFAULT 'reconcile',
reason TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
```
ON CONFLICT DO UPDATE: 동일 slot_id의 중복 삽입 시 case_code/actor/reason/updated_at 갱신.
## 4. reconcile_positions C 케이스 slot_id 조회
**결정: reconcile_positions에 `slot_repo` Optional 파라미터 추가.**
현재 `reconcile_positions`는 portfolio_id 단위로 동작. C 케이스 차단 시 slot_id가 필요. `slot_repo.find_slot_by_portfolio(instance_key, portfolio_id)` 로 조회.
- `slot_repo=None`이면 기존 동작(in-memory warning만) 유지 — 하위 호환.
- `instance_key` 파라미터도 추가 (Optional, default="default").
## 5. 안전망 경로 분리 구조 확인
**확인: safety-sell / kill-switch / watchdog는 `_admit_*` 게이트를 거치지 않는다.**
- `SafetySellService`: `SlotService.sell()` 직접 호출 → `transit_slot(HOLDING → PENDING_SELL)` 경유. `IntentService._admit_sell` 미경유.
- `KillSwitchService.fire()`: `SlotService` 직접 → `IntentService` 미경유.
- Watchdog 만료 → `SafetySellService` 경유 → 위와 동일.
따라서 `IntentService._admit_buy`/`_admit_sell`에만 reconcile-warning 게이트를 추가하면 구조적으로 안전망 차단 예외가 보장된다. 별도 우회 플래그 불필요.
## 6. IntentService warn_store 의존성 추가
```python
class IntentService:
def __init__(
self,
...,
warn_store: Optional[ReconcileWarningStore] = None,
) -> None:
...
self._warn_store = warn_store
```
`_admit_buy`/`_admit_sell`에서:
```python
if self._warn_store is not None and self._warn_store.is_warned(str(slot.slot_id)):
return IntentDecision(intent.intent_id, "rejected", None, "reconcile_warned")
```
게이트 순서: pause 체크 → reconcile_warned 체크 → 기존 capacity/state 체크.
## 7. slot_to_dict reconcile_warned 필드
bulk 조회 패턴 채택 (N+1 방지):
```python
def slot_to_dict(
s,
*,
snapshot_store=None,
watchdog_store=None,
pause_store=None,
warn_store=None, # ReconcileWarningStore (선택)
watchdog_timeout_sec=120,
) -> dict:
...
warned_set = warn_store.list_warned() if warn_store is not None else set()
d["reconcile_warned"] = str(s.slot_id) in warned_set
```
`make_slots_rpc_handler`에서 `warn_store`를 한 번 받아 `slot_to_dict` 호출 시 전달.
## 8. IntentService pause 게이트 현황 확인
현재 `_admit_buy`/`_admit_sell`에는 pause 체크가 없다. pause 차단은 `messaging_handlers.py`의 handler 레벨에서 처리된다고 예상했으나 실제 코드 확인 결과 `IntentService` 내부에는 pause 체크가 없고, `make_intent_rpc_handler`에도 pause 체크가 없다.
**실제 pause 차단 위치 재확인 필요**: 기존 pause 게이트가 `_admit_*` 외부에 있을 수 있다. 구현 시 pause 체크와 동일 위치에 reconcile_warned 체크를 배치한다.
REQ-104 AC-1: "IntentService._admit_buy 및 _admit_sell 수행 시 ... reconcile_warned ... rejected" → IntentService 내부에 두는 것이 REQ 명세를 그대로 따르는 방향. pause 게이트도 이 기회에 IntentService 내부로 통합.
## 9. daemon.py 배선 범위
- `ReconcileWarningStore` 인스턴스 생성 (PostgreSQL 또는 InMemory — 환경)
- `SnapshotScheduler` 생성 시 `warn_store` 주입
- `IntentService` 생성 시 `warn_store` 주입
- `make_slots_rpc_handler` 호출 시 `warn_store` 주입
## 10. wire 계약 영향 (NFR-4 확인)
- `SlotState` enum: 변경 없음.
- `ALLOWED_TRANSITIONS`: 변경 없음.
- `trex.slots.req` 응답: `reconcile_warned: bool` 필드 **additive 추가**. 기존 클라이언트(orb/tsl)가 이 필드를 무시해도 JSON 파싱은 정상 동작(추가 필드는 파이썬 dict에서 무시됨). trex-orb-v1/trex-tsl-v1이 slots 응답을 `pydantic` 또는 `TypedDict`로 엄격 파싱하는지 확인 필요 — 불가피하면 팀장에게 보고. (현재 추정: dict 직접 접근 방식으로 추가 필드 무시 → 하위 호환)
- `trex.intent.req` 응답: `reason="reconcile_warned"` 신규 reason 코드 추가. 기존 클라이언트는 unknown reason에 대해 rejected로만 처리하므로 하위 호환.
## 11. 로깅 구조 (REQ-107)
차단 전이 시 (`set_warned` 호출 지점, `reconciliation.py`):
```python
_log.warning(
"reconcile_warning set: slot_id=%s portfolio_id=%s symbol=%s "
"case_code=%s broker_qty=%s slot_qty=%s actor=%s",
slot_id, portfolio_id, symbol, case_code, broker_qty, slot_qty, actor,
)
```
해제 전이 시 (`clear_warned` 호출 지점, 향후 sync/verify CLI — core-B):
```python
_log.info(
"reconcile_warning cleared: slot_id=%s portfolio_id=%s symbol=%s actor=%s",
slot_id, portfolio_id, symbol, actor,
)
```
REQ-084(구조화 로깅) 기반: `logging_setup.py`의 JSON formatter와 일관. key=value 형식으로도 필터링 가능.
@@ -0,0 +1,64 @@
# BAT-050 Implementation
- Status: done
- Batch: BAT-050
## 변경 파일 목록
### 신규 파일
- `trex_core/adapters/persistence/sql/016_create_slot_reconcile_warning.sql` — DB 마이그레이션
- `trex_core/adapters/portfolio/reconcile_warning_store.py` — PostgreSQLReconcileWarningStore
- `tests/application/test_reconcile_warning_store.py` — ReconcileWarningStore 단위 테스트
- `tests/application/test_reconcile_warning_blocking.py` — B/C 차단 + 게이트 통합 테스트
### 변경 파일
- `trex_core/application/portfolio.py` — ReconcileWarningStore Protocol + InMemoryReconcileWarningStore + slot_to_dict warn_store 파라미터 + reconcile_warned 필드
- `trex_core/application/reconciliation.py` — reconcile_core_holdings B케이스 durable 차단 + reconcile_positions C케이스 durable 차단 + 구조화 로그
- `trex_core/application/snapshot_scheduler.py` — warn_store 파라미터 추가 + reconcile 호출 시 전달
- `trex_core/application/intents.py` — warn_store 파라미터 + _admit_buy/_admit_sell reconcile-warning 게이트
- `trex_core/application/messaging_handlers.py` — make_slots_rpc_handler warn_store 파라미터 + slot_to_dict 전달
- `trex_core/adapters/portfolio/__init__.py` — PostgreSQLReconcileWarningStore export
- `trex_core/runtime/daemon.py` — warn_store 인스턴스 생성 + intent_service/snapshot_scheduler/slots_rpc_handler 배선
## 핵심 구현 요약
### 1. ReconcileWarningStore (REQ-102)
- Protocol: `set_warned(slot_id, *, portfolio_id, case_code, actor, reason)`, `clear_warned(slot_id)`, `is_warned(slot_id)`, `list_warned() -> set[str]`
- InMemoryReconcileWarningStore: 테스트용, threading.Lock 보호, dict 기반 upsert
- PostgreSQLReconcileWarningStore: `slot_reconcile_warning` 테이블, ON CONFLICT DO UPDATE, PK=slot_id
- SQL 마이그레이션 `016_create_slot_reconcile_warning.sql`
### 2. B/C 차단 전이 (REQ-103)
- `reconcile_core_holdings`: elif bq != 0 and slot.qty != bq (B case) → `warn_store.set_warned(case_code='B')`
- `reconcile_positions`: hub_total != broker_total (C case) + slot_repo 주입 시 → `warn_store.set_warned(case_code='C')`
- A case (broker flat): 기존 SlotState.ERROR 전이 유지, warn_store 미사용
- 모든 파라미터 Optional — None 시 기존 WARN 로그 동작 유지 (하위 호환)
### 3. 전략 차단 게이트 (REQ-104)
- `IntentService.__init__`: `warn_store=None` Optional 파라미터 추가
- `_admit_buy`: slot 조회 직후 `warn_store.is_warned(slot_id)` → rejected("reconcile_warned")
- `_admit_sell`: slot 조회 직후 동일 게이트
- 안전망 경로 차단 예외(OQ-B): safety_sell/kill_switch/watchdog → SlotService.transit_slot() 직접 호출 → IntentService._admit_* 미경유 → 구조적 우회 보장
- `slot_to_dict`: `warn_store.list_warned()` 벌크 조회, `reconcile_warned: bool` 필드 추가 (additive, NFR-4)
- `make_slots_rpc_handler`: `warn_store: Optional[ReconcileWarningStore]` 파라미터 추가
### 4. 구조화 로그 (REQ-107)
- B 케이스: `WARNING reconcile_warning set: slot_id=... portfolio_id=... symbol=... case_code=B broker_qty=... slot_qty=... actor=reconcile`
- C 케이스: `WARNING reconcile_warning set: slot_id=... portfolio_id=... symbol=... case_code=C hub_qty=... broker_qty=... actor=reconcile`
- A 케이스 알람: 기존 REQ-100 경로 그대로 (확인: 기존 alarm_emitter.publish_alarm("core_holding_broker_flat", ...) 유지)
### 5. daemon.py 배선 순서 조정
- warn_store 생성을 pause_store 다음으로 배치
- intent_service 생성을 warn_store 생성 이후로 이동 (warn_store 주입 가능하게)
- snapshot_scheduler, slots_rpc_handler에 warn_store 전달
## wire 계약 영향 (NFR-4 확인)
- `SlotState` enum: 변경 없음 (INACTIVE/PENDING_BUY/HOLDING/PENDING_SELL/ERROR 5개 유지)
- `ALLOWED_TRANSITIONS`: 변경 없음 (13개 전이 유지)
- `trex.slots.req` 응답: `reconcile_warned: bool` additive 추가. 기존 클라이언트가 무시해도 JSON dict 파싱 정상 동작
- `trex.intent.req` 응답: `reason="reconcile_warned"` 신규 코드 — rejected 케이스이므로 기존 클라이언트는 rejected 처리만 하면 됨
## 범위 밖 (core-B)
- REQ-105 sync CLI: 미구현
- REQ-106 verify CLI: 미구현
- SlotState 추가, INACTIVE→HOLDING 전이 추가: 미구현 (범위 밖)
@@ -0,0 +1,26 @@
# BAT-050: reconcile-warning 차단형 게이트 (core-A)
- Status: in-delivery
- Profile: standard
- Discovery: dcy-034
- Created: 2026-06-26
## Included REQ
- REQ-102: reconcile-warning durable store — slot_id/pid 키 별도 테이블
- REQ-103: 차단형 reconcile — B/C 불일치 슬롯 reconcile-warning 전이
- REQ-104: 전략 차단 게이트 — pause ∨ reconcile-warning 중 하나라도 걸리면 차단
- REQ-107: 차단/해제 전이 식별 로깅 + 고영향 불일치 알람
- REQ-108: 차단형 reconcile 비기능 요건 — 내구성·회귀 방지·자동 정정 금지·wire 계약 최소 침습
## Excluded REQ (core-B)
- REQ-105: sync CLI 명령 — core-B 별도 batch
- REQ-106: verify CLI 명령 — core-B 별도 batch
## Documents
- [planning.md](./planning.md)
- [design.md](./design.md)
- [implementation.md](./implementation.md)
- [verification.md](./verification.md)
@@ -0,0 +1,65 @@
# BAT-050 Planning
- Status: confirmed
- Batch: BAT-050
- Profile: standard
## Included REQ
- REQ-102: reconcile-warning durable store — slot_id/pid 키 별도 테이블
- REQ-103: 차단형 reconcile — B/C 불일치 슬롯 reconcile-warning 전이
- REQ-104: 전략 차단 게이트 — pause ∨ reconcile-warning 중 하나라도 걸리면 차단
- REQ-107: 차단/해제 전이 식별 로깅 + 고영향 불일치 알람
- REQ-108: 차단형 reconcile 비기능 요건 — 내구성·회귀 방지·자동 정정 금지·wire 계약 최소 침습
## Delivery Plan
REQ-102 → REQ-103 → REQ-104 → REQ-107 → REQ-108 인과 사슬:
1. **REQ-102 먼저**: `ReconcileWarningStore` 포트(Protocol) + `InMemoryReconcileWarningStore` (테스트용) + `PostgreSQLReconcileWarningStore` (어댑터) + SQL 마이그레이션. pause_store 동형 설계.
2. **REQ-103**: `reconcile_core_holdings`와 `reconcile_positions`에 `warn_store: Optional[ReconcileWarningStore]` 파라미터 추가. B 케이스(qty mismatch) → `set_warned`, C 케이스(원장↔브로커) → `set_warned`. `SnapshotScheduler.run_once()`에 warn_store 주입.
3. **REQ-104**: `IntentService._admit_buy`/`_admit_sell`에 reconcile-warning 게이트 추가. `slot_to_dict`에 `reconcile_warned: bool` 필드. `make_slots_rpc_handler`에 `warn_store` 파라미터 추가. 안전망 경로(safety-sell/kill-switch/watchdog)는 `_admit_*` 게이트를 우회하므로 구조적으로 차단 예외.
4. **REQ-107**: 차단/해제 전이 시 구조화 로그(`WARNING`/`INFO`) 추가. A 케이스 알람은 기존 구현 확인.
5. **REQ-108**: 불변 확인 테스트 + 회귀 방지 테스트. `SlotState`·`ALLOWED_TRANSITIONS` 불변 검증.
구현 순서:
1. SQL 마이그레이션 (`016_create_slot_reconcile_warning.sql`)
2. `adapters/portfolio/reconcile_warning_store.py` (포트 + InMemory + PostgreSQL)
3. `application/portfolio.py` (`ReconcileWarningStore` Protocol + InMemory 통합)
4. `application/reconciliation.py` (B/C 차단 전이 + 로그)
5. `application/snapshot_scheduler.py` (warn_store 주입)
6. `application/intents.py` (게이트 추가 + `ReconcileWarningStore` 의존)
7. `application/portfolio.py` (`slot_to_dict` reconcile_warned 필드)
8. `application/messaging_handlers.py` (`make_slots_rpc_handler` warn_store 파라미터)
9. `runtime/daemon.py` (warn_store 배선)
10. 테스트 작성
## Dependencies
- BAT-049 (alarm-system-dcy-033): 완료(release-candidate) — `AlarmEmitter.publish_alarm` 경로가 REQ-100으로 구현됨. A 케이스 알람은 기존 경로 재사용.
- `pause_store` (BAT-008/020): 동형 설계의 선례.
- `reconcile_core_holdings`, `reconcile_positions` (BAT-029): 차단 전이 추가 대상.
## Design Gate
**Design 필요: yes (standard — 포트/어댑터 신설, 게이트 확장, 안전망 경로 분리 구조 확인)**
- ReconcileWarningStore 포트 위치 결정: `application/portfolio.py` 내 통합 vs 별도 파일.
- `reconcile_positions`에서 slot_id를 얻기 위한 slot_repo 주입 필요 여부 설계.
- `IntentService` 생성자에 warn_store 의존성 추가 방식 설계.
- 안전망 경로가 `_admit_*` 게이트를 구조적으로 우회하는지 명시 확인.
- slots RPC `reconcile_warned` 필드: bulk 조회 vs N+1 trade-off.
## Milestones
1. SQL 마이그레이션 + ReconcileWarningStore 포트/어댑터
2. reconcile_core_holdings/reconcile_positions B/C 차단 전이
3. IntentService 게이트 + slot_to_dict reconcile_warned 필드
4. make_slots_rpc_handler warn_store 주입 + daemon.py 배선
5. 전체 테스트 통과 (신규 + 회귀)
## Risks
- R-1(Medium): reconcile_positions에서 C 케이스 slot_id 조회 — portfolio_id로 slot을 찾아야 함. slot_repo 주입이 필요할 수 있음. 완화: design에서 조회 방식 확정.
- R-2(Low): warn_store Optional 처리 누락 시 기존 테스트 더블 깨짐. 완화: 모든 파라미터 Optional로 추가, None 시 기존 동작 유지.
- R-3(Low): slots RPC reconcile_warned 필드가 기존 클라이언트(orb/tsl)에서 unknown 필드로 수신될 때 파싱 오류 발생 가능성. 완화: additive only, 클라이언트가 unknown 필드를 무시하는지 design에서 확인.
@@ -0,0 +1,104 @@
# BAT-050 Verification
- Status: done
- Batch: BAT-050
## pytest 실행 결과
실행 명령: `pytest tests/ -q`
```
642 passed, 47 skipped in 1.45s
```
- 기존 608개 테스트 전부 통과 (회귀 0)
- 신규 34개 테스트 전부 통과
- 47개 스킵 (DB 연결 필요한 통합 테스트 — 기존과 동일, 변화 없음)
- 실패 0
## 신규 테스트 파일
### tests/application/test_reconcile_warning_store.py (7개)
- `test_set_warned_is_warned_true` — AC-1 (REQ-102): set/is_warned 기본 동작
- `test_clear_warned_returns_false` — AC-4: clear 후 False
- `test_set_warned_upsert_same_slot` — AC-3: 동일 slot_id 재삽입 시 1행 유지
- `test_list_warned_returns_set` — AC-5: 복수 slot_id 조회
- `test_is_warned_unknown_slot_false` — 미등록 slot → False
- `test_clear_warned_unknown_slot_noop` — 미등록 slot clear → no-op
- `test_list_warned_empty` — 빈 상태 → empty set
### tests/application/test_reconcile_warning_blocking.py (27개)
- B 케이스 차단 (REQ-103 AC-1): `test_reconcile_core_holdings_b_case_sets_warned`, `..._b_case_code`
- 정상 케이스 오발동 없음 (REQ-103 AC-3, S-4): `test_reconcile_core_holdings_matching_qty_no_warn`
- A 케이스 기존 동작 유지 (REQ-103 AC-4): `test_reconcile_core_holdings_a_case_error_not_warned`
- 하위 호환 (REQ-103 AC-5): `test_reconcile_core_holdings_no_warn_store_backward_compat`
- C 케이스 차단 (REQ-103 AC-2): `test_reconcile_positions_c_case_sets_warned`, `..._c_case_matching_no_warn`, `..._no_warn_store_backward_compat`
- buy intent 차단 (REQ-104 AC-1): `test_intent_service_buy_rejected_when_reconcile_warned`
- sell intent 차단 (REQ-104 AC-2, 외부): `test_intent_service_sell_rejected_when_reconcile_warned`
- 정상 intent 오발동 없음 (REQ-104 AC-3): `test_intent_service_no_warn_admitted_normally`
- 하위 호환 (REQ-104): `test_intent_service_no_warn_store_backward_compat`
- 안전망 우회 확인 (REQ-104 OQ-B): `test_safety_sell_bypasses_reconcile_warning_gate` — SlotService.transit_slot 직접 호출 시 warned 슬롯도 정상 전이
- slots RPC reconcile_warned 필드 (REQ-104 AC-4~8): 5개 테스트
- 구조화 로그 (REQ-107): B케이스/C케이스 WARNING 로그 필드 검증
- SlotState 불변 (REQ-108 NFR-4): `test_slot_state_enum_unchanged`, `test_allowed_transitions_unchanged`
- 단기 인스턴스 오발동 없음 (REQ-108 NFR-2, S-4): `test_short_term_instance_normal_no_warn`
- 자동 정정 금지 (REQ-108 NFR-3): `test_reconcile_no_auto_fix_slot_qty`
- slot_to_dict 필드 (REQ-104): 3개 테스트
## AC 검증 매핑
| AC | 테스트 | 결과 |
| --- | --- | --- |
| REQ-102 AC-1 (마이그레이션 테이블 생성) | SQL 파일 존재 확인 (DB 스킵) | SQL 파일 생성됨 |
| REQ-102 AC-2 (durable — set 후 재시작 후 True) | InMemory 동치 테스트 / PG는 DB 스킵 | PASS |
| REQ-102 AC-3 (ON CONFLICT DO UPDATE) | `test_set_warned_upsert_same_slot` | PASS |
| REQ-102 AC-4 (clear_warned → False) | `test_clear_warned_returns_false` | PASS |
| REQ-102 AC-5 (list_warned) | `test_list_warned_returns_set` | PASS |
| REQ-102 AC-6 (SlotState 불변) | `test_slot_state_enum_unchanged` | PASS |
| REQ-103 AC-1 (B case → set_warned case_code=B) | `test_reconcile_core_holdings_b_case_sets_warned` | PASS |
| REQ-103 AC-2 (C case → set_warned case_code=C) | `test_reconcile_positions_c_case_sets_warned` | PASS |
| REQ-103 AC-3 (정상 케이스 오발동 없음) | `test_reconcile_core_holdings_matching_qty_no_warn`, `test_reconcile_positions_c_case_matching_no_warn` | PASS |
| REQ-103 AC-4 (A case → ERROR, warn_store 미사용) | `test_reconcile_core_holdings_a_case_error_not_warned` | PASS |
| REQ-103 AC-5 (warn_store=None 하위 호환) | 양 함수 backward_compat 테스트 | PASS |
| REQ-104 AC-1 (buy intent → reconcile_warned 차단) | `test_intent_service_buy_rejected_when_reconcile_warned` | PASS |
| REQ-104 AC-2 (sell intent → reconcile_warned 차단 + 안전망 예외) | `test_intent_service_sell_rejected_when_reconcile_warned`, `test_safety_sell_bypasses_reconcile_warning_gate` | PASS |
| REQ-104 AC-3 (정상 → 오발동 없음) | `test_intent_service_no_warn_admitted_normally` | PASS |
| REQ-104 AC-4 (pause only: paused=T, reconcile_warned=F) | `test_slots_rpc_paused_only` | PASS |
| REQ-104 AC-5 (warn only: reconcile_warned=T) | `test_slots_rpc_reconcile_warned_true` | PASS |
| REQ-104 AC-6 (both: paused=T, reconcile_warned=T) | `test_slots_rpc_both_pause_and_reconcile_warned` | PASS |
| REQ-104 AC-7 (warn_store=None → reconcile_warned=F) | `test_slots_rpc_no_warn_store_reconcile_warned_false` | PASS |
| REQ-104 AC-8 (기존 warned 필드 불변) | `test_slots_rpc_existing_warned_field_unchanged` | PASS |
| REQ-107 AC-1 (B case WARNING 로그 필드) | `test_reconcile_core_holdings_b_case_logging` | PASS |
| REQ-107 AC-2 (C case WARNING 로그 필드) | `test_reconcile_positions_c_case_logging` | PASS |
| REQ-107 AC-3 (sync 해제 INFO 로그) | core-B 범위 — 미검증 (REQ-105/106 미구현) | 해당 없음 |
| REQ-107 AC-4 (verify 해제 INFO 로그) | core-B 범위 | 해당 없음 |
| REQ-107 AC-5 (A case CRITICAL 알람 기존 동작) | 기존 test_alarm_emitter.py 회귀 확인 | PASS (608 기존 통과) |
| REQ-108 AC-1 (durable) | InMemory 동치 + PG 스킵 | PASS |
| REQ-108 AC-2 (정상 단기 오발동 없음, NFR-2, S-4) | `test_short_term_instance_normal_no_warn` | PASS |
| REQ-108 AC-3 (자동 정정 없음, NFR-3) | `test_reconcile_no_auto_fix_slot_qty` | PASS |
| REQ-108 AC-4 (additive 하위 호환, NFR-4) | `test_slots_rpc_no_warn_store_reconcile_warned_false` | PASS |
| REQ-108 AC-5 (SlotState enum 불변, NFR-4) | `test_slot_state_enum_unchanged` | PASS |
| REQ-108 AC-6 (ALLOWED_TRANSITIONS 불변, NFR-4) | `test_allowed_transitions_unchanged` | PASS |
## wire 계약 무회귀 근거
- `SlotState` 5개 값 불변 확인: `test_slot_state_enum_unchanged` PASS
- `ALLOWED_TRANSITIONS` 13개 불변 확인: `test_allowed_transitions_unchanged` PASS
- `trex.slots.req` 기존 필드: 기존 test_slots_handler.py 전부 통과 (회귀 0)
- `reconcile_warned` additive 필드: 기존 클라이언트가 무시 가능 (JSON dict extra key)
## 미검증 항목 (핸들링)
- PostgreSQLReconcileWarningStore durable 검증: DB 연결 필요 — InMemory 동치 테스트로 계약 검증, PG 어댑터는 pause_store 동형 패턴으로 구현됨.
- sync/verify CLI clear_warned 해제 로그 (REQ-107 AC-3/4): core-B 범위 (REQ-105/106 미구현).
## 롤백
```bash
git revert <commit-sha> # 단일 커밋 롤백
```
또는 마이그레이션 롤백:
```sql
DROP TABLE IF EXISTS slot_reconcile_warning;
```
+1
View File
@@ -57,3 +57,4 @@
| BAT-047 | standard | release-candidate | REQ-091, REQ-092, REQ-093, REQ-094 | dcy-031 | [bat-047](./bat-047_20260619_event-publisher-connection-reliability/) |
| BAT-048 | standard | in-delivery | REQ-095, REQ-096, REQ-097 | dcy-032 | [bat-048](./bat-048_20260621_fill-price-backfill-guard-logging-alert-spike/) |
| BAT-049 | standard | release-candidate | REQ-098, REQ-099, REQ-100, REQ-101 | dcy-033 | [bat-049](./bat-049_20260621_alarm-system-dcy-033/) |
| BAT-050 | standard | in-delivery | REQ-102, REQ-103, REQ-104, REQ-107, REQ-108 | dcy-034 (core-A) | [bat-050](./bat-050_20260626_reconcile-warning-blocking-gate-core-a/) |
@@ -0,0 +1,228 @@
# 0. 문서 상태
이 문서의 현재 상태와 식별 정보를 기록한다. 문서 추적과 승인 흐름에 필요한 최소 메타데이터를 적는다.
- 상태: confirmed
- 문서 ID: dcy-034_20260625_slot-account-blocking-reconcile-sync-coldstart
- 이슈명: 슬롯↔실계좌 차단형 reconcile + sync/verify 명령 — 중장기 cold-start (기존 보유 포지션 onboarding)
- 작성 시각(KST): 2026-06-25 (KST)
- 마지막 갱신 시각(KST): 2026-06-25 (KST, confirm-discovery — OQ-1~5 전부 Answered)
- 대체됨: 없음
- 후속 Discovery 참조: 없음
- 생성된 REQ 참조: REQ-102 ~ REQ-108 (draft-req 2026-06-25, Proposed — confirm-req 대기)
# 1. 계획 상태 요약
현재 Discovery가 어떤 배경에서 작성되고 있는지, 연계 문서가 있는지, 지금 시점의 해석이 무엇인지 짧게 요약한다.
- 연계 문서 현황:
- 관련 점수 파일: 미생성
- 관련 TODO/메모: GitHub 보드 `fourblocks2020/trex` #7 항목 "trex-core: 슬롯↔실계좌 차단형 reconcile + sync/verify 명령 — 중장기 cold-start (M3)" (M3/P1, 설계방향 본문 보유). 워크스페이스 메모리 `m3-goal-midlong-core-instance`.
- 선행 Discovery: dcy-020(자산중심 슬롯), dcy-027(중장기 슬롯 운영·운영 프로파일), dcy-028(slot strategy-state store), dcy-029(슬롯/PnL 뷰). 본 건은 이들 위에 cold-start 동기화 갭을 정의한다.
- 해석:
- M3 메인 목표는 "중/장기 전략용 별도 trex-core 인스턴스 추가"(사장님 2026-06-25). 그 인스턴스는 **이미 실계좌에 보유 중인 중장기 종목 위에서 cold-start** 한다 — portfolio-hub에 종목·ledger(잔고)가 있고 브로커 계좌에 실보유가 있는데 **slot DB는 비어 있는 상태**에서 데몬이 처음 뜨는 상황이 정상 시나리오다.
- 현행 reconcile는 이 cold-start 갭에서 **탐지(WARN/error)만 하고 차단도 해소 경로도 없다.** 슬롯↔브로커·원장↔슬롯 불일치가 있어도 전략이 그대로 돌 수 있고(데이터 오염 위 매매 위험), 운영자가 불일치를 안전하게 정합화해 전략을 재개할 표준 명령이 없다.
- 본 Discovery는 이 갭을 "차단형 reconcile(A→B→C) + 운영자 sync/verify 명령 + 차단형 warning 상태"라는 trex-core 변경 단위로 정식화한다. (중장기 **전략 모듈 자체**·멀티데이 PnL·인스턴스 프로파일 신설은 별개 단위 — 범위 경계 참조.)
# 2. 요구사항 판정 결과
이번 요청이 기존 요구사항과 비교해 신규인지, 유사한지, 중복인지 판단하고 그 근거를 남긴다.
- 판정: 신규
- 근거
- 기존 reconcile 자산은 **탐지 전용**이다. `reconcile_core_holdings`(REQ-062)는 A(슬롯 보유·브로커 0)만 ERROR 전이하고 B(브로커 보유·슬롯 없음)·C(수량 불일치)는 **WARN 로그만** 남긴다(`application/reconciliation.py:48-83`). `reconcile_positions`(REQ-031)는 portfolio-hub↔브로커 불일치 시 asset overlay `set_warning(pid)`를 켜지만 **in-memory·비차단**이며 docstring이 명시하듯 *"pause is the durable channel for manual holds"*(`reconciliation.py:1-8,118`).
- 즉 "불일치 시 전략을 **차단**하고, 운영자가 **명령으로 정합화해 차단을 해제**한다"는 행위는 어디에도 없다. dcy-027(중장기 슬롯 운영)은 운영 프로파일·멀티데이 리스크까지 다뤘으나 cold-start 시 기존 보유 onboarding·동기화 차단은 Out-of-Scope로 두었다.
- 신규 운영자 CLI 명령(sync/verify)과 차단형 슬롯 상태 도입은 dcy-016(운영자 CLI) 이후의 독립 능력 추가라 별도 주기로 추적하는 편이 명확하다.
# 3. 문제점의 요약
문제의 현재 상태, 기대 상태, 관련 이해관계자, 제약사항을 정리한다. Discovery의 핵심 맥락을 가장 먼저 이해할 수 있어야 한다.
- 현재 상태
- **cold-start 갭**: 중장기 인스턴스가 처음 뜰 때 slot DB는 비어 있다. boot시 `snapshot_scheduler.run_once()`가 ① whoami → ② get_portfolios → ③ `store.swap` → ④ `reconcile_positions`(portfolio-hub↔브로커) → ⑤ `_reconcile_slots`(`reconcile_universe`로 INACTIVE 슬롯 생성) → ⑥ `reconcile_core_holdings`(슬롯↔브로커) 순으로 돈다(`snapshot_scheduler.py:85-146`). 그 결과 portfolio-hub 자산은 **INACTIVE 슬롯으로 생성**되지만, 실계좌에 이미 보유 중인 수량은 슬롯에 **HOLDING으로 반영되지 않는다**(슬롯 생성 기준은 자산 리스트지 브로커 잔고가 아님). 브로커가 보유한 종목은 `reconcile_core_holdings`의 케이스 B("unmanaged position")로 **WARN 로그만** 남고 슬롯은 INACTIVE에 머문다.
- **차단 부재**: 위 불일치(B 미반영, C 수량 차이, asset warning)는 전략 수행을 막지 않는다. SlotState는 5상태(inactive/pending_buy/holding/pending_sell/error)뿐이고 "warning"은 슬롯 필드가 아니다(`domain/slot/state.py:30-37`). asset warning은 in-memory overlay라 재시작 시 사라지고 전략 read/intent 경로를 차단하지 않는다. 유일한 durable 차단 채널은 **pause**(portfolio_id 단위, `snapshot_pause` 테이블/pause_store)뿐인데, 이는 reconcile가 자동으로 걸지 않는 **수동 채널**이다.
- **해소 명령 부재**: 운영자가 "슬롯을 실계좌에 맞춰라"라고 지시할 표준 CLI가 없다. 현 `trex-core` CLI는 pause/resume/paused/universe/slots/enter/exit/cancel/report뿐이다(`runtime/cli.py`). 불일치를 손으로 정합화하려면 원장 수정(pfhub) 또는 슬롯 직접 손질에 의존해야 하고, 정합 후 "warning 해제·전략 재개"를 안전하게 확인하는 경로가 없다.
- **결과 위험**: 평단 0/수량 불일치 슬롯 위에서 중장기 전략이 매도·증액 결정을 내리면(예: tsl 류 평단 기반 tier, 사이징) 잘못된 cost basis로 실거래가 나간다. dcy-032에서 평단 0 오염의 하류 피해(tier 무시 폴백 매도, 실현손익 과대)를 이미 확인했다 — cold-start 미정합은 그 위험을 인스턴스 기동 시점에 구조적으로 만든다.
- 기대 상태
- 중장기 인스턴스 cold-start 시, portfolio-hub 자산은 슬롯 유니버스로 정합되고(A), 실계좌 보유는 **불일치로 탐지되면 해당 슬롯이 차단(전략 미수행) 상태**가 되어, 정합 전 잘못된 매매가 절대 나가지 않는다.
- 운영자는 표준 CLI로 (B) 슬롯을 브로커 잔고에 맞춰 동기화(`sync`)하고, (C) 원장↔슬롯 불일치는 portfolio-hub CLI로 원장을 고친 뒤 trex-core `verify`로 재확인해 차단을 해제한다. 강제 해제(force-clear) 없이 **재대조가 일치할 때만** 차단이 풀린다.
- 차단 채널이 pause(수동 hold)와 별개로 **reconcile 기반 자동 차단(warning)** 으로 durable하게 존재하고, 두 채널 중 하나라도 걸리면 전략이 차단된다.
- 이해관계자
- 사장님 — M3 범위·차단/해제 정책·비가역 운영(실계좌 동기화) 승인자
- 팀장(Claude) — Discovery/게이트 관리, cold-start 갭 추적자
- trex-core-dev — delivery 담당
- 운영자 — cold-start 시 sync/verify 수행 주체, 차단/해제의 최종 소비자
- 제약사항
- 브로커(KIS) 잔고가 reconcile의 ground truth다(invariant B, 단일 계좌). 슬롯/원장은 미러이며 권위는 브로커에 있다.
- **자동 무음 정정·자동 청산 금지**(issue #15 기조 유지). reconcile는 탐지+차단까지만 자동이고, 실제 정합(슬롯=브로커 반영, 원장 수정)은 **운영자 명령**으로만 일어난다.
- trex-core wire 계약(slots RPC 필드 등) 변경은 blast radius가 커 가급적 피한다. 차단 상태가 슬롯 read 표면에 노출돼야 한다면 그 스키마 영향은 design에서 최소화·명시한다.
- 단기 인스턴스(M1/M2 라이브: orb+tsl)에 회귀를 주지 않아야 한다 — 차단형 reconcile는 모든 인스턴스에 공통 적용되므로, 단기 인스턴스의 정상 운영(당일 슬롯·평소 일치 상태)에서 신규 차단이 오발동하지 않아야 한다.
## 주요 사용자 시나리오
사용자 또는 운영자가 실제로 어떤 상황에서 이 변경을 필요로 하는지 대표 시나리오를 적는다.
- 운영자(cold-start onboarding): 중장기 인스턴스를 처음 띄운다. portfolio-hub에 A·B·C 3종목이 있고 실계좌에 이미 보유 중이다. 데몬 기동 → 슬롯 유니버스 생성 + 보유 불일치 탐지로 해당 슬롯 차단(전략 정지). 운영자가 `trex-core sync`로 슬롯을 실계좌 잔고에 맞추고, 일치 확인 후 차단이 풀려 전략이 비로소 돈다.
- 운영자(원장↔슬롯 불일치, C): reconcile가 원장(portfolio-hub 스냅샷)과 슬롯/브로커 간 수량 불일치를 차단으로 표면화. 운영자가 `pfhub portfolio buy/sell/invest`로 원장을 정정 → `trex-core verify <pid>`로 재대조 → 일치 시 차단 해제, 여전히 불일치면 해제 거부(사유 출력).
- 운영자(직접 매매 phantom, B 주의): 운영자가 KIS HTS로 직접 사고판 종목이 슬롯 없이 브로커에만 있다. `sync`가 이를 슬롯에 반영할 때 방향(매니지 대상으로 편입할지/무시할지)을 잘못 잡으면 중장기 전략이 의도치 않은 포지션을 떠안는다 — 방향 정책 확인이 필요하다.
# 4. 이번에 정의할 변경
이번 Discovery에서 다루는 핵심 변경 항목을 목록으로 적는다. 기능, 구조, 규칙 변경을 함께 포함해도 된다.
- 변경 1 — 차단형 reconcile(A→B→C): boot/일일 reconcile에서 불일치를 탐지하면 **해당 슬롯을 차단 상태로 전이**한다. A=portfolio-hub 자산→슬롯 유니버스 정합(기존 유지), B=슬롯↔브로커 수량 불일치→슬롯 차단, C=원장(portfolio-hub 스냅샷)↔슬롯 수량 불일치→슬롯 차단. 차단된 슬롯은 전략 수행(매수/매도/사이징 intent) 대상에서 제외된다.
- 변경 2 — 차단형 warning 상태 도입: pause(수동·durable)와 **별개의 reconcile 기반 차단 상태(warning)** 를 durable하게 도입하고, pause OR warning 중 하나라도 걸리면 전략을 차단하도록 차단 게이트를 확장한다. (저장 위치·표현 방식은 OQ.)
- 변경 3 — 운영자 sync 명령: `trex-core sync`(신규) — 슬롯 수량을 브로커 잔고(ground truth)에 맞춰 반영하고, 일치하면 해당 슬롯의 reconcile-warning을 해제한다. cold-start 시 기존 보유의 슬롯 onboarding 경로이기도 하다.
- 변경 4 — 운영자 verify 명령: `trex-core verify`(신규) — C(원장↔슬롯) 불일치로 차단된 슬롯에 대해, 운영자가 portfolio-hub CLI로 원장을 정정한 뒤 **재대조**해 일치 시 warning을 해제, 불일치면 사유와 함께 해제를 거부한다(force-clear 없음).
## 영향 범위
변경이 미칠 코드/문서/운영 범위를 명시해 REQ 정제와 batch planning에서 추정 누락을 줄인다.
- 코드 영향:
- `trex_core/application/reconciliation.py` — `reconcile_core_holdings`(B/C를 WARN→슬롯 차단으로 승격), `reconcile_positions`(asset warning을 durable 차단으로 연계할지 결정).
- `trex_core/application/snapshot_scheduler.py` — reconcile 순서/차단 적용 지점(`run_once`).
- 슬롯 도메인/저장소 — 차단형 warning 상태의 저장(슬롯 필드 신설 vs pause류 별도 store vs 신규 SlotState). `domain/slot/state.py`, slot repo.
- 전략 차단 게이트 — slots RPC read 표면/ intent 수용 경로(`application/messaging_handlers.py`)에서 pause에 더해 warning도 차단으로 반영.
- `trex_core/runtime/cli.py` — `sync`/`verify` 서브커맨드(데몬 RPC) 추가.
- 문서 영향:
- `docs/discovery/index.md` 신규 행 추가.
- `docs/runtime-flows.md`(reconcile/차단/해제 흐름), `docs/operations.md`(cold-start onboarding 런북) 갱신.
- 운영 영향:
- 중장기 인스턴스 cold-start 표준 절차 신설(기동→차단 확인→sync/verify→재개).
- 차단/해제가 운영자 명령 의존이므로 런북·교육 필요. pfhub 원장 정정과 trex-core verify의 2-서비스 협응 절차 명시.
# 5. 요구사항 목록
실제로 구현과 검증으로 이어질 요구사항을 기능/비기능으로 나누어 정리하고, 범위 경계를 명확히 적는다.
## 기능 요구사항
- FR-1: boot/일일 reconcile에서 슬롯↔브로커(B) 또는 원장↔슬롯(C) 불일치가 탐지되면 해당 슬롯을 **차단 상태(reconcile-warning)** 로 전이하고, 차단된 슬롯은 전략 read 표면/intent 수용에서 제외된다.
- FR-2: 전략 차단 게이트는 pause(수동) **또는** reconcile-warning 중 하나라도 걸리면 해당 슬롯/포트폴리오의 전략 수행을 차단한다.
- FR-3: `trex-core sync` 명령(별도 명령, OQ-2)은 **브로커 잔고(정본)를 유지한 채 대상 슬롯의 보유 수량을 브로커에 맞춰 갱신**하고(슬롯 미러를 브로커로 수렴, INACTIVE→HOLDING 전이 포함), 정합 후 일치하면 그 슬롯의 reconcile-warning을 해제한다. cold-start 시 portfolio-hub 유니버스에 있어 슬롯이 생성된 보유 종목(B)이 그 대상이다. **브로커에만 있고 portfolio-hub에 없는 종목(슬롯 부재)은 sync 대상이 아니다** — unmanaged 경고로 유지하며 자동 슬롯 생성하지 않는다(슬롯 생성 기준=portfolio-hub 유니버스, OQ-3).
- FR-4: `trex-core verify` 명령(별도 명령, read-중심, OQ-2)은 C로 차단된 슬롯을 재대조해, 일치하면 warning을 해제하고 불일치면 사유와 함께 해제를 거부한다(강제 해제 없음). 슬롯 수량을 변경하지 않는다(운영자가 portfolio-hub CLI로 원장을 이미 정정).
- FR-5: reconcile-warning 차단 상태는 **pause_store와 동형의 별도 durable store**(slot_id/pid 키)에 저장한다 — SlotState enum·전이표·slots RPC wire 계약을 변경하지 않는다(OQ-1).
- FR-6: 차단/해제 전이는 식별 가능한 로그(슬롯·심볼·원인 케이스·수량 before/after·actor)를 남기고, 고영향 불일치(예: A phantom)는 기존 알람 채널(dcy-033/trex.alerts)로 통지한다.
- FR-7(교차 서비스 의존): cold-start cost basis seed를 위해 **portfolio-hub에 "현재 보유 평단(WAC) read" 엔드포인트를 신규 추가**하고(→ **portfolio-hub `dcy-008` / `REQ-043` GET /v1/portfolios/{id}/holdings/cost-basis**, 2026-06-25 confirm), trex-core sync/onboarding가 이를 읽어 슬롯 평단을 seed한다(OQ-4). 현행 portfolio-hub는 미매도 보유분 평단 read가 없음(`pnl/realized` 매도행 `cost_basis_per_unit`만 노출). REQ-105(sync)는 이 read 가용 시 평단 seed, 미가용 시 수량만 갱신+WARN으로 graceful degrade.
## 비기능 요구사항
성능, 운영성, 일관성, 자동화 안정성 등 기능 외 요구사항을 적는다.
- NFR-1: 차단형 warning 상태는 **durable**(재시작 후에도 유지)해야 한다 — in-memory overlay로 두지 않는다.
- NFR-2: 단기 인스턴스(M1/M2 라이브)의 정상(일치) 운영에서 신규 차단이 오발동하지 않아야 한다(회귀 0). 차단은 실제 불일치에서만 발생한다.
- NFR-3: reconcile/차단은 무음 자동 정정·자동 청산을 하지 않는다(issue #15 기조). 정합 행위는 운영자 명령으로만 일어난다.
- NFR-4: 가능하면 wire 계약(slots RPC 스키마) 변경을 피하거나 최소화한다. 차단 상태 노출이 필요하면 영향 범위를 design에서 명시한다.
## 범위 경계
이번 반복에서 반드시 포함할 범위와 명시적으로 제외할 범위를 구분한다.
- In Scope
- 차단형 reconcile(B/C → 슬롯 차단), 차단형 warning durable 상태(별도 store, OQ-1), pause∨warning 차단 게이트.
- `trex-core sync` / `trex-core verify` 운영자 명령(별도 2명령, OQ-2) + cold-start onboarding 경로.
- 차단/해제 로깅 + 고영향 알람 연계, cold-start 운영 런북.
- (교차 서비스 의존, FR-7) portfolio-hub "현재 보유 평단(WAC) read" 엔드포인트 신규 추가 — cold-start cost basis seed용. portfolio-hub-dev 별도 REQ로 발주(trex-core REQ의 선행 의존).
- Out of Scope
- 중장기 **전략 모듈 자체**(매매 로직)와 중장기 인스턴스 TOML 프로파일 신설 — 별개 단위(dcy-027 기반 후속).
- 멀티데이 PnL 리포트 — portfolio-hub 실현 PnL API(REQ-040/041)로 별도 처리(보드 M3 항목).
- 과거 0/불일치로 기록된 원장·슬롯의 소급 일괄 정정.
- 실시간(틱 단위) 슬롯↔계좌 동기화 — 본 건은 boot/일일 reconcile + 운영자 명령 시점 동기화에 한정.
# 6. 리스크/가정 목록
불확실성과 전제 조건을 분리해서 적는다. 리스크는 영향과 완화 방안을, 가정은 현재 판단의 전제를 기록한다.
## 리스크
- R-1 (Medium, OQ-3로 완화됨): B 동기화 방향 오판 — 운영자 직접 매매로 생긴 phantom 포지션을 `sync`가 무분별하게 슬롯에 편입하면 중장기 전략이 의도치 않은 포지션을 관리·매도하게 된다.
- 완화 방안(확정): `sync`는 **portfolio-hub 유니버스에 있어 슬롯이 생성된 종목만** 대상으로 하고 슬롯 qty를 브로커로 수렴한다. 브로커-only(portfolio-hub 부재, 슬롯 없음) 포지션은 sync가 건드리지 않고 unmanaged 경고로 유지 → phantom 자동 편입 경로가 구조적으로 차단된다(OQ-3). 추가로 sync는 종목/슬롯 명시 대상으로 한정(전역 일괄 금지), 적용 전 before/after 출력.
- R-2 (Medium): 차단 게이트 확장이 단기 인스턴스에 회귀를 줄 수 있다(정상 상태인데 차단).
- 완화 방안: 차단은 실제 수량 불일치에서만 발생하도록 조건을 좁히고, 단기 인스턴스 시나리오(당일 슬롯·일치) 회귀 테스트를 design/verification에 포함.
- R-3 (Medium): 차단형 warning 저장 위치 선택(슬롯 필드 vs 별도 store vs 신규 SlotState)이 slots RPC wire 계약·전이표(`state.py`)에 파급될 수 있다.
- 완화 방안: pause(별도 store, 비침습)를 선례로 우선 검토. wire 영향 최소 안을 design에서 비교.
- R-4 (Medium): cold-start 시 평단(cost basis)을 어디서 가져올지 — 브로커 잔고는 수량은 주지만 중장기 전략이 쓸 평단/취득가를 슬롯에 seed해야 한다.
- 완화 방안: portfolio-hub 단가/평단 read 가용성 확인(OQ). 부재 시 폴백(브로커 평균가/원장 재구성) 정책 design.
## 가정
아직 확정되지 않았지만 현재 문서 작성의 기반이 되는 전제를 적는다.
- A-1: 중장기 인스턴스는 기존 multi-instance 토대(dcy-009/BAT-013, instance_key별 큐/락/TOML)를 그대로 재사용한다. 본 건은 그 위의 cold-start 동기화 능력이다.
- A-2: 브로커 `get_balance()`가 cold-start 시점에 실보유 수량을 신뢰 가능하게 반환한다(ground truth).
- A-3: portfolio-hub에 중장기 종목과 ledger(잔고)가 선행 등록되어 있다(자산 리스트가 슬롯 유니버스의 기준).
- A-4: pause가 durable 차단의 검증된 선례이므로, reconcile-warning도 유사한 durable·비침습 저장 방식을 취할 수 있다.
## 오픈 질문 (전부 Answered — 사장님 2026-06-25 confirm-discovery)
모든 OQ가 confirm-discovery에서 확정되었다. 결정 결과는 아래에 resolved 기록으로 남기고 본문(FR-3~7, 변경 1~4, R-1)에 반영했다.
- OQ-1 (Answered): 차단형 warning 상태 저장 위치 → **(b) pause_store와 동형의 별도 durable store**(slot_id/pid 키). SlotState enum·전이표·slots RPC wire 계약 불변(blast radius 최소). 반영: FR-5.
- OQ-2 (Answered): 명령 표면 → **별도 2명령 `sync`/`verify`**(단일 --apply 통합 안 채택 안 함 — --apply 오타 시 의도치 않은 슬롯 변경 위험). sync=쓰기(슬롯 qty←브로커), verify=read-중심 재대조. 반영: FR-3/FR-4.
- OQ-3 (Answered): B 동기화 방향 → **브로커 보유 정본 유지, 슬롯 보유량을 브로커에 맞춰 갱신.** 슬롯이 있는 종목(portfolio-hub 유니버스 기반)만 sync 대상. 브로커-only(portfolio-hub 부재)는 슬롯 자동생성 안 하고 unmanaged 경고 유지(슬롯 생성 기준=portfolio-hub). 반영: FR-3, R-1.
- OQ-4 (Answered): cold-start 평단 seed → **portfolio-hub에 "현재 보유 평단(WAC) read" 엔드포인트 신규 추가** 후 trex-core가 읽어 seed. 교차 서비스 의존(별도 portfolio-hub REQ). 근거: 현행 portfolio-hub는 WAC를 내부 계산하나(`app/domain/pnl.py:calculate_realized_pnl` running_wac) 외부 노출은 `GET /v1/portfolios/{id}/pnl/realized`(REQ-040) 매도행 `cost_basis_per_unit`뿐 — 미매도 보유분 현재 평단 read 부재(팀장 확인 2026-06-25). 반영: FR-7. 브로커 평균가 단독 의존은 dcy-032(평균가 0/None 케이스)로 위험.
- OQ-5 (Answered): C(원장↔슬롯) 대조 정의 → **현행 브로커 경유 2-대조 재사용**(브로커=단일 정본 일관). reconcile_positions(원장↔브로커)+reconcile_core_holdings(슬롯↔브로커) 양쪽을 브로커 기준으로 보고 불일치에 차단만 입힌다. B sync로 슬롯=브로커가 되면 원장↔슬롯 불일치=원장↔브로커 불일치로 환원되어 verify는 reconcile_positions 재실행으로 판정 가능. 반영: 변경 1, FR-4.
# 7. 초기 성공 기준
이 변경이 성공했다고 판단할 기준을 측정 가능하게 정의한다. 가능하면 데이터 출처까지 연결한다.
- S-1: 보유 종목이 실계좌에 있고 slot DB가 빈 cold-start 입력에서, 데몬 기동 후 불일치 슬롯이 **차단 상태**가 되고 전략 intent가 발행되지 않는다.
- S-2: `trex-core sync` 후 슬롯 수량이 브로커 잔고와 일치하고 해당 슬롯의 reconcile-warning이 해제되어 전략이 재개된다.
- S-3: C로 차단된 슬롯은 원장 정정 전 `verify`가 해제를 거부하고, 원장 정정 후 `verify`가 해제한다(강제 해제 경로 없음).
- S-4: 단기 인스턴스 정상(일치) 시나리오에서 신규 차단이 발생하지 않는다(회귀 0).
## 측정 방식 및 데이터 출처
각 성공 기준을 어떻게 측정할지와 어떤 데이터나 문서를 근거로 쓸지 적는다.
- S-1 측정 방식: cold-start 픽스처(빈 slot DB + 브로커 보유 + portfolio-hub 자산) 통합 테스트로 슬롯 차단 상태·intent 미발행 검증 / 데이터 출처: 신규 테스트.
- S-2 측정 방식: sync 명령 테스트로 슬롯 수량=브로커, warning 해제, 전략 게이트 통과 검증 / 데이터 출처: 슬롯 repo + RPC 응답.
- S-3 측정 방식: 원장 불일치 상태에서 verify 거부 → 정정 후 verify 해제 시나리오 테스트 / 데이터 출처: 신규 테스트 + 로그.
- S-4 측정 방식: 기존 단기 reconcile/실행 테스트 스위트 회귀 / 데이터 출처: 테스트 결과.
# 8. REQ로 넘기기 전 확인 체크
REQ 초안 작성 단계로 넘기기 전에 무엇이 확정되어야 하는지 확인한다. 미완료 항목은 후속 결정이 필요함을 뜻한다.
- [x] 범위(In Scope/Out of Scope) 확정
- 기준: 전략 모듈/인스턴스 프로파일/멀티데이 PnL을 본 건에서 제외하는 데 사장님 합의 — M3 framing(메모리 m3-goal-midlong-core-instance)상 전략 모듈은 별개 단위, 멀티데이 PnL은 portfolio-hub REQ-040/041로 분리 확정(사장님 2026-06-25). portfolio-hub 평단 read만 교차 의존으로 In Scope 편입.
- [x] 성공 지표의 측정 방식/데이터 출처 확정
- 기준: S-1~S-4 측정안에 사장님/팀장 이견 없음
- [x] High 영향 리스크 우선순위 및 해소 책임자 지정
- 기준: R-1(B 동기화 방향)은 OQ-3 확정(슬롯 qty←브로커, 브로커-only 자동편입 금지)으로 Medium으로 완화. 해소 책임=trex-core-dev(sync 구현 시 대상 한정·before/after 출력).
- [x] 모든 오픈 질문(OQ) `Open` 상태 없음 확인
- 기준: OQ-1~5 전부 Answered(사장님 2026-06-25). Open 0건.
- [x] Freeze 확정 담당자(CONFIRMED_BY) 지정
- 기준: 팀장(Claude)이 CONFIRMED_BY로 기록.
# 9. 파일 처리 결과
이 Discovery 문서 생성/갱신 결과와 참조 문서를 기록한다. 이후 추적과 리뷰 시 근거로 사용한다.
- 처리 결과: 생성
- 생성 경로: docs/discovery/dcy-034_20260625_slot-account-blocking-reconcile-sync-coldstart.md
- 참조 문서:
- docs/discovery/dcy-020_20260610_asset-centric-slot-model.md (자산중심 슬롯·유니버스 reconcile)
- docs/discovery/dcy-027_20260612_long-term-strategy-slot-operation.md (중장기 슬롯 운영·운영 프로파일, cold-start Out-of-Scope 이월원)
- docs/discovery/dcy-028_20260615_slot-strategy-state-store.md (slot strategy-state — onboarding 시 seed 대상)
- trex_core/application/reconciliation.py, trex_core/application/snapshot_scheduler.py, trex_core/runtime/cli.py, trex_core/domain/slot/state.py (현재 구현 근거)
- GitHub 보드 #7 "슬롯↔실계좌 차단형 reconcile + sync/verify" 항목(설계방향 본문)
# 10. 사용자 결정 필요 항목 요약
사용자나 승인자가 결정해야 하는 항목만 모아 정리한다. 결정, 확인, 데이터 요청을 구분해서 적는다.
## DECIDE (전부 결정됨 — 사장님 2026-06-25)
- (확정) OQ-3 B 동기화 방향 → 브로커 정본 유지·슬롯 qty를 브로커로 수렴. 브로커-only(portfolio-hub 부재) 자동 슬롯 편입 금지(unmanaged 경고 유지).
- (확정) 범위 경계 → 중장기 전략 모듈·인스턴스 TOML 프로파일·멀티데이 PnL은 본 건에서 제외(별개 단위). portfolio-hub 평단 read는 교차 의존으로 In Scope.
- (확정) OQ-1 warning 저장=별도 durable store / OQ-2 명령=별도 2명령 sync,verify / OQ-5 C대조=현행 브로커 경유 2-대조 재사용.
## CONFIRM (확정)
- 본 Discovery 핵심 방향(차단형 reconcile + sync/verify + durable warning)을 M3 cold-start 단위로 채택 — 사장님 2026-06-25.
- pause∨warning 차단 게이트로 전략 차단 일원화 — 채택.
## DATA (확보됨)
- (OQ-4 확인 완료) portfolio-hub는 미매도 보유분 현재 평단 read 부재 → "현재 보유 평단(WAC) read" 신규 추가로 결정(FR-7, 교차 서비스 의존 REQ).
# 11. Discovery Freeze
REQ 초안 작성 인계 시점의 확정 플래그와 섹션 참조만 기록한다. 내용 재작성 없이 원본 섹션을 링크로 대신한다.
## 섹션 참조
- 범위: [# 5. 요구사항 목록 > 범위 경계](#5-요구사항-목록)
- 리스크/오픈 질문: [# 6. 리스크/가정 목록](#6-리스크가정-목록)
- 성공 기준: [# 7. 초기 성공 기준](#7-초기-성공-기준)
- 인계 전 확인: [# 8. REQ로 넘기기 전 확인 체크](#8-req로-넘기기-전-확인-체크)
- 사용자 결정 필요: [# 10. 사용자 결정 필요 항목 요약](#10-사용자-결정-필요-항목-요약)
## Freeze 플래그
- Handoff Decision: REQ Drafting 진행 가능
- Handoff Rationale: 핵심 방향(차단형 reconcile + sync/verify + durable warning) 채택, OQ-1~5 전부 Answered(사장님 2026-06-25), High 리스크(R-1) OQ-3 확정으로 Medium 완화. portfolio-hub 평단 read(FR-7)는 교차 서비스 선행 의존으로 명시 — draft-req 시 trex-core REQ와 portfolio-hub 의존 REQ를 함께 분해. Open OQ 0건 → 인계 가능.
- Ready for REQ Drafting: true
- Confirmed By: 팀장(Claude)
- Confirmed At (KST): 2026-06-25 (KST)
# 12. 작성 가이드
- 이 문서는 dcy 템플릿 기반으로 작성되었으며, Open Questions는 가정으로 대체하지 않고 그대로 유지한다.
- confirm-discovery 시 OQ-1~5의 처리(Answered/Deferred)와 Freeze 플래그를 갱신한다.
+1
View File
@@ -39,3 +39,4 @@
| dcy-031_20260619_event-publisher-connection-reliability | 20260619 | 이벤트 발행 연결 신뢰성 — idle heartbeat 사망 후 첫 발행 유실 + DLQ 가시성 (OPS-005) | [Discovery](./dcy-031_20260619_event-publisher-connection-reliability.md) | confirmed |
| dcy-032_20260621_fill-missing-price-cost-basis-backfill | 20260621 | 체결가 누락(브로커 평균가 0/None) → 슬롯 평단·원장 cost basis 0 오염(무경고·영구) → 지정가 백필 + 로깅 + 알람 검토 | [Discovery](./dcy-032_20260621_fill-missing-price-cost-basis-backfill.md) | confirmed |
| dcy-033_20260621_suite-alarm-delivery-notifier | 20260621 | 제품군 알람 전달 체계 — 모듈 발신 + 중앙 notifier(trex-notifier) → 텔레그램(P1 아웃바운드). envelope 계약+전송(trex.alerts AMQP 확정)+등급/상관억제/하트비트 | [Discovery](./dcy-033_20260621_suite-alarm-delivery-notifier.md) | confirmed |
| dcy-034_20260625_slot-account-blocking-reconcile-sync-coldstart | 20260625 | 슬롯↔실계좌 차단형 reconcile + sync/verify 명령 — 중장기 cold-start(기존 보유 onboarding). B/C 불일치→슬롯 차단(durable warning) + pause∨warning 게이트 + 운영자 sync/verify (M3) | [Discovery](./dcy-034_20260625_slot-account-blocking-reconcile-sync-coldstart.md) | confirmed |
@@ -0,0 +1,108 @@
# req-102: reconcile-warning durable store — slot_id/pid 키 별도 테이블
- Status: Approved
- Type: Data
- Priority: High
- Owner: trex-core-dev
## Intent
- boot/일일 reconcile에서 슬롯↔브로커(B) 또는 원장↔슬롯(C) 불일치가 탐지될 때 해당 슬롯을 차단하는 **durable한 reconcile-warning 상태**를 저장할 별도 PostgreSQL 테이블을 도입한다.
- OQ-1(dcy-034) 확정: pause_store와 동형 설계를 선례로 삼아 SlotState enum·전이표·slots RPC wire 계약을 변경하지 않는 비침습 접근을 취한다(NFR-4).
- 재시작 후에도 차단 상태가 유지되어야 한다(NFR-1).
## Requirement
- 시스템은 `slot_reconcile_warning` 테이블(PK: slot_id)을 PostgreSQL에 생성하고, `slot_id`, `portfolio_id`, `case_code`(B 또는 C), `actor`, `reason`, `created_at`, `updated_at` 컬럼을 가져야 한다.
- `ReconcileWarningStore`(application port) 및 `PostgreSQLReconcileWarningStore`(adapter)는 pause_store와 동형 인터페이스(`set_warned`, `clear_warned`, `list_warned`, `is_warned`)를 제공해야 한다.
- 스토어는 slot_id를 PK로 삼고 동일 slot_id의 중복 삽입 시 `ON CONFLICT DO UPDATE`로 갱신해야 한다.
- DB 마이그레이션 스크립트로 테이블 생성을 관리해야 한다.
## Acceptance Criteria
1. Given `slot_reconcile_warning` 테이블이 없는 DB에서 마이그레이션을 실행하면, When 마이그레이션이 완료되면, Then 테이블이 존재하고 PK(slot_id), case_code, portfolio_id, actor, reason, created_at, updated_at 컬럼이 모두 존재한다.
2. Given `ReconcileWarningStore.set_warned(slot_id, portfolio_id, case_code, actor, reason)` 호출 후, When 데몬이 재시작되어도, Then `is_warned(slot_id)` = True가 유지된다(durable).
3. Given 동일 slot_id에 대해 `set_warned`를 두 번 호출하면, When DB를 조회하면, Then 행이 1개이고 최신 값으로 갱신되어 있다(ON CONFLICT DO UPDATE).
4. Given `clear_warned(slot_id)` 호출 후, When `is_warned(slot_id)`를 조회하면, Then False를 반환한다.
5. Given `list_warned()` 호출 시, When 복수의 warned slot이 존재하면, Then 해당 slot_id 집합이 반환된다.
6. Given `SlotState` enum 및 `ALLOWED_TRANSITIONS`, When 스토어를 추가해도, Then `domain/slot/state.py`에 새 SlotState 또는 전이 추가가 없다(wire 계약 불변, NFR-4).
## Impacted Area
- Docs: `docs/srs/index.md` (Next Requirement ID, Register 갱신)
- Modules:
- `trex_core/adapters/portfolio/reconcile_warning_store.py` (신규 — pause_store.py 동형)
- `trex_core/application/ports.py` 또는 `application/portfolio.py` (ReconcileWarningStore 포트 정의)
- `trex_core/adapters/persistence/migrations/` (신규 마이그레이션)
- `trex_core/domain/slot/state.py` (변경 없음 — 불변 확인)
- Tests:
- `tests/application/` 또는 `tests/adapters/` — ReconcileWarningStore 단위 테스트 (set/clear/list/is_warned, durable 검증, ON CONFLICT 검증)
- 기존 slot state machine 테스트 회귀 확인
## Notes
- pause_store 선례(`adapters/portfolio/pause_store.py`, `application/portfolio.py:PauseStore`)를 동형으로 따른다.
- 포트 정의 위치(application/portfolio.py 내 Protocol 클래스 vs 별도 파일)는 batch design에서 결정한다.
- `case_code` 값: `B`(슬롯 보유·브로커 수량 불일치), `C`(원장↔슬롯 수량 불일치).
- dcy-034 FR-5, NFR-1, NFR-4 대응.
## Change Log
### CHG-20260625-02
- Date: 2026-06-25
- Author: trex-core-dev
#### Change Summary
- REQ-102 **Proposed → Approved** (confirm-req, 팀장 2026-06-25).
#### Intent
- 팀장 confirm-req로 상태 승인. 내용 변경 없음(OQ-1 반영 초안 그대로 승인).
#### Acceptance Criteria Delta
- Added: 없음.
- Updated: 없음.
- Removed: 없음.
#### Impacted Area Delta
- 없음.
#### Delivery Trace Delta
- Batches: 미정 (suggest-batch-reqs 이후)
- Releases: 미정
#### Revalidation Impact
- Reverification Needed: no
- Existing Implementation Invalidated: no
- Status Recommendation: Approved
- Follow-up Action: batch 편성 후 구현.
#### Validation Plan
- ReconcileWarningStore 단위 테스트 pass / DB 마이그레이션 스크립트 적용 검증 / SlotState 불변 회귀 테스트 pass.
### CHG-20260625-01
- Date: 2026-06-25
- Author: trex-core-dev
#### Change Summary
- REQ-102 신규 생성 (Proposed) — dcy-034 FR-5 대응, draft-req 단계.
#### Intent
- dcy-034 OQ-1 확정(pause_store 동형 별도 durable store)을 반영해 reconcile-warning 저장 능력 도입.
#### Acceptance Criteria Delta
- Added: AC-1~6 전부 신규.
- Updated: 없음.
- Removed: 없음.
#### Impacted Area Delta
- Docs: index.md 갱신.
- Modules: reconcile_warning_store.py 신규, 마이그레이션 신규.
- Tests: ReconcileWarningStore 단위 테스트 신규.
#### Delivery Trace Delta
- Batches: 미정 (suggest-batch-reqs 이후)
- Releases: 미정
#### Revalidation Impact
- Reverification Needed: no (신규 REQ)
- Existing Implementation Invalidated: no
- Status Recommendation: keep-current
- Follow-up Action: confirm-req 후 batch 편성.
#### Validation Plan
- ReconcileWarningStore 단위 테스트 pass / DB 마이그레이션 스크립트 적용 검증 / SlotState 불변 회귀 테스트 pass.
@@ -0,0 +1,109 @@
# req-107: 차단/해제 전이 식별 로깅 + 고영향 불일치 알람
- Status: Approved
- Type: Exception
- Priority: High
- Owner: trex-core-dev
## Intent
- reconcile-warning 차단 및 해제 전이마다 슬롯·심볼·원인케이스·수량 before/after·actor를 포함한 **식별 가능한 구조화 로그**를 남겨 운영자가 차단 원인과 이력을 추적할 수 있게 한다.
- 고영향 불일치(케이스 A: 슬롯 보유인데 브로커 0 — phantom holding)는 기존 알람 채널(dcy-033/`trex.alerts`)로 통지한다.
- dcy-034 FR-6 대응.
## Requirement
- 시스템은 reconcile-warning 차단 전이(`set_warned`) 시 WARNING 레벨 로그를 남겨야 하며, 로그에는 `slot_id`, `portfolio_id`, `symbol`, `case_code`(B 또는 C), `broker_qty`, `slot_qty`(B의 경우 before), `hub_qty`(C의 경우 원장 수량), `actor`="reconcile" 필드가 포함되어야 한다.
- 시스템은 reconcile-warning 해제 전이(`clear_warned`) 시 INFO 레벨 로그를 남겨야 하며, 로그에는 `slot_id`, `portfolio_id`, `symbol`, `actor`(sync/verify/reconcile), `resolved_by`(sync 또는 verify) 필드가 포함되어야 한다.
- 케이스 A(슬롯 보유, 브로커 0 — phantom holding)는 기존 REQ-100(`AlarmEmitter.publish_alarm`) 경로를 통해 `trex.alerts` exchange로 CRITICAL 알람을 발행해야 한다(기존 `reconcile_core_holdings` 내 alarm_emitter 호출 활성 — 이미 구현됨, 여기서는 차단형 전이와의 일관성 확인).
- B/C 케이스 차단 시 WARNING 로그는 구조화 포맷(JSON 또는 key=value)으로 남겨져 Loki/로그 검색에서 `slot_id`, `case_code` 필드로 필터링 가능해야 한다(REQ-084 구조화 로깅 기반과 일관).
- sync 또는 verify로 warning이 해제될 때, actor 필드에 "sync" 또는 "verify"가 기록되어야 한다.
## Acceptance Criteria
1. Given 케이스 B 불일치 탐지 시, When `set_warned`가 호출되면, Then `level=WARNING`, `slot_id`, `portfolio_id`, `symbol`, `case_code='B'`, `broker_qty`, `slot_qty`(before) 필드를 포함한 로그가 기록된다.
2. Given 케이스 C 불일치 탐지 시, When `set_warned`가 호출되면, Then `level=WARNING`, `slot_id`, `portfolio_id`, `symbol`, `case_code='C'`, `hub_qty`, `broker_qty` 필드를 포함한 로그가 기록된다.
3. Given `trex-core sync`로 warning 해제 시, When `clear_warned`가 호출되면, Then `level=INFO`, `slot_id`, `portfolio_id`, `symbol`, `actor='sync'` 필드를 포함한 로그가 기록된다.
4. Given `trex-core verify`로 warning 해제 시, When `clear_warned`가 호출되면, Then `level=INFO`, `slot_id`, `portfolio_id`, `symbol`, `actor='verify'` 필드를 포함한 로그가 기록된다.
5. Given 케이스 A(슬롯 보유, 브로커 0)에서, When `reconcile_core_holdings`가 실행되면, Then 기존 REQ-100 경로로 `trex.alerts` CRITICAL 알람이 발행된다(기존 동작 회귀 없음).
6. Given 차단/해제 로그가 남겨진 경우, When 로그를 `slot_id` 또는 `case_code`로 필터링하면, Then 해당 이벤트를 특정할 수 있다(Loki 구조화 로그 필터링 가능).
## Impacted Area
- Docs: `docs/operations.md` (로그 조회 방법 추가)
- Modules:
- `trex_core/application/reconciliation.py` (차단 전이 로그 — set_warned 호출 지점)
- `trex_core/runtime/cli.py` (`sync`/`verify` 해제 로그 — clear_warned 호출 지점)
- `trex_core/adapters/portfolio/reconcile_warning_store.py` (선택: store 자체에 로그 위임 vs 호출부 로그 — batch design에서 결정)
- Tests:
- `tests/application/test_reconciliation.py` (차단 로그 필드 검증)
- `tests/runtime/test_cli.py` (해제 로그 actor 필드 검증)
- 기존 REQ-100 알람 테스트 회귀 확인
## Notes
- 케이스 A 알람은 REQ-100 구현(`reconcile_core_holdings` 내 `alarm_emitter.publish_alarm("core_holding_broker_flat", ...)`)이 이미 존재하므로, 이 REQ에서는 B/C 차단 로그 추가와 A 알람 기존 동작 회귀 없음을 확인하면 된다.
- 구조화 로그 포맷은 REQ-084(`trex_core/runtime/logging_setup.py`)와 일관성 있게 작성한다.
- 고영향 B 불일치(large qty 차이 등)에 대해 B 케이스도 `trex.alerts` 알람으로 확대할지는 batch design에서 검토한다(dcy-034는 "고영향(A phantom)은 trex.alerts" 명시, B/C는 WARN 로그로 충분함을 시사).
- dcy-034 FR-6 대응.
## Change Log
### CHG-20260625-02
- Date: 2026-06-25
- Author: trex-core-dev
#### Change Summary
- REQ-107 **Proposed → Approved** (confirm-req, 팀장 2026-06-25).
#### Intent
- 팀장 confirm-req로 상태 승인. 내용 변경 없음(초안 그대로 승인).
#### Acceptance Criteria Delta
- Added: 없음.
- Updated: 없음.
- Removed: 없음.
#### Impacted Area Delta
- 없음.
#### Delivery Trace Delta
- Batches: 미정 (suggest-batch-reqs 이후)
- Releases: 미정
#### Revalidation Impact
- Reverification Needed: no
- Existing Implementation Invalidated: no
- Status Recommendation: Approved
- Follow-up Action: batch 편성 후 구현.
#### Validation Plan
- 차단 로그 필드 검증 테스트 pass / 해제 로그 actor 필드 검증 pass / A 알람 회귀 pass.
### CHG-20260625-01
- Date: 2026-06-25
- Author: trex-core-dev
#### Change Summary
- REQ-107 신규 생성 (Proposed) — dcy-034 FR-6 대응, draft-req 단계.
#### Intent
- 차단/해제 전이 가시화. 운영자가 로그만으로 불일치 발생 및 해소 이력을 추적할 수 있는 구조화 로그 신설.
#### Acceptance Criteria Delta
- Added: AC-1~6 전부 신규.
- Updated: 없음.
- Removed: 없음.
#### Impacted Area Delta
- Docs: operations.md 갱신.
- Modules: reconciliation.py, cli.py.
- Tests: 로그 필드 검증 신규.
#### Delivery Trace Delta
- Batches: 미정
- Releases: 미정
#### Revalidation Impact
- Reverification Needed: no (신규 REQ)
- Existing Implementation Invalidated: no
- Status Recommendation: keep-current
- Follow-up Action: confirm-req 후 batch design.
#### Validation Plan
- 차단 로그 필드(slot_id/case_code/qty before-after/actor) 검증 테스트 pass / 해제 로그 actor 필드 검증 pass / A 알람 회귀 pass.
@@ -0,0 +1,108 @@
# req-103: 차단형 reconcile — B/C 불일치 슬롯 reconcile-warning 전이
- Status: Approved
- Type: Integration
- Priority: High
- Owner: trex-core-dev
## Intent
- boot/일일 reconcile(`reconcile_core_holdings`, `reconcile_positions`) 수행 중 B(슬롯↔브로커 수량 불일치) 또는 C(원장↔슬롯 수량 불일치)가 탐지되면, 해당 슬롯을 **WARN 로그만 남기던 기존 동작에서 reconcile-warning durable 차단으로 승격**한다.
- dcy-034 FR-1 대응: 불일치 슬롯이 탐지 즉시 차단되어 정합 전 잘못된 매매가 나가지 않도록 한다.
- 단기 인스턴스 정상(일치) 시나리오에서 차단이 오발동하지 않아야 한다(NFR-2/S-4).
## Requirement
- 시스템은 `reconcile_core_holdings` 실행 중 케이스 B(슬롯 보유, 브로커 수량 불일치 — qty 차이)를 탐지하면 해당 slot_id를 `ReconcileWarningStore.set_warned(slot_id, portfolio_id, case_code='B', actor='reconcile', reason=...)` 로 durable 차단해야 한다.
- 시스템은 `reconcile_positions` 실행 중 케이스 C(원장 portfolio-hub 수량 ≠ 브로커 수량)를 탐지하면 관련 슬롯(portfolio_id로 조회)을 `ReconcileWarningStore.set_warned(slot_id, portfolio_id, case_code='C', actor='reconcile', reason=...)` 로 durable 차단해야 한다.
- 케이스 A(슬롯 보유, 브로커 0)는 기존 `SlotState.ERROR` 전이를 유지하고 reconcile-warning 스토어를 사용하지 않는다(기존 동작 보존).
- `snapshot_scheduler.run_once()` 내 reconcile 순서(reconcile_positions → _reconcile_slots → reconcile_core_holdings)에서 두 함수 모두 ReconcileWarningStore를 주입받아 차단을 기록해야 한다.
- 불일치가 실제로 있을 때만 차단이 발생하며, 수량이 일치하는 슬롯에는 차단이 적용되지 않아야 한다.
## Acceptance Criteria
1. Given 슬롯 보유 수량과 브로커 잔고 수량이 다른 케이스 B 입력에서, When `reconcile_core_holdings`가 실행되면, Then 해당 slot_id가 ReconcileWarningStore에 `case_code='B'`로 기록된다.
2. Given portfolio-hub 원장 수량과 브로커 수량이 다른 케이스 C 입력에서, When `reconcile_positions`가 실행되면, Then 관련 슬롯의 slot_id가 ReconcileWarningStore에 `case_code='C'`로 기록된다.
3. Given 슬롯 수량과 브로커 수량이 일치하는 정상 케이스에서, When reconcile가 실행되면, Then ReconcileWarningStore에 해당 slot_id 행이 생기지 않는다(오발동 없음, S-4).
4. Given 케이스 A(슬롯 보유, 브로커 0)에서, When `reconcile_core_holdings`가 실행되면, Then 기존처럼 SlotState.ERROR 전이가 발생하고 ReconcileWarningStore는 사용하지 않는다.
5. Given `ReconcileWarningStore`가 주입되지 않은 구성에서, When reconcile가 실행되면, Then 기존 WARN 로그 동작이 유지되고 예외가 발생하지 않는다(하위 호환 / 테스트 더블 지원).
6. Given 단기 인스턴스(M1/M2 라이브) 정상 시나리오에서, When boot/일일 reconcile가 실행되면, Then 신규 reconcile-warning이 발생하지 않는다(회귀 0, NFR-2, S-4).
## Impacted Area
- Docs: `docs/interface-contract.md`, `docs/runtime-flows.md` (reconcile 흐름 갱신 필요 여부 batch design에서 확인)
- Modules:
- `trex_core/application/reconciliation.py` (`reconcile_core_holdings`, `reconcile_positions` — ReconcileWarningStore 주입 파라미터 추가)
- `trex_core/application/snapshot_scheduler.py` (`SnapshotScheduler.__init__`, `run_once` — ReconcileWarningStore 주입 및 전달)
- Tests:
- `tests/application/test_reconciliation.py` (신규 B/C 차단 케이스, 정상 케이스 오발동 없음, A 케이스 기존 동작 유지, store 미주입 하위 호환)
- `tests/application/test_snapshot_scheduler.py` (run_once 내 차단 흐름 통합 검증)
- 기존 reconcile 회귀 테스트
## Notes
- `reconcile_positions`는 현재 portfolio_id 단위 경고(`store.set_warning`)를 in-memory로 관리한다. C 차단은 portfolio_id에 대응하는 slot을 조회해야 하므로, `reconcile_positions`에 `slot_repo` 주입이 필요할 수 있다. 구체 구현은 batch design에서 결정한다.
- ReconcileWarningStore 파라미터는 Optional로 추가해 기존 호출부(테스트 포함)의 하위 호환을 유지한다.
- 불일치 수량 before/after 정보는 REQ-107(로깅) 범위에서 다룬다.
- dcy-034 FR-1, NFR-2, NFR-3, S-4 대응.
## Change Log
### CHG-20260625-02
- Date: 2026-06-25
- Author: trex-core-dev
#### Change Summary
- REQ-103 **Proposed → Approved** (confirm-req, 팀장 2026-06-25).
#### Intent
- 팀장 confirm-req로 상태 승인. 내용 변경 없음(초안 그대로 승인).
#### Acceptance Criteria Delta
- Added: 없음.
- Updated: 없음.
- Removed: 없음.
#### Impacted Area Delta
- 없음.
#### Delivery Trace Delta
- Batches: 미정 (suggest-batch-reqs 이후)
- Releases: 미정
#### Revalidation Impact
- Reverification Needed: no
- Existing Implementation Invalidated: no
- Status Recommendation: Approved
- Follow-up Action: batch 편성 후 구현.
#### Validation Plan
- 신규 B/C 차단 테스트 pass / 정상 케이스 오발동 없음 테스트 pass / 기존 reconcile 회귀 pass.
### CHG-20260625-01
- Date: 2026-06-25
- Author: trex-core-dev
#### Change Summary
- REQ-103 신규 생성 (Proposed) — dcy-034 FR-1 대응, draft-req 단계.
#### Intent
- 기존 WARN 로그 전용이던 B/C 불일치를 durable 차단으로 승격해 cold-start 시 정합 전 매매를 구조적으로 차단.
#### Acceptance Criteria Delta
- Added: AC-1~6 전부 신규.
- Updated: 없음.
- Removed: 없음.
#### Impacted Area Delta
- Docs: runtime-flows.md 갱신 예정.
- Modules: reconciliation.py, snapshot_scheduler.py.
- Tests: 신규 B/C 케이스 테스트.
#### Delivery Trace Delta
- Batches: 미정
- Releases: 미정
#### Revalidation Impact
- Reverification Needed: no (신규 REQ)
- Existing Implementation Invalidated: no
- Status Recommendation: keep-current
- Follow-up Action: confirm-req 후 batch 편성.
#### Validation Plan
- 신규 B/C 차단 테스트 pass / 정상 케이스 오발동 없음 테스트 pass / 기존 reconcile 회귀 pass.
@@ -0,0 +1,118 @@
# req-104: 전략 차단 게이트 — pause ∨ reconcile-warning 중 하나라도 걸리면 차단
- Status: Approved
- Type: Interface
- Priority: High
- Owner: trex-core-dev
## Intent
- 현재 전략 차단은 pause(수동 durable) 채널에만 의존한다. reconcile-warning(자동 durable) 채널을 추가해, **pause ∨ reconcile-warning 중 하나라도 존재하면 해당 슬롯/포트폴리오의 전략 수행(intent 수용 + slots read 차단 표면)을 차단**한다.
- dcy-034 FR-2 대응: 두 채널이 독립적으로 작동하며 OR 논리로 게이트를 확장한다.
- slots RPC wire 계약(`trex.slots.req` 응답 스키마)에서 `reconcile_warned` 플래그를 additive 필드로 노출해 운영자가 차단 원인을 식별할 수 있게 한다(NFR-4 최소 침습).
- **차단 범위(OQ-B 확정)**: reconcile-warning 차단은 **외부 전략 intent/read 전용**이다. **내부 안전망(safety-sell · watchdog · kill-switch)은 차단 예외**다. 근거: 집행 수량 정본은 브로커 잔고(execution.py)이므로 안전망은 수량 오류에 안전하며, 차단 시 포지션이 무보호로 방치된다.
## Requirement
- 시스템은 `IntentService._admit_buy` 및 `_admit_sell` 수행 시 대상 슬롯의 `pause_store` 또는 `ReconcileWarningStore` 중 하나라도 차단 기록이 있으면 intent를 `rejected`(reason: `reconcile_warned` 또는 `paused`)로 반환해야 한다.
- **내부 안전망 경로(safety-sell / kill-switch / watchdog)는 reconcile-warning 차단을 우회해야 한다.** 이 경로들은 `IntentService._admit_*` 게이트를 거치지 않는 별도 내부 경로를 사용하며, reconcile-warning이 걸린 슬롯에 대해서도 안전망 매도를 실행할 수 있어야 한다(OQ-B 확정, 차단 대상은 외부 전략 intent만).
- 시스템은 slots RPC 핸들러(`make_slots_rpc_handler`)에서 각 슬롯 행에 `reconcile_warned: bool` 필드를 추가해 reconcile-warning 차단 여부를 노출해야 한다.
- `slot_to_dict` 함수는 `ReconcileWarningStore`를 선택적으로 주입받고, `reconcile_warned` 필드를 산출해야 한다(pause_store의 `paused` 필드 처리 방식과 동형).
- 기존 `paused` 필드 및 `warned` 필드는 변경 없이 유지해야 한다(additive only, NFR-4).
- reconcile-warning 차단으로 rejected된 buy intent는 `reason="reconcile_warned"` 를 반환해야 한다.
## Acceptance Criteria
1. Given 슬롯의 portfolio_id가 ReconcileWarningStore에 warned 상태일 때, When buy intent가 제출되면, Then status=`rejected`, reason=`reconcile_warned`가 반환된다(전략 진입 차단).
2. Given 슬롯의 portfolio_id가 ReconcileWarningStore에 warned 상태일 때, When sell intent가 제출되면(외부 전략 경로), Then status=`rejected`, reason=`reconcile_warned`가 반환된다(전략 매도 차단). **단, safety-sell / kill-switch / watchdog의 내부 안전망 매도 경로는 이 차단을 받지 않으며 정상 실행되어야 한다(OQ-B 확정, 차단 예외).**
3. Given pause도 reconcile-warning도 없는 정상 슬롯에서, When buy/sell intent가 제출되면, Then 기존 admission 로직이 그대로 동작한다(오발동 없음).
4. Given pause만 있는 슬롯에서, When slots RPC가 호출되면, Then `paused=True`, `reconcile_warned=False` 필드가 반환된다(기존 paused 동작 불변).
5. Given reconcile-warning만 있는 슬롯에서, When slots RPC가 호출되면, Then `paused=False`, `reconcile_warned=True` 필드가 반환된다.
6. Given pause와 reconcile-warning이 모두 있는 슬롯에서, When slots RPC가 호출되면, Then `paused=True`, `reconcile_warned=True`가 모두 반환된다.
7. Given ReconcileWarningStore가 주입되지 않은 구성에서, When slots RPC가 호출되면, Then `reconcile_warned=False`(또는 필드 부재 시 기본값)로 반환되어 기존 클라이언트가 깨지지 않는다(하위 호환).
8. Given 기존 `warned` 필드(슬롯 qty ≠ hub asset_quantity 로컬 계산), When 신규 필드가 추가돼도, Then `warned` 필드 정의와 동작이 변경되지 않는다.
## Impacted Area
- Docs: `docs/interface-contract.md` (slots RPC 응답 스키마 `reconcile_warned` 필드 추가 명시)
- Modules:
- `trex_core/application/portfolio.py` (`slot_to_dict` — `reconcile_warned` 필드 추가)
- `trex_core/application/intents.py` (`IntentService._admit_buy`, `_admit_sell` — reconcile-warning 게이트 추가)
- `trex_core/application/messaging_handlers.py` (`make_slots_rpc_handler` — ReconcileWarningStore 주입 파라미터 추가)
- `trex_core/runtime/daemon.py` (ReconcileWarningStore 주입 배선)
- Tests:
- `tests/application/test_intents.py` (reconcile_warned 차단 시나리오, 정상 슬롯 오발동 없음)
- `tests/application/test_messaging_handlers.py` (slots RPC reconcile_warned 필드 노출)
- `tests/application/test_portfolio.py` (`slot_to_dict` reconcile_warned 필드 검증)
## Notes
- **safety-sell / kill-switch / watchdog 차단 예외(OQ-B 확정)**: 내부 안전망(safety-sell REQ-037~039, kill-switch REQ-045, watchdog REQ-034) 경로는 reconcile-warning 차단 예외다. 집행 수량 정본은 브로커 잔고(`execution.py`)이므로 안전망은 수량 오류에 안전하며, 차단하면 포지션이 무보호로 방치된다. 이 경로들은 `IntentService._admit_*` 게이트를 거치지 않는 별도 내부 호출 경로를 사용하므로 구조적으로 차단을 우회한다. batch design에서 경로 분리 구조를 명시적으로 확인한다.
- `reconcile_warned` 필드는 `slot_to_dict` 단에서 `ReconcileWarningStore.is_warned(slot_id)` 또는 `slot_id in list_warned()` 조회로 산출한다. batch design에서 성능(N+1) 고려해 bulk 조회 방식 선택.
- AMQP wire 계약 변경 사항: `trex.slots.req` 응답 행에 `reconcile_warned: bool` 필드 additive 추가. trex-orb-v1·trex-tsl-v1이 이 필드를 무시해도 하위 호환이 유지되는지 batch design에서 확인 필요.
- dcy-034 FR-2, NFR-4 대응.
## Change Log
### CHG-20260625-02
- Date: 2026-06-25
- Author: trex-core-dev
#### Change Summary
- REQ-104 **Proposed → Approved** (confirm-req, 팀장 2026-06-25).
- OQ-B 결정 반영: reconcile-warning 차단 범위 = 외부 전략 intent/read 전용. 내부 안전망(safety-sell/watchdog/kill-switch)은 차단 예외로 확정. AC-2에 예외 명시.
- Intent, Requirement, Notes에 OQ-B 결정 근거(집행 수량 정본=브로커, 차단 시 포지션 무보호) 추가.
#### Intent
- 팀장 confirm-req 결정(OQ-B 차단 예외 확정)을 REQ에 반영.
#### Acceptance Criteria Delta
- Added: 없음.
- Updated: AC-2(safety-sell/kill-switch/watchdog 차단 예외 명시).
- Removed: 없음.
#### Impacted Area Delta
- Notes: 안전망 경로 차단 예외 설계 원칙 구체화.
- Modules: `intents.py` — 차단 게이트가 외부 전략 intent 경로에만 적용됨을 구현 시 명시.
- Tests: safety-sell/kill-switch가 reconcile-warning 슬롯에서도 실행됨을 확인하는 테스트 추가 필요.
#### Delivery Trace Delta
- Batches: 미정 (suggest-batch-reqs 이후)
- Releases: 미정
#### Revalidation Impact
- Reverification Needed: no
- Existing Implementation Invalidated: no
- Status Recommendation: Approved
- Follow-up Action: batch design에서 안전망 경로 분리 구조 명시 확인.
#### Validation Plan
- 외부 intent reconcile_warned 차단 테스트 pass / safety-sell 차단 우회 테스트 pass / slots RPC reconcile_warned 필드 반환 테스트 pass / 기존 paused/warned 동작 회귀 pass.
### CHG-20260625-01
- Date: 2026-06-25
- Author: trex-core-dev
#### Change Summary
- REQ-104 신규 생성 (Proposed) — dcy-034 FR-2 대응, draft-req 단계.
#### Intent
- pause 단독 게이트를 pause ∨ reconcile-warning OR 게이트로 확장해 자동 차단 채널을 활성화.
#### Acceptance Criteria Delta
- Added: AC-1~8 전부 신규.
- Updated: 없음.
- Removed: 없음.
#### Impacted Area Delta
- Docs: interface-contract.md 갱신 예정.
- Modules: portfolio.py, intents.py, messaging_handlers.py.
- Tests: 신규 게이트 테스트.
#### Delivery Trace Delta
- Batches: 미정
- Releases: 미정
#### Revalidation Impact
- Reverification Needed: no (신규 REQ)
- Existing Implementation Invalidated: no
- Status Recommendation: keep-current
- Follow-up Action: confirm-req 후 wire 계약 영향 확인 포함 batch design.
#### Validation Plan
- reconcile_warned 차단 및 정상 슬롯 오발동 없음 테스트 pass / slots RPC reconcile_warned 필드 반환 테스트 pass / 기존 paused/warned 동작 회귀 pass.
@@ -0,0 +1,123 @@
# req-105: trex-core sync 명령 — 슬롯 수량을 브로커에 맞춰 갱신 + warning 해제
- Status: Approved
- Type: Interface
- Priority: High
- Owner: trex-core-dev
## Intent
- 운영자가 `trex-core sync` 명령으로 **브로커 잔고(정본)를 기준으로 대상 슬롯의 보유 수량을 갱신**(INACTIVE→HOLDING 전이 포함)하고, 갱신 후 브로커와 일치하면 해당 슬롯의 reconcile-warning을 자동 해제한다.
- cold-start 시 실계좌에 이미 보유 중인 종목(B 케이스)의 슬롯 onboarding 경로이기도 하다.
- dcy-034 FR-3, OQ-2/OQ-3 확정 반영: **브로커 잔고 정본 유지, 슬롯 qty ← 브로커**. 브로커에만 있고 portfolio-hub에 없는 종목(슬롯 부재)은 sync 대상 아님(자동 슬롯 생성 금지).
- portfolio-hub WAC(보유 평단) read 엔드포인트(FR-7, portfolio-hub **dcy-008 / REQ-043** `GET /v1/portfolios/{id}/holdings/cost-basis`) 가용 시 슬롯 avg_price를 seed한다. 포트 미가용 또는 조회 실패 시 수량만 갱신하고 WARN 로그를 남긴다(graceful degrade).
- **INACTIVE→HOLDING 전이 엣지 추가 승인(OQ-A)**: `ALLOWED_TRANSITIONS`에 `(INACTIVE, HOLDING)` 전이를 추가한다. 이 전이는 **actor=sync 또는 reconcile/reconcile_sync로 제한**되며, 일반 전략 경로(INACTIVE→PENDING_BUY→HOLDING)는 유지된다. transition_log reason은 `onboarding` 또는 `reconcile_sync`류로 식별 가능하게 기록한다. **wire 계약 무영향**: SlotState enum 상태값 5개(INACTIVE/PENDING_BUY/HOLDING/PENDING_SELL/ERROR) 불변, 전이 엣지만 추가이므로 slots RPC 스키마·상태값 변화 없음.
## Requirement
- 시스템은 `trex-core sync [--portfolio-id <pid> | --all]` 서브커맨드를 제공해야 한다.
- sync는 portfolio-hub 유니버스에 있어 슬롯이 생성된 종목만 대상으로 한다. 브로커에만 있고 슬롯이 없는 종목은 sync가 건드리지 않고 unmanaged 경고를 로그에 남긴다(자동 슬롯 생성 금지).
- sync 실행 시 대상 슬롯마다 브로커 잔고(`BrokerPort.get_balance()`)를 조회하여 슬롯 qty를 브로커 수량으로 갱신해야 한다. 브로커 수량 > 0이고 슬롯이 INACTIVE이면 **INACTIVE→HOLDING 전이(actor=sync, reason=onboarding/reconcile_sync)**를 수행해야 한다. 이 전이는 OQ-A 승인으로 `ALLOWED_TRANSITIONS`에 추가되는 새 엣지를 사용하며 일반 전략 진입 경로와 구분된다.
- portfolio-hub WAC read 포트(FR-7: **portfolio-hub dcy-008 / REQ-043**, `GET /v1/portfolios/{id}/holdings/cost-basis`)가 연결되어 있으면, sync 시 보유 평단(WAC)을 읽어 슬롯 avg_price에 seed해야 한다. 포트가 없거나 조회 실패 시 avg_price seed를 건너뛰고 WARN 로그를 남긴다(graceful degrade).
- sync 후 슬롯 qty == 브로커 수량이면 `ReconcileWarningStore.clear_warned(slot_id)`로 reconcile-warning을 해제해야 한다.
- sync 실행 전 before 상태, 실행 후 after 상태(슬롯 qty, 브로커 qty, warning 해제 여부)를 출력해야 한다.
- sync는 confirmation 프롬프트(`--yes` 스킵 가능)와 `--dry-run` 모드를 지원해야 한다. live 계좌에서는 `--yes --live` 이중 확인을 요구해야 한다.
- sync는 직접-DB 경로(pause/resume 방식)로 구현하며, 데몬 RPC를 거치지 않는다.
## Acceptance Criteria
1. Given cold-start 상태(슬롯 INACTIVE, 브로커 보유 qty > 0)에서 `trex-core sync --portfolio-id <pid>` 실행 시, When sync가 완료되면, Then 슬롯 qty = 브로커 qty이고 슬롯 상태가 HOLDING으로 전이되며 reconcile-warning이 해제된다(S-2, OQ-A 승인 전이).
2. Given 슬롯 qty ≠ 브로커 qty인 B 케이스에서 sync 실행 시, When sync가 완료되면, Then 슬롯 qty = 브로커 qty로 갱신되고 reconcile-warning이 해제된다.
3. Given 브로커에만 있고 슬롯이 없는 종목(슬롯 부재)에서 sync 실행 시, When sync가 실행되면, Then 슬롯이 자동 생성되지 않고 unmanaged 경고가 로그에 남는다.
4. Given portfolio-hub WAC read 포트(portfolio-hub dcy-008 / REQ-043 `GET /v1/portfolios/{id}/holdings/cost-basis`)가 연결되어 있을 때, When sync를 실행하면, Then 슬롯 avg_price에 WAC 값이 seed된다.
5. Given portfolio-hub WAC read 포트가 없거나 조회 실패 시, When sync를 실행하면, Then avg_price seed 없이 수량 갱신만 수행하고 WARN 로그를 남긴다(graceful degrade).
6. Given `--dry-run` 플래그로 sync 실행 시, When 명령이 실행되면, Then 슬롯 qty 변경 없이 before/after 예상치만 출력된다.
7. Given live 계좌에서 `--yes` 없이 sync 실행 시, When 명령이 실행되면, Then 오류 메시지와 함께 실행을 거부한다(live double-ack 게이트).
8. Given sync 실행 후 슬롯 qty가 여전히 브로커 수량과 다를 경우(갱신 실패 등), When sync가 완료되면, Then reconcile-warning이 해제되지 않는다.
9. Given `--all` 플래그로 sync 실행 시, When 명령이 실행되면, Then 인스턴스의 모든 B-warned 슬롯에 대해 sync가 실행된다.
10. Given INACTIVE→HOLDING 전이 시, When transition_log 또는 로그를 확인하면, Then actor 및 reason 필드에 sync/onboarding(또는 reconcile_sync)이 기록되어 일반 전략 진입 경로(INACTIVE→PENDING_BUY)와 구분된다(OQ-A actor 식별).
## Impacted Area
- Docs: `docs/operations.md` (cold-start onboarding 절차 신설), `docs/runtime-flows.md` (sync 흐름 추가)
- Modules:
- `trex_core/runtime/cli.py` (`sync` 서브커맨드 추가, `_build_parser`, `_cmd_sync`)
- `trex_core/application/reconciliation.py` (sync 로직 또는 별도 `sync_slot_to_broker` 함수 — batch design에서 결정)
- `trex_core/application/ports.py` 또는 `application/portfolio.py` (WAC read 포트 의존 명시)
- `trex_core/adapters/portfolio/` (WAC read 어댑터 — portfolio-hub FR-7 REQ 선행 의존)
- Tests:
- `tests/application/test_sync.py` 또는 `tests/integration/test_sync.py` (cold-start onboarding, warning 해제, unmanaged 슬롯 처리, dry-run, WAC seed 유무)
- `tests/runtime/test_cli.py` (sync 서브커맨드 인수 파싱, 확인 프롬프트, live double-ack)
## Notes
- **FR-7 의존 구체화(OQ-A 팀장 결정)**: portfolio-hub WAC read 엔드포인트는 **portfolio-hub dcy-008 / REQ-043**, `GET /v1/portfolios/{id}/holdings/cost-basis`. 2026-06-25 confirm-discovery 완료. 가용 시 avg_price seed, 미가용/실패 시 수량만 갱신 + WARN(graceful degrade). 구현 시 portfolio-hub REQ-043 완료 여부 확인 필요.
- **INACTIVE→HOLDING 전이 엣지 추가(OQ-A 팀장 승인)**: `state.py:ALLOWED_TRANSITIONS`에 `(INACTIVE, HOLDING)` 엣지 추가가 승인되었다. 이 전이는 **actor=sync 또는 reconcile로 제한**되며 일반 전략 경로(INACTIVE→PENDING_BUY→HOLDING)는 유지된다. transition_log reason은 `onboarding` 또는 `reconcile_sync`류로 식별. **wire 무영향**: SlotState enum 5개(inactive/pending_buy/holding/pending_sell/error) 불변, 엣지만 추가이므로 slots RPC 스키마·상태값 변화 없음. batch design에서 `_BASE_TRANSITIONS` 확장 또는 별도 `_SYNC_TRANSITIONS` 집합 구성을 결정한다.
- sync 대상 슬롯 결정 방법(portfolio_id 명시 vs all warned 슬롯 vs all INACTIVE 슬롯)은 batch design에서 구체화.
- dcy-034 FR-3, OQ-2/3, OQ-A(팀장 2026-06-25 confirm), R-1 대응.
## Change Log
### CHG-20260625-02
- Date: 2026-06-25
- Author: trex-core-dev
#### Change Summary
- REQ-105 **Proposed → Approved** (confirm-req, 팀장 2026-06-25).
- OQ-A 결정 반영: INACTIVE→HOLDING 전이 엣지 추가 승인(actor=sync/reconcile 제한, wire 무영향 명시).
- FR-7 의존 구체화: portfolio-hub dcy-008 / REQ-043 (`GET /v1/portfolios/{id}/holdings/cost-basis`) 로 참조 갱신.
- AC-10 신규 추가(전이 actor 식별).
#### Intent
- 팀장 confirm-req 결정(OQ-A 승인 + FR-7 참조 구체화)을 REQ에 반영.
#### Acceptance Criteria Delta
- Added: AC-10 신규(INACTIVE→HOLDING 전이 actor/reason 식별).
- Updated: AC-1(OQ-A 전이 명시), AC-4(FR-7 참조 구체화), AC-5(graceful degrade 명시).
- Removed: 없음.
#### Impacted Area Delta
- Notes: FR-7 참조 및 전이 엣지 추가 내용 구체화.
- Modules: `trex_core/domain/slot/state.py` — `ALLOWED_TRANSITIONS`에 `(INACTIVE, HOLDING)` 엣지 추가 필요(batch implementation 단계).
- Tests: AC-10 actor 식별 테스트 신규.
#### Delivery Trace Delta
- Batches: 미정 (suggest-batch-reqs 이후)
- Releases: 미정
#### Revalidation Impact
- Reverification Needed: no
- Existing Implementation Invalidated: no
- Status Recommendation: Approved
- Follow-up Action: batch design에서 state.py 전이 집합 확장 방식 결정 및 actor 제한 구현 방안 확정.
#### Validation Plan
- cold-start onboarding 시나리오 테스트 pass / INACTIVE→HOLDING 전이 actor 식별 테스트 pass / warning 해제 확인 / unmanaged 슬롯 자동 생성 없음 테스트 pass / FR-7 graceful degrade 테스트 pass.
### CHG-20260625-01
- Date: 2026-06-25
- Author: trex-core-dev
#### Change Summary
- REQ-105 신규 생성 (Proposed) — dcy-034 FR-3 대응, draft-req 단계.
#### Intent
- cold-start 시 운영자가 안전하게 슬롯을 브로커에 맞춰 onboarding하는 표준 CLI 경로 신설.
#### Acceptance Criteria Delta
- Added: AC-1~9 전부 신규.
- Updated: 없음.
- Removed: 없음.
#### Impacted Area Delta
- Docs: operations.md 신설, runtime-flows.md 갱신.
- Modules: cli.py, reconciliation.py.
- Tests: sync 통합 테스트 신규.
#### Delivery Trace Delta
- Batches: 미정
- Releases: 미정
#### Revalidation Impact
- Reverification Needed: no (신규 REQ)
- Existing Implementation Invalidated: no
- Status Recommendation: keep-current
- Follow-up Action: INACTIVE→HOLDING 전이표 추가 여부 팀장 확인 후 batch design 진행.
#### Validation Plan
- cold-start onboarding 시나리오 테스트 pass / warning 해제 확인 / unmanaged 슬롯 자동 생성 없음 테스트 pass.
@@ -0,0 +1,111 @@
# req-106: trex-core verify 명령 — C 불일치 슬롯 재대조 + warning 해제
- Status: Approved
- Type: Interface
- Priority: High
- Owner: trex-core-dev
## Intent
- 운영자가 portfolio-hub CLI로 원장을 정정한 뒤 `trex-core verify [--portfolio-id <pid>]` 명령으로 **C 불일치(원장↔슬롯) 차단 슬롯을 재대조**하여, 일치 시 warning을 해제하고 불일치 시 사유와 함께 해제를 거부한다.
- dcy-034 FR-4, OQ-2/5, **OQ-C 확정** 반영: read-중심 명령(슬롯 수량 변경 없음), 강제 해제(force-clear) 없음.
- 재대조 로직은 현행 `reconcile_positions`(브로커 경유 2-대조)를 재사용한다(OQ-5).
- **verify는 C 케이스(원장↔슬롯 수량 불일치) 전용**이다. B 케이스(슬롯↔브로커 수량 불일치)는 sync 명령(REQ-105)이 해소 경로이며 verify 범위에 포함되지 않는다(OQ-C 확정).
## Requirement
- 시스템은 `trex-core verify [--portfolio-id <pid>]` 서브커맨드를 제공해야 한다.
- verify는 대상 슬롯(portfolio_id 기반)에 대해 `reconcile_positions`를 다시 실행해(브로커=정본, 원장↔브로커 대조) 일치 여부를 판정해야 한다.
- 대조 결과 일치(원장 수량 == 브로커 수량)이면 `ReconcileWarningStore.clear_warned(slot_id)` 로 reconcile-warning을 해제하고 "해제됨" 메시지를 출력해야 한다.
- 대조 결과 불일치이면 warning을 해제하지 않고 불일치 사유(원장 수량, 브로커 수량, 차이)를 출력하고 비-0 종료코드를 반환해야 한다(강제 해제 경로 없음).
- verify는 슬롯 qty를 변경하지 않는다(read-중심 — 슬롯 수량 변경 없음).
- verify는 C 케이스(case_code='C')로 warned된 슬롯만을 대상으로 한다. **B 케이스(슬롯↔브로커 수량 불일치)에 대한 해소는 sync 명령(REQ-105) 책임이며, verify는 B 케이스에 적용하지 않는다(OQ-C 확정, C 전용).**
## Acceptance Criteria
1. Given C 불일치로 차단된 슬롯에서 운영자가 portfolio-hub CLI로 원장을 정정하고 `trex-core verify --portfolio-id <pid>` 실행 시, When 원장 수량 == 브로커 수량이면, Then reconcile-warning이 해제되고 "해제됨" 메시지가 출력된다(S-3 1차).
2. Given C 불일치로 차단된 슬롯에서 `trex-core verify` 실행 시, When 원장 수량 ≠ 브로커 수량이면, Then reconcile-warning이 해제되지 않고 불일치 사유(원장qty, 브로커qty, 차이)가 출력되며 비-0 종료코드를 반환한다(S-3 2차, 강제 해제 없음).
3. Given verify 실행 시, When 어떤 경우에도, Then 슬롯 qty가 변경되지 않는다(read-중심 불변식).
4. Given reconcile-warning이 없는 슬롯에 대해 verify 실행 시, When 명령이 실행되면, Then 이미 해제 상태임을 알리는 메시지 출력 후 0 종료코드로 반환한다(idempotent).
5. Given `--json` 플래그로 verify 실행 시, When 명령이 실행되면, Then `{portfolio_id, slot_id, result: "cleared"|"rejected", hub_qty, broker_qty, reason?}` JSON이 stdout에 출력된다.
6. Given `trex-core verify` (--portfolio-id 없이) 실행 시, When 명령이 실행되면, Then 인스턴스의 모든 C-warned 슬롯에 대해 재대조를 수행하고 결과를 슬롯별로 출력한다.
## Impacted Area
- Docs: `docs/operations.md` (원장 정정 후 verify 절차 추가), `docs/runtime-flows.md` (verify 흐름 추가)
- Modules:
- `trex_core/runtime/cli.py` (`verify` 서브커맨드 추가)
- `trex_core/application/reconciliation.py` (`reconcile_positions` 재사용 또는 호출 래퍼 — batch design에서 결정)
- Tests:
- `tests/runtime/test_cli.py` (verify 서브커맨드 인수 파싱)
- `tests/application/test_verify.py` 또는 `tests/integration/test_verify.py` (일치→해제, 불일치→거부, read-중심 불변식, idempotent)
## Notes
- OQ-5 확정: verify의 재대조는 `reconcile_positions`(원장↔브로커 2-대조, 브로커=정본)를 재사용한다. 별도 대조 로직을 만들지 않는다.
- verify는 read-중심이므로 pause/resume의 live double-ack 게이트는 불필요하다. --yes, --live 옵션이 필요 없다.
- **OQ-C 확정: verify는 C 전용**. B 케이스(슬롯↔브로커 수량 불일치)는 sync(REQ-105)로 해소한다. verify가 B-warned 슬롯 ID로 호출되면 "C 케이스 대상 아님" 안내 후 0 종료코드를 반환한다(batch design에서 메시지 확정).
- dcy-034 FR-4, OQ-2/5, OQ-C(팀장 2026-06-25 confirm), S-3 대응.
## Change Log
### CHG-20260625-02
- Date: 2026-06-25
- Author: trex-core-dev
#### Change Summary
- REQ-106 **Proposed → Approved** (confirm-req, 팀장 2026-06-25).
- OQ-C 결정 반영: verify = C 케이스(원장↔슬롯) 전용 확정. B 케이스는 sync(REQ-105) 책임. Intent, Requirement, Notes에 "C 전용, B는 sync 책임" 명시.
#### Intent
- 팀장 confirm-req 결정(OQ-C 확정: verify는 C 전용)을 REQ에 반영.
#### Acceptance Criteria Delta
- Added: 없음.
- Updated: 없음(기존 AC는 이미 C 케이스 중심으로 작성됨).
- Removed: 없음.
#### Impacted Area Delta
- Notes: OQ-C 확정 및 B-warned 슬롯 호출 시 처리 방침 추가.
- Modules: cli.py verify 서브커맨드 — B-warned 슬롯 필터링 로직 추가 필요.
#### Delivery Trace Delta
- Batches: 미정 (suggest-batch-reqs 이후)
- Releases: 미정
#### Revalidation Impact
- Reverification Needed: no
- Existing Implementation Invalidated: no
- Status Recommendation: Approved
- Follow-up Action: batch design에서 B-warned 슬롯 필터링 메시지 확정.
#### Validation Plan
- 일치→해제, 불일치→거부 시나리오(C 케이스) 테스트 pass / B-warned 슬롯에 verify 적용 시 "대상 아님" 처리 테스트 pass / 슬롯 qty 불변 검증 / 기존 reconcile_positions 회귀 pass.
### CHG-20260625-01
- Date: 2026-06-25
- Author: trex-core-dev
#### Change Summary
- REQ-106 신규 생성 (Proposed) — dcy-034 FR-4 대응, draft-req 단계.
#### Intent
- C 불일치 차단 해소를 위한 운영자 read-중심 재대조 경로 신설. 강제 해제 없이 재대조 일치 시에만 차단 해제.
#### Acceptance Criteria Delta
- Added: AC-1~6 전부 신규.
- Updated: 없음.
- Removed: 없음.
#### Impacted Area Delta
- Docs: operations.md, runtime-flows.md 갱신.
- Modules: cli.py, reconciliation.py.
- Tests: verify 시나리오 테스트 신규.
#### Delivery Trace Delta
- Batches: 미정
- Releases: 미정
#### Revalidation Impact
- Reverification Needed: no (신규 REQ)
- Existing Implementation Invalidated: no
- Status Recommendation: keep-current
- Follow-up Action: confirm-req 후 batch design.
#### Validation Plan
- 일치→해제, 불일치→거부 시나리오 테스트 pass / 슬롯 qty 불변 검증 / 기존 reconcile_positions 회귀 pass.
@@ -0,0 +1,105 @@
# req-108: 차단형 reconcile 비기능 요건 — 내구성·회귀 방지·자동 정정 금지·wire 계약 최소 침습
- Status: Approved
- Type: Non-Functional
- Priority: High
- Owner: trex-core-dev
## Intent
- dcy-034 NFR-1~4를 단일 REQ로 통합해, 차단형 reconcile 기능 전반에 걸쳐 적용되는 비기능 요건을 명시한다.
- 주요 불변식: (1) warning은 durable해야 함, (2) 단기 인스턴스 오발동 없음, (3) 자동 정정·자동 청산 금지, (4) wire 계약(slots RPC 스키마) 최소 침습.
## Requirement
- [NFR-1 내구성] reconcile-warning 차단 상태는 데몬 재시작 후에도 유지되어야 한다. in-memory overlay만으로 저장하지 않는다.
- [NFR-2 회귀 방지] 단기 인스턴스(M1/M2 라이브 orb+tsl) 정상(일치) 운영에서 신규 reconcile-warning 차단이 오발동하지 않아야 한다. 차단은 실제 수량 불일치가 있을 때만 발생한다.
- [NFR-3 자동 정정 금지] reconcile는 탐지+차단까지만 자동이고, 슬롯 수량·원장 변경은 운영자 명령(`sync`/`verify`)으로만 일어난다. 자동 무음 정정·자동 청산을 하지 않는다(issue #15 기조).
- [NFR-4 wire 계약 최소 침습] `SlotState` enum, `ALLOWED_TRANSITIONS`, slots RPC(`trex.slots.req`) 기존 필드는 변경하지 않는다. 신규 노출(`reconcile_warned` 필드)은 additive only로 추가하며, 기존 클라이언트(trex-orb-v1, trex-tsl-v1)가 신규 필드를 무시해도 동작이 깨지지 않아야 한다.
## Acceptance Criteria
1. Given reconcile-warning이 기록된 상태에서 데몬을 재시작하면, When `ReconcileWarningStore.is_warned(slot_id)` 를 조회하면, Then True가 반환된다(NFR-1, durable).
2. Given 단기 인스턴스의 슬롯 qty == 브로커 qty인 정상 시나리오에서, When boot/일일 reconcile가 실행되면, Then ReconcileWarningStore에 신규 행이 생기지 않는다(NFR-2, 회귀 0, S-4).
3. Given 불일치 탐지(B 또는 C) 후, When reconcile가 자동 실행되면, Then 슬롯 qty, 원장 레코드, 브로커 포지션에 자동 변경이 없다(NFR-3, 탐지+차단만 자동).
4. Given 기존 trex-orb-v1 또는 trex-tsl-v1 클라이언트가 `trex.slots.req` 응답에서 `reconcile_warned` 필드를 수신할 때, When 클라이언트가 해당 필드를 무시하면, Then 기존 동작이 유지된다(NFR-4, additive 하위 호환).
5. Given `domain/slot/state.py`에 새 SlotState 또는 새 전이가 추가되지 않으면, When slots RPC 응답을 생성하면, Then 기존 `status` 필드 값 집합이 유지된다(NFR-4, enum 불변).
6. Given 기존 `ALLOWED_TRANSITIONS`에 없는 전이를 `transit_slot`으로 시도하면, When SlotService가 처리하면, Then 기존 예외(InvalidTransitionError 등)가 발생한다(전이표 불변 확인).
## Impacted Area
- Docs: `docs/interface-contract.md` (additive 필드 명시, enum 불변 확인)
- Modules:
- `trex_core/domain/slot/state.py` (변경 없음 — 불변 확인 테스트)
- `trex_core/adapters/persistence/` (reconcile_warning_store durable 검증)
- Tests:
- `tests/domain/test_slot_state.py` (SlotState enum 불변, ALLOWED_TRANSITIONS 불변 회귀)
- `tests/application/test_reconciliation.py` (정상 케이스 오발동 없음 회귀, 자동 정정 없음 검증)
- `tests/application/test_messaging_handlers.py` (reconcile_warned additive 필드 하위 호환)
## Notes
- NFR-4의 slots RPC wire 계약 additive 변경은 REQ-104와 함께 delivery된다. 두 REQ의 AC가 일관되는지 batch design에서 확인한다.
- 단기 인스턴스 회귀(NFR-2/S-4)는 별도 픽스처를 사용한 통합 테스트로 검증한다: 단기 인스턴스 시나리오(당일 슬롯, 슬롯 qty == 브로커 qty)에서 boot reconcile를 실행하고 ReconcileWarningStore가 빈 상태임을 확인.
- dcy-034 NFR-1~4, S-4 대응.
## Change Log
### CHG-20260625-02
- Date: 2026-06-25
- Author: trex-core-dev
#### Change Summary
- REQ-108 **Proposed → Approved** (confirm-req, 팀장 2026-06-25).
#### Intent
- 팀장 confirm-req로 상태 승인. 내용 변경 없음(초안 그대로 승인).
#### Acceptance Criteria Delta
- Added: 없음.
- Updated: 없음.
- Removed: 없음.
#### Impacted Area Delta
- 없음.
#### Delivery Trace Delta
- Batches: 미정 (suggest-batch-reqs 이후)
- Releases: 미정
#### Revalidation Impact
- Reverification Needed: no
- Existing Implementation Invalidated: no
- Status Recommendation: Approved
- Follow-up Action: batch 편성 후 구현.
#### Validation Plan
- durable 재시작 검증 / 정상 케이스 오발동 없음 회귀 / SlotState enum+전이표 불변 회귀 / additive 하위 호환 테스트 pass.
### CHG-20260625-01
- Date: 2026-06-25
- Author: trex-core-dev
#### Change Summary
- REQ-108 신규 생성 (Proposed) — dcy-034 NFR-1~4 대응, draft-req 단계.
#### Intent
- 차단형 reconcile 도입이 기존 시스템(단기 인스턴스, wire 계약, 도메인 불변식)에 의도치 않은 영향을 주지 않도록 비기능 요건을 명시하고 검증 기준을 확정.
#### Acceptance Criteria Delta
- Added: AC-1~6 전부 신규.
- Updated: 없음.
- Removed: 없음.
#### Impacted Area Delta
- Docs: interface-contract.md 갱신 예정.
- Modules: 변경 없음(불변 확인 목적).
- Tests: 불변 회귀 테스트 신규.
#### Delivery Trace Delta
- Batches: 미정
- Releases: 미정
#### Revalidation Impact
- Reverification Needed: no (신규 REQ)
- Existing Implementation Invalidated: no
- Status Recommendation: keep-current
- Follow-up Action: confirm-req 후 REQ-102~107과 동일 batch 편성.
#### Validation Plan
- durable 재시작 검증 / 정상 케이스 오발동 없음 회귀 / SlotState enum+전이표 불변 회귀 / additive 하위 호환 테스트 pass.
+10 -2
View File
@@ -74,7 +74,7 @@
## Next Requirement ID
- Current: `REQ-102`
- Current: `REQ-109`
- Rule: `Requirement Register`에 있는 가장 큰 REQ 번호보다 정확히 1 커야 한다.
## Requirement Register
@@ -182,13 +182,21 @@
| REQ-099 | trex.alerts AMQP exchange 토폴로지 + 가산·격리 불변식 | Integration | Implemented | High | trex-core-dev | [req-099](./Integration/req-099_alarm-exchange-topology.md) |
| REQ-100 | trex-core 알람 emitter — CRITICAL code 발신 배선 | Integration | Implemented | High | trex-core-dev | [req-100](./Integration/req-100_core-alarm-emitter.md) |
| REQ-101 | 알람 발신 흐름 baseline 문서 정합 | Documentation | Implemented | Medium | trex-core-dev | [req-101](./Documentation/req-101_alarm-baseline-alignment.md) |
| REQ-102 | reconcile-warning durable store — slot_id/pid 키 별도 테이블 | Data | Approved | High | trex-core-dev | [req-102](./Data/req-102_reconcile-warning-durable-store.md) |
| REQ-103 | 차단형 reconcile — B/C 불일치 슬롯 reconcile-warning 전이 | Integration | Approved | High | trex-core-dev | [req-103](./Integration/req-103_blocking-reconcile-b-c-cases.md) |
| REQ-104 | 전략 차단 게이트 — pause ∨ reconcile-warning OR 게이트 (안전망 예외) | Interface | Approved | High | trex-core-dev | [req-104](./Interface/req-104_reconcile-warning-strategy-gate.md) |
| REQ-105 | trex-core sync 명령 — 슬롯 수량을 브로커에 맞춰 갱신 + warning 해제 (INACTIVE→HOLDING OQ-A) | Interface | Approved | High | trex-core-dev | [req-105](./Interface/req-105_sync-cli-command.md) |
| REQ-106 | trex-core verify 명령 — C 불일치 슬롯 재대조 + warning 해제 (C 전용 OQ-C) | Interface | Approved | High | trex-core-dev | [req-106](./Interface/req-106_verify-cli-command.md) |
| REQ-107 | 차단/해제 전이 식별 로깅 + 고영향 불일치 알람 | Exception | Approved | High | trex-core-dev | [req-107](./Exception/req-107_blocking-reconcile-logging-and-alarm.md) |
| REQ-108 | 차단형 reconcile 비기능 요건 — 내구성·회귀 방지·자동 정정 금지·wire 계약 최소 침습 | Non-Functional | Approved | High | trex-core-dev | [req-108](./Non-Functional/req-108_reconcile-blocking-regression-and-nfr.md) |
## Recent Change Log Summary
- 2026-06-25 :: REQ-102~108 **Proposed → Approved** (confirm-req, 팀장): dcy-034 OQ-A/B/C 결정 + FR-7 참조 구체화 반영. **OQ-A**: REQ-105에 INACTIVE→HOLDING 전이 엣지 추가 승인(actor=sync/reconcile 제한, wire 무영향 — enum 5개 불변·엣지만 추가), AC-10 신규, FR-7 → portfolio-hub dcy-008/REQ-043(`GET /v1/portfolios/{id}/holdings/cost-basis`) 구체 참조 갱신. **OQ-B**: REQ-104에 차단 예외 명시 — 내부 안전망(safety-sell/watchdog/kill-switch)은 reconcile-warning 차단 우회, AC-2 갱신. **OQ-C**: REQ-106에 verify=C 전용 확정, B 케이스는 sync(REQ-105) 책임 명시. REQ-102·103·107·108은 초안 그대로 승인.
- 2026-06-25 :: REQ-102~108 **신규 생성(Proposed, draft-req dcy-034)**: 슬롯↔실계좌 차단형 reconcile + sync/verify 명령 — M3 cold-start. REQ-102(durable warning store), REQ-103(B/C 차단형 reconcile), REQ-104(pause∨warning OR 게이트), REQ-105(sync CLI), REQ-106(verify CLI), REQ-107(차단/해제 로깅+알람), REQ-108(NFR: 내구성·회귀·자동정정금지·wire계약최소침습). FR-7(portfolio-hub WAC read)은 portfolio-hub-dev 별도 REQ로 위임, trex-core REQ에는 의존 참조만 포함.
- 2026-06-21 :: REQ-098·099·100·101 **Approved → Implemented** (confirm-req-implemented, BAT-049 release-candidate, dcy-033): 알람 시스템 1단계 구현·검증 완료. 단위 608 passed/47 skipped/0 fail, 신규 AlarmEmitter 29 테스트, ruff clean. 독립 opus QC=PASS-WITH-NOTES(blocker 0) + 팀장 실인프라 e2e(trex.alerts 발행 → trex-notifier → 텔레그램 HTTP 200). 기존 topology 불변 확인. 잔여(non-blocker): reset.py 2 code 간접 검증.
- 2026-06-21 :: REQ-098·099·100·101 **Proposed → Approved** (confirm-req, 팀장): dcy-033 확정 설계(trex.alerts AMQP·envelope 7필드·core CRITICAL 8종) 충실 반영, AC 측정가능, 가산·격리 불변식(098 AC-3/099 AC-2)·best-effort 비차단(099 AC-6/100 AC-2~4)·시크릿 격리(100 AC-5)·의존성역전/domain 순수성(100 AC-7/8) 강제 확인. emitter-in-adapter 경계·reset.py transport는 batch design 확정. **delivery는 첫 tsl REL(M2) 이후 큐잉.**
- 2026-06-21 :: **BAT-048 confirm-batch-verification**(팀장): REQ-095·096 **Approved → Implemented**. 구현=`execution.py` `_resolve_fill_price` 단일화(application) + `_record_ledger` resolved_price + skip+강WARN. 검증=신규 21 단위 테스트(매수 16+매도 5), **전체 575 passed/47 skipped/0 fail**(팀장 독립 재실행) + ruff clean. 독립 opus QC=PASS-WITH-NOTES → NOTE-1(ruff 2건)·NOTE-2(매도 경로 테스트) 정정 완료. wire/LedgerTrade 스키마 불변(AC-5). REQ-097=스파이크 Implemented.
- 2026-06-21 :: **BAT-048 design review**(팀장+사장님): D-1 백필 지점=application 단일화·D-2 폴백=skip+강WARN **팀장 승인**. **D-3 사장님 결정: 우선 백필+WARN 로깅(REQ-095/096)만 구현, 알람은 BAT-048 완료 후 별도 진행**. REQ-097 스파이크 산출물(design.md) 제출로 **Implemented**(후보 A 권고). BAT-048 구현 범위=REQ-095+096.
- 2026-06-21 :: REQ-095·096·097 **Proposed → Approved** (confirm-req, 팀장): 세 REQ가 dcy-032 FR-1~4·NFR-1~3을 충실히 반영, AC 측정 가능, design Deferred 항목(백필 지점·지정가 부재 폴백·알람 채널) 명시 확인. REQ-095 AC-6(지정가 부재 폴백)은 design 확정 후 구체화(사장님 합의 deferral).
- 2026-06-16 :: REQ-083 신규 생성(Proposed, draft-req dcy-030): KRX 호가단위(tick) 산출 유틸 — 가격→tick 순수 함수(2023.1.25~ 구간표) + floor/ceil 배수 헬퍼. 주식 전용(OQ-1). REQ-070 슬리피지 스냅이 소비.
- 2026-06-16 :: REQ-070 change-req (CHG-20260616-01, dcy-030/issue #28): 슬리피지 실효 지정가에 KRX 호가단위 스냅 추가 + 반올림 방향 전환(체결 보장 → **상한 준수**: 매수 내림/매도 올림) + band<1tick 하한/상한 보장. 기존 int(ceil/floor) 무스냅 구현 무효화 → Implemented → **Approved** 되돌림. 신규 AC-7~10, AC-1·2 갱신. dcy-030 batch에서 재구현·검증.
@@ -0,0 +1,595 @@
"""Blocking reconcile B/C cases + gate tests (REQ-103, REQ-104, REQ-107, REQ-108, BAT-050)."""
from __future__ import annotations
import logging
import pytest
from trex_core.application.broker_port import BalanceItem
from trex_core.application.intents import BuyIntent, IntentService, SellIntent
from trex_core.application.messaging import RpcRequest
from trex_core.application.messaging_handlers import make_slots_rpc_handler
from trex_core.application.portfolio import (
InMemoryPauseStore,
InMemoryReconcileWarningStore,
PortfolioItem,
SnapshotStore,
slot_to_dict,
)
from trex_core.application.reconciliation import (
reconcile_core_holdings,
reconcile_positions,
)
from trex_core.application.ports import IntentStore
from trex_core.domain.slot import SlotService, SlotState
from trex_core.domain.slot.in_memory_repository import InMemorySlotRepository
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
class FakeBroker:
def __init__(self, balances):
self._b = balances
def name(self): return "fake"
def submit_order(self, req): ...
def poll_fill(self, *args, **kw): ...
def cancel_order(self, *args, **kw): ...
def get_balance(self): return list(self._b)
class InMemoryIntentStore:
"""Minimal in-memory intent store for tests."""
def __init__(self):
self._db: dict = {}
def try_insert(self, intent_id, intent_type, payload):
if intent_id in self._db:
return False
self._db[intent_id] = {"status": None, "slot_id": None, "reason": None}
return True
def get(self, intent_id):
rec = self._db.get(intent_id)
if rec is None:
return None
class R:
def __init__(self, d): self.__dict__.update(d)
r = R(rec); r.intent_id = intent_id
return r
def finalize(self, intent_id, status, slot_id, reason):
self._db[intent_id] = {"status": status, "slot_id": slot_id, "reason": reason}
def _make_holding_slot(repo, svc, instance_key="default", portfolio_id="pf-A", symbol="005930", qty=10):
"""Helper: creates universe, puts slot in HOLDING state with given qty."""
repo.reconcile_universe(instance_key, {portfolio_id: symbol})
slot = repo.find_slot_by_portfolio(instance_key, portfolio_id)
pending = svc.transit_slot(
slot.slot_id, SlotState.INACTIVE, SlotState.PENDING_BUY,
reason="buy", actor="test", symbol=symbol,
)
holding = svc.transit_slot(
pending.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
reason="filled", actor="test", avg_price=100.0, qty=float(qty),
)
return holding
def _store_with(items):
store = SnapshotStore()
store.swap(items)
return store
# ===========================================================================
# REQ-103 AC-1: B case (slot qty != broker qty) => warn_store.set_warned(case_code='B')
# ===========================================================================
def test_reconcile_core_holdings_b_case_sets_warned():
repo = InMemorySlotRepository()
svc = SlotService(repo)
warn_store = InMemoryReconcileWarningStore()
slot = _make_holding_slot(repo, svc, qty=10)
# Broker has different qty (5 != 10) => B case
broker = FakeBroker([BalanceItem(symbol="005930", hldg_qty=5)])
decisions = reconcile_core_holdings(
slot_repo=repo, slot_service=svc, broker=broker,
instance_key="default", warn_store=warn_store,
)
slot_id_str = str(slot.slot_id)
assert decisions[slot_id_str] == "qty_warning"
assert warn_store.is_warned(slot_id_str) is True
# REQ-103 AC-1: B case stores case_code='B'
def test_reconcile_core_holdings_b_case_code():
repo = InMemorySlotRepository()
svc = SlotService(repo)
warn_store = InMemoryReconcileWarningStore()
slot = _make_holding_slot(repo, svc, qty=10)
broker = FakeBroker([BalanceItem(symbol="005930", hldg_qty=3)])
reconcile_core_holdings(
slot_repo=repo, slot_service=svc, broker=broker,
instance_key="default", warn_store=warn_store,
)
assert warn_store.list_warned() == {str(slot.slot_id)}
# REQ-103 AC-3: matching qty => warn_store NOT set
def test_reconcile_core_holdings_matching_qty_no_warn(caplog):
repo = InMemorySlotRepository()
svc = SlotService(repo)
warn_store = InMemoryReconcileWarningStore()
_make_holding_slot(repo, svc, qty=10)
broker = FakeBroker([BalanceItem(symbol="005930", hldg_qty=10)]) # match
decisions = reconcile_core_holdings(
slot_repo=repo, slot_service=svc, broker=broker,
instance_key="default", warn_store=warn_store,
)
assert warn_store.list_warned() == set() # S-4: no false positive
assert all(v == "ok" for v in decisions.values() if v != "unmanaged_warning")
# REQ-103 AC-4: A case (broker 0) => ERROR transition, NOT warn_store
def test_reconcile_core_holdings_a_case_error_not_warned():
repo = InMemorySlotRepository()
svc = SlotService(repo)
warn_store = InMemoryReconcileWarningStore()
slot = _make_holding_slot(repo, svc, qty=10)
broker = FakeBroker([]) # broker flat (qty=0)
decisions = reconcile_core_holdings(
slot_repo=repo, slot_service=svc, broker=broker,
instance_key="default", warn_store=warn_store,
)
slot_id_str = str(slot.slot_id)
assert decisions[slot_id_str] == "error"
assert warn_store.is_warned(slot_id_str) is False # A uses error, not warn_store
# REQ-103 AC-5: warn_store=None => backward compat, no exception
def test_reconcile_core_holdings_no_warn_store_backward_compat():
repo = InMemorySlotRepository()
svc = SlotService(repo)
_make_holding_slot(repo, svc, qty=10)
broker = FakeBroker([BalanceItem(symbol="005930", hldg_qty=5)]) # mismatch
decisions = reconcile_core_holdings(
slot_repo=repo, slot_service=svc, broker=broker,
instance_key="default",
warn_store=None, # no store
)
# Still returns qty_warning, no exception
assert any(v == "qty_warning" for v in decisions.values())
# ===========================================================================
# REQ-103 AC-2: C case (hub qty != broker qty) => warn_store.set_warned(case_code='C')
# ===========================================================================
def test_reconcile_positions_c_case_sets_warned():
repo = InMemorySlotRepository()
svc = SlotService(repo)
warn_store = InMemoryReconcileWarningStore()
slot = _make_holding_slot(repo, svc, qty=10, portfolio_id="pf-A")
store = _store_with([
PortfolioItem(portfolio_id="pf-A", symbol="005930", cash_balance=0, asset_quantity=10),
])
broker = FakeBroker([BalanceItem(symbol="005930", hldg_qty=7)]) # hub=10, broker=7 => C
decisions = reconcile_positions(
store=store, broker=broker,
slot_repo=repo, instance_key="default",
warn_store=warn_store,
)
assert decisions["pf-A"] == "warning"
assert warn_store.is_warned(str(slot.slot_id)) is True
# REQ-103 AC-3: C case matching => no warn
def test_reconcile_positions_c_case_matching_no_warn():
repo = InMemorySlotRepository()
svc = SlotService(repo)
warn_store = InMemoryReconcileWarningStore()
_make_holding_slot(repo, svc, qty=10, portfolio_id="pf-A")
store = _store_with([
PortfolioItem(portfolio_id="pf-A", symbol="005930", cash_balance=0, asset_quantity=10),
])
broker = FakeBroker([BalanceItem(symbol="005930", hldg_qty=10)]) # match
decisions = reconcile_positions(
store=store, broker=broker,
slot_repo=repo, instance_key="default",
warn_store=warn_store,
)
assert decisions["pf-A"] == "ok"
assert warn_store.list_warned() == set() # S-4: no false positive
# REQ-103 AC-5: C case with warn_store=None => backward compat
def test_reconcile_positions_no_warn_store_backward_compat():
repo = InMemorySlotRepository()
store = _store_with([
PortfolioItem(portfolio_id="pf-A", symbol="005930", cash_balance=0, asset_quantity=10),
])
broker = FakeBroker([BalanceItem(symbol="005930", hldg_qty=7)])
decisions = reconcile_positions(store=store, broker=broker, warn_store=None)
# in-memory warning still set on store
assert decisions["pf-A"] == "warning"
assert store.warnings() == {"pf-A"}
# ===========================================================================
# REQ-104 AC-1: reconcile-warned slot => buy intent rejected
# ===========================================================================
def test_intent_service_buy_rejected_when_reconcile_warned():
repo = InMemorySlotRepository()
svc = SlotService(repo)
warn_store = InMemoryReconcileWarningStore()
intent_store = InMemoryIntentStore()
repo.reconcile_universe("default", {"pf-A": "005930"})
slot = repo.find_slot_by_portfolio("default", "pf-A")
warn_store.set_warned(str(slot.slot_id), portfolio_id="pf-A", case_code="B")
intent_svc = IntentService(
svc, repo, intent_store,
instance_key="default",
warn_store=warn_store,
)
d = intent_svc.submit_buy(BuyIntent(
intent_id="b-001",
slot_id=slot.slot_id,
entry_price=100.0,
qty=10.0,
))
assert d.status == "rejected"
assert d.reason == "reconcile_warned"
# REQ-104 AC-2: reconcile-warned HOLDING slot => sell intent rejected (external path)
def test_intent_service_sell_rejected_when_reconcile_warned():
repo = InMemorySlotRepository()
svc = SlotService(repo)
warn_store = InMemoryReconcileWarningStore()
intent_store = InMemoryIntentStore()
slot = _make_holding_slot(repo, svc, qty=10)
warn_store.set_warned(str(slot.slot_id), portfolio_id="pf-A", case_code="B")
intent_svc = IntentService(
svc, repo, intent_store,
instance_key="default",
warn_store=warn_store,
)
d = intent_svc.submit_sell(SellIntent(
intent_id="s-001",
slot_id=slot.slot_id,
reason="strategy_exit",
))
assert d.status == "rejected"
assert d.reason == "reconcile_warned"
# REQ-104 AC-3: no warn, no pause => buy/sell admitted normally
def test_intent_service_no_warn_admitted_normally():
repo = InMemorySlotRepository()
svc = SlotService(repo)
warn_store = InMemoryReconcileWarningStore()
intent_store = InMemoryIntentStore()
repo.reconcile_universe("default", {"pf-A": "005930"})
slot = repo.find_slot_by_portfolio("default", "pf-A")
intent_svc = IntentService(
svc, repo, intent_store,
instance_key="default",
warn_store=warn_store,
)
d = intent_svc.submit_buy(BuyIntent(
intent_id="b-002",
slot_id=slot.slot_id,
entry_price=100.0,
qty=10.0,
))
assert d.status == "admitted"
# REQ-104: warn_store=None => gate skipped, backward compat
def test_intent_service_no_warn_store_backward_compat():
repo = InMemorySlotRepository()
svc = SlotService(repo)
intent_store = InMemoryIntentStore()
repo.reconcile_universe("default", {"pf-A": "005930"})
slot = repo.find_slot_by_portfolio("default", "pf-A")
intent_svc = IntentService(
svc, repo, intent_store,
instance_key="default",
warn_store=None, # no gate
)
d = intent_svc.submit_buy(BuyIntent(
intent_id="b-003",
slot_id=slot.slot_id,
entry_price=100.0,
qty=10.0,
))
assert d.status == "admitted"
# ===========================================================================
# REQ-104: safety-sell / kill-switch / watchdog bypass (OQ-B 확정)
# Internal path: SlotService.sell() / transit_slot() directly — NOT IntentService
# ===========================================================================
def test_safety_sell_bypasses_reconcile_warning_gate():
"""Safety-sell calls SlotService directly — reconcile_warned slot can still be sold."""
repo = InMemorySlotRepository()
svc = SlotService(repo)
warn_store = InMemoryReconcileWarningStore()
slot = _make_holding_slot(repo, svc, qty=10)
warn_store.set_warned(str(slot.slot_id), portfolio_id="pf-A", case_code="B")
# Safety-sell path: SlotService.sell() directly (no IntentService gate)
# Verify that transit_slot HOLDING -> PENDING_SELL succeeds regardless of warn_store.
updated = svc.transit_slot(
slot.slot_id,
SlotState.HOLDING,
SlotState.PENDING_SELL,
reason="safety_sell",
actor="trex-safety-sell",
)
assert updated.status == SlotState.PENDING_SELL
# reconcile_warned flag unchanged — sell went through
assert warn_store.is_warned(str(slot.slot_id)) is True
# ===========================================================================
# REQ-104 AC-4/5/6/7: slots RPC reconcile_warned field
# ===========================================================================
def _wire_with_warn(warned_slot_ids=None):
repo = InMemorySlotRepository()
svc = SlotService(repo)
repo.reconcile_universe("default", {"pf-A": "SYM-A", "pf-B": "SYM-B"})
store = SnapshotStore()
store.swap([
PortfolioItem(portfolio_id="pf-A", symbol="SYM-A", cash_balance=0, asset_quantity=0),
PortfolioItem(portfolio_id="pf-B", symbol="SYM-B", cash_balance=0, asset_quantity=0),
])
pause = InMemoryPauseStore()
warn_store = InMemoryReconcileWarningStore()
if warned_slot_ids:
for sid in warned_slot_ids:
warn_store.set_warned(sid, portfolio_id="pf-A", case_code="B")
handler = make_slots_rpc_handler(
repo,
snapshot_store=store,
pause_store=pause,
warn_store=warn_store,
)
return repo, svc, handler, pause, warn_store
def _req(filter=None):
return RpcRequest(payload={"filter": filter or "all"}, correlation_id="t")
# REQ-104 AC-5: reconcile_warned=True for warned slot
def test_slots_rpc_reconcile_warned_true():
repo, svc, handler, _, warn_store = _wire_with_warn()
slot_a = repo.find_slot_by_portfolio("default", "pf-A")
warn_store.set_warned(str(slot_a.slot_id), portfolio_id="pf-A", case_code="B")
resp = handler(_req())
rows = {r["portfolio_id"]: r for r in resp.payload["slots"]}
assert rows["pf-A"]["reconcile_warned"] is True
assert rows["pf-B"]["reconcile_warned"] is False
# REQ-104 AC-4: pause only => paused=True, reconcile_warned=False
def test_slots_rpc_paused_only():
repo, svc, handler, pause, _ = _wire_with_warn()
pause.pause("pf-A")
resp = handler(_req())
rows = {r["portfolio_id"]: r for r in resp.payload["slots"]}
assert rows["pf-A"]["paused"] is True
assert rows["pf-A"]["reconcile_warned"] is False
# REQ-104 AC-6: both pause + reconcile_warned
def test_slots_rpc_both_pause_and_reconcile_warned():
repo, svc, handler, pause, warn_store = _wire_with_warn()
slot_a = repo.find_slot_by_portfolio("default", "pf-A")
pause.pause("pf-A")
warn_store.set_warned(str(slot_a.slot_id), portfolio_id="pf-A", case_code="C")
resp = handler(_req())
rows = {r["portfolio_id"]: r for r in resp.payload["slots"]}
assert rows["pf-A"]["paused"] is True
assert rows["pf-A"]["reconcile_warned"] is True
# REQ-104 AC-7: warn_store=None => reconcile_warned=False (backward compat, NFR-4)
def test_slots_rpc_no_warn_store_reconcile_warned_false():
repo = InMemorySlotRepository()
repo.reconcile_universe("default", {"pf-A": "SYM"})
handler = make_slots_rpc_handler(repo, warn_store=None)
resp = handler(_req())
for row in resp.payload["slots"]:
assert row["reconcile_warned"] is False
# REQ-104 AC-8: existing 'warned' field unchanged
def test_slots_rpc_existing_warned_field_unchanged():
"""warned field (slot qty vs hub asset_quantity divergence) must not be affected."""
repo = InMemorySlotRepository()
svc = SlotService(repo)
repo.reconcile_universe("default", {"pf-A": "SYM"})
store = SnapshotStore()
store.swap([
PortfolioItem(portfolio_id="pf-A", symbol="SYM", cash_balance=0, asset_quantity=5),
])
slot_a = repo.find_slot_by_portfolio("default", "pf-A")
pending = svc.transit_slot(slot_a.slot_id, SlotState.INACTIVE, SlotState.PENDING_BUY,
reason="buy", actor="test", symbol="SYM")
svc.transit_slot(pending.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
reason="filled", actor="test", avg_price=100.0, qty=10.0)
warn_store = InMemoryReconcileWarningStore()
handler = make_slots_rpc_handler(repo, snapshot_store=store, warn_store=warn_store)
resp = handler(RpcRequest(payload={"filter": "holding"}, correlation_id="t"))
row = resp.payload["slots"][0]
# slot.qty=10 != hub asset_quantity=5 => warned=True (existing field)
assert row["warned"] is True
# reconcile_warned is separate
assert row["reconcile_warned"] is False
# ===========================================================================
# REQ-107: logging fields
# ===========================================================================
def test_reconcile_core_holdings_b_case_logging(caplog):
repo = InMemorySlotRepository()
svc = SlotService(repo)
warn_store = InMemoryReconcileWarningStore()
slot = _make_holding_slot(repo, svc, qty=10)
broker = FakeBroker([BalanceItem(symbol="005930", hldg_qty=5)])
with caplog.at_level(logging.WARNING, logger="trex_core.application.reconciliation"):
reconcile_core_holdings(
slot_repo=repo, slot_service=svc, broker=broker,
instance_key="default", warn_store=warn_store,
)
log_text = caplog.text
assert "reconcile_warning set" in log_text
assert "case_code=B" in log_text
assert "broker_qty=5" in log_text
def test_reconcile_positions_c_case_logging(caplog):
repo = InMemorySlotRepository()
svc = SlotService(repo)
warn_store = InMemoryReconcileWarningStore()
_make_holding_slot(repo, svc, qty=10, portfolio_id="pf-A")
store = _store_with([
PortfolioItem(portfolio_id="pf-A", symbol="005930", cash_balance=0, asset_quantity=10),
])
broker = FakeBroker([BalanceItem(symbol="005930", hldg_qty=7)])
with caplog.at_level(logging.WARNING, logger="trex_core.application.reconciliation"):
reconcile_positions(
store=store, broker=broker,
slot_repo=repo, instance_key="default",
warn_store=warn_store,
)
log_text = caplog.text
assert "reconcile_warning set" in log_text
assert "case_code=C" in log_text
# ===========================================================================
# REQ-108: SlotState enum + ALLOWED_TRANSITIONS invariant (NFR-4)
# ===========================================================================
def test_slot_state_enum_unchanged():
"""SlotState enum has exactly the same 5 values as before BAT-050."""
from trex_core.domain.slot.state import SlotState
expected = {"inactive", "pending_buy", "holding", "pending_sell", "error"}
assert {s.value for s in SlotState} == expected
def test_allowed_transitions_unchanged():
"""ALLOWED_TRANSITIONS set must not have new entries from BAT-050."""
from trex_core.domain.slot.state import ALLOWED_TRANSITIONS, SlotState
# Canonical count: 7 base + 4 to_error + 2 from_error = 13
assert len(ALLOWED_TRANSITIONS) == 13
# Spot-check: no new reconcile-warning-related transition
assert (SlotState.INACTIVE, SlotState.HOLDING) not in ALLOWED_TRANSITIONS
# NFR-2: short-term instance normal scenario (slot qty == broker qty) => no warn
def test_short_term_instance_normal_no_warn():
"""M1/M2 daily slot matching scenario — no false positive blocking (S-4, NFR-2)."""
repo = InMemorySlotRepository()
svc = SlotService(repo)
warn_store = InMemoryReconcileWarningStore()
slot = _make_holding_slot(repo, svc, qty=10, portfolio_id="pf-A")
store = _store_with([
PortfolioItem(portfolio_id="pf-A", symbol="005930", cash_balance=0, asset_quantity=10),
])
broker = FakeBroker([BalanceItem(symbol="005930", hldg_qty=10)]) # perfect match
reconcile_positions(
store=store, broker=broker,
slot_repo=repo, instance_key="default",
warn_store=warn_store,
)
reconcile_core_holdings(
slot_repo=repo, slot_service=svc, broker=broker,
instance_key="default", warn_store=warn_store,
)
# No new warn_store entries
assert warn_store.list_warned() == set()
# NFR-3: reconcile does NOT auto-modify slot qty
def test_reconcile_no_auto_fix_slot_qty():
"""Reconcile must only detect and block — no auto-modification of slot qty."""
repo = InMemorySlotRepository()
svc = SlotService(repo)
warn_store = InMemoryReconcileWarningStore()
slot = _make_holding_slot(repo, svc, qty=10)
broker = FakeBroker([BalanceItem(symbol="005930", hldg_qty=5)])
reconcile_core_holdings(
slot_repo=repo, slot_service=svc, broker=broker,
instance_key="default", warn_store=warn_store,
)
# Slot qty must remain 10 — not auto-corrected to 5
updated_slot = repo.fetch_slot(slot.slot_id)
assert float(updated_slot.qty) == 10.0
# ===========================================================================
# slot_to_dict unit tests for reconcile_warned field
# ===========================================================================
def test_slot_to_dict_reconcile_warned_false_when_no_warn_store():
"""When warn_store is None, reconcile_warned=False (NFR-4 additive)."""
repo = InMemorySlotRepository()
svc = SlotService(repo)
slot = _make_holding_slot(repo, svc, qty=5)
row = slot_to_dict(slot, warn_store=None)
assert "reconcile_warned" in row
assert row["reconcile_warned"] is False
def test_slot_to_dict_reconcile_warned_true_when_warned():
repo = InMemorySlotRepository()
svc = SlotService(repo)
slot = _make_holding_slot(repo, svc, qty=5)
warn_store = InMemoryReconcileWarningStore()
warn_store.set_warned(str(slot.slot_id), portfolio_id="pf-A", case_code="B")
row = slot_to_dict(slot, warn_store=warn_store)
assert row["reconcile_warned"] is True
def test_slot_to_dict_paused_and_warned_independent():
"""paused and reconcile_warned are independent fields."""
repo = InMemorySlotRepository()
svc = SlotService(repo)
slot = _make_holding_slot(repo, svc, qty=5)
pause_store = InMemoryPauseStore()
pause_store.pause("pf-A")
warn_store = InMemoryReconcileWarningStore()
warn_store.set_warned(str(slot.slot_id), portfolio_id="pf-A", case_code="C")
row = slot_to_dict(slot, pause_store=pause_store, warn_store=warn_store)
assert row["paused"] is True
assert row["reconcile_warned"] is True
@@ -0,0 +1,72 @@
"""ReconcileWarningStore unit tests (REQ-102, BAT-050).
Tests InMemoryReconcileWarningStore (store port contract).
PostgreSQL adapter is tested by DB-skipped integration tests.
"""
from __future__ import annotations
import pytest
from trex_core.application.portfolio import InMemoryReconcileWarningStore
def _store():
return InMemoryReconcileWarningStore()
# AC-1 (REQ-102): set_warned records an entry; is_warned returns True.
def test_set_warned_is_warned_true():
store = _store()
store.set_warned(
"slot-1",
portfolio_id="pf-A",
case_code="B",
actor="reconcile",
reason="slot_qty=10 broker_qty=5",
)
assert store.is_warned("slot-1") is True
# AC-4 (REQ-102): clear_warned removes entry; is_warned returns False.
def test_clear_warned_returns_false():
store = _store()
store.set_warned("slot-1", portfolio_id="pf-A", case_code="B")
store.clear_warned("slot-1")
assert store.is_warned("slot-1") is False
# AC-3 (REQ-102): duplicate set_warned on same slot_id => upsert (single entry).
def test_set_warned_upsert_same_slot():
store = _store()
store.set_warned("slot-1", portfolio_id="pf-A", case_code="B", reason="first")
store.set_warned("slot-1", portfolio_id="pf-A", case_code="C", reason="second")
# After second set, is_warned still True — single entry (no duplicate row).
assert store.is_warned("slot-1") is True
assert store.list_warned() == {"slot-1"}
# AC-5 (REQ-102): list_warned returns set of warned slot_ids.
def test_list_warned_returns_set():
store = _store()
store.set_warned("slot-1", portfolio_id="pf-A", case_code="B")
store.set_warned("slot-2", portfolio_id="pf-B", case_code="C")
assert store.list_warned() == {"slot-1", "slot-2"}
# is_warned on unknown slot => False.
def test_is_warned_unknown_slot_false():
store = _store()
assert store.is_warned("nonexistent") is False
# clear_warned on unknown slot is a no-op (no exception).
def test_clear_warned_unknown_slot_noop():
store = _store()
store.clear_warned("nonexistent") # must not raise
assert store.list_warned() == set()
# list_warned on empty store => empty set.
def test_list_warned_empty():
store = _store()
assert store.list_warned() == set()
@@ -0,0 +1,12 @@
-- BAT-050 / REQ-102: reconcile-warning durable store (dcy-034).
-- PK: slot_id (TEXT, UUID string). pause_store 동형 설계.
-- ON CONFLICT DO UPDATE: 동일 slot_id 재삽입 시 최신 값으로 갱신.
CREATE TABLE IF NOT EXISTS slot_reconcile_warning (
slot_id TEXT PRIMARY KEY,
portfolio_id TEXT NOT NULL,
case_code TEXT NOT NULL,
actor TEXT NOT NULL DEFAULT 'reconcile',
reason TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
+7 -1
View File
@@ -1,6 +1,12 @@
"""portfolio-hub read adapters (REQ-027, dcy-005)."""
from trex_core.adapters.portfolio.hub_read import PortfolioHubReadAdapter
from trex_core.adapters.portfolio.pause_store import PostgreSQLPauseStore
from trex_core.adapters.portfolio.reconcile_warning_store import PostgreSQLReconcileWarningStore
from trex_core.adapters.portfolio.stub_read import StubPortfolioRead
__all__ = ["PortfolioHubReadAdapter", "PostgreSQLPauseStore", "StubPortfolioRead"]
__all__ = [
"PortfolioHubReadAdapter",
"PostgreSQLPauseStore",
"PostgreSQLReconcileWarningStore",
"StubPortfolioRead",
]
@@ -0,0 +1,69 @@
"""PostgreSQL-backed durable reconcile-warning store (REQ-102, BAT-050).
pause_store.py와 동형 설계. PK: slot_id. case_code: 'B' | 'C'.
Survives daemon restart (dcy-034 NFR-1).
"""
from __future__ import annotations
from datetime import datetime, timezone
from typing import Any
from trex_core.adapters.persistence.postgresql import _require_psycopg
class PostgreSQLReconcileWarningStore:
"""`slot_reconcile_warning` table CRUD. slot_id PK is the gate (REQ-102)."""
def __init__(self, dsn: str, *, psycopg_module: Any = None) -> None:
self._psycopg = _require_psycopg(psycopg_module)
self._dsn = dsn
def set_warned(
self,
slot_id: str,
*,
portfolio_id: str,
case_code: str,
actor: str = "reconcile",
reason: str = "",
) -> None:
now = datetime.now(tz=timezone.utc)
with self._psycopg.connect(self._dsn, autocommit=False) as conn:
with conn.cursor() as cur:
cur.execute(
"INSERT INTO slot_reconcile_warning "
"(slot_id, portfolio_id, case_code, actor, reason, created_at, updated_at) "
"VALUES (%s, %s, %s, %s, %s, %s, %s) "
"ON CONFLICT (slot_id) DO UPDATE "
"SET portfolio_id = EXCLUDED.portfolio_id, "
" case_code = EXCLUDED.case_code, "
" actor = EXCLUDED.actor, "
" reason = EXCLUDED.reason, "
" updated_at = EXCLUDED.updated_at",
(slot_id, portfolio_id, case_code, actor, reason, now, now),
)
conn.commit()
def clear_warned(self, slot_id: str) -> None:
with self._psycopg.connect(self._dsn, autocommit=False) as conn:
with conn.cursor() as cur:
cur.execute(
"DELETE FROM slot_reconcile_warning WHERE slot_id = %s",
(slot_id,),
)
conn.commit()
def is_warned(self, slot_id: str) -> bool:
with self._psycopg.connect(self._dsn) as conn:
with conn.cursor() as cur:
cur.execute(
"SELECT 1 FROM slot_reconcile_warning WHERE slot_id = %s LIMIT 1",
(slot_id,),
)
return cur.fetchone() is not None
def list_warned(self) -> set[str]:
with self._psycopg.connect(self._dsn) as conn:
with conn.cursor() as cur:
cur.execute("SELECT slot_id FROM slot_reconcile_warning")
return {row[0] for row in cur.fetchall()}
+52
View File
@@ -14,6 +14,11 @@ dcy-020 (BAT-030): admission is asset-centric only — the legacy pool path
cutover. Buy is keyed by slot_id (REQ-061 canonical; portfolio_id is the
legacy dual-accept mapping) and admits FCFS under the `max_active_slots` cap
M when configured (no cap when unset).
BAT-050 / REQ-104: reconcile-warning gate added to _admit_buy/_admit_sell.
warn_store is Optional — when None, gate is skipped (backward compat).
Safety-sell / kill-switch / watchdog bypass this gate by design (OQ-B):
those paths call SlotService.sell() directly, not through IntentService.
"""
from __future__ import annotations
@@ -104,6 +109,7 @@ class IntentService:
instance_key: str = "default",
max_active_slots: Optional[int] = None,
default_order_timeout_sec: Optional[int] = None,
warn_store=None, # Optional[ReconcileWarningStore] — BAT-050 / REQ-104
) -> None:
self._svc = slot_service
self._repo = slot_repo
@@ -119,6 +125,9 @@ class IntentService:
# dcy-022 / REQ-068: default timeout when intent omits timeout_sec.
# None = OFF = indefinite wait (legacy behavior). Per-intent value overrides.
self._default_order_timeout_sec = default_order_timeout_sec
# BAT-050 / REQ-104: reconcile-warning gate store (Optional).
# When None, gate is skipped (backward compat, NFR-4).
self._warn_store = warn_store
# ------------------------------------------------------------
def lookup(self, intent_id: str) -> Optional[IntentDecision]:
@@ -176,6 +185,23 @@ class IntentService:
return IntentDecision(intent_id, "rejected", None, "duplicate_in_flight")
return IntentDecision(intent_id, rec.status, rec.slot_id, rec.reason)
def _check_reconcile_warned(self, slot_id) -> Optional[IntentDecision]:
"""BAT-050 / REQ-104: return rejected decision if slot is reconcile-warned.
Returns None if not warned (gate passes). The warn_store check is best-effort:
if the store raises, we allow the intent through (fail-open for resilience).
Safety-sell / kill-switch / watchdog bypass this gate — they call
SlotService.sell() directly without going through IntentService (OQ-B).
"""
if self._warn_store is None:
return None
try:
if self._warn_store.is_warned(str(slot_id)):
return None # placeholder — intent_id unknown here; caller provides it
except Exception: # noqa: BLE001 - fail-open
pass
return None # not warned (or store error — fail-open)
def _admit_buy(self, intent: BuyIntent) -> IntentDecision:
"""dcy-020 / REQ-059·REQ-061 + dcy-021/REQ-066: activate or size up the
asset's permanent slot.
@@ -207,6 +233,19 @@ class IntentService:
return IntentDecision(intent.intent_id, "rejected", None, "slot_id_or_portfolio_required")
if slot is None:
return IntentDecision(intent.intent_id, "rejected", None, miss_reason)
# BAT-050 / REQ-104: reconcile-warning gate (external strategy intent only).
# Safety-sell / kill-switch / watchdog bypass this gate by design (OQ-B):
# those paths call SlotService.sell() directly.
if self._warn_store is not None:
try:
if self._warn_store.is_warned(str(slot.slot_id)):
return IntentDecision(
intent.intent_id, "rejected", None, "reconcile_warned"
)
except Exception: # noqa: BLE001 - fail-open
pass
# dcy-021: a buy on a HOLDING slot is a position-sizing increase.
is_increase = slot.status is SlotState.HOLDING
if slot.status in (SlotState.PENDING_BUY, SlotState.PENDING_SELL):
@@ -260,6 +299,19 @@ class IntentService:
slot = self._repo.fetch_slot(intent.slot_id)
if slot is None:
return IntentDecision(intent.intent_id, "rejected", None, "slot_not_found")
# BAT-050 / REQ-104: reconcile-warning gate for external strategy sell intent.
# Internal safety-sell / kill-switch / watchdog bypass this gate: they call
# SlotService.sell() / transit_slot() directly without IntentService (OQ-B).
if self._warn_store is not None:
try:
if self._warn_store.is_warned(str(slot.slot_id)):
return IntentDecision(
intent.intent_id, "rejected", None, "reconcile_warned"
)
except Exception: # noqa: BLE001 - fail-open
pass
if slot.status is not SlotState.HOLDING:
return IntentDecision(
intent.intent_id, "rejected", None, f"slot_not_holding:{slot.status.value}"
@@ -16,6 +16,7 @@ from trex_core.application.intents import BuyIntent, IntentService, SellIntent
from trex_core.application.messaging import RpcRequest, RpcResponse
from trex_core.application.portfolio import (
PauseStore,
ReconcileWarningStore,
SnapshotStore,
slot_to_dict,
)
@@ -220,6 +221,7 @@ def make_slots_rpc_handler(
instance_key: str = "default",
snapshot_store: Optional[SnapshotStore] = None,
pause_store: Optional[PauseStore] = None,
warn_store: Optional[ReconcileWarningStore] = None,
watchdog_store: Optional[WatchdogStore] = None,
watchdog_timeout_sec: int = 120,
ledger_outbox=None,
@@ -261,12 +263,14 @@ def make_slots_rpc_handler(
watchdog_store.update(str(s.slot_id))
# Build merged slot rows (REQ-074)
# BAT-050 / REQ-104: warn_store passed to slot_to_dict for reconcile_warned field.
slot_rows = [
slot_to_dict(
s,
snapshot_store=snapshot_store,
watchdog_store=watchdog_store,
pause_store=pause_store,
warn_store=warn_store,
watchdog_timeout_sec=watchdog_timeout_sec,
)
for s in slots
+84 -5
View File
@@ -5,10 +5,13 @@ snapshot store + asset-selection service. Domain stays free of HTTP and
RabbitMQ deps (NFR-1).
The snapshot is split between:
- in-memory `SnapshotStore` universe + cash/position + warnings (process-local;
warning is automatic/temporary, reset on restart)
- durable `PauseStore` portfolio_id -> paused (Postgres; manual/persistent,
survives restart and daily refresh — REQ-032)
- in-memory `SnapshotStore` universe + cash/position + warnings (process-local;
warning is automatic/temporary, reset on restart)
- durable `PauseStore` portfolio_id -> paused (Postgres; manual/persistent,
survives restart and daily refresh — REQ-032)
- durable `ReconcileWarningStore` slot_id -> reconcile-warning (Postgres; automatic,
set by reconcile B/C cases, cleared by sync/verify
— REQ-102, dcy-034)
"""
from __future__ import annotations
@@ -246,6 +249,73 @@ class InMemoryKillSwitchStore:
self._excluded.discard((portfolio_id, trading_date))
# ---------------------------------------------------------------- reconcile-warning store (REQ-102)
# BAT-050 / dcy-034: durable reconcile-warning channel — distinct from pause (manual).
# Keyed by slot_id (TEXT UUID string). case_code: 'B' (slot↔broker qty mismatch)
# or 'C' (ledger↔broker mismatch). Survives restart (PostgreSQL-backed in production).
class ReconcileWarningStore(Protocol):
"""Durable reconcile-warning overlay — slot_id PK (REQ-102, dcy-034)."""
def set_warned(
self,
slot_id: str,
*,
portfolio_id: str,
case_code: str,
actor: str = "reconcile",
reason: str = "",
) -> None:
...
def clear_warned(self, slot_id: str) -> None:
...
def is_warned(self, slot_id: str) -> bool:
...
def list_warned(self) -> "set[str]":
...
class InMemoryReconcileWarningStore:
"""Process-local reconcile-warning store for tests + CI (REQ-102)."""
def __init__(self) -> None:
self._lock = threading.Lock()
# slot_id -> {"portfolio_id", "case_code", "actor", "reason"}
self._warned: dict[str, dict] = {}
def set_warned(
self,
slot_id: str,
*,
portfolio_id: str,
case_code: str,
actor: str = "reconcile",
reason: str = "",
) -> None:
with self._lock:
self._warned[slot_id] = {
"portfolio_id": portfolio_id,
"case_code": case_code,
"actor": actor,
"reason": reason,
}
def clear_warned(self, slot_id: str) -> None:
with self._lock:
self._warned.pop(slot_id, None)
def is_warned(self, slot_id: str) -> bool:
with self._lock:
return slot_id in self._warned
def list_warned(self) -> "set[str]":
with self._lock:
return set(self._warned.keys())
def slot_to_dict(
s,
@@ -253,6 +323,7 @@ def slot_to_dict(
snapshot_store: "Optional[SnapshotStore]" = None,
watchdog_store=None,
pause_store: "Optional[PauseStore]" = None,
warn_store: "Optional[ReconcileWarningStore]" = None,
watchdog_timeout_sec: int = 120,
) -> dict:
"""Merged slot row for trex.slots.req (REQ-073/074).
@@ -260,7 +331,7 @@ def slot_to_dict(
Carries slot/core state + hub asset data + watchdog + overlay flags.
Field-level authority: slot/core = slot_id/status/qty/avg_price/entry_price/
forced_close_at; hub = asset_quantity/cash_balance; watchdog = watchdog{};
overlay = paused/warned. strategy fields excluded (REQ-074 AC-5).
overlay = paused/warned/reconcile_warned. strategy fields excluded (REQ-074 AC-5).
"""
d = {
"slot_id": str(s.slot_id),
@@ -312,6 +383,14 @@ def slot_to_dict(
paused = s.portfolio_id in pause_store.list_paused()
d["paused"] = paused
# BAT-050 / REQ-104: reconcile_warned overlay (ReconcileWarningStore) — additive field.
# Bulk list_warned() called once per RPC (caller pre-fetches; see make_slots_rpc_handler).
# warn_store=None → reconcile_warned=False (backward compatible, NFR-4).
reconcile_warned = False
if warn_store is not None:
reconcile_warned = str(s.slot_id) in warn_store.list_warned()
d["reconcile_warned"] = reconcile_warned
return d
+81 -13
View File
@@ -1,10 +1,15 @@
"""Position reconciliation between portfolio-hub and broker (REQ-031).
"""Position reconciliation between portfolio-hub and broker (REQ-031, REQ-103).
The broker account is single (invariant B) so portfolio-hub quantities are
aggregated to `symbol` before being compared with `BrokerPort.get_balance()`.
Mismatches flip the asset's `warning` overlay; a subsequent successful match
clears it automatically (in-memory only — pause is the durable channel for
manual holds).
BAT-050 / REQ-103: B-case (slot qty mismatch) and C-case (ledger mismatch)
now also set a durable reconcile-warning via ReconcileWarningStore (slot_id
keyed). The in-memory warning overlay is kept for backward compat; the durable
store is additive and Optional (None => warn-log-only, backward compat).
"""
from __future__ import annotations
@@ -13,7 +18,7 @@ from typing import Optional
from trex_core.application.alarm_emitter import AlarmEmitter
from trex_core.application.broker_port import BrokerPort
from trex_core.application.portfolio import SnapshotStore
from trex_core.application.portfolio import ReconcileWarningStore, SnapshotStore
from trex_core.domain.slot.state import SlotState
_log = logging.getLogger(__name__)
@@ -26,16 +31,24 @@ def reconcile_core_holdings(
broker: BrokerPort,
instance_key: str,
alarm_emitter: Optional[AlarmEmitter] = None,
warn_store: Optional[ReconcileWarningStore] = None,
) -> dict[str, str]:
"""dcy-020 / REQ-062 (BAT-029): surface core-slot holding ↔ broker divergence.
"""dcy-020 / REQ-062 (BAT-029) + REQ-103 (BAT-050): surface core-slot holding
vs broker divergence and set durable reconcile-warning for B case.
Broker balance is the reconcile ground truth. Decisions (no silent auto-fix,
no auto-liquidation — issue #15):
- A. core holding but broker flat (qty 0) -> slot to `error` + WARN (operator resolve)
- C. both hold but qty differs -> WARN (mirror is non-authoritative)
- A. core holding but broker flat (qty 0) -> slot to `error` + WARN + CRITICAL alarm
- C. both hold but qty differs (B in REQ-103 naming) -> WARN + durable reconcile-warning
- B. broker holds, no core holding slot -> WARN (unmanaged position)
REQ-103 case codes:
- case_code='B': slot has holding but qty differs from broker (reconcile_core_holdings)
- case_code='C': ledger/hub qty differs from broker (reconcile_positions)
warn_store: Optional — when None, WARN-log-only (backward compat, REQ-103 AC-5).
Returns {key: 'error'|'qty_warning'|'ok'|'unmanaged_warning'} for telemetry.
(Liquidation qty = broker authoritative in execution dispatch is BAT-δ.)"""
"""
broker_qty: dict[str, int] = {
item.symbol: int(item.hldg_qty) for item in broker.get_balance()
}
@@ -65,15 +78,32 @@ def reconcile_core_holdings(
)
except Exception: # noqa: BLE001 - never let reconcile crash the loop
_log.exception("failed to error-quarantine slot %s", slot.slot_id)
elif slot.qty is not None and int(slot.qty) != bq: # C — qty mismatch
decisions[str(slot.slot_id)] = "qty_warning"
elif slot.qty is not None and int(slot.qty) != bq: # B case (REQ-103) — qty mismatch
slot_id_str = str(slot.slot_id)
decisions[slot_id_str] = "qty_warning"
# REQ-107: structured WARNING log for B case.
_log.warning(
"qty mismatch: slot=%s symbol=%s core=%s broker=%d (mirror non-authoritative)",
slot.slot_id, sym, slot.qty, bq,
"reconcile_warning set: slot_id=%s portfolio_id=%s symbol=%s "
"case_code=B broker_qty=%d slot_qty=%s actor=reconcile",
slot_id_str, slot.portfolio_id, sym, bq, slot.qty,
)
# REQ-103 / BAT-050: durable reconcile-warning (case_code='B').
if warn_store is not None:
try:
warn_store.set_warned(
slot_id_str,
portfolio_id=slot.portfolio_id or "",
case_code="B",
actor="reconcile",
reason=f"slot_qty={slot.qty} broker_qty={bq} symbol={sym}",
)
except Exception: # noqa: BLE001 - never let reconcile crash the loop
_log.exception(
"failed to set reconcile_warning for slot %s", slot.slot_id
)
else:
decisions[str(slot.slot_id)] = "ok"
for sym, bq in broker_qty.items(): # B — unmanaged broker position
for sym, bq in broker_qty.items(): # unmanaged broker position
if bq > 0 and sym not in matched:
decisions[f"broker:{sym}"] = "unmanaged_warning"
_log.warning(
@@ -83,11 +113,23 @@ def reconcile_core_holdings(
return decisions
def reconcile_positions(*, store: SnapshotStore, broker: BrokerPort) -> dict[str, str]:
"""Run one reconciliation pass.
def reconcile_positions(
*,
store: SnapshotStore,
broker: BrokerPort,
slot_repo=None,
instance_key: str = "default",
warn_store: Optional[ReconcileWarningStore] = None,
) -> dict[str, str]:
"""Run one reconciliation pass (REQ-031 + REQ-103 BAT-050).
Returns a `{portfolio_id: 'warning' | 'cleared' | 'ok'}` map for telemetry.
The map is also reflected onto `store` via `set_warning(...)`.
BAT-050 / REQ-103: when warn_store and slot_repo are provided, C-case mismatches
(ledger/hub qty vs broker) also set durable reconcile-warning on the corresponding
slot (portfolio_id -> slot lookup via slot_repo). When either is None, falls back
to in-memory warning only (backward compat, REQ-103 AC-5).
"""
broker_qty: dict[str, int] = {
item.symbol: int(item.hldg_qty) for item in broker.get_balance()
@@ -117,6 +159,32 @@ def reconcile_positions(*, store: SnapshotStore, broker: BrokerPort) -> dict[str
)
store.set_warning(pid, True)
decisions[pid] = "warning"
# REQ-103 / BAT-050: durable reconcile-warning for C case (case_code='C').
if warn_store is not None and slot_repo is not None:
try:
slot = slot_repo.find_slot_by_portfolio(instance_key, pid)
if slot is not None:
slot_id_str = str(slot.slot_id)
# REQ-107: structured WARNING log for C case.
_log.warning(
"reconcile_warning set: slot_id=%s portfolio_id=%s "
"symbol=%s case_code=C hub_qty=%d broker_qty=%d actor=reconcile",
slot_id_str, pid, symbol, hub_total, broker_total,
)
warn_store.set_warned(
slot_id_str,
portfolio_id=pid,
case_code="C",
actor="reconcile",
reason=(
f"hub_qty={hub_total} broker_qty={broker_total} "
f"symbol={symbol}"
),
)
except Exception: # noqa: BLE001
_log.exception(
"failed to set reconcile_warning for portfolio_id=%s", pid
)
else:
if was_warned:
store.set_warning(pid, False)
+16 -1
View File
@@ -4,6 +4,8 @@ Wakes at the configured KST time, fetches universe from PortfolioHubReadPort,
swaps the SnapshotStore, then runs reconciliation. Option D `*_after` writes
(REQ-030 AC-2/AC-3) are wired through `SnapshotStore.update_cash_position`
but disabled at the ledger layer until portfolio-hub#8 ships.
BAT-050 / REQ-103: reconcile now accepts warn_store for durable reconcile-warning.
"""
from __future__ import annotations
@@ -18,6 +20,7 @@ from trex_core.application.portfolio import (
DegradedReason,
PortfolioHubReadPort,
PortfolioHubUnavailableError,
ReconcileWarningStore,
SnapshotStore,
)
from trex_core.application.reconciliation import reconcile_positions
@@ -42,6 +45,7 @@ class SnapshotScheduler:
slot_service=None,
instance_key: str = "default",
alarm_emitter: Optional[AlarmEmitter] = None,
warn_store: Optional[ReconcileWarningStore] = None,
) -> None:
self._read = read_port
self._store = store
@@ -59,6 +63,8 @@ class SnapshotScheduler:
self._last_universe_size: Optional[int] = None
# dcy-033 / REQ-100: best-effort alarm emitter.
self._alarm_emitter = alarm_emitter
# BAT-050 / REQ-103: durable reconcile-warning store (Optional).
self._warn_store = warn_store
# ---- callable from a daemon thread loop --------------------------------
def run_forever(self, stop: threading.Event, *, tick_sec: float = 60.0) -> None:
@@ -124,7 +130,14 @@ class SnapshotScheduler:
self._store.swap(items)
try:
reconcile_positions(store=self._store, broker=self._broker)
# BAT-050 / REQ-103: pass warn_store + slot_repo for C-case durable warning.
reconcile_positions(
store=self._store,
broker=self._broker,
slot_repo=self._slot_repo,
instance_key=self._instance_key,
warn_store=self._warn_store,
)
except Exception: # noqa: BLE001
_log.exception("reconciliation pass failed")
if self._slot_repo is not None:
@@ -135,10 +148,12 @@ class SnapshotScheduler:
if self._slot_service is not None:
try:
from trex_core.application.reconciliation import reconcile_core_holdings
# BAT-050 / REQ-103: pass warn_store for B-case durable warning.
reconcile_core_holdings(
slot_repo=self._slot_repo, slot_service=self._slot_service,
broker=self._broker, instance_key=self._instance_key,
alarm_emitter=self._alarm_emitter, # dcy-033 / REQ-100
warn_store=self._warn_store, # BAT-050 / REQ-103
)
except Exception: # noqa: BLE001
_log.exception("core-holding divergence reconcile failed")
+13 -7
View File
@@ -41,6 +41,7 @@ from trex_core.adapters.persistence.postgresql import (
from trex_core.adapters.portfolio import (
PortfolioHubReadAdapter,
PostgreSQLPauseStore,
PostgreSQLReconcileWarningStore,
StubPortfolioRead,
)
from trex_core.adapters.portfolio.killswitch_store import PostgreSQLKillSwitchStore
@@ -158,13 +159,6 @@ class Daemon:
instance_key=config.instance_key,
strategy_state_store=self.strategy_state_store,
)
self.intent_service = IntentService(
self.slot_service, self.slot_repo, self.intent_store,
resolve_symbol=self._resolve_symbol,
instance_key=config.instance_key,
max_active_slots=config.max_active_slots, # dcy-020: asset-centric gate
default_order_timeout_sec=config.default_order_timeout_sec, # dcy-022
)
self.broker = _build_broker(config)
self.outbox = PostgreSQLLedgerOutbox(config.dsn)
# BAT-008: portfolio-hub read + snapshot store + durable pause + scheduler.
@@ -173,6 +167,16 @@ class Daemon:
# BAT-010/011: per-slot watchdog (snapshot RPC writer, safety-sell reader).
self.watchdog = WatchdogStore()
self.pause_store = PostgreSQLPauseStore(config.dsn)
# BAT-050 / REQ-102: durable reconcile-warning store (slot_id PK).
self.warn_store = PostgreSQLReconcileWarningStore(config.dsn)
self.intent_service = IntentService(
self.slot_service, self.slot_repo, self.intent_store,
resolve_symbol=self._resolve_symbol,
instance_key=config.instance_key,
max_active_slots=config.max_active_slots, # dcy-020: asset-centric gate
default_order_timeout_sec=config.default_order_timeout_sec, # dcy-022
warn_store=self.warn_store, # BAT-050 / REQ-104: reconcile-warning gate
)
# BAT-012: day-scoped kill-switch exclusion store + service.
self.killswitch_store = PostgreSQLKillSwitchStore(config.dsn)
self.portfolio_read = _build_portfolio_read(config)
@@ -218,6 +222,7 @@ class Daemon:
slot_service=self.slot_service,
instance_key=config.instance_key,
alarm_emitter=self.alarm_emitter, # dcy-033 / REQ-100
warn_store=self.warn_store, # BAT-050 / REQ-103: durable reconcile-warning
)
self.execution = ExecutionService(
self.slot_service, self.slot_repo, self.broker,
@@ -315,6 +320,7 @@ class Daemon:
instance_key=self.config.instance_key,
snapshot_store=self.snapshot_store,
pause_store=self.pause_store,
warn_store=self.warn_store, # BAT-050 / REQ-104: reconcile_warned field
watchdog_store=self.watchdog,
watchdog_timeout_sec=self.config.safety_sell.watchdog_timeout_sec,
ledger_outbox=self.outbox,