Skip to content

: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.

fix(today): read key metrics through the query cache (#118536)

Shy Alter460fb90c28b7
diff --git a/products/actions/backend/facade/api.py b/products/actions/backend/facade/api.py
index 5878d35ca360..0b0ab8cc4758 100644
--- a/products/actions/backend/facade/api.py
+++ b/products/actions/backend/facade/api.py
@@ -48,12 +48,3 @@ 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.
continue
return 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.py
index f891aa533bef..6cc46d905283 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -5755,9 +5755,6 @@ def list_announcement_channels(team_id: int) -> list[contracts.AnnouncementChann
return []
-def get_key_metrics(*, team: Team, user: "User") -> list[contracts.KeyMetric]:
+def get_key_metrics(*, team: Team, user: "User") -> list[contracts.KeyMetric] | None:
+ """The key metrics, or None while a background calculation is still running."""
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/logic/key_metrics.py b/products/customer_analytics/backend/logic/key_metrics.py
index 817a8f4a8cae..4aa0e790ff26 100644
--- a/products/customer_analytics/backend/logic/key_metrics.py
+++ b/products/customer_analytics/backend/logic/key_metrics.py
@@ -1,22 +1,22 @@
-import json
-import hashlib
-from datetime import timedelta
+import re
+from datetime import date, datetime, time, timedelta
from typing import Any, cast
from django.utils import timezone
-from posthog.schema import HogQLQueryModifiers
+from pydantic import BaseModel
from posthog.hogql import ast
-from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.parser import parse_expr, parse_select
+from posthog.hogql.printer import to_printed_hogql
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.hogql_queries.query_runner import ExecutionMode
from posthog.models import Team, User
+from posthog.utils import relative_date_parse
-from products.actions.backend.facade.api import action_filter_conditions, action_revisions
+from products.actions.backend.facade.api import action_filter_conditions
from products.customer_analytics.backend.facade.contracts import KeyMetric
KEY_METRICS = {
@@ -27,17 +27,18 @@ KEY_METRICS = {
}
PEOPLE_METRIC = "activity_event"
DAYS = 35
-QUERY_TIMEOUT_SECONDS = 10
+EXECUTION_MODE = ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE
+DATE_OPERATORS = {"is_date_exact", "is_date_before", "is_date_after"}
+RELATIVE_DATE = re.compile(r"^-?[0-9]+[hdwmqysHDWMQY]")
DAILY = (
"SELECT toDate(timestamp) AS day FROM events"
- " WHERE timestamp >= toStartOfDay(now()) - INTERVAL {days} DAY AND timestamp < toStartOfDay(now())"
+ " WHERE timestamp >= {start} AND timestamp < {end}"
" 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())"
+ "SELECT uniqIf(person_id, timestamp >= {week}), uniqIf(person_id, timestamp < {week}) FROM events"
+ " WHERE timestamp >= {start} AND timestamp < {end}"
" AND {match} AND {test_accounts}"
)
@@ -55,15 +56,28 @@ 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:
+def _anchored(filters: Any, team: Team, anchor: datetime) -> Any:
+ if isinstance(filters, list):
+ return [_anchored(item, team, anchor) for item in filters]
+ if not isinstance(filters, dict):
+ return filters
+ anchored = {key: _anchored(value, team, anchor) if key == "values" else value for key, value in filters.items()}
+ value = anchored.get("value")
+ if anchored.get("operator") in DATE_OPERATORS and isinstance(value, str) and RELATIVE_DATE.match(value):
+ resolved = relative_date_parse(value, team.timezone_info, now=anchor)
+ anchored["value"] = resolved.strftime("%Y-%m-%d %H:%M:%S")
+ return anchored
+
+
+def _condition(node: dict[str, Any], team: Team, anchor: datetime) -> ast.Expr:
if node["kind"] == "ActionsNode":
- match = clone_expr(actions[int(node["id"])])
+ match = parse_expr("matchesAction({id})", placeholders={"id": ast.Constant(value=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 ast.And(exprs=[match, property_to_expr(_anchored(node["properties"], team, anchor), team)])
return match
@@ -71,38 +85,45 @@ 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,
+def _run(query: ast.SelectQuery, team: Team, user: User) -> list[Any] | None:
+ from posthog.api.services.query import process_query_dict # noqa: PLC0415 — the query service imports this facade
+
+ response = process_query_dict(
team,
- query_type=query_type,
+ {"kind": "HogQLQuery", "query": to_printed_hogql(query, team), "modifiers": {"convertToProjectTimezone": True}},
+ execution_mode=EXECUTION_MODE,
user=user,
- modifiers=HogQLQueryModifiers(convertToProjectTimezone=True),
- settings=HogQLGlobalSettings(max_execution_time=QUERY_TIMEOUT_SECONDS, timeout_overflow_mode="throw"),
- ).results
+ )
+ results = (response.model_dump() if isinstance(response, BaseModel) else response).get("results")
+ return None if results is None else list(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 _midnight(team: Team, day: date) -> ast.Constant:
+ return ast.Constant(value=datetime.combine(day, time.min, tzinfo=team.timezone_info))
-def key_metrics(team: Team, user: User) -> list[KeyMetric]:
+def _day(value: date | str) -> date:
+ return value if isinstance(value, date) else date.fromisoformat(value[:10])
+
+
+def key_metrics(team: Team, user: User) -> list[KeyMetric] | None:
nodes = _configured_nodes(team)
- actions = action_filter_conditions(team=team, action_ids=_action_ids(nodes))
+ live_actions = action_filter_conditions(team=team, action_ids=_action_ids(nodes))
+ today = timezone.now().astimezone(team.timezone_info).date()
+ anchor = datetime.combine(today, time.min, tzinfo=team.timezone_info)
conditions = {
- key: _condition(node, team, actions)
+ key: _condition(node, team, anchor)
for key, node in nodes.items()
- if node["kind"] == "EventsNode" or int(node["id"]) in actions
+ if node["kind"] == "EventsNode" or int(node["id"]) in live_actions
}
if not conditions:
return []
- test_accounts = property_to_expr(team.test_account_filters or [], team)
+ test_accounts = property_to_expr(_anchored(team.test_account_filters or [], team, anchor), team)
daily = _select(
DAILY,
- days=ast.Constant(value=DAYS),
+ start=_midnight(team, today - timedelta(days=DAYS)),
+ end=_midnight(team, today),
match=ast.Or(exprs=[clone_expr(c) for c in conditions.values()]),
test_accounts=clone_expr(test_accounts),
)
@@ -116,16 +137,27 @@ def key_metrics(team: Team, user: User) -> list[KeyMetric]:
)
for key, condition in conditions.items()
)
- by_day = {row[0]: row[1:] for row in _run(daily, team, user, "customer_analytics_key_metrics_daily")}
+ rows = _run(daily, team, user)
+ if rows is None:
+ return None
+ by_day = {_day(row[0]): row[1:] for row in rows}
- 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")
+ weekly_query = _select(
+ WEEKLY_PEOPLE,
+ start=_midnight(team, today - timedelta(days=14)),
+ week=_midnight(team, today - timedelta(days=7)),
+ end=_midnight(team, today),
+ match=condition,
+ test_accounts=clone_expr(test_accounts),
+ )
+ weekly = _run(weekly_query, team, user)
+ if weekly is None:
+ return None
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])
diff --git a/products/customer_analytics/backend/test/test_key_metrics.py b/products/customer_analytics/backend/test/test_key_metrics.py
index 7fbcd4bb01b3..fcc23eca0afe 100644
--- a/products/customer_analytics/backend/test/test_key_metrics.py
+++ b/products/customer_analytics/backend/test/test_key_metrics.py
@@ -1,23 +1,33 @@
-from datetime import datetime, timedelta
+from datetime import date, datetime, timedelta
import time_machine
from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
+from unittest.mock import patch
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 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
+from products.customer_analytics.backend.facade.api import get_key_metrics
+from products.customer_analytics.backend.logic import key_metrics as key_metrics_logic
class TestKeyMetrics(ClickhouseTestMixin, BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ blocking = patch.object(
+ key_metrics_logic, "EXECUTION_MODE", ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
+ )
+ blocking.start()
+ self.addCleanup(blocking.stop)
+
def _midnight(self) -> datetime:
return timezone.now().replace(hour=0, minute=0, second=0, microsecond=0)
@@ -87,42 +97,77 @@ class TestKeyMetrics(ClickhouseTestMixin, BaseTest):
flush_persons_and_events()
metrics = get_key_metrics(team=self.team, user=viewer)
+ cached = get_key_metrics(team=self.team, user=viewer)
+ assert metrics is not None
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}),
+ (
+ {m.key: (m.this_week, m.last_week) for m in metrics},
+ {m.key: len(m.daily) for m in metrics},
+ cached,
+ ),
+ (expected, {"signup_event": 35, "activity_event": 35}, metrics),
)
- 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))
+ def test_days_follow_the_project_timezone(self) -> None:
+ self.team.timezone = "Asia/Tokyo"
+ self.team.save()
+ config = self.team.customer_analytics_config
+ config.activity_event = {"kind": "EventsNode", "event": "opened_file"}
+ config.save()
+ with time_machine.travel("2026-03-02T12:00:00Z", tick=False):
+ for person, at in (("late-yesterday", "2026-03-01T14:00:00Z"), ("early-today", "2026-03-01T16:00:00Z")):
+ create_person(team=self.team, distinct_ids=[person])
+ _create_event(team=self.team, event="opened_file", distinct_id=person, timestamp=at)
+ flush_persons_and_events()
+
+ metrics = get_key_metrics(team=self.team, user=self.user)
+
+ assert metrics is not None
+ activity = metrics[0]
+ self.assertEqual((activity.this_week, activity.daily[-1]), (1.0, (date(2026, 3, 1), 1.0)))
+
+ def test_an_uncached_query_returns_nothing_and_calculates_in_the_background(self) -> None:
+ config = self.team.customer_analytics_config
+ config.activity_event = {"kind": "EventsNode", "event": "opened_file"}
+ config.save()
+
+ with (
+ patch.object(key_metrics_logic, "EXECUTION_MODE", ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE),
+ patch("posthog.hogql_queries.query_runner.QueryRunner.enqueue_async_calculation") as enqueue,
+ ):
+ metrics = get_key_metrics(team=self.team, user=self.user)
+
+ self.assertEqual((metrics, enqueue.call_count), (None, 1))
+
+ @parameterized.expand(
+ [
+ ("a later minute reuses the result", timedelta(minutes=10), True),
+ ("a new day calculates again", timedelta(days=1), False),
+ ]
+ )
+ def test_a_relative_date_filter_keeps_the_cached_result_until_the_day_changes(
+ self, _name: str, later: timedelta, reused: bool
+ ) -> None:
+ self.team.test_account_filters = [
+ {"key": "signed_up_at", "value": "-30d", "operator": "is_date_after", "type": "person"}
+ ]
+ self.team.save()
+ config = self.team.customer_analytics_config
+ config.activity_event = {
+ "kind": "EventsNode",
+ "event": "opened_file",
+ "properties": [{"key": "opened_at", "value": "-7d", "operator": "is_date_after", "type": "event"}],
+ }
+ config.save()
+
+ with time_machine.travel("2026-03-02T12:00:00Z", tick=False) as traveller:
+ first = get_key_metrics(team=self.team, user=self.user)
+ traveller.shift(later)
+ with (
+ patch.object(key_metrics_logic, "EXECUTION_MODE", ExecutionMode.RECENT_CACHE_CALCULATE_ASYNC_IF_STALE),
+ patch("posthog.hogql_queries.query_runner.QueryRunner.enqueue_async_calculation"),
+ ):
+ second = get_key_metrics(team=self.team, user=self.user)
+
+ self.assertEqual((first is not None, second == first), (True, reused))
diff --git a/products/today/backend/logic/highlight_sources/key_metrics.py b/products/today/backend/logic/highlight_sources/key_metrics.py
index 2f7d599e6b34..59395dd0879d 100644
--- a/products/today/backend/logic/highlight_sources/key_metrics.py
+++ b/products/today/backend/logic/highlight_sources/key_metrics.py
@@ -1,11 +1,11 @@
-from products.customer_analytics.backend.facade.api import get_key_metrics, get_key_metrics_fingerprint
+from products.customer_analytics.backend.facade.api import get_key_metrics
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
+from ..highlight_types import Candidate, Context, DailyValueNotReady, Found, Source
KEY_METRIC_DAY = {
True: "‘{name}’ increased by {pct}% yesterday",
@@ -16,10 +16,9 @@ KEY_METRIC_DAY_DETAIL_WEEK = "{now} yesterday · {usual} a day over the week bef
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),
- )
+ metrics = get_key_metrics(team=context.team, user=context.user)
+ if metrics is None:
+ raise DailyValueNotReady("key_metrics")
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))
diff --git a/products/today/backend/tests/test_highlight_key_metrics.py b/products/today/backend/tests/test_highlight_key_metrics.py
index 9e3794ba2062..75652200b922 100644
--- a/products/today/backend/tests/test_highlight_key_metrics.py
+++ b/products/today/backend/tests/test_highlight_key_metrics.py
@@ -9,7 +9,7 @@ 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
+from products.today.backend.logic.highlight_types import Context, DailyValueNotReady
TODAY = date(2026, 10, 13)
@@ -41,15 +41,11 @@ class TestKeyMetrics(SimpleTestCase):
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"),
- ):
+ with patch.object(key_metrics, "get_key_metrics", return_value=metrics):
found = registered.find(context)
self.assertEqual(
@@ -62,3 +58,10 @@ class TestKeyMetrics(SimpleTestCase):
[("‘Signup event’ decreased by 50% yesterday", "500 yesterday · 1,000 on an average Monday", "risk")],
),
)
+
+ def test_a_pending_calculation_asks_for_a_quick_retry(self) -> None:
+ context = cast(Context, SimpleNamespace(team=SimpleNamespace(id=1), user=SimpleNamespace(id=2), today=TODAY))
+ registered = next(s for s in load_sources() if s.name == "key_metrics")
+
+ with patch.object(key_metrics, "get_key_metrics", return_value=None), self.assertRaises(DailyValueNotReady):
+ registered.find(context)