:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(data-modeling): delete the v1 materialization workflow (#92157)
Jovan Sakovic5ee8add7942d
diff --git a/.depot/workflows/ci-backend.yml b/.depot/workflows/ci-backend.ymlindex b9e44a7f6d39..fb24f6ea601e 100644--- a/.depot/workflows/ci-backend.yml+++ b/.depot/workflows/ci-backend.yml@@ -2339,9 +2339,6 @@ jobs:# shellcheck disable=SC2086pytest -v --tb=short --reuse-db -o junit_duration_report=call $TEMPORAL_FILES -m "not async_migrations" \"${SELECTED_SPLIT[@]}" \- --deselect "posthog/temporal/tests/data_modeling/test_run_workflow.py::test_run_workflow_with_minio_bucket" \- --deselect "posthog/temporal/tests/data_modeling/test_run_workflow.py::test_run_workflow_timeout_does_not_pause_schedule_without_consecutive_failures" \- --deselect "posthog/temporal/tests/data_modeling/test_run_workflow.py::test_run_workflow_timeout_pauses_schedule_after_5_consecutive_failures" \-r fEsxX \--junitxml=junit-temporal.xml \$PYTEST_ARGS@@ -2350,9 +2347,6 @@ jobs:# safety net. The per-test timeout also terminates the whole process, so it adds# no protection beyond the job timeout.pytest -v --tb=short --reuse-db -o junit_duration_report=call posthog/temporal products/signals/backend/emission -m "not async_migrations" \- --deselect "posthog/temporal/tests/data_modeling/test_run_workflow.py::test_run_workflow_with_minio_bucket" \- --deselect "posthog/temporal/tests/data_modeling/test_run_workflow.py::test_run_workflow_timeout_does_not_pause_schedule_without_consecutive_failures" \- --deselect "posthog/temporal/tests/data_modeling/test_run_workflow.py::test_run_workflow_timeout_pauses_schedule_after_5_consecutive_failures" \--splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \--durations=100 --durations-min=1.0 \--pytest-durations=100 \diff --git a/.github/CODEOWNERS b/.github/CODEOWNERSindex 3bc76c0b79c8..688d0c7f3ffe 100644--- a/.github/CODEOWNERS+++ b/.github/CODEOWNERS@@ -57,10 +57,6 @@ posthog/api/authentication.py @PostHog/team-securityposthog/auth.py @PostHog/team-securityee/api/scim/auth.py @PostHog/team-security-# v1 data-modeling workflow is frozen during the v1 → v2 migration.-# this will be removed from CODEOWNERS by June 1-posthog/temporal/data_modeling/run_workflow.py @PostHog/team-data-modeling-# Dev sandbox provides important protection in local devbin/dev-sandbox* @PostHog/team-securitydiff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.ymlindex 72a08e6505a4..2d805f066df7 100644--- a/.github/workflows/ci-backend.yml+++ b/.github/workflows/ci-backend.yml@@ -922,8 +922,8 @@ jobs:# via sync_connect() in their tests, so keep a readiness gate before tests run.# By this point Temporal has warmed up in the background, so the wait is negligible.# data_warehouse tests use custom search attributes (PostHogTeamId, PostHogOrgId,- # PostHogDagId) when calling schedule_materialization() → sync_saved_query_workflow(),- # so they must be registered before tests run.+ # PostHogDagId) when scheduling materialization, so they must be registered+ # before tests run.run: |bin/wait-for-docker temporalpython manage.py register_temporal_search_attributesdiff --git a/posthog/temporal/data_modeling/AGENTS.md b/posthog/temporal/data_modeling/AGENTS.mdindex 12557a748b9b..01c13a298a62 100644--- a/posthog/temporal/data_modeling/AGENTS.md+++ b/posthog/temporal/data_modeling/AGENTS.md@@ -1,34 +1,31 @@# Data-modeling Temporal workflowsTemporal workflows and activities that materialize data-modeling saved queries.-v2 is the only backend. The v1 code stays registered until its schedules are removed.+v2 is the only backend, and the only one there has ever been in this tree since v1 was deleted.-## v1 — dead, pending removal+## Layout-- `run_workflow.py` (1814-line monolith).-- Node and saved-query interactive paths always start v2. No production or management-command- call site creates a `data-modeling-run` schedule. Endpoint compatibility paths can still trigger- a pre-existing schedule until the v1 control cleanup lands.-- `RunWorkflow` stays in `WORKFLOWS` (`__init__.py`) on purpose. A schedule that points at a- deregistered workflow type keeps firing, fails its workflow task, and writes no job row, so- the workflow can only be removed after its schedules are gone.--**Do not extend v1.** No new features, no refactors, no new error types.-The v1 code exists only until its schedules are removed.--## v2 — active--- `workflows/materialize_view.py` and `workflows/execute_dag.py`.+- `workflows/materialize_view.py` materializes one saved query.+- `workflows/execute_dag.py` runs a DAG, or a tier's subset of its nodes.- Activities in `activities/*.py`.- Node `run` starts `data-modeling-execute-dag`. Node `materialize` and saved-query `run` start`data-modeling-materialize-view` through `start_node_materialization`.-All new work targets v2: new activities, new error types, configuration knobs,-reliability fixes, and tests.+## The retired v1 backend++`run_workflow.py` and the `data-modeling-run` per-query schedules it served are gone. Deleting+the workflow type had to come last: a schedule pointing at a deregistered type does not fail+loudly, it keeps firing, fails its workflow task, and writes no job row. So the type was+deregistered only once both regions held zero `data-modeling-run` schedules.++Two artifacts of v1 survive on purpose. `resolve_log_source` still parses the v1 workflow id+shape, or every pre-cutover run loses its logs; and the v1 `DataModelingJob` rows are the only+record of what ran before the cutover.## Scoping-- `products/data_warehouse/` is owned by another team. Read-only from here —- do not modify code under that tree without their review.-- `DataModelingJob` currently lives in `products/data_warehouse/` for historical- reasons; It will soon be moved to `products/data_modeling/`.+- `products/data_warehouse/` is owned by another team, but the saved-query surface in it+ (`presentation/views/saved_query.py` and `logic/data_load/saved_query_service.py`) is data+ modeling's to change. Anything else under that tree needs their review.+- `DataModelingJob` lives in `products/data_modeling/backend/models/`. Only its viewset is+ still under `products/data_warehouse/`.diff --git a/posthog/temporal/data_modeling/__init__.py b/posthog/temporal/data_modeling/__init__.pyindex c8b172fe80bf..310a10763d6a 100644--- a/posthog/temporal/data_modeling/__init__.py+++ b/posthog/temporal/data_modeling/__init__.py@@ -16,24 +16,13 @@ from posthog.temporal.data_modeling.activities import (stage_queryable_files_activity,succeed_materialization_activity,)-from posthog.temporal.data_modeling.run_workflow import (- RunWorkflow,- build_dag_activity,- cancel_jobs_activity,- cleanup_running_jobs_activity,- create_job_model_activity,- fail_jobs_activity,- finish_run_activity,- run_dag_activity,- start_run_activity,-)from posthog.temporal.data_modeling.workflows import (EnrichViewSemanticsWorkflow,ExecuteDAGWorkflow,MaterializeViewWorkflow,)-WORKFLOWS = [RunWorkflow, MaterializeViewWorkflow, ExecuteDAGWorkflow]+WORKFLOWS = [MaterializeViewWorkflow, ExecuteDAGWorkflow]# Semantic enrichment is LLM work that must not contend with materialization slots, so it runs on the# metadata queue rather than the materialization queues. Kept as separate lists (NOT folded into@@ -54,14 +43,6 @@ ACTIVITIES = [quality_block_materialization_activity,stage_queryable_files_activity,succeed_materialization_activity,- finish_run_activity,- start_run_activity,- build_dag_activity,- run_dag_activity,- cancel_jobs_activity,- fail_jobs_activity,- create_job_model_activity,- cleanup_running_jobs_activity,preempt_dag_run_activity,notify_dag_materialization_failures_activity,]diff --git a/posthog/temporal/data_modeling/run_workflow.py b/posthog/temporal/data_modeling/run_workflow.pydeleted file mode 100644index 3cb4eea24a41..000000000000--- a/posthog/temporal/data_modeling/run_workflow.py+++ /dev/null@@ -1,1875 +0,0 @@-"""Data-modeling Temporal workflow v1 — FROZEN.--Do not extend this module. v1 is being migrated to v2, which lives at-`posthog/temporal/data_modeling/workflows/{materialize_view,execute_dag}.py`.-New features, bug fixes for new behavior, and refactors belong in v2.--Bug fixes that affect both versions can land here, but treat that as the-exception.-"""--import gc-import os-import re-import enum-import json-import uuid-import typing-import asyncio-import datetime as dt-import itertools-import dataclasses-import collections.abc--from django.conf import settings-from django.core.exceptions import ObjectDoesNotExist-from django.db import transaction--import pyarrow as pa-import deltalake-import asyncstdlib-import pyarrow.compute as pc-import temporalio.common-import temporalio.activity-import temporalio.workflow-import temporalio.exceptions-from structlog.contextvars import bind_contextvars-from structlog.types import FilteringBoundLogger-from temporalio.exceptions import WorkflowAlreadyStartedError-from temporalio.workflow import ParentClosePolicy--from posthog.hogql import ast-from posthog.hogql.constants import HogQLGlobalSettings-from posthog.hogql.context import HogQLContext-from posthog.hogql.database.database import Database-from posthog.hogql.modifiers import create_default_modifiers_for_team-from posthog.hogql.parser import parse_select-from posthog.hogql.printer import prepare_ast_for_printing, print_prepared_ast--from posthog.clickhouse.query_tagging import Feature, Product, tag_queries-from posthog.exceptions_capture import capture_exception-from posthog.models import Team-from posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME-from posthog.settings.base_variables import TEST-from posthog.sync import database_sync_to_async-from posthog.temporal.common.base import PostHogWorkflow-from posthog.temporal.common.clickhouse import get_client-from posthog.temporal.common.heartbeat import Heartbeater-from posthog.temporal.common.logger import get_logger-from posthog.temporal.data_modeling.activities.fail_materialization import (- CONSECUTIVE_TIMEOUTS_TO_PAUSE,- should_pause_schedule_for_timeout,-)-from posthog.temporal.data_modeling.activities.utils import strip_hostname_from_error-from posthog.temporal.data_modeling.metrics import get_data_modeling_finished_metric--from products.data_modeling.backend.facade.modeling import DataWarehouseModelPath-from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery-from products.data_warehouse.backend.facade.api import (- a_pause_saved_query_schedule,- create_table_from_saved_query,- ensure_bucket_exists,- get_s3_client,-)-from products.endpoints.backend.facade.temporal import (- prepare_executable_query,- update_materialization_ready_for_saved_query,-)-from products.managed_warehouse.backend.facade.temporal import (- DataModelingDuckLakeCopyInputs,- DuckLakeCopyDataModelingWorkflow,- DuckLakeCopyModelInput,-)-from products.warehouse_sources.backend.facade.models import DataWarehouseTable-from products.warehouse_sources.backend.facade.temporal import prepare_s3_files_for_querying--LOGGER = get_logger(__name__)---def _build_model_table_uri(team_id: int, model_label: str, normalized_name: str) -> str:- return f"{settings.BUCKET_URL}/team_{team_id}_model_{model_label}/modeling/{normalized_name}"---# preserve casing since we are already coming from a sql dialect, we don't need to worry about normalizing-os.environ["SCHEMA__NAMING"] = "direct"---class EmptyHogQLResponseColumnsError(Exception):- def __init__(self):- super().__init__("After running a HogQL query, no columns where returned")---class DataModelingCancelledException(Exception):- """Exception raised when a data modeling job is cancelled."""-- pass---class NonRetryableException(Exception):- @property- def cause(self) -> BaseException | None:- """Cause of the exception.-- This is the same as ``Exception.__cause__``.- """- return self.__cause__--[email protected](frozen=True)-class ModelNode:- """A node representing a model in a DAG.-- Attributes:- label: The model's label, which represents the model in all paths.- children: A set of labels from all this model's direct children. This implies the- existence of an edge from this model to each of the children.- parents: A set of labels from all this model's direct parents. This implies the- existence of an edge from each of the parents to this model.- """-- label: str- children: set[str] = dataclasses.field(default_factory=set)- parents: set[str] = dataclasses.field(default_factory=set)- selected: bool = False-- def as_selected(self, selected: bool) -> "ModelNode":- return ModelNode(label=self.label, children=self.children, parents=self.parents, selected=selected)---DAG = dict[str, ModelNode]---class RunDagActivityInputs:- """Inputs for `run_dag_activity`.-- Attributes:- team_id: The team ID of the team whom this DAG belongs in.- dag: The DAG to run.- We require the DAG to be represented as a dictionary of model labels to- `ModelNode` instances, as this is useful for the algorithm that- `run_dag_activity` executes. See it for more details.- """-- team_id: int- dag: DAG- job_id: str-- @property- def properties_to_log(self) -> dict[str, typing.Any]:- return {- "team_id": self.team_id,- }---class ModelStatus(enum.StrEnum):- """The status a model in the queue can be in."""-- COMPLETED = "Completed"- FAILED = "Failed"- READY = "Ready"---class QueueMessage:- """A queue message used to orchestrate the running of a DAG."""-- status: ModelStatus- label: str- error: str | None = None- ducklake_model: DuckLakeCopyModelInput | None = None---Results = collections.namedtuple("Results", ("completed", "failed", "ancestor_failed", "ducklake_models"))--NullablePattern = re.compile(r"Nullable\((.*)\)")---async def run_dag_activity(inputs: RunDagActivityInputs) -> Results:- """A Temporal activity to run a data modeling DAG.-- First, let's establish some definitions:- * "Running a model" means:- 1. Executing the model's query (which is always a `SELECT` query).- 2. Save query results as a delta lake table in S3 ("materialize the results").- Both steps are achieved with a dlt pipeline.- * A model is considered "ready to run" if all of its ancestors have successfully ran- already or if it has no ancestors.- * PostHog tables (e.g. events, persons, sessions) are assumed to be always available- and up to date, and thus can be considered to have ran successfully.-- This activity runs the following algorithm:- 1. Initialize 3 sets: completed, failed, and ancestor failed.- 2. Initialize a queue for models and statuses.- 3. Populate it with any models without parents set to status `ModelStatus.READY`.- 4. Start a loop.- 5. Pop an item from the queue and check the status:- a. If it's `ModelStatus.READY`, schedule a task to run the model. Once the task is- done, report back results by putting the same model with a- `ModelStatus.COMPLETED` or `ModelStatus.FAILED` in the queue.- b. If it's `ModelStatus.COMPLETED`, add the model to the completed set. Also, check- if any of the model's children have become ready to run, by checking if all of- their parents are in the completed set. Put any children that pass this check in- status `ModelStatus.READY` in the queue.- c. If it's `ModelStatus.FAILED`, add the model to the failed set. Also, add all- descendants of the model that just failed to the ancestor failed set.- 6. If the number of models in the completed, failed, and ancestor failed sets is equal- to the total number of models passed to this activity, exit the loop. Else, goto 5.- """- bind_contextvars(team_id=inputs.team_id)- logger = LOGGER.bind()-- completed = set()- ancestor_failed = set()- failed = set()- ducklake_models: list[DuckLakeCopyModelInput] = []- queue: asyncio.Queue[QueueMessage] = asyncio.Queue()-- tag_queries(team_id=inputs.team_id, product=Product.WAREHOUSE, feature=Feature.DATA_MODELING)-- await logger.adebug(f"DAG size = {len(inputs.dag)}")-- for name, node in inputs.dag.items():- await logger.adebug(f"Looping over DAG: {name}. node.label={node.label}")-- if not node.parents:- queue.put_nowait(QueueMessage(status=ModelStatus.READY, label=node.label))- await logger.adebug(f"Inserted to queue: {name}. node.label={node.label}")-- if queue.empty():- await logger.adebug("Queue is empty, raising")- raise asyncio.QueueEmpty()-- running_tasks = set()-- async with Heartbeater():- while True:- message = await queue.get()-- match message:- case QueueMessage(status=ModelStatus.READY, label=label):- await logger.adebug(f"Handling queue message READY. label={label}")- model = inputs.dag[label]- task = asyncio.create_task(handle_model_ready(model, inputs.team_id, queue, inputs.job_id, logger))- running_tasks.add(task)- task.add_done_callback(running_tasks.discard)-- case QueueMessage(status=ModelStatus.COMPLETED, label=label, ducklake_model=ducklake_model):- await logger.adebug(f"Handling queue message COMPLETED. label={label}")- node = inputs.dag[label]- completed.add(node.label)-- to_queue = []- for child_label in node.children:- child_node = inputs.dag[child_label]-- if completed >= child_node.parents:- to_queue.append(child_node)-- await logger.adebug(f"Putting models in queue: {[node.label for node in to_queue]}")-- task = asyncio.create_task(put_models_in_queue(to_queue, queue))- running_tasks.add(task)- task.add_done_callback(running_tasks.discard)-- if ducklake_model is not None:- ducklake_models.append(ducklake_model)-- queue.task_done()-- case QueueMessage(status=ModelStatus.FAILED, label=label):- await logger.adebug(f"Handling queue message FAILED. label={label}")- node = inputs.dag[label]- failed.add(node.label)-- to_mark_as_ancestor_failed = list(node.children)- marked = set()- while to_mark_as_ancestor_failed:- to_mark = to_mark_as_ancestor_failed.pop()- ancestor_failed.add(to_mark)- marked.add(to_mark)-- marked_node = inputs.dag[to_mark]- for child in marked_node.children:- if child in marked:- continue-- to_mark_as_ancestor_failed.append(child)-- queue.task_done()-- case message:- raise ValueError(f"Queue received an invalid message: {message}")-- if len(failed) + len(ancestor_failed) + len(completed) == len(inputs.dag):- break-- await logger.ainfo(- f"DAG run finished. completed={len(completed)}. failed={len(failed)}. ancestor_failed={len(ancestor_failed)}"- )- return Results(completed, failed, ancestor_failed, ducklake_models)---async def put_models_in_queue(models: collections.abc.Iterable[ModelNode], queue: asyncio.Queue[QueueMessage]) -> None:- """Put models in queue.-- Intended to handle the queue put calls in the background to avoid blocking the main thread.- We wait for all models to be put into the queue, concurrently, in a `asyncio.TaskGroup`.- """-- async with asyncio.TaskGroup() as tg:- for model in models:- tg.create_task(queue.put(QueueMessage(status=ModelStatus.READY, label=model.label)))---class CHQueryErrorMemoryLimitExceeded(Exception):- """Exception raised when a ClickHouse query exceeds memory limits."""-- pass---class CannotCoerceColumnException(Exception):- """Exception raised when column types cannot be coerced."""-- pass---async def handle_model_ready(- model: ModelNode,- team_id: int,- queue: asyncio.Queue[QueueMessage],- job_id: str,- logger: FilteringBoundLogger,-) -> None:- """Handle a model that is ready to run by materializing.-- After materializing is done, we can report back to the execution queue the result. If- the model is not marked as `selected`, then it doesn't need to be materialized, and we- can immediately put it back in the queue as `ModelStatus.COMPLETED`.-- Args:- model: The model we are trying to run.- team_id: The ID of the team who owns this model.- queue: The execution queue where we will report back results.- """-- ducklake_model: DuckLakeCopyModelInput | None = None- job: DataModelingJob | None = None-- try:- if model.selected is True:- job = await database_sync_to_async(DataModelingJob.objects.get)(id=job_id)-- team = await database_sync_to_async(Team.objects.get)(id=team_id)- saved_query = await get_saved_query(team, model.label)- if saved_query.origin == DataWarehouseSavedQuery.Origin.ENDPOINT:- await database_sync_to_async(prepare_executable_query)(saved_query)-- await materialize_model(model.label, team, saved_query, job, logger)- ducklake_model = DuckLakeCopyModelInput(- model_label=model.label,- saved_query_id=str(saved_query.id),- table_uri=_build_model_table_uri(team.pk, model.label, saved_query.normalized_name),- )- except CHQueryErrorMemoryLimitExceeded as err:- await logger.aexception("Memory limit exceeded for model %s", model.label, job_id=job_id)- await handle_error(job, model, queue, err, "Memory limit exceeded for model %s: %s", logger)- except CannotCoerceColumnException as err:- await logger.aexception("Type coercion error for model %s", model.label, job_id=job_id)- await handle_error(job, model, queue, err, "Type coercion error for model %s: %s", logger)- except DataModelingCancelledException as err:- await logger.aexception("Data modeling run was cancelled for model %s", model.label, job_id=job_id)- await handle_cancelled(job, model, queue, err, "Data modeling run was cancelled for model %s: %s", logger)- except ObjectDoesNotExist as err:- error_msg = (- f"Object not found (team_id={team_id}, model_label={model.label}, job_id={job_id}): {err}. "- "This likely indicates an orphaned Temporal schedule that should be cleaned up."- )- await logger.aerror(- error_msg,- team_id=team_id,- model_label=model.label,- job_id=job_id,- )- capture_exception(err)- wrapped = Exception(error_msg)- wrapped.__cause__ = err- await handle_error(job, model, queue, wrapped, error_msg, logger)- except Exception as err:- await logger.aexception(- "Failed to materialize model %s due to unexpected error: %s", model.label, str(err), job_id=job_id- )- capture_exception(err)- await handle_error(job, model, queue, err, "Failed to materialize model %s due to error: %s", logger)- else:- await logger.ainfo("Materialized model %s", model.label)- await queue.put(QueueMessage(status=ModelStatus.COMPLETED, label=model.label, ducklake_model=ducklake_model))- finally:- queue.task_done()---async def handle_error(- job: DataModelingJob | None,- model: ModelNode,- queue: asyncio.Queue[QueueMessage],- error: Exception,- error_message: str,- logger: FilteringBoundLogger,-):- error_str = str(error)- if job:- await logger.ainfo("Marking job %s as failed", job.id)- await logger.aerror(f"handle_error: error={error_str}. error_message={error_message}", write_only=True)- job.status = DataModelingJob.Status.FAILED- job.rows_materialized = 0- job.error = strip_hostname_from_error(error_str)- job.last_run_at = dt.datetime.now(dt.UTC)- await database_sync_to_async(job.save)()- await queue.put(- QueueMessage(status=ModelStatus.FAILED, label=model.label, error=strip_hostname_from_error(error_str))- )---async def handle_cancelled(- job: DataModelingJob | None,- model: ModelNode,- queue: asyncio.Queue[QueueMessage],- error: Exception,- error_message: str,- logger: FilteringBoundLogger,-):- error_str = str(error)- if job:- await logger.aerror(f"handle_cancelled: error={error_str}. error_message={error_message}", write_only=True)- job.status = DataModelingJob.Status.CANCELLED- job.rows_materialized = 0- job.error = strip_hostname_from_error(error_str)- job.last_run_at = dt.datetime.now(dt.UTC)- await database_sync_to_async(job.save)()- await queue.put(- QueueMessage(status=ModelStatus.FAILED, label=model.label, error=strip_hostname_from_error(error_str))- )---async def start_job_modeling_run(- team: Team, workflow_id: str, workflow_run_id: str, saved_query: DataWarehouseSavedQuery | None-) -> DataModelingJob:- """Create a DataModelingJob record in an async-safe way."""- job_create = database_sync_to_async(DataModelingJob.objects.create)- return await job_create(- team=team,- saved_query=saved_query,- status=DataModelingJob.Status.RUNNING,- workflow_id=workflow_id,- workflow_run_id=workflow_run_id,- created_by_id=saved_query.created_by_id if saved_query is not None else None,- )---async def get_saved_query(team: Team, model_label: str) -> DataWarehouseSavedQuery:- filter_params: dict[str, str | uuid.UUID] = {}- try:- model_id = uuid.UUID(model_label)- filter_params["id"] = model_id- except ValueError:- model_name = model_label- filter_params["name"] = model_name-- return await database_sync_to_async(- DataWarehouseSavedQuery.objects.prefetch_related("team")- .exclude(deleted=True)- .filter(team=team, **filter_params)- .get- )()---async def materialize_model(- model_label: str,- team: Team,- saved_query: DataWarehouseSavedQuery,- job: DataModelingJob,- logger: FilteringBoundLogger,-):- """Materialize a given model by running its query and piping the results into a delta table.-- Arguments:- model_label: A label representing the ID or the name of the model to materialize.- If it's a valid UUID, then we will assume it's the ID, otherwise we'll assume- it is the model's name.- team: The team the model belongs to.- saved_query: The saved query to materialize.- job: The DataModelingJob record for this run that tracks the lifecycle and rows of the run.- """- await logger.ainfo(f"Starting materialization for model: label={model_label} name={saved_query.name}")-- if not isinstance(saved_query.query, dict):- raise ValueError(f"Saved query {saved_query.id} is missing its query payload")-- hogql_query_value = saved_query.query.get("query")- if not isinstance(hogql_query_value, str):- raise ValueError(f"Saved query {saved_query.id} has an invalid query payload")-- hogql_query = hogql_query_value-- try:- row_count = 0-- table_uri = _build_model_table_uri(team.pk, model_label, saved_query.normalized_name)- storage_options = _get_credentials()-- await logger.adebug(f"Delta table URI = {table_uri}")-- # Delete existing table first so that there are no schema conflicts- s3 = get_s3_client()- try:- await logger.adebug(f"Deleting existing delta table at {table_uri}")- s3.delete(table_uri, recursive=True)- await logger.adebug("Table deleted")- except FileNotFoundError:- await logger.adebug(f"Table at {table_uri} not found - skipping deletion")-- try:- rows_expected = await get_query_row_count(hogql_query, team, logger)- await logger.ainfo(f"Expected rows: {rows_expected}")- # Set expected rows on the job- job.rows_expected = rows_expected- await database_sync_to_async(job.save)()- except Exception as e:- exception_str = str(e)- # If the count doesn't succeed due to the query timeout being exceeded, then re-raise- if "Timeout exceeded" in exception_str:- raise-- await logger.awarning(f"Failed to get expected row count: {str(e)}. Continuing without progress tracking.")- job.rows_expected = None- await database_sync_to_async(job.save)()-- delta_table: deltalake.DeltaTable | None = None-- async for index, res in asyncstdlib.enumerate(hogql_table(hogql_query, team, logger)):- batch, ch_types = res- batch = _transform_unsupported_decimals(batch)- batch = _transform_date_and_datetimes(batch, ch_types)- batch = _force_nullable(batch)-- if index == 0:- await logger.adebug(- f"Writing batch to delta table. index={index}. mode=overwrite. schema_mode=overwrite. batch_row_count={batch.num_rows}"- )-- write_start = dt.datetime.now()- deltalake.write_deltalake(- table_or_uri=table_uri,- storage_options=storage_options,- data=batch,- mode="overwrite",- schema_mode="overwrite",- )- delta_table = deltalake.DeltaTable(table_uri, storage_options=storage_options)- else:- await logger.adebug(- f"Writing batch to delta table. index={index}. mode=append. batch_row_count={batch.num_rows}"- )-- write_start = dt.datetime.now()- deltalake.write_deltalake(- table_or_uri=delta_table, # type: ignore[call-overload]- storage_options=storage_options,- data=batch,- mode="append",- )- write_duration = (dt.datetime.now() - write_start).total_seconds()-- row_count = row_count + batch.num_rows- save_start = dt.datetime.now()- updated = await database_sync_to_async(- DataModelingJob.objects.filter(id=job.id, status=DataModelingJob.Status.RUNNING).update- )(rows_materialized=row_count)- save_duration = (dt.datetime.now() - save_start).total_seconds()-- if updated == 0:- await logger.awarning("Job %s is no longer running, stopping materialization", job.id)- raise DataModelingCancelledException("Job was cancelled or preempted during materialization")-- await logger.adebug(- f"Batch {index} timings: write={write_duration:.2f}s, save={save_duration:.2f}s, total={write_duration + save_duration:.2f}s"- )-- # Explicitly delete batch to free memory after writing- del batch, ch_types-- await logger.ainfo(f"Finished writing to delta table. row_count={row_count}")-- except ObjectDoesNotExist:- raise- except DataModelingCancelledException:- raise- except Exception as e:- error_message = str(e)- await logger.aerror(f"Error materializing model {model_label}: {strip_hostname_from_error(error_message)}")- if "Query exceeds memory limits" in error_message:- error_message = f"Query exceeded memory limit. Try reducing its scope by changing the time range."- saved_query.latest_error = error_message- await database_sync_to_async(saved_query.save)()- await mark_job_as_failed(job, error_message, logger)- raise CHQueryErrorMemoryLimitExceeded(- f"Query for model {model_label} exceeds memory limits. Try reducing its scope by changing the time range."- ) from e-- elif "Cannot coerce type" in error_message:- error_message = f"Type coercion error. If you believe this is an error, please contact support."- saved_query.latest_error = error_message- await database_sync_to_async(saved_query.save)()- await mark_job_as_failed(job, error_message, logger)- raise CannotCoerceColumnException(f"Type coercion error in model {model_label}: {error_message}") from e- elif "Invalid data type for Delta Lake" in error_message:- error_message = f"Data type not supported. If you believe this is an error, please contact support."- saved_query.latest_error = error_message- await database_sync_to_async(saved_query.save)()- await mark_job_as_failed(job, error_message, logger)- raise CannotCoerceColumnException(- f"Data type not supported in model {model_label}: {error_message}. This is likely due to decimal precision."- ) from e- elif (- "Decimal value does not fit in precision" in error_message- or "Rescaling Decimal128 value would cause data loss" in error_message- ):- error_message = f"Decimal precision issue. Try reducing the precision of the decimal columns, or using toInt() or toFloat() to a cast to a different column type."- saved_query.latest_error = error_message- await database_sync_to_async(saved_query.save)()- await mark_job_as_failed(job, error_message, logger)- raise CannotCoerceColumnException(f"Decimal precision error in model {model_label}: {error_message}") from e- elif "Unknown table" in error_message:- error_message = (- f"Table reference no longer exists for model. This is likely due to a table no longer being available."- )- saved_query.latest_error = error_message- await logger.ainfo("Table reference no longer exists for model %s, reverting materialization", model_label)- # saving query handled in revert_materialization()- await revert_materialization(saved_query, logger)- await mark_job_as_failed(job, error_message, logger)- raise Exception(f"Table reference missing for model {model_label}: {error_message}") from e- elif "Memory limit" in error_message:- error_message = f"Query exceeded memory limit. Try reducing its scope by changing the time range."- saved_query.latest_error = error_message- await logger.ainfo("Query exceeded memory limit for model %s", model_label)- await database_sync_to_async(saved_query.save)()- await mark_job_as_failed(job, error_message, logger)- raise Exception(f"Query exceeded memory limit for model {model_label}: {error_message}") from e- elif "Timeout exceeded" in error_message or "exceeded timeout" in error_message.lower():- error_message = f"Query exceeded timeout - we limit queries to a 10-minute timeout."- saved_query.latest_error = error_message- await logger.ainfo("Query exceeded timeout limit for model %s", model_label)- await mark_job_as_failed(job, error_message, logger)-- should_pause, count = await database_sync_to_async(should_pause_schedule_for_timeout)(saved_query.id, job)- if should_pause:- saved_query.sync_frequency_interval = None- await database_sync_to_async(saved_query.save)()- await a_pause_saved_query_schedule(saved_query)- await logger.ainfo(- "Paused temporal schedule for query due to %d consecutive timeouts: saved_query_id=%s",- CONSECUTIVE_TIMEOUTS_TO_PAUSE,- saved_query.id,- )- else:- await database_sync_to_async(saved_query.save)()- await logger.ainfo(- "Timeout for query saved_query_id=%s - not pausing schedule (%d/%d consecutive timeouts)",- saved_query.id,- count,- CONSECUTIVE_TIMEOUTS_TO_PAUSE,- )- raise NonRetryableException(f"Query exceeded timeout limit for model {model_label}: {error_message}") from e- else:- sanitized_error = strip_hostname_from_error(error_message)- saved_query.latest_error = f"Query failed to materialize: {sanitized_error}"- await logger.aerror("Failed to materialize model with unexpected error: %s", str(e))- await database_sync_to_async(saved_query.save)()- await mark_job_as_failed(job, error_message, logger)- if isinstance(e, NonRetryableException):- raise- raise Exception(sanitized_error) from e-- data_modeling_job = await database_sync_to_async(DataModelingJob.objects.get)(id=job.id)- if data_modeling_job.status == DataModelingJob.Status.CANCELLED:- raise DataModelingCancelledException("Data modeling run was cancelled")-- # early exit for no results- if delta_table is None:- await database_sync_to_async(job.refresh_from_db)()- job.rows_materialized = 0- job.status = DataModelingJob.Status.COMPLETED- job.last_run_at = dt.datetime.now(dt.UTC)- job.error = "Warning: query returned no results" # we log an error to signify that this isn't an ideal result- await database_sync_to_async(job.save)()- return (saved_query.normalized_name, delta_table, job.id)-- await logger.ainfo("Compacting delta table")- delta_table.optimize.compact()- await logger.ainfo("Vacuuming delta table")- delta_table.vacuum(retention_hours=24, enforce_retention_duration=False, dry_run=False)-- file_uris = delta_table.file_uris()-- saved_query_table: DataWarehouseTable | None = None- if saved_query.table_id:- saved_query_table = await database_sync_to_async(DataWarehouseTable.objects.get)(id=saved_query.table_id)-- await logger.ainfo("Preparing queryable table in S3")- folder_path = await prepare_s3_files_for_querying(- folder_path=saved_query.folder_path,- table_name=saved_query.normalized_name,- file_uris=file_uris,- preserve_table_name_casing=True,- existing_queryable_folder=saved_query_table.queryable_folder if saved_query_table else None,- logger=logger,- # Reopen the table instead of reusing this snapshot: a concurrent compaction can advance the- # log after `delta_table` loaded, so the retry needs the listing that log now holds.- refresh_file_uris=lambda: asyncio.to_thread(- lambda: deltalake.DeltaTable(table_uri, storage_options=storage_options).file_uris()- ),- )-- saved_query.is_materialized = True- await database_sync_to_async(saved_query.save)()-- await logger.ainfo("Creating table")- create_result = await create_table_from_saved_query(str(job.id), str(saved_query.id), team.pk, folder_path)- dwh_table = create_result.table-- await database_sync_to_async(saved_query.refresh_from_db)()- saved_query.table_id = dwh_table.id- await database_sync_to_async(saved_query.save)()-- await update_table_row_count(saved_query, row_count, logger)-- # Update the job record with the row count and completed status- await database_sync_to_async(job.refresh_from_db)()- job.rows_materialized = row_count- job.status = DataModelingJob.Status.COMPLETED- job.last_run_at = dt.datetime.now(dt.UTC)- job.error = None # clear any previous error message- await database_sync_to_async(job.save)()-- await logger.adebug("Setting DataModelingJob.Status = COMPLETED")- await logger.ainfo("Materialization completed")- return (saved_query.normalized_name, delta_table, job.id)---async def mark_job_as_failed(job: DataModelingJob, error_message: str, logger: FilteringBoundLogger) -> None:- """- Mark DataModelingJob as failed.-- The original error message (with hostnames) is logged for internal debugging,- but the user-facing error has hostnames stripped to avoid exposing infrastructure details.- """-- await logger.aerror(f"mark_job_as_failed: {error_message}", write_only=True)- await logger.ainfo("Marking job %s as failed", job.id)- job.status = DataModelingJob.Status.FAILED- job.rows_materialized = 0- job.error = strip_hostname_from_error(error_message)- job.last_run_at = dt.datetime.now(dt.UTC)- await database_sync_to_async(job.save)()---async def revert_materialization(saved_query: DataWarehouseSavedQuery, logger: FilteringBoundLogger) -> None:- """- This stops the temporal workflow for a materialization view. Expected to be used in the case of an- unrecoverable error, like a table reference no longer existing.- """- try:- await database_sync_to_async(saved_query.revert_materialization)()-- await logger.ainfo("Successfully reverted materialization for saved query %s", saved_query.name)-- except Exception as e:- capture_exception(e)- await logger.aexception("Failed to revert materialization for saved query %s: %s", saved_query.name, str(e))---async def update_table_row_count(- saved_query: DataWarehouseSavedQuery, row_count: int, logger: FilteringBoundLogger-) -> None:- try:- table = None- if saved_query.table_id:- table = await database_sync_to_async(DataWarehouseTable.objects.get)(id=saved_query.table_id)-- if table:- table.row_count = row_count- await database_sync_to_async(table.save)()- await logger.ainfo("Updated row count for table %s to %d", saved_query.name, row_count)- else:- capture_exception(- ValueError(f"Could not find DataWarehouseTable record for saved query {saved_query.name}")- )- await logger.aexception("Could not find DataWarehouseTable record for saved query %s", saved_query.name)- except Exception as e:- capture_exception(e)- await logger.aexception("Failed to update row count for table %s: %s", saved_query.name, str(e))---async def get_query_row_count(query: str, team: Team, logger: FilteringBoundLogger) -> int:- """Get the total row count for a HogQL query. Differs in extraction with std query since it's a count query."""- count_query = f"SELECT count() FROM ({query})"-- query_node = parse_select(count_query)-- settings = HogQLGlobalSettings()- settings.max_execution_time = HOGQL_INCREASED_MAX_EXECUTION_TIME-- modifiers = await database_sync_to_async(create_default_modifiers_for_team)(team)- context = HogQLContext(- team=team,- team_id=team.id,- enable_select_queries=True,- limit_top_select=False,- modifiers=modifiers,- )- context.output_format = "TabSeparated"- # Userless materialization context; bypass warehouse HogQL access control so the model query- # can resolve its source tables/views.- context.database = await database_sync_to_async(Database.create_for)(- team=team, modifiers=context.modifiers, bypass_warehouse_access_control=True- )-- prepared_hogql_query = await database_sync_to_async(prepare_ast_for_printing)(- query_node, context=context, dialect="clickhouse", settings=settings, stack=[]- )-- if prepared_hogql_query is None:- raise EmptyHogQLResponseColumnsError()-- printed = await database_sync_to_async(print_prepared_ast)(- prepared_hogql_query,- context=context,- dialect="clickhouse",- settings=settings,- stack=[],- )-- await logger.adebug(f"Running count query: {printed}")-- async with get_client() as client:- async with client.apost_query(- query=printed,- query_parameters=context.values,- query_id=str(uuid.uuid4()),- ) as response:- result = await response.content.read()- count = int(result.decode("utf-8").strip())- return count---MB_100_IN_BYTES = 100 * 1000 * 1000---async def hogql_table(query: str, team: Team, logger: FilteringBoundLogger):- """A HogQL table given by a HogQL query."""-- await logger.adebug("Configuring hogql_table")-- query_node = parse_select(query)- assert query_node is not None-- settings = HogQLGlobalSettings()- settings.max_execution_time = HOGQL_INCREASED_MAX_EXECUTION_TIME-- modifiers = await database_sync_to_async(create_default_modifiers_for_team)(team)- context = HogQLContext(- team=team,- team_id=team.id,- enable_select_queries=True,- limit_top_select=False,- modifiers=modifiers,- )- # Userless materialization context; bypass warehouse HogQL access control so the model query- # can resolve its source tables/views.- context.database = await database_sync_to_async(Database.create_for)(- team=team, modifiers=context.modifiers, bypass_warehouse_access_control=True- )-- prepared_hogql_query = await database_sync_to_async(prepare_ast_for_printing)(- query_node, context=context, dialect="clickhouse", settings=settings, stack=[]- )- if prepared_hogql_query is None:- raise EmptyHogQLResponseColumnsError()-- printed = await database_sync_to_async(print_prepared_ast)(- prepared_hogql_query,- context=context,- dialect="clickhouse",- settings=settings,- stack=[],- )-- table_describe_query = f"DESCRIBE TABLE ({printed}) FORMAT TabSeparatedRaw"- arrow_type_conversion: dict[str, tuple[str, tuple[ast.Constant, ...]]] = {- # Guarantee timezone is stable- "DateTime": ("toTimeZone", (ast.Constant(value="UTC"),)),- # If Clickhouse detects this is a constant `NULL` column let's turn into `Nullable(String)` since ArrayFormat doesn't support `Nullable(Nothing)`- "Nullable(Nothing)": ("toNullableString", ()),- # A bunch of non-supported fields, just treat them as strings- "FIXED_SIZE_BINARY": ("toString", ()),- "JSON": ("toString", ()),- "UUID": ("toString", ()),- "ENUM": ("toString", ()),- "IPv4": ("toString", ()),- "IPv6": ("toString", ()),- }-- # Query for types first, check for any types ArrowStream doesn't support- # and rewrite the query wrapping those columns in a `toString(..)`- async with get_client() as client:- query_typings: list[tuple[str, str, tuple[str, tuple[ast.Constant, ...]] | None]] = []- has_type_to_convert = False-- await logger.adebug(f"Running describe query: {table_describe_query}")-- async with client.apost_query(- query=table_describe_query, query_parameters=context.values, query_id=str(uuid.uuid4())- ) as ch_response:- table_describe_response = await ch_response.content.read()- for line in table_describe_response.decode("utf-8").splitlines():- split_arr = line.strip().split("\t")- column_name = split_arr[0]- ch_type = split_arr[1]-- # Skip array types from conversion - they are already properly typed by ClickHouse- # and attempting to convert them causes errors like:- # "Illegal type Array(DateTime) of argument of function toTimezone"- is_array_type = ch_type.lower().startswith("array(")-- # Does the clickhouse type exist in our mapping of types to convert?- if any(uat.lower() in ch_type.lower() for uat in arrow_type_conversion.keys()) and not is_array_type:- # Find which type we need to convert- call_tuples = [- call_tuple- for uat, call_tuple in arrow_type_conversion.items()- if uat.lower() in ch_type.lower()- ]-- # We can safely assume there is at least one element in this array due to the outer `if`- selected_call_tuple = call_tuples[0]-- has_type_to_convert = True- query_typings.append((column_name, ch_type, selected_call_tuple))- else:- query_typings.append((column_name, ch_type, None))- if has_type_to_convert:- await logger.adebug("Query has fields that need converting")-- select_fields: list[ast.Expr] = []- for column_name, ch_type, conversion_tuple in query_typings:- if conversion_tuple is not None:- function_name, function_args = conversion_tuple- is_array = ch_type.lower().startswith("array(")-- if is_array:- await logger.adebug(- f"Converting {column_name} of type {ch_type} using arrayMap with {function_name}(..)"- )- # Use arrayMap to apply the conversion function to each array element- lambda_expr = ast.Lambda(- args=["x"],- expr=ast.Call(name=function_name, args=[ast.Field(chain=["x"]), *function_args]),- )- select_fields.append(- ast.Alias(- expr=ast.Call(name="arrayMap", args=[lambda_expr, ast.Field(chain=[column_name])]),- alias=column_name,- )- )- else:- await logger.adebug(- f"Converting {column_name} of type {ch_type} to be wrapped with {function_name}(..)"- )- select_fields.append(- ast.Alias(- expr=ast.Call(name=function_name, args=[ast.Field(chain=[column_name]), *function_args]),- alias=column_name,- )- )- else:- select_fields.append(ast.Field(chain=[column_name]))-- query_node = ast.SelectQuery(select=select_fields, select_from=ast.JoinExpr(table=query_node))-- # Re-print the query with `FORMAT = ArrowStream`- context.output_format = "ArrowStream"- # Set the preferred record batch size to be 100 MB- settings.preferred_block_size_bytes = MB_100_IN_BYTES-- arrow_prepared_hogql_query = await database_sync_to_async(prepare_ast_for_printing)(- query_node, context=context, dialect="clickhouse", stack=[], settings=settings- )-- if arrow_prepared_hogql_query is None:- raise EmptyHogQLResponseColumnsError()-- arrow_printed = await database_sync_to_async(print_prepared_ast)(- arrow_prepared_hogql_query, context=context, dialect="clickhouse", stack=[], settings=settings- )-- await logger.adebug(f"Running clickhouse query: {arrow_printed}")-- # Set max block size to 50,000 rows- async with get_client(max_block_size=50_000) as client:- batches = []- batches_size = 0- batch_count = 0- async for batch in client.astream_query_as_arrow(arrow_printed, query_parameters=context.values):- batches_size = batches_size + batch.nbytes- batches.append(batch)-- if batches_size >= MB_100_IN_BYTES:- await logger.adebug(f"Yielding {len(batches)} batches for total size of {batches_size / 1000 / 1000}MB")-- combined = _combine_batches(batches)- yield (- combined,- [(column_name, column_type) for column_name, column_type, _ in query_typings],- )-- # Explicitly clear references to allow garbage collection- del combined- batches.clear()- batches_size = 0- batch_count += 1-- # Trigger garbage collection every 10 batches to prevent memory fragmentation- if batch_count % 10 == 0:- await logger.adebug("Running garbage collection on batches")- gc.collect()-- # Yield any left over batches- if len(batches) > 0:- await logger.adebug(f"Yielding {len(batches)} batches for total size of {batches_size / 1000 / 1000}MB")- combined = _combine_batches(batches)- yield (- combined,- [(column_name, column_type) for column_name, column_type, _ in query_typings],- )- del combined- batches.clear()---def _combine_batches(batches: list[pa.RecordBatch]) -> pa.RecordBatch:- if len(batches) == 1:- return batches[0]-- table = pa.Table.from_batches(batches)- table = table.combine_chunks()- return table.to_batches(max_chunksize=table.num_rows)[0]---def _transform_date_and_datetimes(batch: pa.RecordBatch, types: list[tuple[str, str]]) -> pa.RecordBatch:- """Clickhouse can return date/datetimes as UInts. We need to transform the response back into a real date/datetime object-- The return types from clickhouse are:- ```- Date/Date32 => UInt16 (days since 1970-01-01)- DateTime => UInt32 (seconds since 1970-01-01)- DateTime64 => Timestamp (no need to convert)- ```- """-- new_columns: list[pa.Array] = []- new_fields: list[pa.Field] = []-- types_to_transform = ["Date", "Date32", "DateTime", "DateTime64"]- for column_name, type in types:- field = batch.schema.field(column_name)- column = batch.column(column_name)-- if not any(t.lower() in type.lower() for t in types_to_transform) or pa.types.is_date(field.type):- new_columns.append(column)- new_fields.append(field)- continue-- # Handle array/list types (e.g., Array(DateTime))- if pa.types.is_list(field.type):- if "datetime64" in type.lower():- # Array(DateTime64) -> list<timestamp(us, UTC)>- list_element_type: pa.DataType = pa.timestamp("us", tz="UTC")- list_type = pa.list_(list_element_type)- list_field = field.with_type(list_type)- # Cast list<uint64> -> list<int64> -> list<timestamp>- list_int64 = pc.cast(column, pa.list_(pa.int64()))- list_timestamp_s = pc.cast(list_int64, pa.list_(pa.timestamp("s")))- list_column = pc.cast(list_timestamp_s, list_type)- elif "datetime" in type.lower():- # Array(DateTime) -> list<timestamp(us, UTC)>- list_element_type = pa.timestamp("us", tz="UTC")- list_type = pa.list_(list_element_type)- list_field = field.with_type(list_type)- # Cast list<uint32> -> list<int64> -> list<timestamp(s)> -> list<timestamp(us, UTC)>- list_int64 = pc.cast(column, pa.list_(pa.int64()))- list_timestamp_s = pc.cast(list_int64, pa.list_(pa.timestamp("s")))- list_column = pc.cast(list_timestamp_s, list_type)- else:- # Array(Date) -> list<date32>- list_element_type = pa.date32()- list_type = pa.list_(list_element_type)- list_field = field.with_type(list_type)- # Cast list<uint16> -> list<int32> -> list<date32>- list_int32 = pc.cast(column, pa.list_(pa.int32()))- list_column = pc.cast(list_int32, list_type)-- new_fields.append(list_field)- new_columns.append(list_column)- continue-- # Handle scalar types- if "datetime64" in type.lower() and pa.types.is_timestamp(field.type):- scalar_field: pa.Field = field.with_type(pa.timestamp("us", tz="UTC"))- scalar_column = pc.cast(column, scalar_field.type)- elif "datetime" in type.lower():- scalar_field = field.with_type(pa.timestamp("us", tz="UTC"))- # Gotta upcast from UInt32 to Int64 then Timestamp(s) first, and finally after to microseconds after- int64_col = pc.cast(column, pa.int64())- seconds_col = pc.cast(int64_col, pa.timestamp("s"))- scalar_column = pc.cast(seconds_col, scalar_field.type)- else:- scalar_field = field.with_type(pa.date32())- # Gotta upcast from uint16 to int32 first- int32_col = pc.cast(column, pa.int32())- scalar_column = pc.cast(int32_col, scalar_field.type)-- new_fields.append(scalar_field)- new_columns.append(scalar_column)-- new_metadata: dict[str | bytes, str | bytes] | None = (- typing.cast(dict[str | bytes, str | bytes], dict(batch.schema.metadata)) if batch.schema.metadata else None- )-- return pa.RecordBatch.from_arrays(new_columns, schema=pa.schema(new_fields, metadata=new_metadata))---def _transform_unsupported_decimals(batch: pa.RecordBatch) -> pa.RecordBatch:- """- Transform high-precision decimal columns to types supported by Delta Lake.- Delta Lake supports decimal up to precision 38; ClickHouse may return Decimal256 (precision 76).- """- schema = batch.schema- columns_to_cast: dict[str, pa.DataType] = {}-- precision = 38- scale = 38 - 1-- for field in schema:- if isinstance(field.type, pa.Decimal128Type | pa.Decimal256Type):- if field.type.precision > 38:- original_scale = field.type.scale- new_scale = min(original_scale, scale)- columns_to_cast[field.name] = pa.decimal128(precision, new_scale)-- if not columns_to_cast:- return batch-- new_columns: list[pa.Array] = []- new_fields: list[pa.Field] = []-- for field in batch.schema:- col = batch[field.name]- if field.name in columns_to_cast:- decimal128_type = columns_to_cast[field.name]- try:- cast_col = pc.cast(col, decimal128_type)- new_fields.append(field.with_type(decimal128_type))- new_columns.append(cast_col)- except Exception:- # Fallback: cast via string, truncate, then cast to reduced decimal- reduced_decimal_type = pa.decimal128(precision, scale)- string_col = typing.cast(pa.StringArray, pc.cast(col, pa.string()))- truncated = pc.utf8_slice_codeunits(string_col, 0, precision)- cast_reduced = pc.cast(truncated, reduced_decimal_type)- new_fields.append(field.with_type(reduced_decimal_type))- new_columns.append(cast_reduced)- else:- new_fields.append(field)- new_columns.append(col)-- new_metadata: dict[str | bytes, str | bytes] | None = (- typing.cast(dict[str | bytes, str | bytes], dict(schema.metadata)) if schema.metadata else None- )-- return pa.RecordBatch.from_arrays(new_columns, schema=pa.schema(new_fields, metadata=new_metadata))---def _force_nullable(batch: pa.RecordBatch) -> pa.RecordBatch:- """Mark every column nullable so batch schemas don't diverge across delta commits.-- ClickHouse emits non-nullable columns for expressions, constants, concat()/toString(),- and non-Nullable source columns. When such a query spans more than one batch, the first- batch's overwrite pins a non-nullable delta schema and the later append routes through- delta-rs's DataFusion writer to reconcile schemas. DataFusion lowercases identifiers and- then fails to resolve case-sensitive columns, e.g. "No field named userid. ... Did you- mean 'userId'?" — breaking any column with uppercase characters. Pinning every column to- nullable keeps each batch's schema identical to the first overwrite, so the append never- triggers that path and camelCase column names survive.- """- nullable_schema = pa.schema(- [pa.field(field.name, field.type, nullable=True, metadata=field.metadata) for field in batch.schema],- metadata=typing.cast("dict[bytes | str, bytes | str] | None", batch.schema.metadata),- )- return batch.cast(nullable_schema)---def _get_credentials():- if settings.USE_LOCAL_SETUP:- ensure_bucket_exists(- settings.BUCKET_URL,- settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY,- settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,- settings.OBJECT_STORAGE_ENDPOINT,- )-- return {- "aws_access_key_id": settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY,- "aws_secret_access_key": settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,- "endpoint_url": settings.OBJECT_STORAGE_ENDPOINT,- "region_name": settings.DATAWAREHOUSE_LOCAL_BUCKET_REGION,- "AWS_DEFAULT_REGION": settings.DATAWAREHOUSE_LOCAL_BUCKET_REGION,- "AWS_ALLOW_HTTP": "true",- "AWS_S3_ALLOW_UNSAFE_RENAME": "true",- }-- if TEST:- return {- "aws_access_key_id": settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY,- "aws_secret_access_key": settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET,- "endpoint_url": settings.OBJECT_STORAGE_ENDPOINT,- "region_name": settings.DATAWAREHOUSE_LOCAL_BUCKET_REGION,- "AWS_DEFAULT_REGION": settings.DATAWAREHOUSE_LOCAL_BUCKET_REGION,- "AWS_ALLOW_HTTP": "true",- "AWS_S3_ALLOW_UNSAFE_RENAME": "true",- }-- return {- "AWS_S3_ALLOW_UNSAFE_RENAME": "true",- }--[email protected](frozen=True)-class Selector:- """A selector represents the models to select from a set of paths.-- Attributes:- label: The model we are selecting around.- ancestors: How many ancestors to select from the model from each of the paths.- descendants: How many descendants to select from the model from each of the paths.- """-- label: str- ancestors: int | typing.Literal["ALL"] = 0- descendants: int | typing.Literal["ALL"] = 0---Paths = list[str]-SelectorPaths = dict[Selector, Paths]---class BuildDagActivityInputs:- team_id: int- select: list[Selector] = dataclasses.field(default_factory=list)-- @property- def properties_to_log(self) -> dict[str, typing.Any]:- return {- "team_id": self.team_id,- }---class InvalidSelector(Exception):- def __init__(self, invalid_input: str):- super().__init__(f"invalid selector: '{invalid_input}'")---async def build_dag_activity(inputs: BuildDagActivityInputs) -> DAG:- """Construct a DAG from provided selector inputs."""- bind_contextvars(team_id=inputs.team_id)- logger = LOGGER.bind()-- await logger.adebug(f"starting build_dag_activity. selectors = {[select.label for select in inputs.select]}")-- tag_queries(team_id=inputs.team_id, product=Product.WAREHOUSE, feature=Feature.DATA_MODELING)- async with Heartbeater():- selector_paths: SelectorPaths = {}-- if not inputs.select:- matching_paths: list[str] = await database_sync_to_async(- lambda: list(- DataWarehouseModelPath.objects.filter(team_id=inputs.team_id).values_list("path", flat=True)- )- )()- selector_paths[- Selector(- label="*",- ancestors="ALL",- descendants="ALL",- )- ] = matching_paths- await logger.adebug(f"No selectors passed. Selecting all model paths")-- for selector_input in inputs.select:- query = f"*.{selector_input.label}.*"-- # TODO: Make this one database fetch for all selectors, instead of one per selector- matching_paths = await database_sync_to_async(- lambda query_value=query: list(- DataWarehouseModelPath.objects.filter(team_id=inputs.team_id, path__lquery=query_value).values_list(- "path", flat=True- )- )- )()-- selector_paths[selector_input] = matching_paths-- dag = await build_dag_from_selectors(selector_paths=selector_paths, team_id=inputs.team_id)-- return dag---async def build_dag_from_selectors(selector_paths: SelectorPaths, team_id: int) -> DAG:- """Build a DAG from a list of `DataWarehouseModelPath` paths.-- Our particular representation of a DAG includes all edges directly with each of the- nodes, as each `ModelNode` instance contains the label of each of its children and- parents, which implies the existence of edges between them.-- This particular representation of a DAG is useful for `run_dag_activity`, which needs- to locate nodes by label (thus, our DAG is a dictionary) and then check their children- and parents (thus both of these are sets already included with the node). Naturally,- this means that the same children and parents appear in multiple nodes.-- The cost of the redundancy of this representation is larger memory use, but we assume- that simple strings and sets won't blow things up until we grow massively. If that- ever does happen, some solution involving another level of indirection by storing- indexes to a list of nodes could be implemented. Good luck!- """- posthog_table_names = await get_posthog_table_names(team_id)- dag = {}-- for selector, paths in selector_paths.items():- ancestors_offset = selector.ancestors- descendants_offset = selector.descendants-- for path in paths:- if selector.label == "*":- label_index = -1- start = 0- end = len(path)-- else:- label_index = path.index(selector.label)-- if ancestors_offset == "ALL":- start = 0- else:- start = max(label_index - ancestors_offset, 0)-- if descendants_offset == "ALL":- end = len(path)- else:- end = min(label_index + descendants_offset, len(path) - 1)-- for index, label in enumerate(path):- if label not in dag:- dag[label] = ModelNode(label=label)-- node = dag[label]-- if (- (index == label_index or end >= index >= start)- and label not in posthog_table_names- and node.selected is False- ):- node = dag[label] = node.as_selected(True)-- if index > 0:- parent_node = path[index - 1]- node.parents.add(parent_node)-- if index < len(path) - 1:- child_node = path[index + 1]- node.children.add(child_node)-- return dag---async def get_posthog_table_names(team_id: int) -> list[str]:- team = await database_sync_to_async(Team.objects.get)(id=team_id)- hogql_db = await database_sync_to_async(Database.create_for)(team=team)- posthog_table_names = hogql_db.get_posthog_table_names()- return posthog_table_names---class StartRunActivityInputs:- dag: DAG- run_at: str- team_id: int-- @property- def properties_to_log(self) -> dict[str, typing.Any]:- return {- "team_id": self.team_id,- "run_at": self.run_at,- }---class CreateJobModelInputs:- team_id: int- select: list[Selector]---async def create_job_model_activity(inputs: CreateJobModelInputs) -> str:- bind_contextvars(team_id=inputs.team_id)- logger = LOGGER.bind()-- await logger.adebug(f"Creating DataModelingJob for {[selector.label for selector in inputs.select]}")-- team = await database_sync_to_async(Team.objects.get)(id=inputs.team_id)- workflow_id = temporalio.activity.info().workflow_id- workflow_run_id = temporalio.activity.info().workflow_run_id-- # Will always be defined if this activity was started by a workflow- assert workflow_id- assert workflow_run_id-- if len(inputs.select) != 0:- label = inputs.select[0].label- saved_query = await get_saved_query(team, label)- job = await start_job_modeling_run(team, workflow_id, workflow_run_id, saved_query)- else:- job = await start_job_modeling_run(team, workflow_id, workflow_run_id, None)-- return str(job.id)---class CleanupRunningJobsActivityInputs:- team_id: int- saved_query_ids: list[str] = dataclasses.field(default_factory=list)---@database_sync_to_async-def _preempt_running_jobs(team_id: int, saved_query_ids: list[str] | None = None) -> list[DataModelingJob]:- """Atomically fetch and mark orphaned RUNNING jobs as FAILED.-- When saved_query_ids is provided, only jobs belonging to those saved queries- are preempted (self-preemption). Otherwise, falls back to team-wide cleanup- for backwards compatibility.-- The SELECT and UPDATE run inside a single transaction with row-level locks- so concurrent cleanups cannot process the same jobs twice.- """- with transaction.atomic():- filters: dict[str, typing.Any] = {- "team_id": team_id,- "status": DataModelingJob.Status.RUNNING,- "engine": DataModelingJob.Engine.CLICKHOUSE,- }- if saved_query_ids:- resolved_uuids: list[uuid.UUID] = []- for label in saved_query_ids:- try:- resolved_uuids.append(uuid.UUID(label))- except ValueError:- try:- sq = DataWarehouseSavedQuery.objects.exclude(deleted=True).get(team_id=team_id, name=label)- resolved_uuids.append(sq.id)- except DataWarehouseSavedQuery.DoesNotExist:- pass- if resolved_uuids:- filters["saved_query_id__in"] = resolved_uuids-- orphaned_jobs = list(DataModelingJob.objects.select_for_update().filter(**filters))-- if not orphaned_jobs:- return []-- DataModelingJob.objects.filter(id__in=[job.id for job in orphaned_jobs]).update(- status=DataModelingJob.Status.FAILED,- rows_materialized=0,- error="Preempted: This job did not complete before the next scheduled job was triggered.",- updated_at=dt.datetime.now(dt.UTC),- last_run_at=dt.datetime.now(dt.UTC),- )-- return orphaned_jobs---async def cleanup_running_jobs_activity(inputs: CleanupRunningJobsActivityInputs) -> None:- """Marks orphaned RUNNING DataModelingJobs for this saved query as FAILED when starting a new run."""- bind_contextvars(team_id=inputs.team_id)- logger = LOGGER.bind()-- orphaned_jobs = await _preempt_running_jobs(inputs.team_id, inputs.saved_query_ids or None)-- if not orphaned_jobs:- await logger.adebug("No orphaned jobs found")- return-- await logger.ainfo(- f"Cleaned up {len(orphaned_jobs)} orphaned jobs",- orphaned_count=len(orphaned_jobs),- orphaned_job_ids=[str(job.id) for job in orphaned_jobs],- orphaned_saved_query_ids=[str(job.saved_query_id) for job in orphaned_jobs if job.saved_query_id is not None],- orphaned_workflow_ids=[job.workflow_id for job in orphaned_jobs if job.workflow_id],- )---async def start_run_activity(inputs: StartRunActivityInputs) -> None:- """Activity that starts a run by updating statuses of associated models."""- bind_contextvars(team_id=inputs.team_id)- logger = LOGGER.bind()-- try:- async with asyncio.TaskGroup() as tg:- for label, model in inputs.dag.items():- if model.selected is False:- continue-- await logger.adebug(f"Updating saved query status for {label} to RUNNING")- tg.create_task(- update_saved_query_status(label, DataWarehouseSavedQuery.Status.RUNNING, None, inputs.team_id)- )- except* Exception:- await logger.aexception("Failed to update saved query status when starting run")- raise---class FinishRunActivityInputs:- completed: list[str]- failed: list[str]- run_at: str- team_id: int-- @property- def properties_to_log(self) -> dict[str, typing.Any]:- return {- "team_id": self.team_id,- "run_at": self.run_at,- }---async def finish_run_activity(inputs: FinishRunActivityInputs) -> None:- """Activity that finishes a run by updating statuses of associated models."""- bind_contextvars(team_id=inputs.team_id)- logger = LOGGER.bind()-- run_at = dt.datetime.fromisoformat(inputs.run_at)-- try:- async with asyncio.TaskGroup() as tg:- for label in inputs.completed:- await logger.adebug(f"Updating saved query status for {label} to COMPLETED")- tg.create_task(- update_saved_query_status(label, DataWarehouseSavedQuery.Status.COMPLETED, run_at, inputs.team_id)- )-- for label in inputs.failed:- await logger.adebug(f"Updating saved query status for {label} to FAILED")- tg.create_task(- update_saved_query_status(label, DataWarehouseSavedQuery.Status.FAILED, None, inputs.team_id)- )- except* Exception:- await logger.aexception("Failed to update saved query status when finishing run")- raise---async def update_saved_query_status(- label: str, status: DataWarehouseSavedQuery.Status, run_at: dt.datetime | None, team_id: int-):- logger = LOGGER.bind()- filter_params: dict[str, int | str | uuid.UUID] = {"team_id": team_id}-- try:- model_id = uuid.UUID(label)- filter_params["id"] = model_id- except ValueError:- await logger.awarning(- f"Label '{label}' is not a valid UUID, falling back to name lookup - this indicates a data integrity issue"- )- filter_params["name"] = label-- saved_query = await database_sync_to_async(- DataWarehouseSavedQuery.objects.exclude(deleted=True).filter(**filter_params).get- )()-- if run_at:- saved_query.last_run_at = run_at- saved_query.status = status-- await database_sync_to_async(saved_query.save)()-- if saved_query.origin == DataWarehouseSavedQuery.Origin.ENDPOINT:- is_ready = status == DataWarehouseSavedQuery.Status.COMPLETED- await database_sync_to_async(update_materialization_ready_for_saved_query)(team_id, saved_query, is_ready)---class CancelJobsActivityInputs:- workflow_id: str- workflow_run_id: str- team_id: int---class FailJobsActivityInputs:- job_id: str- error: str- team_id: int---async def cancel_jobs_activity(inputs: CancelJobsActivityInputs) -> None:- """Activity to cancel data modeling jobs."""- bind_contextvars(team_id=inputs.team_id)- logger = LOGGER.bind()-- # updated_at is auto_now, which QuerySet.update() skips, so it has to be set by hand here to- # stay in step with last_run_at.- cancelled_at = dt.datetime.now(dt.UTC)- await database_sync_to_async(- DataModelingJob.objects.filter(workflow_id=inputs.workflow_id, workflow_run_id=inputs.workflow_run_id).update- )(- status=DataModelingJob.Status.CANCELLED,- rows_materialized=0,- last_run_at=cancelled_at,- updated_at=cancelled_at,- )- await logger.ainfo(- "Cancelled data modeling jobs", workflow_id=inputs.workflow_id, workflow_run_id=inputs.workflow_run_id- )---async def fail_jobs_activity(inputs: FailJobsActivityInputs) -> None:- """Activity to fail data modeling jobs."""- bind_contextvars(team_id=inputs.team_id)- logger = LOGGER.bind()-- job = await database_sync_to_async(DataModelingJob.objects.get)(id=inputs.job_id)-- await mark_job_as_failed(job, inputs.error, logger)---def _format_exception_chain(e: BaseException) -> str:- """Walk the exception cause chain and return a detailed error string."""- parts = [str(e)]- cause = e.__cause__- while cause is not None:- parts.append(f"Caused by {type(cause).__name__}: {cause}")- cause = cause.__cause__- return "\n".join(parts)---class RunWorkflowInputs:- """Inputs to `RunWorkflow`.-- Attributes:- team_id: The ID of the team we are running this for.- select: A list of model selectors to define the models to run.- """-- team_id: int- select: list[Selector] = dataclasses.field(default_factory=list)-- @property- def properties_to_log(self) -> dict[str, typing.Any]:- return {- "team_id": self.team_id,- }--[email protected](name="data-modeling-run")-class RunWorkflow(PostHogWorkflow):- """A Temporal Workflow to run PostHog data models.-- A model is defined by a label, a saved query that dictates how to select the data that- makes up the model, and the path or paths to the model through all of its ancestors.- """-- ducklake_copy_inputs: list[DataModelingDuckLakeCopyInputs] = []-- @staticmethod- def parse_inputs(inputs: list[str]) -> RunWorkflowInputs:- """Parse inputs from the management command CLI."""- loaded = json.loads(inputs[0])- return RunWorkflowInputs(**loaded)-- @temporalio.workflow.run- async def run(self, inputs: RunWorkflowInputs) -> Results:- saved_query_ids = [s.label for s in inputs.select]- await temporalio.workflow.execute_activity(- cleanup_running_jobs_activity,- CleanupRunningJobsActivityInputs(team_id=inputs.team_id, saved_query_ids=saved_query_ids),- start_to_close_timeout=dt.timedelta(minutes=5),- retry_policy=temporalio.common.RetryPolicy(maximum_attempts=2),- )-- job_id = await temporalio.workflow.execute_activity(- create_job_model_activity,- CreateJobModelInputs(team_id=inputs.team_id, select=inputs.select),- start_to_close_timeout=dt.timedelta(minutes=5),- retry_policy=temporalio.common.RetryPolicy(- maximum_attempts=1,- ),- )-- build_dag_inputs = BuildDagActivityInputs(team_id=inputs.team_id, select=inputs.select)- dag = await temporalio.workflow.execute_activity(- build_dag_activity,- build_dag_inputs,- start_to_close_timeout=dt.timedelta(minutes=20),- heartbeat_timeout=dt.timedelta(minutes=1),- retry_policy=temporalio.common.RetryPolicy(- maximum_attempts=1,- ),- )-- run_at = dt.datetime.now(dt.UTC).isoformat()-- start_run_activity_inputs = StartRunActivityInputs(dag=dag, run_at=run_at, team_id=inputs.team_id)- await temporalio.workflow.execute_activity(- start_run_activity,- start_run_activity_inputs,- start_to_close_timeout=dt.timedelta(minutes=5),- retry_policy=temporalio.common.RetryPolicy(- maximum_attempts=1,- ),- )-- # Run the DAG- run_model_activity_inputs = RunDagActivityInputs(team_id=inputs.team_id, dag=dag, job_id=job_id)- try:- results = await temporalio.workflow.execute_activity(- run_dag_activity,- run_model_activity_inputs,- start_to_close_timeout=dt.timedelta(minutes=30),- heartbeat_timeout=dt.timedelta(minutes=2),- retry_policy=temporalio.common.RetryPolicy(- maximum_attempts=2, non_retryable_error_types=["NonRetryableException", "CancelledError"]- ),- cancellation_type=temporalio.workflow.ActivityCancellationType.TRY_CANCEL,- )- except temporalio.exceptions.ActivityError as e:- if isinstance(e.cause, temporalio.exceptions.CancelledError):- workflow_id = temporalio.workflow.info().workflow_id- workflow_run_id = temporalio.workflow.info().run_id- try:- await temporalio.workflow.execute_activity(- cancel_jobs_activity,- CancelJobsActivityInputs(- workflow_id=workflow_id, workflow_run_id=workflow_run_id, team_id=inputs.team_id- ),- start_to_close_timeout=dt.timedelta(minutes=5),- retry_policy=temporalio.common.RetryPolicy(- maximum_attempts=2,- ),- )- except Exception as cancel_err:- capture_exception(cancel_err)- temporalio.workflow.logger.error(f"Failed to cancel jobs: {str(cancel_err)}")- raise- raise-- capture_exception(e)- error_detail = _format_exception_chain(e)- temporalio.workflow.logger.error(f"Activity failed during model run: {error_detail}")-- await temporalio.workflow.execute_activity(- fail_jobs_activity,- FailJobsActivityInputs(job_id=job_id, error=error_detail, team_id=inputs.team_id),- start_to_close_timeout=dt.timedelta(minutes=5),- retry_policy=temporalio.common.RetryPolicy(- maximum_attempts=2,- ),- )- raise- except Exception as e:- error_detail = _format_exception_chain(e)- await temporalio.workflow.execute_activity(- fail_jobs_activity,- FailJobsActivityInputs(job_id=job_id, error=error_detail, team_id=inputs.team_id),- start_to_close_timeout=dt.timedelta(minutes=5),- retry_policy=temporalio.common.RetryPolicy(- maximum_attempts=2,- ),- )- raise-- completed, failed, ancestor_failed, ducklake_models = results-- self.ducklake_copy_inputs = [- DataModelingDuckLakeCopyInputs(- team_id=inputs.team_id,- job_id=job_id,- models=[DuckLakeCopyModelInput(**model) if isinstance(model, dict) else model],- )- for model in ducklake_models- ]- temporalio.workflow.logger.debug(- "Prepared DuckLake copy inputs",- team_id=inputs.team_id,- job_id=job_id,- models=len(self.ducklake_copy_inputs),- )-- # publish metrics- if failed or ancestor_failed:- get_data_modeling_finished_metric(status="failed").add(1)- elif completed:- get_data_modeling_finished_metric(status="completed").add(1)-- finish_run_activity_inputs = FinishRunActivityInputs(- completed=[label for label in completed if dag[label].selected is True],- failed=[label for label in itertools.chain(failed, ancestor_failed) if dag[label].selected is True],- run_at=run_at,- team_id=inputs.team_id,- )- await temporalio.workflow.execute_activity(- finish_run_activity,- finish_run_activity_inputs,- start_to_close_timeout=dt.timedelta(minutes=5),- retry_policy=temporalio.common.RetryPolicy(- maximum_attempts=1,- ),- )-- for copy_inputs in self.ducklake_copy_inputs:- model = copy_inputs.models[0]- try:- await temporalio.workflow.start_child_workflow(- DuckLakeCopyDataModelingWorkflow.run,- copy_inputs,- id=f"ducklake-copy-data-modeling-{inputs.team_id}-{model.saved_query_id}",- task_queue=settings.DUCKLAKE_TASK_QUEUE,- parent_close_policy=ParentClosePolicy.ABANDON,- retry_policy=temporalio.common.RetryPolicy(- maximum_attempts=1,- non_retryable_error_types=["NondeterminismError"],- ),- )- except WorkflowAlreadyStartedError:- temporalio.workflow.logger.warning(- "DuckLake copy already running, skipping",- saved_query_id=model.saved_query_id,- )-- return resultsdiff --git a/posthog/temporal/tests/data_modeling/test_run_workflow.py b/posthog/temporal/tests/data_modeling/test_run_workflow.pydeleted file mode 100644index bfa4f02ddde0..000000000000--- a/posthog/temporal/tests/data_modeling/test_run_workflow.py+++ /dev/null@@ -1,1892 +0,0 @@-import os-import re-import uuid-import asyncio-import datetime as dt-from typing import cast--import pytest-import unittest.mock-from freezegun.api import freeze_time--from django.conf import settings-from django.test import override_settings--import pyarrow as pa-import deltalake-import pytest_asyncio-import temporalio.common-import temporalio.worker-from asgiref.sync import sync_to_async-from temporalio import (- activity as temporal_activity,- workflow as temporal_workflow,-)-from temporalio.testing import WorkflowEnvironment--from posthog.hogql.database.database import Database-from posthog.hogql.query import execute_hogql_query--from posthog.models import Team-from posthog.models.event.sql import EVENTS_DATA_TABLE, EVENTS_JSON_DATA_TABLE-from posthog.models.event.util import bulk_create_events-from posthog.sync import database_sync_to_async-from posthog.temporal.data_modeling import run_workflow as run_workflow_module-from posthog.temporal.data_modeling.run_workflow import (- BuildDagActivityInputs,- CleanupRunningJobsActivityInputs,- CreateJobModelInputs,- ModelNode,- RunDagActivityInputs,- RunWorkflow,- RunWorkflowInputs,- Selector,- build_dag_activity,- cleanup_running_jobs_activity,- create_job_model_activity,- fail_jobs_activity,- finish_run_activity,- hogql_table,- materialize_model,- run_dag_activity,- start_run_activity,-)-from posthog.temporal.tests.utils.events import generate_test_events_in_clickhouse, truncate_table--from products.data_modeling.backend.facade.modeling import DataWarehouseModelPath-from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery-from products.managed_warehouse.backend.facade.temporal import DuckLakeCopyModelInput-from products.warehouse_sources.backend.facade.models import DataWarehouseTable--pytestmark = [pytest.mark.asyncio, pytest.mark.django_db(transaction=True)]---def test_time() -> dt.datetime:- # Freeze from test start rather than module import: boto3 signs S3 requests with the frozen- # clock, and the object store rejects a signature skewed by more than 15 minutes, so a shard- # that reaches this file late enough would fail every S3 call.- return dt.datetime.now(dt.UTC)---@pytest_asyncio.fixture-async def posthog_table_names(ateam):- team = await database_sync_to_async(Team.objects.get)(id=ateam.pk)- hogql_db = await database_sync_to_async(Database.create_for)(team=team)- posthog_table_names = hogql_db.get_posthog_table_names()-- return posthog_table_names--- "dag",- [- {- "events": ModelNode(label="events", children={"my_events_model"}),- "persons": ModelNode(label="persons", children={"my_persons_model"}),- "my_events_model": ModelNode(- label="my_events_model", children={"my_joined_model"}, parents={"events"}, selected=True- ),- "my_persons_model": ModelNode(- label="my_persons_model", children={"my_joined_model"}, parents={"persons"}, selected=True- ),- "my_joined_model": ModelNode(- label="my_joined_model", parents={"my_events_model", "my_persons_model"}, selected=True- ),- },- ],-)-async def test_run_dag_activity_activity_materialize_mocked(activity_environment, ateam, dag, posthog_table_names):- """Test all models are completed with a mocked materialize."""- for model_label in dag.keys():- if model_label not in posthog_table_names:- await database_sync_to_async(DataWarehouseSavedQuery.objects.create)(- team=ateam,- name=model_label,- query={"query": f"SELECT * FROM events LIMIT 10", "kind": "HogQLQuery"},- )-- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- )- run_dag_activity_inputs = RunDagActivityInputs(team_id=ateam.pk, dag=dag, job_id=job.id)-- magic_mock = unittest.mock.AsyncMock(return_value=("test_key", unittest.mock.MagicMock(), uuid.uuid4()))-- with unittest.mock.patch("posthog.temporal.data_modeling.run_workflow.materialize_model", new=magic_mock):- async with asyncio.timeout(10):- results = await activity_environment.run(run_dag_activity, run_dag_activity_inputs)-- models_materialized = [model for model in dag.keys() if model not in posthog_table_names]-- calls = magic_mock.mock_calls-- assert all(call.args[0] in models_materialized for call in calls), (- f"Found models that shouldn't have been materialized: {tuple(call.args[0] for call in calls if call.args[0] not in models_materialized)}"- )- assert all(call.args[1].pk == ateam.pk for call in calls), (- f"Found team ids that do not match test team ({ateam.pk}): {tuple(call.args[1].pk for call in calls)}"- )- assert len(calls) == len(models_materialized)- assert results.completed == set(dag.keys())--- "dag,make_fail",- [- (- {- "events": ModelNode(label="events", children={"my_events_model"}),- "persons": ModelNode(label="persons", children={"my_persons_model"}),- "my_events_model": ModelNode(- label="my_events_model", children={"my_joined_model"}, parents={"events"}, selected=True- ),- "my_persons_model": ModelNode(- label="my_persons_model", children={"my_joined_model"}, parents={"persons"}, selected=True- ),- "my_joined_model": ModelNode(- label="my_joined_model",- children={"my_read_from_joined_model"},- parents={"my_events_model", "my_persons_model"},- selected=True,- ),- "my_read_from_joined_model": ModelNode(- label="my_read_from_joined_model", parents={"my_joined_model"}, selected=True- ),- },- ("my_events_model",),- ),- ],-)-async def test_run_dag_activity_activity_skips_if_ancestor_failed_mocked(- activity_environment, ateam, dag, make_fail, posthog_table_names-):- """Test some models are completed while some fail with a mocked materialize.-- Args:- dag: The dictionary of `ModelNode`s representing the model DAG.- make_fail: A sequence of model labels of models that should fail to check they are- handled properly.- """- # Create the necessary saved queries for the test- for model_label in dag.keys():- if model_label not in posthog_table_names:- await database_sync_to_async(DataWarehouseSavedQuery.objects.create)(- team=ateam,- name=model_label,- query={"query": f"SELECT * FROM events LIMIT 10", "kind": "HogQLQuery"},- )-- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- )- run_dag_activity_inputs = RunDagActivityInputs(team_id=ateam.pk, dag=dag, job_id=job.id)- assert all(model not in posthog_table_names for model in make_fail), "PostHog tables cannot fail"-- def raise_if_should_make_fail(model_label, *args, **kwargs):- if model_label in make_fail:- raise ValueError("Oh no!")- return ("test_key", unittest.mock.MagicMock(), uuid.uuid4())-- expected_failed = set()- expected_ancestor_failed = set()-- for model in make_fail:- expected_failed.add(model)-- children_to_fail = list(dag[model].children)- while children_to_fail:- child = children_to_fail.pop()- expected_ancestor_failed.add(child)-- children_to_fail.extend(list(dag[child].children))-- expected_completed = {- key for key in dag.keys() if key not in expected_failed and key not in expected_ancestor_failed- }-- magic_mock = unittest.mock.AsyncMock(side_effect=raise_if_should_make_fail)- with unittest.mock.patch("posthog.temporal.data_modeling.run_workflow.materialize_model", new=magic_mock):- async with asyncio.timeout(10):- results = await activity_environment.run(run_dag_activity, run_dag_activity_inputs)-- models_materialized = [- model for model in expected_failed | expected_completed if model not in posthog_table_names- ]-- calls = magic_mock.mock_calls-- assert all(call.args[0] in models_materialized for call in calls), (- f"Found models that shouldn't have been materialized: {tuple(call.args[0] for call in calls if call.args[0] not in models_materialized)}"- )- assert all(call.args[1].pk == ateam.pk for call in calls), (- f"Found team ids that do not match test team ({ateam.pk}): {tuple(call.args[1].pk for call in calls)}"- )- assert len(calls) == len(models_materialized)-- assert results.completed == expected_completed- assert results.failed == expected_failed- assert results.ancestor_failed == expected_ancestor_failed---def mock_to_session_credentials(class_self):- return {- "aws_access_key_id": settings.OBJECT_STORAGE_ACCESS_KEY_ID,- "aws_secret_access_key": settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- "endpoint_url": settings.OBJECT_STORAGE_ENDPOINT,- "aws_session_token": None,- "AWS_ALLOW_HTTP": "true",- "AWS_S3_ALLOW_UNSAFE_RENAME": "true",- }---def mock_to_object_store_rs_credentials(class_self):- return {- "aws_access_key_id": settings.OBJECT_STORAGE_ACCESS_KEY_ID,- "aws_secret_access_key": settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- "endpoint_url": settings.OBJECT_STORAGE_ENDPOINT,- "region": "us-east-1",- "AWS_ALLOW_HTTP": "true",- "AWS_S3_ALLOW_UNSAFE_RENAME": "true",- }---@pytest_asyncio.fixture-async def truncate_events_table(clickhouse_client):- table = EVENTS_JSON_DATA_TABLE if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA else EVENTS_DATA_TABLE()- await truncate_table(clickhouse_client, table)---@pytest_asyncio.fixture-async def pageview_events(clickhouse_client, ateam, truncate_events_table):- start_time, end_time = dt.datetime.now(dt.UTC) - dt.timedelta(days=1), dt.datetime.now(dt.UTC)- table = EVENTS_JSON_DATA_TABLE if settings.CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA else EVENTS_DATA_TABLE()- events, _, events_from_other_team = await generate_test_events_in_clickhouse(- clickhouse_client,- ateam.pk,- start_time,- end_time,- event_name="$pageview",- count=50,- count_outside_range=0,- distinct_ids=["a", "b"],- table=table,- )- return (events, events_from_other_team)---async def test_materialize_model(ateam, bucket_name, minio_client, pageview_events):- query = """\- select- event as event,- if(distinct_id != '0', distinct_id, null) as distinct_id,- timestamp as timestamp- from events- where event = '$pageview'- """- saved_query = await DataWarehouseSavedQuery.objects.acreate(- team=ateam,- name="my_model",- query={"query": query, "kind": "HogQLQuery"},- )-- with override_settings(- BUCKET_URL=f"s3://{bucket_name}",- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",- ):- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- status=DataModelingJob.Status.RUNNING,- workflow_id="test_workflow",- )-- key, delta_table, job_id = await materialize_model(- saved_query.id.hex,- ateam,- saved_query,- job,- unittest.mock.AsyncMock(),- )-- s3_objects = await minio_client.list_objects_v2(- Bucket=bucket_name, Prefix=f"team_{ateam.pk}_model_{saved_query.id.hex}/"- )- table = delta_table.to_pyarrow_table(columns=["event", "distinct_id", "timestamp"])- events, _ = pageview_events- expected_events = sorted(- [- {- k: dt.datetime.fromisoformat(v).replace(tzinfo=dt.UTC) if k == "timestamp" else v- for k, v in event.items()- if k in ("event", "distinct_id", "timestamp")- }- for event in events- ],- key=lambda d: (d["distinct_id"], d["timestamp"]),- )-- query_folder_pattern = re.compile(r"^.+?\_\_query\_\d+_[0-9a-f]{8}\/.+")-- assert any(query_folder_pattern.match(obj["Key"]) for obj in s3_objects["Contents"])- assert any(f"{saved_query.normalized_name}__query" in obj["Key"] for obj in s3_objects["Contents"])- assert table.num_rows == len(expected_events)- assert table.num_columns == 3- assert table.column_names == ["event", "distinct_id", "timestamp"]- assert len(s3_objects["Contents"]) != 0- assert key == saved_query.normalized_name- assert sorted(table.to_pylist(), key=lambda d: (d["distinct_id"], d["timestamp"])) == expected_events-- # Ensure we can query the table- await sync_to_async(execute_hogql_query)(f"SELECT * FROM {saved_query.name}", ateam)---async def test_materialize_model_timestamps(ateam, bucket_name, minio_client, pageview_events):- query = """\- select toDateTime64(toDateTime('2025-01-01T00:00:00.000'), 3, 'Asia/Istanbul') as now_converted, toDateTime('2025-01-01T00:00:00.000') as now- """- saved_query = await DataWarehouseSavedQuery.objects.acreate(- team=ateam,- name="my_model",- query={"query": query, "kind": "HogQLQuery"},- )- with override_settings(- BUCKET_URL=f"s3://{bucket_name}",- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",- ):- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- status=DataModelingJob.Status.RUNNING,- workflow_id="test_workflow",- )-- _, delta_table, _ = await materialize_model(- saved_query.id.hex,- ateam,- saved_query,- job,- unittest.mock.AsyncMock(),- )-- table = delta_table.to_pyarrow_table(columns=["now_converted", "now"])- assert table.num_rows == 1- assert table.num_columns == 2- assert table.column_names == ["now_converted", "now"]- assert table.column(0).type == pa.timestamp("us", tz="UTC")- assert table.column(1).type == pa.timestamp("us", tz="UTC")-- # replace microsecond because they won't match exactly- row = table.to_pylist()[0]- now_converted = row["now_converted"]- now = row["now"]- assert now_converted == now---async def test_materialize_model_nullable_nothing_column(ateam, bucket_name, minio_client, pageview_events):- query = """\- select NULL as nullable_nothing_column, toTypeName(nullable_nothing_column) as nullable_nothing_column_type- """- saved_query = await DataWarehouseSavedQuery.objects.acreate(- team=ateam,- name="my_model",- query={"query": query, "kind": "HogQLQuery"},- )- with override_settings(- BUCKET_URL=f"s3://{bucket_name}",- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",- ):- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- status=DataModelingJob.Status.RUNNING,- workflow_id="test_workflow",- )-- _, delta_table, _ = await materialize_model(- saved_query.id.hex,- ateam,- saved_query,- job,- unittest.mock.AsyncMock(),- )-- table = delta_table.to_pyarrow_table(columns=["nullable_nothing_column", "nullable_nothing_column_type"])- assert table.num_rows == 1- assert table.num_columns == 2- assert table.column_names == ["nullable_nothing_column", "nullable_nothing_column_type"]- assert table.column(0).type == pa.string() # Mapped to a string even though it was null---async def test_materialize_model_with_pascal_cased_name(ateam, bucket_name, minio_client, pageview_events):- query = """\- select- event as event,- if(distinct_id != '0', distinct_id, null) as distinct_id,- timestamp as timestamp- from events- where event = '$pageview'- """- saved_query = await DataWarehouseSavedQuery.objects.acreate(- team=ateam,- name="PascalCasedView",- query={"query": query, "kind": "HogQLQuery"},- )-- with override_settings(- BUCKET_URL=f"s3://{bucket_name}",- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",- ):- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- status=DataModelingJob.Status.RUNNING,- workflow_id="test_workflow",- )-- key, delta_table, job_id = await materialize_model(- saved_query.id.hex,- ateam,- saved_query,- job,- unittest.mock.AsyncMock(),- )-- s3_objects = await minio_client.list_objects_v2(- Bucket=bucket_name, Prefix=f"team_{ateam.pk}_model_{saved_query.id.hex}/"- )- table = delta_table.to_pyarrow_table(columns=["event", "distinct_id", "timestamp"])- events, _ = pageview_events- expected_events = sorted(- [- {- k: dt.datetime.fromisoformat(v).replace(tzinfo=dt.UTC) if k == "timestamp" else v- for k, v in event.items()- if k in ("event", "distinct_id", "timestamp")- }- for event in events- ],- key=lambda d: (d["distinct_id"], d["timestamp"]),- )-- query_folder_pattern = re.compile(r"^.+?\_\_query\_\d+_[0-9a-f]{8}\/.+")-- assert any(query_folder_pattern.match(obj["Key"]) for obj in s3_objects["Contents"])- assert any(f"{saved_query.normalized_name}__query" in obj["Key"] for obj in s3_objects["Contents"])- assert table.num_rows == len(expected_events)- assert table.num_columns == 3- assert table.column_names == ["event", "distinct_id", "timestamp"]- assert len(s3_objects["Contents"]) != 0- assert key == saved_query.normalized_name- assert sorted(table.to_pylist(), key=lambda d: (d["distinct_id"], d["timestamp"])) == expected_events-- # Ensure we can query the table- await sync_to_async(execute_hogql_query)(f"SELECT * FROM {saved_query.name}", ateam)---@pytest_asyncio.fixture-async def saved_queries(ateam):- parent_query = """\- select- events.event as event,- events.distinct_id as distinct_id,- events.timestamp as timestamp- from events- where events.event = '$pageview'- """- parent_saved_query = DataWarehouseSavedQuery(- team=ateam,- name="my_model",- query={"query": parent_query, "kind": "HogQLQuery"},- )- parent_saved_query.columns = await sync_to_async(parent_saved_query.get_columns)()- await parent_saved_query.asave()-- child_saved_query = DataWarehouseSavedQuery(- team=ateam,- name="my_model_child",- query={"query": "select * from my_model where distinct_id = 'b'", "kind": "HogQLQuery"},- )- child_saved_query.columns = await sync_to_async(child_saved_query.get_columns)()- await child_saved_query.asave()-- child_2_saved_query = DataWarehouseSavedQuery(- team=ateam,- name="my_model_child_2",- query={"query": "select * from my_model where distinct_id = 'a'", "kind": "HogQLQuery"},- )- child_2_saved_query.columns = await sync_to_async(child_2_saved_query.get_columns)()- await child_2_saved_query.asave()-- grand_child_saved_query = DataWarehouseSavedQuery(- team=ateam,- name="my_model_grand_child",- query={"query": "select * from my_model_child union all select * from my_model_child_2", "kind": "HogQLQuery"},- )- grand_child_saved_query.columns = await sync_to_async(grand_child_saved_query.get_columns)()- await grand_child_saved_query.asave()-- await database_sync_to_async(DataWarehouseModelPath.objects.create_from_saved_query)(parent_saved_query)- await database_sync_to_async(DataWarehouseModelPath.objects.create_from_saved_query)(child_saved_query)- await database_sync_to_async(DataWarehouseModelPath.objects.create_from_saved_query)(child_2_saved_query)- await database_sync_to_async(DataWarehouseModelPath.objects.create_from_saved_query)(grand_child_saved_query)-- yield parent_saved_query, child_saved_query, child_2_saved_query, grand_child_saved_query---async def test_build_dag_activity_select_all_ancestors(activity_environment, ateam, saved_queries):- """Test the build dag activity with a sample set of models.-- In this test we attempt to select all ancestors of a model using a single '+' prefix.- """- parent_saved_query, child_saved_query, _, grand_child_saved_query = saved_queries-- select = [Selector(label=child_saved_query.id.hex, ancestors="ALL")]- inputs = BuildDagActivityInputs(team_id=ateam.pk, select=select)-- async with asyncio.timeout(10):- dag = await activity_environment.run(build_dag_activity, inputs)-- assert dag[parent_saved_query.id.hex].children == {child_saved_query.id.hex}- assert dag[parent_saved_query.id.hex].selected is True-- assert dag[child_saved_query.id.hex].parents == {parent_saved_query.id.hex}- assert dag[child_saved_query.id.hex].children == {grand_child_saved_query.id.hex}- assert dag[child_saved_query.id.hex].selected is True-- selected = (- child_saved_query.id.hex,- parent_saved_query.id.hex,- )- assert all(dag[other].selected is False for other in dag.keys() if other not in selected)---async def test_build_dag_activity_select_all_descendants(activity_environment, ateam, saved_queries):- """Test the build dag activity with a sample set of models.-- In this test we attempt to select all descendants of a model using a single '+' suffix.- """- parent_saved_query, child_saved_query, child_2_saved_query, grand_child_saved_query = saved_queries-- select = [Selector(label=parent_saved_query.id.hex, descendants="ALL")]- inputs = BuildDagActivityInputs(team_id=ateam.pk, select=select)-- async with asyncio.timeout(10):- dag = await activity_environment.run(build_dag_activity, inputs)-- assert dag[parent_saved_query.id.hex].children == {child_saved_query.id.hex, child_2_saved_query.id.hex}- assert dag[parent_saved_query.id.hex].selected is True-- assert dag[child_saved_query.id.hex].parents == {parent_saved_query.id.hex}- assert dag[child_saved_query.id.hex].children == {grand_child_saved_query.id.hex}- assert dag[child_saved_query.id.hex].selected is True-- assert dag[child_2_saved_query.id.hex].parents == {parent_saved_query.id.hex}- assert dag[child_2_saved_query.id.hex].children == {grand_child_saved_query.id.hex}- assert dag[child_2_saved_query.id.hex].selected is True-- assert dag[grand_child_saved_query.id.hex].parents == {child_saved_query.id.hex, child_2_saved_query.id.hex}- assert not dag[grand_child_saved_query.id.hex].children- assert dag[grand_child_saved_query.id.hex].selected is True-- selected = (- grand_child_saved_query.id.hex,- child_2_saved_query.id.hex,- child_saved_query.id.hex,- parent_saved_query.id.hex,- )- assert all(dag[other].selected is False for other in dag.keys() if other not in selected)---async def test_build_dag_activity_select_multiple_individual_models(activity_environment, ateam, saved_queries):- """Test the build dag activity with a sample set of models.-- In this test we select multiple individual models to assert that:- * All selected models are marked as selected to run.- * Additional models are included to account for paths connecting models.- * These additional models are not marked as selected.- """- parent_saved_query, child_saved_query, child_2_saved_query, _ = saved_queries-- select = [- Selector(label=parent_saved_query.id.hex),- Selector(label=child_saved_query.id.hex),- Selector(label=child_2_saved_query.id.hex),- ]- inputs = BuildDagActivityInputs(team_id=ateam.pk, select=select)-- async with asyncio.timeout(10):- dag = await activity_environment.run(build_dag_activity, inputs)-- assert len(dag) == 5- assert dag[parent_saved_query.id.hex].children == {child_saved_query.id.hex, child_2_saved_query.id.hex}-- assert dag[child_saved_query.id.hex].parents == {parent_saved_query.id.hex}- assert dag[child_2_saved_query.id.hex].parents == {parent_saved_query.id.hex}-- selected = tuple(selected.label for selected in select)- assert all(dag[selected].selected is True for selected in selected)- assert all(dag[other].selected is False for other in dag.keys() if other not in selected)---async def test_build_dag_activity_select_first_parents(activity_environment, ateam, saved_queries):- """Test the build dag activity with a sample set of models.-- In this test we attempt to select first parents of a model using a '1+' prefix.- """- _, child_saved_query, child_2_saved_query, grand_child_saved_query = saved_queries-- select = [Selector(label=grand_child_saved_query.id.hex, ancestors=1)]- inputs = BuildDagActivityInputs(team_id=ateam.pk, select=select)-- async with asyncio.timeout(10):- dag = await activity_environment.run(build_dag_activity, inputs)-- assert dag[child_2_saved_query.id.hex].children == {grand_child_saved_query.id.hex}- assert dag[child_saved_query.id.hex].children == {grand_child_saved_query.id.hex}- assert dag[grand_child_saved_query.id.hex].parents == {child_2_saved_query.id.hex, child_saved_query.id.hex}-- selected = (- child_saved_query.id.hex,- child_2_saved_query.id.hex,- grand_child_saved_query.id.hex,- )- assert all(dag[selected].selected is True for selected in selected)- assert all(dag[other].selected is False for other in dag.keys() if other not in selected)---async def test_build_dag_activity_select_first_children(activity_environment, ateam, saved_queries):- """Test the build dag activity with a sample set of models.-- In this test we attempt to select first children of a model using a '+1' suffix.- """- parent_saved_query, child_saved_query, child_2_saved_query, _ = saved_queries-- select = [Selector(label=parent_saved_query.id.hex, descendants=1)]- inputs = BuildDagActivityInputs(team_id=ateam.pk, select=select)-- async with asyncio.timeout(10):- dag = await activity_environment.run(build_dag_activity, inputs)-- assert dag[child_2_saved_query.id.hex].parents == {parent_saved_query.id.hex}- assert dag[child_saved_query.id.hex].parents == {parent_saved_query.id.hex}- assert dag[parent_saved_query.id.hex].children == {child_2_saved_query.id.hex, child_saved_query.id.hex}-- selected = (- child_saved_query.id.hex,- child_2_saved_query.id.hex,- parent_saved_query.id.hex,- )- assert all(dag[selected].selected is True for selected in selected)- assert all(dag[other].selected is False for other in dag.keys() if other not in selected)---async def test_build_dag_activity_select_first_family(activity_environment, ateam, saved_queries):- """Test the build dag activity with a sample set of models.-- In this test we attempt to select first children and first parents of a model using a- both a'+1' suffix and a '1+' prefix.- """- parent_saved_query, child_saved_query, _, grand_child_saved_query = saved_queries-- select = [Selector(label=child_saved_query.id.hex, descendants=1, ancestors=1)]- inputs = BuildDagActivityInputs(team_id=ateam.pk, select=select)-- async with asyncio.timeout(10):- dag = await activity_environment.run(build_dag_activity, inputs)-- assert dag[child_saved_query.id.hex].parents == {parent_saved_query.id.hex}- assert dag[grand_child_saved_query.id.hex].parents == {child_saved_query.id.hex}- assert dag[parent_saved_query.id.hex].children == {child_saved_query.id.hex}-- selected = (- child_saved_query.id.hex,- parent_saved_query.id.hex,- grand_child_saved_query.id.hex,- )- assert all(dag[selected].selected is True for selected in selected)- assert all(dag[other].selected is False for other in dag.keys() if other not in selected)---async def test_build_dag_activity_select_all(activity_environment, ateam, saved_queries):- """Test the build dag activity with a sample set of models.-- In this test we attempt to select all models by not passing any selectors.- """- parent_saved_query, child_saved_query, child_2_saved_query, grand_child_saved_query = saved_queries-- inputs = BuildDagActivityInputs(team_id=ateam.pk)-- async with asyncio.timeout(10):- dag = await activity_environment.run(build_dag_activity, inputs)-- assert dag[child_saved_query.id.hex].parents == {parent_saved_query.id.hex}- assert dag[child_saved_query.id.hex].children == {grand_child_saved_query.id.hex}- assert dag[child_2_saved_query.id.hex].parents == {parent_saved_query.id.hex}- assert dag[child_2_saved_query.id.hex].children == {grand_child_saved_query.id.hex}- assert dag[grand_child_saved_query.id.hex].parents == {child_saved_query.id.hex, child_2_saved_query.id.hex}- assert dag[parent_saved_query.id.hex].children == {child_saved_query.id.hex, child_2_saved_query.id.hex}-- assert all(dag[selected].selected is True for selected in dag.keys() if selected not in {"events", "persons"})---async def test_run_workflow_with_minio_bucket(- minio_client,- ateam,- bucket_name,- pageview_events,- saved_queries,- temporal_client,- test_time,-):- """Test run workflow end-to-end using a local MinIO bucket."""- events, _ = pageview_events- all_expected_events = sorted(- [- {- k: dt.datetime.fromisoformat(v).replace(tzinfo=dt.UTC) if k == "timestamp" else v- for k, v in event.items()- if k in ("event", "distinct_id", "timestamp")- }- for event in events- ],- key=lambda d: (d["distinct_id"], d["timestamp"]),- )- expected_events_a = [event for event in all_expected_events if event["distinct_id"] == "a"]- expected_events_b = [event for event in all_expected_events if event["distinct_id"] == "b"]-- with (- override_settings(- BUCKET_URL=f"s3://{bucket_name}",- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",- ),- freeze_time(test_time),- ):- async with temporalio.worker.Worker(- temporal_client,- task_queue=settings.DATA_MODELING_TASK_QUEUE,- workflows=[RunWorkflow],- activities=[- start_run_activity,- build_dag_activity,- run_dag_activity,- finish_run_activity,- create_job_model_activity,- fail_jobs_activity,- cleanup_running_jobs_activity,- ],- workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),- ):- # Ensure the team exists in the DB context before running workflow- await database_sync_to_async(Team.objects.get)(pk=ateam.pk)-- for saved_query in saved_queries:- workflow_id = str(uuid.uuid4())- inputs = RunWorkflowInputs(- team_id=ateam.pk,- select=[Selector(label=saved_query.id.hex, ancestors=0, descendants=0)],- )- await temporal_client.execute_workflow(- RunWorkflow.run,- inputs,- id=workflow_id,- task_queue=settings.DATA_MODELING_TASK_QUEUE,- retry_policy=temporalio.common.RetryPolicy(maximum_attempts=1),- execution_timeout=dt.timedelta(seconds=30),- )-- tables_and_queries = {}-- for query in saved_queries:- await database_sync_to_async(query.refresh_from_db)()-- delta_table = deltalake.DeltaTable(- table_uri=f"s3://{bucket_name}/team_{ateam.pk}_model_{query.id.hex}/modeling/{query.normalized_name}",- storage_options={- "aws_access_key_id": str(settings.DATAWAREHOUSE_LOCAL_ACCESS_KEY),- "aws_secret_access_key": str(settings.DATAWAREHOUSE_LOCAL_ACCESS_SECRET),- "endpoint_url": settings.OBJECT_STORAGE_ENDPOINT,- "region_name": str(settings.DATAWAREHOUSE_LOCAL_BUCKET_REGION),- "AWS_ALLOW_HTTP": "true",- "AWS_S3_ALLOW_UNSAFE_RENAME": "true",- },- )-- # All test tables have the same columns, which is a limitation of our test- table = delta_table.to_pyarrow_table(columns=["event", "distinct_id", "timestamp"])- tables_and_queries[query.normalized_name] = (table, query)-- for key, table_and_query in tables_and_queries.items():- table, query = table_and_query-- if "distinct_id = 'a'" in query.query["query"]:- expected_data = expected_events_a- elif "distinct_id = 'b'" in query.query["query"]:- expected_data = expected_events_b- else:- expected_data = all_expected_events-- assert table.num_rows == len(expected_data)- assert table.num_columns == 3- assert table.column_names == ["event", "distinct_id", "timestamp"]- assert key == query.normalized_name-- sorted_rows = sorted(table.to_pylist(), key=lambda d: (d["distinct_id"], d["timestamp"]))- for index, row in enumerate(sorted_rows):- # Hack:- # There's some drift in microseconds of the datetimes, the pyarrow- # tabls is rounding the microseconds to the nearest 100,000- row["timestamp"] = row["timestamp"].replace(microsecond=0)- expected_data[index]["timestamp"] = expected_data[index]["timestamp"].replace(microsecond=0)- assert row == expected_data[index]-- assert query.status == DataWarehouseSavedQuery.Status.COMPLETED- assert query.last_run_at == test_time- assert query.is_materialized is True-- # Verify row count was updated in the DataWarehouseTable- warehouse_table = await DataWarehouseTable.objects.aget(team_id=ateam.pk, id=query.table_id)- assert warehouse_table is not None, f"DataWarehouseTable for {query.name} not found"- # Match the 50 page_view events defined above- assert warehouse_table.row_count == len(expected_data), (- f"Row count for {query.name} not the expected value"- )- assert warehouse_table.size_in_s3_mib is not None and warehouse_table.size_in_s3_mib != 0, (- f"Table size in mib for {query.name} is not set"- )- assert warehouse_table.credential_id is None, "Table has credentials set when it shouldn't"-- job = await DataModelingJob.objects.aget(workflow_id=workflow_id)- assert job.storage_delta_mib is not None and job.storage_delta_mib != 0, f"Job storage delta is not set"---async def test_run_workflow_with_minio_bucket_with_errors(- minio_client,- ateam,- bucket_name,- pageview_events,- saved_queries,- temporal_client,- test_time,-):- workflow_id = str(uuid.uuid4())- inputs = RunWorkflowInputs(- team_id=ateam.pk,- select=[Selector(label=saved_query.id.hex, ancestors=0, descendants=0) for saved_query in saved_queries],- )-- async def mock_materialize_model(model_label, team, saved_query, job):- raise Exception("testing exception")-- with (- override_settings(- BUCKET_URL=f"s3://{bucket_name}",- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",- ),- freeze_time(test_time),- unittest.mock.patch("posthog.temporal.data_modeling.run_workflow.materialize_model", mock_materialize_model),- ):- async with temporalio.worker.Worker(- temporal_client,- task_queue=settings.DATA_MODELING_TASK_QUEUE,- workflows=[RunWorkflow],- activities=[- start_run_activity,- build_dag_activity,- run_dag_activity,- finish_run_activity,- create_job_model_activity,- fail_jobs_activity,- cleanup_running_jobs_activity,- ],- workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),- ):- # Ensure the team exists in the DB context before running workflow- await database_sync_to_async(Team.objects.get)(pk=ateam.pk)- await temporal_client.execute_workflow(- RunWorkflow.run,- inputs,- id=workflow_id,- task_queue=settings.DATA_MODELING_TASK_QUEUE,- retry_policy=temporalio.common.RetryPolicy(maximum_attempts=1),- execution_timeout=dt.timedelta(seconds=30),- )-- job = await DataModelingJob.objects.aget(workflow_id=workflow_id)- assert job is not None- assert job.status == DataModelingJob.Status.FAILED- assert job.rows_materialized == 0---async def test_materialize_model_reverts_materialization_on_unknown_table(ateam):- def mock_hogql_table(_query, _team, _logger):- raise Exception("Unknown table")-- with (- unittest.mock.patch("posthog.temporal.data_modeling.run_workflow.hogql_table", mock_hogql_table),- unittest.mock.patch("posthog.temporal.data_modeling.run_workflow.get_query_row_count", return_value=0),- unittest.mock.patch("posthog.temporal.data_modeling.run_workflow.get_s3_client"),- # Reaches object storage before hogql_table runs, so an unready bucket would land in the- # generic error branch rather than the revert one under test.- unittest.mock.patch("posthog.temporal.data_modeling.run_workflow._get_credentials", return_value={}),- unittest.mock.patch("products.data_modeling.backend.logic.enrich_view_semantics._start_enrichment_workflow"),- unittest.mock.patch(- "products.data_warehouse.backend.logic.data_load.saved_query_service.delete_saved_query_schedule"- ),- ):- saved_query = await DataWarehouseSavedQuery.objects.acreate(- team=ateam,- name="my_model",- query={"query": "select 1 as one", "kind": "HogQLQuery"},- is_materialized=True,- sync_frequency_interval=dt.timedelta(hours=1),- status=DataWarehouseSavedQuery.Status.COMPLETED,- )- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- status=DataModelingJob.Status.RUNNING,- workflow_id=str(uuid.uuid4()),- )-- with pytest.raises(Exception, match="Table reference missing"):- await materialize_model(saved_query.id.hex, ateam, saved_query, job, unittest.mock.AsyncMock())-- await database_sync_to_async(job.refresh_from_db)()- assert job.status == DataModelingJob.Status.FAILED- assert job.rows_materialized == 0-- await database_sync_to_async(saved_query.refresh_from_db)()- assert saved_query.is_materialized is False- assert saved_query.sync_frequency_interval is None- assert saved_query.status is None---async def test_run_workflow_timeout_does_not_pause_schedule_without_consecutive_failures(- minio_client,- ateam,- bucket_name,- pageview_events,- saved_queries,- temporal_client,- test_time,-):- """Timeout should not pause the schedule when there aren't 5 consecutive timeout failures."""- for query in saved_queries:- query.sync_frequency_interval = dt.timedelta(hours=1)- await database_sync_to_async(query.save)()-- workflow_id = str(uuid.uuid4())- inputs = RunWorkflowInputs(team_id=ateam.pk)-- with (- override_settings(- BUCKET_URL=f"s3://{bucket_name}",- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",- ),- freeze_time(test_time),- unittest.mock.patch("posthog.temporal.data_modeling.run_workflow.hogql_table") as mock_hogql_table,- unittest.mock.patch(- "posthog.temporal.data_modeling.run_workflow.a_pause_saved_query_schedule"- ) as mock_pause_saved_query_schedule,- ):- mock_hogql_table.side_effect = Exception(- "Code: 159. DB::Exception: Timeout exceeded: elapsed 600585.167566 ms, maximum: 600000 ms. (TIMEOUT_EXCEEDED) (version 25.8.12.129 (official build))"- )-- async with temporalio.worker.Worker(- temporal_client,- task_queue=settings.DATA_MODELING_TASK_QUEUE,- workflows=[RunWorkflow],- activities=[- start_run_activity,- build_dag_activity,- run_dag_activity,- finish_run_activity,- create_job_model_activity,- fail_jobs_activity,- cleanup_running_jobs_activity,- ],- workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),- ):- await database_sync_to_async(Team.objects.get)(pk=ateam.pk)- await temporal_client.execute_workflow(- RunWorkflow.run,- inputs,- id=workflow_id,- task_queue=settings.DATA_MODELING_TASK_QUEUE,- retry_policy=temporalio.common.RetryPolicy(maximum_attempts=1),- execution_timeout=dt.timedelta(seconds=30),- )-- assert mock_hogql_table.call_count == 1- mock_pause_saved_query_schedule.assert_not_called()-- job = await DataModelingJob.objects.aget(workflow_id=workflow_id)- assert job is not None- assert job.status == DataModelingJob.Status.FAILED- assert job.rows_materialized == 0-- for query in saved_queries:- await database_sync_to_async(query.refresh_from_db)()- assert query.is_materialized is False- assert query.sync_frequency_interval is not None---async def test_run_workflow_timeout_pauses_schedule_after_5_consecutive_failures(- minio_client,- ateam,- bucket_name,- pageview_events,- saved_queries,- temporal_client,- test_time,-):- """Timeout should pause the schedule when there are 5 consecutive timeout failures."""- parent_query = saved_queries[0]-- # The run under test is frozen to test_time, so its own job row is stamped then, while these- # are created at the wall clock that has already passed it. Dating them back makes them the- # history the run counts, rather than rows it is entitled to ignore as newer than itself.- for i in range(5):- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- saved_query=parent_query,- status=DataModelingJob.Status.FAILED,- error="Query exceeded timeout - we limit queries to a 10-minute timeout.",- workflow_id=f"prev-workflow-{i}",- )- await database_sync_to_async(DataModelingJob.objects.filter(id=job.id).update)(- created_at=test_time - dt.timedelta(minutes=5 - i)- )-- workflow_id = str(uuid.uuid4())- inputs = RunWorkflowInputs(team_id=ateam.pk)-- with (- override_settings(- BUCKET_URL=f"s3://{bucket_name}",- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",- ),- freeze_time(test_time),- unittest.mock.patch("posthog.temporal.data_modeling.run_workflow.hogql_table") as mock_hogql_table,- unittest.mock.patch(- "posthog.temporal.data_modeling.run_workflow.a_pause_saved_query_schedule"- ) as mock_pause_saved_query_schedule,- ):- mock_hogql_table.side_effect = Exception(- "Code: 159. DB::Exception: Timeout exceeded: elapsed 600585.167566 ms, maximum: 600000 ms. (TIMEOUT_EXCEEDED) (version 25.8.12.129 (official build))"- )-- async with temporalio.worker.Worker(- temporal_client,- task_queue=settings.DATA_MODELING_TASK_QUEUE,- workflows=[RunWorkflow],- activities=[- start_run_activity,- build_dag_activity,- run_dag_activity,- finish_run_activity,- create_job_model_activity,- fail_jobs_activity,- cleanup_running_jobs_activity,- ],- workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),- ):- await database_sync_to_async(Team.objects.get)(pk=ateam.pk)- await temporal_client.execute_workflow(- RunWorkflow.run,- inputs,- id=workflow_id,- task_queue=settings.DATA_MODELING_TASK_QUEUE,- retry_policy=temporalio.common.RetryPolicy(maximum_attempts=1),- execution_timeout=dt.timedelta(seconds=30),- )-- assert mock_hogql_table.call_count == 1- mock_pause_saved_query_schedule.assert_called()-- job = await DataModelingJob.objects.aget(workflow_id=workflow_id)- assert job is not None- assert job.status == DataModelingJob.Status.FAILED- assert job.rows_materialized == 0-- await database_sync_to_async(parent_query.refresh_from_db)()- assert parent_query.is_materialized is False- assert parent_query.sync_frequency_interval is None---async def test_run_workflow_triggers_ducklake_copy_child(monkeypatch):- model_label = "model-under-test"- ducklake_model = DuckLakeCopyModelInput(- model_label=model_label,- saved_query_id=str(uuid.uuid4()),- table_uri="s3://source/table",- )-- @temporal_activity.defn- async def cleanup_stub(inputs):- return None-- @temporal_activity.defn- async def create_job_stub(inputs):- return "job-child"-- @temporal_activity.defn- async def build_dag_stub(inputs) -> run_workflow_module.DAG:- return {model_label: ModelNode(label=model_label, selected=True)}-- @temporal_activity.defn- async def start_run_stub(inputs):- return None-- @temporal_activity.defn- async def run_dag_stub(inputs):- return run_workflow_module.Results(- completed={model_label},- failed=set(),- ancestor_failed=set(),- ducklake_models=[ducklake_model],- )-- @temporal_activity.defn- async def finish_run_stub(inputs):- return None-- @temporal_activity.defn- async def fail_jobs_stub(inputs):- return None-- monkeypatch.setattr(run_workflow_module, "cleanup_running_jobs_activity", cleanup_stub)- monkeypatch.setattr(run_workflow_module, "create_job_model_activity", create_job_stub)- monkeypatch.setattr(run_workflow_module, "build_dag_activity", build_dag_stub)- monkeypatch.setattr(run_workflow_module, "start_run_activity", start_run_stub)- monkeypatch.setattr(run_workflow_module, "run_dag_activity", run_dag_stub)- monkeypatch.setattr(run_workflow_module, "finish_run_activity", finish_run_stub)- monkeypatch.setattr(run_workflow_module, "fail_jobs_activity", fail_jobs_stub)-- with override_settings(DUCKLAKE_TASK_QUEUE="ducklake-test"):- child_ducklake_workflow_runs.clear()- async with await WorkflowEnvironment.start_time_skipping() as env:- async with temporalio.worker.Worker(- env.client,- task_queue="ducklake-test",- workflows=[RunWorkflow, DummyDuckLakeCopyDataModelingWorkflow],- activities=[- cleanup_stub,- create_job_stub,- build_dag_stub,- start_run_stub,- run_dag_stub,- finish_run_stub,- fail_jobs_stub,- ],- workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),- ):- await env.client.execute_workflow(- RunWorkflow.run,- RunWorkflowInputs(team_id=1),- id=str(uuid.uuid4()),- task_queue="ducklake-test",- execution_timeout=dt.timedelta(seconds=30),- )-- assert len(child_ducklake_workflow_runs) == 1- assert child_ducklake_workflow_runs[0]["team_id"] == 1- assert child_ducklake_workflow_runs[0]["models"][0]["model_label"] == model_label---async def test_dlt_direct_naming(ateam, bucket_name, minio_client, pageview_events):- """Test that setting SCHEMA__NAMING=direct preserves original column casing when materializing models."""- # Query with CamelCase and PascalCase column names, not snake_case- query = """\- select- event as Event,- if(distinct_id != '0', distinct_id, null) as DistinctId,- timestamp as TimeStamp,- 'example' as CamelCaseColumn- from events- where event = '$pageview'- """- saved_query = await DataWarehouseSavedQuery.objects.acreate(- team=ateam,- name="camel_case_model",- query={"query": query, "kind": "HogQLQuery"},- )-- # Make sure we have pageview events for the query to work with- events, _ = pageview_events-- with (- override_settings(- BUCKET_URL=f"s3://{bucket_name}",- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",- ),- unittest.mock.patch.dict(os.environ, {"SCHEMA__NAMING": "direct"}, clear=True),- ):- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- status=DataModelingJob.Status.RUNNING,- workflow_id="test_workflow",- )-- # Check that SCHEMA__NAMING is set to direct in the environment- assert os.environ.get("SCHEMA__NAMING") == "direct", "SCHEMA__NAMING should be 'direct'"-- key, delta_table, job_id = await materialize_model(- saved_query.id.hex,- ateam,- saved_query,- job,- unittest.mock.AsyncMock(),- )-- await database_sync_to_async(saved_query.refresh_from_db)()- assert saved_query.is_materialized is True-- # Check that the column names maintain their original casing- table_columns = delta_table.to_pyarrow_table().column_names- # Verify the original capitalization is preserved- assert "Event" in table_columns, "Column 'Event' should maintain its original capitalization"- assert "DistinctId" in table_columns, "Column 'DistinctId' should maintain its original capitalization"- assert "TimeStamp" in table_columns, "Column 'TimeStamp' should maintain its original capitalization"- assert "CamelCaseColumn" in table_columns, "Column 'CamelCaseColumn' should maintain its original capitalization"---async def test_materialize_model_with_decimal256_fix(ateam, bucket_name, minio_client):- """Test that materialize_model successfully transforms Decimal256 types to float since decimal128 is not precise enough."""- query = "SELECT 1 as test_column FROM events LIMIT 1"- saved_query = await DataWarehouseSavedQuery.objects.acreate(- team=ateam,- name="decimal_fix_test_model",- query={"query": query, "kind": "HogQLQuery"},- )-- def mock_hogql_table(*args, **kwargs):- from decimal import Decimal-- high_precision_decimal_type = pa.decimal256(76, 32)- problematic_data = pa.array(- [Decimal("12345678901234567890123456789012345678901234.12345678901234567890123456789012")],- type=high_precision_decimal_type,- )-- batch1 = pa.RecordBatch.from_arrays(- cast(list[pa.Array], [problematic_data, pa.array([1], type=pa.int64())]),- names=["high_precision_decimal", "regular_column"],- )-- async def async_generator():- yield batch1, [("high_precision_decimal", "Decimal(76, 32)"), ("regular_column", "Int64")]-- return async_generator()-- with (- override_settings(- BUCKET_URL=f"s3://{bucket_name}",- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",- ),- unittest.mock.patch("posthog.temporal.data_modeling.run_workflow.hogql_table", mock_hogql_table),- ):- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- status=DataModelingJob.Status.RUNNING,- workflow_id="test_workflow",- )-- key, delta_table, job_id = await materialize_model(- saved_query.id.hex,- ateam,- saved_query,- job,- unittest.mock.AsyncMock(),- )-- assert key == saved_query.normalized_name-- table = delta_table.to_pyarrow_table()- assert table.num_rows == 1- assert "high_precision_decimal" in table.column_names- assert "regular_column" in table.column_names-- high_precision_column = table.column("high_precision_decimal")- # Should be Decimal128 with reduced precision, not float64- assert pa.types.is_decimal(high_precision_column.type)- assert isinstance(high_precision_column.type, pa.Decimal128Type)- assert high_precision_column.type.precision == 38- assert high_precision_column.type.scale == 37-- await database_sync_to_async(job.refresh_from_db)()- assert job.status == DataModelingJob.Status.COMPLETED-- await database_sync_to_async(saved_query.refresh_from_db)()- assert saved_query.is_materialized is True---async def test_materialize_model_with_decimal256_downscale_to_decimal128(ateam, bucket_name, minio_client):- """Test that materialize_model successfully downscales Decimal256 to Decimal128 when the value fits."""- query = "SELECT 1 as test_column FROM events LIMIT 1"- saved_query = await DataWarehouseSavedQuery.objects.acreate(- team=ateam,- name="decimal_downscale_test_model",- query={"query": query, "kind": "HogQLQuery"},- )-- def mock_hogql_table(*args, **kwargs):- from decimal import Decimal-- high_precision_decimal_type = pa.decimal256(50, 10)- manageable_data = pa.array(- [Decimal("1234567890123456789012345678.1234567890")],- type=high_precision_decimal_type,- )-- batch1 = pa.RecordBatch.from_arrays(- cast(list[pa.Array], [manageable_data, pa.array([1], type=pa.int64())]),- names=["manageable_decimal", "regular_column"],- )-- async def async_generator():- yield batch1, [("manageable_decimal", "Decimal(50, 10)"), ("regular_column", "Int64")]-- return async_generator()-- with (- override_settings(- BUCKET_URL=f"s3://{bucket_name}",- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",- ),- unittest.mock.patch("posthog.temporal.data_modeling.run_workflow.hogql_table", mock_hogql_table),- ):- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- status=DataModelingJob.Status.RUNNING,- workflow_id="test_workflow",- )-- key, delta_table, job_id = await materialize_model(- saved_query.id.hex,- ateam,- saved_query,- job,- unittest.mock.AsyncMock(),- )-- assert key == saved_query.normalized_name-- table = delta_table.to_pyarrow_table()- assert table.num_rows == 1- assert "manageable_decimal" in table.column_names- assert "regular_column" in table.column_names-- manageable_decimal_column = table.column("manageable_decimal")- # Should be Decimal128, not float64- assert pa.types.is_decimal(manageable_decimal_column.type)- assert isinstance(manageable_decimal_column.type, pa.Decimal128Type)- assert manageable_decimal_column.type.precision == 38- assert manageable_decimal_column.type.scale == 10-- await database_sync_to_async(job.refresh_from_db)()- assert job.status == DataModelingJob.Status.COMPLETED-- await database_sync_to_async(saved_query.refresh_from_db)()- assert saved_query.is_materialized is True--- "saved_query_ids_fn, expected_a, expected_b",- [- pytest.param(- lambda sq_a, sq_b: [sq_a.id.hex],- DataModelingJob.Status.FAILED,- DataModelingJob.Status.RUNNING,- id="uuid_hex",- ),- pytest.param(- lambda sq_a, sq_b: [sq_a.name],- DataModelingJob.Status.FAILED,- DataModelingJob.Status.RUNNING,- id="name_label",- ),- pytest.param(- lambda sq_a, sq_b: [], DataModelingJob.Status.FAILED, DataModelingJob.Status.FAILED, id="team_wide_fallback"- ),- ],-)-async def test_cleanup_running_jobs_activity(activity_environment, ateam, saved_query_ids_fn, expected_a, expected_b):- sq_a = await database_sync_to_async(DataWarehouseSavedQuery.objects.create)(- team=ateam, name="query_a", query={"query": "SELECT 1", "kind": "HogQLQuery"}- )- sq_b = await database_sync_to_async(DataWarehouseSavedQuery.objects.create)(- team=ateam, name="query_b", query={"query": "SELECT 2", "kind": "HogQLQuery"}- )- job_a = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam, saved_query=sq_a, status=DataModelingJob.Status.RUNNING, workflow_id="wf-a", workflow_run_id="run-a"- )- completed_job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- saved_query=sq_a,- status=DataModelingJob.Status.COMPLETED,- workflow_id="wf-c",- workflow_run_id="run-c",- )- job_b = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam, saved_query=sq_b, status=DataModelingJob.Status.RUNNING, workflow_id="wf-b", workflow_run_id="run-b"- )-- saved_query_ids = saved_query_ids_fn(sq_a, sq_b)- inputs = CleanupRunningJobsActivityInputs(team_id=ateam.pk)- if saved_query_ids:- inputs.saved_query_ids = saved_query_ids- await activity_environment.run(cleanup_running_jobs_activity, inputs)-- await database_sync_to_async(job_a.refresh_from_db)()- await database_sync_to_async(completed_job.refresh_from_db)()- await database_sync_to_async(job_b.refresh_from_db)()-- assert job_a.status == expected_a- assert job_a.error is not None if expected_a == DataModelingJob.Status.FAILED else job_a.error is None- assert completed_job.status == DataModelingJob.Status.COMPLETED- assert job_b.status == expected_b---async def test_create_job_model_activity_cleans_up_running_jobs(activity_environment, ateam, temporal_client):- """Test that orphaned jobs are cleaned up when running the full workflow."""- saved_query = await database_sync_to_async(DataWarehouseSavedQuery.objects.create)(- team=ateam, name="test_query", query={"query": "SELECT * FROM events LIMIT 10", "kind": "HogQLQuery"}- )-- # Create old orphaned job for the same saved query- orphaned_job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- saved_query=saved_query,- status=DataModelingJob.Status.RUNNING,- workflow_id="orphaned-1",- workflow_run_id="run-1",- )- await database_sync_to_async(DataModelingJob.objects.filter(id=orphaned_job.id).update)(- updated_at=dt.datetime.now(dt.UTC) - dt.timedelta(hours=2)- )-- await activity_environment.run(- cleanup_running_jobs_activity,- CleanupRunningJobsActivityInputs(team_id=ateam.pk, saved_query_ids=[saved_query.id.hex]),- )-- await database_sync_to_async(orphaned_job.refresh_from_db)()- assert orphaned_job.status == DataModelingJob.Status.FAILED- assert orphaned_job.rows_materialized == 0- assert orphaned_job.error is not None- assert "Preempted" in orphaned_job.error-- with unittest.mock.patch("temporalio.activity.info") as mock_info:- mock_info.return_value.workflow_id = "new-workflow"- mock_info.return_value.workflow_run_id = "new-run"-- new_job_id = await activity_environment.run(- create_job_model_activity,- CreateJobModelInputs(- team_id=ateam.pk, select=[Selector(label=saved_query.id.hex, ancestors=0, descendants=0)]- ),- )-- new_job = await database_sync_to_async(DataModelingJob.objects.get)(id=new_job_id)- assert new_job.status == DataModelingJob.Status.RUNNING- assert new_job.workflow_id == "new-workflow"- assert new_job.workflow_run_id == "new-run"---async def test_materialize_model_progress_tracking(ateam, bucket_name, minio_client):- """Test that materialize_model tracks progress during S3 writes."""- query = "SELECT 1 as test_column FROM events LIMIT 1"- saved_query = await DataWarehouseSavedQuery.objects.acreate(- team=ateam,- name="progress_tracking_test_model",- query={"query": query, "kind": "HogQLQuery"},- )-- def mock_hogql_table(*args, **kwargs):- # Create multiple batches to test progress tracking- batch1 = pa.RecordBatch.from_arrays([pa.array([1, 2, 3], type=pa.int64())], names=["test_column"])- batch2 = pa.RecordBatch.from_arrays([pa.array([4, 5], type=pa.int64())], names=["test_column"])- batch3 = pa.RecordBatch.from_arrays([pa.array([6], type=pa.int64())], names=["test_column"])-- async def async_generator():- yield batch1, [("test_column", "Int64")]- yield batch2, [("test_column", "Int64")]- yield batch3, [("test_column", "Int64")]-- return async_generator()-- with (- override_settings(- BUCKET_URL=f"s3://{bucket_name}",- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",- ),- unittest.mock.patch("posthog.temporal.data_modeling.run_workflow.hogql_table", mock_hogql_table),- unittest.mock.patch("posthog.temporal.data_modeling.run_workflow.get_query_row_count", return_value=6),- ):- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- status=DataModelingJob.Status.RUNNING,- workflow_id="test_workflow",- )-- # Verify initial state- assert job.rows_materialized == 0-- key, delta_table, job_id = await materialize_model(- saved_query.id.hex,- ateam,- saved_query,- job,- unittest.mock.AsyncMock(),- )-- # Verify final state- await database_sync_to_async(job.refresh_from_db)()- assert job.status == DataModelingJob.Status.COMPLETED- assert job.rows_materialized == 6- assert job.rows_expected == 6---async def test_materialize_model_with_non_utc_timestamp(ateam, bucket_name, minio_client, truncate_events_table):- await sync_to_async(bulk_create_events)(- [{"event": "user signed up", "distinct_id": "1", "team": ateam, "timestamp": "2022-01-01T12:00:00"}]- )-- query = "SELECT toTimeZone(timestamp, 'US/Samoa') as timestamp FROM events LIMIT 1"- saved_query = await DataWarehouseSavedQuery.objects.acreate(- team=ateam,- name="timezone_fix_test_model",- query={"query": query, "kind": "HogQLQuery"},- )-- with override_settings(- BUCKET_URL=f"s3://{bucket_name}",- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",- ):- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- status=DataModelingJob.Status.RUNNING,- workflow_id="test_workflow",- )-- key, delta_table, job_id = await materialize_model(- saved_query.id.hex,- ateam,- saved_query,- job,- unittest.mock.AsyncMock(),- )-- assert key == saved_query.normalized_name-- table = delta_table.to_pyarrow_table()- assert table.num_rows == 1- assert "timestamp" in table.column_names-- timestamp_column = table.column("timestamp")- assert pa.types.is_timestamp(timestamp_column.type)-- assert timestamp_column[0].as_py() == dt.datetime(2022, 1, 1, 12, 0, tzinfo=dt.UTC)-- await database_sync_to_async(job.refresh_from_db)()- assert job.status == DataModelingJob.Status.COMPLETED---async def test_materialize_model_with_utc_timestamp(ateam, bucket_name, minio_client, truncate_events_table):- await sync_to_async(bulk_create_events)(- [{"event": "user signed up", "distinct_id": "1", "team": ateam, "timestamp": "2022-01-01T00:00:00"}]- )-- query = "SELECT toTimeZone(timestamp, 'UTC') as timestamp FROM events LIMIT 1"- saved_query = await DataWarehouseSavedQuery.objects.acreate(- team=ateam,- name="timezone_fix_test_model",- query={"query": query, "kind": "HogQLQuery"},- )-- with override_settings(- BUCKET_URL=f"s3://{bucket_name}",- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",- ):- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- status=DataModelingJob.Status.RUNNING,- workflow_id="test_workflow",- )-- key, delta_table, job_id = await materialize_model(- saved_query.id.hex,- ateam,- saved_query,- job,- unittest.mock.AsyncMock(),- )-- assert key == saved_query.normalized_name-- table = delta_table.to_pyarrow_table()- assert table.num_rows == 1- assert "timestamp" in table.column_names-- timestamp_column = table.column("timestamp")- assert pa.types.is_timestamp(timestamp_column.type)-- assert timestamp_column[0].as_py() == dt.datetime(2022, 1, 1, 0, 0, tzinfo=dt.UTC)-- await database_sync_to_async(job.refresh_from_db)()- assert job.status == DataModelingJob.Status.COMPLETED---async def test_materialize_model_with_date(ateam, bucket_name, minio_client, truncate_events_table):- await sync_to_async(bulk_create_events)(- [{"event": "user signed up", "distinct_id": "1", "team": ateam, "timestamp": "2022-01-01T12:00:00"}]- )-- query = "SELECT toStartOfMonth(timestamp) as timestamp FROM events LIMIT 1"- saved_query = await DataWarehouseSavedQuery.objects.acreate(- team=ateam,- name="timezone_fix_test_model",- query={"query": query, "kind": "HogQLQuery"},- )-- with override_settings(- BUCKET_URL=f"s3://{bucket_name}",- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",- ):- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- status=DataModelingJob.Status.RUNNING,- workflow_id="test_workflow",- )-- key, delta_table, job_id = await materialize_model(- saved_query.id.hex,- ateam,- saved_query,- job,- unittest.mock.AsyncMock(),- )-- assert key == saved_query.normalized_name-- table = delta_table.to_pyarrow_table()- assert table.num_rows == 1- assert "timestamp" in table.column_names-- timestamp_column = table.column("timestamp")- assert pa.types.is_date(timestamp_column.type)-- assert timestamp_column[0].as_py() == dt.date(2022, 1, 1)-- await database_sync_to_async(job.refresh_from_db)()- assert job.status == DataModelingJob.Status.COMPLETED---async def test_materialize_model_with_plain_datetime(ateam, bucket_name, minio_client, truncate_events_table):- await sync_to_async(bulk_create_events)(- [{"event": "user signed up", "distinct_id": "1", "team": ateam, "timestamp": "2022-01-01T12:00:00"}]- )-- query = "SELECT toDateTime(timestamp) as timestamp FROM events LIMIT 1"- saved_query = await DataWarehouseSavedQuery.objects.acreate(- team=ateam,- name="timezone_fix_test_model",- query={"query": query, "kind": "HogQLQuery"},- )-- with override_settings(- BUCKET_URL=f"s3://{bucket_name}",- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",- ):- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- status=DataModelingJob.Status.RUNNING,- workflow_id="test_workflow",- )-- key, delta_table, _ = await materialize_model(- saved_query.id.hex,- ateam,- saved_query,- job,- unittest.mock.AsyncMock(),- )-- assert key == saved_query.normalized_name- assert delta_table is not None-- table = delta_table.to_pyarrow_table()- assert table.num_rows == 1- assert "timestamp" in table.column_names-- timestamp_column = table.column("timestamp")- assert pa.types.is_timestamp(timestamp_column.type)-- assert timestamp_column[0].as_py() == dt.datetime(2022, 1, 1, 12, 0, tzinfo=dt.UTC)-- await database_sync_to_async(job.refresh_from_db)()- assert job.status == DataModelingJob.Status.COMPLETED---async def test_materialize_model_empty_results(ateam, bucket_name, minio_client):- """Test that materialize_model raises NonRetryableException when query returns no results."""- query = "SELECT 1 WHERE 1 = 0"- saved_query = await DataWarehouseSavedQuery.objects.acreate(- team=ateam,- name="empty_results_test_model",- query={"query": query, "kind": "HogQLQuery"},- )-- async def mock_hogql_table(*args, **kwargs):- return- yield # makes this a generator but nothing is ever yielded because of the return-- with (- override_settings(- BUCKET_URL=f"s3://{bucket_name}",- DATAWAREHOUSE_LOCAL_ACCESS_KEY=settings.OBJECT_STORAGE_ACCESS_KEY_ID,- DATAWAREHOUSE_LOCAL_ACCESS_SECRET=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,- DATAWAREHOUSE_LOCAL_BUCKET_REGION="us-east-1",- DATAWAREHOUSE_BUCKET_DOMAIN="objectstorage:19000",- ),- unittest.mock.patch("posthog.temporal.data_modeling.run_workflow.hogql_table", mock_hogql_table),- unittest.mock.patch("posthog.temporal.data_modeling.run_workflow.get_query_row_count", return_value=0),- unittest.mock.patch("posthog.temporal.data_modeling.run_workflow.a_pause_saved_query_schedule"),- ):- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- status=DataModelingJob.Status.RUNNING,- workflow_id="test_workflow",- )-- await materialize_model(- saved_query.id.hex,- ateam,- saved_query,- job,- unittest.mock.AsyncMock(),- )-- await database_sync_to_async(job.refresh_from_db)()- assert job.status == DataModelingJob.Status.COMPLETED- assert job.error is not None- assert "returned no results" in job.error---child_ducklake_workflow_runs: list[dict] = []---@temporal_workflow.defn(name="ducklake-copy.data-modeling")-class DummyDuckLakeCopyDataModelingWorkflow:- @temporal_workflow.run- async def run(self, inputs: dict) -> None:- child_ducklake_workflow_runs.append(inputs)---async def test_hogql_table_applies_custom_modifier_to_sessions_query(ateam):- """Test that team-level bounceRateDurationSeconds is applied to sessions queries.-- The $is_bounce calculation uses bounceRateDurationSeconds. Without the fix to pass- modifiers to HogQLContext, the default value (10) would be used instead of the- team's custom value.- """- # Set custom bounce rate duration (default is 10)- custom_bounce_rate_duration = 123- ateam.modifiers = {"bounceRateDurationSeconds": custom_bounce_rate_duration}- await database_sync_to_async(ateam.save)()-- captured_sql = None-- async def mock_astream_query(self, query, *args, **kwargs):- nonlocal captured_sql- captured_sql = query- # returns early but yield makes this a generator. intentional unreachable- return- yield # type: ignore[unreachable]-- logger = unittest.mock.AsyncMock()- query = "SELECT $is_bounce FROM sessions LIMIT 1"- with unittest.mock.patch(- "posthog.temporal.common.clickhouse.ClickHouseClient.astream_query_as_arrow",- mock_astream_query,- ):- try:- async for _ in hogql_table(query, ateam, logger):- break- except (StopAsyncIteration, StopIteration):- pass-- assert captured_sql is not None, "SQL was not captured"- assert str(custom_bounce_rate_duration) in captured_sql, (- f"Expected bounce rate duration {custom_bounce_rate_duration} in SQL, got: {captured_sql}"- )---async def test_create_default_modifiers_for_team_in_async_context(ateam):- """Test that create_default_modifiers_for_team must be wrapped with database_sync_to_async in async context.-- The function accesses team.organization.created_at via person_on_events_mode_flag_based_default,- which triggers a lazy load of the organization foreign key. Without database_sync_to_async,- this raises SynchronousOnlyOperation in an async context.-- This is a regression test for the fix that wrapped the call in hogql_table and get_query_row_count.- """- from django.core.exceptions import SynchronousOnlyOperation-- from posthog.hogql.modifiers import create_default_modifiers_for_team-- # fetch team without select_related to ensure organization needs lazy loading- team = await database_sync_to_async(Team.objects.get)(id=ateam.pk)- # mock is_cloud() to return true so that the code path accessing team.organization.created_at is triggered- with unittest.mock.patch("posthog.models.team.team.is_cloud", return_value=True):- # calling directly raises- with pytest.raises(SynchronousOnlyOperation):- create_default_modifiers_for_team(team)- # wrapped doesn't raise- await database_sync_to_async(create_default_modifiers_for_team)(team)diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex db2ecd5d5f46..07ef330cb85f 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -1363,7 +1363,6 @@1 products/web_analytics/backend/test/test_digest_notification_workflows.py1 products/web_analytics/backend/test/test_weekly_digest_workflows.py10 posthog/temporal/ai_observability/trace_summarization/models.py-10 posthog/temporal/data_modeling/run_workflow.py10 posthog/temporal/sync_person_distinct_ids/activities.py10 products/signals/backend/temporal/grouping.py10 products/signals/backend/temporal/summary.pydiff --git a/products/data_modeling/backend/logic/schedule_reconcile.py b/products/data_modeling/backend/logic/schedule_reconcile.pyindex 67967809d085..3f2a3bfe1a28 100644--- a/products/data_modeling/backend/logic/schedule_reconcile.py+++ b/products/data_modeling/backend/logic/schedule_reconcile.py@@ -37,13 +37,7 @@ from temporalio.service import RPCError, RPCStatusCodefrom posthog.exceptions_capture import capture_exceptionfrom posthog.ph_client import feature_enabled_or_falsefrom posthog.temporal.common.client import async_connect, sync_connect-from posthog.temporal.common.schedule import (- a_create_schedule,- a_delete_schedule,- a_update_schedule,- delete_schedule,- schedule_exists,-)+from posthog.temporal.common.schedule import a_create_schedule, a_delete_schedule, a_update_schedule, delete_schedulefrom posthog.temporal.common.search_attributes import POSTHOG_DAG_ID_KEYfrom products.data_modeling.backend.logic.cohort_scheduling import (@@ -112,12 +106,10 @@ def maybe_reconcile_dag(dag: DAG) -> None:Runs after commit so the reconcile reads the mutated graph, and never raises past thecommit — the user's write already succeeded. Only DAGs already converted to cadence- tiers are touched: legacy single-schedule DAGs are converted solely by the- reconcile_freshness_schedules command, so a stray mutation can neither unschedule an- unseeded DAG nor create tiers alongside live v1 schedules on an unmigrated team.+ tiers are touched: `require_tiered` below leaves legacy single-schedule DAGs to the+ reconcile_freshness_schedules command, so a stray mutation cannot unschedule an+ unseeded DAG."""- if not tiered_schedules_enabled(dag.team):- returntransaction.on_commit(lambda: _reconcile_dag_best_effort(dag))@@ -131,47 +123,12 @@ def _reconcile_dag_best_effort(dag: DAG) -> None:capture_exception(error)-def dag_has_live_v1_schedules(dag: DAG) -> bool:- """Whether any of the DAG's schedulable saved queries still has a live v1 per-query schedule.-- Short-circuits on the first hit, so an unmigrated DAG — where the first query checked almost- always has one — costs a single Temporal call.- """- temporal = sync_connect()- for saved_query_id in schedulable_nodes(dag).values_list("saved_query_id", flat=True):- if saved_query_id is None:- continue- if schedule_exists(temporal, schedule_id=str(saved_query_id)):- return True- return False---def dag_can_bootstrap_to_tiers(dag: DAG) -> bool:- """Whether this DAG can be born straight onto cadence tiers. Decides only — no side effects.-- Callers reach this only once the v2 lookup has said the DAG has no `execute-dag` schedule.- Adding "and no live v1 schedules either" identifies a DAG that nothing has ever scheduled —- a new team's first materialization — where seeding tiers cannot double-schedule anything.- That is the one safe moment to do it: without this a fresh DAG mints a v1 per-query schedule- (v2 is otherwise created only by the migration commands), so every new team is born on v1 and- the v1 population grows on its own.-- A DAG carrying live v1 schedules is deliberately left alone — tiers next to them would- materialize everything twice. It stays for a migration command to convert and sweep.-- Deliberately not gated on `data-modeling-tiered-schedules`. Nothing mints v1 schedules any- more, so a DAG this declines gets no scheduler at all rather than the older one, and the flag- evaluates false for every self-hosted deployment.- """- return not dag_has_live_v1_schedules(dag)--def bootstrap_dag_to_tiers(dag: DAG, *, requested_by: "DataWarehouseSavedQuery | None" = None) -> None:"""Seed the DAG's targets and queue the reconcile that creates its first tier schedules.Everything here is a side effect, and `transaction.on_commit` runs the callback immediately- for callers that are not inside an atomic block — so call this only once- `dag_can_bootstrap_to_tiers` has said yes, and only after whatever frequency validation the+ for callers that are not inside an atomic block — so call this only once the v2 lookup has+ said the DAG has no `execute-dag` schedule, and only after whatever frequency validation thecaller does, never before.Reconciles without `require_tiered`, because this is the pass that creates the DAG's firstdiff --git a/products/data_modeling/backend/management/commands/resync_data_modeling_schedules.py b/products/data_modeling/backend/management/commands/resync_data_modeling_schedules.pydeleted file mode 100644index 86a182c87e08..000000000000--- a/products/data_modeling/backend/management/commands/resync_data_modeling_schedules.py+++ /dev/null@@ -1,128 +0,0 @@-import time-import logging-from datetime import timedelta--from django.conf import settings-from django.core.management.base import BaseCommand, CommandError-from django.core.paginator import Paginator--import structlog-import temporalio--from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery-from products.data_modeling.backend.schedule import get_v2_saved_query_ids-from products.data_warehouse.backend.facade.api import sync_saved_query_workflow--logger = structlog.get_logger(__name__)--BATCH_SIZE = 100-BATCH_DELAY_SECONDS = 0.5---class Command(BaseCommand):- help = "Resyncs Temporal schedules for data modeling saved queries"-- def add_arguments(self, parser):- parser.add_argument(- "--team-ids",- default=None,- type=str,- help="Comma separated list of team IDs to filter by",- )- parser.add_argument(- "--start-after-saved-query-id",- default=None,- type=str,- help="Resume after this saved query UUID (exclusive), following the id ordering used by this command",- )- parser.add_argument(- "--all",- action="store_true",- default=False,- help="Update all materialized saved queries, not just daily+ ones",- )- parser.add_argument(- "--dry-run",- action="store_true",- default=False,- help="Only show what would be updated without making changes",- )-- def handle(self, **options):- logger.setLevel(logging.INFO)-- if options["all"]:- queryset = DataWarehouseSavedQuery.objects.select_related("team").filter(- deleted=False,- sync_frequency_interval__isnull=False,- )- else:- queryset = DataWarehouseSavedQuery.objects.select_related("team").filter(- deleted=False,- sync_frequency_interval__gte=timedelta(hours=24),- )-- if options.get("team_ids") is not None:- try:- team_ids = [int(tid) for tid in options["team_ids"].split(",")]- except ValueError:- raise CommandError("team_ids must be a comma separated list of team IDs")- queryset = queryset.filter(team_id__in=team_ids)-- if options.get("start_after_saved_query_id") is not None:- queryset = queryset.filter(id__gt=options["start_after_saved_query_id"])-- # Never refresh a v1 schedule for a saved query whose DAG already runs on v2.- v2_ids = get_v2_saved_query_ids(list(queryset.values_list("id", flat=True)))- if v2_ids:- logger.info(f"Skipping {len(v2_ids)} saved queries on DAGs already migrated to v2")- queryset = queryset.exclude(id__in=v2_ids)-- queryset = queryset.order_by("id")- total = queryset.count()-- if total == 0:- raise CommandError("No saved queries found matching filters")-- logger.info(f"Found {total} saved queries to update")-- if options["dry_run"]:- for sq in queryset.iterator(chunk_size=BATCH_SIZE):- logger.info("Would update schedule", saved_query_id=str(sq.id), team_id=sq.team_id)- return-- if not settings.TEST:- confirm = input(f"\n\tWill update schedules for {total} saved queries. Proceed? (y/n) ")- if confirm.strip().lower() != "y":- logger.info("Aborting")- return-- updated = 0- failed = 0- not_found_ids: list[str] = []- processed = 0-- for batch in Paginator(queryset, BATCH_SIZE):- for saved_query in batch.object_list:- try:- saved_query.setup_model_paths()- sync_saved_query_workflow(saved_query, create=False)- updated += 1- except temporalio.service.RPCError as e:- if e.status == temporalio.service.RPCStatusCode.NOT_FOUND:- not_found_ids.append(str(saved_query.id))- logger.warning("Schedule not found in Temporal", saved_query_id=str(saved_query.id))- else:- failed += 1- logger.exception("Error updating schedule", saved_query_id=str(saved_query.id))- except Exception:- failed += 1- logger.exception("Error updating schedule", saved_query_id=str(saved_query.id))- processed += 1- logger.info(f"Progress: {processed}/{total}")- time.sleep(BATCH_DELAY_SECONDS)-- logger.info(f"Done! Updated: {updated}, Failed: {failed}, Not found: {len(not_found_ids)}")-- if not_found_ids:- logger.info("Saved queries with no Temporal schedule (orphaned):\n" + "\n".join(not_found_ids))diff --git a/products/data_modeling/backend/models/datawarehouse_saved_query.py b/products/data_modeling/backend/models/datawarehouse_saved_query.pyindex 8eb359e40094..b5396bcb1c46 100644--- a/products/data_modeling/backend/models/datawarehouse_saved_query.py+++ b/products/data_modeling/backend/models/datawarehouse_saved_query.py@@ -209,15 +209,17 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,def schedule_materialization(self, reconcile: bool = True, trigger_immediate_run: bool = False):"""- It will schedule the saved query workflow to run at the configured frequency.+ Put this saved query on the schedule that will materialize it, at the frequency in+ sync_frequency_interval.- trigger_immediate_run is for callers enabling materialization: on v2 it starts the first- materialization right away instead of waiting for the next scheduled DAG tick, matching- v1 schedule creation (which triggers immediately). Callers merely updating frequency- must leave it False. Best-effort: a failed start never disables materialization, since- the DAG schedule still covers the query.+ trigger_immediate_run is for callers enabling materialization: it starts the first+ materialization right away instead of waiting for the node's cadence tier to fire.+ Callers merely updating frequency must leave it False. The start is best effort, so a+ failure to start never disables materialization, because the tier still covers the query.- If the workflow fails to schedule, it will disable materialization for this view.+ A rejected frequency propagates to the caller. Any other failure disables+ materialization, because the alternative is a query that reports itself materialized+ while nothing is scheduled to materialize it."""from products.data_modeling.backend.logic.freshness import (UnsatisfiableFrequencyError,@@ -227,8 +229,6 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,from products.data_modeling.backend.logic.schedule_reconcile import (apply_saved_query_frequency_target,bootstrap_dag_to_tiers,- dag_can_bootstrap_to_tiers,- tiered_schedules_enabled,)from products.data_modeling.backend.models.node import Nodefrom products.data_modeling.backend.schedule import get_v2_saved_query_ids@@ -247,10 +247,9 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,)dag_to_bootstrap = Noneif not on_v2:- # Nothing creates a DAG's first v2 schedule outside the migration commands, so a- # brand-new team would fall through to v1 forever. Bootstrap it instead — declined- # unless the DAG has never been scheduled at all.- if node is not None and node.dag is not None and dag_can_bootstrap_to_tiers(node.dag):+ # Nothing creates a DAG's first schedule outside the migration commands, so a+ # brand-new team has nothing to materialize it. Bootstrap it onto tiers instead.+ if node is not None and node.dag is not None:dag_to_bootstrap = node.dagon_v2 = True@@ -262,11 +261,11 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,raise MissingDagNodeError(f"Saved query {self.id} is on a v2 team but has no DAG node to schedule through")- # Tiered v2: the interval is one-shot transport for frequency intent — consume- # it into the node target(s) and reconcile. Validation raises before the- # nulling below, so a rejected frequency stays visible for retry. A call with- # no interval carries no frequency opinion and must not touch existing targets.- if tiered_schedules_enabled(self.team) and self.sync_frequency_interval is not None:+ # The interval is one-shot transport for frequency intent — consume it into the+ # node target(s) and reconcile. Validation raises before the nulling below, so a+ # rejected frequency stays visible for retry. A call with no interval carries no+ # frequency opinion and must not touch existing targets.+ if self.sync_frequency_interval is not None:# A bootstrap reconciles the whole DAG once below, once the target has landed,# so asking for a second pass here would only repeat it.apply_saved_query_frequency_target(@@ -277,9 +276,8 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,# no schedules behind: on_commit fires immediately for the callers that are not# inside an atomic block, and two of the three are not.bootstrap_dag_to_tiers(dag_to_bootstrap, requested_by=self)- # On any v2 flavor the interval must end up NULL: a lingering value would let- # a v1 per-query schedule be recreated, and on tiered teams the node target is- # the only durable store of frequency intent.+ # The interval must end up NULL: the node target is the only durable store of+ # frequency intent.if self.sync_frequency_interval is not None:self.sync_frequency_interval = Noneself.save(update_fields=["sync_frequency_interval"])@@ -330,10 +328,7 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,)def revert_materialization(self):- from products.data_modeling.backend.logic.schedule_reconcile import (- apply_saved_query_frequency_target,- tiered_schedules_enabled,- )+ from products.data_modeling.backend.logic.schedule_reconcile import apply_saved_query_frequency_targetfrom products.data_modeling.backend.models.modeling import DataWarehouseModelPathfrom products.data_warehouse.backend.facade.api import delete_saved_query_schedule@@ -362,8 +357,7 @@ class DataWarehouseSavedQuery(CreatedMetaFields, UUIDTModel, UpdatedMetaFields,# materialized on tiered v2. Best-effort like the schedule delete above — the# revert itself already succeeded.try:- if tiered_schedules_enabled(self.team):- apply_saved_query_frequency_target(self, None)+ apply_saved_query_frequency_target(self, None)except Exception as e:capture_exception(e, {"saved_query_id": self.id, "saved_query_name": self.name})logger.exception(diff --git a/products/data_modeling/backend/test/test_schedule_materialization.py b/products/data_modeling/backend/test/test_schedule_materialization.pyindex fcb504a12dea..903102c0cb25 100644--- a/products/data_modeling/backend/test/test_schedule_materialization.py+++ b/products/data_modeling/backend/test/test_schedule_materialization.py@@ -79,30 +79,33 @@ class TestScheduleMaterializationV2Guard(BaseTest):nodeless.refresh_from_db()assert nodeless.is_materialized is False- def test_disables_materialization_when_dag_is_not_on_v2(self):- self.sq.is_materialized = True- self.sq.save(update_fields=["is_materialized"])+ def test_reports_and_disables_when_there_is_no_node_to_bootstrap(self):+ # a DAG with no v2 schedule is bootstrapped through its node, so the one way left to+ # reach the end of schedule_materialization with nothing scheduled is a query that has+ # no node at all. That is the arrival the winddown reporter exists to catch.+ nodeless = DataWarehouseSavedQuery.objects.create(+ name="sync_failed",+ team=self.team,+ query={"query": "SELECT 1", "kind": "HogQLQuery"},+ is_materialized=True,+ )with (mock.patch(GET_V2_DAG_IDS, return_value=set()),- mock.patch(f"{RECONCILE}.schedule_exists", return_value=True),mock.patch(f"{MODEL}.capture_exception") as capture,):- self.sq.schedule_materialization()+ nodeless.schedule_materialization()- self.sq.refresh_from_db()- assert self.sq.is_materialized is False+ nodeless.refresh_from_db()+ assert nodeless.is_materialized is Falseassert isinstance(capture.call_args.args[0], V1SchedulingPathReached)assert capture.call_args.args[1]["team_id"] == self.team.pk- def test_virgin_dag_is_born_on_tiers_instead_of_minting_a_v1_schedule(self):- # a brand-new team's DAG has no v2 schedule *and* no v1 schedules, so the v2 lookup says- # "not on v2" and the query would get a per-query v1 schedule — that is how every new team- # lands on v1 and why the v1 population grows on its own+ def test_virgin_dag_is_born_on_tiers(self):+ # a brand-new team's DAG has no schedule at all, so the v2 lookup says "not on v2" and+ # nothing would ever materialize the query — the bootstrap is what gives it a schedulenode = Node.objects.get(saved_query=self.sq)with (mock.patch(GET_V2_DAG_IDS, return_value=set()),- mock.patch(f"{RECONCILE}.schedule_exists", return_value=False),- mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=True),mock.patch(f"{RECONCILE}.sync_connect"),mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_no_schedules())),mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,@@ -118,29 +121,6 @@ class TestScheduleMaterializationV2Guard(BaseTest):self.sq.refresh_from_db()assert self.sq.sync_frequency_interval is None- def test_virgin_dag_is_born_on_tiers_with_the_tiered_flag_off(self):- # nothing mints v1 schedules any more, so a bootstrap the flag declines leaves the query- # with no scheduler at all — and the flag reads false on every self-hosted deployment- node = Node.objects.get(saved_query=self.sq)- with (- mock.patch(GET_V2_DAG_IDS, return_value=set()),- mock.patch(f"{RECONCILE}.schedule_exists", return_value=False),- mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=False),- mock.patch(f"{RECONCILE}.sync_connect"),- mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_no_schedules())),- mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,- mock.patch(f"{NODE_MAT}.sync_connect"),- self.captureOnCommitCallbacks(execute=True),- ):- self.sq.schedule_materialization()-- create.assert_called_once()- assert is_tier_schedule_id(create.call_args.kwargs["id"])- # the flag gates the write-through path, so the requested cadence has to survive as a- # seeded target instead- node.refresh_from_db()- assert get_declared_target(node) == timedelta(hours=12)-def test_failed_bootstrap_retracts_the_materialized_claim(self):# the reconcile runs after the caller's transaction commits, so a failure has no caller# left to raise into: leaving is_materialized set would report a schedule that was@@ -149,8 +129,6 @@ class TestScheduleMaterializationV2Guard(BaseTest):self.sq.save(update_fields=["is_materialized"])with (mock.patch(GET_V2_DAG_IDS, return_value=set()),- mock.patch(f"{RECONCILE}.schedule_exists", return_value=False),- mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=True),mock.patch(f"{RECONCILE}.sync_connect"),mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_no_schedules())),mock.patch(@@ -174,8 +152,6 @@ class TestScheduleMaterializationV2Guard(BaseTest):self.sq.save(update_fields=["sync_frequency_interval"])with (mock.patch(GET_V2_DAG_IDS, return_value=set()),- mock.patch(f"{RECONCILE}.schedule_exists", return_value=False),- mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=True),mock.patch(f"{RECONCILE}.sync_connect"),mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_no_schedules())),mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,diff --git a/products/data_modeling/backend/test/test_schedule_reconcile.py b/products/data_modeling/backend/test/test_schedule_reconcile.pyindex 4aecc445a708..9cc301fcdfe2 100644--- a/products/data_modeling/backend/test/test_schedule_reconcile.py+++ b/products/data_modeling/backend/test/test_schedule_reconcile.py@@ -427,22 +427,11 @@ class TestMaybeReconcileDag(BaseTest):temporal.list_schedules = fake_list_schedulesreturn temporal- def test_flag_off_never_touches_temporal(self):- dag = self._dag_with_target()- with (- mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=False),- mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock()) as connect,- ):- with self.captureOnCommitCallbacks(execute=True):- maybe_reconcile_dag(dag)- connect.assert_not_called()-def test_untiered_dag_is_left_alone(self):# a legacy single-schedule DAG converts only via the conversion command; a mutation# trigger must neither unschedule it nor create tiers next to live v1 schedulesdag = self._dag_with_target()with (- mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=True),mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=self._temporal_listing([str(dag.id)]))),@@ -460,7 +449,6 @@ class TestMaybeReconcileDag(BaseTest):dag = self._dag_with_target()tier_id = tier_schedule_id(str(dag.id), M15)with (- mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=True),mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=self._temporal_listing([tier_id]))),@@ -475,7 +463,6 @@ class TestMaybeReconcileDag(BaseTest):def test_reconcile_failure_never_raises_past_commit(self):dag = self._dag_with_target()with (- mock.patch(f"{RECONCILE}.feature_enabled_or_false", return_value=True),mock.patch(f"{RECONCILE}.async_connect", new=mock.AsyncMock(side_effect=RuntimeError("temporal down"))),mock.patch(f"{RECONCILE}.capture_exception") as capture,):diff --git a/products/data_modeling/backend/tests/test_managed_viewset_providers.py b/products/data_modeling/backend/tests/test_managed_viewset_providers.pyindex 701e6b33fb73..866904386188 100644--- a/products/data_modeling/backend/tests/test_managed_viewset_providers.py+++ b/products/data_modeling/backend/tests/test_managed_viewset_providers.py@@ -115,18 +115,14 @@ class TestManagedViewSetProviders(BaseTest):self.assertEqual(first_ids, second_ids)- def test_provisioning_a_new_team_never_mints_v1_schedules(self):+ def test_provisioning_a_new_team_puts_every_view_on_tier_schedules(self):# Managed viewsets are how most new teams first materialize anything (a provider makes- # several views at once), and their DAG is brand new — so without a birth-on-v2 path every- # view here gets its own v1 per-query schedule. Views after the first must follow the+ # several views at once), and their DAG is brand new. Views after the first must follow the# bootstrap too, even though its tier schedules are only created after commit.views = [_fake_view(name=f"provided_view_{i}") for i in range(3)]with (patch.dict(_expected_views_providers, clear=True),patch(GET_V2_DAG_IDS, return_value=set()),- patch(f"{SERVICE}.sync_saved_query_workflow") as sync_wf,- patch(f"{SERVICE}.saved_query_workflow_exists", return_value=False),- patch(f"{RECONCILE}.schedule_exists", return_value=False),patch(f"{RECONCILE}.feature_enabled_or_false", return_value=True),patch(f"{RECONCILE}.sync_connect"),patch(f"{RECONCILE}.async_connect", new=AsyncMock(return_value=_no_schedules())),@@ -138,7 +134,6 @@ class TestManagedViewSetProviders(BaseTest):with self.captureOnCommitCallbacks(execute=True):viewset.sync_views()- sync_wf.assert_not_called()assert create.call_count > 0assert all(is_tier_schedule_id(call.kwargs["id"]) for call in create.call_args_list)assert [v.sync_frequency_interval for v in self._views(viewset)] == [None, None, None]diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.pyindex a59fe3cbdb9b..48da87bc5db8 100644--- a/products/data_warehouse/backend/facade/api.py+++ b/products/data_warehouse/backend/facade/api.py@@ -19,12 +19,9 @@ _B = "products.data_warehouse.backend."_LAZY = {"CreateTableResult": "logic.data_load.create_table","create_table_from_saved_query": "logic.data_load.create_table",- "a_pause_saved_query_schedule": "logic.data_load.saved_query_service","delete_saved_query_schedule": "logic.data_load.saved_query_service",- "get_saved_query_schedule": "logic.data_load.saved_query_service","pause_saved_query_schedule": "logic.data_load.saved_query_service","saved_query_workflow_exists": "logic.data_load.saved_query_service",- "sync_saved_query_workflow": "logic.data_load.saved_query_service","trigger_saved_query_schedule": "logic.data_load.saved_query_service","unpause_saved_query_schedule": "logic.data_load.saved_query_service","a_unpause_external_data_schedule": "logic.data_load.service",diff --git a/products/data_warehouse/backend/logic/data_load/saved_query_service.py b/products/data_warehouse/backend/logic/data_load/saved_query_service.pyindex 474edc6f973a..0ceb947a93eb 100644--- a/products/data_warehouse/backend/logic/data_load/saved_query_service.py+++ b/products/data_warehouse/backend/logic/data_load/saved_query_service.py@@ -1,106 +1,22 @@-from dataclasses import asdictfrom datetime import timedeltafrom typing import TYPE_CHECKING-from django.conf import settings-import temporalio-from temporalio.client import (- Schedule,- ScheduleActionStartWorkflow,- ScheduleOverlapPolicy,- SchedulePolicy,- ScheduleState,-)-from temporalio.common import RetryPolicy, SearchAttributePair, TypedSearchAttributesfrom posthog.models.activity_logging.activity_log import Change, Detail, log_activity-from posthog.temporal.common.client import async_connect, sync_connect+from posthog.temporal.common.client import sync_connectfrom posthog.temporal.common.schedule import (- a_pause_schedule,- create_schedule,delete_schedule,pause_schedule,schedule_exists,trigger_schedule,unpause_schedule,- update_schedule,)-from posthog.temporal.common.search_attributes import POSTHOG_DAG_ID_KEY, POSTHOG_ORG_ID_KEY, POSTHOG_TEAM_ID_KEY--from products.data_modeling.backend.facade.models import Node-from products.data_modeling.backend.facade.tasks import build_schedule_specif TYPE_CHECKING:from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery-def get_saved_query_schedule(saved_query: "DataWarehouseSavedQuery") -> Schedule:- from posthog.temporal.data_modeling.run_workflow import RunWorkflowInputs, Selector-- inputs = RunWorkflowInputs(- team_id=saved_query.team_id,- select=[Selector(label=saved_query.id.hex, ancestors=0, descendants=0)],- )-- interval = saved_query.sync_frequency_interval or timedelta(hours=24)- spec = build_schedule_spec(- entity_id=saved_query.id,- interval=interval,- team_timezone=saved_query.team.timezone,- )-- return Schedule(- action=ScheduleActionStartWorkflow(- "data-modeling-run",- asdict(inputs),- id=str(saved_query.id),- task_queue=str(settings.DATA_MODELING_TASK_QUEUE),- retry_policy=RetryPolicy(- initial_interval=timedelta(seconds=10),- maximum_interval=timedelta(seconds=60),- maximum_attempts=2,- non_retryable_error_types=["NondeterminismError", "CancelledError"],- ),- ),- spec=spec,- state=ScheduleState(note=f"Schedule for saved query: {saved_query.pk}"),- policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.CANCEL_OTHER),- )---def get_saved_query_search_attributes(saved_query: "DataWarehouseSavedQuery") -> TypedSearchAttributes:- dag_id = Node.objects.filter(saved_query=saved_query).values_list("dag_id", flat=True).first()- search_attributes: list[SearchAttributePair] = [- SearchAttributePair(key=POSTHOG_TEAM_ID_KEY, value=saved_query.team_id),- SearchAttributePair(key=POSTHOG_ORG_ID_KEY, value=str(saved_query.team.organization_id)),- ]- if dag_id:- search_attributes.append(SearchAttributePair(key=POSTHOG_DAG_ID_KEY, value=str(dag_id)))- return TypedSearchAttributes(search_attributes=search_attributes)---def sync_saved_query_workflow(- saved_query: "DataWarehouseSavedQuery", create: bool = False-) -> "DataWarehouseSavedQuery":- temporal = sync_connect()- schedule = get_saved_query_schedule(saved_query)- search_attributes = get_saved_query_search_attributes(saved_query)-- if create:- create_schedule(- temporal,- id=str(saved_query.id),- schedule=schedule,- trigger_immediately=True,- search_attributes=search_attributes,- )- else:- update_schedule(temporal, id=str(saved_query.id), schedule=schedule, search_attributes=search_attributes)-- return saved_query--def delete_saved_query_schedule(saved_query: "DataWarehouseSavedQuery"):temporal = sync_connect()try:@@ -117,11 +33,6 @@ def pause_saved_query_schedule(saved_query: "DataWarehouseSavedQuery") -> None:pause_schedule(temporal, schedule_id=str(saved_query.id))-async def a_pause_saved_query_schedule(saved_query: "DataWarehouseSavedQuery") -> None:- temporal = await async_connect()- await a_pause_schedule(temporal, schedule_id=str(saved_query.id))--def unpause_saved_query_schedule(saved_query: "DataWarehouseSavedQuery") -> None:temporal = sync_connect()unpause_schedule(temporal, schedule_id=str(saved_query.id))diff --git a/products/data_warehouse/backend/models/test/test_managed_viewset.py b/products/data_warehouse/backend/models/test/test_managed_viewset.pyindex 98af99b5f0ec..51128f39b239 100644--- a/products/data_warehouse/backend/models/test/test_managed_viewset.py+++ b/products/data_warehouse/backend/models/test/test_managed_viewset.py@@ -81,7 +81,7 @@ class TestDataWarehouseManagedViewSetModel(BaseTest):reconcile.assert_called_once()- def test_failed_dag_sync_does_not_mint_a_v1_schedule(self):+ def test_failed_dag_sync_leaves_nothing_materialized(self):managed_viewset = DataWarehouseManagedViewSet.objects.create(team=self.team,kind=DataWarehouseManagedViewSetKind.REVENUE_ANALYTICS,@@ -96,17 +96,9 @@ class TestDataWarehouseManagedViewSetModel(BaseTest):"products.data_modeling.backend.schedule.get_v2_scheduled_dag_ids",side_effect=lambda candidate_dag_ids=None: set(candidate_dag_ids or []),),- patch(- "products.data_warehouse.backend.logic.data_load.saved_query_service.sync_saved_query_workflow"- ) as sync_wf,- patch(- "products.data_warehouse.backend.logic.data_load.saved_query_service.saved_query_workflow_exists",- return_value=False,- ),):managed_viewset.sync_views()- sync_wf.assert_not_called()assert not DataWarehouseSavedQuery.objects.filter(managed_viewset=managed_viewset, is_materialized=True).exists()diff --git a/products/data_warehouse/backend/test/test_saved_query_dag_sync_integration.py b/products/data_warehouse/backend/test/test_saved_query_dag_sync_integration.pyindex 650c393854c0..56fb1e8aba23 100644--- a/products/data_warehouse/backend/test/test_saved_query_dag_sync_integration.py+++ b/products/data_warehouse/backend/test/test_saved_query_dag_sync_integration.py@@ -124,10 +124,7 @@ class TestSavedQueryDagSyncIntegration(APIBaseTest):node.refresh_from_db()self.assertEqual(node.type, NodeType.MAT_VIEW)- @patch(- "products.data_warehouse.backend.presentation.views.saved_query.saved_query_workflow_exists", return_value=True- )- def test_revert_materialization_updates_node_type(self, _mock_workflow_exists):+ def test_revert_materialization_updates_node_type(self):# create materializedcreate_response = self.client.post(f"/api/environments/{self.team.id}/warehouse_saved_queries/",diff --git a/products/data_warehouse/backend/test/test_saved_query_schedule.py b/products/data_warehouse/backend/test/test_saved_query_schedule.pydeleted file mode 100644index 7693b7ad5e5c..000000000000--- a/products/data_warehouse/backend/test/test_saved_query_schedule.py+++ /dev/null@@ -1,71 +0,0 @@-import uuid-from datetime import timedelta--from unittest.mock import MagicMock--from django.test import TestCase--from parameterized import parameterized--from products.data_warehouse.backend.logic.data_load.saved_query_service import get_saved_query_schedule---class TestGetSavedQuerySchedule(TestCase):- def _make_saved_query(self, sync_frequency_interval: timedelta | None = None, timezone: str = "UTC") -> MagicMock:- sq = MagicMock()- sq.id = uuid.uuid4()- sq.team_id = 1- sq.pk = sq.id- sq.sync_frequency_interval = sync_frequency_interval- sq.team.timezone = timezone- return sq-- def test_uses_calendar_spec(self):- sq = self._make_saved_query(sync_frequency_interval=timedelta(hours=24))- schedule = get_saved_query_schedule(sq)- assert len(schedule.spec.calendars) >= 1-- def test_defaults_to_24h_when_no_interval(self):- sq = self._make_saved_query(sync_frequency_interval=None)- schedule = get_saved_query_schedule(sq)- # 24hr -> medium tier -> 1 hour entry- assert len(schedule.spec.calendars) == 1- assert len(schedule.spec.calendars[0].hour) == 1-- def test_passes_team_timezone(self):- sq = self._make_saved_query(sync_frequency_interval=timedelta(hours=24), timezone="America/New_York")- schedule = get_saved_query_schedule(sq)- assert schedule.spec.time_zone_name == "America/New_York"-- @parameterized.expand(- [- ("15min", timedelta(minutes=15)),- ("30min", timedelta(minutes=30)),- ("1h", timedelta(hours=1)),- ("6h", timedelta(hours=6)),- ("12h", timedelta(hours=12)),- ("24h", timedelta(hours=24)),- ("7d", timedelta(days=7)),- ("30d", timedelta(days=30)),- ]- )- def test_deterministic_for_same_id(self, _name, interval):- sq = self._make_saved_query(sync_frequency_interval=interval)- schedule_a = get_saved_query_schedule(sq)- schedule_b = get_saved_query_schedule(sq)- assert schedule_a.spec.calendars == schedule_b.spec.calendars-- def test_schedule_has_cancel_other_overlap_policy(self):- sq = self._make_saved_query(sync_frequency_interval=timedelta(hours=6))- schedule = get_saved_query_schedule(sq)- from temporalio.client import ScheduleOverlapPolicy-- assert schedule.policy.overlap == ScheduleOverlapPolicy.CANCEL_OTHER-- def test_schedule_action_is_data_modeling_run(self):- from temporalio.client import ScheduleActionStartWorkflow-- sq = self._make_saved_query(sync_frequency_interval=timedelta(hours=6))- schedule = get_saved_query_schedule(sq)- assert isinstance(schedule.action, ScheduleActionStartWorkflow)- assert schedule.action.workflow == "data-modeling-run"diff --git a/products/endpoints/backend/tests/test_endpoint_materialization.py b/products/endpoints/backend/tests/test_endpoint_materialization.pyindex c8ef9cdb8afd..03235b7bee9c 100644--- a/products/endpoints/backend/tests/test_endpoint_materialization.py+++ b/products/endpoints/backend/tests/test_endpoint_materialization.py@@ -20,13 +20,11 @@ from rest_framework.response import Responsefrom posthog.hogql.errors import QueryErrorfrom posthog.constants import RETENTION_FIRST_EVER_OCCURRENCE, TREND_FILTER_TYPE_EVENTS-from posthog.settings.temporal import DATA_MODELING_TASK_QUEUEfrom posthog.sync import database_sync_to_asyncfrom products.data_modeling.backend.facade.api import UnsatisfiableFrequencyError, get_declared_targetfrom products.data_modeling.backend.facade.modeling import DataWarehouseModelPathfrom products.data_modeling.backend.facade.models import DAG, DataModelingJob, DataWarehouseSavedQuery, Node-from products.data_warehouse.backend.facade.api import get_saved_query_schedulefrom products.endpoints.backend.logic.execution import EndpointExecutionServicefrom products.endpoints.backend.logic.materialization import (EndpointMaterializationService,@@ -2360,57 +2358,3 @@ class TestEndpointMaterializationTemporal:await sync_to_async(version.save)()yield endpoint-- async def test_saved_query_temporal_schedule_created(self, materialized_endpoint):- """Test that a Temporal schedule is created for the SavedQuery."""- version = await sync_to_async(materialized_endpoint.get_version)()-- def get_saved_query(v):- return v.saved_query-- saved_query = await sync_to_async(get_saved_query)(version)- assert saved_query is not None-- # Get the schedule that should be created- schedule = await sync_to_async(get_saved_query_schedule)(saved_query)-- # Verify schedule configuration- from temporalio.client import ScheduleActionStartWorkflow, ScheduleOverlapPolicy-- assert isinstance(schedule.action, ScheduleActionStartWorkflow)- assert schedule.action.id == str(saved_query.id)- assert schedule.action.task_queue == DATA_MODELING_TASK_QUEUE-- # Verify schedule uses calendar spec (medium interval for 12h)- assert len(schedule.spec.calendars) == 1- assert schedule.spec.jitter == timedelta(hours=1)-- # Verify schedule policy- assert schedule.policy.overlap == ScheduleOverlapPolicy.CANCEL_OTHER-- async def test_sync_frequency_affects_schedule_interval(self, materialized_endpoint):- """Test that different sync_frequency values create schedules with correct intervals."""- version = await sync_to_async(materialized_endpoint.get_version)()-- def get_saved_query(v):- return v.saved_query-- saved_query = await sync_to_async(get_saved_query)(version)-- # Test 1-hour frequency (short interval: calendar with minute buckets, 1min jitter)- saved_query.sync_frequency_interval = timedelta(hours=1)- schedule = await sync_to_async(get_saved_query_schedule)(saved_query)- assert len(schedule.spec.calendars) == 1- assert schedule.spec.jitter == timedelta(minutes=1)-- # Test 12-hour frequency (medium interval: calendar with hour buckets, 1hr jitter)- saved_query.sync_frequency_interval = timedelta(hours=12)- schedule = await sync_to_async(get_saved_query_schedule)(saved_query)- assert len(schedule.spec.calendars) == 1- assert schedule.spec.jitter == timedelta(hours=1)-- # Test 24-hour frequency (medium interval: calendar with hour buckets, 1hr jitter)- saved_query.sync_frequency_interval = timedelta(hours=24)- schedule = await sync_to_async(get_saved_query_schedule)(saved_query)- assert len(schedule.spec.calendars) == 1- assert schedule.spec.jitter == timedelta(hours=1)diff --git a/products/model_crossing_uses_baseline.txt b/products/model_crossing_uses_baseline.txtindex 6d589c37ed1a..d3182b735af8 100644--- a/products/model_crossing_uses_baseline.txt+++ b/products/model_crossing_uses_baseline.txt@@ -705,7 +705,6 @@ warehouse_sources.DataWarehouseTable posthog.hogql.database.database instance-mawarehouse_sources.DataWarehouseTable posthog.hogql.direct_connection instance-many(filter) 1warehouse_sources.DataWarehouseTable posthog.hogql_queries.access_controlled_resources instance-many(only) 1warehouse_sources.DataWarehouseTable posthog.tasks.usage_report instance-many(annotate) 2-warehouse_sources.DataWarehouseTable posthog.temporal.data_modeling.run_workflow instance-single 2warehouse_sources.DataWarehouseTable products.data_catalog.backend.logic.certifications instance-many(select_related) 1warehouse_sources.DataWarehouseTable products.data_catalog.evals.seeders instance-many(filter) 1warehouse_sources.DataWarehouseTable products.data_catalog.evals.seeders write(create) 1