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.

chore(workflows): route schedules through the facade (#109400)

Harley Alexander525af6aee917
diff --git a/posthog/test/repo_invariants/test_serializer_timestamp_guard.py b/posthog/test/repo_invariants/test_serializer_timestamp_guard.py
index a9f62f27229d..79d962165ca5 100644
--- a/posthog/test/repo_invariants/test_serializer_timestamp_guard.py
+++ b/posthog/test/repo_invariants/test_serializer_timestamp_guard.py
@@ -146,7 +146,6 @@ REVIEWED_WRITABLE: dict[str, str] = {
"products.surveys.backend.api.survey.SurveySerializerCreateUpdateOnlySchema.end_date": "Client stops the survey by setting this",
"products.surveys.backend.api.survey.SurveySerializerCreateUpdateOnlySchema.response_sampling_start_date": "Client sets when response sampling starts",
"products.surveys.backend.api.survey.SurveySerializerCreateUpdateOnlySchema.start_date": "Client launches the survey by setting this",
- "products.workflows.backend.presentation.views.hog_flow.HogFlowScheduleSerializer.starts_at": "Client sets when the schedule starts",
}
# Views and serializers the guard cannot read, each with a reason. An entry hides part
diff --git a/products/workflows/backend/facade/contracts.py b/products/workflows/backend/facade/contracts.py
index 5a7f6455d777..19ac37ccd353 100644
--- a/products/workflows/backend/facade/contracts.py
+++ b/products/workflows/backend/facade/contracts.py
@@ -8,6 +8,7 @@ from posthog.dataclasses import frozen
from products.workflows.backend.facade.enums import (
HogFlowBatchJobState,
+ HogFlowScheduleStatus,
HogFlowTemplateExitCondition,
HogFlowTemplateScope,
)
@@ -70,6 +71,35 @@ class WorkflowBatchJobNotFound(Exception):
pass
+@frozen
+class WorkflowSchedule:
+ """One recurring schedule of a workflow."""
+
+ id: UUID
+ hog_flow_id: UUID
+ rrule: str
+ starts_at: datetime
+ timezone: str
+ variables: dict[str, Any]
+ status: HogFlowScheduleStatus
+ next_run_at: datetime | None
+ created_at: datetime
+ updated_at: datetime
+
+
+class WorkflowScheduleNotFound(Exception):
+ pass
+
+
+@frozen
+class ProcessedSchedules:
+ """The schedule ids one scheduler pass fired, initialized, or failed on."""
+
+ processed: list[str]
+ initialized: list[str]
+ failed: list[str]
+
+
@dataclass(frozen=True)
class HogFlowReference:
id: str
diff --git a/products/workflows/backend/facade/schedules.py b/products/workflows/backend/facade/schedules.py
new file mode 100644
index 000000000000..5a3af4d01479
--- /dev/null
+++ b/products/workflows/backend/facade/schedules.py
@@ -0,0 +1,22 @@
+"""Recurring workflow schedules: CRUD, RRULE checks, and the scheduler pass that fires due schedules."""
+
+from products.workflows.backend.services.hog_flow_schedules import (
+ create_schedule,
+ delete_schedule,
+ get_schedule,
+ list_schedules,
+ process_due_schedules,
+ update_schedule,
+)
+from products.workflows.backend.utils.rrule_utils import compute_next_occurrences, validate_rrule
+
+__all__ = [
+ "compute_next_occurrences",
+ "create_schedule",
+ "delete_schedule",
+ "get_schedule",
+ "list_schedules",
+ "process_due_schedules",
+ "update_schedule",
+ "validate_rrule",
+]
diff --git a/products/workflows/backend/presentation/views/hog_flow.py b/products/workflows/backend/presentation/views/hog_flow.py
index 7e36408baef7..388fbe403fcf 100644
--- a/products/workflows/backend/presentation/views/hog_flow.py
+++ b/products/workflows/backend/presentation/views/hog_flow.py
@@ -138,7 +138,11 @@ from products.workflows.backend.facade.blast_radius import (
is_account_audience,
parse_account_audience_filters,
)
-from products.workflows.backend.facade.contracts import StaffPausedError, WorkflowBatchJobNotFound
+from products.workflows.backend.facade.contracts import (
+ StaffPausedError,
+ WorkflowBatchJobNotFound,
+ WorkflowScheduleNotFound,
+)
from products.workflows.backend.facade.email_health import (
fetch_aws_tenant_reputation,
fetch_email_totals_by_source,
@@ -149,7 +153,17 @@ from products.workflows.backend.facade.email_health import (
resume_email_sending,
team_email_sending_allowance,
)
-from products.workflows.backend.facade.enums import HogFlowBatchJobState
+from products.workflows.backend.facade.enums import HogFlowBatchJobState, HogFlowScheduleStatus
+from products.workflows.backend.facade.schedules import (
+ compute_next_occurrences,
+ create_schedule,
+ delete_schedule,
+ get_schedule,
+ list_schedules,
+ process_due_schedules,
+ update_schedule,
+ validate_rrule,
+)
from products.workflows.backend.facade.secrets import (
TemplateCache,
mask_derived_trigger,
@@ -194,10 +208,8 @@ from products.workflows.backend.models.hog_flow.hog_flow import (
WORKFLOW_SAFE_INTERNAL_EVENTS,
HogFlow,
)
-from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob
from products.workflows.backend.models.hog_flow_optimization import HogFlowOptimization
from products.workflows.backend.models.hog_flow_revision import HogFlowRevision
-from products.workflows.backend.models.hog_flow_schedule import SCHEDULED_TRIGGER_TYPES, HogFlowSchedule
from products.workflows.backend.models.workflow_proposal import WorkflowProposal
from products.workflows.backend.presentation.views.action_redirects import compute_action_redirects
from products.workflows.backend.presentation.views.graph_operations import _deep_merge, apply_graph_operations
@@ -224,7 +236,6 @@ from products.workflows.backend.services.timing_reschedule import (
get_timing_reschedule_action_ids,
)
from products.workflows.backend.tasks.hog_flows import reschedule_hog_flow_timing
-from products.workflows.backend.utils.rrule_utils import compute_next_occurrences, validate_rrule
logger = structlog.get_logger(__name__)
@@ -930,6 +941,20 @@ class InternalBlastRadiusPersonsSerializer(serializers.Serializer):
has_more = serializers.BooleanField(help_text="Whether another page may follow.")
+class InternalProcessedSchedulesSerializer(serializers.Serializer):
+ """Response contract for the internal due-schedules endpoint, read by the scheduler service."""
+
+ processed = serializers.ListField(
+ child=serializers.CharField(), help_text="Ids of due schedules that dispatched a run."
+ )
+ initialized = serializers.ListField(
+ child=serializers.CharField(), help_text="Ids of new schedules that got their first run time."
+ )
+ failed = serializers.ListField(
+ child=serializers.CharField(), help_text="Ids of due schedules that failed to dispatch."
+ )
+
+
class InternalBatchJobStatusSerializer(serializers.Serializer):
"""Response contract for the internal batch job status write, read by the Node batch resolver."""
@@ -1983,34 +2008,30 @@ class HogFlowEmailSendingRateLimitSerializer(serializers.Serializer):
return value
-class HogFlowScheduleSerializer(serializers.ModelSerializer):
- class Meta:
- model = HogFlowSchedule
- fields = [
- "id",
- "rrule",
- "starts_at",
- "timezone",
- "variables",
- "status",
- "next_run_at",
- "created_at",
- "updated_at",
- ]
- read_only_fields = ["id", "status", "next_run_at", "created_at", "updated_at"]
- extra_kwargs = {
- "rrule": {
- "help_text": (
- "iCalendar RRULE string (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once "
- "per hour."
- )
- },
- "starts_at": {"help_text": "ISO 8601 datetime the schedule starts from."},
- "timezone": {"help_text": "IANA timezone for interpreting the RRULE (default 'UTC')."},
- "variables": {"help_text": "Variable value overrides merged with the workflow defaults on each run."},
- "status": {"help_text": "active, paused, or completed (set once the RRULE's COUNT/UNTIL is exhausted)."},
- "next_run_at": {"help_text": "Next scheduled fire time, computed by the scheduler."},
- }
+class HogFlowScheduleSerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True)
+ rrule = serializers.CharField(
+ help_text=(
+ "iCalendar RRULE string (e.g. 'FREQ=DAILY;INTERVAL=1'). Must produce occurrences at most once per hour."
+ )
+ )
+ starts_at = serializers.DateTimeField(help_text="ISO 8601 datetime the schedule starts from.")
+ timezone = serializers.CharField(
+ max_length=64, required=False, help_text="IANA timezone for interpreting the RRULE (default 'UTC')."
+ )
+ variables = serializers.JSONField(
+ required=False, help_text="Variable value overrides merged with the workflow defaults on each run."
+ )
+ status = serializers.ChoiceField(
+ choices=HogFlowScheduleStatus.choices,
+ read_only=True,
+ help_text="active, paused, or completed (set once the RRULE's COUNT/UNTIL is exhausted).",
+ )
+ next_run_at = serializers.DateTimeField(
+ read_only=True, allow_null=True, help_text="Next scheduled fire time, computed by the scheduler."
+ )
+ created_at = serializers.DateTimeField(read_only=True)
+ updated_at = serializers.DateTimeField(read_only=True)
def validate(self, data):
# For partial updates, fall back to instance values
@@ -2044,14 +2065,6 @@ class HogFlowScheduleSerializer(serializers.ModelSerializer):
return data
- def update(self, instance, validated_data):
- if any(field in validated_data for field in ("rrule", "starts_at", "timezone")):
- # Force the scheduler to recalculate the next occurrence on its next poll
- instance.next_run_at = None
- if instance.status != HogFlowSchedule.Status.PAUSED:
- instance.status = HogFlowSchedule.Status.ACTIVE
- return super().update(instance, validated_data)
-
class HogFlowRunRequestSerializer(serializers.Serializer):
variables = serializers.DictField(
@@ -5506,8 +5519,8 @@ class HogFlowViewSet(
"filters"
):
return
- paused = after.schedules.filter(status=HogFlowSchedule.Status.ACTIVE).update(
- status=HogFlowSchedule.Status.PAUSED, next_run_at=None, updated_at=timezone.now()
+ paused = after.schedules.filter(status=HogFlowScheduleStatus.ACTIVE).update(
+ status=HogFlowScheduleStatus.PAUSED, next_run_at=None, updated_at=timezone.now()
)
if paused:
self._report_workflow_action("hog_flow_schedules_paused_on_audience_change", after, {"paused": paused})
@@ -5581,7 +5594,7 @@ class HogFlowViewSet(
schedule_overrides = {
str(schedule_id): variables or {}
for schedule_id, variables in hog_flow.schedules.exclude(
- status=HogFlowSchedule.Status.COMPLETED
+ status=HogFlowScheduleStatus.COMPLETED
).values_list("id", "variables")
}
return build_publish_impact(
@@ -7125,11 +7138,11 @@ class HogFlowViewSet(
serializer = HogFlowScheduleSerializer(data=request.data, context=self.get_serializer_context())
serializer.is_valid(raise_exception=True)
- schedule = serializer.save(team=self.team, hog_flow=hog_flow)
+ schedule = create_schedule(team_id=self.team_id, hog_flow_id=hog_flow.id, fields=serializer.validated_data)
self._report_workflow_action("hog_flow_schedule_created", hog_flow, {"schedule_id": str(schedule.id)})
- return Response(serializer.data, status=201)
+ return Response(HogFlowScheduleSerializer(schedule).data, status=201)
- schedules = HogFlowSchedule.objects.filter(hog_flow=hog_flow, team=self.team).order_by("-created_at")
+ schedules = list_schedules(team_id=self.team_id, hog_flow_id=hog_flow.id)
serializer = HogFlowScheduleSerializer(schedules, many=True)
return Response(serializer.data)
@@ -7148,13 +7161,13 @@ class HogFlowViewSet(
def schedule_detail(self, request: Request, schedule_id=None, *args, **kwargs):
hog_flow = self.get_object()
try:
- schedule = HogFlowSchedule.objects.get(id=schedule_id, hog_flow=hog_flow, team=self.team)
- except HogFlowSchedule.DoesNotExist:
+ schedule = get_schedule(team_id=self.team_id, hog_flow_id=hog_flow.id, schedule_id=schedule_id)
+ except WorkflowScheduleNotFound:
raise exceptions.NotFound("Schedule not found")
if request.method == "DELETE":
schedule_id_str = str(schedule.id)
- schedule.delete()
+ delete_schedule(team_id=self.team_id, hog_flow_id=hog_flow.id, schedule_id=schedule.id)
self._report_workflow_action("hog_flow_schedule_deleted", hog_flow, {"schedule_id": schedule_id_str})
return Response(status=204)
@@ -7162,9 +7175,11 @@ class HogFlowViewSet(
schedule, data=request.data, partial=True, context=self.get_serializer_context()
)
serializer.is_valid(raise_exception=True)
- serializer.save()
+ schedule = update_schedule(
+ team_id=self.team_id, hog_flow_id=hog_flow.id, schedule_id=schedule.id, fields=serializer.validated_data
+ )
self._report_workflow_action("hog_flow_schedule_updated", hog_flow, {"schedule_id": str(schedule.id)})
- return Response(serializer.data)
+ return Response(HogFlowScheduleSerializer(schedule).data)
@extend_schema(
request=HogFlowRunRequestSerializer,
@@ -7406,159 +7421,16 @@ class InternalHogFlowViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, AppMetricsMi
Internal endpoint called by the scheduler service to process due schedules.
Handles both executing due schedules and initializing next_run_at for new ones.
"""
- from django.db import transaction # noqa: PLC0415
-
- from products.workflows.backend.models.hog_flow_schedule import HogFlowSchedule # noqa: PLC0415
- from products.workflows.backend.utils.rrule_utils import compute_next_occurrences # noqa: PLC0415
-
- def advance_next_run(schedule, after=None):
- """Compute and set next_run_at, or mark completed if RRULE is exhausted."""
- occurrences = compute_next_occurrences(
- rrule_string=schedule.rrule,
- starts_at=schedule.starts_at,
- timezone_str=schedule.timezone,
- after=after,
- count=1,
- )
- if occurrences:
- schedule.next_run_at = occurrences[0]
- schedule.save(update_fields=["next_run_at", "updated_at"])
- else:
- schedule.status = HogFlowSchedule.Status.COMPLETED
- schedule.next_run_at = None
- schedule.save(update_fields=["status", "next_run_at", "updated_at"])
- return occurrences
-
- def resolve_variables(hog_flow, schedule):
- """Build default variables from HogFlow schema, then merge schedule overrides."""
- variables = {}
- for var in hog_flow.variables or []:
- variables[var.get("key")] = var.get("default")
- variables.update(schedule.variables or {})
- return variables
-
- processed = []
- initialized = []
- failed = []
-
try:
- # 1. Process due schedules (next_run_at <= now)
- # nosemgrep: idor-lookup-without-team (internal endpoint processes all teams)
- due_schedule_ids = list(
- HogFlowSchedule.objects.filter(
- status=HogFlowSchedule.Status.ACTIVE, next_run_at__lte=timezone.now()
- ).values_list("id", flat=True)
- )
-
- for schedule_id in due_schedule_ids:
- try:
- batch_job_params: dict | None = None
- schedule_invocation_params: dict | None = None
- with transaction.atomic():
- # Per-schedule transaction: lock only one row at a time to minimize
- # lock duration and allow concurrent replicas via skip_locked.
- # Re-checks conditions since the schedule may have been processed
- # between the ID scan and this lock.
- schedule = (
- # nosemgrep: idor-lookup-without-team
- HogFlowSchedule.objects.select_for_update(skip_locked=True)
- .select_related("hog_flow")
- .filter(
- id=schedule_id, status=HogFlowSchedule.Status.ACTIVE, next_run_at__lte=timezone.now()
- )
- .first()
- )
- if not schedule:
- continue
-
- hog_flow = schedule.hog_flow
- trigger_type = (hog_flow.trigger or {}).get("type")
-
- if hog_flow.status != "active" or trigger_type not in SCHEDULED_TRIGGER_TYPES:
- schedule.next_run_at = None
- schedule.save(update_fields=["next_run_at", "updated_at"])
- continue
-
- advance_next_run(schedule, after=schedule.next_run_at)
-
- if trigger_type == "batch":
- batch_job_params = {
- "team_id": schedule.team_id,
- "hog_flow": hog_flow,
- "variables": resolve_variables(hog_flow, schedule),
- "filters": (hog_flow.trigger or {}).get("filters", {}),
- }
- else:
- schedule_invocation_params = {
- "team_id": schedule.team_id,
- "hog_flow_id": str(hog_flow.id),
- "variables": resolve_variables(hog_flow, schedule),
- }
-
- # Dispatch outside the transaction so HTTP calls don't hold the row lock.
- if batch_job_params:
- with transaction.atomic():
- # Re-read the status under the flow's lock, so a stop that committed after
- # the check above wins, and a stop that lands later sees this job.
- still_active = (
- HogFlow.objects.select_for_update()
- .filter(id=batch_job_params["hog_flow"].id, status=HogFlow.State.ACTIVE)
- .exists()
- )
- if still_active:
- HogFlowBatchJob.objects.create(
- **batch_job_params,
- status=HogFlowBatchJob.State.QUEUED,
- )
- if still_active:
- processed.append(str(schedule_id))
- elif schedule_invocation_params:
- response = create_hog_flow_scheduled_invocation(**schedule_invocation_params)
- response.raise_for_status()
- processed.append(str(schedule_id))
- except Exception:
- logger.exception("Error processing schedule", schedule_id=str(schedule_id))
- failed.append(str(schedule_id))
-
- # 2. Initialize next_run_at for schedules that need it
- # nosemgrep: idor-lookup-without-team (internal endpoint processes all teams)
- uninitialized_ids = list(
- HogFlowSchedule.objects.filter(
- status=HogFlowSchedule.Status.ACTIVE,
- next_run_at__isnull=True,
- hog_flow__status="active",
- hog_flow__trigger__type__in=SCHEDULED_TRIGGER_TYPES,
- ).values_list("id", flat=True)
- )
-
- for schedule_id in uninitialized_ids:
- try:
- with transaction.atomic():
- # Per-schedule transaction: lock only one row at a time to minimize
- # lock duration and allow concurrent replicas via skip_locked.
- # Re-checks conditions since the schedule may have been initialized
- # between the ID scan and this lock.
- schedule = (
- # nosemgrep: idor-lookup-without-team
- HogFlowSchedule.objects.select_for_update(skip_locked=True)
- .filter(id=schedule_id, status=HogFlowSchedule.Status.ACTIVE, next_run_at__isnull=True)
- .first()
- )
- if not schedule:
- continue
-
- if advance_next_run(schedule):
- initialized.append(str(schedule.id))
- except Exception:
- logger.exception("Error initializing schedule", schedule_id=str(schedule_id))
- failed.append(str(schedule_id))
-
+ result = process_due_schedules()
return Response(
- {
- "processed": processed,
- "initialized": initialized,
- "failed": failed,
- }
+ InternalProcessedSchedulesSerializer(
+ {
+ "processed": result.processed,
+ "initialized": result.initialized,
+ "failed": result.failed,
+ }
+ ).data
)
except Exception as e:
logger.exception("Error in internal_process_due_schedules", error=str(e))
diff --git a/products/workflows/backend/services/hog_flow_schedules.py b/products/workflows/backend/services/hog_flow_schedules.py
new file mode 100644
index 000000000000..f3b50e7aa365
--- /dev/null
+++ b/products/workflows/backend/services/hog_flow_schedules.py
@@ -0,0 +1,227 @@
+from collections.abc import Mapping
+from datetime import datetime
+from typing import Any
+from uuid import UUID
+
+from django.core.exceptions import ValidationError
+from django.db import transaction
+from django.utils import timezone
+
+import structlog
+
+from posthog.plugins.plugin_server_api import create_hog_flow_scheduled_invocation
+
+from products.workflows.backend.facade.contracts import ProcessedSchedules, WorkflowSchedule, WorkflowScheduleNotFound
+from products.workflows.backend.facade.enums import HogFlowScheduleStatus
+from products.workflows.backend.models.hog_flow.hog_flow import HogFlow
+from products.workflows.backend.models.hog_flow_batch_job import HogFlowBatchJob
+from products.workflows.backend.models.hog_flow_schedule import SCHEDULED_TRIGGER_TYPES, HogFlowSchedule
+from products.workflows.backend.utils.rrule_utils import compute_next_occurrences
+
+logger = structlog.get_logger(__name__)
+
+WRITABLE_SCHEDULE_FIELDS = frozenset({"rrule", "starts_at", "timezone", "variables"})
+
+
+def _to_schedule(schedule: HogFlowSchedule) -> WorkflowSchedule:
+ return WorkflowSchedule(
+ id=schedule.id,
+ hog_flow_id=schedule.hog_flow_id,
+ rrule=schedule.rrule,
+ starts_at=schedule.starts_at,
+ timezone=schedule.timezone,
+ variables=schedule.variables,
+ status=HogFlowScheduleStatus(schedule.status),
+ next_run_at=schedule.next_run_at,
+ created_at=schedule.created_at,
+ updated_at=schedule.updated_at,
+ )
+
+
+def _get_schedule_row(team_id: int, hog_flow_id: UUID, schedule_id: str | UUID) -> HogFlowSchedule:
+ try:
+ return HogFlowSchedule.objects.get(id=schedule_id, hog_flow_id=hog_flow_id, team_id=team_id)
+ except (HogFlowSchedule.DoesNotExist, ValidationError, ValueError):
+ # ValidationError and ValueError fire when the id is not a parseable UUID.
+ raise WorkflowScheduleNotFound()
+
+
+def list_schedules(*, team_id: int, hog_flow_id: UUID) -> list[WorkflowSchedule]:
+ schedules = HogFlowSchedule.objects.filter(hog_flow_id=hog_flow_id, team_id=team_id).order_by("-created_at")
+ return [_to_schedule(s) for s in schedules]
+
+
+def get_schedule(*, team_id: int, hog_flow_id: UUID, schedule_id: str) -> WorkflowSchedule:
+ return _to_schedule(_get_schedule_row(team_id, hog_flow_id, schedule_id))
+
+
+def create_schedule(*, team_id: int, hog_flow_id: UUID, fields: Mapping[str, Any]) -> WorkflowSchedule:
+ values = {key: value for key, value in fields.items() if key in WRITABLE_SCHEDULE_FIELDS}
+ schedule = HogFlowSchedule.objects.create(team_id=team_id, hog_flow_id=hog_flow_id, **values)
+ return _to_schedule(schedule)
+
+
+def update_schedule(
+ *, team_id: int, hog_flow_id: UUID, schedule_id: UUID, fields: Mapping[str, Any]
+) -> WorkflowSchedule:
+ schedule = _get_schedule_row(team_id, hog_flow_id, schedule_id)
+ if any(field in fields for field in ("rrule", "starts_at", "timezone")):
+ # Force the scheduler to recalculate the next occurrence on its next poll
+ schedule.next_run_at = None
+ if schedule.status != HogFlowScheduleStatus.PAUSED:
+ schedule.status = HogFlowScheduleStatus.ACTIVE
+ for key, value in fields.items():
+ if key in WRITABLE_SCHEDULE_FIELDS:
+ setattr(schedule, key, value)
+ schedule.save()
+ return _to_schedule(schedule)
+
+
+def delete_schedule(*, team_id: int, hog_flow_id: UUID, schedule_id: UUID) -> None:
+ _get_schedule_row(team_id, hog_flow_id, schedule_id).delete()
+
+
+def _advance_next_run(schedule: HogFlowSchedule, after: datetime | None = None) -> list[datetime]:
+ """Compute and set next_run_at, or mark completed if RRULE is exhausted."""
+ occurrences = compute_next_occurrences(
+ rrule_string=schedule.rrule,
+ starts_at=schedule.starts_at,
+ timezone_str=schedule.timezone,
+ after=after,
+ count=1,
+ )
+ if occurrences:
+ schedule.next_run_at = occurrences[0]
+ schedule.save(update_fields=["next_run_at", "updated_at"])
+ else:
+ schedule.status = HogFlowScheduleStatus.COMPLETED
+ schedule.next_run_at = None
+ schedule.save(update_fields=["status", "next_run_at", "updated_at"])
+ return occurrences
+
+
+def _resolve_variables(hog_flow: HogFlow, schedule: HogFlowSchedule) -> dict[str, Any]:
+ """Build default variables from HogFlow schema, then merge schedule overrides."""
+ variables = {}
+ for var in hog_flow.variables or []:
+ variables[var.get("key")] = var.get("default")
+ variables.update(schedule.variables or {})
+ return variables
+
+
+def process_due_schedules() -> ProcessedSchedules:
+ """Execute due schedules and initialize next_run_at for new ones, across all teams."""
+ processed: list[str] = []
+ initialized: list[str] = []
+ failed: list[str] = []
+
+ # 1. Process due schedules (next_run_at <= now)
+ # nosemgrep: idor-lookup-without-team (internal endpoint processes all teams)
+ due_schedule_ids = list(
+ HogFlowSchedule.objects.filter(
+ status=HogFlowScheduleStatus.ACTIVE, next_run_at__lte=timezone.now()
+ ).values_list("id", flat=True)
+ )
+
+ for schedule_id in due_schedule_ids:
+ try:
+ batch_job_params: dict | None = None
+ schedule_invocation_params: dict | None = None
+ with transaction.atomic():
+ # Per-schedule transaction: lock only one row at a time to minimize
+ # lock duration and allow concurrent replicas via skip_locked.
+ # Re-checks conditions since the schedule may have been processed
+ # between the ID scan and this lock.
+ schedule = (
+ # nosemgrep: idor-lookup-without-team
+ HogFlowSchedule.objects.select_for_update(skip_locked=True)
+ .select_related("hog_flow")
+ .filter(id=schedule_id, status=HogFlowScheduleStatus.ACTIVE, next_run_at__lte=timezone.now())
+ .first()
+ )
+ if not schedule:
+ continue
+
+ hog_flow = schedule.hog_flow
+ trigger_type = (hog_flow.trigger or {}).get("type")
+
+ if hog_flow.status != "active" or trigger_type not in SCHEDULED_TRIGGER_TYPES:
+ schedule.next_run_at = None
+ schedule.save(update_fields=["next_run_at", "updated_at"])
+ continue
+
+ _advance_next_run(schedule, after=schedule.next_run_at)
+
+ if trigger_type == "batch":
+ batch_job_params = {
+ "team_id": schedule.team_id,
+ "hog_flow": hog_flow,
+ "variables": _resolve_variables(hog_flow, schedule),
+ "filters": (hog_flow.trigger or {}).get("filters", {}),
+ }
+ else:
+ schedule_invocation_params = {
+ "team_id": schedule.team_id,
+ "hog_flow_id": str(hog_flow.id),
+ "variables": _resolve_variables(hog_flow, schedule),
+ }
+
+ # Dispatch outside the transaction so HTTP calls don't hold the row lock.
+ if batch_job_params:
+ with transaction.atomic():
+ # Re-read the status under the flow's lock, so a stop that committed after
+ # the check above wins, and a stop that lands later sees this job.
+ still_active = (
+ HogFlow.objects.select_for_update()
+ .filter(id=batch_job_params["hog_flow"].id, status=HogFlow.State.ACTIVE)
+ .exists()
+ )
+ if still_active:
+ HogFlowBatchJob.objects.create(
+ **batch_job_params,
+ status=HogFlowBatchJob.State.QUEUED,
+ )
+ if still_active:
+ processed.append(str(schedule_id))
+ elif schedule_invocation_params:
+ response = create_hog_flow_scheduled_invocation(**schedule_invocation_params)
+ response.raise_for_status()
+ processed.append(str(schedule_id))
+ except Exception:
+ logger.exception("Error processing schedule", schedule_id=str(schedule_id))
+ failed.append(str(schedule_id))
+
+ # 2. Initialize next_run_at for schedules that need it
+ # nosemgrep: idor-lookup-without-team (internal endpoint processes all teams)
+ uninitialized_ids = list(
+ HogFlowSchedule.objects.filter(
+ status=HogFlowScheduleStatus.ACTIVE,
+ next_run_at__isnull=True,
+ hog_flow__status="active",
+ hog_flow__trigger__type__in=SCHEDULED_TRIGGER_TYPES,
+ ).values_list("id", flat=True)
+ )
+
+ for schedule_id in uninitialized_ids:
+ try:
+ with transaction.atomic():
+ # Per-schedule transaction: lock only one row at a time to minimize
+ # lock duration and allow concurrent replicas via skip_locked.
+ # Re-checks conditions since the schedule may have been initialized
+ # between the ID scan and this lock.
+ schedule = (
+ # nosemgrep: idor-lookup-without-team
+ HogFlowSchedule.objects.select_for_update(skip_locked=True)
+ .filter(id=schedule_id, status=HogFlowScheduleStatus.ACTIVE, next_run_at__isnull=True)
+ .first()
+ )
+ if not schedule:
+ continue
+
+ if _advance_next_run(schedule):
+ initialized.append(str(schedule.id))
+ except Exception:
+ logger.exception("Error initializing schedule", schedule_id=str(schedule_id))
+ failed.append(str(schedule_id))
+
+ return ProcessedSchedules(processed=processed, initialized=initialized, failed=failed)
diff --git a/products/workflows/backend/test/test_hog_flow_schedule.py b/products/workflows/backend/test/test_hog_flow_schedule.py
index a769dfd9d33f..22b13a23e5d7 100644
--- a/products/workflows/backend/test/test_hog_flow_schedule.py
+++ b/products/workflows/backend/test/test_hog_flow_schedule.py
@@ -181,9 +181,10 @@ class TestHogFlowScheduleAPI(APIBaseTest):
assert response.status_code == status.HTTP_204_NO_CONTENT
assert HogFlowSchedule.objects.filter(id=schedule_id).count() == 0
- def test_delete_nonexistent_schedule_returns_404(self):
+ @parameterized.expand([("unknown_id", "00000000-0000-0000-0000-000000000000"), ("malformed_id", "not-a-uuid")])
+ def test_delete_nonexistent_schedule_returns_404(self, _name: str, schedule_id: str):
workflow = self._create_batch_workflow()
- response = self.client.delete(self._schedule_detail_url(workflow["id"], "00000000-0000-0000-0000-000000000000"))
+ response = self.client.delete(self._schedule_detail_url(workflow["id"], schedule_id))
assert response.status_code == status.HTTP_404_NOT_FOUND
def test_multiple_schedules_per_workflow(self):
@@ -315,7 +316,8 @@ class TestProcessDueSchedules(APIBaseTest):
return real_compute(*args, **kwargs)
with unittest.mock.patch(
- "products.workflows.backend.utils.rrule_utils.compute_next_occurrences", side_effect=stop_then_compute
+ "products.workflows.backend.services.hog_flow_schedules.compute_next_occurrences",
+ side_effect=stop_then_compute,
):
response = self._post()
@@ -434,7 +436,7 @@ class TestProcessDueSchedules(APIBaseTest):
@override_settings(INTERNAL_API_SECRET="test-secret")
[email protected]("products.workflows.backend.presentation.views.hog_flow.create_hog_flow_scheduled_invocation")
[email protected]("products.workflows.backend.services.hog_flow_schedules.create_hog_flow_scheduled_invocation")
class TestProcessDueScheduleTriggers(APIBaseTest):
INTERNAL_URL = "/api/internal/hog_flows/process_due_schedules"
diff --git a/pyproject.toml b/pyproject.toml
index fabeaf8c8254..09d210a2869d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -724,14 +724,11 @@ ignore_imports = [
"products.workflows.backend.presentation.views.hog_flow -> products.messaging.backend.unlayer",
"products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.metrics",
"products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow.hog_flow",
- "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow_batch_job",
"products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow_optimization",
"products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow_revision",
- "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.hog_flow_schedule",
"products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.models.workflow_proposal",
"products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.services.timing_reschedule",
"products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.tasks.hog_flows",
- "products.workflows.backend.presentation.views.hog_flow -> products.workflows.backend.utils.rrule_utils",
# TODO: access-control presentation wave — the consolidated RBAC viewsets carry their ORM
# access with them. Thin them to parse -> facade -> serialize and delete each entry.
"products.access_control.backend.presentation.access_control -> products.access_control.backend.models.access_control",