: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(experiments): read metric-events preagg parts from the aux cluster in cache_health (#71917)
Juraj Majerik64560a67f42e
diff --git a/frontend/src/scenes/instance/QueryPerformance/CacheHealth.tsx b/frontend/src/scenes/instance/QueryPerformance/CacheHealth.tsxindex dbdae970614e..89e13ed7f8cd 100644--- a/frontend/src/scenes/instance/QueryPerformance/CacheHealth.tsx+++ b/frontend/src/scenes/instance/QueryPerformance/CacheHealth.tsx@@ -41,6 +41,15 @@ function tableLabel(table: string): string {}function TableCard({ table }: { table: CacheTableStats }): JSX.Element {+ if (table.unavailable) {+ return (+ <LemonCard hoverEffect={false} className="flex-1 min-w-72">+ <div className="font-mono text-xs text-muted">{table.table}</div>+ <div className="text-xl font-semibold mt-1">Unavailable</div>+ <div className="text-xs text-muted mt-1">Couldn't read system.parts from this table's cluster</div>+ </LemonCard>+ )+ }return (<LemonCard hoverEffect={false} className="flex-1 min-w-72"><div className="font-mono text-xs text-muted">{table.table}</div>diff --git a/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.ts b/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.tsindex e7d7a9034450..355952db0865 100644--- a/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.ts+++ b/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.ts@@ -103,6 +103,9 @@ export interface CacheTableStats {oldest_partition: string | nullnewest_partition: string | nullpartitions: CachePartitionStats[]+ // Set when system.parts couldn't be read from the cluster this table lives on — the zeros+ // above are then "unknown", not "empty".+ unavailable?: boolean}export interface CacheHealthResponse {diff --git a/posthog/api/debug_ch_queries.py b/posthog/api/debug_ch_queries.pyindex 0569c99497c6..5c5f426c960f 100644--- a/posthog/api/debug_ch_queries.py+++ b/posthog/api/debug_ch_queries.py@@ -34,7 +34,7 @@ from posthog.models.team.extensions import get_or_create_team_extensionfrom posthog.models.team.team import Teamfrom posthog.permissions import APIScopePermissionfrom posthog.settings.base_variables import DEBUG-from posthog.settings.data_stores import CLICKHOUSE_CLUSTER, CLICKHOUSE_DATABASE+from posthog.settings.data_stores import CLICKHOUSE_AUX_CLUSTER, CLICKHOUSE_CLUSTER, CLICKHOUSE_DATABASEfrom products.analytics_platform.backend.models import PreaggregationJobfrom products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig@@ -85,36 +85,15 @@ def _cache_table_stats() -> list[dict]:ttl_only_drop_parts=1, so each partition id is the day the partition drops — theper-partition breakdown doubles as a TTL/growth timeline."""+ # Each sharded table's parts live on the cluster its Distributed table targets: exposures on+ # the main cluster, metric_events on the aux cluster — so system.parts must be read per cluster.tables = {- SHARDED_EXPERIMENT_EXPOSURES_TABLE(): DISTRIBUTED_EXPERIMENT_EXPOSURES_TABLE(),- SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE(): DISTRIBUTED_EXPERIMENT_METRIC_EVENTS_TABLE(),+ SHARDED_EXPERIMENT_EXPOSURES_TABLE(): (DISTRIBUTED_EXPERIMENT_EXPOSURES_TABLE(), CLICKHOUSE_CLUSTER),+ SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE(): (+ DISTRIBUTED_EXPERIMENT_METRIC_EVENTS_TABLE(),+ CLICKHOUSE_AUX_CLUSTER,+ ),}- # cluster() reads one replica per shard. clusterAllReplicas would visit every replica and,- # unlike query_log (deduped via is_initial_query), each replica of a shard reports the same- # parts — rows/bytes would be multiplied by the replica count.- response = sync_execute(- """- SELECT- table,- partition,- sum(rows) AS rows,- sum(bytes_on_disk) AS bytes_on_disk,- count() AS parts- FROM cluster(%(cluster)s, system, parts)- WHERE- database = %(database)s- AND table IN %(tables)s- AND active- GROUP BY table, partition- ORDER BY table, partition- SETTINGS skip_unavailable_shards=1- """,- {- "cluster": CLICKHOUSE_CLUSTER,- "database": CLICKHOUSE_DATABASE,- "tables": list(tables.keys()),- },- )stats: dict[str, dict[str, Any]] = {sharded: {@@ -127,19 +106,56 @@ def _cache_table_stats() -> list[dict]:"newest_partition": None,"partitions": [],}- for sharded, base in tables.items()+ for sharded, (base, _) in tables.items()}- for table, partition, rows, bytes_on_disk, parts in response:- entry = stats.get(table)- if entry is None:++ for cluster in dict.fromkeys(cluster for _, cluster in tables.values()):+ cluster_tables = [sharded for sharded, (_, c) in tables.items() if c == cluster]+ # cluster() reads one replica per shard. clusterAllReplicas would visit every replica and,+ # unlike query_log (deduped via is_initial_query), each replica of a shard reports the same+ # parts — rows/bytes would be multiplied by the replica count.+ try:+ response = sync_execute(+ """+ SELECT+ table,+ partition,+ sum(rows) AS rows,+ sum(bytes_on_disk) AS bytes_on_disk,+ count() AS parts+ FROM cluster(%(cluster)s, system, parts)+ WHERE+ database = %(database)s+ AND table IN %(tables)s+ AND active+ GROUP BY table, partition+ ORDER BY table, partition+ SETTINGS skip_unavailable_shards=1+ """,+ {+ "cluster": cluster,+ "database": CLICKHOUSE_DATABASE,+ "tables": cluster_tables,+ },+ )+ except Exception:+ # One cluster being unreachable (or absent in a single-cluster deployment) must not+ # take down the stats read from the healthy cluster.+ logger.exception("cache_health: failed to read system.parts from cluster %s", cluster)+ for sharded in cluster_tables:+ stats[sharded]["unavailable"] = Truecontinue- entry["total_rows"] += rows- entry["bytes_on_disk"] += bytes_on_disk- entry["active_parts"] += parts- entry["partition_count"] += 1- entry["partitions"].append(- {"partition": partition, "rows": rows, "bytes_on_disk": bytes_on_disk, "parts": parts}- )+ for table, partition, rows, bytes_on_disk, parts in response:+ entry = stats.get(table)+ if entry is None:+ continue+ entry["total_rows"] += rows+ entry["bytes_on_disk"] += bytes_on_disk+ entry["active_parts"] += parts+ entry["partition_count"] += 1+ entry["partitions"].append(+ {"partition": partition, "rows": rows, "bytes_on_disk": bytes_on_disk, "parts": parts}+ )for entry in stats.values():if entry["partitions"]:entry["oldest_partition"] = entry["partitions"][0]["partition"]diff --git a/posthog/api/test/test_debug_ch_queries.py b/posthog/api/test/test_debug_ch_queries.pyindex 69e0e8eaa07f..4a29867ba2cd 100644--- a/posthog/api/test/test_debug_ch_queries.py+++ b/posthog/api/test/test_debug_ch_queries.py@@ -1,10 +1,16 @@from posthog.test.base import APIBaseTestfrom unittest.mock import patch+from django.test import SimpleTestCase+from rest_framework.status import HTTP_200_OK, HTTP_403_FORBIDDEN+from posthog.api.debug_ch_queries import _cache_table_stats+from posthog.clickhouse.preaggregation.experiment_exposures_sql import SHARDED_EXPERIMENT_EXPOSURES_TABLE+from posthog.clickhouse.preaggregation.experiment_metric_events_sql import SHARDED_EXPERIMENT_METRIC_EVENTS_TABLEfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.utils import generate_random_token_personal, hash_key_value+from posthog.settings.data_stores import CLICKHOUSE_AUX_CLUSTER, CLICKHOUSE_CLUSTERclass TestDebugCHQuery(APIBaseTest):@@ -92,3 +98,47 @@ class TestDebugCHQuery(APIBaseTest):headers={"authorization": f"Bearer {token}"},)self.assertEqual(resp.status_code, HTTP_200_OK, resp.content)+++class TestCacheTableStats(SimpleTestCase):+ def test_reads_each_table_from_its_own_cluster(self):+ # The metric-events sharded table lives on the aux cluster; reading system.parts only on+ # the main cluster silently reported it as empty in prod. This fails if the per-cluster+ # dispatch is reverted to a single main-cluster query.+ def fake_sync_execute(_query, params):+ parts_by_cluster = {+ CLICKHOUSE_CLUSTER: [(SHARDED_EXPERIMENT_EXPOSURES_TABLE(), "20260801", 10, 100, 1)],+ CLICKHOUSE_AUX_CLUSTER: [(SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE(), "20260802", 20, 200, 2)],+ }+ return [row for row in parts_by_cluster[params["cluster"]] if row[0] in params["tables"]]++ with patch("posthog.api.debug_ch_queries.sync_execute", side_effect=fake_sync_execute):+ stats = {entry["table"]: entry for entry in _cache_table_stats()}++ exposures = stats["experiment_exposures_preaggregated"]+ metric_events = stats["experiment_metric_events_preaggregated"]+ self.assertEqual(exposures["total_rows"], 10)+ self.assertEqual(exposures["newest_partition"], "20260801")+ self.assertEqual(metric_events["total_rows"], 20)+ self.assertEqual(metric_events["active_parts"], 2)+ self.assertEqual(+ metric_events["partitions"], [{"partition": "20260802", "rows": 20, "bytes_on_disk": 200, "parts": 2}]+ )++ def test_unreachable_cluster_degrades_instead_of_raising(self):+ # A deployment without the aux cluster (or an aux outage) must not 500 the whole+ # endpoint and lose the stats already readable from the main cluster.+ def fake_sync_execute(_query, params):+ if params["cluster"] == CLICKHOUSE_AUX_CLUSTER:+ raise Exception("Requested cluster 'aux' not found")+ return [(SHARDED_EXPERIMENT_EXPOSURES_TABLE(), "20260801", 10, 100, 1)]++ with patch("posthog.api.debug_ch_queries.sync_execute", side_effect=fake_sync_execute):+ stats = {entry["table"]: entry for entry in _cache_table_stats()}++ exposures = stats["experiment_exposures_preaggregated"]+ metric_events = stats["experiment_metric_events_preaggregated"]+ self.assertEqual(exposures["total_rows"], 10)+ self.assertNotIn("unavailable", exposures)+ self.assertTrue(metric_events["unavailable"])+ self.assertEqual(metric_events["total_rows"], 0)