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(heatmaps): add the page history capture service (#114970)

Jordan Mryyana0652deb4072
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index 9e223e27875d..31b3087b9c77 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -375,6 +375,7 @@ MCPA_TASK_QUEUE = _set_temporal_task_queue(os.getenv("MCPA_TASK_QUEUE", "general
ERROR_TRACKING_TASK_QUEUE = _set_temporal_task_queue("error-tracking-task-queue")
ERROR_TRACKING_LIFECYCLE_TASK_QUEUE = _set_temporal_task_queue("error-tracking-lifecycle-task-queue")
EVENT_SCREENSHOTS_TASK_QUEUE = _set_temporal_task_queue("event-screenshots-task-queue")
+WEB_ANALYTICS_TASK_QUEUE = _set_temporal_task_queue("web-analytics-task-queue")
LOGS_ALERTING_TASK_QUEUE = _set_temporal_task_queue("logs-alerting-task-queue")
# Polled by the temporal-worker-self-driving fleet. The default matches it, so a deploy without the
# env var still registers the autoresearch coordinator schedule on the queue that fleet polls.
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index c3f8ceebc299..6d7019599613 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -122,6 +122,7 @@ post_delete:products.slack_app.backend.signals.invalidate_repo_list_on_user_gith
post_delete:products.surveys.backend.models.survey_changed
post_delete:products.tasks.backend.models.delete_task_session_object
post_delete:products.tasks.backend.search_index.channel_deleted
+post_delete:products.web_analytics.backend.heatmap_history_expiry.delete_request_images
post_delete:products.workflows.backend.models.hog_flow.hog_flow.hog_flow_deleted
post_delete:products.workflows.backend.receivers.optimization_deleted
post_init:posthog.storage.gateway_credential_signal_handlers._snapshot_oauth
@@ -304,6 +305,7 @@ pre_save:products.feature_flags.backend.flag_version_sync.capture_flag_definitio
pre_save:products.feature_flags.backend.session_recording_links.capture_replay_link_key_before_save
pre_save:products.signals.backend.receivers.capture_prior_state
pre_save:products.surveys.backend.models.pre_save_survey
+pre_save:products.web_analytics.backend.heatmap_history_expiry.invalidate_history
user_logged_in:posthog.models.activity_logging.signal_handlers.log_user_login_activity
user_logged_in:posthog.models.activity_logging.signal_handlers.post_login
user_logged_out:posthog.models.activity_logging.signal_handlers.log_user_logout_activity
diff --git a/products/web_analytics/backend/apps.py b/products/web_analytics/backend/apps.py
index 8ac1189359d9..aacd1a028aef 100644
--- a/products/web_analytics/backend/apps.py
+++ b/products/web_analytics/backend/apps.py
@@ -5,3 +5,8 @@ class WebAnalyticsConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "products.web_analytics.backend"
label = "web_analytics"
+
+ def ready(self) -> None:
+ from products.web_analytics.backend import (
+ heatmap_history_expiry, # noqa: F401, PLC0415 — registers model receivers
+ )
diff --git a/products/web_analytics/backend/heatmap_history.py b/products/web_analytics/backend/heatmap_history.py
new file mode 100644
index 000000000000..961b0fa40517
--- /dev/null
+++ b/products/web_analytics/backend/heatmap_history.py
@@ -0,0 +1,480 @@
+import json
+import hashlib
+from datetime import UTC, date, datetime, time, timedelta
+from io import BytesIO
+from uuid import UUID, uuid4
+from zoneinfo import ZoneInfo
+
+from django.conf import settings
+from django.db import connection, transaction
+from django.utils import timezone
+
+import structlog
+from asgiref.sync import async_to_sync
+from PIL import Image
+from prometheus_client import Counter
+
+from posthog.dataclasses import frozen
+from posthog.egress.limiter.policies import Priority
+from posthog.models import Team
+from posthog.scheduling.jitter import deterministic_offset
+from posthog.security.url_validation import is_url_allowed
+from posthog.storage.object_storage import ObjectStorageError
+from posthog.temporal.common.client import async_connect
+
+from products.web_analytics.backend.api.heatmaps_utils import capture_image_within_limits, heatmaps_flag_enabled
+from products.web_analytics.backend.heatmap_history_expiry import cancel_live_requests
+from products.web_analytics.backend.heatmap_history_storage import delete_images_on_commit, write_image
+from products.web_analytics.backend.models import HeatmapCaptureRequest, HeatmapScreenshotHistory, SavedHeatmap
+from products.web_analytics.backend.tasks.heatmap_screenshot import (
+ BrowserlessPermanentError,
+ PageHttpStatusError,
+ _classify_failure,
+ _resolve_widths,
+ render_page,
+)
+from products.web_analytics.backend.temporal.page_history.types import (
+ CAPTURE_WORKFLOW_NAME,
+ RENDER_RETRY_DELAY,
+ CaptureInputs,
+ RenderOutcome,
+ capture_workflow_id,
+ tick_start,
+)
+
+logger = structlog.get_logger(__name__)
+HEATMAPS_PAGE_HISTORY_FLAG = "heatmaps-page-history"
+HEATMAP_HISTORY_PREFERRED_WIDTH = 1024
+HEATMAP_HISTORY_RETENTION = timedelta(days=90)
+HEATMAP_HISTORY_MANUAL_COOLDOWN = timedelta(minutes=10)
+HEATMAP_HISTORY_REQUEST_TIMEOUT = timedelta(minutes=30)
+HEATMAP_HISTORY_TEAM_DAILY_CAP = 100
+HEATMAP_HISTORY_GLOBAL_DAILY_CAP = 5000
+HEATMAP_HISTORY_TICK_CAP = 18
+HISTORY_CAPTURES = Counter("heatmap_screenshot_history_captures", "History capture outcomes", ["outcome", "cause"])
+
+
+class CaptureCooldown(ValueError):
+ pass
+
+
+class CaptureDispatchError(Exception):
+ pass
+
+
+@frozen
+class CaptureDay:
+ captured_on: date
+ timezone: str
+ start: datetime
+ end: datetime
+
+
+def capture_day(now: datetime, timezone_name: str) -> CaptureDay:
+ zone = ZoneInfo(timezone_name)
+ day = now.astimezone(zone).date()
+ return CaptureDay(
+ captured_on=day,
+ timezone=timezone_name,
+ start=datetime.combine(day, time.min, tzinfo=zone).astimezone(UTC),
+ end=datetime.combine(day + timedelta(days=1), time.min, tzinfo=zone).astimezone(UTC),
+ )
+
+
+def history_due_at(heatmap_id: UUID, day: CaptureDay) -> datetime:
+ return day.start + deterministic_offset(str(heatmap_id), day.end - day.start - HEATMAP_HISTORY_REQUEST_TIMEOUT)
+
+
+def next_history_due_at(heatmap_id: UUID, day: CaptureDay) -> datetime:
+ return history_due_at(heatmap_id, capture_day(day.end + timedelta(seconds=1), day.timezone))
+
+
+def advisory_xact_lock(key: str) -> None:
+ with connection.cursor() as cursor:
+ cursor.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))", [key])
+
+
+def history_width(heatmap: SavedHeatmap) -> int:
+ widths = _resolve_widths(heatmap)
+ return min(widths, key=lambda width: (abs(width - HEATMAP_HISTORY_PREFERRED_WIDTH), width))
+
+
+def history_enabled(team: Team) -> bool:
+ return heatmaps_flag_enabled(
+ HEATMAPS_PAGE_HISTORY_FLAG, str(team.uuid), team_id=team.id, organization_id=str(team.organization_id)
+ )
+
+
+def capture_signature(heatmap: SavedHeatmap) -> str:
+ inputs = [
+ heatmap.url,
+ heatmap.data_url,
+ history_width(heatmap),
+ heatmap.block_consent_modals,
+ heatmap.type,
+ heatmap.source,
+ heatmap.team.timezone,
+ str(heatmap.history_configuration_revision),
+ ]
+ return hashlib.sha256(json.dumps(inputs).encode()).hexdigest()
+
+
+def history_eligible(heatmap: SavedHeatmap) -> bool:
+ return (
+ settings.OBJECT_STORAGE_ENABLED
+ and not heatmap.deleted
+ and not heatmap.is_prewarm
+ and heatmap.type == SavedHeatmap.Type.SCREENSHOT
+ and heatmap.source == SavedHeatmap.Source.SERVER
+ )
+
+
+def capture_still_wanted(heatmap: SavedHeatmap | None, request: HeatmapCaptureRequest, enabled: bool) -> bool:
+ return (
+ heatmap is not None
+ and enabled
+ and history_eligible(heatmap)
+ and request.input_signature == capture_signature(heatmap)
+ and timezone.now() < request.deadline
+ )
+
+
+def scheduled_requests_today(now: datetime) -> int:
+ utc_start = datetime.combine(now.date(), time.min, tzinfo=UTC)
+ return (
+ HeatmapCaptureRequest.objects.unscoped()
+ .filter(
+ trigger=HeatmapScreenshotHistory.Trigger.SCHEDULED,
+ created_at__gte=utc_start,
+ created_at__lt=utc_start + timedelta(days=1),
+ )
+ .count()
+ )
+
+
+def defer_to_next_day(heatmap: SavedHeatmap, day: CaptureDay) -> None:
+ SavedHeatmap.objects.filter(team_id=heatmap.team_id, id=heatmap.id).update(
+ next_history_capture_at=next_history_due_at(heatmap.id, day)
+ )
+
+
+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)),
+ )
+
+
+class HeatmapHistoryService:
+ @staticmethod
+ def enqueue(*, team_id: int, heatmap_id: UUID, trigger: str, dispatch: bool = True) -> HeatmapCaptureRequest | None:
+ candidate = SavedHeatmap.objects.select_related("team").get(team_id=team_id, id=heatmap_id)
+ if not history_eligible(candidate) or not history_enabled(candidate.team):
+ return None
+ now = timezone.now()
+ scheduled = trigger == HeatmapScreenshotHistory.Trigger.SCHEDULED
+ with transaction.atomic():
+ if scheduled:
+ advisory_xact_lock(f"heatmap-history:{now.date()}")
+ heatmap = (
+ SavedHeatmap.objects.select_for_update(of=("self",))
+ .select_related("team")
+ .get(team_id=team_id, id=heatmap_id)
+ )
+ if not history_eligible(heatmap):
+ return None
+ day = capture_day(now, heatmap.team.timezone)
+ requests = HeatmapCaptureRequest.objects.for_team(team_id).filter(heatmap=heatmap)
+ if scheduled:
+ advisory_xact_lock(f"heatmap-history-team:{team_id}:{day.captured_on}")
+ global_count = scheduled_requests_today(now)
+ team_count = (
+ HeatmapCaptureRequest.objects.for_team(team_id)
+ .filter(trigger=trigger, captured_on=day.captured_on)
+ .count()
+ )
+ tick_count = (
+ HeatmapCaptureRequest.objects.unscoped()
+ .filter(trigger=trigger, created_at__gte=tick_start(now))
+ .count()
+ )
+ if team_count >= HEATMAP_HISTORY_TEAM_DAILY_CAP:
+ defer_to_next_day(heatmap, day)
+ return None
+ if global_count >= HEATMAP_HISTORY_GLOBAL_DAILY_CAP or tick_count >= HEATMAP_HISTORY_TICK_CAP:
+ return None
+ already_requested = requests.filter(captured_on=day.captured_on, trigger=trigger).exists()
+ already_captured = (
+ HeatmapScreenshotHistory.objects.for_team(team_id)
+ .filter(
+ heatmap=heatmap,
+ captured_on=day.captured_on,
+ status=HeatmapScreenshotHistory.Status.OK,
+ expires_at__gt=now,
+ revision__isnull=False,
+ )
+ .exists()
+ )
+ if already_requested or already_captured:
+ defer_to_next_day(heatmap, day)
+ return None
+ if requests.filter(state__in=HeatmapCaptureRequest.LIVE_STATES).exists():
+ return None
+ elif (
+ requests.filter(trigger=trigger, created_at__gt=now - HEATMAP_HISTORY_MANUAL_COOLDOWN)
+ .exclude(failure_cause="dispatch_failed")
+ .exists()
+ ):
+ raise CaptureCooldown("A capture was requested in the last 10 minutes")
+ width = history_width(heatmap)
+ expires_at = now + HEATMAP_HISTORY_RETENTION
+ history, _ = HeatmapScreenshotHistory.objects.for_team(team_id).get_or_create(
+ heatmap=heatmap,
+ captured_on=day.captured_on,
+ defaults={
+ "team_id": team_id,
+ "width": width,
+ "timezone": day.timezone,
+ "day_start": day.start,
+ "day_end": day.end,
+ "expires_at": expires_at,
+ "status": HeatmapScreenshotHistory.Status.PENDING,
+ },
+ )
+ cancel_live_requests(team_id=team_id, heatmap_id=heatmap.id)
+ request = HeatmapCaptureRequest.objects.for_team(team_id).create(
+ team_id=team_id,
+ heatmap=heatmap,
+ history=history,
+ trigger=trigger,
+ captured_on=day.captured_on,
+ timezone=day.timezone,
+ day_start=day.start,
+ day_end=day.end,
+ width=width,
+ url=heatmap.url,
+ block_consent_modals=heatmap.block_consent_modals,
+ input_signature=capture_signature(heatmap),
+ deadline=min(now + HEATMAP_HISTORY_REQUEST_TIMEOUT, day.end),
+ expires_at=expires_at,
+ created_at=now,
+ )
+ history.latest_request = request
+ if not history.has_content:
+ history.status = HeatmapScreenshotHistory.Status.PENDING
+ history.save(update_fields=["latest_request", "status", "updated_at"])
+ if scheduled:
+ defer_to_next_day(heatmap, day)
+ if dispatch:
+ transaction.on_commit(lambda: HeatmapHistoryService.dispatch(request))
+ return request
+
+ @staticmethod
+ def dispatch(request: HeatmapCaptureRequest) -> None:
+ try:
+ async_to_sync(start_capture_workflow)(request)
+ except Exception as error:
+ HeatmapHistoryService.fail(request, "dispatch_failed")
+ raise CaptureDispatchError("Could not queue the capture") from error
+
+ @staticmethod
+ def fail(
+ request: HeatmapCaptureRequest,
+ cause: str,
+ page_status: int | None = None,
+ state: HeatmapCaptureRequest.State = HeatmapCaptureRequest.State.FAILED,
+ ) -> None:
+ updated = (
+ HeatmapCaptureRequest.objects.for_team(request.team_id)
+ .filter(id=request.id, state__in=HeatmapCaptureRequest.LIVE_STATES, claim_id=request.claim_id)
+ .update(
+ state=state,
+ completed_at=timezone.now(),
+ failure_cause=cause,
+ page_status=page_status,
+ )
+ )
+ if not updated:
+ return
+ HeatmapScreenshotHistory.objects.for_team(request.team_id).filter(
+ id=request.history_id,
+ latest_request_id=request.id,
+ revision__isnull=True,
+ ).update(status=HeatmapScreenshotHistory.Status.FAILED, failure_cause=cause, page_status=page_status)
+ delete_images_on_commit(request.team_id, [request.id])
+ HISTORY_CAPTURES.labels(outcome="failed", cause=cause).inc()
+
+ @staticmethod
+ def claim(*, team_id: int, request_id: UUID) -> HeatmapCaptureRequest | None:
+ queued = (
+ HeatmapCaptureRequest.objects.for_team(team_id)
+ .filter(id=request_id)
+ .select_related("heatmap__team")
+ .first()
+ )
+ if queued is None:
+ return None
+ enabled = history_enabled(queued.heatmap.team)
+ with transaction.atomic():
+ heatmap = (
+ SavedHeatmap.objects.select_for_update(of=("self",))
+ .select_related("team")
+ .filter(team_id=team_id, id=queued.heatmap_id)
+ .first()
+ )
+ request = (
+ HeatmapCaptureRequest.objects.for_team(team_id)
+ .select_for_update()
+ .filter(id=request_id, state=HeatmapCaptureRequest.State.QUEUED)
+ .first()
+ )
+ if heatmap is None or request is None:
+ return None
+ current = (
+ HeatmapScreenshotHistory.objects.for_team(team_id)
+ .filter(id=request.history_id, latest_request_id=request.id)
+ .exists()
+ )
+ if not current or not capture_still_wanted(heatmap, request, enabled):
+ HeatmapHistoryService.fail(request, "capture_cancelled", state=HeatmapCaptureRequest.State.CANCELLED)
+ return None
+ request.state = HeatmapCaptureRequest.State.RUNNING
+ request.claim_id = uuid4()
+ request.save(update_fields=["state", "claim_id"])
+ return request
+
+ @staticmethod
+ def render(request: HeatmapCaptureRequest) -> bytes:
+ allowed, _ = is_url_allowed(request.url)
+ if not allowed:
+ raise BrowserlessPermanentError("Page URL cannot be rendered", cause="ssrf_blocked")
+ image = render_page(
+ request.team_id,
+ request.url,
+ request.width,
+ request.block_consent_modals,
+ priority=Priority.BATCH,
+ source="heatmap_screenshot_history",
+ )
+ try:
+ if not image.endswith(b"\xff\xd9"):
+ raise ValueError("Screenshot is not a complete JPEG")
+ with Image.open(BytesIO(image), formats=["JPEG"]) as screenshot:
+ if screenshot.width != request.width or not capture_image_within_limits(
+ screenshot.width, screenshot.height
+ ):
+ raise ValueError("Screenshot dimensions or size are invalid")
+ screenshot.load()
+ except Exception as error:
+ raise BrowserlessPermanentError("Screenshot is not a valid JPEG", cause="invalid_image") from error
+ return image
+
+ @staticmethod
+ def thumbnail(image: bytes) -> bytes | None:
+ try:
+ with Image.open(BytesIO(image), formats=["JPEG"]) as screenshot:
+ screenshot.draft("RGB", (640, 640))
+ preview = screenshot.crop(
+ (0, 0, screenshot.width, min(screenshot.height, int(screenshot.width * 0.75)))
+ ).convert("RGB")
+ preview.thumbnail((320, 320))
+ buffer = BytesIO()
+ preview.save(buffer, format="JPEG", quality=70, optimize=True)
+ return buffer.getvalue()
+ except Exception:
+ logger.warning("heatmap_history.thumbnail_failed", exc_info=True)
+ return None
+
+ @staticmethod
+ def publish(request: HeatmapCaptureRequest, thumbnail_available: bool) -> None:
+ team = Team.objects.filter(id=request.team_id).first()
+ enabled = team is not None and history_enabled(team)
+ with transaction.atomic():
+ heatmap = (
+ SavedHeatmap.objects.select_for_update(of=("self",))
+ .select_related("team")
+ .filter(team_id=request.team_id, id=request.heatmap_id)
+ .first()
+ )
+ current = (
+ HeatmapCaptureRequest.objects.for_team(request.team_id)
+ .select_for_update()
+ .filter(id=request.id, state=HeatmapCaptureRequest.State.RUNNING, claim_id=request.claim_id)
+ .first()
+ )
+ history = (
+ HeatmapScreenshotHistory.objects.for_team(request.team_id)
+ .select_for_update()
+ .filter(id=request.history_id)
+ .first()
+ )
+ if current is None:
+ if history is None or history.revision != request.id:
+ delete_images_on_commit(request.team_id, [request.id])
+ return
+ if (
+ history is None
+ or history.latest_request_id != request.id
+ or not capture_still_wanted(heatmap, request, enabled)
+ ):
+ HeatmapHistoryService.fail(request, "capture_cancelled", state=HeatmapCaptureRequest.State.CANCELLED)
+ return
+ retired = history.revision
+ history.revision = request.id
+ history.has_thumbnail = thumbnail_available
+ history.captured_at = timezone.now()
+ history.width = request.width
+ history.timezone = request.timezone
+ history.day_start = request.day_start
+ history.day_end = request.day_end
+ history.expires_at = request.expires_at
+ history.status = HeatmapScreenshotHistory.Status.OK
+ history.trigger = request.trigger
+ history.failure_cause = None
+ history.page_status = None
+ history.save()
+ current.state = HeatmapCaptureRequest.State.SUCCEEDED
+ current.completed_at = timezone.now()
+ current.save(update_fields=["state", "completed_at"])
+ if retired is not None and retired != request.id:
+ delete_images_on_commit(request.team_id, [retired])
+ HISTORY_CAPTURES.labels(outcome="ok", cause="").inc()
+
+ @staticmethod
+ def load_claimed(*, team_id: int, request_id: UUID, claim_id: UUID) -> HeatmapCaptureRequest | None:
+ return (
+ HeatmapCaptureRequest.objects.for_team(team_id)
+ .filter(id=request_id, state=HeatmapCaptureRequest.State.RUNNING, claim_id=claim_id)
+ .first()
+ )
+
+ @staticmethod
+ def render_and_store(request: HeatmapCaptureRequest, *, final_attempt: bool) -> RenderOutcome:
+ try:
+ image = HeatmapHistoryService.render(request)
+ write_image(request.team_id, request.id, "full", image)
+ thumbnail = HeatmapHistoryService.thumbnail(image)
+ if thumbnail is not None:
+ try:
+ write_image(request.team_id, request.id, "thumbnail", thumbnail)
+ except Exception:
+ logger.warning("heatmap_history.thumbnail_write_failed", exc_info=True)
+ thumbnail = None
+ except BrowserlessPermanentError as error:
+ return RenderOutcome(
+ failure_cause=_classify_failure(error),
+ page_status=error.status_code if isinstance(error, PageHttpStatusError) else None,
+ )
+ except Exception as error:
+ if not final_attempt and timezone.now() + RENDER_RETRY_DELAY < request.deadline:
+ raise
+ return RenderOutcome(
+ failure_cause="storage_write_failed"
+ if isinstance(error, ObjectStorageError)
+ else _classify_failure(error)
+ )
+ return RenderOutcome(has_thumbnail=thumbnail is not None)
diff --git a/products/web_analytics/backend/heatmap_history_expiry.py b/products/web_analytics/backend/heatmap_history_expiry.py
new file mode 100644
index 000000000000..c50578fca120
--- /dev/null
+++ b/products/web_analytics/backend/heatmap_history_expiry.py
@@ -0,0 +1,53 @@
+from uuid import UUID, uuid4
+
+from django.db.models.signals import post_delete, pre_save
+from django.dispatch import receiver
+from django.utils import timezone
+
+from products.web_analytics.backend.heatmap_history_storage import delete_images_on_commit
+from products.web_analytics.backend.models import HeatmapCaptureRequest, HeatmapScreenshotHistory, SavedHeatmap
+
+HISTORY_INPUTS = ("url", "data_url", "target_widths", "block_consent_modals", "type", "source", "deleted")
+
+
+def cancel_live_requests(*, team_id: int, heatmap_id: UUID) -> None:
+ live = HeatmapCaptureRequest.objects.for_team(team_id).filter(
+ heatmap_id=heatmap_id, state__in=HeatmapCaptureRequest.LIVE_STATES
+ )
+ request_ids = list(live.values_list("id", flat=True))
+ live.filter(id__in=request_ids).update(state=HeatmapCaptureRequest.State.CANCELLED, completed_at=timezone.now())
+ delete_images_on_commit(team_id, request_ids)
+
+
+@receiver(post_delete, sender=HeatmapCaptureRequest)
+def delete_request_images(
+ sender: type[HeatmapCaptureRequest], instance: HeatmapCaptureRequest, **kwargs: object
+) -> None:
+ if instance.expires_at <= timezone.now():
+ return
+ delete_images_on_commit(instance.team_id, [instance.id])
+
+
+@receiver(pre_save, sender=SavedHeatmap)
+def invalidate_history(
+ sender: type[SavedHeatmap], instance: SavedHeatmap, update_fields: frozenset[str] | None = None, **kwargs: object
+) -> None:
+ if instance._state.adding:
+ instance.history_configuration_revision = uuid4()
+ return
+ if update_fields is not None and update_fields.isdisjoint(HISTORY_INPUTS):
+ return
+ previous = SavedHeatmap.objects.filter(team_id=instance.team_id, id=instance.id).values(*HISTORY_INPUTS).first()
+ if previous is None or not any(previous[field] != getattr(instance, field) for field in HISTORY_INPUTS):
+ return
+ instance.history_configuration_revision = uuid4()
+ instance.next_history_capture_at = None
+ if update_fields is not None:
+ SavedHeatmap.objects.filter(team_id=instance.team_id, id=instance.id).update(
+ history_configuration_revision=instance.history_configuration_revision,
+ next_history_capture_at=None,
+ )
+ if previous["url"] != instance.url or previous["data_url"] != instance.data_url or instance.deleted:
+ HeatmapScreenshotHistory.objects.for_team(instance.team_id).filter(heatmap_id=instance.id).delete()
+ else:
+ cancel_live_requests(team_id=instance.team_id, heatmap_id=instance.id)
diff --git a/products/web_analytics/backend/heatmap_history_storage.py b/products/web_analytics/backend/heatmap_history_storage.py
new file mode 100644
index 000000000000..8422ba00d0f6
--- /dev/null
+++ b/products/web_analytics/backend/heatmap_history_storage.py
@@ -0,0 +1,45 @@
+from collections.abc import Iterable
+from typing import Literal
+from uuid import UUID
+
+from django.db import transaction
+
+import structlog
+
+from posthog.storage import object_storage
+
+logger = structlog.get_logger(__name__)
+
+HEATMAP_HISTORY_PREFIX = "heatmap_screenshot_history"
+Variant = Literal["full", "thumbnail"]
+VARIANTS: tuple[Variant, ...] = ("full", "thumbnail")
+
+
+def image_key(team_id: int, request_id: UUID, variant: Variant) -> str:
+ return f"{HEATMAP_HISTORY_PREFIX}/team-{team_id}/{request_id}/{variant}.jpg"
+
+
+def write_image(team_id: int, request_id: UUID, variant: Variant, content: bytes) -> None:
+ object_storage.write(image_key(team_id, request_id, variant), content, extras={"ContentType": "image/jpeg"})
+
+
+def read_image(team_id: int, request_id: UUID, variant: Variant) -> bytes | None:
+ return object_storage.read_bytes(image_key(team_id, request_id, variant), missing_ok=True)
+
+
+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:
+ return set()
+ try:
+ failed = object_storage.delete_objects(list(keys))
+ except Exception:
+ logger.warning("heatmap_history.image_delete_failed", team_id=team_id, exc_info=True)
+ return set(keys.values())
+ return {keys[key] for key in failed if key in keys}
+
+
+def delete_images_on_commit(team_id: int, request_ids: Iterable[UUID]) -> None:
+ pending = list(request_ids)
+ if pending:
+ transaction.on_commit(lambda: delete_images_now(team_id, pending))
diff --git a/products/web_analytics/backend/tasks/heatmap_screenshot.py b/products/web_analytics/backend/tasks/heatmap_screenshot.py
index 7259cb563bc9..5b3d8a493413 100644
--- a/products/web_analytics/backend/tasks/heatmap_screenshot.py
+++ b/products/web_analytics/backend/tasks/heatmap_screenshot.py
@@ -108,8 +108,8 @@ def _classify_failure(e: BaseException) -> str:
if isinstance(e, PageHttpStatusError):
return "page_http_status"
if isinstance(e, BrowserlessError):
- if e.cause == "not_configured":
- return "not_configured"
+ if e.cause in ("not_configured", "invalid_image", "ssrf_blocked"):
+ return e.cause
if e.cause in ("empty_body", "non_image", "non_jpeg", "oversized"):
return "validation_error"
if e.cause == "egress_budget_exhausted":
diff --git a/products/web_analytics/backend/temporal/page_history/__init__.py b/products/web_analytics/backend/temporal/page_history/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/web_analytics/backend/temporal/page_history/types.py b/products/web_analytics/backend/temporal/page_history/types.py
new file mode 100644
index 000000000000..585ae4d87c1b
--- /dev/null
+++ b/products/web_analytics/backend/temporal/page_history/types.py
@@ -0,0 +1,63 @@
+from datetime import datetime, timedelta
+
+from posthog.dataclasses import frozen
+
+CAPTURE_WORKFLOW_NAME = "heatmap-page-history-capture"
+TICK_WORKFLOW_NAME = "heatmap-page-history-tick"
+TICK_SCHEDULE_ID = "heatmap-page-history-tick-schedule"
+TICK_INTERVAL = timedelta(minutes=5)
+RENDER_ATTEMPTS = 2
+RENDER_RETRY_DELAY = timedelta(seconds=120)
+
+
+def capture_workflow_id(request_id: str) -> str:
+ return f"{CAPTURE_WORKFLOW_NAME}-{request_id}"
+
+
+def tick_start(now: datetime) -> datetime:
+ return now - (now - datetime.min.replace(tzinfo=now.tzinfo)) % TICK_INTERVAL
+
+
+@frozen
+class CaptureInputs:
+ team_id: int
+ request_id: str
+
+
+@frozen
+class ClaimedCapture:
+ team_id: int
+ request_id: str
+ claim_id: str
+
+
+@frozen
+class RenderOutcome:
+ has_thumbnail: bool = False
+ failure_cause: str | None = None
+ page_status: int | None = None
+
+
+@frozen
+class FinishInputs:
+ capture: ClaimedCapture
+ outcome: RenderOutcome
+
+
+@frozen
+class DueCapture:
+ team_id: int
+ request_id: str
+ seconds_left: float
+
+
+@frozen
+class TickInputs:
+ pass
+
+
+@frozen
+class TickResult:
+ pruned: int = 0
+ started: int = 0
+ already_running: int = 0
diff --git a/products/web_analytics/backend/test/test_heatmap_screenshot_history.py b/products/web_analytics/backend/test/test_heatmap_screenshot_history.py
new file mode 100644
index 000000000000..c75da3a41048
--- /dev/null
+++ b/products/web_analytics/backend/test/test_heatmap_screenshot_history.py
@@ -0,0 +1,362 @@
+from concurrent.futures import ThreadPoolExecutor
+from datetime import UTC, datetime, timedelta
+from io import BytesIO
+from threading import Barrier
+from uuid import UUID
+
+import pytest
+from posthog.test.base import APIBaseTest
+from unittest.mock import MagicMock, patch
+
+from django.db import close_old_connections, connections
+from django.test import SimpleTestCase, override_settings
+from django.utils import timezone
+
+from parameterized import parameterized
+from PIL import Image
+
+from posthog.models import Organization, Team
+from posthog.storage.object_storage import ObjectStorageError
+
+from products.web_analytics.backend.heatmap_history import (
+ CaptureCooldown,
+ CaptureDispatchError,
+ HeatmapHistoryService,
+ capture_day,
+ history_due_at,
+ history_width,
+)
+from products.web_analytics.backend.heatmap_history_storage import image_key
+from products.web_analytics.backend.models import HeatmapCaptureRequest, HeatmapScreenshotHistory, SavedHeatmap
+from products.web_analytics.backend.tasks.heatmap_screenshot import BrowserlessPermanentError
+
+TASK_MODULE = "products.web_analytics.backend.heatmap_history"
+RENDER_MODULE = "products.web_analytics.backend.tasks.heatmap_screenshot"
+STORAGE_MODULE = "products.web_analytics.backend.heatmap_history_storage"
+
+
+def jpeg(width: int = 1024) -> bytes:
+ buffer = BytesIO()
+ Image.new("RGB", (width, 100), "white").save(buffer, format="JPEG")
+ return buffer.getvalue()
+
+
+class TestHistoryDates(SimpleTestCase):
+ def test_latest_due_slot_leaves_time_before_midnight(self) -> None:
+ day = capture_day(datetime(2024, 3, 10, 12, tzinfo=UTC), "America/New_York")
+ due = history_due_at(UUID("00000000-0000-0000-0000-0000000000c2"), day)
+ assert day.start < due < day.end - timedelta(minutes=30)
+
+ @parameterized.expand(
+ [
+ ("spring", "2024-03-10T12:00:00+00:00", 23, "2024-03-10"),
+ ("fall", "2024-11-03T12:00:00+00:00", 25, "2024-11-03"),
+ ("midnight", "2024-05-02T02:00:00+00:00", 24, "2024-05-01"),
+ ]
+ )
+ def test_project_day(self, _name: str, instant: str, hours: int, captured_on: str) -> None:
+ day = capture_day(datetime.fromisoformat(instant), "America/New_York")
+ assert day.end - day.start == timedelta(hours=hours)
+ assert day.captured_on.isoformat() == captured_on
+
+ @parameterized.expand([([320, 1024, 1920], 1024), ([320, 768, 1440], 768), ([800, 1248], 800), ([], 1024)])
+ def test_history_width(self, widths: list[int], expected: int) -> None:
+ assert history_width(SavedHeatmap(target_widths=widths)) == expected
+
+
+@override_settings(OBJECT_STORAGE_ENABLED=True)
+class TestHeatmapHistory(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.heatmap = SavedHeatmap.objects.create(
+ team=self.team,
+ url="https://example.com",
+ target_widths=[1024],
+ created_by=self.user,
+ status=SavedHeatmap.Status.COMPLETED,
+ last_viewed_at=timezone.now(),
+ next_history_capture_at=timezone.now(),
+ )
+ self.blobs: dict[str, bytes] = {}
+ 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.delete_objects.side_effect = self.delete_blobs
+ for name, replacement in [
+ (f"{STORAGE_MODULE}.object_storage", self.storage),
+ (f"{TASK_MODULE}.history_enabled", lambda team: True),
+ ]:
+ patcher = patch(name, replacement)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def enqueue(self, trigger: str = "manual") -> HeatmapCaptureRequest:
+ with patch.object(HeatmapHistoryService, "dispatch"), self.captureOnCommitCallbacks(execute=True):
+ request = HeatmapHistoryService.enqueue(team_id=self.team.id, heatmap_id=self.heatmap.id, trigger=trigger)
+ assert request is not None
+ return request
+
+ def delete_blobs(self, keys: list[str], **kwargs: object) -> list[str]:
+ for key in keys:
+ self.blobs.pop(key, None)
+ return []
+
+ def images(self, request: HeatmapCaptureRequest) -> set[str]:
+ return {key for key in self.blobs if f"/{request.id}/" in key}
+
+ def execute_capture(self, request: HeatmapCaptureRequest, error: Exception | None = None) -> None:
+ with (
+ patch.object(HeatmapHistoryService, "render", return_value=jpeg(request.width), side_effect=error),
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ claimed = HeatmapHistoryService.claim(team_id=self.team.id, request_id=request.id)
+ if claimed is not None:
+ outcome = HeatmapHistoryService.render_and_store(claimed, final_attempt=True)
+ if outcome.failure_cause is None:
+ HeatmapHistoryService.publish(claimed, outcome.has_thumbnail)
+ else:
+ HeatmapHistoryService.fail(claimed, outcome.failure_cause, outcome.page_status)
+ request.refresh_from_db()
+
+ def history(self) -> HeatmapScreenshotHistory:
+ return HeatmapScreenshotHistory.objects.for_team(self.team.id).get(heatmap=self.heatmap)
+
+ def allow_recapture(self) -> None:
+ HeatmapCaptureRequest.objects.for_team(self.team.id).filter(heatmap=self.heatmap).update(
+ created_at=timezone.now() - timedelta(minutes=11)
+ )
+
+ def test_capture_claims_once_and_writes_both_images(self) -> None:
+ request = self.enqueue()
+ self.execute_capture(request)
+ assert request.state == "succeeded"
+ self.storage.write.reset_mock()
+ self.execute_capture(request)
+ self.storage.write.assert_not_called()
+ with self.captureOnCommitCallbacks(execute=True):
+ HeatmapHistoryService.publish(request, False)
+ assert self.history().revision == request.id
+ assert self.history().has_thumbnail
+ assert {key.rsplit("/", 1)[1] for key in self.images(request)} == {"full.jpg", "thumbnail.jpg"}
+
+ def replace_with_manual_capture(self) -> None:
+ self.execute_capture(self.enqueue())
+
+ def toggle_render_setting_and_back(self) -> None:
+ for value in (True, False):
+ self.heatmap.block_consent_modals = value
+ self.heatmap.save(update_fields=["block_consent_modals"])
+
+ @parameterized.expand(
+ [
+ ("replaced_by_manual_capture", "replace_with_manual_capture", True),
+ ("settings_changed_and_back", "toggle_render_setting_and_back", True),
+ ("flag_disabled", None, False),
+ ]
+ )
+ def test_late_publish_is_fenced(self, _name: str, change: str | None, enabled: bool) -> None:
+ request = self.enqueue("scheduled")
+ claimed = HeatmapHistoryService.claim(team_id=self.team.id, request_id=request.id)
+ assert claimed is not None
+ if change:
+ getattr(self, change)()
+ self.blobs[image_key(self.team.id, claimed.id, "full")] = jpeg()
+ with (
+ patch(f"{TASK_MODULE}.history_enabled", return_value=enabled),
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ HeatmapHistoryService.publish(claimed, True)
+ assert self.history().revision != claimed.id
+ assert not self.images(claimed)
+
+ def test_failed_replacement_preserves_good_image(self) -> None:
+ good = self.enqueue()
+ self.execute_capture(good)
+ self.allow_recapture()
+ bad = self.enqueue()
+ self.execute_capture(bad, BrowserlessPermanentError("Failed", cause="invalid_image"))
+ assert bad.state == "failed"
+ with self.captureOnCommitCallbacks(execute=True):
+ HeatmapHistoryService.publish(good, False)
+ history = self.history()
+ assert history.revision == good.id
+ assert history.status == "ok"
+ assert history.has_content
+ assert history.latest_request == bad
+ assert history.has_thumbnail
+ assert {key.rsplit("/", 1)[1] for key in self.images(good)} == {"full.jpg", "thumbnail.jpg"}
+ assert not self.images(bad)
+
+ def test_successful_replacement_deletes_old_images(self) -> None:
+ old = self.enqueue()
+ self.execute_capture(old)
+ self.allow_recapture()
+ new = self.enqueue()
+ self.execute_capture(new)
+ assert self.history().revision == new.id
+ assert not self.images(old)
+ assert self.images(new)
+
+ def test_dispatch_failure_is_retryable_and_reported(self) -> None:
+ with (
+ self.assertRaises(CaptureDispatchError),
+ patch(f"{TASK_MODULE}.async_connect", side_effect=RuntimeError("unavailable")),
+ self.captureOnCommitCallbacks(execute=True),
+ ):
+ HeatmapHistoryService.enqueue(team_id=self.team.id, heatmap_id=self.heatmap.id, trigger="manual")
+ latest = self.history().latest_request
+ assert latest is not None
+ assert latest.failure_cause == "dispatch_failed"
+ assert self.enqueue().state == "queued"
+
+ @parameterized.expand(
+ [
+ ("url", "https://example.com/new"),
+ ("data_url", "https://example.com/data"),
+ ("deleted", True),
+ ("hard_delete", None),
+ ]
+ )
+ def test_configuration_reset_cancels_render_and_deletes_images(self, field: str, value: str | bool | None) -> None:
+ request = self.enqueue()
+ claimed = HeatmapHistoryService.claim(team_id=self.team.id, request_id=request.id)
+ assert claimed is not None
+ self.blobs[image_key(self.team.id, request.id, "full")] = jpeg()
+ with self.captureOnCommitCallbacks(execute=True):
+ if field == "hard_delete":
+ self.heatmap.delete()
+ else:
+ setattr(self.heatmap, field, value)
+ self.heatmap.save(update_fields=[field])
+ assert not self.images(request)
+ with self.captureOnCommitCallbacks(execute=True):
+ HeatmapHistoryService.publish(claimed, True)
+ assert not HeatmapScreenshotHistory.objects.for_team(self.team.id).exists()
+
+ def test_thumbnail_failure_uses_no_full_image_fallback(self) -> None:
+ 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
+
+ @parameterized.expand(
+ [
+ ("HEATMAP_HISTORY_TEAM_DAILY_CAP", True),
+ ("HEATMAP_HISTORY_GLOBAL_DAILY_CAP", False),
+ ("HEATMAP_HISTORY_TICK_CAP", False),
+ ]
+ )
+ def test_scheduled_reservations_enforce_caps(self, setting: str, waits_for_tomorrow: bool) -> None:
+ self.enqueue("scheduled")
+ second = SavedHeatmap.objects.create(
+ team=self.team, url="https://example.com/second", status="completed", next_history_capture_at=timezone.now()
+ )
+ with patch(f"{TASK_MODULE}.{setting}", 1):
+ assert (
+ HeatmapHistoryService.enqueue(team_id=self.team.id, heatmap_id=second.id, trigger="scheduled") is None
+ )
+ second.refresh_from_db()
+ assert second.next_history_capture_at is not None
+ assert (second.next_history_capture_at > timezone.now()) == waits_for_tomorrow
+
+ @parameterized.expand(
+ [
+ ("valid", jpeg(1024), True),
+ ("wrong_width", jpeg(768), False),
+ ("truncated", jpeg()[:-2], False),
+ ("not_a_jpeg", b"not-a-jpeg", False),
+ ]
+ )
+ def test_render_validates_complete_jpeg_and_dimensions(self, _name: str, image: bytes, valid: bool) -> None:
+ request = self.enqueue()
+ with (
+ patch(f"{TASK_MODULE}.is_url_allowed", return_value=(True, None)),
+ patch(f"{RENDER_MODULE}._build_browserless_screenshot_url", return_value="https://browserless.example.com"),
+ patch(f"{RENDER_MODULE}._browserless_screenshot", return_value=(image, 200)),
+ ):
+ if valid:
+ assert HeatmapHistoryService.render(request) == image
+ else:
+ with self.assertRaises(BrowserlessPermanentError):
+ HeatmapHistoryService.render(request)
+
+ def test_request_deadline_is_capped_at_project_midnight(self) -> None:
+ instant = datetime(2024, 3, 11, 3, 50, tzinfo=UTC)
+ self.team.timezone = "America/New_York"
+ self.team.save(update_fields=["timezone"])
+ with patch(f"{TASK_MODULE}.timezone.now", return_value=instant):
+ request = self.enqueue()
+ assert request.captured_on.isoformat() == "2024-03-10"
+ assert request.deadline == datetime(2024, 3, 11, 4, tzinfo=UTC)
+
+ def test_pending_manual_capture_does_not_skip_automatic_capture_after_failure(self) -> None:
+ manual = self.enqueue()
+ assert (
+ HeatmapHistoryService.enqueue(team_id=self.team.id, heatmap_id=self.heatmap.id, trigger="scheduled") is None
+ )
+ self.heatmap.refresh_from_db()
+ assert self.heatmap.next_history_capture_at is not None
+ assert self.heatmap.next_history_capture_at <= timezone.now()
+ self.execute_capture(manual, BrowserlessPermanentError("Failed", cause="invalid_image"))
+ assert self.enqueue("scheduled").state == "queued"
+
+ def test_transient_storage_failure_retries_until_the_final_attempt(self) -> None:
+ claimed = HeatmapHistoryService.claim(team_id=self.team.id, request_id=self.enqueue().id)
+ assert claimed is not None
+ self.storage.write.side_effect = ObjectStorageError("unavailable")
+ with patch.object(HeatmapHistoryService, "render", return_value=jpeg()):
+ with self.assertRaises(ObjectStorageError):
+ HeatmapHistoryService.render_and_store(claimed, final_attempt=False)
+ outcome = HeatmapHistoryService.render_and_store(claimed, final_attempt=True)
+ assert outcome.failure_cause == "storage_write_failed"
+ HeatmapCaptureRequest.objects.for_team(self.team.id).filter(id=claimed.id).update(
+ deadline=timezone.now() + timedelta(seconds=60)
+ )
+ claimed.refresh_from_db()
+ with patch.object(HeatmapHistoryService, "render", return_value=jpeg()):
+ outcome = HeatmapHistoryService.render_and_store(claimed, final_attempt=False)
+ assert outcome.failure_cause == "storage_write_failed"
+
+
[email protected]_db(transaction=True)
+@override_settings(OBJECT_STORAGE_ENABLED=True)
+def test_concurrent_requests_and_duplicate_delivery_have_one_winner() -> None:
+ organization = Organization.objects.create(name="Concurrency test")
+ team = Team.objects.create(organization=organization)
+ heatmap = SavedHeatmap.objects.create(team=team, url="https://example.com", target_widths=[1024])
+ barrier = Barrier(2)
+
+ def enqueue() -> HeatmapCaptureRequest | None:
+ close_old_connections()
+ try:
+ barrier.wait(timeout=10)
+ return HeatmapHistoryService.enqueue(team_id=team.id, heatmap_id=heatmap.id, trigger="manual")
+ except CaptureCooldown:
+ return None
+ finally:
+ connections["default"].close()
+
+ with (
+ patch(f"{TASK_MODULE}.history_enabled", return_value=True),
+ patch.object(HeatmapHistoryService, "dispatch"),
+ ThreadPoolExecutor(max_workers=2) as pool,
+ ):
+ requests = list(pool.map(lambda _: enqueue(), range(2)))
+ winners = [request for request in requests if request is not None]
+ assert len(winners) == 1
+ request_id = winners[0].id
+ barrier = Barrier(2)
+
+ def claim() -> HeatmapCaptureRequest | None:
+ close_old_connections()
+ try:
+ barrier.wait(timeout=10)
+ return HeatmapHistoryService.claim(team_id=team.id, request_id=request_id)
+ finally:
+ connections["default"].close()
+
+ with patch(f"{TASK_MODULE}.history_enabled", return_value=True), ThreadPoolExecutor(max_workers=2) as pool:
+ claims = list(pool.map(lambda _: claim(), range(2)))
+ assert len([claim for claim in claims if claim is not None]) == 1