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.

chore(web-analytics): scaffold preagg tables for goals and frustration (#59979)

Lucas Ricoy58baa55d71e7
diff --git a/posthog/clickhouse/migrations/0263_web_goals_and_frustration_preaggregated.py b/posthog/clickhouse/migrations/0263_web_goals_and_frustration_preaggregated.py
new file mode 100644
index 000000000000..1fa87fb7c2c4
--- /dev/null
+++ b/posthog/clickhouse/migrations/0263_web_goals_and_frustration_preaggregated.py
@@ -0,0 +1,53 @@
+from posthog.clickhouse.client.connection import NodeRole
+from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.clickhouse.preaggregation.web_goals_preaggregated_sql import (
+ DISTRIBUTED_WEB_GOALS_PREAGGREGATED_TABLE_SQL,
+ SHARDED_WEB_GOALS_PREAGGREGATED_TABLE_SQL,
+)
+from posthog.clickhouse.preaggregation.web_stats_frustration_preaggregated_sql import (
+ DISTRIBUTED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE_SQL,
+ SHARDED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE_SQL,
+)
+
+# Both new web-analytics precompute tables ship together as a single
+# foundation drop and are applied atomically. Each table follows the same
+# 3-op AUX/DATA convention used by `0259_web_stats_preaggregated.py` and the
+# other web-analytics precompute migrations:
+#
+# 1. Sharded data table on AUX — keeps the small precompute storage off
+# the main DATA cluster (these tables are never JOINed against events).
+# 2. Distributed read table on DATA — production query path; fan-outs
+# resolve to AUX shards via the engine's `cluster=AUX`.
+# 3. Same distributed table on AUX — lets operators run ad-hoc
+# `SELECT … FROM <table>` directly from an AUX node without bouncing
+# through DATA. Same DDL, no production cost.
+operations = [
+ # ---------------- web_stats_frustration_preaggregated ----------------
+ run_sql_with_exceptions(
+ SHARDED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE_SQL(),
+ node_roles=[NodeRole.AUX],
+ sharded=True,
+ ),
+ run_sql_with_exceptions(
+ DISTRIBUTED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE_SQL(),
+ node_roles=[NodeRole.DATA],
+ ),
+ run_sql_with_exceptions(
+ DISTRIBUTED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE_SQL(),
+ node_roles=[NodeRole.AUX],
+ ),
+ # ---------------- web_goals_preaggregated ----------------
+ run_sql_with_exceptions(
+ SHARDED_WEB_GOALS_PREAGGREGATED_TABLE_SQL(),
+ node_roles=[NodeRole.AUX],
+ sharded=True,
+ ),
+ run_sql_with_exceptions(
+ DISTRIBUTED_WEB_GOALS_PREAGGREGATED_TABLE_SQL(),
+ node_roles=[NodeRole.DATA],
+ ),
+ run_sql_with_exceptions(
+ DISTRIBUTED_WEB_GOALS_PREAGGREGATED_TABLE_SQL(),
+ node_roles=[NodeRole.AUX],
+ ),
+]
diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txt
index 91079858efe4..56b88e5b70fc 100644
--- a/posthog/clickhouse/migrations/max_migration.txt
+++ b/posthog/clickhouse/migrations/max_migration.txt
@@ -1 +1 @@
-0262_property_values_swap_text_index_for_ngrambf
+0263_web_goals_and_frustration_preaggregated
diff --git a/posthog/clickhouse/preaggregation/web_goals_preaggregated_sql.py b/posthog/clickhouse/preaggregation/web_goals_preaggregated_sql.py
new file mode 100644
index 000000000000..27585402e592
--- /dev/null
+++ b/posthog/clickhouse/preaggregation/web_goals_preaggregated_sql.py
@@ -0,0 +1,107 @@
+# Table for storing lazy-precomputed web goals (conversion) aggregates.
+#
+# One row per (team, job, UTC hour, action_id) where action_id is one of the
+# top-5 actions the runner picks at query time
+# (`Action.objects…order_by("pinned_at", "-last_calculated_at")[:5]`). The set
+# of action expressions and IDs is baked into the INSERT AST and therefore the
+# lazy_computation cache key — a different top-5 set yields a different job_id,
+# so storing only the integer `action_id` is enough; the action expression
+# itself doesn't need to live in the row.
+#
+# At read time the response is pivoted back to the runner's column layout
+# (current/previous count + uniq person tuples per action) using
+# `sumStateIf` / `uniqStateIf` keyed by `action_id`.
+
+from django.conf import settings
+
+from posthog.clickhouse.table_engines import Distributed, ReplacingMergeTree, ReplicationScheme
+
+TABLE_BASE_NAME = "web_goals_preaggregated"
+
+
+def DISTRIBUTED_WEB_GOALS_PREAGGREGATED_TABLE():
+ return TABLE_BASE_NAME
+
+
+def SHARDED_WEB_GOALS_PREAGGREGATED_TABLE():
+ return f"sharded_{TABLE_BASE_NAME}"
+
+
+def SHARDED_WEB_GOALS_PREAGGREGATED_TABLE_ENGINE():
+ return ReplacingMergeTree(TABLE_BASE_NAME, replication_scheme=ReplicationScheme.SHARDED, ver="computed_at")
+
+
+WEB_GOALS_PREAGGREGATED_TABLE_BASE_SQL = """
+CREATE TABLE IF NOT EXISTS {table_name}
+(
+ team_id Int64,
+ job_id UUID,
+
+ -- Hourly UTC bucket. Reads filter by [window_start_utc, window_end_utc).
+ time_window_start DateTime64(6, 'UTC'),
+
+ -- Django Action.id of the action this row aggregates. The action expression
+ -- itself is in the INSERT AST (cache-key shaped), not stored here.
+ action_id Int64,
+
+ -- Total match count (sum across sessions in the hour) and unique converting
+ -- persons (HLL-estimated). The runner reads top-5 actions only; this table
+ -- stores exactly that set per the precompute scope.
+ count_state AggregateFunction(sum, Int64),
+ unique_persons_state AggregateFunction(uniq, UUID),
+
+ -- ReplacingMergeTree version column: latest INSERT wins on duplicate ORDER BY keys.
+ computed_at DateTime64(6, 'UTC') DEFAULT now(),
+
+ -- Sub-day precision so the framework can attach TTLs like 15 min for "today".
+ expires_at DateTime64(6, 'UTC') DEFAULT now() + INTERVAL 7 DAY
+) ENGINE = {engine}
+"""
+
+
+def SHARDED_WEB_GOALS_PREAGGREGATED_TABLE_SQL():
+ # Partition by `expires_at` so `ttl_only_drop_parts=1` can drop whole parts
+ # atomically as soon as all rows in them expire. Mixed-TTL writes (15m for
+ # today, 7d for older) land in distinct parts and the short-TTL parts drop
+ # cleanly.
+ #
+ # ORDER BY puts `action_id` ahead of `time_window_start` because the read
+ # pivots metrics per-action and benefits from co-locating rows for a given
+ # action. One `job_id` covers exactly one UTC day, so rows under a matched
+ # job are within the read's window already — `time_window_start` is a
+ # tiebreaker, not a prune key.
+ return (
+ WEB_GOALS_PREAGGREGATED_TABLE_BASE_SQL
+ + """
+PARTITION BY toYYYYMMDD(expires_at)
+ORDER BY (team_id, job_id, action_id, time_window_start)
+TTL toDateTime(expires_at)
+SETTINGS index_granularity=8192, ttl_only_drop_parts = 1
+"""
+ ).format(
+ table_name=SHARDED_WEB_GOALS_PREAGGREGATED_TABLE(),
+ engine=SHARDED_WEB_GOALS_PREAGGREGATED_TABLE_ENGINE(),
+ )
+
+
+def DISTRIBUTED_WEB_GOALS_PREAGGREGATED_TABLE_SQL():
+ return WEB_GOALS_PREAGGREGATED_TABLE_BASE_SQL.format(
+ table_name=DISTRIBUTED_WEB_GOALS_PREAGGREGATED_TABLE(),
+ engine=Distributed(
+ data_table=SHARDED_WEB_GOALS_PREAGGREGATED_TABLE(),
+ sharding_key="sipHash64(job_id)",
+ cluster=settings.CLICKHOUSE_AUX_CLUSTER,
+ ),
+ )
+
+
+def DROP_WEB_GOALS_PREAGGREGATED_TABLE_SQL():
+ return f"DROP TABLE IF EXISTS {DISTRIBUTED_WEB_GOALS_PREAGGREGATED_TABLE()}"
+
+
+def DROP_SHARDED_WEB_GOALS_PREAGGREGATED_TABLE_SQL():
+ return f"DROP TABLE IF EXISTS {SHARDED_WEB_GOALS_PREAGGREGATED_TABLE()} SYNC"
+
+
+def TRUNCATE_WEB_GOALS_PREAGGREGATED_TABLE_SQL():
+ return f"TRUNCATE TABLE IF EXISTS {SHARDED_WEB_GOALS_PREAGGREGATED_TABLE()}"
diff --git a/posthog/clickhouse/preaggregation/web_stats_frustration_preaggregated_sql.py b/posthog/clickhouse/preaggregation/web_stats_frustration_preaggregated_sql.py
new file mode 100644
index 000000000000..9dcc8fd11fb7
--- /dev/null
+++ b/posthog/clickhouse/preaggregation/web_stats_frustration_preaggregated_sql.py
@@ -0,0 +1,110 @@
+# Table for storing lazy-precomputed web stats FRUSTRATION metrics
+# (rage clicks, dead clicks, exceptions).
+#
+# One row per (team, job, UTC hour, breakdown_value). The strategy that drives
+# the frustration tile groups events per session × breakdown_value, then sums
+# the per-session counts across sessions. Each session is attributed to its
+# `min(session.$start_timestamp)` hour; rows from the same hour for the same
+# breakdown_value are summed via `sumMerge` at read time.
+#
+# `breakdown_value` is whatever the runner's `_counts_breakdown_value()` emits
+# (typically the URL pathname for the only breakdown the frustration tile ships
+# today). The choice of `breakdown_by` is encoded into the INSERT AST and
+# therefore into the lazy_computation cache key — different `breakdown_by`
+# values become distinct precompute jobs, so storing the discriminator in the
+# row is unnecessary.
+
+from django.conf import settings
+
+from posthog.clickhouse.table_engines import Distributed, ReplacingMergeTree, ReplicationScheme
+
+TABLE_BASE_NAME = "web_stats_frustration_preaggregated"
+
+
+def DISTRIBUTED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE():
+ return TABLE_BASE_NAME
+
+
+def SHARDED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE():
+ return f"sharded_{TABLE_BASE_NAME}"
+
+
+def SHARDED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE_ENGINE():
+ return ReplacingMergeTree(TABLE_BASE_NAME, replication_scheme=ReplicationScheme.SHARDED, ver="computed_at")
+
+
+WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE_BASE_SQL = """
+CREATE TABLE IF NOT EXISTS {table_name}
+(
+ team_id Int64,
+ job_id UUID,
+
+ -- Hourly UTC bucket. Reads filter by [window_start_utc, window_end_utc).
+ time_window_start DateTime64(6, 'UTC'),
+
+ -- Breakdown value emitted by the strategy (URL path, etc.). The choice of
+ -- `breakdown_by` is part of the cache key, not stored here.
+ breakdown_value String,
+
+ -- Per-hour per-breakdown sums of session-level event counts (matching the
+ -- FRUSTRATION_METRICS_INNER_QUERY semantics: countIf at the session level,
+ -- summed across sessions in the outer query).
+ sum_rage_clicks_state AggregateFunction(sum, Int64),
+ sum_dead_clicks_state AggregateFunction(sum, Int64),
+ sum_errors_state AggregateFunction(sum, Int64),
+
+ -- ReplacingMergeTree version column: latest INSERT wins on duplicate ORDER BY keys.
+ computed_at DateTime64(6, 'UTC') DEFAULT now(),
+
+ -- Sub-day precision so the framework can attach TTLs like 15 min for "today".
+ expires_at DateTime64(6, 'UTC') DEFAULT now() + INTERVAL 7 DAY
+) ENGINE = {engine}
+"""
+
+
+def SHARDED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE_SQL():
+ # Partition by `expires_at` so `ttl_only_drop_parts=1` can drop whole parts
+ # atomically as soon as all rows in them expire. Mixed-TTL writes (15m for
+ # today, 7d for older) land in distinct parts and the short-TTL parts drop
+ # cleanly.
+ #
+ # ORDER BY puts `breakdown_value` ahead of `time_window_start` because the
+ # read query's outer `GROUP BY breakdown_value` benefits from co-locating
+ # rows for a given breakdown. One `job_id` covers exactly one UTC day, so
+ # rows under a matched job are within the read's `[cur_start, cur_end)`
+ # range already — `time_window_start` is a tiebreaker, not a prune key.
+ return (
+ WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE_BASE_SQL
+ + """
+PARTITION BY toYYYYMMDD(expires_at)
+ORDER BY (team_id, job_id, breakdown_value, time_window_start)
+TTL toDateTime(expires_at)
+SETTINGS index_granularity=8192, ttl_only_drop_parts = 1
+"""
+ ).format(
+ table_name=SHARDED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE(),
+ engine=SHARDED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE_ENGINE(),
+ )
+
+
+def DISTRIBUTED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE_SQL():
+ return WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE_BASE_SQL.format(
+ table_name=DISTRIBUTED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE(),
+ engine=Distributed(
+ data_table=SHARDED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE(),
+ sharding_key="sipHash64(job_id)",
+ cluster=settings.CLICKHOUSE_AUX_CLUSTER,
+ ),
+ )
+
+
+def DROP_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE_SQL():
+ return f"DROP TABLE IF EXISTS {DISTRIBUTED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE()}"
+
+
+def DROP_SHARDED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE_SQL():
+ return f"DROP TABLE IF EXISTS {SHARDED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE()} SYNC"
+
+
+def TRUNCATE_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE_SQL():
+ return f"TRUNCATE TABLE IF EXISTS {SHARDED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE()}"
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 91b8993f7a0e..ac024d9c9a71 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -136,7 +136,9 @@ from posthog.hogql.database.schema.web_analytics_preaggregated import (
WebPreAggregatedBouncesTable,
WebPreAggregatedStatsTable,
)
+from posthog.hogql.database.schema.web_goals_preaggregated import WebGoalsPreaggregatedTable
from posthog.hogql.database.schema.web_overview_preaggregated import WebOverviewPreaggregatedTable
+from posthog.hogql.database.schema.web_stats_frustration_preaggregated import WebStatsFrustrationPreaggregatedTable
from posthog.hogql.database.schema.web_stats_paths_preaggregated import WebStatsPathsPreaggregatedTable
from posthog.hogql.database.schema.web_stats_preaggregated import WebStatsPreaggregatedTable
from posthog.hogql.database.utils import get_join_field_chain, qualify_join_key_expr
@@ -306,6 +308,12 @@ def build_database_root_node(*, include_posthog_tables: bool = True) -> TableNod
"web_stats_preaggregated": TableNode(
name="web_stats_preaggregated", table=WebStatsPreaggregatedTable()
),
+ "web_stats_frustration_preaggregated": TableNode(
+ name="web_stats_frustration_preaggregated", table=WebStatsFrustrationPreaggregatedTable()
+ ),
+ "web_goals_preaggregated": TableNode(
+ name="web_goals_preaggregated", table=WebGoalsPreaggregatedTable()
+ ),
},
),
"system": SystemTables(),
diff --git a/posthog/hogql/database/schema/web_goals_preaggregated.py b/posthog/hogql/database/schema/web_goals_preaggregated.py
new file mode 100644
index 000000000000..237b5f879a01
--- /dev/null
+++ b/posthog/hogql/database/schema/web_goals_preaggregated.py
@@ -0,0 +1,38 @@
+from pydantic import Field
+
+from posthog.hogql.constants import HogQLQuerySettings
+from posthog.hogql.database.models import (
+ DateTimeDatabaseField,
+ FieldOrTable,
+ IntegerDatabaseField,
+ StringDatabaseField,
+ Table,
+ UnknownDatabaseField,
+)
+
+from posthog.clickhouse.preaggregation.web_goals_preaggregated_sql import DISTRIBUTED_WEB_GOALS_PREAGGREGATED_TABLE
+
+
+class WebGoalsPreaggregatedTable(Table):
+ # Mirrors `WebStatsPathsPreaggregatedTable`: deterministic replica
+ # selection via `load_balancing="in_order"` (read-your-writes) and shard
+ # pruning via `optimize_skip_unused_shards=1` (sharded by
+ # `sipHash64(job_id)`, and the read filters `job_id IN (...)`).
+ top_level_settings: HogQLQuerySettings | None = Field(
+ default_factory=lambda: HogQLQuerySettings(load_balancing="in_order", optimize_skip_unused_shards=True)
+ )
+
+ fields: dict[str, FieldOrTable] = {
+ "team_id": IntegerDatabaseField(name="team_id"),
+ "job_id": StringDatabaseField(name="job_id"),
+ "time_window_start": DateTimeDatabaseField(name="time_window_start"),
+ "action_id": IntegerDatabaseField(name="action_id"),
+ "count_state": UnknownDatabaseField(name="count_state"),
+ "unique_persons_state": UnknownDatabaseField(name="unique_persons_state"),
+ }
+
+ def to_printed_clickhouse(self, context):
+ return DISTRIBUTED_WEB_GOALS_PREAGGREGATED_TABLE()
+
+ def to_printed_hogql(self):
+ return "web_goals_preaggregated"
diff --git a/posthog/hogql/database/schema/web_stats_frustration_preaggregated.py b/posthog/hogql/database/schema/web_stats_frustration_preaggregated.py
new file mode 100644
index 000000000000..e4e4d9cef878
--- /dev/null
+++ b/posthog/hogql/database/schema/web_stats_frustration_preaggregated.py
@@ -0,0 +1,41 @@
+from pydantic import Field
+
+from posthog.hogql.constants import HogQLQuerySettings
+from posthog.hogql.database.models import (
+ DateTimeDatabaseField,
+ FieldOrTable,
+ IntegerDatabaseField,
+ StringDatabaseField,
+ Table,
+ UnknownDatabaseField,
+)
+
+from posthog.clickhouse.preaggregation.web_stats_frustration_preaggregated_sql import (
+ DISTRIBUTED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE,
+)
+
+
+class WebStatsFrustrationPreaggregatedTable(Table):
+ # Mirrors `WebStatsPathsPreaggregatedTable`: deterministic replica selection
+ # via `load_balancing="in_order"` (read-your-writes) and shard pruning via
+ # `optimize_skip_unused_shards=1` (sharded by `sipHash64(job_id)`, and the
+ # read filters `job_id IN (...)`).
+ top_level_settings: HogQLQuerySettings | None = Field(
+ default_factory=lambda: HogQLQuerySettings(load_balancing="in_order", optimize_skip_unused_shards=True)
+ )
+
+ fields: dict[str, FieldOrTable] = {
+ "team_id": IntegerDatabaseField(name="team_id"),
+ "job_id": StringDatabaseField(name="job_id"),
+ "time_window_start": DateTimeDatabaseField(name="time_window_start"),
+ "breakdown_value": StringDatabaseField(name="breakdown_value"),
+ "sum_rage_clicks_state": UnknownDatabaseField(name="sum_rage_clicks_state"),
+ "sum_dead_clicks_state": UnknownDatabaseField(name="sum_dead_clicks_state"),
+ "sum_errors_state": UnknownDatabaseField(name="sum_errors_state"),
+ }
+
+ def to_printed_clickhouse(self, context):
+ return DISTRIBUTED_WEB_STATS_FRUSTRATION_PREAGGREGATED_TABLE()
+
+ def to_printed_hogql(self):
+ return "web_stats_frustration_preaggregated"
diff --git a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
index bd122df21b84..e567b63f0318 100644
--- a/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
+++ b/products/analytics_platform/backend/lazy_computation/lazy_computation_executor.py
@@ -280,6 +280,8 @@ class LazyComputationTable(StrEnum):
WEB_OVERVIEW_PREAGGREGATED = "web_overview_preaggregated"
WEB_STATS_PREAGGREGATED = "web_stats_preaggregated"
WEB_STATS_PATHS_PREAGGREGATED = "web_stats_paths_preaggregated"
+ WEB_STATS_FRUSTRATION_PREAGGREGATED = "web_stats_frustration_preaggregated"
+ WEB_GOALS_PREAGGREGATED = "web_goals_preaggregated"
# Tables where expires_at is a Date (not DateTime64). Date truncates to midnight,