: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
chore(workflows): route batch jobs through the facade (#110124)
Harley Alexanderf56e386163bd
diff --git a/products/workflows/backend/facade/batch_jobs.py b/products/workflows/backend/facade/batch_jobs.pynew file mode 100644index 000000000000..b1a23c273ada--- /dev/null+++ b/products/workflows/backend/facade/batch_jobs.py@@ -0,0 +1,17 @@+"""Workflow batch runs: create, list, status writes, and the broadcast status derived from them."""++from products.workflows.backend.services.batch_jobs import (+ create_batch_job,+ get_batch_job,+ hog_flow_ids_with_broadcast_status,+ list_batch_jobs,+ set_batch_job_status,+)++__all__ = [+ "create_batch_job",+ "get_batch_job",+ "hog_flow_ids_with_broadcast_status",+ "list_batch_jobs",+ "set_batch_job_status",+]diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.pyindex 89763e4564ef..5a7f6455d777 100644--- a/products/workflows/backend/facade/contracts.py+++ b/products/workflows/backend/facade/contracts.py@@ -66,6 +66,10 @@ class WorkflowBatchJob:created_by: "User | None"+class WorkflowBatchJobNotFound(Exception):+ pass++@dataclass(frozen=True)class HogFlowReference:id: strdiff --git a/products/workflows/backend/facade/enums.py b/products/workflows/backend/facade/enums.pyindex 667fa859fe39..af215e1a8520 100644--- a/products/workflows/backend/facade/enums.py+++ b/products/workflows/backend/facade/enums.py@@ -41,3 +41,9 @@ class HogFlowBatchJobState(LabeledStrEnum):COMPLETED = "completed"CANCELLED = "cancelled"FAILED = "failed"+++class HogFlowScheduleStatus(LabeledStrEnum):+ ACTIVE = "active"+ PAUSED = "paused"+ COMPLETED = "completed" # RRULE exhausted (COUNT/UNTIL reached)diff --git a/products/workflows/backend/models/hog_flow_schedule/hog_flow_schedule.py b/products/workflows/backend/models/hog_flow_schedule/hog_flow_schedule.pyindex f9986ab7bc47..1d6ed33146a2 100644--- a/products/workflows/backend/models/hog_flow_schedule/hog_flow_schedule.py+++ b/products/workflows/backend/models/hog_flow_schedule/hog_flow_schedule.py@@ -2,6 +2,8 @@ from django.db import modelsfrom posthog.models.utils import RootTeamMixin, UUIDTModel+from products.workflows.backend.facade.enums import HogFlowScheduleStatus+# Trigger types that use HogFlowSchedule for recurring executionSCHEDULED_TRIGGER_TYPES = ("batch", "schedule")@@ -13,10 +15,7 @@ class HogFlowSchedule(RootTeamMixin, UUIDTModel):RRULE, timezone, and variable overrides."""- class Status(models.TextChoices):- ACTIVE = "active"- PAUSED = "paused"- COMPLETED = "completed" # RRULE exhausted (COUNT/UNTIL reached)+ Status = HogFlowScheduleStatusteam = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, related_name="+")hog_flow = models.ForeignKey("workflows.HogFlow", on_delete=models.CASCADE, related_name="schedules")@@ -24,7 +23,7 @@ class HogFlowSchedule(RootTeamMixin, UUIDTModel):starts_at = models.DateTimeField()timezone = models.CharField(max_length=64, default="UTC")variables = models.JSONField(default=dict) # {key: value} overrides, merged with HogFlow defaults at execution- status = models.CharField(max_length=20, choices=Status, default=Status.ACTIVE)+ status = models.CharField(max_length=20, choices=Status.choices, default=Status.ACTIVE.value)next_run_at = models.DateTimeField(null=True, blank=True, db_index=True)created_at = models.DateTimeField(auto_now_add=True)diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.pyindex 8dd1c3d2c433..7e36408baef7 100644--- a/products/workflows/backend/presentation/views/hog_flow.py+++ b/products/workflows/backend/presentation/views/hog_flow.py@@ -13,7 +13,6 @@ from zoneinfo import ZoneInfo, ZoneInfoNotFoundErrorfrom django.conf import settingsfrom django.core.cache import cache-from django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.core.signing import BadSignature, SignatureExpired, TimestampSignerfrom django.db import IntegrityError, models, transactionfrom django.db.models import Count, Exists, OuterRef, Q, QuerySet, Subquery@@ -122,7 +121,13 @@ from products.tasks.backend.facade.workflow_tasks import (resolve_connectors,validate_skill_names,)-from products.workflows.backend.facade.api import create_batch_job+from products.workflows.backend.facade.batch_jobs import (+ create_batch_job,+ get_batch_job,+ hog_flow_ids_with_broadcast_status,+ list_batch_jobs,+ set_batch_job_status,+)from products.workflows.backend.facade.blast_radius import (SUPPORTED_DEDUPE_KEYS,get_account_audience_ids_page,@@ -133,7 +138,7 @@ from products.workflows.backend.facade.blast_radius import (is_account_audience,parse_account_audience_filters,)-from products.workflows.backend.facade.contracts import StaffPausedError+from products.workflows.backend.facade.contracts import StaffPausedError, WorkflowBatchJobNotFoundfrom products.workflows.backend.facade.email_health import (fetch_aws_tenant_reputation,fetch_email_totals_by_source,@@ -144,6 +149,7 @@ from products.workflows.backend.facade.email_health import (resume_email_sending,team_email_sending_allowance,)+from products.workflows.backend.facade.enums import HogFlowBatchJobStatefrom products.workflows.backend.facade.secrets import (TemplateCache,mask_derived_trigger,@@ -924,6 +930,14 @@ class InternalBlastRadiusPersonsSerializer(serializers.Serializer):has_more = serializers.BooleanField(help_text="Whether another page may follow.")+class InternalBatchJobStatusSerializer(serializers.Serializer):+ """Response contract for the internal batch job status write, read by the Node batch resolver."""++ id = serializers.CharField(help_text="Batch job id.")+ status = serializers.CharField(help_text="Status of the batch job after the call.")+ no_op = serializers.BooleanField(help_text="True when the job was already terminal and nothing changed.")++class InternalAccountAudienceSerializer(serializers.Serializer):"""Response contract for the internal account audience endpoint, read by the Node batch resolver."""@@ -4377,52 +4391,6 @@ def annotate_broadcast_shape(queryset: QuerySet) -> QuerySet:BROADCAST_STATUSES = ("draft", "scheduled", "sending", "sent", "failed", "archived")-def filter_by_broadcast_status(queryset: QuerySet, statuses: set[str]) -> QuerySet:- # The status a sender sees on a broadcast, derived the way the broadcasts UI derives it: from the- # latest run and whether a schedule still has sends to come.- latest_run_status = (- HogFlowBatchJob.objects.filter(team_id=OuterRef("team_id"), hog_flow_id=OuterRef("pk"))- .order_by("-created_at")- .values("status")[:1]- )- queryset = queryset.annotate(- _latest_run_status=Subquery(latest_run_status),- _has_pending_schedule=Exists(- HogFlowSchedule.objects.filter(- team_id=OuterRef("team_id"), hog_flow_id=OuterRef("pk"), status=HogFlowSchedule.Status.ACTIVE- )- ),- )- live = Q(status=HogFlow.State.ACTIVE)- # Only a wizard launch always leaves a schedule or a run. An opened workflow can wait for an API send.- nothing_to_come = Q(_latest_run_status__isnull=True, _has_pending_schedule=False)- unfinished_launch = nothing_to_come & Q(origin_product="broadcasts")- running = [HogFlowBatchJob.State.WAITING, HogFlowBatchJob.State.QUEUED, HogFlowBatchJob.State.ACTIVE]- conditions = {- "draft": Q(status=HogFlow.State.DRAFT),- "archived": Q(status=HogFlow.State.ARCHIVED),- "sending": live & Q(_latest_run_status__in=running),- "sent": live & Q(_latest_run_status=HogFlowBatchJob.State.COMPLETED, _has_pending_schedule=False),- "scheduled": live- & (- (- Q(_has_pending_schedule=True)- & (Q(_latest_run_status__isnull=True) | Q(_latest_run_status=HogFlowBatchJob.State.COMPLETED))- )- | (nothing_to_come & ~Q(origin_product="broadcasts"))- ),- "failed": live- & (- Q(_latest_run_status__in=[HogFlowBatchJob.State.FAILED, HogFlowBatchJob.State.CANCELLED])- | unfinished_launch- ),- }- combined = Q()- for broadcast_status in statuses:- combined |= conditions[broadcast_status]- return queryset.filter(combined)--class HogFlowFilterSet(FilterSet):# A producer's work list, so an agent need not read every workflow to find the few it may look at.optimization_enabled = BooleanFilter(@@ -4851,7 +4819,9 @@ class HogFlowViewSet(raise exceptions.ValidationError({"broadcast_status": f"Must be one or more of: {', '.join(BROADCAST_STATUSES)}"})- queryset = filter_by_broadcast_status(queryset, requested_statuses)+ queryset = queryset.filter(+ id__in=hog_flow_ids_with_broadcast_status(team_id=self.team_id, statuses=requested_statuses)+ )# `?type=loop` and `?type=broadcast` return the same rows, but Desktop's Loops list sends# this param and ships on its own release cadence, so installed builds keep sending it.@@ -7046,7 +7016,7 @@ class HogFlowViewSet(self._report_workflow_action("hog_flow_batch_job_created", hog_flow, {"batch_job_id": str(batch_job.id)})return Response(HogFlowBatchJobSerializer(batch_job).data)else:- batch_jobs = HogFlowBatchJob.objects.filter(hog_flow=hog_flow, team=self.team).order_by("-created_at")+ batch_jobs = list_batch_jobs(team_id=self.team_id, hog_flow_id=hog_flow.id)serializer = HogFlowBatchJobSerializer(batch_jobs, many=True)return Response(serializer.data)@@ -7075,16 +7045,18 @@ class HogFlowViewSet(hog_flow = self.get_object()try:- batch_job = HogFlowBatchJob.objects.get(id=kwargs["batch_job_id"], hog_flow=hog_flow, team_id=self.team_id)- except (HogFlowBatchJob.DoesNotExist, DjangoValidationError, ValueError):- # DjangoValidationError fires when the id is not a parseable UUID — surface- # as 404 rather than a 500 reported to error tracking.+ batch_job = get_batch_job(+ team_id=self.team_id, hog_flow_id=hog_flow.id, batch_job_id=kwargs["batch_job_id"]+ )+ except WorkflowBatchJobNotFound:+ # An id that is not a parseable UUID lands here too, as a 404 rather than a 500+ # reported to error tracking.raise exceptions.NotFound("Batch job not found")non_terminal = {- HogFlowBatchJob.State.WAITING,- HogFlowBatchJob.State.QUEUED,- HogFlowBatchJob.State.ACTIVE,+ HogFlowBatchJobState.WAITING,+ HogFlowBatchJobState.QUEUED,+ HogFlowBatchJobState.ACTIVE,}if batch_job.status not in non_terminal:return Response({"status": batch_job.status, "marked": 0, "remaining": 0, "done": True})@@ -7110,13 +7082,15 @@ class HogFlowViewSet(if data["done"]:# Conditional so a completion that landed mid-cancel wins over the flip; the- # resolver's own terminal write absorbs the reverse race. `.update()` bypasses- # auto_now, so stamp updated_at explicitly.- HogFlowBatchJob.objects.filter(id=batch_job.id, status__in=non_terminal).update(- status=HogFlowBatchJob.State.CANCELLED, updated_at=timezone.now()+ # resolver's own terminal write absorbs the reverse race.+ set_batch_job_status(+ team_id=self.team_id,+ batch_job_id=batch_job.id,+ status=HogFlowBatchJobState.CANCELLED,+ from_statuses=non_terminal,)- batch_job.refresh_from_db()+ batch_job = get_batch_job(team_id=self.team_id, hog_flow_id=hog_flow.id, batch_job_id=str(batch_job.id))self._report_workflow_action("hog_flow_batch_job_cancel_requested",hog_flow,@@ -7434,7 +7408,6 @@ class InternalHogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMi"""from django.db import transaction # noqa: PLC0415- from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob # noqa: PLC0415from products.workflows.backend.models.hog_flow_schedule import HogFlowSchedule # noqa: PLC0415from products.workflows.backend.utils.rrule_utils import compute_next_occurrences # noqa: PLC0415@@ -7600,8 +7573,6 @@ class InternalHogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMiAccepts: { status: "completed" | "failed" }"""- from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob # noqa: PLC0415-if request.method != "PUT":return Response({"error": "Method not allowed"}, status=405)@@ -7611,45 +7582,45 @@ class InternalHogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMireturn Response({"error": "Team not found"}, status=404)new_status = request.data.get("status")- if new_status not in (HogFlowBatchJob.State.COMPLETED, HogFlowBatchJob.State.FAILED):+ if new_status not in (HogFlowBatchJobState.COMPLETED, HogFlowBatchJobState.FAILED):return Response({"error": "status must be one of: completed, failed"},status=400,)try:- batch_job = HogFlowBatchJob.objects.get(id=batch_job_id, team=team)- except (HogFlowBatchJob.DoesNotExist, DjangoValidationError, ValueError):- # `DjangoValidationError` fires when `batch_job_id` is not a parseable- # UUID (UUIDField rejects it before the lookup). `ValueError` is a- # belt-and-suspenders catch for str→int / str→UUID edge cases on- # other backends. Either way, surface as 404, not 500.+ batch_job = get_batch_job(team_id=team.id, batch_job_id=batch_job_id)+ except WorkflowBatchJobNotFound:+ # An unparseable `batch_job_id` lands here too: surface as 404, not 500.return Response({"error": "Batch job not found"}, status=404)terminal_states = {- HogFlowBatchJob.State.COMPLETED,- HogFlowBatchJob.State.FAILED,- HogFlowBatchJob.State.CANCELLED,+ HogFlowBatchJobState.COMPLETED,+ HogFlowBatchJobState.FAILED,+ HogFlowBatchJobState.CANCELLED,}if batch_job.status in terminal_states:# Idempotent no-op: already in a terminal state.return Response(- {- "id": str(batch_job.id),- "status": batch_job.status,- "no_op": True,- }+ InternalBatchJobStatusSerializer(+ {+ "id": str(batch_job.id),+ "status": batch_job.status,+ "no_op": True,+ }+ ).data)try:- batch_job.status = new_status- batch_job.save(update_fields=["status", "updated_at"])+ set_batch_job_status(team_id=team.id, batch_job_id=batch_job.id, status=HogFlowBatchJobState(new_status))return Response(- {- "id": str(batch_job.id),- "status": batch_job.status,- "no_op": False,- }+ InternalBatchJobStatusSerializer(+ {+ "id": str(batch_job.id),+ "status": new_status,+ "no_op": False,+ }+ ).data)except Exception as e:logger.exception(diff --git a/products/workflows/backend/services/batch_jobs.py b/products/workflows/backend/services/batch_jobs.pyindex a71e68638aec..401cb8c23b5d 100644--- a/products/workflows/backend/services/batch_jobs.py+++ b/products/workflows/backend/services/batch_jobs.py@@ -1,9 +1,16 @@+from collections.abc import Collectionfrom typing import Anyfrom uuid import UUID-from products.workflows.backend.facade.contracts import WorkflowBatchJob-from products.workflows.backend.facade.enums import HogFlowBatchJobState+from django.core.exceptions import ValidationError as DjangoValidationError+from django.db.models import Exists, OuterRef, Q, Subquery+from django.utils import timezone++from products.workflows.backend.facade.contracts import WorkflowBatchJob, WorkflowBatchJobNotFound+from products.workflows.backend.facade.enums import HogFlowBatchJobState, HogFlowScheduleStatus+from products.workflows.backend.models.hog_flow.hog_flow import HogFlowfrom products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob+from products.workflows.backend.models.hog_flow_schedule import HogFlowScheduledef to_batch_job(job: HogFlowBatchJob) -> WorkflowBatchJob:@@ -38,3 +45,77 @@ def create_batch_job(**({} if status is None else {"status": status}),)return to_batch_job(job)+++def list_batch_jobs(*, team_id: int, hog_flow_id: UUID) -> list[WorkflowBatchJob]:+ jobs = HogFlowBatchJob.objects.filter(hog_flow_id=hog_flow_id, team_id=team_id).order_by("-created_at")+ return [to_batch_job(job) for job in jobs]+++def get_batch_job(*, team_id: int, batch_job_id: str, hog_flow_id: UUID | None = None) -> WorkflowBatchJob:+ lookup: dict[str, Any] = {"id": batch_job_id, "team_id": team_id}+ if hog_flow_id is not None:+ lookup["hog_flow_id"] = hog_flow_id+ try:+ return to_batch_job(HogFlowBatchJob.objects.get(**lookup))+ except (HogFlowBatchJob.DoesNotExist, DjangoValidationError, ValueError):+ # DjangoValidationError fires when the id is not a parseable UUID.+ raise WorkflowBatchJobNotFound()+++def set_batch_job_status(+ *,+ team_id: int,+ batch_job_id: UUID,+ status: HogFlowBatchJobState,+ from_statuses: Collection[HogFlowBatchJobState] | None = None,+) -> None:+ """Write the status. With from_statuses, only a job still in one of them changes."""+ jobs = HogFlowBatchJob.objects.filter(id=batch_job_id, team_id=team_id)+ if from_statuses is not None:+ jobs = jobs.filter(status__in=from_statuses)+ # `.update()` bypasses auto_now, so stamp updated_at explicitly.+ jobs.update(status=status, updated_at=timezone.now())+++def hog_flow_ids_with_broadcast_status(*, team_id: int, statuses: Collection[str]) -> list[UUID]:+ # The status a sender sees on a broadcast, derived the way the broadcasts UI derives it: from the+ # latest run and whether a schedule still has sends to come.+ latest_run_status = (+ HogFlowBatchJob.objects.filter(team_id=OuterRef("team_id"), hog_flow_id=OuterRef("pk"))+ .order_by("-created_at")+ .values("status")[:1]+ )+ queryset = HogFlow.objects.filter(team_id=team_id).annotate(+ _latest_run_status=Subquery(latest_run_status),+ _has_pending_schedule=Exists(+ HogFlowSchedule.objects.filter(+ team_id=OuterRef("team_id"), hog_flow_id=OuterRef("pk"), status=HogFlowScheduleStatus.ACTIVE+ )+ ),+ )+ live = Q(status=HogFlow.State.ACTIVE)+ # Only a wizard launch always leaves a schedule or a run. An opened workflow can wait for an API send.+ nothing_to_come = Q(_latest_run_status__isnull=True, _has_pending_schedule=False)+ unfinished_launch = nothing_to_come & Q(origin_product="broadcasts")+ running = [HogFlowBatchJobState.WAITING, HogFlowBatchJobState.QUEUED, HogFlowBatchJobState.ACTIVE]+ conditions = {+ "draft": Q(status=HogFlow.State.DRAFT),+ "archived": Q(status=HogFlow.State.ARCHIVED),+ "sending": live & Q(_latest_run_status__in=running),+ "sent": live & Q(_latest_run_status=HogFlowBatchJobState.COMPLETED, _has_pending_schedule=False),+ "scheduled": live+ & (+ (+ Q(_has_pending_schedule=True)+ & (Q(_latest_run_status__isnull=True) | Q(_latest_run_status=HogFlowBatchJobState.COMPLETED))+ )+ | (nothing_to_come & ~Q(origin_product="broadcasts"))+ ),+ "failed": live+ & (Q(_latest_run_status__in=[HogFlowBatchJobState.FAILED, HogFlowBatchJobState.CANCELLED]) | unfinished_launch),+ }+ combined = Q()+ for broadcast_status in statuses:+ combined |= conditions[broadcast_status]+ return list(queryset.filter(combined).values_list("id", flat=True))