: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 precomputed read latency trends to staff tooling (#96150)
Juraj Majerik91ac1e8e3468
diff --git a/.agents/skills/analyzing-experiment-query-performance/SKILL.md b/.agents/skills/analyzing-experiment-query-performance/SKILL.mdindex e91b7da80894..af3805569906 100644--- a/.agents/skills/analyzing-experiment-query-performance/SKILL.md+++ b/.agents/skills/analyzing-experiment-query-performance/SKILL.md@@ -13,7 +13,7 @@ description: ># Analyzing experiment query performance-The `/experiments/staff` scene (staff-only UI, "Experiments staff tools") is backed by three GET endpoints+The `/experiments/staff` scene (staff-only UI, "Experiments staff tools") is backed by a set of GET endpointsthat are also callable directly with a personal API key.They return the exact data the UI renders, sourced from ClickHouse `query_log_archive`(experiment queries only, `lc_product = 'experiments'`), `system.parts`,@@ -131,6 +131,19 @@ Aggregate precompute health for the window. One param: `hours` (1–168, defaultDuration/bytes percentiles cover **successful** reads only (failed reads have truncated durations).+### GET `/api/debug_ch_queries/precompute_timeseries/`++Bucketed history behind the Trends tab. One param: `hours` (1–504, default 168).+Returns zero-filled arrays aligned to `buckets` (hourly up to 48h, daily beyond):+read counts (`total`, `precomputed`, `fallback`),+latency and cost of the precomputed read path+(`precomputed_p50_duration_ms`, `precomputed_p90_duration_ms`, `precomputed_avg_read_bytes`;+successful precomputed reads only).+The latency and bytes-per-read series should stay flat as the preaggregation tables grow —+a sustained rise means precomputed reads are scanning more than their own jobs' rows,+which breaks the core assumption that read cost tracks experiment size, not cache size.+Also `builds.failed_by_code` and `builds.failed_read_bytes`.+### GET `/api/debug_ch_queries/cache_health/`No params.diff --git a/frontend/src/scenes/experiments/staff/PrecomputeTrends.tsx b/frontend/src/scenes/experiments/staff/PrecomputeTrends.tsxindex 7cb507038c00..907cf4b7faf5 100644--- a/frontend/src/scenes/experiments/staff/PrecomputeTrends.tsx+++ b/frontend/src/scenes/experiments/staff/PrecomputeTrends.tsx@@ -6,6 +6,7 @@ import type { Series } from '@posthog/quill-charts'import { useChartTheme } from 'lib/charts/hooks'import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { formatDurationMilliseconds } from 'lib/utils/durations'import { humanizeBytes } from 'lib/utils/numbers'import { EXCEPTION_CODE_LABELS, queryPerformanceLogic } from './queryPerformanceLogic'@@ -47,6 +48,17 @@ export function PrecomputeTrends(): JSX.Element {const fallbackSeries: Series[] = ts ? [{ key: 'fallback', label: 'Fallback reads', data: ts.reads.fallback }] : []+ const latencySeries: Series[] = ts+ ? [+ { key: 'p50', label: 'p50', data: ts.reads.precomputed_p50_duration_ms },+ { key: 'p90', label: 'p90', data: ts.reads.precomputed_p90_duration_ms },+ ]+ : []++ const bytesPerReadSeries: Series[] = ts+ ? [{ key: 'avg_bytes', label: 'Avg bytes read', data: ts.reads.precomputed_avg_read_bytes }]+ : []+// One stacked series per exit code, biggest offenders first so the legend leads with them.const failureSeries: Series[] = ts? Object.entries(ts.builds.failed_by_code)@@ -81,7 +93,7 @@ export function PrecomputeTrends(): JSX.Element {</div>{!ts && precomputeTimeseriesLoading ? (<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">- {[0, 1, 2, 3].map((i) => (+ {[0, 1, 2, 3, 4, 5].map((i) => (<LemonSkeleton key={i} className="h-56 w-full" />))}</div>@@ -103,6 +115,33 @@ export function PrecomputeTrends(): JSX.Element {config={{ xAxis, showGrid: true }}/></ChartCard>+ <ChartCard title="Precomputed read latency (p50/p90, successful reads only; should stay flat as the cache grows)">+ <TimeSeriesLineChart+ series={latencySeries}+ labels={ts.buckets}+ theme={theme}+ config={{+ xAxis,+ yAxis: { tickFormatter: (value: number) => formatDurationMilliseconds(value) },+ tooltip: { valueFormatter: (value: number) => formatDurationMilliseconds(value) },+ showGrid: true,+ legend: { show: true },+ }}+ />+ </ChartCard>+ <ChartCard title="Bytes read per precomputed read (average; a rise means reads scan more than their own rows)">+ <TimeSeriesLineChart+ series={bytesPerReadSeries}+ labels={ts.buckets}+ theme={theme}+ config={{+ xAxis,+ yAxis: { tickFormatter: (value: number) => humanizeBytes(value) },+ tooltip: { valueFormatter: (value: number) => humanizeBytes(value) },+ showGrid: true,+ }}+ />+ </ChartCard><ChartCard title="Failed builds by exit code"><TimeSeriesBarChartseries={failureSeries}diff --git a/frontend/src/scenes/experiments/staff/queryPerformanceLogic.ts b/frontend/src/scenes/experiments/staff/queryPerformanceLogic.tsindex 533dbf634a29..04f8515f8b92 100644--- a/frontend/src/scenes/experiments/staff/queryPerformanceLogic.ts+++ b/frontend/src/scenes/experiments/staff/queryPerformanceLogic.ts@@ -80,6 +80,10 @@ export interface PrecomputeTimeseriesResponse {total: number[]precomputed: number[]fallback: number[]+ // Successful precomputed-path reads only; 0 where a bucket has none+ precomputed_p50_duration_ms: number[]+ precomputed_p90_duration_ms: number[]+ precomputed_avg_read_bytes: number[]}builds: {failed_by_code: Record<string, number[]>diff --git a/posthog/api/debug_ch_queries.py b/posthog/api/debug_ch_queries.pyindex 21db4d239a6f..0a6d3cf8ca04 100644--- a/posthog/api/debug_ch_queries.py+++ b/posthog/api/debug_ch_queries.py@@ -991,9 +991,9 @@ class DebugCHQueries(viewsets.ViewSet):"""Bucketed history of the precompute overview's headline numbers, for the trend charts.Returns arrays aligned to `buckets` (zero-filled, so charts get a continuous axis):- read counts by path outcome, failed-build counts by exit code, and bytes wasted on- failed builds. Hourly buckets up to 48h, daily beyond; window capped at 21 days- (query_log_archive retention).+ read counts by path outcome, latency and bytes per precomputed read, failed-build+ counts by exit code, and bytes wasted on failed builds. Hourly buckets up to 48h,+ daily beyond; window capped at 21 days (query_log_archive retention)."""if not request.user.is_staff:raise exceptions.PermissionDenied("Only staff users can view the precompute timeseries.")@@ -1013,16 +1013,31 @@ class DebugCHQueries(viewsets.ViewSet):"not_query": "%request:_api_debug_ch_queries_%",}+ # Latency and bytes stats cover successful precomputed reads only, matching the+ # overview endpoint (failed reads have truncated durations). ifNotFinite guards the+ # empty buckets, where quantileIf/avgIf return nan and nan is not valid JSON.# nosemgrep: clickhouse-fstring-param-audit - bucket_fn is one of two hardcoded function namesreads_sql = f"""SELECTformatDateTime({bucket_fn}(event_time, 'UTC'), '%%Y-%%m-%%dT%%H:%%i:%%SZ', 'UTC') AS bucket,count() AS reads,countIf(exposures_path = 'precomputed') AS precomputed_reads,- countIf(exposures_path != 'precomputed' AND skip_reason = '') AS fallback_reads+ countIf(exposures_path != 'precomputed' AND skip_reason = '') AS fallback_reads,+ ifNotFinite(+ quantileIf(0.5)(query_duration_ms, exposures_path = 'precomputed' AND exception_code = 0), 0+ ) AS precomputed_p50_duration_ms,+ ifNotFinite(+ quantileIf(0.9)(query_duration_ms, exposures_path = 'precomputed' AND exception_code = 0), 0+ ) AS precomputed_p90_duration_ms,+ ifNotFinite(+ avgIf(read_bytes, exposures_path = 'precomputed' AND exception_code = 0), 0+ ) AS precomputed_avg_read_bytesFROM (SELECTevent_time,+ query_duration_ms,+ read_bytes,+ exception_code,coalesce(nullIf(toString(log_comment.experiment_exposures_path), ''),ifNull(toString(log_comment.experiment_execution_path), '')@@ -1068,15 +1083,29 @@ class DebugCHQueries(viewsets.ViewSet):reads = [0] * nprecomputed_reads = [0] * nfallback_reads = [0] * n+ precomputed_p50_duration_ms = [0] * n+ precomputed_p90_duration_ms = [0] * n+ precomputed_avg_read_bytes = [0] * nfailed_build_read_bytes = [0] * nfailed_builds_by_code: dict[str, list[int]] = {}- for bucket, bucket_reads, bucket_precomputed, bucket_fallback in reads_response:+ for (+ bucket,+ bucket_reads,+ bucket_precomputed,+ bucket_fallback,+ bucket_p50,+ bucket_p90,+ bucket_bytes,+ ) in reads_response:i = index_by_bucket.get(bucket)if i is None:continuereads[i] = bucket_readsprecomputed_reads[i] = bucket_precomputedfallback_reads[i] = bucket_fallback+ precomputed_p50_duration_ms[i] = round(bucket_p50)+ precomputed_p90_duration_ms[i] = round(bucket_p90)+ precomputed_avg_read_bytes[i] = round(bucket_bytes)for bucket, exception_code, bucket_builds, bucket_read_bytes in builds_response:i = index_by_bucket.get(bucket)if i is None or exception_code == 0:@@ -1094,6 +1123,9 @@ class DebugCHQueries(viewsets.ViewSet):"total": reads,"precomputed": precomputed_reads,"fallback": fallback_reads,+ "precomputed_p50_duration_ms": precomputed_p50_duration_ms,+ "precomputed_p90_duration_ms": precomputed_p90_duration_ms,+ "precomputed_avg_read_bytes": precomputed_avg_read_bytes,},"builds": {"failed_by_code": failed_builds_by_code,diff --git a/posthog/api/test/test_debug_ch_queries.py b/posthog/api/test/test_debug_ch_queries.pyindex c406a7dfdeb7..f948b3a5a331 100644--- a/posthog/api/test/test_debug_ch_queries.py+++ b/posthog/api/test/test_debug_ch_queries.py@@ -150,6 +150,30 @@ class TestDebugCHQuery(APIBaseTest):self.assertEqual(data["tables"]["exposures"]["written_bytes"][i], 100)self.assertEqual(sum(data["tables"]["metric_events"]["written_rows"]), 0)+ def test_precompute_timeseries_latency_series_are_bucket_aligned_and_zero_filled(self):+ # Same positional-indexing contract as cache_growth: the latency and bytes-per-read+ # series must align to `buckets` and stay zero-filled where a bucket has no reads.+ self.user.is_staff = True+ self.user.save()+ bucket = datetime.now(UTC).strftime("%Y-%m-%dT00:00:00Z")++ with patch(+ "posthog.api.debug_ch_queries.sync_execute",+ side_effect=[[(bucket, 5, 4, 1, 120.0, 450.0, 2048.0)], []],+ ):+ resp = self.client.get("/api/debug_ch_queries/precompute_timeseries/?hours=336")++ self.assertEqual(resp.status_code, HTTP_200_OK, resp.content)+ data = resp.json()+ i = data["buckets"].index(bucket)+ reads = data["reads"]+ for series in ("precomputed_p50_duration_ms", "precomputed_p90_duration_ms", "precomputed_avg_read_bytes"):+ self.assertEqual(len(reads[series]), len(data["buckets"]))+ self.assertEqual(reads["precomputed_p50_duration_ms"][i], 120)+ self.assertEqual(reads["precomputed_p90_duration_ms"][i], 450)+ self.assertEqual(reads["precomputed_avg_read_bytes"][i], 2048)+ self.assertEqual(sum(reads["precomputed_p50_duration_ms"]), 120)+@patch("posthog.api.debug_ch_queries.sync_execute", return_value=[])def test_slowest_queries_pat_with_scope_and_staff_allowed(self, _mock_execute):self.user.is_staff = True