Coverage for app / services / background_activity.py: 91%
77 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"""Background activity — what the platform did for an owner outside a request.
3The scheduler's own record (``scheduled_jobs``) is one row per job, read by
4an operator: "dashboard_refresh refreshed 12 widgets". A user arriving at the
5Activity page asks a different question — what happened to *my* things while
6I was away — and needs one row per subject: this board's digest regenerated,
7that website re-crawled with two pages changed. :func:`record` writes those.
9Three callers, one per :class:`BackgroundEnum.Kind`:
11* ``dashboards.refresh`` after every tile regeneration, whatever triggered it
12 (the scheduler, a board load, "Refresh now", a new or edited tile);
13* ``knowledge.web_crawl`` when a crawl finishes, whatever started it;
14* the ``review_retention`` job, once per owner whose flags it deleted.
16The table is bounded by :func:`purge_expired`, run hourly by the
17``background_retention`` job: a tile refreshing every minute writes 1,440
18rows a day, and a routine refresh is worth keeping for weeks, not forever.
19The read path applies the same window, so a row past it is never served
20even where the scheduler is off.
22The LLM call a generated tile makes is on the invocation trace separately,
23under ``dashboard_widget``; this row is the refresh, and covers feed tiles
24that make no LLM call at all.
25"""
27from __future__ import annotations
29import logging
30from datetime import datetime, timedelta
31from typing import Any, Optional
32from uuid import UUID
34from sqlalchemy.orm import Session
36from app.common.settings import get_settings
38from app.db.postgres.enums import BackgroundEnum
39from app.db.postgres.models import BackgroundEvent
40from app.util.time import aware_utcnow
42logger = logging.getLogger(__name__)
44Kind = BackgroundEnum.Kind
45Trigger = BackgroundEnum.Trigger
46Status = BackgroundEnum.Status
49def _aware(value: Optional[datetime]) -> Optional[datetime]:
50 if value is None:
51 return None
52 return value if value.tzinfo else value.replace(tzinfo=aware_utcnow().tzinfo)
55def _uuid(value: Any) -> Optional[UUID]:
56 if value is None or isinstance(value, UUID):
57 return value
58 try:
59 return UUID(str(value))
60 except ValueError:
61 return None
64def record(
65 db: Session,
66 *,
67 kind: Kind,
68 trigger: Trigger | str,
69 status: Status,
70 summary: str,
71 owner: Any = None,
72 subject_type: Optional[str] = None,
73 subject_id: Any = None,
74 subject_name: Optional[str] = None,
75 detail: Optional[dict] = None,
76 reference: Optional[dict] = None,
77 error: Optional[str] = None,
78 started_at: Optional[datetime] = None,
79) -> Optional[BackgroundEvent]:
80 """Add one event to the session. Does not commit; never raises.
82 ``owner`` is any row carrying the three ``owner_*`` columns — the board
83 or source the work was done to. The caller commits with the change the
84 event describes, so the log cannot record a refresh that was rolled back.
86 Never raises for the reason the usage ledger does not: the record of a
87 refresh is worth less than the refresh.
88 """
89 try:
90 finished = aware_utcnow()
91 started = _aware(started_at)
92 duration = int((finished - started).total_seconds() * 1000) if started else None
93 event = BackgroundEvent(
94 owner_user_id=_uuid(getattr(owner, "owner_user_id", None)),
95 owner_project_id=_uuid(getattr(owner, "owner_project_id", None)),
96 owner_organisation_id=_uuid(getattr(owner, "owner_organisation_id", None)),
97 kind=Kind(kind).value,
98 trigger=str(getattr(trigger, "value", trigger)),
99 status=Status(status).value,
100 subject_type=subject_type,
101 subject_id=_uuid(subject_id),
102 subject_name=(subject_name or None) and subject_name[:255],
103 summary=summary[:500],
104 detail=detail or None,
105 reference={k: str(v) for k, v in (reference or {}).items() if v} or None,
106 error=error[:1000] if error else None,
107 started_at=started,
108 finished_at=finished,
109 duration_ms=max(duration, 0) if duration is not None else None,
110 )
111 db.add(event)
112 return event
113 except Exception: # noqa: BLE001 - see docstring
114 logger.exception("Could not record background event %s", kind)
115 return None
118#: Rows deleted per statement, so one purge never holds a long lock over a
119#: table the dashboard refresh is writing to every minute.
120PURGE_CHUNK = 5_000
121#: Ceiling on one run's deletes. A backlog (retention newly shortened, or the
122#: scheduler off for a while) drains over several hourly runs instead of one
123#: long one occupying a worker thread.
124MAX_PURGE_PER_RUN = 100_000
127def retention_days() -> Optional[int]:
128 """How many days a row is kept, or None when retention is off."""
129 days = get_settings().BACKGROUND_EVENT_RETENTION_DAYS
130 return days if days and days > 0 else None
133def retention_cutoff(now: Optional[datetime] = None) -> Optional[datetime]:
134 """The oldest ``finished_at`` still kept, or None when nothing expires."""
135 days = retention_days()
136 if days is None:
137 return None
138 return (now or aware_utcnow()) - timedelta(days=days)
141def purge_expired(
142 db: Session,
143 *,
144 now: Optional[datetime] = None,
145 chunk: int = PURGE_CHUNK,
146 limit: int = MAX_PURGE_PER_RUN,
147) -> int:
148 """Delete events older than the retention window, across every owner.
150 Returns how many went. Commits after each chunk: the rows are independent
151 and a partial purge is simply one that the next run finishes, so there is
152 nothing to gain from one long transaction and a lock to lose by it.
153 """
154 cutoff = retention_cutoff(now)
155 if cutoff is None:
156 return 0
157 purged = 0
158 while purged < limit:
159 ids = [
160 row[0]
161 for row in db.query(BackgroundEvent.id)
162 .filter(BackgroundEvent.finished_at < cutoff)
163 .limit(min(chunk, limit - purged))
164 .all()
165 ]
166 if not ids:
167 break
168 db.query(BackgroundEvent).filter(BackgroundEvent.id.in_(ids)).delete(
169 synchronize_session=False
170 )
171 db.commit()
172 purged += len(ids)
173 if len(ids) < chunk:
174 break
175 return purged
178def list_for_owner(
179 db: Session,
180 owner_user_id: Optional[UUID],
181 *,
182 workspace: Any = None,
183 kinds: Optional[list[Kind]] = None,
184 since: Optional[datetime] = None,
185 limit: int = 100,
186 offset: int = 0,
187) -> tuple[list[BackgroundEvent], int]:
188 """Events for one workspace, newest first, and the total before paging.
190 ``workspace`` (``app/services/workspace.py``) keeps the events of what
191 it owns — a personal board's refresh in Personal, an organisation's in
192 the organisation — and never another's. Without one, ``owner_user_id``
193 reads one person's, and None every owner's (the superuser view).
194 """
195 query = db.query(BackgroundEvent)
196 if workspace is not None:
197 query = query.filter(workspace.filed_under(BackgroundEvent))
198 elif owner_user_id is not None:
199 query = query.filter(BackgroundEvent.owner_user_id == owner_user_id)
200 if kinds:
201 query = query.filter(BackgroundEvent.kind.in_([Kind(k).value for k in kinds]))
202 if since is not None:
203 query = query.filter(BackgroundEvent.finished_at >= since)
204 # The retention window applies on read too, so a row the job has not got
205 # to yet is not served — the feed and the policy say the same thing.
206 cutoff = retention_cutoff()
207 if cutoff is not None:
208 query = query.filter(BackgroundEvent.finished_at >= cutoff)
209 total = query.count()
210 rows = (
211 query.order_by(BackgroundEvent.finished_at.desc())
212 .offset(offset)
213 .limit(limit)
214 .all()
215 )
216 return rows, total