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(approvals): count failed change request inserts (#102563)

Phil Haack6b65aecdfd17
diff --git a/products/approvals/backend/decorators.py b/products/approvals/backend/decorators.py
index c053768c356a..54a4a633eb8e 100644
--- a/products/approvals/backend/decorators.py
+++ b/products/approvals/backend/decorators.py
@@ -9,6 +9,7 @@ from django.core.serializers.json import DjangoJSONEncoder
from django.db import transaction
from django.utils import timezone
+from prometheus_client import Counter
from rest_framework import status
from rest_framework.exceptions import APIException, PermissionDenied, ValidationError
from rest_framework.response import Response
@@ -26,6 +27,23 @@ from products.approvals.backend.serializers import ChangeRequestSerializer
logger = logging.getLogger(__name__)
+# ChangeRequest creates that raised inside the approval gate. The caller always gets
+# "Failed to create approval request", but that message does not tell a responder
+# whether the row exists. The counted block covers get_display_data (before the
+# insert), the insert itself, and the post-insert analytics call. A failure before or
+# in the insert leaves no row. A failure in the analytics call can leave a PENDING
+# row, unless an enclosing transaction rolls the insert back. A responder must check
+# for a PENDING request before advising a retry. The on_commit notification is only
+# queued here, not run. It cannot raise inside this block. Drives the
+# ApprovalsChangeRequestCreateFailing alert in PostHog/charts.
+# error_type carries the exception class name only, because the message would make the
+# label unbounded.
+CHANGE_REQUEST_CREATE_FAILURE_COUNTER = Counter(
+ "posthog_approvals_change_request_create_failures_total",
+ "ChangeRequest creations that failed inside the approval gate",
+ labelnames=["action", "error_type"],
+)
+
@dataclass
class GateResult:
@@ -353,6 +371,7 @@ def _evaluate_gate(
extra={"action": action_class.key, "error": str(e), "error_type": type(e).__name__},
exc_info=True,
)
+ CHANGE_REQUEST_CREATE_FAILURE_COUNTER.labels(action=action_class.key, error_type=type(e).__name__).inc()
error_msg = (
f"Failed to create approval request: {type(e).__name__}: {str(e)}"
if settings.DEBUG
diff --git a/products/approvals/backend/tests/test_decorators.py b/products/approvals/backend/tests/test_decorators.py
index 556049518aa5..72090c429260 100644
--- a/products/approvals/backend/tests/test_decorators.py
+++ b/products/approvals/backend/tests/test_decorators.py
@@ -7,6 +7,9 @@ from unittest.mock import MagicMock, patch
from django.utils import timezone
+from prometheus_client import REGISTRY
+from rest_framework.exceptions import APIException
+
from posthog.api.utils import ServiceRequest
from products.approvals.backend.decorators import _create_change_request
@@ -16,11 +19,8 @@ from products.feature_flags.backend.api.feature_flag import FeatureFlagSerialize
from products.feature_flags.backend.models.feature_flag import FeatureFlag
-@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
-class TestApprovalGateFailsClosed(APIBaseTest):
- """The gate must derive team/org from the serializer instance when the
- context lacks get_team/get_organization callables, instead of silently
- skipping the approval workflow (fail-closed, not fail-open)."""
+class _ApprovalGateFixtures(APIBaseTest):
+ """Shared fixtures for gating a feature flag save behind an approval policy."""
def _create_disabled_flag(self) -> FeatureFlag:
return FeatureFlag.objects.create(
@@ -55,6 +55,13 @@ class TestApprovalGateFailsClosed(APIBaseTest):
serializer.is_valid()
return serializer
+
+@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+class TestApprovalGateFailsClosed(_ApprovalGateFixtures):
+ """The gate must derive team/org from the serializer instance when the
+ context lacks get_team/get_organization callables, instead of silently
+ skipping the approval workflow (fail-closed, not fail-open)."""
+
def test_gate_blocks_when_context_lacks_org_and_team_callables(self, _mock_enabled):
flag = self._create_disabled_flag()
self._create_enable_policy()
@@ -195,3 +202,49 @@ class TestChangeRequestIntentIsJsonSafe(APIBaseTest):
stored = change_request.intent["full_request_data"]["last_called_at"]
assert isinstance(stored, str), "the datetime must be rendered, not handed to psycopg as-is"
assert abs(datetime.fromisoformat(stored) - called_at) < timedelta(milliseconds=1)
+
+
+@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+class TestChangeRequestCreateFailureCounter(_ApprovalGateFixtures):
+ def _failures(self, action: str, error_type: str) -> float:
+ return (
+ REGISTRY.get_sample_value(
+ "posthog_approvals_change_request_create_failures_total",
+ {"action": action, "error_type": error_type},
+ )
+ or 0.0
+ )
+
+ def _gated_serializer(self) -> FeatureFlagSerializer:
+ flag = self._create_disabled_flag()
+ self._create_enable_policy()
+ request = self._drf_request({"active": True})
+ return self._serializer(
+ flag,
+ {"active": True},
+ {
+ "request": request,
+ "team_id": self.team.id,
+ "project_id": self.team.project_id,
+ "get_team": lambda: self.team,
+ "get_organization": lambda: self.organization,
+ },
+ )
+
+ def test_failed_change_request_insert_increments_the_counter(self, _mock_enabled):
+ serializer = self._gated_serializer()
+ before = self._failures("feature_flag.enable", "TypeError")
+
+ # Patching the ORM boundary rather than _create_change_request keeps the helper's
+ # own display-data, expiry and JSON-safe steps in the path, so the no-row assertion
+ # below covers code that actually runs.
+ with patch.object(
+ ChangeRequest.objects,
+ "create",
+ side_effect=TypeError("Object of type datetime is not JSON serializable"),
+ ):
+ with self.assertRaises(APIException):
+ serializer.save()
+
+ assert self._failures("feature_flag.enable", "TypeError") == before + 1
+ assert ChangeRequest.objects.count() == 0