9 Commits
Author SHA1 Message Date
Hermes Agent f8ad591f0d docs: formalize issue 61 proofline specification
Publish verified container image / publish (push) Canceled after 0s
Publish verified container image / verify (push) Canceled after 0s
2026-08-19 13:21:16 +09:00
Hermes Agent 43f6fea7ac test: cover null venue SOR normalization 2026-08-19 13:16:14 +09:00
Hermes Agent 64e4e32f9d docs: align venue defaults with SOR contract 2026-08-19 13:12:59 +09:00
Hermes Agent 4975d7166f docs: formalize issue 60 proofline specification 2026-08-19 13:05:02 +09:00
Hermes Agent 359ea098ff fix: enforce actual venue persistence contract 2026-08-19 12:53:56 +09:00
Hermes Agent 7366cadf03 fix: preserve SOR execution venue separately 2026-08-19 12:48:05 +09:00
Hermes Agent 15aeae6930 fix: converge broker failures without retry 2026-08-19 11:29:26 +09:00
Hermes Agent be98965f2c fix(ci): use canonical migration inventory size 2026-08-15 16:22:46 +09:00
Hermes Agent 7dadc3dd2d ci(release): verify published image selectors 2026-08-15 16:20:57 +09:00
40 changed files with 1020 additions and 228 deletions
@@ -0,0 +1,72 @@
name: Verify published trex-core image
on:
workflow_dispatch:
inputs:
version:
description: "Strict release tag (for example v0.2.0)"
required: true
type: string
commit:
description: "Exact 40-character lowercase source commit"
required: true
type: string
permissions:
contents: read
packages: read
jobs:
verify:
runs-on: ubuntu-24.04
steps:
- name: Validate immutable selectors and image contract
env:
REGISTRY_TOKEN: ${{ secrets.GITHUB_TOKEN }}
ACTOR: ${{ github.actor }}
VERSION: ${{ inputs.version }}
COMMIT: ${{ inputs.commit }}
IMAGE: ghcr.io/fourblocks2020/trex-core
run: |
set -euo pipefail
[[ "$VERSION" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]
[[ "$COMMIT" =~ ^[0-9a-f]{40}$ ]]
short_sha="${COMMIT:0:12}"
printf '%s' "$REGISTRY_TOKEN" | docker login ghcr.io --username "$ACTOR" --password-stdin >/dev/null
version_raw="$(docker buildx imagetools inspect --raw "$IMAGE:$VERSION")"
source_raw="$(docker buildx imagetools inspect --raw "$IMAGE:$short_sha")"
version_digest="sha256:$(printf '%s' "$version_raw" | sha256sum | cut -d' ' -f1)"
source_digest="sha256:$(printf '%s' "$source_raw" | sha256sum | cut -d' ' -f1)"
test "$version_digest" = "$source_digest"
docker pull "$IMAGE@$version_digest" >/dev/null
test "$(docker image inspect "$IMAGE@$version_digest" --format '{{.Architecture}}')" = amd64
test "$(docker image inspect "$IMAGE@$version_digest" --format '{{.Config.User}}')" = 10001:10001
test "$(docker image inspect "$IMAGE@$version_digest" --format '{{index .Config.Labels "org.opencontainers.image.revision"}}')" = "$COMMIT"
test "$(docker image inspect "$IMAGE@$version_digest" --format '{{index .Config.Labels "org.opencontainers.image.source"}}')" = https://github.com/fourblocks2020/trex-core
test "$(docker image inspect "$IMAGE@$version_digest" --format '{{json .Config.Entrypoint}}')" = '["trex-core-daemon"]'
test "$(docker run --rm --entrypoint python "$IMAGE@$version_digest" -c 'from trex_core.adapters.persistence.migrate import migration_files; p=migration_files(); print(f"count={len(p)} last={p[-1].name}")')" = 'count=21 last=022_persist_order_timeout_anchor.sql'
if docker buildx imagetools inspect "$IMAGE:latest" >/dev/null 2>&1; then
echo "mutable latest selector exists" >&2
exit 1
fi
echo "digest=$version_digest"
echo "version_selector=$IMAGE:$VERSION"
echo "source_selector=$IMAGE:$short_sha"
echo "immutable=$IMAGE@$version_digest"
{
echo "## Verified published trex-core image"
echo
echo "- digest: \`$version_digest\`"
echo "- version selector: \`$IMAGE:$VERSION\`"
echo "- source selector: \`$IMAGE:$short_sha\`"
echo "- source commit: \`$COMMIT\`"
echo "- architecture: \`linux/amd64\`"
echo "- runtime user: \`10001:10001\`"
echo "- entrypoint: \`trex-core-daemon\`"
echo "- migration inventory: \`21\`, last \`022_persist_order_timeout_anchor.sql\`"
echo "- latest: absent"
} >> "$GITHUB_STEP_SUMMARY"
+16
View File
@@ -0,0 +1,16 @@
---
id: "ac-0015"
status: active
---
# 명시적 sell 미수락·미체결 상태 수렴
## Criterion
KIS submission 또는 authoritative order lookup이 sell 주문의 미수락·미체결을 명시적으로 확인하면 core는 실패 evidence를 기록하고 해당 dispatch를 정리하며 새 broker attempt를 생성하지 않고 slot을 broker-authoritative 보유수량의 `holding`으로 수렴시켜야 한다. 이 경로는 로컬 추정수량으로 보유량을 변경하거나 strategy에 broker retry 판단을 요구해서는 안 된다.
## Verification
- 성공 조건: `pending_sell`에서 명시적 rejection 또는 lookup-confirmed absence가 발생하면 기존 보유수량을 유지한 `holding`으로 전이하고 dispatch metadata가 정리되며 broker submit 호출은 한 번뿐이다.
- 실패·경계 조건: 체결 가능성이 남은 unknown outcome을 rejection으로 취급하거나, 수량을 0으로 만들거나, 자동 새 주문을 제출하거나, broker-authoritative 수량과 다른 값으로 수렴하면 FAIL이다.
- 검사 방법: `tests/application/test_execution_policy.py`, `tests/application/test_order_timeout_reconciliation.py`와 관련 repository transition tests에서 상태·수량·dispatch·broker call count를 단언하고 전체 회귀를 실행한다.
+16
View File
@@ -0,0 +1,16 @@
---
id: "ac-0016"
status: active
---
# 결과 불명확 submission의 중복 제출 방지와 reconciliation
## Criterion
주문 submission timeout, 연결 단절, 응답 누락 또는 응답 해석 실패로 broker acceptance 여부가 불명확하면 core는 original dispatch identity와 결과 불명확 sentinel을 durable하게 보존하고 새 broker order를 제출하지 않아야 한다. daemon 재시작과 반복 tick에서도 original order date·client identity를 사용한 broker lookup과 reconciliation을 먼저 수행하고 authoritative terminal evidence가 생기기 전에는 slot을 재사용 가능한 상태로 전환하지 않아야 한다.
## Verification
- 성공 조건: submit 결과 불명확 후 동일 slot의 반복 tick과 restart 모사에서 broker submit call count가 증가하지 않고 lookup/reconciliation이 실행되며 durable dispatch metadata가 유지된다.
- 실패·경계 조건: timeout 자체로 terminal reject·holding·inactive를 추론하거나, sentinel을 지우거나, 새 broker attempt를 만들거나, 현재 날짜·wall-clock 값으로 original order identity를 대체하면 FAIL이다.
- 검사 방법: `tests/application/test_order_timeout_reconciliation.py`의 timeout, restart, order visibility와 lookup fixture에서 call ordering·dispatch persistence·상태를 검증한다.
+16
View File
@@ -0,0 +1,16 @@
---
id: "ac-0017"
status: active
---
# strategy·TVR과 broker failure ownership 분리
## Criterion
KIS failure, raw broker error, broker attempt identity, retryability, retry schedule과 retry budget은 `trex-core` 내부 execution/reconciliation 경계를 벗어나 strategy 또는 TVR wire에 노출되어서는 안 된다. core도 broker failure를 retryable/non-retryable로 분류하여 자동 새 주문 attempt를 생성해서는 안 되며 strategy/TVR은 core가 수렴한 slot snapshot만 소비해야 한다. 이후 strategy가 독립적으로 생성한 별도 intent는 core의 자동 retry와 구분한다.
## Verification
- 성공 조건: sell response와 strategy-facing schema에 retryability·KIS error·attempt field가 없고 explicit reject 및 unknown outcome에서 자동 resubmit이 발생하지 않는다.
- 실패·경계 조건: raw KIS payload나 retryable boolean이 strategy/TVR wire에 나타나거나, core가 retry schedule·budget을 산출하거나, 동일 intent에서 새 broker attempt를 자동 생성하면 FAIL이다.
- 검사 방법: `tests/application/test_sell_retryable_flag.py`, messaging handler tests, execution rejection·unknown tests와 schema/document contract 검색을 실행한다.
+16
View File
@@ -0,0 +1,16 @@
---
id: "ac-0018"
status: active
---
# 주문 venue 기본값·명시값 보존과 AUTO 제거
## Criterion
intent venue가 누락되거나 null이면 core는 original order venue를 `SOR`로 정규화해야 하고 explicit `KRX`, `NXT`, `SOR`는 submit·ack·slot·restart·cancel 전 과정에서 변경 없이 보존해야 한다. `AUTO`는 admission, broker request와 persistence에서 거부해야 하며 기존 persisted AUTO는 migration으로 SOR로 전환해야 한다. core는 wall-clock time이나 session 추정으로 order venue를 KRX/NXT로 재라우팅해서는 안 된다.
## Verification
- 성공 조건: 누락/null→SOR, explicit KRX/NXT/SOR identity 보존, SOR 부분체결 후 잔량 cancel과 restart가 original SOR를 사용하는 흐름이 통과한다.
- 실패·경계 조건: AUTO acceptance·저장, 시간 기반 venue 변환, ack actual venue로 slot order venue 덮어쓰기 또는 restart/cancel에서 original venue 손실은 FAIL이다.
- 검사 방법: `tests/adapters/broker/test_venue.py`, `tests/application/test_venue_intent_flow.py`, migration/drift tests와 KIS request capture를 실행하여 wire·slot·SQL constraint를 단언한다.
+16
View File
@@ -0,0 +1,16 @@
---
id: "ac-0019"
status: active
---
# 원주문 venue와 실제 체결 venue의 durable 분리
## Criterion
core는 original `order_venue`와 broker-authoritative actual `execution_venue`를 서로 다른 의미로 보존해야 한다. `order_venue`는 KRX/NXT/SOR이며 submit, ack, slot, restart와 cancel에 사용한다. actual venue는 KRX/NXT 또는 미확정 NULL이며 KIS의 검증된 `ORD_EXG_GB`와 명시 exchange-id allowlist에서만 결정하여 fill, ledger와 outbox에 기록한다. `SOR`, 누락, 미지원 코드 또는 wall-clock time으로 actual venue를 추론해서는 안 된다. historical outbox SOR는 `order_venue=SOR`, actual NULL로 변환하고 migration replay는 신규 정상 조합을 오염시키지 않아야 한다.
## Verification
- 성공 조건: SOR order의 actual KRX/NXT fill이 `(order_venue=SOR, venue=KRX|NXT)`로 기록되고 cancel/restart는 SOR를 유지한다. historical SOR는 `(SOR,NULL)`이며 정상 `(order=KRX, actual=NXT)`는 migration 반복 후 보존된다.
- 실패·경계 조건: actual SOR 저장, unknown code를 KRX/NXT로 추론, actual venue로 slot order venue 덮어쓰기, NULL actual SOR fill의 거짓 ledger 기록, AUTO·NULL order 저장 또는 migration replay 오염은 FAIL이다.
- 검사 방법: KIS parser tests, execution ledger tests, `tests/adapters/persistence/test_postgresql_ledger_outbox.py`, `tests/adapters/persistence/test_migration_and_drift.py`를 실행한다. 실제 PostgreSQL에서 historical conversion, replay, round-trip과 check violation을 검증하고 전체 회귀·Ruff 및 독립 read-only QC를 수행한다.
+2 -2
View File
@@ -1,5 +1,5 @@
{
"schema_version": 1,
"next_line_number": 5,
"next_ac_number": 15
"next_line_number": 7,
"next_ac_number": 20
}
+67
View File
@@ -0,0 +1,67 @@
---
id: "dcy-0005"
status: confirmed
---
# broker 실행 실패의 기록·상태 수렴 경계
## Problem
`trex-core`의 broker execution 경계는 명시적인 주문 거부, timeout·연결 단절·응답 누락처럼 결과가 불명확한 submission, 취소·부분체결·재시작을 서로 다른 authority로 처리해야 한다. 기존 계약이 이 경계를 충분히 명시하지 않으면 core가 broker failure를 retryability로 분류하거나 새 주문 attempt를 자동 생성하여 중복 주문을 만들 수 있고, strategy/TVR이 KIS 실패와 broker retry 판단을 소유하는 잘못된 결합이 생길 수 있다.
주문 venue도 같은 execution lifecycle에서 의미가 혼재될 위험이 있었다. 누락 venue의 기본값, 명시 `KRX`/`NXT`/`SOR`, 폐기된 `AUTO`, 원주문 routing venue와 실제 KRX/NXT 체결 venue를 구분하지 않으면 wall-clock routing, 취소 시 원주문 venue 손실, ledger/outbox에 실제 거래소 대신 `SOR` 기록, 기존 persisted `AUTO` 및 historical `SOR` row의 잘못된 해석이 발생할 수 있다.
기대 상태는 core가 broker-authoritative evidence로 상태를 수렴하되 자동 새 주문을 만들지 않고, strategy/TVR에는 core slot snapshot만 노출하며, 원주문 venue와 실제 체결 venue를 각각 durable하게 보존하는 것이다.
## Evidence
- 원본 승인 문서: GitHub issue #60 `https://github.com/fourblocks2020/trex-core/issues/60`의 승인된 본문은 명시적 sell rejection, unknown outcome reconciliation, TVR wire 경계, SOR 기본값, AUTO 제거와 자동 retry 금지를 정의한다.
- 연계 승인 계약: GitHub issue #61은 venue admission부터 broker request/ack/cancel과 ledger/outbox까지 explicit venue 보존 경계를 정의한다.
- 구현 진행 원본: issue #60 comment `https://github.com/fourblocks2020/trex-core/issues/60#issuecomment-5336722059`은 기준 revision, 계획, 구현·검증 진행, 두 차례의 독립 QC blocker와 교정 기록을 포함한다.
- 구현 완료 원본: issue #60 comment `https://github.com/fourblocks2020/trex-core/issues/60#issuecomment-5337338182`은 구현 내용, 검증 결과, 로컬 commit 및 push·PR·배포·릴리스·실주문 경계를 기록한다.
- 구현 revision은 `15aeae6930f8c3e6ef9cf659f41278b099a78459`, `7366cadf03fc6002bfd01ecf0cba7c24486bb618`, `359ea098ff717e7f04cf4206dcbc64ad17b47755`이며 현재 local `main` HEAD는 `359ea098ff717e7f04cf4206dcbc64ad17b47755`다.
- `trex_core/application/execution.py`는 명시적 sell 미수락·미체결의 `pending_sell → holding`, 결과 불명확 submission의 durable dispatch sentinel·lookup/reconciliation, fill의 actual venue 확인과 ledger enqueue 경계를 구현한다.
- `trex_core/application/broker_port.py`는 original submission/routing venue를 가진 `OrderAck`와 nullable broker-authoritative `FillStatus.execution_venue`를 분리한다.
- `trex_core/adapters/broker/kis.py`는 주문 요청의 `KRX`/`NXT`/`SOR`를 보존하고 `ORD_EXG_GB` 및 명시 exchange-id allowlist로 실제 KRX/NXT만 파싱하며 `SOR` 단독·unknown을 추론하지 않는다.
- `trex_core/adapters/persistence/sql/023_remove_auto_order_venue.sql`은 persisted `AUTO → SOR` 변환과 이후 AUTO 저장 차단을 수행한다.
- `trex_core/adapters/persistence/sql/024_add_ledger_order_venue.sql`은 original `order_venue`와 nullable actual `venue`를 분리하고 historical SOR actual을 NULL로 보존하며 replay-safe NULL-only backfill과 DB constraint를 적용한다.
- `trex_core/adapters/persistence/postgresql.py`와 `trex_core/application/ledger_port.py`는 outbox에서 `order_venue`와 actual `venue`를 독립적으로 저장·복원한다.
- 구현자 검증은 focused unit `77 passed`, 전체 `1074 passed, 52 skipped`, disposable PostgreSQL 16 `24 passed`, Ruff `All checks passed!`였다.
- 최종 독립 read-only QC는 `359ea098ff717e7f04cf4206dcbc64ad17b47755`에서 blocker/critical/major/minor finding 없이 PASS했다. 실제 PostgreSQL 16에서 historical SOR→`order_venue=SOR`+actual NULL, 정상 actual NXT/order KRX의 replay 보존, actual SOR·AUTO·NULL order 거부를 확인했고 worktree는 clean이었다.
- 현재 `proofline validate`는 exit 0이다.
## Scope
- AC admission은 기존 active AC-0011의 timeout/cancel reconciliation 및 AC-0013의 terminal cancel·partial fill 상태 수렴과 인접하지만, 명시적 submission rejection, strategy wire ownership, venue admission/migration 및 order/execution venue 분리를 독립적으로 검증 가능한 장기 계약으로 추가하는 `create`다. 기존 AC의 의미나 status는 변경하지 않는다.
- KIS 조회로 sell 주문의 미수락·미체결이 명시적으로 확인되면 새 broker attempt 없이 실패 evidence를 기록하고 dispatch를 정리하며 broker-authoritative 보유수량으로 `pending_sell → holding` 전이한다.
- timeout, 연결 단절, 응답 누락 등 submission 결과가 불명확하면 durable sentinel을 유지하고 새 주문을 생성하지 않으며 broker lookup과 reconciliation을 먼저 수행한다.
- core는 broker failure의 retryability, retry schedule, retry budget을 판정하거나 자동 새 broker attempt를 생성하지 않는다. 이후 strategy가 독립적으로 생성한 새 intent는 이 자동 retry 금지와 구분한다.
- strategy/TVR에는 KIS failure, raw broker error, broker attempt, retryability를 노출하지 않는다. strategy/TVR은 core가 수렴한 slot snapshot만 소비한다.
- intent venue 누락은 `SOR`로 정규화하고 명시 `KRX`/`NXT`/`SOR`는 보존한다. `AUTO`는 admission과 persistence에서 거부하고 기존 persisted AUTO는 SOR로 전환하며 wall-clock venue routing을 수행하지 않는다.
- original `order_venue` KRX/NXT/SOR는 submit/ack/slot/restart/cancel에 보존한다. broker-authoritative actual `execution_venue`는 KRX/NXT 또는 미확정 NULL로 별도 취급하고 fill·ledger/outbox에 기록한다.
- KIS actual venue는 검증된 `ORD_EXG_GB`와 명시 exchange-id allowlist에서만 KRX/NXT로 변환한다. `SOR` 단독, 누락 또는 미지원 값은 KRX/NXT로 추론하지 않는다.
- historical outbox의 SOR는 original order venue로 보존하고 actual venue는 NULL로 전환한다. migration 재실행은 신규 정상 order/execution venue 조합을 오염시키지 않아야 하며 DB는 actual SOR와 invalid order venue를 거부한다.
- 관련 focused·전체 회귀, PostgreSQL migration·round-trip, lint와 독립 QC evidence를 구현 상태 평가에 포함한다.
## Out of Scope
- strategy/TVR의 KIS failure 수신, retryability 판단, broker attempt 관리 또는 자동 retry 기능
- TVR 세션·portfolio `markets` 판단 구현과 KRX/NXT session policy 자체
- 실제 KIS 주문·취소, production credential, live RabbitMQ·database·portfolio-hub 연결
- push, PR, 원격 main 반영, image publication, 운영 migration, deployment, GitHub Release 또는 실주문
- ProofLine delivery/release lifecycle이 과거 구현 당시 완료되었다는 소급 주장
## Risks and Unknowns
### Risks
- KIS 응답의 실제 venue 필드가 누락되거나 미지원 코드이면 SOR 주문의 actual venue가 NULL로 남아 ledger enqueue가 fail-closed 될 수 있다. 임의 시간 추론보다 안전하며 운영 관측과 authoritative reconciliation이 필요하다.
- migration runner는 history table 없이 SQL을 재실행하므로 migration 024의 NULL-only backfill과 replay-safe 불변식을 이후 변경에서도 유지해야 한다.
- 환경 의존 KIS·RabbitMQ 검증은 skip되었으므로 실제 운영 외부 시스템 상호작용은 별도 승인 환경에서 확인해야 한다.
### Approval State
- Discovery status: `confirmed`
- 승인 근거: 요청자 genichin이 승인 상태인 issue #60 본문을 최대한 보존하여 템플릿 기반 Discovery를 승인된 상태로 정리하라고 명시했다.
- 추가로 필요한 제품 결정: 없음
- 이 확인은 사후 specification 정리이며 구현·테스트·독립 QC의 실제 evidence는 별도 보존한다. push, PR, 배포, release 또는 실주문 승인을 뜻하지 않는다.
@@ -0,0 +1,49 @@
# GitHub issue #60 comment evidence
- Source: https://github.com/fourblocks2020/trex-core/issues/60#issuecomment-5337338182
- Author: `genichin`
- Created At: `2026-08-19T03:57:52Z`
- Evidence Role: repository-local snapshot of a non-canonical implementation comment
- Canonical Authority: GitHub source comment; this snapshot does not create ProofLine lifecycle status
---
## 구현 완료
### 구현 내용
- 명시적 주문 미수락·미체결 sell 실패를 자동 재주문 없이 `pending_sell → holding`으로 수렴시켰다.
- submission outcome unknown은 durable sentinel과 broker lookup/reconciliation을 우선하고 중복 제출하지 않는다.
- strategy RPC에서 KIS failure·broker attempt·retryability 전달을 제거했다.
- venue 누락은 SOR, 명시 KRX/NXT/SOR는 보존하고 AUTO 및 wall-clock routing을 제거했다.
- 기존 persisted AUTO를 SOR로 전환하는 migration을 추가했다.
- SOR 원주문 venue와 실제 체결 venue를 분리했다.
- slot·재시작·취소: `order_venue` KRX/NXT/SOR
- fill·ledger/outbox actual venue: KRX/NXT, 복원 불가능한 historical SOR는 NULL
- KIS `ORD_EXG_GB` 및 명시 exchange-id allowlist로 실제 KRX/NXT를 파싱하며 SOR/unknown은 추론하지 않는다.
- migration replay가 정상 `(actual=NXT, order=KRX)` 행을 오염시키지 않도록 NULL-only backfill과 DB constraint를 적용했다.
### 실제 검증 결과
- 구현자 전체 회귀: `1074 passed, 52 skipped`
- 구현자 focused unit: `77 passed`
- 구현자 disposable PostgreSQL 16: `24 passed`
- Ruff: `All checks passed!`
- 독립 QC 전체 pytest + PostgreSQL 16 검증: PASS
- 독립 QC finding: blocker/critical/major/minor 모두 없음
- 독립 QC worktree: clean
### 로컬 커밋
- `15aeae6930f8c3e6ef9cf659f41278b099a78459` — broker 실패 수렴·AUTO 제거
- `7366cadf03fc6002bfd01ecf0cba7c24486bb618` — SOR 원주문/실제 체결 venue 분리
- `359ea098ff717e7f04cf4206dcbc64ad17b47755` — actual venue DB constraint 및 replay-safe migration 보강
### 비차단 후속 권고
- migration runner는 history table 없이 SQL 전체를 재실행하므로 현재 migration의 replay-safe 불변식을 계속 유지한다.
- 실제 운영 KIS 응답·RabbitMQ·자격증명 게이트 검증은 별도 승인된 환경에서 수행한다.
### 범위 경계
현재 완료된 것은 **로컬 `main`의 구현·테스트·PostgreSQL 검증·커밋과 독립 QC PASS**다. push, PR, 원격 main 반영, 이미지 게시, 운영 배포, migration 운영 실행, GitHub Release, 실주문은 수행하지 않았으며 완료를 의미하지 않는다.
@@ -0,0 +1,55 @@
# GitHub issue #60 comment evidence
- Source: https://github.com/fourblocks2020/trex-core/issues/60#issuecomment-5336722059
- Author: `genichin`
- Created At: `2026-08-19T02:20:28Z`
- Evidence Role: repository-local snapshot of a non-canonical implementation comment
- Canonical Authority: GitHub source comment; this snapshot does not create ProofLine lifecycle status
---
## 구현 진행 상황
- **대상:** [Discovery] broker 실행 실패의 기록·상태 수렴 경계
- **브랜치:** `main`
- **기준:** `main` (`be98965f2c5d1bad933802282bd7284642203cb8`)
- **상태:** 로컬 main 구현·검증·커밋 및 독립 QC PASS — 미푸시, 미배포
- **최종 업데이트:** 2026-08-19 12:57:49 KST
### 구현 계획 및 작업 목록
- [x] 명시적으로 주문이 거부되고 미체결임이 확인된 매도 주문을 새 주문 없이 보유 상태로 복구한다.
- 주문 배정 정보를 정리하고 기존 보유수량을 유지하는 집중 검증을 통과했다.
- [x] 주문 결과가 불명확한 경우 중복 주문을 만들지 않고 조회·대조 절차를 우선한다.
- 기존 결과불명 sentinel·조회 경로와 재시작 중복 제출 방지 회귀를 확인했다.
- [x] 전략 서비스에 KIS 실패·재시도 판단 정보를 전달하지 않고, core가 자동 주문 재시도를 추가하지 않았음을 검증한다.
- sell 응답의 `retryable` 필드를 제거하고 strategy RPC 응답에 retryability가 없음을 검증했다.
- [x] venue 누락 시 SOR 기본값, 명시 venue 보존, AUTO 제거·기존 데이터 전환 계약과의 교차 회귀를 검증한다.
- 원주문 `order_venue`와 실제 `execution_venue`를 분리하고, KIS allowlist 파싱·outbox 이중 보존·실제 PostgreSQL migration 검증을 완료했다.
- [x] 관련 집중 테스트와 전체 회귀 테스트를 실행하고 결과를 기록한다.
- [x] 변경사항을 검토하고 로컬 main에 커밋한다.
- commits: `15aeae6930f8c3e6ef9cf659f41278b099a78459`, blocker fixes `7366cadf03fc6002bfd01ecf0cba7c24486bb618`, `359ea098ff717e7f04cf4206dcbc64ad17b47755`; push·PR·배포·릴리스·실주문은 수행하지 않았다.
### 진행 기록
- 2026-08-19 11:29:51 KST — 승인된 이슈 본문과 `main` 기준 SHA를 확인하고 별도 worktree·기능 브랜치 없이 구현을 시작했다.
- 2026-08-19 11:29:51 KST — sell 명시적 거부 후 `pending_sell → holding`, dispatch 정리, 후속 자동 재주문 부재를 검증했다.
- 2026-08-19 11:29:51 KST — 결과불명 주문은 durable sentinel과 broker lookup/reconciliation 경로를 유지하며 재제출하지 않는 회귀를 확인했다.
- 2026-08-19 11:29:51 KST — venue 누락→SOR, explicit KRX/NXT/SOR 보존, AUTO admission 거부, wall-clock routing 제거, persisted AUTO→SOR migration을 구현했다.
- 2026-08-19 11:29:51 KST — 집중 테스트 `127 passed`; 전체 회귀 `1062 passed, 51 skipped`; ruff `All checks passed!`.
- 2026-08-19 11:29:51 KST — disposable PostgreSQL 16 실제 엔진 검증 `23 passed`; 검증 컨테이너를 제거했다.
- 2026-08-19 11:29:51 KST — 로컬 main commit `15aeae6930f8c3e6ef9cf659f41278b099a78459` 생성 후 집중 테스트 `127 passed`, ruff 통과, 작업트리 clean을 재확인했다.
- 2026-08-19 11:59:05 KST — 독립 QC 결과 FAIL. KIS adapter가 SOR 요청값을 ack/slot/ledger에 그대로 보존하고 일별 체결조회 row의 실제 KRX/NXT venue를 파싱하지 않아 AC 6을 충족하지 못한다. 수정·독립 재검증 전에는 delivery 검증 완료로 판정하지 않는다.
- 2026-08-19 12:47:57 KST — 승인된 해결책을 적용했다. Slot/취소에는 원주문 KRX/NXT/SOR를 유지하고, KIS fill의 `ORD_EXG_GB` 및 명시 exchange-id allowlist에서 실제 KRX/NXT를 `FillStatus.execution_venue`로 전달한다. outbox는 `order_venue`와 실제 `venue`를 분리 저장하며 SOR 단독·미지원 코드는 실제 거래소로 추론하지 않는다.
- 2026-08-19 12:47:57 KST — 전체 회귀 `1074 passed, 51 skipped`, disposable PostgreSQL 16 검증 `23 passed`, ruff 통과, migration 024 및 outbox round-trip을 확인했다.
- 2026-08-19 12:48:36 KST — blocker 수정 commit `7366cadf03fc6002bfd01ecf0cba7c24486bb618`을 로컬 main에 생성하고 worktree clean을 확인했다. 독립 재QC를 시작했다.
- 2026-08-19 12:54:15 KST — 독립 재QC에서 migration 024의 historical SOR actual 값과 replay-safe backfill 결함을 blocker로 확인했다. `order_venue IS NULL` one-time backfill, historical SOR actual→NULL, actual venue KRX/NXT/NULL DB constraint를 적용했다. 신규 actual NXT + order KRX 행이 replay 후 보존됨을 검증했다.
- 2026-08-19 12:54:15 KST — 수정 commit `359ea098ff717e7f04cf4206dcbc64ad17b47755`; 전체 `1074 passed, 52 skipped`, PostgreSQL 16 `24 passed`, ruff 통과, worktree clean. 독립 재QC를 다시 요청한다.
- 2026-08-19 12:57:49 KST — 독립 재QC PASS. blocker/critical/major/minor finding 없음. 독립 PG16에서 historical SOR→order SOR+actual NULL, 정상 NXT/KRX replay 보존, actual SOR·AUTO·NULL order 거부를 확인했다. HEAD `359ea098ff717e7f04cf4206dcbc64ad17b47755`, worktree clean.
> 각 작업이 실제로 완료되고 검증될 때마다 이 댓글의 체크박스와 진행 기록을 갱신한다. 체크 표시는 구현 완료 또는 해당 검증의 실제 통과를 의미하며, 배포·릴리스 완료를 의미하지 않는다.
+3
View File
@@ -0,0 +1,3 @@
---
id: "line-0005"
---
+61
View File
@@ -0,0 +1,61 @@
---
id: "req-0005"
status: approved
discovery: "dcy-0005"
criteria:
create:
- "ac-0015"
- "ac-0016"
- "ac-0017"
- "ac-0018"
- "ac-0019"
update: []
retire: []
satisfy: []
---
# broker 실행 실패의 기록·상태 수렴 경계
## Objective
`trex-core`가 broker-authoritative evidence를 기준으로 주문 실패·불명확 결과·부분체결·취소 상태를 중복 주문 없이 수렴하게 한다. core가 자동 broker retry를 생성하거나 strategy/TVR에 KIS 실패 판단을 넘기지 않도록 ownership을 제한하고, original order venue와 actual execution venue를 durable하게 분리하여 submit부터 restart·cancel·ledger/outbox까지 의미를 보존한다.
## Scope
- 명시적으로 미수락·미체결이 확인된 sell 주문은 실패 evidence를 기록하고 dispatch를 정리하며 새 broker attempt 없이 broker-authoritative 보유수량으로 `pending_sell → holding` 전이한다.
- submission timeout·연결 단절·응답 누락 등 결과 불명확 상태는 durable sentinel로 보존하고 신규 주문 없이 original order lookup과 reconciliation을 우선한다.
- core는 broker failure의 retryability, retry schedule, retry budget 또는 자동 새 broker attempt를 산출하지 않는다. 이후 별도 strategy intent는 자동 retry와 구분한다.
- strategy/TVR 응답·이벤트에는 KIS failure, raw broker error, broker attempt와 retryability를 노출하지 않는다. strategy/TVR은 core slot snapshot만 소비한다.
- intent venue 누락은 `SOR`로 정규화하고 explicit `KRX`/`NXT`/`SOR`를 그대로 보존한다. `AUTO`는 admission·broker routing·persistence에서 허용하지 않고 persisted AUTO는 SOR로 전환하며 wall-clock routing을 제거한다.
- original `order_venue`는 submit, ack, slot, restart와 cancel에 KRX/NXT/SOR로 보존한다. actual `execution_venue`는 broker-authoritative KRX/NXT 또는 미확정 NULL이며 fill, ledger와 outbox에 별도로 기록한다.
- KIS actual venue는 `ORD_EXG_GB`의 승인된 mapping과 명시 exchange-id allowlist만 사용한다. `SOR`, 누락, 미지원 값과 wall-clock time으로 actual KRX/NXT를 추론하지 않는다.
- historical outbox SOR는 `order_venue=SOR`, actual `venue=NULL`로 보존한다. migration은 NULL-only backfill로 반복 적용이 안전해야 하고 정상 `(actual=NXT, order=KRX)` 같은 조합을 오염시키지 않아야 한다.
- PostgreSQL은 order venue를 KRX/NXT/SOR non-null로 제한하고 actual venue를 KRX/NXT/NULL로 제한한다.
- focused·전체 회귀, actual PostgreSQL migration·round-trip, lint와 독립 read-only QC를 verification evidence로 유지한다.
## Constraints
- broker evidence가 없는 actual venue, 체결, 미수락 또는 terminal state를 추론하지 않는다.
- explicit order venue와 original order date·broker order identity를 restart/cancel 중 변경하지 않는다.
- strategy/TVR에 KIS failure나 retry ownership을 추가하지 않는다.
- live credential·token·connection string·raw sensitive payload를 문서나 외부 wire에 기록하지 않는다.
- existing active AC-0011의 timeout/cancel reconciliation 및 AC-0013의 terminal cancellation·partial fill 계약을 완화하거나 대체하지 않는다.
- Normative Design Documents: 없음. 이 REQ와 active AC가 normative specification을 소유한다.
### Current Implementation Assessment
- 이 specification은 승인된 GitHub issue #60과 연결된 #61을 이미 local `main`에서 구현·검증한 결과를 사후 정리한다. 과거 구현이 ProofLine delivery chronology를 따랐다는 뜻은 아니다.
- 구현 revision은 `15aeae6930f8c3e6ef9cf659f41278b099a78459`, `7366cadf03fc6002bfd01ecf0cba7c24486bb618`, `359ea098ff717e7f04cf4206dcbc64ad17b47755`다.
- 현재 구현은 명시적 sell rejection 수렴, unknown submission sentinel·lookup, strategy wire retryability 제거, SOR default·explicit venue 보존·AUTO 제거, KIS actual venue parser와 order/execution venue 분리, replay-safe migration·DB constraint를 포함한다.
- 구현자 검증은 focused `77 passed`, 전체 `1074 passed, 52 skipped`, disposable PostgreSQL 16 `24 passed`, Ruff PASS다.
- 최종 독립 read-only QC는 actual PostgreSQL 16 probe를 포함하여 blocker/critical/major/minor finding 없이 PASS했으며 HEAD `359ea098ff717e7f04cf4206dcbc64ad17b47755`와 clean worktree를 확인했다.
- 환경 의존 KIS·RabbitMQ 검증은 skip되었고 실제 외부 system interaction은 수행하지 않았다.
- `approved` REQ와 `active` AC는 current specification authority 및 현재 implementation assessment를 나타낸다. push, PR, 원격 main 반영, deployment, release 또는 운영 주문 완료를 뜻하지 않는다.
## Non-Goals
- strategy/TVR의 KIS failure 수신, retryability 계산, broker retry schedule·budget 또는 자동 재주문
- TVR session·portfolio `markets` gate와 거래 세션 정책 구현
- live KIS 주문·취소, 운영 broker/account/database/RabbitMQ/portfolio-hub 연결
- push, PR, remote main merge, image publication, production migration, deployment, GitHub Release 또는 실주문
- ProofLine delivery·release lifecycle closure의 소급 주장
+68
View File
@@ -0,0 +1,68 @@
---
id: "dcy-0006"
status: confirmed
---
# 명시 venue 기반 주문 실행 계약
## Problem
`trex-core`의 주문 venue 계약에는 과거 `AUTO`와 기본 `KRX` 동작이 혼재했다. buy/sell intent에서 venue가 누락될 때 core가 wall-clock으로 KRX/NXT를 선택하거나 내부·저장 계층에서 AUTO를 허용하면 caller가 요청한 routing provenance를 잃고 세션 판단이 execution core로 새어 들어간다. 기존 persisted AUTO row도 현재 계약과 충돌한다.
SOR 주문에서는 원주문 routing venue와 실제 체결 거래소가 서로 다른 의미다. 이를 하나의 venue 값으로 취급하면 submit acknowledgement 뒤 slot venue를 실제 KRX/NXT로 덮어쓰거나, 반대로 fill·ledger/outbox에 실제 거래소 대신 SOR를 기록할 수 있다. 부분체결 잔량 취소와 daemon 재시작은 원주문 SOR를 필요로 하고, actual venue는 broker-authoritative KRX/NXT evidence가 있을 때만 확정되어야 한다.
기대 상태는 venue 누락/null intent를 SOR로 정규화하고 explicit KRX/NXT/SOR를 변경 없이 보존하며 AUTO와 wall-clock routing을 제거하는 것이다. original order venue와 actual execution venue는 submit·ack·cancel·fill polling·restart·ledger/outbox 전체에서 별도 의미로 durable하게 보존되어야 한다.
## Evidence
- 원본 승인 문서: GitHub issue #61 `https://github.com/fourblocks2020/trex-core/issues/61`은 SOR default, explicit venue preservation, AUTO removal, persisted AUTO→SOR migration, no wall-clock routing과 execution venue lifecycle을 승인했다.
- 승인 결정은 venue 누락의 SOR default, explicit KRX/NXT/SOR 유지, AUTO의 public wire·internal model·persistence 제거, persisted AUTO의 SOR 정규화, SOR ack·조회·취소 계약을 구현 검증으로 증명하고 실패 시 AUTO routing으로 회귀하지 않는다는 다섯 항목이다.
- 구현 진행 원본: issue #61 comment `https://github.com/fourblocks2020/trex-core/issues/61#issuecomment-5337421562`는 baseline `4975d7166fa70e045096503e85c26d740ae92c55`, 한국어 계획, stale PostgreSQL DSN 실패 분류, 수정·검증·독립 QC와 최종 PASS를 기록한다.
- 구현 완료 원본: issue #61 comment `https://github.com/fourblocks2020/trex-core/issues/61#issuecomment-5337469578`은 구현 내용, 실제 검증 결과, local commits와 외부 단계 경계를 기록한다.
- `trex_core/application/messaging_handlers.py`는 buy/sell wire의 누락 또는 explicit null venue를 `SOR`로 정규화하고 invalid venue를 admission 전에 거부한다.
- `trex_core/application/intents.py`는 intent venue 기본값과 validation을 소유하고 slot에 original order venue를 전달한다.
- `trex_core/adapters/broker/kis.py`는 KRX/NXT/SOR allowlist를 시간과 독립적으로 보존하여 `EXCG_ID_DVSN_CD`로 제출하고, actual execution venue는 검증된 `ORD_EXG_GB`와 explicit exchange-id allowlist에서만 KRX/NXT로 파싱한다.
- `trex_core/application/execution.py`는 slot의 original venue를 submit·restart·cancel에 사용하고 `FillStatus.execution_venue`를 ledger actual venue로 전달한다. SOR actual이 확인되지 않으면 추론하지 않고 fail-closed 한다.
- migration 023은 persisted AUTO slot/outbox row를 SOR로 전환하고 AUTO 저장을 차단한다. migration 024는 outbox `order_venue`와 nullable actual `venue`를 분리하고 historical SOR actual을 NULL로 보존하며 NULL-only replay-safe backfill과 constraint를 적용한다.
- 구현 기반 revision은 `15aeae6930f8c3e6ef9cf659f41278b099a78459`, `7366cadf03fc6002bfd01ecf0cba7c24486bb618`, `359ea098ff717e7f04cf4206dcbc64ad17b47755`다. issue #61 정합 수정은 `64e4e32f9d7abf7082588b3c4c9a8c0d272762f6`, explicit null regression은 `43f6fea7ac805f27fba35586af27f0090a672222`다.
- 구현자 검증은 비-DB focused `107 passed`, omitted/null focused `8 passed`, disposable PostgreSQL 16 `24 passed`, 전체 `1074 passed, 52 skipped`, Ruff·ProofLine validate·diff check PASS다.
- 최초 combined focused의 `107 passed, 1 failed, 5 errors`는 종료된 이전 QC PostgreSQL DSN의 connection refused였으며 새 disposable PostgreSQL 16 semantic suite `24 passed`로 재검증되었다.
- 최종 독립 read-only 재QC는 omitted/null SOR normalization, broker request와 ack 이후 slot routing provenance를 확인하고 blocker 0, major 0, minor 0으로 PASS했다. HEAD `43f6fea7ac805f27fba35586af27f0090a672222`, worktree clean이었다.
- 현재 active AC-0018은 SOR default, explicit venue preservation, AUTO removal과 no wall-clock routing을 이미 소유하고, active AC-0019는 original order venue와 actual execution venue의 durable split·migration contract를 이미 소유한다.
## Scope
- AC admission은 중복 criterion을 새로 만들지 않고 기존 active AC의 의미를 변경하지 않는 `satisfy`다.
- `satisfy`: AC-0018에 issue #61의 venue 누락/null→SOR, explicit KRX/NXT/SOR 보존, AUTO 제거·migration과 no wall-clock routing 구현 evidence를 결속한다.
- `satisfy`: AC-0019에 issue #61의 ack·cancel·fill polling·restart·ledger/outbox order/execution venue 분리와 fail-closed actual venue 구현 evidence를 결속한다.
- buy/sell intent의 venue 누락과 explicit null은 SOR로 정규화하고 KIS request에 `EXCG_ID_DVSN_CD="SOR"`를 명시한다.
- caller가 explicit KRX/NXT/SOR를 제공하면 admission, slot, broker request, acknowledgement, restart와 cancel에서 변경 없이 보존한다.
- AUTO는 AMQP intent, domain admission, runtime routing, broker adapter input과 persistence에서 허용·생성·저장하지 않는다. 기존 persisted AUTO는 SOR로 idempotent하게 변환한다.
- core는 wall-clock time으로 KRX/NXT를 선택하거나 SOR를 변환하지 않는다.
- original `order_venue`는 KRX/NXT/SOR이며 submit·ack·slot·restart·cancel에 사용한다. actual `execution_venue`는 broker-authoritative KRX/NXT 또는 미확정 NULL이며 fill·ledger/outbox에 별도로 기록한다.
- SOR actual venue는 검증된 KIS code에서만 KRX/NXT로 확정한다. 누락·SOR 단독·미지원 값과 시간으로 actual venue를 추론하지 않는다.
- historical SOR actual은 order SOR와 actual NULL로 보존한다. migration replay는 정상 `(order=KRX, actual=NXT)` 같은 신규 조합을 오염시키지 않고 DB는 AUTO·invalid order와 actual SOR를 거부한다.
- repository current contract 문서와 KIS adapter 주석을 SOR normalization에 맞추고 omitted와 explicit null을 독립 regression으로 검증한다.
## Out of Scope
- TVR의 session·portfolio `markets` 전략 판단 또는 KRX/NXT session policy 변경
- SOR 주문을 실제 운영 KIS 계좌로 제출하거나 취소하는 작업
- live credential·account·database·RabbitMQ·portfolio-hub 연결
- push, PR, 원격 main 반영, image publication, production migration, deployment, release, issue closure 또는 실주문
- ProofLine delivery/release lifecycle closure의 소급 주장
## Risks and Unknowns
### Risks
- 실제 KIS 운영 응답의 actual exchange field 변형은 fixture 기반 parser 검증 범위를 벗어날 수 있다. 미지원 값은 추론하지 않고 NULL/fail-closed로 유지하며 운영 검증은 별도 승인 환경에서 수행한다.
- migration runner는 history table 없이 SQL을 재실행하므로 AUTO→SOR 및 order/execution split migration의 semantic replay-safe 불변식을 향후 변경에서도 유지해야 한다.
- cancel adapter의 내부 backward-compatible default와 intent의 public SOR default는 서로 다른 경계다. execution path는 항상 stored original venue를 명시적으로 전달해야 하며 문서가 이를 혼동하지 않아야 한다.
### Approval State
- Discovery status: `confirmed`
- 승인 근거: 요청자 genichin이 승인 상태인 issue #61 본문을 최대한 포함하여 템플릿 기반 Discovery와 REQ·AC를 승인된 상태로 사후 정리하라고 명시했다.
- Open Questions: 없음
- 이 확인은 current specification과 implementation evidence의 사후 정리다. push, PR, deployment, release, production migration, issue closure 또는 실주문 승인을 의미하지 않는다.
@@ -0,0 +1,49 @@
# GitHub issue #61 comment evidence
- Source: https://github.com/fourblocks2020/trex-core/issues/61#issuecomment-5337469578
- Author: `genichin`
- Created At: `2026-08-19T04:17:48Z`
- Evidence Role: repository-local snapshot of a non-canonical implementation comment
- Canonical Authority: GitHub source comment; this snapshot does not create ProofLine lifecycle status
---
## 구현 완료
### 구현 내용
- venue가 누락되거나 `null`인 buy/sell intent를 `SOR`로 정규화하고 KIS 요청에 `EXCG_ID_DVSN_CD="SOR"`를 명시한다.
- explicit `KRX`/`NXT`/`SOR`를 submit·ack·slot·restart·cancel 전 과정에서 원주문 venue로 보존한다.
- `AUTO`를 admission에서 거부하고 wall-clock KRX/NXT routing을 제거했다.
- persisted `AUTO`를 `SOR`로 전환하고 이후 invalid venue 저장을 차단한다.
- 원주문 `order_venue`와 broker-authoritative actual execution venue를 분리한다. 취소·재시작은 원주문 venue를, ledger/outbox actual venue는 KRX/NXT 또는 미확정 NULL을 사용한다.
- historical SOR actual은 임의 추론하지 않고 NULL로 보존하며 migration replay가 정상 order/execution venue 조합을 오염시키지 않는다.
- current SOR 계약과 충돌하던 interface 문서와 KIS adapter 주석을 정정했다.
- omitted와 explicit `venue: null`을 각각 검증하는 regression을 추가했다.
### 실제 검증 결과
- 구현자 비-DB focused: `107 passed`
- 구현자 explicit omitted/null focused: `8 passed`
- 구현자 disposable PostgreSQL 16: `24 passed`
- 구현자 전체 회귀: `1074 passed, 52 skipped`
- Ruff·ProofLine validate·diff check: PASS
- 최종 독립 재QC: PASS — blocker 0 / major 0 / minor 0
- 최종 worktree: clean
최초 combined focused 실행의 `1 failed, 5 errors`는 종료된 이전 QC PostgreSQL DSN의 connection refused였으며, 새 disposable PostgreSQL 16에서 semantic migration suite를 재실행해 `24 passed`를 확인했다.
### 로컬 커밋
- 기능 구현 기반: `15aeae6930f8c3e6ef9cf659f41278b099a78459`, `7366cadf03fc6002bfd01ecf0cba7c24486bb618`, `359ea098ff717e7f04cf4206dcbc64ad17b47755`
- 계약 문서 정합: `64e4e32f9d7abf7082588b3c4c9a8c0d272762f6`
- explicit null regression: `43f6fea7ac805f27fba35586af27f0090a672222`
### 비차단 후속 권고
- 실제 KIS 운영계좌 SOR 주문과 외부 인프라 검증은 별도 승인된 환경에서 수행한다.
- migration runner의 replay-safe 불변식을 향후 migration 변경에서도 유지한다.
### 범위 경계
현재 완료된 것은 **로컬 `main` 구현·테스트·PostgreSQL 검증·커밋과 독립 QC PASS**다. push, PR, 원격 main 반영, image 게시, 운영 migration, 배포, GitHub Release, issue 종료와 실주문은 수행하지 않았다.
@@ -0,0 +1,51 @@
# GitHub issue #61 comment evidence
- Source: https://github.com/fourblocks2020/trex-core/issues/61#issuecomment-5337421562
- Author: `genichin`
- Created At: `2026-08-19T04:10:59Z`
- Evidence Role: repository-local snapshot of a non-canonical implementation comment
- Canonical Authority: GitHub source comment; this snapshot does not create ProofLine lifecycle status
---
## 구현 진행 상황
- **대상:** [Discovery] 명시 venue 기반 주문 실행 계약
- **브랜치:** `main`
- **기준:** `main` (`4975d7166fa70e045096503e85c26d740ae92c55`)
- **상태:** 로컬 main 구현·검증·커밋 및 독립 QC PASS — 미푸시, 미배포
- **최종 업데이트:** 2026-08-19 13:17:45 KST
### 구현 계획 및 작업 목록
- [x] venue가 없는 매수·매도 주문을 SOR 주문으로 제출한다.
- 누락과 `null` 모두 같은 기본값을 사용하고 KIS 요청에 SOR를 명시한다.
- [x] 사용자가 지정한 KRX·NXT·SOR venue를 주문 전 과정에서 그대로 보존한다.
- 주문 접수부터 KIS 제출, 재시작 후 조회와 취소까지 원주문 venue가 바뀌지 않아야 한다.
- [x] AUTO venue를 입력·실행·저장 경계에서 제거한다.
- AUTO 요청을 입구에서 거부하고 시간대에 따라 KRX/NXT를 선택하는 동작도 제거한다.
- [x] 기존 저장 데이터의 AUTO venue를 SOR로 안전하게 전환한다.
- 실제 PostgreSQL에서 반복 적용과 저장 제약을 함께 검증한다.
- [x] SOR 원주문 venue와 실제 체결된 KRX/NXT venue를 구분해 보존한다.
- 취소·재시작은 원주문 SOR를 사용하고 체결 원장에는 확인된 실제 거래소만 기록한다.
- [x] 문서·설정·테스트에 폐기된 runtime AUTO 계약이 남아 있지 않은지 점검한다.
- [x] 관련 집중 테스트, 전체 회귀 테스트, PostgreSQL migration 검증과 코드 품질 검사를 실행한다.
- 검증 실패가 승인 범위 안의 결함이면 수정하고, 계획의 의미나 범위를 바꿔야 하면 즉시 중지하고 재승인을 요청한다.
### 진행 기록
- 2026-08-19 13:10:40 KST — 승인된 이슈 본문, `main` branch와 clean worktree, 기준 SHA `4975d7166fa70e045096503e85c26d740ae92c55`를 확인했다. 별도 worktree나 기능 branch를 만들지 않고 구현·검증을 시작한다.
- 2026-08-19 13:12:28 KST — 기존 local main 구현에서 누락/null→SOR, explicit KRX/NXT/SOR 보존, AUTO admission 거부와 wall-clock routing 제거, order/execution venue 분리를 확인했다. 관련 비-DB 집중 테스트 `107 passed`.
- 2026-08-19 13:12:28 KST — 최초 focused 실행은 종료된 이전 QC의 stale PostgreSQL DSN(`127.0.0.1:32778`) 때문에 `107 passed, 1 failed, 5 errors`였으며 코드 실패가 아니었다. 새 disposable PostgreSQL 16에서 migration·outbox·repository `24 passed`를 확인하고 컨테이너를 제거했다.
- 2026-08-19 13:12:28 KST — current 계약과 충돌하던 interface 문서의 과거 KRX-default 설명 및 KIS adapter 주석을 SOR intent normalization 기준으로 수정했다.
- 2026-08-19 13:13:08 KST — repository 전체 AUTO 검색에서 잔존 항목은 admission 거부·migration 변환 검증과 현재 문서의 폐기 설명뿐이며 runtime AUTO 생성·허용 계약은 확인되지 않았다.
- 2026-08-19 13:13:08 KST — 전체 회귀 `1074 passed, 52 skipped`, Ruff·ProofLine validate·diff check PASS. 로컬 main commit `64e4e32f9d7abf7082588b3c4c9a8c0d272762f6`을 생성하고 worktree clean을 확인했다. push·PR·배포·릴리스·실주문은 수행하지 않았다.
- 2026-08-19 13:16:22 KST — 독립 read-only QC PASS: blocker 0, major 0, minor 1. 기능 결함은 없었고 explicit wire `venue: null`을 독립적으로 이름 붙인 테스트가 없다는 minor 검증 공백을 확인했다.
- 2026-08-19 13:16:22 KST — 승인 계획의 누락/null→SOR 검증 범위 안에서 omitted/null parameterized regression을 추가했다. focused `8 passed`, Ruff·diff check PASS, commit `43f6fea7ac805f27fba35586af27f0090a672222`, worktree clean. 독립 재QC를 요청한다.
- 2026-08-19 13:17:45 KST — 독립 재QC PASS: blocker 0, major 0, minor 0. omitted/null 두 케이스의 SOR normalization, broker request, ack 후 slot routing provenance를 독립 확인했다. 최종 HEAD `43f6fea7ac805f27fba35586af27f0090a672222`, worktree clean.
> 각 작업이 실제로 완료되고 검증될 때마다 이 댓글의 체크박스와 진행 기록을 갱신한다. 체크 표시는 구현 완료 또는 해당 검증의 실제 통과를 의미하며, 배포·릴리스 완료를 의미하지 않는다.
+3
View File
@@ -0,0 +1,3 @@
---
id: "line-0006"
---
+62
View File
@@ -0,0 +1,62 @@
---
id: "req-0006"
status: approved
discovery: "dcy-0006"
criteria:
create: []
update: []
retire: []
satisfy:
- "ac-0018"
- "ac-0019"
---
# 명시 venue 기반 주문 실행 계약
## Objective
buy/sell intent의 venue 누락과 explicit null을 SOR로 정규화하고 caller가 명시한 KRX/NXT/SOR를 original order venue로 보존한다. AUTO와 wall-clock venue routing을 runtime·persistence 계약에서 제거하며 기존 AUTO row를 SOR로 전환한다. SOR 원주문 venue와 broker-authoritative actual execution venue를 분리해 submit·ack·cancel·fill polling·restart·ledger/outbox 전 과정에서 routing provenance와 실제 체결 거래소를 각각 정확하게 보존한다.
## Scope
- buy/sell intent의 venue가 누락되거나 explicit null이면 `SOR`를 사용하고 KIS submit request에 `EXCG_ID_DVSN_CD="SOR"`를 명시한다.
- caller가 `KRX`, `NXT`, `SOR`를 명시하면 admission, slot persistence, KIS submit, acknowledgement, restart lookup와 cancel에서 변경하지 않는다.
- `AUTO` intent는 slot transition과 broker submission 전에 `invalid_venue`로 거부한다. runtime source·설정·문서는 AUTO를 생성하거나 허용하지 않고, negative tests와 migration history만 폐기 계약을 언급할 수 있다.
- core는 wall-clock time 또는 session 추정으로 KRX/NXT를 선택하지 않는다.
- existing persisted AUTO slot/outbox row를 SOR로 idempotent하게 전환하고 이후 invalid venue 저장을 DB constraint로 차단한다.
- original `order_venue`는 KRX/NXT/SOR이며 submit·ack·slot·restart·cancel routing authority다.
- actual `execution_venue`는 broker-authoritative KRX/NXT 또는 미확정 NULL이다. KIS `ORD_EXG_GB`와 explicit exchange-id allowlist에서만 결정하여 fill·ledger/outbox에 별도로 기록한다.
- SOR 단독, 누락, unknown code 또는 time으로 actual venue를 추론하지 않는다. SOR 주문에서 actual이 확인되지 않으면 거짓 ledger actual을 만들지 않는다.
- historical outbox의 SOR는 `order_venue=SOR`, actual `venue=NULL`로 보존한다. NULL-only backfill로 migration replay가 정상 order/execution 조합을 재해석하지 않게 한다.
- omitted와 explicit null wire input, KRX/NXT/SOR preservation, AUTO rejection, KIS payload, partial fill·cancel·restart, outbox round-trip 및 migration semantics를 repository tests와 실제 PostgreSQL에서 검증한다.
- 기존 active AC-0018과 AC-0019의 exact 의미를 변경하지 않고 이 Requirement의 구현 evidence를 해당 criterion에 `satisfy`로 결속한다.
## Constraints
- actual venue, terminal execution state 또는 broker acceptance를 wall-clock이나 default로 추론하지 않는다.
- cancel·restart는 stored original venue와 original order identity를 사용한다.
- KIS raw payload, credential, token 또는 connection string을 public wire·document evidence에 기록하지 않는다.
- active AC-0018과 AC-0019의 본문·status를 이 satisfy binding으로 변경하지 않는다.
- TVR session/markets 판단과 strategy policy는 변경하지 않는다.
- Normative Design Documents: 없음. 이 REQ와 만족 대상으로 결속한 active AC-0018·AC-0019가 normative specification을 소유한다.
### Current Implementation Assessment
- 이 Requirement는 승인된 GitHub issue #61의 이미 완료된 local implementation을 현재 ProofLine schema에 사후 명세화한다. 과거 구현이 ProofLine delivery chronology를 따랐다는 뜻은 아니다.
- AC-0018 구현 상태: **satisfied by current local implementation evidence**. 누락/null intent→SOR, explicit KRX/NXT/SOR preservation, AUTO admission rejection, no wall-clock routing, persisted AUTO→SOR와 constraint가 구현·검증되었다.
- AC-0019 구현 상태: **satisfied by current local implementation evidence**. original order venue와 actual execution venue split, KIS fail-closed parser, cancel/restart routing provenance, ledger/outbox split, historical SOR actual NULL과 replay-safe migration이 구현·검증되었다.
- 구현 기반 commits는 `15aeae6930f8c3e6ef9cf659f41278b099a78459`, `7366cadf03fc6002bfd01ecf0cba7c24486bb618`, `359ea098ff717e7f04cf4206dcbc64ad17b47755`다.
- issue #61 계약 문서 정합 commit은 `64e4e32f9d7abf7082588b3c4c9a8c0d272762f6`, explicit null regression commit은 `43f6fea7ac805f27fba35586af27f0090a672222`다.
- 구현자 검증: 비-DB focused `107 passed`, omitted/null focused `8 passed`, disposable PostgreSQL 16 `24 passed`, 전체 `1074 passed, 52 skipped`, Ruff·ProofLine validate·diff check PASS.
- 최초 combined focused의 `1 failed, 5 errors`는 stale PostgreSQL DSN connection refused로 분류했고 새 disposable PostgreSQL 16 semantic suite `24 passed`로 재검증했다.
- 최종 독립 재QC는 omitted/null SOR normalization, broker request, ack 후 slot routing provenance를 검증하여 blocker 0, major 0, minor 0으로 PASS했다. 최종 implementation HEAD는 `43f6fea7ac805f27fba35586af27f0090a672222`, worktree clean이었다.
- 실제 KIS 운영계좌 SOR 주문, 외부 RabbitMQ·database·portfolio-hub, push·PR·remote main·production migration·deployment·release는 수행하지 않았다.
- REQ `approved`, AC `active` 및 `satisfy` binding은 current specification authority와 repository-local implementation assessment를 나타낸다. delivery closure, production validation, release 또는 deployment 완료를 의미하지 않는다.
## Non-Goals
- TVR session·portfolio markets gate, KRX/NXT session policy 또는 strategy intent 생성 판단 변경
- actual venue가 불명확할 때 KRX/NXT를 추정하거나 AUTO routing을 복원하는 fallback
- 실제 KIS 운영 주문·취소, live credential 또는 production broker/account 검증
- push, PR, remote main integration, image publication, production migration, deployment, GitHub Release 또는 issue closure
- 기존 active AC-0018·AC-0019의 의미 변경, 신규 중복 AC 생성 또는 ProofLine lifecycle closure 소급 주장
+3 -2
View File
@@ -49,7 +49,7 @@
- limit_price :: numeric? :: 현재 pending 주문 지정가(side 무관, dcy-012/REQ-002 — 과거 `entry_price`에서 rename). pending 진입(매수/매도 지정가) 시 set, pending 이탈(→holding/→closed) 시 None 으로 clear → 매수 지정가가 매도로 누수되지 않음(issue #10). None 이면 dispatch 시 시장가.
- allocated_capital :: numeric? :: 배정 자본
- order_id / broker_order_id :: str? :: 주문 식별자(자유 주석 / 브로커 핸들)
- venue :: TEXT NOT NULL DEFAULT 'KRX' :: 현재 주문 거래소 구분(AUTO/KRX/NXT/SOR). intent 단계의 AUTO는 KIS 제출 시 실제 KRX/NXT로 교체되며 주문번호와 원자 저장한다. pending 주문·취소까지 보존하고 HOLDING 진입 시 다음 자율주문의 AUTO, INACTIVE 진입 시 KRX로 초기화한다.
- venue :: TEXT NOT NULL DEFAULT 'KRX' :: 원주문/라우팅 거래소(KRX/NXT/SOR). venue 누락 intent는 SOR로 저장하고, pending 주문·재시작·취소까지 보존한다. 실제 KRX/NXT 체결 거래소는 `FillStatus.execution_venue`에서 별도로 확정해 `ledger_outbox.venue`에 기록하고 원주문은 `ledger_outbox.order_venue`에 보존한다.
- cancel_state :: TEXT? :: 취소 요청의 즉시 결과(requested/rejected/unknown). 최종 취소 상태가 아니다. requested는 재시도하지 않고, rejected/unknown만 authoritative open-row 확인과 bounded backoff 뒤 재시도할 수 있다.
- cancel_requested_at :: TIMESTAMPTZ? :: 마지막 취소 시도 예약 시각. 주문 종료·dispatch clear 때 함께 제거한다.
- order_submitted_at :: TIMESTAMPTZ? :: timeout deadline의 immutable 주문 제출 기준점. poll/cancel bookkeeping 및 daemon 재시작에서 보존하고 terminal dispatch clear 때 제거한다.
@@ -153,7 +153,8 @@
- side :: TEXT CHECK ('buy','sell')
- qty / price / fee / tax :: NUMERIC(18,4)
- executed_at :: TIMESTAMPTZ?
- venue :: TEXT NOT NULL DEFAULT 'KRX' :: 실제 제출 거래소. 기존 행은 KRX로 보존한다.
- venue :: TEXT? CHECK (NULL 또는 'KRX'/'NXT') :: broker-authoritative 실제 체결 거래소. 과거 SOR row처럼 실제 거래소를 복원할 수 없으면 NULL이며 임의 추론하지 않는다.
- order_venue :: TEXT NOT NULL DEFAULT 'KRX' CHECK ('KRX'/'NXT'/'SOR') :: 원주문/라우팅 venue. 취소·재시작 감사에 사용한다.
- status :: TEXT CHECK ('pending','completed','conflict_blocked','delivery_failed') — `delivery_failed` 추가(dcy-015, 마이그레이션 007)
- attempts :: INTEGER :: 재시도 누적
- last_outcome :: TEXT? CHECK ('completed','duplicate_completed','retryable_failure','conflict_blocked','permanent_failure','dead_lettered')
+8 -8
View File
@@ -64,7 +64,7 @@
| 패턴 | 표면 | 요청 속성 | 응답 |
|---|---|---|---|
| 슬롯 RPC | `trex.slots.req` | `correlation_id`, `reply_to=amq.rabbitmq.reply-to` | reply-to 큐로 `{slots[], degraded, reason, message}` (REQ-073/074, BAT-035) |
| intent RPC | `trex.intent.req` | `correlation_id` = intent 멱등키, `reply_to=amq.rabbitmq.reply-to`, `delivery_mode=2` | reply-to 큐로 `{intent_id, status:admitted|rejected, slot_id?, reason?}`. **rejected sell** 응답은 additive `retryable: bool` 포함(REQ-007 AC-7/issue #27 — core 소유 reason→retryable, 미인식 기본 true, `bad_request:*` false; admitted/processing/buy 는 미포함). 체결/종료는 응답 아닌 이벤트로 |
| intent RPC | `trex.intent.req` | `correlation_id` = intent 멱등키, `reply_to=amq.rabbitmq.reply-to`, `delivery_mode=2` | reply-to 큐로 `{intent_id, status:admitted|rejected, slot_id?, reason?}`. retryability·broker attempt·KIS failure 정보는 strategy 응답에 포함하지 않는다. 체결/종료는 응답 아닌 이벤트로 |
| update_thresholds | `trex.intent.req` | `action="update_thresholds"`, `reply_to` | reply-to 큐로 `{status:updated|ignored, slot_id, reason?}` (REQ-040) |
| 이벤트 pub/sub | `trex.events` (topic) | routing key `{event_type}.{strategy_id}.{symbol}` | 전략 큐가 자기 `strategy_id` 패턴으로 바인딩 |
@@ -396,7 +396,7 @@ resume_kill_switch 요청·응답 (REQ-046):
### Persistence
- PostgreSQL: `ledger_outbox(correlation_id PK, asset_id, order_id, execution_id, side, qty, price, fee, tax, executed_at, venue, status, attempts, last_outcome, last_error, created_at, updated_at)` — `ON CONFLICT (correlation_id) DO NOTHING` 이 outbox dedup 게이트. `venue`는 Core 내부 실제 제출 거래소이며 Portfolio Hub wire에는 아직 보내지 않는다.
- PostgreSQL: `ledger_outbox(..., venue, order_venue, ...)` — `ON CONFLICT (correlation_id) DO NOTHING` 이 outbox dedup 게이트. `order_venue`는 원주문 KRX/NXT/SOR, `venue`는 broker fill에서 확인한 실제 KRX/NXT 체결 거래소다. Portfolio Hub wire에는 아직 보내지 않는다.
## `OrderRequest` DTO (BAT-004 / REQ-011, BAT-056 / REQ-117)
@@ -414,10 +414,10 @@ resume_kill_switch 요청·응답 (REQ-046):
### Additive Notes (REQ-117)
- `venue` 필드는 BAT-056에서 additive 추가. 기존 orb/tsl 미지정 호출 → 기본값 `"KRX"` 자동 적용 → 하위 호환.
- `OrderRequest`는 AMQP wire 위를 직접 흐르지 않는다. buy/sell intent의 선택적 `venue` 기본은 `AUTO`이고, 명시한 KRX/NXT/SOR는 그대로 슬롯에 보존한다. 허용값 외에는 `invalid_venue`로 admission 전 거부한다.
- KIS 어댑터는 `AUTO`를 KST 세션 기준 실제 KRX/NXT로 확정한 뒤 `EXCG_ID_DVSN_CD`로 전송한다. 결정 불가능 구간은 KRX로 대체하지 않고 주문을 거부한다.
- `OrderAck.venue`의 실제 제출 거래소는 `broker_order_id`와 함께 슬롯에 원자 저장되며 재시작·취소·Core 원장 outbox에서 재사용한다.
- `venue` 필드는 BAT-056에서 additive 추가됐으며, 현재 계약에서 기존 orb/tsl을 포함한 미지정 호출은 `SOR`로 정규화한다.
- `OrderRequest`는 AMQP wire 위를 직접 흐르지 않는다. buy/sell intent의 선택적 `venue` 누락은 `SOR`이고, 명시한 KRX/NXT/SOR는 그대로 슬롯에 보존한다. 폐기된 `AUTO`와 그 밖의 값은 `invalid_venue`로 admission 전 거부한다.
- KIS 어댑터는 KRX/NXT/SOR를 시간과 무관하게 보존해 `EXCG_ID_DVSN_CD`로 전송한다.
- `OrderAck.venue`는 원주문 KRX/NXT/SOR를 `broker_order_id`와 함께 슬롯에 원자 저장하며 재시작·취소에 재사용한다. 실제 체결 거래소는 `FillStatus.execution_venue`의 KRX/NXT로 별도 전달해 outbox `venue`에 기록한다. SOR 또는 미지원 코드는 실제 거래소로 추론하지 않는다.
## `BrokerPort` Protocol 메서드 (BAT-056 / REQ-118)
@@ -461,7 +461,7 @@ get_current_price(symbol: str, market: str = "J") -> Optional[Decimal]
### KIS 어댑터 EXCG 명시화 (REQ-118)
- `submit_order`: body에 `EXCG_ID_DVSN_CD: req.venue` 항상 명시 전송 (이전: 미전송·서버 기본값 의존 → 명시화로 견고성 향상). 실측(2026-07-06): NXT(EXCG=NXT) 주문 rt_cd=0 확인.
- `AUTO` 세션: 08:00~08:49:59 NXT, 09:00:30~15:29:59 KRX, 15:30~20:00 NXT. 그 밖의 시간은 `auto_venue_session_closed`로 fail-closed 한다.
- venue 누락은 `SOR`로 제출하며, 명시 KRX/NXT/SOR는 그대로 제출한다. core는 wall-clock으로 venue를 선택하지 않는다.
- `cancel_order`: body에 `EXCG_ID_DVSN_CD: venue` 명시 전송. 실측(2026-07-06): NXT 취소 rt_cd=0 확인.
- `poll_fill`: KIS 신형 일별주문체결조회 실전 `TTTC0081R`, 모의
`VTTC0081R`을 사용하고 `EXCG_ID_DVSN_CD=ALL`을 전달한다. 일반 주문번호
@@ -634,7 +634,7 @@ trex-core가 `source="trex-core"`, `severity="critical"`로 발행하는 초기
- 2026-06-05 :: BAT-007 — HTTP `/v1` API 인터페이스 제거(adapters/api + fastapi/uvicorn 의존 정리), RabbitMQ messaging 계약 추가(스냅샷 RPC `trex.snapshot.req`, intent RPC `trex.intent.req`, 이벤트 topic `trex.events`, 전략별 durable queue + TTL/max-length, DLQ, publisher confirms, ack-after-commit), `MessagingTransport` Protocol + `TransportHealth` 노출 (REQ-021~026).
- 2026-06-06 :: BAT-008 — `trex.snapshot.req` envelope 계약 정의(`assets[]/view/available_slots/degraded/reason/message`, no price field), `trex.pause.req` 제어 RPC 추가, `PortfolioHubReadPort`/`SnapshotStore`/`PauseStore`/`SnapshotScheduler` 인터페이스, `BrokerPort.get_balance()` 확장, `trex-core` CLI 추가 (REQ-027~033; REQ-030 옵션 D 는 portfolio-hub#8 배포 후).
- 2026-06-10 :: BAT-030 (dcy-020 마감) — buy intent 계약 키 `slot_id` 정본(+`portfolio_id` dual-accept, `trading_date` 제거), 거부 어휘(`unknown_slot`/`already_active`/`capacity_full`/`slot_id_or_portfolio_required`), `slots[]` 5-state + `universe_detached`(trading_date 키 제거), 이벤트 payload trading_date 제거, `available_slots`=admission headroom, SlotService/SlotRepository 자산 중심 계약, 매도 체결 `pending_sell→inactive` (REQ-056~065).
- 2026-06-15 :: BAT-043 (issue #27, REQ-007 CHG-20260615-01) — rejected SellIntent 응답에 additive `retryable: bool`(core 소유 reason→retryable 매핑, 미인식 기본 true, `bad_request:*`/terminal false). 손절매 재시도 안전 경로 decoupling. 완전 additive(admitted/processing/buy·기존 필드 불변).
- 2026-06-15 :: BAT-043 (issue #27, REQ-007 CHG-20260615-01) — rejected SellIntent 응답에 additive `retryable: bool`을 도입했으나, GitHub #60 승인 계약으로 폐기됐다. 현재 strategy RPC는 retryability·broker attempt·KIS failure를 전달하지 않는다.
- 2026-06-15 :: BAT-042 (dcy-028) — slot strategy-state 계약: 신규 write RPC `trex.slots.strategy_state.set`(occupancy_seq+version CAS, reject reason 집합 `occupancy_changed`/`version_conflict`/`slot_inactive`/`state_too_large`/`bad_request`), `trex.slots.req` 행에 additive `occupancy_seq`+`strategy_state` 맵(REQ-073 AC-7/REQ-074 AC-6, opaque UTF-8+size cap, strategy_* reasoning 필드와 구분). close(`→INACTIVE`) 시 state 자동 삭제 (REQ-079~082).
- 2026-06-11 :: BAT-035 (dcy-025) — `trex.snapshot.req` → `trex.slots.req` lockstep 교체: 요청 `{filter, spy}`, 응답 `{slots[], degraded, reason, message}`. 슬롯 row 에 hub `asset_quantity`/`cash_balance` + `warned`/`cash_estimated`/`watchdog`/`paused` 병합(REQ-073/074). `trex.snapshot.req` envelope(`assets[]`/`available_slots`/view enum) 제거(REQ-028 Deprecated). strategy 필드 제거(REQ-074 AC-5). CLI `universe`/`slots` → `trex.slots.req`(spy=true). `trex.direct` channel_type `snapshot` → `slots`.
- 2026-06-11 :: BAT-036 (dcy-024) — `safety_sell_enabled: bool=True` per-instance TOML 플래그 추가(REQ-048 CHG-01). `false` 시 `trex-safety-sell` worker 미기동 + WARNING 로그(REQ-005 CHG-01).
+1 -1
View File
@@ -264,7 +264,7 @@
- 슬롯 `limit_price` 생애주기(dcy-012/REQ-002): INACTIVE→PENDING_BUY(매수 지정가 set) → PENDING_BUY→HOLDING(clear) → HOLDING→PENDING_SELL(매도 지정가 set 또는 None=시장가) → PENDING_SELL→INACTIVE(clear). 롤백(→INACTIVE) 전이에서도 clear. 외부 취소 후 holding 복귀에서도 clear 되어 재매도는 시장가.
- **실행 정책 생애주기(dcy-022/REQ-068)**: `timeout_sec`·`slippage_pct` 는 `limit_price` 와 동일한 생애주기(PENDING_* 진입 시 set, HOLDING/INACTIVE 탈출 시 clear). 슬롯의 `updated_at` 이 dispatch 시각 proxy 로 사용된다(mark_dispatched 가 갱신, stale-alert 와 동일 방법).
- 어댑터: paper(결정적 async 더블) / KIS(모의투자 검증, 실계좌 게이팅).
- **venue 전달 경로(BAT-056/REQ-117/118, BAT-059/REQ-124, dcy-041)**: buy/sell intent `venue`(기본 AUTO) → pending `Slot.venue` → KIS 제출 시 KST 세션별 실제 KRX/NXT 확정 → `OrderAck.venue`와 주문번호 원자 저장 → 취소·재시작·Core outbox에서 실제 거래소 재사용. 허용값은 AUTO/KRX/NXT/SOR이며 invalid는 슬롯 전이 전 거부한다. HOLDING은 다음 자율매도를 위해 AUTO, INACTIVE는 하위 호환을 위해 KRX로 초기화한다.
- **venue 전달 경로(BAT-056/REQ-117/118, BAT-059/REQ-124, dcy-041, GitHub #61)**: buy/sell intent `venue`(누락 시 SOR) → pending `Slot.venue` → KIS에 명시 KRX/NXT/SOR 제출 → `OrderAck.venue`와 주문번호 원자 저장 → 취소·재시작·Core outbox에서 실제 거래소 재사용. AUTO와 invalid 값은 슬롯 전이 전 거부한다. HOLDING은 다음 주문을 위해 SOR, INACTIVE는 하위 호환을 위해 KRX로 초기화한다.
### 계좌조회 단기 복구 (dcy-041 / GitHub #45)
+49 -43
View File
@@ -91,38 +91,28 @@ def test_order_request_venue_nxt():
assert req.venue == "NXT"
@pytest.mark.parametrize(
("at", "expected"),
[
(datetime(2026, 7, 29, 8, 0, tzinfo=timezone(timedelta(hours=9))), "NXT"),
(datetime(2026, 7, 29, 8, 49, 59, tzinfo=timezone(timedelta(hours=9))), "NXT"),
(datetime(2026, 7, 29, 9, 0, 30, tzinfo=timezone(timedelta(hours=9))), "KRX"),
(datetime(2026, 7, 29, 15, 29, 59, tzinfo=timezone(timedelta(hours=9))), "KRX"),
(datetime(2026, 7, 29, 15, 30, tzinfo=timezone(timedelta(hours=9))), "NXT"),
(datetime(2026, 7, 29, 20, 0, tzinfo=timezone(timedelta(hours=9))), "NXT"),
],
)
def test_auto_venue_resolves_by_kst_session(at, expected):
assert resolve_order_venue("AUTO", at) == expected
@pytest.mark.parametrize("venue", ["KRX", "NXT", "SOR"])
@pytest.mark.parametrize(
"at",
[
datetime(2026, 7, 29, 7, 59, 59, tzinfo=timezone(timedelta(hours=9))),
datetime(2026, 7, 29, 8, 50, tzinfo=timezone(timedelta(hours=9))),
datetime(2026, 7, 29, 9, 0, 29, tzinfo=timezone(timedelta(hours=9))),
datetime(2026, 7, 29, 8, 0, tzinfo=timezone(timedelta(hours=9))),
datetime(2026, 7, 29, 8, 55, tzinfo=timezone(timedelta(hours=9))),
datetime(2026, 7, 29, 20, 0, 1, tzinfo=timezone(timedelta(hours=9))),
],
)
def test_auto_venue_fails_closed_outside_supported_sessions(at):
with pytest.raises(ValueError, match="auto_venue_session_closed"):
def test_explicit_venue_is_preserved_independent_of_time(venue, at):
assert resolve_order_venue(venue, at) == venue
def test_auto_venue_is_rejected():
at = datetime(2026, 7, 29, 8, 1, tzinfo=timezone(timedelta(hours=9)))
with pytest.raises(ValueError, match="unsupported_order_venue"):
resolve_order_venue("AUTO", at)
def test_submit_auto_uses_nxt_and_reports_actual_venue(monkeypatch):
def test_submit_sor_preserves_sor(monkeypatch):
captured = {}
at = datetime(2026, 7, 29, 8, 1, tzinfo=timezone(timedelta(hours=9)))
at = datetime(2026, 7, 29, 8, 55, tzinfo=timezone(timedelta(hours=9)))
def fake_post(url, headers=None, json=None, timeout=None):
captured["body"] = json
@@ -134,39 +124,55 @@ def test_submit_auto_uses_nxt_and_reports_actual_venue(monkeypatch):
monkeypatch.setattr(kis_mod.httpx, "post", fake_post)
ack = broker.submit_order(
OrderRequest(
slot_id="s-auto",
slot_id="s-sor",
side="buy",
symbol="005930",
qty=1,
venue="AUTO",
venue="SOR",
)
)
assert ack.accepted is True
assert ack.venue == "NXT"
assert captured["body"]["EXCG_ID_DVSN_CD"] == "NXT"
assert ack.venue == "SOR"
assert captured["body"]["EXCG_ID_DVSN_CD"] == "SOR"
def test_submit_auto_outside_session_rejects_without_http(monkeypatch):
at = datetime(2026, 7, 29, 8, 55, tzinfo=timezone(timedelta(hours=9)))
broker = _mock_broker(clock=lambda: at)
@pytest.mark.parametrize(
("row", "expected"),
[
({"ord_exg_gb": "1"}, "KRX"),
({"ord_exg_gb": "2"}, "NXT"),
({"ord_exg_gb": "3"}, "KRX"),
({"ord_exg_gb": "4"}, "NXT"),
({"excg_id_dvsn_cd": "KRX"}, "KRX"),
({"excg_id_dvsn_cd": "NXT"}, "NXT"),
({"excg_id_dvsn_cd": "SOR-KRX"}, "KRX"),
({"excg_id_dvsn_Cd": "SOR-NXT"}, "NXT"),
({"excg_id_dvsn_cd": "SOR"}, None),
({"excg_dvsn_cd": "02"}, None),
({}, None),
],
)
def test_kis_execution_venue_parser_is_allowlisted(row, expected):
assert KISBroker._execution_venue_from_row(row) == expected
def unexpected_post(*args, **kwargs):
raise AssertionError("AUTO session rejection must happen before HTTP")
monkeypatch.setattr(kis_mod.httpx, "post", unexpected_post)
ack = broker.submit_order(
OrderRequest(
slot_id="s-auto-closed",
side="buy",
symbol="005930",
qty=1,
venue="AUTO",
)
def test_kis_fill_status_carries_sor_actual_execution_venue():
status = KISBroker._fill_status_from_row(
{
"ord_qty": "10",
"tot_ccld_qty": "10",
"avg_prvs": "70000",
"ord_dt": "20260819",
"ord_gno_brno": "12345",
"odno": "0000000001",
"excg_id_dvsn_cd": "NXT",
},
side="buy",
today="20260819",
fallback_odno="0000000001",
)
assert ack.accepted is False
assert ack.reason == "auto_venue_session_closed"
assert status.execution_venue == "NXT"
# ---------------------------------------------------------------------------
@@ -7,10 +7,16 @@ iteration: EXPECTED_SLOT_FIELDS (code contract) vs daily_slot actual columns
from __future__ import annotations
import psycopg
import pytest
from datetime import datetime, timezone
from trex_core.adapters.persistence.migrate import apply_migrations, migration_files
from trex_core.adapters.persistence.postgresql import PostgreSQLSlotRepository
from trex_core.domain.slot import EXPECTED_SLOT_FIELDS, SlotService, SlotState
from trex_core.adapters.persistence.postgresql import (
PostgreSQLLedgerOutbox,
PostgreSQLSlotRepository,
)
from trex_core.application.ledger_port import LedgerTrade
from trex_core.domain.slot import EXPECTED_SLOT_FIELDS
_EXPECTED_TABLES = {
"daily_slot",
@@ -64,20 +70,90 @@ def test_apply_migrations_is_idempotent(pg_dsn):
apply_migrations(pg_dsn)
def test_migration_replay_accepts_existing_auto_venue_row(pg_clean):
def test_migration_replay_converts_existing_auto_venue_row_to_sor(pg_clean):
repo = PostgreSQLSlotRepository(pg_clean)
service = SlotService(repo, instance_key="migration-auto")
repo.reconcile_universe("migration-auto", {"pf-auto": "005930"})
slot = repo.find_slot_by_portfolio("migration-auto", "pf-auto")
service.transit_slot(
slot.slot_id,
SlotState.INACTIVE,
SlotState.PENDING_BUY,
reason="migration_replay",
actor="test",
venue="AUTO",
)
assert slot is not None
# Simulate a row written before migration 023 tightened the constraint.
with psycopg.connect(pg_clean) as conn:
with conn.cursor() as cur:
cur.execute("ALTER TABLE daily_slot DROP CONSTRAINT daily_slot_venue_check")
cur.execute(
"UPDATE daily_slot SET venue = 'AUTO' WHERE slot_id = %s",
(slot.slot_id,),
)
conn.commit()
apply_migrations(pg_clean)
assert repo.fetch_slot(slot.slot_id).venue == "AUTO"
assert repo.fetch_slot(slot.slot_id).venue == "SOR"
with psycopg.connect(pg_clean) as conn:
with conn.cursor() as cur:
with pytest.raises(psycopg.errors.CheckViolation):
cur.execute(
"UPDATE daily_slot SET venue = 'AUTO' WHERE slot_id = %s",
(slot.slot_id,),
)
def test_migration_024_separates_legacy_sor_and_is_replay_safe(pg_clean):
outbox = PostgreSQLLedgerOutbox(pg_clean)
normal = LedgerTrade(
asset_id="PF-NORMAL",
order_id="O-NORMAL",
execution_id="E-NORMAL",
side="buy",
qty=1,
price=1000,
executed_at=datetime(2026, 8, 19, tzinfo=timezone.utc),
venue="NXT",
order_venue="KRX",
)
legacy = LedgerTrade(
asset_id="PF-LEGACY",
order_id="O-LEGACY",
execution_id="E-LEGACY",
side="buy",
qty=1,
price=1000,
executed_at=datetime(2026, 8, 19, tzinfo=timezone.utc),
venue="KRX",
order_venue="SOR",
)
outbox.enqueue(normal)
outbox.enqueue(legacy)
# Recreate a pre-024 SOR row: one venue column carried routing provenance,
# and no separate order_venue was available.
with psycopg.connect(pg_clean) as conn:
with conn.cursor() as cur:
cur.execute("ALTER TABLE ledger_outbox DROP CONSTRAINT ledger_outbox_venue_check")
cur.execute("ALTER TABLE ledger_outbox ALTER COLUMN order_venue DROP NOT NULL")
cur.execute(
"UPDATE ledger_outbox SET venue='SOR', order_venue=NULL "
"WHERE correlation_id=%s",
(legacy.correlation_id,),
)
conn.commit()
apply_migrations(pg_clean)
apply_migrations(pg_clean)
normal_row = outbox.get(normal.correlation_id)
legacy_row = outbox.get(legacy.correlation_id)
assert normal_row is not None
assert normal_row.trade.venue == "NXT"
assert normal_row.trade.order_venue == "KRX"
assert legacy_row is not None
assert legacy_row.trade.venue is None
assert legacy_row.trade.order_venue == "SOR"
with psycopg.connect(pg_clean) as conn:
with conn.cursor() as cur:
with pytest.raises(psycopg.errors.CheckViolation):
cur.execute(
"UPDATE ledger_outbox SET venue='SOR' WHERE correlation_id=%s",
(normal.correlation_id,),
)
@@ -20,7 +20,8 @@ def _trade(execution_id="paper:1:10") -> LedgerTrade:
return LedgerTrade(
asset_id="PF-1", order_id="ORD-1", execution_id=execution_id,
side="buy", qty=10, price=1000.0, fee=1.5, tax=0.0,
executed_at=datetime(2026, 6, 4, tzinfo=timezone.utc), venue="NXT",
executed_at=datetime(2026, 6, 4, tzinfo=timezone.utc),
venue="NXT", order_venue="SOR",
)
@@ -33,6 +34,7 @@ def test_enqueue_persists_and_is_idempotent(pg_clean):
assert len(pending) == 1
assert pending[0].status is WorkItemStatus.PENDING
assert pending[0].trade.venue == "NXT"
assert pending[0].trade.order_venue == "SOR"
def test_writer_completes_persisted_item(pg_clean):
+2 -1
View File
@@ -116,7 +116,8 @@ def test_partial_fill_then_cancel_records_and_keeps_remainder():
broker.balance = {"005930": 6}
broker.responder = lambda side: FillStatus(
state="partially_filled", filled_qty=4, avg_price=1100.0,
execution_id="exec-partial", fee=0.5, tax=0.0, cancelled=True,
execution_id="exec-partial", fee=0.5, tax=0.0,
execution_venue="KRX", cancelled=True,
)
r = execution.run_once()
slot = repo.fetch_slot(sid)
@@ -148,6 +148,7 @@ def _make_filled_status(
execution_id=execution_id,
fee=fee,
tax=tax,
execution_venue="KRX",
)
@@ -167,6 +168,7 @@ def _make_partial_cancel_status(
execution_id=execution_id,
fee=fee,
tax=tax,
execution_venue="KRX",
cancelled=True,
)
+2 -1
View File
@@ -59,7 +59,8 @@ def test_buy_fill_enqueues_one_ledger_item_and_writer_records_it():
assert (t.asset_id, t.side, t.qty, t.price) == ("PF-1", "buy", 10, 1000.0)
assert t.execution_id.startswith("paper:PAPER-")
assert t.fee > 0.0 and t.tax == 0.0
assert t.venue == "AUTO"
assert t.order_venue == "SOR"
assert t.venue == "KRX" # paper's deterministic SOR execution exchange
def test_sell_fill_enqueues_sell_ledger_item():
@@ -253,6 +253,33 @@ class TestOrderResultLogging:
assert all(r.levelno == logging.ERROR for r in rejects)
assert "호가단위" in rejects[0].getMessage()
def test_sell_reject_returns_to_holding_without_new_attempt(self):
broker = _RecordingBroker()
repo, _, intents, execution = _wire(broker)
slot_id = _buy_to_pending(intents)
assert slot_id is not None
execution.run_once()
holding = repo.fetch_slot(slot_id)
assert holding is not None and holding.status is SlotState.HOLDING
intents.submit_sell(SellIntent(intent_id="s1", slot_id=slot_id))
broker.submit_order = lambda req: (
broker.orders.append(req)
or OrderAck(accepted=False, reason="broker_rejected", venue=req.venue)
)
result = execution.run_once()
recovered = repo.fetch_slot(slot_id)
assert recovered is not None
assert recovered.status is SlotState.HOLDING
assert recovered.qty == 10
assert recovered.broker_order_id is None
assert result.rolled_back == 1
assert len([order for order in broker.orders if order.side == "sell"]) == 1
execution.run_once()
assert len([order for order in broker.orders if order.side == "sell"]) == 1
def test_normal_fill_emits_no_error(self, caplog):
broker = _RecordingBroker()
repo, svc, intents, execution = _wire(broker)
+66 -74
View File
@@ -1,18 +1,12 @@
"""rejected SellIntent `retryable` flag (issue #27 / REQ-007 CHG-20260615-01).
Additive: only on intent_type="sell" + status="rejected". Maps reason→retryable
via the core-owned table (unrecognized → True, safety default; bad_request → False).
admitted / processing / buy responses must NOT carry the field.
"""
"""Strategy RPC responses never expose broker retryability (GitHub #60)."""
from __future__ import annotations
from uuid import uuid4
from trex_core.adapters.persistence.in_memory_intent_store import InMemoryIntentStore
from trex_core.application.intents import IntentService
from trex_core.application.messaging import RpcRequest
from trex_core.application.messaging_handlers import (
_sell_reject_retryable,
make_intent_rpc_handler,
)
from trex_core.application.messaging_handlers import make_intent_rpc_handler
from trex_core.domain.slot import SlotService, SlotState
from trex_core.domain.slot.in_memory_repository import InMemorySlotRepository
@@ -22,9 +16,14 @@ INST = "default"
def _wire():
repo = InMemorySlotRepository()
svc = SlotService(repo, instance_key=INST)
intents = IntentService(svc, repo, InMemoryIntentStore(),
resolve_symbol=lambda pid: "005930",
instance_key=INST, max_active_slots=5)
intents = IntentService(
svc,
repo,
InMemoryIntentStore(),
resolve_symbol=lambda pid: "005930",
instance_key=INST,
max_active_slots=5,
)
repo.reconcile_universe(INST, {"PF-1": "SYM"})
handler = make_intent_rpc_handler(intents)
slot = repo.list_slots(INST)[0]
@@ -32,72 +31,65 @@ def _wire():
def _sell(handler, slot_id, intent_id="s1"):
return handler(RpcRequest(payload={
"intent_type": "sell", "intent_id": intent_id, "slot_id": str(slot_id),
}, correlation_id=intent_id))
return handler(
RpcRequest(
payload={
"intent_type": "sell",
"intent_id": intent_id,
"slot_id": str(slot_id),
},
correlation_id=intent_id,
)
)
class TestRetryableMapping:
def test_each_reason_maps(self):
assert _sell_reject_retryable("slot_state_changed") is True
assert _sell_reject_retryable("slot_not_holding:pending_buy") is True
assert _sell_reject_retryable("duplicate_in_flight") is True
assert _sell_reject_retryable("slot_not_found") is False
assert _sell_reject_retryable("slot_not_holding:inactive") is False
assert _sell_reject_retryable("slot_not_holding:pending_sell") is False
assert _sell_reject_retryable("slot_not_holding:error") is False
def test_unrecognized_defaults_true(self):
assert _sell_reject_retryable("some_future_reason") is True
assert _sell_reject_retryable(None) is True
def test_bad_request_is_false(self):
assert _sell_reject_retryable("bad_request:KeyError('slot_id')") is False
def test_rejected_sell_does_not_expose_retryability():
_, _, _, handler, slot = _wire()
response = _sell(handler, slot.slot_id)
assert response.payload["status"] == "rejected"
assert response.payload["reason"] == "slot_not_holding:inactive"
assert "retryable" not in response.payload
class TestResponseField:
def test_rejected_sell_inactive_slot_has_retryable_false(self):
# slot is inactive (never bought) → slot_not_holding:inactive → terminal
repo, svc, intents, handler, slot = _wire()
resp = _sell(handler, slot.slot_id)
assert resp.payload["status"] == "rejected"
assert resp.payload["reason"] == "slot_not_holding:inactive"
assert resp.payload["retryable"] is False
def test_unknown_slot_sell_does_not_expose_retryability():
_, _, _, handler, _ = _wire()
response = _sell(handler, uuid4())
assert response.payload["status"] == "rejected"
assert response.payload["reason"] == "slot_not_found"
assert "retryable" not in response.payload
def test_rejected_sell_unknown_slot_false(self):
from uuid import uuid4
_, _, _, handler, _ = _wire()
resp = _sell(handler, uuid4())
assert resp.payload["status"] == "rejected"
assert resp.payload["reason"] == "slot_not_found"
assert resp.payload["retryable"] is False
def test_bad_request_sell_carries_retryable_false(self):
_, _, _, handler, _ = _wire()
resp = handler(RpcRequest(payload={
"intent_type": "sell", "intent_id": "x", # missing slot_id
}, correlation_id="x"))
assert resp.payload["status"] == "rejected"
assert resp.payload["reason"].startswith("bad_request")
assert resp.payload["retryable"] is False
def test_malformed_sell_does_not_expose_retryability():
_, _, _, handler, _ = _wire()
response = handler(
RpcRequest(
payload={"intent_type": "sell", "intent_id": "x"},
correlation_id="x",
)
)
assert response.payload["status"] == "rejected"
assert response.payload["reason"].startswith("bad_request")
assert "retryable" not in response.payload
def test_admitted_sell_has_no_retryable(self):
repo, svc, intents, handler, slot = _wire()
# bring slot to holding so the sell is admitted
svc.transit_slot(slot.slot_id, SlotState.INACTIVE, SlotState.PENDING_BUY,
reason="buy", actor="t")
svc.transit_slot(slot.slot_id, SlotState.PENDING_BUY, SlotState.HOLDING,
reason="filled", actor="t", qty=10, avg_price=100)
resp = _sell(handler, slot.slot_id)
assert resp.payload["status"] == "admitted"
assert "retryable" not in resp.payload
def test_buy_rejection_has_no_retryable(self):
# buy on a non-existent slot → rejected, but buy responses omit retryable
from uuid import uuid4
_, _, _, handler, _ = _wire()
resp = handler(RpcRequest(payload={
"intent_type": "buy", "intent_id": "b1", "slot_id": str(uuid4()),
}, correlation_id="b1"))
assert resp.payload["status"] == "rejected"
assert "retryable" not in resp.payload
def test_admitted_sell_does_not_expose_retryability():
_, svc, _, handler, slot = _wire()
svc.transit_slot(
slot.slot_id,
SlotState.INACTIVE,
SlotState.PENDING_BUY,
reason="buy",
actor="test",
)
svc.transit_slot(
slot.slot_id,
SlotState.PENDING_BUY,
SlotState.HOLDING,
reason="filled",
actor="test",
qty=10,
avg_price=100,
)
response = _sell(handler, slot.slot_id)
assert response.payload["status"] == "admitted"
assert "retryable" not in response.payload
+18 -9
View File
@@ -3,6 +3,8 @@ from __future__ import annotations
from uuid import UUID
import pytest
from trex_core.adapters.persistence.in_memory_intent_store import InMemoryIntentStore
from trex_core.application.broker_port import (
BalanceItem,
@@ -31,7 +33,7 @@ class RecordingBroker:
return OrderAck(
accepted=True,
broker_order_id=f"order-{len(self.orders)}",
venue=self.actual_venue or req.venue,
venue=req.venue,
)
def poll_fill(self, broker_order_id: str, *, side: str, symbol: str) -> FillStatus:
@@ -96,7 +98,8 @@ def test_nxt_buy_wire_value_reaches_broker_order() -> None:
assert broker.orders[0].venue == "NXT"
def test_invalid_venue_is_rejected_before_slot_transition() -> None:
@pytest.mark.parametrize("invalid_venue", ["AUTO", "UNKNOWN"])
def test_invalid_venue_is_rejected_before_slot_transition(invalid_venue: str) -> None:
repo, intents, _, _ = _wire()
handler = make_intent_rpc_handler(intents)
@@ -107,7 +110,7 @@ def test_invalid_venue_is_rejected_before_slot_transition() -> None:
"intent_id": "bad-venue",
"portfolio_id": "PF-1",
"qty": 1,
"venue": "UNKNOWN",
"venue": invalid_venue,
},
correlation_id="bad-venue",
)
@@ -118,7 +121,10 @@ def test_invalid_venue_is_rejected_before_slot_transition() -> None:
assert repo.list_slots("default")[0].status is SlotState.INACTIVE
def test_omitted_wire_venue_is_auto_then_actual_venue_is_persisted() -> None:
@pytest.mark.parametrize("venue_field", [{}, {"venue": None}], ids=["omitted", "null"])
def test_missing_wire_venue_remains_sor_for_cancel_and_restart(
venue_field: dict[str, object],
) -> None:
repo = InMemorySlotRepository()
service = SlotService(repo)
intents = IntentService(
@@ -139,6 +145,7 @@ def test_omitted_wire_venue_is_auto_then_actual_venue_is_persisted() -> None:
"intent_id": "auto-buy",
"portfolio_id": "PF-1",
"qty": 1,
**venue_field,
},
correlation_id="auto-buy",
)
@@ -146,11 +153,13 @@ def test_omitted_wire_venue_is_auto_then_actual_venue_is_persisted() -> None:
slot_id = UUID(response.payload["slot_id"])
pending = repo.fetch_slot(slot_id)
assert pending is not None and pending.venue == "AUTO"
assert pending is not None and pending.venue == "SOR"
execution.run_once()
dispatched = repo.fetch_slot(slot_id)
assert broker.orders[0].venue == "AUTO"
assert dispatched is not None and dispatched.venue == "NXT"
assert broker.orders[0].venue == "SOR"
# Ack cannot turn SOR routing provenance into an execution venue. Actual
# KRX/NXT is established by fill polling and stored on the ledger trade.
assert dispatched is not None and dispatched.venue == "SOR"
def test_inactive_transition_resets_venue_to_krx() -> None:
@@ -180,7 +189,7 @@ def test_inactive_transition_resets_venue_to_krx() -> None:
assert reset.venue == "KRX"
def test_holding_transition_resets_next_order_venue_to_auto() -> None:
def test_holding_transition_resets_next_order_venue_to_sor() -> None:
repo, intents, _, _ = _wire()
decision = intents.submit_buy(
BuyIntent(
@@ -201,7 +210,7 @@ def test_holding_transition_resets_next_order_venue_to_auto() -> None:
qty=1,
avg_price=1000,
)
assert holding.venue == "AUTO"
assert holding.venue == "SOR"
def test_operator_cancel_uses_original_nxt_venue() -> None:
+33 -19
View File
@@ -15,7 +15,7 @@ import base64
import hashlib
import json
from dataclasses import replace
from datetime import datetime, time, timedelta, timezone
from datetime import datetime, timedelta, timezone
from decimal import Decimal, InvalidOperation
from time import monotonic
from typing import Callable, Optional
@@ -40,7 +40,7 @@ _MOCK_HINTS = ("openapivts", "virtual", "mock")
_FILL_POLL_MIN_INTERVAL_SECONDS = 5.0
_FILL_POLL_TRANSPORT_BACKOFF_SECONDS = 30.0
_SUBMISSION_LOOKUP_GRACE_SECONDS = 90.0
_SUPPORTED_ORDER_VENUES = frozenset({"AUTO", "KRX", "NXT", "SOR"})
_SUPPORTED_ORDER_VENUES = frozenset({"KRX", "NXT", "SOR"})
def _balance_http_error_code(status: Optional[int]) -> str:
@@ -54,26 +54,15 @@ def _balance_http_error_code(status: Optional[int]) -> str:
def resolve_order_venue(venue: str, at: datetime) -> str:
"""Resolve AUTO to the venue that accepts domestic-stock orders at `at`.
"""Validate and preserve an explicit KRX/NXT/SOR order venue.
The gaps are intentional fail-closed intervals. They prevent an AUTO order
from silently falling back to KRX while the opening venue is indeterminate.
Explicit KRX/NXT/SOR values are preserved.
``at`` remains in the signature for compatibility with existing callers;
venue selection is deliberately independent of wall-clock time.
"""
normalized = str(venue).strip().upper()
if normalized not in _SUPPORTED_ORDER_VENUES:
raise ValueError("unsupported_order_venue")
if normalized != "AUTO":
return normalized
current = at.astimezone(_KST).time().replace(tzinfo=None)
if time(8, 0) <= current < time(8, 50):
return "NXT"
if time(9, 0, 30) <= current < time(15, 30):
return "KRX"
if time(15, 30) <= current <= time(20, 0):
return "NXT"
raise ValueError("auto_venue_session_closed")
return normalized
def _safe_int(v: object) -> Optional[int]:
@@ -284,8 +273,8 @@ class KISBroker:
"ORD_DVSN": resolved_req.order_type,
"ORD_QTY": str(resolved_req.qty),
"ORD_UNPR": str(resolved_req.limit_price or 0),
# REQ-118: always send EXCG_ID_DVSN_CD from req.venue (default "KRX").
# Previously omitted (server defaulted to KRX); explicit is more robust.
# The intent layer normalizes missing venue to SOR. The broker
# adapter always forwards the resulting explicit order venue.
# Real-account NXT order confirmed rt_cd=0 on 2026-07-06.
"EXCG_ID_DVSN_CD": actual_venue,
}
@@ -584,6 +573,27 @@ class KISBroker:
delta = (ordered_at - submitted_at).total_seconds()
return -5.0 <= delta <= 120.0
@staticmethod
def _execution_venue_from_row(row: dict) -> str | None:
"""Parse broker-authoritative KRX/NXT without time inference."""
notice_code = str(row.get("ord_exg_gb") or row.get("ORD_EXG_GB") or "").strip()
notice_map = {"1": "KRX", "2": "NXT", "3": "KRX", "4": "NXT"}
if notice_code in notice_map:
return notice_map[notice_code]
for key in (
"excg_id_dvsn_cd",
"excg_id_dvsn_Cd",
"EXCG_ID_DVSN_CD",
"execution_venue",
):
value = str(row.get(key) or "").strip().upper()
if value in {"KRX", "SOR-KRX"}:
return "KRX"
if value in {"NXT", "SOR-NXT"}:
return "NXT"
# SOR is routing provenance, not an execution exchange.
return None
@staticmethod
def _fill_status_from_row(
row: dict,
@@ -592,6 +602,7 @@ class KISBroker:
today: str,
fallback_odno: str,
) -> FillStatus:
execution_venue = KISBroker._execution_venue_from_row(row)
ord_qty = _safe_int(row.get("ord_qty")) or 0
ccld_qty = _safe_int(row.get("tot_ccld_qty")) or 0
rejected_qty = _safe_int(row.get("rjct_qty")) or 0
@@ -634,6 +645,7 @@ class KISBroker:
execution_id=execution_id,
fee=fee,
tax=tax,
execution_venue=execution_venue,
raw=row,
)
# 0 < ccld_qty < ord_qty
@@ -657,6 +669,7 @@ class KISBroker:
execution_id=execution_id,
fee=fee,
tax=tax,
execution_venue=execution_venue,
cancelled=True,
raw=row,
)
@@ -664,6 +677,7 @@ class KISBroker:
state="partially_filled",
filled_qty=ccld_qty,
avg_price=float(avg) if avg else None,
execution_venue=execution_venue,
raw=row,
)
+5
View File
@@ -31,6 +31,9 @@ class _Order:
self.side = req.side
self.symbol = req.symbol
self.qty = req.qty
# Deterministic SOR simulation: paper routes SOR to KRX while retaining
# req.venue on the acknowledgement as submission provenance.
self.execution_venue = "KRX" if req.venue == "SOR" else req.venue
self.price = float(req.limit_price) if req.limit_price is not None else 1000.0
self.polls = 0
self.filled = 0
@@ -118,11 +121,13 @@ class PaperBroker:
return FillStatus(
state="filled", filled_qty=o.filled, avg_price=o.price,
execution_id=execution_id, fee=fee, tax=tax,
execution_venue=o.execution_venue,
)
return FillStatus(
state="partially_filled",
filled_qty=o.filled,
avg_price=o.price,
execution_venue=o.execution_venue,
raw={"order_open_confirmed": True},
)
+5 -3
View File
@@ -548,7 +548,7 @@ class _PgIntentRecord:
_OUTBOX_COLUMNS = (
"correlation_id, asset_id, order_id, execution_id, side, qty, price, "
"fee, tax, executed_at, status, attempts, last_outcome, last_error, "
"created_at, updated_at, next_retry_at, venue"
"created_at, updated_at, next_retry_at, venue, order_venue"
)
@@ -565,8 +565,8 @@ class PostgreSQLLedgerOutbox:
cur.execute(
"INSERT INTO ledger_outbox "
"(correlation_id, asset_id, order_id, execution_id, side, "
" qty, price, fee, tax, executed_at, venue) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) "
" qty, price, fee, tax, executed_at, venue, order_venue) "
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) "
"ON CONFLICT (correlation_id) DO NOTHING",
(
trade.correlation_id,
@@ -580,6 +580,7 @@ class PostgreSQLLedgerOutbox:
trade.tax,
trade.executed_at,
trade.venue,
trade.order_venue,
),
)
conn.commit()
@@ -684,6 +685,7 @@ class PostgreSQLLedgerOutbox:
tax=f(row[8]),
executed_at=row[9],
venue=row[17],
order_venue=row[18],
)
return LedgerWorkItem(
correlation_id=row[0],
@@ -0,0 +1,16 @@
-- GitHub #61: remove Core-owned wall-clock AUTO routing.
-- Existing durable AUTO values are normalized before the stricter constraints.
UPDATE daily_slot SET venue = 'SOR' WHERE venue = 'AUTO';
UPDATE ledger_outbox SET venue = 'SOR' WHERE venue = 'AUTO';
ALTER TABLE daily_slot
DROP CONSTRAINT IF EXISTS daily_slot_venue_check;
ALTER TABLE daily_slot
ADD CONSTRAINT daily_slot_venue_check
CHECK (venue IN ('KRX', 'NXT', 'SOR'));
ALTER TABLE ledger_outbox
DROP CONSTRAINT IF EXISTS ledger_outbox_venue_check;
ALTER TABLE ledger_outbox
ADD CONSTRAINT ledger_outbox_venue_check
CHECK (venue IN ('KRX', 'NXT', 'SOR'));
@@ -0,0 +1,33 @@
-- GitHub #61: keep original submission venue separate from actual execution venue.
-- The nullable add + NULL-only backfill makes replay safe: rows written after
-- this migration already have order_venue and are never reinterpreted.
ALTER TABLE ledger_outbox
ADD COLUMN IF NOT EXISTS order_venue TEXT;
UPDATE ledger_outbox
SET order_venue = venue
WHERE order_venue IS NULL
AND venue IN ('KRX', 'NXT', 'SOR');
ALTER TABLE ledger_outbox
ALTER COLUMN order_venue SET DEFAULT 'KRX';
ALTER TABLE ledger_outbox
ALTER COLUMN order_venue SET NOT NULL;
ALTER TABLE ledger_outbox
DROP CONSTRAINT IF EXISTS ledger_outbox_order_venue_check;
ALTER TABLE ledger_outbox
ADD CONSTRAINT ledger_outbox_order_venue_check
CHECK (order_venue IN ('KRX', 'NXT', 'SOR'));
-- Historical SOR in `venue` recorded routing provenance, not a proven KRX/NXT
-- execution exchange. Preserve SOR in order_venue and mark actual as unknown.
ALTER TABLE ledger_outbox
ALTER COLUMN venue DROP NOT NULL;
UPDATE ledger_outbox SET venue = NULL WHERE venue = 'SOR';
ALTER TABLE ledger_outbox
DROP CONSTRAINT IF EXISTS ledger_outbox_venue_check;
ALTER TABLE ledger_outbox
ADD CONSTRAINT ledger_outbox_venue_check
CHECK (venue IS NULL OR venue IN ('KRX', 'NXT'));
+6 -4
View File
@@ -71,9 +71,8 @@ class OrderAck:
accepted: bool
broker_order_id: Optional[str] = None
reason: Optional[str] = None
# Actual venue used for submission. KIS resolves AUTO before the HTTP call;
# execution persists this value with the broker order id so restart/cancel
# never has to infer the original venue.
# Original submission/routing venue. Execution persists this with the
# broker order id so restart/cancel never infer it from wall-clock time.
venue: Optional[str] = None
raw: dict[str, Any] = field(default_factory=dict)
submitted_at: Optional[datetime] = None
@@ -105,7 +104,10 @@ class FillStatus:
execution_id: Optional[str] = None
fee: float = 0.0
tax: float = 0.0
# dcy-013 / REQ-012 (issue #9): an external cancel was detected. When the
# Broker-authoritative execution exchange. For SOR orders this is KRX or
# NXT; None means the polling surface did not establish it.
execution_venue: Optional[str] = None
# dcy-013 / REQ-012: an external cancel was detected.
# order had a partial fill before the cancel, state stays "partially_filled"
# and this flag is set so execution records the filled portion and returns
# the remainder to holding (is_partial_cancel). A zero-fill external cancel
+16 -1
View File
@@ -773,6 +773,20 @@ class ExecutionService:
if resolved_price is not None
else (float(fs.avg_price) if fs.avg_price is not None else 0.0)
)
execution_venue = fs.execution_venue
if execution_venue is None and slot.venue in {"KRX", "NXT"}:
execution_venue = slot.venue
if execution_venue not in {"KRX", "NXT"}:
r.ledger_skipped += 1
_log.warning(
"ledger skip: slot=%s portfolio_id=%s side=%s "
"reason=missing_execution_venue order_venue=%s",
slot.slot_id,
slot.portfolio_id,
side,
slot.venue,
)
return
trade = LedgerTrade(
asset_id=str(slot.portfolio_id),
order_id=str(broker_order_id),
@@ -783,7 +797,8 @@ class ExecutionService:
fee=float(fs.fee),
tax=float(fs.tax),
executed_at=datetime.now(tz=timezone.utc),
venue=slot.venue,
venue=execution_venue,
order_venue=slot.venue,
)
self._ledger_outbox.enqueue(trade)
r.ledger_enqueued += 1
+5 -6
View File
@@ -77,9 +77,8 @@ class BuyIntent:
# slippage_pct: effective limit = entry_price*(1+pct/100) buy / *(1-pct/100) sell.
timeout_sec: Optional[int] = None
slippage_pct: Optional[float] = None
# Strategy wire default. AUTO is resolved at the broker boundary so
# strategies remain session-agnostic while explicit KRX/NXT/SOR is kept.
venue: str = "AUTO"
# Missing strategy venue uses KIS SOR; explicit KRX/NXT/SOR is preserved.
venue: str = "SOR"
extra: dict[str, Any] = field(default_factory=dict)
@@ -98,7 +97,7 @@ class SellIntent:
# dcy-022 / REQ-068: execution policy (optional, backward-compat).
timeout_sec: Optional[int] = None
slippage_pct: Optional[float] = None
venue: str = "AUTO"
venue: str = "SOR"
extra: dict[str, Any] = field(default_factory=dict)
@@ -229,7 +228,7 @@ class IntentService:
timeout_error = self._timeout_error(intent.timeout_sec)
if timeout_error is not None:
return IntentDecision(intent.intent_id, "rejected", None, timeout_error)
if intent.venue not in {"AUTO", "KRX", "NXT", "SOR"}:
if intent.venue not in {"KRX", "NXT", "SOR"}:
return IntentDecision(intent.intent_id, "rejected", None, "invalid_venue")
# dcy-036 / REQ-114: day-start entry gate (fail-closed).
@@ -347,7 +346,7 @@ class IntentService:
timeout_error = self._timeout_error(intent.timeout_sec)
if timeout_error is not None:
return IntentDecision(intent.intent_id, "rejected", None, timeout_error)
if intent.venue not in {"AUTO", "KRX", "NXT", "SOR"}:
if intent.venue not in {"KRX", "NXT", "SOR"}:
return IntentDecision(intent.intent_id, "rejected", None, "invalid_venue")
slot = self._repo.fetch_slot(intent.slot_id)
+5 -3
View File
@@ -57,9 +57,11 @@ class LedgerTrade:
fee: float = 0.0
tax: float = 0.0
executed_at: Optional[datetime] = None
# Actual order venue persisted in the Core outbox. Portfolio Hub remains
# unchanged until its API contract explicitly accepts this additive field.
venue: str = "KRX"
# Broker-authoritative execution exchange (KRX/NXT). Historical rows whose
# SOR execution exchange cannot be reconstructed are None.
venue: Optional[str] = None
# Original submission/routing venue (KRX/NXT/SOR), retained for audit.
order_venue: str = "KRX"
@property
def correlation_id(self) -> str:
+2 -34
View File
@@ -30,32 +30,6 @@ from trex_core.domain.slot import (
_log = logging.getLogger(__name__)
# ---- sell-reject retryability (issue #27 / REQ-007 CHG-20260615-01) ---------
# core-owned reason -> retryable mapping for the rejected SellIntent response.
# Maintained with the reject vocabulary (intents.py _admit_sell/_dedup) so a new
# reason gets a correct flag without the daemon touching a table. Unrecognized
# reasons default to retryable=True: a stranded stop-loss (held losing position)
# is worse than bounded, observable hammering on a terminal decision.
_SELL_REJECT_RETRYABLE: dict[str, bool] = {
"slot_state_changed": True,
"slot_not_holding:pending_buy": True,
"duplicate_in_flight": True,
"slot_not_found": False,
"slot_not_holding:inactive": False,
"slot_not_holding:pending_sell": False,
"slot_not_holding:error": False,
}
def _sell_reject_retryable(reason: Optional[str]) -> bool:
"""Map a rejected-sell reason to retryable (issue #27). Default True (safety)."""
if reason is None:
return True
# malformed payload: client defect — retrying the same bytes is pointless.
if reason.startswith("bad_request"):
return False
return _SELL_REJECT_RETRYABLE.get(reason, True)
# ---- intent RPC handler -----------------------------------------------------
@@ -117,7 +91,7 @@ def make_intent_rpc_handler(
# dcy-022 / REQ-068: execution policy (optional, backward-compat).
timeout_sec=_opt_int(body.get("timeout_sec")),
slippage_pct=_opt_float(body.get("slippage_pct")),
venue=_opt_str(body.get("venue")) or "AUTO",
venue=_opt_str(body.get("venue")) or "SOR",
)
d = intent_service.submit_buy(buy)
elif intent_type == "sell":
@@ -133,7 +107,7 @@ def make_intent_rpc_handler(
# dcy-022 / REQ-068: execution policy (optional, backward-compat).
timeout_sec=_opt_int(body.get("timeout_sec")),
slippage_pct=_opt_float(body.get("slippage_pct")),
venue=_opt_str(body.get("venue")) or "AUTO",
venue=_opt_str(body.get("venue")) or "SOR",
)
d = intent_service.submit_sell(sell)
else:
@@ -146,9 +120,6 @@ def make_intent_rpc_handler(
"intent_id": intent_id, "status": "rejected",
"slot_id": None, "reason": f"bad_request:{exc}",
}
# issue #27: sell-side malformed payload carries retryable=False.
if intent_type == "sell":
payload["retryable"] = _sell_reject_retryable(payload["reason"])
return RpcResponse(payload=payload)
payload = {
"intent_id": d.intent_id,
@@ -156,9 +127,6 @@ def make_intent_rpc_handler(
"slot_id": (str(d.slot_id) if d.slot_id else None),
"reason": d.reason,
}
# issue #27 / REQ-007 AC-7: additive retryable on rejected sell only.
if intent_type == "sell" and d.status == "rejected":
payload["retryable"] = _sell_reject_retryable(d.reason)
return RpcResponse(payload=payload)
return handler
+2 -3
View File
@@ -232,9 +232,8 @@ class SlotService:
new_timeout_sec = None
new_slippage_pct = None
# A completed order's venue must not leak into a later autonomous
# sell. The next order starts session-aware unless its intent
# explicitly chooses KRX/NXT/SOR.
new_venue = "AUTO" if to_state is SlotState.HOLDING else slot.venue
# sell. Missing venue defaults to KIS SOR for the next order.
new_venue = "SOR" if to_state is SlotState.HOLDING else slot.venue
# occupancy_seq (dcy-028/REQ-081): bump when a slot begins a new
# occupancy (inactive→pending_buy). Stable across the rest of the