: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(activity-log): use cache for advanced filters for small orgs (#113588)
Reece Jones68c0420955e5
diff --git a/docs/internal/activity-logging.md b/docs/internal/activity-logging.mdindex a304541903d5..e45d8615c611 100644--- a/docs/internal/activity-logging.md+++ b/docs/internal/activity-logging.md@@ -280,6 +280,14 @@ When a reader is unavailable, stop using that reader for the run and record theTo audit scheduled scout writes, use the server-derived `scout:<skill_name>` client tag and the run window. The tag identifies a scout, not a run; inspect actors, items, and timestamps when runs overlap.Do not infer that no configuration change occurred from missing access.+### Available filters++`advanced_activity_logs/available_filters/` checks the organization-wide cache before counting activity rows.+For organizations with at most 20,000 rows, cache hits reuse detail field names without fetching detail documents.+Static options (users, scopes, activities, and clients) still use distinct values from the request's visibility-filtered queryset.+Small organizations cache discovered detail fields for 12 hours, so new detail field names can take that long to appear.+On a cache miss, organizations with at most 20,000 rows run discovery in the request; larger organizations return empty filters until the background refresh populates the cache.+A scene that wants its own paginated history registers its URL in `activityLogLogic.tsx`.Most scenes do not need this; the side panel and deep links work without it.diff --git a/posthog/api/advanced_activity_logs/field_discovery.py b/posthog/api/advanced_activity_logs/field_discovery.pyindex c72d7f745568..aed1128e8199 100644--- a/posthog/api/advanced_activity_logs/field_discovery.py+++ b/posthog/api/advanced_activity_logs/field_discovery.py@@ -27,17 +27,23 @@ class AdvancedActivityLogFieldDiscovery:self.organization_id = organization_iddef get_available_filters(self, base_queryset: QuerySet) -> dict[str, Any]:+ cached = get_cached_fields(str(self.organization_id))record_count = self._get_org_record_count()if record_count > SMALL_ORG_THRESHOLD:- cached = get_cached_fields(str(self.organization_id))- if cached:+ if cached is not None:return cachedreturn {"static_filters": {"users": [], "scopes": [], "activities": [], "clients": []},"detail_fields": {},}+ if cached is not None:+ return {+ "static_filters": self._get_static_filters(base_queryset),+ "detail_fields": cached["detail_fields"],+ }+static_filters = self._get_static_filters(base_queryset)detail_fields = self._analyze_detail_fields_memory()@@ -58,7 +64,9 @@ class AdvancedActivityLogFieldDiscovery:}def _get_available_users(self, queryset: QuerySet) -> list[dict[str, str]]:- users_query = queryset.values("user__uuid", "user__first_name", "user__last_name", "user__email").distinct()+ users_query = (+ queryset.order_by().values("user__uuid", "user__first_name", "user__last_name", "user__email").distinct()+ )seen_users = set()unique_users = []@@ -75,17 +83,17 @@ class AdvancedActivityLogFieldDiscovery:return unique_usersdef _get_available_scopes(self, queryset: QuerySet) -> list[dict[str, str]]:- scopes_query = queryset.values_list("scope", flat=True)+ scopes_query = queryset.order_by().values_list("scope", flat=True).distinct()scopes = set(scopes_query)return [{"value": scope} for scope in sorted(scopes) if scope]def _get_available_activities(self, queryset: QuerySet) -> list[dict[str, str]]:- activities_query = queryset.values_list("activity", flat=True)+ activities_query = queryset.order_by().values_list("activity", flat=True).distinct()activities = set(activities_query)return [{"value": activity} for activity in sorted(activities) if activity]def _get_available_clients(self, queryset: QuerySet) -> list[dict[str, str]]:- clients_query = queryset.values_list("client", flat=True)+ clients_query = queryset.order_by().values_list("client", flat=True).distinct()clients = set(clients_query)return [{"value": client} for client in sorted(c for c in clients if c)]diff --git a/posthog/api/advanced_activity_logs/test_field_discovery.py b/posthog/api/advanced_activity_logs/test_field_discovery.pyindex e03efcc28608..8c17deb0e4a6 100644--- a/posthog/api/advanced_activity_logs/test_field_discovery.py+++ b/posthog/api/advanced_activity_logs/test_field_discovery.py@@ -1,6 +1,7 @@from typing import Anyfrom posthog.test.base import BaseTest+from unittest.mock import patchfrom posthog.api.advanced_activity_logs.fields_cache import _get_cache_key, get_clientfrom posthog.models.activity_logging.activity_log import ActivityLog@@ -110,3 +111,35 @@ class FieldDiscoveryTest(BaseTest):self._create_activity_log("Dashboard", detail)results = self._run_field_discovery()self._assert_field_discovered(results, "Dashboard", field_pattern, expected_types)++ with self.assertNumQueries(5):+ cached_results = self._run_field_discovery()+ self.assertEqual(cached_results, results)++ @patch("posthog.api.advanced_activity_logs.field_discovery.SMALL_ORG_THRESHOLD", 0)+ def test_large_org_uses_cache_without_static_filter_queries(self) -> None:+ self._create_activity_log("Dashboard", {"name": "example"})++ with self.assertNumQueries(1):+ results = self._run_field_discovery()+ self.assertEqual(results["detail_fields"], {})+ self.assertTrue(all(not options for options in results["static_filters"].values()))++ self.discovery.process_batch_for_large_org([{"scope": "Dashboard", "detail": {"name": "example"}}])+ with self.assertNumQueries(1):+ results = self._run_field_discovery()+ self.assertIn({"value": "Dashboard"}, results["static_filters"]["scopes"])+ self._assert_field_discovered(results, "Dashboard", "name", ["string"])++ def test_cached_detail_fields_preserve_static_filter_scope(self) -> None:+ self._create_activity_log("Dashboard", {"name": "example"})+ self._create_activity_log("Insight", {"description": "example"})+ queryset = ActivityLog.objects.filter(organization_id=self.organization.id)++ self.discovery.get_available_filters(queryset.filter(scope="Dashboard"))+ with self.assertNumQueries(5):+ results = self.discovery.get_available_filters(queryset.filter(scope="Insight"))++ self.assertEqual(results["static_filters"]["scopes"], [{"value": "Insight"}])+ self._assert_field_discovered(results, "Dashboard", "name", ["string"])+ self._assert_field_discovered(results, "Insight", "description", ["string"])