: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 precompute overview to query performance (#68980)
Juraj Majerike4a0abc8e275
diff --git a/frontend/src/scenes/instance/QueryPerformance/PrecomputeOverview.tsx b/frontend/src/scenes/instance/QueryPerformance/PrecomputeOverview.tsxnew file mode 100644index 000000000000..70d8049444c5--- /dev/null+++ b/frontend/src/scenes/instance/QueryPerformance/PrecomputeOverview.tsx@@ -0,0 +1,399 @@+import { useActions, useValues } from 'kea'++import { LemonButton } from '@posthog/lemon-ui'++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 { Tooltip } from 'lib/lemon-ui/Tooltip'+import { humanFriendlyDuration } from 'lib/utils/durations'+import { humanFriendlyNumber, humanizeBytes } from 'lib/utils/numbers'++import { PrecomputePathStats, queryPerformanceLogic } from './queryPerformanceLogic'++const TIME_RANGE_OPTIONS = [+ { label: '1h', hours: 1 },+ { label: '6h', hours: 6 },+ { label: '24h', hours: 24 },+ { label: '7d', hours: 168 },+]++const SKIP_REASON_LABELS: Record<string, string> = {+ team_disabled: 'Precompute off for team',+ min_runtime: 'Experiment <12h old',+ override_direct: 'Forced direct (query override)',+ data_warehouse: 'Data warehouse metric',+}++const EXCEPTION_CODE_LABELS: Record<string, string> = {+ '307': 'byte limit',+ '159': 'timeout',+ '241': 'out of memory',+ '202': 'cluster busy',+}++const formatMs = (ms: number | null): string => {+ if (ms == null) {+ return '–'+ }+ return ms >= 1000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.round(ms)}ms`+}++const formatPercent = (numerator: number, denominator: number): string =>+ denominator > 0 ? `${((numerator / denominator) * 100).toFixed(1)}%` : '–'++function StatCard({+ title,+ value,+ subtitle,+ tooltip,+ type,+}: {+ title: string+ value: string+ subtitle?: string+ tooltip?: string+ type?: LemonTagType+}): JSX.Element {+ const card = (+ <LemonCard hoverEffect={false} className="flex-1 min-w-52">+ <div className="text-xs text-muted">{title}</div>+ <div className={`text-xl font-semibold mt-1 ${type === 'danger' ? 'text-danger' : ''}`}>{value}</div>+ {subtitle && <div className="text-xs text-muted mt-1">{subtitle}</div>}+ </LemonCard>+ )+ return tooltip ? <Tooltip title={tooltip}>{card}</Tooltip> : card+}++interface DirectReasonRow {+ reason: string+ label: string+ count: number+ type: LemonTagType+}++interface PathPerfRow {+ path: string+ stats: PrecomputePathStats+}++export function PrecomputeOverview(): JSX.Element {+ const { precomputeOverview, precomputeOverviewLoading, overviewHoursBack } = useValues(queryPerformanceLogic)+ const { loadPrecomputeOverview, setOverviewHoursBack } = useActions(queryPerformanceLogic)++ const overview = precomputeOverview+ const precomputed = overview?.reads.by_exposures_path['precomputed']+ const direct = overview?.reads.by_exposures_path['direct_scan']++ const totalReads = overview?.reads.total ?? 0+ const precomputedReads = precomputed?.reads ?? 0+ const directReads = direct?.reads ?? 0+ // Reads that attempted precompute but still scanned events directly: they paid for the failed+ // build AND the full scan. This is the number that should stay near zero.+ const fallbackReads = direct?.attempted ?? 0+ const attemptedReads = precomputedReads + fallbackReads++ const builds = overview?.builds+ const jobs = overview?.jobs++ const directReasonRows: DirectReasonRow[] = direct+ ? [+ ...Object.entries(direct.skip_reasons).map(+ (entry): DirectReasonRow => ({+ reason: entry[0],+ label: SKIP_REASON_LABELS[entry[0]] ?? entry[0],+ count: entry[1],+ type: 'muted',+ })+ ),+ {+ reason: 'fallback',+ label: 'Attempted, but fell back (build failed / not ready)',+ count: fallbackReads,+ type: fallbackReads > 0 ? 'danger' : 'muted',+ } satisfies DirectReasonRow,+ ]+ .filter((row) => row.count > 0)+ .sort((a, b) => b.count - a.count)+ : []++ const directReasonColumns: LemonTableColumns<DirectReasonRow> = [+ {+ title: 'Reason',+ render: function Reason(_, row) {+ return <LemonTag type={row.type}>{row.label}</LemonTag>+ },+ },+ {+ title: 'Reads',+ width: 120,+ render: function Count(_, row) {+ return <span className="font-mono">{humanFriendlyNumber(row.count)}</span>+ },+ },+ {+ title: '% of direct reads',+ width: 140,+ render: function Share(_, row) {+ return <span className="font-mono">{formatPercent(row.count, directReads)}</span>+ },+ },+ ]++ const pathPerfRows: PathPerfRow[] = overview+ ? Object.entries(overview.reads.by_exposures_path)+ .filter(([, stats]) => stats.reads > 0)+ .map(([path, stats]) => ({ path, stats }))+ : []++ const pathPerfColumns: LemonTableColumns<PathPerfRow> = [+ {+ title: 'Exposures path',+ width: 160,+ render: function Path(_, row) {+ return (+ <LemonTag type={row.path === 'precomputed' ? 'success' : 'default'}>+ {row.path === 'precomputed' ? 'precomputed' : 'direct scan'}+ </LemonTag>+ )+ },+ },+ {+ title: 'Reads',+ width: 100,+ render: function Reads(_, row) {+ return <span className="font-mono">{humanFriendlyNumber(row.stats.reads)}</span>+ },+ },+ {+ title: 'Failed',+ width: 100,+ render: function Failed(_, row) {+ return (+ <span className={`font-mono ${row.stats.failed_reads > 0 ? 'text-danger' : ''}`}>+ {humanFriendlyNumber(row.stats.failed_reads)}+ </span>+ )+ },+ },+ {+ title: 'p50',+ width: 90,+ render: function P50(_, row) {+ return <span className="font-mono">{formatMs(row.stats.p50_duration_ms)}</span>+ },+ },+ {+ title: 'p90',+ width: 90,+ render: function P90(_, row) {+ return <span className="font-mono">{formatMs(row.stats.p90_duration_ms)}</span>+ },+ },+ {+ title: 'Avg read',+ width: 110,+ render: function AvgBytes(_, row) {+ return (+ <span className="font-mono">+ {row.stats.avg_read_bytes != null ? humanizeBytes(row.stats.avg_read_bytes) : '–'}+ </span>+ )+ },+ },+ {+ title: 'Total read',+ width: 110,+ render: function TotalBytes(_, row) {+ return <span className="font-mono">{humanizeBytes(row.stats.total_read_bytes)}</span>+ },+ },+ ]++ const metricEvents = overview?.reads.metric_events+ const meApplicable = metricEvents ? metricEvents.precomputed + metricEvents.direct_scan : 0++ return (+ <>+ <div className="flex flex-wrap items-center justify-between gap-2 mb-4">+ <p className="text-muted text-sm mb-0 max-w-200">+ Global health of exposure/metric-events lazy precomputation: how experiment metric reads are served,+ why they go direct, and whether the precompute builds themselves succeed. Aggregated from ClickHouse+ query_log and the preaggregation job table.+ </p>+ <div className="flex items-center gap-2">+ {TIME_RANGE_OPTIONS.map(({ label, hours }) => (+ <LemonButton+ key={hours}+ type={overviewHoursBack === hours ? 'primary' : 'tertiary'}+ size="small"+ onClick={() => setOverviewHoursBack(hours)}+ >+ {label}+ </LemonButton>+ ))}+ <LemonButton+ type="secondary"+ size="small"+ onClick={() => loadPrecomputeOverview()}+ disabledReason={precomputeOverviewLoading ? 'Loading...' : undefined}+ >+ Refresh+ </LemonButton>+ </div>+ </div>++ {!overview && precomputeOverviewLoading ? (+ <div className="flex flex-wrap gap-4 mb-4">+ {[0, 1, 2, 3].map((i) => (+ <LemonCard key={i} hoverEffect={false} className="flex-1 min-w-52">+ <LemonSkeleton className="h-3 w-2/3" />+ <LemonSkeleton className="h-6 w-1/2 mt-2" />+ <LemonSkeleton className="h-3 w-3/4 mt-2" />+ </LemonCard>+ ))}+ </div>+ ) : (+ <>+ <div className="flex flex-wrap gap-4 mb-4">+ <StatCard+ title="Precompute coverage"+ value={formatPercent(precomputedReads, totalReads)}+ subtitle={`${humanFriendlyNumber(precomputedReads)} of ${humanFriendlyNumber(+ totalReads+ )} metric reads used precomputed exposures`}+ tooltip="Share of ALL experiment metric reads served from the precomputed exposures table, including teams where precompute is off."+ />+ <StatCard+ title="Reliability when attempted"+ value={formatPercent(precomputedReads, attemptedReads)}+ subtitle={`${humanFriendlyNumber(+ fallbackReads+ )} reads fell back to a direct scan after attempting`}+ tooltip="Of reads that attempted precompute (no skip reason), how many were actually served from precomputed data. Fallbacks paid for the failed build AND the full events scan."+ type={attemptedReads > 0 && fallbackReads / attemptedReads > 0.05 ? 'danger' : undefined}+ />+ <StatCard+ title="Build success rate"+ value={builds ? formatPercent(builds.succeeded, builds.total) : '–'}+ subtitle={+ builds+ ? Object.entries(builds.by_table)+ .map(+ ([table, counts]) =>+ `${table}: ${humanFriendlyNumber(counts.succeeded)} ok / ${humanFriendlyNumber(counts.failed)} failed`+ )+ .join(' · ') || 'No builds in this window'+ : undefined+ }+ type={+ builds && builds.total > 0 && builds.failed / builds.total > 0.05 ? 'danger' : undefined+ }+ />+ <StatCard+ title="Reads per successful build"+ value={+ builds && builds.succeeded > 0 ? (precomputedReads / builds.succeeded).toFixed(1) : '–'+ }+ subtitle="Amortization: how often each build's data is reused"+ tooltip="Precomputed reads divided by successful builds in the window. Near or below 1 means we rebuild for almost every read (TTL churn or one-off views) and the cache isn't amortizing its cost."+ />+ </div>++ <div className="flex flex-wrap gap-4 mb-4">+ <StatCard+ title="Build cost"+ value={builds ? humanizeBytes(builds.total_read_bytes) : '–'}+ subtitle={+ builds+ ? `${humanFriendlyDuration(builds.total_duration_ms / 1000)} total ClickHouse time`+ : undefined+ }+ tooltip="Total bytes scanned and time spent by precompute-build INSERTs. This is the investment; the read-path savings are the return."+ />+ <StatCard+ title="Metric-events precompute"+ value={metricEvents ? formatPercent(metricEvents.precomputed, meApplicable) : '–'}+ subtitle={+ metricEvents+ ? `${humanFriendlyNumber(metricEvents.not_applicable)} reads not applicable (only ordered funnels qualify)`+ : undefined+ }+ tooltip="Hit rate of the metric-events precompute among reads where it applies. Not applicable covers mean/ratio/retention metrics, unordered/strict funnels, breakdowns, CUPED, and data warehouse metrics."+ />+ <StatCard+ title="Jobs (Postgres)"+ value={+ jobs+ ? `${humanFriendlyNumber(jobs.ready)} ready · ${humanFriendlyNumber(+ jobs.failed+ )} failed`+ : '–'+ }+ subtitle={+ jobs+ ? `${humanFriendlyNumber(jobs.pending)} pending · ${humanFriendlyNumber(+ jobs.stale_failed+ )} stale (executor crashed)`+ : undefined+ }+ tooltip="PreaggregationJob rows created in the window, across all lazy-computation users (experiments, web analytics, marketing analytics). Stale = a waiter marked the job failed because the owning executor stopped heartbeating."+ />+ <StatCard+ title="Stuck pending jobs"+ value={jobs ? humanFriendlyNumber(jobs.stuck_pending) : '–'}+ subtitle="PENDING for >15 min right now"+ tooltip="Jobs no INSERT will ever finish. Waiters block on these until stale detection fires, so a non-zero number here means slow experiment loads right now."+ type={jobs && jobs.stuck_pending > 0 ? 'danger' : undefined}+ />+ </div>++ <h3>Why reads went direct</h3>+ <LemonTable+ size="small"+ columns={directReasonColumns}+ dataSource={directReasonRows}+ loading={precomputeOverviewLoading}+ emptyState="No direct-scan reads in this window"+ className="overflow-visible! flex-none! mb-6 max-w-160"+ />++ <div className="flex items-center gap-2">+ <h3 className="mb-0">Read performance by path</h3>+ <Tooltip title="Indicative, not causal: teams with precompute enabled are typically the largest, so their direct scans would be even slower than the direct-scan row suggests.">+ <LemonTag type="muted">selection bias</LemonTag>+ </Tooltip>+ </div>+ <LemonTable+ size="small"+ columns={pathPerfColumns}+ dataSource={pathPerfRows}+ loading={precomputeOverviewLoading}+ emptyState="No experiment metric reads in this window"+ className="overflow-visible! flex-none! mt-2 mb-6"+ />++ {builds && builds.failed > 0 && (+ <>+ <h3>Build failures by exit code</h3>+ <div className="flex flex-wrap gap-2 mb-8">+ {Object.entries(builds.failures_by_code)+ .sort((a, b) => b[1] - a[1])+ .map(([code, count]) => (+ <LemonTag key={code} type="danger">+ {code}+ {EXCEPTION_CODE_LABELS[code]+ ? ` (${EXCEPTION_CODE_LABELS[code]})`+ : ''} ×{' '}+ {humanFriendlyNumber(count)}+ </LemonTag>+ ))}+ </div>+ </>+ )}+ </>+ )}+ </>+ )+}diff --git a/frontend/src/scenes/instance/QueryPerformance/QueryPerformance.tsx b/frontend/src/scenes/instance/QueryPerformance/QueryPerformance.tsxindex 2c053b817c41..ef375b05df99 100644--- a/frontend/src/scenes/instance/QueryPerformance/QueryPerformance.tsx+++ b/frontend/src/scenes/instance/QueryPerformance/QueryPerformance.tsx@@ -22,6 +22,7 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { CacheHealth } from './CacheHealth'+import { PrecomputeOverview } from './PrecomputeOverview'import { PrecomputationTeam, queryPerformanceLogic, SlowestQuery } from './queryPerformanceLogic'export const scene: SceneExport = {@@ -680,6 +681,11 @@ export function QueryPerformance(): JSX.Element {</>),},+ {+ key: 'precompute_overview',+ label: 'Precompute overview',+ content: <PrecomputeOverview />,+ },{key: 'cache_health',label: 'Cache health',diff --git a/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.ts b/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.tsindex b833418c6bba..ee0670ddb9fa 100644--- a/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.ts+++ b/frontend/src/scenes/instance/QueryPerformance/queryPerformanceLogic.ts@@ -15,7 +15,51 @@ export interface PrecomputationTeam {experiment_precomputation_enabled: boolean}-export type ExperimentsTab = 'slowest_queries' | 'cache_health'+export type ExperimentsTab = 'slowest_queries' | 'precompute_overview' | 'cache_health'++export interface PrecomputePathStats {+ reads: number+ failed_reads: number+ // Reads where precompute was attempted (no skip reason). On the direct_scan path these paid+ // for the build AND the full events scan — the failure bucket to watch.+ attempted: number+ skip_reasons: Record<string, number>+ avg_duration_ms: number | null+ p50_duration_ms: number | null+ p90_duration_ms: number | null+ avg_read_bytes: number | null+ total_read_bytes: number+}++export interface PrecomputeBuildStats {+ total: number+ succeeded: number+ failed: number+ total_duration_ms: number+ total_read_bytes: number+ by_table: Record<string, { succeeded: number; failed: number }>+ failures_by_code: Record<string, number>+}++export interface PrecomputeJobStats {+ ready: number+ failed: number+ pending: number+ stale_failed: number+ stuck_pending: number+}++export interface PrecomputeOverviewResponse {+ hours: number+ reads: {+ total: number+ failed: number+ by_exposures_path: Record<string, PrecomputePathStats>+ metric_events: { precomputed: number; direct_scan: number; not_applicable: number }+ }+ builds: PrecomputeBuildStats+ jobs: PrecomputeJobStats+}export interface CachePartitionStats {partition: string // YYYYMMDD — the expiry day of the partition (tables partition by toYYYYMMDD(expires_at))@@ -92,6 +136,7 @@ export const queryPerformanceLogic = kea<queryPerformanceLogicType>([setMetricTypeFilter: (metricType: string) => ({ metricType }),setExceptionCodeFilter: (exceptionCode: string) => ({ exceptionCode }),setExperimentsTab: (tab: ExperimentsTab) => ({ tab }),+ setOverviewHoursBack: (hours: number) => ({ hours }),}),reducers({search: [@@ -136,6 +181,12 @@ export const queryPerformanceLogic = kea<queryPerformanceLogicType>([setExperimentsTab: (_, { tab }) => tab,},],+ overviewHoursBack: [+ 24,+ {+ setOverviewHoursBack: (_, { hours }) => hours,+ },+ ],}),loaders(({ values }) => ({precomputationTeams: [@@ -171,6 +222,14 @@ export const queryPerformanceLogic = kea<queryPerformanceLogicType>([},},],+ precomputeOverview: [+ null as PrecomputeOverviewResponse | null,+ {+ loadPrecomputeOverview: async () => {+ return await api.get(`api/debug_ch_queries/precompute_overview/?hours=${values.overviewHoursBack}`)+ },+ },+ ],slowestQueries: [[] as SlowestQuery[],{@@ -238,12 +297,16 @@ export const queryPerformanceLogic = kea<queryPerformanceLogicType>([setExceptionCodeFilter: () => {actions.loadSlowestQueries()},+ setOverviewHoursBack: () => {+ actions.loadPrecomputeOverview()+ },})),afterMount(({ actions }) => {if (userLogic.findMounted()?.values.user?.is_staff) {actions.loadPrecomputationTeams()actions.loadSlowestQueries()actions.loadCacheHealth()+ actions.loadPrecomputeOverview()}}),])diff --git a/posthog/api/debug_ch_queries.py b/posthog/api/debug_ch_queries.pyindex 49c6bc53d2d6..800a93308bbf 100644--- a/posthog/api/debug_ch_queries.py+++ b/posthog/api/debug_ch_queries.py@@ -4,6 +4,7 @@ import loggingfrom datetime import UTC, datetime, timedeltafrom typing import Any, Optional+from django.db.models import Countfrom django.utils.timezone import nowfrom dateutil.relativedelta import relativedelta@@ -35,6 +36,7 @@ from posthog.permissions import APIScopePermissionfrom posthog.settings.base_variables import DEBUGfrom posthog.settings.data_stores import CLICKHOUSE_CLUSTER, CLICKHOUSE_DATABASE+from products.analytics_platform.backend.models import PreaggregationJobfrom products.experiments.backend.models.team_experiments_config import TeamExperimentsConfiglogger = logging.getLogger(__name__)@@ -696,6 +698,208 @@ class DebugCHQueries(viewsets.ViewSet):return Response(_nest_subqueries([_record(row) for row in response]))+ # Skip reasons the runner tags on reads that never attempted precompute. An empty reason on a+ # direct-scan read means precompute WAS attempted but the data wasn't ready (build failed/slow) —+ # that read paid for the build AND the full events scan, so it's the bucket to watch.+ _PRECOMPUTE_SKIP_REASONS = ("team_disabled", "min_runtime", "override_direct", "data_warehouse")++ @action(detail=False, methods=["GET"], url_path="precompute_overview", required_scopes=["query_performance:read"])+ def precompute_overview(self, request):+ if not request.user.is_staff:+ raise exceptions.PermissionDenied("Only staff users can view the precompute overview.")++ tag_queries(product=Product.INTERNAL, feature=Feature.DEBUG_QUERY)++ try:+ hours = int(request.query_params.get("hours", 24))+ except (TypeError, ValueError):+ raise exceptions.ValidationError("hours must be an integer.")+ hours = max(1, min(hours, 168)) # clamp to 1h–7d++ params: dict = {+ "cluster": CLICKHOUSE_CLUSTER,+ "hours": hours,+ "not_query": "%request:_api_debug_ch_queries_%",+ }++ skip_reason_counts = ",\n".join(+ f"countIf(skip_reason = '{reason}') AS skip_{reason}" for reason in self._PRECOMPUTE_SKIP_REASONS+ )+ # One terminal query_log row per query (toInt8(type) > 1 excludes QueryStart), so plain+ # counts are per-query without the GROUP BY query_id dedup the slowest_queries endpoint needs.+ # Duration/bytes stats only cover successful reads — failed ones have truncated durations.+ # nosemgrep: clickhouse-fstring-param-audit - skip_reason_counts is built from a hardcoded tuple+ reads_sql = f"""+ SELECT+ coalesce(+ nullIf(JSONExtractString(log_comment, 'experiment_exposures_path'), ''),+ JSONExtractString(log_comment, 'experiment_execution_path')+ ) AS exposures_path,+ count() AS reads,+ countIf(exception_code != 0) AS failed_reads,+ {skip_reason_counts},+ countIf(skip_reason = '') AS attempted,+ countIf(JSONExtractString(log_comment, 'experiment_metric_events_path') = 'precomputed') AS me_precomputed,+ countIf(JSONExtractString(log_comment, 'experiment_metric_events_path') = 'direct_scan') AS me_direct_scan,+ countIf(JSONExtractString(log_comment, 'experiment_metric_events_path') = 'not_applicable') AS me_not_applicable,+ avgIf(query_duration_ms, exception_code = 0) AS avg_duration_ms,+ quantileIf(0.5)(query_duration_ms, exception_code = 0) AS p50_duration_ms,+ quantileIf(0.9)(query_duration_ms, exception_code = 0) AS p90_duration_ms,+ avgIf(read_bytes, exception_code = 0) AS avg_read_bytes,+ sum(read_bytes) AS total_read_bytes+ FROM (+ SELECT+ query_duration_ms, exception_code, read_bytes, log_comment,+ JSONExtractString(log_comment, 'experiment_precompute_skip_reason') AS skip_reason+ FROM clusterAllReplicas(%(cluster)s, system, query_log)+ WHERE+ event_time > now() - INTERVAL %(hours)s HOUR+ AND JSONExtractString(log_comment, 'product') = 'experiments'+ AND JSONExtractString(log_comment, 'experiment_query_surface') = 'metric'+ AND is_initial_query+ AND toInt8(type) > 1+ AND query NOT LIKE %(not_query)s+ )+ GROUP BY exposures_path+ SETTINGS skip_unavailable_shards=1+ """+ reads_response = sync_execute(reads_sql, params)++ empty_path = {+ "reads": 0,+ "failed_reads": 0,+ "attempted": 0,+ "avg_duration_ms": None,+ "p50_duration_ms": None,+ "p90_duration_ms": None,+ "avg_read_bytes": None,+ "total_read_bytes": 0,+ }+ # Must match the projection order of reads_sql.+ reads_columns = (+ "exposures_path",+ "reads",+ "failed_reads",+ *(f"skip_{reason}" for reason in self._PRECOMPUTE_SKIP_REASONS),+ "attempted",+ "me_precomputed",+ "me_direct_scan",+ "me_not_applicable",+ "avg_duration_ms",+ "p50_duration_ms",+ "p90_duration_ms",+ "avg_read_bytes",+ "total_read_bytes",+ )++ def _empty_path_entry() -> dict:+ return {**empty_path, "skip_reasons": dict.fromkeys(self._PRECOMPUTE_SKIP_REASONS, 0)}++ reads_by_path: dict[str, dict] = {+ "precomputed": _empty_path_entry(),+ "direct_scan": _empty_path_entry(),+ }+ metric_events = {"precomputed": 0, "direct_scan": 0, "not_applicable": 0}+ for raw_row in reads_response:+ row = dict(zip(reads_columns, raw_row))+ path = row["exposures_path"] or "direct_scan"+ entry = reads_by_path.setdefault(path, _empty_path_entry())+ entry["reads"] += row["reads"]+ entry["failed_reads"] += row["failed_reads"]+ entry["attempted"] += row["attempted"]+ entry["total_read_bytes"] += row["total_read_bytes"]+ if row["reads"] > 0:+ for stat in ("avg_duration_ms", "p50_duration_ms", "p90_duration_ms", "avg_read_bytes"):+ entry[stat] = row[stat]+ for reason in self._PRECOMPUTE_SKIP_REASONS:+ entry["skip_reasons"][reason] += row[f"skip_{reason}"]+ metric_events["precomputed"] += row["me_precomputed"]+ metric_events["direct_scan"] += row["me_direct_scan"]+ metric_events["not_applicable"] += row["me_not_applicable"]++ builds_sql = """+ SELECT+ JSONExtractString(log_comment, 'experiment_precompute_table') AS build_table,+ exception_code,+ count() AS builds,+ sum(query_duration_ms) AS total_duration_ms,+ sum(read_bytes) AS total_read_bytes+ FROM clusterAllReplicas(%(cluster)s, system, query_log)+ WHERE+ event_time > now() - INTERVAL %(hours)s HOUR+ AND JSONExtractString(log_comment, 'product') = 'experiments'+ AND JSONExtractString(log_comment, 'experiment_query_surface') = 'precompute_build'+ AND is_initial_query+ AND toInt8(type) > 1+ AND query NOT LIKE %(not_query)s+ GROUP BY build_table, exception_code+ SETTINGS skip_unavailable_shards=1+ """+ builds_response = sync_execute(builds_sql, params)++ builds: dict[str, Any] = {+ "total": 0,+ "succeeded": 0,+ "failed": 0,+ "total_duration_ms": 0,+ "total_read_bytes": 0,+ "by_table": {},+ "failures_by_code": {},+ }+ for build_table, exception_code, count, total_duration_ms, total_read_bytes in builds_response:+ table_key = build_table or "unknown"+ table_entry = builds["by_table"].setdefault(table_key, {"succeeded": 0, "failed": 0})+ builds["total"] += count+ builds["total_duration_ms"] += total_duration_ms+ builds["total_read_bytes"] += total_read_bytes+ if exception_code == 0:+ builds["succeeded"] += count+ table_entry["succeeded"] += count+ else:+ builds["failed"] += count+ table_entry["failed"] += count+ code_key = str(exception_code)+ builds["failures_by_code"][code_key] = builds["failures_by_code"].get(code_key, 0) + count++ window_start = now() - timedelta(hours=hours)+ job_status_counts = dict(+ PreaggregationJob.objects.filter(created_at__gte=window_start).values_list("status").annotate(n=Count("id"))+ )+ jobs = {+ "ready": job_status_counts.get(PreaggregationJob.Status.READY, 0),+ "failed": job_status_counts.get(PreaggregationJob.Status.FAILED, 0),+ "pending": job_status_counts.get(PreaggregationJob.Status.PENDING, 0),+ # Marked FAILED by a waiter because the owning executor stopped heartbeating — crashes,+ # OOM-killed pods. Invisible in query_log (the INSERT never finished), so PG is the only source.+ "stale_failed": PreaggregationJob.objects.filter(+ created_at__gte=window_start,+ status=PreaggregationJob.Status.FAILED,+ error__startswith="Job was stale",+ ).count(),+ # PENDING far past any plausible INSERT runtime: nothing will ever mark these, and they+ # block the range they cover (waiters keep waiting on them until staleness detection fires).+ "stuck_pending": PreaggregationJob.objects.filter(+ status=PreaggregationJob.Status.PENDING,+ created_at__lt=now() - timedelta(minutes=15),+ ).count(),+ }++ total_reads = sum(entry["reads"] for entry in reads_by_path.values())+ total_failed_reads = sum(entry["failed_reads"] for entry in reads_by_path.values())+ return Response(+ {+ "hours": hours,+ "reads": {+ "total": total_reads,+ "failed": total_failed_reads,+ "by_exposures_path": reads_by_path,+ "metric_events": metric_events,+ },+ "builds": builds,+ "jobs": jobs,+ }+ )+@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: