: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
chore(devex): replace fixed-key dict payloads with frozen dataclasses (#83535)
Arno Hillen206b5db2d418
diff --git a/posthog/management/commands/migrate_ses_tenants.py b/posthog/management/commands/migrate_ses_tenants.pyindex 5939ed945be1..44339eb27bf1 100644--- a/posthog/management/commands/migrate_ses_tenants.py+++ b/posthog/management/commands/migrate_ses_tenants.py@@ -1,5 +1,6 @@import loggingfrom collections.abc import Iterable+from dataclasses import dataclassfrom django.conf import settingsfrom django.core.management.base import BaseCommand, CommandError@@ -14,6 +15,15 @@ from posthog.models.integration import Integrationlogger = logging.getLogger(__name__)+# Mutable on purpose: the counters are incremented in place throughout the migration loop+@dataclass(frozen=False)+class SesTenantMigrationCounts:+ tenants: int = 0+ associations_ok: int = 0+ tenant_failures: int = 0+ association_failures: int = 0++def _batched(iterable: Iterable, size: int) -> Iterable[list]:batch: list = []for item in iterable:@@ -25,15 +35,14 @@ def _batched(iterable: Iterable, size: int) -> Iterable[list]:yield batch-def migrate_ses_tenants(team_ids: list[int], domains: list[str], dry_run: bool = False) -> dict[str, int]:+def migrate_ses_tenants(team_ids: list[int], domains: list[str], dry_run: bool = False) -> SesTenantMigrationCounts:"""Ensure existing SES email identities have SES Tenants and Tenant Resource Associations(the identity plus every configuration set sends reference).- Idempotent. Returns counts so callers can tell a complete pass from a partial one:- {"tenants": ..., "associations_ok": ..., "tenant_failures": ..., "association_failures": ...}.+ Idempotent. Returns counts so callers can tell a complete pass from a partial one."""- counts = {"tenants": 0, "associations_ok": 0, "tenant_failures": 0, "association_failures": 0}+ counts = SesTenantMigrationCounts()if team_ids and domains:print("Please provide either team_ids or domains, not both") # noqa: T201return counts@@ -87,7 +96,7 @@ def migrate_ses_tenants(team_ids: list[int], domains: list[str], dry_run: bool =except (ClientError, BotoCoreError) as e:logger.exception("Failed to get AWS account id for SES tenant association: %s", e)print("Error determining AWS account ID. Aborting.") # noqa: T201- counts["tenant_failures"] = len(pairs)+ counts.tenant_failures = len(pairs)return countsfor batch in _batched(pairs, 50):@@ -114,9 +123,9 @@ def migrate_ses_tenants(team_ids: list[int], domains: list[str], dry_run: bool =except (ClientError, BotoCoreError) as e:logger.exception("Error creating SES tenant '%s': %s", tenant_name, e)print(f"Error creating tenant '{tenant_name}': {e}") # noqa: T201- counts["tenant_failures"] += 1+ counts.tenant_failures += 1continue- counts["tenants"] += 1+ counts.tenants += 1# Associate the identity plus the configuration sets sends reference — an attributed# send fails unless EVERY resource it uses is associated with the tenant.@@ -140,7 +149,7 @@ def migrate_ses_tenants(team_ids: list[int], domains: list[str], dry_run: bool =print(f"Association already exists for '{resource_arn}' and tenant '{tenant_name}'") # noqa: T201else:raise- counts["associations_ok"] += 1+ counts.associations_ok += 1except (ClientError, BotoCoreError) as e:logger.exception("Error creating SES tenant_resource_association for '%s' on '%s': %s",@@ -149,7 +158,7 @@ def migrate_ses_tenants(team_ids: list[int], domains: list[str], dry_run: bool =e,)print(f"Error creating tenant_resource_association for '{resource_arn}' on '{tenant_name}': {e}") # noqa: T201- counts["association_failures"] += 1+ counts.association_failures += 1continuereturn counts@@ -186,12 +195,12 @@ class Command(BaseCommand):counts = migrate_ses_tenants(team_ids=team_ids, domains=domains, dry_run=dry_run)self.stdout.write(- f"Summary: {counts['tenants']} tenants processed, "- f"{counts['associations_ok']} associations ensured, "- f"{counts['tenant_failures']} tenant failures, "- f"{counts['association_failures']} association failures"+ f"Summary: {counts.tenants} tenants processed, "+ f"{counts.associations_ok} associations ensured, "+ f"{counts.tenant_failures} tenant failures, "+ f"{counts.association_failures} association failures")- failures = counts["tenant_failures"] + counts["association_failures"]+ failures = counts.tenant_failures + counts.association_failuresif failures:# Non-zero exit: an incomplete pass must not read as a successful rollout step —# tenants missing an association fail attributed sends. Rerun for the logged tenants.diff --git a/posthog/management/commands/resave_cohorts.py b/posthog/management/commands/resave_cohorts.pyindex bbcfa7cd9cfc..654a002e63c0 100644--- a/posthog/management/commands/resave_cohorts.py+++ b/posthog/management/commands/resave_cohorts.py@@ -7,6 +7,7 @@ from django.core.management.base import BaseCommand, CommandParserimport structlogfrom posthog.api.cohort import validate_filters_and_compute_realtime_support+from posthog.dataclasses import frozenfrom posthog.models.team.team import Teamfrom products.cohorts.backend.models.cohort import Cohort@@ -15,6 +16,15 @@ from products.cohorts.backend.models.util import get_all_cohort_dependencies, sologger = structlog.get_logger(__name__)+@frozen+class CohortResaveStats:+ total: int+ changed: int+ errors: int+ validation_errors: int+ prospective_realtime: int++class Command(BaseCommand):help = "Regenerate inline bytecode (in filters), cohort_type, and condition_type for cohorts."@@ -81,34 +91,30 @@ class Command(BaseCommand):stats = self._process_team_cohorts(team, batch_size, dry_run)# Accumulate stats- global_total += stats["total"]- global_changed += stats["changed"]- global_errors += stats["errors"]- global_validation_errors += stats["validation_errors"]- global_prospective_realtime += stats["prospective_realtime"]+ global_total += stats.total+ global_changed += stats.changed+ global_errors += stats.errors+ global_validation_errors += stats.validation_errors+ global_prospective_realtime += stats.prospective_realtime# Log team completion- if stats["total"] > 0:+ if stats.total > 0:logger.info("cohort_resave_team_completed",team_id=team.id,- total_cohorts=stats["total"],- changed_cohorts=stats["changed"],- realtime_cohorts=stats["prospective_realtime"],- error_count=stats["errors"],- validation_error_count=stats["validation_errors"],+ total_cohorts=stats.total,+ changed_cohorts=stats.changed,+ realtime_cohorts=stats.prospective_realtime,+ error_count=stats.errors,+ validation_error_count=stats.validation_errors,dry_run=dry_run,)- msg = f" Team {team.id}: {stats['total']} cohorts, {stats['changed']} changed, {stats['prospective_realtime']} realtime"- if stats["errors"] > 0:- msg += f", {stats['errors']} errors"- if stats["validation_errors"] > 0:- msg += f", {stats['validation_errors']} validation errors"- style = (- self.style.WARNING- if (stats["errors"] > 0 or stats["validation_errors"] > 0)- else self.style.SUCCESS- )+ msg = f" Team {team.id}: {stats.total} cohorts, {stats.changed} changed, {stats.prospective_realtime} realtime"+ if stats.errors > 0:+ msg += f", {stats.errors} errors"+ if stats.validation_errors > 0:+ msg += f", {stats.validation_errors} validation errors"+ style = self.style.WARNING if (stats.errors > 0 or stats.validation_errors > 0) else self.style.SUCCESSself.stdout.write(style(msg))# Log final summary@@ -138,7 +144,7 @@ class Command(BaseCommand):))- def _process_team_cohorts(self, team: Team, batch_size: int, dry_run: bool) -> dict[str, int]:+ def _process_team_cohorts(self, team: Team, batch_size: int, dry_run: bool) -> CohortResaveStats:"""Process all cohorts for a single team."""# Initialize stats for this teamtotal = 0@@ -262,13 +268,13 @@ class Command(BaseCommand):exc_info=True,)- return {- "total": total,- "changed": changed,- "errors": errors,- "validation_errors": validation_errors,- "prospective_realtime": prospective_realtime,- }+ return CohortResaveStats(+ total=total,+ changed=changed,+ errors=errors,+ validation_errors=validation_errors,+ prospective_realtime=prospective_realtime,+ )def _get_direct_cohort_references(self, filters: dict[str, Any]) -> set[int]:"""Get only the direct cohort references from filters (not transitive)."""diff --git a/posthog/management/commands/test/test_migrate_ses_tenants.py b/posthog/management/commands/test/test_migrate_ses_tenants.pyindex c2533a837dc5..f08d149bd4c4 100644--- a/posthog/management/commands/test/test_migrate_ses_tenants.py+++ b/posthog/management/commands/test/test_migrate_ses_tenants.py@@ -3,7 +3,7 @@ from unittest.mock import patchfrom django.test import override_settings-from posthog.management.commands.migrate_ses_tenants import migrate_ses_tenants+from posthog.management.commands.migrate_ses_tenants import SesTenantMigrationCounts, migrate_ses_tenantsfrom posthog.models.integration import Integration@@ -161,4 +161,6 @@ class TestMigrateSESTenants(BaseTest):# The identity succeeded; both config-set associations failed and must be reported so the# rollout can't mistake a partial pass for a complete one- assert counts == {"tenants": 1, "associations_ok": 1, "tenant_failures": 0, "association_failures": 2}+ assert counts == SesTenantMigrationCounts(+ tenants=1, associations_ok=1, tenant_failures=0, association_failures=2+ )diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 42ac4099eb45..dc2254a87ff9 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -2237,13 +2237,13 @@ def send_error_tracking_weekly_digest_for_org(self: Task, org_id: str) -> None:# counts: unfiltered counts can permanently enroll a user onto a project whose digest builds empty# (auto-select is a one-shot decision). Only computed when the org actually has a first-time user.setting_key = _DIGEST_PROJECT_SETTING_KEYS[NotificationSetting.ERROR_TRACKING_WEEKLY_DIGEST.value]- autoselect_counts: dict[int, dict] = {}+ autoselect_counts: dict[int, error_tracking_api.ExceptionSummary] = {}if any(setting_key not in (m.user.partial_notification_settings or {}) for m in memberships):autoselect_counts = {tid: summaryfor tid in team_ids_with_exceptionsif (summary := error_tracking_api.get_exception_summary_for_team(all_org_teams[tid]))- and summary["exception_count"] > 0+ and summary.exception_count > 0}# Pass 1 — resolve each recipient's enabled teams from notification settings + project access only (nodiff --git a/posthog/tasks/email_utils.py b/posthog/tasks/email_utils.pyindex ac37e5954610..c8696f175c81 100644--- a/posthog/tasks/email_utils.py+++ b/posthog/tasks/email_utils.py@@ -4,9 +4,9 @@ from typing import Anydef auto_select_digest_project(user: Any,- team_data: dict[int, dict],+ team_data: dict[int, Any],setting_key: str,- sort_key: Callable[[dict], float],+ sort_key: Callable[[Any], float],persist: bool = True,) -> bool:"""Auto-select the busiest project for first-time digest users.diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.pyindex b853ab42e4a8..21eeb73bec17 100644--- a/products/error_tracking/backend/facade/api.py+++ b/products/error_tracking/backend/facade/api.py@@ -22,13 +22,17 @@ from ..models import ()from ..remote_config import build_error_tracking_config as build_error_tracking_configfrom . import contracts+from .contracts import (+ CrashFreeSummary as CrashFreeSummary,+ ExceptionSummary as ExceptionSummary,+)IssueNotFoundError = logic.ErrorTrackingIssueNotFoundErrorExternalReferenceValidationError = logic.ErrorTrackingExternalReferenceValidationErrorReleaseHashInUseError = logic.ErrorTrackingReleaseHashInUseErrorInvalidBytecodeError = logic.ErrorTrackingInvalidBytecodeError-SOURCE_MAPS_DOCS_URL = weekly_digest.SOURCE_MAPS_DOCS_URL+SOURCE_MAPS_DOCS_URL = contracts.SOURCE_MAPS_DOCS_URLdef _to_issue_assignee(assignment) -> contracts.ErrorTrackingIssueAssignee | None:@@ -644,7 +648,7 @@ def get_exception_counts(team_ids: list[int] | None = None) -> list[Any]:return weekly_digest.get_exception_counts(team_ids=team_ids)-def get_exception_summary_for_team(team: Any) -> dict[str, Any]:+def get_exception_summary_for_team(team: Any) -> ExceptionSummary | None:return weekly_digest.get_exception_summary_for_team(team)@@ -660,11 +664,11 @@ def get_daily_exception_counts(team: Any) -> list[dict[str, Any]]:return weekly_digest.get_daily_exception_counts(team)-def get_crash_free_sessions(team: Any) -> dict[str, Any]:+def get_crash_free_sessions(team: Any) -> CrashFreeSummary | None:return weekly_digest.get_crash_free_sessions(team)-def auto_select_project_for_user(user: Any, org_id: int, team_exception_counts: dict[int, dict[str, Any]]) -> bool:+def auto_select_project_for_user(user: Any, org_id: int, team_exception_counts: dict[int, ExceptionSummary]) -> bool:return weekly_digest.auto_select_project_for_user(user=user,org_id=org_id,diff --git a/products/error_tracking/backend/facade/contracts.py b/products/error_tracking/backend/facade/contracts.pyindex 777805dc4335..c4cd2a689b39 100644--- a/products/error_tracking/backend/facade/contracts.py+++ b/products/error_tracking/backend/facade/contracts.py@@ -17,6 +17,24 @@ from pydantic.dataclasses import dataclassERROR_TRACKING_ISSUE_SEVERITIES = ("low", "medium", "high", "critical")+# Keep in sync with SOURCE_MAPS_DOCS_URL in sourceMapsFixWizardLogic.ts+SOURCE_MAPS_DOCS_URL = "https://posthog.com/docs/error-tracking/upload-source-maps"+++@dataclass(frozen=True)+class ExceptionSummary:+ exception_count: int+ ingestion_failure_count: int+ prev_exception_count: int+++@dataclass(frozen=True)+class CrashFreeSummary:+ total_sessions: int+ crash_free_rate: float+ crash_free_rate_change: dict | None+ total_sessions_change: dict | None+@dataclass(frozen=True)class ErrorTrackingIssueAssignee:diff --git a/products/error_tracking/backend/temporal/weekly_digest/activities.py b/products/error_tracking/backend/temporal/weekly_digest/activities.pyindex ba588d1ef06e..933984c235f4 100644--- a/products/error_tracking/backend/temporal/weekly_digest/activities.py+++ b/products/error_tracking/backend/temporal/weekly_digest/activities.py@@ -17,6 +17,7 @@ from posthog.temporal.common.heartbeat_sync import HeartbeaterSyncfrom posthog.user_permissions import UserPermissionsfrom products.error_tracking.backend import weekly_digest+from products.error_tracking.backend.facade.contracts import ExceptionSummaryfrom products.error_tracking.backend.temporal.weekly_digest.types import (CleanupDigestOrgsInputs,GetDigestOrgsInputs,@@ -119,7 +120,7 @@ def _send_org_digest(inputs: SendOrgDigestInputs, attempt: int) -> SendOrgDigest# counts: unfiltered counts can permanently enroll a user onto a project whose digest builds empty# (auto-select is a one-shot decision). Only computed when the org actually has a first-time user.setting_key = weekly_digest.DIGEST_PROJECT_SETTING_KEY- autoselect_counts: dict[int, dict] = {}+ autoselect_counts: dict[int, ExceptionSummary] = {}# Kept for Pass 2: the 14-day row query is the most expensive thing this activity does, so a team# ranked here shouldn't pay for it again when its digest is built.daily_rows_by_team: dict[int, list] = {}@@ -134,7 +135,7 @@ def _send_org_digest(inputs: SendOrgDigestInputs, attempt: int) -> SendOrgDigestlogger.exception("et_weekly_digest.autoselect_rank_failed", team_id=tid, org_id=org_id)continuesummary = weekly_digest.get_exception_summary_for_team(all_org_teams[tid], daily_rows_by_team[tid])- if summary and summary["exception_count"] > 0:+ if summary and summary.exception_count > 0:autoselect_counts[tid] = summary# Pass 1 — resolve each recipient's enabled teams from notification settings + project access only (nodiff --git a/products/error_tracking/backend/test/test_weekly_digest.py b/products/error_tracking/backend/test/test_weekly_digest.pyindex 4f9d9c3cee6e..74ab9657a76e 100644--- a/products/error_tracking/backend/test/test_weekly_digest.py+++ b/products/error_tracking/backend/test/test_weekly_digest.py@@ -21,6 +21,7 @@ from posthog.tasks.email import send_error_tracking_weekly_digest_for_orgfrom posthog.tasks.email_utils import compute_week_over_week_changefrom products.error_tracking.backend.facade import api as error_tracking_facade+from products.error_tracking.backend.facade.contracts import ExceptionSummaryfrom products.error_tracking.backend.models import (ErrorTrackingIssue,ErrorTrackingIssueFingerprintV2,@@ -153,12 +154,13 @@ class TestWeeklyDigest(ClickhouseTestMixin, APIBaseTest):result = get_crash_free_sessions(self.team)- assert result["total_sessions"] == 3- assert result["crash_free_rate"] == 66.67+ assert result is not None+ assert result.total_sessions == 3+ assert result.crash_free_rate == 66.67def test_get_crash_free_sessions_empty_when_no_sessions(self):result = get_crash_free_sessions(self.team)- assert result == {}+ assert result is Nonedef test_get_crash_free_sessions_includes_previous_week_comparison(self):s1, s2, s3 = str(uuid7()), str(uuid7()), str(uuid7())@@ -172,9 +174,10 @@ class TestWeeklyDigest(ClickhouseTestMixin, APIBaseTest):result = get_crash_free_sessions(self.team)- assert result["total_sessions"] == 2- assert result["crash_free_rate"] == 50.0- assert result["total_sessions_change"] is not None+ assert result is not None+ assert result.total_sessions == 2+ assert result.crash_free_rate == 50.0+ assert result.total_sessions_change is not Nonedef test_get_daily_exception_counts_returns_7_days(self):issue = self._create_issue()@@ -296,8 +299,9 @@ class TestWeeklyDigest(ClickhouseTestMixin, APIBaseTest):result = get_exception_summary_for_team(self.team)- assert result["exception_count"] == 1- assert result["prev_exception_count"] == 101+ assert result is not None+ assert result.exception_count == 1+ assert result.prev_exception_count == 101def test_top_issues_follow_issue_merges(self):issue_a = self._create_issue(name="OriginalIssue")@@ -340,9 +344,7 @@ class TestWeeklyDigest(ClickhouseTestMixin, APIBaseTest):result = get_exception_summary_for_team(self.team)- assert result["exception_count"] == 4- assert result["ingestion_failure_count"] == 1- assert result["prev_exception_count"] == 0+ assert result == ExceptionSummary(exception_count=4, ingestion_failure_count=1, prev_exception_count=0)def test_get_exception_summary_for_team_includes_previous_week(self):issue = self._create_issue()@@ -354,8 +356,9 @@ class TestWeeklyDigest(ClickhouseTestMixin, APIBaseTest):result = get_exception_summary_for_team(self.team)- assert result["exception_count"] == 3- assert result["prev_exception_count"] == 5+ assert result is not None+ assert result.exception_count == 3+ assert result.prev_exception_count == 5def test_get_exception_summary_for_team_excludes_other_teams(self):other_org = Organization.objects.create(name="Other Org")@@ -367,7 +370,7 @@ class TestWeeklyDigest(ClickhouseTestMixin, APIBaseTest):result = get_exception_summary_for_team(other_team)- assert result == {} or result["exception_count"] == 0+ assert result is None or result.exception_count == 0@parameterized.expand(["engineering", "data", "founder", "Engineering", "DATA", "Founder"])def test_auto_select_project_enrolls_eligible_roles(self, role):@@ -375,7 +378,7 @@ class TestWeeklyDigest(ClickhouseTestMixin, APIBaseTest):self.user.save()team_exception_counts = {- self.team.pk: {"exception_count": 10, "ingestion_failure_count": 0, "prev_exception_count": 0},+ self.team.pk: ExceptionSummary(exception_count=10, ingestion_failure_count=0, prev_exception_count=0),}auto_select_project_for_user(self.user, self.organization.id, team_exception_counts)@@ -391,7 +394,7 @@ class TestWeeklyDigest(ClickhouseTestMixin, APIBaseTest):self.user.save()team_exception_counts = {- self.team.pk: {"exception_count": 10, "ingestion_failure_count": 0, "prev_exception_count": 0},+ self.team.pk: ExceptionSummary(exception_count=10, ingestion_failure_count=0, prev_exception_count=0),}auto_select_project_for_user(self.user, self.organization.id, team_exception_counts)@@ -409,7 +412,7 @@ class TestWeeklyDigest(ClickhouseTestMixin, APIBaseTest):self.user.save()team_exception_counts = {- self.team.pk: {"exception_count": 5, "ingestion_failure_count": 0, "prev_exception_count": 0},+ self.team.pk: ExceptionSummary(exception_count=5, ingestion_failure_count=0, prev_exception_count=0),}auto_select_project_for_user(self.user, self.organization.id, team_exception_counts)@@ -436,7 +439,8 @@ class TestWeeklyDigest(ClickhouseTestMixin, APIBaseTest):result = get_exception_summary_for_team(self.team)- assert result["exception_count"] == 2+ assert result is not None+ assert result.exception_count == 2def test_get_daily_exception_counts_filters_internal_users(self):self._set_internal_user_filter()@@ -493,8 +497,9 @@ class TestWeeklyDigest(ClickhouseTestMixin, APIBaseTest):result = get_crash_free_sessions(self.team)- assert result["total_sessions"] == 1- assert result["crash_free_rate"] == 100.0+ assert result is not None+ assert result.total_sessions == 1+ assert result.crash_free_rate == 100.0class TestComputeWeekOverWeekChange:diff --git a/products/error_tracking/backend/weekly_digest.py b/products/error_tracking/backend/weekly_digest.pyindex 8e7eb3c95e9b..e61cc57be24e 100644--- a/products/error_tracking/backend/weekly_digest.py+++ b/products/error_tracking/backend/weekly_digest.py@@ -1,4 +1,5 @@import datetime+from dataclasses import asdictfrom typing import Anyfrom django.conf import settings@@ -15,6 +16,8 @@ from posthog.models import Teamfrom posthog.schema_enums import ProductKeyfrom posthog.utils import compact_number+from products.error_tracking.backend.facade.contracts import SOURCE_MAPS_DOCS_URL, CrashFreeSummary, ExceptionSummary+logger = structlog.get_logger(__name__)DIGEST_WEBHOOK_TIMEOUT_SECONDS = 10@@ -24,9 +27,6 @@ DIGEST_WEBHOOK_TIMEOUT_SECONDS = 10# the error_tracking ClickHouse profile's execution ceiling — keep the two in sync.DIGEST_MAX_EXECUTION_TIME_SECONDS = 120-# Keep in sync with SOURCE_MAPS_DOCS_URL in sourceMapsFixWizardLogic.ts-SOURCE_MAPS_DOCS_URL = "https://posthog.com/docs/error-tracking/upload-source-maps"-def get_org_ids_with_exceptions() -> list[str]:"""Return distinct organization IDs that have teams with exceptions in the last 7 days"""@@ -78,12 +78,12 @@ def query_daily_rows(team: Team, filter_test_accounts: bool = True) -> list:return response.results or []-def get_exception_summary_for_team(team: Team, daily_rows: list | None = None) -> dict:+def get_exception_summary_for_team(team: Team, daily_rows: list | None = None) -> ExceptionSummary | None:"""Exception counts, ingestion failures, and previous-week count. This week = 1-7 days ago, previous = 8-14."""if daily_rows is None:daily_rows = query_daily_rows(team)if not daily_rows:- return {}+ return None# ClickHouse returns team-timezone dates, so bucket against the team-local today, not UTCtoday = timezone.now().astimezone(team.timezone_info).date()@@ -98,11 +98,11 @@ def get_exception_summary_for_team(team: Team, daily_rows: list | None = None) -elif 8 <= days_ago <= 14:prev_exception_count += day_count- return {- "exception_count": exception_count,- "ingestion_failure_count": ingestion_failure_count,- "prev_exception_count": prev_exception_count,- }+ return ExceptionSummary(+ exception_count=exception_count,+ ingestion_failure_count=ingestion_failure_count,+ prev_exception_count=prev_exception_count,+ )ELIGIBLE_ROLES_FOR_AUTO_DIGEST = {"engineering", "data", "founder"}@@ -113,7 +113,7 @@ DIGEST_PROJECT_SETTING_KEY = "error_tracking_weekly_digest_project_enabled"def auto_select_project_for_user(- user: Any, org_id: int, team_exception_counts: dict[int, dict], persist: bool = True+ user: Any, org_id: int, team_exception_counts: dict[int, ExceptionSummary], persist: bool = True) -> bool:"""For first-time users who have no ET digest project settings, auto-select the project with the most exceptionsand persist the selection to their notification settings.@@ -149,7 +149,7 @@ def auto_select_project_for_user(user=user,team_data=team_exception_counts,setting_key=setting_key,- sort_key=lambda d: d["exception_count"],+ sort_key=lambda d: d.exception_count,persist=persist,)@@ -194,7 +194,7 @@ def get_exception_counts(team_ids: list[int] | None = None) -> list:return results if isinstance(results, list) else []-def get_crash_free_sessions(team: Team, filter_test_accounts: bool = True) -> dict:+def get_crash_free_sessions(team: Team, filter_test_accounts: bool = True) -> CrashFreeSummary | None:"""Calculate crash free sessions rate for the last 7 days with previous week comparison."""from posthog.hogql.constants import HogQLGlobalSettingsfrom posthog.hogql.query import execute_hogql_query@@ -209,7 +209,7 @@ def get_crash_free_sessions(team: Team, filter_test_accounts: bool = True) -> ditag_queries(product=ProductKey.ERROR_TRACKING, team_id=team.pk, name="weekly_digest:crash_free_sessions")# A ClickHouse failure propagates (task fails and retries) rather than being swallowed into an- # empty result. A successful query with no sessions still returns {} below.+ # empty result. A successful query with no sessions still returns None below.response = execute_hogql_query(query="""SELECT@@ -232,33 +232,28 @@ def get_crash_free_sessions(team: Team, filter_test_accounts: bool = True) -> di)if not response.results or not response.results[0]:- return {}+ return Nonetotal_sessions, crash_sessions, prev_total_sessions, prev_crash_sessions = response.results[0]if total_sessions == 0:- return {}+ return Nonecrash_free_rate = round((1 - crash_sessions / total_sessions) * 100, 2)prev_crash_free_rate = (round((1 - prev_crash_sessions / prev_total_sessions) * 100, 2) if prev_total_sessions > 0 else None)- result: dict = {- "total_sessions": total_sessions,- "crash_free_rate": crash_free_rate,- }-- result["crash_free_rate_change"] = (- compute_week_over_week_change(crash_free_rate, prev_crash_free_rate, higher_is_better=True)- if prev_crash_free_rate is not None- else None- )- result["total_sessions_change"] = compute_week_over_week_change(- total_sessions, prev_total_sessions, higher_is_better=True+ return CrashFreeSummary(+ total_sessions=total_sessions,+ crash_free_rate=crash_free_rate,+ crash_free_rate_change=(+ compute_week_over_week_change(crash_free_rate, prev_crash_free_rate, higher_is_better=True)+ if prev_crash_free_rate is not None+ else None+ ),+ total_sessions_change=compute_week_over_week_change(total_sessions, prev_total_sessions, higher_is_better=True),)- return result-def get_daily_exception_counts(team: Team, daily_rows: list | None = None) -> list[dict]:"""Exception counts per day for the last 7 days, as sparkline-ready bars."""@@ -465,18 +460,18 @@ def build_team_digest_data(if daily_rows is None:daily_rows = query_daily_rows(team, filter_test_accounts)counts = get_exception_summary_for_team(team, daily_rows)- if not counts or counts["exception_count"] == 0:+ if counts is None or counts.exception_count == 0:return Noneissue_rows = _query_issue_rows(team, filter_test_accounts)return {"team": team,- "exception_count": counts["exception_count"],+ "exception_count": counts.exception_count,"exception_change": compute_week_over_week_change(- counts["exception_count"], counts["prev_exception_count"], higher_is_better=False+ counts.exception_count, counts.prev_exception_count, higher_is_better=False),- "ingestion_failure_count": counts["ingestion_failure_count"],+ "ingestion_failure_count": counts.ingestion_failure_count,"top_issues": get_top_issues_for_team(team, issue_rows),"new_issues": get_new_issues_for_team(team, issue_rows),"daily_counts": get_daily_exception_counts(team, daily_rows),@@ -504,11 +499,11 @@ def build_team_section_payload(data: dict[str, Any]) -> dict[str, Any]:section["team_name"] = data["team"].namesection["exception_count"] = compact_number(data["exception_count"])section["ingestion_failure_count_display"] = compact_number(data["ingestion_failure_count"])- if data["crash_free"]:- section["crash_free"] = {- **data["crash_free"],- "total_sessions": compact_number(data["crash_free"]["total_sessions"]),- }+ crash_free = data["crash_free"]+ # The digest webhook payload represents "no crash-free data" as {}, not null+ section["crash_free"] = (+ {**asdict(crash_free), "total_sessions": compact_number(crash_free.total_sessions)} if crash_free else {}+ )section["top_issues"] = [serialize_issue(i) for i in data["top_issues"]]section["new_issues"] = [serialize_issue(i) for i in data["new_issues"]]return section