: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(today): show routine insights in the pulse and home dashboard drops (#117313)
Shy Alterc6b6c8aca381
diff --git a/posthog/migrations/1400_file_system_view_days.py b/posthog/migrations/1400_file_system_view_days.pynew file mode 100644index 000000000000..d281da237afb--- /dev/null+++ b/posthog/migrations/1400_file_system_view_days.py@@ -0,0 +1,18 @@+# Generated by Django 5.2.18 on 2026-10-14 10:08++import django.contrib.postgres.fields+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("posthog", "1399_alter_user_ui_configuration_help_text")]++ operations = [+ migrations.AddField(+ model_name="filesystemviewlog",+ name="view_days",+ field=django.contrib.postgres.fields.ArrayField(+ base_field=models.DateField(), blank=True, null=True, size=None+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex 90ac8b1a295b..24c9597dc6de 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1399_alter_user_ui_configuration_help_text+1400_file_system_view_daysdiff --git a/posthog/models/file_system/file_system_view_log.py b/posthog/models/file_system/file_system_view_log.pyindex 937ef3821aa0..bf6871d59126 100644--- a/posthog/models/file_system/file_system_view_log.py+++ b/posthog/models/file_system/file_system_view_log.py@@ -2,10 +2,12 @@ from __future__ import annotationsfrom collections.abc import Collection, Sequencefrom dataclasses import is_dataclass-from datetime import datetime+from datetime import date, datetime, timedeltafrom typing import TYPE_CHECKING, Optional, cast+from zoneinfo import ZoneInfo-from django.db import IntegrityError, models+from django.contrib.postgres.fields import ArrayField+from django.db import IntegrityError, models, transactionfrom django.db.models import Exists, OuterRef, Q, QuerySetfrom django.db.models.signals import post_deletefrom django.dispatch import receiver@@ -14,11 +16,14 @@ from django.utils import timezonefrom posthog.models.file_system.constants import DEFAULT_SURFACE, surface_qfrom posthog.models.file_system.file_system import FileSystemfrom posthog.models.file_system.file_system_representation import FileSystemRepresentation+from posthog.models.team import Teamfrom posthog.models.utils import UUIDModelif TYPE_CHECKING:from posthog.models.user import User+VIEW_DAYS_KEPT = 35+class FileSystemViewLog(UUIDModel):team = models.ForeignKey("Team", on_delete=models.CASCADE)@@ -31,6 +36,7 @@ class FileSystemViewLog(UUIDModel):# so (team, user, type, ref) already identifies a view uniquely. The column only lets us# filter Recents to a single surface without joining back to FileSystem.surface = models.CharField(max_length=100, null=True, blank=True)+ view_days = ArrayField(models.DateField(), null=True, blank=True)class Meta:indexes = [@@ -90,17 +96,29 @@ def log_file_system_view("ref": str(representation.ref),}surface = getattr(representation, "surface", DEFAULT_SURFACE)+ team_timezone = Team.objects.filter(id=resolved_team_id).values_list("timezone", flat=True).first()+ day = now.astimezone(ZoneInfo(team_timezone or "UTC")).date()- updated = FileSystemViewLog.objects.filter(**update_kwargs).update(viewed_at=now, surface=surface)-- if updated:+ if _record_view(update_kwargs, viewed_at=now, surface=surface, day=day):returntry:- FileSystemViewLog.objects.create(viewed_at=now, surface=surface, **update_kwargs)+ with transaction.atomic():+ FileSystemViewLog.objects.create(viewed_at=now, surface=surface, view_days=[day], **update_kwargs)except IntegrityError:# Another request may have created the row after our update attempt.- FileSystemViewLog.objects.filter(**update_kwargs).update(viewed_at=now, surface=surface)+ _record_view(update_kwargs, viewed_at=now, surface=surface, day=day)+++def _record_view(lookup: dict[str, object], *, viewed_at: datetime, surface: str, day: date) -> bool:+ with transaction.atomic():+ row = FileSystemViewLog.objects.select_for_update().filter(**lookup).values_list("id", "view_days").first()+ if row is None:+ return False+ log_id, known_days = row+ view_days = sorted({d for d in [*(known_days or []), day] if d > day - timedelta(days=VIEW_DAYS_KEPT)})+ FileSystemViewLog.objects.filter(id=log_id).update(viewed_at=viewed_at, surface=surface, view_days=view_days)+ return Truedef recent_view_logs(diff --git a/posthog/models/file_system/starred_products.py b/posthog/models/file_system/starred_products.pyindex 5b46464c912c..3226003b1d3e 100644--- a/posthog/models/file_system/starred_products.py+++ b/posthog/models/file_system/starred_products.py@@ -35,6 +35,11 @@ def _product_stars(user: User, team: "Team") -> QuerySet[FileSystemShortcut]:return _project_shortcuts(user, team).filter(ref__isnull=True).exclude(type="folder")+def has_starred_product(user: User, team: "Team", product_paths: list[str]) -> bool:+ """Whether the user starred any of these products anywhere in the team's project."""+ return _product_stars(user, team).filter(path__in=product_paths).exists()++def star_products(user: User, team: "Team", product_paths: list[str]) -> int:"""Star products on the user's sidebar for a team, after their existing stars. Returns how many were added.diff --git a/posthog/models/file_system/test/test_file_system_view_log.py b/posthog/models/file_system/test/test_file_system_view_log.pyindex 0f545f43f8ae..b3ef10b7ee65 100644--- a/posthog/models/file_system/test/test_file_system_view_log.py+++ b/posthog/models/file_system/test/test_file_system_view_log.py@@ -1,4 +1,4 @@-from datetime import UTC, datetime+from datetime import UTC, date, datetimefrom typing import Protocol, castimport time_machine@@ -105,6 +105,16 @@ class TestFileSystemViewLog(TestCase):datetime(2024, 2, 1, 10, 0, 10, tzinfo=UTC),)+ def test_view_log_keeps_one_entry_per_project_day_for_the_last_five_weeks(self) -> None:+ self.team.timezone = "America/Los_Angeles"+ self.team.save()+ for moment in ("2024-02-01T09:00:00Z", "2024-02-01T17:00:00Z", "2024-02-20T09:00:00Z", "2024-03-11T03:00:00Z"):+ with time_machine.travel(moment, tick=False):+ log_file_system_view(user=self.user, obj=self._representation(), team_id=self.team.id)++ log = FileSystemViewLog.objects.get(team=self.team, user=self.user, type="doc", ref="ref-1")+ self.assertEqual(log.view_days, [date(2024, 2, 20), date(2024, 3, 10)])+def _representation(self, *, surface: str = "web", ref: str = "ref-1") -> FileSystemRepresentation:return FileSystemRepresentation(base_folder="", type="doc", ref=ref, name="", href="", meta={}, surface=surface)diff --git a/posthog/models/test/test_default_starred_products.py b/posthog/models/test/test_default_starred_products.pyindex fe99699c7b78..e970c4792324 100644--- a/posthog/models/test/test_default_starred_products.py+++ b/posthog/models/test/test_default_starred_products.py@@ -6,7 +6,11 @@ from parameterized import parameterizedfrom posthog.constants import AvailableFeaturefrom posthog.models import Team, Userfrom posthog.models.file_system.file_system_shortcut import FileSystemShortcut-from posthog.models.file_system.starred_products import DEFAULT_PRODUCT_PATHS, star_default_products+from posthog.models.file_system.starred_products import (+ DEFAULT_PRODUCT_PATHS,+ has_starred_product,+ star_default_products,+)from posthog.models.organization import OrganizationMembershipfrom posthog.models.organization_invite import OrganizationInvitefrom posthog.products import Products@@ -39,6 +43,22 @@ class TestDefaultStarredProducts(BaseTest):)assert starred == ["Logs"]+ @parameterized.expand(+ [+ ("a star in this environment", "same", None, True),+ ("a star in another environment of the project", "other", None, True),+ ("a starred file with the same name", "same", "42", False),+ ]+ )+ def test_has_starred_product(self, _name: str, environment: str, ref: str | None, expected: bool) -> None:+ other_environment = Team.objects.create(organization=self.organization, project=self.project, name="Staging")+ team = other_environment if environment == "other" else self.team+ user = User.objects.create_user(email="[email protected]", password="password", first_name="Stars")+ FileSystemShortcut.objects.create(team=team, user=user, path="Error tracking", type="error_tracking", ref=ref)++ assert has_starred_product(user, self.team, ["Error tracking", "Session replay"]) is expected+ assert has_starred_product(user, self.team, ["Session replay"]) is False+def _make_team_private(self, team: Team) -> None:# Project-level access controls only apply when the org has the feature.self.organization.available_product_features = [diff --git a/products/dashboards/backend/facade/api.py b/products/dashboards/backend/facade/api.pyindex 0b272b406461..220efe533b48 100644--- a/products/dashboards/backend/facade/api.py+++ b/products/dashboards/backend/facade/api.py@@ -11,6 +11,7 @@ matters. Refusals are raised as the error types defined here — the caller deciresponse they become."""+import refrom collections.abc import Collection, Sequencefrom typing import TYPE_CHECKING, Any@@ -23,6 +24,7 @@ from rest_framework import serializersfrom posthog.api.sharing_publish_gate import check_can_add_insight_to_shared_dashboardfrom posthog.helpers.dashboard_templates import create_from_templatefrom posthog.models.user import User+from posthog.models.user_home_settings import UserHomeSettingsfrom posthog.user_permissions import UserPermissionsfrom products.access_control.backend.facade.user_access_control import UserAccessControl@@ -93,6 +95,44 @@ def _refs_in_given_order(dashboard_ids: Sequence[int]) -> tuple[DashboardRef, ..)+@dataclass(frozen=True)+class HomeDashboardTile:+ insight_short_id: str+ filters_overrides: dict[str, Any] | None+++@dataclass(frozen=True)+class HomeDashboardInsights:+ dashboard_id: int+ filters: dict[str, Any]+ variables: dict[str, Any] | None+ tiles: tuple[HomeDashboardTile, ...]+++def home_dashboard_insights(*, team: "Team", user: User, limit: int) -> HomeDashboardInsights | None:+ homepage = UserHomeSettings.objects.filter(team=team, user=user).values_list("homepage", flat=True).first()+ match = re.search(r"/dashboard/(\d+)", str((homepage or {}).get("pathname") or ""))+ dashboard_id = int(match.group(1)) if match else team.primary_dashboard_id+ if dashboard_id is None:+ return None+ dashboard = Dashboard.objects.filter(team_id=team.id, pk=dashboard_id).first()+ access = UserAccessControl(user=user, team=team)+ if dashboard is None or not access.check_access_level_for_object(dashboard, "viewer"):+ return None+ insight_tiles = DashboardTile.objects.filter(dashboard=dashboard, insight__isnull=False, insight__deleted=False)+ tiles = DashboardTile.sort_tiles_by_layout(insight_tiles.select_related("insight"))+ return HomeDashboardInsights(+ dashboard_id=dashboard.id,+ filters=dashboard.filters or {},+ variables=dashboard.variables or None,+ tiles=tuple(+ HomeDashboardTile(insight_short_id=tile.insight.short_id, filters_overrides=tile.filters_overrides or None)+ for tile in tiles[:limit]+ if tile.insight is not None+ ),+ )++def viewable_dashboard_ref(dashboard_id: int, *, team: "Team", user: User) -> DashboardRef | None:"""The dashboard as a ref when it is live in this team and the user may view it, else None.diff --git a/products/dashboards/backend/test/test_home_dashboard_insights.py b/products/dashboards/backend/test/test_home_dashboard_insights.pynew file mode 100644index 000000000000..a7d281385926--- /dev/null+++ b/products/dashboards/backend/test/test_home_dashboard_insights.py@@ -0,0 +1,62 @@+from typing import Any++from posthog.test.base import APIBaseTest++from parameterized import parameterized++from posthog.models.user_home_settings import UserHomeSettings++from products.dashboards.backend.facade.api import home_dashboard_insights+from products.dashboards.backend.models.dashboard import Dashboard+from products.dashboards.backend.models.dashboard_tile import DashboardTile+from products.product_analytics.backend.facade.models import Insight++FILTERS = {"properties": [{"key": "plan"}]}+VARIABLES = {"v1": {"value": "pro"}}+OVERRIDE = {"date_from": "-7d"}+++class TestHomeDashboardInsights(APIBaseTest):+ def _dashboard(self, name: str, short_ids: list[str]) -> Dashboard:+ dashboard = Dashboard.objects.create(team=self.team, name=name, filters=FILTERS, variables=VARIABLES)+ for row, short_id in reversed(list(enumerate(short_ids))):+ insight = Insight.objects.create(team=self.team, short_id=short_id, deleted=short_id.startswith("gone"))+ DashboardTile.objects.create(+ dashboard=dashboard,+ insight=insight,+ layouts={"sm": {"x": 0, "y": row * 5, "w": 6, "h": 5}},+ filters_overrides=OVERRIDE if short_id.endswith("2") else None,+ )+ return dashboard++ @parameterized.expand(+ [+ ("the homepage dashboard", True, True, [("h1", None), ("h2", OVERRIDE)]),+ ("the project dashboard without a homepage", False, True, [("p1", None), ("p2", OVERRIDE)]),+ ("nothing without either", False, False, None),+ ]+ )+ def test_the_home_dashboard_lists_its_live_insights_in_layout_order(+ self,+ _name: str,+ homepage: bool,+ primary: bool,+ expected: list[tuple[str, dict[str, Any] | None]] | None,+ ) -> None:+ home = self._dashboard("Home", ["h1", "gone-h", "h2", "h3"])+ main = self._dashboard("Main", ["p1", "p2"])+ if homepage:+ UserHomeSettings.objects.create(+ team=self.team, user=self.user, homepage={"pathname": f"/project/{self.team.id}/dashboard/{home.id}"}+ )+ self.team.primary_dashboard = main if primary else None+ self.team.save()++ found = home_dashboard_insights(team=self.team, user=self.user, limit=2)++ self.assertEqual(+ ([(t.insight_short_id, t.filters_overrides) for t in found.tiles], found.filters, found.variables)+ if found+ else None,+ (expected, FILTERS, VARIABLES) if expected else None,+ )diff --git a/products/product_analytics/backend/facade/api.py b/products/product_analytics/backend/facade/api.pyindex c515bd492a27..f0632e2a051e 100644--- a/products/product_analytics/backend/facade/api.py+++ b/products/product_analytics/backend/facade/api.py@@ -24,7 +24,12 @@ from posthog.models import Team, Userfrom products.access_control.backend.facade.user_access_control import UserAccessControlfrom products.product_analytics.backend import logic-from products.product_analytics.backend.facade.contracts import InsightVariableDefinition, SavedInsightDefinition+from products.product_analytics.backend.facade.contracts import (+ InsightDashboardContext,+ InsightSeries,+ InsightVariableDefinition,+ SavedInsightDefinition,+)from products.product_analytics.backend.models.insight import Insightfrom products.product_analytics.backend.models.insight_variable import InsightVariable@@ -228,3 +233,21 @@ def save_saved_insight_query(insight.last_modified_by = userinsight.save(update_fields=["query", "saved", "last_modified_by", "updated_at"])return None+++def get_insight_series(+ *, team: Team, user: User, short_id: str, dashboard: InsightDashboardContext | None = None+) -> InsightSeries | None:+ insight = Insight.objects.filter(team__project_id=team.project_id, short_id=short_id, deleted=False).first()+ if insight is None:+ return None+ access_control = UserAccessControl(user=user, team=team, organization_id=str(team.organization_id))+ if not access_control.check_access_level_for_object(insight, "viewer"):+ return None+ from products.product_analytics.backend import ( # noqa: PLC0415 -- insight_series imports the query runner, which imports this facade+ insight_series,+ )++ return insight_series.insight_series(+ team, user, short_id=insight.short_id, name=insight.name, query=insight.query or {}, dashboard=dashboard+ )diff --git a/products/product_analytics/backend/facade/contracts.py b/products/product_analytics/backend/facade/contracts.pyindex aae9d58260bc..fdcdec9e5260 100644--- a/products/product_analytics/backend/facade/contracts.py+++ b/products/product_analytics/backend/facade/contracts.py@@ -106,3 +106,24 @@ class InsightDataChecks:status: InsightDataChecksStatuschecks: list[InsightDataCheck]coverage: InsightDataChecksCoverage | None+++@dataclass(frozen=True)+class InsightSeries:+ short_id: str+ name: str | None+ series: dict[str, list[tuple[date, float]]]+ period: str+ averaged_series: list[str]+ event_name: str+ value_format: str | None = None+ value_prefix: str | None = None+ value_postfix: str | None = None+ decimal_places: int | None = None+++@dataclass(frozen=True)+class InsightDashboardContext:+ filters: dict[str, Any]+ tile_filters: dict[str, Any] | None = None+ variables: dict[str, Any] | None = Nonediff --git a/products/product_analytics/backend/insight_series.py b/products/product_analytics/backend/insight_series.pynew file mode 100644index 000000000000..d1e40c4d6bbf--- /dev/null+++ b/products/product_analytics/backend/insight_series.py@@ -0,0 +1,157 @@+import json+from datetime import date+from typing import Any++from pydantic import BaseModel++from posthog.hogql_queries.apply_dashboard_filters import resolve_effective_dashboard_filters+from posthog.hogql_queries.query_runner import ExecutionMode+from posthog.models import Team, User++from products.product_analytics.backend.facade.contracts import InsightDashboardContext, InsightSeries++ADDITIVE_MATH = {+ "total",+ "sum",+ "first_time_for_user",+ "first_matching_event_for_user",+ "first_time_for_group",+ "first_matching_event_for_group",+}+UNCHARTED_DISPLAYS = {+ "ActionsTable",+ "ActionsPie",+ "BoldNumber",+ "WorldMap",+ "ActionsBarValue",+ "ActionsLineGraphCumulative",+ "SlopeGraph",+}+LOOKBACK = {"day": "-56d", "week": "-16w", "month": "-24m"}+DATE_FILTERS = ("date_from", "date_to", "explicitDate", "interval", "compareFilter")+EXECUTION_MODE = ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE+++def _run(+ team: Team,+ user: User,+ source: dict[str, Any],+ filters: dict[str, Any] | None,+ variables: dict[str, Any] | None,+) -> dict[str, Any]:+ from posthog.api.services.query import process_query_dict # noqa: PLC0415++ response = process_query_dict(+ team,+ source,+ dashboard_filters_json=filters,+ variables_override_json=variables,+ execution_mode=EXECUTION_MODE,+ user=user,+ )+ return response.model_dump() if isinstance(response, BaseModel) else response+++def _value_key(result: dict[str, Any], position: int) -> str:+ order = (result.get("action") or {}).get("order")+ payload: dict[str, Any] = {+ "series": order if isinstance(order, int) else f"formula{position + 1}" if position else "formula"+ }+ if "breakdown_value" in result:+ breakdown = result["breakdown_value"]+ payload["breakdown_value"] = breakdown if isinstance(breakdown, list) else [breakdown]+ return json.dumps(payload, separators=(",", ":"), ensure_ascii=False)+++def _visible(trends: dict[str, Any], results: list[dict[str, Any]]) -> list[dict[str, Any]]:+ customizations = trends.get("resultCustomizations") or {}+ if not customizations:+ return results+ by_position = trends.get("resultCustomizationBy") == "position"+ ranked = sorted(range(len(results)), key=lambda i: (results[i].get("action") or {}).get("order") or 0)+ positions = {index: rank for rank, index in enumerate(ranked)}+ return [+ result+ for index, result in enumerate(results)+ if not (+ customizations.get(str(positions[index]) if by_position else _value_key(result, positions[index])) or {}+ ).get("hidden")+ ]+++def insight_series(+ team: Team,+ user: User,+ *,+ short_id: str,+ name: str | None,+ query: dict[str, Any],+ dashboard: InsightDashboardContext | None,+) -> InsightSeries | None:+ dashboard_filters: dict[str, Any] = {}+ variables: dict[str, Any] | None = None+ if dashboard is not None:+ effective = resolve_effective_dashboard_filters(query, dashboard.filters, dashboard.tile_filters)+ query = effective.query+ dashboard_filters = effective.filters or {}+ variables = dashboard.variables+ filters = {key: value for key, value in dashboard_filters.items() if key not in DATE_FILTERS}+ source = query.get("source", query)+ trends = source.get("trendsFilter") or {}+ if source.get("kind") != "TrendsQuery" or trends.get("display") in UNCHARTED_DISPLAYS:+ return None+ interval = dashboard_filters.get("interval") or source.get("interval") or "day"+ if interval not in LOOKBACK:+ interval = "day"+ date_range = source.get("dateRange") or {}+ if interval == "day" and date_range.get("daysOfWeek"):+ return None+ kept = {key: value for key, value in date_range.items() if key not in DATE_FILTERS}+ bounded = {key: value for key, value in source.items() if key != "compareFilter"}+ bounded.update(+ interval=interval,+ dateRange={**kept, "date_from": LOOKBACK[interval], "excludeIncompletePeriods": True},+ trendsFilter={**{k: v for k, v in trends.items() if k != "smoothingIntervals"}, "metricShowChange": False},+ )+ response = _run(team, user, bounded, filters, variables)+ formula = bool(trends.get("formula") or trends.get("formulas") or trends.get("formulaNodes"))+ several = len(source.get("series") or []) > 1+ series: dict[str, list[tuple[date, float]]] = {}+ averaged: list[str] = []+ for result in _visible(trends, response.get("results") or []):+ if not result.get("days"):+ continue+ action = result.get("action") or {}+ shown = str(result.get("label") or "Series")+ label = str(action.get("custom_name") or action.get("name") or shown)+ breakdown = result.get("breakdown_value")+ if breakdown not in (None, ""):+ if action:+ value = shown.removeprefix(f"{action.get('name')} - ") if several else shown+ else:+ value = ", ".join(str(b) for b in breakdown) if isinstance(breakdown, list) else str(breakdown)+ label = f"{label} · {value}" if several else value+ while label in series:+ label += " (2)"+ series[label] = [+ (date.fromisoformat(str(d)[:10]), float(v or 0)) for d, v in zip(result["days"], result["data"])+ ]+ if formula or (action.get("math") or "total") not in ADDITIVE_MATH:+ averaged.append(label)+ if not series:+ return None+ nodes = source.get("series") or []+ node = nodes[0] if len(nodes) == 1 else {}+ places = trends.get("decimalPlaces")+ return InsightSeries(+ short_id=short_id,+ name=name,+ series=series,+ period=interval,+ averaged_series=averaged,+ event_name=str(node.get("custom_name") or node.get("event") or node.get("name") or ""),+ value_format=trends.get("aggregationAxisFormat"),+ value_prefix=trends.get("aggregationAxisPrefix"),+ value_postfix=trends.get("aggregationAxisPostfix"),+ decimal_places=None if places is None else min(max(int(places), 0), 9),+ )diff --git a/products/product_analytics/backend/tests/test_insight_series.py b/products/product_analytics/backend/tests/test_insight_series.pynew file mode 100644index 000000000000..518fc10139b9--- /dev/null+++ b/products/product_analytics/backend/tests/test_insight_series.py@@ -0,0 +1,253 @@+from datetime import datetime, timedelta+from typing import Any, cast++from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events+from unittest.mock import patch++from django.test import SimpleTestCase+from django.utils import timezone++from parameterized import parameterized++from posthog.constants import AvailableFeature+from posthog.hogql_queries.query_runner import ExecutionMode+from posthog.models import Team, User++from products.access_control.backend.facade.testing import create_access_control+from products.product_analytics.backend import insight_series+from products.product_analytics.backend.facade.api import get_insight_series+from products.product_analytics.backend.facade.contracts import InsightDashboardContext+from products.product_analytics.backend.insight_series import _visible+from products.product_analytics.backend.models.insight import Insight+++class TestVisibleResults(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "by value",+ None,+ {'{"series":1,"breakdown_value":["Chrome"]}': {"hidden": True}},+ ["0 Chrome", "1 Safari"],+ ),+ ("by position", "position", {"2": {"hidden": True}}, ["0 Chrome", "1 Chrome"]),+ (+ "a visible customization",+ None,+ {'{"series":0,"breakdown_value":["Chrome"]}': {"color": "preset-2"}},+ ["0 Chrome", "1 Chrome", "1 Safari"],+ ),+ ]+ )+ def test_hidden_trend_results_are_left_out(+ self, _name: str, by: str | None, customizations: dict[str, Any], expected: list[str]+ ) -> None:+ results = [+ {"action": {"order": order}, "breakdown_value": browser}+ for order, browser in ((1, "Chrome"), (1, "Safari"), (0, "Chrome"))+ ]++ visible = _visible({"resultCustomizationBy": by, "resultCustomizations": customizations}, results)++ self.assertEqual(sorted(f"{r['action']['order']} {r['breakdown_value']}" for r in visible), expected)+++def _result(label: str, breakdown: Any = None, **action: Any) -> dict[str, Any]:+ return {+ "action": {"name": "signed up", "order": 0, **action},+ "label": label,+ "breakdown_value": breakdown,+ "days": ["2026-10-12"],+ "data": [1],+ }+++class TestSeriesNames(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "a cohort breakdown shows the cohort name",+ 1,+ [_result("Enterprise", 12), _result("Free", 13)],+ {"Enterprise": False, "Free": False},+ ),+ (+ "several series name each series once",+ 2,+ [+ _result("signed up - Chrome", "Chrome"),+ _result("logged in - Chrome", "Chrome", name="logged in", custom_name="Logins"),+ ],+ {"signed up · Chrome": False, "Logins · Chrome": False},+ ),+ (+ "first group occurrences add up",+ 3,+ [+ _result("signed up", math="first_time_for_group"),+ _result("signed up", math="first_matching_event_for_group", custom_name="Matches"),+ _result("signed up", math="dau", custom_name="Daily people"),+ ],+ {"signed up": False, "Matches": False, "Daily people": True},+ ),+ ]+ )+ def test_series_names_and_averaging(+ self, _name: str, series_count: int, results: list[dict[str, Any]], expected: dict[str, bool]+ ) -> None:+ with patch.object(insight_series, "_run", return_value={"results": results}):+ found = insight_series.insight_series(+ cast(Team, None),+ cast(User, None),+ short_id="abc",+ name="Sign-ups",+ query={"kind": "TrendsQuery", "series": [{}] * series_count},+ dashboard=None,+ )++ assert found is not None+ self.assertEqual({name: name in found.averaged_series for name in found.series}, expected)+++class TestGetInsightSeries(ClickhouseTestMixin, BaseTest):+ def setUp(self) -> None:+ super().setUp()+ blocking = patch.object(+ insight_series, "EXECUTION_MODE", ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE+ )+ blocking.start()+ self.addCleanup(blocking.stop)++ def _ago(self, days: int) -> datetime:+ return timezone.now() - timedelta(days=days)++ def _signups(self, *days_and_browsers: tuple[int, str]) -> None:+ _create_person(team=self.team, distinct_ids=["user-1"])+ for days, browser in days_and_browsers:+ _create_event(+ team=self.team,+ event="signed up",+ distinct_id="user-1",+ properties={"$browser": browser},+ timestamp=self._ago(days),+ )+ flush_persons_and_events()++ def _insight(self, **query: Any) -> Insight:+ return Insight.objects.create(+ team=self.team,+ name="Sign-ups",+ created_by=self.user,+ saved=True,+ query={"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", **query}},+ )++ def test_a_daily_trend_returns_each_series_with_its_averaging_and_display_format(self) -> None:+ self._signups((2, "Chrome"), (2, "Chrome"), (9, "Chrome"))+ insight = self._insight(+ series=[+ {"kind": "EventsNode", "event": "signed up", "custom_name": "Sign-ups"},+ {"kind": "EventsNode", "event": "signed up", "math": "dau", "custom_name": "Daily people"},+ ],+ trendsFilter={"aggregationAxisFormat": "percentage", "display": "Metric", "decimalPlaces": 1_000_000},+ )++ found = get_insight_series(team=self.team, user=self.user, short_id=insight.short_id)++ assert found is not None+ self.assertEqual(+ (+ found.period,+ found.averaged_series,+ found.value_format,+ found.decimal_places,+ {name: (len(points), sum(v for _, v in points)) for name, points in found.series.items()},+ ),+ ("day", ["Daily people"], "percentage", 9, {"Sign-ups": (56, 3.0), "Daily people": (56, 2.0)}),+ )++ def test_a_smoothed_trend_returns_its_raw_daily_counts(self) -> None:+ self._signups((9, "Chrome"), (10, "Chrome"), (11, "Chrome"))+ insight = self._insight(+ series=[{"kind": "EventsNode", "event": "signed up"}], trendsFilter={"smoothingIntervals": 7}+ )++ found = get_insight_series(team=self.team, user=self.user, short_id=insight.short_id)++ assert found is not None+ self.assertEqual(sum(v for _, v in found.series["signed up"]), 3.0)++ def test_a_dashboard_filter_replaces_the_insight_filter_and_the_interval(self) -> None:+ self._signups((9, "Safari"), (10, "Safari"), (11, "Chrome"))+ insight = self._insight(+ series=[{"kind": "EventsNode", "event": "signed up"}],+ properties=[{"key": "$browser", "value": "Chrome", "operator": "exact", "type": "event"}],+ )+ dashboard = InsightDashboardContext(+ filters={+ "date_from": "-1d",+ "interval": "week",+ "properties": [{"key": "$browser", "value": "Safari", "operator": "exact", "type": "event"}],+ }+ )++ found = get_insight_series(team=self.team, user=self.user, short_id=insight.short_id, dashboard=dashboard)++ assert found is not None+ self.assertEqual((found.period, sum(v for _, v in found.series["signed up"])), ("week", 2.0))++ @parameterized.expand(+ [+ ("a table", {"kind": "TrendsQuery", "series": [], "trendsFilter": {"display": "ActionsTable"}}),+ ("a funnel", {"kind": "FunnelsQuery", "series": []}),+ (+ "a SQL insight",+ {"kind": "HogQLQuery", "query": "SELECT toDate(timestamp), count() FROM events GROUP BY 1"},+ ),+ (+ "a slope graph",+ {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode", "event": "signed up"}],+ "trendsFilter": {"display": "SlopeGraph"},+ },+ ),+ (+ "a daily trend on weekdays only",+ {+ "kind": "TrendsQuery",+ "series": [{"kind": "EventsNode", "event": "signed up"}],+ "dateRange": {"daysOfWeek": [1, 2, 3, 4, 5]},+ },+ ),+ ]+ )+ def test_an_insight_without_a_trend_series_returns_none(self, _name: str, source: dict[str, Any]) -> None:+ insight = Insight.objects.create(team=self.team, query={"kind": "InsightVizNode", "source": source})++ self.assertIsNone(get_insight_series(team=self.team, user=self.user, short_id=insight.short_id))++ def test_a_query_that_is_not_cached_yet_returns_none_and_does_not_block(self) -> None:+ self._signups((2, "Chrome"))+ insight = self._insight(series=[{"kind": "EventsNode", "event": "signed up"}])++ with (+ patch.object(insight_series, "EXECUTION_MODE", ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE),+ patch("posthog.hogql_queries.query_runner.QueryRunner.enqueue_async_calculation") as enqueue,+ ):+ found = get_insight_series(team=self.team, user=self.user, short_id=insight.short_id)++ self.assertEqual((found, enqueue.call_count), (None, 1))++ def test_an_insight_the_person_cannot_view_returns_none(self) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ insight = self._insight(series=[{"kind": "EventsNode", "event": "signed up"}])+ create_access_control(+ team_id=self.team.id, resource="insight", resource_id=str(insight.id), access_level="none"+ )+ reader = self._create_user("[email protected]")++ self.assertIsNone(get_insight_series(team=self.team, user=reader, short_id=insight.short_id))diff --git a/products/today/backend/logic/highlight_rules.py b/products/today/backend/logic/highlight_rules.pynew file mode 100644index 000000000000..2010453e29b1--- /dev/null+++ b/products/today/backend/logic/highlight_rules.py@@ -0,0 +1,40 @@+import re++from posthog.models.file_system.starred_products import has_starred_product++from .highlight_types import Context+++def human(value: float) -> str:+ size = abs(value)+ if size >= 999_500:+ return f"{value / 1_000_000:.1f}M"+ if size >= 9_950:+ return f"{value / 1000:.0f}k"+ if size >= 999.5:+ return f"{value / 1000:.1f}k"+ return f"{value:.0f}" if size >= 10 or float(value).is_integer() else f"{value:.1f}"+++def exact(value: float, decimal_places: int | None = None) -> str:+ if abs(value) >= 100_000:+ return human(value)+ if decimal_places is None:+ decimal_places = 0 if abs(value) >= 100 or float(value).is_integer() else 2+ return f"{value:,.{decimal_places}f}"+++def users(count: float) -> str:+ return "1 user" if count == 1 else f"{human(count)} users"+++def short(text: str, limit: int = 60) -> str:+ text = re.sub(r"\s+", " ", str(text or "")).replace('"', "").strip()+ text = re.sub(r"'([^']*)'", "‘\\1’", text).replace("'", "’")+ if len(text) <= limit:+ return text+ return text[:limit].rsplit(" ", 1)[0].rstrip(",;:(-– ")+++def uses_product(context: Context, *product_paths: str) -> bool:+ return has_starred_product(context.user, context.team, list(product_paths))diff --git a/products/today/backend/logic/highlight_series.py b/products/today/backend/logic/highlight_series.pynew file mode 100644index 000000000000..a384e37deeb0--- /dev/null+++ b/products/today/backend/logic/highlight_series.py@@ -0,0 +1,31 @@+import re+from datetime import date++from posthog.taxonomy.taxonomy import CORE_FILTER_DEFINITIONS_BY_GROUP++from products.product_analytics.backend.facade.contracts import InsightSeries++from .highlight_trends import UNCLEAR_LABEL, stale++CORE_EVENTS = CORE_FILTER_DEFINITIONS_BY_GROUP["events"]+++def pretty(name: str) -> str:+ event, separator, rest = name.partition(" · ")+ if event in CORE_EVENTS:+ return f"{CORE_EVENTS[event]['label']}{separator}{rest}"+ if re.fullmatch(r"[a-z0-9]+(_[a-z0-9]+)+", name):+ name = name.replace("_", " ")+ return name[0].upper() + name[1:]+ return name+++def usable_series(insight: InsightSeries, today: date) -> dict[str, list[tuple[date, float]]]:+ unclear = len(insight.series) > 1 or not insight.name+ return {+ name: points+ for name, points in insight.series.items()+ if "@" not in name+ and not (unclear and UNCLEAR_LABEL.search(pretty(name).strip()))+ and not stale(points, insight.period, today)+ }diff --git a/products/today/backend/logic/highlight_sources/home.py b/products/today/backend/logic/highlight_sources/home.pynew file mode 100644index 000000000000..b25dfe4c0f7b--- /dev/null+++ b/products/today/backend/logic/highlight_sources/home.py@@ -0,0 +1,110 @@+import json+from functools import partial+from urllib.parse import quote, urlencode++from products.dashboards.backend.facade.api import home_dashboard_insights+from products.product_analytics.backend.facade.api import get_insight_series+from products.product_analytics.backend.facade.contracts import InsightDashboardContext++from ...facade.enums import HighlightLabel+from ..highlight_rules import exact, short+from ..highlight_series import pretty, usable_series+from ..highlight_trends import BAD_METRIC, MONEY, UNKNOWN_DIRECTION, detect+from ..highlight_types import Candidate, Context, Found, Source++HOME_WORSE = "‘{name}’ {moved} by {pct}% last {period}"+HOME_WORSE_SERIES = "‘{name}’ ({series}) {moved} by {pct}% last {period}"+CHANGE = "{before} → {now}"+CHANGE_DAILY = "{before} → {now} a day on average"++HOME_TILES = 4+MIN_CHANGE_PCT = 15+MIN_VALUE = 200+MIN_DIFFERENCE = 50+++def find(context: Context) -> Found:+ home = home_dashboard_insights(team=context.team, user=context.user, limit=HOME_TILES)+ if home is None:+ return Found()+ found = [+ context.guard(+ f"tile {tile.insight_short_id}",+ partial(+ _tile,+ context,+ tile.insight_short_id,+ home.dashboard_id,+ InsightDashboardContext(+ filters=home.filters, tile_filters=tile.filters_overrides, variables=home.variables+ ),+ ),+ None,+ )+ for tile in home.tiles+ ]+ return Found(items=tuple(candidate for candidate in found if candidate is not None))+++def _url(short_id: str, dashboard_id: int, dashboard: InsightDashboardContext) -> str:+ overrides = {+ "variables_override": dashboard.variables,+ "filters_override": dashboard.filters,+ "tile_filters_override": dashboard.tile_filters,+ }+ params = {"dashboard": dashboard_id} | {+ key: json.dumps(value, separators=(",", ":")) for key, value in overrides.items() if value+ }+ return f"/insights/{short_id}?{urlencode(params, quote_via=quote)}"+++def _tile(context: Context, short_id: str, dashboard_id: int, dashboard: InsightDashboardContext) -> Candidate | None:+ insight = get_insight_series(team=context.team, user=context.user, short_id=short_id, dashboard=dashboard)+ if insight is None:+ return None+ series = usable_series(insight, context.today)+ if not series:+ return None+ period = insight.period+ name, points = max(series.items(), key=lambda item: sum(abs(v) for _, v in item[1]))+ average = period == "day" and name in insight.averaged_series+ _, values = detect(points, period, context.today, average)+ if len(values) < 2:+ return None+ now, before = values[-1], values[-2]+ if not now or not before or 0 < now / before <= 0.02:+ return None+ label = f"{insight.name} {name} {insight.event_name}"+ money = insight.value_format == "currency" or bool(MONEY.search(label))+ if abs(now) < 10 and not money:+ return None+ change = (now - before) / abs(before) * 100+ bad = bool(BAD_METRIC.search(label))+ if abs(change) < MIN_CHANGE_PCT or (change > 0) != bad or (not bad and UNKNOWN_DIRECTION.search(label)):+ return None+ if not money and (max(abs(now), abs(before)) < MIN_VALUE or abs(now - before) < MIN_DIFFERENCE):+ return None+ measured = short(pretty(name), 30) if len(series) > 1 and insight.name else ""+ return Candidate(+ key=f"home:{short_id}",+ label=HighlightLabel.RISK,+ family="home",+ importance=0.6,+ relevance=1.0,+ title=(HOME_WORSE_SERIES if measured else HOME_WORSE).format(+ name=short(insight.name or pretty(name), 60),+ series=measured,+ moved="increased" if change > 0 else "decreased",+ pct=f"{abs(change):.0f}",+ period="month" if period == "month" else "week",+ ),+ detail=(CHANGE_DAILY if average else CHANGE).format(+ now=exact(now, insight.decimal_places), before=exact(before, insight.decimal_places)+ ),+ url=_url(short_id, dashboard_id, dashboard),+ ref=short_id,+ series=values[-8:],+ )+++SOURCE = Source(name="home", find=find, scopes=("dashboard:read", "insight:read"))diff --git a/products/today/backend/logic/highlight_sources/routine.py b/products/today/backend/logic/highlight_sources/routine.pynew file mode 100644index 000000000000..8e1aa4676f13--- /dev/null+++ b/products/today/backend/logic/highlight_sources/routine.py@@ -0,0 +1,103 @@+from collections.abc import Sequence+from datetime import date, timedelta+from functools import partial++from django.utils import timezone++from posthog.models import FileSystemViewLog++from products.product_analytics.backend.facade.api import get_insight_series++from ...facade import contracts+from ...facade.enums import HighlightInterval, HighlightUnit+from ..highlight_rules import short+from ..highlight_series import pretty, usable_series+from ..highlight_trends import complete, detect+from ..highlight_types import Context, Found, Source++ROUTINE_WINDOW_DAYS = 28+DAILY_ROUTINE_DAYS = 8+WEEKLY_ROUTINE_WEEKS = 3+ROUTINE_CANDIDATES = 6+ROUTINE_TILES = 2+++def find(context: Context) -> Found:+ metrics: list[contracts.HighlightMetric] = []+ for short_id in _routine_insights(context):+ metric = context.guard(f"routine {short_id}", partial(_metric, context, short_id), None)+ if metric is not None:+ metrics.append(metric)+ if len(metrics) == ROUTINE_TILES:+ break+ return Found(pulse=tuple(metrics))+++def routine_days(view_days: Sequence[date], today: date) -> int:+ recent = {day for day in view_days if today - timedelta(days=ROUTINE_WINDOW_DAYS) < day <= today}+ daily = sum(1 for day in recent if day > today - timedelta(days=14)) >= DAILY_ROUTINE_DAYS+ weekly = len({day.isocalendar()[:2] for day in recent}) >= WEEKLY_ROUTINE_WEEKS+ return len(recent) if daily or weekly else 0+++def _routine_insights(context: Context) -> list[str]:+ views = FileSystemViewLog.objects.filter(+ team=context.team,+ user=context.user,+ type="insight",+ viewed_at__gte=timezone.now() - timedelta(days=ROUTINE_WINDOW_DAYS),+ ).values_list("ref", "view_days", "viewed_at")+ ranked = sorted(+ ((routine_days(days or [], context.today), viewed_at, ref) for ref, days, viewed_at in views), reverse=True+ )+ return [ref for days, _viewed_at, ref in ranked if days][:ROUTINE_CANDIDATES]+++def _metric(context: Context, short_id: str) -> contracts.HighlightMetric | None:+ insight = get_insight_series(team=context.team, user=context.user, short_id=short_id)+ if insight is None:+ return None+ series = usable_series(insight, context.today)+ if not series:+ return None+ name, points = max(series.items(), key=lambda item: sum(abs(v) for _, v in item[1]))+ period = insight.period+ _, values = detect(points, period, context.today, period == "day" and name in insight.averaged_series)+ if len(values) < 2:+ return None+ if period == "day":+ by_day = dict(complete(points, "day", context.today))+ line = [by_day.get(context.today - timedelta(days=offset), 0.0) for offset in range(28, 0, -1)]+ else:+ line = values[-12:]+ value_format = (+ contracts.HighlightValueFormat(+ format=insight.value_format,+ prefix=insight.value_prefix,+ postfix=insight.value_postfix,+ decimal_places=insight.decimal_places,+ )+ if insight.value_format not in (None, "numeric")+ or insight.value_prefix+ or insight.value_postfix+ or insight.decimal_places is not None+ else None+ )+ title = short(insight.name or pretty(name), 40)+ if len(series) > 1 and insight.name:+ measured = short(pretty(name), 18)+ title = f"{short(insight.name, 37 - len(measured))} ({measured})"+ return contracts.HighlightMetric(+ key=f"insight:{short_id}",+ name=title,+ value=values[-1],+ unit=HighlightUnit.NUMBER,+ change_pct=round((values[-1] - values[-2]) / abs(values[-2]) * 100, 1) if values[-2] else None,+ series=line,+ interval=HighlightInterval(period),+ url=f"/insights/{short_id}",+ value_format=value_format,+ )+++SOURCE = Source(name="routine", find=find, scopes=("insight:read",), pulse_order=1)diff --git a/products/today/backend/logic/highlight_trends.py b/products/today/backend/logic/highlight_trends.pynew file mode 100644index 000000000000..a79f6f067719--- /dev/null+++ b/products/today/backend/logic/highlight_trends.py@@ -0,0 +1,150 @@+import re+import math+import statistics+from datetime import date, timedelta++from posthog.dataclasses import frozen++WEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]+BAD_METRIC = re.compile(+ r"(?i)(error|fail|latency|duration|(load|response|build|query|wait) time|time to|p50|p90|p95|p99|cost|spend|churn"+ r"|bounce|cancel|refund|exception|crash|timeout|lost|contraction|downgrade|abort|(?<![a-z])rage)"+)+UNKNOWN_DIRECTION = re.compile(r"(?i)(share|split| vs\.? |(?<![a-z])ratios?(?![a-z])|%|percent|rate by)")+UNCLEAR_LABEL = re.compile(+ r"(?i)^(other|others|series \d+|null|none|unknown|\$.*|(sum|count|avg|unique|total)_.*)$|, series \d+$"+)+MONEY = re.compile(r"(?i)(revenue|\barr\b|\bmrr\b|\bnrr\b|spend|cost|usd|\$(?![a-z_])|invoice)")+MAX_FILLED_DAYS = 120+++@frozen+class Detection:+ kind: str+ strength: float+ direction: int+ pct: float | None = None+ now: float | None = None+ usual: float | None = None+ weekday: str | None = None+ same_weekday: bool = False+++def complete(points: list[tuple[date, float]], period: str, today: date) -> list[tuple[date, float]]:+ if period == "day":+ return [(d, v) for d, v in points if d < today]+ if period == "week":+ return [(d, v) for d, v in points if d + timedelta(days=7) <= today]+ return [(d, v) for d, v in points if (d.year, d.month) < (today.year, today.month)]+++def stale(points: list[tuple[date, float]], period: str, today: date) -> bool:+ usable = complete(points, period, today)+ if not usable:+ return True+ last = usable[-1][0]+ step = {"day": timedelta(days=1), "week": timedelta(days=7)}.get(period)+ after = last + step if step else (last.replace(day=1) + timedelta(days=32)).replace(day=1)+ return bool(complete([(after, 0.0)], period, today))+++def fill_days(points: list[tuple[date, float]]) -> list[tuple[date, float]]:+ if not points:+ return points+ known = dict(points)+ end = points[-1][0]+ day, out = max(points[0][0], end - timedelta(days=MAX_FILLED_DAYS)), []+ while day <= end:+ out.append((day, known.get(day, 0.0)))+ day += timedelta(days=1)+ return out+++def windows(points: list[tuple[date, float]], period: str, average: bool = False) -> list[float]:+ values = [v for _, v in points]+ if period != "day":+ return values+ count = len(values) // 7+ totals = [sum(values[len(values) - 7 * i : len(values) - 7 * (i - 1)]) for i in range(count, 0, -1)]+ return [total / 7 for total in totals] if average else totals+++def zscore(last: float, prior: list[float]) -> float | None:+ if len(prior) < 2:+ return None+ spread, mean = statistics.pstdev(prior), statistics.mean(prior)+ if spread == 0:+ return None if last == mean else math.copysign(9.9, last - mean)+ return (last - mean) / spread+++def detect(+ points: list[tuple[date, float]], period: str, today: date, average: bool = False+) -> tuple[list[Detection], list[float]]:+ usable = complete(points, period, today)+ found: list[Detection] = []+ if period == "day":+ usable = fill_days(usable)+ daily = [v for _, v in usable]+ if len(daily) >= 17 and all(v == 0 for v in daily[-3:]) and statistics.mean(daily[-17:-3]) >= 100:+ found.append(Detection(kind="went_quiet", strength=0.7, direction=-1))+ found.extend(_same_weekday(usable))+ values = windows(usable, period, average)+ if len(values) >= 6 and all(v == 0 for v in values[-6:]) and any(v != 0 for v in values[:-6]):+ found.append(Detection(kind="flatline", strength=0.6, direction=-1))+ if len(values) < 4 or values[-1] == 0:+ return found, values+ last, previous = values[-1], values[-2]+ changes = [values[i] / values[i - 1] - 1 for i in range(max(1, len(values) - 9), len(values)) if values[i - 1]]+ change_z = zscore(changes[-1], changes[:-1]) if len(changes) >= 4 and previous else None+ if change_z is not None and abs(change_z) >= 2 and abs(changes[-1]) >= 0.1:+ found.append(+ Detection(+ kind="spike",+ strength=min(1.0, 0.6 + 0.1 * (abs(change_z) - 2)),+ direction=1 if changes[-1] > 0 else -1,+ )+ )+ steps = [values[-3] - values[-4], values[-2] - values[-3], values[-1] - values[-2]]+ if (+ (all(s > 0 for s in steps) or all(s < 0 for s in steps))+ and values[-4]+ and abs(values[-1] / values[-4] - 1) >= 0.2+ ):+ direction = 1 if steps[0] > 0 else -1+ history = [values[i] - values[i - 1] for i in range(max(1, len(values) - 9), len(values) - 3)]+ usual = (sum(1 for h in history if h > 0) - sum(1 for h in history if h < 0)) if len(history) >= 3 else 0+ if usual * direction <= 0:+ found.append(Detection(kind="trend", strength=0.6, direction=direction))+ earlier = statistics.mean(values[:-1][-3:])+ if earlier > 0 and (last / earlier >= 3 or last / earlier <= 1 / 3) and max(last, earlier) >= 100:+ found.append(Detection(kind="level_shift", strength=0.8, direction=1 if last > earlier else -1))+ return found, values+++def _same_weekday(usable: list[tuple[date, float]]) -> list[Detection]:+ start = next((i for i, (_, v) in enumerate(usable) if v != 0), 0)+ days = usable[start:]+ if len(days) < 8:+ return []+ last_day, last_value = days[-1]+ same = [v for d, v in days[:-1] if d.weekday() == last_day.weekday()]+ use_same = len(same) >= 3+ base = same[-4:] if use_same else [v for _, v in days[-8:-1]]+ score, mean = zscore(last_value, base), statistics.mean(base)+ if score is None or abs(score) < 3 or not mean or abs(last_value / mean - 1) < 0.15:+ return []+ if abs(last_value - mean) < max(5, 3 * math.sqrt(max(mean, 1))):+ return []+ return [+ Detection(+ kind="same_weekday",+ strength=0.7,+ direction=1 if last_value > mean else -1,+ pct=(last_value / mean - 1) * 100,+ now=last_value,+ usual=mean,+ weekday=WEEKDAYS[last_day.weekday()],+ same_weekday=use_same,+ )+ ]diff --git a/products/today/backend/tests/test_highlight_insights.py b/products/today/backend/tests/test_highlight_insights.pynew file mode 100644index 000000000000..e3b50525796c--- /dev/null+++ b/products/today/backend/tests/test_highlight_insights.py@@ -0,0 +1,255 @@+import re+from datetime import date, timedelta+from types import SimpleNamespace+from typing import Any, cast++import time_machine+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.models import FileSystemViewLog++from products.dashboards.backend.facade.api import HomeDashboardInsights, HomeDashboardTile+from products.product_analytics.backend.facade.contracts import InsightDashboardContext, InsightSeries+from products.today.backend.logic.highlight_rules import human, short+from products.today.backend.logic.highlight_sources import home, routine+from products.today.backend.logic.highlight_trends import BAD_METRIC, MONEY, UNCLEAR_LABEL, UNKNOWN_DIRECTION+from products.today.backend.logic.highlight_types import Context++TODAY = date(2026, 10, 13)+++def days(values: list[float]) -> list[tuple[date, float]]:+ start = TODAY - timedelta(days=len(values))+ return [(start + timedelta(days=i), v) for i, v in enumerate(values)]+++def insight(series: dict[str, list[tuple[date, float]]], **fields: Any) -> InsightSeries:+ return InsightSeries(+ **{"short_id": "abc", "name": "By browser", "period": "day", "averaged_series": [], "event_name": "", **fields},+ series=series,+ )+++class TestInsightRules(SimpleTestCase):+ @parameterized.expand(+ [+ ("opened on most days", [TODAY - timedelta(days=d) for d in range(10)], 10),+ ("opened every Monday", [TODAY - timedelta(days=1 + 7 * w) for w in range(4)], 4),+ ("opened on many days of one week", [TODAY - timedelta(days=d) for d in range(5)], 0),+ ("a habit that stopped a month ago", [TODAY - timedelta(days=30 + 7 * w) for w in range(4)], 0),+ ]+ )+ def test_routine_days(self, _name: str, view_days: list[date], expected: int) -> None:+ self.assertEqual(routine.routine_days(view_days, TODAY), expected)++ @parameterized.expand(+ [+ (+ "long text cuts at a word with no ellipsis",+ "Cannot read properties of undefined (reading 'earliest')",+ 30,+ "Cannot read properties of",+ ),+ (+ "straight quotes become curly",+ "Cannot read properties of null (reading 'price') in user's cart",+ 80,+ "Cannot read properties of null (reading ‘price’) in user’s cart",+ ),+ ]+ )+ def test_short(self, _name: str, text: str, limit: int, expected: str) -> None:+ self.assertEqual(short(text, limit), expected)++ @parameterized.expand([(842, "842"), (1240, "1.2k"), (9_960, "10k"), (999_960, "1.0M"), (2_350_000, "2.4M")])+ def test_human_never_prints_a_thousand_of_a_unit(self, value: float, expected: str) -> None:+ self.assertEqual(human(value), expected)+++DROP = days([1000.0] * 49 + [550.0] * 7)+ALTERNATING = days([v for week in range(8) for v in [1000.0 if week % 2 == 0 else 800.0] * 7])+++class TestHomeTiles(SimpleTestCase):+ @parameterized.expand(+ [+ ("fewer failures is good news", DROP, "payment failed", False, ["Chrome"], None),+ (+ "fewer sign-ups is bad news",+ DROP,+ "signed up",+ False,+ ["Chrome"],+ ("‘By browser’ decreased by 45% last week", "7,000 → 3,850"),+ ),+ (+ "daily users compare daily averages",+ DROP,+ "signed up",+ True,+ ["Chrome"],+ ("‘By browser’ decreased by 45% last week", "1,000 → 550 a day on average"),+ ),+ (+ "several series name the series measured",+ DROP,+ "",+ False,+ ["signed up · Chrome", "logged in · Chrome"],+ ("‘By browser’ (signed up · Chrome) decreased by 45% last week", "7,000 → 3,850"),+ ),+ (+ "a drop that no detector flags still counts",+ ALTERNATING,+ "signed up",+ False,+ ["Chrome"],+ ("‘By browser’ decreased by 20% last week", "7,000 → 5,600"),+ ),+ (+ "built-in events read as their names",+ DROP,+ "",+ False,+ ["$pageview", "$autocapture"],+ ("‘By browser’ (Pageview) decreased by 45% last week", "7,000 → 3,850"),+ ),+ (+ "net revenue rising toward zero is good news",+ days([-30.0] * 49 + [-20.0] * 7),+ "revenue",+ False,+ ["Chrome"],+ None,+ ),+ (+ "revenue falling below zero is bad news",+ days([30.0] * 49 + [-10.0] * 7),+ "revenue",+ False,+ ["Chrome"],+ ("‘By browser’ decreased by 133% last week", "210 → -70"),+ ),+ (+ "small money values keep their cents",+ days([0.2] * 49 + [0.1] * 7),+ "revenue",+ False,+ ["Chrome"],+ ("‘By browser’ decreased by 50% last week", "1.40 → 0.70"),+ ),+ (+ "a currency format counts as money",+ days([6.0] * 49 + [3.0] * 7),+ "",+ False,+ ["Chrome"],+ ("‘By browser’ decreased by 50% last week", "42 → 21"),+ "currency",+ ),+ ]+ )+ def test_a_home_tile_shows_when_it_moves_the_wrong_way(+ self,+ _name: str,+ points: list[tuple[date, float]],+ event_name: str,+ averaged: bool,+ labels: list[str],+ expected: tuple[str, str] | None,+ value_format: str | None = None,+ ) -> None:+ found_insight = insight(+ {name: [(day, value / (index + 1)) for day, value in points] for index, name in enumerate(labels)},+ averaged_series=labels if averaged else [],+ event_name=event_name,+ value_format=value_format,+ )+ context = cast(+ Context,+ SimpleNamespace(+ team=SimpleNamespace(id=1),+ user=SimpleNamespace(id=2),+ today=TODAY,+ guard=lambda _name, provider, _default: provider(),+ ),+ )+ home_tiles = HomeDashboardInsights(+ dashboard_id=7,+ filters={},+ variables=None,+ tiles=(HomeDashboardTile(insight_short_id="abc", filters_overrides=None),),+ )++ with (+ patch.object(home, "home_dashboard_insights", return_value=home_tiles),+ patch.object(home, "get_insight_series", return_value=found_insight),+ ):+ found = home.find(context).items++ self.assertEqual([(c.title, c.detail) for c in found], [expected] if expected else [])++ @parameterized.expand(+ [+ ("$pageview", MONEY, False),+ ("Revenue by plan", MONEY, True),+ ("Spend in $", MONEY, True),+ ("$5 orders", MONEY, True),+ ("Average order value", BAD_METRIC, False),+ ("payment_failed", BAD_METRIC, True),+ ("Rage clicks", BAD_METRIC, True),+ ("Registrations", UNKNOWN_DIRECTION, False),+ ("Conversion ratio", UNKNOWN_DIRECTION, True),+ ("Total revenue", UNCLEAR_LABEL, False),+ ("sum_amount", UNCLEAR_LABEL, True),+ ("Series 2", UNCLEAR_LABEL, True),+ ]+ )+ def test_metric_names_match_whole_terms(self, label: str, pattern: re.Pattern[str], matches: bool) -> None:+ self.assertEqual(bool(pattern.search(label)), matches)++ def test_a_home_link_opens_the_insight_as_the_dashboard_shows_it(self) -> None:+ dashboard = InsightDashboardContext(+ filters={"properties": [{"key": "$browser", "value": "Safari"}]}, tile_filters={"date_from": "-7d"}+ )++ self.assertEqual(+ home._url("abc", 7, dashboard),+ "/insights/abc?dashboard=7"+ "&filters_override=%7B%22properties%22%3A%5B%7B%22key%22%3A%22%24browser%22%2C%22value%22%3A%22Safari%22%7D%5D%7D"+ "&tile_filters_override=%7B%22date_from%22%3A%22-7d%22%7D",+ )+++class TestRoutineInsights(BaseTest):+ @time_machine.travel("2026-10-13T12:00:00Z", tick=False)+ def test_an_insight_opened_most_days_shows_its_last_week_in_the_pulse(self) -> None:+ FileSystemViewLog.objects.create(+ team=self.team,+ user=self.user,+ type="insight",+ ref="abc",+ view_days=[TODAY - timedelta(days=d) for d in range(10)],+ )+ points = [(TODAY - timedelta(days=d), 2.0 if d <= 7 else 1.0) for d in range(14, 0, -1)]+ found_insight = insight(+ {"exported_report": points, "$pageview": [(day, value / 2) for day, value in points]},+ name="Files opened",+ value_format="currency",+ )++ with patch.object(routine, "get_insight_series", return_value=found_insight):+ pulse = routine.find(Context(self.team, self.user, TODAY)).pulse++ self.assertEqual(+ [+ (m.name, m.value, m.change_pct, m.interval, m.url, m.value_format and m.value_format.format)+ for m in pulse+ ],+ [("Files opened (Exported report)", 14.0, 100.0, "day", "/insights/abc", "currency")],+ )diff --git a/products/today/backend/tests/test_highlight_trends.py b/products/today/backend/tests/test_highlight_trends.pynew file mode 100644index 000000000000..4328eb0c1aed--- /dev/null+++ b/products/today/backend/tests/test_highlight_trends.py@@ -0,0 +1,79 @@+from collections.abc import Sequence+from datetime import date, timedelta++from django.test import SimpleTestCase++from parameterized import parameterized++from products.today.backend.logic.highlight_trends import MAX_FILLED_DAYS, detect, fill_days, stale++TODAY = date(2026, 10, 13)+++def days(values: Sequence[float]) -> list[tuple[date, float]]:+ start = TODAY - timedelta(days=len(values))+ return [(start + timedelta(days=i), v) for i, v in enumerate(values)]+++def weeks(values: Sequence[float]) -> list[tuple[date, float]]:+ start = TODAY - timedelta(weeks=len(values) + 1)+ return [(start + timedelta(weeks=i), v) for i, v in enumerate(values)]+++class TestHighlightTrends(SimpleTestCase):+ @parameterized.expand(+ [+ ("steady growth is not news", weeks([100, 110, 121, 133, 146, 161, 177, 195, 214]), "week", set()),+ ("a zero last period is not a drop", weeks([500, 520, 480, 510, 0]), "week", set()),+ ("a 5x jump is a level shift", weeks([200, 210, 190, 1000]), "week", {"level_shift"}),+ ("an issue that stops went quiet", days([400] * 25 + [0, 0, 0]), "day", {"went_quiet"}),+ ]+ )+ def test_detectors(self, _name: str, points: list[tuple[date, float]], period: str, expected: set[str]) -> None:+ found, _ = detect(points, period, TODAY)++ self.assertEqual({d.kind for d in found} & {"spike", "trend", "level_shift", "went_quiet"}, expected)++ @parameterized.expand(+ [+ (+ "a drop is measured against the same weekday",+ [1000.0] * 6 + [1010.0] + [1000.0] * 6 + [990.0] + [1000.0] * 13 + [500.0],+ [(True, -1)],+ ),+ (+ "a drop on a tiny metric is not news",+ [1.0, 2.0, 1.0, 2.0, 1.0, 2.0, 1.0] * 3 + [1.0, 2.0, 1.0, 2.0, 1.0, 2.0, 0.0],+ [],+ ),+ ]+ )+ def test_same_weekday(self, _name: str, values: list[float], expected: list[tuple[bool, int]]) -> None:+ found, _ = detect(days(values), "day", TODAY)++ self.assertEqual([(d.same_weekday, d.direction) for d in found if d.kind == "same_weekday"], expected)++ @parameterized.expand(+ [+ ("daily data up to yesterday", days([5.0] * 10), "day", False),+ ("daily data that stopped a week ago", days([5.0] * 10)[:-7], "day", True),+ (+ "weekly data up to last week",+ [(TODAY - timedelta(weeks=w), 5.0) for w in range(6, 0, -1)],+ "week",+ False,+ ),+ ("weekly data that stopped a month ago", weeks([5.0] * 6)[:-2], "week", True),+ ]+ )+ def test_stale(self, _name: str, points: list[tuple[date, float]], period: str, expected: bool) -> None:+ self.assertEqual(stale(points, period, TODAY), expected)++ def test_filling_missing_days_stops_at_the_supported_lookback(self) -> None:+ points = [(date(1, 1, 1), 1.0), (TODAY - timedelta(days=2), 1.0), (TODAY - timedelta(days=1), 1.0)]++ filled = fill_days(points)++ self.assertEqual(+ (len(filled), filled[0][0]), (MAX_FILLED_DAYS + 1, TODAY - timedelta(days=1 + MAX_FILLED_DAYS))+ )diff --git a/tach.toml b/tach.tomlindex b40d870027e9..6ec2f3238bf1 100644--- a/tach.toml+++ b/tach.toml@@ -1645,6 +1645,8 @@ depends_on = ["posthog","products.access_control","products.conversations",+ "products.dashboards",+ "products.product_analytics","products.signals","products.tasks",]