:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(growth): send error details and daily charts in the weekly digest (#115763)
Rafael Audiberte9b75e11016a
diff --git a/posthog/temporal/tests/weekly_digest/test_activities.py b/posthog/temporal/tests/weekly_digest/test_activities.pyindex d84812172588..24a31ce34ea2 100644--- a/posthog/temporal/tests/weekly_digest/test_activities.py+++ b/posthog/temporal/tests/weekly_digest/test_activities.py@@ -264,6 +264,14 @@ def _make_error_issues(team: Team, other_team: Team, digest: Digest) -> list[strreturn [f"issue {index}" for index in range(1, NEW_ERROR_ISSUES_PER_TEAM_LIMIT + 1)]+def _error_issue_lookup_from_postgres(input: GenerateDigestDataBatchInput) -> None:+ # A failed error tracking query keeps the issues the Postgres lookup found, which this test checks.+ with patch(+ "posthog.temporal.weekly_digest.activities._query_new_issues_for_team", side_effect=RuntimeError("down")+ ):+ run_sync(generate_error_issue_lookup, input)++@pytest.mark.django_db@pytest.mark.parametrize("activity_fn,key_kind,payload_field,make_rows",@@ -280,7 +288,7 @@ def _make_error_issues(team: Team, other_team: Team, digest: Digest) -> list[str),(generate_feature_flag_lookup, TeamDataKey.FEATURE_FLAGS, "name", _make_feature_flags),(generate_survey_lookup, TeamDataKey.SURVEYS_LAUNCHED, "name", _make_surveys),- (generate_error_issue_lookup, TeamDataKey.ERROR_ISSUES, "name", _make_error_issues),+ (_error_issue_lookup_from_postgres, TeamDataKey.ERROR_ISSUES, "name", _make_error_issues),],)def test_generic_lookup_stores_only_this_teams_rows_from_the_window(@@ -308,12 +316,63 @@ def test_generic_lookup_stores_only_this_teams_rows_from_the_window(assert redis_servers.digest.keys(f"{digest.key}-{key_kind}-*") == [key]+ "error_tracking_result,expected",+ [+ (+ [+ {+ "id": str(uuid4()),+ "name": "Error",+ "description": "busy",+ "occurrence_count": 12,+ "sparkline": [{"height_percent": 100}],+ }+ ],+ [("busy", 12, [{"height_percent": 100}])],+ ),+ (RuntimeError("ClickHouse is down"), [("quiet", None, []), ("busy", None, [])]),+ ([], None),+ ],+)+def test_generate_error_issue_lookup_takes_new_issues_from_error_tracking(+ error_tracking_result, expected, team, redis_servers, common_input, digest+):+ create_issue(+ team_id=team.id, name="TypeError", description="quiet", created_at=digest.period_end - timedelta(hours=1)+ )+ create_issue(team_id=team.id, name="Error", description="busy", created_at=digest.period_start + timedelta(hours=1))+ mock_kwargs = (+ {"side_effect": error_tracking_result}+ if isinstance(error_tracking_result, Exception)+ else {"return_value": error_tracking_result}+ )++ with patch("posthog.temporal.weekly_digest.activities._query_new_issues_for_team", **mock_kwargs):+ run_sync(generate_error_issue_lookup, batch_input(team, digest, common_input))++ stored = redis_servers.digest.get(team_data_key(digest.key, TeamDataKey.ERROR_ISSUES, team.id))+ if expected is None:+ assert stored is None+ else:+ assert [+ (issue["description"], issue["occurrence_count"], issue["sparkline"]) for issue in json.loads(stored)+ ] == expected++def _run_lookup(activity_fn: Callable[..., Any]) -> Callable[[TeamIdRange, Digest, CommonInput], None]:return lambda team_range, digest, common: run_sync(activity_fn, GenerateDigestDataBatchInput(team_id_range=team_range, digest=digest, common=common))+def _run_error_issue_lookup_without_occurrences(team_range: TeamIdRange, digest: Digest, common: CommonInput) -> None:+ # Error tracking runs one HogQL query per team with new issues, like usage trends.+ with patch("posthog.temporal.weekly_digest.activities._query_new_issues_for_team", return_value=[]):+ _run_lookup(generate_error_issue_lookup)(team_range, digest, common)++def _run_organization_digest_batch(team_range: TeamIdRange, digest: Digest, common: CommonInput) -> None:run_sync(generate_organization_digest_batch,@@ -326,7 +385,7 @@ def _run_organization_digest_batch(team_range: TeamIdRange, digest: Digest, comm"run_activity,make_row",[(_run_lookup(generate_dashboard_lookup), lambda team: Dashboard.objects.create(team=team, name="Dashboard")),- (_run_lookup(generate_error_issue_lookup), lambda team: create_issue(team_id=team.id, name="issue")),+ (_run_error_issue_lookup_without_occurrences, lambda team: create_issue(team_id=team.id, name="issue")),(_run_lookup(generate_filter_lookup),lambda team: SessionRecordingPlaylist.objects.create(team=team, name="Filter", type="filters"),@@ -797,6 +856,8 @@ def test_query_team_usage_trends_windows_persons_and_test_accounts(team):# test_account_filters are phrased to KEEP real accounts, so "is_not localhost" drops the test event below.team.test_account_filters = [{"key": "$host", "type": "event", "value": "localhost", "operator": "is_not"}]+ # A project timezone away from UTC would shift calendar-day buckets by one.+ team.timezone = "America/Los_Angeles"team.save()# Test-account traffic in the current window must not inflate the numbers._create_event(@@ -815,6 +876,8 @@ def test_query_team_usage_trends_windows_persons_and_test_accounts(team):events, users = result.metricsassert (events.label, events.current, events.previous) == ("Events", 3, 1)assert (users.label, users.current, users.previous) == ("Active users", 2, 1)+ assert events.daily == [0, 0, 1, 1, 1, 0, 0]+ assert users.daily == [0, 0, 1, 1, 1, 0, 0]@pytest.mark.django_db@@ -856,7 +919,10 @@ def test_generate_usage_trends_lookup_waits_out_a_busy_clickhouse(team, redis_se),patch("posthog.temporal.weekly_digest.activities.execute_hogql_query",- side_effect=[ClickHouseAtCapacity(), HogQLQueryResponse(results=[[5, 4, 2, 2]])],+ side_effect=[+ ClickHouseAtCapacity(),+ HogQLQueryResponse(results=[[5, 4, 2, 2, [5, 0, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0, 0]]]),+ ],),patch("posthog.temporal.common.utils.time.sleep"),):diff --git a/posthog/temporal/tests/weekly_digest/test_types.py b/posthog/temporal/tests/weekly_digest/test_types.pyindex 0582859e86b5..afcab03bdbd3 100644--- a/posthog/temporal/tests/weekly_digest/test_types.py+++ b/posthog/temporal/tests/weekly_digest/test_types.py@@ -189,10 +189,39 @@ def test_team_digest_render_payload():filters=FilterList(root=[filter]),expiring_recordings=RecordingCount(recording_count=7),surveys_launched=SurveyList(root=[]),+ usage_trends=UsageTrends(+ metrics=[UsageTrendMetric(label="Events", current=1_525_962, daily=[0, 1, 400_000, 0, 0, 0, 0])]+ ),+ error_issues=ErrorIssueList(+ root=[+ DigestErrorIssue(+ name="Error",+ id=uuid4(),+ description="Request failed\n at fetch " + "x" * 200,+ occurrence_count=1_525,+ sparkline=[{"height_percent": 100}],+ ),+ DigestErrorIssue(name="TypeError", id=uuid4()),+ ]+ ),)payload = digest.render_payload()+ report = payload["report"]+ assert isinstance(report, dict)+ counted, uncounted = report["new_error_issues"]+ assert counted["description"].startswith("Request failed at fetch xxx")+ assert len(counted["description"]) == 140+ assert (counted["occurrence_count"], counted["occurrence_count_display"]) == (1_525, "1.52K")+ assert counted["sparkline"] == [{"height_percent": 100}]+ assert (uncounted["occurrence_count"], uncounted["sparkline"]) == (None, [])+ usage_trends = report["usage_trends"]+ assert isinstance(usage_trends, dict)+ (events,) = usage_trends["metrics"]+ assert events["current_display"] == "1.53M"+ assert [bar["height_percent"] for bar in events["sparkline"]] == [0, 5, 100, 0, 0, 0, 0]+assert payload["team_name"] == "Test Team"assert payload["team_id"] == 1assert "report" in payloaddiff --git a/posthog/temporal/weekly_digest/README.md b/posthog/temporal/weekly_digest/README.mdindex 3da5be5f5aec..72bec480de98 100644--- a/posthog/temporal/weekly_digest/README.md+++ b/posthog/temporal/weekly_digest/README.md@@ -33,20 +33,21 @@ Generated via `team_data_key(digest_key, TeamDataKey.*, team_id)`.Each Postgres-backed generator reads a team id range with two queries, one for the eligible teams and one for the data, and writes its keys in one Redis pipeline.A team with no data of a kind gets no key for it; organization aggregation substitutes an empty default for a missing key.The two ClickHouse-backed generators work per range too: expiring recordings are counted for the whole range in one grouped query, and usage trends first find the teams with events in the window in one query, then run the per-team HogQL query for those teams only.--| `TeamDataKey` enum | Key Pattern | Contents |-| ----------------------- | ---------------------------------------------- | ---------------------------------- |-| `DASHBOARDS` | `{digest_key}-dashboards-{team_id}` | New dashboards created |-| `EVENT_DEFINITIONS` | `{digest_key}-event-definitions-{team_id}` | New event definitions |-| `EXPERIMENTS_LAUNCHED` | `{digest_key}-experiments-launched-{team_id}` | Experiments started |-| `EXPERIMENTS_COMPLETED` | `{digest_key}-experiments-completed-{team_id}` | Experiments finished |-| `EXTERNAL_DATA_SOURCES` | `{digest_key}-external-data-sources-{team_id}` | New data sources |-| `FEATURE_FLAGS` | `{digest_key}-feature-flags-{team_id}` | New feature flags |-| `SAVED_FILTERS` | `{digest_key}-saved-filters-{team_id}` | Interesting replay filters |-| `EXPIRING_RECORDINGS` | `{digest_key}-expiring-recordings-{team_id}` | Count of soon-to-expire recordings |-| `SURVEYS_LAUNCHED` | `{digest_key}-surveys-launched-{team_id}` | Surveys launched |-| `USAGE_TRENDS` | `{digest_key}-usage-trends-{team_id}` | Event volume + active users, WoW |-| `ERROR_ISSUES` | `{digest_key}-error-issues-{team_id}` | New error-tracking issues |+New error issues come from one range-wide Postgres query, which finds the teams with new issues. For each of those teams, the error tracking digest query then ranks and counts the new issues. A team whose count query fails keeps its Postgres issues without counts.++| `TeamDataKey` enum | Key Pattern | Contents |+| ----------------------- | ---------------------------------------------- | ---------------------------------------------- |+| `DASHBOARDS` | `{digest_key}-dashboards-{team_id}` | New dashboards created |+| `EVENT_DEFINITIONS` | `{digest_key}-event-definitions-{team_id}` | New event definitions |+| `EXPERIMENTS_LAUNCHED` | `{digest_key}-experiments-launched-{team_id}` | Experiments started |+| `EXPERIMENTS_COMPLETED` | `{digest_key}-experiments-completed-{team_id}` | Experiments finished |+| `EXTERNAL_DATA_SOURCES` | `{digest_key}-external-data-sources-{team_id}` | New data sources |+| `FEATURE_FLAGS` | `{digest_key}-feature-flags-{team_id}` | New feature flags |+| `SAVED_FILTERS` | `{digest_key}-saved-filters-{team_id}` | Interesting replay filters |+| `EXPIRING_RECORDINGS` | `{digest_key}-expiring-recordings-{team_id}` | Count of soon-to-expire recordings |+| `SURVEYS_LAUNCHED` | `{digest_key}-surveys-launched-{team_id}` | Surveys launched |+| `USAGE_TRENDS` | `{digest_key}-usage-trends-{team_id}` | Event volume + active users, WoW, daily counts |+| `ERROR_ISSUES` | `{digest_key}-error-issues-{team_id}` | New error-tracking issues, daily occurrences |### Organization-level datadiff --git a/posthog/temporal/weekly_digest/activities.py b/posthog/temporal/weekly_digest/activities.pyindex f4c278c5ba67..7afd4b56e798 100644--- a/posthog/temporal/weekly_digest/activities.py+++ b/posthog/temporal/weekly_digest/activities.py@@ -85,6 +85,7 @@ from posthog.temporal.weekly_digest.types import (UserDigestContext,)+from products.error_tracking.backend.facade.api import get_new_issues_for_teamfrom products.growth.backend.product_push.selection import project_uses_product, resolve_product_path# Every activity below is a sync body behind `@asyncify`, which runs it on the worker's thread pool.@@ -226,46 +227,66 @@ def _limit_per_team(rows: QuerySet, limit: int) -> QuerySet:).filter(team_rank__lte=limit)-def generate_digest_data_lookup(+def _resources_by_team(input: GenerateDigestDataBatchInput,- key_kind: TeamDataKey,+ logger: FilteringBoundLogger,query_func: Callable[[datetime, datetime], QuerySet],resource_type: DigestResourceType,+ eligible_team_ids: set[int],per_team_limit: int | None = None,-) -> None:- logger = _bind_batch_logger(input)- logger.info("Generating digest data batch", key_kind=key_kind)-+) -> dict[int, Any]:rows: QuerySet = query_func(input.digest.period_start, input.digest.period_end)if per_team_limit is not None:rows = _limit_per_team(rows, per_team_limit)- resource_count = 0- eligible_team_ids = _eligible_team_ids(input)- payload_by_team: dict[int, str] = {}- # Teams with nothing new get no key. Aggregation substitutes an empty default for a missing key.+ resources_by_team: dict[int, Any] = {}for team_id, team_rows in _rows_by_team(input, rows, eligible_team_ids).items():try:- digest_data = resource_type.model_validate(team_rows)+ resources_by_team[team_id] = resource_type.model_validate(team_rows)except ValidationError as e:logger.warning(f"Failed to generate digest data for team {team_id}, skipping...", error=str(e), team_id=team_id)- continue- payload_by_team[team_id] = digest_data.model_dump_json()- resource_count += len(digest_data.root)+ return resources_by_team++def _store_resources(+ input: GenerateDigestDataBatchInput,+ logger: FilteringBoundLogger,+ key_kind: TeamDataKey,+ resources_by_team: dict[int, Any],+ eligible_team_ids: set[int],+) -> None:+ # Teams with nothing new get no key. Aggregation substitutes an empty default for a missing key.+ payload_by_team = {team_id: resources.model_dump_json() for team_id, resources in resources_by_team.items()}with _digest_redis(input.common) as r:_store_team_data(r, input, key_kind, payload_by_team, eligible_team_ids)logger.info("Finished generating digest data batch",key_kind=key_kind,- resource_count=resource_count,+ resource_count=sum(len(resources.root) for resources in resources_by_team.values()),team_count=len(payload_by_team),)+def generate_digest_data_lookup(+ input: GenerateDigestDataBatchInput,+ key_kind: TeamDataKey,+ query_func: Callable[[datetime, datetime], QuerySet],+ resource_type: DigestResourceType,+ per_team_limit: int | None = None,+) -> None:+ logger = _bind_batch_logger(input)+ logger.info("Generating digest data batch", key_kind=key_kind)++ eligible_team_ids = _eligible_team_ids(input)+ resources_by_team = _resources_by_team(+ input, logger, query_func, resource_type, eligible_team_ids, per_team_limit=per_team_limit+ )+ _store_resources(input, logger, key_kind, resources_by_team, eligible_team_ids)++@activity.defn(name="generate-dashboard-lookup")@asyncifydef generate_dashboard_lookup(input: GenerateDigestDataBatchInput) -> None:@@ -468,19 +489,50 @@ def generate_recording_lookup(input: GenerateDigestDataBatchInput) -> None:NEW_ERROR_ISSUES_PER_TEAM_LIMIT = 5+_query_new_issues_for_team = _retry_while_clickhouse_busy(get_new_issues_for_team)+++def _generate_error_issue_lookup(input: GenerateDigestDataBatchInput) -> None:+ logger = _bind_batch_logger(input)+ logger.info("Generating digest data batch", key_kind=TeamDataKey.ERROR_ISSUES)++ eligible_team_ids = _eligible_team_ids(input)+ issues_by_team: dict[int, ErrorIssueList] = _resources_by_team(+ input,+ logger,+ query_new_error_issues,+ ErrorIssueList,+ eligible_team_ids,+ per_team_limit=NEW_ERROR_ISSUES_PER_TEAM_LIMIT,+ )++ # The Postgres lookup only finds the teams worth a ClickHouse query. Their issues then come from+ # the error tracking digest, so both emails rank and count new issues the same way. A team whose+ # query fails keeps the Postgres issues without counts, which the email renders without a chart.+ # execute_hogql_query reads several team columns, so load the teams in full.+ for team in Team.objects.filter(id__in=issues_by_team.keys()).order_by("id"):+ try:+ counted_issues = ErrorIssueList.model_validate(_query_new_issues_for_team(team))+ except Exception as e:+ logger.warning(+ f"Failed to count error issue occurrences for team {team.id}, skipping counts...",+ error=str(e),+ team_id=team.id,+ )+ continue+ if counted_issues.root:+ issues_by_team[team.id] = counted_issues+ else:+ del issues_by_team[team.id]++ _store_resources(input, logger, TeamDataKey.ERROR_ISSUES, issues_by_team, eligible_team_ids)++@activity.defn(name="generate-error-issue-lookup")@asyncifydef generate_error_issue_lookup(input: GenerateDigestDataBatchInput) -> None:- # New error-tracking issues follow the standard "created within window" lookup,- # exactly like dashboards / feature flags.with HeartbeaterSync(logger=LOGGER):- generate_digest_data_lookup(- input,- key_kind=TeamDataKey.ERROR_ISSUES,- query_func=query_new_error_issues,- resource_type=ErrorIssueList,- per_team_limit=NEW_ERROR_ISSUES_PER_TEAM_LIMIT,- )+ _generate_error_issue_lookup(input)# Weekly usage snapshot per team. Written in HogQL so it inherits the team's test-account@@ -489,22 +541,35 @@ def generate_error_issue_lookup(input: GenerateDigestDataBatchInput) -> None:# which is the conditional form of the `count(DISTINCT person_id)` those insights print. Counting# distinct_ids would overcount (one person, many devices). Two windows are compared in one pass;# the query runs on the offline cluster since it scans two weeks of events for every active team.+# Day slots count seconds from cur_start, because HogQL converts timestamps to the project timezone.USAGE_TRENDS_QUERY = """SELECTcountIf(timestamp >= {cur_start} AND timestamp < {cur_end}) AS events_current,countIf(timestamp >= {prev_start} AND timestamp < {cur_start}) AS events_previous,uniqExactIf(person_id, timestamp >= {cur_start} AND timestamp < {cur_end}) AS users_current,- uniqExactIf(person_id, timestamp >= {prev_start} AND timestamp < {cur_start}) AS users_previous-FROM events-WHERE timestamp >= {prev_start} AND timestamp < {cur_end} AND {filters}+ uniqExactIf(person_id, timestamp >= {prev_start} AND timestamp < {cur_start}) AS users_previous,+ sumForEachIf(+ arrayMap(slot -> if(slot = day_index, 1, 0), range({day_count})),+ timestamp >= {cur_start} AND timestamp < {cur_end}+ ) AS events_daily,+ countDistinctForEachIf(+ arrayMap(slot -> if(slot = day_index, person_id, NULL), range({day_count})),+ timestamp >= {cur_start} AND timestamp < {cur_end}+ ) AS users_daily+FROM (+ SELECT timestamp, person_id, intDiv(dateDiff('second', {cur_start}, timestamp), 86400) AS day_index+ FROM events+ WHERE timestamp >= {prev_start} AND timestamp < {cur_end} AND {filters}+)"""-def _usage_trend_metric(label: str, current: int, previous: int) -> UsageTrendMetric:+def _usage_trend_metric(label: str, current: int, previous: int, daily: list[int] | None = None) -> UsageTrendMetric:has_baseline = previous > 0+ daily = daily or []change = compute_week_over_week_change(current, previous if has_baseline else None, higher_is_better=True)if change is None:- return UsageTrendMetric(label=label, current=current, previous=previous, has_baseline=has_baseline)+ return UsageTrendMetric(label=label, current=current, previous=previous, has_baseline=has_baseline, daily=daily)return UsageTrendMetric(label=label,current=current,@@ -512,6 +577,7 @@ def _usage_trend_metric(label: str, current: int, previous: int) -> UsageTrendMechange_pct=change["percent"],direction="up" if change["direction"] == "Up" else "down",has_baseline=True,+ daily=daily,)@@ -553,6 +619,7 @@ def _query_team_usage_trends(team: Team, period_start: datetime, period_end: dat"cur_start": ast.Constant(value=period_start),"cur_end": ast.Constant(value=period_end),"prev_start": ast.Constant(value=period_start - window),+ "day_count": ast.Constant(value=max(window.days, 1)),},filters=HogQLFilters(filterTestAccounts=True),workload=Workload.OFFLINE,@@ -561,7 +628,7 @@ def _query_team_usage_trends(team: Team, period_start: datetime, period_end: datif not response.results or not response.results[0]:return None- events_current, events_previous, users_current, users_previous = response.results[0]+ events_current, events_previous, users_current, users_previous, events_daily, users_daily = response.results[0]events_current = int(events_current or 0)users_current = int(users_current or 0)@@ -571,8 +638,12 @@ def _query_team_usage_trends(team: Team, period_start: datetime, period_end: datreturn UsageTrends(metrics=[- _usage_trend_metric("Events", events_current, int(events_previous or 0)),- _usage_trend_metric("Active users", users_current, int(users_previous or 0)),+ _usage_trend_metric(+ "Events", events_current, int(events_previous or 0), [int(count) for count in events_daily or []]+ ),+ _usage_trend_metric(+ "Active users", users_current, int(users_previous or 0), [int(count) for count in users_daily or []]+ ),])diff --git a/posthog/temporal/weekly_digest/types.py b/posthog/temporal/weekly_digest/types.pyindex 3cf3395b42a1..f9d36f31c350 100644--- a/posthog/temporal/weekly_digest/types.py+++ b/posthog/temporal/weekly_digest/types.py@@ -4,7 +4,7 @@ from uuid import UUIDfrom pydantic import BaseModel, RootModel, field_validator-from posthog.utils import get_instance_region+from posthog.utils import compact_number, get_instance_regionclass CommonInput(BaseModel):@@ -126,15 +126,58 @@ class DigestSurvey(BaseModel):start_date: datetime+# Keeps a day with any activity visible as a sliver next to a much busier day.+SPARKLINE_MIN_VISIBLE_PERCENT = 5++# Issue descriptions are exception messages of any length. The email shows one line of it.+ERROR_ISSUE_DESCRIPTION_MAX_LENGTH = 140+++def render_sparkline(daily_counts: list[int]) -> list[dict[str, int]]:+ peak = max(daily_counts, default=0)+ bars = []+ for count in daily_counts:+ height_percent = round(count * 100 / peak) if peak else 0+ if count > 0:+ height_percent = max(height_percent, SPARKLINE_MIN_VISIBLE_PERCENT)+ bars.append({"count": count, "height_percent": height_percent})+ return bars+++def _single_line(text: str | None, max_length: int) -> str | None:+ if not text:+ return None+ collapsed = " ".join(text.split())+ if len(collapsed) <= max_length:+ return collapsed+ return collapsed[: max_length - 1].rstrip() + "…"++class DigestErrorIssue(BaseModel):name: str = "Untitled issue"id: UUID+ description: str | None = None+ # None when the counts could not be queried.+ occurrence_count: int | None = None+ sparkline: list[dict[str, int]] = []@field_validator("name", mode="before")@classmethoddef _default_name(cls, value: str | None) -> str:return value or "Untitled issue"+ def render_payload(self) -> dict[str, str | int | list | None]:+ return {+ "id": str(self.id),+ "name": self.name,+ "description": _single_line(self.description, ERROR_ISSUE_DESCRIPTION_MAX_LENGTH),+ "occurrence_count": self.occurrence_count,+ "occurrence_count_display": (+ compact_number(self.occurrence_count) if self.occurrence_count is not None else None+ ),+ "sparkline": self.sparkline,+ }+class UsageTrendMetric(BaseModel):label: str # e.g. "Events", "Active users"@@ -145,11 +188,23 @@ class UsageTrendMetric(BaseModel):# False when there was no previous-week activity to compare against, so the template# can render "new" instead of conflating 0 -> N growth with "no change".has_baseline: bool = True+ daily: list[int] = []++ def render_payload(self) -> dict[str, str | int | bool | list | None]:+ return {+ **self.model_dump(exclude={"daily"}),+ # The email template (Liquid) has no number formatting filter.+ "current_display": compact_number(self.current),+ "sparkline": render_sparkline(self.daily),+ }class UsageTrends(BaseModel):metrics: list[UsageTrendMetric] = []+ def render_payload(self) -> dict[str, list]:+ return {"metrics": [metric.render_payload() for metric in self.metrics]}+class DashboardList(RootModel):root: list[DigestDashboard]@@ -189,6 +244,9 @@ class SurveyList(RootModel):class ErrorIssueList(RootModel):root: list[DigestErrorIssue]+ def render_payload(self) -> list[dict]:+ return [issue.render_payload() for issue in self.root]+# Shown when the campaign carries no hand-written promo copy. Mirrors the nav card's# DEFAULT_PRODUCT_PUSH_DISPLAY tagline so both surfaces say the same thing.@@ -272,8 +330,8 @@ class TeamDigest(BaseModel):"interesting_saved_filters": [f.render_payload() for f in self.filters.root],"expiring_recordings": self.expiring_recordings.model_dump(),"new_surveys_launched": self.surveys_launched.model_dump(),- "usage_trends": self.usage_trends.model_dump(),- "new_error_issues": self.error_issues.model_dump(),+ "usage_trends": self.usage_trends.render_payload(),+ "new_error_issues": self.error_issues.render_payload(),}if product_suggestion:diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.pyindex 112bab607272..d3d04e3b465b 100644--- a/products/error_tracking/backend/facade/api.py+++ b/products/error_tracking/backend/facade/api.py@@ -154,7 +154,7 @@ def query_new_error_issues(period_start: datetime, period_end: datetime) -> Querstatus=ErrorTrackingIssue.Status.ACTIVE,).order_by("-created_at")- .values("team_id", "name", "id")+ .values("team_id", "name", "description", "id"))diff --git a/products/error_tracking/backend/facade/testing.py b/products/error_tracking/backend/facade/testing.pyindex beb16331612e..504cf50f1026 100644--- a/products/error_tracking/backend/facade/testing.py+++ b/products/error_tracking/backend/facade/testing.py@@ -33,8 +33,11 @@ def create_issue(status: ErrorTrackingIssueStatus = ErrorTrackingIssueStatus.ACTIVE,severity: str | None = None,created_at: datetime | None = None,+ description: str | None = None,) -> UUID:- issue = ErrorTrackingIssue.objects.create(team_id=team_id, name=name, status=status, severity=severity)+ issue = ErrorTrackingIssue.objects.create(+ team_id=team_id, name=name, status=status, severity=severity, description=description+ )if created_at is not None:# created_at is auto_now_add, so it can only be set after the insert.ErrorTrackingIssue.objects.filter(id=issue.id).update(created_at=created_at)