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): honor saved-query write fields (#103015)

Jovan Sakovic0980067fc677
diff --git a/docs/internal/sql-editor-schema-tree.md b/docs/internal/sql-editor-schema-tree.md
index 1fd465de4a1c..8cf1e9b61d54 100644
--- a/docs/internal/sql-editor-schema-tree.md
+++ b/docs/internal/sql-editor-schema-tree.md
@@ -44,3 +44,24 @@ Warehouse series, warehouse property menus, and the data quality check editor ex
After that request, catalog reloads also restore complete fields for consumers of the shared store.
Schema mutations refresh previously hydrated or pending tables, as well as expanded nodes.
Saved-query lists expose metadata only; refreshing them preserves the query and columns already fetched for an open editor tab.
+
+## Saved-query writes
+
+The saved-query API accepts `sync_frequency` on create and update.
+Create applies the cadence after creating the DAG node, in the same transaction, so a refused cadence leaves no saved query behind.
+An omitted cadence leaves the target unchanged on update; explicit `null` and `"never"` both clear it.
+Invalid cadence values return 400.
+
+`edited_history_id` protects query updates from concurrent edits and is ignored on create.
+`soft_update` skips column inference and external table discovery on create and update, and skips the revision conflict check on update.
+Query validation and revision updates still run.
+
+`deleted` is read-only.
+Use DELETE to remove a saved query so DAG cleanup, join cleanup, materialization cleanup, and name release run together.
+Create does not upsert deleted rows.
+A deleted row whose name was not released still reserves that name and needs separate cleanup.
+
+`dag_id` must identify a non-managed DAG in the same project; invalid or foreign IDs return 400.
+A DAG-only update moves the existing node and preserves its cadence and job history.
+Moves are refused when the view has dependents, belongs to a managed DAG, has nodes in multiple DAGs, or has a materialization running.
+Explicit `null` selects the default DAG.
diff --git a/posthog/temporal/data_modeling/activities/create_data_modeling_job.py b/posthog/temporal/data_modeling/activities/create_data_modeling_job.py
index 4b24b5d7f1cf..0ee084ca2b88 100644
--- a/posthog/temporal/data_modeling/activities/create_data_modeling_job.py
+++ b/posthog/temporal/data_modeling/activities/create_data_modeling_job.py
@@ -1,5 +1,8 @@
+import uuid
import dataclasses
+from django.db import transaction
+
from structlog import get_logger
from structlog.contextvars import bind_contextvars
from temporalio import activity
@@ -7,6 +10,7 @@ from temporalio import activity
from posthog.sync import database_sync_to_async_pool
from posthog.temporal.data_modeling.activities.utils import bind_data_modeling_log_context
+from products.data_modeling.backend.facade.api import lock_dag
from products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobEngine, Node
LOGGER = get_logger(__name__)
@@ -55,20 +59,28 @@ class RecordSkippedDataModelingJobsInputs:
def _create_data_modeling_job(
inputs: CreateDataModelingJobInputs, workflow_id: str, workflow_run_id: str
) -> CreatedDataModelingJob:
- node = Node.objects.prefetch_related("saved_query").get(
- id=inputs.node_id, team_id=inputs.team_id, dag_id=inputs.dag_id
- )
- job = DataModelingJob.objects.create(
- team_id=inputs.team_id,
- saved_query=node.saved_query,
- status=DataModelingJob.Status.RUNNING,
- engine=inputs.engine,
- workflow_id=workflow_id,
- workflow_run_id=workflow_run_id,
- parent_workflow_id=inputs.parent_workflow_id,
- created_by_id=node.saved_query.created_by_id if node.saved_query else None,
- manually_triggered_by_id=inputs.manually_triggered_by_id,
- )
+ with transaction.atomic():
+ # A move to another DAG refuses while a job of this query is Running, and holds this lock
+ # across that check. Taking it here, around the placement read and the insert both, is
+ # what stops a job from being created against a placement the move has already left. The
+ # rest of this materialization loads the node by team, node and DAG, so such a job would
+ # find nothing, and that includes the activity which records the failure, so the job row
+ # would stay Running with nothing left to close it.
+ lock_dag(inputs.team_id, uuid.UUID(inputs.dag_id))
+ node = Node.objects.prefetch_related("saved_query").get(
+ id=inputs.node_id, team_id=inputs.team_id, dag_id=inputs.dag_id
+ )
+ job = DataModelingJob.objects.create(
+ team_id=inputs.team_id,
+ saved_query=node.saved_query,
+ status=DataModelingJob.Status.RUNNING,
+ engine=inputs.engine,
+ workflow_id=workflow_id,
+ workflow_run_id=workflow_run_id,
+ parent_workflow_id=inputs.parent_workflow_id,
+ created_by_id=node.saved_query.created_by_id if node.saved_query else None,
+ manually_triggered_by_id=inputs.manually_triggered_by_id,
+ )
return CreatedDataModelingJob(
job_id=str(job.id),
saved_query_id=str(node.saved_query.id) if node.saved_query else None,
diff --git a/posthog/temporal/tests/data_modeling/test_create_data_modeling_job_concurrency.py b/posthog/temporal/tests/data_modeling/test_create_data_modeling_job_concurrency.py
new file mode 100644
index 000000000000..590ab708698a
--- /dev/null
+++ b/posthog/temporal/tests/data_modeling/test_create_data_modeling_job_concurrency.py
@@ -0,0 +1,85 @@
+import time
+import threading
+from typing import Any
+
+import pytest
+import unittest.mock
+
+from django.db import connection
+
+from posthog.sync import database_sync_to_async
+from posthog.temporal.data_modeling.activities.create_data_modeling_job import (
+ CreateDataModelingJobInputs,
+ _create_data_modeling_job,
+)
+
+from products.data_modeling.backend.facade.api import NodeMoveError, move_saved_query_to_dag
+from products.data_modeling.backend.facade.models import DAG, DataModelingJob, DataModelingJobStatus, Node
+
+pytestmark = [pytest.mark.asyncio, pytest.mark.django_db(transaction=True)]
+
+BLOCKED_DEADLINE_SECONDS = 30
+
+
+def wait_until_another_backend_waits_on_a_lock() -> bool:
+ """Whether some other connection is parked on a lock this test database can grant.
+
+ Polled rather than slept on, so the wait ends as soon as the other thread reaches its lock
+ instead of after a guessed interval. `pg_locks` is read rather than `pg_stat_activity`
+ because the caller polls from inside an open transaction, and Postgres caches the backend
+ status snapshot `pg_stat_activity` reports for the length of one. A transaction the waiter
+ is queued behind is recorded with no database of its own, so both rows count.
+ """
+ deadline = time.monotonic() + BLOCKED_DEADLINE_SECONDS
+ while time.monotonic() < deadline:
+ with connection.cursor() as cursor:
+ cursor.execute(
+ "SELECT count(*) FROM pg_locks WHERE NOT granted AND pid <> pg_backend_pid() "
+ "AND (database IS NULL OR database = (SELECT oid FROM pg_database WHERE datname = current_database()))"
+ )
+ if cursor.fetchone()[0] > 0:
+ return True
+ time.sleep(0.05)
+ return False
+
+
+async def test_a_move_cannot_land_between_a_job_reading_a_placement_and_inserting_it(ateam, adag, anode, asaved_query):
+ destination = await database_sync_to_async(DAG.objects.create)(team=ateam, name="destination")
+ refusals: list[str] = []
+
+ def move_on_another_connection() -> None:
+ # A thread gets its own connection, so this move commits instead of joining the job's
+ # transaction and rolling back with it.
+ try:
+ move_saved_query_to_dag(ateam.pk, asaved_query.id, destination.id)
+ except NodeMoveError as e:
+ refusals.append(e.reason)
+ finally:
+ connection.close()
+
+ real_create = DataModelingJob.objects.create
+ movers: list[threading.Thread] = []
+
+ def create_after_a_move_tries_to_land(*args: Any, **kwargs: Any) -> Any:
+ # Between the placement read and this insert is the window where a move whose Running
+ # check ran before the job row existed could still commit, leaving the job pointing at a
+ # DAG the node has left.
+ mover = threading.Thread(target=move_on_another_connection)
+ mover.start()
+ movers.append(mover)
+ assert wait_until_another_backend_waits_on_a_lock(), "the move was not held off by the job's DAG lock"
+ return real_create(*args, **kwargs)
+
+ inputs = CreateDataModelingJobInputs(team_id=ateam.pk, node_id=str(anode.id), dag_id=str(adag.id))
+ with unittest.mock.patch.object(DataModelingJob.objects, "create", side_effect=create_after_a_move_tries_to_land):
+ created = await _create_data_modeling_job(inputs, "test-workflow-id", "test-run-id")
+
+ assert len(movers) == 1
+ movers[0].join(timeout=BLOCKED_DEADLINE_SECONDS)
+ assert not movers[0].is_alive()
+
+ assert refusals == ["materializing"]
+ node = await database_sync_to_async(Node.objects.get)(id=anode.id)
+ assert node.dag_id == adag.id
+ job = await database_sync_to_async(DataModelingJob.objects.get)(id=created.job_id)
+ assert job.status == DataModelingJobStatus.RUNNING
diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.py
index d2ceac3ec413..a045134c35c3 100644
--- a/products/data_modeling/backend/facade/api.py
+++ b/products/data_modeling/backend/facade/api.py
@@ -18,8 +18,11 @@ _LAZY = {
"sync_metric_to_dag": "logic.metric_dag_sync",
"HasDependentsError": "logic.saved_query_dag_sync",
"MissingDagNodeError": "logic.saved_query_dag_sync",
+ "NodeMoveError": "logic.saved_query_dag_sync",
"blocked_lineage_node_id": "logic.saved_query_dag_sync",
"delete_node_from_dag": "logic.saved_query_dag_sync",
+ "lock_dag": "logic.saved_query_dag_sync",
+ "move_saved_query_to_dag": "logic.saved_query_dag_sync",
"describe_dependents": "logic.saved_query_dag_sync",
"promote_view_nodes_to_matview": "logic.saved_query_dag_sync",
"sync_saved_query_to_dag": "logic.saved_query_dag_sync",
diff --git a/products/data_modeling/backend/logic/saved_query_dag_sync.py b/products/data_modeling/backend/logic/saved_query_dag_sync.py
index ce9ef7c06fd4..99c9116e73af 100644
--- a/products/data_modeling/backend/logic/saved_query_dag_sync.py
+++ b/products/data_modeling/backend/logic/saved_query_dag_sync.py
@@ -17,6 +17,7 @@ from products.data_modeling.backend.facade.system_tables import DATA_MODELING_AL
from products.data_modeling.backend.logic.node_suspension import clear_suspension_if_query_changed
from products.data_modeling.backend.logic.schedule_reconcile import maybe_reconcile_dag
from products.data_modeling.backend.models.dag import DAG, REVENUE_ANALYTICS_DAG_NAME
+from products.data_modeling.backend.models.data_modeling_job import DataModelingJob, DataModelingJobStatus
from products.data_modeling.backend.models.edge import Edge
from products.data_modeling.backend.models.modeling import UnknownParentError, get_parents_from_model_query
from products.data_modeling.backend.models.node import Node, NodeType
@@ -194,11 +195,14 @@ class ManagedDAGError(Exception):
pass
-def _lock_dag(team_id: int, dag_id: UUID) -> None:
+def lock_dag(team_id: int, dag_id: UUID) -> None:
"""Serialize against every other writer of this DAG's edges.
The same key `Edge._detect_cycles` takes, so an edge write and a node delete cannot interleave.
Callers holding more than one DAG take them in a fixed order, so two of them cannot deadlock.
+
+ Materialization takes it too, on the job-start side, so a job cannot be created against a
+ placement a move has already left behind.
"""
with connection.cursor() as cursor:
cursor.execute("SELECT pg_advisory_xact_lock(%s, hashtext(%s))", [team_id, str(dag_id)])
@@ -226,7 +230,7 @@ def replace_incoming_edges(
"""
unresolved: list[str] = []
with transaction.atomic():
- _lock_dag(team.pk, dag.id)
+ lock_dag(team.pk, dag.id)
Node.objects.select_for_update().filter(pk=target.pk).first()
Edge.objects.filter(team=team, target=target).delete()
for dependency_name in dependency_names:
@@ -495,7 +499,7 @@ def delete_node_from_dag(saved_query: "DataWarehouseSavedQuery") -> None:
# check below and the delete that would cascade its edge away.
dags = sorted({node.dag for node in nodes if node.dag is not None}, key=lambda dag: str(dag.id))
for dag in dags:
- _lock_dag(saved_query.team_id, dag.id)
+ lock_dag(saved_query.team_id, dag.id)
query_dependents = [
Dependent(
@@ -518,6 +522,79 @@ def delete_node_from_dag(saved_query: "DataWarehouseSavedQuery") -> None:
maybe_reconcile_dag(dag)
+NodeMoveRefusal = Literal["multiple_placements", "blocked", "materializing", "moved"]
+
+
+class NodeMoveError(Exception):
+ """Raised when a saved query's node cannot move to the requested DAG.
+
+ Carries `reason` rather than prose, so a caller serving a user words the refusal itself.
+ """
+
+ def __init__(self, reason: NodeMoveRefusal) -> None:
+ super().__init__(reason)
+ self.reason = reason
+
+
+def move_saved_query_to_dag(team_id: int, saved_query_id: UUID, dag_id: UUID) -> None:
+ """Place a saved query's node in the given DAG, keeping its frequency target and job history.
+
+ Holds the source and destination DAGs for the whole check-and-move, in id order, for the
+ reason `delete_node_from_dag` holds every DAG it touches: otherwise a sync can attach a
+ dependent between the dependents check and the move, leaving an edge whose source sits in
+ another DAG, which `Edge.save` treats as an invariant violation.
+
+ A move is refused while a materialization runs. Its activities load the node by team, node
+ and DAG, so the move makes the remaining ones stop finding it -- including the activity that
+ records the failure, which leaves the job row Running with nothing to close it. Job creation
+ takes the same DAG lock and re-reads the node in its DAG, so a job that starts between the
+ check and the move cannot slip past.
+
+ The saved-query row lock is held too, because a query edit picks the DAG to sync into from its
+ own read of the node. Without it that edit can choose the DAG this move is leaving and then
+ `get_or_create` a second node there, which later moves refuse as `multiple_placements`.
+
+ That row lock is `FOR NO KEY UPDATE`, which is what makes it safe to hold alongside a DAG
+ lock. `FOR UPDATE` conflicts with the `KEY SHARE` lock Postgres takes on this row for the
+ foreign key of every job and node insert, so a materialization holding the DAG lock and
+ inserting its job row would deadlock against this transaction waiting for that same DAG.
+ """
+ from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
+
+ with transaction.atomic():
+ saved_query = DataWarehouseSavedQuery.objects.select_for_update(no_key=True).get(
+ team_id=team_id, id=saved_query_id
+ )
+ dag = DAG.objects.get(team_id=team_id, id=dag_id)
+ placements = Node.objects.filter(team_id=team_id, saved_query=saved_query)
+ held = {dag.id} | {node.dag_id for node in placements if node.dag_id is not None}
+ for held_dag_id in sorted(held, key=str):
+ lock_dag(team_id, held_dag_id)
+
+ nodes = list(placements.select_related("dag"))
+ if len(nodes) > 1:
+ raise NodeMoveError("multiple_placements")
+ if nodes and nodes[0].dag_id != dag.id:
+ node = nodes[0]
+ if node.dag_id not in held:
+ # Another move landed between the read above and the locks, so the DAG this node
+ # sits in now is not one of the ones being held.
+ raise NodeMoveError("moved")
+ if node.dag.is_managed or node.outgoing_edges.exists():
+ raise NodeMoveError("blocked")
+ if DataModelingJob.objects.filter(
+ team_id=team_id, saved_query=saved_query, status=DataModelingJobStatus.RUNNING
+ ).exists():
+ raise NodeMoveError("materializing")
+ previous_dag = node.dag
+ # Rebuild parents in the destination without discarding the node's targets or job history.
+ Edge.objects.filter(team_id=team_id, target=node).delete()
+ node.dag = dag
+ node.save(update_fields=["dag"])
+ maybe_reconcile_dag(previous_dag)
+ sync_saved_query_to_dag(saved_query, dag=dag)
+
+
def update_node_type(saved_query: "DataWarehouseSavedQuery", type: NodeType) -> None:
"""Update a Node's type to MAT_VIEW when materialized."""
nodes = Node.objects.filter(team=saved_query.team, saved_query=saved_query).select_related("dag", "dag__team")
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 18f81a783e42..6ee167b87ed7 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query/editing.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query/editing.py
@@ -2,7 +2,8 @@
import copy
import uuid
-from typing import Any, cast
+from datetime import timedelta
+from typing import TYPE_CHECKING, Any, cast
from django.conf import settings
from django.db import transaction
@@ -28,11 +29,14 @@ from posthog.models.activity_logging.activity_log import Change, Detail, changes
from posthog.rbac.query_access import assert_user_can_read_query
from products.access_control.backend.presentation.access_control import UserAccessControlSerializerMixin
+from products.data_modeling.backend.facade import api as modeling_api
from products.data_modeling.backend.facade.api import has_incremental_history
from products.data_modeling.backend.facade.modeling import ResolutionCycleError, get_parents_from_model_query
from products.data_modeling.backend.facade.models import (
+ DAG,
DataWarehouseSavedQuery,
DataWarehouseSavedQueryColumnAnnotation,
+ Node,
)
from products.data_tools.backend.facade.models import DataWarehouseSavedQueryFolder
from products.data_warehouse.backend.presentation.views.column_annotation_base import upsert_annotation
@@ -44,6 +48,9 @@ from products.warehouse_sources.backend.facade.models import sync_frequency_to_s
from . import incremental_config, sync_cadence, view_description, view_state
+if TYPE_CHECKING:
+ from products.access_control.backend.facade.user_access_control import UserAccessControl
+
logger = structlog.get_logger(__name__)
@@ -67,6 +74,51 @@ def _view_types_validation_error(e: Exception) -> serializers.ValidationError:
return serializers.ValidationError(f"Failed to retrieve types for view: unexpected {type(e).__name__}")
+def _apply_frequency_target(
+ view: DataWarehouseSavedQuery,
+ frequency: str | None,
+ user_access_control: "UserAccessControl | None",
+) -> timedelta | None:
+ target = sync_frequency_to_sync_frequency_interval(frequency) if frequency else None
+ # A refusal names what blocks the cadence, so it obeys the same grants the read
+ # payload does — otherwise one rejected PATCH reads back a name the caller was
+ # never shown. Withheld nodes fall back to generic prose inside the refusal.
+ bounds = modeling_api.saved_query_target_bounds(view.team_id, view.pk)
+ visible = (
+ sync_cadence.visible_blocker_names(bounds, user_access_control, team_id=view.team_id)
+ if bounds is not None
+ else {}
+ )
+ try:
+ # Validate before commit so a rejected frequency rolls back the write.
+ nodes_written = modeling_api.apply_saved_query_frequency_target(view, target, visible_names=visible)
+ except (modeling_api.UnsatisfiableFrequencyError, modeling_api.UnsupportedFrequencyTargetError) as e:
+ raise serializers.ValidationError(str(e))
+ if target is not None and nodes_written == 0:
+ raise serializers.ValidationError(
+ "Cannot set a materialization frequency: this view is not wired into the data "
+ "modeling DAG yet. Re-save the view to create its node, then set the frequency."
+ )
+ return target
+
+
+_MOVE_REFUSALS = {
+ "multiple_placements": "This view belongs to multiple DAGs and cannot be moved here.",
+ "blocked": "This view cannot move while its DAG is managed or other views depend on it.",
+ "materializing": (
+ "This view cannot move while it is materializing. Wait for the run to finish or cancel it, then try again."
+ ),
+ "moved": "Something else moved this view while we were moving it. Try again.",
+}
+
+
+def _move_to_dag(view: DataWarehouseSavedQuery, dag: DAG) -> None:
+ try:
+ modeling_api.move_saved_query_to_dag(view.team_id, view.pk, dag.id)
+ except modeling_api.NodeMoveError as e:
+ raise serializers.ValidationError({"dag_id": _MOVE_REFUSALS[e.reason]})
+
+
class DataWarehouseSavedQuerySerializer(
view_state.DataWarehouseSavedQuerySerializerMixin, UserAccessControlSerializerMixin, serializers.ModelSerializer
):
@@ -136,10 +188,16 @@ class DataWarehouseSavedQuerySerializer(
write_only=True,
required=False,
allow_null=True,
- help_text="If true, skip column inference and validation. For saving drafts.",
+ help_text="If true, skip column inference and external table discovery. On update, also skip the query "
+ "revision conflict check. Query validation and revision updates still run.",
)
- dag_id = serializers.UUIDField(
- write_only=True, required=False, allow_null=True, help_text="Optional DAG to place this view into"
+ dag_id = TeamScopedPrimaryKeyRelatedField(
+ queryset=DAG.objects.all(),
+ pk_field=serializers.UUIDField(),
+ write_only=True,
+ required=False,
+ allow_null=True,
+ help_text="DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.",
)
description = view_description.ViewDescriptionField(
required=False, allow_blank=True, allow_null=True, help_text=view_description.VIEW_DESCRIPTION_HELP_TEXT
@@ -197,6 +255,8 @@ class DataWarehouseSavedQuerySerializer(
]
read_only_fields = [
"id",
+ # Deletion must run lifecycle cleanup and release the name through DELETE.
+ "deleted",
"created_by",
"created_at",
"updated_at",
@@ -263,12 +323,12 @@ class DataWarehouseSavedQuerySerializer(
validated_data["created_by"] = self.context["request"].user
validated_data["origin"] = DataWarehouseSavedQuery.Origin.DATA_WAREHOUSE
soft_update = validated_data.pop("soft_update", False)
+ dag_given = "dag_id" in validated_data
dag_id = validated_data.pop("dag_id", None)
has_description = "description" in validated_data
description = validated_data.pop("description", None)
- # Sync cadence is configured via materialization, not on creation — drop it so it
- # isn't passed to the model constructor.
- validated_data.pop("sync_frequency", None)
+ sync_frequency = validated_data.pop("sync_frequency", None)
+ validated_data.pop("edited_history_id", None)
view = DataWarehouseSavedQuery(**validated_data)
if not soft_update:
@@ -329,24 +389,29 @@ class DataWarehouseSavedQuerySerializer(
],
),
)
- # best effort sync to new data modeling DAG representation
- try:
- from products.data_modeling.backend.facade.api import sync_saved_query_to_dag
- from products.data_modeling.backend.facade.models import DAG
-
- dag_obj = None
- if dag_id:
- try:
- dag_obj = DAG.objects.get(id=dag_id, team_id=view.team_id)
- except DAG.DoesNotExist:
- raise serializers.ValidationError({"dag_id": "Invalid DAG ID or DAG does not belong to this team"})
- sync_saved_query_to_dag(view, dag=dag_obj)
- except Exception as e:
- capture_exception(e)
- logger.exception("Failed to sync saved query to DAG", saved_query_name=view.name)
+ # Best-effort only when the caller left placement to us. A supplied dag_id is
+ # write-only, so the response cannot show that the placement was discarded.
+ try:
+ with transaction.atomic():
+ modeling_api.sync_saved_query_to_dag(view, dag=dag_id)
+ except Exception as e:
+ capture_exception(e)
+ logger.exception("Failed to sync saved query to DAG", saved_query_name=view.name)
+ if dag_given:
+ raise serializers.ValidationError({"dag_id": "Could not place this view in the requested DAG."})
+ if sync_frequency is not None:
+ if sync_frequency != "never":
+ assert_user_can_read_query(
+ view.query,
+ view.team_id,
+ cast(User, self.context["request"].user),
+ database=self.context.get("database"),
+ )
+ _apply_frequency_target(view, sync_frequency, self.user_access_control)
return view
def update(self, instance: Any, validated_data: Any) -> Any:
+ dag_given = "dag_id" in validated_data
dag_id = validated_data.pop("dag_id", None)
has_description = "description" in validated_data
description = validated_data.pop("description", None)
@@ -354,6 +419,7 @@ class DataWarehouseSavedQuerySerializer(
if instance.managed_viewset is not None:
raise serializers.ValidationError("Cannot update a query from a managed viewset")
+ frequency_given = "sync_frequency" in validated_data
sync_frequency = validated_data.pop("sync_frequency", None)
if sync_frequency and sync_frequency != "never":
@@ -366,7 +432,7 @@ class DataWarehouseSavedQuerySerializer(
)
# The frequency writes through to the DAG node's freshness target.
- frequency_changed = bool(sync_frequency)
+ frequency_changed = frequency_given
soft_update = validated_data.pop("soft_update", False)
edited_history_id = self.context["request"].data.get("edited_history_id", None)
@@ -421,8 +487,14 @@ class DataWarehouseSavedQuerySerializer(
with transaction.atomic():
try:
+ # `FOR NO KEY UPDATE`, not `FOR UPDATE`: this lock is held across a DAG lock, and
+ # `FOR UPDATE` conflicts with the `KEY SHARE` lock a concurrent materialization
+ # takes on this row for its job's foreign key, which deadlocks the two. It still
+ # blocks every other writer of the row, which is all the lost-update check needs.
locked_instance = (
- DataWarehouseSavedQuery.objects.select_for_update().exclude(deleted=True).get(pk=instance.pk)
+ DataWarehouseSavedQuery.objects.select_for_update(no_key=True)
+ .exclude(deleted=True)
+ .get(pk=instance.pk)
)
except DataWarehouseSavedQuery.DoesNotExist:
raise exceptions.NotFound("Not found.")
@@ -445,39 +517,20 @@ class DataWarehouseSavedQuerySerializer(
view: DataWarehouseSavedQuery = super().update(locked_instance, validated_data)
- if frequency_changed:
- from products.data_modeling.backend.facade.api import (
- UnsatisfiableFrequencyError,
- UnsupportedFrequencyTargetError,
- apply_saved_query_frequency_target,
- declared_targets_by_saved_query,
- saved_query_target_bounds,
- )
+ if dag_given:
+ try:
+ _move_to_dag(view, dag_id or DAG.get_or_create_default(view.team))
+ except serializers.ValidationError:
+ raise
+ except Exception as e:
+ capture_exception(e)
+ raise serializers.ValidationError({"dag_id": "Could not move this view to the requested DAG."})
- target = (
- None if sync_frequency == "never" else sync_frequency_to_sync_frequency_interval(sync_frequency)
- )
- previous_target = declared_targets_by_saved_query(view.team_id, [view.pk]).get(str(view.pk))
- # A refusal names what blocks the cadence, so it obeys the same grants the read
- # payload does — otherwise one rejected PATCH reads back a name the caller was
- # never shown. Withheld nodes fall back to generic prose inside the refusal.
- bounds = saved_query_target_bounds(view.team_id, view.pk)
- visible = (
- sync_cadence.visible_blocker_names(bounds, self.user_access_control, team_id=view.team_id)
- if bounds is not None
- else {}
+ if frequency_changed:
+ previous_target = modeling_api.declared_targets_by_saved_query(view.team_id, [view.pk]).get(
+ str(view.pk)
)
- try:
- # Validates inside the transaction (a rejected frequency rolls the whole
- # update back) and queues the schedule reconcile for after commit.
- nodes_written = apply_saved_query_frequency_target(view, target, visible_names=visible)
- except (UnsatisfiableFrequencyError, UnsupportedFrequencyTargetError) as e:
- raise serializers.ValidationError(str(e))
- if target is not None and nodes_written == 0:
- raise serializers.ValidationError(
- "Cannot set a materialization frequency: this view is not wired into the data "
- "modeling DAG yet. Re-save the view to create its node, then set the frequency."
- )
+ target = _apply_frequency_target(view, sync_frequency, self.user_access_control)
if has_description:
self._write_view_description(view, description)
@@ -529,19 +582,20 @@ class DataWarehouseSavedQuerySerializer(
activity="updated",
detail=Detail(name=view.name, changes=changes),
)
- # best effort sync to new data modeling DAG representation
- if "query" in validated_data:
- try:
- from products.data_modeling.backend.facade.api import sync_saved_query_to_dag
- from products.data_modeling.backend.facade.models import DAG
- dag_obj = None
- if dag_id:
- dag_obj = DAG.objects.filter(id=dag_id, team_id=view.team_id).first()
- sync_saved_query_to_dag(view, dag=dag_obj)
- except Exception as e:
- capture_exception(e)
- logger.exception("Failed to sync saved query to DAG", saved_query_name=view.name)
+ # Best effort sync to the data modeling DAG representation. It reads the node's
+ # placement, so it stays under the row lock a move also takes: outside it a move can
+ # land between the read and the sync, which would then create a second node in the
+ # DAG the move just left. The savepoint keeps a failed sync best effort without
+ # poisoning the update's own transaction.
+ if "query" in validated_data and not dag_given:
+ try:
+ with transaction.atomic():
+ node = Node.objects.filter(team_id=view.team_id, saved_query=view).select_related("dag").first()
+ modeling_api.sync_saved_query_to_dag(view, dag=node.dag if node else None)
+ except Exception as e:
+ capture_exception(e)
+ logger.exception("Failed to sync saved query to DAG", saved_query_name=view.name)
return view
def validate_query(self, query):
@@ -645,6 +699,11 @@ class DataWarehouseSavedQuerySerializer(
raise serializers.ValidationError("Only staff users can create test views.")
return is_test
+ def validate_dag_id(self, dag: DAG | None) -> DAG | None:
+ if dag is not None and dag.is_managed:
+ raise serializers.ValidationError("Choose a DAG that is not system-managed.")
+ return dag
+
def validate_folder(self, folder):
if folder is not None and folder.team_id != self.context["team_id"]:
raise serializers.ValidationError("Folder not found.")
@@ -659,7 +718,11 @@ class DataWarehouseSavedQuerySerializer(
# has_table covers system/posthog tables and warehouse objects the requesting user can see; it's
# user-filtered, so also resolve the name team-wide using get_view_or_table_by_name.
# Otherwise a user with denied table could create another one with colliding name.
- if self.context["database"].has_table(name) or get_view_or_table_by_name(self.context["team_id"], name):
+ if (
+ self.context["database"].has_table(name)
+ or get_view_or_table_by_name(self.context["team_id"], name)
+ or DataWarehouseSavedQuery.objects.filter(team_id=self.context["team_id"], name=name, deleted=True).exists()
+ ):
raise serializers.ValidationError("A table or view with this name already exists. Choose a different name.")
return name
diff --git a/products/data_warehouse/backend/presentation/views/saved_query/sync_cadence.py b/products/data_warehouse/backend/presentation/views/saved_query/sync_cadence.py
index 5defaa4bce28..85ce156373ff 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query/sync_cadence.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query/sync_cadence.py
@@ -289,7 +289,7 @@ class SyncFrequencyField(serializers.ChoiceField):
Reads resolve the cadence via `resolve_sync_frequency` (node target first, then the model's
`sync_frequency_interval`); writes are validated against the choices and consumed by the
- serializer's `update()`. Declaring it as a real (non read-only) field is what lets the
+ serializer's `create()` and `update()`. Declaring it as a real (non read-only) field is what lets the
cadence flow into the generated PATCH body and MCP tool schema.
"""
@@ -301,7 +301,7 @@ class SyncFrequencyField(serializers.ChoiceField):
def to_internal_value(self, data: Any) -> str:
# Clamp deprecated sub-15min cadences up to the floor before validating against choices.
- if data in DEPRECATED_FAST_SYNC_FREQUENCIES:
+ if isinstance(data, str) and data in DEPRECATED_FAST_SYNC_FREQUENCIES:
data = "15min"
return super().to_internal_value(data)
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 05c864e2bd62..f1e847ef447e 100644
--- a/products/data_warehouse/backend/presentation/views/saved_query/viewset.py
+++ b/products/data_warehouse/backend/presentation/views/saved_query/viewset.py
@@ -214,9 +214,11 @@ class DataWarehouseSavedQueryViewSet(TeamAndOrgViewSetMixin, AccessControlViewSe
def create(self, request, *args, **kwargs):
# Check for UPSERT logic
- saved_query = DataWarehouseSavedQuery.objects.filter(
- team_id=self.team_id, name=request.data.get("name")
- ).first()
+ saved_query = (
+ DataWarehouseSavedQuery.objects.exclude(deleted=True)
+ .filter(team_id=self.team_id, name=request.data.get("name"))
+ .first()
+ )
if saved_query:
# The UPSERT branch updates an existing row without going through get_object(),
# so run object-level permission checks explicitly to honor per-object access controls.
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 16ad2ab098cc..80e60de8dd5f 100644
--- a/products/data_warehouse/backend/tests/api/test_saved_query.py
+++ b/products/data_warehouse/backend/tests/api/test_saved_query.py
@@ -1167,12 +1167,46 @@ class TestSavedQuery(APIBaseTest):
self.assertEqual(response.status_code, 201)
return response.json()
- def test_update_sync_frequency_rejects_invalid_value(self):
+ def test_create_applies_the_requested_sync_frequency(self) -> None:
+ from products.data_modeling.backend.facade.api import get_declared_target
+
+ with patch("products.data_modeling.backend.logic.schedule_reconcile.maybe_reconcile_dag"):
+ response = self.client.post(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/",
+ {
+ "name": "event_view",
+ "query": {"kind": "HogQLQuery", "query": "select event from events LIMIT 100"},
+ "sync_frequency": "6hour",
+ },
+ )
+ self.assertEqual(response.status_code, 201, response.content)
+ self.assertEqual(response.json()["sync_frequency"], "6hour")
+ self.assertEqual(
+ get_declared_target(Node.objects.get(saved_query_id=response.json()["id"])), timedelta(hours=6)
+ )
+
+ def test_explicit_null_sync_frequency_clears_the_target(self) -> None:
+ from products.data_modeling.backend.facade.api import get_declared_target
+
+ saved_query = self._create_saved_query_for_frequency_tests()
+ url = f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query['id']}"
+ with patch("products.data_modeling.backend.logic.schedule_reconcile.maybe_reconcile_dag"):
+ initial = self.client.patch(url, {"sync_frequency": "6hour"})
+ self.assertEqual(initial.status_code, 200, initial.content)
+ response = self.client.patch(url, {"sync_frequency": None})
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertIsNone(response.json()["sync_frequency"])
+ self.assertIsNone(get_declared_target(Node.objects.get(saved_query_id=saved_query["id"])))
+
+ @parameterized.expand(
+ [("unknown", "every_fortnight"), ("list", []), ("dict", {}), ("number", 5), ("boolean", True)]
+ )
+ def test_update_sync_frequency_rejects_invalid_value(self, _name, value):
saved_query = self._create_saved_query()
response = self.client.patch(
f"/api/environments/{self.team.id}/warehouse_saved_queries/{saved_query['id']}",
- {"sync_frequency": "every_fortnight"},
+ {"sync_frequency": value},
)
self.assertEqual(response.status_code, 400, response.content)
diff --git a/products/data_warehouse/backend/tests/api/test_saved_query_dag_move_concurrency.py b/products/data_warehouse/backend/tests/api/test_saved_query_dag_move_concurrency.py
new file mode 100644
index 000000000000..616c15851569
--- /dev/null
+++ b/products/data_warehouse/backend/tests/api/test_saved_query_dag_move_concurrency.py
@@ -0,0 +1,106 @@
+import time
+import threading
+from typing import Any
+
+from posthog.test.base import NonAtomicAPIBaseTest
+from unittest.mock import patch
+
+from django.db import connection
+
+from products.data_modeling.backend.facade import api as modeling_api
+from products.data_modeling.backend.facade.models import DAG, DataWarehouseSavedQuery, Node
+
+BLOCKED_DEADLINE_SECONDS = 30
+
+
+def wait_until_another_backend_waits_on_a_lock() -> bool:
+ """Whether some other connection is parked on a lock this test database can grant.
+
+ Polled rather than slept on, so the wait ends as soon as the other thread reaches its lock
+ instead of after a guessed interval. `pg_locks` is read rather than `pg_stat_activity`
+ because the caller polls from inside an open transaction, and Postgres caches the backend
+ status snapshot `pg_stat_activity` reports for the length of one. A transaction the waiter
+ is queued behind is recorded with no database of its own, so both rows count.
+ """
+ deadline = time.monotonic() + BLOCKED_DEADLINE_SECONDS
+ while time.monotonic() < deadline:
+ with connection.cursor() as cursor:
+ cursor.execute(
+ "SELECT count(*) FROM pg_locks WHERE NOT granted AND pid <> pg_backend_pid() "
+ "AND (database IS NULL OR database = (SELECT oid FROM pg_database WHERE datname = current_database()))"
+ )
+ if cursor.fetchone()[0] > 0:
+ return True
+ time.sleep(0.05)
+ return False
+
+
+class TestSavedQueryDagMoveConcurrency(NonAtomicAPIBaseTest):
+ # TransactionTestCase, so a second connection sees what the request under test committed.
+ 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 test_a_move_cannot_land_between_a_query_edit_reading_a_placement_and_syncing_it(self) -> None:
+ created = self.client.post(
+ self._url(),
+ {"name": "event_view", "query": {"kind": "HogQLQuery", "query": "select event from events limit 100"}},
+ )
+ self.assertEqual(created.status_code, 201, created.content)
+ view = created.json()
+ origin_dag_id = Node.objects.get(saved_query_id=view["id"]).dag_id
+ destination = DAG.objects.create(team=self.team, name="Destination")
+
+ def move_on_another_connection() -> None:
+ # A thread gets its own connection, so this move commits instead of joining the
+ # request's transaction and rolling back with it.
+ try:
+ modeling_api.move_saved_query_to_dag(self.team.pk, view["id"], destination.id)
+ finally:
+ connection.close()
+
+ real_sync = modeling_api.sync_saved_query_to_dag
+ movers: list[threading.Thread] = []
+
+ def sync_after_a_move_tries_to_land(*args: Any, **kwargs: Any) -> Any:
+ # The DAG to sync into was read just above this call, so this is the window where a
+ # move that commits would leave the sync writing into the DAG the node has left --
+ # and `get_or_create` would answer with a second node there.
+ mover = threading.Thread(target=move_on_another_connection)
+ mover.start()
+ movers.append(mover)
+ self.assertTrue(
+ wait_until_another_backend_waits_on_a_lock(),
+ "the move was not held off by the request's row lock",
+ )
+ return real_sync(*args, **kwargs)
+
+ with patch(
+ "products.data_modeling.backend.facade.api.sync_saved_query_to_dag",
+ side_effect=sync_after_a_move_tries_to_land,
+ ):
+ response = self.client.patch(
+ self._url(view["id"]),
+ {
+ "query": {"kind": "HogQLQuery", "query": "select event from events limit 10"},
+ "edited_history_id": view["latest_history_id"],
+ },
+ )
+
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(len(movers), 1)
+ movers[0].join(timeout=BLOCKED_DEADLINE_SECONDS)
+ self.assertFalse(movers[0].is_alive())
+
+ nodes = list(Node.objects.filter(team=self.team, saved_query_id=view["id"]))
+ self.assertEqual(len(nodes), 1)
+ self.assertNotEqual(nodes[0].dag_id, origin_dag_id)
+ self.assertEqual(nodes[0].dag_id, destination.id)
diff --git a/products/data_warehouse/backend/tests/api/test_saved_query_write_fields.py b/products/data_warehouse/backend/tests/api/test_saved_query_write_fields.py
new file mode 100644
index 000000000000..c8096a8f3aa8
--- /dev/null
+++ b/products/data_warehouse/backend/tests/api/test_saved_query_write_fields.py
@@ -0,0 +1,195 @@
+import uuid
+from datetime import timedelta
+from typing import Any
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from products.data_modeling.backend.facade.api import get_declared_target, set_declared_target
+from products.data_modeling.backend.facade.models import (
+ DAG,
+ DataModelingJob,
+ DataModelingJobStatus,
+ DataWarehouseSavedQuery,
+ Edge,
+ Node,
+)
+
+
+class TestSavedQueryWriteFields(APIBaseTest):
+ def _create_view(self, **fields: Any) -> Any:
+ return self.client.post(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/",
+ {
+ "name": "event_view",
+ "query": {"kind": "HogQLQuery", "query": "select event from events LIMIT 100"},
+ **fields,
+ },
+ )
+
+ def test_create_tolerates_an_edited_history_id(self) -> None:
+ response = self._create_view(edited_history_id=str(uuid.uuid4()))
+ self.assertEqual(response.status_code, 201, response.content)
+
+ def test_create_frequency_failure_rolls_back_the_view(self) -> None:
+ with patch("products.data_modeling.backend.facade.api.sync_saved_query_to_dag", side_effect=RuntimeError):
+ response = self._create_view(sync_frequency="6hour")
+ self.assertEqual(response.status_code, 400, response.content)
+ self.assertFalse(DataWarehouseSavedQuery.objects.filter(team=self.team, name="event_view").exists())
+
+ @parameterized.expand([("supplied", True, 400), ("omitted", False, 201)])
+ def test_create_reports_a_discarded_dag_placement_only_when_asked_for(
+ self, _name: str, supply_dag_id: bool, expected_status: int
+ ) -> None:
+ dag = DAG.objects.create(team=self.team, name="Other")
+ fields = {"dag_id": str(dag.id)} if supply_dag_id else {}
+ with patch("products.data_modeling.backend.facade.api.sync_saved_query_to_dag", side_effect=RuntimeError):
+ response = self._create_view(**fields)
+ self.assertEqual(response.status_code, expected_status, response.content)
+ self.assertEqual(
+ DataWarehouseSavedQuery.objects.filter(team=self.team, name="event_view").exists(),
+ expected_status == 201,
+ )
+ self.assertFalse(Node.objects.filter(dag=dag).exists())
+
+ def test_create_applies_the_requested_dag_and_cadence(self) -> None:
+ dag = DAG.objects.create(team=self.team, name="Other")
+ response = self._create_view(dag_id=str(dag.id), sync_frequency="6hour")
+ self.assertEqual(response.status_code, 201, response.content)
+ node = Node.objects.get(saved_query_id=response.json()["id"])
+ self.assertEqual(node.dag_id, dag.id)
+ self.assertEqual(get_declared_target(node), timedelta(hours=6))
+
+ @parameterized.expand([("create",), ("update",)])
+ def test_managed_dag_is_rejected(self, operation: str) -> None:
+ dag = DAG.get_or_create_revenue_analytics(self.team)
+ if operation == "create":
+ response = self._create_view(dag_id=str(dag.id))
+ else:
+ created = self._create_view().json()
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{created['id']}",
+ {"dag_id": str(dag.id)},
+ )
+ self.assertEqual(response.status_code, 400, response.content)
+ self.assertFalse(Node.objects.filter(dag=dag).exists())
+
+ def test_deleted_cannot_be_set_through_the_write_api(self) -> None:
+ created = self._create_view().json()
+ url = f"/api/environments/{self.team.id}/warehouse_saved_queries/{created['id']}"
+ response = self.client.patch(url, {"deleted": True})
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertFalse(DataWarehouseSavedQuery.objects.get(id=created["id"]).deleted)
+ self.assertEqual(self.client.get(url).status_code, 200)
+
+ def test_create_rejects_an_unknown_dag_id(self) -> None:
+ response = self._create_view(dag_id=str(uuid.uuid4()))
+ self.assertEqual(response.status_code, 400, response.content)
+ self.assertFalse(DataWarehouseSavedQuery.objects.filter(team=self.team, name="event_view").exists())
+
+ def test_create_does_not_upsert_a_deleted_view(self) -> None:
+ view = DataWarehouseSavedQuery.objects.create(
+ team=self.team,
+ name="event_view",
+ query={"kind": "HogQLQuery", "query": "select event from events LIMIT 7"},
+ deleted=True,
+ )
+ response = self._create_view(edited_history_id=str(view.query_revision))
+ self.assertEqual(response.status_code, 400, response.content)
+ view.refresh_from_db()
+ self.assertEqual(view.query, {"kind": "HogQLQuery", "query": "select event from events LIMIT 7"})
+
+ def test_dag_id_alone_reparents_the_node(self) -> None:
+ created = self._create_view().json()
+ node = Node.objects.get(saved_query_id=created["id"])
+ set_declared_target(node, timedelta(hours=6))
+ other = DAG.objects.create(team=self.team, name="Other")
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{created['id']}",
+ {"dag_id": str(other.id)},
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+ moved_node = Node.objects.get(saved_query_id=created["id"])
+ self.assertEqual(moved_node.dag_id, other.id)
+ self.assertEqual(moved_node.id, node.id)
+ self.assertEqual(get_declared_target(moved_node), timedelta(hours=6))
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{created['id']}",
+ {
+ "query": {"kind": "HogQLQuery", "query": "select event from events LIMIT 7"},
+ "edited_history_id": created["latest_history_id"],
+ },
+ )
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(Node.objects.get(saved_query_id=created["id"]).dag_id, other.id)
+
+ def test_failed_move_preserves_the_node_and_its_parents(self) -> None:
+ created = self._create_view().json()
+ node = Node.objects.get(saved_query_id=created["id"])
+ parents = set(Edge.objects.filter(target=node).values_list("id", flat=True))
+ self.assertTrue(parents)
+ other = DAG.objects.create(team=self.team, name="Other")
+ with patch(
+ "products.data_modeling.backend.logic.saved_query_dag_sync.sync_saved_query_to_dag",
+ side_effect=RuntimeError,
+ ):
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{created['id']}",
+ {"dag_id": str(other.id)},
+ )
+ self.assertEqual(response.status_code, 400, response.content)
+ self.assertEqual(Node.objects.get(id=node.id).dag_id, node.dag_id)
+ self.assertEqual(set(Edge.objects.filter(target=node).values_list("id", flat=True)), parents)
+
+ def test_update_rejects_another_teams_dag_id(self) -> None:
+ created = self._create_view().json()
+ foreign_team = self.create_team_with_organization(organization=self.organization)
+ foreign_dag = DAG.objects.create(team=foreign_team, name="Foreign")
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{created['id']}",
+ {
+ "dag_id": str(foreign_dag.id),
+ "query": {"kind": "HogQLQuery", "query": "select event from events LIMIT 7"},
+ "edited_history_id": created["latest_history_id"],
+ },
+ )
+ self.assertEqual(response.status_code, 400, response.content)
+ self.assertEqual(Node.objects.filter(dag=foreign_dag).count(), 0)
+
+ @parameterized.expand(
+ [("running", DataModelingJobStatus.RUNNING, 400), ("completed", DataModelingJobStatus.COMPLETED, 200)]
+ )
+ def test_move_waits_for_a_materialization_in_flight(
+ self, _name: str, job_status: str, expected_status: int
+ ) -> None:
+ created = self._create_view().json()
+ node = Node.objects.get(saved_query_id=created["id"])
+ DataModelingJob.objects.create(team=self.team, saved_query_id=created["id"], status=job_status)
+ other = DAG.objects.create(team=self.team, name="Other")
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{created['id']}",
+ {"dag_id": str(other.id)},
+ )
+ self.assertEqual(response.status_code, expected_status, response.content)
+ moved = Node.objects.get(id=node.id)
+ self.assertEqual(moved.dag_id, node.dag_id if expected_status == 400 else other.id)
+
+ def test_reparenting_refuses_to_strand_dependents(self) -> None:
+ created = self._create_view().json()
+ consumer = self._create_view(
+ name="consumer_view",
+ query={"kind": "HogQLQuery", "query": "select event from event_view"},
+ )
+ self.assertEqual(consumer.status_code, 201, consumer.content)
+ node = Node.objects.get(saved_query_id=created["id"])
+ other = DAG.objects.create(team=self.team, name="Other")
+ response = self.client.patch(
+ f"/api/environments/{self.team.id}/warehouse_saved_queries/{created['id']}",
+ {"dag_id": str(other.id)},
+ )
+ self.assertEqual(response.status_code, 400, response.content)
+ self.assertEqual(Node.objects.get(id=node.id).dag_id, node.dag_id)
+ self.assertTrue(Edge.objects.filter(source=node, target__saved_query_id=consumer.json()["id"]).exists())
diff --git a/products/data_warehouse/frontend/generated/api.schemas.ts b/products/data_warehouse/frontend/generated/api.schemas.ts
index 20cdec16700f..372bb1b14bb8 100644
--- a/products/data_warehouse/frontend/generated/api.schemas.ts
+++ b/products/data_warehouse/frontend/generated/api.schemas.ts
@@ -1663,7 +1663,7 @@ export interface SyncFrequencyBoundsApi {
export interface DataWarehouseSavedQueryApi {
readonly id: string
/** @nullable */
- deleted?: boolean | null
+ readonly deleted: boolean | null
/**
* Unique name for the view. Used as the table name in HogQL queries and the node name in the data modeling Node.
* @maxLength 128
@@ -1729,12 +1729,12 @@ export interface DataWarehouseSavedQueryApi {
*/
readonly latest_history_id: string | null
/**
- * If true, skip column inference and validation. For saving drafts.
+ * If true, skip column inference and external table discovery. On update, also skip the query revision conflict check. Query validation and revision updates still run.
* @nullable
*/
soft_update?: boolean | null
/**
- * Optional DAG to place this view into
+ * DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.
* @nullable
*/
dag_id?: string | null
@@ -1792,7 +1792,7 @@ export type PatchedDataWarehouseSavedQueryApiSuspended = { [key: string]: SavedQ
export interface PatchedDataWarehouseSavedQueryApi {
readonly id?: string
/** @nullable */
- deleted?: boolean | null
+ readonly deleted?: boolean | null
/**
* Unique name for the view. Used as the table name in HogQL queries and the node name in the data modeling Node.
* @maxLength 128
@@ -1858,12 +1858,12 @@ export interface PatchedDataWarehouseSavedQueryApi {
*/
readonly latest_history_id?: string | null
/**
- * If true, skip column inference and validation. For saving drafts.
+ * If true, skip column inference and external table discovery. On update, also skip the query revision conflict check. Query validation and revision updates still run.
* @nullable
*/
soft_update?: boolean | null
/**
- * Optional DAG to place this view into
+ * DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.
* @nullable
*/
dag_id?: string | null
diff --git a/products/data_warehouse/frontend/generated/api.zod.ts b/products/data_warehouse/frontend/generated/api.zod.ts
index f6cdf478eb6e..fae32e7e4a58 100644
--- a/products/data_warehouse/frontend/generated/api.zod.ts
+++ b/products/data_warehouse/frontend/generated/api.zod.ts
@@ -455,7 +455,6 @@ export const warehouseSavedQueriesCreateBodyIncrementalOneLookbackSecondsMax = 2
export const WarehouseSavedQueriesCreateBody = /* @__PURE__ */ zod
.object({
- deleted: zod.boolean().nullish(),
name: zod
.string()
.max(warehouseSavedQueriesCreateBodyNameMax)
@@ -536,8 +535,15 @@ export const WarehouseSavedQueriesCreateBody = /* @__PURE__ */ zod
soft_update: zod
.boolean()
.nullish()
- .describe('If true, skip column inference and validation. For saving drafts.'),
- dag_id: zod.uuid().nullish().describe('Optional DAG to place this view into'),
+ .describe(
+ 'If true, skip column inference and external table discovery. On update, also skip the query revision conflict check. Query validation and revision updates still run.'
+ ),
+ dag_id: zod
+ .uuid()
+ .nullish()
+ .describe(
+ 'DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.'
+ ),
is_test: zod.boolean().optional().describe('Whether this view is for testing only and will auto-expire.'),
})
.describe(
@@ -557,7 +563,6 @@ export const warehouseSavedQueriesUpdateBodyIncrementalOneLookbackSecondsMax = 2
export const WarehouseSavedQueriesUpdateBody = /* @__PURE__ */ zod
.object({
- deleted: zod.boolean().nullish(),
name: zod
.string()
.max(warehouseSavedQueriesUpdateBodyNameMax)
@@ -638,8 +643,15 @@ export const WarehouseSavedQueriesUpdateBody = /* @__PURE__ */ zod
soft_update: zod
.boolean()
.nullish()
- .describe('If true, skip column inference and validation. For saving drafts.'),
- dag_id: zod.uuid().nullish().describe('Optional DAG to place this view into'),
+ .describe(
+ 'If true, skip column inference and external table discovery. On update, also skip the query revision conflict check. Query validation and revision updates still run.'
+ ),
+ dag_id: zod
+ .uuid()
+ .nullish()
+ .describe(
+ 'DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.'
+ ),
is_test: zod.boolean().optional().describe('Whether this view is for testing only and will auto-expire.'),
})
.describe(
@@ -659,7 +671,6 @@ export const warehouseSavedQueriesPartialUpdateBodyIncrementalOneLookbackSeconds
export const WarehouseSavedQueriesPartialUpdateBody = /* @__PURE__ */ zod
.object({
- deleted: zod.boolean().nullish(),
name: zod
.string()
.max(warehouseSavedQueriesPartialUpdateBodyNameMax)
@@ -742,8 +753,15 @@ export const WarehouseSavedQueriesPartialUpdateBody = /* @__PURE__ */ zod
soft_update: zod
.boolean()
.nullish()
- .describe('If true, skip column inference and validation. For saving drafts.'),
- dag_id: zod.uuid().nullish().describe('Optional DAG to place this view into'),
+ .describe(
+ 'If true, skip column inference and external table discovery. On update, also skip the query revision conflict check. Query validation and revision updates still run.'
+ ),
+ dag_id: zod
+ .uuid()
+ .nullish()
+ .describe(
+ 'DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.'
+ ),
is_test: zod.boolean().optional().describe('Whether this view is for testing only and will auto-expire.'),
})
.describe(
@@ -780,7 +798,6 @@ export const warehouseSavedQueriesCancelCreateBodyIncrementalOneLookbackSecondsM
export const WarehouseSavedQueriesCancelCreateBody = /* @__PURE__ */ zod
.object({
- deleted: zod.boolean().nullish(),
name: zod
.string()
.max(warehouseSavedQueriesCancelCreateBodyNameMax)
@@ -861,8 +878,15 @@ export const WarehouseSavedQueriesCancelCreateBody = /* @__PURE__ */ zod
soft_update: zod
.boolean()
.nullish()
- .describe('If true, skip column inference and validation. For saving drafts.'),
- dag_id: zod.uuid().nullish().describe('Optional DAG to place this view into'),
+ .describe(
+ 'If true, skip column inference and external table discovery. On update, also skip the query revision conflict check. Query validation and revision updates still run.'
+ ),
+ dag_id: zod
+ .uuid()
+ .nullish()
+ .describe(
+ 'DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.'
+ ),
is_test: zod.boolean().optional().describe('Whether this view is for testing only and will auto-expire.'),
})
.describe(
@@ -919,7 +943,6 @@ export const warehouseSavedQueriesRevertMaterializationCreateBodyIncrementalOneL
export const WarehouseSavedQueriesRevertMaterializationCreateBody = /* @__PURE__ */ zod
.object({
- deleted: zod.boolean().nullish(),
name: zod
.string()
.max(warehouseSavedQueriesRevertMaterializationCreateBodyNameMax)
@@ -1004,8 +1027,15 @@ export const WarehouseSavedQueriesRevertMaterializationCreateBody = /* @__PURE__
soft_update: zod
.boolean()
.nullish()
- .describe('If true, skip column inference and validation. For saving drafts.'),
- dag_id: zod.uuid().nullish().describe('Optional DAG to place this view into'),
+ .describe(
+ 'If true, skip column inference and external table discovery. On update, also skip the query revision conflict check. Query validation and revision updates still run.'
+ ),
+ dag_id: zod
+ .uuid()
+ .nullish()
+ .describe(
+ 'DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.'
+ ),
is_test: zod.boolean().optional().describe('Whether this view is for testing only and will auto-expire.'),
})
.describe(
diff --git a/products/data_warehouse/mcp/tools.yaml b/products/data_warehouse/mcp/tools.yaml
index 13a95763dabb..177d74309b02 100644
--- a/products/data_warehouse/mcp/tools.yaml
+++ b/products/data_warehouse/mcp/tools.yaml
@@ -308,7 +308,6 @@ tools:
Delete a data warehouse saved query (view) by ID. This is a soft delete — the view is marked as deleted and
will no longer appear in lists or be queryable in HogQL. Any materialization schedule is also removed.
Cannot delete views that have downstream dependencies or views from managed viewsets.
- soft_delete: true
view-get:
operation: warehouse_saved_queries_retrieve
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4e433d807e26..01a32579ecd9 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -27093,7 +27093,7 @@ export namespace Schemas {
export interface DataWarehouseSavedQuery {
readonly id: string;
/** @nullable */
- deleted?: boolean | null;
+ readonly deleted: boolean | null;
/**
* Unique name for the view. Used as the table name in HogQL queries and the node name in the data modeling Node.
* @maxLength 128
@@ -27159,12 +27159,12 @@ export namespace Schemas {
*/
readonly latest_history_id: string | null;
/**
- * If true, skip column inference and validation. For saving drafts.
+ * If true, skip column inference and external table discovery. On update, also skip the query revision conflict check. Query validation and revision updates still run.
* @nullable
*/
soft_update?: boolean | null;
/**
- * Optional DAG to place this view into
+ * DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.
* @nullable
*/
dag_id?: string | null;
@@ -73176,7 +73176,7 @@ export namespace Schemas {
export interface PatchedDataWarehouseSavedQuery {
readonly id?: string;
/** @nullable */
- deleted?: boolean | null;
+ readonly deleted?: boolean | null;
/**
* Unique name for the view. Used as the table name in HogQL queries and the node name in the data modeling Node.
* @maxLength 128
@@ -73242,12 +73242,12 @@ export namespace Schemas {
*/
readonly latest_history_id?: string | null;
/**
- * If true, skip column inference and validation. For saving drafts.
+ * If true, skip column inference and external table discovery. On update, also skip the query revision conflict check. Query validation and revision updates still run.
* @nullable
*/
soft_update?: boolean | null;
/**
- * Optional DAG to place this view into
+ * DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.
* @nullable
*/
dag_id?: string | null;
diff --git a/services/mcp/src/generated/data_warehouse/api.ts b/services/mcp/src/generated/data_warehouse/api.ts
index a265f866981e..f2013beb4d91 100644
--- a/services/mcp/src/generated/data_warehouse/api.ts
+++ b/services/mcp/src/generated/data_warehouse/api.ts
@@ -400,7 +400,12 @@ export const WarehouseSavedQueriesCreateBody = () => zod
.string()
.nullish()
.describe('Optional folder ID used to organize this view in the SQL editor sidebar.'),
- dag_id: zod.string().nullish().describe('Optional DAG to place this view into'),
+ dag_id: zod
+ .string()
+ .nullish()
+ .describe(
+ 'DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.'
+ ),
is_test: zod.boolean().optional().describe('Whether this view is for testing only and will auto-expire.'),
})
.describe(
@@ -520,7 +525,12 @@ export const WarehouseSavedQueriesPartialUpdateBody = () => zod
.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'),
+ dag_id: zod
+ .string()
+ .nullish()
+ .describe(
+ 'DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.'
+ ),
is_test: zod.boolean().optional().describe('Whether this view is for testing only and will auto-expire.'),
})
.describe(
@@ -590,7 +600,6 @@ export const warehouseSavedQueriesRevertMaterializationCreateBodyIncrementalOneL
export const WarehouseSavedQueriesRevertMaterializationCreateBody = () => zod
.object({
- deleted: zod.boolean().nullish(),
name: zod
.string()
.max(warehouseSavedQueriesRevertMaterializationCreateBodyNameMax)
@@ -675,8 +684,15 @@ export const WarehouseSavedQueriesRevertMaterializationCreateBody = () => zod
soft_update: zod
.boolean()
.nullish()
- .describe('If true, skip column inference and validation. For saving drafts.'),
- dag_id: zod.string().nullish().describe('Optional DAG to place this view into'),
+ .describe(
+ 'If true, skip column inference and external table discovery. On update, also skip the query revision conflict check. Query validation and revision updates still run.'
+ ),
+ dag_id: zod
+ .string()
+ .nullish()
+ .describe(
+ 'DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed.'
+ ),
is_test: zod.boolean().optional().describe('Whether this view is for testing only and will auto-expire.'),
})
.describe(
diff --git a/services/mcp/src/tools/generated/data_warehouse.ts b/services/mcp/src/tools/generated/data_warehouse.ts
index 5e83d3f89c87..ae8b04bf0058 100644
--- a/services/mcp/src/tools/generated/data_warehouse.ts
+++ b/services/mcp/src/tools/generated/data_warehouse.ts
@@ -277,15 +277,14 @@ const ViewDeleteSchema = () => {
return WarehouseSavedQueriesDestroyParams.omit({ project_id: true })
}
-const viewDelete = (): ToolBase<ReturnType<typeof ViewDeleteSchema>, Schemas.DataWarehouseSavedQuery> => ({
+const viewDelete = (): ToolBase<ReturnType<typeof ViewDeleteSchema>, unknown> => ({
name: 'view-delete',
schema: ViewDeleteSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof ViewDeleteSchema>>) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.DataWarehouseSavedQuery>({
- method: 'PATCH',
+ const result = await context.api.request<unknown>({
+ method: 'DELETE',
path: `/api/projects/${encodeURIComponent(String(projectId))}/warehouse_saved_queries/${encodeURIComponent(String(params.id))}/`,
- body: { deleted: true },
})
return result
},
@@ -436,9 +435,6 @@ const viewUnmaterialize = (): ToolBase<
handler: async (context: Context, params: z.infer<ReturnType<typeof ViewUnmaterializeSchema>>) => {
const projectId = await context.stateManager.getProjectId()
const body: Record<string, unknown> = {}
- if (params.deleted !== undefined) {
- body['deleted'] = params.deleted
- }
if (params.name !== undefined) {
body['name'] = params.name
}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-create.json
index 9e154cb46bdd..2c0f79b091b0 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-create.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-create.json
@@ -10,7 +10,7 @@
"type": "null"
}
],
- "description": "Optional DAG to place this view into"
+ "description": "DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed."
},
"description": {
"anyOf": [
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 e4441954cfb7..25017dda0d1f 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-unmaterialize.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-unmaterialize.json
@@ -10,17 +10,7 @@
"type": "null"
}
],
- "description": "Optional DAG to place this view into"
- },
- "deleted": {
- "anyOf": [
- {
- "type": "boolean"
- },
- {
- "type": "null"
- }
- ]
+ "description": "DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed."
},
"description": {
"anyOf": [
@@ -130,7 +120,7 @@
"type": "null"
}
],
- "description": "If true, skip column inference and validation. For saving drafts."
+ "description": "If true, skip column inference and external table discovery. On update, also skip the query revision conflict check. Query validation and revision updates still run."
},
"sync_frequency": {
"anyOf": [
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-update.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-update.json
index b81d41e4617b..7254717db045 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/view-update.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/view-update.json
@@ -10,7 +10,7 @@
"type": "null"
}
],
- "description": "Optional DAG to place this view into"
+ "description": "DAG in this project to place the view into. Null uses the default DAG. Managed DAGs are not allowed."
},
"description": {
"anyOf": [