: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(experiments): Add cache footprint panel to query performance scene (#68219)
Juraj Majerik3643acb0ba11
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex ce18d600c59e..b603424818e9 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1375,7 +1375,7 @@ snapshots:components-playerinspector--with-logs-filter--dark:hash: v1.k794b7964.81638d612b02f4198ac27f6c2ee030fbb1f7f63fa6f61d418363a4c977ae5e96.e_NxV6eZxgRi7UyolNkoX79EWtWWfN6WNRY_C-HdTxQcomponents-playerinspector--with-logs-filter--light:- hash: v1.k794b7964.e4a2b000ff9ea9e18a9474d1924a797f9893a9581dc66533aaf628ee52fc68cf.E5TauuBHMLbTsqudJivv3X0OISOKJcmgfPlp6Gdg15M+ hash: v1.k794b7964.65c73551ca898228e94266e312726fa49633b5c23258bdae7d11304e08c9101e.soqrtGoaYmCKjlLNAK8T7n5cjJhcrj0XzAq0w7g_bokcomponents-playerinspector--with-logs-filter-upsell--dark:hash: v1.k794b7964.5e4afe863e34df7278c0dd092946adfd396ee778f0cd0a41e5e3f5e1771a9601.SBOdVp0jJnn1w2H4fMR-3Vf2ac00QSBFQjsl93AbcYAcomponents-playerinspector--with-logs-filter-upsell--light:diff --git a/frontend/src/scenes/instance/QueryPerformance/CacheHealth.tsx b/frontend/src/scenes/instance/QueryPerformance/CacheHealth.tsxnew file mode 100644index 000000000000..33e0cdf1a207--- /dev/null+++ b/frontend/src/scenes/instance/QueryPerformance/CacheHealth.tsx@@ -0,0 +1,153 @@+import { useActions, useValues } from 'kea'++import { LemonButton } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'+import { LemonCard } from 'lib/lemon-ui/LemonCard'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'+import { humanFriendlyLargeNumber, humanFriendlyNumber, humanizeBytes } from 'lib/utils/numbers'++import { CachePartitionRow, CacheTableStats, queryPerformanceLogic } from './queryPerformanceLogic'++// Partitions are keyed by toYYYYMMDD(expires_at), so a partition id is the day its rows expire.+const partitionToISO = (partition: string): string =>+ `${partition.slice(0, 4)}-${partition.slice(4, 6)}-${partition.slice(6, 8)}`++const formatPartitionDay = (partition: string): string => dayjs(partitionToISO(partition)).format('MMM D')++// TTL uses ttl_only_drop_parts=1, so whole partitions drop once their expiry day passes. A partition+// dated before today is expired data still on disk, waiting for the TTL merge to drop it.+function ttlStatus(partition: string): { label: string; type: LemonTagType } {+ const today = dayjs().format('YYYYMMDD')+ if (partition < today) {+ return { label: 'Expired, awaiting drop', type: 'danger' }+ }+ if (partition === today) {+ return { label: 'Drops today', type: 'warning' }+ }+ const days = dayjs(partitionToISO(partition)).diff(dayjs().startOf('day'), 'day')+ return { label: `Drops in ${days}d`, type: 'muted' }+}++// "experiment_exposures_preaggregated" -> "Exposures", "experiment_metric_events_preaggregated" -> "Metric events"+function tableLabel(table: string): string {+ const short = table+ .replace(/^experiment_/, '')+ .replace(/_preaggregated$/, '')+ .replace(/_/g, ' ')+ return short.charAt(0).toUpperCase() + short.slice(1)+}++function TableCard({ table }: { table: CacheTableStats }): JSX.Element {+ 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">+ {humanFriendlyLargeNumber(table.total_rows)} rows · {humanizeBytes(table.bytes_on_disk)}+ </div>+ <div className="text-xs text-muted mt-1">+ {humanFriendlyNumber(table.active_parts)} active parts · {table.partition_count} partition days+ </div>+ <div className="text-xs text-muted">+ {table.oldest_partition && table.newest_partition+ ? `Expiry span: ${formatPartitionDay(table.oldest_partition)} → ${formatPartitionDay(+ table.newest_partition+ )}`+ : 'No active parts'}+ </div>+ </LemonCard>+ )+}++export function CacheHealth(): JSX.Element {+ const { cacheHealth, cacheHealthLoading, cachePartitionRows } = useValues(queryPerformanceLogic)+ const { loadCacheHealth } = useActions(queryPerformanceLogic)++ const tables = cacheHealth?.tables ?? []++ const partitionColumns: LemonTableColumns<CachePartitionRow> = [+ {+ title: 'Expiry day',+ width: 220,+ render: function ExpiryDay(_, row) {+ const { label, type } = ttlStatus(row.partition)+ return (+ <div className="flex items-center gap-2">+ <span className="font-mono text-xs">{formatPartitionDay(row.partition)}</span>+ <LemonTag type={type}>{label}</LemonTag>+ </div>+ )+ },+ },+ ...tables.flatMap((table): LemonTableColumns<CachePartitionRow> => {+ const label = tableLabel(table.table)+ return [+ {+ title: `${label} rows`,+ render: function Rows(_, row) {+ const stats = row.perTable[table.table]+ return (+ <span className="font-mono">+ {stats ? humanFriendlyNumber(stats.rows) : <span className="text-muted">–</span>}+ </span>+ )+ },+ },+ {+ title: `${label} size`,+ render: function Size(_, row) {+ const stats = row.perTable[table.table]+ return (+ <span className="font-mono">+ {stats ? humanizeBytes(stats.bytes_on_disk) : <span className="text-muted">–</span>}+ </span>+ )+ },+ },+ ]+ }),+ ]++ return (+ <>+ <div className="flex items-center gap-2">+ <h2 className="mb-0">Cache health</h2>+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => loadCacheHealth()}+ disabledReason={cacheHealthLoading ? 'Loading...' : undefined}+ >+ Refresh+ </LemonButton>+ </div>+ <p className="text-muted text-sm mt-1 mb-2">+ Physical footprint of the experiment preaggregation tables — active parts across all shards, from+ ClickHouse system.parts.+ </p>+ <div className="flex flex-wrap gap-4 mb-4">+ {!cacheHealth && cacheHealthLoading+ ? [0, 1].map((i) => (+ <LemonCard key={i} hoverEffect={false} className="flex-1 min-w-72">+ <LemonSkeleton className="h-4 w-1/2" />+ <LemonSkeleton className="h-6 w-2/3 mt-2" />+ <LemonSkeleton className="h-3 w-1/2 mt-2" />+ <LemonSkeleton className="h-3 w-1/3 mt-1" />+ </LemonCard>+ ))+ : tables.map((table) => <TableCard key={table.table} table={table} />)}+ </div>+ <h3>Partition breakdown by expiry day</h3>+ <LemonTable+ size="small"+ columns={partitionColumns}+ dataSource={cachePartitionRows}+ loading={cacheHealthLoading}+ emptyState="No active parts found"+ className="overflow-visible! flex-none! mb-8"+ />+ </>+ )+}diff --git a/frontend/src/scenes/instance/QueryPerformance/QueryPerformance.tsx b/frontend/src/scenes/instance/QueryPerformance/QueryPerformance.tsxindex 7dac8d3f1e17..80827f45d25a 100644--- a/frontend/src/scenes/instance/QueryPerformance/QueryPerformance.tsx+++ b/frontend/src/scenes/instance/QueryPerformance/QueryPerformance.tsx@@ -21,6 +21,7 @@ import { userLogic } from 'scenes/userLogic'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { CacheHealth } from './CacheHealth'import { PrecomputationTeam, queryPerformanceLogic, SlowestQuery } from './queryPerformanceLogic'export const scene: SceneExport = {@@ -497,6 +498,7 @@ export function QueryPerformance(): JSX.Element {label: 'Experiments',content: (<>+ <CacheHealth /><h2>Slowest queries</h2><div className="flex flex-wrap gap-2 mb-4 items-center">{TIME_RANGE_OPTIONS.map(({ label, hours }) => (diff --git a/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.ts b/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.tsindex f780f076d477..2f417842041e 100644--- a/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.ts+++ b/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.ts@@ -1,4 +1,4 @@-import { actions, afterMount, kea, listeners, path, reducers } from 'kea'+import { actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import api from 'lib/api'@@ -15,6 +15,34 @@ export interface PrecomputationTeam {experiment_precomputation_enabled: boolean}+export interface CachePartitionStats {+ partition: string // YYYYMMDD — the expiry day of the partition (tables partition by toYYYYMMDD(expires_at))+ rows: number+ bytes_on_disk: number+ parts: number+}++export interface CacheTableStats {+ table: string+ total_rows: number+ bytes_on_disk: number+ active_parts: number+ partition_count: number+ oldest_partition: string | null+ newest_partition: string | null+ partitions: CachePartitionStats[]+}++export interface CacheHealthResponse {+ tables: CacheTableStats[]+}++// One row of the partition breakdown table: a single expiry day, with each cache table's stats for that day.+export interface CachePartitionRow {+ partition: string+ perTable: Record<string, CachePartitionStats>+}+export interface SlowestQuery {query_id: stringquery: string@@ -126,6 +154,14 @@ export const queryPerformanceLogic = kea<queryPerformanceLogicType>([},},],+ cacheHealth: [+ null as CacheHealthResponse | null,+ {+ loadCacheHealth: async () => {+ return await api.get('api/debug_ch_queries/cache_health/')+ },+ },+ ],slowestQueries: [[] as SlowestQuery[],{@@ -153,6 +189,24 @@ export const queryPerformanceLogic = kea<queryPerformanceLogicType>([},],})),+ selectors({+ cachePartitionRows: [+ (s) => [s.cacheHealth],+ (cacheHealth): CachePartitionRow[] => {+ const byPartition: Record<string, CachePartitionRow> = {}+ for (const table of cacheHealth?.tables ?? []) {+ for (const partition of table.partitions) {+ const row = (byPartition[partition.partition] ??= {+ partition: partition.partition,+ perTable: {},+ })+ row.perTable[table.table] = partition+ }+ }+ return Object.values(byPartition).sort((a, b) => a.partition.localeCompare(b.partition))+ },+ ],+ }),listeners(({ actions }) => ({setSearch: async (_, breakpoint) => {await breakpoint(300)@@ -180,6 +234,7 @@ export const queryPerformanceLogic = kea<queryPerformanceLogicType>([if (userLogic.findMounted()?.values.user?.is_staff) {actions.loadPrecomputationTeams()actions.loadSlowestQueries()+ actions.loadCacheHealth()}}),])diff --git a/posthog/api/debug_ch_queries.py b/posthog/api/debug_ch_queries.pyindex e81ee21471d3..49c6bc53d2d6 100644--- a/posthog/api/debug_ch_queries.py+++ b/posthog/api/debug_ch_queries.py@@ -2,7 +2,7 @@ import reimport jsonimport loggingfrom datetime import UTC, datetime, timedelta-from typing import Optional+from typing import Any, Optionalfrom django.utils.timezone import now@@ -19,13 +19,21 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.auth import PersonalAPIKeyAuthentication, SessionAuthenticationfrom posthog.clickhouse.client import sync_execute+from posthog.clickhouse.preaggregation.experiment_exposures_sql import (+ DISTRIBUTED_EXPERIMENT_EXPOSURES_TABLE,+ SHARDED_EXPERIMENT_EXPOSURES_TABLE,+)+from posthog.clickhouse.preaggregation.experiment_metric_events_sql import (+ DISTRIBUTED_EXPERIMENT_METRIC_EVENTS_TABLE,+ SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE,+)from posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.cloud_utils import is_cloudfrom 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+from posthog.settings.data_stores import CLICKHOUSE_CLUSTER, CLICKHOUSE_DATABASEfrom products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig@@ -68,6 +76,75 @@ def _nest_subqueries(records: list[dict]) -> list[dict]:return results+def _cache_table_stats() -> list[dict]:+ """Physical footprint of the experiment preaggregation tables, from system.parts.++ Both tables are PARTITION BY toYYYYMMDD(expires_at) with TTL expires_at and+ ttl_only_drop_parts=1, so each partition id is the day the partition drops — the+ per-partition breakdown doubles as a TTL/growth timeline.+ """+ tables = {+ SHARDED_EXPERIMENT_EXPOSURES_TABLE(): DISTRIBUTED_EXPERIMENT_EXPOSURES_TABLE(),+ SHARDED_EXPERIMENT_METRIC_EVENTS_TABLE(): DISTRIBUTED_EXPERIMENT_METRIC_EVENTS_TABLE(),+ }+ # 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: {+ "table": base,+ "total_rows": 0,+ "bytes_on_disk": 0,+ "active_parts": 0,+ "partition_count": 0,+ "oldest_partition": None,+ "newest_partition": None,+ "partitions": [],+ }+ for sharded, base in tables.items()+ }+ 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"]+ entry["newest_partition"] = entry["partitions"][-1]["partition"]+ return list(stats.values())++@extend_schema(exclude=True)class DebugCHQueries(viewsets.ViewSet):"""@@ -618,3 +695,12 @@ class DebugCHQueries(viewsets.ViewSet):}return Response(_nest_subqueries([_record(row) for row in response]))++ @action(detail=False, methods=["GET"], url_path="cache_health", required_scopes=["query_performance:read"])+ def cache_health(self, request):+ if not request.user.is_staff:+ raise exceptions.PermissionDenied("Only staff users can view cache health.")++ tag_queries(product=Product.INTERNAL, feature=Feature.DEBUG_QUERY)++ return Response({"tables": _cache_table_stats()})