: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
feat(dags): daily rollup of warehouse object reads (#109211)
Thiago Salvatore0340d327c30d
diff --git a/posthog/dags/common/resources.py b/posthog/dags/common/resources.pyindex 6710d690d41e..7148fe30f847 100644--- a/posthog/dags/common/resources.py+++ b/posthog/dags/common/resources.py@@ -111,9 +111,10 @@ class ClickhouseClusterResource(dagster.ConfigurableResource):)-class OpsClickhouseClusterResource(dagster.ConfigurableResource):+class SatelliteClickhouseClusterResource(dagster.ConfigurableResource):max_execution_time: intmax_memory_usage: int+ satellite_cluster: str# OPS is discoverable only from the migrations host/cluster: satellite discovery runs# clusterAllReplicas(ops, system.clusters) WHERE cluster = <migrations cluster>, which the default@@ -126,7 +127,7 @@ class OpsClickhouseClusterResource(dagster.ConfigurableResource):context.log,host=self.host,cluster=self.cluster,- satellite_clusters=[settings.CLICKHOUSE_OPS_CLUSTER],+ satellite_clusters=[self.satellite_cluster],client_settings={"max_execution_time": str(self.max_execution_time),"max_memory_usage": str(self.max_memory_usage),@@ -142,6 +143,10 @@ class OpsClickhouseClusterResource(dagster.ConfigurableResource):)+class OpsClickhouseClusterResource(SatelliteClickhouseClusterResource):+ satellite_cluster: str = settings.CLICKHOUSE_OPS_CLUSTER++class BackupsClickhouseClusterResource(dagster.ConfigurableResource):"""ClickHouse cluster resource that connects as the dedicated 'backups' user.diff --git a/posthog/dags/locations/clickhouse.py b/posthog/dags/locations/clickhouse.pyindex f4a46dee4ee1..fd0e019fc88d 100644--- a/posthog/dags/locations/clickhouse.py+++ b/posthog/dags/locations/clickhouse.py@@ -18,6 +18,7 @@ from posthog.dags import (person_pg_cleanup_drain,postgres_to_clickhouse_etl,property_definitions,+ warehouse_object_reads_daily,)from . import loggers, resources@@ -54,6 +55,7 @@ defs = dagster.Definitions(data_deletion_requests.verify_queued_deletion_requests_job,data_deletion_requests.auto_approve_deletion_requests_job,part_breaker.break_oversized_parts,+ warehouse_object_reads_daily.warehouse_object_reads_daily_job,],schedules=[export_query_log_archive_to_s3.query_log_archive_export_schedule,@@ -67,6 +69,7 @@ defs = dagster.Definitions(backups.incremental_non_sharded_backup_schedule,part_breaker.break_oversized_parts_schedule,data_deletion_requests.auto_approve_deletion_requests_schedule,+ warehouse_object_reads_daily.warehouse_object_reads_daily_schedule,],sensors=[clickhouse_cleanup.run_cleanup_sweep_after_deletes,diff --git a/posthog/dags/tests/test_warehouse_object_reads_daily.py b/posthog/dags/tests/test_warehouse_object_reads_daily.pynew file mode 100644index 000000000000..c47e2f585f63--- /dev/null+++ b/posthog/dags/tests/test_warehouse_object_reads_daily.py@@ -0,0 +1,241 @@+import json+import uuid+from collections.abc import Iterator+from datetime import date, datetime, time, timedelta+from functools import partial+from typing import Any++import pytest+from unittest.mock import patch++import dagster+from clickhouse_driver import Client++from posthog.clickhouse.client.connection import NodeRole+from posthog.clickhouse.cluster import ClickhouseCluster+from posthog.clickhouse.query_log_archive import SHARDED_QUERY_LOG_ARCHIVE_TABLE+from posthog.clickhouse.warehouse_object_reads import WAREHOUSE_OBJECT_READS_DAILY_TABLE+from posthog.dags.warehouse_object_reads_daily import (+ ROLLUP_START_DATE,+ insert_rollup_into_staging,+ warehouse_object_reads_daily_job,+ warehouse_object_reads_daily_schedule,+)+from posthog.models import Team++from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery+from products.warehouse_sources.backend.facade.models import DataWarehouseTable++ROLLUP_MODULE = "posthog.dags.warehouse_object_reads_daily"++[email protected](autouse=True)+def rollup_on_the_local_data_node() -> Iterator[None]:+ with patch("posthog.dags.warehouse_object_reads_daily.ROLLUP_NODE_ROLE", NodeRole.DATA):+ yield+++def rollup_day() -> date:+ return date.today() - timedelta(days=2)+++def archive_row(+ team: Team,+ day: date,+ *,+ log_comment: dict[str, Any],+ is_initial_query: bool = True,+ duration_ms: int = 100,+ read_bytes: int = 1000,+) -> dict[str, Any]:+ query_id = str(uuid.uuid4())+ return {+ "team_id": team.pk,+ "query_id": query_id,+ "initial_query_id": query_id,+ "is_initial_query": int(is_initial_query),+ "type": "QueryFinish",+ "event_date": day,+ "event_time": datetime.combine(day, time(hour=12)),+ "query_duration_ms": duration_ms,+ "read_bytes": read_bytes,+ "log_comment": json.dumps({"team_id": team.pk, **log_comment}),+ }+++def read_comment(client_query_id: str, user_id: int, **tags: Any) -> dict[str, Any]:+ return {+ "kind": "request",+ "product": "sql_editor",+ "client_query_id": client_query_id,+ "user_id": user_id,+ **tags,+ }+++def read_tags(+ *, saved_query_ids: list[str], warehouse_table_ids: list[str], directly_read_ids: list[str]+) -> dict[str, list[str]]:+ return {+ "saved_query_ids": saved_query_ids,+ "warehouse_table_ids": warehouse_table_ids,+ "directly_read_ids": directly_read_ids,+ }+++def refresh_comment(workflow_id: str, materialized_saved_query_id: str) -> dict[str, Any]:+ return {+ "kind": "temporal",+ "product": "warehouse",+ "feature": "data_modeling",+ "temporal": {"workflow_id": workflow_id},+ "materialized_saved_query_id": materialized_saved_query_id,+ }+++def clear_archive(client: Client) -> None:+ client.execute(f"TRUNCATE TABLE {SHARDED_QUERY_LOG_ARCHIVE_TABLE}")+++def run_rollup(cluster: ClickhouseCluster, day: date, *, succeeds: bool = True) -> None:+ result = warehouse_object_reads_daily_job.execute_in_process(+ partition_key=day.isoformat(), resources={"cluster": cluster}, raise_on_error=False+ )+ assert result.success is succeeds+++def insert_archive_rows(rows: list[dict[str, Any]], client: Client) -> None:+ columns = list(rows[0])+ for row in rows:+ client.execute(+ f"INSERT INTO {SHARDED_QUERY_LOG_ARCHIVE_TABLE} ({', '.join(columns)}) "+ f"SELECT {', '.join(f'%({column})s' for column in columns)}",+ row,+ )+++def read_rollup(team_id: int, day: date, subject_ids: list[str], client: Client) -> list[tuple]:+ return sorted(+ client.execute(+ f"""+ SELECT read_kind, subject_kind, subject_id, workflow_id, read_alone,+ uniqMerge(requests), uniqMerge(users), sum(read_count), sum(duration_ms_sum), sum(read_bytes_sum)+ FROM {WAREHOUSE_OBJECT_READS_DAILY_TABLE}+ WHERE team_id = %(team_id)s AND day = %(day)s AND subject_id IN %(subject_ids)s+ GROUP BY read_kind, subject_kind, subject_id, workflow_id, read_alone+ """,+ {"team_id": team_id, "day": day, "subject_ids": subject_ids},+ )+ )+++def test_rollup_counts_view_and_table_reads_and_refreshes_and_replaces_its_partition_on_rerun(+ cluster: ClickhouseCluster, team: Team+) -> None:+ day = rollup_day()+ orders = DataWarehouseSavedQuery.objects.create(+ team=team, name="orders", query={"kind": "HogQLQuery", "query": "SELECT 1"}+ )+ customers = DataWarehouseSavedQuery.objects.create(+ team=team, name="customers", query={"kind": "HogQLQuery", "query": "SELECT 1"}+ )+ stripe_charges = DataWarehouseTable.objects.create(+ team=team, name="stripe_charges", format="Parquet", url_pattern="https://example.com/stripe_charges"+ )+ hubspot_contacts = DataWarehouseTable.objects.create(+ team=team, name="hubspot_contacts", format="Parquet", url_pattern="https://example.com/hubspot_contacts"+ )+ refresh_workflow_id = f"materialize-view-{uuid.uuid4()}"++ view_id, nested_view_id = str(orders.id), str(customers.id)+ table_id, joined_table_id = str(stripe_charges.id), str(hubspot_contacts.id)+ from_view = read_tags(+ saved_query_ids=[view_id, nested_view_id], warehouse_table_ids=[table_id], directly_read_ids=[view_id]+ )+ from_view_joined_to_table = read_tags(+ saved_query_ids=[view_id, nested_view_id],+ warehouse_table_ids=[table_id, joined_table_id],+ directly_read_ids=[view_id, joined_table_id],+ )+ from_table = read_tags(saved_query_ids=[], warehouse_table_ids=[table_id], directly_read_ids=[table_id])+ untagged_view_read = {"saved_query_ids": [view_id]}+ rows = [+ archive_row(team, day, log_comment=read_comment("shared", 7, **from_view), duration_ms=100),+ archive_row(team, day, log_comment=read_comment("shared", 7, **from_view), duration_ms=300),+ archive_row(team, day, log_comment=read_comment("joined", 8, **from_view_joined_to_table), duration_ms=50),+ archive_row(team, day, log_comment=read_comment("table", 9, **from_table), duration_ms=20),+ archive_row(team, day, log_comment=read_comment("untagged", 7, **untagged_view_read), duration_ms=10),+ archive_row(team, day, log_comment=read_comment("staff", 9, is_impersonated=True, **from_view)),+ archive_row(team, day, log_comment=read_comment("leaf", 7, **from_view), is_initial_query=False),+ archive_row(+ team,+ day,+ log_comment=refresh_comment(refresh_workflow_id, nested_view_id),+ duration_ms=2000,+ read_bytes=50000,+ ),+ ]+ cluster.any_host(partial(insert_archive_rows, rows)).result()++ expected = sorted(+ [+ ("read", "saved_query", view_id, "", True, 1, 1, 2, 400, 2000),+ ("read", "saved_query", view_id, "", False, 2, 2, 2, 60, 2000),+ ("read", "saved_query", nested_view_id, "", False, 2, 2, 3, 450, 3000),+ ("read", "table", table_id, "", False, 2, 2, 3, 450, 3000),+ ("read", "table", table_id, "", True, 1, 1, 1, 20, 1000),+ ("read", "table", joined_table_id, "", False, 1, 1, 1, 50, 1000),+ ("refresh", "saved_query", nested_view_id, refresh_workflow_id, False, 1, 1, 1, 2000, 50000),+ ]+ )+ subject_ids = [view_id, nested_view_id, table_id, joined_table_id]+ run_rollup(cluster, day)+ assert cluster.any_host(partial(read_rollup, team.pk, day, subject_ids)).result() == expected++ def insert_twice(*args: Any) -> None:+ insert_rollup_into_staging(*args)+ insert_rollup_into_staging(*args)++ with patch(f"{ROLLUP_MODULE}.insert_rollup_into_staging", side_effect=insert_twice):+ run_rollup(cluster, day)+ assert cluster.any_host(partial(read_rollup, team.pk, day, subject_ids)).result() == expected++ with patch(f"{ROLLUP_MODULE}.insert_rollup_into_staging"):+ run_rollup(cluster, day, succeeds=False)+ assert cluster.any_host(partial(read_rollup, team.pk, day, subject_ids)).result() == expected++ cluster.any_host(clear_archive).result()+ run_rollup(cluster, day)+ assert cluster.any_host(partial(read_rollup, team.pk, day, subject_ids)).result() == []+++def test_rollup_of_a_day_without_archive_rows_succeeds(cluster: ClickhouseCluster) -> None:+ result = warehouse_object_reads_daily_job.execute_in_process(+ partition_key=ROLLUP_START_DATE, resources={"cluster": cluster}+ )++ assert result.success+++def test_schedule_runs_after_the_archive_day_closes() -> None:+ assert isinstance(warehouse_object_reads_daily_schedule, dagster.ScheduleDefinition)+ assert warehouse_object_reads_daily_schedule.cron_schedule == "0 7 * * *"+++def test_rollup_fails_before_touching_staging_while_another_run_executes(cluster: ClickhouseCluster) -> None:+ instance = dagster.DagsterInstance.ephemeral()+ other_run = instance.create_run_for_job(+ job_def=warehouse_object_reads_daily_job, status=dagster.DagsterRunStatus.STARTED+ )++ with patch("posthog.dags.warehouse_object_reads_daily.recreate_staging_table") as recreate_staging_table:+ result = warehouse_object_reads_daily_job.execute_in_process(+ partition_key=ROLLUP_START_DATE, resources={"cluster": cluster}, instance=instance, raise_on_error=False+ )++ assert not result.success+ assert other_run.run_id in str(result.all_events)+ recreate_staging_table.assert_not_called()diff --git a/posthog/dags/warehouse_object_reads_daily.py b/posthog/dags/warehouse_object_reads_daily.pynew file mode 100644index 000000000000..fd10dc19232c--- /dev/null+++ b/posthog/dags/warehouse_object_reads_daily.py@@ -0,0 +1,294 @@+from datetime import UTC, date, datetime, time, timedelta++from django.conf import settings++import dagster+from clickhouse_driver import Client++from posthog.clickhouse.client.connection import NodeRole+from posthog.clickhouse.cluster import ClickhouseCluster+from posthog.clickhouse.query_tagging import Feature+from posthog.clickhouse.warehouse_object_reads import (+ REPLACE_SHARDED_WAREHOUSE_OBJECT_READS_DAILY_STAGING_TABLE_SQL,+ SHARDED_WAREHOUSE_OBJECT_READS_DAILY_STAGING_TABLE,+ SHARDED_WAREHOUSE_OBJECT_READS_DAILY_TABLE,+ SORT_KEY_COLUMNS,+ ReadKind,+ SubjectKind,+)+from posthog.dags.common import JobOwners, settings_with_log_comment+from posthog.dags.common.common import EXECUTING_RUN_STATUSES, describe_runs+from posthog.dags.common.resources import SatelliteClickhouseClusterResource++from products.web_analytics.dags.web_preaggregated_utils import (+ get_partitions,+ recreate_staging_table,+ swap_partitions_from_staging,+ sync_partitions_on_replicas,+)++QUERY_LOG_ARCHIVE_TABLE = "query_log_archive"+TEMPORAL_QUERY_KIND = "temporal"+QUERY_FINISH_TYPE = "QueryFinish"+MAX_EXECUTION_TIME_SECONDS = 600+ONE_GIB = 1024**3+MAX_MEMORY_USAGE_BYTES = 8 * ONE_GIB+SPILL_GROUP_BY_AFTER_BYTES = 2 * ONE_GIB+MAX_THREADS = 8+ROLLUP_NODE_ROLE = NodeRole.AUX+ROLLUP_START_DATE = "2026-09-17"+SCHEDULE_HOUR_UTC = 7+CONCURRENCY_TAG = {"warehouse_object_reads_backfill_concurrency": "warehouse_object_reads_v1"}+MAX_RUNTIME_SECONDS = 60 * 60+STUCK_RUN_AGE = timedelta(hours=3)++PARTITION_ID_FORMAT = "%Y%m%d"+READ_SUBJECT_ID = "read_subject_id"+DIRECTLY_READ_IDS = "log_comment.directly_read_ids::Array(String)"+MATERIALIZED_SAVED_QUERY_ID = "log_comment.materialized_saved_query_id::String"+SUBJECT_ID_TAGS = {+ SubjectKind.SAVED_QUERY: "saved_query_ids",+ SubjectKind.TABLE: "warehouse_table_ids",+}++AGGREGATE_COLUMNS = (+ "uniqState(request_id) AS requests",+ "uniqState(user_id) AS users",+ "count() AS read_count",+ "sum(query_duration_ms) AS duration_ms_sum",+ "sum(read_bytes) AS read_bytes_sum",+ "quantilesState(0.5, 0.9)(query_duration_ms) AS duration_ms_quantiles",+ "quantilesState(0.5, 0.9)(read_bytes) AS read_bytes_quantiles",+ "max(event_time) AS max_event_time",+)++ARCHIVE_ROW_FILTER = f"""event_date = %(day)s+ AND event_time >= %(day_start)s AND event_time < %(day_end)s+ AND is_initial_query+ AND type = '{QUERY_FINISH_TYPE}'+ AND NOT lc_is_impersonated"""++REFRESH_ROW_FILTER = f"""lc_feature = '{Feature.DATA_MODELING.value}'+ AND lc_kind = '{TEMPORAL_QUERY_KIND}'+ AND {MATERIALIZED_SAVED_QUERY_ID} != ''"""++daily_partitions = dagster.DailyPartitionsDefinition(start_date=ROLLUP_START_DATE, timezone="UTC")+++def _archive_branch_sql(+ *,+ read_kind: ReadKind,+ subject_kind: SubjectKind,+ subject_id_column: str,+ workflow_id_column: str,+ read_alone_expression: str,+ array_join: str,+ extra_filter: str,+) -> str:+ return f"""+ SELECT+ team_id,+ toDate(%(day)s) AS day,+ '{read_kind.value}' AS read_kind,+ '{subject_kind.value}' AS subject_kind,+ {subject_id_column} AS subject_id,+ {workflow_id_column} AS workflow_id,+ lc_kind,+ lc_product,+ lc_feature,+ lc_access_method,+ log_comment.source::String AS source,+ log_comment.scene::String AS scene,+ lc_user_id > 0 AS has_user_id,+ if(lc_client_query_id = '', query_id, lc_client_query_id) AS request_id,+ lc_user_id AS user_id,+ query_duration_ms,+ read_bytes,+ event_time,+ {read_alone_expression} AS read_alone+ FROM {QUERY_LOG_ARCHIVE_TABLE}+ {array_join}+ WHERE {ARCHIVE_ROW_FILTER}{extra_filter}"""+++def _subject_reads_sql(subject_kind: SubjectKind) -> str:+ return _archive_branch_sql(+ read_kind=ReadKind.READ,+ subject_kind=subject_kind,+ subject_id_column=READ_SUBJECT_ID,+ workflow_id_column="''",+ read_alone_expression=f"{DIRECTLY_READ_IDS} = [{READ_SUBJECT_ID}]",+ array_join=f"ARRAY JOIN log_comment.{SUBJECT_ID_TAGS[subject_kind]}::Array(String) AS {READ_SUBJECT_ID}",+ extra_filter="",+ )+++REFRESH_READS_SQL = _archive_branch_sql(+ read_kind=ReadKind.REFRESH,+ subject_kind=SubjectKind.SAVED_QUERY,+ subject_id_column=MATERIALIZED_SAVED_QUERY_ID,+ workflow_id_column="lc_temporal__workflow_id",+ read_alone_expression="false",+ array_join="",+ extra_filter=f"\n AND {REFRESH_ROW_FILTER}",+)++ROLLUP_SOURCE_SQL = f"""{_subject_reads_sql(SubjectKind.SAVED_QUERY)}+UNION ALL{_subject_reads_sql(SubjectKind.TABLE)}+UNION ALL{REFRESH_READS_SQL}+"""++INSERT_ROLLUP_SQL = f"""+INSERT INTO {SHARDED_WAREHOUSE_OBJECT_READS_DAILY_STAGING_TABLE}+SELECT+ {", ".join(SORT_KEY_COLUMNS)},+ {", ".join(AGGREGATE_COLUMNS)}+FROM ({ROLLUP_SOURCE_SQL})+GROUP BY {", ".join(SORT_KEY_COLUMNS)}+"""++COUNT_ROLLUP_SOURCE_ROWS_SQL = f"SELECT count() FROM ({ROLLUP_SOURCE_SQL})"++TRUNCATE_STAGING_SQL = f"TRUNCATE TABLE {SHARDED_WAREHOUSE_OBJECT_READS_DAILY_STAGING_TABLE}"+++def _day_query_parameters(day: date) -> dict[str, date | datetime | str]:+ day_start = datetime.combine(day, time.min)+ return {+ "day": day,+ "day_start": day_start,+ "day_end": day_start + timedelta(days=1),+ }+++def _rollup_query_settings(context: dagster.OpExecutionContext) -> dict[str, str | int]:+ return {+ **settings_with_log_comment(context),+ "max_bytes_before_external_group_by": SPILL_GROUP_BY_AFTER_BYTES,+ "max_threads": MAX_THREADS,+ }+++def insert_rollup_into_staging(+ context: dagster.OpExecutionContext,+ cluster: ClickhouseCluster,+ day: date,+) -> None:+ def stage_day(client: Client) -> None:+ client.execute(TRUNCATE_STAGING_SQL)+ client.execute(INSERT_ROLLUP_SQL, _day_query_parameters(day), settings=_rollup_query_settings(context))++ cluster.any_host_by_roles(stage_day, [ROLLUP_NODE_ROLE]).result()+++def count_rollup_source_rows(context: dagster.OpExecutionContext, cluster: ClickhouseCluster, day: date) -> int:+ [[source_rows]] = cluster.any_host_by_roles(+ lambda client: client.execute(+ COUNT_ROLLUP_SOURCE_ROWS_SQL, _day_query_parameters(day), settings=_rollup_query_settings(context)+ ),+ [ROLLUP_NODE_ROLE],+ ).result()+ return source_rows+++def refuse_to_run_beside_another_rollup(context: dagster.OpExecutionContext) -> None:+ others = describe_runs(+ context.instance,+ (context.job_name,),+ statuses=EXECUTING_RUN_STATUSES,+ created_after=datetime.now(UTC) - STUCK_RUN_AGE,+ exclude_run_id=context.run_id,+ )+ if others:+ raise dagster.Failure(+ description=f"{'; '.join(others)} is executing, and every run shares one staging table. "+ "Wait for that run to finish, then run this day again."+ )+++def publish_day(context: dagster.OpExecutionContext, cluster: ClickhouseCluster, day: date) -> None:+ sync_partitions_on_replicas(+ context, cluster, SHARDED_WAREHOUSE_OBJECT_READS_DAILY_STAGING_TABLE, node_role=ROLLUP_NODE_ROLE+ )+ staged_partitions = get_partitions(+ context,+ cluster,+ SHARDED_WAREHOUSE_OBJECT_READS_DAILY_STAGING_TABLE,+ filter_by_partition_window=True,+ node_role=ROLLUP_NODE_ROLE,+ )+ day_partition = day.strftime(PARTITION_ID_FORMAT)+ if staged_partitions == [day_partition]:+ swap_partitions_from_staging(+ context,+ cluster,+ SHARDED_WAREHOUSE_OBJECT_READS_DAILY_TABLE,+ SHARDED_WAREHOUSE_OBJECT_READS_DAILY_STAGING_TABLE,+ node_role=ROLLUP_NODE_ROLE,+ )+ return+ if staged_partitions:+ raise dagster.Failure(+ description=f"Staging holds partitions {staged_partitions}, not only {day_partition}. "+ "Nothing was published."+ )+ source_rows = count_rollup_source_rows(context, cluster, day)+ if source_rows:+ raise dagster.Failure(+ description=f"The archive has {source_rows} reads for {day}, but staging is empty. "+ "The published day was kept. Run the day again."+ )+ drop_day_partition(cluster, day)+++def drop_day_partition(cluster: ClickhouseCluster, day: date) -> None:+ cluster.any_host_by_roles(+ lambda client: client.execute(+ f"ALTER TABLE {SHARDED_WAREHOUSE_OBJECT_READS_DAILY_TABLE} DROP PARTITION ID %(partition_id)s",+ {"partition_id": day.strftime(PARTITION_ID_FORMAT)},+ ),+ [ROLLUP_NODE_ROLE],+ ).result()+++def rollup_warehouse_object_reads_for_day(+ context: dagster.OpExecutionContext,+ cluster: dagster.ResourceParam[ClickhouseCluster],+) -> None:+ refuse_to_run_beside_another_rollup(context)+ day = date.fromisoformat(context.partition_key)+ context.log.info(f"Rolling up warehouse object reads for {day}")++ recreate_staging_table(+ context,+ cluster,+ SHARDED_WAREHOUSE_OBJECT_READS_DAILY_STAGING_TABLE,+ REPLACE_SHARDED_WAREHOUSE_OBJECT_READS_DAILY_STAGING_TABLE_SQL,+ node_role=ROLLUP_NODE_ROLE,+ )+ insert_rollup_into_staging(context, cluster, day)+ publish_day(context, cluster, day)+++ partitions_def=daily_partitions,+ resource_defs={+ "cluster": SatelliteClickhouseClusterResource(+ satellite_cluster=settings.CLICKHOUSE_AUX_CLUSTER,+ max_execution_time=MAX_EXECUTION_TIME_SECONDS,+ max_memory_usage=MAX_MEMORY_USAGE_BYTES,+ )+ },+ tags={"owner": JobOwners.TEAM_DATA_MODELING.value, "dagster/max_runtime": MAX_RUNTIME_SECONDS, **CONCURRENCY_TAG},+)+def warehouse_object_reads_daily_job() -> None:+ rollup_warehouse_object_reads_for_day()+++warehouse_object_reads_daily_schedule = dagster.build_schedule_from_partitioned_job(+ warehouse_object_reads_daily_job,+ hour_of_day=SCHEDULE_HOUR_UTC,+ minute_of_hour=0,+ default_status=dagster.DefaultScheduleStatus.STOPPED,+)diff --git a/products/web_analytics/dags/web_preaggregated_utils.py b/products/web_analytics/dags/web_preaggregated_utils.pyindex 3b1e61de3b8a..7402a374f4d3 100644--- a/products/web_analytics/dags/web_preaggregated_utils.py+++ b/products/web_analytics/dags/web_preaggregated_utils.py@@ -61,12 +61,13 @@ def merge_clickhouse_settings(base_settings: dict[str, str], extra_settings: Optdef get_partitions(- context: dagster.AssetExecutionContext,+ context: dagster.OpExecutionContext | dagster.AssetExecutionContext,cluster: ClickhouseCluster,table_name: str,filter_by_partition_window: bool = False,+ node_role: NodeRole = NodeRole.DATA,) -> list[str]:- partition_query = f"SELECT DISTINCT partition FROM system.parts WHERE table = '{table_name}' AND active = 1"+ partition_query = f"SELECT DISTINCT partition FROM system.parts WHERE database = currentDatabase() AND table = '{table_name}' AND active = 1"if filter_by_partition_window and context.partition_time_window:start_datetime, end_datetime = context.partition_time_window@@ -75,7 +76,7 @@ def get_partitions(partition_query += f" AND partition >= '{start_partition}' AND partition < '{end_partition}'"partitions_result = cluster.any_host_by_roles(- lambda client: client.execute(partition_query), node_roles=[NodeRole.DATA]+ lambda client: client.execute(partition_query), node_roles=[node_role]).result()context.log.info(f"Found {len(partitions_result)} partitions for {table_name}: {partitions_result}")return sorted([partition_row[0] for partition_row in partitions_result if partition_row and len(partition_row) > 0])@@ -103,26 +104,35 @@ def drop_partitions_for_date_range(def sync_partitions_on_replicas(- context: dagster.AssetExecutionContext, cluster: ClickhouseCluster, target_table: str+ context: dagster.OpExecutionContext | dagster.AssetExecutionContext,+ cluster: ClickhouseCluster,+ target_table: str,+ node_role: NodeRole = NodeRole.DATA,) -> None:context.log.info(f"Syncing replicas for {target_table} on all hosts")cluster.map_hosts_by_roles(lambda client: client.execute(f"SYSTEM SYNC REPLICA {target_table}"),- node_roles=[NodeRole.DATA],+ node_roles=[node_role],).result()def swap_partitions_from_staging(- context: dagster.AssetExecutionContext, cluster: ClickhouseCluster, target_table: str, staging_table: str+ context: dagster.OpExecutionContext | dagster.AssetExecutionContext,+ cluster: ClickhouseCluster,+ target_table: str,+ staging_table: str,+ node_role: NodeRole = NodeRole.DATA,) -> None:- staging_partitions = get_partitions(context, cluster, staging_table, filter_by_partition_window=True)+ staging_partitions = get_partitions(+ context, cluster, staging_table, filter_by_partition_window=True, node_role=node_role+ )context.log.info(f"Swapping partitions {staging_partitions} from {staging_table} to {target_table}")def replace_partition(client, pid):return client.execute(f"ALTER TABLE {target_table} REPLACE PARTITION '{pid}' FROM {staging_table}")for partition_id in staging_partitions:- cluster.any_host_by_roles(partial(replace_partition, pid=partition_id), node_roles=[NodeRole.DATA]).result()+ cluster.any_host_by_roles(partial(replace_partition, pid=partition_id), node_roles=[node_role]).result()def clear_all_staging_partitions(@@ -148,10 +158,11 @@ def clear_all_staging_partitions(def recreate_staging_table(- context: dagster.AssetExecutionContext,+ context: dagster.OpExecutionContext | dagster.AssetExecutionContext,cluster: ClickhouseCluster,staging_table: str,replace_sql_func: Callable[[], str],+ node_role: NodeRole = NodeRole.DATA,) -> None:"""Recreate staging table on all hosts using REPLACE TABLE."""context.log.info(f"Recreating staging table {staging_table}")@@ -160,7 +171,7 @@ def recreate_staging_table(# exact command on each host, otherwise we would get a new uuid per host and replication# woudn't kick in.sql_statement = replace_sql_func()- cluster.map_hosts_by_roles(lambda client: client.execute(sql_statement), node_roles=[NodeRole.DATA]).result()+ cluster.map_hosts_by_roles(lambda client: client.execute(sql_statement), node_roles=[node_role]).result()# Shared config schema for daily processing