: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
fix(today): keep slow key numbers loading and replace ones that cannot load (#129177)
Shy Altere116078c78e8
diff --git a/products/today/backend/logic/highlights.py b/products/today/backend/logic/highlights.pyindex 321ec97d2bfe..7cf72237518c 100644--- a/products/today/backend/logic/highlights.py+++ b/products/today/backend/logic/highlights.py@@ -218,7 +218,11 @@ def _pulse_content(status=PulseSlotStatus.READY,)pin_order = {pin.key: index for index, pin in enumerate(content.pins)}- selected = [slot for slot in slots.values() if slot.key not in offered or slot.key in metrics]+ selected = [+ slot+ for slot in slots.values()+ if slot.status != PulseSlotStatus.EMPTY and (slot.key not in offered or slot.key in metrics)+ ]selected.sort(key=lambda slot: (slot.key not in pin_order,diff --git a/products/today/backend/logic/today_highlights/routine.py b/products/today/backend/logic/today_highlights/routine.pyindex bfe4af378285..528d265a42bf 100644--- a/products/today/backend/logic/today_highlights/routine.py+++ b/products/today/backend/logic/today_highlights/routine.py@@ -1,4 +1,4 @@-from collections.abc import Collection, Iterator, Sequence+from collections.abc import Collection, Iterable, Iterator, Sequencefrom dataclasses import replacefrom datetime import date, timedeltafrom functools import partial@@ -37,7 +37,7 @@ FRECENCY_HALF_LIFE_DAYS = 14FRECENCY_LOOKBACK_DAYS = VIEW_DAYS_KEPTFRECENCY_CANDIDATES = 8PULSE_CANDIDATES = 6-BLOCKING_SECONDS = 20+BLOCKING_SECONDS = 150POPULAR_DAYS = 30POPULAR_CANDIDATES = 8DASHBOARD_TILES_TRIED = 6@@ -61,6 +61,13 @@ class PulseCandidate:tile: DashboardInsightTile | None = None+@frozen+class PulseChoice:+ key: str+ candidate: PulseCandidate+ slot: contracts.PulseSlot++def find(context: Context) -> Found:pinned = context.pinnedif context.publish_pulse is not None:@@ -95,45 +102,30 @@ def _progressive_metrics(context: Context, excluded: Collection[str], budget: inPulseCandidate(viewed=item, short_id=tile.insight_short_id, dashboard=dashboard, tile=tile)for tile in dashboard.tiles)- definitions = viewable_insight_definitions(- team=context.team, user=context.user, short_ids=[candidate.short_id for candidate in candidates]- )- selected: dict[str, PulseCandidate] = {}+ choices = _eligible_choices(context, excluded, candidates)+ selected: dict[str, PulseChoice] = {}+ tried: set[str] = set()slots: dict[str, contracts.PulseSlot] = {}- dashboards: set[int] = set()- for candidate in candidates:- key = f"insight:{candidate.short_id}"- definition = definitions.get(candidate.short_id)- if key in excluded or key in selected or definition is None:- continue- source = definition.query.get("source", definition.query)- if not context.guard(- f"eligible insight {candidate.short_id}",- partial(insight_series_supported, query=definition.query, dashboard=_dashboard_context(candidate)),- False,- ):- continue- dashboard = candidate.dashboard- if dashboard is not None and dashboard.dashboard_id in dashboards:- continue- interval = (dashboard.filters.get("interval") if dashboard else None) or source.get("interval", "day")- selected[key] = candidate- slots[key] = contracts.PulseSlot(- key=key,- name=definition.name or "Untitled insight",- reason=HighlightMetricReason.POPULAR if candidate.viewed.popular else HighlightMetricReason.ROUTINE,- url=f"/dashboard/{dashboard.dashboard_id}" if dashboard else f"/insights/{candidate.short_id}",- interval=HighlightInterval(interval)- if source.get("kind") == "TrendsQuery" and interval in HighlightInterval.values- else None,- )- if dashboard is not None:- dashboards.add(dashboard.dashboard_id)- if len(selected) >= budget:- break+ pending: dict[str, PulseCandidate] = {}++ def fill() -> None:+ while len(selected) < budget:+ choice = _next_choice(choices, tried, selected.values())+ if choice is None:+ return+ tried.add(choice.key)+ selected[choice.key] = choice+ slots[choice.key] = choice.slot+ pending[choice.key] = choice.candidate++ def drop(key: str) -> None:+ slots[key] = replace(slots[key], status=PulseSlotStatus.EMPTY)+ del selected[key]+ fill()++ fill()metrics: dict[str, contracts.HighlightMetric] = {}context.publish_pulse(Found(), list(slots.values()))- pending = dict(selected)query_ids: dict[str, str] = {}while pending and monotonic() < deadline:for key, candidate in list(pending.items()):@@ -159,15 +151,19 @@ def _progressive_metrics(context: Context, excluded: Collection[str], budget: inraise ValueError("Pending insight has no query ID") from errorquery_ids[key] = error.query_idcontinue+ except ValueError as error:+ capture_exception(error, {"product": "today", "provider": "routine"})+ metric = Noneexcept Exception as error:context.failures.append(key)capture_exception(error, {"product": "today", "provider": "routine"})- slots[key] = replace(slots[key], status=PulseSlotStatus.ERROR)- else:- slots[key] = replace(slots[key], status=PulseSlotStatus.READY if metric else PulseSlotStatus.EMPTY)- if metric is not None:- metrics[key] = metric+ metric = Nonedel pending[key]+ if metric is None:+ drop(key)+ else:+ slots[key] = replace(slots[key], status=PulseSlotStatus.READY)+ metrics[key] = metriccontext.publish_pulse(Found(pulse=tuple(metrics.values())), list(slots.values()))if pending:sleep(min(1.0, max(0, deadline - monotonic())))@@ -179,6 +175,60 @@ def _progressive_metrics(context: Context, excluded: Collection[str], budget: inreturn [metrics[key] for key in selected if key in metrics]+def _eligible_choices(+ context: Context, excluded: Collection[str], candidates: Sequence[PulseCandidate]+) -> list[PulseChoice]:+ definitions = viewable_insight_definitions(+ team=context.team, user=context.user, short_ids=[candidate.short_id for candidate in candidates]+ )+ choices: list[PulseChoice] = []+ for candidate in candidates:+ key = f"insight:{candidate.short_id}"+ definition = definitions.get(candidate.short_id)+ if key in excluded or definition is None:+ continue+ if not context.guard(+ f"eligible insight {candidate.short_id}",+ partial(insight_series_supported, query=definition.query, dashboard=_dashboard_context(candidate)),+ False,+ ):+ continue+ source = definition.query.get("source", definition.query)+ dashboard = candidate.dashboard+ interval = (dashboard.filters.get("interval") if dashboard else None) or source.get("interval", "day")+ choices.append(+ PulseChoice(+ key=key,+ candidate=candidate,+ slot=contracts.PulseSlot(+ key=key,+ name=definition.name or "Untitled insight",+ reason=HighlightMetricReason.POPULAR if candidate.viewed.popular else HighlightMetricReason.ROUTINE,+ url=f"/dashboard/{dashboard.dashboard_id}" if dashboard else f"/insights/{candidate.short_id}",+ interval=HighlightInterval(interval)+ if source.get("kind") == "TrendsQuery" and interval in HighlightInterval.values+ else None,+ ),+ )+ )+ return choices+++def _next_choice(+ choices: Sequence[PulseChoice], tried: Collection[str], selected: Iterable[PulseChoice]+) -> PulseChoice | None:+ shown = {choice.candidate.dashboard.dashboard_id for choice in selected if choice.candidate.dashboard is not None}+ return next(+ (+ choice+ for choice in choices+ if choice.key not in tried+ and (choice.candidate.dashboard is None or choice.candidate.dashboard.dashboard_id not in shown)+ ),+ None,+ )++def frecency(view_days: Collection[date], today: date) -> float:ages = [(today - day).days for day in view_days]return sum(0.5 ** (age / FRECENCY_HALF_LIFE_DAYS) for age in ages if 0 <= age <= FRECENCY_LOOKBACK_DAYS)diff --git a/products/today/backend/temporal/workflows.py b/products/today/backend/temporal/workflows.pyindex 743dfdd1ea52..c660e54c0879 100644--- a/products/today/backend/temporal/workflows.py+++ b/products/today/backend/temporal/workflows.py@@ -20,7 +20,8 @@ with temporalio.workflow.unsafe.imports_passed_through():ResolvePinsInputs,)-HIGHLIGHT_SOURCE_TIMEOUT = timedelta(seconds=60)+HIGHLIGHT_SOURCE_TIMEOUT = timedelta(seconds=180)+HIGHLIGHT_SOURCE_TOTAL_TIMEOUT = timedelta(seconds=240)FINALIZE_HIGHLIGHTS_TIMEOUT = timedelta(seconds=30)PINNED_NUMBERS_PATCH = "today-pinned-numbers"@@ -64,6 +65,7 @@ async def _run_source(inputs: ComputeHighlightsInputs, source_name: str) -> Highhighlights_id=inputs.highlights_id if inputs.progressive else None,),start_to_close_timeout=HIGHLIGHT_SOURCE_TIMEOUT,+ schedule_to_close_timeout=HIGHLIGHT_SOURCE_TOTAL_TIMEOUT,retry_policy=temporalio.common.RetryPolicy(maximum_attempts=2),)except ActivityError:diff --git a/products/today/backend/tests/test_highlight_insights.py b/products/today/backend/tests/test_highlight_insights.pyindex de5678a4b448..7e61ced5adc9 100644--- a/products/today/backend/tests/test_highlight_insights.py+++ b/products/today/backend/tests/test_highlight_insights.py@@ -421,7 +421,7 @@ class TestRoutineInsights(BaseTest):started.add(ref)return Noneif ref == slow_ref and kwargs["blocking"]:- clock[0] = 30.0+ clock[0] = routine.BLOCKING_SECONDS + 10if ref in ("slow", slow_ref):return Nonereturn insight({"opened": points}, short_id=ref, name=ref)@@ -437,9 +437,9 @@ class TestRoutineInsights(BaseTest):self.assertEqual([metric.key for metric in pulse], [f"insight:{ref}" for ref in expected])self.assertEqual({ref for ref, _, _, _ in queried}, {"a", "slow", "b", "c", "d"})- self.assertTrue(all(deadline == 20.0 for _, _, deadline, _ in queried))+ self.assertTrue(all(deadline == routine.BLOCKING_SECONDS for _, _, deadline, _ in queried))self.assertTrue(any(blocking for _, blocking, _, _ in queried))- self.assertTrue(all(not blocking for _, blocking, _, at in queried if at >= 30.0))+ self.assertTrue(all(not blocking for _, blocking, _, at in queried if at > routine.BLOCKING_SECONDS))@time_machine.travel("2026-10-13T12:00:00Z", tick=False)def test_a_person_with_few_views_also_sees_the_insights_the_project_opens_most(self) -> None:@@ -483,7 +483,7 @@ class TestProgressiveInsights(SimpleTestCase):def test_ready_numbers_are_published_while_the_first_query_is_still_running(self) -> None:clock = [0.0]published: list[tuple[float, HighlightFindings, list[PulseSlot]]] = []- ready_at = {"slow": 8.0, "fast": 1.0, "empty": 0.0, "timeout": 30.0}+ ready_at = {"slow": 30.0, "fast": 1.0, "empty": 0.0, "timeout": 200.0, "spare": 2.0}views = [routine.ViewedItem(kind="insight", ref=ref, days=frozenset({TODAY})) for ref in ready_at]definitions = {ref: SavedInsightDefinition(id=i, short_id=ref, name=ref, query={"kind": "TrendsQuery"})@@ -525,25 +525,84 @@ class TestProgressiveInsights(SimpleTestCase):patch.object(routine, "monotonic", side_effect=lambda: clock[0]),patch.object(routine, "sleep", side_effect=advance),):- found = routine._progressive_metrics(context, frozenset(), 6)+ found = routine._progressive_metrics(context, frozenset(), 4)self.assertEqual(published[0][0], 0)+ self.assertEqual([slot.key for slot in published[0][2]], [f"insight:{ref}" for ref in list(ready_at)[:4]])self.assertTrue(all(slot.status == PulseSlotStatus.PENDING for slot in published[0][2]))first_number = next((at, result) for at, result, _ in published if result.pulse)self.assertEqual(first_number[0], 1.0)self.assertEqual(first_number[1].pulse[0].key, "insight:fast")- self.assertEqual([metric.key for metric in found], ["insight:slow", "insight:fast"])- self.assertEqual(clock[0], 20.0)- self.assertEqual({ref for ref, at in queried if at == 0}, set(ready_at))+ self.assertEqual([metric.key for metric in found], ["insight:slow", "insight:fast", "insight:spare"])+ self.assertEqual(clock[0], routine.BLOCKING_SECONDS)+ self.assertEqual({ref for ref, at in queried if at == 0}, {"slow", "fast", "empty", "timeout"})self.assertEqual(- [slot.status for slot in published[-1][2]],- [PulseSlotStatus.READY, PulseSlotStatus.READY, PulseSlotStatus.EMPTY, PulseSlotStatus.ERROR],+ {slot.key: slot.status for slot in published[-1][2]},+ {+ "insight:slow": PulseSlotStatus.READY,+ "insight:fast": PulseSlotStatus.READY,+ "insight:empty": PulseSlotStatus.EMPTY,+ "insight:timeout": PulseSlotStatus.ERROR,+ "insight:spare": PulseSlotStatus.READY,+ },)self.assertEqual(context.failures, ["insight:timeout"])- self.assertEqual(Counter(ref for ref, _ in queried), {"slow": 2, "fast": 2, "empty": 1, "timeout": 1})- self.assertTrue(- all([slot.key for slot in slots] == [slot.key for slot in published[0][2]] for _, _, slots in published)+ self.assertEqual(+ Counter(ref for ref, _ in queried), {"slow": 2, "fast": 2, "empty": 1, "timeout": 1, "spare": 2}+ )++ def test_failed_candidates_are_replaced_and_only_transient_errors_mark_the_source_failed(self) -> None:+ dashboard = DashboardInsights(+ dashboard_id=7,+ name="Growth",+ filters={},+ variables=None,+ tiles=(+ DashboardInsightTile(insight_short_id="a", filters_overrides=None),+ DashboardInsightTile(insight_short_id="b", filters_overrides=None),+ ),+ )+ views = [+ routine.ViewedItem(kind="dashboard", ref="7", days=frozenset({TODAY})),+ *(routine.ViewedItem(kind="insight", ref=ref, days=frozenset({TODAY})) for ref in ("broken", "bad", "b")),+ ]+ definitions = {+ ref: SavedInsightDefinition(id=i, short_id=ref, name=ref, query={"kind": "TrendsQuery"})+ for i, ref in enumerate(("a", "b", "broken", "bad"))+ }+ errors: dict[str, Exception] = {"broken": ConnectionError("network"), "bad": ValueError("Insight query failed")}++ def series(**kwargs: Any) -> InsightSeries:+ ref = kwargs["short_id"]+ if ref in errors:+ raise errors[ref]+ return insight({"opened": days([10.0] * 56)}, short_id=ref, name=ref)++ context = cast(+ Context,+ SimpleNamespace(+ team=None,+ user=None,+ today=TODAY,+ failures=[],+ guard=lambda name, compute, fallback: compute(),+ publish_pulse=lambda found, slots: None,+ ),+ )+ with (+ patch.object(routine, "_frecent_views", return_value=views),+ patch.object(routine, "_candidates", side_effect=lambda context, own: iter(own)),+ patch.object(routine, "dashboard_insights", return_value=dashboard),+ patch.object(routine, "viewable_insight_definitions", return_value=definitions),+ patch.object(routine, "get_insight_series", side_effect=series),+ patch.object(routine, "capture_exception"),+ ):+ found = routine._progressive_metrics(context, frozenset(), 2)++ self.assertEqual(+ [(metric.key, metric.dashboard_id) for metric in found], [("insight:a", 7), ("insight:b", None)])+ self.assertEqual(context.failures, ["insight:broken"])def test_a_dashboard_skips_an_unsupported_tile_before_selecting_a_loading_card(self) -> None:viewed = routine.ViewedItem(kind="dashboard", ref="7", days=frozenset({TODAY}))diff --git a/products/today/backend/tests/test_highlights.py b/products/today/backend/tests/test_highlights.pyindex 96b1729e1f8e..e8d5281e3ee7 100644--- a/products/today/backend/tests/test_highlights.py+++ b/products/today/backend/tests/test_highlights.py@@ -518,7 +518,11 @@ class TestProgressiveHighlights(BaseTest):source_name="routine",highlights_id=str(row.id),)- slots = [contracts.PulseSlot(key="fast", name="Fast"), contracts.PulseSlot(key="slow", name="Slow")]+ slots = [+ contracts.PulseSlot(key="fast", name="Fast"),+ contracts.PulseSlot(key="slow", name="Slow"),+ contracts.PulseSlot(key="no-data", name="No data", status=PulseSlotStatus.EMPTY),+ ]highlights.publish_pulse(inputs, HighlightFindings(), slots)highlights.publish_pulse(inputs, HighlightFindings(pulse=(metric("fast"),)), slots)highlights.publish_pulse(inputs, HighlightFindings(), slots)