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.

chore(views): add missing activity logging to saved queries (#59197)

Jovan Sakovicfaea46710e6c
diff --git a/.env.local.example b/.env.local.example
index 39e67f4ced97..0dd12b1c6202 100644
--- a/.env.local.example
+++ b/.env.local.example
@@ -15,6 +15,10 @@
# AZURE_INFERENCE_ENDPOINT=op://General/yw6efvcz5ooxx5fgll3kyang5a/username
# AZURE_INFERENCE_CREDENTIAL=op://General/yw6efvcz5ooxx5fgll3kyang5a/credential
+# ── Billing - Enterprise license (PostHog employees) ──────────────────
+# STRIPE_PUBLIC_KEY="op://General/vr7jkjl3ael7mj3rlbi4ojy3wm/credential"
+# LICENSE_SECRET_KEY="op://General/fn3h7kn2j6tt3sah7d2fhitsri/credential"
+
# ── Personal overrides ────────────────────────────────────────────────
# Auto-login as a specific user (skips the login flow)
diff --git a/frontend/src/scenes/data-warehouse/saved_queries/activityDescriptions.tsx b/frontend/src/scenes/data-warehouse/saved_queries/activityDescriptions.tsx
index 666023c52546..bd79efe70669 100644
--- a/frontend/src/scenes/data-warehouse/saved_queries/activityDescriptions.tsx
+++ b/frontend/src/scenes/data-warehouse/saved_queries/activityDescriptions.tsx
@@ -1,4 +1,5 @@
import {
+ ActivityChange,
ActivityLogItem,
HumanizedChange,
defaultDescriber,
@@ -6,6 +7,49 @@ import {
} from 'lib/components/ActivityLog/humanizeActivity'
import { SentenceList } from 'lib/components/ActivityLog/SentenceList'
+// Mirrors backend `sync_frequency_to_sync_frequency_interval` in
+// products/data_warehouse/backend/models/external_data_schema.py — the values arrive
+// as `str(timedelta(...))` ("H:MM:SS" or "X day(s), H:MM:SS"). Falls through to the raw
+// string for any unmapped interval, so the UI degrades gracefully if a new bucket lands
+// on the backend before this map is updated.
+function humanizeInterval(raw: string | null | undefined): string {
+ if (!raw) {
+ return 'none'
+ }
+ const buckets: Record<string, string> = {
+ '0:01:00': '1 minute',
+ '0:05:00': '5 minutes',
+ '0:15:00': '15 minutes',
+ '0:30:00': '30 minutes',
+ '1:00:00': '1 hour',
+ '6:00:00': '6 hours',
+ '12:00:00': '12 hours',
+ '1 day, 0:00:00': '1 day',
+ '7 days, 0:00:00': '7 days',
+ '30 days, 0:00:00': '30 days',
+ }
+ return buckets[raw] ?? raw
+}
+
+function describeChange(change: ActivityChange): JSX.Element | null {
+ if (change.field === 'sync_frequency_interval') {
+ const before = humanizeInterval(change.before as string | null)
+ const after = humanizeInterval(change.after as string | null)
+ return (
+ <>
+ changed sync frequency from <strong>{before}</strong> to <strong>{after}</strong>
+ </>
+ )
+ }
+ if (change.field === 'is_materialized') {
+ return <>{change.after ? <>enabled materialization</> : <>disabled materialization</>}</>
+ }
+ if (change.field === 'query') {
+ return <>updated the query</>
+ }
+ return <>changed {change.field}</>
+}
+
export function dataWarehouseSavedQueryActivityDescriber(
logItem: ActivityLogItem,
asNotification?: boolean
@@ -15,31 +59,62 @@ export function dataWarehouseSavedQueryActivityDescriber(
return { description: null }
}
+ const user = <strong className="ph-no-capture">{userNameForLogItem(logItem)}</strong>
+
if (logItem.activity === 'created') {
return {
- description: (
- <SentenceList
- listParts={[<>created a new view</>]}
- prefix={
- <>
- <strong className="ph-no-capture">{userNameForLogItem(logItem)}</strong>
- </>
- }
- />
- ),
+ description: <SentenceList listParts={[<>created a new view</>]} prefix={user} />,
}
}
if (logItem.activity === 'updated') {
+ const changes = logItem.detail?.changes ?? []
+ const parts = changes.map(describeChange).filter((p): p is JSX.Element => p !== null)
+ return {
+ description: <SentenceList listParts={parts.length > 0 ? parts : [<>updated the view</>]} prefix={user} />,
+ }
+ }
+
+ if (logItem.activity === 'sync_triggered') {
+ return { description: <SentenceList listParts={[<>triggered an ad-hoc sync</>]} prefix={user} /> }
+ }
+
+ if (logItem.activity === 'sync_cancelled') {
+ return { description: <SentenceList listParts={[<>cancelled a running sync</>]} prefix={user} /> }
+ }
+
+ if (logItem.activity === 'materialization_enabled') {
+ const changes = logItem.detail?.changes ?? []
+ const freqChange = changes.find((c) => c.field === 'sync_frequency_interval')
+ const parts: JSX.Element[] = [<>enabled materialization</>]
+ if (freqChange) {
+ const after = humanizeInterval(freqChange.after as string | null)
+ parts.push(
+ <>
+ with sync frequency <strong>{after}</strong>
+ </>
+ )
+ }
+ return { description: <SentenceList listParts={parts} prefix={user} /> }
+ }
+
+ if (logItem.activity === 'materialization_disabled') {
+ return { description: <SentenceList listParts={[<>disabled materialization</>]} prefix={user} /> }
+ }
+
+ if (logItem.activity === 'sync_frequency_reset') {
+ const changes = logItem.detail?.changes ?? []
+ const freqChange = changes.find((c) => c.field === 'sync_frequency_interval')
+ const after = freqChange ? humanizeInterval(freqChange.after as string | null) : 'default'
return {
description: (
<SentenceList
- listParts={[<>updated the view</>]}
- prefix={
+ listParts={[
<>
- <strong className="ph-no-capture">{userNameForLogItem(logItem)}</strong>
- </>
- }
+ auto-reset sync frequency to <strong>{after}</strong>
+ </>,
+ ]}
+ prefix={user}
/>
),
}
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index ae5a178866eb..50ad13f4af9b 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -458,7 +458,6 @@ field_exclusions: dict[ActivityScope, list[str]] = {
"external_tables",
"last_run_at",
"latest_error",
- "sync_frequency_interval",
"deleted_name",
],
"Endpoint": [
diff --git a/products/data_warehouse/backend/api/saved_query.py b/products/data_warehouse/backend/api/saved_query.py
index bb82959525c8..b66e07ee9cb1 100644
--- a/products/data_warehouse/backend/api/saved_query.py
+++ b/products/data_warehouse/backend/api/saved_query.py
@@ -31,7 +31,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.api.scoped_related_fields import TeamScopedPrimaryKeyRelatedField
from posthog.api.shared import UserBasicSerializer
from posthog.exceptions_capture import capture_exception
-from posthog.models import Team
+from posthog.models import Team, User
from posthog.models.activity_logging.activity_log import (
ActivityLog,
Change,
@@ -809,6 +809,17 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe
trigger_saved_query_schedule(saved_query)
+ log_activity(
+ organization_id=self.team.organization_id,
+ team_id=self.team_id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ item_id=saved_query.id,
+ scope="DataWarehouseSavedQuery",
+ activity="sync_triggered",
+ detail=Detail(name=saved_query.name),
+ )
+
return response.Response(status=status.HTTP_200_OK)
@action(
@@ -839,6 +850,17 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe
capture_exception(e)
logger.exception("Failed to update node type to view", saved_query_name=saved_query.name)
+ log_activity(
+ organization_id=self.team.organization_id,
+ team_id=self.team_id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ item_id=saved_query.id,
+ scope="DataWarehouseSavedQuery",
+ activity="materialization_disabled",
+ detail=Detail(name=saved_query.name),
+ )
+
return response.Response(status=status.HTTP_200_OK)
@action(
@@ -859,6 +881,7 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe
sync_frequency_interval = sync_frequency_to_sync_frequency_interval("24hour")
should_unpause = saved_query.sync_frequency_interval is None
+ previous_interval = saved_query.sync_frequency_interval
saved_query.sync_frequency_interval = sync_frequency_interval
saved_query.is_materialized = True
@@ -886,6 +909,28 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe
capture_exception(e)
logger.exception("Failed to update node type to matview", saved_query_name=saved_query.name)
+ log_activity(
+ organization_id=self.team.organization_id,
+ team_id=self.team_id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ item_id=saved_query.id,
+ scope="DataWarehouseSavedQuery",
+ activity="materialization_enabled",
+ detail=Detail(
+ name=saved_query.name,
+ changes=[
+ Change(
+ field="sync_frequency_interval",
+ action="changed",
+ type="DataWarehouseSavedQuery",
+ before=str(previous_interval) if previous_interval else None,
+ after=str(sync_frequency_interval),
+ ),
+ ],
+ ),
+ )
+
return response.Response(status=status.HTTP_200_OK)
@action(methods=["POST"], detail=False)
@@ -1031,14 +1076,25 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe
# This is because the saved_query is used by our UI to prevent multiple cancellations
saved_query.status = DataWarehouseSavedQuery.Status.CANCELLED
saved_query.save()
-
- return response.Response(status=status.HTTP_200_OK)
except Exception as e:
logger.exception("Failed to cancel workflow", workflow_id=workflow_id, error=str(e))
return response.Response(
{"error": f"Failed to cancel workflow"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR
)
+ log_activity(
+ organization_id=self.team.organization_id,
+ team_id=self.team_id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ item_id=saved_query.id,
+ scope="DataWarehouseSavedQuery",
+ activity="sync_cancelled",
+ detail=Detail(name=saved_query.name),
+ )
+
+ return response.Response(status=status.HTTP_200_OK)
+
@action(methods=["GET"], detail=True)
def dependencies(self, request: request.Request, *args, **kwargs) -> response.Response:
"""Return the count of immediate upstream and downstream dependencies for this saved query."""
diff --git a/products/data_warehouse/backend/data_load/saved_query_service.py b/products/data_warehouse/backend/data_load/saved_query_service.py
index e8710ad7ddeb..2597d4982279 100644
--- a/products/data_warehouse/backend/data_load/saved_query_service.py
+++ b/products/data_warehouse/backend/data_load/saved_query_service.py
@@ -14,6 +14,7 @@ from temporalio.client import (
)
from temporalio.common import RetryPolicy, SearchAttributePair, TypedSearchAttributes
+from posthog.models.activity_logging.activity_log import Change, Detail, log_activity
from posthog.temporal.common.client import async_connect, sync_connect
from posthog.temporal.common.schedule import (
a_pause_schedule,
@@ -127,8 +128,32 @@ def unpause_saved_query_schedule(saved_query: "DataWarehouseSavedQuery") -> None
# reset the automatic sync interval for rev analytics
viewset = saved_query.managed_viewset
if viewset and viewset.kind == "revenue_analytics":
- saved_query.sync_frequency_interval = timedelta(hours=12)
+ previous_interval = saved_query.sync_frequency_interval
+ new_interval = timedelta(hours=12)
+ saved_query.sync_frequency_interval = new_interval
saved_query.save()
+ if previous_interval != new_interval:
+ log_activity(
+ organization_id=saved_query.team.organization_id,
+ team_id=saved_query.team_id,
+ user=None,
+ was_impersonated=False,
+ item_id=saved_query.id,
+ scope="DataWarehouseSavedQuery",
+ activity="sync_frequency_reset",
+ detail=Detail(
+ name=saved_query.name,
+ changes=[
+ Change(
+ field="sync_frequency_interval",
+ action="changed",
+ type="DataWarehouseSavedQuery",
+ before=str(previous_interval) if previous_interval else None,
+ after=str(new_interval),
+ ),
+ ],
+ ),
+ )
def saved_query_workflow_exists(saved_query: "DataWarehouseSavedQuery") -> bool:
diff --git a/products/endpoints/backend/api.py b/products/endpoints/backend/api.py
index be60f438612e..763d626a7c89 100644
--- a/products/endpoints/backend/api.py
+++ b/products/endpoints/backend/api.py
@@ -898,7 +898,7 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.Model
# Step 1: Handle deactivation (disables materialization, prevents any materialization operations)
if not final_is_active and was_materialized:
- self._disable_materialization(endpoint, current_version)
+ self._disable_materialization(endpoint, request, current_version)
# Step 2: Handle query changes and versioning (independent of active/materialization state)
old_bucket_overrides: dict[str, str] | None = None
@@ -997,7 +997,7 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.Model
else:
raise
elif should_disable:
- self._disable_materialization(endpoint, target_version)
+ self._disable_materialization(endpoint, request, target_version)
endpoint_changes = changes_between("Endpoint", previous=endpoint_before_update, current=endpoint)
if endpoint_changes:
@@ -1100,6 +1100,21 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.Model
try:
self._enable_materialization_inner(endpoint, data_freshness_seconds, request, version, bucket_overrides)
ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="enable", status="success").inc()
+ target_version = version or endpoint.get_version()
+ if target_version and target_version.saved_query:
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ item_id=str(target_version.saved_query.id),
+ scope="DataWarehouseSavedQuery",
+ activity="materialization_enabled",
+ detail=Detail(
+ name=target_version.saved_query.name,
+ context=EndpointContext(version=target_version.version),
+ ),
+ )
except ValidationError:
ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="enable", status="validation_error").inc()
raise
@@ -1167,7 +1182,9 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.Model
version.bucket_overrides = bucket_overrides
version.save(update_fields=["saved_query", "bucket_overrides", "updated_at"])
- def _disable_materialization(self, endpoint: Endpoint, version: EndpointVersion | None = None) -> None:
+ def _disable_materialization(
+ self, endpoint: Endpoint, request: Request, version: EndpointVersion | None = None
+ ) -> None:
"""Disable materialization for an endpoint version.
If version is not specified, uses the current version.
@@ -1175,6 +1192,8 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.Model
version = version or endpoint.get_version()
if version:
if version.saved_query:
+ saved_query_id = str(version.saved_query.id)
+ saved_query_name = version.saved_query.name
try:
delete_node_from_dag(version.saved_query)
except Exception as e:
@@ -1198,6 +1217,19 @@ class EndpointViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.Model
ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="disable", status="error").inc()
raise
ENDPOINT_MATERIALIZATION_EVENT_TOTAL.labels(action="disable", status="success").inc()
+ log_activity(
+ organization_id=self.organization.id,
+ team_id=self.team.id,
+ user=cast(User, request.user),
+ was_impersonated=is_impersonated_session(request),
+ item_id=saved_query_id,
+ scope="DataWarehouseSavedQuery",
+ activity="materialization_disabled",
+ detail=Detail(
+ name=saved_query_name,
+ context=EndpointContext(version=version.version),
+ ),
+ )
clear_endpoint_materialization_cache(self.team_id, endpoint.name)
def destroy(self, request: Request, name=None, *args, **kwargs) -> Response:
diff --git a/products/endpoints/backend/tests/test_endpoint_execution.py b/products/endpoints/backend/tests/test_endpoint_execution.py
index 30555becc028..2982fdef88d4 100644
--- a/products/endpoints/backend/tests/test_endpoint_execution.py
+++ b/products/endpoints/backend/tests/test_endpoint_execution.py
@@ -2152,7 +2152,7 @@ class TestEndpointExecution(ClickhouseTestMixin, APIBaseTest):
viewset = EndpointViewSet()
viewset.team_id = self.team.id
- viewset._disable_materialization(endpoint)
+ viewset._disable_materialization(endpoint, mock.MagicMock())
after = REGISTRY.get_sample_value("posthog_endpoint_materialization_event_total", labels) or 0.0
self.assertEqual(after - before, 0.0)