Coverage for app / services / dashboards / refresh.py: 89%
141 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"""Staleness rules and cache writes for dynamic widgets.
3Two things call in here, and the rules below serve both.
5``app.services.scheduler``'s ``dashboard_refresh`` job runs on a timer and is
6now the primary path: a board's daily digest is current when somebody arrives
7at it, rather than daily only for somebody who *looks* daily.
9Refresh **on view** remains, deliberately. It is what makes a newly added tile
10fill in immediately instead of waiting for a tick, and it is the whole
11mechanism wherever the scheduler is off (``SCHEDULER_ENABLED=false``) or this
12replica is not the elected leader. Loading a board queues a background
13regeneration for every dynamic widget whose cache has aged past its interval,
14and the response returns the cached (stale) value immediately alongside a
15``refreshing`` flag the client polls on.
17The two cannot double-refresh. :func:`mark_refreshing` claims a widget by
18committing its status *before* generation starts, and :func:`is_stale` will
19not pick up a claimed widget until ``STUCK_REFRESH_TIMEOUT`` has passed — so
20whichever path gets there first, the other steps over it.
21"""
23from __future__ import annotations
25import logging
26from datetime import UTC, datetime, timedelta
27from typing import Iterable
28from uuid import UUID
30from sqlalchemy.orm import Session
32from app.db.postgres.engine import SessionLocal
33from app.db.postgres.enums import BackgroundEnum, DashboardEnum
34from app.db.postgres.models import Dashboard, DashboardWidget
35from app.services import ai_client, background_activity
36from app.util.time import aware_utcnow
38from .widgets import (
39 WidgetConfigError,
40 WidgetGenerationError,
41 dynamic_types,
42 get_renderer,
43)
45logger = logging.getLogger(__name__)
47RefreshStatus = DashboardEnum.RefreshStatus
49#: How long a widget may sit in ``refreshing`` before another request is
50#: allowed to retry it. Guards against a crashed worker wedging a tile.
51STUCK_REFRESH_TIMEOUT = timedelta(minutes=15)
54def _aware(value):
55 """Treat naive timestamps from Postgres as UTC."""
56 if value is None:
57 return None
58 return value if value.tzinfo else value.replace(tzinfo=aware_utcnow().tzinfo)
61def is_stale(widget: DashboardWidget) -> bool:
62 """Whether ``widget`` should be regenerated now."""
63 renderer = get_renderer(widget.widget_type)
64 if not renderer.is_dynamic:
65 return False
67 now = aware_utcnow()
68 cached_at = _aware(widget.cached_at)
70 if widget.cache_status == RefreshStatus.refreshing:
71 # Only retry a refresh that has plainly been abandoned.
72 return cached_at is not None and now - cached_at > STUCK_REFRESH_TIMEOUT
74 if widget.cache_status in (RefreshStatus.empty, RefreshStatus.failed):
75 return True
77 interval = widget.refresh_interval_seconds
78 if not interval:
79 return False
80 if cached_at is None:
81 return True
82 return now - cached_at >= timedelta(seconds=interval)
85def stale_widgets(widgets: Iterable[DashboardWidget]) -> list[DashboardWidget]:
86 return [w for w in widgets if is_stale(w)]
89#: How long a tile that failed waits before the scheduler tries it again,
90#: unless its own interval is shorter. A failure used to be due on every
91#: tick, and one that failed after its model had run was a paid call a
92#: minute. A person's view or Refresh still retries it at once.
93FAILED_RETRY_AFTER = timedelta(hours=1)
95#: Earlier than any real time: when a tile that has never been filled is due.
96_NEVER_FILLED = datetime(1970, 1, 1, tzinfo=UTC)
99def scheduled_due_at(widget: DashboardWidget) -> datetime | None:
100 """When the scheduler should next refresh ``widget``, or None for never.
102 A tile never filled is due at once; one being refreshed only once its
103 claim has plainly been abandoned; one that failed after a backoff; one
104 that is ready once its interval has passed. A tile with no interval
105 refreshes when a person asks, so the scheduler only ever fills it.
106 """
107 try:
108 if not get_renderer(widget.widget_type).is_dynamic:
109 return None
110 except WidgetConfigError:
111 return None
112 cached_at = _aware(widget.cached_at)
113 status = widget.cache_status
114 interval = widget.refresh_interval_seconds
115 if status == RefreshStatus.refreshing:
116 return cached_at + STUCK_REFRESH_TIMEOUT if cached_at else _NEVER_FILLED
117 if status == RefreshStatus.empty or cached_at is None:
118 return _NEVER_FILLED
119 if not interval:
120 return None
121 if status == RefreshStatus.failed:
122 return cached_at + min(timedelta(seconds=interval), FAILED_RETRY_AFTER)
123 return cached_at + timedelta(seconds=interval)
126def due_widgets(db: Session, *, limit: int, now=None) -> list[DashboardWidget]:
127 """The dynamic tiles due a scheduled refresh, most overdue first, at
128 most ``limit``.
130 Only dynamic types are read, and only the columns that say when a tile
131 is due. The scheduler used to take the 100 widgets of *any* type with
132 the oldest cache and filter those: static tiles never set one, so once a
133 deployment had 100 of them every window was static and nothing was
134 ever refreshed on schedule again.
135 """
136 now = now or aware_utcnow()
137 rows = (
138 db.query(
139 DashboardWidget.id,
140 DashboardWidget.widget_type,
141 DashboardWidget.cache_status,
142 DashboardWidget.cached_at,
143 DashboardWidget.refresh_interval_seconds,
144 )
145 .filter(DashboardWidget.widget_type.in_(dynamic_types()))
146 .all()
147 )
148 due = sorted(
149 (
150 (when, row.id)
151 for row in rows
152 if (when := scheduled_due_at(row)) is not None and when <= now
153 ),
154 key=lambda pair: pair[0],
155 )[:limit]
156 if not due:
157 return []
158 ids = [widget_id for _, widget_id in due]
159 loaded = {
160 widget.id: widget
161 for widget in db.query(DashboardWidget)
162 .filter(DashboardWidget.id.in_(ids))
163 .all()
164 }
165 return [loaded[widget_id] for widget_id in ids if widget_id in loaded]
168def mark_refreshing(db: Session, widget: DashboardWidget) -> None:
169 """Claim a widget before its background refresh starts.
171 Committed by the request thread so a concurrent board load sees the claim
172 and does not queue the same generation twice.
173 """
174 widget.cache_status = RefreshStatus.refreshing
175 widget.cached_at = aware_utcnow()
176 db.add(widget)
177 db.commit()
180Trigger = BackgroundEnum.Trigger
183def refresh_widget(
184 db: Session, widget_id: UUID, trigger: Trigger = Trigger.view
185) -> None:
186 """Regenerate one widget's cached payload.
188 Runs on a background task, so it never raises into a request: a failed
189 generation is recorded on the row as ``failed`` with its error, which the
190 tile surfaces alongside whatever it last managed to produce.
192 ``trigger`` says why, for the owner's activity feed — every refresh,
193 success or failure, writes one background event with it.
194 """
195 widget = db.get(DashboardWidget, widget_id)
196 if widget is None:
197 logger.warning("Refresh requested for missing widget %s", widget_id)
198 return
200 started = aware_utcnow()
201 # The board's workspace, for svc-ai's trace rows — whoever's view or
202 # schedule set the refresh off. A built-in board has none: its tiles are
203 # the platform's, traced to nobody.
204 from app.services import workspace as workspace_service
206 board_id = getattr(widget, "dashboard_id", None)
207 board = db.get(Dashboard, board_id) if board_id else None
208 home = workspace_service.home_of(db, board) if board is not None else None
209 # Captured around the whole generation, so the event says what the
210 # refresh cost — including a call that was made and then failed to parse.
211 # For a built-in board this is the only record: the usage ledger is keyed
212 # by user, and the platform pays for a tile nobody owns.
213 with (
214 ai_client.in_workspace(home.key if home is not None else None),
215 ai_client.usage_capture() as used,
216 ):
217 try:
218 renderer = get_renderer(widget.widget_type)
219 payload = renderer.generate(db, widget)
220 error = None
221 except WidgetGenerationError as exc:
222 error = str(exc)
223 except Exception: # noqa: BLE001 - background task must not escape
224 # Logged, never shown: the tile and its event carry what a person
225 # may read.
226 logger.exception("Widget %s refresh failed unexpectedly", widget_id)
227 error = "This tile could not be refreshed. Try again shortly."
228 usage = usage_summary(used)
229 if error is not None:
230 _record_failure(db, widget, error, trigger, started, usage=usage)
231 return
233 widget.cache_payload = payload
234 widget.cache_status = RefreshStatus.ready
235 widget.cache_error = None
236 widget.cached_at = aware_utcnow()
237 _record_event(db, widget, trigger, started, error=None, usage=usage)
238 try:
239 db.add(widget)
240 db.commit()
241 except Exception:
242 db.rollback()
243 logger.exception("Failed to store refreshed widget %s", widget_id)
246def usage_summary(used: ai_client.UsageCapture) -> dict | None:
247 """What a refresh's model calls cost, for its background event — or None
248 when it made none (a feed tile)."""
249 return used.report()
252def _widget_label(widget: DashboardWidget) -> str:
253 if getattr(widget, "title", None):
254 return widget.title
255 try:
256 return get_renderer(widget.widget_type).label
257 except Exception: # noqa: BLE001 - an unregistered type still gets a label
258 return str(widget.widget_type)
261def _record_event(
262 db: Session,
263 widget: DashboardWidget,
264 trigger: Trigger,
265 started,
266 *,
267 error: str | None,
268 usage: dict | None = None,
269) -> None:
270 """One background event for this refresh, against the widget's board.
272 Guarded end to end: the record of a refresh must never be what fails it.
273 """
274 try:
275 dashboard_id = getattr(widget, "dashboard_id", None)
276 dashboard = db.get(Dashboard, dashboard_id) if dashboard_id else None
277 label = _widget_label(widget)
278 widget_type = getattr(widget.widget_type, "value", widget.widget_type)
279 background_activity.record(
280 db,
281 kind=BackgroundEnum.Kind.widget_refresh,
282 trigger=trigger,
283 status=(
284 BackgroundEnum.Status.failed if error else BackgroundEnum.Status.ok
285 ),
286 summary=(
287 f"“{label}” failed to refresh" if error else f"Refreshed “{label}”"
288 ),
289 owner=dashboard,
290 subject_type="dashboard",
291 subject_id=dashboard_id,
292 subject_name=getattr(dashboard, "name", None),
293 detail={
294 "widget_type": str(widget_type),
295 "widget_title": label,
296 **({"usage": usage} if usage else {}),
297 },
298 reference={"widget_id": getattr(widget, "id", None)},
299 error=error,
300 started_at=started,
301 )
302 except Exception: # noqa: BLE001 - see docstring
303 logger.exception("Could not record refresh of widget %s", widget)
306def _record_failure(
307 db: Session,
308 widget: DashboardWidget,
309 error: str,
310 trigger: Trigger = Trigger.view,
311 started=None,
312 *,
313 usage: dict | None = None,
314) -> None:
315 widget.cache_status = RefreshStatus.failed
316 widget.cache_error = error[:1000]
317 widget.cached_at = aware_utcnow()
318 _record_event(db, widget, trigger, started, error=error, usage=usage)
319 try:
320 db.add(widget)
321 db.commit()
322 except Exception:
323 db.rollback()
324 logger.exception("Failed to record widget %s failure", widget.id)
327def refresh_widget_task(widget_id: UUID, trigger: Trigger = Trigger.view) -> None:
328 """Background-task entry point — owns its own session.
330 The request's session is closed once the response is sent, so a queued
331 refresh cannot borrow it.
332 """
333 db = SessionLocal()
334 try:
335 refresh_widget(db, widget_id, trigger)
336 finally:
337 db.close()