: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: export query_log_archive to S3 via Dagster (#65562)
Andy Zhao30ef2ab28aef
diff --git a/posthog/dags/common/resources.py b/posthog/dags/common/resources.pyindex 21af9a0c77a3..23e322b8f65d 100644--- a/posthog/dags/common/resources.py+++ b/posthog/dags/common/resources.py@@ -88,6 +88,34 @@ class ClickhouseClusterResource(dagster.ConfigurableResource):)+class OpsClickhouseClusterResource(dagster.ConfigurableResource):+ max_execution_time: int+ max_memory_usage: int++ host: str = settings.CLICKHOUSE_HOST+ cluster: str | None = None++ def create_resource(self, context: dagster.InitResourceContext) -> ClickhouseCluster:+ return get_cluster(+ context.log,+ host=self.host,+ cluster=self.cluster,+ satellite_clusters=[settings.CLICKHOUSE_OPS_CLUSTER],+ client_settings={+ "max_execution_time": str(self.max_execution_time),+ "max_memory_usage": str(self.max_memory_usage),+ # Socket read timeout must outlast the query's own time cap.+ "receive_timeout": str(self.max_execution_time + 300),+ "mutations_sync": "0",+ },+ retry_policy=RetryPolicy(+ max_attempts=2,+ delay=ExponentialBackoff(20),+ exceptions=_is_retryable_clickhouse_exception,+ ),+ )++class BackupsClickhouseClusterResource(dagster.ConfigurableResource):"""ClickHouse cluster resource that connects as the dedicated 'backups' user.diff --git a/posthog/dags/export_query_log_archive_to_s3.py b/posthog/dags/export_query_log_archive_to_s3.pynew file mode 100644index 000000000000..051dd7f0d794--- /dev/null+++ b/posthog/dags/export_query_log_archive_to_s3.py@@ -0,0 +1,166 @@+import dagster+from clickhouse_driver import Client++from posthog import settings+from posthog.clickhouse.client.connection import NodeRole+from posthog.clickhouse.cluster import ClickhouseCluster+from posthog.dags.common import JobOwners, settings_with_log_comment+from posthog.dags.common.resources import OpsClickhouseClusterResource++SOURCE_TABLE = "posthog.query_log_archive"++KEEP_COLUMNS = (+ "hostname",+ "user",+ "query_id",+ "initial_query_id",+ "is_initial_query",+ "type",+ "event_date",+ "event_time",+ "event_time_microseconds",+ "query_start_time",+ "query_start_time_microseconds",+ "query_duration_ms",+ "read_rows",+ "read_bytes",+ "written_rows",+ "written_bytes",+ "result_rows",+ "result_bytes",+ "memory_usage",+ "peak_threads_usage",+ "current_database",+ "normalized_query_hash",+ "query_kind",+ "exception_code",+ "exception_name",+ "team_id",+ "ProfileEvents_RealTimeMicroseconds",+ "ProfileEvents_OSCPUVirtualTimeMicroseconds",+ "ProfileEvents_S3Clients",+ "ProfileEvents_S3DeleteObjects",+ "ProfileEvents_S3CopyObject",+ "ProfileEvents_S3ListObjects",+ "ProfileEvents_S3HeadObject",+ "ProfileEvents_S3GetObjectAttributes",+ "ProfileEvents_S3CreateMultipartUpload",+ "ProfileEvents_S3UploadPartCopy",+ "ProfileEvents_S3UploadPart",+ "ProfileEvents_S3AbortMultipartUpload",+ "ProfileEvents_S3CompleteMultipartUpload",+ "ProfileEvents_S3PutObject",+ "ProfileEvents_S3GetObject",+ "ProfileEvents_ReadBufferFromS3Bytes",+ "ProfileEvents_WriteBufferFromS3Bytes",+ "lc_workflow",+ "lc_kind",+ "lc_id",+ "lc_route_id",+ "lc_access_method",+ "lc_api_key_mask",+ "lc_query_type",+ "lc_product",+ "lc_chargeable",+ "lc_name",+ "lc_request_name",+ "lc_client_query_id",+ "lc_org_id",+ "lc_user_id",+ "lc_is_impersonated",+ "lc_session_id",+ "lc_dashboard_id",+ "lc_insight_id",+ "lc_cohort_id",+ "lc_batch_export_id",+ "lc_experiment_id",+ "lc_alert_config_id",+ "lc_feature",+ "lc_table_id",+ "lc_warehouse_query",+ "lc_person_on_events_mode",+ "lc_service_name",+ "lc_workload",+ "lc_query__kind",+ "lc_temporal__workflow_namespace",+ "lc_temporal__workflow_type",+ "lc_temporal__workflow_id",+ "lc_temporal__workflow_run_id",+ "lc_temporal__activity_type",+ "lc_temporal__activity_id",+ "lc_temporal__attempt",+ "lc_dagster__job_name",+ "lc_dagster__run_id",+ "lc_dagster__owner",+ "lc_modifiers",+)++ONE_GB = 1024 * 1024 * 1024+++class QueryLogArchiveExportConfig(dagster.Config):+ s3_prefix: str = "query_log_archive"+ s3_bucket: str = settings.QUERY_LOG_ARCHIVE_EXPORT_S3_BUCKET+++daily_partitions = dagster.DailyPartitionsDefinition(+ start_date="2026-01-01",+ timezone="UTC",+ # query_log_archive only retains a few weeks on the source, so older partitions will export+ # empty; that is harmless (idempotent overwrite of one key per day).+)+++def export_query_log_archive_day(+ context: dagster.OpExecutionContext,+ config: QueryLogArchiveExportConfig,+ cluster: dagster.ResourceParam[ClickhouseCluster],+) -> str:+ day = context.partition_key # "YYYY-MM-DD"+ if not config.s3_bucket:+ # No export bucket for this region (e.g. dev); nothing to write to.+ context.log.warning(f"No query_log_archive export bucket configured for this deployment; skipping {day}")+ return f"Skipped {day} (no export bucket)"++ s3_url = f"https://{config.s3_bucket}.s3.amazonaws.com/{config.s3_prefix}/day={day}/data.parquet"+ columns = ",\n ".join(f"`{column}`" for column in KEEP_COLUMNS)+ query = f"""+INSERT INTO FUNCTION s3('{s3_url}', 'Parquet')+SELECT+ {columns},+ normalizeQuery(query) AS query_shape,+ normalizeQuery(lc_query__query) AS hogql_shape+FROM {SOURCE_TABLE}+WHERE event_date = toDate('{day}') AND is_initial_query+SETTINGS s3_truncate_on_insert = 1+"""++ def run(client: Client) -> str:+ [[hostname]] = client.execute("SELECT hostName()")+ context.log.info(f"Exporting {day} -> {s3_url} on OPS host {hostname}")+ client.execute(query, settings=settings_with_log_comment(context))+ return hostname++ # Run once on a single OPS host so the two OPS replicas don't race to write the same S3 key.+ hostname = cluster.any_host_by_role(run, NodeRole.OPS).result()+ context.log.info(f"Exported {day} on {hostname}")+ return f"Exported {day}"+++ partitions_def=daily_partitions,+ resource_defs={+ "cluster": OpsClickhouseClusterResource(max_execution_time=2 * 60 * 60, max_memory_usage=20 * ONE_GB)+ },+ tags={"owner": JobOwners.TEAM_QUERY_PERFORMANCE.value},+)+def export_query_log_archive_to_s3():+ export_query_log_archive_day()+++query_log_archive_export_schedule = dagster.build_schedule_from_partitioned_job(+ export_query_log_archive_to_s3,+ hour_of_day=6,+ minute_of_hour=0,+)diff --git a/posthog/dags/locations/clickhouse.py b/posthog/dags/locations/clickhouse.pyindex 12f2b5977949..e057b7b59fad 100644--- a/posthog/dags/locations/clickhouse.py+++ b/posthog/dags/locations/clickhouse.py@@ -9,6 +9,7 @@ from posthog.dags import (data_deletion_requests,deletes,drop_materialized_column,+ export_query_log_archive_to_s3,export_query_logs_to_s3,fix_missing_person_overrides,fix_person_id_overrides,@@ -36,6 +37,7 @@ defs = dagster.Definitions(drop_materialized_column.drop_materialized_column,deletes.deletes_job,export_query_logs_to_s3.export_query_logs_to_s3,+ export_query_log_archive_to_s3.export_query_log_archive_to_s3,backfill_materialized_column.backfill_materialized_column,fix_missing_person_overrides.fix_missing_person_overrides_job,fix_person_id_overrides.fix_person_id_overrides_job,@@ -52,6 +54,7 @@ defs = dagster.Definitions(],schedules=[export_query_logs_to_s3.query_logs_export_schedule,+ export_query_log_archive_to_s3.query_log_archive_export_schedule,person_overrides.squash_schedule,postgres_to_clickhouse_etl.postgres_to_clickhouse_hourly_schedule,property_definitions.property_definitions_hourly_schedule,diff --git a/posthog/settings/dagster.py b/posthog/settings/dagster.pyindex 09987c689254..7fb6ed7bc3ad 100644--- a/posthog/settings/dagster.py+++ b/posthog/settings/dagster.py@@ -1,8 +1,18 @@import os+from posthog.settings.base_variables import CLOUD_DEPLOYMENT+DAGSTER_S3_BUCKET: str = os.getenv("DAGSTER_S3_BUCKET", "posthog-dags")DAGSTER_DEFAULT_SLACK_ALERTS_CHANNEL: str = os.getenv("DAGSTER_DEFAULT_SLACK_ALERTS_CHANNEL", "#alerts-clickhouse")DAGSTER_DATA_EXPORT_S3_BUCKET: str = os.getenv("DAGSTER_DATA_EXPORT_S3_BUCKET", "dagster-data-export")++_QUERY_LOG_ARCHIVE_EXPORT_BUCKETS = {+ "US": "posthog-query-log-archive-export-us-east-1",+ "EU": "posthog-query-log-archive-export-eu-central-1",+}+QUERY_LOG_ARCHIVE_EXPORT_S3_BUCKET: str = os.getenv(+ "QUERY_LOG_ARCHIVE_EXPORT_S3_BUCKET", _QUERY_LOG_ARCHIVE_EXPORT_BUCKETS.get(CLOUD_DEPLOYMENT or "", "")+)CLICKHOUSE_BACKUPS_BUCKET: str | None = os.getenv("CLICKHOUSE_BACKUPS_BUCKET")CLICKHOUSE_BACKUPS_MAX_BANDWIDTH: int = int(os.getenv("CLICKHOUSE_BACKUPS_MAX_BANDWIDTH", "100000000"))