Coverage for app / services / scheduler / jobs.py: 74%
283 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"""
2Jobs — the work the scheduler does on a timer.
4One class per job, registered with :func:`register_job`, mirroring how widget
5types, rule actions, scorers and stat metrics already work. A job owns four
6things: how often it should run, what it does, what to say about what it did,
7and whether it is safe to run again immediately.
9──────────────────────────────────────────────────────────────────────────────
10Every job must be idempotent
11──────────────────────────────────────────────────────────────────────────────
13The scheduler makes no at-most-once promise and is not written to. A replica
14can lose the leader lock mid-tick and another can pick the job up; a restart
15re-runs anything due. Both jobs below are safe under that because they ask the
16database what still needs doing rather than tracking what they have done —
17``is_stale`` gates a refresh, and an expired flag either still exists or does
18not.
20A job that cannot be written that way does not belong here without a claim
21mechanism of its own, and ``run`` is the wrong place to invent one.
23──────────────────────────────────────────────────────────────────────────────
24A job never raises
25──────────────────────────────────────────────────────────────────────────────
27``run`` returns a :class:`JobResult`; the runner records it. An exception that
28escaped would stop the tick and take every *other* job down with it, which is
29the failure mode a scheduler exists to avoid — one wedged job silently ending
30retention enforcement for the whole platform.
31"""
33from __future__ import annotations
35import logging
36from abc import ABC, abstractmethod
37from dataclasses import dataclass
38from typing import Any, ClassVar
40from sqlalchemy.orm import Session
42from app.db.postgres.enums import SchedulerEnum
44logger = logging.getLogger(__name__)
47@dataclass
48class JobResult:
49 """What one run of a job came to."""
51 status: SchedulerEnum.Status
52 #: One line describing what happened, shown on the scheduler status page.
53 detail: str = ""
55 @classmethod
56 def did(cls, detail: str) -> JobResult:
57 return cls(SchedulerEnum.Status.ok, detail)
59 @classmethod
60 def nothing_to_do(cls, detail: str = "Nothing to do.") -> JobResult:
61 """Ran and found nothing.
63 Distinct from ``ok`` because "ran and found nothing to do" and "did
64 not run" look identical in a log and mean opposite things when
65 somebody is asking whether retention is being enforced.
66 """
67 return cls(SchedulerEnum.Status.skipped, detail)
70class Job(ABC):
71 """One unit of work the scheduler runs on a timer."""
73 #: Stable key. Also the primary key of the job's ``scheduled_jobs`` row,
74 #: so renaming one starts a fresh history rather than rewriting the old.
75 key: ClassVar[str]
76 #: Human label for the status page.
77 label: ClassVar[str]
78 #: One line saying what the job is for.
79 description: ClassVar[str] = ""
80 #: How often it should run. The tick interval bounds the resolution: a
81 #: job asking for 10s on a 60s tick runs every 60s, and says so on the
82 #: status page rather than pretending otherwise.
83 interval_seconds: ClassVar[int]
85 @abstractmethod
86 def run(self, db: Session) -> JobResult:
87 """Do the work. Owns its transaction; the runner commits nothing."""
89 def spec(self) -> dict[str, Any]:
90 return {
91 "key": self.key,
92 "label": self.label,
93 "description": self.description,
94 "interval_seconds": self.interval_seconds,
95 }
98_REGISTRY: dict[str, Job] = {}
99_ORDER: list[str] = []
102def register_job(cls: type[Job]) -> type[Job]:
103 """Class decorator adding one job to the registry."""
104 instance = cls()
105 if instance.key in _REGISTRY:
106 raise RuntimeError(f"Scheduled job '{instance.key}' is already registered.")
107 if instance.interval_seconds <= 0:
108 raise RuntimeError(
109 f"Scheduled job '{instance.key}' must declare a positive interval."
110 )
111 _REGISTRY[instance.key] = instance
112 _ORDER.append(instance.key)
113 return cls
116def get_job(key: str | None) -> Job | None:
117 """The job registered under ``key``, or None if there is none."""
118 if not key:
119 return None
120 return _REGISTRY.get(str(key))
123def job_keys() -> frozenset[str]:
124 """Every registered job key."""
125 return frozenset(_REGISTRY)
128def all_jobs() -> list[Job]:
129 """Registered jobs, in registration order."""
130 return [_REGISTRY[key] for key in _ORDER]
133def catalogue() -> list[dict[str, Any]]:
134 """Registered jobs, described for the status page."""
135 return [job.spec() for job in all_jobs()]
138# ─── Dashboard refresh ────────────────────────────────────────────────────────
141@register_job
142class DashboardRefreshJob(Job):
143 """Regenerate dynamic dashboard widgets whose cache has aged out.
145 This is what refresh-on-view was standing in for. A board's daily digest
146 used to be daily only for somebody who *looked* at the board daily; now
147 the tile is current when they arrive.
149 Refresh-on-view stays, deliberately. It is what makes a newly added tile
150 fill in immediately instead of waiting for a tick, and it is the fallback
151 when the scheduler is disabled or has lost its lock. The two cannot
152 double-refresh: ``mark_refreshing`` claims a widget by committing its
153 status before generating, and ``is_stale`` will not pick up a claimed
154 widget until the stuck-refresh timeout has passed.
155 """
157 key = "dashboard_refresh"
158 label = "Dashboard refresh"
159 description = (
160 "Regenerate feed and generated widgets whose cached result has aged "
161 "past its interval."
162 )
163 interval_seconds = 60
165 #: Ceiling on one tick's work. A board can hold many dynamic tiles and
166 #: each generated one is an LLM call; refreshing every stale widget on the
167 #: platform in a single tick would turn a scheduler into a stampede. The
168 #: rest are picked up next tick, most overdue first, so nothing starves.
169 MAX_PER_TICK = 20
171 #: Wall-clock a tick may spend refreshing before it leaves the rest to
172 #: the next one. Tiles refresh one after another, and an agent's may take
173 #: minutes (``widgets.TILE_TIMEOUT_S``): twenty of them would hold every
174 #: other job for over an hour.
175 TICK_BUDGET_SECONDS = 240
177 def run(self, db: Session) -> JobResult:
178 import time
180 from app.services.dashboards import refresh as refresh_service
182 # Most overdue first, so a tile that has been due longest is
183 # refreshed before one that has just aged out — which is what stops
184 # a busy board's tiles starving a quiet one's.
185 due = refresh_service.due_widgets(db, limit=self.MAX_PER_TICK)
186 if not due:
187 return JobResult.nothing_to_do("No widgets were due.")
189 started = time.monotonic()
190 refreshed = 0
191 for widget in due:
192 if time.monotonic() - started >= self.TICK_BUDGET_SECONDS:
193 break
194 # Claimed before generating, so a board load happening at the same
195 # instant does not queue the same generation a second time.
196 refresh_service.mark_refreshing(db, widget)
197 refresh_service.refresh_widget(
198 db, widget.id, refresh_service.Trigger.scheduled
199 )
200 refreshed += 1
201 left = len(due) - refreshed
202 return JobResult.did(
203 f"Refreshed {refreshed} widget(s)."
204 + (f" {left} left for the next tick." if left else "")
205 )
208# ─── Review retention ─────────────────────────────────────────────────────────
211@register_job
212class ReviewRetentionJob(Job):
213 """Delete review flags whose retention period has passed.
215 ``flag_for_review`` takes a ``retention_days``, and until now it was
216 enforced when the queue happened to be read. That made a retention period
217 "deleted no earlier than" rather than "deleted" — defensible as a
218 fallback, but not as the design: a queue nobody opens for a month keeps
219 flagged excerpts a month past the period somebody set deliberately, and
220 over-retention of flagged content is exactly what a retention setting
221 exists to prevent.
223 Purge-on-read stays as the fallback, for the same reason refresh-on-view
224 does.
225 """
227 key = "review_retention"
228 label = "Review flag retention"
229 description = (
230 "Delete flagged invocations whose retention period has passed, "
231 "across every owner."
232 )
233 #: Hourly. The period is expressed in days, so a finer tick would buy
234 #: nothing and a coarser one would let a same-day retention overrun
235 #: visibly.
236 interval_seconds = 3600
238 def run(self, db: Session) -> JobResult:
239 from app.services import review as review_service
241 # No owner filter: the read path purges only the queue being read,
242 # which is what left every *other* owner's expired flags in place.
243 # Counted per owner first, so each owner's activity feed says what
244 # retention deleted of theirs.
245 by_owner = review_service.expired_counts_by_owner(db)
246 purged = review_service.purge_expired(db)
247 if not purged:
248 return JobResult.nothing_to_do("No flags had expired.")
249 review_service.record_retention_events(db, by_owner)
250 db.commit()
251 return JobResult.did(f"Purged {purged} expired flag(s).")
254# ─── Quick try retention ──────────────────────────────────────────────────────
257@register_job
258class QuickTryRetentionJob(Job):
259 """Delete Quick try comparisons nobody saved.
261 A comparison is persisted as an unowned batch so that saving it can keep
262 the results the user saw (see ``app.services.evaluation.quick_try``). One
263 that was never saved is scratch, and scratch older than
264 ``quick_try.RETENTION_HOURS`` goes — runs included — so the scratchpad
265 never becomes storage nobody asked for.
266 """
268 key = "quick_try_retention"
269 label = "Quick try retention"
270 description = (
271 "Delete unsaved Quick try comparisons older than the retention window."
272 )
273 #: Hourly, like review retention: the window is a day, so a finer tick
274 #: would buy nothing.
275 interval_seconds = 3600
277 def run(self, db: Session) -> JobResult:
278 from app.services.evaluation import quick_try
280 purged = quick_try.purge_expired(db)
281 if not purged:
282 return JobResult.nothing_to_do("No unsaved comparisons had expired.")
283 db.commit()
284 return JobResult.did(f"Purged {purged} unsaved comparison(s).")
287# ─── Background activity retention ────────────────────────────────────────────
290@register_job
291class BackgroundRetentionJob(Job):
292 """Delete background activity older than its retention window.
294 ``background_events`` is append-only and fed by the dashboard refresh
295 above — one row per tile per refresh, 1,440 a day for a tile on a minute's
296 interval. Without this it grew without bound.
298 It records no background event of its own: a per-owner "deleted 1,400
299 refresh records" row, every hour, would be the clutter it is removing.
300 The job's own ``scheduled_jobs`` row is its record.
301 """
303 key = "background_retention"
304 label = "Background activity retention"
305 description = (
306 "Delete background activity records (tile refreshes, website crawls) "
307 "older than BACKGROUND_EVENT_RETENTION_DAYS, across every owner."
308 )
309 #: Hourly, like the other retention jobs: the window is in days.
310 interval_seconds = 3600
312 def run(self, db: Session) -> JobResult:
313 from app.services import background_activity
315 days = background_activity.retention_days()
316 if days is None:
317 return JobResult.nothing_to_do("Retention is off; nothing expires.")
318 purged = background_activity.purge_expired(db)
319 if not purged:
320 return JobResult.nothing_to_do(
321 f"No background activity was older than {days} day(s)."
322 )
323 return JobResult.did(
324 f"Purged {purged} background event(s) older than {days} day(s)."
325 )
328# ─── Retrieval record retention ───────────────────────────────────────────────
331@register_job
332class KnowledgeTurnRetentionJob(Job):
333 """Clear the person's words from the retrieval record once its retention
334 window has passed.
336 A turn's record (``knowledge_turns``) keeps the request as retrieval
337 searched for it, the gaps the quality check named and the files the
338 person named — redacted, and deleted with the answer. What says which
339 knowledge to add needs them for a while, not as long as the answer is
340 kept: after ``KNOWLEDGE_TURN_TEXT_RETENTION_DAYS`` they are cleared, and
341 the counts stay (``services/knowledge/retrievals.py``).
342 """
344 key = "knowledge_turn_retention"
345 label = "Retrieval record retention"
346 description = (
347 "Clear the request text, gaps and file names from retrieval records "
348 "older than KNOWLEDGE_TURN_TEXT_RETENTION_DAYS, across every owner."
349 )
350 #: Hourly, like the other retention jobs: the window is in days.
351 interval_seconds = 3600
353 def run(self, db: Session) -> JobResult:
354 from app.services.knowledge import retrievals
356 days = retrievals.text_retention_days()
357 if days is None:
358 return JobResult.nothing_to_do("Retention is off; nothing is cleared.")
359 cleared = retrievals.clear_expired_text(db)
360 if not cleared:
361 return JobResult.nothing_to_do(
362 f"No retrieval record was older than {days} day(s)."
363 )
364 return JobResult.did(
365 f"Cleared the text of {cleared} retrieval record(s) older than "
366 f"{days} day(s)."
367 )
370# ─── Search-index rebuild ─────────────────────────────────────────────────────
373@register_job
374class KnowledgeReindexJob(Job):
375 """Rebuild search indexes built with an embedding model svc-ai no longer
376 uses, from what is already stored.
378 Registered before the crawls, the guide sync and the benchmark, so on
379 the first tick after a deploy that changes the model the rebuild starts
380 first — and the benchmark waits for the guide's
381 (``services/knowledge/reindex.py``).
382 """
384 key = "knowledge_reindex"
385 label = "Search index rebuild"
386 description = (
387 "When the embedding model changes, recreate each knowledge base's "
388 "search index for it and re-embed its documents, pages and the user "
389 "guide from storage."
390 )
391 #: Every minute while there is work; a tick with nothing to do costs one
392 #: Qdrant read per knowledge base.
393 interval_seconds = 60
395 def run(self, db: Session) -> JobResult:
396 from app.services import ai_client
397 from app.services.knowledge import held, reindex
398 from app.util import embedding
400 try:
401 result = reindex.tick(db)
402 except (ai_client.AIServiceError, embedding.EmbeddingError) as exc:
403 return JobResult(SchedulerEnum.Status.failed, f"svc-ai: {exc}"[:500])
404 # Uploads a used-up budget held, once it starts again
405 # (``knowledge/held.py``).
406 released = held.retry_due(db)
407 note = f" Indexed {released} document(s) a budget had held." if released else ""
408 if result.failed:
409 return JobResult(SchedulerEnum.Status.failed, (result.detail + note)[:500])
410 if not result.started:
411 if released:
412 return JobResult.did(note.strip())
413 return JobResult.nothing_to_do(result.detail)
414 return JobResult.did((result.detail + note)[:500])
417# ─── Website knowledge refresh ────────────────────────────────────────────────
420@register_job
421class WebKnowledgeRefreshJob(Job):
422 """Re-crawl website knowledge sources whose refresh cadence has come round.
424 The job only *claims* crawls and hands them to the crawl pool: a crawl
425 with polite per-host delays runs for minutes, and running it here would
426 hold up every other job on the tick. The claim is a committed
427 ``running`` row, so a manual "Refresh now" landing at the same moment is
428 refused by the database rather than crawling twice.
429 """
431 key = "web_knowledge_refresh"
432 label = "Website knowledge refresh"
433 description = (
434 "Start crawls of website knowledge sources that are due on their "
435 "hourly, daily or weekly cadence."
436 )
437 #: The shortest cadence is hourly; a quarter-hour tick is plenty.
438 interval_seconds = 900
440 #: Crawls started per tick. The pool runs two at a time; the rest of a
441 #: backlog is picked up on later ticks, longest-waiting first. Eight per
442 #: tick is 32 an hour: room for the built-in news feeds (hourly, while
443 #: in use) without users' own sources waiting behind them. A feed crawl
444 #: is short — it fetches only entries it has not seen.
445 MAX_PER_TICK = 8
447 def run(self, db: Session) -> JobResult:
448 from app.services.knowledge import web_crawl
450 abandoned = web_crawl.expire_abandoned(db)
451 started = 0
452 for knowledge in web_crawl.due_sources(db, self.MAX_PER_TICK):
453 try:
454 web_crawl.start(db, knowledge, web_crawl.Trigger.scheduled)
455 started += 1
456 except web_crawl.CrawlError:
457 continue # already running, or its URLs were removed
458 if not started and not abandoned:
459 return JobResult.nothing_to_do("No website sources were due.")
460 detail = f"Started {started} crawl(s)."
461 if abandoned:
462 detail += f" Closed {abandoned} abandoned crawl(s)."
463 return JobResult.did(detail)
466# ─── CHAINR Bot ───────────────────────────────────────────────────────────────
469@register_job
470class ChainrBotSyncJob(Job):
471 """Keep the built-in resources provisioned and their written knowledge
472 indexed.
474 Startup provisions the built-in rows, but indexing the knowledge CHAIN-R
475 writes (the user guide, and every other written source in
476 ``system_resources.knowledge``) needs svc-ai (for embeddings) and Qdrant,
477 neither of which startup may wait on. This does both, idempotently: the
478 rows are re-checked against the definition, and a written document is
479 indexed only when it is new, changed, or its last indexing did not
480 finish — so one that failed to index while svc-ai was starting is picked
481 up on the next run rather than never.
482 """
484 key = "chainr_bot_sync"
485 label = "Built-in resources sync"
486 description = (
487 "Provision the built-in resources — CHAINR Bot, the built-in skillsets "
488 "and the built-in knowledge — and index the knowledge CHAIN-R writes, "
489 "the user guide included, re-indexing any document a release changed."
490 )
491 #: Hourly. Written knowledge changes only with a release, and a new
492 #: release's first tick runs this immediately (a job with no run yet is
493 #: due).
494 interval_seconds = 3600
496 def run(self, db: Session) -> JobResult:
497 from app.services import system_resources
499 provisioned = system_resources.ensure_system_resources(db)
500 synced = system_resources.sync_written(db)
501 if synced.failed:
502 return JobResult(
503 SchedulerEnum.Status.failed,
504 f"{provisioned.summary()} {synced.summary()}",
505 )
506 if not provisioned.changed and not synced.changed:
507 return JobResult.nothing_to_do(
508 f"The built-in resources are up to date; {synced.summary()}"
509 )
510 return JobResult.did(f"{provisioned.summary()} {synced.summary()}")
513@register_job
514class PlatformBenchmarkJob(Job):
515 """Score CHAINR Bot and each maker's strongest model on the gold datasets.
517 Registered after ``chainr_bot_sync``, so on a deploy's first tick the bot
518 is provisioned and its guide re-indexed before it is benchmarked: the
519 benchmark measures the bot as deployed. The job only decides what is due
520 and hands it to the benchmark's own worker — a benchmark runs for an hour
521 or more and must never hold up the tick (see
522 ``app/services/evaluation/benchmark.py``).
523 """
525 key = "platform_benchmark"
526 label = "Platform benchmark"
527 description = (
528 "Score CHAINR Bot on every gold dataset on each deploy, and every "
529 "built-in model when a gold dataset or the judge changes."
530 )
531 #: Ten minutes: a deploy is benchmarked shortly after it lands, and a
532 #: tick with nothing due costs one catalogue read.
533 interval_seconds = 600
535 def run(self, db: Session) -> JobResult:
536 from app.services import ai_client
537 from app.services.evaluation import benchmark
538 from app.services.knowledge import reindex
540 if reindex.guide_pending(db):
541 # The bot answers from the guide: scored on a half-built index,
542 # its benchmark would measure the rebuild, not the bot.
543 return JobResult.nothing_to_do(
544 "Waiting for the user guide's search index to be rebuilt."
545 )
546 try:
547 result = benchmark.tick(db)
548 except ai_client.AIServiceError as exc:
549 return JobResult(SchedulerEnum.Status.failed, f"svc-ai: {exc}"[:500])
550 if not result.started:
551 return JobResult.nothing_to_do(result.detail)
552 return JobResult.did(result.detail)
555@register_job
556class EconomicsExportJob(Job):
557 """Write each finished UTC day's model spend and what it bought.
559 The day's tables (``app/services/economics/export.py``) go into
560 ``ECONOMICS_EXPORT_DIR``, where the compose host picks them up and ships
561 them: to S3 for Athena, and the day's totals to CloudWatch
562 (``infra/aws/economics``). Idempotent the way the module docstring asks:
563 a day is written when its directory has no manifest, and only then.
564 """
566 key = "economics_export"
567 label = "Economics export"
568 description = (
569 "Write each finished UTC day's model spend, by workspace, source and "
570 "model, and what it bought, for the host to ship to S3 and CloudWatch."
571 )
572 #: Hourly. A day is due an hour after midnight UTC; each run also writes
573 #: any day a stopped scheduler missed, a week at a time.
574 interval_seconds = 3600
576 def run(self, db: Session) -> JobResult:
577 from pathlib import Path
579 from app.common.settings import get_settings
580 from app.services.economics import export
582 settings = get_settings()
583 if not settings.ECONOMICS_EXPORT_DIR:
584 return JobResult.nothing_to_do("Off: ECONOMICS_EXPORT_DIR is not set.")
585 try:
586 result = export.run(
587 db,
588 Path(settings.ECONOMICS_EXPORT_DIR),
589 lookback_days=settings.ECONOMICS_EXPORT_LOOKBACK_DAYS,
590 )
591 except export.ExportError as exc:
592 return JobResult(SchedulerEnum.Status.failed, str(exc)[:500])
593 if not result.written:
594 return JobResult.nothing_to_do("Every finished day is written.")
595 days = ", ".join(day.isoformat() for day in result.written)
596 detail = f"Wrote {days}."
597 if result.pending:
598 detail += f" {result.pending} more day(s) next run."
599 return JobResult.did(detail)
602@register_job
603class SpendStatementJob(Job):
604 """Close each finished month: write every workspace's statement once.
606 An hour after a month ends (``app/services/statements/store.py``), each
607 workspace with spend in it gets its statement — spend, budgets and what
608 governed it, aggregate figures only — kept unchanged from then on.
609 Catches up on any month of the last year that has none yet.
610 """
612 key = "spend_statements"
613 label = "Monthly statements"
614 description = (
615 "Write each workspace's statement for each finished month: its spend, "
616 "budgets and governance, kept unchanged once written."
617 )
618 #: Hourly. A month is due an hour after it ends.
619 interval_seconds = 3600
621 def run(self, db: Session) -> JobResult:
622 from app.services.statements import store
624 result = store.run(db)
625 if not result.written:
626 return JobResult.nothing_to_do("Every finished month is written.")
627 detail = f"Wrote {len(result.written)} statement(s)."
628 if result.pending:
629 detail += f" {result.pending} more next run."
630 return JobResult.did(detail)
633@register_job
634class BudgetAlertJob(Job):
635 """Tell those who govern a workspace when its budgets cross their alert
636 levels or head over, and when its platform allowance does
637 (``app/services/budgets/alerts.py``) — each once per period, in their
638 inbox. Also deletes notifications past their retention."""
640 key = "budget_alerts"
641 label = "Budget alerts"
642 description = (
643 "Send inbox alerts when a budget or the platform allowance passes its "
644 "alert levels or is heading over, once each per period."
645 )
646 #: Every ten minutes: an alert follows the spend within that.
647 interval_seconds = 600
649 def run(self, db: Session) -> JobResult:
650 from app.services import notifications
651 from app.services.budgets import alerts
653 result = alerts.run(db)
654 pruned = notifications.prune(db)
655 parts = [f"Checked {result.budgets} budget(s); sent {result.sent} alert(s)."]
656 if pruned:
657 parts.append(f"Deleted {pruned} old notification(s).")
658 if result.errors:
659 return JobResult(
660 SchedulerEnum.Status.failed,
661 " ".join(parts) + f" {len(result.errors)} could not be read.",
662 )
663 if not result.sent and not pruned:
664 return JobResult.nothing_to_do(parts[0])
665 return JobResult.did(" ".join(parts))
668# ─── Swarm runs ───────────────────────────────────────────────────────────────
671@register_job
672class SwarmWatchdogJob(Job):
673 """Resume swarm runs whose coordinator went away — a restart, a deploy —
674 from their last finished task, and end pauses nobody answered before a
675 run's time ran out (``app/services/swarms/engine.py``)."""
677 key = "swarm_watchdog"
678 label = "Swarm watchdog"
679 description = (
680 "Resume swarm runs a restart left without a coordinator, and end "
681 "plans and questions nobody answered in time."
682 )
683 #: Every minute: a run silent for two is taken to have lost its
684 #: coordinator, so a deploy costs a run about that much time.
685 interval_seconds = 60
687 def run(self, db: Session) -> JobResult:
688 from app.common.settings import get_settings
689 from app.services.swarms import engine
691 if not get_settings().SWARMS_ENABLED:
692 return JobResult.nothing_to_do("Swarms are switched off.")
693 acted = engine.watchdog(db)
694 if not acted:
695 return JobResult.nothing_to_do("No swarm run needed resuming.")
696 return JobResult.did(f"Resumed or ended {acted} swarm run(s).")