: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): run page history captures on temporal (#114971)
Jordan Mryyana4361abc2b19
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex 71dab6c2096d..9096866b6de7 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -320,6 +320,10 @@ from products.web_analytics.backend.temporal import (ACTIVITIES as WA_DIGEST_ACTIVITIES,WORKFLOWS as WA_DIGEST_WORKFLOWS,)+from products.web_analytics.backend.temporal.page_history.registry import (+ ACTIVITIES as HEATMAP_PAGE_HISTORY_ACTIVITIES,+ WORKFLOWS as HEATMAP_PAGE_HISTORY_WORKFLOWS,+)from products.wizard.backend.facade.temporal import (ACTIVITIES as WIZARD_ACTIVITIES,WORKFLOWS as WIZARD_WORKFLOWS,@@ -573,6 +577,11 @@ _task_queue_specs = [EVENT_SCREENSHOTS_WORKFLOWS,EVENT_SCREENSHOTS_ACTIVITIES,),+ (+ settings.WEB_ANALYTICS_TASK_QUEUE,+ HEATMAP_PAGE_HISTORY_WORKFLOWS,+ HEATMAP_PAGE_HISTORY_ACTIVITIES,+ ),(settings.LOGS_ALERTING_TASK_QUEUE,LOGS_ALERTING_WORKFLOWS,diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex 43488e828f39..fa60ff1ea9dc 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -143,6 +143,7 @@ from products.signals.backend.temporal.agentic.schedule import (from products.today.backend.facade.temporal import create_today_briefing_schedulefrom products.warehouse_suggestions.backend.facade.temporal import create_warehouse_suggestions_schedulefrom products.web_analytics.backend.temporal.digest_notification.types import WADigestNotificationInput+from products.web_analytics.backend.temporal.page_history.schedule import create_heatmap_page_history_schedulefrom products.web_analytics.backend.temporal.weekly_digest.types import WAWeeklyDigestInputfrom ee.billing.salesforce_enrichment.constants import DEFAULT_CHUNK_SIZE@@ -961,6 +962,7 @@ schedules = [create_error_tracking_weekly_digest_schedule,create_wa_weekly_digest_schedule,create_wa_digest_notification_schedule,+ create_heatmap_page_history_schedule,create_data_catalog_weekly_digest_schedule,create_alerts_platform_tick_schedule,create_logs_alert_check_schedule,diff --git a/products/web_analytics/backend/heatmap_history.py b/products/web_analytics/backend/heatmap_history.pyindex 961b0fa40517..f38891224960 100644--- a/products/web_analytics/backend/heatmap_history.py+++ b/products/web_analytics/backend/heatmap_history.py@@ -24,7 +24,11 @@ from posthog.temporal.common.client import async_connectfrom products.web_analytics.backend.api.heatmaps_utils import capture_image_within_limits, heatmaps_flag_enabledfrom 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.heatmap_history_storage import (+ delete_images_now,+ delete_images_on_commit,+ write_image,+)from products.web_analytics.backend.models import HeatmapCaptureRequest, HeatmapScreenshotHistory, SavedHeatmapfrom products.web_analytics.backend.tasks.heatmap_screenshot import (BrowserlessPermanentError,@@ -37,6 +41,7 @@ from products.web_analytics.backend.temporal.page_history.types import (CAPTURE_WORKFLOW_NAME,RENDER_RETRY_DELAY,CaptureInputs,+ FinishInputs,RenderOutcome,capture_workflow_id,tick_start,@@ -309,7 +314,7 @@ class HeatmapHistoryService:HISTORY_CAPTURES.labels(outcome="failed", cause=cause).inc()@staticmethod- def claim(*, team_id: int, request_id: UUID) -> HeatmapCaptureRequest | None:+ def claim(*, team_id: int, request_id: UUID, claim_id: UUID | None = None) -> HeatmapCaptureRequest | None:queued = (HeatmapCaptureRequest.objects.for_team(team_id).filter(id=request_id)@@ -329,11 +334,15 @@ class HeatmapHistoryService:request = (HeatmapCaptureRequest.objects.for_team(team_id).select_for_update()- .filter(id=request_id, state=HeatmapCaptureRequest.State.QUEUED)+ .filter(id=request_id, state__in=HeatmapCaptureRequest.LIVE_STATES).first())if heatmap is None or request is None:return None+ if request.state == HeatmapCaptureRequest.State.RUNNING and (+ claim_id is None or request.claim_id != claim_id+ ):+ return Nonecurrent = (HeatmapScreenshotHistory.objects.for_team(team_id).filter(id=request.history_id, latest_request_id=request.id)@@ -342,8 +351,10 @@ class HeatmapHistoryService:if not current or not capture_still_wanted(heatmap, request, enabled):HeatmapHistoryService.fail(request, "capture_cancelled", state=HeatmapCaptureRequest.State.CANCELLED)return None+ if request.state == HeatmapCaptureRequest.State.RUNNING:+ return requestrequest.state = HeatmapCaptureRequest.State.RUNNING- request.claim_id = uuid4()+ request.claim_id = claim_id or uuid4()request.save(update_fields=["state", "claim_id"])return request@@ -452,6 +463,26 @@ class HeatmapHistoryService:.first())+ @staticmethod+ def finish(inputs: FinishInputs) -> None:+ capture = inputs.capture+ request_id = UUID(capture.request_id)+ request = HeatmapCaptureRequest.objects.for_team(capture.team_id).filter(id=request_id).first()+ if request is None or request.state in (+ HeatmapCaptureRequest.State.FAILED,+ HeatmapCaptureRequest.State.CANCELLED,+ ):+ if delete_images_now(capture.team_id, [request_id]):+ raise ObjectStorageError("Could not delete cancelled capture images")+ return+ if request.state != HeatmapCaptureRequest.State.RUNNING or request.claim_id != UUID(capture.claim_id):+ return+ outcome = inputs.outcome+ if outcome.failure_cause is None:+ HeatmapHistoryService.publish(request, outcome.has_thumbnail)+ else:+ HeatmapHistoryService.fail(request, outcome.failure_cause, outcome.page_status)+@staticmethoddef render_and_store(request: HeatmapCaptureRequest, *, final_attempt: bool) -> RenderOutcome:try:diff --git a/products/web_analytics/backend/temporal/page_history/activities.py b/products/web_analytics/backend/temporal/page_history/activities.pynew file mode 100644index 000000000000..05c61d9c6415--- /dev/null+++ b/products/web_analytics/backend/temporal/page_history/activities.py@@ -0,0 +1,62 @@+from uuid import UUID++from temporalio import activity++from posthog.sync import database_sync_to_async_pool+from posthog.temporal.common.heartbeat import Heartbeater++from products.web_analytics.backend.heatmap_history import HeatmapHistoryService+from products.web_analytics.backend.models import HeatmapCaptureRequest+from products.web_analytics.backend.temporal.page_history.scheduling import prune_history, schedule_due_captures+from products.web_analytics.backend.temporal.page_history.types import (+ RENDER_ATTEMPTS,+ CaptureInputs,+ ClaimedCapture,+ DueCapture,+ FinishInputs,+ RenderOutcome,+)+++def _load(capture: ClaimedCapture) -> HeatmapCaptureRequest | None:+ return HeatmapHistoryService.load_claimed(+ team_id=capture.team_id, request_id=UUID(capture.request_id), claim_id=UUID(capture.claim_id)+ )++[email protected](name="heatmap-page-history-claim")+async def claim_capture(inputs: CaptureInputs) -> str | None:+ run_id = activity.info().workflow_run_id+ assert run_id is not None+ request = await database_sync_to_async_pool(HeatmapHistoryService.claim)(+ team_id=inputs.team_id, request_id=UUID(inputs.request_id), claim_id=UUID(run_id)+ )+ return None if request is None else str(request.claim_id)+++def _render(capture: ClaimedCapture, final_attempt: bool) -> RenderOutcome:+ request = _load(capture)+ if request is None:+ return RenderOutcome(failure_cause="capture_cancelled")+ return HeatmapHistoryService.render_and_store(request, final_attempt=final_attempt)++[email protected](name="heatmap-page-history-render")+async def render_capture(capture: ClaimedCapture) -> RenderOutcome:+ async with Heartbeater(details=(capture.request_id,), factor=4):+ return await database_sync_to_async_pool(_render)(capture, activity.info().attempt >= RENDER_ATTEMPTS)++[email protected](name="heatmap-page-history-finish")+async def finish_capture(inputs: FinishInputs) -> None:+ await database_sync_to_async_pool(HeatmapHistoryService.finish)(inputs)++[email protected](name="heatmap-page-history-prune")+async def prune_page_history() -> int:+ return await database_sync_to_async_pool(prune_history)()++[email protected](name="heatmap-page-history-schedule")+async def schedule_page_history() -> list[DueCapture]:+ return await database_sync_to_async_pool(schedule_due_captures)()diff --git a/products/web_analytics/backend/temporal/page_history/registry.py b/products/web_analytics/backend/temporal/page_history/registry.pynew file mode 100644index 000000000000..26804ea307d8--- /dev/null+++ b/products/web_analytics/backend/temporal/page_history/registry.py@@ -0,0 +1,14 @@+from products.web_analytics.backend.temporal.page_history.activities import (+ claim_capture,+ finish_capture,+ prune_page_history,+ render_capture,+ schedule_page_history,+)+from products.web_analytics.backend.temporal.page_history.workflows import (+ HeatmapPageHistoryCaptureWorkflow,+ HeatmapPageHistoryTickWorkflow,+)++WORKFLOWS = [HeatmapPageHistoryCaptureWorkflow, HeatmapPageHistoryTickWorkflow]+ACTIVITIES = [claim_capture, render_capture, finish_capture, prune_page_history, schedule_page_history]diff --git a/products/web_analytics/backend/temporal/page_history/schedule.py b/products/web_analytics/backend/temporal/page_history/schedule.pynew file mode 100644index 000000000000..04d5fd0f692e--- /dev/null+++ b/products/web_analytics/backend/temporal/page_history/schedule.py@@ -0,0 +1,45 @@+from datetime import timedelta++from django.conf import settings++from temporalio.client import (+ Client,+ Schedule,+ ScheduleActionStartWorkflow,+ ScheduleIntervalSpec,+ ScheduleOverlapPolicy,+ SchedulePolicy,+ ScheduleSpec,+)++from posthog.scheduling.jitter import deterministic_offset+from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule++from products.web_analytics.backend.temporal.page_history.types import (+ TICK_INTERVAL,+ TICK_SCHEDULE_ID,+ TICK_WORKFLOW_NAME,+ TickInputs,+)+++async def create_heatmap_page_history_schedule(client: Client) -> None:+ schedule = Schedule(+ action=ScheduleActionStartWorkflow(+ TICK_WORKFLOW_NAME,+ TickInputs(),+ id=TICK_SCHEDULE_ID,+ task_queue=settings.WEB_ANALYTICS_TASK_QUEUE,+ execution_timeout=timedelta(minutes=10),+ ),+ spec=ScheduleSpec(+ intervals=[+ ScheduleIntervalSpec(every=TICK_INTERVAL, offset=deterministic_offset(TICK_SCHEDULE_ID, TICK_INTERVAL))+ ]+ ),+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),+ )+ if await a_schedule_exists(client, TICK_SCHEDULE_ID):+ await a_update_schedule(client, TICK_SCHEDULE_ID, schedule)+ else:+ await a_create_schedule(client, TICK_SCHEDULE_ID, schedule, trigger_immediately=False)diff --git a/products/web_analytics/backend/temporal/page_history/scheduling.py b/products/web_analytics/backend/temporal/page_history/scheduling.pynew file mode 100644index 000000000000..34ef9b3c8e24--- /dev/null+++ b/products/web_analytics/backend/temporal/page_history/scheduling.py@@ -0,0 +1,178 @@+from datetime import datetime, timedelta+from uuid import UUID++from django.conf import settings+from django.db.models import Count, F, Max, Min, OuterRef, Q, Subquery+from django.utils import timezone++from prometheus_client import Counter, Gauge++from posthog.models import Team++from products.web_analytics.backend.heatmap_history import (+ HEATMAP_HISTORY_GLOBAL_DAILY_CAP,+ HEATMAP_HISTORY_TICK_CAP,+ HeatmapHistoryService,+ capture_day,+ history_due_at,+ history_enabled,+ scheduled_requests_today,+)+from products.web_analytics.backend.heatmap_history_storage import delete_images_now+from products.web_analytics.backend.models import HeatmapCaptureRequest, HeatmapScreenshotHistory, SavedHeatmap+from products.web_analytics.backend.temporal.page_history.types import DueCapture++HEATMAP_HISTORY_VIEWED_WITHIN = timedelta(days=30)+HEATMAP_HISTORY_METADATA_BATCH = 2000+HEATMAP_HISTORY_DISPATCH_GRACE = timedelta(minutes=2)+HISTORY_SCHEDULED = Counter("heatmap_screenshot_history_scheduled", "Scheduled history captures")+HISTORY_PENDING = Gauge("heatmap_screenshot_history_pending", "Outstanding capture requests")+HISTORY_PENDING_AGE = Gauge(+ "heatmap_screenshot_history_pending_age_seconds", "Age of oldest outstanding capture request"+)+HISTORY_CLEANUP_BACKLOG = Gauge("heatmap_screenshot_history_cleanup_backlog", "Expired history rows awaiting cleanup")+HISTORY_EXPIRED = Counter("heatmap_screenshot_history_expired", "Expired history metadata")+++def due_capture(request: HeatmapCaptureRequest, now: datetime) -> DueCapture:+ return DueCapture(+ team_id=request.team_id,+ request_id=str(request.id),+ seconds_left=(request.deadline - now).total_seconds(),+ )+++def undispatched_captures(now: datetime) -> list[DueCapture]:+ stale = (+ HeatmapCaptureRequest.objects.unscoped()+ .filter(+ state=HeatmapCaptureRequest.State.QUEUED,+ created_at__lte=now - HEATMAP_HISTORY_DISPATCH_GRACE,+ deadline__gt=now + HEATMAP_HISTORY_DISPATCH_GRACE,+ )+ .order_by("created_at", "id")[:HEATMAP_HISTORY_TICK_CAP]+ )+ return [due_capture(request, now) for request in stale]+++def schedule_due_captures() -> list[DueCapture]:+ if not settings.OBJECT_STORAGE_ENABLED:+ return []+ now = timezone.now()+ if scheduled_requests_today(now) >= HEATMAP_HISTORY_GLOBAL_DAILY_CAP:+ return undispatched_captures(now)+ eligible = SavedHeatmap.objects.filter(+ type=SavedHeatmap.Type.SCREENSHOT,+ source=SavedHeatmap.Source.SERVER,+ status=SavedHeatmap.Status.COMPLETED,+ deleted=False,+ is_prewarm=False,+ last_viewed_at__gte=now - HEATMAP_HISTORY_VIEWED_WITHIN,+ ).filter(Q(next_history_capture_at__lte=now) | Q(next_history_capture_at__isnull=True))+ last_dispatch = (+ HeatmapCaptureRequest.objects.unscoped()+ .filter(team_id=OuterRef("pk"), trigger=HeatmapScreenshotHistory.Trigger.SCHEDULED)+ .order_by()+ .values("team_id")+ .annotate(latest=Max("created_at"))+ .values("latest")+ )+ teams = (+ Team.objects.filter(id__in=eligible.values("team_id"))+ .annotate(last_dispatch=Subquery(last_dispatch))+ .order_by(F("last_dispatch").asc(nulls_first=True), "id")+ .only("id", "uuid", "organization_id", "timezone")+ )+ scheduled: list[DueCapture] = []+ candidates: dict[int, list[UUID]] = {}+ for team in teams:+ if not history_enabled(team):+ continue+ day = capture_day(now, team.timezone)+ due: list[UUID] = []+ backfill: list[SavedHeatmap] = []+ for heatmap_id, next_capture_at in (+ eligible.filter(team_id=team.id)+ .order_by("-last_viewed_at", "id")+ .values_list("id", "next_history_capture_at")+ ):+ due_at = next_capture_at or history_due_at(heatmap_id, day)+ if next_capture_at is None:+ backfill.append(SavedHeatmap(id=heatmap_id, team_id=team.id, next_history_capture_at=due_at))+ if due_at <= now:+ due.append(heatmap_id)+ if len(due) >= HEATMAP_HISTORY_TICK_CAP:+ break+ SavedHeatmap.objects.bulk_update(backfill, ["next_history_capture_at"])+ if due:+ candidates[team.id] = due+ while candidates and len(scheduled) < HEATMAP_HISTORY_TICK_CAP:+ for team_id in list(candidates):+ heatmap_id = candidates[team_id].pop(0)+ request = HeatmapHistoryService.enqueue(+ team_id=team_id,+ heatmap_id=heatmap_id,+ trigger=HeatmapScreenshotHistory.Trigger.SCHEDULED,+ dispatch=False,+ )+ if request is not None:+ scheduled.append(due_capture(request, now))+ if not candidates[team_id]:+ del candidates[team_id]+ if len(scheduled) >= HEATMAP_HISTORY_TICK_CAP:+ break+ HISTORY_SCHEDULED.inc(len(scheduled))+ return scheduled + undispatched_captures(now)+++def prune_history() -> int:+ now = timezone.now()+ stale = (+ HeatmapCaptureRequest.objects.unscoped()+ .filter(state__in=HeatmapCaptureRequest.LIVE_STATES, deadline__lte=now)+ .order_by("deadline", "id")[:HEATMAP_HISTORY_METADATA_BATCH]+ )+ for request in stale:+ HeatmapHistoryService.fail(request, "worker_timeout")+ expired = list(+ HeatmapScreenshotHistory.objects.unscoped()+ .filter(expires_at__lte=now)+ .order_by("expires_at", "id")+ .values_list("id", flat=True)[:HEATMAP_HISTORY_METADATA_BATCH]+ )+ requests = list(+ HeatmapCaptureRequest.objects.unscoped()+ .filter(Q(expires_at__lte=now) | Q(history_id__in=expired))+ .order_by("expires_at", "id")+ .values_list("team_id", "id")[:HEATMAP_HISTORY_METADATA_BATCH]+ )+ by_team: dict[int, list[UUID]] = {}+ for team_id, request_id in requests:+ by_team.setdefault(team_id, []).append(request_id)+ undeletable = {request_id for team_id, ids in by_team.items() for request_id in delete_images_now(team_id, ids)}+ deleted, _ = (+ HeatmapCaptureRequest.objects.unscoped()+ .filter(id__in=[request_id for _, request_id in requests if request_id not in undeletable])+ .delete()+ )+ remaining = HEATMAP_HISTORY_METADATA_BATCH - len(requests)+ histories = list(+ HeatmapScreenshotHistory.objects.unscoped()+ .filter(id__in=expired, requests__isnull=True)+ .values_list("id", flat=True)[:remaining]+ )+ history_deleted, _ = HeatmapScreenshotHistory.objects.unscoped().filter(id__in=histories).delete()+ deleted += history_deleted+ HISTORY_EXPIRED.inc(len(histories))+ pending = (+ HeatmapCaptureRequest.objects.unscoped()+ .filter(state__in=HeatmapCaptureRequest.LIVE_STATES)+ .aggregate(oldest=Min("created_at"), count=Count("id"))+ )+ HISTORY_PENDING.set(pending["count"])+ HISTORY_PENDING_AGE.set((now - pending["oldest"]).total_seconds() if pending["oldest"] else 0)+ HISTORY_CLEANUP_BACKLOG.set(+ HeatmapScreenshotHistory.objects.unscoped().filter(expires_at__lte=now).count()+ + HeatmapCaptureRequest.objects.unscoped().filter(expires_at__lte=now).count()+ )+ return deleteddiff --git a/products/web_analytics/backend/temporal/page_history/workflows.py b/products/web_analytics/backend/temporal/page_history/workflows.pynew file mode 100644index 000000000000..1a80537f60e1--- /dev/null+++ b/products/web_analytics/backend/temporal/page_history/workflows.py@@ -0,0 +1,101 @@+import asyncio+from datetime import timedelta++from temporalio import workflow+from temporalio.common import RetryPolicy+from temporalio.exceptions import ActivityError, WorkflowAlreadyStartedError++from posthog.temporal.common.base import PostHogWorkflow++with workflow.unsafe.imports_passed_through():+ from products.web_analytics.backend.tasks.heatmap_screenshot import HEATMAP_SCREENSHOT_TIME_LIMIT+ from products.web_analytics.backend.temporal.page_history.activities import (+ claim_capture,+ finish_capture,+ prune_page_history,+ render_capture,+ schedule_page_history,+ )+ from products.web_analytics.backend.temporal.page_history.types import (+ CAPTURE_WORKFLOW_NAME,+ RENDER_ATTEMPTS,+ RENDER_RETRY_DELAY,+ TICK_WORKFLOW_NAME,+ CaptureInputs,+ ClaimedCapture,+ FinishInputs,+ RenderOutcome,+ TickInputs,+ TickResult,+ capture_workflow_id,+ )++DATABASE_TIMEOUT = timedelta(minutes=2)+DATABASE_RETRY = RetryPolicy(initial_interval=timedelta(seconds=5), maximum_attempts=3)++[email protected](name=CAPTURE_WORKFLOW_NAME)+class HeatmapPageHistoryCaptureWorkflow(PostHogWorkflow):+ inputs_cls = CaptureInputs++ @workflow.run+ async def run(self, inputs: CaptureInputs) -> str:+ claim_id = await workflow.execute_activity(+ claim_capture, inputs, start_to_close_timeout=DATABASE_TIMEOUT, retry_policy=DATABASE_RETRY+ )+ if claim_id is None:+ return "skipped"+ capture = ClaimedCapture(team_id=inputs.team_id, request_id=inputs.request_id, claim_id=claim_id)+ try:+ outcome = await workflow.execute_activity(+ render_capture,+ capture,+ start_to_close_timeout=timedelta(seconds=HEATMAP_SCREENSHOT_TIME_LIMIT),+ heartbeat_timeout=timedelta(minutes=1),+ retry_policy=RetryPolicy(+ initial_interval=RENDER_RETRY_DELAY, backoff_coefficient=1.0, maximum_attempts=RENDER_ATTEMPTS+ ),+ )+ except ActivityError:+ outcome = RenderOutcome(failure_cause="render_timeout")+ await workflow.execute_activity(+ finish_capture,+ FinishInputs(capture=capture, outcome=outcome),+ start_to_close_timeout=DATABASE_TIMEOUT,+ retry_policy=DATABASE_RETRY,+ )+ return "succeeded" if outcome.failure_cause is None else "failed"++[email protected](name=TICK_WORKFLOW_NAME)+class HeatmapPageHistoryTickWorkflow(PostHogWorkflow):+ inputs_cls = TickInputs+ inputs_optional = True++ @workflow.run+ async def run(self, inputs: TickInputs) -> TickResult:+ pruned = await workflow.execute_activity(+ prune_page_history, start_to_close_timeout=DATABASE_TIMEOUT, retry_policy=DATABASE_RETRY+ )+ due = await workflow.execute_activity(+ schedule_page_history,+ start_to_close_timeout=DATABASE_TIMEOUT,+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ starts = [+ workflow.start_child_workflow(+ HeatmapPageHistoryCaptureWorkflow.run,+ CaptureInputs(team_id=capture.team_id, request_id=capture.request_id),+ id=capture_workflow_id(capture.request_id),+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,+ execution_timeout=timedelta(seconds=capture.seconds_left),+ )+ for capture in due+ if capture.seconds_left > 0+ ]+ results = await asyncio.gather(*starts, return_exceptions=True)+ for result in results:+ if isinstance(result, BaseException) and not isinstance(result, WorkflowAlreadyStartedError):+ raise result+ already_running = sum(isinstance(result, WorkflowAlreadyStartedError) for result in results)+ return TickResult(pruned=pruned, started=len(results) - already_running, already_running=already_running)diff --git a/products/web_analytics/backend/test/test_heatmap_page_history_workflows.py b/products/web_analytics/backend/test/test_heatmap_page_history_workflows.pynew file mode 100644index 000000000000..b8a261e656cd--- /dev/null+++ b/products/web_analytics/backend/test/test_heatmap_page_history_workflows.py@@ -0,0 +1,132 @@+import uuid++import pytest++import temporalio.worker+from temporalio import activity+from temporalio.client import Client+from temporalio.exceptions import ApplicationError+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import Worker++from products.web_analytics.backend.temporal.page_history.types import (+ CaptureInputs,+ ClaimedCapture,+ DueCapture,+ FinishInputs,+ RenderOutcome,+ TickInputs,+ TickResult,+ capture_workflow_id,+)+from products.web_analytics.backend.temporal.page_history.workflows import (+ HeatmapPageHistoryCaptureWorkflow,+ HeatmapPageHistoryTickWorkflow,+)+++class FakeActivities:+ def __init__(self, claim_id: str | None, render: RenderOutcome | Exception, due: list[DueCapture]) -> None:+ self.claim_id = claim_id+ self.render = render+ self.due = due+ self.finished: list[FinishInputs] = []++ def activities(self) -> list:+ @activity.defn(name="heatmap-page-history-claim")+ async def claim(inputs: CaptureInputs) -> str | None:+ return self.claim_id++ @activity.defn(name="heatmap-page-history-render")+ async def render(capture: ClaimedCapture) -> RenderOutcome:+ if isinstance(self.render, Exception):+ raise self.render+ return self.render++ @activity.defn(name="heatmap-page-history-finish")+ async def finish(inputs: FinishInputs) -> None:+ self.finished.append(inputs)++ @activity.defn(name="heatmap-page-history-prune")+ async def prune() -> int:+ return 3++ @activity.defn(name="heatmap-page-history-schedule")+ async def schedule() -> list[DueCapture]:+ return self.due++ return [claim, render, finish, prune, schedule]+++async def run_capture(client: Client, task_queue: str, request_id: str) -> str:+ return await client.execute_workflow(+ HeatmapPageHistoryCaptureWorkflow.run,+ CaptureInputs(team_id=1, request_id=request_id),+ id=capture_workflow_id(request_id),+ task_queue=task_queue,+ )+++PAGE_NOT_FOUND = RenderOutcome(failure_cause="page_http_status", page_status=404)+++ "claim_id,render,result,finished",+ [+ (None, RenderOutcome(), "skipped", None),+ ("claim", RenderOutcome(has_thumbnail=True), "succeeded", RenderOutcome(has_thumbnail=True)),+ ("claim", PAGE_NOT_FOUND, "failed", PAGE_NOT_FOUND),+ (+ "claim",+ ApplicationError("hung", non_retryable=True),+ "failed",+ RenderOutcome(failure_cause="render_timeout"),+ ),+ ],+)+async def test_capture_workflow_publishes_or_records_the_failure(+ claim_id: str | None, render: RenderOutcome | Exception, result: str, finished: RenderOutcome | None+) -> None:+ fakes = FakeActivities(claim_id, render, [])+ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[HeatmapPageHistoryCaptureWorkflow],+ activities=fakes.activities(),+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ assert await run_capture(env.client, task_queue, str(uuid.uuid4())) == result+ assert [inputs.outcome for inputs in fakes.finished] == ([finished] if finished else [])+++async def test_tick_starts_each_due_capture_once() -> None:+ running = str(uuid.uuid4())+ due = [+ DueCapture(team_id=1, request_id=str(uuid.uuid4()), seconds_left=600),+ DueCapture(team_id=1, request_id=running, seconds_left=600),+ DueCapture(team_id=1, request_id=str(uuid.uuid4()), seconds_left=0),+ ]+ fakes = FakeActivities("claim", RenderOutcome(), due)+ task_queue = str(uuid.uuid4())+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[HeatmapPageHistoryCaptureWorkflow, HeatmapPageHistoryTickWorkflow],+ activities=fakes.activities(),+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),+ ):+ await env.client.start_workflow(+ HeatmapPageHistoryCaptureWorkflow.run,+ CaptureInputs(team_id=1, request_id=running),+ id=capture_workflow_id(running),+ task_queue=str(uuid.uuid4()),+ )+ result = await env.client.execute_workflow(+ HeatmapPageHistoryTickWorkflow.run, TickInputs(), id=str(uuid.uuid4()), task_queue=task_queue+ )+ assert result == TickResult(pruned=3, started=1, already_running=1)diff --git a/products/web_analytics/backend/test/test_heatmap_screenshot_history.py b/products/web_analytics/backend/test/test_heatmap_screenshot_history.pyindex c75da3a41048..ba6b2756ad11 100644--- a/products/web_analytics/backend/test/test_heatmap_screenshot_history.py+++ b/products/web_analytics/backend/test/test_heatmap_screenshot_history.py@@ -29,8 +29,11 @@ from products.web_analytics.backend.heatmap_history import (from products.web_analytics.backend.heatmap_history_storage import image_keyfrom products.web_analytics.backend.models import HeatmapCaptureRequest, HeatmapScreenshotHistory, SavedHeatmapfrom products.web_analytics.backend.tasks.heatmap_screenshot import BrowserlessPermanentError+from products.web_analytics.backend.temporal.page_history.scheduling import prune_history, schedule_due_captures+from products.web_analytics.backend.temporal.page_history.types import ClaimedCapture, FinishInputs, RenderOutcomeTASK_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"STORAGE_MODULE = "products.web_analytics.backend.heatmap_history_storage"@@ -85,6 +88,7 @@ class TestHeatmapHistory(APIBaseTest):for 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),]:patcher = patch(name, replacement)patcher.start()@@ -104,6 +108,18 @@ class TestHeatmapHistory(APIBaseTest):def images(self, request: HeatmapCaptureRequest) -> set[str]:return {key for key in self.blobs if f"/{request.id}/" in key}+ def finish_capture(self, request: HeatmapCaptureRequest, outcome: RenderOutcome) -> None:+ assert request.claim_id is not None+ with self.captureOnCommitCallbacks(execute=True):+ HeatmapHistoryService.finish(+ FinishInputs(+ capture=ClaimedCapture(+ team_id=request.team_id, request_id=str(request.id), claim_id=str(request.claim_id)+ ),+ outcome=outcome,+ )+ )+def execute_capture(self, request: HeatmapCaptureRequest, error: Exception | None = None) -> None:with (patch.object(HeatmapHistoryService, "render", return_value=jpeg(request.width), side_effect=error),@@ -112,10 +128,7 @@ class TestHeatmapHistory(APIBaseTest):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)+ self.finish_capture(claimed, outcome)request.refresh_from_db()def history(self) -> HeatmapScreenshotHistory:@@ -130,6 +143,10 @@ class TestHeatmapHistory(APIBaseTest):request = self.enqueue()self.execute_capture(request)assert request.state == "succeeded"+ self.finish_capture(request, RenderOutcome(has_thumbnail=True))+ 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"}self.storage.write.reset_mock()self.execute_capture(request)self.storage.write.assert_not_called()@@ -139,6 +156,26 @@ class TestHeatmapHistory(APIBaseTest):assert self.history().has_thumbnailassert {key.rsplit("/", 1)[1] for key in self.images(request)} == {"full.jpg", "thumbnail.jpg"}+ @parameterized.expand(+ [+ ("same_run", UUID(int=1), True),+ ("other_run", UUID(int=2), False),+ ("unowned", None, False),+ ]+ )+ def test_claim_retry_preserves_ownership(self, _name: str, retry_claim_id: UUID | None, recovered: bool) -> None:+ request = self.enqueue()+ claim_id = UUID(int=1)+ claimed = HeatmapHistoryService.claim(team_id=self.team.id, request_id=request.id, claim_id=claim_id)+ assert claimed is not None+ retried = HeatmapHistoryService.claim(team_id=self.team.id, request_id=request.id, claim_id=retry_claim_id)+ assert (retried is not None) == recovered+ if retried is not None:+ assert retried.claim_id == claim_id+ request.refresh_from_db()+ assert request.state == HeatmapCaptureRequest.State.RUNNING+ assert request.claim_id == claim_id+def replace_with_manual_capture(self) -> None:self.execute_capture(self.enqueue())@@ -211,28 +248,60 @@ class TestHeatmapHistory(APIBaseTest):@parameterized.expand([- ("url", "https://example.com/new"),- ("data_url", "https://example.com/data"),- ("deleted", True),- ("hard_delete", None),+ ("url", "https://example.com/new", False),+ ("data_url", "https://example.com/data", False),+ ("deleted", True, False),+ ("hard_delete", None, False),+ ("url", "https://example.com/new", True),])- def test_configuration_reset_cancels_render_and_deletes_images(self, field: str, value: str | bool | None) -> None:+ def test_configuration_reset_cancels_render_and_deletes_images(+ self, field: str, value: str | bool | None, retry_cleanup: bool+ ) -> None:request = self.enqueue()claimed = HeatmapHistoryService.claim(team_id=self.team.id, request_id=request.id)assert claimed is not Noneself.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])++ def reset_during_render(render_request: HeatmapCaptureRequest) -> bytes:+ 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)+ return jpeg(render_request.width)++ with patch.object(HeatmapHistoryService, "render", side_effect=reset_during_render):+ outcome = HeatmapHistoryService.render_and_store(claimed, final_attempt=True)+ assert self.images(request)+ if retry_cleanup:+ self.storage.delete_objects.side_effect = lambda keys: list(keys)+ with self.assertRaises(ObjectStorageError):+ self.finish_capture(claimed, outcome)+ assert self.images(request)+ self.storage.delete_objects.side_effect = self.delete_blobs+ self.finish_capture(claimed, outcome)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_worker_loss_is_reaped_and_late_completion_is_fenced(self) -> None:+ request = self.enqueue()+ claimed = HeatmapHistoryService.claim(team_id=self.team.id, request_id=request.id)+ HeatmapCaptureRequest.objects.for_team(self.team.id).filter(id=request.id).update(+ deadline=timezone.now() - timedelta(seconds=1)+ )+ prune_history()+ request.refresh_from_db()+ assert request.state == "failed"+ assert request.failure_cause == "worker_timeout"+ assert claimed is not None+ self.blobs[image_key(self.team.id, request.id, "full")] = jpeg()+ self.finish_capture(claimed, RenderOutcome())+ assert not self.images(request)+ assert not self.history().has_content+def test_thumbnail_failure_uses_no_full_image_fallback(self) -> None:request = self.enqueue()with patch.object(HeatmapHistoryService, "thumbnail", return_value=None):@@ -241,6 +310,18 @@ class TestHeatmapHistory(APIBaseTest):assert history.has_contentassert not history.has_thumbnail+ def test_scheduler_enqueues_once_per_day(self) -> None:+ with patch.object(HeatmapHistoryService, "dispatch") as dispatch, self.captureOnCommitCallbacks(execute=True):+ assert len(schedule_due_captures()) == 1+ assert schedule_due_captures() == []+ dispatch.assert_not_called()+ assert HeatmapCaptureRequest.objects.for_team(self.team.id).count() == 1+ self.heatmap.next_history_capture_at = timezone.now()+ self.heatmap.save(update_fields=["next_history_capture_at"])+ assert (+ HeatmapHistoryService.enqueue(team_id=self.team.id, heatmap_id=self.heatmap.id, trigger="scheduled") is None+ )+@parameterized.expand([("HEATMAP_HISTORY_TEAM_DAILY_CAP", True),@@ -261,6 +342,42 @@ class TestHeatmapHistory(APIBaseTest):assert second.next_history_capture_at is not Noneassert (second.next_history_capture_at > timezone.now()) == waits_for_tomorrow+ def test_scheduler_redispatches_requests_whose_workflow_never_started(self) -> None:+ noon = timezone.now().replace(hour=12, minute=0, second=0, microsecond=0)+ with patch(f"{TASK_MODULE}.timezone.now", return_value=noon):+ orphan = self.enqueue("scheduled")+ assert schedule_due_captures() == []+ HeatmapCaptureRequest.objects.for_team(self.team.id).filter(id=orphan.id).update(+ created_at=noon - timedelta(minutes=3)+ )+ assert [capture.request_id for capture in schedule_due_captures()] == [str(orphan.id)]++ def test_scheduler_gives_each_team_a_turn_and_prefers_recent_views(self) -> None:+ other = Team.objects.create(organization=self.organization)+ now = timezone.now()+ SavedHeatmap.objects.filter(id=self.heatmap.id).update(last_viewed_at=now - timedelta(hours=1))+ recent = SavedHeatmap.objects.create(+ team=self.team,+ url="https://example.com/recent",+ status="completed",+ last_viewed_at=now,+ next_history_capture_at=now,+ )+ SavedHeatmap.objects.create(+ team=other,+ url="https://example.com/other",+ status="completed",+ last_viewed_at=now,+ next_history_capture_at=now,+ )+ with (+ patch(f"{TASK_MODULE}.HEATMAP_HISTORY_TICK_CAP", 2),+ patch(f"{SCHEDULING_MODULE}.HEATMAP_HISTORY_TICK_CAP", 2),+ ):+ assert len(schedule_due_captures()) == 2+ assert HeatmapCaptureRequest.objects.for_team(self.team.id).get().heatmap_id == recent.id+ assert HeatmapCaptureRequest.objects.for_team(other.id).count() == 1+@parameterized.expand([("valid", jpeg(1024), True),@@ -291,6 +408,23 @@ class TestHeatmapHistory(APIBaseTest):assert request.captured_on.isoformat() == "2024-03-10"assert request.deadline == datetime(2024, 3, 11, 4, tzinfo=UTC)+ def test_cleanup_deletes_images_before_rows_and_bounds_batches(self) -> None:+ request = self.enqueue()+ self.execute_capture(request)+ HeatmapScreenshotHistory.objects.for_team(self.team.id).filter(id=request.history_id).update(+ expires_at=timezone.now() - timedelta(seconds=1)+ )+ self.storage.delete_objects.side_effect = lambda keys, **kwargs: list(keys)+ assert prune_history() == 0+ assert self.images(request)+ self.storage.delete_objects.side_effect = self.delete_blobs+ with patch(f"{SCHEDULING_MODULE}.HEATMAP_HISTORY_METADATA_BATCH", 1):+ assert prune_history() == 1+ assert self.history().latest_request is None+ assert prune_history() == 1+ assert not HeatmapScreenshotHistory.objects.for_team(self.team.id).exists()+ assert not self.images(request)+def test_pending_manual_capture_does_not_skip_automatic_capture_after_failure(self) -> None:manual = self.enqueue()assert (