Coverage for app / services / scheduler / runner.py: 79%
175 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""
2The scheduler — the thing the stack did not have.
4Three features were shaped around its absence and say so in their own
5docstrings: dashboard widgets refresh when a board is *viewed*, review-flag
6retention is enforced when the queue is *read*, and nothing can alert. This
7runs them on a timer instead.
9──────────────────────────────────────────────────────────────────────────────
10In svc-core's process, not a new container
11──────────────────────────────────────────────────────────────────────────────
13The deployment is deliberately segmented — every service on its own network,
14every outbound path explicit — so a new container is a real architectural
15decision, not a convenience. A scheduler needs exactly what svc-core already
16has: the core database, the widget registry, the rule engine. Giving it its
17own image would mean duplicating all three across a network boundary to run
18two functions that already live here.
20The cost is stated rather than hidden: a job runs in svc-core's thread pool,
21so a slow job occupies a worker thread that would otherwise serve requests.
22:attr:`DashboardRefreshJob.MAX_PER_TICK` is the bound on that, and a job heavy
23enough to need more is the signal to revisit this decision rather than to
24raise the ceiling.
26──────────────────────────────────────────────────────────────────────────────
27One leader, elected by Postgres
28──────────────────────────────────────────────────────────────────────────────
30svc-core can run as several replicas, and two replicas both purging retention
31is harmless while two both refreshing the same widget is an LLM call paid for
32twice. So a replica holds a **session-level advisory lock** for as long as it
33schedules, on a connection of its own.
35Session-level rather than the transactional form the migration runner uses,
36because the lock must outlive a single statement. The important property is
37what happens when a leader *dies*: its connection drops, Postgres releases the
38lock automatically, and the next replica to tick picks it up. There is no
39lease to expire and no heartbeat to get wrong — which is the failure mode
40hand-rolled leader election usually has.
42A replica that does not hold the lock still serves requests normally, and
43refresh-on-view still works there. Losing the election costs nothing.
45──────────────────────────────────────────────────────────────────────────────
46Overlap, and why the tick is not a timer
47──────────────────────────────────────────────────────────────────────────────
49The loop sleeps between ticks rather than firing on a fixed schedule, so a
50tick that takes longer than the interval delays the next one instead of
51stacking a second copy on top of it. Jobs are therefore never re-entered while
52still running in this process, which is what lets each one be written as a
53plain synchronous function.
54"""
56from __future__ import annotations
58import asyncio
59import logging
60from time import perf_counter
61from typing import Any
63from sqlalchemy import text
64from sqlalchemy.exc import SQLAlchemyError
65from sqlalchemy.orm import Session
67from app.db.postgres.engine import SessionLocal, engine
68from app.db.postgres.enums import SchedulerEnum
69from app.db.postgres.models import ScheduledJob
70from app.util.time import aware_utcnow
72from .jobs import Job, JobResult, all_jobs, get_job
74logger = logging.getLogger(__name__)
76#: Advisory lock id for scheduler leadership. Distinct from the migration
77#: runner's 123456789 — a replica must be able to hold one without the other,
78#: and sharing an id would make migrations and scheduling exclude each other
79#: for no reason.
80SCHEDULER_LOCK_ID = 987654321
83def _aware(value: Any):
84 """Treat naive timestamps from Postgres as UTC, as the refresh rules do."""
85 if value is None:
86 return None
87 return value if value.tzinfo else value.replace(tzinfo=aware_utcnow().tzinfo)
90# ─── Job state ────────────────────────────────────────────────────────────────
93def due_jobs(db: Session, jobs: list[Job], now=None) -> list[Job]:
94 """Which of ``jobs`` should run now.
96 A job with no row has never run and is due immediately: that is what makes
97 a freshly deployed job take effect without waiting out its first interval.
98 """
99 moment = now or aware_utcnow()
100 try:
101 rows = {row.key: row for row in db.query(ScheduledJob).all()}
102 except SQLAlchemyError:
103 logger.exception("Could not read scheduled job state; skipping this tick")
104 return []
106 due: list[Job] = []
107 for job in jobs:
108 row = rows.get(job.key)
109 last = _aware(row.last_started_at) if row else None
110 if last is None or (moment - last).total_seconds() >= job.interval_seconds:
111 due.append(job)
112 return due
115def record(
116 db: Session,
117 job: Job,
118 result: JobResult,
119 *,
120 started_at,
121 duration_ms: int,
122) -> None:
123 """Write one run onto the job's row.
125 Never raises: a scheduler that fell over while recording that a job
126 succeeded would be worse than one that simply did not record it.
127 """
128 try:
129 row = db.get(ScheduledJob, job.key)
130 if row is None:
131 row = ScheduledJob(key=job.key, run_count=0, failure_count=0)
132 db.add(row)
133 row.last_started_at = started_at
134 row.last_finished_at = aware_utcnow()
135 row.last_duration_ms = duration_ms
136 row.last_status = result.status
137 row.last_detail = (result.detail or "")[:500]
138 row.run_count = int(row.run_count or 0) + 1
139 if result.status is SchedulerEnum.Status.failed:
140 row.failure_count = int(row.failure_count or 0) + 1
141 row.last_error = (result.detail or "")[:1000]
142 row.last_error_at = aware_utcnow()
143 # A success deliberately does not clear last_error: "working now but
144 # failed at 03:00" is a different statement from "has never failed",
145 # and only one of them is worth waking somebody for.
146 db.commit()
147 except Exception:
148 db.rollback()
149 logger.exception("Could not record the outcome of job %s", job.key)
152def run_job(db: Session, job: Job) -> JobResult:
153 """Run one job and record it. Returns what happened.
155 Exceptions are caught here rather than in the job, so a job author cannot
156 forget to: one raising job must not end the tick and take every other
157 job's schedule down with it.
158 """
159 started_at = aware_utcnow()
160 clock = perf_counter()
161 try:
162 result = job.run(db)
163 except Exception as exc: # one bad job must not stop the rest
164 logger.exception("Scheduled job %s failed", job.key)
165 try:
166 db.rollback()
167 except Exception:
168 logger.exception("Could not roll back after job %s failed", job.key)
169 result = JobResult(SchedulerEnum.Status.failed, f"{type(exc).__name__}: {exc}")
170 duration_ms = int((perf_counter() - clock) * 1000)
171 record(db, job, result, started_at=started_at, duration_ms=duration_ms)
172 return result
175def tick(db: Session, now=None) -> dict[str, JobResult]:
176 """Run every job that is due. Returns what each one did.
178 Separated from the loop so it is testable without asyncio, and callable
179 by hand — which is what the manual-trigger endpoint uses.
180 """
181 outcomes: dict[str, JobResult] = {}
182 for job in due_jobs(db, all_jobs(), now=now):
183 outcomes[job.key] = run_job(db, job)
184 return outcomes
187def run_named(db: Session, key: str) -> JobResult | None:
188 """Run one job by key regardless of whether it is due.
190 For the manual trigger. Returns None when no such job is registered.
191 """
192 job = get_job(key)
193 if job is None:
194 return None
195 return run_job(db, job)
198# ─── Leadership ───────────────────────────────────────────────────────────────
201class Leadership:
202 """A session-level advisory lock held for as long as this replica leads.
204 Holds its own connection, checked out of the pool for the process
205 lifetime. That is the point: the lock is tied to the connection, so a
206 crashed leader releases it without anybody noticing it crashed.
207 """
209 def __init__(self, lock_id: int = SCHEDULER_LOCK_ID) -> None:
210 self._lock_id = lock_id
211 self._connection = None
213 @property
214 def held(self) -> bool:
215 return self._connection is not None
217 def acquire(self) -> bool:
218 """Try to become leader. Cheap and safe to call every tick."""
219 if self.held:
220 # Holding the lock is exactly holding the *connection*, so a
221 # connection that has died — killed by the server, dropped by a
222 # middlebox after days idle — means the lock is already gone and
223 # another replica may well have taken it. Continuing to tick on
224 # the strength of a stale flag is how a design with one leader
225 # ends up with two, so liveness is checked rather than assumed.
226 if self._alive():
227 return True
228 logger.warning(
229 "Scheduler lock connection died; standing down and re-electing"
230 )
231 self._discard()
232 try:
233 connection = engine.connect()
234 got = connection.execute(
235 text("SELECT pg_try_advisory_lock(:id)"), {"id": self._lock_id}
236 ).scalar()
237 except SQLAlchemyError:
238 logger.exception("Could not reach the database to elect a scheduler")
239 return False
240 if not got:
241 # Another replica leads. Not an error, and not worth logging every
242 # tick — this is the normal state of every replica but one.
243 connection.close()
244 return False
245 self._connection = connection
246 logger.info("This replica is now the scheduler leader")
247 return True
249 def _alive(self) -> bool:
250 """Whether the lock-holding connection is still usable."""
251 try:
252 self._connection.execute(text("SELECT 1"))
253 return True
254 except SQLAlchemyError:
255 return False
257 def _discard(self) -> None:
258 """Drop a connection whose lock Postgres has already released.
260 No unlock attempt: the connection is dead, so the lock went with it,
261 and the only thing left to do is stop pretending to hold it.
262 """
263 try:
264 self._connection.invalidate()
265 except Exception: # noqa: BLE001 — the connection is already gone
266 logger.debug("Could not invalidate the dead scheduler connection")
267 finally:
268 self._connection = None
270 def release(self) -> None:
271 """Stand down. Called on shutdown; a crash achieves the same thing."""
272 if self._connection is None:
273 return
274 try:
275 self._connection.execute(
276 text("SELECT pg_advisory_unlock(:id)"), {"id": self._lock_id}
277 )
278 except SQLAlchemyError:
279 logger.warning("Could not release the scheduler lock cleanly")
280 finally:
281 try:
282 self._connection.close()
283 finally:
284 self._connection = None
285 logger.info("Released scheduler leadership")
288# ─── The loop ─────────────────────────────────────────────────────────────────
291class Scheduler:
292 """The background loop. One per process; started from the lifespan."""
294 def __init__(self, tick_seconds: int = 60) -> None:
295 self.tick_seconds = max(1, int(tick_seconds))
296 self.leadership = Leadership()
297 self._task: asyncio.Task | None = None
298 self._stopping = asyncio.Event()
300 @property
301 def running(self) -> bool:
302 return self._task is not None and not self._task.done()
304 async def start(self) -> None:
305 if self.running:
306 return
307 self._stopping.clear()
308 self._task = asyncio.create_task(self._loop(), name="chainr-scheduler")
309 logger.info("Scheduler started (tick every %ss)", self.tick_seconds)
311 async def stop(self) -> None:
312 """Stop ticking and stand down as leader.
314 Waits for an in-flight tick rather than cancelling it: a job halfway
315 through refreshing widgets should finish the one it is on, and every
316 job is short by construction.
317 """
318 self._stopping.set()
319 if self._task is not None:
320 try:
321 await asyncio.wait_for(self._task, timeout=30)
322 except TimeoutError:
323 logger.warning("Scheduler did not stop in time; cancelling")
324 self._task.cancel()
325 except asyncio.CancelledError:
326 pass
327 self._task = None
328 self.leadership.release()
330 async def _loop(self) -> None:
331 loop = asyncio.get_running_loop()
332 while not self._stopping.is_set():
333 try:
334 if self.leadership.acquire():
335 # Jobs are synchronous SQLAlchemy, so they run in the
336 # thread pool rather than blocking the event loop that is
337 # also serving this replica's HTTP requests.
338 await loop.run_in_executor(None, _tick_in_session)
339 except Exception: # the loop must outlive any tick
340 logger.exception("Scheduler tick failed")
341 try:
342 # Sleeping *after* the tick is what keeps a long tick from
343 # stacking a second copy on top of itself.
344 await asyncio.wait_for(self._stopping.wait(), timeout=self.tick_seconds)
345 except TimeoutError:
346 continue
349def _tick_in_session() -> None:
350 """Run a tick with a session of its own.
352 The loop has no request to borrow a session from, and a long-lived one
353 would hold a connection and a stale transaction snapshot between ticks.
354 """
355 db = SessionLocal()
356 try:
357 tick(db)
358 finally:
359 db.close()
362#: The process's scheduler, created by the lifespan. None when disabled.
363_scheduler: Scheduler | None = None
366def get_scheduler() -> Scheduler | None:
367 return _scheduler
370def set_scheduler(scheduler: Scheduler | None) -> None:
371 global _scheduler
372 _scheduler = scheduler