# Forecasting Backend Architecture ## Mục tiêu - Tách riêng forecasting subsystem khỏi route monolith. - Chuẩn hóa contract dùng chung cho `Kronos`, `TimesFM`, `Chronos`. - Bảo đảm mỗi model inference độc lập, có warmup/state/cache/log riêng. ## Cấu trúc hiện tại - `config.py` - Danh sách model chuẩn. - Default selection. - Hàm chuẩn hóa `model_selection`. - `rules.py` - Load file `AI_MODEL_RULES.md`. - Sinh `rules version` để dùng cho cache key và response metadata. - `AI_MODEL_RULES.md` - Nguồn quy tắc vận hành chính thức cho forecast subsystem. - `providers/timesfm_provider.py` - Provider TimesFM theo contract OHLC4 chuẩn. - `providers/chronos_provider.py` - Provider Chronos theo contract OHLC4 chuẩn. - `backend/kronos_adapter.py` - Provider Kronos hiện hữu, tiếp tục được dùng như provider độc lập. ## Contract provider Mỗi provider phải đảm bảo: - Input là chuỗi lịch sử OHLC4 cùng timeframe. - Output thống nhất: - `p10` - `p50` - `p90` - `model_name` - `context_length` - `output_horizon` - `input_semantics` - `input_validation` - `output_semantics` - `output_validation` - Lazy-load an toàn bằng async lock. - Predict lock riêng để tránh race condition trên CPU/GPU cục bộ. ## Runtime state Mỗi model có startup state độc lập: - `available` - `preload_enabled` - `warming` - `loaded` - `device` - `last_error` - `model` ## Cache rules Forecast cache key phải phân biệt theo: - `symbol` - `interval` - `horizon` - `model selection` - `rules version` ## Response rules `/api/forecast/{symbol}` luôn trả: - `forecast` - `forecast_models` - `model_selection` - `forecast_contract` - `rules` Nhờ vậy frontend và test regression có thể bám vào một schema ổn định khi thêm model mới. ## Frontend integration Frontend đồng bộ cùng contract này qua: - `frontend/forecast-models.js` - Nguồn cấu hình dùng chung cho thứ tự model, label, palette và `defaultLineWidth`. - `frontend/workspace.js` - Đồng bộ selection/signature/cache theo cùng model order. - `frontend/app.js` - Render line riêng theo từng model. - Hover vào line phải hiện đúng tên model đang được trỏ tới.