: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
fix(signals): close three report cap and budget bypasses (#85413)
Georgiy Tarasove8fdee5292d1
diff --git a/products/signals/backend/task_run_artefacts.py b/products/signals/backend/task_run_artefacts.pyindex ede3cf1a2d18..136e10e00386 100644--- a/products/signals/backend/task_run_artefacts.py+++ b/products/signals/backend/task_run_artefacts.py@@ -43,6 +43,7 @@ __all__ = ["ReportTaskCapExceeded","aappend_task_run_artefact","append_task_run_artefact",+ "enforce_report_implementation_rerun_cap","enforce_report_task_cap","record_implementation_task","record_report_task",@@ -132,7 +133,7 @@ def signals_task_ids(*, report_id: str, type: str) -> list[str]:]-def _live_implementation_exists(*, team_id: int, report_id: str) -> bool:+def _live_implementation_exists(*, team_id: int, report_id: str, exclude_task_id: str | None = None) -> bool:"""Whether the report has an implementation task that still claims its one slot.Reads the `SignalReportTask` gate rows (not the API-mutable artefact log) and traverses@@ -142,11 +143,12 @@ def _live_implementation_exists(*, team_id: int, report_id: str) -> bool:claims it permanently (the report is implemented). Quota-cancelled implementations deletetheir gate rows (`release_quota_cancelled_implementation`), so they never count."""- rows = (- SignalReportTask.objects.filter(team_id=team_id, report_id=report_id, relationship=TASK_RUN_TYPE_IMPLEMENTATION)- .exclude(task__deleted=True)- .values_list("task_id", "task__runs__status", "task__runs__output__pr_url")- )+ claimants = SignalReportTask.objects.filter(+ team_id=team_id, report_id=report_id, relationship=TASK_RUN_TYPE_IMPLEMENTATION+ ).exclude(task__deleted=True)+ if exclude_task_id is not None:+ claimants = claimants.exclude(task_id=exclude_task_id)+ rows = claimants.values_list("task_id", "task__runs__status", "task__runs__output__pr_url")runs_by_task: dict[str, list[tuple[str | None, object]]] = {}for task_id, status, pr_url in rows:runs_by_task.setdefault(str(task_id), []).append((status, pr_url))@@ -204,6 +206,45 @@ def enforce_report_task_cap(*, team_id: int, report_id: str, relationship: str |)+def enforce_report_implementation_rerun_cap(*, team_id: int, report_id: str, task_id: str) -> None:+ """Re-check the one-live-implementation slot before starting another run of an existing task.++ `enforce_report_task_cap` guards task *creation*, but a task outlives its runs. An+ implementation whose every run ended failed/cancelled without a PR releases its slot, which+ lets a second implementation be created for the report — and then running the first one again+ would put two live implementations on it, spending unbilled inference twice over.++ Only another task holding the slot blocks: a task reclaiming the slot it released is the+ ordinary "my run failed, try again" path and stays allowed. Non-implementation tasks are+ unaffected, since the discussion cap counts tasks rather than runs and conversation inside+ one is deliberately unlimited.++ Must be called inside an open transaction: it locks the report row, the same lock creation+ and auto-start take. That lock only serializes for as long as the caller's transaction stays+ open, and a live run is what marks the slot taken, so a caller that goes on to start the run+ has to insert the run row in this same transaction. Releasing the lock first would leave the+ task looking released for the whole span before the insert, which is long enough for a+ concurrent create to pass its own count check.+ """+ if not transaction.get_connection().in_atomic_block:+ raise RuntimeError(+ "enforce_report_implementation_rerun_cap must run inside a transaction; it locks the report row"+ )+ is_implementation = SignalReportTask.objects.filter(+ team_id=team_id, report_id=report_id, task_id=task_id, relationship=TASK_RUN_TYPE_IMPLEMENTATION+ ).exists()+ if not is_implementation:+ return+ report = SignalReport.objects.select_for_update().filter(id=report_id, team_id=team_id).first()+ if report is None:+ return+ if _live_implementation_exists(team_id=team_id, report_id=report_id, exclude_task_id=task_id):+ raise ReportTaskCapExceeded(+ kind=TASK_RUN_TYPE_IMPLEMENTATION,+ detail="A PR task already exists for this report. Open the existing task to continue.",+ )++def record_implementation_task(*, team_id: int, report_id: str, task_id: str, run_id: str | None = None, billing_exempt_reason: str | None = None) -> SignalReportArtefact:diff --git a/products/signals/backend/test/test_signal_report_artefact_api.py b/products/signals/backend/test/test_signal_report_artefact_api.pyindex 5ba6f582ab90..96937f0466e4 100644--- a/products/signals/backend/test/test_signal_report_artefact_api.py+++ b/products/signals/backend/test/test_signal_report_artefact_api.py@@ -1193,6 +1193,46 @@ class TestSignalReportArtefactLogWriteViewSet(APIBaseTest):assert response.status_code == status.HTTP_204_NO_CONTENTassert not SignalReportArtefact.objects.filter(id=artefact.id).exists()+ @parameterized.expand([("exact", "signals"), ("padded", " signals ")])+ def test_create_task_run_cannot_assert_the_signals_product(self, _name: str, asserted_product: str):+ # `signals` is what the per-report task cap counts, so a client that could assert it+ # would fill another report's discussion allowance with its own tasks — permanently,+ # since the log is append-only. The padded case is the one a raw comparison misses:+ # content validation strips the value before it is stored, so it lands as `signals`.+ report = self._create_report()+ task = Task.objects.create(+ team=self.team, title="t", description="d", origin_product=Task.OriginProduct.SIGNAL_REPORT+ )++ response = self.client.post(+ self._list_url(str(report.id)),+ data=json.dumps(+ {+ "artefact_type": "task_run",+ "content": {"task_id": str(task.id), "product": asserted_product, "type": "discussion"},+ }+ ),+ content_type="application/json",+ )+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+ assert not SignalReportArtefact.objects.filter(+ report=report, type=SignalReportArtefact.ArtefactType.TASK_RUN+ ).exists()++ # The default namespace still associates the task, which is what agents actually need.+ allowed = self.client.post(+ self._list_url(str(report.id)),+ data=json.dumps({"artefact_type": "task_run", "content": {"task_id": str(task.id)}}),+ content_type="application/json",+ )+ assert allowed.status_code in (status.HTTP_200_OK, status.HTTP_201_CREATED), allowed.json()+ assert (+ json.loads(+ SignalReportArtefact.objects.get(report=report, type=SignalReportArtefact.ArtefactType.TASK_RUN).content+ )["product"]+ == "tasks"+ )+def test_delete_task_run_artefact_is_rejected(self):# The work log is what the per-report task cap counts; a deletable log would let a# client at the cap free its own slots.diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex cd148dd20eb5..ed84d0482567 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -68,6 +68,7 @@ from posthog.user_permissions import UserPermissionsfrom products.data_warehouse.backend.facade.api import trigger_external_data_workflowfrom products.signals.backend.artefact_schemas import (NON_WRITABLE_ARTEFACT_TYPES,+ SIGNALS_PRODUCT,ArtefactContentValidationError,Dismissal,SuggestedReviewers,@@ -3387,6 +3388,24 @@ class SignalReportArtefactViewSet(status=status.HTTP_400_BAD_REQUEST,)content = {**content, "task_id": str(task_id)}+ asserted_product = content.get("product")+ if isinstance(asserted_product, str) and asserted_product.strip() == SIGNALS_PRODUCT:+ # `signals` is the built-in pipeline's own namespace, and it is what the+ # per-report task cap counts. A client that could assert it would be able to fill+ # another report's discussion allowance with associations to arbitrary tasks of+ # its own, permanently — the log is append-only. Server-side writers reach+ # `append_task_run_artefact` in-process and never come through here; custom agents+ # carry their own identifier pair. Mirrors the tasks write serializer, which+ # rejects the pipeline's reserved relationship labels for the same reason.+ #+ # Compared on the stripped value because `identifier_part_must_be_routing_safe`+ # strips before storing, so an unstripped comparison would let `" signals "` land+ # in the reserved namespace. The regex it then applies rejects every other+ # variation, so whitespace is the only normalization the two sides must agree on.+ return Response(+ {"error": f"content.product '{SIGNALS_PRODUCT}' is reserved for server-created runs."},+ status=status.HTTP_400_BAD_REQUEST,+ )content.setdefault("product", "tasks")content.setdefault("type", "agent_run")existing = (diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex cd5e3d4c36c4..e231ec1d324c 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -5831,6 +5831,9 @@ def run_task(``TaskRunResult`` carrying the refreshed task detail DTO or a structured error. The usagegate (429) is applied by the view before calling this."""+ from products.signals.backend.task_run_artefacts import ( # noqa: PLC0415 — cross-product read kept off the api import path+ enforce_report_implementation_rerun_cap,+ )from products.tasks.backend.logic.services.staged_artifacts import get_task_staged_artifacts # noqa: PLC0415from products.tasks.backend.temporal.process_task.utils import ( # noqa: PLC0415 — keep temporalio off the api import pathPrAuthorshipMode,@@ -5844,6 +5847,20 @@ def run_task(task = _visible_task_qs(team_id, user_id, for_control=True).filter(id=task_id).first()if task is None:return None+ report_id_for_slot_check = (+ str(task.signal_report_id)+ if task.signal_report_id and task.origin_product == Task.OriginProduct.SIGNAL_REPORT+ else None+ )+ if report_id_for_slot_check is not None:+ # Ahead of the warm-run reuse below, which returns early: a task released its slot when+ # its runs all failed, so another implementation may hold it by now. Refusing here also+ # avoids the sandbox and repository lookups a doomed run would otherwise do first. The+ # check that actually holds the slot is the one wrapping `create_run` below.+ with transaction.atomic():+ enforce_report_implementation_rerun_cap(+ team_id=team_id, report_id=report_id_for_slot_check, task_id=str(task.id)+ )mode = validated_data.get("mode", "background")branch = validated_data.get("branch")resume_from_run_id = validated_data.get("resume_from_run_id")@@ -6146,7 +6163,18 @@ def run_task()logger.info("Creating task run for task %s with mode=%s, branch=%s", task.id, mode, branch)- task_run = task.create_run(mode=mode, branch=branch, extra_state=extra_state)+ with transaction.atomic():+ task_run = task.create_run(mode=mode, branch=branch, extra_state=extra_state)+ if report_id_for_slot_check is not None:+ # A live run is what marks the report's implementation slot taken, so the slot is only+ # really claimed once this row exists. Inserting first and locking the report second+ # keeps the row lock off `create_run`, which evaluates a feature flag, and still+ # serializes against a concurrent create: that create either takes the report lock+ # first, so this check sees the task it added and rolls the run back, or takes it+ # second, by which point this run is committed and its own count check refuses.+ enforce_report_implementation_rerun_cap(+ team_id=team_id, report_id=report_id_for_slot_check, task_id=str(task.id)+ )if is_pi_task and resume_from_run_id:task_run.active_task_session = previous_run.active_task_sessiontask_run.save(update_fields=["active_task_session", "updated_at"])diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex b9a1fc38072b..2205eca15cb3 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -561,16 +561,22 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):except ComputeBillingLimitExceeded as error:return compute_quota_limit_response(error.reason)except ReportTaskCapExceeded as error:- # `code` distinguishes this from the compute-quota 429 for frontend handling.- return Response(- TaskRunErrorResponseSerializer(- {"type": "rate_limit", "code": "signal_report_task_cap", "error": error.detail}- ).data,- status=status.HTTP_429_TOO_MANY_REQUESTS,- )+ return self._report_task_cap_response(error.detail)self._forward_signals_discussion_note(request, task, relationship)return Response(TaskSerializer(task).data, status=status.HTTP_201_CREATED)+ def _report_task_cap_response(self, detail: str) -> Response:+ """429 for a report that has spent its task allowance, on both create and run.++ `code` distinguishes this from the compute-quota 429 for frontend handling.+ """+ return Response(+ TaskRunErrorResponseSerializer(+ {"type": "rate_limit", "code": "signal_report_task_cap", "error": detail}+ ).data,+ status=status.HTTP_429_TOO_MANY_REQUESTS,+ )+def _forward_signals_discussion_note(self, request, task: tasks_contracts.TaskDetailDTO, relationship: str | None) -> None:@@ -932,7 +938,11 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):),404: OpenApiResponse(description="Task not found"),429: OpenApiResponse(- response=TaskRunErrorResponseSerializer, description="Team is over its posthog_code usage limit"+ response=TaskRunErrorResponseSerializer,+ description=(+ "Team is over its posthog_code usage limit, or the task's signal report has "+ "reached its task limit (code `signal_report_task_cap`)"+ ),),},summary="Run task",@@ -959,7 +969,16 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):if limit_response := usage_limit_response(request.user, self.team_id):return limit_response- result = tasks_facade.run_task(pk, self.team_id, self._user_id(), validated_data=dict(request.validated_data))+ from products.signals.backend.facade.api import ( # noqa: PLC0415 — keeps the signals stack off this module's import path+ ReportTaskCapExceeded,+ )++ try:+ result = tasks_facade.run_task(+ pk, self.team_id, self._user_id(), validated_data=dict(request.validated_data)+ )+ except ReportTaskCapExceeded as error:+ return self._report_task_cap_response(error.detail)if result is None:raise NotFound()if result.error is not None:diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex e25bdbec01f5..5c017cbdd710 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -2098,6 +2098,62 @@ class TestTaskAPI(BaseTaskAPITest):self.assertEqual(response.json()["code"], "signal_report_task_cap")self.assertFalse(Task.objects.filter(title="Report task").exists())+ @parameterized.expand(+ [+ # Another task took the slot this one released, so rerunning would make two live+ # implementations for the report.+ ("another_task_holds_the_slot", True, True),+ # Nothing else claimed it, so the ordinary "my run failed, try again" path stands.+ ("reclaims_its_own_released_slot", False, False),+ ]+ )+ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_rerunning_a_released_implementation_rechecks_the_report_slot(+ self, _name, create_second_task, expect_refused, mock_workflow+ ):+ from products.signals.backend.models import SignalReport++ report = SignalReport.objects.create(team=self.team)+ # Every run failed without a PR, which releases the slot for a second implementation.+ task = self._create_implementation_task_with_runs(report, [("failed", None), ("failed", None)])+ if create_second_task:+ self.assertEqual(+ self._post_signal_report_task(report.id, "implementation").status_code, status.HTTP_201_CREATED+ )++ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/run/")++ if expect_refused:+ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)+ self.assertEqual(response.json()["code"], "signal_report_task_cap")+ mock_workflow.assert_not_called()+ else:+ self.assertNotEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)++ @patch("products.tasks.backend.temporal.client.execute_task_processing_workflow")+ def test_rerun_refuses_when_the_slot_is_taken_after_the_preflight_check(self, mock_workflow):+ from products.signals.backend.models import SignalReport++ report = SignalReport.objects.create(team=self.team)+ task = self._create_implementation_task_with_runs(report, [("failed", None)])+ original_create_run = Task.create_run++ def claim_the_slot_then_create_the_run(task_being_run, *args, **kwargs):+ # Stands in for a create that lands in the window between the pre-flight check and+ # the run insert that claims the slot. Only a check holding the report lock across+ # the insert catches it, so removing that check turns this back into two live+ # implementations for one report.+ self._post_signal_report_task(report.id, "implementation")+ return original_create_run(task_being_run, *args, **kwargs)++ with patch.object(Task, "create_run", autospec=True, side_effect=claim_the_slot_then_create_the_run):+ response = self.client.post(f"/api/projects/@current/tasks/{task.id}/run/")++ self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)+ self.assertEqual(response.json()["code"], "signal_report_task_cap")+ mock_workflow.assert_not_called()+ self.assertFalse(TaskRun.objects.filter(task=task, status=TaskRun.Status.QUEUED).exists())+def test_discussion_task_cap_per_report_counts_free_form_labels(self):from products.signals.backend.models import SignalReportfrom products.signals.backend.task_run_artefacts import MAX_DISCUSSION_TASKS_PER_REPORTdiff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.pyindex 3b581d3c697a..a5c55dddde5b 100644--- a/services/llm-gateway/src/llm_gateway/products/config.py+++ b/services/llm-gateway/src/llm_gateway/products/config.py@@ -436,8 +436,6 @@ INTERNAL_RUN_SCOPE: Final[str] = "internal_run:read"# it can't be self-granted. Used to pick the budget, never to grant access.INTERACTIVE_RUN_SCOPE: Final[str] = "interactive_run:read"-SIGNALS_PRODUCT: Final[str] = "signals"-# Not a product: no caller can declare it, and it never appears in PRODUCTS. It only names a# budget in product_cost_limits / user_cost_limits, resolved from the token by resolve_cost_key.SIGNALS_INTERACTIVE_COST_KEY: Final[str] = "signals_interactive"@@ -510,11 +508,16 @@ def resolve_cost_key(product: str, scopes: list[str] | None) -> str:Their volume has different owners — ours and the customer's — so they get separate budgets,resolved from the token's own provenance marker rather than from the product the callerdeclared, which a sandbox is free to choose.++ The marker decides alone, without also requiring the declared product to be `signals`: a run+ whose token still comes from the Array app (the fallback while a region has no Signals app+ row) can declare `posthog_code` or `background_agents` instead, and pairing the two would let+ that choice move the run off the interactive budget and out of the per-run spend ceiling.+ Only interactive Signals runs are ever minted with the scope, so keying on it is sufficient."""- resolved = resolve_product_alias(product)- if resolved == SIGNALS_PRODUCT and INTERACTIVE_RUN_SCOPE in (scopes or []):+ if INTERACTIVE_RUN_SCOPE in (scopes or []):return SIGNALS_INTERACTIVE_COST_KEY- return resolved+ return resolve_product_alias(product)def check_product_access(diff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py b/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.pyindex f113cf565f48..d1376734bb43 100644--- a/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/cost_throttles.py@@ -253,8 +253,19 @@ class _UserCostThrottleBase(CostThrottle):return DEFAULT_USER_COST_LIMITreturn config+ def _is_exempt(self, context: ThrottleContext) -> bool:+ """Whether this request meters against the posthog_code budget, which billable credits+ cover instead of a per-user cost limit.++ Keyed on the resolved cost key rather than the declared product, for the same reason+ `_cost_key` is: a Signals run holding an Array-app token declares `posthog_code`, and+ reading the declaration here would hand it this exemption and leave the interactive+ budget its spend is keyed to unenforced.+ """+ return self._cost_key(context) == POSTHOG_CODE_PRODUCT+async def allow_request(self, context: ThrottleContext) -> ThrottleResult:- if not context.end_user_id or context.product == POSTHOG_CODE_PRODUCT:+ if not context.end_user_id or self._is_exempt(context):return ThrottleResult.allow()if is_usage_unlimited(context.user):return ThrottleResult.allow()@@ -265,7 +276,7 @@ class _UserCostThrottleBase(CostThrottle):return await super().allow_request(context)async def get_status(self, context: ThrottleContext) -> CostStatus:- if context.product == POSTHOG_CODE_PRODUCT or is_usage_unlimited(context.user):+ if self._is_exempt(context) or is_usage_unlimited(context.user):# Staff have no per-user cap: report an effectively unlimited budget# so the usage endpoint computes 0% used and never flags the user as# rate limited. `float("inf")` never crosses the wire — only@@ -281,7 +292,7 @@ class _UserCostThrottleBase(CostThrottle):return await super().get_status(context)async def record_cost(self, context: ThrottleContext, cost: float) -> None:- if not context.end_user_id or context.product == POSTHOG_CODE_PRODUCT:+ if not context.end_user_id or self._is_exempt(context):returnawait super().record_cost(context, cost)diff --git a/services/llm-gateway/tests/test_cost_throttles.py b/services/llm-gateway/tests/test_cost_throttles.pyindex 6c8eef114013..89c631f468bd 100644--- a/services/llm-gateway/tests/test_cost_throttles.py+++ b/services/llm-gateway/tests/test_cost_throttles.py@@ -1281,11 +1281,16 @@ class TestSignalsInteractiveCostKey:[("signals", ["llm_gateway:read", "interactive_run:read"], "signals_interactive"),("signals", ["llm_gateway:read"], "signals"),- ("posthog_code", ["llm_gateway:read", "interactive_run:read"], "posthog_code"),- ("background_agents", ["llm_gateway:read", "interactive_run:read"], "background_agents"),+ ("posthog_code", ["llm_gateway:read"], "posthog_code"),+ ("background_agents", ["llm_gateway:read"], "background_agents"),+ # The marker alone decides. A run still holding an Array-app token can declare either+ # of these routes, and honouring the declaration would drop it off the interactive+ # budget and out of the per-run ceiling, which only `signals_interactive` configures.+ ("posthog_code", ["llm_gateway:read", "interactive_run:read"], "signals_interactive"),+ ("background_agents", ["llm_gateway:read", "interactive_run:read"], "signals_interactive"),],)- def test_only_a_marked_signals_token_meters_against_the_interactive_budget(+ def test_only_a_marked_token_meters_against_the_interactive_budget(self, product: str, scopes: list[str], expected: str) -> None:assert resolve_cost_key(product, scopes) == expected@@ -1301,6 +1306,20 @@ class TestSignalsInteractiveCostKey:assert await recorded_cost(throttle, pipeline) == 5.0assert await recorded_cost(throttle, interactive) == 0.0+ @pytest.mark.asyncio+ async def test_marked_run_declaring_posthog_code_keeps_its_user_budget(self) -> None:+ # posthog_code is exempt from per-user cost limits because billable credits meter it+ # instead. Reading that exemption off the declared product would hand it to a marked run+ # on an Array-app token, which spends against `signals_interactive`.+ throttle = UserCostBurstThrottle(redis=None)+ context = make_context(product="posthog_code", user=make_signals_user(interactive=True))+ limit, _ = throttle._get_limit_and_window(context)++ await throttle.record_cost(context, limit)++ assert await recorded_cost(throttle, context) == limit+ assert (await throttle.allow_request(context)).allowed is False+class TestSandboxTaskCostThrottle:@pytest.mark.asyncio