feat: self-driving scan (chunk'ları tamamlanana kadar sürer, cron'suz)
Browse files190 unmodified lines19119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224395 unmodified lines3393403413423433443453463473483493503513521 unmodified line3543553563573583593607 unmodified lines36836937037137237337437595 unmodified lines47147247347447547647747847948048148248348448548648748848912 unmodified lines5025035045055065075085095105115125135145155165171941 unmodified lines24592460246124622463246424652466246724682469247024712472247324742475247624772478190 unmodified linesprint(f"[scheduler] stale-check error ({market_id}): {_e}")result_data: dict = {}try:from trading.scanner_engine import ScanConfig, run_scan as _engine_scanimport logging as _logging_scan_logger = _logging.getLogger(f"scan-{label.lower()}-{market_id}")config = ScanConfig(market_id=market_id,universe_name=universe,title=title,max_stage2_per_run=max_stage2_per_run,)result_data = _engine_scan(config, _scan_logger, force=force_fresh, stage1_only=stage1_only) or {}except Exception as e:_scan_status = {"running": False,"progress": f"{label} tarama hatası ({title}): {e}","error": str(e),"universe": universe,"market_id": market_id,"scheduled": True,}print(f"[scheduler] {label} scan error ({market_id}): {e}")try:# Best-effort upload of partial state so progress isn't lost.from trading.scan_state_sync import upload_scan_stateupload_scan_state(market_id, final=False)except Exception:passtry:from trading.telegram_notify import notify as _tgn_tgn("scan_error", force=True, market_id=market_id,universe=universe, error=str(e))except Exception:passreturnis_completed = bool(result_data.get("completed"))# Always upload work state after a chunk; upload final on completion.try:from trading.scan_state_sync import upload_scan_stateupload_scan_state(market_id, final=False)if is_completed:upload_scan_state(market_id, final=True)except Exception as _e:print(f"[scheduler] scan_state upload error ({market_id}): {_e}")s2 = result_data.get("stage2") or {}s1 = result_data.get("stage1") or {}95 unmodified linesif finished:scan_dt = datetime.fromisoformat(str(finished).replace("Z", "+00:00"))age_hours = (datetime.now(timezone(timedelta(hours=0))) - scan_dt).total_seconds() / 3600# Boot-scan staleness threshold: previously 72h (3 days),# which combined with HF free-tier sleep meant scans would# be skipped during normal nightly windows. Now driven by# BOOT_SCAN_MAX_AGE_HOURS (default 168h = 7 days). Nightly# re-runs are still enforced separately via SCAN_MAX_AGE_HOURS.boot_max_age = float(os.environ.get("BOOT_SCAN_MAX_AGE_HOURS", "168"))if age_hours > boot_max_age:print(f"[scheduler] {market_id} scan results stale ({age_hours:.0f}h > {boot_max_age:.0f}h)")try:from trading.telegram_notify import notify as _tgn_tgn("scan_stale", market_id=market_id, age_hours=age_hours)1 unmodified linepassreturn Trueelse:print(f"[scheduler] {market_id} scan results fresh ({age_hours:.0f}h old, <{boot_max_age:.0f}h)")return Falseelse:return True7 unmodified lines# Now: run a small Stage 2 chunk on boot so the worker has signals# quickly, while leaving the bulk of Stage 2 to the cron-driven# /scan/tick endpoint during off-hours.BOOT_CHUNK = 3boot_enabled = os.environ.get("SCAN_BOOT_ENABLED", "0").strip().lower() in {"1", "true", "yes", "on"}if boot_enabled:if _needs_boot_scan("bist"):_run_scan_in_thread("bist100", "Boot-BIST", stage1_only=False,95 unmodified linesdef _load_scan_payload(market_id: str) -> tuple[Optional[dict], str]:"""Pick the best scan payload to expose to consumers.Overlap protection: a COMPLETED scan is preferred over an in-progress (work)scan even when the work scan has a newer timestamp. Without this, a freshlystarted chunked scan with only a handful of stage2 results would shadow theprevious fully-completed scan (e.g. eligible=2 instead of eligible=15)until it finishes hours/days later.Tiebreaker: when both candidates share the same completed flag, the newertimestamp wins. A staleness check is applied separately in`_scan_already_completed` (SCAN_MAX_AGE_HOURS) so we still re-run scanswhose completed snapshot has aged out."""from trading.market_registry import get_scan_results_pathwork_file = get_scan_results_path(market_id, completed=False)12 unmodified linesreturn None, "none"loaded.sort(key=lambda item: (# 1) completed scans rank above in-progress scansbool(item[1].get("completed")),# 2) tiebreak by max known timestampmax(_scan_timestamp(item[1].get("updated_at")),_scan_timestamp(item[1].get("scan_finished")),_scan_timestamp(item[1].get("chunk_paused_at")),_scan_timestamp(item[1].get("scan_started")),),# 3) final source-label beats work-label when everything else ties1 if item[0] == "final" else 0,),reverse=True,1941 unmodified lines_timestamp_of((work_data or {}).get("scan_started")),)# Overlap protection: prefer a completed (final) scan over an# in-progress (work) scan, even if the work scan is newer. Falls back# to the work scan only when no completed scan exists, or when the# work scan itself is already completed and newer.final_completed = bool((final_data or {}).get("completed"))work_completed = bool((work_data or {}).get("completed"))if work_data and (not final_dataor (work_completed and (work_ts >= final_ts or not final_completed))or (not final_completed and not work_completed and work_ts >= final_ts)):using_work_file = Trueelse:using_work_file = Falsedata = work_data if using_work_file else final_dataif data is None:raise RuntimeError("Scan payload is empty")190 unmodified lines19119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927095 unmodified lines3663673683693703713723731 unmodified line3753763773783793803817 unmodified lines38939039139239339439539639739839940040140295 unmodified lines49849950050150250312 unmodified lines5165175185195205215225235245255265271941 unmodified lines2469247024712472247324742475190 unmodified linesprint(f"[scheduler] stale-check error ({market_id}): {_e}")result_data: dict = {}from trading.scanner_engine import ScanConfig, run_scan as _engine_scanfrom trading.scan_state_sync import upload_scan_stateimport logging as _logging_scan_logger = _logging.getLogger(f"scan-{label.lower()}-{market_id}")# ── SELF-DRIVING SCAN ─────────────────────────────────────────────# Run chunks back-to-back IN THIS background thread until the scan# completes. No dependency on an external /scan/tick cron — HF finishes# the scan by itself. Each chunk uploads a checkpoint to Supabase, so a# container restart resumes from where it left off (crash-safe).# force_fresh wipes ONLY on the first chunk; later chunks resume._SELF_DRIVE_MAX_CHUNKS = 300 # safety capis_completed = Falsefor _chunk_i in range(_SELF_DRIVE_MAX_CHUNKS):config = ScanConfig(market_id=market_id,universe_name=universe,title=title,max_stage2_per_run=max_stage2_per_run,)try:result_data = _engine_scan(config, _scan_logger,force=(force_fresh and _chunk_i == 0),stage1_only=stage1_only,) or {}except Exception as e:_scan_status = {"running": False,"progress": f"{label} tarama hatası ({title}): {e}","error": str(e),"universe": universe,"market_id": market_id,"scheduled": True,}print(f"[scheduler] {label} scan error ({market_id}): {e}")try:upload_scan_state(market_id, final=False)except Exception:passtry:from trading.telegram_notify import notify as _tgn_tgn("scan_error", force=True, market_id=market_id,universe=universe, error=str(e))except Exception:passreturnis_completed = bool(result_data.get("completed"))# Checkpoint after every chunk (crash-safe resume across restarts)try:upload_scan_state(market_id, final=False)if is_completed:upload_scan_state(market_id, final=True)except Exception as _e:print(f"[scheduler] scan_state upload error ({market_id}): {_e}")# Live progress between chunks (status endpoint + keeps running flag)_s2 = result_data.get("stage2") or {}_s1 = result_data.get("stage1") or {}_s1p = sum(1 for v in _s1.values() if isinstance(v, dict) and v.get("passed"))_scan_status = {"running": not (is_completed or stage1_only),"progress": f"{label} ilerliyor ({universe}, {title}) — Stage2: {len(_s2)}/{_s1p}","universe": universe, "market_id": market_id, "scheduled": True,"completed": is_completed, "stage2_done": len(_s2), "stage2_total": _s1p,"eligible_count": sum(1 for v in _s2.values() if isinstance(v, dict) and v.get("eligible")),}print(f"[scheduler] {label} chunk {_chunk_i+1}: stage2={len(_s2)}/{_s1p} completed={is_completed}")if is_completed or stage1_only:break_time.sleep(2) # brief settle between chunks (memory release)s2 = result_data.get("stage2") or {}s1 = result_data.get("stage1") or {}95 unmodified linesif finished:scan_dt = datetime.fromisoformat(str(finished).replace("Z", "+00:00"))age_hours = (datetime.now(timezone(timedelta(hours=0))) - scan_dt).total_seconds() / 3600if age_hours > 72:print(f"[scheduler] {market_id} scan results stale ({age_hours:.0f}h old)")try:from trading.telegram_notify import notify as _tgn_tgn("scan_stale", market_id=market_id, age_hours=age_hours)1 unmodified linepassreturn Trueelse:print(f"[scheduler] {market_id} scan results fresh ({age_hours:.0f}h old)")return Falseelse:return True7 unmodified lines# Now: run a small Stage 2 chunk on boot so the worker has signals# quickly, while leaving the bulk of Stage 2 to the cron-driven# /scan/tick endpoint during off-hours.# Checkpoint interval (stocks per chunk). Self-driving loop continues# past this until the whole scan completes; smaller = more frequent# crash-safe Supabase checkpoints.BOOT_CHUNK = 5# Boot scan ON by default: on every Space (re)start, if the scan is stale or# incomplete, the self-driving loop resumes and finishes it without any# external cron — this is what makes HF fully self-sufficient.boot_enabled = os.environ.get("SCAN_BOOT_ENABLED", "1").strip().lower() in {"1", "true", "yes", "on"}if boot_enabled:if _needs_boot_scan("bist"):_run_scan_in_thread("bist100", "Boot-BIST", stage1_only=False,95 unmodified linesdef _load_scan_payload(market_id: str) -> tuple[Optional[dict], str]:from trading.market_registry import get_scan_results_pathwork_file = get_scan_results_path(market_id, completed=False)12 unmodified linesreturn None, "none"loaded.sort(key=lambda item: (max(_scan_timestamp(item[1].get("updated_at")),_scan_timestamp(item[1].get("scan_finished")),_scan_timestamp(item[1].get("chunk_paused_at")),_scan_timestamp(item[1].get("scan_started")),),1 if item[0] == "final" else 0,),reverse=True,1941 unmodified lines_timestamp_of((work_data or {}).get("scan_started")),)using_work_file = bool(work_data) and (not final_data or work_ts >= final_ts)data = work_data if using_work_file else final_dataif data is None:raise RuntimeError("Scan payload is empty")
app.py+77-80