:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): route materialization run logs to log_entries (#76958)
Thiago Salvatoreb25da139812b
diff --git a/posthog/temporal/data_modeling/activities/create_data_modeling_job.py b/posthog/temporal/data_modeling/activities/create_data_modeling_job.pyindex 15f4982904a1..586bf9dd03d8 100644--- a/posthog/temporal/data_modeling/activities/create_data_modeling_job.py+++ b/posthog/temporal/data_modeling/activities/create_data_modeling_job.py@@ -5,6 +5,7 @@ from structlog.contextvars import bind_contextvarsfrom temporalio import activityfrom posthog.sync import database_sync_to_async_pool+from posthog.temporal.data_modeling.activities.utils import bind_data_modeling_log_contextfrom products.data_modeling.backend.facade.models import DataModelingJob, DataModelingJobEngine, Node@@ -20,8 +21,16 @@ class CreateDataModelingJobInputs:parent_workflow_id: str | None = None[email protected](frozen=True, kw_only=True)+class CreatedDataModelingJob:+ job_id: str+ saved_query_id: str | None++@database_sync_to_async_pool-def _create_data_modeling_job(inputs: CreateDataModelingJobInputs, workflow_id: str, workflow_run_id: str) -> str:+def _create_data_modeling_job(+ inputs: CreateDataModelingJobInputs, workflow_id: str, workflow_run_id: str+) -> CreatedDataModelingJob:node = Node.objects.prefetch_related("saved_query").get(id=inputs.node_id, team_id=inputs.team_id, dag_id=inputs.dag_id)@@ -35,7 +44,10 @@ def _create_data_modeling_job(inputs: CreateDataModelingJobInputs, workflow_id:parent_workflow_id=inputs.parent_workflow_id,created_by_id=node.saved_query.created_by_id if node.saved_query else None,)- return str(job.id)+ return CreatedDataModelingJob(+ job_id=str(job.id),+ saved_query_id=str(node.saved_query.id) if node.saved_query else None,+ )@activity.defn@@ -51,6 +63,8 @@ async def create_data_modeling_job_activity(inputs: CreateDataModelingJobInputs)assert workflow_idassert workflow_run_id- job_id = await _create_data_modeling_job(inputs, workflow_id, workflow_run_id)- await logger.ainfo(f"Created DataModelingJob {job_id} for node {inputs.node_id}")- return job_id+ created = await _create_data_modeling_job(inputs, workflow_id, workflow_run_id)+ if created.saved_query_id is not None:+ bind_data_modeling_log_context(inputs.team_id, created.saved_query_id)+ await logger.ainfo(f"Created DataModelingJob {created.job_id} for node {inputs.node_id}")+ return created.job_iddiff --git a/posthog/temporal/data_modeling/activities/fail_materialization.py b/posthog/temporal/data_modeling/activities/fail_materialization.pyindex bc84ae25f418..f7121faa1319 100644--- a/posthog/temporal/data_modeling/activities/fail_materialization.py+++ b/posthog/temporal/data_modeling/activities/fail_materialization.py@@ -23,6 +23,7 @@ from products.data_warehouse.backend.facade.api import pause_saved_query_schedulfrom ..metrics import get_node_suspended_metricfrom .utils import (CONSECUTIVE_FAILURES_TO_SUSPEND,+ bind_data_modeling_log_context,maybe_suspend_node_for_engine,strip_hostname_from_error,update_node_system_properties,@@ -148,10 +149,16 @@ async def fail_materialization_activity(inputs: FailMaterializationInputs) -> Nobind_contextvars(team_id=inputs.team_id)logger = LOGGER.bind()_, job = await _fail_node_and_data_modeling_job(inputs)- await logger.aerror(- f"Failed materialization job: node={inputs.node_id} dag={inputs.dag_id} job={job.id} "- f"workflow={job.workflow_id} workflow_run={job.workflow_run_id} error={inputs.error}"+ if job.saved_query_id is not None:+ bind_data_modeling_log_context(inputs.team_id, job.saved_query_id)+ job_context = (+ f"node={inputs.node_id} dag={inputs.dag_id} job={job.id} "+ f"workflow={job.workflow_id} workflow_run={job.workflow_run_id}")+ # The bound context above puts this line in front of users, so it carries the same sanitized+ # error the job row does. The raw one stays write-only, where only internal logging sees it.+ await logger.aerror(f"Failed materialization job: {job_context} error={strip_hostname_from_error(inputs.error)}")+ await logger.aerror(f"Failed materialization job: {job_context} error={inputs.error}", write_only=True)# error-specific recovery: pause schedule on timeout, revert on unknown table, else suspend after repeated failuresif not inputs.update_node:return@@ -193,4 +200,6 @@ async def fail_materialization_activity(inputs: FailMaterializationInputs) -> No)except Exception as e:capture_exception(e)- await logger.aexception(f"Failed to run error-specific recovery for node {inputs.node_id}: {str(e)}")+ await logger.aexception(+ f"Failed to run error-specific recovery for node {inputs.node_id}: {strip_hostname_from_error(str(e))}"+ )diff --git a/posthog/temporal/data_modeling/activities/materialize_view.py b/posthog/temporal/data_modeling/activities/materialize_view.pyindex 50d82f51c6c3..41bc0bb1f4c7 100644--- a/posthog/temporal/data_modeling/activities/materialize_view.py+++ b/posthog/temporal/data_modeling/activities/materialize_view.py@@ -29,6 +29,7 @@ from posthog.sync import database_sync_to_async_poolfrom posthog.temporal.common.clickhouse import get_client as get_clickhouse_clientfrom posthog.temporal.common.heartbeat import Heartbeaterfrom posthog.temporal.common.logger import get_logger+from posthog.temporal.data_modeling.activities.utils import bind_data_modeling_log_contextfrom products.data_modeling.backend.facade.modeling import bounded_resolver_factory_for_viewfrom products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery, Node, NodeType@@ -394,7 +395,9 @@ async def hogql_table(query: str, team: Team, logger: FilteringBoundLogger, viewarrow_prepared_hogql_query, context=context, dialect="clickhouse", stack=[], settings=settings)- await logger.adebug(f"Running clickhouse query: {arrow_printed}")+ # The query goes in a field rather than the message: only the message is copied into the+ # log_entries row users can read, and the compiled query is the saved query's own SQL.+ await logger.adebug("Running clickhouse query", query=arrow_printed)async with (_clickhouse_query_semaphore,@@ -487,6 +490,7 @@ async def materialize_view_activity(inputs: MaterializeViewInputs) -> Materializtag_queries(team_id=inputs.team_id, product=Product.WAREHOUSE, feature=Feature.DATA_MODELING)objects = await _get_matview_input_objects(inputs)+ bind_data_modeling_log_context(inputs.team_id, objects.saved_query.id)await logger.ainfo(f"Starting materialization for node {objects.node.name}")table_uri = _build_model_table_uri(objects.team.pk, objects.saved_query.id.hex, objects.saved_query.normalized_name)diff --git a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.pyindex d7748355d44d..4fb100e8a5b4 100644--- a/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py+++ b/posthog/temporal/data_modeling/activities/materialize_view_duckgres.py@@ -28,7 +28,12 @@ from products.managed_warehouse.backend.facade.api import ()from ..metrics import get_node_suspended_metric-from .utils import CONSECUTIVE_FAILURES_TO_SUSPEND, clear_node_suspension_for_engine, maybe_suspend_node_for_engine+from .utils import (+ CONSECUTIVE_FAILURES_TO_SUSPEND,+ bind_data_modeling_log_context,+ clear_node_suspension_for_engine,+ maybe_suspend_node_for_engine,+)LOGGER = get_logger(__name__)@@ -163,6 +168,7 @@ async def materialize_view_duckgres_activity(inputs: DuckgresShadowInputs) -> Dulogger = LOGGER.bind()team, node, saved_query = await _get_shadow_input_objects(inputs)+ bind_data_modeling_log_context(inputs.team_id, saved_query.id)hogql_query = typing.cast(dict, saved_query.query)["query"]schema_name = duckgres_data_modeling_schema(team.pk)table_name = saved_query.normalized_namediff --git a/posthog/temporal/data_modeling/activities/prepare_queryable_table.py b/posthog/temporal/data_modeling/activities/prepare_queryable_table.pyindex f4528c63c008..629cd4bd326a 100644--- a/posthog/temporal/data_modeling/activities/prepare_queryable_table.py+++ b/posthog/temporal/data_modeling/activities/prepare_queryable_table.py@@ -1,10 +1,10 @@import dataclassesfrom structlog import get_logger-from structlog.contextvars import bind_contextvarsfrom temporalio import activityfrom posthog.sync import database_sync_to_async_pool+from posthog.temporal.data_modeling.activities.utils import bind_data_modeling_log_contextfrom products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.data_warehouse.backend.facade.api import create_table_from_saved_query@@ -58,7 +58,7 @@ async def prepare_queryable_table_activity(inputs: PrepareQueryableTableInputs)Returns storage metrics (delta and total MiB) for the materialized table."""- bind_contextvars(team_id=inputs.team_id)+ bind_data_modeling_log_context(inputs.team_id, inputs.saved_query_id)logger = LOGGER.bind()saved_query = await _get_saved_query_with_table(inputs)diff --git a/posthog/temporal/data_modeling/activities/succeed_materialization.py b/posthog/temporal/data_modeling/activities/succeed_materialization.pyindex d61fe870f4bf..bcc1a6c61cc7 100644--- a/posthog/temporal/data_modeling/activities/succeed_materialization.py+++ b/posthog/temporal/data_modeling/activities/succeed_materialization.py@@ -18,7 +18,7 @@ from products.data_modeling.backend.facade.models import (Node,)-from .utils import clear_node_suspension, update_node_system_properties+from .utils import bind_data_modeling_log_context, clear_node_suspension, update_node_system_propertiesLOGGER = get_logger(__name__)@@ -153,6 +153,8 @@ async def succeed_materialization_activity(inputs: SucceedMaterializationInputs)outcome = await _succeed_node_and_data_modeling_job(inputs)+ if outcome.job.saved_query_id is not None:+ bind_data_modeling_log_context(inputs.team_id, outcome.job.saved_query_id)await logger.ainfo(f"Succeeded materialization job: node={inputs.node_id} dag={inputs.dag_id} job={outcome.job.id} "f"workflow={outcome.job.workflow_id} workflow_run={outcome.job.workflow_run_id}"diff --git a/posthog/temporal/data_modeling/activities/utils.py b/posthog/temporal/data_modeling/activities/utils.pyindex 78a83ddb8ab8..a4dac623ea2e 100644--- a/posthog/temporal/data_modeling/activities/utils.py+++ b/posthog/temporal/data_modeling/activities/utils.py@@ -4,6 +4,8 @@ from uuid import UUIDfrom django.db import transaction+from structlog.contextvars import bind_contextvars+from posthog.sync import database_sync_to_async_poolfrom products.data_modeling.backend.facade.api import (@@ -25,6 +27,7 @@ from products.data_modeling.backend.facade.models import (# API and DAG-sync paths that clear it. Re-exported so the activities keep importing from here.__all__ = ["CONSECUTIVE_FAILURES_TO_SUSPEND",+ "bind_data_modeling_log_context","clear_node_suspension","clear_node_suspension_for_engine","is_node_suspended",@@ -37,6 +40,17 @@ __all__ = [# Consecutive failed jobs (per engine) before a node is suspended from future DAG runs.CONSECUTIVE_FAILURES_TO_SUSPEND = 5++def bind_data_modeling_log_context(team_id: int, saved_query_id: UUID | str) -> None:+ """Route this activity's log lines to `log_entries` under the saved query's id.++ The v2 workflow types aren't mapped in `resolve_log_source` (their workflow ids carry a node+ id, not the saved query id the UI queries by), so without this event-level override every+ produced line lands with a NULL log_source and the run-history modal shows no logs.+ """+ bind_contextvars(team_id=team_id, log_source="data_modeling_run", log_source_id=str(saved_query_id))++# Regex patterns for stripping hostnames from ClickHouse error messages# Matches patterns like: "(from chi-xxx.svc.cluster.local:9000)" or "(from 10.0.0.1:9000)"_HOSTNAME_FROM_PATTERN = re.compile(r"\(from\s+[^\s\)]+:\d+\)")diff --git a/posthog/temporal/data_modeling/run_workflow.py b/posthog/temporal/data_modeling/run_workflow.pyindex edf8c3c807c7..86c645bce153 100644--- a/posthog/temporal/data_modeling/run_workflow.py+++ b/posthog/temporal/data_modeling/run_workflow.py@@ -420,7 +420,7 @@ async def handle_error(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}")+ await logger.aerror(f"handle_error: error={error_str}. error_message={error_message}", write_only=True)job.status = DataModelingJob.Status.FAILEDjob.rows_materialized = 0job.error = strip_hostname_from_error(error_str)@@ -440,7 +440,7 @@ async def handle_cancelled():error_str = str(error)if job:- await logger.aerror(f"handle_cancelled: error={error_str}. error_message={error_message}")+ await logger.aerror(f"handle_cancelled: error={error_str}. error_message={error_message}", write_only=True)job.status = DataModelingJob.Status.CANCELLEDjob.rows_materialized = 0job.error = strip_hostname_from_error(error_str)@@ -605,7 +605,7 @@ async def materialize_model(raiseexcept Exception as e:error_message = str(e)- await logger.aerror(f"Error materializing model {model_label}: {error_message}")+ 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@@ -761,7 +761,7 @@ async def mark_job_as_failed(job: DataModelingJob, error_message: str, logger: Fbut the user-facing error has hostnames stripped to avoid exposing infrastructure details."""- await logger.aerror(f"mark_job_as_failed: {error_message}")+ 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.FAILEDjob.rows_materialized = 0diff --git a/posthog/temporal/tests/common/test_logger.py b/posthog/temporal/tests/common/test_logger.pyindex cc77015bbcc9..0c7a99a1ab55 100644--- a/posthog/temporal/tests/common/test_logger.py+++ b/posthog/temporal/tests/common/test_logger.py@@ -810,6 +810,39 @@ def test_log_messages_renderer_event_level_log_source_override():assert payload["instance_id"] == "abc-run-id"+def test_log_messages_renderer_keeps_structured_fields_out_of_the_produce_message():+ """Only the message text reaches `log_entries`; other event keys stay in the written log.++ Callers rely on this to keep sensitive values (compiled SQL, credentials) out of the rows+ users can read, by passing them as fields instead of interpolating them into the message.+ """+ from posthog.temporal.common.logger import Logger, LogMessagesRenderer++ renderer = LogMessagesRenderer(event_key="msg")+ event_dict = {+ "msg": "Running clickhouse query",+ "query": "SELECT secret_column FROM some_private_table",+ "level": "debug",+ "team_id": 2,+ "timestamp": "2024-01-01 00:00:00.000000",+ "workflow_type": "data-modeling-materialize-view",+ "workflow_id": "materialize-view-abc-def",+ "workflow_run_id": "abc-run-id",+ "log_source": "data_modeling_run",+ "log_source_id": "019df430-79ff-0000-4434-e9fc02f7216b",+ }++ rendered = renderer(logger=cast(Logger, None), name="debug", event_dict=event_dict)++ assert rendered["produce_message"] is not None+ assert rendered["write_message"] is not None++ produced = rendered["produce_message"].decode("utf-8")+ assert json.loads(produced)["message"] == "Running clickhouse query"+ assert "secret_column" not in produced+ assert "secret_column" in rendered["write_message"]++def test_log_messages_renderer_appends_resource_to_message():"""`resource_name` / `resource` in the event dict gets appended to the produce message text.diff --git a/posthog/temporal/tests/data_modeling/conftest.py b/posthog/temporal/tests/data_modeling/conftest.pyindex d8db08af9735..d491a9aafb9f 100644--- a/posthog/temporal/tests/data_modeling/conftest.py+++ b/posthog/temporal/tests/data_modeling/conftest.py@@ -15,6 +15,9 @@ import pytest_asyncio# fixture setup. Importing the chain here — while structlog is still the default config —# runs that module-level code safely and caches it, so the signal's lazy import is a no-op.import posthog.api.advanced_activity_logs # noqa: F401, E402 — warm import; see comment above+from posthog.sync import database_sync_to_async++from products.data_modeling.backend.facade.models import DAG, DataModelingJob, DataWarehouseSavedQuery, Node, NodeTypeTEST_ROOT_BUCKET = "test-data-modeling"SESSION = aioboto3.Session()@@ -42,3 +45,47 @@ async def minio_client(bucket_name):await client.create_bucket(Bucket=bucket_name)yield client+++@pytest_asyncio.fixture+async def asaved_query(ateam, auser):+ query = await database_sync_to_async(DataWarehouseSavedQuery.objects.create)(+ team=ateam,+ name="test_model",+ query={"query": "SELECT 1", "kind": "HogQLQuery"},+ created_by=auser,+ )+ yield query+ await database_sync_to_async(query.delete)()+++@pytest_asyncio.fixture+async def adag(ateam):+ dag = await database_sync_to_async(DAG.objects.create)(team=ateam, name="test-dag")+ yield dag+ await database_sync_to_async(dag.delete)()+++@pytest_asyncio.fixture+async def anode(ateam, asaved_query, adag):+ node = await database_sync_to_async(Node.objects.create)(+ team=ateam,+ saved_query=asaved_query,+ dag=adag,+ name="test_model",+ type=NodeType.MAT_VIEW,+ )+ yield node+ await database_sync_to_async(node.delete)()+++@pytest_asyncio.fixture+async def ajob(ateam, asaved_query):+ job = await database_sync_to_async(DataModelingJob.objects.create)(+ team=ateam,+ saved_query=asaved_query,+ status=DataModelingJob.Status.RUNNING,+ workflow_id="test-workflow",+ )+ yield job+ await database_sync_to_async(job.delete)()diff --git a/posthog/temporal/tests/data_modeling/test_log_routing.py b/posthog/temporal/tests/data_modeling/test_log_routing.pynew file mode 100644index 000000000000..34ab8253b1e6--- /dev/null+++ b/posthog/temporal/tests/data_modeling/test_log_routing.py@@ -0,0 +1,180 @@+import json+import uuid+import asyncio+import dataclasses+from typing import TYPE_CHECKING, cast++import pytest++from django.test import override_settings++import pytest_asyncio+import temporalio.testing++from posthog.temporal.common.logger import BACKGROUND_LOGGER_TASKS, configure_logger+from posthog.temporal.data_modeling.activities import (+ CreateDataModelingJobInputs,+ FailMaterializationInputs,+ SucceedMaterializationInputs,+ create_data_modeling_job_activity,+ fail_materialization_activity,+ succeed_materialization_activity,+)++if TYPE_CHECKING:+ from posthog.kafka_client.client import _AsyncKafkaProducer++pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]+++class QueueCapture(asyncio.Queue[bytes]):+ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ self.entries: list[bytes] = []++ def put_nowait(self, item: bytes) -> None:+ self.entries.append(item)+ super().put_nowait(item)+++class NoopKafkaProducer:+ """Consumes produced log messages without a Kafka broker; capture happens at the queue."""++ async def produce(self, *, topic, data, key=None, value_serializer=None) -> None:+ return None++ async def flush(self, timeout=None) -> None:+ return None++ async def close(self) -> None:+ return None+++class ActivityInfo:+ activity_id: str+ activity_type: str+ attempt: int+ task_queue: str+ workflow_id: str+ workflow_namespace: str+ workflow_run_id: str+ workflow_type: str+++@pytest_asyncio.fixture+async def queue():+ return QueueCapture(maxsize=0)+++@pytest_asyncio.fixture(autouse=True)+async def configure_produce_capture(queue):+ loop = asyncio.get_running_loop()+ with override_settings(TEST=False, DEBUG=False):+ configure_logger(+ queue=queue,+ producer=cast("_AsyncKafkaProducer", NoopKafkaProducer()),+ cache_logger_on_first_use=False,+ loop=loop,+ raise_on_producer_error=True,+ )++ yield++ for task in BACKGROUND_LOGGER_TASKS.values():+ task.cancel()+ if BACKGROUND_LOGGER_TASKS:+ await asyncio.wait(BACKGROUND_LOGGER_TASKS.values())+++def v2_activity_environment():+ env = temporalio.testing.ActivityEnvironment()+ env.info = ActivityInfo( # type: ignore[assignment]+ activity_id=str(uuid.uuid4()),+ activity_type="test-activity",+ attempt=1,+ task_queue="data-modeling-task-queue",+ workflow_id=f"materialize-view-{uuid.uuid4()}-{uuid.uuid4()}",+ workflow_namespace="test",+ workflow_type="data-modeling-materialize-view",+ workflow_run_id=str(uuid.uuid4()),+ )+ return env+++async def _wait_for_queue_entries(queue: QueueCapture) -> None:+ for _ in range(100):+ if queue.entries:+ return+ await asyncio.sleep(0)+ raise TimeoutError("Timed out waiting for produced log messages")++[email protected]("activity_case", ["create_job", "succeed", "fail"])+async def test_v2_activity_log_lines_are_routed_to_the_saved_query(+ activity_case, v2_activity_environment, queue, ateam, adag, anode, asaved_query, ajob+):+ if activity_case == "create_job":+ await v2_activity_environment.run(+ create_data_modeling_job_activity,+ CreateDataModelingJobInputs(team_id=ateam.pk, node_id=str(anode.id), dag_id=str(adag.id)),+ )+ elif activity_case == "succeed":+ await v2_activity_environment.run(+ succeed_materialization_activity,+ SucceedMaterializationInputs(+ team_id=ateam.pk,+ node_id=str(anode.id),+ dag_id=str(adag.id),+ job_id=str(ajob.id),+ row_count=1,+ duration_seconds=1.0,+ ),+ )+ else:+ await v2_activity_environment.run(+ fail_materialization_activity,+ FailMaterializationInputs(+ team_id=ateam.pk,+ node_id=str(anode.id),+ dag_id=str(adag.id),+ job_id=str(ajob.id),+ error="Something broke",+ update_node=False,+ ),+ )+ await _wait_for_queue_entries(queue)++ messages = [json.loads(entry.decode("utf-8")) for entry in queue.entries]+ routed_messages = [m for m in messages if m["log_source"] == "data_modeling_run"]+ assert len(routed_messages) >= 1+ for message in routed_messages:+ assert message["log_source_id"] == str(asaved_query.id)+ assert message["instance_id"] == v2_activity_environment.info.workflow_run_id+ assert message["team_id"] == ateam.pk+++async def test_failure_logs_do_not_expose_clickhouse_hostnames(+ v2_activity_environment, queue, ateam, adag, anode, asaved_query, ajob+):+ await v2_activity_environment.run(+ fail_materialization_activity,+ FailMaterializationInputs(+ team_id=ateam.pk,+ node_id=str(anode.id),+ dag_id=str(adag.id),+ job_id=str(ajob.id),+ error="Code 241. Memory limit exceeded (from chi-posthog-data-0-0.svc.cluster.local:9000)",+ update_node=False,+ ),+ )+ await _wait_for_queue_entries(queue)++ routed_messages = [+ json.loads(entry.decode("utf-8")) for entry in queue.entries if json.loads(entry.decode("utf-8"))["log_source"]+ ]+ assert len(routed_messages) >= 1+ for message in routed_messages:+ assert "svc.cluster.local" not in message["message"]+ assert any("Memory limit exceeded" in message["message"] for message in routed_messages)diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.pyindex 56a43d84fded..a83ef5a712c0 100644--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py@@ -12,7 +12,6 @@ from django.test import override_settingsimport pyarrow as paimport deltalake-import pytest_asyncioimport pyarrow.parquet as pqfrom posthog.hogql.resolver import ResolverFactory@@ -41,7 +40,6 @@ from posthog.temporal.data_modeling.activities.materialize_view import (from products.data_modeling.backend.facade.api import compute_enrichment_hashfrom products.data_modeling.backend.facade.modeling import bounded_resolver_factory_for_viewfrom products.data_modeling.backend.facade.models import (- DAG,DataModelingJob,DataModelingJobEngine,DataModelingJobStatus,@@ -55,50 +53,6 @@ from products.warehouse_sources.backend.facade.models import DataWarehouseTablepytestmark = [pytest.mark.asyncio, pytest.mark.django_db]-@pytest_asyncio.fixture-async def asaved_query(ateam, auser):- query = await database_sync_to_async(DataWarehouseSavedQuery.objects.create)(- team=ateam,- name="test_model",- query={"query": "SELECT 1", "kind": "HogQLQuery"},- created_by=auser,- )- yield query- await database_sync_to_async(query.delete)()---@pytest_asyncio.fixture-async def adag(ateam):- dag = await database_sync_to_async(DAG.objects.create)(team=ateam, name="test-dag")- yield dag- await database_sync_to_async(dag.delete)()---@pytest_asyncio.fixture-async def anode(ateam, asaved_query, adag):- node = await database_sync_to_async(Node.objects.create)(- team=ateam,- saved_query=asaved_query,- dag=adag,- name="test_model",- type=NodeType.MAT_VIEW,- )- yield node- await database_sync_to_async(node.delete)()---@pytest_asyncio.fixture-async def ajob(ateam, asaved_query):- job = await database_sync_to_async(DataModelingJob.objects.create)(- team=ateam,- saved_query=asaved_query,- status=DataModelingJob.Status.RUNNING,- workflow_id="test-workflow",- )- yield job- await database_sync_to_async(job.delete)()--async def _make_job(ateam, saved_query, status, *, engine=DataModelingJobEngine.CLICKHOUSE, error=None):return await database_sync_to_async(DataModelingJob.objects.create)(team=ateam, saved_query=saved_query, status=status, engine=engine, error=errordiff --git a/products/data_modeling/backend/logic/node_materialization.py b/products/data_modeling/backend/logic/node_materialization.pyindex fa36c412d6dc..496dc2c94675 100644--- a/products/data_modeling/backend/logic/node_materialization.py+++ b/products/data_modeling/backend/logic/node_materialization.py@@ -1,6 +1,6 @@import asynciofrom dataclasses import asdict-from datetime import timedelta+from datetime import UTC, datetime, timedeltafrom uuid import uuid4from django.conf import settings@@ -41,7 +41,10 @@ def start_node_materialization(node: Node, *, is_v2: bool) -> None:select=[Selector(label=str(node.saved_query_id), ancestors=0, descendants=0)],)workflow_name = "data-modeling-run"- workflow_id = f"data-modeling-run-{node.id}-{uuid4()}"+ # Mirror the scheduled-run id shape ({saved_query_id}-{iso timestamp}) so+ # resolve_log_source can recover the saved query id and the run's logs show up+ # in the materialization history UI.+ workflow_id = f"{node.saved_query_id}-{datetime.now(UTC).isoformat()}"temporal = sync_connect()asyncio.run(diff --git a/products/data_modeling/backend/tests/api/test_node_api.py b/products/data_modeling/backend/tests/api/test_node_api.pyindex df9c78196813..bd72446a8a90 100644--- a/products/data_modeling/backend/tests/api/test_node_api.py+++ b/products/data_modeling/backend/tests/api/test_node_api.py@@ -9,6 +9,7 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.models import Team+from posthog.temporal.common.logger import resolve_log_sourcefrom products.data_modeling.backend.logic.node_frequency import set_declared_targetfrom products.data_modeling.backend.logic.node_suspension import mark_node_suspended, suspension_state@@ -238,6 +239,14 @@ class TestNodeViewSet(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)mock_client.start_workflow.assert_called_once()+ # The workflow id must resolve back to the saved query id, or the run's log lines+ # detach from the materialization history UI (which queries by saved query id).+ workflow_id = mock_client.start_workflow.call_args.kwargs["id"]+ self.assertEqual(+ resolve_log_source("data-modeling-run", workflow_id),+ ("data_modeling_run", str(self.saved_query.id)),+ )+def _suspend(self, node: Node) -> None:mark_node_suspended(node, engine="clickhouse", reason="boom", job_id=str(uuid4()), fingerprint=None)node.save()