: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(analytics-platform): precompute health debug endpoint with per-team economics (#78486)
Lucas Ricoy0651133e281e
diff --git a/posthog/api/debug_ch_queries.py b/posthog/api/debug_ch_queries.pyindex d3d465100e2e..6b8140df54b4 100644--- a/posthog/api/debug_ch_queries.py+++ b/posthog/api/debug_ch_queries.py@@ -5,11 +5,13 @@ import loggingfrom datetime import UTC, datetime, timedeltafrom typing import Any, Optional+from django.core.cache import cachefrom django.db.models import Countfrom django.utils.timezone import nowfrom dateutil.relativedelta import relativedelta-from drf_spectacular.utils import extend_schema+from drf_spectacular.types import OpenApiTypes+from drf_spectacular.utils import OpenApiParameter, extend_schemafrom loginas.utils import is_impersonated_sessionfrom rest_framework import exceptions, viewsetsfrom rest_framework.decorators import action@@ -39,6 +41,9 @@ from posthog.settings.data_stores import CLICKHOUSE_AUX_CLUSTER, CLICKHOUSE_CLUSfrom products.analytics_platform.backend.models import PreaggregationJobfrom products.experiments.backend.hogql_queries.types import PrecomputeSkipReasonfrom products.experiments.backend.models.team_experiments_config import TeamExperimentsConfig+from products.web_analytics.backend.hogql_queries.web_lazy_precompute_common import (+ BACKGROUND_WARMING_TRIGGERS as WEB_ANALYTICS_WARMING_TRIGGERS,+)logger = logging.getLogger(__name__)@@ -164,6 +169,55 @@ def _cache_table_stats() -> list[dict]:return list(stats.values())+# Products on the shared lazy-precompute framework, keyed by the `product` query+# param of `precompute_health`. Lazy-served reads share the framework's uniform+# `_lazy_query` tag suffix, scoped by `log_comment_product` (the product tag the+# runners set) so registered products cannot cross-contaminate each other's hit+# ratios. `warming_triggers` are the product's OWN background-warmer triggers,+# imported from the product module — deliberately not the framework-shared+# "warmingV2", which belongs to the fleet-wide generic insight cache warmer and+# would attribute every product's insight warming to this product's economics.+# `eligible_live_query_types` — live (non-precomputed) read tags whose shapes the+# product's lazy path could have served, the denominator of its hit ratio. When a+# product grows a new live strategy tag, add it here or the ratio undercounts+# that family's misses.+_PRECOMPUTE_PRODUCTS: dict[str, dict[str, Any]] = {+ "web_analytics": {+ "log_comment_product": "web_analytics",+ "warming_triggers": tuple(sorted(WEB_ANALYTICS_WARMING_TRIGGERS)),+ "eligible_live_query_types": (+ "web_overview_query",+ "web_overview_preaggregated_query",+ "web_overview_no_join_query",+ "web_overview_session_id_set_query",+ "stats_table_main_query",+ "stats_table_path_bounce_query",+ "stats_table_path_bounce_and_avg_time_query",+ "stats_table_no_join_path_bounce_query",+ "stats_table_no_join_path_bounce_and_avg_time_query",+ "stats_table_session_id_set_path_bounce_query",+ "stats_table_session_id_set_path_bounce_and_avg_time_query",+ "stats_table_frustration_metrics_query",+ "stats_table_entry_bounce_query",+ "stats_table_preaggregated_query",+ "stats_table_preaggregated_path_breakdown_query",+ "stats_table_preaggregated_entry_bounce_query",+ "web_goals_query",+ "web_vitals_path_breakdown_query",+ ),+ },+}++# Reads that arrive through these channels are not user-facing dashboard traffic+# (background warming, batch workflows, API scripts) and would distort the ratio.+_PRECOMPUTE_EXCLUDED_WORKLOADS = ("Workload.OFFLINE", "OFFLINE")++# One replica being down must degrade this observability endpoint to+# partial data, not take it out entirely — the endpoint exists precisely+# for incidents, which is when replicas tend to be missing.+_PRECOMPUTE_HEALTH_QUERY_SETTINGS = {"skip_unavailable_shards": 1, "max_execution_time": 90}++def _bucket_axis(hours: int) -> tuple[str, str, list[str], dict[str, int]]:"""Zero-fillable time axis for the timeseries endpoints: hourly buckets up to 48h, daily beyond.@@ -1153,6 +1207,344 @@ class DebugCHQueries(viewsets.ViewSet):return Response({"tables": _cache_table_stats()})+ @extend_schema(+ description="Lazy-precompute health for a product on the shared framework: hourly hit "+ "ratio (lazy-served vs eligible live reads), warmer activity, per-family miss breakdown, "+ "and per-team warmed/missing rankings. `product` selects the vocabulary "+ "(default web_analytics). Staff only.",+ parameters=[+ OpenApiParameter(+ name="product",+ type=OpenApiTypes.STR,+ enum=sorted(_PRECOMPUTE_PRODUCTS),+ required=False,+ description="Precompute vocabulary to report on. Defaults to web_analytics.",+ ),+ OpenApiParameter(+ name="hours",+ type=OpenApiTypes.INT,+ required=False,+ description="Look-back window in hours. Clamped to 1-168 (7 days). Defaults to 24.",+ ),+ OpenApiParameter(+ name="team_id",+ type=OpenApiTypes.INT,+ required=False,+ description="Narrow every section to one team's reads. Fleet-wide when omitted.",+ ),+ ],+ responses={200: dict},+ )+ @action(detail=False, methods=["GET"], url_path="precompute_health", required_scopes=["query_performance:read"])+ def precompute_health(self, request):+ if not request.user.is_staff:+ raise exceptions.PermissionDenied("Only staff users can view precompute health.")++ tag_queries(product=Product.INTERNAL, feature=Feature.DEBUG_QUERY)++ product = request.query_params.get("product", "web_analytics")+ if product not in _PRECOMPUTE_PRODUCTS:+ raise exceptions.ValidationError(f"product must be one of: {', '.join(sorted(_PRECOMPUTE_PRODUCTS))}.")+ vocabulary = _PRECOMPUTE_PRODUCTS[product]++ 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; query_log retention bounds it anyway++ # Fleet-wide by default (the warmer is one fleet-level system); a team_id+ # narrows every section to that tenant's reads.+ team_id_filter: Optional[int] = None+ if request.query_params.get("team_id"):+ try:+ team_id_filter = int(request.query_params["team_id"])+ except (TypeError, ValueError):+ raise exceptions.ValidationError("team_id must be an integer.")+ if team_id_filter <= 0:+ raise exceptions.ValidationError("team_id must be a positive integer.")++ # Identical params yield near-identical answers within minutes, but every+ # request costs several fleet-wide query_log scans — polling automation+ # must not multiply that load onto the shared cluster.+ response_cache_key = f"precompute_health/{product}/{hours}/{team_id_filter}"+ cached_payload = cache.get(response_cache_key)+ if cached_payload is not None:+ return Response(cached_payload)++ params: dict = {+ "hours": hours,+ "cluster": CLICKHOUSE_CLUSTER,+ "eligible_live_types": vocabulary["eligible_live_query_types"],+ "warming_triggers": vocabulary["warming_triggers"],+ "log_product": vocabulary["log_comment_product"],+ "excluded_workloads": _PRECOMPUTE_EXCLUDED_WORKLOADS,+ }+ team_filter_sql = ""+ if team_id_filter is not None:+ team_filter_sql = " AND JSONExtractInt(log_comment, 'team_id') = %(team_id)s"+ params["team_id"] = team_id_filter++ # One failed scan (a timeout on a strained cluster, a memory limit) must+ # cost its own section, not 500 the whole response — this endpoint is for+ # incidents, when scans are slowest. Mirrors _cache_table_stats.+ unavailable_sections: list[str] = []++ def run_section(name: str, query: str) -> list:+ try:+ return sync_execute(query, params, settings=_PRECOMPUTE_HEALTH_QUERY_SETTINGS)+ except Exception:+ logger.exception("precompute_health: section %s failed", name)+ unavailable_sections.append(name)+ return []++ # Shared read predicate: the product's lazy-served reads (framework+ # `_lazy_query` suffix, scoped by the product tag so another registered+ # product's lazy reads cannot inflate this product's numerator) or its+ # eligible live reads. The LIKE prefilter keeps the JSON parsing off the+ # bulk of query_log rows that never carried a query_type tag.+ read_predicate = """log_comment LIKE '%%"query_type"%%'+ AND (+ (+ endsWith(JSONExtractString(log_comment, 'query_type'), '_lazy_query')+ AND JSONExtractString(log_comment, 'product') = %(log_product)s+ )+ OR JSONExtractString(log_comment, 'query_type') IN %(eligible_live_types)s+ )"""++ # User-facing reads only: background workloads, temporal batch requests,+ # and API-key scripts would distort the ratio. Exception rows are counted+ # too — tenants whose live reads FAIL are the ones precompute would help+ # most, and dropping them hid exactly those teams from the rankings.+ user_facing_sql = """+ AND JSONExtractString(log_comment, 'workload') NOT IN %(excluded_workloads)s+ AND JSONExtractString(log_comment, 'kind') != 'temporal'+ AND JSONExtractString(log_comment, 'access_method') != 'personal_api_key'"""++ hourly_rows = run_section(+ "hourly",+ f"""+ SELECT+ toStartOfHour(event_time) AS hour,+ countIf(endsWith(JSONExtractString(log_comment, 'query_type'), '_lazy_query')) AS lazy_hits,+ countIf(JSONExtractString(log_comment, 'query_type') IN %(eligible_live_types)s) AS eligible_live,+ countIf(+ JSONExtractString(log_comment, 'query_type') IN %(eligible_live_types)s+ AND exception_code != 0+ ) AS live_errored+ FROM clusterAllReplicas(%(cluster)s, system.query_log)+ WHERE event_time > now() - toIntervalHour(%(hours)s)+ AND type IN ('QueryFinish', 'ExceptionWhileProcessing')+ AND is_initial_query{user_facing_sql}+ AND {read_predicate}{team_filter_sql}+ GROUP BY hour+ ORDER BY hour+ """,+ )++ warming_rows = run_section(+ "warming",+ f"""+ SELECT+ toStartOfHour(event_time) AS hour,+ count() AS queries,+ uniqExactIf(+ JSONExtractInt(log_comment, 'team_id'), JSONExtractInt(log_comment, 'team_id') != 0+ ) AS teams,+ countIf(exception_code != 0) AS errored+ FROM clusterAllReplicas(%(cluster)s, system.query_log)+ WHERE event_time > now() - toIntervalHour(%(hours)s)+ AND type IN ('QueryFinish', 'ExceptionWhileProcessing', 'ExceptionBeforeStart')+ AND is_initial_query+ AND log_comment LIKE '%%"trigger"%%'+ AND JSONExtractString(log_comment, 'trigger') IN %(warming_triggers)s{team_filter_sql}+ GROUP BY hour+ ORDER BY hour+ """,+ )++ miss_rows = run_section(+ "miss_breakdown",+ f"""+ SELECT+ JSONExtractString(log_comment, 'query_type') AS query_type,+ count() AS misses,+ countIf(exception_code != 0) AS errored+ FROM clusterAllReplicas(%(cluster)s, system.query_log)+ WHERE event_time > now() - toIntervalHour(%(hours)s)+ AND type IN ('QueryFinish', 'ExceptionWhileProcessing')+ AND is_initial_query{user_facing_sql}+ AND log_comment LIKE '%%"query_type"%%'+ AND JSONExtractString(log_comment, 'query_type') IN %(eligible_live_types)s{team_filter_sql}+ GROUP BY query_type+ ORDER BY misses DESC+ """,+ )++ # Per-strategy execution detail for one tenant: latency percentiles, volume,+ # and error codes per query_type tag. This is the triage layer — a latency+ # finding names a team; this section says which strategy regressed and+ # whether it failed by timeout, memory, or contention. Fleet-wide it would+ # be an unbounded scan for numbers the hourly sections already summarize.+ detail_rows: list = []+ if team_id_filter is not None:+ detail_rows = run_section(+ "query_detail",+ f"""+ SELECT+ JSONExtractString(log_comment, 'query_type') AS query_type,+ count() AS reads,+ round(quantile(0.5)(query_duration_ms)) AS p50_ms,+ round(quantile(0.95)(query_duration_ms)) AS p95_ms,+ round(quantile(0.99)(query_duration_ms)) AS p99_ms,+ max(read_bytes) AS max_read_bytes,+ max(memory_usage) AS max_memory_bytes,+ countIf(exception_code != 0) AS errored,+ arrayDistinct(groupArrayIf(exception_code, exception_code != 0)) AS error_codes+ FROM clusterAllReplicas(%(cluster)s, system.query_log)+ WHERE event_time > now() - toIntervalHour(%(hours)s)+ AND type IN ('QueryFinish', 'ExceptionWhileProcessing', 'ExceptionBeforeStart')+ AND is_initial_query{user_facing_sql}+ AND {read_predicate}{team_filter_sql}+ GROUP BY query_type+ ORDER BY reads DESC+ """,+ )++ # Which tenants eat the most live (missed) reads — the scout's raw material+ # for enrollment/coverage suggestions. Redundant under a team filter.+ top_team_rows: list = []+ if team_id_filter is None:+ top_team_rows = run_section(+ "top_missing_teams",+ f"""+ SELECT+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ count() AS misses,+ countIf(exception_code != 0) AS errored+ FROM clusterAllReplicas(%(cluster)s, system.query_log)+ WHERE event_time > now() - toIntervalHour(%(hours)s)+ AND type IN ('QueryFinish', 'ExceptionWhileProcessing')+ AND is_initial_query{user_facing_sql}+ AND log_comment LIKE '%%"query_type"%%'+ AND JSONExtractString(log_comment, 'query_type') IN %(eligible_live_types)s+ AND JSONExtractInt(log_comment, 'team_id') != 0+ GROUP BY team_id+ ORDER BY misses DESC+ LIMIT 25+ """,+ )++ # Warming spend per tenant — the cost side of the per-team economics the+ # miss ranking gives the benefit side of. Redundant under a team filter+ # (the hourly warming section already carries that tenant's numbers).+ top_warmed_rows: list = []+ if team_id_filter is None:+ top_warmed_rows = run_section(+ "top_warmed_teams",+ f"""+ SELECT+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ count() AS warming_queries,+ round(sum(query_duration_ms) / 1000, 1) AS warming_seconds,+ countIf(exception_code != 0) AS errored+ FROM clusterAllReplicas(%(cluster)s, system.query_log)+ WHERE event_time > now() - toIntervalHour(%(hours)s)+ AND type IN ('QueryFinish', 'ExceptionWhileProcessing', 'ExceptionBeforeStart')+ AND is_initial_query+ AND log_comment LIKE '%%"trigger"%%'+ AND JSONExtractString(log_comment, 'trigger') IN %(warming_triggers)s+ AND JSONExtractInt(log_comment, 'team_id') != 0+ GROUP BY team_id+ ORDER BY warming_seconds DESC+ LIMIT 25+ """,+ )++ # ClickHouse returns naive server-time (UTC) datetimes; stamp them and+ # zero-fill the series so a silent hour reads as an explicit zero (a dead+ # warmer is the alarm condition, not a missing bucket). A failed section+ # stays an empty list — zeros there would masquerade as data.+ window_end = datetime.now(UTC).replace(minute=0, second=0, microsecond=0)+ hour_keys = [window_end - timedelta(hours=offset) for offset in range(hours, -1, -1)]+ hourly_by_hour = {row[0].replace(tzinfo=UTC): row for row in hourly_rows}+ warming_by_hour = {row[0].replace(tzinfo=UTC): row for row in warming_rows}++ hourly_series = []+ if "hourly" not in unavailable_sections:+ for key in hour_keys:+ _, lazy, live, live_errored = hourly_by_hour.get(key, (key, 0, 0, 0))+ hourly_series.append(+ {+ "hour": key.isoformat(),+ "lazy_hits": lazy,+ "eligible_live": live,+ "live_errored": live_errored,+ "hit_ratio": round(100.0 * lazy / (lazy + live), 1) if lazy + live else None,+ }+ )+ warming_series = []+ if "warming" not in unavailable_sections:+ warming_series = [+ {"hour": key.isoformat(), "queries": row[1], "teams": row[2], "errored": row[3]}+ for key in hour_keys+ for row in [warming_by_hour.get(key, (key, 0, 0, 0))]+ ]++ total_lazy = sum(row[1] for row in hourly_rows)+ total_live = sum(row[2] for row in hourly_rows)+ payload = {+ "product": product,+ "hours": hours,+ "team_id": team_id_filter,+ "unavailable_sections": unavailable_sections,+ "summary": {+ "lazy_hits": total_lazy,+ "eligible_live": total_live,+ "live_errored": sum(row[3] for row in hourly_rows),+ "hit_ratio": round(100.0 * total_lazy / (total_lazy + total_live), 1)+ if total_lazy + total_live+ else None,+ },+ "hourly": hourly_series,+ "warming": warming_series,+ "miss_breakdown": [+ {"query_type": query_type, "misses": misses, "errored": errored}+ for query_type, misses, errored in miss_rows+ ],+ "top_missing_teams": [+ {"team_id": team_id, "misses": misses, "errored": errored} for team_id, misses, errored in top_team_rows+ ],+ "top_warmed_teams": [+ {+ "team_id": team_id,+ "warming_queries": warming_queries,+ "warming_seconds": warming_seconds,+ "errored": errored,+ }+ for team_id, warming_queries, warming_seconds, errored in top_warmed_rows+ ],+ "query_detail": [+ {+ "query_type": query_type,+ "reads": reads,+ "p50_ms": p50,+ "p95_ms": p95,+ "p99_ms": p99,+ "max_read_bytes": max_read_bytes,+ "max_memory_bytes": max_memory_bytes,+ "errored": errored,+ "error_codes": error_codes,+ }+ for query_type, reads, p50, p95, p99, max_read_bytes, max_memory_bytes, errored, error_codes in detail_rows+ ],+ }+ # A partial response must not be served for the cache window as if it+ # were the real state — only complete payloads are cached.+ if not unavailable_sections:+ cache.set(response_cache_key, payload, timeout=120)+ return Response(payload)+# Keys match the experiment_precompute_table tag on build INSERTs; both are always present in# the response so the charts render a (zero) series even for a table with no builds in window._CACHE_GROWTH_TABLES = ("exposures", "metric_events")diff --git a/posthog/api/test/test_debug_ch_queries.py b/posthog/api/test/test_debug_ch_queries.pyindex 365500735ee7..109ab599636c 100644--- a/posthog/api/test/test_debug_ch_queries.py+++ b/posthog/api/test/test_debug_ch_queries.py@@ -1,8 +1,9 @@-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom posthog.test.base import APIBaseTestfrom unittest.mock import patch+from django.core.cache import cachefrom django.test import SimpleTestCasefrom rest_framework.status import HTTP_200_OK, HTTP_403_FORBIDDEN@@ -270,6 +271,161 @@ class TestDebugCHQuery(APIBaseTest):self.assertEqual(resp.status_code, HTTP_200_OK, resp.content)+class TestPrecomputeHealth(APIBaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ def setUp(self) -> None:+ super().setUp()+ cache.clear() # the endpoint caches complete payloads; tests must not share them++ def _create_pat(self, scopes: list[str]) -> str:+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ user=self.user,+ label="test",+ secure_value=hash_key_value(token),+ scopes=scopes,+ )+ return token++ def test_scope_and_staff_gate_wired_on_action(self) -> None:+ # The scope/wildcard/staff mechanics are proven on slowest_queries; this+ # only guards that THIS action declares the scope and the staff check.+ token = self._create_pat(scopes=["query_performance:read"])+ self.client.logout()++ resp = self.client.get(+ "/api/debug_ch_queries/precompute_health/",+ headers={"authorization": f"Bearer {token}"},+ )+ self.assertEqual(resp.status_code, HTTP_403_FORBIDDEN)++ self.user.is_staff = True+ self.user.save()+ with patch("posthog.api.debug_ch_queries.sync_execute", return_value=[]):+ resp = self.client.get(+ "/api/debug_ch_queries/precompute_health/",+ headers={"authorization": f"Bearer {token}"},+ )+ self.assertEqual(resp.status_code, HTTP_200_OK, resp.content)++ # An unregistered product must be rejected before any scan runs.+ resp = self.client.get(+ "/api/debug_ch_queries/precompute_health/?product=nonsense",+ headers={"authorization": f"Bearer {token}"},+ )+ self.assertEqual(resp.status_code, 400, resp.content)++ def test_assembles_ratio_from_query_log_rows(self) -> None:+ self.user.is_staff = True+ self.user.save()++ hour = datetime.now(UTC).replace(minute=0, second=0, microsecond=0) - timedelta(hours=1)+ results = iter(+ [+ [(hour.replace(tzinfo=None), 750, 250, 12)], # hourly: lazy, eligible_live, live_errored+ [(hour.replace(tzinfo=None), 12000, 2100, 3)], # warming: queries, teams, errored+ [("web_overview_query", 180, 9), ("stats_table_main_query", 70, 0)],+ [(2, 120, 5), (1589, 60, 0)], # top_missing_teams+ [(2, 45210, 3811.5, 4)], # top_warmed_teams+ ]+ )+ call_count = {"n": 0}++ def fake_sync_execute(*_a, **_k):+ call_count["n"] += 1+ return next(results)++ with patch("posthog.api.debug_ch_queries.sync_execute", side_effect=fake_sync_execute):+ resp = self.client.get("/api/debug_ch_queries/precompute_health/?hours=9999")++ self.assertEqual(resp.status_code, HTTP_200_OK, resp.content)+ data = resp.json()+ self.assertEqual(data["hours"], 168) # clamped+ self.assertEqual(data["unavailable_sections"], [])+ self.assertEqual(+ data["summary"], {"lazy_hits": 750, "eligible_live": 250, "live_errored": 12, "hit_ratio": 75.0}+ )+ # Series are zero-filled over the whole window with explicit UTC stamps —+ # a silent hour must read as zero, and the data hour must land in place.+ self.assertEqual(len(data["hourly"]), 169)+ (data_hour,) = [e for e in data["hourly"] if e["lazy_hits"]]+ self.assertEqual(data_hour["hour"], hour.isoformat())+ self.assertEqual(data_hour["hit_ratio"], 75.0)+ self.assertEqual(sum(e["queries"] for e in data["warming"]), 12000)+ self.assertEqual(data["miss_breakdown"][0], {"query_type": "web_overview_query", "misses": 180, "errored": 9})+ self.assertEqual(data["top_missing_teams"][0], {"team_id": 2, "misses": 120, "errored": 5})+ self.assertEqual(+ data["top_warmed_teams"][0],+ {"team_id": 2, "warming_queries": 45210, "warming_seconds": 3811.5, "errored": 4},+ )+ self.assertEqual(data["product"], "web_analytics")++ # A complete payload is cached: an identical request runs no new scans.+ with patch("posthog.api.debug_ch_queries.sync_execute", side_effect=AssertionError("must be cached")):+ resp2 = self.client.get("/api/debug_ch_queries/precompute_health/?hours=9999")+ self.assertEqual(resp2.status_code, HTTP_200_OK, resp2.content)+ self.assertEqual(resp2.json()["summary"], data["summary"])++ def test_failed_section_degrades_to_partial_response(self) -> None:+ # One slow scan (timeout, OOM) must cost its own section, not 500 the+ # whole response — and a partial payload must not be cached as complete.+ self.user.is_staff = True+ self.user.save()++ def fake_sync_execute(query: str, *_a, **_k) -> list:+ if "'trigger'" in query or '"trigger"' in query:+ raise Exception("Code: 159. DB::Exception: Timeout exceeded")+ return []++ with patch("posthog.api.debug_ch_queries.sync_execute", side_effect=fake_sync_execute):+ resp = self.client.get("/api/debug_ch_queries/precompute_health/")++ self.assertEqual(resp.status_code, HTTP_200_OK, resp.content)+ data = resp.json()+ self.assertEqual(data["unavailable_sections"], ["warming", "top_warmed_teams"])+ self.assertEqual(data["warming"], [])+ self.assertEqual(len(data["hourly"]), 25) # healthy sections still zero-fill++ # Not cached: the next request must re-run the scans.+ calls = {"n": 0}++ def counting_sync_execute(*_a, **_k) -> list:+ calls["n"] += 1+ return []++ with patch("posthog.api.debug_ch_queries.sync_execute", side_effect=counting_sync_execute):+ self.client.get("/api/debug_ch_queries/precompute_health/")+ self.assertGreater(calls["n"], 0)++ def test_team_filter_narrows_all_sections_and_skips_team_ranking(self) -> None:+ # A per-team read must inject the tenant filter into every section's SQL,+ # swap the fleet-wide team ranking for the per-strategy triage detail, and+ # never run an unfiltered scan.+ self.user.is_staff = True+ self.user.save()++ executed: list[tuple[str, dict]] = []++ def fake_sync_execute(query: str, params: dict, **_kwargs) -> list:+ executed.append((query, params))+ return []++ with patch("posthog.api.debug_ch_queries.sync_execute", side_effect=fake_sync_execute):+ resp = self.client.get("/api/debug_ch_queries/precompute_health/?team_id=42")++ self.assertEqual(resp.status_code, HTTP_200_OK, resp.content)+ self.assertEqual(len(executed), 4) # hourly, warming, miss_breakdown, query_detail+ for query, params in executed:+ self.assertIn("JSONExtractInt(log_comment, 'team_id') = %(team_id)s", query)+ self.assertEqual(params["team_id"], 42)+ self.assertEqual(resp.json()["team_id"], 42)+ self.assertEqual(resp.json()["top_missing_teams"], [])+ self.assertEqual(resp.json()["top_warmed_teams"], [])+ self.assertEqual(resp.json()["query_detail"], [])+ self.assertEqual(resp.json()["unavailable_sections"], [])++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