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(web-analytics): staff-only precompute debug endpoint and scene (#71325)

Lucas Ricoy4940ebc7da20
diff --git a/frontend/package.json b/frontend/package.json
index d5829e3547db..5e9834f54d76 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -88,6 +88,7 @@
"@posthog/products-ai-observability": "workspace:*",
"@posthog/products-ai-training": "workspace:*",
"@posthog/products-alerts": "workspace:*",
+ "@posthog/products-analytics-platform": "workspace:*",
"@posthog/products-annotations": "workspace:*",
"@posthog/products-apm": "workspace:*",
"@posthog/products-batch-exports": "workspace:*",
diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsx
index 514080ac45a8..78bc598671d0 100644
--- a/frontend/src/productScenes.tsx
+++ b/frontend/src/productScenes.tsx
@@ -37,6 +37,7 @@ export const productScenes: Record<string, () => Promise<any>> = {
AIObservabilityCluster: () =>
import('../../products/ai_observability/frontend/clusters/AIObservabilityClusterScene'),
Alerts: () => import('../../products/alerts/frontend/AlertsScene'),
+ PrecomputeDebug: () => import('../../products/analytics_platform/frontend/PrecomputeDebugScene'),
Annotations: () => import('../../products/annotations/frontend/pages/Annotations'),
BusinessKnowledge: () => import('../../products/business_knowledge/frontend/scenes/BusinessKnowledgeScene'),
BusinessKnowledgeSettings: () =>
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 959f6fac1bf5..1555881d8f9d 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -95,6 +95,7 @@ export const productRoutes: Record<string, [string, string]> = {
'/prompt-management/prompts': ['AIObservabilityPrompts', 'aiObservabilityPrompts'],
'/prompt-management/prompts/:name': ['AIObservabilityPrompt', 'aiObservabilityPrompt'],
'/alerts': ['Alerts', 'alerts'],
+ '/debug/precompute': ['PrecomputeDebug', 'precomputeDebug'],
'/data-management/annotations': ['Annotations', 'annotations'],
'/data-management/annotations/:id': ['Annotations', 'annotation'],
'/business-knowledge': ['BusinessKnowledge', 'businessKnowledge'],
@@ -574,6 +575,13 @@ export const productConfiguration: Record<string, any> = {
iconType: 'inbox',
description: 'Monitor insight metrics and get notified when conditions are met.',
},
+ PrecomputeDebug: {
+ projectBased: true,
+ name: 'Precompute debug',
+ description: 'Staff-only view of stored precompute hashes, buckets, and TTLs.',
+ layout: 'app-container',
+ iconType: 'web_analytics',
+ },
Annotations: {
name: 'Annotations',
projectBased: true,
@@ -1164,6 +1172,7 @@ export const productUrls = {
`/ai-observability/clusters/${encodeURIComponent(runId)}/${clusterId}`,
alert: (alertId: string): string => `/alerts?alert_type=insights&alert_id=${alertId}`,
alerts: (): string => '/alerts',
+ precomputeDebug: (): string => `/debug/precompute`,
annotations: (): string => '/data-management/annotations',
annotation: (id: AnnotationType['id'] | ':id'): string => `/data-management/annotations/${id}`,
businessKnowledge: (): string => '/business-knowledge',
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index ebd6c1dab20c..e9b59a9ae68b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -662,6 +662,9 @@ importers:
'@posthog/products-alerts':
specifier: workspace:*
version: link:../products/alerts
+ '@posthog/products-analytics-platform':
+ specifier: workspace:*
+ version: link:../products/analytics_platform
'@posthog/products-annotations':
specifier: workspace:*
version: link:../products/annotations
@@ -2527,7 +2530,23 @@ importers:
specifier: 'catalog:'
version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
- products/analytics_platform: {}
+ products/analytics_platform:
+ dependencies:
+ '@posthog/icons':
+ specifier: 'catalog:'
+ '@types/react':
+ specifier: 18.3.27
+ version: 18.3.27
+ kea:
+ specifier: 'catalog:'
+ version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])
+ kea-loaders:
+ specifier: 'catalog:'
+ version: 3.1.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
+ react:
+ specifier: 18.3.1
+ version: 18.3.1
products/annotations:
dependencies:
diff --git a/products/analytics_platform/backend/api/precompute_debug.py b/products/analytics_platform/backend/api/precompute_debug.py
new file mode 100644
index 000000000000..162de84eaa9d
--- /dev/null
+++ b/products/analytics_platform/backend/api/precompute_debug.py
@@ -0,0 +1,372 @@
+"""Staff/dev-only debug surface for the lazy precompute store.
+
+Answers "what precompute do we have for this team?" across every product that
+uses the lazy-computation framework (web analytics, marketing analytics,
+experiments): which query hashes are stored, which buckets each covers, how
+long until each bucket's TTL expires, and — where recoverable — the
+originating query (with filters) each hash serves. Also allows invalidating a
+team's stored precompute (marking READY jobs stale) so the next read
+recomputes, e.g. after a source resync changed the underlying data.
+Conceptually a sibling of the "Debug ClickHouse queries" page.
+
+The `PreaggregationJob` table stores only the SHA-256 of the normalized insert
+AST, not the query itself. The originating query is recovered by correlation:
+every insert statement embeds its `job_id` literal and its `log_comment`
+carries the runner's full query JSON plus `query_type`, so a `system.query_log`
+lookup over recent inserts labels each hash. Hashes whose last insert predates
+the query_log lookback stay unlabeled rather than guessed.
+"""
+
+from collections import defaultdict
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from django.conf import settings
+from django.db.models import F, Max, Q
+
+from drf_spectacular.types import OpenApiTypes
+from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
+from loginas.utils import is_impersonated_session
+from rest_framework import serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.clickhouse.client import sync_execute
+
+from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob
+
+# Dead (expired/failed) jobs older than this are not shown. Unexpired jobs are
+# always shown regardless of age, so long-TTL stores (e.g. the 90-day
+# dimensional buckets) never silently drop out of the view.
+JOB_LOOKBACK_DAYS = 35
+
+# How far back to search `system.query_log` for the insert that produced a
+# hash's most recent job. Bounded by query_log retention and scan cost; hashes
+# whose newest insert is older than this simply come back unlabeled.
+QUERY_LOG_LOOKBACK_DAYS = 3
+
+# Per-response caps: hash groups are the unit of attention, buckets per group
+# cover a full warm window plus slack.
+MAX_GROUPS_DEFAULT = 50
+MAX_GROUPS = 200
+MAX_BUCKETS_PER_GROUP = 70
+
+
+class PrecomputeDebugBucketSerializer(serializers.Serializer):
+ time_range_start = serializers.DateTimeField(help_text="Start of the bucket's time window (inclusive).")
+ time_range_end = serializers.DateTimeField(help_text="End of the bucket's time window (exclusive).")
+ status = serializers.ChoiceField(
+ choices=PreaggregationJob.Status.choices, help_text="Lifecycle state of this bucket's job."
+ )
+ computed_at = serializers.DateTimeField(
+ allow_null=True, help_text="When the bucket's data was last computed; null if never computed."
+ )
+ expires_at = serializers.DateTimeField(
+ allow_null=True, help_text="When the bucket's data expires in ClickHouse; null if no TTL recorded."
+ )
+ ttl_seconds_remaining = serializers.IntegerField(
+ allow_null=True,
+ help_text="Seconds until the bucket expires; negative when already expired, null if no TTL recorded.",
+ )
+
+
+class PrecomputeDebugSampleSerializer(serializers.Serializer):
+ query_type = serializers.CharField(
+ allow_null=True, help_text="query_type tag of the insert that built this hash (identifies the query family)."
+ )
+ trigger = serializers.CharField(
+ allow_null=True,
+ help_text="Trigger tag of the insert: a warmer trigger name, or empty for a user-initiated read.",
+ )
+ query_json = serializers.CharField(
+ allow_null=True,
+ help_text=(
+ "Originating query as JSON (from the insert's log_comment) including date range and property "
+ "filters — shows which dashboard queries this hash serves."
+ ),
+ )
+ last_insert_at = serializers.DateTimeField(
+ allow_null=True, help_text="When the sampled insert for this hash finished."
+ )
+
+
+class PrecomputeDebugGroupSerializer(serializers.Serializer):
+ query_hash = serializers.CharField(help_text="SHA-256 of the normalized insert query this group covers.")
+ job_count = serializers.IntegerField(help_text="Number of bucket jobs stored for this hash (within caps).")
+ status_counts = serializers.DictField(
+ child=serializers.IntegerField(), help_text="Job count per lifecycle status for this hash."
+ )
+ earliest_start = serializers.DateTimeField(help_text="Start of the earliest bucket stored for this hash.")
+ latest_end = serializers.DateTimeField(help_text="End of the latest bucket stored for this hash.")
+ last_computed_at = serializers.DateTimeField(
+ allow_null=True, help_text="Most recent computed_at across the hash's buckets."
+ )
+ sample = PrecomputeDebugSampleSerializer(
+ allow_null=True,
+ help_text="Originating-query sample recovered from query_log; null when no recent insert was found.",
+ )
+ buckets = PrecomputeDebugBucketSerializer(
+ many=True, help_text=f"Most recent buckets for this hash (capped at {MAX_BUCKETS_PER_GROUP})."
+ )
+
+
+class PrecomputeDebugResponseSerializer(serializers.Serializer):
+ generated_at = serializers.DateTimeField(help_text="When this snapshot was generated.")
+ job_lookback_days = serializers.IntegerField(
+ help_text="Expired/failed jobs older than this many days are omitted; unexpired jobs are always shown."
+ )
+ query_log_lookback_days = serializers.IntegerField(
+ help_text="How far back query_log was searched to label hashes with their originating query."
+ )
+ total_hashes = serializers.IntegerField(help_text="Distinct hashes stored for the team within the job lookback.")
+ groups = PrecomputeDebugGroupSerializer(many=True, help_text="Per-hash groups, most recently computed first.")
+
+
+class PrecomputeInvalidateRequestSerializer(serializers.Serializer):
+ query_hash = serializers.CharField(
+ required=False,
+ allow_null=True,
+ default=None,
+ max_length=64,
+ help_text="Only invalidate jobs for this query hash. Omit to invalidate every hash stored for the team.",
+ )
+
+
+class PrecomputeInvalidateResponseSerializer(serializers.Serializer):
+ updated_count = serializers.IntegerField(help_text="Number of READY jobs marked stale.")
+ pending_count = serializers.IntegerField(
+ help_text=(
+ "In-flight PENDING jobs left untouched. A job that started before a source resync can still "
+ "finish READY with pre-resync data; invalidate again once these settle to catch it."
+ )
+ )
+ query_hash = serializers.CharField(
+ allow_null=True, help_text="The hash that was invalidated, or null when all hashes were targeted."
+ )
+
+
+def _fetch_samples_from_query_log(team_id: int, job_ids_by_hash: dict[str, str]) -> dict[str, dict[str, Any]]:
+ """Label hashes with the insert that produced their most recent job.
+
+ Matches the `job_id` literal embedded in each insert statement. Best-effort:
+ any failure returns {} so the debug page still renders the Postgres side.
+ """
+ if not job_ids_by_hash:
+ return {}
+ hashes = list(job_ids_by_hash.keys())
+ job_ids = [job_ids_by_hash[h] for h in hashes]
+ try:
+ rows = sync_execute(
+ """
+ SELECT
+ multiSearchFirstIndex(query, %(job_ids)s) AS idx,
+ argMax(JSONExtractString(log_comment, 'query_type'), event_time) AS query_type,
+ argMax(JSONExtractString(log_comment, 'trigger'), event_time) AS trigger,
+ argMax(JSONExtractRaw(log_comment, 'query'), event_time) AS query_json,
+ max(event_time) AS last_insert_at
+ FROM clusterAllReplicas(%(cluster)s, system, query_log)
+ WHERE event_time > now() - INTERVAL %(lookback_days)s DAY
+ AND query_kind = 'Insert'
+ AND type = 'QueryFinish'
+ AND is_initial_query = 1
+ AND JSONExtractInt(log_comment, 'team_id') = %(team_id)s
+ AND multiSearchAny(query, %(job_ids)s)
+ GROUP BY idx
+ """,
+ {
+ "cluster": settings.CLICKHOUSE_CLUSTER,
+ "lookback_days": QUERY_LOG_LOOKBACK_DAYS,
+ "team_id": team_id,
+ "job_ids": job_ids,
+ },
+ )
+ except Exception:
+ return {}
+
+ samples: dict[str, dict[str, Any]] = {}
+ for idx, query_type, trigger, query_json, last_insert_at in rows:
+ if idx < 1 or idx > len(hashes):
+ continue
+ samples[hashes[idx - 1]] = {
+ "query_type": query_type or None,
+ "trigger": trigger,
+ "query_json": query_json or None,
+ "last_insert_at": last_insert_at,
+ }
+ return samples
+
+
+class PrecomputeDebugViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
+ # `scope_object = "INTERNAL"` blocks a staff user's full-access (`*`) PAT via the
+ # wildcard short-circuit in `APIScopePermission.has_permission`. Each action pins a
+ # `query_performance` scope — OAuth-hidden, PAT-grantable (see OAUTH_HIDDEN_SCOPE_OBJECTS)
+ # so staff automation can reach it; the browser uses session auth, which bypasses scope
+ # checks. `_check_debug_access` gates every action in every case.
+ scope_object = "INTERNAL"
+
+ def _check_debug_access(self, request: Request) -> Response | None:
+ # Staff (or impersonating staff) everywhere, including self-hosted: the
+ # Django staff flag exists there too, so deployment mode grants nothing.
+ if request.user.is_staff or settings.DEBUG or is_impersonated_session(request):
+ return None
+ return Response({"detail": "Staff access required."}, status=status.HTTP_403_FORBIDDEN)
+
+ @extend_schema(
+ operation_id="precompute_debug_state",
+ summary="Inspect stored lazy-precompute state (staff only)",
+ description=(
+ "Staff/dev-only debug view of the team's lazy precompute store: which query hashes are stored, "
+ "which buckets each covers, per-bucket TTL, and — where recoverable from query_log — the "
+ "originating query (with filters) each hash serves."
+ ),
+ parameters=[
+ OpenApiParameter(
+ name="limit",
+ type=OpenApiTypes.INT,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ default=MAX_GROUPS_DEFAULT,
+ description=f"Maximum number of hash groups to return (1–{MAX_GROUPS}).",
+ ),
+ ],
+ responses={200: OpenApiResponse(response=PrecomputeDebugResponseSerializer)},
+ )
+ @action(detail=False, methods=["get"], url_path="state", required_scopes=["query_performance:read"])
+ def state(self, request: Request, **kwargs: Any) -> Response:
+ denied = self._check_debug_access(request)
+ if denied is not None:
+ return denied
+
+ try:
+ limit = max(1, min(int(request.query_params.get("limit", MAX_GROUPS_DEFAULT)), MAX_GROUPS))
+ except ValueError:
+ limit = MAX_GROUPS_DEFAULT
+
+ now = datetime.now(UTC)
+ live_window = Q(expires_at__gte=now) | Q(created_at__gte=now - timedelta(days=JOB_LOOKBACK_DAYS))
+
+ # Pick the top hashes in the database before materializing any job rows,
+ # so a project with many stored hashes never streams them all into Python.
+ top_hash_rows = (
+ PreaggregationJob.objects.filter(live_window, team_id=self.team.pk)
+ .values("query_hash")
+ .annotate(last_computed=Max("computed_at"))
+ .order_by(F("last_computed").desc(nulls_last=True))[:limit]
+ )
+ top_hashes = [row["query_hash"] for row in top_hash_rows]
+ total_hashes = (
+ PreaggregationJob.objects.filter(live_window, team_id=self.team.pk).values("query_hash").distinct().count()
+ )
+
+ jobs = (
+ PreaggregationJob.objects.filter(live_window, team_id=self.team.pk, query_hash__in=top_hashes)
+ .order_by("-time_range_end")
+ .values("query_hash", "time_range_start", "time_range_end", "status", "computed_at", "expires_at")
+ )
+
+ grouped: dict[str, list[Any]] = defaultdict(list)
+ for job in jobs.iterator(chunk_size=2000):
+ grouped[job["query_hash"]].append(job)
+
+ def group_sort_key(item: tuple[str, list[Any]]) -> datetime:
+ computed = [j["computed_at"] for j in item[1] if j["computed_at"] is not None]
+ return max(computed) if computed else datetime.min.replace(tzinfo=UTC)
+
+ ordered = sorted(grouped.items(), key=group_sort_key, reverse=True)
+
+ groups: list[dict[str, Any]] = []
+ job_ids_by_hash: dict[str, str] = {}
+ for query_hash, hash_jobs in ordered:
+ status_counts: dict[str, int] = defaultdict(int)
+ for j in hash_jobs:
+ status_counts[j["status"]] += 1
+ computed = [j["computed_at"] for j in hash_jobs if j["computed_at"] is not None]
+ groups.append(
+ {
+ "query_hash": query_hash,
+ "job_count": len(hash_jobs),
+ "status_counts": dict(status_counts),
+ "earliest_start": min(j["time_range_start"] for j in hash_jobs),
+ "latest_end": max(j["time_range_end"] for j in hash_jobs),
+ "last_computed_at": max(computed) if computed else None,
+ "sample": None,
+ "buckets": [
+ {
+ "time_range_start": j["time_range_start"],
+ "time_range_end": j["time_range_end"],
+ "status": j["status"],
+ "computed_at": j["computed_at"],
+ "expires_at": j["expires_at"],
+ "ttl_seconds_remaining": (
+ int((j["expires_at"] - now).total_seconds()) if j["expires_at"] else None
+ ),
+ }
+ for j in hash_jobs[:MAX_BUCKETS_PER_GROUP]
+ ],
+ }
+ )
+
+ # Correlate each hash with its most recent job's insert in query_log. Jobs
+ # need an id for the match; re-query only the ids for the sampled jobs.
+ sampled_hashes = [g["query_hash"] for g in groups]
+ if sampled_hashes:
+ id_rows = (
+ PreaggregationJob.objects.filter(
+ team_id=self.team.pk,
+ query_hash__in=sampled_hashes,
+ computed_at__isnull=False,
+ )
+ .order_by("query_hash", "-computed_at")
+ .distinct("query_hash")
+ .values_list("query_hash", "id")
+ )
+ job_ids_by_hash = {h: str(job_id) for h, job_id in id_rows}
+ samples = _fetch_samples_from_query_log(self.team.pk, job_ids_by_hash)
+ for group in groups:
+ group["sample"] = samples.get(group["query_hash"])
+
+ payload = {
+ "generated_at": now,
+ "job_lookback_days": JOB_LOOKBACK_DAYS,
+ "query_log_lookback_days": QUERY_LOG_LOOKBACK_DAYS,
+ "total_hashes": total_hashes,
+ "groups": groups,
+ }
+ return Response(PrecomputeDebugResponseSerializer(payload).data)
+
+ @extend_schema(
+ operation_id="precompute_debug_invalidate",
+ summary="Invalidate stored precompute for this team (staff only)",
+ description=(
+ "Marks the team's READY precompute jobs stale so the next read recomputes them, e.g. after a "
+ "source resync changed the underlying data. Optionally scoped to a single query hash. PENDING "
+ "jobs are left alone: anything in flight is already computing against current data."
+ ),
+ request=PrecomputeInvalidateRequestSerializer,
+ responses={200: OpenApiResponse(response=PrecomputeInvalidateResponseSerializer)},
+ )
+ @action(detail=False, methods=["post"], url_path="invalidate", required_scopes=["query_performance:write"])
+ def invalidate(self, request: Request, **kwargs: Any) -> Response:
+ denied = self._check_debug_access(request)
+ if denied is not None:
+ return denied
+
+ request_serializer = PrecomputeInvalidateRequestSerializer(data=request.data)
+ request_serializer.is_valid(raise_exception=True)
+ query_hash = request_serializer.validated_data["query_hash"]
+
+ scope = PreaggregationJob.objects.filter(team_id=self.team.pk)
+ if query_hash:
+ scope = scope.filter(query_hash=query_hash)
+ # Count in-flight jobs before the update, not after: a job that flips
+ # PENDING -> READY between the two queries would otherwise miss both and
+ # leave the operator with stale data and no hint to invalidate again.
+ pending_count = scope.filter(status=PreaggregationJob.Status.PENDING).count()
+ updated_count = scope.filter(status=PreaggregationJob.Status.READY).update(
+ status=PreaggregationJob.Status.STALE
+ )
+
+ payload = {"updated_count": updated_count, "pending_count": pending_count, "query_hash": query_hash}
+ return Response(PrecomputeInvalidateResponseSerializer(payload).data)
diff --git a/products/analytics_platform/backend/api/tests/__init__.py b/products/analytics_platform/backend/api/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/analytics_platform/backend/api/tests/test_precompute_debug.py b/products/analytics_platform/backend/api/tests/test_precompute_debug.py
new file mode 100644
index 000000000000..8adc9719d45c
--- /dev/null
+++ b/products/analytics_platform/backend/api/tests/test_precompute_debug.py
@@ -0,0 +1,188 @@
+from datetime import timedelta
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.models.team import Team
+
+from products.analytics_platform.backend.api.precompute_debug import _fetch_samples_from_query_log
+from products.analytics_platform.backend.models.preaggregation_job import PreaggregationJob
+
+_MODULE = "products.analytics_platform.backend.api.precompute_debug"
+
+
+def _make_job(
+ team: Team,
+ *,
+ query_hash: str,
+ days_ago_start: int,
+ status: str = PreaggregationJob.Status.READY,
+ ttl_hours: int = 6,
+ created_days_ago: int | None = None,
+) -> PreaggregationJob:
+ now = timezone.now()
+ start = now - timedelta(days=days_ago_start)
+ job = PreaggregationJob.objects.create(
+ team=team,
+ time_range_start=start,
+ time_range_end=start + timedelta(days=1),
+ query_hash=query_hash,
+ status=status,
+ computed_at=now - timedelta(hours=1),
+ expires_at=now + timedelta(hours=ttl_hours),
+ )
+ if created_days_ago is not None:
+ # created_at is auto_now_add; backdate it directly for lookback tests.
+ PreaggregationJob.objects.filter(id=job.id).update(created_at=now - timedelta(days=created_days_ago))
+ return job
+
+
+class TestPrecomputeDebugAPI(APIBaseTest):
+ def _state_url(self) -> str:
+ return f"/api/projects/{self.team.pk}/precompute_debug/state/"
+
+ def _invalidate_url(self) -> str:
+ return f"/api/projects/{self.team.pk}/precompute_debug/invalidate/"
+
+ @parameterized.expand(
+ [
+ # Non-staff must be refused on both actions regardless of deployment
+ # mode: state exposes internal precompute state, invalidate mutates it.
+ ("state_non_staff_forbidden", "get", "state", False, 403),
+ ("state_staff_allowed", "get", "state", True, 200),
+ ("invalidate_non_staff_forbidden", "post", "invalidate", False, 403),
+ ("invalidate_staff_allowed", "post", "invalidate", True, 200),
+ ]
+ )
+ @patch(f"{_MODULE}._fetch_samples_from_query_log", return_value={})
+ def test_staff_gate(self, _name, method, endpoint, is_staff, expected_status, _samples):
+ self.user.is_staff = is_staff
+ self.user.save()
+ url = self._state_url() if endpoint == "state" else self._invalidate_url()
+ response = getattr(self.client, method)(url)
+ assert response.status_code == expected_status
+
+ @patch(f"{_MODULE}._fetch_samples_from_query_log", return_value={})
+ def test_groups_buckets_by_hash_with_ttl(self, _samples):
+ self.user.is_staff = True
+ self.user.save()
+ _make_job(self.team, query_hash="a" * 64, days_ago_start=1)
+ _make_job(self.team, query_hash="a" * 64, days_ago_start=2, status=PreaggregationJob.Status.PENDING)
+ # Expired bucket: negative TTL remaining must be reported, not hidden.
+ _make_job(self.team, query_hash="b" * 64, days_ago_start=1, ttl_hours=-2)
+
+ response = self.client.get(self._state_url())
+ assert response.status_code == 200
+ data = response.json()
+ assert data["total_hashes"] == 2
+ groups = {g["query_hash"]: g for g in data["groups"]}
+ assert groups["a" * 64]["job_count"] == 2
+ assert groups["a" * 64]["status_counts"] == {"ready": 1, "pending": 1}
+ assert groups["b" * 64]["buckets"][0]["ttl_seconds_remaining"] < 0
+
+ @patch(f"{_MODULE}._fetch_samples_from_query_log", return_value={})
+ def test_limit_bounds_groups_but_not_total(self, _samples):
+ # The group limit must trim the response without hiding how many hashes
+ # exist, and hashes outside the limit must not be fetched into groups.
+ self.user.is_staff = True
+ self.user.save()
+ for i in range(3):
+ _make_job(self.team, query_hash=str(i) * 64, days_ago_start=1)
+
+ response = self.client.get(self._state_url() + "?limit=2")
+ assert response.status_code == 200
+ data = response.json()
+ assert len(data["groups"]) == 2
+ assert data["total_hashes"] == 3
+
+ @patch(f"{_MODULE}._fetch_samples_from_query_log", return_value={})
+ def test_unexpired_old_jobs_still_shown(self, _samples):
+ # Long-TTL stores (e.g. 90-day dimensional buckets) must not silently
+ # drop out of the view just because the job row is older than the
+ # recent-history lookback.
+ self.user.is_staff = True
+ self.user.save()
+ _make_job(self.team, query_hash="a" * 64, days_ago_start=60, ttl_hours=24 * 30, created_days_ago=60)
+ # An expired job that old is legitimately dropped.
+ _make_job(self.team, query_hash="b" * 64, days_ago_start=60, ttl_hours=-24, created_days_ago=60)
+
+ response = self.client.get(self._state_url())
+ assert response.status_code == 200
+ assert [g["query_hash"] for g in response.json()["groups"]] == ["a" * 64]
+
+ @patch(f"{_MODULE}._fetch_samples_from_query_log", return_value={})
+ def test_scoped_to_team(self, _samples):
+ # Another team's jobs must never appear — this is per-team debug state.
+ self.user.is_staff = True
+ self.user.save()
+ other_team = self.organization.teams.create(name="other")
+ _make_job(other_team, query_hash="c" * 64, days_ago_start=1)
+
+ response = self.client.get(self._state_url())
+ assert response.status_code == 200
+ assert response.json()["total_hashes"] == 0
+
+ @parameterized.expand(
+ [
+ # All hashes: both READY jobs flip, PENDING and other-team stay.
+ ("all_hashes", None, 2, {"a" * 64: "stale", "b" * 64: "stale"}),
+ # Single hash: only that hash's READY job flips.
+ ("single_hash", "a" * 64, 1, {"a" * 64: "stale", "b" * 64: "ready"}),
+ ]
+ )
+ def test_invalidate_marks_ready_jobs_stale(self, _name, query_hash, expected_count, expected_statuses):
+ self.user.is_staff = True
+ self.user.save()
+ _make_job(self.team, query_hash="a" * 64, days_ago_start=1)
+ _make_job(self.team, query_hash="b" * 64, days_ago_start=1)
+ pending = _make_job(self.team, query_hash="a" * 64, days_ago_start=2, status=PreaggregationJob.Status.PENDING)
+ other_team = self.organization.teams.create(name="other")
+ other_job = _make_job(other_team, query_hash="a" * 64, days_ago_start=1)
+
+ body = {"query_hash": query_hash} if query_hash else {}
+ response = self.client.post(self._invalidate_url(), body)
+ assert response.status_code == 200
+ assert response.json()["updated_count"] == expected_count
+ # The untouched in-flight job is reported so the operator knows a second
+ # invalidation may be needed once it settles.
+ assert response.json()["pending_count"] == 1
+
+ for expected_hash, expected_status in expected_statuses.items():
+ job = PreaggregationJob.objects.get(team=self.team, query_hash=expected_hash, status__in=["ready", "stale"])
+ assert job.status == expected_status, expected_hash
+ # In-flight and cross-team jobs must never be touched.
+ pending.refresh_from_db()
+ assert pending.status == PreaggregationJob.Status.PENDING
+ other_job.refresh_from_db()
+ assert other_job.status == PreaggregationJob.Status.READY
+
+ def test_invalidate_rejects_blank_hash(self):
+ # A blank hash must 400, never fall through the falsy guard and
+ # invalidate every hash stored for the team.
+ self.user.is_staff = True
+ self.user.save()
+ job = _make_job(self.team, query_hash="a" * 64, days_ago_start=1)
+
+ response = self.client.post(self._invalidate_url(), {"query_hash": ""})
+ assert response.status_code == 400
+ job.refresh_from_db()
+ assert job.status == PreaggregationJob.Status.READY
+
+ def test_sample_index_mapping(self):
+ # multiSearchFirstIndex is 1-based: row idx=2 must map to the SECOND hash,
+ # and out-of-range indexes must be dropped, not crash or mislabel.
+ now = timezone.now()
+ with patch(
+ f"{_MODULE}.sync_execute",
+ return_value=[
+ (2, "web_stats_lazy_insert", "webAnalyticsEagerBaselineWarming", '{"kind":"WebStatsTableQuery"}', now),
+ (99, "bogus", "", "{}", now),
+ ],
+ ):
+ samples = _fetch_samples_from_query_log(self.team.pk, {"hash_one": "id1", "hash_two": "id2"})
+ assert set(samples.keys()) == {"hash_two"}
+ assert samples["hash_two"]["query_type"] == "web_stats_lazy_insert"
diff --git a/products/analytics_platform/backend/routes.py b/products/analytics_platform/backend/routes.py
new file mode 100644
index 000000000000..0f9bb3c2b6ae
--- /dev/null
+++ b/products/analytics_platform/backend/routes.py
@@ -0,0 +1,12 @@
+from posthog.api.routing import RouterRegistry
+
+from products.analytics_platform.backend.api.precompute_debug import PrecomputeDebugViewSet
+
+
+def register_routes(routers: RouterRegistry) -> None:
+ routers.projects.register(
+ r"precompute_debug",
+ PrecomputeDebugViewSet,
+ "project_precompute_debug",
+ ["team_id"],
+ )
diff --git a/products/analytics_platform/frontend/PrecomputeDebugScene.tsx b/products/analytics_platform/frontend/PrecomputeDebugScene.tsx
new file mode 100644
index 000000000000..b6d5a3807091
--- /dev/null
+++ b/products/analytics_platform/frontend/PrecomputeDebugScene.tsx
@@ -0,0 +1,246 @@
+import { useActions, useValues } from 'kea'
+
+import { IconRefresh, IconTrash } from '@posthog/icons'
+
+import { CodeSnippet, Language } from 'lib/components/CodeSnippet'
+import { TZLabel } from 'lib/components/TZLabel'
+import { dayjs } from 'lib/dayjs'
+import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
+import { LemonTable, LemonTableColumns } from 'lib/lemon-ui/LemonTable'
+import { LemonTag, LemonTagType } from 'lib/lemon-ui/LemonTag'
+import { humanFriendlyDuration } from 'lib/utils/durations'
+import { SceneExport } from 'scenes/sceneTypes'
+import { userLogic } from 'scenes/userLogic'
+
+import type { PrecomputeDebugBucketApi, PrecomputeDebugGroupApi } from './generated/api.schemas'
+import { precomputeDebugLogic } from './precomputeDebugLogic'
+
+export const scene: SceneExport = {
+ component: PrecomputeDebugScene,
+ logic: precomputeDebugLogic,
+}
+
+const STATUS_TAG_TYPE: Record<string, LemonTagType> = {
+ ready: 'success',
+ pending: 'warning',
+ stale: 'caution',
+ failed: 'danger',
+}
+
+function formatTtl(seconds: number | null): JSX.Element {
+ if (seconds === null || seconds === undefined) {
+ return <span className="text-muted">no TTL</span>
+ }
+ if (seconds < 0) {
+ return <LemonTag type="danger">expired {humanFriendlyDuration(-seconds)} ago</LemonTag>
+ }
+ return <span>{humanFriendlyDuration(seconds)}</span>
+}
+
+function prettyQueryJson(queryJson: string | null): string | null {
+ if (!queryJson) {
+ return null
+ }
+ try {
+ return JSON.stringify(JSON.parse(queryJson), null, 2)
+ } catch {
+ return queryJson
+ }
+}
+
+function BucketsTable({ group }: { group: PrecomputeDebugGroupApi }): JSX.Element {
+ const columns: LemonTableColumns<PrecomputeDebugBucketApi> = [
+ {
+ title: 'Bucket',
+ render: (_, bucket) =>
+ `${dayjs(bucket.time_range_start).format('YYYY-MM-DD HH:mm')} → ${dayjs(bucket.time_range_end).format(
+ 'YYYY-MM-DD HH:mm'
+ )}`,
+ },
+ {
+ title: 'Status',
+ render: (_, bucket) => (
+ <LemonTag type={STATUS_TAG_TYPE[bucket.status] ?? 'default'}>{bucket.status}</LemonTag>
+ ),
+ },
+ {
+ title: 'Computed',
+ render: (_, bucket) => (bucket.computed_at ? <TZLabel time={bucket.computed_at} /> : 'Never'),
+ },
+ {
+ title: 'TTL remaining',
+ render: (_, bucket) => formatTtl(bucket.ttl_seconds_remaining),
+ },
+ ]
+ const sampleJson = prettyQueryJson(group.sample?.query_json ?? null)
+ return (
+ <div className="deprecated-space-y-2 py-2">
+ {sampleJson ? (
+ <div>
+ <div className="font-semibold mb-1">Originating query (from the latest insert)</div>
+ <CodeSnippet language={Language.JSON} maxLinesWithoutExpansion={12}>
+ {sampleJson}
+ </CodeSnippet>
+ </div>
+ ) : (
+ <LemonBanner type="info">
+ No recent insert found in query_log for this hash, so the originating query can't be shown. It was
+ last built before the query_log lookback window.
+ </LemonBanner>
+ )}
+ <LemonTable dataSource={group.buckets} columns={columns} size="small" embedded />
+ </div>
+ )
+}
+
+export function PrecomputeDebugScene(): JSX.Element {
+ const { debugState, debugStateLoading, invalidatingHash } = useValues(precomputeDebugLogic)
+ const { loadDebugState, invalidate } = useActions(precomputeDebugLogic)
+ const { user } = useValues(userLogic)
+
+ const confirmInvalidate = (queryHash: string | null): void => {
+ LemonDialog.open({
+ title: queryHash ? 'Mark this hash stale?' : 'Mark all precompute stale?',
+ description: queryHash
+ ? 'Ready jobs for this hash will be marked stale and recomputed on the next read.'
+ : 'Every ready precompute job for this project will be marked stale and recomputed on the next read. Use this after a source resync changed the underlying data.',
+ primaryButton: {
+ children: 'Mark stale',
+ status: 'danger',
+ onClick: () => invalidate(queryHash),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+
+ const columns: LemonTableColumns<PrecomputeDebugGroupApi> = [
+ {
+ title: 'Query hash',
+ render: (_, group) => <code className="text-xs">{group.query_hash.slice(0, 16)}…</code>,
+ },
+ {
+ title: 'Serves',
+ render: (_, group) =>
+ group.sample?.query_type ? (
+ <LemonTag type="highlight">{group.sample.query_type}</LemonTag>
+ ) : (
+ <span className="text-muted">unknown</span>
+ ),
+ },
+ {
+ title: 'Built by',
+ render: (_, group) =>
+ group.sample ? (
+ group.sample.trigger ? (
+ <LemonTag type="completion">warmer: {group.sample.trigger}</LemonTag>
+ ) : (
+ <LemonTag type="default">user read</LemonTag>
+ )
+ ) : (
+ 'Unknown'
+ ),
+ },
+ {
+ title: 'Buckets',
+ render: (_, group) => (
+ <span>
+ {group.job_count}{' '}
+ <span className="text-muted">
+ (
+ {Object.entries(group.status_counts)
+ .map(([status, count]) => `${count} ${status}`)
+ .join(', ')}
+ )
+ </span>
+ </span>
+ ),
+ },
+ {
+ title: 'Coverage',
+ render: (_, group) =>
+ `${dayjs(group.earliest_start).format('YYYY-MM-DD')} → ${dayjs(group.latest_end).format('YYYY-MM-DD')}`,
+ },
+ {
+ title: 'Last computed',
+ render: (_, group) => (group.last_computed_at ? <TZLabel time={group.last_computed_at} /> : 'Never'),
+ },
+ {
+ width: 0,
+ render: (_, group) => (
+ <LemonButton
+ size="small"
+ type="secondary"
+ status="danger"
+ loading={invalidatingHash === group.query_hash}
+ disabledReason={
+ invalidatingHash && invalidatingHash !== group.query_hash
+ ? 'Another invalidation is in progress'
+ : undefined
+ }
+ onClick={() => confirmInvalidate(group.query_hash)}
+ >
+ Mark stale
+ </LemonButton>
+ ),
+ },
+ ]
+
+ return (
+ <div className="deprecated-space-y-4">
+ {!user?.is_staff && (
+ <LemonBanner type="warning">
+ This is a staff-only debug tool. The request will be rejected unless you are logged in as staff or
+ running in development.
+ </LemonBanner>
+ )}
+ <div className="flex items-center justify-between">
+ <div>
+ <h1 className="text-xl font-semibold mb-0">Precompute debug</h1>
+ <p className="text-muted mb-0">
+ Stored precompute hashes for this project: the buckets each covers, per-bucket TTL, and the
+ originating query each hash serves.
+ {debugState ? ` Showing ${debugState.groups.length} of ${debugState.total_hashes} hashes.` : ''}
+ </p>
+ </div>
+ <div className="flex gap-2">
+ <LemonButton
+ type="secondary"
+ status="danger"
+ icon={<IconTrash />}
+ loading={invalidatingHash === 'all'}
+ disabledReason={
+ invalidatingHash && invalidatingHash !== 'all'
+ ? 'Another invalidation is in progress'
+ : !debugState?.groups.length
+ ? 'No precompute jobs to invalidate'
+ : undefined
+ }
+ onClick={() => confirmInvalidate(null)}
+ >
+ Mark all stale
+ </LemonButton>
+ <LemonButton
+ type="secondary"
+ icon={<IconRefresh />}
+ onClick={loadDebugState}
+ loading={debugStateLoading}
+ >
+ Refresh
+ </LemonButton>
+ </div>
+ </div>
+ <LemonTable
+ dataSource={debugState?.groups ?? []}
+ columns={columns}
+ loading={debugStateLoading}
+ rowKey="query_hash"
+ expandable={{
+ expandedRowRender: (group) => <BucketsTable group={group} />,
+ }}
+ emptyState="No precompute jobs stored for this project in the lookback window."
+ />
+ </div>
+ )
+}
diff --git a/products/analytics_platform/frontend/generated/api.schemas.ts b/products/analytics_platform/frontend/generated/api.schemas.ts
new file mode 100644
index 000000000000..1e3c8abdff8a
--- /dev/null
+++ b/products/analytics_platform/frontend/generated/api.schemas.ts
@@ -0,0 +1,144 @@
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+export interface PrecomputeInvalidateRequestApi {
+ /**
+ * Only invalidate jobs for this query hash. Omit to invalidate every hash stored for the team.
+ * @maxLength 64
+ * @nullable
+ */
+ query_hash?: string | null
+}
+
+export interface PrecomputeInvalidateResponseApi {
+ /** Number of READY jobs marked stale. */
+ updated_count: number
+ /** In-flight PENDING jobs left untouched. A job that started before a source resync can still finish READY with pre-resync data; invalidate again once these settle to catch it. */
+ pending_count: number
+ /**
+ * The hash that was invalidated, or null when all hashes were targeted.
+ * @nullable
+ */
+ query_hash: string | null
+}
+
+export interface PrecomputeDebugSampleApi {
+ /**
+ * query_type tag of the insert that built this hash (identifies the query family).
+ * @nullable
+ */
+ query_type: string | null
+ /**
+ * Trigger tag of the insert: a warmer trigger name, or empty for a user-initiated read.
+ * @nullable
+ */
+ trigger: string | null
+ /**
+ * Originating query as JSON (from the insert's log_comment) including date range and property filters — shows which dashboard queries this hash serves.
+ * @nullable
+ */
+ query_json: string | null
+ /**
+ * When the sampled insert for this hash finished.
+ * @nullable
+ */
+ last_insert_at: string | null
+}
+
+/**
+ * * `pending` - Pending
+ * * `ready` - Ready
+ * * `stale` - Stale
+ * * `failed` - Failed
+ */
+export type PreaggregationJobStatusEnumApi =
+ (typeof PreaggregationJobStatusEnumApi)[keyof typeof PreaggregationJobStatusEnumApi]
+
+export const PreaggregationJobStatusEnumApi = {
+ Pending: 'pending',
+ Ready: 'ready',
+ Stale: 'stale',
+ Failed: 'failed',
+} as const
+
+export interface PrecomputeDebugBucketApi {
+ /** Start of the bucket's time window (inclusive). */
+ time_range_start: string
+ /** End of the bucket's time window (exclusive). */
+ time_range_end: string
+ /** Lifecycle state of this bucket's job.
+ *
+ * * `pending` - Pending
+ * * `ready` - Ready
+ * * `stale` - Stale
+ * * `failed` - Failed */
+ status: PreaggregationJobStatusEnumApi
+ /**
+ * When the bucket's data was last computed; null if never computed.
+ * @nullable
+ */
+ computed_at: string | null
+ /**
+ * When the bucket's data expires in ClickHouse; null if no TTL recorded.
+ * @nullable
+ */
+ expires_at: string | null
+ /**
+ * Seconds until the bucket expires; negative when already expired, null if no TTL recorded.
+ * @nullable
+ */
+ ttl_seconds_remaining: number | null
+}
+
+/**
+ * Job count per lifecycle status for this hash.
+ */
+export type PrecomputeDebugGroupApiStatusCounts = { [key: string]: number }
+
+export interface PrecomputeDebugGroupApi {
+ /** SHA-256 of the normalized insert query this group covers. */
+ query_hash: string
+ /** Number of bucket jobs stored for this hash (within caps). */
+ job_count: number
+ /** Job count per lifecycle status for this hash. */
+ status_counts: PrecomputeDebugGroupApiStatusCounts
+ /** Start of the earliest bucket stored for this hash. */
+ earliest_start: string
+ /** End of the latest bucket stored for this hash. */
+ latest_end: string
+ /**
+ * Most recent computed_at across the hash's buckets.
+ * @nullable
+ */
+ last_computed_at: string | null
+ /** Originating-query sample recovered from query_log; null when no recent insert was found. */
+ sample: PrecomputeDebugSampleApi | null
+ /** Most recent buckets for this hash (capped at 70). */
+ buckets: PrecomputeDebugBucketApi[]
+}
+
+export interface PrecomputeDebugResponseApi {
+ /** When this snapshot was generated. */
+ generated_at: string
+ /** Expired/failed jobs older than this many days are omitted; unexpired jobs are always shown. */
+ job_lookback_days: number
+ /** How far back query_log was searched to label hashes with their originating query. */
+ query_log_lookback_days: number
+ /** Distinct hashes stored for the team within the job lookback. */
+ total_hashes: number
+ /** Per-hash groups, most recently computed first. */
+ groups: PrecomputeDebugGroupApi[]
+}
+
+export type PrecomputeDebugStateParams = {
+ /**
+ * Maximum number of hash groups to return (1–200).
+ */
+ limit?: number
+}
diff --git a/products/analytics_platform/frontend/generated/api.ts b/products/analytics_platform/frontend/generated/api.ts
new file mode 100644
index 000000000000..d7be1e6605c5
--- /dev/null
+++ b/products/analytics_platform/frontend/generated/api.ts
@@ -0,0 +1,68 @@
+import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
+/**
+ * Auto-generated from the Django backend OpenAPI schema.
+ * To modify these types, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import type {
+ PrecomputeDebugResponseApi,
+ PrecomputeDebugStateParams,
+ PrecomputeInvalidateRequestApi,
+ PrecomputeInvalidateResponseApi,
+} from './api.schemas'
+
+export const getPrecomputeDebugInvalidateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/precompute_debug/invalidate/`
+}
+
+/**
+ * Marks the team's READY precompute jobs stale so the next read recomputes them, e.g. after a source resync changed the underlying data. Optionally scoped to a single query hash. PENDING jobs are left alone: anything in flight is already computing against current data.
+ * @summary Invalidate stored precompute for this team (staff only)
+ */
+export const precomputeDebugInvalidate = async (
+ projectId: string,
+ precomputeInvalidateRequestApi?: PrecomputeInvalidateRequestApi,
+ options?: RequestInit
+): Promise<PrecomputeInvalidateResponseApi> => {
+ return apiMutator<PrecomputeInvalidateResponseApi>(getPrecomputeDebugInvalidateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(precomputeInvalidateRequestApi),
+ })
+}
+
+export const getPrecomputeDebugStateUrl = (projectId: string, params?: PrecomputeDebugStateParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/precompute_debug/state/?${stringifiedParams}`
+ : `/api/projects/${projectId}/precompute_debug/state/`
+}
+
+/**
+ * Staff/dev-only debug view of the team's lazy precompute store: which query hashes are stored, which buckets each covers, per-bucket TTL, and — where recoverable from query_log — the originating query (with filters) each hash serves.
+ * @summary Inspect stored lazy-precompute state (staff only)
+ */
+export const precomputeDebugState = async (
+ projectId: string,
+ params?: PrecomputeDebugStateParams,
+ options?: RequestInit
+): Promise<PrecomputeDebugResponseApi> => {
+ return apiMutator<PrecomputeDebugResponseApi>(getPrecomputeDebugStateUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
diff --git a/products/analytics_platform/frontend/generated/api.zod.ts b/products/analytics_platform/frontend/generated/api.zod.ts
new file mode 100644
index 000000000000..21cdc088a686
--- /dev/null
+++ b/products/analytics_platform/frontend/generated/api.zod.ts
@@ -0,0 +1,24 @@
+/**
+ * Auto-generated Zod validation schemas from the Django backend OpenAPI schema.
+ * To modify these schemas, update the Django serializers or views, then run:
+ * hogli build:openapi
+ * Questions or issues? #team-devex on Slack
+ *
+ * PostHog API - generated
+ * OpenAPI spec version: 1.0.0
+ */
+import * as zod from 'zod'
+
+/**
+ * Marks the team's READY precompute jobs stale so the next read recomputes them, e.g. after a source resync changed the underlying data. Optionally scoped to a single query hash. PENDING jobs are left alone: anything in flight is already computing against current data.
+ * @summary Invalidate stored precompute for this team (staff only)
+ */
+export const precomputeDebugInvalidateBodyQueryHashMax = 64
+
+export const PrecomputeDebugInvalidateBody = /* @__PURE__ */ zod.object({
+ query_hash: zod
+ .string()
+ .max(precomputeDebugInvalidateBodyQueryHashMax)
+ .nullish()
+ .describe('Only invalidate jobs for this query hash. Omit to invalidate every hash stored for the team.'),
+})
diff --git a/products/analytics_platform/frontend/precomputeDebugLogic.ts b/products/analytics_platform/frontend/precomputeDebugLogic.ts
new file mode 100644
index 000000000000..88d974327d95
--- /dev/null
+++ b/products/analytics_platform/frontend/precomputeDebugLogic.ts
@@ -0,0 +1,105 @@
+import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+
+import { getCurrentTeamId } from '~/lib/utils/getAppContext'
+
+import { precomputeDebugInvalidate, precomputeDebugState } from './generated/api'
+import type { PrecomputeDebugResponseApi } from './generated/api.schemas'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface precomputeDebugLogicValues {
+ debugState: PrecomputeDebugResponseApi | null
+ debugStateLoading: boolean
+ invalidatingHash: string | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface precomputeDebugLogicActions {
+ invalidate: (queryHash: string | null) => {
+ queryHash: string | null
+ }
+ invalidateFinished: () => {
+ value: true
+ }
+ loadDebugState: () => any
+ loadDebugStateFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadDebugStateSuccess: (
+ debugState: PrecomputeDebugResponseApi,
+ payload?: any
+ ) => {
+ debugState: PrecomputeDebugResponseApi
+ payload?: any
+ }
+}
+
+export type precomputeDebugLogicType = MakeLogicType<precomputeDebugLogicValues, precomputeDebugLogicActions>
+
+export const precomputeDebugLogic = kea<precomputeDebugLogicType>([
+ path(['products', 'analytics_platform', 'frontend', 'precomputeDebugLogic']),
+
+ actions({
+ invalidate: (queryHash: string | null) => ({ queryHash }),
+ invalidateFinished: true,
+ }),
+
+ loaders({
+ debugState: [
+ null as PrecomputeDebugResponseApi | null,
+ {
+ loadDebugState: async () => {
+ return await precomputeDebugState(String(getCurrentTeamId()))
+ },
+ },
+ ],
+ }),
+
+ reducers({
+ // The hash being invalidated, or 'all' — drives per-button loading and
+ // blocks concurrent invalidations.
+ invalidatingHash: [
+ null as string | null,
+ {
+ invalidate: (_, { queryHash }) => queryHash ?? 'all',
+ invalidateFinished: () => null,
+ },
+ ],
+ }),
+
+ listeners(({ actions }) => ({
+ invalidate: async ({ queryHash }) => {
+ try {
+ const result = await precomputeDebugInvalidate(String(getCurrentTeamId()), {
+ query_hash: queryHash,
+ })
+ const pendingNote =
+ result.pending_count > 0
+ ? ` (${result.pending_count} in-flight ${
+ result.pending_count === 1 ? 'job' : 'jobs'
+ } untouched, invalidate again once ${result.pending_count === 1 ? 'it' : 'they'} settle)`
+ : ''
+ lemonToast.success(
+ `Marked ${result.updated_count} precompute ${
+ result.updated_count === 1 ? 'job' : 'jobs'
+ } stale${pendingNote}`
+ )
+ actions.loadDebugState()
+ } catch {
+ lemonToast.error('Failed to invalidate precompute jobs')
+ } finally {
+ actions.invalidateFinished()
+ }
+ },
+ })),
+
+ afterMount(({ actions }) => {
+ actions.loadDebugState()
+ }),
+])
diff --git a/products/analytics_platform/manifest.tsx b/products/analytics_platform/manifest.tsx
index c178d26a3f6a..46f930975de7 100644
--- a/products/analytics_platform/manifest.tsx
+++ b/products/analytics_platform/manifest.tsx
@@ -2,5 +2,20 @@ import { ProductManifest } from '~/types'
export const manifest: ProductManifest = {
name: 'Analytics Platform',
- urls: {},
+ scenes: {
+ PrecomputeDebug: {
+ import: () => import('./frontend/PrecomputeDebugScene'),
+ projectBased: true,
+ name: 'Precompute debug',
+ description: 'Staff-only view of stored precompute hashes, buckets, and TTLs.',
+ layout: 'app-container',
+ iconType: 'web_analytics',
+ },
+ },
+ routes: {
+ '/debug/precompute': ['PrecomputeDebug', 'precomputeDebug'],
+ },
+ urls: {
+ precomputeDebug: (): string => `/debug/precompute`,
+ },
}
diff --git a/products/analytics_platform/package.json b/products/analytics_platform/package.json
index 1699de4babbf..7b0b3c184594 100644
--- a/products/analytics_platform/package.json
+++ b/products/analytics_platform/package.json
@@ -2,5 +2,14 @@
"name": "@posthog/products-analytics-platform",
"scripts": {
"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short"
+ },
+ "dependencies": {
+ "kea": "catalog:",
+ "kea-loaders": "catalog:"
+ },
+ "peerDependencies": {
+ "@posthog/icons": "catalog:",
+ "@types/react": "*",
+ "react": "*"
}
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index c0a84715e8be..ec4188f224ae 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -75055,6 +75055,135 @@ export namespace Schemas {
Postgres: 'Postgres',
} as const;
+ /**
+ * * `pending` - Pending
+ * * `ready` - Ready
+ * * `stale` - Stale
+ * * `failed` - Failed
+ */
+ export type PreaggregationJobStatusEnum = typeof PreaggregationJobStatusEnum[keyof typeof PreaggregationJobStatusEnum];
+
+
+ export const PreaggregationJobStatusEnum = {
+ Pending: 'pending',
+ Ready: 'ready',
+ Stale: 'stale',
+ Failed: 'failed',
+ } as const;
+
+ export interface PrecomputeDebugBucket {
+ /** Start of the bucket's time window (inclusive). */
+ time_range_start: string;
+ /** End of the bucket's time window (exclusive). */
+ time_range_end: string;
+ /** Lifecycle state of this bucket's job.
+ *
+ * * `pending` - Pending
+ * * `ready` - Ready
+ * * `stale` - Stale
+ * * `failed` - Failed */
+ status: PreaggregationJobStatusEnum;
+ /**
+ * When the bucket's data was last computed; null if never computed.
+ * @nullable
+ */
+ computed_at: string | null;
+ /**
+ * When the bucket's data expires in ClickHouse; null if no TTL recorded.
+ * @nullable
+ */
+ expires_at: string | null;
+ /**
+ * Seconds until the bucket expires; negative when already expired, null if no TTL recorded.
+ * @nullable
+ */
+ ttl_seconds_remaining: number | null;
+ }
+
+ /**
+ * Job count per lifecycle status for this hash.
+ */
+ export type PrecomputeDebugGroupStatusCounts = {[key: string]: number};
+
+ export interface PrecomputeDebugSample {
+ /**
+ * query_type tag of the insert that built this hash (identifies the query family).
+ * @nullable
+ */
+ query_type: string | null;
+ /**
+ * Trigger tag of the insert: a warmer trigger name, or empty for a user-initiated read.
+ * @nullable
+ */
+ trigger: string | null;
+ /**
+ * Originating query as JSON (from the insert's log_comment) including date range and property filters — shows which dashboard queries this hash serves.
+ * @nullable
+ */
+ query_json: string | null;
+ /**
+ * When the sampled insert for this hash finished.
+ * @nullable
+ */
+ last_insert_at: string | null;
+ }
+
+ export interface PrecomputeDebugGroup {
+ /** SHA-256 of the normalized insert query this group covers. */
+ query_hash: string;
+ /** Number of bucket jobs stored for this hash (within caps). */
+ job_count: number;
+ /** Job count per lifecycle status for this hash. */
+ status_counts: PrecomputeDebugGroupStatusCounts;
+ /** Start of the earliest bucket stored for this hash. */
+ earliest_start: string;
+ /** End of the latest bucket stored for this hash. */
+ latest_end: string;
+ /**
+ * Most recent computed_at across the hash's buckets.
+ * @nullable
+ */
+ last_computed_at: string | null;
+ /** Originating-query sample recovered from query_log; null when no recent insert was found. */
+ sample: PrecomputeDebugSample | null;
+ /** Most recent buckets for this hash (capped at 70). */
+ buckets: PrecomputeDebugBucket[];
+ }
+
+ export interface PrecomputeDebugResponse {
+ /** When this snapshot was generated. */
+ generated_at: string;
+ /** Expired/failed jobs older than this many days are omitted; unexpired jobs are always shown. */
+ job_lookback_days: number;
+ /** How far back query_log was searched to label hashes with their originating query. */
+ query_log_lookback_days: number;
+ /** Distinct hashes stored for the team within the job lookback. */
+ total_hashes: number;
+ /** Per-hash groups, most recently computed first. */
+ groups: PrecomputeDebugGroup[];
+ }
+
+ export interface PrecomputeInvalidateRequest {
+ /**
+ * Only invalidate jobs for this query hash. Omit to invalidate every hash stored for the team.
+ * @maxLength 64
+ * @nullable
+ */
+ query_hash?: string | null;
+ }
+
+ export interface PrecomputeInvalidateResponse {
+ /** Number of READY jobs marked stale. */
+ updated_count: number;
+ /** In-flight PENDING jobs left untouched. A job that started before a source resync can still finish READY with pre-resync data; invalidate again once these settle to catch it. */
+ pending_count: number;
+ /**
+ * The hash that was invalidated, or null when all hashes were targeted.
+ * @nullable
+ */
+ query_hash: string | null;
+ }
+
export interface PreferencesLink {
/** Token-gated URL where the recipient can manage their preferences. */
preferences_url: string;
@@ -107750,6 +107879,13 @@ export namespace Schemas {
offset?: number;
};
+ export type PrecomputeDebugStateParams = {
+ /**
+ * Maximum number of hash groups to return (1–200).
+ */
+ limit?: number;
+ };
+
export type ProductToursListParams = {
/**
* Number of results to return per page.
diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.json
index 0aeb82163561..3b31b7df573f 100644
--- a/services/mcp/src/tools/links/app-url-manifest.json
+++ b/services/mcp/src/tools/links/app-url-manifest.json
@@ -1254,6 +1254,11 @@
"params": [],
"scope": "project"
},
+ "precomputeDebug": {
+ "template": "/debug/precompute",
+ "params": [],
+ "scope": "project"
+ },
"preflight": {
"template": "/preflight",
"params": [],
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
index 7f6fd9272069..456f1d0d00e2 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
@@ -13,7 +13,7 @@
"type": "object"
},
"url": {
- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/health\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/health\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
"type": "string"
}
},