Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat: replace exported leaf rows with rollup columns (#75698)

Andy Zhao87d8516a5cad
diff --git a/posthog/dags/export_query_log_archive_to_s3.py b/posthog/dags/export_query_log_archive_to_s3.py
index e06c2f858314..003cda2b27b5 100644
--- a/posthog/dags/export_query_log_archive_to_s3.py
+++ b/posthog/dags/export_query_log_archive_to_s3.py
@@ -96,6 +96,11 @@ KEEP_COLUMNS = (
"lc_modifiers",
)
+# ClickHouse folds leaf read_rows/read_bytes into the initial row via progress packets, but
+# ProfileEvents and memory_usage stay per-host, so each initial row gets its leaves rolled up
+# here where the per-query-id join is cheap; consumers cannot afford it at read time.
+LEAF_SUM_COLUMNS = tuple(column for column in KEEP_COLUMNS if column.startswith("ProfileEvents_"))
+
ONE_GB = 1024 * 1024 * 1024
@@ -131,14 +136,38 @@ def export_query_log_archive_day(
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)
+ leaf_sums = ",\n ".join(f"sum(`{column}`) AS `leaf_{column}`" for column in LEAF_SUM_COLUMNS)
+ leaf_columns = ",\n ".join(f"`leaf_{column}`" for column in LEAF_SUM_COLUMNS)
+ # Leaf rows of a query straddling midnight land on the next event_date, hence the two-day window.
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}')
+ normalizeQuery(lc_query__query) AS hogql_shape,
+ leaf_count,
+ leaf_memory_usage_max,
+ {leaf_columns}
+FROM
+(
+ SELECT
+ {columns},
+ query,
+ lc_query__query
+ FROM {SOURCE_TABLE}
+ WHERE event_date = toDate('{day}') AND is_initial_query
+) AS initial_rows
+LEFT JOIN
+(
+ SELECT
+ initial_query_id AS leaf_initial_query_id,
+ count() AS leaf_count,
+ max(memory_usage) AS leaf_memory_usage_max,
+ {leaf_sums}
+ FROM {SOURCE_TABLE}
+ WHERE event_date >= toDate('{day}') AND event_date <= toDate('{day}') + 1 AND NOT is_initial_query
+ GROUP BY leaf_initial_query_id
+) AS leaf ON initial_rows.query_id = leaf.leaf_initial_query_id
SETTINGS s3_truncate_on_insert = 1, max_threads = {config.max_threads}
"""