fix: close broker uncertainty audit gaps
This commit is contained in:
@@ -11,7 +11,7 @@ import os
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from trex_core.adapters.broker.kis import KISBroker
|
||||
from trex_core.adapters.broker.kis import KISBroker, _balance_http_error_code
|
||||
from trex_core.application.broker_port import (
|
||||
BrokerBalanceError,
|
||||
CancelState,
|
||||
@@ -31,6 +31,41 @@ def test_account_split_and_mock_tr_ids():
|
||||
assert "12345678" not in b.account_scope_hash()
|
||||
|
||||
|
||||
def test_account_scope_hash_separates_endpoint_and_application_identity():
|
||||
mock_a = KISBroker(
|
||||
"12345678-01", app_key="app-a", app_secret="s", base_url=_MOCK_URL
|
||||
)
|
||||
mock_b = KISBroker(
|
||||
"12345678-01", app_key="app-b", app_secret="s", base_url=_MOCK_URL
|
||||
)
|
||||
live_a = KISBroker(
|
||||
"12345678-01",
|
||||
app_key="app-a",
|
||||
app_secret="s",
|
||||
base_url="https://openapi.koreainvestment.com:9443",
|
||||
allow_live=True,
|
||||
)
|
||||
|
||||
assert len({mock_a.account_scope_hash(), mock_b.account_scope_hash(),
|
||||
live_a.account_scope_hash()}) == 3
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("status", "code"),
|
||||
[
|
||||
(400, "broker_rejected"),
|
||||
(401, "authentication_failed"),
|
||||
(403, "authorization_failed"),
|
||||
(422, "broker_rejected"),
|
||||
(429, "transport_failed"),
|
||||
(500, "transport_failed"),
|
||||
(None, "broker_rejected"),
|
||||
],
|
||||
)
|
||||
def test_balance_http_status_classification(status, code):
|
||||
assert _balance_http_error_code(status) == code
|
||||
|
||||
|
||||
def test_live_base_url_requires_allow_live():
|
||||
with pytest.raises(RuntimeError):
|
||||
KISBroker(
|
||||
|
||||
@@ -9,7 +9,8 @@ from __future__ import annotations
|
||||
import psycopg
|
||||
|
||||
from trex_core.adapters.persistence.migrate import apply_migrations, migration_files
|
||||
from trex_core.domain.slot import EXPECTED_SLOT_FIELDS
|
||||
from trex_core.adapters.persistence.postgresql import PostgreSQLSlotRepository
|
||||
from trex_core.domain.slot import EXPECTED_SLOT_FIELDS, SlotService, SlotState
|
||||
|
||||
_EXPECTED_TABLES = {
|
||||
"daily_slot",
|
||||
@@ -61,3 +62,22 @@ def test_apply_migrations_is_idempotent(pg_dsn):
|
||||
# applying twice must not error (CREATE ... IF NOT EXISTS)
|
||||
apply_migrations(pg_dsn)
|
||||
apply_migrations(pg_dsn)
|
||||
|
||||
|
||||
def test_migration_replay_accepts_existing_auto_venue_row(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",
|
||||
)
|
||||
|
||||
apply_migrations(pg_clean)
|
||||
|
||||
assert repo.fetch_slot(slot.slot_id).venue == "AUTO"
|
||||
|
||||
@@ -132,6 +132,29 @@ def test_dispatch_queue_instance_scoped(pg_clean):
|
||||
assert repo_a.list_dispatched_pending("inst-b") == []
|
||||
|
||||
|
||||
def test_cancel_attempt_reservation_is_compare_and_set(pg_clean):
|
||||
repo, _, intents = _wire(pg_clean)
|
||||
repo.reconcile_universe(INST, {"PF-1": "005930"})
|
||||
decision = intents.submit_buy(
|
||||
BuyIntent(intent_id="pg-cancel-cas", qty=1, portfolio_id="PF-1")
|
||||
)
|
||||
assert repo.mark_dispatched(decision.slot_id, "ord-cas")
|
||||
assert repo.mark_cancel_outcome(
|
||||
decision.slot_id,
|
||||
"ord-cas",
|
||||
"unknown",
|
||||
only_if_unset=True,
|
||||
)
|
||||
assert not repo.mark_cancel_outcome(
|
||||
decision.slot_id,
|
||||
"ord-cas",
|
||||
"unknown",
|
||||
only_if_unset=True,
|
||||
)
|
||||
assert repo.mark_cancel_outcome(decision.slot_id, "ord-cas", "requested")
|
||||
assert repo.fetch_slot(decision.slot_id).cancel_state == "requested"
|
||||
|
||||
|
||||
# dcy-028 / REQ-079·081 (BAT-042): strategy-state store + occupancy_seq column
|
||||
def test_strategy_state_store_pg(pg_clean):
|
||||
from trex_core.adapters.persistence.postgresql import PgStrategyStateStore
|
||||
|
||||
@@ -40,6 +40,7 @@ class ProgrammableBroker:
|
||||
)
|
||||
self.polls = 0
|
||||
self.balance = {"005930": 10}
|
||||
self.cancel_calls = 0
|
||||
|
||||
def name(self):
|
||||
return "stub"
|
||||
@@ -53,6 +54,7 @@ class ProgrammableBroker:
|
||||
return self.responder(side)
|
||||
|
||||
def cancel_order(self, broker_order_id, *, side, symbol, qty, venue="KRX"):
|
||||
self.cancel_calls += 1
|
||||
return CancelOutcome(CancelState.REQUESTED)
|
||||
|
||||
def get_balance(self):
|
||||
@@ -159,3 +161,20 @@ def test_stale_watchdog_disabled_by_default():
|
||||
repo._slots[sid] = replace(s, updated_at=datetime.now(tz=timezone.utc) - timedelta(seconds=9999))
|
||||
r = execution.run_once()
|
||||
assert r.stale_pending == 0 # disabled => never warns
|
||||
|
||||
|
||||
def test_operator_cancel_is_sent_once_across_repeat_and_restart():
|
||||
broker = ProgrammableBroker()
|
||||
repo, svc, intents, execution, _, _ = _wire(broker)
|
||||
sid = _buy_to_holding(intents, execution)
|
||||
intents.submit_sell(SellIntent(intent_id="s1", slot_id=sid))
|
||||
broker.responder = lambda side: FillStatus(state="accepted")
|
||||
execution.run_once()
|
||||
|
||||
assert execution.cancel_pending_slot(sid) == "ok"
|
||||
assert execution.cancel_pending_slot(sid) == "cancel_already_recorded"
|
||||
|
||||
restarted = ExecutionService(svc, repo, broker)
|
||||
assert restarted.cancel_pending_slot(sid) == "cancel_already_recorded"
|
||||
assert broker.cancel_calls == 1
|
||||
assert repo.fetch_slot(sid).cancel_state == CancelState.REQUESTED.value
|
||||
|
||||
@@ -49,13 +49,9 @@ def test_concurrent_buys_admit_at_most_m():
|
||||
|
||||
admitted = [s for s in results if s == "admitted"]
|
||||
pending = [s for s in repo.list_slots(INST) if s.status is SlotState.PENDING_BUY]
|
||||
# NOTE: the M-cap check happens before the serialized transit, so racing
|
||||
# admissions can momentarily exceed M only if count_active were not
|
||||
# re-checked — the single intent thread is the production serializer
|
||||
# (dcy-020 OQ-1). The invariant here: admissions == activated slots
|
||||
# (no double-use) and at least one rejection occurred at the cap.
|
||||
# Capacity admission and transition share the same instance advisory lock.
|
||||
assert len(admitted) == len(pending)
|
||||
assert len(admitted) >= 5
|
||||
assert len(admitted) == 5
|
||||
assert len(results) == 20
|
||||
|
||||
|
||||
@@ -95,3 +91,52 @@ def test_duplicate_intent_id_admits_once_under_concurrency():
|
||||
pending = [s for s in repo.list_slots(INST) if s.status is SlotState.PENDING_BUY]
|
||||
assert len(pending) == 1
|
||||
assert all(s in ("admitted", "processing") for s in statuses)
|
||||
|
||||
|
||||
def test_concurrent_cached_cash_reservations_are_atomic_with_transition():
|
||||
repo = InMemorySlotRepository()
|
||||
svc = SlotService(repo, instance_key=INST)
|
||||
repo.reconcile_universe(INST, {"PF-0": "SYM", "PF-1": "SYM"})
|
||||
|
||||
def cash_guard(intent: BuyIntent):
|
||||
reserved = sum(
|
||||
float(slot.qty or 0) * float(slot.limit_price or 0)
|
||||
for slot in repo.list_slots(INST, {"pending_buy"})
|
||||
)
|
||||
requested = float(intent.qty or 0) * float(intent.entry_price or 0)
|
||||
return None if reserved + requested <= 100 else "insufficient_snapshot_cash"
|
||||
|
||||
intents = IntentService(
|
||||
svc,
|
||||
repo,
|
||||
InMemoryIntentStore(),
|
||||
resolve_symbol=lambda pid: f"SYM-{pid}",
|
||||
instance_key=INST,
|
||||
buy_guard_fn=cash_guard,
|
||||
)
|
||||
results = []
|
||||
result_lock = threading.Lock()
|
||||
|
||||
def worker(index: int) -> None:
|
||||
decision = intents.submit_buy(
|
||||
BuyIntent(
|
||||
intent_id=f"cash-{index}",
|
||||
portfolio_id=f"PF-{index}",
|
||||
qty=1,
|
||||
entry_price=100,
|
||||
)
|
||||
)
|
||||
with result_lock:
|
||||
results.append(decision)
|
||||
|
||||
threads = [threading.Thread(target=worker, args=(index,)) for index in range(2)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
|
||||
assert [decision.status for decision in results].count("admitted") == 1
|
||||
assert [decision.reason for decision in results].count(
|
||||
"insufficient_snapshot_cash"
|
||||
) == 1
|
||||
assert len(repo.list_slots(INST, {"pending_buy"})) == 1
|
||||
|
||||
Reference in New Issue
Block a user