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(tasks): rate-limit workflow-created AI tasks (#88254)

Harley Alexanderb1724cc9d83f
diff --git a/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.ts b/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.ts
index e8bd0f5aed6d..af0f210d712a 100644
--- a/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.ts
+++ b/nodejs/src/cdp/templates/_destinations/posthog_tasks/posthog-create-task.template.ts
@@ -138,7 +138,7 @@ return response.body
required: false,
default: 5,
description:
- 'New runs are skipped while this many tasks from this workflow are still running. Protects against a burst of trigger events starting too many agents at once.',
+ 'New runs are skipped while this many tasks from this workflow are still running. Protects against a burst of trigger events starting too many agents at once. Daily limits on how many tasks a workflow and project can create also apply.',
},
{
// Only meaningful on a Slack-triggered workflow; the builder hides it for other
diff --git a/products/tasks/backend/facade/workflow_tasks.py b/products/tasks/backend/facade/workflow_tasks.py
index 26666aed8654..cb513f3db4f8 100644
--- a/products/tasks/backend/facade/workflow_tasks.py
+++ b/products/tasks/backend/facade/workflow_tasks.py
@@ -10,6 +10,9 @@ from products.tasks.backend.logic.services.workflow_tasks import (
WorkflowTaskLimitExceeded,
WorkflowTaskOriginKeyConflict,
WorkflowTaskOwnerIneligible,
+ WorkflowTaskRateCapped,
+ WorkflowTaskTeamRateCapped,
+ WorkflowTaskUsageLimited,
create_workflow_task,
validate_connectors,
)
@@ -19,7 +22,10 @@ __all__ = [
"WorkflowTaskLimitExceeded",
"WorkflowTaskOriginKeyConflict",
"WorkflowTaskOwnerIneligible",
+ "WorkflowTaskRateCapped",
"WorkflowTaskSlackContext",
+ "WorkflowTaskTeamRateCapped",
+ "WorkflowTaskUsageLimited",
"create_workflow_task",
"validate_connectors",
]
diff --git a/products/tasks/backend/logic/services/workflow_tasks.py b/products/tasks/backend/logic/services/workflow_tasks.py
index 278f9894940d..eacfbe892029 100644
--- a/products/tasks/backend/logic/services/workflow_tasks.py
+++ b/products/tasks/backend/logic/services/workflow_tasks.py
@@ -7,13 +7,16 @@ never touches tasks internals.
import json
import uuid
+from datetime import timedelta
from typing import Any
from django.db import IntegrityError, connection, transaction
+from django.utils import timezone as django_timezone
import structlog
from posthog.dataclasses import frozen
+from posthog.models import User
from posthog.models.integration import Integration, SlackIntegration
from posthog.models.team.team import Team
from posthog.temporal.oauth import PosthogMcpScopes
@@ -23,7 +26,12 @@ from products.slack_app.backend.facade.api import slack_channel_is_approved
from products.slack_app.backend.models import SlackThreadTaskMapping
from products.slack_app.backend.slack_thread import SlackThreadContext
from products.tasks.backend.facade import contracts
-from products.tasks.backend.logic.services.run_actor import loop_owner_eligible_for_credentials
+from products.tasks.backend.logic.services.code_usage_gate import usage_limit_response
+from products.tasks.backend.logic.services.run_actor import (
+ loop_owner_eligible_for_credentials,
+ user_has_current_team_access,
+)
+from products.tasks.backend.metrics import observe_workflow_task_create
from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.temporal.constants import WORKFLOW_RUN_IDLE_TIMEOUT_SECONDS
@@ -39,6 +47,14 @@ EVENT_PROMPT_MAX_CHARS = 16_000
# `hedgehog` (or `x`) replaces this rather than stacking a second reaction beside it.
TRIGGER_ACK_EMOJI = "eyes"
+# Daily ceilings on created tasks (trailing 24h) on top of the in-flight cap: a workflow
+# triggered by a common event can otherwise sustain hundreds of agent runs a day through
+# the concurrency cap alone. The team cap aggregates across a team's workflows so N
+# workflows can't each spend the per-workflow cap; it is deliberately separate from the
+# loops budget (LOOP_RATE_CAP_PER_DAY / LOOP_TEAM_RATE_CAP_PER_DAY).
+WORKFLOW_TASK_RATE_CAP_PER_DAY = 100
+WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY = 500
+
WORKFLOW_FRAMING_BLOCK = (
"This is an unattended run started by a PostHog workflow. No human is available to "
"answer questions or clarify ambiguous instructions while it executes. Prefer opening "
@@ -74,6 +90,22 @@ class WorkflowTaskOriginKeyConflict(Exception):
super().__init__(f"Idempotency key {origin_key!r} is already used by another workflow")
+class WorkflowTaskRateCapped(Exception):
+ def __init__(self, cap: int) -> None:
+ self.cap = cap
+ super().__init__(f"Workflow reached its daily cap of {cap} created tasks")
+
+
+class WorkflowTaskTeamRateCapped(Exception):
+ def __init__(self, cap: int) -> None:
+ self.cap = cap
+ super().__init__(f"Team reached its daily cap of {cap} workflow-created tasks")
+
+
+class WorkflowTaskUsageLimited(Exception):
+ pass
+
+
def create_workflow_task(
*,
team: Team,
@@ -99,7 +131,10 @@ def create_workflow_task(
`WorkflowTaskConnectorsInvalid` when the requested connectors aren't ones the owner
can mount, `WorkflowTaskOwnerIneligible` when the owner lost access to the project,
and `WorkflowTaskLimitExceeded` when the workflow already has `max_parallel_tasks`
- runs in flight.
+ runs in flight. Also raises `WorkflowTaskUsageLimited` when the owner is over the
+ AI usage limit, and `WorkflowTaskRateCapped` / `WorkflowTaskTeamRateCapped` when
+ the workflow or its team reached the daily created-task cap. A replayed
+ `origin_key` bypasses the gate and every cap.
`event` is rendered into the agent's prompt as data. `slack_context` binds the run to
the Slack thread that triggered the workflow. The task is created either way: a context
@@ -109,10 +144,43 @@ def create_workflow_task(
"""
replay = _find_replayed_task(team.id, hog_flow_id, origin_key)
if replay is not None:
+ observe_workflow_task_create(reason="replayed")
return replay
validate_connectors(team.id, owner_id, mcp_installation_ids)
+ gate_owner = User.objects.filter(id=owner_id).first()
+ if gate_owner is None:
+ observe_workflow_task_create(reason="owner_ineligible")
+ raise WorkflowTaskOwnerIneligible()
+
+ # Fast, unlocked pre-checks before the gate call below. The gate mints an
+ # OAuthAccessToken for gate_owner and makes a blocking request to the LLM gateway, so
+ # an owner who already lost team access, or a workflow that's already past its daily
+ # cap, must not reach it: checking first means neither pays for that mint-and-call on
+ # every trigger event. These reads are not authoritative, since nothing holds the
+ # advisory locks here yet, so a concurrent write can move the counts after this check
+ # runs. The same checks run again under the locks below, and that locked run is the
+ # one that decides.
+ if not user_has_current_team_access(gate_owner, team):
+ observe_workflow_task_create(reason="owner_ineligible")
+ raise WorkflowTaskOwnerIneligible()
+ daily_counts = _daily_task_counts(team.id, hog_flow_id)
+ if daily_counts.workflow >= WORKFLOW_TASK_RATE_CAP_PER_DAY:
+ observe_workflow_task_create(reason="rate_capped")
+ raise WorkflowTaskRateCapped(WORKFLOW_TASK_RATE_CAP_PER_DAY)
+ if daily_counts.team >= WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY:
+ observe_workflow_task_create(reason="team_rate_capped")
+ raise WorkflowTaskTeamRateCapped(WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY)
+
+ # The gate stays outside the transaction: it calls the LLM gateway (short timeout,
+ # fails open), and holding the advisory locks across an external call would stall
+ # every workflow fire for the team. Replays never reach it, so engine retries of an
+ # already-created task succeed even for a blocked owner.
+ if usage_limit_response(gate_owner, team.id) is not None:
+ observe_workflow_task_create(reason="gate_blocked")
+ raise WorkflowTaskUsageLimited()
+
# Snapshot the connector allowlist onto the run: the sandbox mounts only what's here
# (see loop_mcp_installation_allowlist), so a later edit of the workflow can't change
# what an already-queued run may reach.
@@ -135,9 +203,13 @@ def create_workflow_task(
# One transaction so a duplicate origin_key rolls back the task, its run, and the
# (on_commit, therefore never-fired) dispatch together.
with transaction.atomic():
- # Serialize fires per workflow: without this, concurrent triggers all read the
- # same in-flight count and overshoot max_parallel_tasks.
+ # Team lock first, per-workflow lock second, always in this order so fires
+ # can't deadlock. The team lock serializes the team-wide daily-cap check
+ # (two workflows hold different per-workflow locks and would both read a
+ # below-cap count); the per-workflow lock keeps the in-flight count exact,
+ # including against pods that predate the team lock during a rolling deploy.
with connection.cursor() as cursor:
+ cursor.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", [f"workflow-tasks-team:{team.id}"])
cursor.execute("SELECT pg_advisory_xact_lock(hashtext(%s))", [f"workflow-tasks:{hog_flow_id}"])
if slack_context is not None:
# And once per thread, across workflows, because the live-run check below
@@ -149,15 +221,35 @@ def create_workflow_task(
[f"workflow-task-slack-thread:{slack_context.channel}:{slack_context.thread_ts}"],
)
+ # Prometheus counters are process-local: the rollback these raises trigger
+ # can't undo an increment, and each raise ends the call, so each outcome
+ # counts exactly once.
# Same in-transaction check loops make before minting: locks the owner and
# membership rows so a concurrent offboarding can't slip between check and create.
if not loop_owner_eligible_for_credentials(owner_id, team):
+ observe_workflow_task_create(reason="owner_ineligible")
raise WorkflowTaskOwnerIneligible()
+ # The daily caps count created Task rows in the trailing 24h. A capped attempt
+ # raises and rolls back, writing no row, so rejections can't consume the
+ # budget: the Task table is the "created" ledger, like loops'
+ # outcome_reason="created" fires. Read again here even though the pre-check
+ # above already ran the same query: that read was unlocked, so a concurrent
+ # create could have pushed the count over the cap since then. This locked
+ # read is the one that decides.
+ daily_counts = _daily_task_counts(team.id, hog_flow_id)
+ if daily_counts.workflow >= WORKFLOW_TASK_RATE_CAP_PER_DAY:
+ observe_workflow_task_create(reason="rate_capped")
+ raise WorkflowTaskRateCapped(WORKFLOW_TASK_RATE_CAP_PER_DAY)
+ if daily_counts.team >= WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY:
+ observe_workflow_task_create(reason="team_rate_capped")
+ raise WorkflowTaskTeamRateCapped(WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY)
+
in_flight = TaskRun.objects.filter(
task__team_id=team.id, task__hog_flow_id=hog_flow_id, status__in=ACTIVE_RUN_STATUSES
).count()
if in_flight >= max_parallel_tasks:
+ observe_workflow_task_create(reason="limit_reached")
raise WorkflowTaskLimitExceeded(in_flight, max_parallel_tasks)
# Resolved under the thread lock so the live-run check inside it holds for the
@@ -202,8 +294,12 @@ def create_workflow_task(
replay = _find_replayed_task(team.id, hog_flow_id, origin_key)
if replay is None:
raise
+ observe_workflow_task_create(reason="replayed")
return replay
+ # Emitted after the transaction: an IntegrityError can divert a create into the
+ # replay path above, which counts as replayed instead.
+ observe_workflow_task_create(reason="created")
return _task_dto(task, created=True)
@@ -225,6 +321,25 @@ def _find_replayed_task(
return _task_dto(existing, created=False)
+@frozen
+class _DailyTaskCounts:
+ """Task rows created in the trailing 24h, checked against the two daily caps."""
+
+ workflow: int
+ team: int
+
+
+def _daily_task_counts(team_id: int, hog_flow_id: uuid.UUID) -> _DailyTaskCounts:
+ """One function so the unlocked pre-check and the authoritative locked recheck run
+ the identical query and can't drift apart."""
+ since = django_timezone.now() - timedelta(hours=24)
+ workflow_count = Task.objects.filter(team_id=team_id, hog_flow_id=hog_flow_id, created_at__gte=since).count()
+ team_count = Task.objects.filter(
+ team_id=team_id, origin_product=Task.OriginProduct.WORKFLOW, created_at__gte=since
+ ).count()
+ return _DailyTaskCounts(workflow=workflow_count, team=team_count)
+
+
def validate_connectors(team_id: int, owner_id: int, mcp_installation_ids: list[str] | None) -> None:
"""Raise `WorkflowTaskConnectorsInvalid` for any id the owner can't mount.
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index 83ba65e26caa..158b92a3f348 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -282,6 +282,14 @@ LOOP_FIRE_TOTAL = Counter(
labelnames=["reason"],
)
+# reason is one of: created, replayed, gate_blocked, rate_capped, team_rate_capped,
+# limit_reached, owner_ineligible, a fixed, code-defined set, safe as a label.
+WORKFLOW_TASK_CREATE_TOTAL = Counter(
+ "posthog_tasks_workflow_task_create_total",
+ 'Workflow "Create AI task" action outcomes',
+ labelnames=["reason"],
+)
+
LOOP_AUTO_PAUSED_TOTAL = Counter(
"posthog_tasks_loop_auto_paused_total",
"Loops auto-paused after exceeding the consecutive-failure threshold",
@@ -613,6 +621,10 @@ def observe_loop_fire(*, reason: str) -> None:
LOOP_FIRE_TOTAL.labels(reason=reason).inc()
+def observe_workflow_task_create(*, reason: str) -> None:
+ WORKFLOW_TASK_CREATE_TOTAL.labels(reason=reason).inc()
+
+
def observe_loop_auto_paused() -> None:
LOOP_AUTO_PAUSED_TOTAL.inc()
diff --git a/products/tasks/backend/tests/test_workflow_tasks_api.py b/products/tasks/backend/tests/test_workflow_tasks_api.py
index d27477f8bc38..c929a57f6336 100644
--- a/products/tasks/backend/tests/test_workflow_tasks_api.py
+++ b/products/tasks/backend/tests/test_workflow_tasks_api.py
@@ -1,13 +1,16 @@
-from datetime import timedelta
+from datetime import datetime, timedelta
from types import SimpleNamespace
from typing import Any
-from uuid import uuid4
+from uuid import UUID, uuid4
from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.test import SimpleTestCase, override_settings
-from django.utils import timezone
+from django.utils import (
+ timezone,
+ timezone as django_timezone,
+)
from parameterized import parameterized
from rest_framework import status
@@ -21,6 +24,10 @@ from posthog.models.team.team import Team
from posthog.temporal.oauth import ARRAY_APP_CLIENT_ID_DEV
from products.slack_app.backend.models import SlackChannel, SlackThreadTaskMapping
+from products.tasks.backend.logic.services.workflow_tasks import (
+ WORKFLOW_TASK_RATE_CAP_PER_DAY,
+ WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY,
+)
from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.visibility import task_control_q, task_visibility_q
from products.workflows.backend.api.workflow_tasks import WorkflowTaskCreateSerializer
@@ -75,6 +82,30 @@ class TestWorkflowTasksAPI(APIBaseTest):
TaskRun.objects.create(task=task, team=self.team, status=run_status)
return task
+ def _seed_created_tasks(
+ self,
+ count: int,
+ *,
+ hog_flow_id: UUID | None,
+ origin_product: str = Task.OriginProduct.WORKFLOW,
+ created_at: datetime | None = None,
+ ) -> None:
+ # No TaskRun rows: the daily caps count Task rows only, and runless tasks keep the
+ # in-flight count at 0, so a cap test cannot pass via the in-flight 409 instead.
+ Task.objects.bulk_create(
+ [
+ Task(
+ team=self.team,
+ title=f"seed-{i}",
+ description="seed",
+ origin_product=origin_product,
+ hog_flow_id=hog_flow_id,
+ **({"created_at": created_at} if created_at is not None else {}),
+ )
+ for i in range(count)
+ ]
+ )
+
def test_creates_a_task_and_run_attributed_to_the_workflow_and_its_owner(self) -> None:
response = self._post()
@@ -210,7 +241,8 @@ class TestWorkflowTasksAPI(APIBaseTest):
assert response.status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)
assert not Task.objects.filter(hog_flow_id=self.hog_flow.id).exists()
- def test_refuses_a_workflow_whose_owner_is_deactivated(self) -> None:
+ @patch("products.tasks.backend.logic.services.workflow_tasks.usage_limit_response")
+ def test_refuses_a_workflow_whose_owner_is_deactivated(self, usage_limit_response_mock) -> None:
self.user.is_active = False
self.user.save()
@@ -218,8 +250,12 @@ class TestWorkflowTasksAPI(APIBaseTest):
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
assert not Task.objects.filter(hog_flow_id=self.hog_flow.id).exists()
+ # A deactivated owner must never reach the gate: it would mint an OAuth token
+ # scoped to this owner and team before anything has confirmed they still belong.
+ usage_limit_response_mock.assert_not_called()
- def test_refuses_an_owner_removed_from_the_organization(self) -> None:
+ @patch("products.tasks.backend.logic.services.workflow_tasks.usage_limit_response")
+ def test_refuses_an_owner_removed_from_the_organization(self, usage_limit_response_mock) -> None:
former_member = self._create_user("[email protected]")
flow = HogFlow.objects.create(team=self.team, name="Orphaned", created_by=former_member)
OrganizationMembership.objects.filter(user=former_member, organization=self.organization).delete()
@@ -228,6 +264,7 @@ class TestWorkflowTasksAPI(APIBaseTest):
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
assert not Task.objects.filter(hog_flow_id=flow.id).exists()
+ usage_limit_response_mock.assert_not_called()
@parameterized.expand([("unknown_workflow",), ("another_teams_workflow",)])
def test_refuses_a_workflow_it_cannot_find_in_the_tokens_team(self, case: str) -> None:
@@ -257,6 +294,58 @@ class TestWorkflowTasksAPI(APIBaseTest):
assert response.status_code == status.HTTP_201_CREATED, response.json()
+ @parameterized.expand(["per_workflow", "team_wide"])
+ @patch("products.tasks.backend.logic.services.workflow_tasks.usage_limit_response")
+ def test_skips_creation_at_the_daily_cap(self, scope: str, usage_limit_response_mock) -> None:
+ if scope == "per_workflow":
+ self._seed_created_tasks(WORKFLOW_TASK_RATE_CAP_PER_DAY, hog_flow_id=self.hog_flow.id)
+ expected_fragment = "This workflow reached its daily limit"
+ else:
+ # Two other workflows fill the team budget; this workflow is far under its own cap.
+ for _ in range(2):
+ self._seed_created_tasks(WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY // 2, hog_flow_id=uuid4())
+ expected_fragment = "This project reached its daily limit"
+ seeded = Task.objects.count()
+
+ response = self._post()
+
+ assert response.status_code == status.HTTP_409_CONFLICT, response.json()
+ assert expected_fragment in response.json()["detail"]
+ assert Task.objects.count() == seeded
+ # A workflow or team already at its cap must never reach the gate, or every
+ # remaining event that day would still pay for an OAuth mint and a gateway
+ # round trip only to be rejected anyway.
+ usage_limit_response_mock.assert_not_called()
+
+ @parameterized.expand(["older_than_24h", "non_workflow_origin"])
+ def test_old_and_foreign_tasks_do_not_consume_the_daily_caps(self, case: str) -> None:
+ if case == "older_than_24h":
+ self._seed_created_tasks(
+ WORKFLOW_TASK_RATE_CAP_PER_DAY,
+ hog_flow_id=self.hog_flow.id,
+ created_at=django_timezone.now() - timedelta(hours=25),
+ )
+ else:
+ self._seed_created_tasks(
+ WORKFLOW_TASK_TEAM_RATE_CAP_PER_DAY,
+ hog_flow_id=None,
+ origin_product=Task.OriginProduct.LOOP,
+ )
+
+ response = self._post()
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+
+ @patch("products.tasks.backend.logic.services.workflow_tasks.usage_limit_response")
+ def test_rejects_creation_when_the_owner_is_over_the_usage_limit(self, usage_limit_response_mock) -> None:
+ usage_limit_response_mock.return_value = object() # any non-None reply means blocked
+
+ response = self._post()
+
+ assert response.status_code == status.HTTP_409_CONFLICT, response.json()
+ assert "usage limit" in response.json()["detail"]
+ assert Task.objects.count() == 0
+
def test_replaying_an_idempotency_key_returns_the_existing_task(self) -> None:
first = self._post({"idempotency_key": "invocation-1"})
replay = self._post({"idempotency_key": "invocation-1"})
@@ -275,10 +364,13 @@ class TestWorkflowTasksAPI(APIBaseTest):
first = self._post({"idempotency_key": "invocation-1", "connectors": ["inst-1"], "max_parallel_tasks": 1})
assert first.status_code == status.HTTP_201_CREATED, first.json()
- # The connector is gone and the workflow is at its limit; the retry of the
- # already-created request must still return the existing task.
+ # The connector is gone, the workflow is at its in-flight and daily limits, and the
+ # owner is over the usage limit; the retry of the already-created request must
+ # still return the existing task.
get_active_installations.return_value = []
- replay = self._post({"idempotency_key": "invocation-1", "connectors": ["inst-1"], "max_parallel_tasks": 1})
+ self._seed_created_tasks(WORKFLOW_TASK_RATE_CAP_PER_DAY, hog_flow_id=self.hog_flow.id)
+ with patch("products.tasks.backend.logic.services.workflow_tasks.usage_limit_response", return_value=object()):
+ replay = self._post({"idempotency_key": "invocation-1", "connectors": ["inst-1"], "max_parallel_tasks": 1})
assert replay.status_code == status.HTTP_200_OK, replay.json()
assert replay.json()["id"] == first.json()["id"]
diff --git a/products/workflows/backend/api/workflow_tasks.py b/products/workflows/backend/api/workflow_tasks.py
index 1e8bede9c212..cd094f08eff7 100644
--- a/products/workflows/backend/api/workflow_tasks.py
+++ b/products/workflows/backend/api/workflow_tasks.py
@@ -17,7 +17,10 @@ from products.tasks.backend.facade.workflow_tasks import (
WorkflowTaskLimitExceeded,
WorkflowTaskOriginKeyConflict,
WorkflowTaskOwnerIneligible,
+ WorkflowTaskRateCapped,
WorkflowTaskSlackContext,
+ WorkflowTaskTeamRateCapped,
+ WorkflowTaskUsageLimited,
create_workflow_task,
)
from products.workflows.backend.models import HogFlow
@@ -146,7 +149,11 @@ class WorkflowTaskViewSet(viewsets.GenericViewSet):
),
409: OpenApiResponse(
response=WorkflowTaskRejectedSerializer,
- description="The workflow already has its maximum runs in flight, or the idempotency key belongs to another workflow",
+ description=(
+ "The task was not created: the workflow is at its in-flight or daily limit, "
+ "the project is at its daily limit of workflow-created tasks, "
+ "the owner is over the AI usage limit, or the idempotency key belongs to another workflow"
+ ),
),
422: OpenApiResponse(
response=WorkflowTaskRejectedSerializer,
@@ -207,6 +214,41 @@ class WorkflowTaskViewSet(viewsets.GenericViewSet):
f"Workflow already has {error.in_flight} tasks in flight (limit {error.limit}).",
status.HTTP_409_CONFLICT,
)
+ except WorkflowTaskRateCapped as error:
+ logger.info(
+ "workflow_task_create_rate_capped",
+ team_id=team_id,
+ hog_flow_id=str(hog_flow_id),
+ cap=error.cap,
+ )
+ return _rejected(
+ f"This workflow reached its daily limit of {error.cap} tasks. "
+ "The event was skipped. Task creation resumes automatically within 24 hours.",
+ status.HTTP_409_CONFLICT,
+ )
+ except WorkflowTaskTeamRateCapped as error:
+ logger.info(
+ "workflow_task_create_team_rate_capped",
+ team_id=team_id,
+ hog_flow_id=str(hog_flow_id),
+ cap=error.cap,
+ )
+ return _rejected(
+ f"This project reached its daily limit of {error.cap} tasks created by workflows. "
+ "The event was skipped. Task creation resumes automatically within 24 hours.",
+ status.HTTP_409_CONFLICT,
+ )
+ except WorkflowTaskUsageLimited:
+ logger.info(
+ "workflow_task_create_usage_limited",
+ team_id=team_id,
+ hog_flow_id=str(hog_flow_id),
+ )
+ return _rejected(
+ "The workflow owner is over the AI usage limit, so no task was created. "
+ "Task creation resumes when the limit resets.",
+ status.HTTP_409_CONFLICT,
+ )
return Response(
WorkflowTaskResponseSerializer({"id": result.task_id, "run_id": result.run_id}).data,