: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(error-tracking): batch DB queries in recommendations refresh sweep (#62526)
Aleksander Błaszkiewicz49493119ffc9
diff --git a/products/error_tracking/backend/recommendations/alerts.py b/products/error_tracking/backend/recommendations/alerts.pyindex c5b8aa246a7e..23a6a9a39d48 100644--- a/products/error_tracking/backend/recommendations/alerts.py+++ b/products/error_tracking/backend/recommendations/alerts.py@@ -1,11 +1,10 @@+from collections import defaultdictfrom functools import reducefrom operator import or_from typing import Anyfrom django.db.models import Q-from posthog.models.team.team import Team-from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionTypefrom .base import Recommendation@@ -25,37 +24,38 @@ class AlertsRecommendation(Recommendation):alerts = meta.get("alerts") or []return bool(alerts) and all(a.get("enabled") for a in alerts)- def compute(self, team: Team) -> dict[str, Any]:+ def compute_batch(self, team_ids: list[int]) -> dict[int, dict[str, Any]]:event_filter = reduce(or_,(Q(filters__contains={"events": [{"id": trigger["event"]}]}) for trigger in ALERT_TRIGGERS),)- filters_list = (+ rows = (HogFunction.objects.filter(- team_id=team.id,+ team_id__in=team_ids,type=HogFunctionType.INTERNAL_DESTINATION,deleted=False,).filter(event_filter)- .values_list("filters", flat=True)+ .values_list("team_id", "filters"))- events_with_alerts: set[str] = set()- for filters in filters_list:- if not filters:- continue- for event in filters.get("events") or []:+ events_with_alerts: dict[int, set[str]] = defaultdict(set)+ for team_id, filters in rows:+ for event in (filters or {}).get("events") or []:event_id = event.get("id")if event_id:- events_with_alerts.add(event_id)+ events_with_alerts[team_id].add(event_id)return {- "alerts": [- {- "key": trigger["key"],- "enabled": trigger["event"] in events_with_alerts,- }- for trigger in ALERT_TRIGGERS- ]+ team_id: {+ "alerts": [+ {+ "key": trigger["key"],+ "enabled": trigger["event"] in events_with_alerts[team_id],+ }+ for trigger in ALERT_TRIGGERS+ ]+ }+ for team_id in team_ids}diff --git a/products/error_tracking/backend/recommendations/base.py b/products/error_tracking/backend/recommendations/base.pyindex 6808259a8cb2..ae4ac43f71ee 100644--- a/products/error_tracking/backend/recommendations/base.py+++ b/products/error_tracking/backend/recommendations/base.py@@ -10,7 +10,13 @@ class Recommendation(ABC):refresh_interval: timedelta | None = None@abstractmethod- def compute(self, team: Team) -> dict[str, Any]: ...+ def compute_batch(self, team_ids: list[int]) -> dict[int, dict[str, Any]]:+ """Compute metas for many teams at once, with a bounded number of queries+ regardless of batch size. Must return a meta for every requested team; teams+ omitted from the result are reverted to ready by the caller."""++ def compute(self, team: Team) -> dict[str, Any]:+ return self.compute_batch([team.id])[team.id]def enrich(self, team: Team, meta: dict[str, Any]) -> dict[str, Any]:return metadiff --git a/products/error_tracking/backend/recommendations/long_running_issues.py b/products/error_tracking/backend/recommendations/long_running_issues.pyindex 886b5242bfdd..aad238ee30d0 100644--- a/products/error_tracking/backend/recommendations/long_running_issues.py+++ b/products/error_tracking/backend/recommendations/long_running_issues.py@@ -1,11 +1,12 @@-from datetime import datetime, timedelta+from datetime import timedeltafrom typing import Any-from posthog.schema import HogQLFilters, ProductKey--from posthog.hogql import ast+from posthog.schema import ProductKey+from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.materialized_columns import get_materialized_column_for_propertyfrom posthog.clickhouse.query_tagging import Feature, tag_queries+from posthog.clickhouse.workload import Workloadfrom posthog.models.team.team import Teamfrom products.error_tracking.backend.models import ErrorTrackingIssue@@ -14,59 +15,96 @@ from .base import RecommendationISSUE_LIMIT = 5+BATCH_QUERY = """+ SELECT+ events.team_id AS team_id,+ issue_state.issue_id AS issue_id,+ any(issue_state.first_seen) AS first_seen,+ count() AS occurrences+ FROM events+ INNER JOIN (+ SELECT+ team_id,+ fp_hash,+ tupleElement(state, 1) AS issue_id,+ tupleElement(state, 2) AS first_seen,+ tupleElement(state, 3) AS issue_status+ FROM (+ SELECT+ team_id,+ cityHash64(fingerprint) AS fp_hash,+ argMax((issue_id, first_seen, issue_status), version) AS state+ FROM error_tracking_fingerprint_issue_state+ WHERE team_id IN %(team_ids)s+ GROUP BY team_id, fp_hash+ HAVING argMax(is_deleted, version) = 0+ SETTINGS optimize_aggregation_in_order=1+ )+ ) AS issue_state+ ON events.team_id = issue_state.team_id+ AND cityHash64({fingerprint_expr}) = issue_state.fp_hash+ WHERE events.team_id IN %(team_ids)s+ AND events.event = '$exception'+ AND events.timestamp >= now() - INTERVAL 7 DAY+ AND issue_state.issue_status = 'active'+ AND issue_state.first_seen < now() - INTERVAL 7 DAY+ GROUP BY team_id, issue_id+ ORDER BY team_id ASC, first_seen ASC+ LIMIT %(issue_limit)s BY team_id+"""+++def _fingerprint_expr() -> str:+ column = get_materialized_column_for_property("events", "properties", "$exception_fingerprint")+ if column is None:+ return "JSONExtractString(events.properties, '$exception_fingerprint')"+ if column.is_nullable:+ return f"ifNull(events.`{column.name}`, '')"+ return f"events.`{column.name}`"+class LongRunningIssuesRecommendation(Recommendation):type = "long_running_issues"refresh_interval = timedelta(hours=6)- def compute(self, team: Team) -> dict[str, Any]:- from posthog.hogql.query import execute_hogql_query-+ def compute_batch(self, team_ids: list[int]) -> dict[int, dict[str, Any]]:tag_queries(product=ProductKey.ERROR_TRACKING,feature=Feature.ENRICHMENT,- team_id=team.pk,name="recommendations:long_running_issues",)- response = execute_hogql_query(- query="""- SELECT- issue_id_v2,- any(issue_name) AS name,- any(issue_description) AS description,- any(issue_first_seen) AS first_seen,- count() AS occurrences- FROM events- WHERE event = '$exception'- AND timestamp >= now() - INTERVAL 7 DAY- AND issue_id_v2 IS NOT NULL- AND issue_status = 'active'- AND issue_first_seen < now() - INTERVAL 7 DAY- AND {filters}- GROUP BY issue_id_v2- ORDER BY first_seen ASC- LIMIT {limit}- """,- team=team,- filters=HogQLFilters(filterTestAccounts=True),- placeholders={"limit": ast.Constant(value=ISSUE_LIMIT)},+ rows = sync_execute(+ BATCH_QUERY.format(fingerprint_expr=_fingerprint_expr()),+ {"team_ids": team_ids, "issue_limit": ISSUE_LIMIT},+ workload=Workload.OFFLINE,)- return {- "issues": [+ issues_by_id = {+ issue.id: issue+ # nosemgrep: idor-lookup-without-team (team_id__in scopes the lookup; background sweep, not user input)+ for issue in ErrorTrackingIssue.objects.filter(+ team_id__in=team_ids, id__in=[issue_id for _, issue_id, _, _ in rows]+ ).only("id", "name", "description", "status")+ }++ metas: dict[int, dict[str, Any]] = {team_id: {"issues": []} for team_id in team_ids}+ for team_id, issue_id, first_seen, occurrences in rows:+ issue = issues_by_id.get(issue_id)+ # Stale state rows can reference issues deleted from Postgres — skip them.+ if issue is None or first_seen is None:+ continue+ metas[team_id]["issues"].append({"id": str(issue_id),- "name": name or "Untitled issue",- "description": description,- "created_at": first_seen.isoformat() if isinstance(first_seen, datetime) else first_seen,+ "name": issue.name or "Untitled issue",+ "description": issue.description,+ "created_at": first_seen.isoformat(),"occurrences": occurrences,- "status": ErrorTrackingIssue.Status.ACTIVE,+ "status": issue.status,}- for issue_id, name, description, first_seen, occurrences in (response.results or [])- if issue_id and first_seen- ]- }+ )+ return metasdef is_completed(self, meta: dict[str, Any]) -> bool:return not meta.get("issues")diff --git a/products/error_tracking/backend/recommendations/rate_limits.py b/products/error_tracking/backend/recommendations/rate_limits.pyindex 5fe4ad958041..349c276da2f6 100644--- a/products/error_tracking/backend/recommendations/rate_limits.py+++ b/products/error_tracking/backend/recommendations/rate_limits.py@@ -1,7 +1,5 @@from typing import Any-from posthog.models.team.team import Team-from products.error_tracking.backend.models import ErrorTrackingSettingsfrom .base import Recommendation@@ -20,14 +18,21 @@ class RateLimitsRecommendation(Recommendation):rate_limits = meta.get("rate_limits") or []return bool(rate_limits) and all(r.get("enabled") for r in rate_limits)- def compute(self, team: Team) -> dict[str, Any]:- settings = ErrorTrackingSettings.objects.filter(team_id=team.id).first()+ def compute_batch(self, team_ids: list[int]) -> dict[int, dict[str, Any]]:+ fields = [rate_limit["field"] for rate_limit in RATE_LIMITS]+ settings_by_team = {+ row["team_id"]: row+ for row in ErrorTrackingSettings.objects.filter(team_id__in=team_ids).values("team_id", *fields)+ }+ return {team_id: self._build_meta(settings_by_team.get(team_id)) for team_id in team_ids}+ @staticmethod+ def _build_meta(settings: dict[str, Any] | None) -> dict[str, Any]:return {"rate_limits": [{"key": rate_limit["key"],- "enabled": settings is not None and getattr(settings, rate_limit["field"]) is not None,+ "enabled": settings is not None and settings.get(rate_limit["field"]) is not None,}for rate_limit in RATE_LIMITS]diff --git a/products/error_tracking/backend/recommendations/refresh.py b/products/error_tracking/backend/recommendations/refresh.pyindex 99b68141e3b9..c1b4d8521e5b 100644--- a/products/error_tracking/backend/recommendations/refresh.py+++ b/products/error_tracking/backend/recommendations/refresh.py@@ -1,5 +1,5 @@-import asyncioimport hashlib+from collections.abc import Callablefrom datetime import datetime, timedeltafrom django.db import IntegrityError@@ -9,8 +9,6 @@ from django.utils import timezoneimport structlogfrom posthoganalytics import capture_exception-from posthog.sync import database_sync_to_async_pool-from products.error_tracking.backend.models import ErrorTrackingRecommendationfrom products.error_tracking.backend.recommendations import RECOMMENDATIONSfrom products.error_tracking.backend.recommendations.base import Recommendation@@ -93,7 +91,7 @@ def revert_to_ready(obj_id, team_id: int) -> None:)-def _refresh_one(rec: Recommendation, team_id: int, now: datetime, *, compute_sync: bool) -> int:+def _refresh_one(rec: Recommendation, team_id: int, now: datetime) -> int:try:obj = ensure_recommendation_row(rec, team_id)if not is_stale(rec, obj, now):@@ -101,10 +99,7 @@ def _refresh_one(rec: Recommendation, team_id: int, now: datetime, *, compute_syif not claim_for_compute(obj.id, team_id, now):return 0try:- if compute_sync:- compute_error_tracking_recommendation(str(obj.id), team_id)- else:- compute_error_tracking_recommendation.delay(str(obj.id), team_id)+ compute_error_tracking_recommendation.delay(str(obj.id), team_id)return 1except Exception:revert_to_ready(obj.id, team_id)@@ -131,19 +126,128 @@ def refresh_team_recommendations(team_id: int) -> int:Returns the number of recommendations kicked."""now = timezone.now()- return sum(_refresh_one(rec, team_id, now, compute_sync=False) for rec in RECOMMENDATIONS)+ return sum(_refresh_one(rec, team_id, now) for rec in RECOMMENDATIONS)-async def refresh_team_recommendations_inline(team_id: int) -> int:- """Compute every stale recommendation for a team inline, all at once.+def refresh_teams_recommendations_batched(team_ids: list[int], on_progress: Callable[[str], None] | None = None) -> int:+ """Compute every stale recommendation for a batch of teams with a bounded number+ of queries, independent of batch size.- Runs each rec's blocking ``compute()`` on the shared thread pool via- ``database_sync_to_async_pool`` and waits for all to finish. Used by the Temporal- background sweep so the work happens on the error-tracking worker.+ Bookkeeping (row creation, staleness, claiming, result writes) is bulked across+ the batch, and each recommendation answers all claimed teams via one+ ``compute_batch`` call. Used by the Temporal background sweep.- Returns the number of recommendations kicked.+ Returns the number of recommendations computed."""now = timezone.now()- refresh_one = database_sync_to_async_pool(_refresh_one)- results = await asyncio.gather(*[refresh_one(rec, team_id, now, compute_sync=True) for rec in RECOMMENDATIONS])- return sum(results)+ types = [rec.type for rec in RECOMMENDATIONS]++ def fetch_rows() -> dict[tuple[int, str], ErrorTrackingRecommendation]:+ return {+ (obj.team_id, obj.type): obj+ for obj in ErrorTrackingRecommendation.objects.filter(team_id__in=team_ids, type__in=types)+ }++ rows = fetch_rows()+ missing = [+ ErrorTrackingRecommendation(team_id=team_id, type=rec.type, status=ErrorTrackingRecommendation.Status.READY)+ for rec in RECOMMENDATIONS+ for team_id in team_ids+ if (team_id, rec.type) not in rows+ ]+ if missing:+ # ignore_conflicts means concurrently-created rows don't error, but it also+ # means we can't trust the in-memory ids — refetch instead.+ ErrorTrackingRecommendation.objects.bulk_create(missing, ignore_conflicts=True)+ rows = fetch_rows()++ computed = 0+ for rec in RECOMMENDATIONS:+ computed += _refresh_rec_for_teams(rec, team_ids, rows, now)+ if on_progress is not None:+ on_progress(rec.type)+ return computed+++def _refresh_rec_for_teams(+ rec: Recommendation,+ team_ids: list[int],+ rows: dict[tuple[int, str], ErrorTrackingRecommendation],+ now: datetime,+) -> int:+ stale_ids = [+ obj.id for team_id in team_ids if (obj := rows.get((team_id, rec.type))) is not None and is_stale(rec, obj, now)+ ]+ if not stale_ids:+ return 0++ claim_ts = timezone.now()+ stuck_threshold = claim_ts - COMPUTING_STUCK_AFTER+ # nosemgrep: idor-lookup-without-team (team_id__in scopes the update; background sweep, not user input)+ ErrorTrackingRecommendation.objects.filter(team_id__in=team_ids, id__in=stale_ids).filter(+ Q(status=ErrorTrackingRecommendation.Status.READY)+ | Q(status=ErrorTrackingRecommendation.Status.COMPUTING, status_changed_at__lt=stuck_threshold)+ ).update(status=ErrorTrackingRecommendation.Status.COMPUTING, status_changed_at=claim_ts)+ # claim_ts doubles as a claim marker: only rows this exact UPDATE transitioned+ # carry it, so rows owned by a concurrent worker (e.g. the on-demand API path)+ # are excluded here.+ claimed = dict(+ # nosemgrep: idor-lookup-without-team (team_id__in scopes the lookup; background sweep, not user input)+ ErrorTrackingRecommendation.objects.filter(+ team_id__in=team_ids,+ id__in=stale_ids,+ status=ErrorTrackingRecommendation.Status.COMPUTING,+ status_changed_at=claim_ts,+ ).values_list("id", "team_id")+ )+ if not claimed:+ return 0++ try:+ metas = rec.compute_batch(sorted(claimed.values()))+ except Exception as e:+ capture_exception(e)+ logger.warning(+ "error_tracking_recommendation_batch_compute_failed",+ recommendation_type=rec.type,+ team_count=len(claimed),+ exc_info=True,+ )+ _bulk_revert_to_ready(list(claimed))+ return 0++ computed_at = timezone.now()+ to_update = []+ to_revert = []+ for obj_id, team_id in claimed.items():+ meta = metas.get(team_id)+ if meta is None:+ to_revert.append(obj_id)+ continue+ to_update.append(+ ErrorTrackingRecommendation(+ id=obj_id,+ meta=meta,+ computed_at=computed_at,+ status=ErrorTrackingRecommendation.Status.READY,+ status_changed_at=computed_at,+ )+ )+ if to_update:+ ErrorTrackingRecommendation.objects.bulk_update(+ to_update, ["meta", "computed_at", "status", "status_changed_at"]+ )+ if to_revert:+ _bulk_revert_to_ready(to_revert)+ return len(to_update)+++def _bulk_revert_to_ready(obj_ids: list) -> None:+ # nosemgrep: idor-lookup-without-team (ids come from a prior team-scoped query)+ ErrorTrackingRecommendation.objects.filter(+ id__in=obj_ids,+ status=ErrorTrackingRecommendation.Status.COMPUTING,+ ).update(+ status=ErrorTrackingRecommendation.Status.READY,+ status_changed_at=timezone.now(),+ )diff --git a/products/error_tracking/backend/recommendations/source_maps.py b/products/error_tracking/backend/recommendations/source_maps.pyindex 44302c674ecb..f6910b3342ff 100644--- a/products/error_tracking/backend/recommendations/source_maps.py+++ b/products/error_tracking/backend/recommendations/source_maps.py@@ -4,8 +4,6 @@ from typing import Anyfrom django.db.models import Count, Qfrom django.utils import timezone-from posthog.models.team.team import Team-from products.error_tracking.backend.models import ErrorTrackingStackFramefrom .base import Recommendation@@ -24,7 +22,7 @@ class SourceMapsRecommendation(Recommendation):type = "source_maps"refresh_interval = timedelta(hours=6)- def compute(self, team: Team) -> dict[str, Any]:+ def compute_batch(self, team_ids: list[int]) -> dict[int, dict[str, Any]]:# `lang` is set on the resolved frame contents by cymbal — both browser JS# and Node frames are tagged "javascript". TypeScript frames also surface# as "javascript" pre-resolution; the source map is what would map them@@ -32,17 +30,25 @@ class SourceMapsRecommendation(Recommendation):# care about here.since = timezone.now() - timedelta(hours=LOOKBACK_HOURS)- counts = ErrorTrackingStackFrame.objects.filter(- team=team,- created_at__gte=since,- contents__lang="javascript",- ).aggregate(- total=Count("id"),- unresolved=Count("id", filter=Q(resolved=False)),- )-- total = counts["total"] or 0- unresolved = counts["unresolved"] or 0+ counts_by_team = {+ row["team_id"]: row+ for row in ErrorTrackingStackFrame.objects.filter(+ team_id__in=team_ids,+ created_at__gte=since,+ contents__lang="javascript",+ )+ .values("team_id")+ .annotate(+ total=Count("id"),+ unresolved=Count("id", filter=Q(resolved=False)),+ )+ }+ return {team_id: self._build_meta(counts_by_team.get(team_id)) for team_id in team_ids}++ @staticmethod+ def _build_meta(counts: dict[str, Any] | None) -> dict[str, Any]:+ total = (counts or {}).get("total") or 0+ unresolved = (counts or {}).get("unresolved") or 0unresolved_pct = (unresolved / total) if total > 0 else 0.0return {diff --git a/products/error_tracking/backend/temporal/__init__.py b/products/error_tracking/backend/temporal/__init__.pyindex e9d454cc3102..c8186a2dcc4d 100644--- a/products/error_tracking/backend/temporal/__init__.py+++ b/products/error_tracking/backend/temporal/__init__.py@@ -8,7 +8,7 @@ from products.error_tracking.backend.temporal.recommendations_refresh import (ACTIVITIES as RECOMMENDATIONS_REFRESH_ACTIVITIES,WORKFLOWS as RECOMMENDATIONS_REFRESH_WORKFLOWS,ErrorTrackingRecommendationsRefreshWorkflow,- get_teams_with_recent_exceptions_activity,+ get_team_batches_activity,refresh_recommendations_batch_activity,)from products.error_tracking.backend.temporal.spike_event_cleanup import (@@ -46,7 +46,7 @@ __all__ = ["ErrorTrackingSymbolSetCleanupWorkflow","cleanup_spike_events_activity","cleanup_symbol_sets_activity",- "get_teams_with_recent_exceptions_activity",+ "get_team_batches_activity","merge_similar_fingerprints_activity","refresh_recommendations_batch_activity",]diff --git a/products/error_tracking/backend/temporal/recommendations_refresh/__init__.py b/products/error_tracking/backend/temporal/recommendations_refresh/__init__.pyindex b0eb88e07f7f..bfd9cfa46954 100644--- a/products/error_tracking/backend/temporal/recommendations_refresh/__init__.py+++ b/products/error_tracking/backend/temporal/recommendations_refresh/__init__.py@@ -1,5 +1,5 @@from products.error_tracking.backend.temporal.recommendations_refresh.activities import (- get_teams_with_recent_exceptions_activity,+ get_team_batches_activity,refresh_recommendations_batch_activity,)from products.error_tracking.backend.temporal.recommendations_refresh.workflow import (@@ -7,12 +7,12 @@ from products.error_tracking.backend.temporal.recommendations_refresh.workflow i)WORKFLOWS = [ErrorTrackingRecommendationsRefreshWorkflow]-ACTIVITIES = [get_teams_with_recent_exceptions_activity, refresh_recommendations_batch_activity]+ACTIVITIES = [get_team_batches_activity, refresh_recommendations_batch_activity]__all__ = ["ACTIVITIES","WORKFLOWS","ErrorTrackingRecommendationsRefreshWorkflow",- "get_teams_with_recent_exceptions_activity",+ "get_team_batches_activity","refresh_recommendations_batch_activity",]diff --git a/products/error_tracking/backend/temporal/recommendations_refresh/activities.py b/products/error_tracking/backend/temporal/recommendations_refresh/activities.pyindex 0ea4d0026899..6a847ec2196e 100644--- a/products/error_tracking/backend/temporal/recommendations_refresh/activities.py+++ b/products/error_tracking/backend/temporal/recommendations_refresh/activities.py@@ -4,7 +4,7 @@ from temporalio import activityfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.workload import Workload-from products.error_tracking.backend.recommendations.refresh import refresh_team_recommendations_inline+from products.error_tracking.backend.recommendations.refresh import refresh_teams_recommendations_batchedfrom products.error_tracking.backend.temporal.recommendations_refresh.types import (RecommendationsRefreshInputs,RefreshBatchInputs,@@ -13,38 +13,59 @@ from products.error_tracking.backend.temporal.recommendations_refresh.types impologger = structlog.get_logger(__name__)-# Distinct teams that ingested at least one exception in the lookback window.+# Teams that ingested at least one exception in the lookback window, heaviest first.# Runs on the offline cluster so the cross-team scan doesn't compete with user queries.TEAMS_WITH_RECENT_EXCEPTIONS_QUERY = """- SELECT DISTINCT team_id+ SELECT team_id, count() AS exception_countFROM eventsWHERE event = '$exception'AND timestamp > now() - toIntervalDay(%(lookback_days)s)+ GROUP BY team_id+ ORDER BY exception_count DESC"""+def pack_team_batches(teams_with_counts: list[tuple[int, int]], max_teams: int, max_events: int) -> list[list[int]]:+ """Greedily pack (team_id, event_count) pairs, heaviest first, closing a batch when+ it reaches ``max_teams`` or adding the next team would push it past ``max_events``.+ A single team above the volume cap gets a batch of its own."""+ batches: list[list[int]] = []+ current: list[int] = []+ current_events = 0+ for team_id, count in teams_with_counts:+ if current and (len(current) >= max_teams or current_events + count > max_events):+ batches.append(current)+ current = []+ current_events = 0+ current.append(team_id)+ current_events += count+ if current:+ batches.append(current)+ return batches++@activity.defn-def get_teams_with_recent_exceptions_activity(inputs: RecommendationsRefreshInputs) -> list[int]:+def get_team_batches_activity(inputs: RecommendationsRefreshInputs) -> list[list[int]]:rows = sync_execute(TEAMS_WITH_RECENT_EXCEPTIONS_QUERY,{"lookback_days": inputs.lookback_days},workload=Workload.OFFLINE,)- team_ids = [int(row[0]) for row in rows]+ batches = pack_team_batches(+ [(int(team_id), int(count)) for team_id, count in rows],+ max_teams=inputs.batch_size,+ max_events=inputs.max_events_per_batch,+ )logger.info("error_tracking.recommendations_refresh.teams_enumerated",- team_count=len(team_ids),+ team_count=len(rows),+ batch_count=len(batches),lookback_days=inputs.lookback_days,)- return team_ids+ return batches@activity.defn-async def refresh_recommendations_batch_activity(inputs: RefreshBatchInputs) -> RefreshBatchResult:- kicked = 0- for index, team_id in enumerate(inputs.team_ids):- # refresh_team_recommendations_inline swallows per-team errors, so one bad team- # never sinks the batch.- kicked += await refresh_team_recommendations_inline(team_id)- activity.heartbeat(index)+def refresh_recommendations_batch_activity(inputs: RefreshBatchInputs) -> RefreshBatchResult:+ kicked = refresh_teams_recommendations_batched(inputs.team_ids, on_progress=activity.heartbeat)return RefreshBatchResult(teams_processed=len(inputs.team_ids), recommendations_kicked=kicked)diff --git a/products/error_tracking/backend/temporal/recommendations_refresh/test/test_recommendations_refresh.py b/products/error_tracking/backend/temporal/recommendations_refresh/test/test_recommendations_refresh.pyindex 95864d3e305c..a726561159ec 100644--- a/products/error_tracking/backend/temporal/recommendations_refresh/test/test_recommendations_refresh.py+++ b/products/error_tracking/backend/temporal/recommendations_refresh/test/test_recommendations_refresh.py@@ -1,28 +1,30 @@import uuid-import asynciofrom datetime import timedeltaimport pytest-from posthog.test.base import (- APIBaseTest,- ClickhouseTestMixin,- NonAtomicBaseTest,- _create_event,- flush_persons_and_events,-)+from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_eventsfrom unittest.mock import patchfrom django.utils import timezone+from parameterized import parameterizedfrom temporalio import activityfrom temporalio.testing import ActivityEnvironment, WorkflowEnvironmentfrom temporalio.worker import UnsandboxedWorkflowRunner, Workerfrom posthog.models import Team-from products.error_tracking.backend.models import ErrorTrackingRecommendation+from products.error_tracking.backend.models import (+ ErrorTrackingIssue,+ ErrorTrackingIssueFingerprintV2,+ ErrorTrackingRecommendation,+ sync_issues_to_clickhouse,+)+from products.error_tracking.backend.recommendations.long_running_issues import LongRunningIssuesRecommendation+from products.error_tracking.backend.sql import TRUNCATE_ERROR_TRACKING_FINGERPRINT_ISSUE_STATE_TABLE_SQLfrom products.error_tracking.backend.temporal.recommendations_refresh.activities import (- get_teams_with_recent_exceptions_activity,+ get_team_batches_activity,+ pack_team_batches,refresh_recommendations_batch_activity,)from products.error_tracking.backend.temporal.recommendations_refresh.types import (@@ -35,12 +37,16 @@ from products.error_tracking.backend.temporal.recommendations_refresh.workflow iErrorTrackingRecommendationsRefreshWorkflow,)-_ALERTS_COMPUTE = "products.error_tracking.backend.recommendations.alerts.AlertsRecommendation.compute"-_LONG_RUNNING_COMPUTE = (- "products.error_tracking.backend.recommendations.long_running_issues.LongRunningIssuesRecommendation.compute"+_ALERTS_COMPUTE_BATCH = "products.error_tracking.backend.recommendations.alerts.AlertsRecommendation.compute_batch"+_LONG_RUNNING_COMPUTE_BATCH = (+ "products.error_tracking.backend.recommendations.long_running_issues.LongRunningIssuesRecommendation.compute_batch"+)+_SOURCE_MAPS_COMPUTE_BATCH = (+ "products.error_tracking.backend.recommendations.source_maps.SourceMapsRecommendation.compute_batch"+)+_RATE_LIMITS_COMPUTE_BATCH = (+ "products.error_tracking.backend.recommendations.rate_limits.RateLimitsRecommendation.compute_batch")-_SOURCE_MAPS_COMPUTE = "products.error_tracking.backend.recommendations.source_maps.SourceMapsRecommendation.compute"-_RATE_LIMITS_COMPUTE = "products.error_tracking.backend.recommendations.rate_limits.RateLimitsRecommendation.compute"_ALERTS_META = {"alerts": [{"key": "error-tracking-issue-created", "enabled": False}]}_LONG_RUNNING_META: dict = {"issues": []}@@ -48,7 +54,15 @@ _SOURCE_MAPS_META = {"total_frames": 0, "unresolved_frames": 0, "unresolved_pct"_RATE_LIMITS_META = {"rate_limits": [{"key": "project", "enabled": False}, {"key": "per_issue", "enabled": False}]}-class TestGetTeamsWithRecentExceptionsActivity(ClickhouseTestMixin, APIBaseTest):+def _batch_meta(meta: dict):+ return lambda team_ids: dict.fromkeys(team_ids, meta)+++def _run_batch_activity(inputs: RefreshBatchInputs) -> RefreshBatchResult:+ return ActivityEnvironment().run(refresh_recommendations_batch_activity, inputs)+++class TestGetTeamBatchesActivity(ClickhouseTestMixin, APIBaseTest):def test_returns_only_teams_with_recent_exceptions(self):team_pageview_only = Team.objects.create(organization=self.organization, name="Pageviews")team_old_exception = Team.objects.create(organization=self.organization, name="Old")@@ -65,30 +79,37 @@ class TestGetTeamsWithRecentExceptionsActivity(ClickhouseTestMixin, APIBaseTest))flush_persons_and_events()- team_ids = get_teams_with_recent_exceptions_activity(RecommendationsRefreshInputs(lookback_days=7))-- assert self.team.id in team_ids- assert team_pageview_only.id not in team_ids- assert team_old_exception.id not in team_ids---class TestRefreshRecommendationsBatchActivity(NonAtomicBaseTest):- # Inline compute fans out over the shared thread pool, each thread with its own DB- # connection, so the data must be committed (not wrapped in TestCase's atomic block).- CLASS_DATA_LEVEL_SETUP = False-- @patch(_RATE_LIMITS_COMPUTE, return_value=_RATE_LIMITS_META)- @patch(_SOURCE_MAPS_COMPUTE, return_value=_SOURCE_MAPS_META)- @patch(_LONG_RUNNING_COMPUTE, return_value=_LONG_RUNNING_META)- @patch(_ALERTS_COMPUTE, return_value=_ALERTS_META)- def test_computes_recommendations_inline_for_all_teams(self, _alerts, _long, _source, _rate_limits):+ batches = get_team_batches_activity(RecommendationsRefreshInputs(lookback_days=7))++ all_team_ids = [team_id for batch in batches for team_id in batch]+ assert self.team.id in all_team_ids+ assert team_pageview_only.id not in all_team_ids+ assert team_old_exception.id not in all_team_ids+++class TestPackTeamBatches:+ @parameterized.expand(+ [+ ("all_fit_in_one_batch", [(1, 10), (2, 10)], 5, 100, [[1, 2]]),+ ("team_cap_closes_batch", [(1, 1), (2, 1), (3, 1)], 2, 100, [[1, 2], [3]]),+ ("volume_cap_closes_batch", [(1, 60), (2, 50), (3, 10)], 5, 100, [[1], [2, 3]]),+ ("oversized_team_gets_own_batch", [(1, 500), (2, 10), (3, 10)], 5, 100, [[1], [2, 3]]),+ ("empty_input", [], 5, 100, []),+ ]+ )+ def test_packing(self, _name, teams_with_counts, max_teams, max_events, expected):+ assert pack_team_batches(teams_with_counts, max_teams=max_teams, max_events=max_events) == expected+++class TestRefreshRecommendationsBatchActivity(APIBaseTest):+ @patch(_RATE_LIMITS_COMPUTE_BATCH, side_effect=_batch_meta(_RATE_LIMITS_META))+ @patch(_SOURCE_MAPS_COMPUTE_BATCH, side_effect=_batch_meta(_SOURCE_MAPS_META))+ @patch(_LONG_RUNNING_COMPUTE_BATCH, side_effect=_batch_meta(_LONG_RUNNING_META))+ @patch(_ALERTS_COMPUTE_BATCH, side_effect=_batch_meta(_ALERTS_META))+ def test_computes_recommendations_for_all_teams(self, _alerts, _long, _source, _rate_limits):team_b = Team.objects.create(organization=self.organization, name="Team B")- result = asyncio.run(- ActivityEnvironment().run(- refresh_recommendations_batch_activity, RefreshBatchInputs(team_ids=[self.team.id, team_b.id])- )- )+ result = _run_batch_activity(RefreshBatchInputs(team_ids=[self.team.id, team_b.id]))assert result.teams_processed == 2assert result.recommendations_kicked == 8@@ -99,31 +120,124 @@ class TestRefreshRecommendationsBatchActivity(NonAtomicBaseTest):assert rec.status == ErrorTrackingRecommendation.Status.READYassert rec.computed_at is not None- @patch(_RATE_LIMITS_COMPUTE, return_value=_RATE_LIMITS_META)- @patch(_SOURCE_MAPS_COMPUTE, return_value=_SOURCE_MAPS_META)- @patch(_LONG_RUNNING_COMPUTE, return_value=_LONG_RUNNING_META)- @patch(_ALERTS_COMPUTE, return_value=_ALERTS_META)+ @patch(_RATE_LIMITS_COMPUTE_BATCH, side_effect=_batch_meta(_RATE_LIMITS_META))+ @patch(_SOURCE_MAPS_COMPUTE_BATCH, side_effect=_batch_meta(_SOURCE_MAPS_META))+ @patch(_LONG_RUNNING_COMPUTE_BATCH, side_effect=_batch_meta(_LONG_RUNNING_META))+ @patch(_ALERTS_COMPUTE_BATCH, side_effect=_batch_meta(_ALERTS_META))def test_rerun_only_recomputes_stale_recommendations(self, _alerts, _long, _source, _rate_limits):team_b = Team.objects.create(organization=self.organization, name="Team B")batch = RefreshBatchInputs(team_ids=[self.team.id, team_b.id])- first = asyncio.run(ActivityEnvironment().run(refresh_recommendations_batch_activity, batch))+ first = _run_batch_activity(batch)assert first.recommendations_kicked == 8- second = asyncio.run(ActivityEnvironment().run(refresh_recommendations_batch_activity, batch))+ second = _run_batch_activity(batch)# `alerts` and `rate_limits` have no refresh_interval, so they recompute for both teams;# long_running_issues and source_maps (both 6h) are still fresh and are skipped.assert second.recommendations_kicked == 4+ @patch(_RATE_LIMITS_COMPUTE_BATCH, side_effect=_batch_meta(_RATE_LIMITS_META))+ @patch(_SOURCE_MAPS_COMPUTE_BATCH, side_effect=_batch_meta(_SOURCE_MAPS_META))+ @patch(_LONG_RUNNING_COMPUTE_BATCH, side_effect=_batch_meta(_LONG_RUNNING_META))+ @patch(_ALERTS_COMPUTE_BATCH, side_effect=Exception("boom"))+ def test_failing_recommendation_reverts_claims_and_spares_others(self, _alerts, _long, _source, _rate_limits):+ team_b = Team.objects.create(organization=self.organization, name="Team B")++ result = _run_batch_activity(RefreshBatchInputs(team_ids=[self.team.id, team_b.id]))++ assert result.recommendations_kicked == 6+ alerts_rows = ErrorTrackingRecommendation.objects.filter(type="alerts")+ assert alerts_rows.count() == 2+ for row in alerts_rows:+ assert row.status == ErrorTrackingRecommendation.Status.READY+ assert row.computed_at is None++ @patch(_RATE_LIMITS_COMPUTE_BATCH, side_effect=_batch_meta(_RATE_LIMITS_META))+ @patch(_SOURCE_MAPS_COMPUTE_BATCH, side_effect=_batch_meta(_SOURCE_MAPS_META))+ @patch(_LONG_RUNNING_COMPUTE_BATCH, side_effect=_batch_meta(_LONG_RUNNING_META))+ @patch(_ALERTS_COMPUTE_BATCH, side_effect=lambda team_ids: {})+ def test_missing_meta_reverts_claim(self, _alerts, _long, _source, _rate_limits):+ result = _run_batch_activity(RefreshBatchInputs(team_ids=[self.team.id]))++ assert result.recommendations_kicked == 3+ alerts_row = ErrorTrackingRecommendation.objects.get(team_id=self.team.id, type="alerts")+ assert alerts_row.status == ErrorTrackingRecommendation.Status.READY+ assert alerts_row.computed_at is None+++class TestLongRunningIssuesComputeBatch(ClickhouseTestMixin, APIBaseTest):+ def setUp(self):+ super().setUp()+ from posthog.clickhouse.client import sync_execute++ sync_execute(TRUNCATE_ERROR_TRACKING_FINGERPRINT_ISSUE_STATE_TABLE_SQL())++ def _create_issue_with_events(+ self, team: Team, fingerprint: str, first_seen, event_count: int, **issue_kwargs+ ) -> ErrorTrackingIssue:+ issue = ErrorTrackingIssue.objects.create(team=team, **issue_kwargs)+ ErrorTrackingIssueFingerprintV2.objects.create(team=team, issue=issue, fingerprint=fingerprint)+ ErrorTrackingIssueFingerprintV2.objects.filter(issue=issue).update(first_seen=first_seen)+ sync_issues_to_clickhouse(issue_ids=[issue.id], team_id=team.id)++ for i in range(event_count):+ _create_event(+ distinct_id=f"u{i}",+ event="$exception",+ team=team,+ timestamp=timezone.now().isoformat(),+ properties={"$exception_fingerprint": fingerprint},+ )+ return issue++ def test_returns_long_running_issues_per_team(self):+ team_b = Team.objects.create(organization=self.organization, name="Team B")+ team_quiet = Team.objects.create(organization=self.organization, name="Quiet")++ old = timezone.now() - timedelta(days=30)+ long_running = self._create_issue_with_events(+ self.team, "fp_old", old, event_count=3, name="Old issue", description="Still firing"+ )+ # Recent issue: first_seen inside the 7 day window, so not long-running.+ self._create_issue_with_events(self.team, "fp_new", timezone.now(), event_count=2, name="New issue")+ # Resolved long-running issue on another team: excluded by status.+ self._create_issue_with_events(+ team_b, "fp_resolved", old, event_count=2, name="Done", status=ErrorTrackingIssue.Status.RESOLVED+ )+ flush_persons_and_events()++ metas = LongRunningIssuesRecommendation().compute_batch([self.team.id, team_b.id, team_quiet.id])++ assert set(metas.keys()) == {self.team.id, team_b.id, team_quiet.id}+ assert metas[team_b.id] == {"issues": []}+ assert metas[team_quiet.id] == {"issues": []}++ issues = metas[self.team.id]["issues"]+ assert len(issues) == 1+ assert issues[0]["id"] == str(long_running.id)+ assert issues[0]["name"] == "Old issue"+ assert issues[0]["description"] == "Still firing"+ assert issues[0]["occurrences"] == 3+ assert issues[0]["status"] == ErrorTrackingIssue.Status.ACTIVE++ def test_compute_delegates_to_batch(self):+ old = timezone.now() - timedelta(days=30)+ issue = self._create_issue_with_events(self.team, "fp_old", old, event_count=1, name="Old issue")+ flush_persons_and_events()++ meta = LongRunningIssuesRecommendation().compute(self.team)++ assert [i["id"] for i in meta["issues"]] == [str(issue.id)]+async def _run_refresh_workflow(- inputs: RecommendationsRefreshInputs | None, team_ids: list[int]+ inputs: RecommendationsRefreshInputs | None, team_batches: list[list[int]]) -> tuple[RecommendationsRefreshResult, list[list[int]]]:captured_batches: list[list[int]] = []- @activity.defn(name="get_teams_with_recent_exceptions_activity")- async def mock_enumerate(activity_inputs: RecommendationsRefreshInputs) -> list[int]:- return team_ids+ @activity.defn(name="get_team_batches_activity")+ async def mock_enumerate(activity_inputs: RecommendationsRefreshInputs) -> list[list[int]]:+ return team_batches@activity.defn(name="refresh_recommendations_batch_activity")async def mock_batch(batch_inputs: RefreshBatchInputs) -> RefreshBatchResult:@@ -154,18 +268,15 @@ async def _run_refresh_workflow(class TestRecommendationsRefreshWorkflow:@pytest.mark.asyncio- async def test_fans_out_into_batches_and_aggregates(self):- inputs = RecommendationsRefreshInputs(batch_size=100, max_concurrent_batches=10)- team_ids = list(range(1, 251))+ async def test_fans_out_batches_and_aggregates(self):+ team_batches = [[1, 2, 3], [4, 5], [6]]- result, batches = await _run_refresh_workflow(inputs, team_ids)+ result, batches = await _run_refresh_workflow(RecommendationsRefreshInputs(), team_batches)- assert result.teams_total == 250- assert result.recommendations_kicked == 250+ assert result.teams_total == 6+ assert result.recommendations_kicked == 6assert result.batches_failed == 0- assert len(batches) == 3- assert sorted(len(b) for b in batches) == [50, 100, 100]- assert sorted(team for batch in batches for team in batch) == team_ids+ assert sorted(batches) == sorted(team_batches)@pytest.mark.asyncioasync def test_no_eligible_teams_skips_batch_activity(self):diff --git a/products/error_tracking/backend/temporal/recommendations_refresh/types.py b/products/error_tracking/backend/temporal/recommendations_refresh/types.pyindex c965309c49d2..fb6061899dbc 100644--- a/products/error_tracking/backend/temporal/recommendations_refresh/types.py+++ b/products/error_tracking/backend/temporal/recommendations_refresh/types.py@@ -5,10 +5,14 @@ import dataclassesclass RecommendationsRefreshInputs:# Only sweep teams that ingested at least one $exception within this window.lookback_days: int = 7- # Teams per batch activity.- batch_size: int = 50+ # Max teams per batch activity.+ batch_size: int = 200+ # Max summed exception volume per batch. The batched ClickHouse query's cost scales+ # with event volume rather than team count, so this keeps memory bounded when+ # high-volume teams land in the same batch.+ max_events_per_batch: int = 20_000_000# How many batch activities run at once (bounds ClickHouse/Postgres load).- max_concurrent_batches: int = 20+ max_concurrent_batches: int = 5@dataclasses.dataclass(frozen=True)diff --git a/products/error_tracking/backend/temporal/recommendations_refresh/workflow.py b/products/error_tracking/backend/temporal/recommendations_refresh/workflow.pyindex 303b510a5a73..2c4bd250e0db 100644--- a/products/error_tracking/backend/temporal/recommendations_refresh/workflow.py+++ b/products/error_tracking/backend/temporal/recommendations_refresh/workflow.py@@ -7,7 +7,7 @@ from posthog.temporal.common.base import PostHogWorkflowwith workflow.unsafe.imports_passed_through():from products.error_tracking.backend.temporal.recommendations_refresh.activities import (- get_teams_with_recent_exceptions_activity,+ get_team_batches_activity,refresh_recommendations_batch_activity,)from products.error_tracking.backend.temporal.recommendations_refresh.types import (@@ -24,7 +24,7 @@ ENUMERATE_TIMEOUT = timedelta(minutes=5)BATCH_RETRY_POLICY = common.RetryPolicy(maximum_attempts=2, initial_interval=timedelta(seconds=30))BATCH_START_TO_CLOSE_TIMEOUT = timedelta(minutes=30)-BATCH_HEARTBEAT_TIMEOUT = timedelta(minutes=2)+BATCH_HEARTBEAT_TIMEOUT = timedelta(minutes=5)@workflow.defn(name=WORKFLOW_NAME)@@ -37,18 +37,16 @@ class ErrorTrackingRecommendationsRefreshWorkflow(PostHogWorkflow):if inputs is None:inputs = RecommendationsRefreshInputs()- team_ids = await workflow.execute_activity(- get_teams_with_recent_exceptions_activity,+ batches = await workflow.execute_activity(+ get_team_batches_activity,inputs,start_to_close_timeout=ENUMERATE_TIMEOUT,retry_policy=ENUMERATE_RETRY_POLICY,)- if not team_ids:+ if not batches:return RecommendationsRefreshResult(teams_total=0, recommendations_kicked=0, batches_failed=0)- batches = [team_ids[i : i + inputs.batch_size] for i in range(0, len(team_ids), inputs.batch_size)]-kicked = 0batches_failed = 0# Keep up to max_concurrent_batches activities in flight at all times: the@@ -78,7 +76,7 @@ class ErrorTrackingRecommendationsRefreshWorkflow(PostHogWorkflow):kicked += result.recommendations_kickedreturn RecommendationsRefreshResult(- teams_total=len(team_ids),+ teams_total=sum(len(batch) for batch in batches),recommendations_kicked=kicked,batches_failed=batches_failed,)