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(workflows): return last run for loop workflows (#107724)

Harley Alexander17b213c28a23
diff --git a/posthog/test/repo_invariants/test_pagination_contract.py b/posthog/test/repo_invariants/test_pagination_contract.py
index 8947e3c2b724..3d4e2e81b966 100644
--- a/posthog/test/repo_invariants/test_pagination_contract.py
+++ b/posthog/test/repo_invariants/test_pagination_contract.py
@@ -24,6 +24,7 @@ LIST_VIEWSETS_WITHOUT_DIRECT_SHARED_PAGINATION = {
"products.managed_migrations.backend.api.support_batch_imports.BatchImportSupportViewSet",
"products.product_analytics.backend.presentation.insight_ee.EnterpriseInsightsViewSet",
"products.reminders.backend.api.reminder.ReminderViewSet",
+ "products.workflows.backend.api.hog_flow.HogFlowViewSet",
"products.workflows.backend.api.hog_flow_template.PublicHogFlowTemplateViewSet",
}
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 2ac7cc54a838..e553cfb9f175 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -313,6 +313,7 @@ __all__ = [
"list_task_repositories",
"list_task_runs",
"list_tasks",
+ "list_workflow_last_runs",
"pi_cloud_runtime_enabled",
"prepare_task_run_artifact_uploads",
"prepare_task_staged_artifacts",
@@ -6351,6 +6352,41 @@ async def select_repository_for_message(team_id: int, user_id: int, message: str
)
+def list_workflow_last_runs(
+ team_id: int, user_id: int | None, hog_flow_ids: Iterable[UUID]
+) -> dict[UUID, contracts.WorkflowLastRunDTO]:
+ """The newest visible task of each given workflow, keyed by workflow id, in one query.
+
+ Uses the same rows as the workflow's run history (``hog_flow_id`` task list with archived tasks
+ included), so a list row never names a run that the history hides. Workflows without a
+ visible task are absent from the result.
+ """
+ ids = list(hog_flow_ids)
+ if not ids:
+ return {}
+ latest_run = TaskRun.objects.filter(task=OuterRef("pk"), team_id=team_id).order_by("-created_at", "-id")
+ rows = (
+ _visible_task_qs(team_id, user_id)
+ .filter(hog_flow_id__in=ids, internal=False)
+ .order_by("hog_flow_id", "-created_at", "-id")
+ .distinct("hog_flow_id")
+ .annotate(
+ _run_status=Subquery(latest_run.values("status")[:1]),
+ _run_created_at=Subquery(latest_run.values("created_at")[:1]),
+ )
+ .values_list("hog_flow_id", "id", "created_at", "_run_status", "_run_created_at")
+ )
+ return {
+ hog_flow_id: contracts.WorkflowLastRunDTO(
+ hog_flow_id=hog_flow_id,
+ task_id=task_id,
+ status=run_status or TaskRun.Status.NOT_STARTED,
+ ran_at=run_created_at or created_at,
+ )
+ for hog_flow_id, task_id, created_at, run_status, run_created_at in rows
+ }
+
+
#: Orderings the task list accepts, keyed by the value clients send. Both fall back to `-id` so a
#: page boundary can't drop or repeat a row when two tasks share a timestamp. A null
#: `last_activity_at` (rows written outside the ORM) sorts first under `DESC`, which is where a row
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index 9f6897cc48c1..4511fb3e5b27 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -767,6 +767,20 @@ class CreatedTaskDTO:
latest_run: TaskRunDTO | None = None
+@dataclass(frozen=True)
+class WorkflowLastRunDTO:
+ """The newest task a workflow created, as its last run.
+
+ ``status`` is the task's newest run status, or ``not_started`` when the task has no run yet.
+ ``ran_at`` is when that run started, or when the task was made if it has no run.
+ """
+
+ hog_flow_id: UUID
+ task_id: UUID
+ status: str
+ ran_at: datetime
+
+
@dataclass(frozen=True)
class WorkflowTaskDTO:
"""Outcome of a workflow's "Create AI task" action.
diff --git a/products/tasks/backend/tests/test_facade.py b/products/tasks/backend/tests/test_facade.py
index aa76c0e2b2b7..b30d7a65897a 100644
--- a/products/tasks/backend/tests/test_facade.py
+++ b/products/tasks/backend/tests/test_facade.py
@@ -373,6 +373,40 @@ class TestFacadeReadsAndMappers(TestCase):
run.refresh_from_db()
self.assertEqual(run.environment, TaskRun.Environment.CLOUD)
+ def test_list_workflow_last_runs_uses_each_workflows_newest_listed_task(self):
+ now = django_timezone.now()
+ flow_with_runs, flow_without_run, flow_not_asked = uuid4(), uuid4(), uuid4()
+ older = self._make_task(origin_product=Task.OriginProduct.WORKFLOW, hog_flow_id=flow_with_runs)
+ newer = self._make_task(origin_product=Task.OriginProduct.WORKFLOW, hog_flow_id=flow_with_runs, archived=True)
+ Task.objects.filter(pk=older.pk).update(created_at=now - timedelta(hours=2))
+ Task.objects.filter(pk=newer.pk).update(created_at=now - timedelta(hours=1))
+ TaskRun.objects.create(task=older, team=self.team, status=TaskRun.Status.COMPLETED)
+ earlier_run = TaskRun.objects.create(task=newer, team=self.team, status=TaskRun.Status.COMPLETED)
+ newest_run = TaskRun.objects.create(task=newer, team=self.team, status=TaskRun.Status.FAILED)
+ TaskRun.objects.filter(pk=earlier_run.pk).update(created_at=now - timedelta(minutes=50))
+ TaskRun.objects.filter(pk=newest_run.pk).update(created_at=now - timedelta(minutes=30))
+ # Run history hides internal tasks, so the newest task here must not count as the last run.
+ self._make_task(origin_product=Task.OriginProduct.WORKFLOW, hog_flow_id=flow_with_runs, internal=True)
+ not_started = self._make_task(origin_product=Task.OriginProduct.WORKFLOW, hog_flow_id=flow_without_run)
+ self._make_task(origin_product=Task.OriginProduct.WORKFLOW, hog_flow_id=flow_not_asked)
+
+ last_runs = facade.list_workflow_last_runs(self.team.id, self.user.id, [flow_with_runs, flow_without_run])
+
+ assert last_runs == {
+ flow_with_runs: contracts.WorkflowLastRunDTO(
+ hog_flow_id=flow_with_runs,
+ task_id=newer.id,
+ status="failed",
+ ran_at=now - timedelta(minutes=30),
+ ),
+ flow_without_run: contracts.WorkflowLastRunDTO(
+ hog_flow_id=flow_without_run,
+ task_id=not_started.id,
+ status="not_started",
+ ran_at=not_started.created_at,
+ ),
+ }
+
def test_task_exists_and_visibility(self):
task = self._make_task()
self.assertTrue(facade.task_exists(task.id, self.team.id))
diff --git a/products/workflows/backend/api/hog_flow.py b/products/workflows/backend/api/hog_flow.py
index d00b6e3e770c..c23cb041ed64 100644
--- a/products/workflows/backend/api/hog_flow.py
+++ b/products/workflows/backend/api/hog_flow.py
@@ -4,6 +4,7 @@ import json
import uuid as uuid_mod
import hashlib
import dataclasses
+from collections.abc import Sequence
from copy import deepcopy
from datetime import datetime, timedelta
from time import monotonic
@@ -118,6 +119,8 @@ from products.messaging.backend.api.message_templates import DesignOperationSeri
from products.messaging.backend.models import MessageTemplate
from products.messaging.backend.unlayer import UnlayerNotConfiguredError, UnlayerRenderError, render_design_html
from products.notifications.backend.facade.api import publish_resource_edited
+from products.tasks.backend.facade.api import list_workflow_last_runs
+from products.tasks.backend.facade.contracts import WorkflowLastRunDTO
from products.tasks.backend.facade.model_catalogue import TASK_RUN_GATEWAY_PRODUCT, available_model_choices
from products.tasks.backend.facade.workflow_tasks import (
WorkflowTaskConnectorsInvalid,
@@ -2822,8 +2825,22 @@ class WorkflowEmailPauseStatusSerializer(serializers.Serializer):
)
+class HogFlowLastRunSerializer(serializers.Serializer):
+ task_id = serializers.UUIDField(read_only=True, help_text="The task this run belongs to.")
+ status = serializers.CharField(
+ read_only=True,
+ help_text="Status of the task's newest run: not_started, queued, in_progress, completed, failed or cancelled.",
+ )
+ ran_at = serializers.DateTimeField(
+ read_only=True, help_text="When the run started, or when the task was created if it has no run yet."
+ )
+
+
class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.ModelSerializer):
created_by = UserBasicSerializer(read_only=True)
+ last_run = serializers.SerializerMethodField(
+ help_text="Newest task this loop workflow created, as its last run. Null when the workflow is not a loop or has not run."
+ )
draft = serializers.JSONField(
read_only=True,
help_text=(
@@ -2859,9 +2876,23 @@ class HogFlowMinimalSerializer(UserAccessControlSerializerMixin, serializers.Mod
"variables",
"billable_action_types",
"user_access_level",
+ "last_run",
]
read_only_fields = fields
+ @extend_schema_field(HogFlowLastRunSerializer(allow_null=True))
+ def get_last_run(self, instance: HogFlow) -> dict | None:
+ if instance.origin_product != HogFlow.OriginProduct.LOOPS:
+ return None
+ # The list view batches this lookup for the whole page; other responses carry one flow.
+ last_runs: dict[uuid_mod.UUID, WorkflowLastRunDTO] | None = self.context.get("workflow_last_runs")
+ if last_runs is None:
+ request = self.context.get("request")
+ user_id = request.user.id if request is not None else None
+ last_runs = list_workflow_last_runs(instance.team_id, user_id, [instance.id])
+ last_run = last_runs.get(instance.id)
+ return HogFlowLastRunSerializer(last_run).data if last_run else None
+
def to_representation(self, instance):
# Never return secret function inputs. Replace each set secret with the {"secret": True}
# presence marker in the live actions and, when present, the staged draft's actions. Values
@@ -3199,6 +3230,7 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
"email_sending_paused_by",
"email_sending_pause_requires_support",
"email_sending_resumed_at",
+ "last_run",
]
read_only_fields = [
"id",
@@ -3221,6 +3253,7 @@ class HogFlowSerializer(HogFlowMinimalSerializer):
"email_sending_paused_by",
"email_sending_pause_requires_support",
"email_sending_resumed_at",
+ "last_run",
]
def validate(self, data):
@@ -4661,6 +4694,7 @@ class HogFlowViewSet(
log_source = "hog_flow"
app_source = "hog_flow"
function_kind = "hog_flow"
+ _workflow_last_runs: dict[uuid_mod.UUID, WorkflowLastRunDTO] | None = None
def dangerously_get_required_scopes(self, request, view) -> Optional[list[str]]:
# Dual-method custom actions need method-aware scopes — the action-name-based read/write
@@ -4732,8 +4766,19 @@ class HogFlowViewSet(
# command). See _should_validate_strictly.
context = super().get_serializer_context()
context["event_source"] = get_event_source(self.request)
+ if self._workflow_last_runs is not None:
+ context["workflow_last_runs"] = self._workflow_last_runs
return context
+ def paginate_queryset(self, queryset: QuerySet | Sequence[Any]) -> Sequence[Any] | None:
+ page = super().paginate_queryset(queryset)
+ # The MCP summary serializer has no last_run, so only the full list row pays for the lookup.
+ if self.action == "list" and page is not None and self.get_serializer_class() is HogFlowMinimalSerializer:
+ # One lookup for every loop on the page, so each row does not query tasks on its own.
+ loop_ids = [flow.id for flow in page if flow.origin_product == HogFlow.OriginProduct.LOOPS]
+ self._workflow_last_runs = list_workflow_last_runs(self.team_id, self.request.user.id, loop_ids)
+ return page
+
def safely_get_queryset(self, queryset: QuerySet) -> QuerySet:
if self.action == "list":
# `id` breaks ties so LIMIT/OFFSET paging stays stable: rows sharing an updated_at can
diff --git a/products/workflows/backend/api/test/test_hog_flow.py b/products/workflows/backend/api/test/test_hog_flow.py
index b8703ecd4fc5..bde7c8458d75 100644
--- a/products/workflows/backend/api/test/test_hog_flow.py
+++ b/products/workflows/backend/api/test/test_hog_flow.py
@@ -4,6 +4,7 @@ from datetime import UTC, datetime, timedelta
from io import StringIO
from types import SimpleNamespace
from typing import Any, Optional
+from uuid import uuid4
from posthog.test.base import APIBaseTest, ClickhouseTestMixin
from unittest.mock import ANY, MagicMock, PropertyMock, patch
@@ -34,6 +35,7 @@ from products.actions.backend.models.action import Action
from products.cdp.backend.api.test.test_hog_function_templates import MOCK_NODE_TEMPLATES
from products.cohorts.backend.models.cohort import Cohort
from products.skills.backend.models.skills import LLMSkill
+from products.tasks.backend.facade.contracts import WorkflowLastRunDTO
from products.workflows.backend.api.hog_flow import (
HogFlowActionSerializer,
_should_validate_strictly,
@@ -472,6 +474,26 @@ class TestHogFlowAPI(APIBaseTest):
response = self.client.get(f"/api/projects/{self.team.id}/hog_flows?origin_product=spreadsheets")
assert response.status_code == 400
+ def test_list_returns_last_run_for_loops_from_one_lookup(self):
+ loop = HogFlow.objects.create(team=self.team, name="Loop", created_by=self.user, origin_product="loops")
+ HogFlow.objects.create(team=self.team, name="Hand built", created_by=self.user)
+ task_id = uuid4()
+ last_run = WorkflowLastRunDTO(
+ hog_flow_id=loop.id, task_id=task_id, status="failed", ran_at=datetime(2026, 1, 1, tzinfo=UTC)
+ )
+
+ with patch(
+ "products.workflows.backend.api.hog_flow.list_workflow_last_runs", return_value={loop.id: last_run}
+ ) as lookup:
+ response = self.client.get(f"/api/projects/{self.team.id}/hog_flows")
+
+ assert response.status_code == 200, response.json()
+ lookup.assert_called_once_with(self.team.id, self.user.id, [loop.id])
+ assert {flow["name"]: flow["last_run"] for flow in response.json()["results"]} == {
+ "Loop": {"task_id": str(task_id), "status": "failed", "ran_at": "2026-01-01T00:00:00Z"},
+ "Hand built": None,
+ }
+
def test_list_filter_by_broadcast_eligible(self):
email_action = {"id": "email_node", "type": "function_email", "config": {}}
exit_action = {"id": "exit_node", "type": "exit", "config": {}}
diff --git a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
index f250bd94110d..bf087168a0ab 100644
--- a/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
+++ b/products/workflows/frontend/Broadcasts/broadcastWizardLogic.test.ts
@@ -22,6 +22,7 @@ function savedBroadcast(overrides: { name: string; subject: string; updatedAt: s
created_at: '2026-01-01T00:00:00Z',
created_by: { id: 1, uuid: 'user-1', email: '[email protected]', hedgehog_config: null },
updated_at: overrides.updatedAt,
+ last_run: null,
trigger: { type: 'batch', filters: { properties: [] } },
conversion: null,
email_sending_rate_limit: null,
diff --git a/products/workflows/frontend/generated/api.schemas.ts b/products/workflows/frontend/generated/api.schemas.ts
index 1034f9594b16..5cf2a02da114 100644
--- a/products/workflows/frontend/generated/api.schemas.ts
+++ b/products/workflows/frontend/generated/api.schemas.ts
@@ -305,6 +305,15 @@ export interface UserBasicApi {
role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null
}
+export interface HogFlowLastRunApi {
+ /** The task this run belongs to. */
+ readonly task_id: string
+ /** Status of the task's newest run: not_started, queued, in_progress, completed, failed or cancelled. */
+ readonly status: string
+ /** When the run started, or when the task was created if it has no run yet. */
+ readonly ran_at: string
+}
+
/**
* Mixin for serializers to add user access control fields
*/
@@ -337,6 +346,8 @@ export interface HogFlowMinimalApi {
* @nullable
*/
readonly user_access_level: string | null
+ /** Newest task this loop workflow created, as its last run. Null when the workflow is not a loop or has not run. */
+ readonly last_run: HogFlowLastRunApi | null
}
export interface PaginatedHogFlowMinimalListApi {
@@ -658,6 +669,8 @@ export interface HogFlowApi {
* @nullable
*/
readonly email_sending_resumed_at: string | null
+ /** Newest task this loop workflow created, as its last run. Null when the workflow is not a loop or has not run. */
+ readonly last_run: HogFlowLastRunApi | null
}
/**
@@ -757,6 +770,8 @@ export interface HogFlowUpdateApi {
* @nullable
*/
readonly email_sending_resumed_at: string | null
+ /** Newest task this loop workflow created, as its last run. Null when the workflow is not a loop or has not run. */
+ readonly last_run: HogFlowLastRunApi | null
}
/**
@@ -856,6 +871,8 @@ export interface PatchedHogFlowUpdateApi {
* @nullable
*/
readonly email_sending_resumed_at?: string | null
+ /** Newest task this loop workflow created, as its last run. Null when the workflow is not a loop or has not run. */
+ readonly last_run?: HogFlowLastRunApi | null
}
/**
diff --git a/products/workflows/frontend/generated/api.zod.ts b/products/workflows/frontend/generated/api.zod.ts
index ee8fc7badce3..b3ee79d823a0 100644
--- a/products/workflows/frontend/generated/api.zod.ts
+++ b/products/workflows/frontend/generated/api.zod.ts
@@ -2355,6 +2355,24 @@ export const HogFlowsInvocationsCreateBody = /* @__PURE__ */ zod.object({
.describe(
'When sending was last resumed. Every detector window starts after this, so resuming does not immediately re-trip on the feedback that caused the pause. Null if never paused.'
),
+ last_run: zod
+ .union([
+ zod.object({
+ task_id: zod.uuid().describe('The task this run belongs to.'),
+ status: zod
+ .string()
+ .describe(
+ "Status of the task's newest run: not_started, queued, in_progress, completed, failed or cancelled."
+ ),
+ ran_at: zod.iso
+ .datetime({ offset: true })
+ .describe('When the run started, or when the task was created if it has no run yet.'),
+ }),
+ zod.null(),
+ ])
+ .describe(
+ 'Newest task this loop workflow created, as its last run. Null when the workflow is not a loop or has not run.'
+ ),
})
.describe('Mixin for serializers to add user access control fields')
.optional()
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 50a8f8e6c0fe..52bedd99c3a9 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -50017,6 +50017,15 @@ export namespace Schemas {
readonly updated_at: string;
}
+ export interface HogFlowLastRun {
+ /** The task this run belongs to. */
+ readonly task_id: string;
+ /** Status of the task's newest run: not_started, queued, in_progress, completed, failed or cancelled. */
+ readonly status: string;
+ /** When the run started, or when the task was created if it has no run yet. */
+ readonly ran_at: string;
+ }
+
/**
* Mixin for serializers to add user access control fields
*/
@@ -50103,6 +50112,8 @@ export namespace Schemas {
* @nullable
*/
readonly email_sending_resumed_at: string | null;
+ /** Newest task this loop workflow created, as its last run. Null when the workflow is not a loop or has not run. */
+ readonly last_run: HogFlowLastRun | null;
}
/**
@@ -50262,6 +50273,8 @@ export namespace Schemas {
* @nullable
*/
readonly user_access_level: string | null;
+ /** Newest task this loop workflow created, as its last run. Null when the workflow is not a loop or has not run. */
+ readonly last_run: HogFlowLastRun | null;
}
export interface HogFlowPublishImpactMoveTarget {
@@ -50572,6 +50585,8 @@ export namespace Schemas {
* @nullable
*/
readonly email_sending_resumed_at: string | null;
+ /** Newest task this loop workflow created, as its last run. Null when the workflow is not a loop or has not run. */
+ readonly last_run: HogFlowLastRun | null;
}
/**
@@ -74713,6 +74728,8 @@ export namespace Schemas {
* @nullable
*/
readonly email_sending_resumed_at?: string | null;
+ /** Newest task this loop workflow created, as its last run. Null when the workflow is not a loop or has not run. */
+ readonly last_run?: HogFlowLastRun | null;
}
/**