Files
ewoooc/run_scheduler.py
ogt ba86f98514
Some checks failed
CD Pipeline / deploy (push) Has been cancelled
feat: integrate Elephant Alpha ecosystem with full ADR-012/013 compliance
- Add ElephantService, AutonomousEngine, Orchestrator, DecisionRouter (EA 4-file stack)
- Fix 10 bugs: URL typo, SQL schema mismatches (price_records JOIN), enum mapping,
  metadata_json, NemoTron PriceThreat dispatch, async/await mismatch, broken imports
- Wire ADR-012 Agent Action Ladder: EventRouter L2 → EA first + AIOrch fallback;
  all decisions dual-write DB + triaged_alert Telegram; momo: callback prefix
- Wire ADR-013 AutoHeal: resource_optimization trigger → AutoHealService
- Add W3 guards: connection cache 300s TTL, $5/hr cost hard limit
- Add W4 persistence: routing decisions + agent performance snapshots → ai_insights
- Add Migration 015: confidence + created_by columns on ai_insights
- Fix run_scheduler.py broken imports (DecisionTracker service didn't exist)
- Fix verify_elephant_integration.py: check_status() → check_connection()

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-20 04:28:26 +08:00

73 lines
2.3 KiB
Python

# run_scheduler.py
import asyncio
import logging
import threading
import time
import schedule
from datetime import datetime, timedelta, timezone
from database.manager import get_session
logger = logging.getLogger(__name__)
# ICAIM completion callback — decision_tracker service reserved for future implementation
def on_icaim_task_complete(plan_id: int, sku: str):
"""Triggered by ICAIM scheduler after task completion."""
logger.info("[Scheduler] [ICAIM] on_icaim_task_complete: plan_id=%s sku=%s", plan_id, sku)
# schedule settings (keep original schedule logic)
def run_icaim_task():
"""Simulate ICAIM task execution."""
logger.info("[Scheduler] [ICAIM] executing ICAIM analysis task...")
plan_id = 123
sku = "sample_sku"
on_icaim_task_complete(plan_id, sku)
logger.info("[Scheduler] [ICAIM] task completed, triggered follow_up schedule")
schedule.every(6).hours.do(run_icaim_task)
logger.info("📅 scheduled: ICAIM analysis task every 6 hours")
# B8 FIX: Elephant Alpha autonomous engine startup
# Runs in a dedicated daemon thread with its own asyncio event loop.
# Isolated from the schedule loop so a crash doesn't kill the scheduler.
def _run_elephant_alpha_engine():
"""Daemon thread: runs EA autonomous monitoring in its own asyncio loop."""
try:
from services.elephant_alpha_autonomous_engine import autonomous_engine
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
logger.info("🐘 [ElephantAlpha] Autonomous engine thread started")
loop.run_until_complete(autonomous_engine.start_autonomous_monitoring())
except Exception as e:
logger.error(f"🐘 [ElephantAlpha] Engine crashed: {e}")
finally:
loop.close()
_ea_thread = threading.Thread(
target=_run_elephant_alpha_engine,
daemon=True,
name="elephant-alpha-engine"
)
_ea_thread.start()
logger.info("🐘 [ElephantAlpha] Autonomous engine thread launched")
# start schedule loop (keep original main loop)
if __name__ == "__main__":
logger.info("Scheduler started.")
while True:
try:
schedule.run_pending()
time.sleep(1)
except KeyboardInterrupt:
logger.info("Scheduler stopped.")
break
except Exception as e:
logger.error(f"Scheduler error: {e}")
time.sleep(5)