Spaces:
Sleeping

File size: 32,533 Bytes
c68f3b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional, Any
import os
import sys
import pandas as pd
import numpy as np
from datetime import datetime, timezone, timedelta
import threading
import time
import json
import logging
import multiprocessing
import contextvars
import hashlib
from uuid import uuid4
from dataclasses import dataclass, field
from enum import Enum

import config
from data_loader import get_parquet_store_from_r2, get_parquet_store_local, get_parquet_store_from_hf
from parquet_store import ParquetStore
from ic_calculator import calculate_cross_sectional_ic
from timeframe_utils import detect_timeframe_suffixes

# --------------- 日志配置 ---------------

request_id_var: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="-")
user_email_var: contextvars.ContextVar[str] = contextvars.ContextVar("user_email", default="-")


class RequestIdFilter(logging.Filter):
    def filter(self, record: logging.LogRecord) -> bool:
        record.request_id = request_id_var.get("-")  # type: ignore[attr-defined]
        record.user_email = user_email_var.get("-")  # type: ignore[attr-defined]
        return True


class BeijingFormatter(logging.Formatter):
    """日志时间强制使用北京时间 (UTC+8)"""
    _beijing_tz = timezone(timedelta(hours=8))

    def formatTime(self, record, datefmt=None):
        dt = datetime.fromtimestamp(record.created, tz=self._beijing_tz)
        if datefmt:
            return dt.strftime(datefmt)
        return dt.strftime("%Y-%m-%d %H:%M:%S")


def setup_logging():
    fmt = "%(asctime)s.%(msecs)03d [%(request_id)s] [%(user_email)s] [%(module)s] %(message)s"
    datefmt = "%Y-%m-%d %H:%M:%S"
    handler = logging.StreamHandler()
    handler.setFormatter(BeijingFormatter(fmt, datefmt=datefmt))
    handler.addFilter(RequestIdFilter())

    root = logging.getLogger()
    root.setLevel(logging.INFO)
    root.handlers.clear()
    root.addHandler(handler)


setup_logging()
logger = logging.getLogger(__name__)

# spawn 子进程会 re-import 此模块,用环境变量标记跳过重量级初始化
_is_worker = os.environ.get("_BACKTEST_WORKER") == "1"

# --------------- FastAPI App ---------------

app = FastAPI(title="AI量化因子回测引擎", version="3.0.0")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000", "https://*.vercel.app", "https://*.hf.space"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.middleware("http")
async def request_id_middleware(request: Request, call_next):
    rid = request.headers.get("x-request-id") or uuid4().hex[:8]
    user_email = request.headers.get("x-user-email", "-")
    request_id_var.set(rid)
    user_email_var.set(user_email)
    start = time.time()
    logger.info(f"<-- {request.method} {request.url.path}")
    response = await call_next(request)
    elapsed = time.time() - start
    logger.info(f"--> {request.method} {request.url.path} {response.status_code} ({elapsed:.2f}s)")
    return response


# --------------- 数据状态(磁盘 parquet 直查模式) ---------------

DATA_STORE: ParquetStore | None = None
_data_loading = False
_data_loaded = False
_data_refreshing = False
_data_lock = threading.Lock()
_last_refresh: datetime | None = None


def _fetch_store(force_check: bool = False) -> ParquetStore | None:
    """根据 DATA_SOURCE 配置获取 ParquetStore。
    force_check=False(启动):本地缓存存在就直接用,不访问远程
    force_check=True(刷新):检查远程文件,按需下载
    """
    source = config.DATA_SOURCE.lower()

    if source == "local":
        data_path = config.DATA_DIR
        logger.info(f"正在从本地创建 ParquetStore: {data_path}")
        return get_parquet_store_local(data_path)

    if source == "huggingface":
        logger.info(f"正在从 Hugging Face 创建 ParquetStore: {config.HF_DATASET_REPO} (force_check={force_check})")
        return get_parquet_store_from_hf(
            repo_id=config.HF_DATASET_REPO,
            token=config.HF_TOKEN,
            force_check=force_check,
        )

    # R2
    if not config.R2_ACCOUNT_ID or not config.R2_ACCESS_KEY_ID or not config.R2_SECRET_ACCESS_KEY:
        raise ValueError("R2 配置不完整(R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY)")
    logger.info(f"正在从 Cloudflare R2 创建 ParquetStore (force_check={force_check})...")
    return get_parquet_store_from_r2(
        account_id=config.R2_ACCOUNT_ID,
        access_key_id=config.R2_ACCESS_KEY_ID,
        secret_access_key=config.R2_SECRET_ACCESS_KEY,
        bucket_name=config.R2_BUCKET_NAME,
        prefix=config.R2_PREFIX,
        force_check=force_check,
    )


def _load_data():
    """启动时加载数据(本地有就用本地,没有才从 R2 拉取)"""
    global DATA_STORE, _data_loaded, _data_loading, _last_refresh
    logger.info(f"数据源: {config.DATA_SOURCE}, 路径: {config.DATA_DIR if config.DATA_SOURCE == 'local' else config.DATA_FILE}")
    try:
        store = _fetch_store(force_check=False)  # 启动时不检查 R2
        if store:
            DATA_STORE = store
            _data_loaded = True
            _last_refresh = datetime.now()
            logger.info(f"ParquetStore 就绪,共 {len(store)} 只标的(DuckDB 磁盘数据库模式)")
        else:
            logger.error("ParquetStore 创建失败")
    except Exception as e:
        logger.error(f"数据加载失败: {e}")
    finally:
        _data_loading = False


def _refresh_data():
    """异步刷新:检查 R2 远程文件,按需下载并重建 store"""
    global DATA_STORE, _data_refreshing, _last_refresh
    if _data_refreshing:
        return

    _data_refreshing = True
    logger.info(f"开始刷新数据 ({datetime.now().strftime('%H:%M:%S')})")
    try:
        new_store = _fetch_store(force_check=True)  # 刷新时才检查 R2
        if new_store:
            DATA_STORE = new_store
            _last_refresh = datetime.now()
            logger.info(f"刷新完成,共 {len(new_store)} 只标的")
        else:
            logger.warning("刷新返回空 store,保留旧数据")
    except Exception as e:
        logger.error(f"刷新失败: {e},保留旧数据")
    finally:
        _data_refreshing = False


def ensure_data():
    """确保数据已加载,未加载则触发后台加载"""
    global _data_loading
    if _data_loaded:
        return True
    with _data_lock:
        if not _data_loading and not _data_loaded:
            _data_loading = True
            t = threading.Thread(target=_load_data, daemon=True)
            t.start()
    return _data_loaded


@app.on_event("startup")
def startup_event():
    """服务启动时立即触发后台数据加载"""
    logger.info("FastAPI startup event 触发")
    ensure_data()


# --------------- 请求模型 ---------------

class BacktestRequest(BaseModel):
    formula: str
    session_id: str = ""           # 用于生成确定性 task_id
    start_date: Optional[str] = None  # YYYY-MM-DD
    end_date: Optional[str] = None
    forward_period: int = 1
    timeframe: str = "1d"          # IC计算的基准周期
    filter_rule: Optional[str] = None  # 数据过滤规则描述


# --------------- 任务队列 ---------------


def _sanitize_for_json(obj):
    """递归将 numpy/pandas 类型转为 Python 原生类型,确保 JSON 可序列化"""
    if isinstance(obj, dict):
        return {k: _sanitize_for_json(v) for k, v in obj.items()}
    if isinstance(obj, (list, tuple)):
        return [_sanitize_for_json(i) for i in obj]
    if isinstance(obj, np.integer):
        return int(obj)
    if isinstance(obj, (np.floating, float)):
        v = float(obj)
        if np.isnan(v) or np.isinf(v):
            return None
        return v
    if isinstance(obj, np.bool_):
        return bool(obj)
    if isinstance(obj, np.ndarray):
        return _sanitize_for_json(obj.tolist())
    if isinstance(obj, (pd.Timestamp, datetime)):
        return obj.isoformat()
    if isinstance(obj, pd.Series):
        return _sanitize_for_json(obj.tolist())
    return obj


class TaskStatus(str, Enum):
    QUEUED = "queued"
    RUNNING = "running"
    COMPLETED = "completed"
    FAILED = "failed"


@dataclass
class BacktestTask:
    task_id: str
    formula: str
    start_date: str | None
    end_date: str | None
    forward_period: int
    timeframe: str
    filter_rule: str | None
    user_email: str = "-"
    status: TaskStatus = TaskStatus.QUEUED
    result: Any = None
    error: str | None = None
    created_at: float = field(default_factory=time.time)
    completed_at: float | None = None
    progress_message: str = ""


class TaskManager:
    """内存任务队列,同一时间只执行一个回测任务"""

    TTL_SECONDS = 24 * 3600  # 结果缓存 24 小时

    def __init__(self):
        self._queue: list[str] = []                # 排队中的 task_id(有序)
        self._tasks: dict[str, BacktestTask] = {}  # 所有任务
        self._lock = threading.Lock()
        self._event = threading.Event()             # 通知 worker 有新任务
        self._running = True

        # 启动后台 worker 线程
        self._worker_thread = threading.Thread(target=self._worker_loop, daemon=True, name="task-worker")
        self._worker_thread.start()

        # 启动清理线程
        self._cleanup_thread = threading.Thread(target=self._cleanup_loop, daemon=True, name="task-cleanup")
        self._cleanup_thread.start()

        logger.info("TaskManager 已启动(单任务串行执行模式)")

    @staticmethod
    def generate_task_id(session_id: str, formula: str) -> str:
        """根据 session_id + formula 生成确定性 task_id"""
        raw = f"{session_id}:{formula.strip()}"
        return hashlib.sha256(raw.encode()).hexdigest()[:16]

    def submit(self, task_id: str, req: BacktestRequest) -> dict:
        """提交任务到队列,返回 { task_id, status, queue_position }"""
        with self._lock:
            # 如果任务已存在
            if task_id in self._tasks:
                existing = self._tasks[task_id]
                if existing.status == TaskStatus.COMPLETED:
                    return {"task_id": task_id, "status": "completed", "queue_position": 0}
                if existing.status in (TaskStatus.QUEUED, TaskStatus.RUNNING):
                    pos = self._get_position(task_id)
                    return {"task_id": task_id, "status": existing.status.value, "queue_position": pos}
                # FAILED 的任务重新排队
                del self._tasks[task_id]

            task = BacktestTask(
                task_id=task_id,
                formula=req.formula,
                start_date=req.start_date,
                end_date=req.end_date,
                forward_period=req.forward_period,
                timeframe=req.timeframe,
                filter_rule=req.filter_rule,
                user_email=user_email_var.get("-"),
            )
            self._tasks[task_id] = task
            self._queue.append(task_id)
            pos = len(self._queue)
            logger.info(f"任务已入队: {task_id}, 位置: {pos}, 公式: {req.formula.strip()[:60]}...")

        self._event.set()  # 通知 worker
        return {"task_id": task_id, "status": "queued", "queue_position": pos}

    def get_status(self, task_id: str) -> dict | None:
        """获取任务状态"""
        with self._lock:
            task = self._tasks.get(task_id)
            if not task:
                return None
            status_dict = {
                "task_id": task_id,
                "status": task.status.value,
                "queue_position": self._get_position(task_id),
                "progress_message": task.progress_message,
                "result": task.result if task.status == TaskStatus.COMPLETED else None,
                "error": task.error if task.status == TaskStatus.FAILED else None,
            }
        return _sanitize_for_json(status_dict)

    def get_queue_info(self) -> dict:
        """获取队列概览"""
        with self._lock:
            running = [t for t in self._tasks.values() if t.status == TaskStatus.RUNNING]
            return {
                "queue_length": len(self._queue),
                "running": running[0].task_id if running else None,
                "total_tasks": len(self._tasks),
            }

    def get_active_tasks_by_user(self, user_email: str) -> list[dict]:
        """获取指定用户的活跃任务(queued/running)"""
        with self._lock:
            return [
                {
                    "task_id": t.task_id,
                    "formula": t.formula,
                    "status": t.status.value,
                    "queue_position": self._get_position(t.task_id),
                    "progress_message": t.progress_message,
                }
                for t in self._tasks.values()
                if t.user_email == user_email
                and t.status in (TaskStatus.QUEUED, TaskStatus.RUNNING)
            ]

    def _get_position(self, task_id: str) -> int:
        """队列位置(1-based)。0 表示正在执行或已完成"""
        try:
            return self._queue.index(task_id) + 1
        except ValueError:
            return 0

    def _worker_loop(self):
        """后台 worker:从队列头部逐个取任务执行"""
        while self._running:
            self._event.wait(timeout=1.0)
            self._event.clear()

            while True:
                task_id = None
                with self._lock:
                    if not self._queue:
                        break
                    task_id = self._queue[0]
                    task = self._tasks.get(task_id)
                    if task:
                        task.status = TaskStatus.RUNNING
                        logger.info(f"开始执行任务: {task_id}")

                if task_id:
                    self._execute_task(task_id)
                    with self._lock:
                        if self._queue and self._queue[0] == task_id:
                            self._queue.pop(0)

    def _execute_task(self, task_id: str):
        """执行单个回测任务"""
        task = self._tasks.get(task_id)
        if not task:
            return

        # 恢复 contextvars 供日志使用
        user_email_var.set(task.user_email)
        request_id_var.set(task_id[:8])

        try:
            req = BacktestRequest(
                formula=task.formula,
                start_date=task.start_date,
                end_date=task.end_date,
                forward_period=task.forward_period,
                timeframe=task.timeframe,
                filter_rule=task.filter_rule,
            )
            result = None
            logger.info(f"[exec] 开始执行回测生成器")
            for event_type, payload in _run_backtest(req):
                if event_type == "progress":
                    with self._lock:
                        task.progress_message = payload.get("message", "")
                elif event_type == "result":
                    logger.info(f"[exec] 收到 result 事件,开始序列化...")
                    t_sanitize = time.time()
                    result = _sanitize_for_json(payload)
                    logger.info(f"[exec] 序列化完成: {time.time()-t_sanitize:.2f}s, ic_series长度={len(result.get('ic_series', []))}")

            logger.info(f"[exec] 生成器结束, result={'有' if result else '无'}")
            with self._lock:
                if result:
                    task.status = TaskStatus.COMPLETED
                    task.result = result
                    task.completed_at = time.time()
                    logger.info(f"任务完成: {task_id}")
                else:
                    task.status = TaskStatus.FAILED
                    task.error = "未收到回测结果"
                    task.completed_at = time.time()
                    logger.error(f"任务失败(无结果): {task_id}")
        except HTTPException as e:
            with self._lock:
                task.status = TaskStatus.FAILED
                task.error = e.detail
                task.completed_at = time.time()
                logger.error(f"任务失败: {task_id}: {e.detail}")
        except Exception as e:
            with self._lock:
                task.status = TaskStatus.FAILED
                task.error = str(e)
                task.completed_at = time.time()
                logger.error(f"任务异常: {task_id}: {e}")

    def _cleanup_loop(self):
        """定期清理过期的已完成/失败任务(24小时TTL)"""
        while self._running:
            time.sleep(3600)  # 每小时检查一次
            now = time.time()
            with self._lock:
                expired = [
                    tid for tid, t in self._tasks.items()
                    if t.status in (TaskStatus.COMPLETED, TaskStatus.FAILED)
                    and t.completed_at
                    and (now - t.completed_at) > self.TTL_SECONDS
                ]
                for tid in expired:
                    del self._tasks[tid]
                if expired:
                    logger.info(f"清理过期任务: {len(expired)} 个")


# 全局单例(仅主进程创建,spawn 子进程通过环境变量跳过)
task_manager: TaskManager | None = None
if not _is_worker:
    os.environ["_BACKTEST_WORKER"] = "1"  # 所有后续子进程会继承
    task_manager = TaskManager()


# --------------- API 端点 ---------------

@app.get("/health")
def health():
    queue_info = task_manager.get_queue_info()
    return {
        "status": "ok",
        "stocks_count": len(DATA_STORE) if DATA_STORE else 0,
        "data_loaded": _data_loaded,
        "data_loading": _data_loading,
        "data_refreshing": _data_refreshing,
        "last_refresh": _last_refresh.strftime("%Y-%m-%d %H:%M:%S") if _last_refresh else None,
        "queue": queue_info,
    }


@app.post("/admin/refresh-data")
def admin_refresh_data():
    """管理台手动触发从 R2 拉取最新数据并重建 DuckDB"""
    if _data_refreshing:
        return {"status": "already_refreshing", "message": "数据正在刷新中"}
    threading.Thread(target=_refresh_data, daemon=True).start()
    return {"status": "refresh_started", "message": "已开始刷新数据"}


@app.post("/backtest")
def backtest(req: BacktestRequest):
    """提交回测任务到队列,立即返回 task_id 和队列位置"""
    if not req.formula.strip():
        raise HTTPException(status_code=400, detail="formula is required")

    task_id = task_manager.generate_task_id(req.session_id, req.formula)
    result = task_manager.submit(task_id, req)
    return result


@app.get("/tasks/active")
def get_active_tasks(request: Request):
    """查询当前用户的活跃任务(queued/running),用于页面恢复"""
    user_email = request.headers.get("x-user-email", "-")
    tasks = task_manager.get_active_tasks_by_user(user_email)
    return {"tasks": tasks}


@app.get("/task/{task_id}")
def get_task_status(task_id: str):
    """查询任务状态、队列位置和结果"""
    status = task_manager.get_status(task_id)
    if not status:
        raise HTTPException(status_code=404, detail="任务不存在")
    s = status["status"]
    msg = status.get("progress_message", "")
    if s == "completed":
        has_result = status.get("result") is not None
        ic_len = len(status["result"].get("ic_series", [])) if has_result else 0
        logger.info(f"[状态查询] {task_id} → {s}, has_result={has_result}, ic_series={ic_len}")
    # else:
    #     logger.info(f"[状态查询] {task_id} → {s}, progress={msg}")
    return status


# --------------- 回测核心逻辑 ---------------

def _run_backtest(req: BacktestRequest):
    """
    执行回测计算,yield (event_type, payload) 在每个阶段。
    阶段1: DuckDB 读取数据(主进程)
    阶段2: 数据准备 + 因子计算(多进程并行)
    阶段3: 面板构建 + IC 计算
    """
    tf = req.timeframe
    if tf not in config.VALID_TIMEFRAMES:
        raise HTTPException(
            status_code=400,
            detail=f"不支持的周期: {tf},可选: {config.VALID_TIMEFRAMES}",
        )

    if not _data_loaded or not DATA_STORE:
        if _data_loading:
            raise HTTPException(status_code=503, detail="数据正在加载中,请稍后重试")
        ensure_data()
        raise HTTPException(status_code=503, detail="数据开始加载,请稍后重试")

    t0 = time.time()

    formula_preview = req.formula.strip()[:80]
    logger.info(f"收到回测请求: formula={formula_preview}... timeframe={tf} workers={config.WORKER_COUNT}")

    # 清理公式:去掉 markdown 代码块标记
    formula = req.formula.strip()
    if formula.startswith("```"):
        lines = formula.split("\n")
        lines = lines[1:]
        if lines and lines[-1].strip() == "```":
            lines = lines[:-1]
        formula = "\n".join(lines).strip()

    # 检测公式中引用的周期后缀
    suffixes = detect_timeframe_suffixes(formula)
    if suffixes:
        logger.info(f"检测到周期后缀: {suffixes}")

    # ---- 过滤规则执行 ----
    filtered_codes = None
    if req.filter_rule:
        yield ("progress", {"step": "filter", "message": "正在解析过滤规则..."})
        try:
            from stock_filter import apply_stock_filter
            filtered_codes = apply_stock_filter(req.filter_rule, DATA_STORE)
            yield ("progress", {"step": "filter", "message": f"过滤完成: {len(filtered_codes)} 只标的符合条件"})
            if not filtered_codes:
                raise HTTPException(status_code=400, detail="过滤后无符合条件的标的")
        except HTTPException:
            raise
        except Exception as e:
            logger.warning(f"过滤规则执行失败,将使用全部标的: {e}")

    # ---- 阶段1: 准备任务参数(无需预加载数据) ----
    target_codes = filtered_codes if filtered_codes else DATA_STORE.get_codes()
    if not target_codes:
        raise HTTPException(status_code=400, detail="无符合条件的标的数据")

    # ---- 公式预验证:用少量股票试算,公式错误立即返回 ----
    yield ("progress", {"step": "validate", "message": "正在验证公式..."})
    from factor_engine import evaluate_formula
    validation_error = None
    for probe_code in target_codes[:5]:
        stock_df = DATA_STORE.get_stock_data(probe_code)
        if stock_df.empty:
            continue
        from timeframe_utils import prepare_multi_tf_variables as prep_tf
        base_df, extra_vars = prep_tf(
            stock_code=probe_code, df_5m=stock_df, suffixes=suffixes,
            ic_timeframe=tf, start_date=req.start_date, end_date=req.end_date,
        )
        if base_df.empty:
            continue
        try:
            evaluate_formula(formula, base_df, extra_variables=extra_vars or None)
            validation_error = None
            break  # 验证通过
        except Exception as e:
            validation_error = str(e)
            break  # 公式错误,直接报错
    if validation_error:
        raise HTTPException(status_code=400, detail=f"公式错误: {validation_error}")
    logger.info("公式预验证通过")

    # 将股票分批
    QUERY_BATCH = 200   # DuckDB 每次查 200 只(减少查询次数)
    WORKER_BATCH = 20   # worker 每次处理 20 只
    query_batches = [
        target_codes[i:i + QUERY_BATCH]
        for i in range(0, len(target_codes), QUERY_BATCH)
    ]

    t1 = time.time()
    total_worker_batches = sum(
        (min(len(qb), QUERY_BATCH) + WORKER_BATCH - 1) // WORKER_BATCH
        for qb in query_batches
    )
    logger.info(f"任务准备完成: {len(target_codes)} 只标的, {len(query_batches)} 次查询, ~{total_worker_batches} worker批, 耗时 {t1-t0:.2f}s")
    yield ("progress", {
        "step": "load",
        "message": f"任务准备完成: {len(target_codes)} 只标的",
        "elapsed": round(t1 - t0, 2),
    })

    # ---- 阶段2: 大批查询 DuckDB + 小批提交 worker(预处理在 worker 中并行) ----
    close_dict: dict[str, pd.Series] = {}
    factor_dict: dict[str, pd.Series] = {}
    errors = 0

    from concurrent.futures import ProcessPoolExecutor, as_completed
    from worker import process_stock_batch

    mp_ctx = multiprocessing.get_context("forkserver" if sys.platform == "linux" else "spawn")
    logger.info(f"启动并行计算: {len(target_codes)} 只标的, {len(query_batches)} 次查询, {config.WORKER_COUNT} workers")

    con = DATA_STORE._connect_readonly()
    try:
        with ProcessPoolExecutor(max_workers=config.WORKER_COUNT, mp_context=mp_ctx) as pool:
            futures: dict = {}
            t_query_start = time.time()
            total_query_time = 0.0
            total_submit_time = 0.0
            submitted_batches = 0

            for qb_idx, query_codes in enumerate(query_batches):
                placeholders = ", ".join([f"${i+1}" for i in range(len(query_codes))])

                tq = time.time()
                batch_df = con.execute(
                    f"SELECT * FROM stocks WHERE code IN ({placeholders})", query_codes
                ).fetchdf()
                total_query_time += time.time() - tq

                if batch_df.empty:
                    errors += len(query_codes)
                    continue

                # 按 code 分组(不做 _process_stock_df,留给 worker 并行处理)
                grouped = {str(code): group for code, group in batch_df.groupby("code")}
                del batch_df

                # 拆成 WORKER_BATCH 只一组提交给 worker
                codes_list = list(grouped.keys())
                for i in range(0, len(codes_list), WORKER_BATCH):
                    sub_codes = codes_list[i:i + WORKER_BATCH]
                    stock_data_list = [(code, grouped[code].copy()) for code in sub_codes]

                    args = (stock_data_list, formula, suffixes, tf, req.start_date, req.end_date)
                    ts = time.time()
                    future = pool.submit(process_stock_batch, args)
                    total_submit_time += time.time() - ts
                    futures[future] = sub_codes
                    submitted_batches += 1

                del grouped

                # 每次查询后报告进度
                elapsed = round(time.time() - t_query_start, 1)
                logger.info(
                    f"查询进度: {qb_idx+1}/{len(query_batches)} 次 [{elapsed}s] "
                    f"(查询={total_query_time:.1f}s 提交={total_submit_time:.1f}s 已提交{submitted_batches}批)"
                )
                yield ("progress", {
                    "step": "query",
                    "message": f"数据查询中: {qb_idx+1}/{len(query_batches)} 次",
                })

            t_query_end = time.time()
            logger.info(
                f"全部提交完成: {submitted_batches} worker批, 耗时 {t_query_end-t_query_start:.2f}s "
                f"(查询={total_query_time:.1f}s 提交={total_submit_time:.1f}s)"
            )

            # 收集结果
            done_stocks = 0
            total = len(target_codes)
            next_log_pct = 10
            first_result = True

            for future in as_completed(futures):
                if first_result:
                    logger.info(f"首个 worker 结果返回, 等待耗时 {time.time()-t_query_start:.1f}s")
                    first_result = False

                batch_codes = futures[future]
                try:
                    batch_results = future.result(timeout=300)
                    for code, close_series, factor in batch_results:
                        close_dict[code] = close_series
                        factor_dict[code] = factor
                except Exception as e:
                    errors += len(batch_codes)
                    done_stocks += len(batch_codes)
                    logger.error(f"批次计算失败 (标的如 {batch_codes[0]} 等): {e}")
                    continue

                done_stocks += len(batch_codes)

                pct = done_stocks * 100 // total
                if pct >= next_log_pct or done_stocks == total:
                    elapsed = round(time.time() - t1, 1)
                    logger.info(f"计算进度: {done_stocks}/{total} ({pct}%) [{elapsed}s]")
                    yield ("progress", {
                        "step": "compute",
                        "message": f"计算中: {done_stocks}/{total} ({pct}%)",
                        "elapsed": elapsed,
                    })
                    next_log_pct = (pct // 10 + 1) * 10
    finally:
        con.close()

    t2 = time.time()
    logger.info(f"并行计算完成: {len(factor_dict)} 只成功, {errors} 只失败, 耗时 {t2-t1:.2f}s")
    yield ("progress", {
        "step": "compute",
        "message": f"计算完成: {len(factor_dict)} 只" + (f",{errors} 只失败" if errors else ""),
        "elapsed": round(t2 - t1, 2),
    })

    if not factor_dict:
        raise HTTPException(status_code=400, detail="所有标的因子计算失败,请检查公式是否正确")

    # ---- 阶段3: 面板构建 + IC 计算 ----
    import gc

    t_panel = time.time()
    factor_panel = pd.concat(factor_dict, axis=1)
    logger.info(f"  factor_panel concat: {time.time()-t_panel:.2f}s, shape={factor_panel.shape}")
    del factor_dict

    t_close = time.time()
    close_panel = pd.concat(close_dict, axis=1)
    logger.info(f"  close_panel concat: {time.time()-t_close:.2f}s")
    del close_dict

    t_ret = time.time()
    returns_panel = close_panel.pct_change(req.forward_period).shift(-req.forward_period)
    logger.info(f"  returns_panel 计算: {time.time()-t_ret:.2f}s")
    del close_panel

    t_gc = time.time()
    gc.collect()
    logger.info(f"  gc.collect: {time.time()-t_gc:.2f}s")

    t3 = time.time()
    logger.info(f"面板构建完成: {factor_panel.shape}, 耗时 {t3-t2:.2f}s")
    yield ("progress", {"step": "panel", "message": f"面板构建完成: {factor_panel.shape}", "elapsed": round(t3 - t2, 2)})

    # 诊断日志(避免 flatten 拷贝全量数据)
    fp_valid = factor_panel.notna().sum(axis=1)
    rp_valid = returns_panel.notna().sum(axis=1)
    logger.info(
        f"面板诊断: dates={len(factor_panel)}, "
        f"factor有效股票/日: min={fp_valid.min()} max={fp_valid.max()} mean={fp_valid.mean():.0f}, "
        f"return有效股票/日: min={rp_valid.min()} max={rp_valid.max()} mean={rp_valid.mean():.0f}"
    )
    vals = factor_panel.values
    mask = ~np.isnan(vals)
    if mask.any():
        logger.info(
            f"factor值分布: min={np.nanmin(vals):.4f} max={np.nanmax(vals):.4f} "
            f"std={np.nanstd(vals):.4f} unique={len(np.unique(vals[mask]))}"
        )
    else:
        logger.warning("factor全部为NaN!")

    # 截面 IC 计算
    t_ic = time.time()
    result = calculate_cross_sectional_ic(factor_panel, returns_panel)

    t4 = time.time()
    logger.info(f"IC 计算完成: {len(result['ic_series'])} 个有效日期, 耗时 {t4-t_ic:.2f}s")
    logger.info(f"回测完成, 总耗时 {t4-t0:.2f}s")
    yield ("progress", {"step": "ic", "message": "IC 计算完成", "elapsed": round(t4 - t3, 2)})

    if not result["ic_series"]:
        raise HTTPException(status_code=400, detail="IC 计算无有效结果,请检查公式")

    yield ("result", result)


@app.post("/validate-filter")
def validate_filter(body: dict):
    """保存规则前验证:解析并检查是否所有条件都能执行"""
    description = body.get("description", "")
    if not description.strip():
        raise HTTPException(status_code=400, detail="过滤规则描述不能为空")
    try:
        from stock_filter import validate_filter_rule
        result = validate_filter_rule(description)
        return result
    except Exception as e:
        logger.error(f"过滤规则验证失败: {e}")
        raise HTTPException(status_code=500, detail=f"规则解析失败: {str(e)}")


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host=config.HOST, port=config.PORT)