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(experiments): nest precompute sub-queries in query performance (#65851)

Juraj Majerik9848bac28926
diff --git a/frontend/src/scenes/instance/QueryPerformance/QueryPerformance.tsx b/frontend/src/scenes/instance/QueryPerformance/QueryPerformance.tsx
index 2b3aba2f8fb5..7783b584adb4 100644
--- a/frontend/src/scenes/instance/QueryPerformance/QueryPerformance.tsx
+++ b/frontend/src/scenes/instance/QueryPerformance/QueryPerformance.tsx
@@ -36,23 +36,14 @@ export function QueryPerformance(): JSX.Element {
precomputationTeams,
precomputationTeamsLoading,
search,
- visibleSlowestQueries,
+ slowestQueries,
slowestQueriesLoading,
- showSubQueries,
- allQueriesHiddenAsSubQueries,
hoursBack,
teamIdFilter,
experimentIdFilter,
} = useValues(queryPerformanceLogic)
- const {
- setSearch,
- setPrecomputation,
- setHoursBack,
- loadSlowestQueries,
- setTeamIdFilter,
- setExperimentIdFilter,
- setShowSubQueries,
- } = useActions(queryPerformanceLogic)
+ const { setSearch, setPrecomputation, setHoursBack, loadSlowestQueries, setTeamIdFilter, setExperimentIdFilter } =
+ useActions(queryPerformanceLogic)
if (!user?.is_staff) {
return (
@@ -148,10 +139,20 @@ export function QueryPerformance(): JSX.Element {
},
{
title: 'Duration (ms)',
- dataIndex: 'execution_time',
- width: 120,
+ width: 150,
render: function Duration(_, item) {
- return <span className="font-mono">{Math.round(item.execution_time)}</span>
+ // Headline is the total the user waited for (precompute builds + read); the read on its own
+ // is shown alongside when this query had sub-queries.
+ const total = Math.round(item.total_duration_ms ?? item.execution_time)
+ const hasSubQueries = item.sub_queries && item.sub_queries.length > 0
+ return (
+ <div className="font-mono">
+ <span>{total}</span>
+ {hasSubQueries && (
+ <span className="text-muted text-xs"> · read {Math.round(item.execution_time)}</span>
+ )}
+ </div>
+ )
},
},
{
@@ -262,6 +263,39 @@ export function QueryPerformance(): JSX.Element {
},
]
+ const subQueryColumns: LemonTableColumns<SlowestQuery> = [
+ {
+ title: 'Build',
+ width: 180,
+ render: function SubQueryBuild(_, item) {
+ return <LemonTag type="warning">build: {item.experiment_precompute_table || 'unknown'}</LemonTag>
+ },
+ },
+ {
+ title: 'Duration (ms)',
+ width: 120,
+ render: function SubQueryDuration(_, item) {
+ return <span className="font-mono">{Math.round(item.execution_time)}</span>
+ },
+ },
+ {
+ title: 'Status',
+ render: function SubQueryStatus(_, item) {
+ if (!item.exception) {
+ return <LemonTag type="success">OK</LemonTag>
+ }
+ const firstLine = item.exception.split('\n')[0]
+ const preview = firstLine.length > 60 ? firstLine.slice(0, 60) + '…' : firstLine
+ return (
+ <div className="flex items-center gap-1 min-w-0">
+ <LemonTag type="danger">Error</LemonTag>
+ <span className="font-mono text-xs text-danger truncate">{preview}</span>
+ </div>
+ )
+ },
+ },
+ ]
+
return (
<SceneContent className="mt-4 pb-8">
<SceneTitleSection
@@ -319,40 +353,50 @@ export function QueryPerformance(): JSX.Element {
>
Refresh
</LemonButton>
- <LemonSwitch
- label="Show sub-queries"
- checked={showSubQueries}
- onChange={setShowSubQueries}
- size="small"
- bordered
- />
</div>
<LemonTable
columns={slowestQueryColumns}
- dataSource={visibleSlowestQueries}
+ dataSource={slowestQueries}
loading={slowestQueriesLoading}
- emptyState={
- allQueriesHiddenAsSubQueries
- ? 'All queries in this range are sub-queries — enable "Show sub-queries" to view them'
- : 'No queries found in this time range'
- }
+ emptyState="No queries found in this time range"
pagination={{ pageSize: 20 }}
className="overflow-visible! flex-none!"
expandable={{
expandedRowRender: function ExpandedQuery(item) {
return (
- <div className="p-2">
- {item.exception && (
- <div className="mb-2">
- <CodeSnippet
- language={Language.Text}
- thing="error"
- maxLinesWithoutExpansion={5}
- >
- {item.exception}
- </CodeSnippet>
+ <div className="flex flex-col gap-2 p-2">
+ {item.sub_queries && item.sub_queries.length > 0 && (
+ <div>
+ <h4 className="mb-1">Sub-queries (precompute builds)</h4>
+ <LemonTable
+ size="small"
+ columns={subQueryColumns}
+ dataSource={item.sub_queries}
+ expandable={{
+ expandedRowRender: function ExpandedSubQuery(sub) {
+ return (
+ <CodeSnippet
+ language={Language.SQL}
+ thing="query"
+ maxLinesWithoutExpansion={10}
+ >
+ {sub.query}
+ </CodeSnippet>
+ )
+ },
+ }}
+ />
</div>
)}
+ {item.exception && (
+ <CodeSnippet
+ language={Language.Text}
+ thing="error"
+ maxLinesWithoutExpansion={5}
+ >
+ {item.exception}
+ </CodeSnippet>
+ )}
<CodeSnippet
language={Language.SQL}
thing="query"
diff --git a/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.ts b/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.ts
index 377a7ce3e5d6..3376cb0400c1 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, selectors } from 'kea'
+import { actions, afterMount, kea, listeners, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
@@ -34,9 +34,12 @@ export interface SlowestQuery {
experiment_metric_events_path: string
experiment_query_surface: string
experiment_precompute_table: string
+ experiment_query_group_id: string
experiment_metric_type: string
experiment_funnel_order_type: string | null
experiment_id: number | null
+ total_duration_ms: number
+ sub_queries: SlowestQuery[]
}
export const queryPerformanceLogic = kea<queryPerformanceLogicType>([
@@ -47,7 +50,6 @@ export const queryPerformanceLogic = kea<queryPerformanceLogicType>([
setHoursBack: (hours: number) => ({ hours }),
setTeamIdFilter: (teamId: string) => ({ teamId }),
setExperimentIdFilter: (experimentId: string) => ({ experimentId }),
- setShowSubQueries: (show: boolean) => ({ show }),
}),
reducers({
search: [
@@ -74,12 +76,6 @@ export const queryPerformanceLogic = kea<queryPerformanceLogicType>([
setExperimentIdFilter: (_, { experimentId }) => experimentId,
},
],
- showSubQueries: [
- false,
- {
- setShowSubQueries: (_, { show }) => show,
- },
- ],
}),
loaders(({ values }) => ({
precomputationTeams: [
@@ -123,24 +119,6 @@ export const queryPerformanceLogic = kea<queryPerformanceLogicType>([
},
],
})),
- selectors({
- // The precompute-build INSERTs are sub-queries of a top-level read; hide them by default so the
- // table reflects what a user actually waited for, with a toggle to surface them for debugging.
- visibleSlowestQueries: [
- (s) => [s.slowestQueries, s.showSubQueries],
- (slowestQueries, showSubQueries): SlowestQuery[] =>
- showSubQueries
- ? slowestQueries
- : slowestQueries.filter((query) => query.experiment_query_surface !== 'precompute_build'),
- ],
- // True when the visible table is empty only because every returned row is a hidden sub-query,
- // so the empty state can say so instead of claiming there are no queries in the range.
- allQueriesHiddenAsSubQueries: [
- (s) => [s.slowestQueries, s.visibleSlowestQueries],
- (slowestQueries, visibleSlowestQueries): boolean =>
- slowestQueries.length > 0 && visibleSlowestQueries.length === 0,
- ],
- }),
listeners(({ actions }) => ({
setSearch: async (_, breakpoint) => {
await breakpoint(300)
diff --git a/posthog/api/debug_ch_queries.py b/posthog/api/debug_ch_queries.py
index 86d5a34a07e7..6550d6ff88e8 100644
--- a/posthog/api/debug_ch_queries.py
+++ b/posthog/api/debug_ch_queries.py
@@ -32,6 +32,42 @@ from products.experiments.backend.models.team_experiments_config import TeamExpe
logger = logging.getLogger(__name__)
+def _nest_subqueries(records: list[dict]) -> list[dict]:
+ """Group the flat slowest-query rows into top-level reads, each carrying its precompute-build
+ sub-queries under ``sub_queries``. Rows sharing an ``experiment_query_group_id`` form one group
+ (rows without one are their own group, keyed by ``query_id``); the non-``precompute_build`` row is
+ the parent. ``records`` must already be ordered for display (group total desc, parent first), which
+ the SQL guarantees — dict insertion order is then preserved as the output order.
+ """
+ groups: dict[str, dict] = {}
+ extra_parents: list[dict] = []
+ for record in records:
+ key = record["experiment_query_group_id"] or record["query_id"]
+ bucket = groups.setdefault(key, {"parent": None, "children": []})
+ if record["experiment_query_surface"] == "precompute_build":
+ bucket["children"].append(record)
+ elif bucket["parent"] is None:
+ bucket["parent"] = record
+ else:
+ # The runner mints one group id per evaluation, so >1 top-level read per group isn't
+ # expected. If it happens, keep the first as the group's parent and surface the rest
+ # standalone rather than dropping them.
+ logger.warning("slowest_queries: multiple top-level reads share group %s", key)
+ extra_parents.append(record)
+
+ results: list[dict] = []
+ for bucket in groups.values():
+ parent = bucket["parent"]
+ if parent is None:
+ # Sub-queries whose top-level read isn't in the window — show standalone so nothing is hidden.
+ results.extend(bucket["children"])
+ continue
+ parent["sub_queries"] = bucket["children"]
+ results.append(parent)
+ results.extend(extra_parents)
+ return results
+
+
@extend_schema(exclude=True)
class DebugCHQueries(viewsets.ViewSet):
"""
@@ -403,43 +439,72 @@ class DebugCHQueries(viewsets.ViewSet):
extra_filters += " AND JSONExtractInt(log_comment, 'experiment_id') = %(experiment_id)s"
params["experiment_id"] = experiment_id_filter
+ # Each row is one ClickHouse query. A top-level read (surface != 'precompute_build') and the
+ # precompute-build INSERTs it triggered share an experiment_query_group_id (set by the runner).
+ # We rank groups by total duration (build + read — the user waited for both, synchronously) and
+ # return every row of the top 100 groups; Python then nests the builds under their parent read.
+ # Rows with no group id (legacy / non-runner queries) fall back to a group of one via `grp`.
# nosemgrep: clickhouse-fstring-param-audit - extra_filters is built from hardcoded SQL fragments; user values flow through params
sql_query = f"""
- SELECT
- query_id,
- argMax(query, type) AS query,
- argMax(query_start_time, type) AS query_start_time,
- argMax(query_duration_ms, type) AS query_duration_ms,
- argMax(exception, type) AS exception,
- max(type) AS status,
- argMax(JSONExtractInt(log_comment, 'team_id'), type) AS team_id,
- argMax(JSONExtractString(log_comment, 'query_type'), type) AS query_type,
- argMax(JSONExtractString(log_comment, 'experiment_name'), type) AS experiment_name,
- argMax(JSONExtractString(log_comment, 'experiment_metric_name'), type) AS experiment_metric_name,
- argMax(JSONExtractString(log_comment, 'experiment_execution_path'), type) AS experiment_execution_path,
- argMax(JSONExtractString(log_comment, 'experiment_metric_type'), type) AS experiment_metric_type,
- argMax(JSONExtractString(log_comment, 'experiment_funnel_order_type'), type) AS experiment_funnel_order_type,
- argMax(JSONExtractInt(log_comment, 'experiment_id'), type) AS experiment_id,
- argMax(JSONExtractString(log_comment, 'experiment_exposures_path'), type) AS experiment_exposures_path,
- argMax(JSONExtractString(log_comment, 'experiment_metric_events_path'), type) AS experiment_metric_events_path,
- argMax(JSONExtractString(log_comment, 'experiment_query_surface'), type) AS experiment_query_surface,
- argMax(JSONExtractString(log_comment, 'experiment_precompute_table'), type) AS experiment_precompute_table
- FROM (
+ WITH per_query AS (
SELECT
- query_id, query, query_start_time, query_duration_ms, exception,
- toInt8(type) AS type, log_comment
- FROM clusterAllReplicas(%(cluster)s, system, query_log)
- WHERE
- event_time > now() - INTERVAL %(hours)s HOUR
- AND JSONExtractString(log_comment, 'product') = 'experiments'
- AND is_initial_query
- AND query NOT LIKE %(not_query)s
- {extra_filters}
- SETTINGS skip_unavailable_shards=1
+ query_id,
+ argMax(query, type) AS query,
+ argMax(query_start_time, type) AS query_start_time,
+ argMax(query_duration_ms, type) AS query_duration_ms,
+ argMax(exception, type) AS exception,
+ max(type) AS status,
+ argMax(JSONExtractInt(log_comment, 'team_id'), type) AS team_id,
+ argMax(JSONExtractString(log_comment, 'query_type'), type) AS query_type,
+ argMax(JSONExtractString(log_comment, 'experiment_name'), type) AS experiment_name,
+ argMax(JSONExtractString(log_comment, 'experiment_metric_name'), type) AS experiment_metric_name,
+ argMax(JSONExtractString(log_comment, 'experiment_execution_path'), type) AS experiment_execution_path,
+ argMax(JSONExtractString(log_comment, 'experiment_metric_type'), type) AS experiment_metric_type,
+ argMax(JSONExtractString(log_comment, 'experiment_funnel_order_type'), type) AS experiment_funnel_order_type,
+ argMax(JSONExtractInt(log_comment, 'experiment_id'), type) AS experiment_id,
+ argMax(JSONExtractString(log_comment, 'experiment_exposures_path'), type) AS experiment_exposures_path,
+ argMax(JSONExtractString(log_comment, 'experiment_metric_events_path'), type) AS experiment_metric_events_path,
+ argMax(JSONExtractString(log_comment, 'experiment_query_surface'), type) AS experiment_query_surface,
+ argMax(JSONExtractString(log_comment, 'experiment_precompute_table'), type) AS experiment_precompute_table,
+ argMax(JSONExtractString(log_comment, 'experiment_query_group_id'), type) AS experiment_query_group_id
+ FROM (
+ SELECT
+ query_id, query, query_start_time, query_duration_ms, exception,
+ toInt8(type) AS type, log_comment
+ FROM clusterAllReplicas(%(cluster)s, system, query_log)
+ WHERE
+ event_time > now() - INTERVAL %(hours)s HOUR
+ AND JSONExtractString(log_comment, 'product') = 'experiments'
+ AND is_initial_query
+ AND query NOT LIKE %(not_query)s
+ {extra_filters}
+ )
+ GROUP BY query_id
+ ),
+ grouped AS (
+ SELECT *, coalesce(nullIf(experiment_query_group_id, ''), query_id) AS grp FROM per_query
+ ),
+ ranked AS (
+ SELECT grp, sum(query_duration_ms) AS total_duration_ms
+ FROM grouped
+ GROUP BY grp
+ ORDER BY total_duration_ms DESC
+ LIMIT 100
)
- GROUP BY query_id
- ORDER BY query_duration_ms DESC
- LIMIT 100
+ SELECT
+ g.query_id, g.query, g.query_start_time, g.query_duration_ms, g.exception, g.status,
+ g.team_id, g.query_type, g.experiment_name, g.experiment_metric_name, g.experiment_execution_path,
+ g.experiment_metric_type, g.experiment_funnel_order_type, g.experiment_id, g.experiment_exposures_path,
+ g.experiment_metric_events_path, g.experiment_query_surface, g.experiment_precompute_table,
+ g.experiment_query_group_id, r.total_duration_ms
+ FROM grouped AS g
+ INNER JOIN ranked AS r ON g.grp = r.grp
+ ORDER BY
+ r.total_duration_ms DESC,
+ g.grp,
+ g.experiment_query_surface = 'precompute_build' ASC,
+ g.query_duration_ms DESC
+ SETTINGS skip_unavailable_shards=1
"""
response = sync_execute(sql_query, params)
@@ -461,31 +526,34 @@ class DebugCHQueries(viewsets.ViewSet):
if org_ids:
arr_by_org = self._fetch_org_arr(org_ids)
- return Response(
- [
- {
- "query_id": row[0],
- "query": row[1],
- "timestamp": row[2],
- "execution_time": row[3],
- "exception": row[4],
- "status": row[5],
- "team_id": row[6],
- "team_name": teams_by_id.get(row[6], {}).get("team_name"),
- "organization_name": teams_by_id.get(row[6], {}).get("organization_name"),
- "organization_arr": arr_by_org.get(teams_by_id.get(row[6], {}).get("organization_id", ""), None),
- "query_type": row[7],
- "experiment_name": row[8],
- "experiment_metric_name": row[9],
- "experiment_execution_path": row[10],
- "experiment_metric_type": row[11],
- "experiment_funnel_order_type": row[12] or None,
- "experiment_id": row[13] or None,
- "experiment_exposures_path": row[14],
- "experiment_metric_events_path": row[15],
- "experiment_query_surface": row[16],
- "experiment_precompute_table": row[17],
- }
- for row in response
- ]
- )
+ # Row indices follow the final SELECT projection above.
+ def _record(row) -> dict:
+ team = teams_by_id.get(row[6], {})
+ return {
+ "query_id": row[0],
+ "query": row[1],
+ "timestamp": row[2],
+ "execution_time": row[3],
+ "exception": row[4],
+ "status": row[5],
+ "team_id": row[6],
+ "team_name": team.get("team_name"),
+ "organization_name": team.get("organization_name"),
+ "organization_arr": arr_by_org.get(team.get("organization_id", ""), None),
+ "query_type": row[7],
+ "experiment_name": row[8],
+ "experiment_metric_name": row[9],
+ "experiment_execution_path": row[10],
+ "experiment_metric_type": row[11],
+ "experiment_funnel_order_type": row[12] or None,
+ "experiment_id": row[13] or None,
+ "experiment_exposures_path": row[14],
+ "experiment_metric_events_path": row[15],
+ "experiment_query_surface": row[16],
+ "experiment_precompute_table": row[17],
+ "experiment_query_group_id": row[18],
+ "total_duration_ms": row[19],
+ "sub_queries": [],
+ }
+
+ return Response(_nest_subqueries([_record(row) for row in response]))
diff --git a/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr b/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr
index a1c0325ab25a..0839c952c78f 100644
--- a/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr
+++ b/posthog/temporal/tests/product_analytics/__snapshots__/test_upgrade_queries_workflow.ambr
@@ -11,14 +11,6 @@
OR query @? '$.** ? (
@.kind == "InsightVizNode" &&
(!exists(@.version) || @.version == null || @.version < 4)
- )'
- OR query @? '$.** ? (
- @.kind == "RetentionQuery" &&
- (!exists(@.version) || @.version == null || @.version < 2)
- )'
- OR query @? '$.** ? (
- @.kind == "StickinessQuery" &&
- (!exists(@.version) || @.version == null || @.version < 2)
)'
OR query @? '$.** ? (
@.kind == "TrendsQuery" &&