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(data-warehouse): track saved query edits with a revision column (#102183)

Jovan Sakovic2c8b81888053
diff --git a/posthog/api/test/__snapshots__/test_element.ambr b/posthog/api/test/__snapshots__/test_element.ambr
index 881d11e72fca..428d1765c90b 100644
--- a/posthog/api/test/__snapshots__/test_element.ambr
+++ b/posthog/api/test/__snapshots__/test_element.ambr
@@ -476,6 +476,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambr
index e3df1de78733..3183b0a1cf61 100644
--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr
+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr
@@ -44,6 +44,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -272,6 +273,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.py
index 7dd6072e99e0..6ea64395387f 100644
--- a/posthog/models/activity_logging/activity_log.py
+++ b/posthog/models/activity_logging/activity_log.py
@@ -773,6 +773,7 @@ field_exclusions: dict[AuditableScope, list[str]] = {
"DataWarehouseSavedQuery": [
"name",
"columns",
+ "query_revision",
"status",
"external_tables",
"last_run_at",
diff --git a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr
index 6cb375c0eef6..23e65990e73c 100644
--- a/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr
+++ b/posthog/session_recordings/test/__snapshots__/test_session_recording_playlist.ambr
@@ -1018,6 +1018,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
diff --git a/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambr b/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambr
index 0ffc54ef9f7f..8f8910e2b9a5 100644
--- a/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambr
+++ b/posthog/session_recordings/test/__snapshots__/test_session_recordings.ambr
@@ -566,6 +566,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -1221,6 +1222,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -1873,6 +1875,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -2525,6 +2528,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -3180,6 +3184,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -3835,6 +3840,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -4490,6 +4496,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -5166,6 +5173,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -5888,6 +5896,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -6594,6 +6603,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -7454,6 +7464,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -7831,6 +7842,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -8667,6 +8679,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -9332,6 +9345,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -10085,6 +10099,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -10287,6 +10302,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -10796,6 +10812,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
@@ -11518,6 +11535,7 @@
"posthog_datawarehousesavedquery"."column_order",
"posthog_datawarehousesavedquery"."external_tables",
"posthog_datawarehousesavedquery"."query",
+ "posthog_datawarehousesavedquery"."query_revision",
"posthog_datawarehousesavedquery"."status",
"posthog_datawarehousesavedquery"."last_run_at",
"posthog_datawarehousesavedquery"."sync_frequency_interval",
diff --git a/products/data_modeling/backend/migrations/0043_datawarehousesavedquery_query_revision.py b/products/data_modeling/backend/migrations/0043_datawarehousesavedquery_query_revision.py
new file mode 100644
index 000000000000..775690788096
--- /dev/null
+++ b/products/data_modeling/backend/migrations/0043_datawarehousesavedquery_query_revision.py
@@ -0,0 +1,25 @@
+import uuid
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("data_modeling", "0042_dwsavedquery_team_live_matvw_idx"),
+ ]
+
+ operations = [
+ # Added without a default so existing rows stay NULL instead of all receiving one shared
+ # value; the column is metadata-only on Postgres this way.
+ migrations.AddField(
+ model_name="datawarehousesavedquery",
+ name="query_revision",
+ field=models.UUIDField(blank=True, null=True),
+ ),
+ # A Python-level default only; this emits no SQL.
+ migrations.AlterField(
+ model_name="datawarehousesavedquery",
+ name="query_revision",
+ field=models.UUIDField(blank=True, default=uuid.uuid4, null=True),
+ ),
+ ]
diff --git a/products/data_modeling/backend/migrations/max_migration.txt b/products/data_modeling/backend/migrations/max_migration.txt
index 5bd5123cd4d0..e38f0fa24db5 100644
--- a/products/data_modeling/backend/migrations/max_migration.txt
+++ b/products/data_modeling/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0042_dwsavedquery_team_live_matvw_idx
+0043_datawarehousesavedquery_query_revision
diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.py
index cdb52884a2e7..e404464305b3 100644
--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py
+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py
@@ -118,6 +118,8 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,
)
external_tables = models.JSONField(default=list, null=True, blank=True, help_text="List of all external tables")
query = models.JSONField(default=dict, null=True, blank=True, help_text="HogQL query")
+ # Null on rows that predate the column; the write path accepts any token for those until their first edit.
+ query_revision = models.UUIDField(default=uuid.uuid4, null=True, blank=True)
status = models.CharField(
null=True, choices=Status, max_length=64, help_text="The status of when this SavedQuery last ran."
)
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/editing.py b/products/data_warehouse/backend/presentation/views/saved_query/editing.py
index 512fe4a26af6..66517b05e943 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query/editing.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query/editing.py
@@ -23,7 +23,7 @@ from posthog.errors import ExposedCHQueryError
from posthog.exceptions_capture import capture_exception
from posthog.helpers.impersonation import is_impersonated
from posthog.models import Team, User
-from posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail, changes_between, log_activity
+from posthog.models.activity_logging.activity_log import Change, Detail, changes_between, log_activity
from posthog.rbac.query_access import assert_user_can_read_query
from products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin
@@ -44,6 +44,16 @@ from . import incremental_config, sync_cadence, view_description, view_state
logger = structlog.get_logger(__name__)
+def _as_uuid(value: object) -> uuid.UUID | None:
+ # Clients echo the revision back in whatever UUID form their stack produces, so parse both
+ # sides before comparing. A raw string comparison rejects an uppercase or unhyphenated spelling
+ # of the same revision as a foreign edit.
+ try:
+ return uuid.UUID(str(value))
+ except (AttributeError, TypeError, ValueError):
+ return None
+
+
def _view_types_validation_error(e: Exception) -> serializers.ValidationError:
# Column inference runs the HogQL-to-ClickHouse path, so a raw exception can carry stack
# traces, internal table or column names, and S3 URIs. Surface only the errors already marked
@@ -54,14 +64,6 @@ def _view_types_validation_error(e: Exception) -> serializers.ValidationError:
return serializers.ValidationError(f"Failed to retrieve types for view: unexpected {type(e).__name__}")
-# A DataWarehouseSavedQuery's activity log also records materialization syncs and status
-# transitions (activity="sync_triggered", status changes) that advance the log without the query
-# being edited. Optimistic-concurrency ("modified by someone else") must key off the latest activity
-# that actually changed the query — otherwise every background sync of a materialized view looks
-# like a foreign edit and blocks the next save. This filter scopes activity lookups to query edits.
-QUERY_CHANGE_ACTIVITY_FILTER = {"detail__changes__contains": [{"field": "query"}]}
-
-
class DataWarehouseSavedQuerySerializer(
view_state.DataWarehouseSavedQuerySerializerMixin, UserAccessControlSerializerMixin, serializers.ModelSerializer
):
@@ -94,11 +96,13 @@ class DataWarehouseSavedQuerySerializer(
sync_frequency_bounds = serializers.SerializerMethodField(
read_only=True, help_text=sync_cadence.SYNC_FREQUENCY_BOUNDS_HELP_TEXT
)
- latest_history_id = serializers.SerializerMethodField(
+ latest_history_id = serializers.UUIDField(
+ source="query_revision",
read_only=True,
- help_text="Activity log ID of the most recent query edit to this view. Send it back as "
- "edited_history_id on the next query write, so conflict detection can tell whether someone else "
- "changed the query in the meantime. Edits that leave the query alone do not advance it.",
+ allow_null=True,
+ help_text="Revision of this view's query. Send it back as edited_history_id on the next query "
+ "write, so conflict detection can tell whether someone else changed the query in the meantime. "
+ "Edits that leave the query alone do not advance it.",
)
last_run_at = serializers.SerializerMethodField(read_only=True)
status = serializers.SerializerMethodField(read_only=True)
@@ -122,7 +126,8 @@ class DataWarehouseSavedQuerySerializer(
write_only=True,
required=False,
allow_null=True,
- help_text="Activity log ID from the last known edit. Used for conflict detection.",
+ help_text="The latest_history_id you last read for this view. Required when changing the query. "
+ "The write is refused if someone else changed the query in the meantime.",
)
soft_update = serializers.BooleanField(
write_only=True,
@@ -226,19 +231,6 @@ class DataWarehouseSavedQuerySerializer(
saved_query=view, column_name=""
).delete()
- @extend_schema_field(serializers.UUIDField(allow_null=True))
- def get_latest_history_id(self, view: DataWarehouseSavedQuery) -> uuid.UUID | None:
- # First check if we have an activity log from a recent creation/update
- if (
- "activity_log" in self.context
- and self.context["activity_log"]
- and self.context["activity_log"].item_id == str(view.id)
- ):
- return self.context["activity_log"].id
-
- # Otherwise check for annotated field from queryset
- return cast(uuid.UUID | None, getattr(view, "latest_activity_id", None))
-
@extend_schema_field(
serializers.DictField(
child=view_state.SavedQuerySuspensionSerializer(),
@@ -304,7 +296,7 @@ class DataWarehouseSavedQuerySerializer(
team = Team.objects.get(id=view.team_id)
- activity_log = log_activity(
+ log_activity(
organization_id=team.organization_id,
team_id=team.id,
user=view.created_by,
@@ -325,10 +317,6 @@ class DataWarehouseSavedQuerySerializer(
],
),
)
-
- # Store the activity log in the serializer context
- if activity_log:
- self.context["activity_log"] = activity_log
# best effort sync to new data modeling DAG representation
try:
from products.data_modeling.backend.facade.api import sync_saved_query_to_dag
@@ -378,25 +366,16 @@ class DataWarehouseSavedQuerySerializer(
with transaction.atomic():
locked_instance = DataWarehouseSavedQuery.objects.select_for_update().get(pk=instance.pk)
- # Get latest activity log for this model
+ query_changed = "query" in validated_data and validated_data["query"] != locked_instance.query
- if validated_data.get("query", None) and not soft_update:
+ if query_changed and not soft_update and locked_instance.query_revision is not None:
edited_history_id = self.context["request"].data.get("edited_history_id", None)
- latest_activity_id = (
- ActivityLog.objects.filter(
- team_id=locked_instance.team_id,
- item_id=locked_instance.id,
- scope="DataWarehouseSavedQuery",
- **QUERY_CHANGE_ACTIVITY_FILTER,
- )
- .order_by("-created_at")
- .values_list("id", flat=True)
- .first()
- )
-
- if str(edited_history_id) != str(latest_activity_id):
+ if _as_uuid(edited_history_id) != locked_instance.query_revision:
raise serializers.ValidationError("The query was modified by someone else.")
+ if query_changed:
+ validated_data["query_revision"] = uuid.uuid4()
+
if frequency_changed:
# The node target is the only store of frequency intent. The interval column
# stays NULL so a stale v1 schedule can never be revived from it.
@@ -502,7 +481,7 @@ class DataWarehouseSavedQuerySerializer(
after=str(target) if target is not None else None,
)
)
- activity_log = log_activity(
+ log_activity(
organization_id=team.organization_id,
team_id=team.id,
user=self.context["request"].user,
@@ -512,23 +491,6 @@ class DataWarehouseSavedQuerySerializer(
activity="updated",
detail=Detail(name=view.name, changes=changes),
)
-
- # Store the activity log in the serializer context
- if activity_log:
- self.context["activity_log"] = activity_log
- else:
- # get latest query-changing activity log for this model (see QUERY_CHANGE_ACTIVITY_FILTER)
- latest_activity_log = (
- ActivityLog.objects.filter(
- team_id=locked_instance.team_id,
- item_id=locked_instance.id,
- scope="DataWarehouseSavedQuery",
- **QUERY_CHANGE_ACTIVITY_FILTER,
- )
- .order_by("-created_at")
- .first()
- )
- self.context["activity_log"] = latest_activity_log
# best effort sync to new data modeling DAG representation
if "query" in validated_data:
try:
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/viewset.py b/products/data_warehouse/backend/presentation/views/saved_query/viewset.py
index 9b387fb4f4d5..84536ec83772 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query/viewset.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query/viewset.py
@@ -3,8 +3,7 @@
from dataclasses import dataclass
from typing import Any, cast
-from django.db.models import Model, OuterRef, Prefetch, Subquery, TextField
-from django.db.models.functions import Cast
+from django.db.models import Model, Prefetch
import structlog
import posthoganalytics
@@ -22,7 +21,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin
from posthog.exceptions_capture import capture_exception
from posthog.helpers.impersonation import is_impersonated
from posthog.models import User
-from posthog.models.activity_logging.activity_log import ActivityLog, Change, Detail, load_activity, log_activity
+from posthog.models.activity_logging.activity_log import Change, Detail, load_activity, log_activity
from posthog.models.activity_logging.activity_page import activity_page_response, parse_activity_page_params
from posthog.rate_limit import MaterializationRateThrottle, RunSavedQueryRateThrottle
from posthog.rbac.query_access import assert_user_can_read_query
@@ -195,24 +194,6 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe
if not is_managed_viewset_enabled:
base_queryset = base_queryset.filter(managed_viewset__isnull=True)
- # Only the detail serializer returns `latest_history_id`, and the subquery costs a jsonb
- # key-path filter the GIN index on `detail` cannot serve, so keep it off the list page.
- if getattr(self, "action", None) == "retrieve":
- # Scoped to query edits (see QUERY_CHANGE_ACTIVITY_FILTER) so materialization syncs
- # don't advance the head.
- latest_activity = (
- ActivityLog.objects.filter(
- scope="DataWarehouseSavedQuery",
- item_id=Cast(OuterRef("id"), output_field=TextField()),
- team_id=self.team_id,
- **editing.QUERY_CHANGE_ACTIVITY_FILTER,
- )
- .order_by("-created_at")
- .values("id")[:1]
- )
-
- return base_queryset.annotate(latest_activity_id=Subquery(latest_activity))
-
return base_queryset
def create(self, request, *args, **kwargs):
diff --git a/products/data_warehouse/backend/tests/api/test_saved_query.py b/products/data_warehouse/backend/tests/api/test_saved_query.py
index 542c52f80c17..207e3ea09b55 100644
--- a/products/data_warehouse/backend/tests/api/test_saved_query.py
+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py
@@ -16,7 +16,6 @@ from django.utils import timezone
from parameterized import parameterized
from posthog.models import ActivityLog
-from posthog.models.activity_logging.activity_log import Detail
from products.data_modeling.backend.facade.api import UnsatisfiableFrequencyError, mark_node_suspended, suspension_state
from products.data_modeling.backend.facade.modeling import DataWarehouseModelPath
@@ -1790,82 +1789,6 @@ class TestSavedQuery(APIBaseTest):
self.assertEqual(response.status_code, 400, response.content)
self.assertEqual(response.json()["detail"], "The query was modified by someone else.")
- def test_update_concurrency_ignores_non_query_activity(self):
- response = self.client.post(
- f"/api/environments/{self.team.id}/warehouse_saved_queries/",
- {
- "name": "sync_view",
- "query": {"kind": "HogQLQuery", "query": "select event as event from events LIMIT 100"},
- },
- )
- self.assertEqual(response.status_code, 201, response.content)
- saved_query = response.json()
- query_change_history_id = saved_query["latest_history_id"]
- self.assertIsNotNone(query_change_history_id)
-
- # A materialized view's sync/status transitions write newer activity logs that do not change
- # the query. They must not advance the optimistic-concurrency head.
- query_activity = ActivityLog.objects.get(id=query_change_history_id)
- ActivityLog.objects.create(
- team_id=self.team.id,
- organization_id=self.team.organization_id,
- activity="sync_triggered",
- scope="DataWarehouseSavedQuery",
- item_id=str(saved_query["id"]),
- detail=Detail(changes=[]),
- created_at=query_activity.created_at + timedelta(minutes=1),
- )
-
- # The concurrency head still points at the last query edit, not the newer sync.
- get_response = self.client.get(f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query['id']}/")
- self.assertEqual(get_response.json()["latest_history_id"], query_change_history_id)
-
- # Saving again based on that head must succeed despite the newer sync activity.
- with patch.object(DataWarehouseSavedQuery, "get_columns") as mock_get_columns:
- mock_get_columns.return_value = {}
- update_response = self.client.patch(
- f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query['id']}",
- {
- "query": {"kind": "HogQLQuery", "query": "select event as event from events LIMIT 10"},
- "edited_history_id": query_change_history_id,
- },
- )
- self.assertEqual(update_response.status_code, 200, update_response.content)
-
- def test_create_with_activity_log_existing_view(self):
- response = self.client.post(
- f"/api/environments/{self.team.id}/warehouse_saved_queries/",
- {
- "name": "event_view",
- "query": {
- "kind": "HogQLQuery",
- "query": "select event as event from events LIMIT 100",
- },
- },
- )
- self.assertEqual(response.status_code, 201, response.content)
- saved_query = response.json()
- self.assertEqual(saved_query["name"], "event_view")
- self.assertEqual(saved_query["query"]["kind"], "HogQLQuery")
- self.assertEqual(saved_query["query"]["query"], "select event as event from events LIMIT 100")
-
- ActivityLog.objects.filter(item_id=saved_query["id"], scope="DataWarehouseSavedQuery").delete()
-
- with patch.object(DataWarehouseSavedQuery, "get_columns") as mock_get_columns:
- mock_get_columns.return_value = {}
- response = self.client.patch(
- f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query['id']}",
- {
- "query": {
- "kind": "HogQLQuery",
- "query": "select event as event from events LIMIT 10",
- },
- "edited_history_id": None,
- },
- )
-
- self.assertEqual(response.status_code, 200, response.content)
-
def test_revert_materialization(self):
response = self.client.post(
f"/api/environments/{self.team.id}/warehouse_saved_queries/",
diff --git a/products/data_warehouse/backend/tests/api/test_saved_query_conflict_token.py b/products/data_warehouse/backend/tests/api/test_saved_query_conflict_token.py
new file mode 100644
index 000000000000..25ad1afaa247
--- /dev/null
+++ b/products/data_warehouse/backend/tests/api/test_saved_query_conflict_token.py
@@ -0,0 +1,178 @@
+import uuid
+import threading
+from collections.abc import Callable
+from typing import TYPE_CHECKING, Any, TypedDict, cast
+
+from posthog.test.base import NonAtomicAPIBaseTest
+from unittest.mock import patch
+
+from django.db import connection
+from django.test import override_settings
+
+from parameterized import parameterized
+
+from posthog.models import ActivityLog
+
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
+
+if TYPE_CHECKING:
+ # The test client's response type only exists in the stubs, and callers here read `.json()` off it.
+ from rest_framework.response import _MonkeyPatchedResponse
+
+# True defers the activity row to on_commit as production does; False is what every other test runs under.
+DEFERRED_AND_IMMEDIATE = [("deferred", True), ("immediate", False)]
+
+
+class SavedQueryResponse(TypedDict):
+ id: str
+ latest_history_id: str
+ query: dict[str, Any]
+
+
+class TestSavedQueryConflictToken(NonAtomicAPIBaseTest):
+ # TransactionTestCase, so the deferred activity row lands when the atomic block commits rather than never.
+ CLASS_DATA_LEVEL_SETUP = False
+
+ def setUp(self) -> None:
+ super().setUp()
+ patcher = patch.object(DataWarehouseSavedQuery, "get_columns", return_value={})
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def _url(self, view_id: str | None = None) -> str:
+ base = f"/api/environments/{self.team.id}/warehouse_saved_queries/"
+ return f"{base}{view_id}" if view_id else base
+
+ def _create(self) -> SavedQueryResponse:
+ response = self.client.post(
+ self._url(),
+ {"name": "event_view", "query": {"kind": "HogQLQuery", "query": "select event from events limit 100"}},
+ )
+ self.assertEqual(response.status_code, 201, response.content)
+ return cast(SavedQueryResponse, response.json())
+
+ def _patch_query(self, view_id: str, sql: str, token: str | None) -> "_MonkeyPatchedResponse":
+ return self.client.patch(
+ self._url(view_id), {"query": {"kind": "HogQLQuery", "query": sql}, "edited_history_id": token}
+ )
+
+ def _revision(self, view_id: str) -> str | None:
+ revision = DataWarehouseSavedQuery.objects.get(id=view_id).query_revision
+ return str(revision) if revision else None
+
+ @parameterized.expand(DEFERRED_AND_IMMEDIATE)
+ def test_create_returns_a_usable_token(self, _name: str, deferred: bool) -> None:
+ with override_settings(ACTIVITY_LOG_TRANSACTION_MANAGEMENT=deferred):
+ created = self._create()
+ self.assertIsNotNone(created["latest_history_id"])
+ self.assertEqual(created["latest_history_id"], self._revision(created["id"]))
+
+ response = self._patch_query(
+ created["id"], "select event from events limit 10", created["latest_history_id"]
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+
+ @parameterized.expand(DEFERRED_AND_IMMEDIATE)
+ def test_update_returns_the_new_head_not_the_one_sent(self, _name: str, deferred: bool) -> None:
+ with override_settings(ACTIVITY_LOG_TRANSACTION_MANAGEMENT=deferred):
+ created = self._create()
+ token = created["latest_history_id"]
+
+ response = self._patch_query(created["id"], "select event from events limit 10", token)
+ self.assertEqual(response.status_code, 200, response.content)
+ new_token = response.json()["latest_history_id"]
+ self.assertNotEqual(new_token, token)
+ self.assertEqual(new_token, self._revision(created["id"]))
+
+ stale = self._patch_query(created["id"], "select event from events limit 5", token)
+ self.assertEqual(stale.status_code, 400, stale.content)
+ chained = self._patch_query(created["id"], "select event from events limit 5", new_token)
+ self.assertEqual(chained.status_code, 200, chained.content)
+
+ def test_edit_that_lands_before_the_lock_is_rejected(self) -> None:
+ created = self._create()
+ token = created["latest_history_id"]
+ other_revision = uuid.uuid4()
+ take_lock = DataWarehouseSavedQuery.objects.select_for_update
+
+ def commit_other_edit() -> None:
+ # A thread gets its own connection, so this edit commits instead of joining the
+ # request's transaction and rolling back with it.
+ try:
+ DataWarehouseSavedQuery.objects.filter(id=created["id"]).update(
+ query={"kind": "HogQLQuery", "query": "select uuid from events"},
+ query_revision=other_revision,
+ )
+ finally:
+ connection.close()
+
+ def edit_then_take_lock(*args: Any, **kwargs: Any) -> Any:
+ # Land the other writer's edit after the view read the row and before this request locks
+ # it. Only that ordering separates the locked row from the instance the view read, so a
+ # conflict check reading the earlier instance would accept the token. The row carries no
+ # lock yet, so the waiting writer cannot block here.
+ other_writer = threading.Thread(target=commit_other_edit)
+ other_writer.start()
+ other_writer.join(timeout=30)
+ self.assertFalse(other_writer.is_alive())
+ return take_lock(*args, **kwargs)
+
+ with patch.object(DataWarehouseSavedQuery.objects, "select_for_update", side_effect=edit_then_take_lock):
+ response = self._patch_query(created["id"], "select event from events limit 10", token)
+
+ self.assertEqual(response.status_code, 400, response.content)
+ self.assertEqual(self._revision(created["id"]), str(other_revision))
+
+ @parameterized.expand(DEFERRED_AND_IMMEDIATE)
+ def test_non_query_update_keeps_the_token(self, _name: str, deferred: bool) -> None:
+ with override_settings(ACTIVITY_LOG_TRANSACTION_MANAGEMENT=deferred):
+ created = self._create()
+ token = created["latest_history_id"]
+
+ # A cadence change writes its own activity row; a rename writes none and would prove nothing.
+ response = self.client.patch(self._url(created["id"]), {"sync_frequency": "6hour"})
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(response.json()["latest_history_id"], token)
+
+ chained = self._patch_query(created["id"], "select event from events limit 10", token)
+ self.assertEqual(chained.status_code, 200, chained.content)
+
+ def test_saving_the_same_query_keeps_the_token(self) -> None:
+ created = self._create()
+ token = created["latest_history_id"]
+
+ response = self._patch_query(created["id"], created["query"]["query"], token)
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(response.json()["latest_history_id"], token)
+
+ @parameterized.expand([("uppercase", str.upper), ("unhyphenated", lambda token: token.replace("-", ""))])
+ def test_token_is_accepted_in_any_uuid_spelling(self, _name: str, reshape: Callable[[str], str]) -> None:
+ created = self._create()
+
+ response = self._patch_query(
+ created["id"], "select event from events limit 10", reshape(created["latest_history_id"])
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+
+ def test_row_without_a_revision_accepts_any_token_once(self) -> None:
+ created = self._create()
+ DataWarehouseSavedQuery.objects.filter(id=created["id"]).update(query_revision=None)
+
+ response = self._patch_query(created["id"], "select event from events limit 10", None)
+ self.assertEqual(response.status_code, 200, response.content)
+ token = response.json()["latest_history_id"]
+ self.assertIsNotNone(token)
+
+ stale = self._patch_query(created["id"], "select event from events limit 5", None)
+ self.assertEqual(stale.status_code, 400, stale.content)
+
+ def test_query_edit_does_not_record_the_revision_bump(self) -> None:
+ created = self._create()
+
+ response = self._patch_query(created["id"], "select event from events limit 10", created["latest_history_id"])
+ self.assertEqual(response.status_code, 200, response.content)
+
+ log = ActivityLog.objects.get(scope="DataWarehouseSavedQuery", item_id=created["id"], activity="updated")
+ changed = [change["field"] for change in cast(dict[str, Any], log.detail)["changes"]]
+ self.assertIn("query", changed)
+ self.assertNotIn("query_revision", changed)
diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.ts
index 616b630dee4e..7977364e9c7f 100644
--- a/products/data_warehouse/frontend/generated/api.schemas.ts
+++ b/products/data_warehouse/frontend/generated/api.schemas.ts
@@ -1488,12 +1488,12 @@ export interface DataWarehouseSavedQueryApi {
/** @nullable */
readonly latest_error: string | null
/**
- * Activity log ID from the last known edit. Used for conflict detection.
+ * The latest_history_id you last read for this view. Required when changing the query. The write is refused if someone else changed the query in the meantime.
* @nullable
*/
edited_history_id?: string | null
/**
- * Activity log ID of the most recent query edit to this view. Send it back as edited_history_id on the next query write, so conflict detection can tell whether someone else changed the query in the meantime. Edits that leave the query alone do not advance it.
+ * Revision of this view's query. Send it back as edited_history_id on the next query write, so conflict detection can tell whether someone else changed the query in the meantime. Edits that leave the query alone do not advance it.
* @nullable
*/
readonly latest_history_id: string | null
@@ -1615,12 +1615,12 @@ export interface PatchedDataWarehouseSavedQueryApi {
/** @nullable */
readonly latest_error?: string | null
/**
- * Activity log ID from the last known edit. Used for conflict detection.
+ * The latest_history_id you last read for this view. Required when changing the query. The write is refused if someone else changed the query in the meantime.
* @nullable
*/
edited_history_id?: string | null
/**
- * Activity log ID of the most recent query edit to this view. Send it back as edited_history_id on the next query write, so conflict detection can tell whether someone else changed the query in the meantime. Edits that leave the query alone do not advance it.
+ * Revision of this view's query. Send it back as edited_history_id on the next query write, so conflict detection can tell whether someone else changed the query in the meantime. Edits that leave the query alone do not advance it.
* @nullable
*/
readonly latest_history_id?: string | null
diff --git a/products/data_warehouse/frontend/generated/api.zod.ts b/products/data_warehouse/frontend/generated/api.zod.ts
index 60a96e718a93..7e450d466235 100644
--- a/products/data_warehouse/frontend/generated/api.zod.ts
+++ b/products/data_warehouse/frontend/generated/api.zod.ts
@@ -522,7 +522,9 @@ export const WarehouseSavedQueriesCreateBody = /* @__PURE__ */ zod
edited_history_id: zod
.string()
.nullish()
- .describe('Activity log ID from the last known edit. Used for conflict detection.'),
+ .describe(
+ 'The latest_history_id you last read for this view. Required when changing the query. The write is refused if someone else changed the query in the meantime.'
+ ),
soft_update: zod
.boolean()
.nullish()
@@ -622,7 +624,9 @@ export const WarehouseSavedQueriesUpdateBody = /* @__PURE__ */ zod
edited_history_id: zod
.string()
.nullish()
- .describe('Activity log ID from the last known edit. Used for conflict detection.'),
+ .describe(
+ 'The latest_history_id you last read for this view. Required when changing the query. The write is refused if someone else changed the query in the meantime.'
+ ),
soft_update: zod
.boolean()
.nullish()
@@ -724,7 +728,9 @@ export const WarehouseSavedQueriesPartialUpdateBody = /* @__PURE__ */ zod
edited_history_id: zod
.string()
.nullish()
- .describe('Activity log ID from the last known edit. Used for conflict detection.'),
+ .describe(
+ 'The latest_history_id you last read for this view. Required when changing the query. The write is refused if someone else changed the query in the meantime.'
+ ),
soft_update: zod
.boolean()
.nullish()
@@ -841,7 +847,9 @@ export const WarehouseSavedQueriesCancelCreateBody = /* @__PURE__ */ zod
edited_history_id: zod
.string()
.nullish()
- .describe('Activity log ID from the last known edit. Used for conflict detection.'),
+ .describe(
+ 'The latest_history_id you last read for this view. Required when changing the query. The write is refused if someone else changed the query in the meantime.'
+ ),
soft_update: zod
.boolean()
.nullish()
@@ -982,7 +990,9 @@ export const WarehouseSavedQueriesRevertMaterializationCreateBody = /* @__PURE__
edited_history_id: zod
.string()
.nullish()
- .describe('Activity log ID from the last known edit. Used for conflict detection.'),
+ .describe(
+ 'The latest_history_id you last read for this view. Required when changing the query. The write is refused if someone else changed the query in the meantime.'
+ ),
soft_update: zod
.boolean()
.nullish()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 731fab5990e8..9d99882e2c72 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -24604,12 +24604,12 @@ export namespace Schemas {
/** @nullable */
readonly latest_error: string | null;
/**
- * Activity log ID from the last known edit. Used for conflict detection.
+ * The latest_history_id you last read for this view. Required when changing the query. The write is refused if someone else changed the query in the meantime.
* @nullable
*/
edited_history_id?: string | null;
/**
- * Activity log ID of the most recent query edit to this view. Send it back as edited_history_id on the next query write, so conflict detection can tell whether someone else changed the query in the meantime. Edits that leave the query alone do not advance it.
+ * Revision of this view's query. Send it back as edited_history_id on the next query write, so conflict detection can tell whether someone else changed the query in the meantime. Edits that leave the query alone do not advance it.
* @nullable
*/
readonly latest_history_id: string | null;
@@ -66955,12 +66955,12 @@ export namespace Schemas {
/** @nullable */
readonly latest_error?: string | null;
/**
- * Activity log ID from the last known edit. Used for conflict detection.
+ * The latest_history_id you last read for this view. Required when changing the query. The write is refused if someone else changed the query in the meantime.
* @nullable
*/
edited_history_id?: string | null;
/**
- * Activity log ID of the most recent query edit to this view. Send it back as edited_history_id on the next query write, so conflict detection can tell whether someone else changed the query in the meantime. Edits that leave the query alone do not advance it.
+ * Revision of this view's query. Send it back as edited_history_id on the next query write, so conflict detection can tell whether someone else changed the query in the meantime. Edits that leave the query alone do not advance it.
* @nullable
*/
readonly latest_history_id?: string | null;
diff --git a/services/mcp/src/generated/data_warehouse/api.ts b/services/mcp/src/generated/data_warehouse/api.ts
index 49485dbc65ae..a265f866981e 100644
--- a/services/mcp/src/generated/data_warehouse/api.ts
+++ b/services/mcp/src/generated/data_warehouse/api.ts
@@ -517,7 +517,9 @@ export const WarehouseSavedQueriesPartialUpdateBody = () => zod
edited_history_id: zod
.string()
.nullish()
- .describe('Activity log ID from the last known edit. Used for conflict detection.'),
+ .describe(
+ 'The latest_history_id you last read for this view. Required when changing the query. The write is refused if someone else changed the query in the meantime.'
+ ),
dag_id: zod.string().nullish().describe('Optional DAG to place this view into'),
is_test: zod.boolean().optional().describe('Whether this view is for testing only and will auto-expire.'),
})
@@ -667,7 +669,9 @@ export const WarehouseSavedQueriesRevertMaterializationCreateBody = () => zod
edited_history_id: zod
.string()
.nullish()
- .describe('Activity log ID from the last known edit. Used for conflict detection.'),
+ .describe(
+ 'The latest_history_id you last read for this view. Required when changing the query. The write is refused if someone else changed the query in the meantime.'
+ ),
soft_update: zod
.boolean()
.nullish()
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-unmaterialize.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-unmaterialize.json
index baca9aae75f3..e4441954cfb7 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-unmaterialize.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-unmaterialize.json
@@ -42,7 +42,7 @@
"type": "null"
}
],
- "description": "Activity log ID from the last known edit. Used for conflict detection."
+ "description": "The latest_history_id you last read for this view. Required when changing the query. The write is refused if someone else changed the query in the meantime."
},
"folder_id": {
"anyOf": [