: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 key metrics in the pulse and weekday drops as items (#117322)
Shy Alter529adb724897
diff --git a/products/actions/backend/facade/api.py b/products/actions/backend/facade/api.pyindex 0b0ab8cc4758..5878d35ca360 100644--- a/products/actions/backend/facade/api.py+++ b/products/actions/backend/facade/api.py@@ -48,3 +48,12 @@ def action_filter_conditions(*, team: Team, action_ids: Sequence[int]) -> dict[i# One action with an uncompilable step must not cost the caller the rest of them.continuereturn conditions+++def action_revisions(*, team: Team, action_ids: Sequence[int]) -> dict[int, str]:+ return {+ action_id: updated_at.isoformat()+ for action_id, updated_at in Action.objects.filter(+ team__project_id=team.project_id, id__in=action_ids, deleted=False+ ).values_list("id", "updated_at")+ }diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.pyindex a902507d7965..f891aa533bef 100644--- a/products/customer_analytics/backend/facade/api.py+++ b/products/customer_analytics/backend/facade/api.py@@ -114,6 +114,7 @@ from products.customer_analytics.backend.logic import (customer_tasks as _customer_tasks_logic,feature_request_github as _feature_request_github_logic,feature_requests as _feature_requests_logic,+ key_metrics as _key_metrics_logic,ownership as _ownership,relationships as _relationships_logic,user_customer_analytics_config as _user_customer_analytics_config_logic,@@ -5752,3 +5753,11 @@ def list_announcement_channels(team_id: int) -> list[contracts.AnnouncementChannexcept SupportSlackChannelsUnavailable:logger.warning("announcement_channels_unavailable", team_id=team_id)return []+++def get_key_metrics(*, team: Team, user: "User") -> list[contracts.KeyMetric]:+ return _key_metrics_logic.key_metrics(team, user)+++def get_key_metrics_fingerprint(team: Team) -> str:+ return _key_metrics_logic.key_metrics_fingerprint(team)diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.pyindex b984a6cad771..6e935fcec9c4 100644--- a/products/customer_analytics/backend/facade/contracts.py+++ b/products/customer_analytics/backend/facade/contracts.py@@ -1503,3 +1503,13 @@ class UpdateCustomerTaskInput:assigned_to_id_provided: bool = Falsedue_at_provided: bool = Falsestatus_provided: bool = False+++@dataclass(frozen=True)+class KeyMetric:+ key: str+ name: str+ people: bool+ daily: list[tuple[date, float]]+ this_week: float+ last_week: floatdiff --git a/products/customer_analytics/backend/logic/key_metrics.py b/products/customer_analytics/backend/logic/key_metrics.pynew file mode 100644index 000000000000..817a8f4a8cae--- /dev/null+++ b/products/customer_analytics/backend/logic/key_metrics.py@@ -0,0 +1,142 @@+import json+import hashlib+from datetime import timedelta+from typing import Any, cast++from django.utils import timezone++from posthog.schema import HogQLQueryModifiers++from posthog.hogql import ast+from posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.parser import parse_expr, parse_select+from posthog.hogql.property import property_to_expr+from posthog.hogql.query import execute_hogql_query+from posthog.hogql.visitor import clone_expr++from posthog.models import Team, User++from products.actions.backend.facade.api import action_filter_conditions, action_revisions+from products.customer_analytics.backend.facade.contracts import KeyMetric++KEY_METRICS = {+ "signup_event": "Sign-ups",+ "payment_event": "Payments",+ "subscription_event": "Subscriptions",+ "activity_event": "Active users",+}+PEOPLE_METRIC = "activity_event"+DAYS = 35+QUERY_TIMEOUT_SECONDS = 10+DAILY = (+ "SELECT toDate(timestamp) AS day FROM events"+ " WHERE timestamp >= toStartOfDay(now()) - INTERVAL {days} DAY AND timestamp < toStartOfDay(now())"+ " AND {match} AND {test_accounts}"+ " GROUP BY day ORDER BY day"+)+WEEKLY_PEOPLE = (+ "SELECT uniqIf(person_id, timestamp >= toStartOfDay(now()) - INTERVAL 7 DAY),"+ " uniqIf(person_id, timestamp < toStartOfDay(now()) - INTERVAL 7 DAY) FROM events"+ " WHERE timestamp >= toStartOfDay(now()) - INTERVAL 14 DAY AND timestamp < toStartOfDay(now())"+ " AND {match} AND {test_accounts}"+)+++def _configured_nodes(team: Team) -> dict[str, dict[str, Any]]:+ config = team.customer_analytics_config+ return {+ key: node+ for key in KEY_METRICS+ if isinstance(node := getattr(config, key), dict) and node.get("kind") in ("EventsNode", "ActionsNode")+ }+++def _action_ids(nodes: dict[str, dict[str, Any]]) -> list[int]:+ return [int(node["id"]) for node in nodes.values() if node["kind"] == "ActionsNode"]+++def _condition(node: dict[str, Any], team: Team, actions: dict[int, ast.Expr]) -> ast.Expr:+ if node["kind"] == "ActionsNode":+ match = clone_expr(actions[int(node["id"])])+ elif node.get("event"):+ match = parse_expr("event = {event}", placeholders={"event": ast.Constant(value=node["event"])})+ else:+ match = ast.Constant(value=True)+ if node.get("properties"):+ return ast.And(exprs=[match, property_to_expr(node["properties"], team)])+ return match+++def _select(query: str, **placeholders: ast.Expr) -> ast.SelectQuery:+ return cast(ast.SelectQuery, parse_select(query, placeholders=placeholders))+++def _run(query: ast.SelectQuery, team: Team, user: User, query_type: str) -> list[Any]:+ return execute_hogql_query(+ query,+ team,+ query_type=query_type,+ user=user,+ modifiers=HogQLQueryModifiers(convertToProjectTimezone=True),+ settings=HogQLGlobalSettings(max_execution_time=QUERY_TIMEOUT_SECONDS, timeout_overflow_mode="throw"),+ ).results+++def key_metrics_fingerprint(team: Team) -> str:+ nodes = _configured_nodes(team)+ payload = [nodes, action_revisions(team=team, action_ids=_action_ids(nodes)), team.test_account_filters]+ return hashlib.sha256(json.dumps(payload, sort_keys=True, default=str).encode()).hexdigest()[:16]+++def key_metrics(team: Team, user: User) -> list[KeyMetric]:+ nodes = _configured_nodes(team)+ actions = action_filter_conditions(team=team, action_ids=_action_ids(nodes))+ conditions = {+ key: _condition(node, team, actions)+ for key, node in nodes.items()+ if node["kind"] == "EventsNode" or int(node["id"]) in actions+ }+ if not conditions:+ return []+ test_accounts = property_to_expr(team.test_account_filters or [], team)++ daily = _select(+ DAILY,+ days=ast.Constant(value=DAYS),+ match=ast.Or(exprs=[clone_expr(c) for c in conditions.values()]),+ test_accounts=clone_expr(test_accounts),+ )+ daily.select.extend(+ ast.Alias(+ alias=key,+ expr=parse_expr(+ "uniqIf(person_id, {match})" if key == PEOPLE_METRIC else "countIf({match})",+ placeholders={"match": clone_expr(condition)},+ ),+ )+ for key, condition in conditions.items()+ )+ by_day = {row[0]: row[1:] for row in _run(daily, team, user, "customer_analytics_key_metrics_daily")}++ today = timezone.now().astimezone(team.timezone_info).date()+ days = [today - timedelta(days=offset) for offset in range(DAYS, 0, -1)]+ metrics = []+ for index, (key, condition) in enumerate(conditions.items()):+ points = [(day, float(by_day[day][index]) if day in by_day else 0.0) for day in days]+ if key == PEOPLE_METRIC:+ weekly_query = _select(WEEKLY_PEOPLE, match=condition, test_accounts=clone_expr(test_accounts))+ weekly = _run(weekly_query, team, user, "customer_analytics_key_metrics_weekly")+ this_week, last_week = (float(value) for value in weekly[0])+ else:+ this_week, last_week = sum(v for _, v in points[-7:]), sum(v for _, v in points[-14:-7])+ metrics.append(+ KeyMetric(+ key=key,+ name=nodes[key].get("custom_name") or KEY_METRICS[key],+ people=key == PEOPLE_METRIC,+ daily=points,+ this_week=this_week,+ last_week=last_week,+ )+ )+ return metricsdiff --git a/products/customer_analytics/backend/test/test_key_metrics.py b/products/customer_analytics/backend/test/test_key_metrics.pynew file mode 100644index 000000000000..7fbcd4bb01b3--- /dev/null+++ b/products/customer_analytics/backend/test/test_key_metrics.py@@ -0,0 +1,128 @@+from datetime import datetime, timedelta++import time_machine+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events++from django.utils import timezone++from parameterized import parameterized++from posthog.constants import AvailableFeature+from posthog.models import PropertyDefinition+from posthog.test.persons import create_person++from products.access_control.backend.facade.api import upsert_property_access_control+from products.access_control.backend.facade.contracts import PropertyAccessLevel, UpsertPropertyAccessControlInput+from products.actions.backend.models.action import Action+from products.customer_analytics.backend.facade.api import get_key_metrics, get_key_metrics_fingerprint+++class TestKeyMetrics(ClickhouseTestMixin, BaseTest):+ def _midnight(self) -> datetime:+ return timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)++ @parameterized.expand(+ [+ ("an unrestricted viewer", False, [], {"signup_event": (7.0, 7.0), "activity_event": (2.0, 1.0)}),+ (+ "a viewer who cannot read the browser",+ True,+ [],+ {"signup_event": (0.0, 0.0), "activity_event": (2.0, 1.0)},+ ),+ (+ "a project that marks Chrome as a test account",+ False,+ [{"key": "$browser", "value": "Chrome", "operator": "is_not", "type": "event"}],+ {"signup_event": (0.0, 0.0), "activity_event": (1.0, 0.0)},+ ),+ ]+ )+ def test_key_metrics_count_filtered_events_and_weekly_unique_people(+ self,+ _name: str,+ restricted: bool,+ test_account_filters: list[dict[str, str]],+ expected: dict[str, tuple[float, float]],+ ) -> None:+ self.team.test_account_filters = test_account_filters+ self.team.save()+ self.organization.available_product_features = [+ {"key": AvailableFeature.PROPERTY_ACCESS_CONTROL, "name": AvailableFeature.PROPERTY_ACCESS_CONTROL}+ ]+ self.organization.save()+ viewer = self._create_user("[email protected]")+ if restricted:+ definition = PropertyDefinition.objects.create(+ team=self.team, name="$browser", type=PropertyDefinition.Type.EVENT+ )+ upsert_property_access_control(+ team_id=self.team.id,+ created_by_id=None,+ input=UpsertPropertyAccessControlInput(+ access_level=PropertyAccessLevel.NONE,+ property_definition_id=str(definition.id),+ organization_member_id=viewer.organization_memberships.get().id,+ ),+ )+ config = self.team.customer_analytics_config+ config.signup_event = {+ "kind": "EventsNode",+ "event": None,+ "properties": [{"key": "$browser", "value": "Chrome", "operator": "exact", "type": "event"}],+ }+ config.activity_event = {"kind": "EventsNode", "event": "opened_file"}+ config.payment_event = {"kind": "ActionsNode", "id": 999_999}+ config.save()+ for browser, days in (("Chrome", 20), ("Firefox", 7)):+ create_person(team=self.team, distinct_ids=[f"person-{browser}"])+ for day in range(1, days + 1):+ _create_event(+ team=self.team,+ event="opened_file",+ distinct_id=f"person-{browser}",+ properties={"$browser": browser},+ timestamp=self._midnight() - timedelta(days=day) + timedelta(hours=12),+ )+ flush_persons_and_events()++ metrics = get_key_metrics(team=self.team, user=viewer)++ self.assertEqual(+ ({m.key: (m.this_week, m.last_week) for m in metrics}, {m.key: len(m.daily) for m in metrics}),+ (expected, {"signup_event": 35, "activity_event": 35}),+ )++ def test_the_fingerprint_changes_only_when_an_action_or_the_test_account_filters_change(self) -> None:+ with time_machine.travel("2026-03-02T09:00:00Z", tick=False) as traveller:+ action = Action.objects.create(+ team=self.team,+ name="Paid",+ steps_json=[+ {+ "event": "paid",+ "properties": [+ {"key": "plan_started", "value": "-7d", "operator": "is_date_after", "type": "event"}+ ],+ }+ ],+ )+ config = self.team.customer_analytics_config+ config.payment_event = {"kind": "ActionsNode", "id": action.id}+ config.save()+ prints = [get_key_metrics_fingerprint(self.team)]+ traveller.shift(timedelta(hours=1))+ prints.append(get_key_metrics_fingerprint(self.team))+ action.steps_json = [{"event": "checkout completed"}]+ action.save()+ prints.append(get_key_metrics_fingerprint(self.team))+ action.deleted = True+ action.save()+ prints.append(get_key_metrics_fingerprint(self.team))+ self.team.test_account_filters = [+ {"key": "email", "value": "@example.com", "operator": "not_icontains", "type": "person"}+ ]+ self.team.save()+ prints.append(get_key_metrics_fingerprint(self.team))++ self.assertEqual((prints[0], len(set(prints[1:]))), (prints[1], 4))diff --git a/products/today/backend/logic/highlight_sources/key_metrics.py b/products/today/backend/logic/highlight_sources/key_metrics.pynew file mode 100644index 000000000000..2f7d599e6b34--- /dev/null+++ b/products/today/backend/logic/highlight_sources/key_metrics.py@@ -0,0 +1,59 @@+from products.customer_analytics.backend.facade.api import get_key_metrics, get_key_metrics_fingerprint+from products.customer_analytics.backend.facade.contracts import KeyMetric++from ...facade import contracts+from ...facade.enums import HighlightLabel, HighlightUnit+from ..highlight_rules import exact+from ..highlight_trends import detect+from ..highlight_types import Candidate, Context, Found, Source++KEY_METRIC_DAY = {+ True: "‘{name}’ increased by {pct}% yesterday",+ False: "‘{name}’ decreased by {pct}% yesterday",+}+KEY_METRIC_DAY_DETAIL = "{now} yesterday · {usual} on an average {weekday}"+KEY_METRIC_DAY_DETAIL_WEEK = "{now} yesterday · {usual} a day over the week before"+++def find(context: Context) -> Found:+ metrics = context.daily(+ f"key_metrics:{context.user.id}:{get_key_metrics_fingerprint(context.team)}",+ lambda: get_key_metrics(team=context.team, user=context.user),+ )+ shown = [metric for metric in metrics if metric.this_week or metric.last_week]+ candidates = [candidate for metric in shown if (candidate := _same_weekday(context, metric)) is not None]+ return Found(items=tuple(candidates), pulse=tuple(_tile(metric) for metric in shown))+++def _tile(metric: KeyMetric) -> contracts.HighlightMetric:+ return contracts.HighlightMetric(+ key=metric.key,+ name=metric.name,+ value=metric.this_week,+ unit=HighlightUnit.PEOPLE if metric.people else HighlightUnit.EVENTS,+ change_pct=round((metric.this_week / metric.last_week - 1) * 100, 1) if metric.last_week else None,+ series=[v for _, v in metric.daily[-28:]],+ )+++def _same_weekday(context: Context, metric: KeyMetric) -> Candidate | None:+ detections, _ = detect(metric.daily, "day", context.today)+ found = next((d for d in detections if d.kind == "same_weekday"), None)+ if found is None:+ return None+ up = found.direction > 0+ return Candidate(+ key=f"key_metric:{metric.key}",+ label=HighlightLabel.OPPORTUNITY if up else HighlightLabel.RISK,+ family="key_metrics",+ importance=0.95 * found.strength,+ relevance=0.6,+ title=KEY_METRIC_DAY[up].format(name=metric.name, pct=f"{abs(found.pct or 0):.0f}"),+ detail=(KEY_METRIC_DAY_DETAIL if found.same_weekday else KEY_METRIC_DAY_DETAIL_WEEK).format(+ now=exact(found.now or 0), usual=exact(found.usual or 0, 0), weekday=found.weekday+ ),+ series=[v for _, v in metric.daily[-14:]],+ )+++SOURCE = Source(name="key_metrics", find=find, scopes=("customer_analytics:read",), pulse_order=2)diff --git a/products/today/backend/tests/test_highlight_key_metrics.py b/products/today/backend/tests/test_highlight_key_metrics.pynew file mode 100644index 000000000000..9e3794ba2062--- /dev/null+++ b/products/today/backend/tests/test_highlight_key_metrics.py@@ -0,0 +1,64 @@+from datetime import date, timedelta+from types import SimpleNamespace+from typing import cast++from unittest.mock import patch++from django.test import SimpleTestCase++from products.customer_analytics.backend.facade.contracts import KeyMetric+from products.today.backend.logic.highlight_registry import load_sources+from products.today.backend.logic.highlight_sources import key_metrics+from products.today.backend.logic.highlight_types import Context++TODAY = date(2026, 10, 13)+++def metric(key: str, values: list[float], *, people: bool = False) -> KeyMetric:+ start = TODAY - timedelta(days=len(values))+ daily = [(start + timedelta(days=i), v) for i, v in enumerate(values)]+ return KeyMetric(+ key=key,+ name=key.replace("_", " ").capitalize(),+ people=people,+ daily=daily,+ this_week=sum(values[-7:]),+ last_week=sum(values[-14:-7]),+ )+++class TestKeyMetrics(SimpleTestCase):+ def test_key_metrics_fill_the_pulse_and_a_weekday_drop_becomes_an_item(self) -> None:+ drop = [1000.0] * 6 + [1010.0] + [1000.0] * 6 + [990.0] + [1000.0] * 20 + [500.0]+ metrics = [+ metric("signup_event", drop),+ metric("payment_event", [0.0] * 35),+ metric("activity_event", [20.0] * 35, people=True),+ ]+ context = cast(+ Context,+ SimpleNamespace(+ team=SimpleNamespace(id=1),+ user=SimpleNamespace(id=2),+ today=TODAY,+ daily=lambda _name, compute: compute(),+ ),+ )+ registered = next(s for s in load_sources() if s.name == "key_metrics")++ with (+ patch.object(key_metrics, "get_key_metrics", return_value=metrics),+ patch.object(key_metrics, "get_key_metrics_fingerprint", return_value="config"),+ ):+ found = registered.find(context)++ self.assertEqual(+ (+ [(m.key, m.value, m.unit, m.change_pct, len(m.series)) for m in found.pulse],+ [(c.title, c.detail, c.label) for c in found.items],+ ),+ (+ [("signup_event", 6500.0, "events", -7.1, 28), ("activity_event", 140.0, "people", 0.0, 28)],+ [("‘Signup event’ decreased by 50% yesterday", "500 yesterday · 1,000 on an average Monday", "risk")],+ ),+ )diff --git a/tach.toml b/tach.tomlindex b5eda2a0b6da..e123a291ebff 100644--- a/tach.toml+++ b/tach.toml@@ -980,6 +980,7 @@ path = "products.customer_analytics"depends_on = ["ee","posthog",+ "products.actions","products.cdp","products.conversations","products.data_modeling",@@ -1646,6 +1647,7 @@ depends_on = ["products.access_control","products.alerts","products.conversations",+ "products.customer_analytics","products.dashboards","products.error_tracking","products.product_analytics",