: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(heatmaps): page history endpoints (#116598)
Jordan Mryyan3bc4f75a20e9
diff --git a/products/web_analytics/backend/api/heatmaps_api.py b/products/web_analytics/backend/api/heatmaps_api.pyindex b6a8369591f6..1498f07a32ba 100644--- a/products/web_analytics/backend/api/heatmaps_api.py+++ b/products/web_analytics/backend/api/heatmaps_api.py@@ -3,7 +3,8 @@ from datetime import UTC, date, datetime, time, timedeltafrom io import BytesIOfrom json import JSONDecodeError, dumps, loadsfrom typing import Any, List, Literal, cast, get_args # noqa: UP035-from urllib.parse import parse_qs, urlparse+from urllib.parse import parse_qs, urlencode, urlparse+from uuid import UUIDfrom django.conf import settingsfrom django.core.exceptions import FieldError@@ -11,6 +12,7 @@ from django.db import transactionfrom django.db.models import Qfrom django.http import HttpResponsefrom django.utils import timezone+from django.utils.cache import get_conditional_response, patch_cache_control, patch_vary_headersimport structlogimport posthoganalytics@@ -19,7 +21,7 @@ from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schefrom PIL import Imagefrom prometheus_client import Counterfrom rest_framework import request, response, serializers, status, viewsets-from rest_framework.exceptions import PermissionDenied, UnsupportedMediaType, ValidationError+from rest_framework.exceptions import NotFound, PermissionDenied, Throttled, UnsupportedMediaType, ValidationErrorfrom rest_framework.parsers import FormParser, MultiPartParserfrom rest_framework.permissions import BasePermissionfrom rest_framework.views import APIView@@ -77,8 +79,25 @@ from products.web_analytics.backend.api.heatmaps_utils import (capture_image_within_limits,heatmaps_flag_enabled,)+from products.web_analytics.backend.heatmap_history import (+ HEATMAP_HISTORY_MANUAL_COOLDOWN,+ HEATMAP_HISTORY_RETENTION,+ CaptureCooldown,+ CaptureDispatchError,+ HeatmapHistoryService,+ history_eligible,+ history_enabled,+ history_width,+)+from products.web_analytics.backend.heatmap_history_storage import Variant, image_exists, read_imagefrom products.web_analytics.backend.heatmap_preflight import BlockedBy, Framing, preflight_page-from products.web_analytics.backend.models import HeatmapCaptureConfigVersion, HeatmapSnapshot, SavedHeatmap+from products.web_analytics.backend.models import (+ HeatmapCaptureConfigVersion,+ HeatmapCaptureRequest,+ HeatmapScreenshotHistory,+ HeatmapSnapshot,+ SavedHeatmap,+)from products.web_analytics.backend.tasks.heatmap_screenshot import (HEATMAP_SCREENSHOT_MAX_BYTES,_persist_snapshot,@@ -86,6 +105,7 @@ from products.web_analytics.backend.tasks.heatmap_screenshot import ()STALE_PROCESSING_THRESHOLD = timedelta(minutes=10)+LAST_VIEWED_WRITE_INTERVAL = timedelta(hours=1)MAX_CAPTURE_TOTAL_BYTES = 60 * 1024 * 1024@@ -1295,6 +1315,111 @@ class HeatmapScreenshotResponseSerializer(UserAccessControlSerializerMixin, serireturn snaps+class HeatmapCaptureRequestSerializer(serializers.ModelSerializer):+ request_id = serializers.UUIDField(source="id", help_text="Durable capture request identifier.")++ class Meta:+ model = HeatmapCaptureRequest+ fields = ["request_id", "state", "deadline", "failure_cause", "page_status", "completed_at"]+ read_only_fields = fields+ extra_kwargs = {+ "state": {"help_text": "Queued, running, succeeded, failed, or cancelled."},+ "deadline": {"help_text": "Deadline after which this request cannot publish an image."},+ "failure_cause": {"help_text": "Reason this capture failed, when known."},+ "page_status": {"help_text": "HTTP status returned by the rendered page."},+ "completed_at": {"help_text": "When this request finished."},+ }+++class HeatmapScreenshotHistoryItemSerializer(serializers.ModelSerializer):+ latest_request = HeatmapCaptureRequestSerializer(+ allow_null=True, help_text="Latest attempt, independent of the available image."+ )+ content_url = serializers.SerializerMethodField(help_text="Authenticated, versioned URL of the available JPEG.")+ thumbnail_url = serializers.SerializerMethodField(help_text="Preview URL, or null when no preview is available.")++ class Meta:+ model = HeatmapScreenshotHistory+ fields = [+ "id",+ "captured_on",+ "captured_at",+ "width",+ "timezone",+ "day_start",+ "day_end",+ "expires_at",+ "revision",+ "trigger",+ "status",+ "failure_cause",+ "page_status",+ "content_url",+ "thumbnail_url",+ "latest_request",+ ]+ read_only_fields = fields+ extra_kwargs = {+ "captured_on": {"help_text": "Project-local calendar day of this capture."},+ "captured_at": {"help_text": "Time of the last successful capture."},+ "width": {"help_text": "Actual viewport width of the available image, in CSS pixels."},+ "timezone": {"help_text": "Project timezone when this image was captured."},+ "day_start": {"help_text": "Inclusive UTC start of the captured project day."},+ "day_end": {"help_text": "Exclusive UTC end of the captured project day."},+ "expires_at": {"help_text": "Time this history item expires."},+ "revision": {"help_text": "Successful request UUID identifying this image revision."},+ }++ def _image_url(self, obj: HeatmapScreenshotHistory, variant: str) -> str | None:+ if (+ obj.status != HeatmapScreenshotHistory.Status.OK+ or not obj.has_content+ or (variant == HeatmapScreenshotHistory.ImageVariant.THUMBNAIL and not obj.has_thumbnail)+ ):+ return None+ params = {"v": str(obj.revision), "variant": variant}+ return f"/api/projects/{obj.team_id}/saved/{self.context['short_id']}/screenshot_history/{obj.id}/content/?{urlencode(params)}"++ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_content_url(self, obj: HeatmapScreenshotHistory) -> str | None:+ return self._image_url(obj, "full")++ @extend_schema_field(serializers.CharField(allow_null=True))+ def get_thumbnail_url(self, obj: HeatmapScreenshotHistory) -> str | None:+ return self._image_url(obj, "thumbnail")+++class HeatmapScreenshotHistoryResponseSerializer(serializers.Serializer):+ width = serializers.IntegerField(+ help_text="Viewport width (CSS pixels) daily captures of this heatmap are rendered at."+ )+ retention_days = serializers.IntegerField(+ help_text="Captures older than this many days are deleted together with their images."+ )+ storage_available = serializers.BooleanField(+ help_text="Whether object storage is configured on this installation. Captures are only kept when it is."+ )+ results = HeatmapScreenshotHistoryItemSerializer(+ many=True, help_text="Captures within the retention window, newest first."+ )+++class HeatmapScreenshotHistoryCaptureResponseSerializer(serializers.Serializer):+ status = serializers.CharField(help_text="Initial state of the durable capture request.")+ request_id = serializers.UUIDField(help_text="Request to poll for the capture outcome.")+ deadline = serializers.DateTimeField(help_text="Time this request expires if it has not completed.")+ width = serializers.IntegerField(help_text="Requested viewport width in CSS pixels.")+++class HeatmapScreenshotHistoryContentQuerySerializer(serializers.Serializer):+ variant = serializers.ChoiceField(+ choices=HeatmapScreenshotHistory.ImageVariant.choices,+ default="full",+ help_text="Full JPEG or thumbnail. Missing thumbnails return 404.",+ )+ v = serializers.UUIDField(help_text="Successful request UUID; stale revisions return 404.")++class HeatmapScreenshotViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):# Screenshot exports render the heatmap in a headless browser, which authenticates# via an EXPORT_RENDERER JWT. Without opting into ExportRendererAuthentication here,@@ -1646,7 +1771,7 @@ class SavedHeatmapViewSet(DEFAULT_ORDER = "-updated_at"def get_throttles(self):- if self.action in ("create", "prewarm", "capture"):+ if self.action in ("create", "prewarm", "capture", "capture_screenshot_history"):# More restrictive rate limiting for expensive screenshot generationreturn [AIBurstRateThrottle(), AISustainedRateThrottle()]if self.action == "preflight":@@ -1917,6 +2042,17 @@ class SavedHeatmapViewSet(def retrieve(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:obj = self.get_object()+ now = timezone.now()+ cutoff = now - LAST_VIEWED_WRITE_INTERVAL+ if (+ history_eligible(obj)+ and (obj.last_viewed_at is None or obj.last_viewed_at < cutoff)+ and history_enabled(self.team)+ ):+ SavedHeatmap.objects.filter(+ Q(last_viewed_at__isnull=True) | Q(last_viewed_at__lt=cutoff), team_id=self.team.id, id=obj.id+ ).update(last_viewed_at=now)+if (obj.type == SavedHeatmap.Type.SCREENSHOTand obj.status == SavedHeatmap.Status.PROCESSING@@ -1950,6 +2086,177 @@ class SavedHeatmapViewSet(response_serializer = HeatmapScreenshotResponseSerializer(obj, context=self.get_serializer_context())return response.Response(response_serializer.data, status=status.HTTP_200_OK)+ def _page_history_heatmap(self) -> SavedHeatmap:+ obj = self.get_object()+ if not history_enabled(self.team) or obj.deleted:+ raise NotFound()+ return obj++ @staticmethod+ def _path_uuid(kwargs: dict[str, Any], name: str) -> UUID:+ try:+ return UUID(str(kwargs.get(name)))+ except ValueError:+ raise NotFound()++ @extend_schema(+ responses={+ 200: HeatmapScreenshotHistoryResponseSerializer,+ 404: OpenApiResponse(description="Page history is not enabled for this project"),+ },+ description="List the daily screenshot captures kept for a saved heatmap, newest first. Each capture is a "+ "render of the page on that day at one viewport width, so the clicks of a day or a range can be viewed "+ "over the background that matches it. Captures older than the retention window are deleted.",+ )+ @action(methods=["GET"], detail=True, url_path="screenshot_history", required_scopes=["heatmap:read"])+ def screenshot_history(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:+ obj = self._page_history_heatmap()+ rows = list(+ HeatmapScreenshotHistory.objects.for_team(self.team.id)+ .filter(heatmap=obj, expires_at__gt=timezone.now())+ .select_related("latest_request")+ .order_by("-captured_on", "-captured_at")+ )+ serializer = HeatmapScreenshotHistoryResponseSerializer(+ {+ "width": history_width(obj),+ "retention_days": HEATMAP_HISTORY_RETENTION.days,+ "storage_available": bool(settings.OBJECT_STORAGE_ENABLED),+ "results": rows,+ },+ context={"short_id": obj.short_id},+ )+ return response.Response(serializer.data, status=status.HTTP_200_OK)++ @extend_schema(+ request=None,+ responses={+ 202: HeatmapScreenshotHistoryCaptureResponseSerializer,+ 400: OpenApiResponse(description="Not a server-rendered screenshot heatmap"),+ 404: OpenApiResponse(description="Page history is not enabled for this project"),+ 429: OpenApiResponse(description="A capture was requested for this heatmap in the last 10 minutes"),+ },+ description="Render and keep a capture of the page now, instead of waiting for the daily run, for example "+ "right after a deploy. The render runs in the background; poll the history list for the new capture. A "+ "capture requested on a day that already has one replaces that day's image.",+ )+ @action(methods=["POST"], detail=True, url_path="screenshot_history/capture", required_scopes=["heatmap:write"])+ def capture_screenshot_history(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:+ obj = self._page_history_heatmap()+ if obj.type != SavedHeatmap.Type.SCREENSHOT or obj.source != SavedHeatmap.Source.SERVER:+ return response.Response(+ {"error": "Only server-rendered screenshot heatmaps keep a page history"},+ status=status.HTTP_400_BAD_REQUEST,+ )+ if not settings.OBJECT_STORAGE_ENABLED:+ return response.Response(+ {"error": "Object storage isn't set up on this installation, so captures can't be kept"},+ status=status.HTTP_400_BAD_REQUEST,+ )+ try:+ capture = HeatmapHistoryService.enqueue(+ team_id=self.team.id, heatmap_id=obj.id, trigger=HeatmapScreenshotHistory.Trigger.MANUAL+ )+ except CaptureCooldown:+ raise Throttled(wait=int(HEATMAP_HISTORY_MANUAL_COOLDOWN.total_seconds()))+ except CaptureDispatchError:+ return response.Response({"detail": "Could not queue the capture. Try again."}, status=503)+ if capture is None:+ raise ValidationError("This heatmap is not eligible for history captures.")+ serializer = HeatmapScreenshotHistoryCaptureResponseSerializer(+ {"status": capture.state, "request_id": capture.id, "deadline": capture.deadline, "width": capture.width}+ )+ return response.Response(serializer.data, status=status.HTTP_202_ACCEPTED)++ @extend_schema(+ parameters=[OpenApiParameter("request_id", OpenApiTypes.UUID, OpenApiParameter.PATH)],+ responses={200: HeatmapCaptureRequestSerializer},+ description="Read the outcome of a capture request.",+ )+ @action(+ methods=["GET"],+ detail=True,+ url_path=r"screenshot_history/requests/(?P<request_id>[^/.]+)",+ required_scopes=["heatmap:read"],+ )+ def screenshot_history_request(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:+ obj = self._page_history_heatmap()+ request_id = self._path_uuid(kwargs, "request_id")+ capture = (+ HeatmapCaptureRequest.objects.for_team(self.team.id)+ .filter(heatmap=obj, id=request_id, expires_at__gt=timezone.now())+ .first()+ )+ if capture is None:+ raise NotFound()+ return response.Response(HeatmapCaptureRequestSerializer(capture).data)++ @extend_schema(+ parameters=[+ OpenApiParameter(+ name="history_id",+ type=OpenApiTypes.UUID,+ location=OpenApiParameter.PATH,+ description="ID of the capture, as listed by the screenshot history endpoint.",+ ),+ HeatmapScreenshotHistoryContentQuerySerializer,+ ],+ responses={+ (200, "image/jpeg"): OpenApiTypes.BINARY,+ 304: OpenApiResponse(description="Not modified"),+ 404: OpenApiResponse(description="No such capture, or page history is not enabled for this project"),+ },+ description="Fetch the JPEG for one daily capture, or its thumbnail. The list endpoint hands out versioned "+ "URLs, so the response carries a private day-long cache lifetime and an ETag that changes when the day "+ "is captured again.",+ )+ @action(+ methods=["GET"],+ detail=True,+ url_path=r"screenshot_history/(?P<history_id>[^/.]+)/content",+ required_scopes=["heatmap:read"],+ )+ def screenshot_history_content(self, request: request.Request, *args: Any, **kwargs: Any) -> HttpResponse:+ obj = self._page_history_heatmap()+ query = HeatmapScreenshotHistoryContentQuerySerializer(data=request.query_params)+ query.is_valid(raise_exception=True)+ history_id = self._path_uuid(kwargs, "history_id")+ revision: UUID = query.validated_data["v"]+ variant = query.validated_data["variant"]+ now = timezone.now()+ rows = HeatmapScreenshotHistory.objects.for_team(self.team.id).filter(+ heatmap=obj,+ id=history_id,+ status=HeatmapScreenshotHistory.Status.OK,+ expires_at__gt=now,+ revision=revision,+ )+ if variant == HeatmapScreenshotHistory.ImageVariant.THUMBNAIL:+ rows = rows.filter(has_thumbnail=True)+ history = rows.first()+ if history is None:+ raise NotFound()+ etag = f'"{revision}:{variant}"'+ conditional = get_conditional_response(request._request, etag=etag)+ content: bytes | None = None+ try:+ if conditional is None:+ content = read_image(self.team.id, revision, cast(Variant, variant))+ found = content is not None+ else:+ found = image_exists(self.team.id, revision, cast(Variant, variant))+ except Exception:+ logger.warning("heatmap_history.content_unavailable", history_id=str(history.id), exc_info=True)+ return response.Response({"detail": "The image is temporarily unavailable."}, status=503)+ if not found:+ raise NotFound()+ http_response = conditional if conditional is not None else HttpResponse(content, content_type="image/jpeg")+ remaining = max(0, int((history.expires_at - now).total_seconds()))+ patch_cache_control(http_response, private=True, max_age=min(86400, remaining))+ http_response["ETag"] = etag+ patch_vary_headers(http_response, ("Cookie", "Authorization"))+ return http_response+@validated_request(request_serializer=HeatmapPreflightRequestSerializer,responses={200: OpenApiResponse(response=HeatmapPreflightResponseSerializer)},@@ -1999,9 +2306,6 @@ class SavedHeatmapViewSet()def partial_update(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:obj = self.get_object()- old_url = obj.url- old_block_consent_modals = obj.block_consent_modals-url_fields_changed = any(field in request.data and request.data[field] != getattr(obj, field) for field in ("url", "data_url"))@@ -2017,21 +2321,28 @@ class SavedHeatmapViewSet(serializer = SavedHeatmapRequestSerializer(obj, data=request.data, partial=True)serializer.is_valid(raise_exception=True)+ validated = serializer.validated_data- if obj.source == SavedHeatmap.Source.TOOLBAR:- validated = serializer.validated_data- render_input_changing = ("url" in validated and validated["url"] != obj.url) or (- "block_consent_modals" in validated and validated["block_consent_modals"] != obj.block_consent_modals+ with transaction.atomic():+ locked = SavedHeatmap.objects.select_for_update(of=("self",)).get(team_id=self.team.id, id=obj.id)+ url_fields_changed = any(+ field in validated and validated[field] != getattr(locked, field) for field in ("url", "data_url"))- if render_input_changing:+ if url_fields_changed and not self.user_access_control.check_access_level_for_resource(+ "heatmap", required_level="editor"+ ):+ raise PermissionDenied("You do not have permission to change the URL of this heatmap.")+ render_input_changing = ("url" in validated and validated["url"] != locked.url) or (+ "block_consent_modals" in validated and validated["block_consent_modals"] != locked.block_consent_modals+ )+ if locked.source == SavedHeatmap.Source.TOOLBAR and render_input_changing:raise ValidationError("Toolbar-captured heatmaps can't change their URL or rendering settings; re-capture from the toolbar instead.")+ serializer.instance = locked+ updated = serializer.save()- updated = serializer.save()-- render_input_changed = updated.url != old_url or updated.block_consent_modals != old_block_consent_modals- if updated.type == SavedHeatmap.Type.SCREENSHOT and render_input_changed:+ if updated.type == SavedHeatmap.Type.SCREENSHOT and render_input_changing:self._regenerate(updated)self._log_heatmap_activity(request, updated, "updated")diff --git a/products/web_analytics/backend/heatmap_history.py b/products/web_analytics/backend/heatmap_history.pyindex f38891224960..f2f56abf431c 100644--- a/products/web_analytics/backend/heatmap_history.py+++ b/products/web_analytics/backend/heatmap_history.py@@ -1,4 +1,5 @@import json+import asyncioimport hashlibfrom datetime import UTC, date, datetime, time, timedeltafrom io import BytesIO@@ -52,6 +53,7 @@ HEATMAPS_PAGE_HISTORY_FLAG = "heatmaps-page-history"HEATMAP_HISTORY_PREFERRED_WIDTH = 1024HEATMAP_HISTORY_RETENTION = timedelta(days=90)HEATMAP_HISTORY_MANUAL_COOLDOWN = timedelta(minutes=10)+HEATMAP_HISTORY_DISPATCH_TIMEOUT = timedelta(seconds=10)HEATMAP_HISTORY_REQUEST_TIMEOUT = timedelta(minutes=30)HEATMAP_HISTORY_TEAM_DAILY_CAP = 100HEATMAP_HISTORY_GLOBAL_DAILY_CAP = 5000@@ -164,14 +166,17 @@ def defer_to_next_day(heatmap: SavedHeatmap, day: CaptureDay) -> None:async def start_capture_workflow(request: HeatmapCaptureRequest) -> None:- client = await async_connect()- await client.start_workflow(- CAPTURE_WORKFLOW_NAME,- CaptureInputs(team_id=request.team_id, request_id=str(request.id)),- id=capture_workflow_id(str(request.id)),- task_queue=settings.WEB_ANALYTICS_TASK_QUEUE,- execution_timeout=max(request.deadline - timezone.now(), timedelta(seconds=1)),- )+ async def start() -> None:+ client = await async_connect()+ await client.start_workflow(+ CAPTURE_WORKFLOW_NAME,+ CaptureInputs(team_id=request.team_id, request_id=str(request.id)),+ id=capture_workflow_id(str(request.id)),+ task_queue=settings.WEB_ANALYTICS_TASK_QUEUE,+ execution_timeout=max(request.deadline - timezone.now(), timedelta(seconds=1)),+ )++ await asyncio.wait_for(start(), timeout=HEATMAP_HISTORY_DISPATCH_TIMEOUT.total_seconds())class HeatmapHistoryService:diff --git a/products/web_analytics/backend/heatmap_history_storage.py b/products/web_analytics/backend/heatmap_history_storage.pyindex 8422ba00d0f6..b93759f24284 100644--- a/products/web_analytics/backend/heatmap_history_storage.py+++ b/products/web_analytics/backend/heatmap_history_storage.py@@ -27,6 +27,10 @@ def read_image(team_id: int, request_id: UUID, variant: Variant) -> bytes | Nonereturn object_storage.read_bytes(image_key(team_id, request_id, variant), missing_ok=True)+def image_exists(team_id: int, request_id: UUID, variant: Variant) -> bool:+ return object_storage.head_object_strict(image_key(team_id, request_id, variant)) is not None++def delete_images_now(team_id: int, request_ids: Iterable[UUID]) -> set[UUID]:keys = {image_key(team_id, request_id, variant): request_id for request_id in request_ids for variant in VARIANTS}if not keys:diff --git a/products/web_analytics/backend/test/test_heatmap_access_control.py b/products/web_analytics/backend/test/test_heatmap_access_control.pyindex b3c50608b0c9..e214a9645dee 100644--- a/products/web_analytics/backend/test/test_heatmap_access_control.py+++ b/products/web_analytics/backend/test/test_heatmap_access_control.py@@ -93,6 +93,10 @@ class TestHeatmapAccessControl(ClickhouseTestMixin, APIBaseTest):("editor", "PATCH", status.HTTP_200_OK, {"name": "updated"}),("editor", "POST_REGENERATE", status.HTTP_200_OK, None),("none", "GET", status.HTTP_403_FORBIDDEN, None),+ ("viewer", "GET_HISTORY", status.HTTP_200_OK, None),+ ("viewer", "POST_HISTORY_CAPTURE", status.HTTP_403_FORBIDDEN, None),+ ("editor", "POST_HISTORY_CAPTURE", status.HTTP_202_ACCEPTED, None),+ ("none", "GET_HISTORY", status.HTTP_403_FORBIDDEN, None),])def test_access_level_matrix(self, access_level, method, expected_status, patch_body):@@ -106,6 +110,15 @@ class TestHeatmapAccessControl(ClickhouseTestMixin, APIBaseTest):response = self.client.patch(self._detail_url(), data=patch_body, format="json")elif method == "POST_REGENERATE":response = self.client.post(self._detail_url() + "regenerate/")+ elif method == "GET_HISTORY":+ with patch("products.web_analytics.backend.api.heatmaps_api.history_enabled", return_value=True):+ response = self.client.get(self._detail_url() + "screenshot_history/")+ elif method == "POST_HISTORY_CAPTURE":+ with (+ patch("products.web_analytics.backend.api.heatmaps_api.history_enabled", return_value=True),+ patch("products.web_analytics.backend.heatmap_history.history_enabled", return_value=True),+ ):+ response = self.client.post(self._detail_url() + "screenshot_history/capture/")else:raise AssertionError(f"Unsupported method {method}")diff --git a/products/web_analytics/backend/test/test_heatmap_screenshot_history.py b/products/web_analytics/backend/test/test_heatmap_screenshot_history.pyindex ba6b2756ad11..5f34e726d7c5 100644--- a/products/web_analytics/backend/test/test_heatmap_screenshot_history.py+++ b/products/web_analytics/backend/test/test_heatmap_screenshot_history.py@@ -1,8 +1,9 @@+import asynciofrom concurrent.futures import ThreadPoolExecutorfrom datetime import UTC, datetime, timedeltafrom io import BytesIOfrom threading import Barrier-from uuid import UUID+from uuid import UUID, uuid4import pytestfrom posthog.test.base import APIBaseTest@@ -16,6 +17,7 @@ from parameterized import parameterizedfrom PIL import Imagefrom posthog.models import Organization, Team+from posthog.rate_limit import AIBurstRateThrottlefrom posthog.storage.object_storage import ObjectStorageErrorfrom products.web_analytics.backend.heatmap_history import (@@ -35,6 +37,7 @@ from products.web_analytics.backend.temporal.page_history.types import ClaimedCaTASK_MODULE = "products.web_analytics.backend.heatmap_history"SCHEDULING_MODULE = "products.web_analytics.backend.temporal.page_history.scheduling"RENDER_MODULE = "products.web_analytics.backend.tasks.heatmap_screenshot"+API_MODULE = "products.web_analytics.backend.api.heatmaps_api"STORAGE_MODULE = "products.web_analytics.backend.heatmap_history_storage"@@ -84,15 +87,18 @@ class TestHeatmapHistory(APIBaseTest):self.storage = MagicMock()self.storage.write.side_effect = lambda key, content, **kwargs: self.blobs.update({key: content})self.storage.read_bytes.side_effect = lambda key, **kwargs: self.blobs.get(key)+ self.storage.head_object_strict.side_effect = lambda key, **kwargs: {} if key in self.blobs else Noneself.storage.delete_objects.side_effect = self.delete_blobsfor name, replacement in [(f"{STORAGE_MODULE}.object_storage", self.storage),(f"{TASK_MODULE}.history_enabled", lambda team: True),(f"{SCHEDULING_MODULE}.history_enabled", lambda team: True),+ (f"{API_MODULE}.history_enabled", lambda team: True),]:patcher = patch(name, replacement)patcher.start()self.addCleanup(patcher.stop)+ self.base_url = f"/api/projects/{self.team.id}/saved/{self.heatmap.short_id}/screenshot_history/"def enqueue(self, trigger: str = "manual") -> HeatmapCaptureRequest:with patch.object(HeatmapHistoryService, "dispatch"), self.captureOnCommitCallbacks(execute=True):@@ -234,10 +240,15 @@ class TestHeatmapHistory(APIBaseTest):assert not self.images(old)assert self.images(new)- def test_dispatch_failure_is_retryable_and_reported(self) -> None:+ @parameterized.expand([("unavailable", RuntimeError("unavailable")), ("stalled", None)])+ def test_dispatch_failure_is_retryable_and_reported(self, _name: str, error: Exception | None) -> None:+ async def stall() -> None:+ await asyncio.sleep(5)+with (self.assertRaises(CaptureDispatchError),- patch(f"{TASK_MODULE}.async_connect", side_effect=RuntimeError("unavailable")),+ patch(f"{TASK_MODULE}.HEATMAP_HISTORY_DISPATCH_TIMEOUT", timedelta(milliseconds=50)),+ patch(f"{TASK_MODULE}.async_connect", side_effect=error or stall),self.captureOnCommitCallbacks(execute=True),):HeatmapHistoryService.enqueue(team_id=self.team.id, heatmap_id=self.heatmap.id, trigger="manual")@@ -306,9 +317,69 @@ class TestHeatmapHistory(APIBaseTest):request = self.enqueue()with patch.object(HeatmapHistoryService, "thumbnail", return_value=None):self.execute_capture(request)- history = self.history()- assert history.has_content- assert not history.has_thumbnail+ row = self.client.get(self.base_url).json()["results"][0]+ assert row["content_url"]+ assert row["thumbnail_url"] is None+ assert self.client.get(row["content_url"] + "&variant=thumbnail").status_code == 404++ def test_capture_api_status_and_cooldown(self) -> None:+ with patch.object(HeatmapHistoryService, "dispatch"), self.captureOnCommitCallbacks(execute=True):+ result = self.client.post(self.base_url + "capture/")+ throttled = self.client.post(self.base_url + "capture/")+ assert result.status_code == 202+ assert throttled.status_code == 429+ assert throttled["Retry-After"] == "600"+ request_id = result.json()["request_id"]+ assert self.client.get(self.base_url + f"requests/{request_id}/").json()["state"] == "queued"+ assert self.client.get(self.base_url + f"requests/{uuid4()}/").status_code == 404+ with patch(f"{API_MODULE}.history_enabled", return_value=False):+ assert self.client.get(self.base_url).status_code == 404++ def test_capture_api_shares_the_render_budget_across_heatmaps(self) -> None:+ second = SavedHeatmap.objects.create(+ team=self.team, url="https://example.com/second", target_widths=[1024], status="completed"+ )+ with (+ patch.object(AIBurstRateThrottle, "rate", "1/minute"),+ patch.object(HeatmapHistoryService, "dispatch"),+ self.captureOnCommitCallbacks(execute=True),+ ):+ first = self.client.post(self.base_url + "capture/")+ throttled = self.client.post(+ f"/api/projects/{self.team.id}/saved/{second.short_id}/screenshot_history/capture/"+ )+ assert first.status_code == 202+ assert throttled.status_code == 429++ def test_image_revisions_expiry_and_cache_headers(self) -> None:+ request = self.enqueue()+ self.execute_capture(request)+ row = self.client.get(self.base_url).json()["results"][0]+ url = row["content_url"]+ image = self.client.get(url)+ assert image.status_code == 200+ assert image.content == jpeg()+ self.storage.read_bytes.reset_mock()+ cached = self.client.get(url, HTTP_IF_NONE_MATCH=image["ETag"])+ assert cached.status_code == 304+ self.storage.read_bytes.assert_not_called()+ assert cached["ETag"] == image["ETag"]+ assert cached["Cache-Control"] == image["Cache-Control"]+ assert self.client.get(url.replace(str(request.id), str(uuid4()))).status_code == 404+ rows = HeatmapScreenshotHistory.objects.for_team(self.team.id).filter(id=row["id"])+ rows.update(expires_at=timezone.now() + timedelta(seconds=30))+ assert int(self.client.get(url)["Cache-Control"].split("=")[1]) <= 30+ rows.update(expires_at=timezone.now() - timedelta(seconds=1))+ assert self.client.get(url).status_code == 404+ assert self.client.get(self.base_url).json()["results"] == []++ def test_missing_object_returns_404_including_conditional_requests(self) -> None:+ request = self.enqueue()+ self.execute_capture(request)+ url = self.client.get(self.base_url).json()["results"][0]["content_url"]+ etag = self.client.get(url)["ETag"]+ self.blobs.clear()+ assert self.client.get(url, HTTP_IF_NONE_MATCH=etag).status_code == 404def test_scheduler_enqueues_once_per_day(self) -> None:with patch.object(HeatmapHistoryService, "dispatch") as dispatch, self.captureOnCommitCallbacks(execute=True):diff --git a/products/web_analytics/frontend/generated/api.schemas.ts b/products/web_analytics/frontend/generated/api.schemas.tsindex 7d5c486eb066..aa06e5a77da2 100644--- a/products/web_analytics/frontend/generated/api.schemas.ts+++ b/products/web_analytics/frontend/generated/api.schemas.ts@@ -370,6 +370,146 @@ export interface PatchedSavedHeatmapRequestApi {block_consent_modals?: boolean}+/**+ * * `scheduled` - Daily capture+ * * `manual` - Requested capture+ */+export type HeatmapScreenshotHistoryTriggerEnumApi =+ (typeof HeatmapScreenshotHistoryTriggerEnumApi)[keyof typeof HeatmapScreenshotHistoryTriggerEnumApi]++export const HeatmapScreenshotHistoryTriggerEnumApi = {+ Scheduled: 'scheduled',+ Manual: 'manual',+} as const++/**+ * * `ok` - Captured+ * * `pending` - Capture pending+ * * `failed` - Capture failed+ */+export type HeatmapScreenshotHistoryStatusEnumApi =+ (typeof HeatmapScreenshotHistoryStatusEnumApi)[keyof typeof HeatmapScreenshotHistoryStatusEnumApi]++export const HeatmapScreenshotHistoryStatusEnumApi = {+ Ok: 'ok',+ Pending: 'pending',+ Failed: 'failed',+} as const++/**+ * * `queued` - Queued+ * * `running` - Running+ * * `succeeded` - Succeeded+ * * `failed` - Failed+ * * `cancelled` - Cancelled+ */+export type HeatmapCaptureRequestStateEnumApi =+ (typeof HeatmapCaptureRequestStateEnumApi)[keyof typeof HeatmapCaptureRequestStateEnumApi]++export const HeatmapCaptureRequestStateEnumApi = {+ Queued: 'queued',+ Running: 'running',+ Succeeded: 'succeeded',+ Failed: 'failed',+ Cancelled: 'cancelled',+} as const++export interface HeatmapCaptureRequestApi {+ /** Durable capture request identifier. */+ request_id: string+ /** Queued, running, succeeded, failed, or cancelled.+ *+ * * `queued` - Queued+ * * `running` - Running+ * * `succeeded` - Succeeded+ * * `failed` - Failed+ * * `cancelled` - Cancelled */+ readonly state: HeatmapCaptureRequestStateEnumApi+ /** Deadline after which this request cannot publish an image. */+ readonly deadline: string+ /**+ * Reason this capture failed, when known.+ * @nullable+ */+ readonly failure_cause: string | null+ /**+ * HTTP status returned by the rendered page.+ * @nullable+ */+ readonly page_status: number | null+ /**+ * When this request finished.+ * @nullable+ */+ readonly completed_at: string | null+}++export interface HeatmapScreenshotHistoryItemApi {+ readonly id: string+ /** Project-local calendar day of this capture. */+ readonly captured_on: string+ /**+ * Time of the last successful capture.+ * @nullable+ */+ readonly captured_at: string | null+ /** Actual viewport width of the available image, in CSS pixels. */+ readonly width: number+ /** Project timezone when this image was captured. */+ readonly timezone: string+ /** Inclusive UTC start of the captured project day. */+ readonly day_start: string+ /** Exclusive UTC end of the captured project day. */+ readonly day_end: string+ /** Time this history item expires. */+ readonly expires_at: string+ /**+ * Successful request UUID identifying this image revision.+ * @nullable+ */+ readonly revision: string | null+ readonly trigger: HeatmapScreenshotHistoryTriggerEnumApi+ readonly status: HeatmapScreenshotHistoryStatusEnumApi+ /** @nullable */+ readonly failure_cause: string | null+ /** @nullable */+ readonly page_status: number | null+ /**+ * Authenticated, versioned URL of the available JPEG.+ * @nullable+ */+ readonly content_url: string | null+ /**+ * Preview URL, or null when no preview is available.+ * @nullable+ */+ readonly thumbnail_url: string | null+ /** Latest attempt, independent of the available image. */+ latest_request: HeatmapCaptureRequestApi | null+}++export interface HeatmapScreenshotHistoryResponseApi {+ /** Viewport width (CSS pixels) daily captures of this heatmap are rendered at. */+ width: number+ /** Captures older than this many days are deleted together with their images. */+ retention_days: number+ /** Whether object storage is configured on this installation. Captures are only kept when it is. */+ storage_available: boolean+ /** Captures within the retention window, newest first. */+ results: HeatmapScreenshotHistoryItemApi[]+}++export interface HeatmapScreenshotHistoryCaptureResponseApi {+ /** Initial state of the durable capture request. */+ status: string+ /** Request to poll for the capture outcome. */+ request_id: string+ /** Time this request expires if it has not completed. */+ deadline: string+ /** Requested viewport width in CSS pixels. */+ width: number+}+export interface SavedHeatmapCaptureRequestApi {/*** Single screenshot of the page, captured client-side by the toolbar (JPEG or PNG). Max 20MB. Pair with 'width'. Use 'images'/'widths' instead to save several viewport widths on one heatmap.@@ -1726,6 +1866,29 @@ export type SavedListParams = {type?: string}+export type SavedScreenshotHistoryContentRetrieveParams = {+ /**+ * Successful request UUID; stale revisions return 404.+ */+ v: string+ /**+ * Full JPEG or thumbnail. Missing thumbnails return 404.+ *+ * * `full` - Full page+ * * `thumbnail` - Thumbnail+ * @minLength 1+ */+ variant?: SavedScreenshotHistoryContentRetrieveVariant+}++export type SavedScreenshotHistoryContentRetrieveVariant =+ (typeof SavedScreenshotHistoryContentRetrieveVariant)[keyof typeof SavedScreenshotHistoryContentRetrieveVariant]++export const SavedScreenshotHistoryContentRetrieveVariant = {+ Full: 'full',+ Thumbnail: 'thumbnail',+} as const+export type WebAnalyticsRecapParams = {/*** When true (default), include period-over-period change for each metric comparing against the prior equal-length period. Set to false to skip the comparison query.diff --git a/products/web_analytics/frontend/generated/api.ts b/products/web_analytics/frontend/generated/api.tsindex 0d79830d99c1..17022d11ec61 100644--- a/products/web_analytics/frontend/generated/api.ts+++ b/products/web_analytics/frontend/generated/api.ts@@ -26,11 +26,14 @@ import type {ContentAutopilotSiteProfileApi,GeneratePathCleaningSuggestionResponseApi,HeatmapCapturePagesApi,+ HeatmapCaptureRequestApi,HeatmapCaptureSettingsApi,HeatmapEventsResponseApi,HeatmapPreflightRequestApi,HeatmapPreflightResponseApi,HeatmapPrewarmRequestApi,+ HeatmapScreenshotHistoryCaptureResponseApi,+ HeatmapScreenshotHistoryResponseApi,HeatmapScreenshotResponseApi,HeatmapScreenshotSettingsApi,HeatmapScreenshotsContentRetrieveParams,@@ -57,6 +60,7 @@ import type {SavedHeatmapListResponseApi,SavedHeatmapRequestApi,SavedListParams,+ SavedScreenshotHistoryContentRetrieveParams,WebAnalyticsBotRuleApi,WebAnalyticsContentAutopilotOpportunitiesListParams,WebAnalyticsContentAutopilotProfilesListParams,@@ -383,6 +387,104 @@ export const savedRegenerateCreate = async (})}+export const getSavedScreenshotHistoryRetrieveUrl = (projectId: string, shortId: string) => {+ return `/api/projects/${projectId}/saved/${shortId}/screenshot_history/`+}++/**+ * List the daily screenshot captures kept for a saved heatmap, newest first. Each capture is a render of the page on that day at one viewport width, so the clicks of a day or a range can be viewed over the background that matches it. Captures older than the retention window are deleted.+ */+export const savedScreenshotHistoryRetrieve = async (+ projectId: string,+ shortId: string,+ options?: RequestInit+): Promise<HeatmapScreenshotHistoryResponseApi> => {+ return apiMutator<HeatmapScreenshotHistoryResponseApi>(getSavedScreenshotHistoryRetrieveUrl(projectId, shortId), {+ ...options,+ method: 'GET',+ })+}++export const getSavedScreenshotHistoryContentRetrieveUrl = (+ projectId: string,+ shortId: string,+ historyId: string,+ params: SavedScreenshotHistoryContentRetrieveParams+) => {+ 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}/saved/${shortId}/screenshot_history/${historyId}/content/?${stringifiedParams}`+ : `/api/projects/${projectId}/saved/${shortId}/screenshot_history/${historyId}/content/`+}++/**+ * Fetch the JPEG for one daily capture, or its thumbnail. The list endpoint hands out versioned URLs, so the response carries a private day-long cache lifetime and an ETag that changes when the day is captured again.+ */+export const savedScreenshotHistoryContentRetrieve = async (+ projectId: string,+ shortId: string,+ historyId: string,+ params: SavedScreenshotHistoryContentRetrieveParams,+ options?: RequestInit+): Promise<Blob> => {+ return apiMutator<Blob>(getSavedScreenshotHistoryContentRetrieveUrl(projectId, shortId, historyId, params), {+ ...options,+ method: 'GET',+ })+}++export const getSavedScreenshotHistoryCaptureCreateUrl = (projectId: string, shortId: string) => {+ return `/api/projects/${projectId}/saved/${shortId}/screenshot_history/capture/`+}++/**+ * Render and keep a capture of the page now, instead of waiting for the daily run, for example right after a deploy. The render runs in the background; poll the history list for the new capture. A capture requested on a day that already has one replaces that day's image.+ */+export const savedScreenshotHistoryCaptureCreate = async (+ projectId: string,+ shortId: string,+ options?: RequestInit+): Promise<HeatmapScreenshotHistoryCaptureResponseApi> => {+ return apiMutator<HeatmapScreenshotHistoryCaptureResponseApi>(+ getSavedScreenshotHistoryCaptureCreateUrl(projectId, shortId),+ {+ ...options,+ method: 'POST',+ }+ )+}++export const getSavedScreenshotHistoryRequestsRetrieveUrl = (projectId: string, shortId: string, requestId: string) => {+ return `/api/projects/${projectId}/saved/${shortId}/screenshot_history/requests/${requestId}/`+}++/**+ * Read the outcome of a capture request.+ */+export const savedScreenshotHistoryRequestsRetrieve = async (+ projectId: string,+ shortId: string,+ requestId: string,+ options?: RequestInit+): Promise<HeatmapCaptureRequestApi> => {+ return apiMutator<HeatmapCaptureRequestApi>(+ getSavedScreenshotHistoryRequestsRetrieveUrl(projectId, shortId, requestId),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getSavedCaptureCreateUrl = (projectId: string) => {return `/api/projects/${projectId}/saved/capture/`}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex da00a52c14b8..fa5d5b980398 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -54368,6 +54368,54 @@ export namespace Schemas {pages: HeatmapCapturePage[];}+ /**+ * * `queued` - Queued+ * * `running` - Running+ * * `succeeded` - Succeeded+ * * `failed` - Failed+ * * `cancelled` - Cancelled+ */+ export type HeatmapCaptureRequestStateEnum = typeof HeatmapCaptureRequestStateEnum[keyof typeof HeatmapCaptureRequestStateEnum];+++ export const HeatmapCaptureRequestStateEnum = {+ Queued: 'queued',+ Running: 'running',+ Succeeded: 'succeeded',+ Failed: 'failed',+ Cancelled: 'cancelled',+ } as const;++ export interface HeatmapCaptureRequest {+ /** Durable capture request identifier. */+ request_id: string;+ /** Queued, running, succeeded, failed, or cancelled.+ *+ * * `queued` - Queued+ * * `running` - Running+ * * `succeeded` - Succeeded+ * * `failed` - Failed+ * * `cancelled` - Cancelled */+ readonly state: HeatmapCaptureRequestStateEnum;+ /** Deadline after which this request cannot publish an image. */+ readonly deadline: string;+ /**+ * Reason this capture failed, when known.+ * @nullable+ */+ readonly failure_cause: string | null;+ /**+ * HTTP status returned by the rendered page.+ * @nullable+ */+ readonly page_status: number | null;+ /**+ * When this request finished.+ * @nullable+ */+ readonly completed_at: string | null;+ }+/*** * `all` - All URLs* * `url_allowlist` - Only listed URLs@@ -54476,6 +54524,98 @@ export namespace Schemas {pointer_target_fixed: boolean;}+ export interface HeatmapScreenshotHistoryCaptureResponse {+ /** Initial state of the durable capture request. */+ status: string;+ /** Request to poll for the capture outcome. */+ request_id: string;+ /** Time this request expires if it has not completed. */+ deadline: string;+ /** Requested viewport width in CSS pixels. */+ width: number;+ }++ /**+ * * `scheduled` - Daily capture+ * * `manual` - Requested capture+ */+ export type HeatmapScreenshotHistoryTriggerEnum = typeof HeatmapScreenshotHistoryTriggerEnum[keyof typeof HeatmapScreenshotHistoryTriggerEnum];+++ export const HeatmapScreenshotHistoryTriggerEnum = {+ Scheduled: 'scheduled',+ Manual: 'manual',+ } as const;++ /**+ * * `ok` - Captured+ * * `pending` - Capture pending+ * * `failed` - Capture failed+ */+ export type HeatmapScreenshotHistoryStatusEnum = typeof HeatmapScreenshotHistoryStatusEnum[keyof typeof HeatmapScreenshotHistoryStatusEnum];+++ export const HeatmapScreenshotHistoryStatusEnum = {+ Ok: 'ok',+ Pending: 'pending',+ Failed: 'failed',+ } as const;++ export interface HeatmapScreenshotHistoryItem {+ readonly id: string;+ /** Project-local calendar day of this capture. */+ readonly captured_on: string;+ /**+ * Time of the last successful capture.+ * @nullable+ */+ readonly captured_at: string | null;+ /** Actual viewport width of the available image, in CSS pixels. */+ readonly width: number;+ /** Project timezone when this image was captured. */+ readonly timezone: string;+ /** Inclusive UTC start of the captured project day. */+ readonly day_start: string;+ /** Exclusive UTC end of the captured project day. */+ readonly day_end: string;+ /** Time this history item expires. */+ readonly expires_at: string;+ /**+ * Successful request UUID identifying this image revision.+ * @nullable+ */+ readonly revision: string | null;+ readonly trigger: HeatmapScreenshotHistoryTriggerEnum;+ readonly status: HeatmapScreenshotHistoryStatusEnum;+ /** @nullable */+ readonly failure_cause: string | null;+ /** @nullable */+ readonly page_status: number | null;+ /**+ * Authenticated, versioned URL of the available JPEG.+ * @nullable+ */+ readonly content_url: string | null;+ /**+ * Preview URL, or null when no preview is available.+ * @nullable+ */+ readonly thumbnail_url: string | null;+ /** Latest attempt, independent of the available image. */+ latest_request: HeatmapCaptureRequest | null;+ }++ export interface HeatmapScreenshotHistoryResponse {+ /** Viewport width (CSS pixels) daily captures of this heatmap are rendered at. */+ width: number;+ /** Captures older than this many days are deleted together with their images. */+ retention_days: number;+ /** Whether object storage is configured on this installation. Captures are only kept when it is. */+ storage_available: boolean;+ /** Captures within the retention window, newest first. */+ results: HeatmapScreenshotHistoryItem[];+ }+/*** * `screenshot` - Screenshot* * `iframe` - Iframe@@ -128669,6 +128809,29 @@ export namespace Schemas {type?: string;};+ export type SavedScreenshotHistoryContentRetrieveParams = {+ /**+ * Successful request UUID; stale revisions return 404.+ */+ v: string;+ /**+ * Full JPEG or thumbnail. Missing thumbnails return 404.+ *+ * * `full` - Full page+ * * `thumbnail` - Thumbnail+ * @minLength 1+ */+ variant?: SavedScreenshotHistoryContentRetrieveVariant;+ };++ export type SavedScreenshotHistoryContentRetrieveVariant = typeof SavedScreenshotHistoryContentRetrieveVariant[keyof typeof SavedScreenshotHistoryContentRetrieveVariant];+++ export const SavedScreenshotHistoryContentRetrieveVariant = {+ Full: 'full',+ Thumbnail: 'thumbnail',+ } as const;+export type SavedQueryColumnAnnotationsListParams = {/*** Number of results to return per page.