devmurtaza commited on
Commit
ca77759
·
1 Parent(s): 1bc8a37

Add auto-retraining scheduler: retrain every 500 new traffic snapshots

Browse files
Files changed (2) hide show
  1. app/main.py +4 -0
  2. app/services/scheduler.py +123 -0
app/main.py CHANGED
@@ -1,5 +1,6 @@
1
  """FastAPI application entrypoint."""
2
  from __future__ import annotations
 
3
  from contextlib import asynccontextmanager
4
  from fastapi import FastAPI
5
  from fastapi.middleware.cors import CORSMiddleware
@@ -8,6 +9,7 @@ from app.config import settings
8
  from app.database import init_db
9
  from app.utils.logger import logger
10
  from app.api import health, routes, training, feedback, cities
 
11
 
12
 
13
  @asynccontextmanager
@@ -17,7 +19,9 @@ async def lifespan(app: FastAPI):
17
  await init_db()
18
  except Exception as e:
19
  logger.warning(f"DB init failed (continuing): {e}")
 
20
  yield
 
21
  logger.info("Shutting down RastaAI backend")
22
 
23
 
 
1
  """FastAPI application entrypoint."""
2
  from __future__ import annotations
3
+ import asyncio
4
  from contextlib import asynccontextmanager
5
  from fastapi import FastAPI
6
  from fastapi.middleware.cors import CORSMiddleware
 
9
  from app.database import init_db
10
  from app.utils.logger import logger
11
  from app.api import health, routes, training, feedback, cities
12
+ from app.services.scheduler import retraining_loop
13
 
14
 
15
  @asynccontextmanager
 
19
  await init_db()
20
  except Exception as e:
21
  logger.warning(f"DB init failed (continuing): {e}")
22
+ task = asyncio.create_task(retraining_loop())
23
  yield
24
+ task.cancel()
25
  logger.info("Shutting down RastaAI backend")
26
 
27
 
app/services/scheduler.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Background retraining scheduler.
2
+
3
+ Runs as an asyncio task inside the FastAPI lifespan. Every CHECK_INTERVAL_HOURS
4
+ it queries the DB for new traffic snapshots accumulated since the last training
5
+ run. If NEW_SNAPSHOTS_THRESHOLD or more have arrived, it fires a full retrain
6
+ in a thread (non-blocking) and hot-reloads the model bundle.
7
+
8
+ Nothing in the existing prediction path changes — this is purely additive.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ from datetime import datetime
14
+
15
+ from app.utils.logger import logger
16
+
17
+ CHECK_INTERVAL_HOURS = 6
18
+ NEW_SNAPSHOTS_THRESHOLD = 500
19
+
20
+ _training_lock = asyncio.Lock()
21
+
22
+
23
+ async def _count_new_snapshots(last_trained_at: datetime | None) -> int:
24
+ """Return how many traffic_snapshots exist since last_trained_at."""
25
+ try:
26
+ from sqlalchemy import select, func
27
+ from app.database import AsyncSessionLocal
28
+ from app.models.db_models import TrafficSnapshot
29
+
30
+ async with AsyncSessionLocal() as session:
31
+ q = select(func.count()).select_from(TrafficSnapshot)
32
+ if last_trained_at is not None:
33
+ q = q.where(TrafficSnapshot.captured_at > last_trained_at)
34
+ result = await session.execute(q)
35
+ return result.scalar_one() or 0
36
+ except Exception as exc:
37
+ logger.warning(f"Scheduler: could not count snapshots: {exc}")
38
+ return 0
39
+
40
+
41
+ async def _last_training_time() -> datetime | None:
42
+ """Return the created_at of the most recent TrainingRun, or None."""
43
+ try:
44
+ from sqlalchemy import select
45
+ from app.database import AsyncSessionLocal
46
+ from app.models.db_models import TrainingRun
47
+
48
+ async with AsyncSessionLocal() as session:
49
+ result = await session.execute(
50
+ select(TrainingRun.created_at).order_by(TrainingRun.created_at.desc()).limit(1)
51
+ )
52
+ row = result.scalar_one_or_none()
53
+ return row
54
+ except Exception as exc:
55
+ logger.warning(f"Scheduler: could not fetch last training time: {exc}")
56
+ return None
57
+
58
+
59
+ async def _run_retrain() -> None:
60
+ """Trigger training in a thread and hot-reload the bundle. Non-fatal."""
61
+ try:
62
+ from app.training.train import train as run_training
63
+ from app.models.inference import bundle
64
+ from app.database import AsyncSessionLocal
65
+ from app.models.db_models import TrainingRun
66
+
67
+ logger.info("Scheduler: starting auto-retrain...")
68
+ result = await asyncio.to_thread(run_training, 20000, 0.2, "xgboost")
69
+
70
+ # Hot-reload so the next request uses the new model immediately
71
+ bundle.load()
72
+
73
+ # Log the training run to DB
74
+ async with AsyncSessionLocal() as session:
75
+ session.add(TrainingRun(
76
+ samples=result["samples"],
77
+ eta_metrics=result["eta_metrics"],
78
+ fuel_metrics=result["fuel_metrics"],
79
+ model_type="xgboost",
80
+ artifact_path=result["saved_to"],
81
+ ))
82
+ await session.commit()
83
+
84
+ logger.info(
85
+ f"Scheduler: auto-retrain complete — "
86
+ f"ETA MAE={result['eta_metrics']['mae']:.1f}min "
87
+ f"Fuel MAE={result['fuel_metrics']['mae']:.3f}L"
88
+ )
89
+ except Exception as exc:
90
+ logger.error(f"Scheduler: auto-retrain failed (model unchanged): {exc}")
91
+
92
+
93
+ async def retraining_loop() -> None:
94
+ """Main scheduler loop. Starts on app startup, runs forever."""
95
+ logger.info(
96
+ f"Scheduler: started — checking every {CHECK_INTERVAL_HOURS}h, "
97
+ f"threshold={NEW_SNAPSHOTS_THRESHOLD} new snapshots"
98
+ )
99
+
100
+ while True:
101
+ await asyncio.sleep(CHECK_INTERVAL_HOURS * 3600)
102
+
103
+ if _training_lock.locked():
104
+ logger.info("Scheduler: training already running, skipping this cycle.")
105
+ continue
106
+
107
+ last_trained = await _last_training_time()
108
+ new_count = await _count_new_snapshots(last_trained)
109
+
110
+ logger.info(
111
+ f"Scheduler: {new_count} new snapshots since "
112
+ f"{last_trained.isoformat() if last_trained else 'never'} "
113
+ f"(threshold={NEW_SNAPSHOTS_THRESHOLD})"
114
+ )
115
+
116
+ if new_count >= NEW_SNAPSHOTS_THRESHOLD:
117
+ async with _training_lock:
118
+ await _run_retrain()
119
+ else:
120
+ logger.info(
121
+ f"Scheduler: not enough data yet "
122
+ f"({NEW_SNAPSHOTS_THRESHOLD - new_count} more snapshots needed)."
123
+ )