feat(runtime): dcy-014 trading_date KST 타임존 분리 + 일일 슬롯 preallocation (BAT-018)
데몬이 시스템 UTC 날짜로 슬롯을 1회만 preallocate 해 trading_date 가 KST 캘린더와 어긋나고 재시작 없이는 다음날 슬롯이 안 생기던 문제(issue #14) 정정. 거버넌스: 전부 change-req (신규 REQ 없음, dcy-014 OQ-3; 스케줄러는 REQ-030 패턴 준용). - REQ-005: trading_date 를 설정 타임존(기본 Asia/Seoul) 기준 계산(timestamp 는 UTC 유지). DailyPreallocationScheduler 신규 — TZ 일자당 1회 멱등 fire, 재시작 없이 다음날 슬롯 자동 생성. setup() 배선 + trex-preallocation 스레드 - REQ-048: TOML trading_timezone/daily_preallocation_time 키 + from_config 전파 - REQ-009: runtime-flows/data-model 정합 + instance.example.toml OQ-1 기본 00:00(TZ 자정, TOML 설정 가능) / OQ-2 매 캘린더일 생성(거래일 캘린더 후속). 멱등 preallocate 로 중복 tick·다중 인스턴스 중복 생성 0. 검증: 단위 302 passed/32 skipped, 인프라 게이트(PG+RabbitMQ) 334 passed, ruff clean. 신규 test_preallocation_scheduler(고정 clock) + test_instance_config 확장. BAT-018 release-candidate. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
"""Daily slot preallocation scheduler (dcy-014 / REQ-005, issue #14).
|
||||
|
||||
trading_date is computed in a configurable timezone (default Asia/Seoul) so the
|
||||
DB trading_date matches the local trading calendar, while all timestamps stay
|
||||
UTC (NFR-1). Modeled on SnapshotScheduler (REQ-030): a tick loop fires once per
|
||||
TZ-day at/after the configured trigger time, calling the idempotent
|
||||
`preallocate_daily_slots` so the next day's slots are created without a daemon
|
||||
restart (NFR-2/NFR-3).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from datetime import date, datetime, time, timezone
|
||||
from typing import Callable, Optional, Protocol
|
||||
|
||||
_log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _Preallocator(Protocol):
|
||||
def preallocate_daily_slots(self, trading_date: date, count: int) -> int:
|
||||
...
|
||||
|
||||
|
||||
class DailyPreallocationScheduler:
|
||||
"""Background-thread-friendly daily preallocation. Use `run_once()` for tests."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
slot_service: _Preallocator,
|
||||
total_slots: int,
|
||||
tz: timezone,
|
||||
schedule_time: time = time(hour=0, minute=0),
|
||||
clock: Optional[Callable[[], datetime]] = None,
|
||||
) -> None:
|
||||
self._svc = slot_service
|
||||
self._total = total_slots
|
||||
self._tz = tz # tzinfo used to derive trading_date (default Asia/Seoul)
|
||||
self._schedule = schedule_time
|
||||
self._clock = clock or (lambda: datetime.now(tz=timezone.utc))
|
||||
self._last_fired_date: Optional[date] = None
|
||||
|
||||
# ---- callable from a daemon thread loop --------------------------------
|
||||
def run_forever(self, stop: threading.Event, *, tick_sec: float = 60.0) -> None:
|
||||
# Boot: ensure the current TZ-day's slots exist immediately (idempotent),
|
||||
# then enter the daily cadence for subsequent day boundaries.
|
||||
self.run_once()
|
||||
while not stop.wait(tick_sec):
|
||||
try:
|
||||
self._maybe_tick()
|
||||
except Exception: # noqa: BLE001 - loop must survive transient errors
|
||||
_log.exception("preallocation scheduler tick failed")
|
||||
|
||||
def _maybe_tick(self) -> None:
|
||||
now_tz = self._clock().astimezone(self._tz)
|
||||
target = datetime.combine(now_tz.date(), self._schedule, tzinfo=self._tz)
|
||||
if now_tz < target:
|
||||
return # before today's trigger time
|
||||
if self._last_fired_date is not None and self._last_fired_date == now_tz.date():
|
||||
return # already created today's slots
|
||||
self.run_once()
|
||||
|
||||
# ---- the actual preallocation -----------------------------------------
|
||||
def run_once(self) -> date:
|
||||
"""Preallocate slots for the current TZ trading_date (idempotent). Returns it."""
|
||||
trading_date = self._clock().astimezone(self._tz).date()
|
||||
created = self._svc.preallocate_daily_slots(trading_date, self._total)
|
||||
if created:
|
||||
_log.info("preallocated %d slots for trading_date=%s", created, trading_date)
|
||||
self._last_fired_date = trading_date
|
||||
return trading_date
|
||||
@@ -99,6 +99,10 @@ class DaemonInstanceConfig:
|
||||
|
||||
instance_key: str
|
||||
portfolio_hub_token: str = ""
|
||||
# dcy-014 / REQ-048: trading_date timezone + daily preallocation trigger.
|
||||
# Optional — absent keys fall back to KST / midnight defaults.
|
||||
trading_timezone: str = "Asia/Seoul"
|
||||
daily_preallocation_time: str = "00:00"
|
||||
|
||||
@staticmethod
|
||||
def from_toml(path: str) -> "DaemonInstanceConfig":
|
||||
@@ -114,6 +118,8 @@ class DaemonInstanceConfig:
|
||||
return DaemonInstanceConfig(
|
||||
instance_key=str(instance_key),
|
||||
portfolio_hub_token=str(data.get("portfolio_hub_token") or ""),
|
||||
trading_timezone=str(data.get("trading_timezone") or "Asia/Seoul"),
|
||||
daily_preallocation_time=str(data.get("daily_preallocation_time") or "00:00"),
|
||||
)
|
||||
|
||||
|
||||
@@ -144,6 +150,11 @@ class DaemonConfig:
|
||||
# threshold in seconds. 0 disables (default). When >0, dispatched-pending
|
||||
# slots older than this are surfaced (WARN + counter) without state change.
|
||||
pending_stale_threshold_sec: int = 0
|
||||
# dcy-014 / REQ-005 (BAT-018): trading_date timezone (default KST) + daily
|
||||
# preallocation trigger time (HH:MM, TZ-local). Operative surface is the
|
||||
# per-instance TOML (REQ-048); these are the env-only defaults.
|
||||
trading_timezone: str = "Asia/Seoul"
|
||||
daily_preallocation_time: str = "00:00"
|
||||
|
||||
@staticmethod
|
||||
def from_env() -> "DaemonConfig":
|
||||
@@ -241,4 +252,11 @@ class DaemonConfig:
|
||||
pf = base.portfolio_hub
|
||||
if inst.portfolio_hub_token and pf is not None:
|
||||
pf = replace(pf, token=inst.portfolio_hub_token)
|
||||
return replace(base, instance_key=inst.instance_key, portfolio_hub=pf)
|
||||
# dcy-014 / REQ-048: trading_date TZ + daily trigger come from TOML.
|
||||
return replace(
|
||||
base,
|
||||
instance_key=inst.instance_key,
|
||||
portfolio_hub=pf,
|
||||
trading_timezone=inst.trading_timezone,
|
||||
daily_preallocation_time=inst.daily_preallocation_time,
|
||||
)
|
||||
|
||||
@@ -10,6 +10,7 @@ Threads (started in `run()`):
|
||||
- execution loop — broker dispatch + poll + slot transitions + event emit
|
||||
- ledger writer — ledger outbox drain (REQ-019)
|
||||
- snapshot scheduler — daily portfolio-hub snapshot refresh (REQ-030)
|
||||
- preallocation scheduler — daily slot preallocation in trading TZ (REQ-005, dcy-014)
|
||||
- safety-sell worker — forced_close / stop-loss·take-profit / market-close (REQ-037/038/039)
|
||||
|
||||
Each consumer/publisher uses its OWN RabbitMQTransport instance because
|
||||
@@ -21,9 +22,8 @@ from __future__ import annotations
|
||||
import logging
|
||||
import signal
|
||||
import threading
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from datetime import time as time_cls
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from trex_core.adapters.broker.paper import PaperBroker
|
||||
from trex_core.adapters.ledger import InMemoryLedger, PortfolioHubLedger
|
||||
@@ -62,6 +62,7 @@ from trex_core.application.portfolio import (
|
||||
SnapshotStore,
|
||||
)
|
||||
from trex_core.application.safety_sell import SafetySellService
|
||||
from trex_core.application.preallocation_scheduler import DailyPreallocationScheduler
|
||||
from trex_core.application.snapshot_scheduler import SnapshotScheduler
|
||||
from trex_core.application.watchdog import WatchdogStore
|
||||
from trex_core.domain.slot import SlotService
|
||||
@@ -167,6 +168,15 @@ class Daemon:
|
||||
broker=self.broker,
|
||||
schedule_kst=_parse_kst_time(config.snapshot_schedule.kst_time),
|
||||
)
|
||||
# dcy-014 / REQ-005: daily slot preallocation in the configured
|
||||
# trading timezone (default KST), so trading_date matches the local
|
||||
# calendar and the next day's slots appear without a restart.
|
||||
self.preallocation_scheduler = DailyPreallocationScheduler(
|
||||
slot_service=self.slot_service,
|
||||
total_slots=config.total_slots,
|
||||
tz=ZoneInfo(config.trading_timezone),
|
||||
schedule_time=_parse_kst_time(config.daily_preallocation_time),
|
||||
)
|
||||
|
||||
# Event publisher transport — one dedicated instance for the
|
||||
# execution-loop thread (pika is not thread-safe).
|
||||
@@ -287,12 +297,19 @@ class Daemon:
|
||||
except Exception: # noqa: BLE001
|
||||
_log.exception("snapshot scheduler loop crashed")
|
||||
|
||||
def _preallocation_loop(self) -> None:
|
||||
try:
|
||||
self.preallocation_scheduler.run_forever(self.stop, tick_sec=60.0)
|
||||
except Exception: # noqa: BLE001
|
||||
_log.exception("preallocation scheduler loop crashed")
|
||||
|
||||
# ------------------------------------------------------------ lifecycle
|
||||
def setup(self) -> None:
|
||||
apply_migrations(self.config.dsn)
|
||||
self.slot_service.preallocate_daily_slots(
|
||||
datetime.now(tz=timezone.utc).date(), self.config.total_slots
|
||||
)
|
||||
# dcy-014 / REQ-005: preallocate against the configured trading timezone
|
||||
# (default KST), not the system UTC date. Boot-time run_once ensures the
|
||||
# current TZ-day's slots exist immediately (idempotent).
|
||||
self.preallocation_scheduler.run_once()
|
||||
self.execution.reconcile() # REQ-014 restart recovery
|
||||
try:
|
||||
self.event_publisher.declare_topology(self.config.instance_key)
|
||||
@@ -307,6 +324,7 @@ class Daemon:
|
||||
("trex-snapshot-rpc", self._snapshot_rpc_loop),
|
||||
("trex-control-rpc", self._control_rpc_loop),
|
||||
("trex-snapshot-scheduler", self._snapshot_scheduler_loop),
|
||||
("trex-preallocation", self._preallocation_loop),
|
||||
("trex-safety-sell", self._safety_sell_loop),
|
||||
]
|
||||
for name, target in workers:
|
||||
|
||||
Reference in New Issue
Block a user