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(error-tracking): add rate-limit bypass rules (#67011)

Aleksander Błaszkiewicz92deee513c1a
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yaml
index 9a6c3344e836..b82121303024 100644
--- a/.semgrep/rules/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/idor-team-scoped-models.yaml
@@ -122,6 +122,7 @@ rules:
|EnterprisePropertyDefinition
|EventFilterConfig
|ErrorTrackingAssignmentRule
+ |ErrorTrackingBypassRule
|ErrorTrackingGroupingRule
|ErrorTrackingIssue
|ErrorTrackingIssueFingerprintV2
@@ -393,6 +394,7 @@ rules:
|EnterprisePropertyDefinition
|EventFilterConfig
|ErrorTrackingAssignmentRule
+ |ErrorTrackingBypassRule
|ErrorTrackingGroupingRule
|ErrorTrackingIssue
|ErrorTrackingIssueFingerprintV2
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index bbed37c4b1ab..c1fc29ce6a70 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6525,9 +6525,9 @@ snapshots:
scenes-app-settings-environment--settings-environment-error-tracking--light:
hash: v1.k794b7964.d2eb44367a4f4e948d2c45e4ad089bdfd0929ae4e1e6ae0e79c624a3a1d8d90f.IWh0_HTcd0w3UEmbt5VOFHToiunPwoEZDRHLYkGKc6c
scenes-app-settings-environment--settings-environment-error-tracking-configuration--dark:
- hash: v1.k794b7964.c030607be142741290a17194eb5a53592b076cbbdda3d70b81ccef75cc9b6c22.hF0RJI0j4NAOVdWGJwOGpip8ckZRCUqgT1rdlGW3YqY
+ hash: v1.k794b7964.42e7194f3f699e0e1c6b3d1365af45ab9456df7c0f701e581a0552a957ea01df.7iaWNb9in0lKwH4twmtNliVTeJ9Nu7uUGlt3NcJrGuA
scenes-app-settings-environment--settings-environment-error-tracking-configuration--light:
- hash: v1.k794b7964.2f40238b917b2e66cf31cca3dbe5c92a33d5f1c5eb0d1645a4178f87cd789580.9Y8shA4VVl68EO_EkKUyYwRr3yBNPd-w1EgPr3VTQhY
+ hash: v1.k794b7964.c092afb7f5eadc1db95ba9c8319f042adcf796e638181cb692ce0ea3c04d5a9d.frfFNTzuk-B2qahYl5KrtG3OMivCmCG3ZFLx2JzOyuo
scenes-app-settings-environment--settings-environment-feature-flags--dark:
hash: v1.k794b7964.4a627c125b4196ab9adfe9389e8fa20e9ba68c9110af68d1087ac9b6325da406.WVq_ojXXs-K3q725sJPCE3y4bmi1S_bf1T72JHY5vvE
scenes-app-settings-environment--settings-environment-feature-flags--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 91cfa1f4123e..a18db23e7f0b 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -297,6 +297,7 @@ export const FEATURE_FLAGS = {
ERROR_TRACKING_ISSUE_CORRELATION: 'error-tracking-issue-correlation', // owner: @david #team-error-tracking
ERROR_TRACKING_ISSUE_SPLITTING: 'error-tracking-issue-splitting', // owner: @david #team-error-tracking
ERROR_TRACKING_RATE_LIMITING: 'error-tracking-rate-limiting', // owner: @ablaszkiewicz #team-error-tracking
+ ERROR_TRACKING_RATE_LIMITING_BYPASS: 'error-tracking-rate-limiting-bypass', // owner: @ablaszkiewicz #team-error-tracking
ERROR_TRACKING_RATE_LIMITING_PER_ISSUE: 'error-tracking-rate-limiting-per-issue', // owner: @ablaszkiewicz #team-error-tracking
ERROR_TRACKING_RECOMMENDATIONS: 'error-tracking-recommendations', // owner: @ablaszkiewicz #team-error-tracking
ERROR_TRACKING_RELATED_ISSUES: 'error-tracking-related-issues', // owner: #team-error-tracking
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index 79309c83fb8e..14736345aedc 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -499,7 +499,7 @@ export const SETTINGS_MAP: SettingSection[] = [
title: 'Rate limits',
component: <RateLimitSettings />,
flag: 'ERROR_TRACKING_RATE_LIMITING',
- keywords: ['rate', 'limit', 'throttle', 'ingestion', 'cap'],
+ keywords: ['rate', 'limit', 'throttle', 'ingestion', 'cap', 'bypass'],
},
{
id: 'error-tracking-auto-assignment',
diff --git a/posthog/models/scoping/baseline_unmigrated.txt b/posthog/models/scoping/baseline_unmigrated.txt
index 08c38277ac95..277f750ee051 100644
--- a/posthog/models/scoping/baseline_unmigrated.txt
+++ b/posthog/models/scoping/baseline_unmigrated.txt
@@ -57,6 +57,7 @@ Endpoint
EnterpriseEventDefinition
EnterprisePropertyDefinition
ErrorTrackingAssignmentRule
+ErrorTrackingBypassRule
ErrorTrackingGroupingRule
ErrorTrackingIssue
ErrorTrackingIssueFingerprintV2
diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.py
index 115c351245cd..e1f074c3cccd 100644
--- a/products/error_tracking/backend/facade/api.py
+++ b/products/error_tracking/backend/facade/api.py
@@ -463,6 +463,46 @@ def get_client_safe_suppression_rules(team_id: int) -> list[dict]:
return logic.get_client_safe_suppression_rules(team_id)
+def _to_bypass_rule(rule) -> contracts.ErrorTrackingBypassRule:
+ return contracts.ErrorTrackingBypassRule(
+ id=rule.id,
+ filters=rule.filters,
+ order_key=rule.order_key,
+ disabled_data=rule.disabled_data,
+ created_at=rule.created_at,
+ updated_at=rule.updated_at,
+ )
+
+
+def list_bypass_rules(team_id: int) -> list[contracts.ErrorTrackingBypassRule]:
+ return [_to_bypass_rule(rule) for rule in logic.list_bypass_rules(team_id)]
+
+
+def get_bypass_rule(team_id: int, rule_id: str) -> contracts.ErrorTrackingBypassRule | None:
+ rule = logic.get_bypass_rule(team_id, rule_id)
+ return _to_bypass_rule(rule) if rule is not None else None
+
+
+def create_bypass_rule(team_id: int, *, filters: dict) -> contracts.ErrorTrackingBypassRule:
+ rule = logic.create_bypass_rule(team_id, filters=filters)
+ return _to_bypass_rule(rule)
+
+
+def update_bypass_rule(
+ team_id: int, rule_id: str, *, filters: dict | None = None
+) -> contracts.ErrorTrackingBypassRule | None:
+ rule = logic.update_bypass_rule(team_id, rule_id, filters=filters)
+ return _to_bypass_rule(rule) if rule is not None else None
+
+
+def delete_bypass_rule(team_id: int, rule_id: str) -> bool:
+ return logic.delete_bypass_rule(team_id, rule_id)
+
+
+def reorder_bypass_rules(team_id: int, orders: dict[str, int]) -> None:
+ logic.reorder_bypass_rules(team_id, orders)
+
+
def get_issue_id_for_fingerprint(team_id: int, fingerprint: str) -> UUID | None:
return logic.get_issue_id_for_fingerprint(team_id=team_id, fingerprint=fingerprint)
diff --git a/products/error_tracking/backend/facade/contracts.py b/products/error_tracking/backend/facade/contracts.py
index 8d51144f16f3..cc5c7108f0f1 100644
--- a/products/error_tracking/backend/facade/contracts.py
+++ b/products/error_tracking/backend/facade/contracts.py
@@ -210,6 +210,16 @@ class ErrorTrackingSuppressionRule:
updated_at: datetime
+@dataclass(frozen=True)
+class ErrorTrackingBypassRule:
+ id: UUID
+ filters: dict
+ order_key: int
+ disabled_data: dict | None
+ created_at: datetime
+ updated_at: datetime
+
+
@dataclass(frozen=True)
class ErrorTrackingIssueBasics:
id: UUID
diff --git a/products/error_tracking/backend/logic/__init__.py b/products/error_tracking/backend/logic/__init__.py
index 960fd5152767..dfd7fd33cd6a 100644
--- a/products/error_tracking/backend/logic/__init__.py
+++ b/products/error_tracking/backend/logic/__init__.py
@@ -15,6 +15,7 @@ from posthog.models.utils import UUIDT
from products.error_tracking.backend.models import (
ErrorTrackingAssignmentRule,
+ ErrorTrackingBypassRule,
ErrorTrackingExternalReference,
ErrorTrackingGroupingRule,
ErrorTrackingIssue,
@@ -526,6 +527,7 @@ def match_all_bytecode() -> list[Any]:
_ReorderableRule = TypeVar(
"_ReorderableRule",
ErrorTrackingAssignmentRule,
+ ErrorTrackingBypassRule,
ErrorTrackingGroupingRule,
ErrorTrackingSuppressionRule,
)
@@ -716,6 +718,49 @@ def reorder_suppression_rules(team_id: int, orders: dict[str, int]) -> None:
_reorder_rules(ErrorTrackingSuppressionRule, team_id, orders)
+def list_bypass_rules(team_id: int) -> QuerySet[ErrorTrackingBypassRule]:
+ return ErrorTrackingBypassRule.objects.filter(team_id=team_id).order_by("order_key")
+
+
+def get_bypass_rule(team_id: int, rule_id: str) -> ErrorTrackingBypassRule | None:
+ return ErrorTrackingBypassRule.objects.filter(team_id=team_id, id=rule_id).first()
+
+
+def create_bypass_rule(team_id: int, *, filters: dict) -> ErrorTrackingBypassRule:
+ return ErrorTrackingBypassRule.objects.create(
+ team_id=team_id,
+ filters=filters,
+ bytecode=_rule_bytecode(team_id, filters),
+ order_key=0,
+ )
+
+
+def update_bypass_rule(
+ team_id: int,
+ rule_id: str,
+ *,
+ filters: dict | None = None,
+) -> ErrorTrackingBypassRule | None:
+ rule = get_bypass_rule(team_id, rule_id)
+ if rule is None:
+ return None
+ if filters is not None:
+ rule.filters = filters
+ rule.bytecode = _rule_bytecode(team_id, filters)
+ rule.disabled_data = None
+ rule.save()
+ return rule
+
+
+def delete_bypass_rule(team_id: int, rule_id: str) -> bool:
+ deleted, _ = ErrorTrackingBypassRule.objects.filter(team_id=team_id, id=rule_id).delete()
+ return deleted > 0
+
+
+def reorder_bypass_rules(team_id: int, orders: dict[str, int]) -> None:
+ _reorder_rules(ErrorTrackingBypassRule, team_id, orders)
+
+
def get_client_safe_filters(filters: dict) -> dict | None:
"""Return the filters if every leaf is client-safe, otherwise None.
diff --git a/products/error_tracking/backend/migrations/0019_errortrackingbypassrule.py b/products/error_tracking/backend/migrations/0019_errortrackingbypassrule.py
new file mode 100644
index 000000000000..8a96cfbfbf4b
--- /dev/null
+++ b/products/error_tracking/backend/migrations/0019_errortrackingbypassrule.py
@@ -0,0 +1,48 @@
+# Generated by Django 5.2.14 on 2026-06-30 11:49
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.models.utils
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("error_tracking", "0018_symbolset_last_used_created_idx"),
+ ("posthog", "1245_duckgres_sink_schema_state"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="ErrorTrackingBypassRule",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.models.utils.UUIDT,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("filters", models.JSONField()),
+ ("bytecode", models.JSONField(blank=True, null=True)),
+ ("disabled_data", models.JSONField(blank=True, null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ ("order_key", models.IntegerField()),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "posthog_errortrackingbypassrule",
+ "indexes": [models.Index(fields=["team_id"], name="posthog_err_team_id_ba5150_idx")],
+ },
+ ),
+ ]
diff --git a/products/error_tracking/backend/migrations/max_migration.txt b/products/error_tracking/backend/migrations/max_migration.txt
index 1db1292b408f..bccd12207561 100644
--- a/products/error_tracking/backend/migrations/max_migration.txt
+++ b/products/error_tracking/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0018_symbolset_last_used_created_idx
+0019_errortrackingbypassrule
diff --git a/products/error_tracking/backend/models.py b/products/error_tracking/backend/models.py
index 0b7698596945..1553812f0b6d 100644
--- a/products/error_tracking/backend/models.py
+++ b/products/error_tracking/backend/models.py
@@ -434,6 +434,30 @@ class ErrorTrackingSuppressionRule(UUIDTModel):
# ]
+class ErrorTrackingBypassRule(UUIDTModel):
+ # Bypass rules exempt matching exception events from rate limiting. When an incoming event
+ # matches an enabled rule, Cymbal keeps it and charges no rate-limit tokens (neither the
+ # per-issue nor the project bucket), recording a "bypassed" status instead of
+ # "allowed"/"rate_limited". They are evaluated only inside the rate-limiting stage and never
+ # affect suppression, which runs earlier.
+ # db_constraint=False keeps the create lock-free on posthog_team (a hot table); team scoping
+ # is enforced at the ORM layer and Cymbal reads by team_id via raw SQL.
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False)
+ filters = models.JSONField(null=False, blank=False) # The json object describing the filter rule
+ bytecode = models.JSONField(null=True, blank=True)
+ disabled_data = models.JSONField(null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+ # Bypass rules are ordered, and greedily evaluated
+ order_key = models.IntegerField(null=False, blank=False)
+
+ class Meta:
+ indexes = [
+ models.Index(fields=["team_id"]),
+ ]
+ db_table = "posthog_errortrackingbypassrule"
+
+
class ErrorTrackingAutoCaptureControls(UUIDTModel):
"""
Controls for error tracking autocapture behavior.
diff --git a/products/error_tracking/backend/presentation/views/__init__.py b/products/error_tracking/backend/presentation/views/__init__.py
index 778dbdccfcd2..76796ba5f9f7 100644
--- a/products/error_tracking/backend/presentation/views/__init__.py
+++ b/products/error_tracking/backend/presentation/views/__init__.py
@@ -1,4 +1,5 @@
from products.error_tracking.backend.presentation.views.assignment_rules import ErrorTrackingAssignmentRuleViewSet
+from products.error_tracking.backend.presentation.views.bypass_rules import ErrorTrackingBypassRuleViewSet
from products.error_tracking.backend.presentation.views.external_references import ErrorTrackingExternalReferenceViewSet
from products.error_tracking.backend.presentation.views.fingerprints import ErrorTrackingFingerprintViewSet
from products.error_tracking.backend.presentation.views.git_provider_file_link_resolver import (
@@ -33,5 +34,6 @@ __all__ = [
"ErrorTrackingSpikeEventViewSet",
"ErrorTrackingSuppressionRuleViewSet",
"ErrorTrackingAssignmentRuleViewSet",
+ "ErrorTrackingBypassRuleViewSet",
"GitProviderFileLinksViewSet",
]
diff --git a/products/error_tracking/backend/presentation/views/bypass_rules.py b/products/error_tracking/backend/presentation/views/bypass_rules.py
new file mode 100644
index 000000000000..b9a4f1c843db
--- /dev/null
+++ b/products/error_tracking/backend/presentation/views/bypass_rules.py
@@ -0,0 +1,161 @@
+import structlog
+import posthoganalytics
+from drf_spectacular.utils import OpenApiResponse, extend_schema_field
+from pydantic import ValidationError as PydanticValidationError
+from rest_framework import serializers, status, viewsets
+from rest_framework.exceptions import NotFound, ValidationError
+from rest_framework.response import Response
+
+from posthog.schema import PropertyGroupFilterValue
+
+from posthog.api.mixins import ValidatedRequest, validated_request
+from posthog.api.routing import TeamAndOrgViewSetMixin
+from posthog.api.utils import action
+from posthog.event_usage import groups
+
+from products.error_tracking.backend.facade import api as error_tracking_api
+
+logger = structlog.get_logger(__name__)
+
+
+class ErrorTrackingBypassRuleSerializer(serializers.Serializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique identifier of the bypass rule.")
+ filters = serializers.JSONField(
+ help_text="Property-group filters that define which incoming error events bypass rate limiting."
+ )
+ order_key = serializers.IntegerField(
+ help_text="Position of the rule in the team's ordered list. Rules are evaluated greedily in ascending order."
+ )
+ disabled_data = serializers.JSONField(
+ allow_null=True,
+ help_text=(
+ "Populated when the rule has been automatically disabled (for example, after its filters failed to "
+ "evaluate during ingestion). Null while the rule is active."
+ ),
+ )
+ created_at = serializers.DateTimeField(read_only=True, help_text="When the rule was created.")
+ updated_at = serializers.DateTimeField(read_only=True, help_text="When the rule was last updated.")
+
+
+@extend_schema_field(PropertyGroupFilterValue) # type: ignore[arg-type]
+class ErrorTrackingBypassRuleFiltersField(serializers.JSONField):
+ def to_internal_value(self, data):
+ value = super().to_internal_value(data)
+
+ if not isinstance(value, dict):
+ raise serializers.ValidationError("Expected an object.")
+
+ # A bypass rule must target specific exceptions. Empty or keyless filters compile to a
+ # match-all rule that bypasses all rate limiting for the project — use the rate limit
+ # settings to disable rate limiting instead of creating a catch-all bypass rule.
+ if not error_tracking_api.has_filter_values(value):
+ raise serializers.ValidationError("A bypass rule must have at least one filter.")
+
+ try:
+ PropertyGroupFilterValue(**value)
+ except (PydanticValidationError, TypeError) as err:
+ logger.warning("Invalid bypass rule filters payload", exc_info=err)
+ raise serializers.ValidationError("Invalid filters payload.") from err
+
+ return value
+
+
+class ErrorTrackingBypassRuleCreateRequestSerializer(serializers.Serializer):
+ filters = ErrorTrackingBypassRuleFiltersField(
+ required=True,
+ help_text=(
+ "Property-group filters that define which incoming error events bypass rate limiting. "
+ "Must contain at least one filter — empty rules are rejected. To stop rate limiting "
+ "entirely, adjust the rate limit settings instead of creating a match-all bypass rule."
+ ),
+ )
+
+
+class ErrorTrackingBypassRuleUpdateRequestSerializer(serializers.Serializer):
+ filters = ErrorTrackingBypassRuleFiltersField(
+ required=False,
+ help_text=(
+ "Property-group filters that define which incoming error events bypass rate limiting. "
+ "Must contain at least one filter. Omit to preserve the existing filters."
+ ),
+ )
+
+
+class ErrorTrackingBypassRuleViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
+ scope_object = "error_tracking"
+ serializer_class = ErrorTrackingBypassRuleSerializer
+
+ def list(self, request, *args, **kwargs) -> Response:
+ rules = error_tracking_api.list_bypass_rules(self.team.id)
+ page = self.paginate_queryset(rules)
+ if page is not None:
+ return self.get_paginated_response(self.get_serializer(page, many=True).data)
+ return Response(self.get_serializer(rules, many=True).data)
+
+ def retrieve(self, request, *args, pk=None, **kwargs) -> Response:
+ rule = error_tracking_api.get_bypass_rule(self.team.id, pk)
+ if rule is None:
+ raise NotFound()
+ return Response(self.get_serializer(rule).data)
+
+ def _apply_rule_update(self, request: ValidatedRequest, pk: str) -> Response:
+ try:
+ rule = error_tracking_api.update_bypass_rule(
+ self.team.id,
+ pk,
+ filters=request.validated_data.get("filters"),
+ )
+ except error_tracking_api.InvalidBytecodeError as err:
+ raise ValidationError(str(err)) from err
+ if rule is None:
+ raise NotFound()
+ posthoganalytics.capture(
+ "error_tracking_bypass_rule_edited",
+ groups=groups(self.team.organization, self.team),
+ )
+ return Response({"ok": True}, status=status.HTTP_204_NO_CONTENT)
+
+ @validated_request(
+ request_serializer=ErrorTrackingBypassRuleUpdateRequestSerializer,
+ responses={204: None},
+ )
+ def update(self, request: ValidatedRequest, *args, pk=None, **kwargs) -> Response:
+ return self._apply_rule_update(request, pk)
+
+ @validated_request(
+ request_serializer=ErrorTrackingBypassRuleUpdateRequestSerializer,
+ responses={204: None},
+ )
+ def partial_update(self, request: ValidatedRequest, *args, pk=None, **kwargs) -> Response:
+ return self._apply_rule_update(request, pk)
+
+ def destroy(self, request, *args, pk=None, **kwargs) -> Response:
+ if not error_tracking_api.delete_bypass_rule(self.team.id, pk):
+ raise NotFound()
+ posthoganalytics.capture(
+ "error_tracking_bypass_rule_deleted",
+ groups=groups(self.team.organization, self.team),
+ )
+ return Response(status=status.HTTP_204_NO_CONTENT)
+
+ @validated_request(
+ request_serializer=ErrorTrackingBypassRuleCreateRequestSerializer,
+ responses={201: OpenApiResponse(response=ErrorTrackingBypassRuleSerializer)},
+ )
+ def create(self, request: ValidatedRequest, *args, **kwargs) -> Response:
+ filters = request.validated_data["filters"]
+ try:
+ rule = error_tracking_api.create_bypass_rule(self.team.id, filters=filters)
+ except error_tracking_api.InvalidBytecodeError as err:
+ raise ValidationError(str(err)) from err
+ posthoganalytics.capture(
+ "error_tracking_bypass_rule_created",
+ groups=groups(self.team.organization, self.team),
+ )
+ return Response(self.get_serializer(rule).data, status=status.HTTP_201_CREATED)
+
+ @action(methods=["PATCH"], detail=False)
+ def reorder(self, request, **kwargs) -> Response:
+ orders: dict[str, int] = request.data.get("orders", {})
+ error_tracking_api.reorder_bypass_rules(self.team.id, orders)
+ return Response({"ok": True}, status=status.HTTP_204_NO_CONTENT)
diff --git a/products/error_tracking/backend/routes.py b/products/error_tracking/backend/routes.py
index 8b4ec41a8bf6..d2e7351892f6 100644
--- a/products/error_tracking/backend/routes.py
+++ b/products/error_tracking/backend/routes.py
@@ -2,6 +2,7 @@ from posthog.api.routing import RouterRegistry
from products.error_tracking.backend.presentation.views import (
ErrorTrackingAssignmentRuleViewSet,
+ ErrorTrackingBypassRuleViewSet,
ErrorTrackingExternalReferenceViewSet,
ErrorTrackingFingerprintViewSet,
ErrorTrackingGroupingRuleViewSet,
@@ -58,6 +59,14 @@ def register_routes(routers: RouterRegistry) -> None:
"project_error_tracking_suppression_rule",
["team_id"],
)
+ # Dual-route (env + project) to match the other rule types: the shared frontend rule API
+ # helper targets the /api/environments/.../error_tracking/<rule_type> path.
+ routers.register_legacy_dual_route(
+ r"error_tracking/bypass_rules",
+ ErrorTrackingBypassRuleViewSet,
+ "project_error_tracking_bypass_rule",
+ ["team_id"],
+ )
routers.register_legacy_dual_route(
r"error_tracking/recommendations",
ErrorTrackingRecommendationViewSet,
diff --git a/products/error_tracking/backend/tests/api/test_bypass_rules.py b/products/error_tracking/backend/tests/api/test_bypass_rules.py
new file mode 100644
index 000000000000..7adff0484a39
--- /dev/null
+++ b/products/error_tracking/backend/tests/api/test_bypass_rules.py
@@ -0,0 +1,140 @@
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+from rest_framework import status
+
+from products.error_tracking.backend.models import ErrorTrackingBypassRule
+
+VALID_FILTERS = {
+ "type": "AND",
+ "values": [
+ {
+ "type": "AND",
+ "values": [
+ {
+ "key": "$exception_type",
+ "type": "event",
+ "value": ["TypeError"],
+ "operator": "exact",
+ }
+ ],
+ }
+ ],
+}
+
+
+class TestBypassRuleAPI(APIBaseTest):
+ def _url(self, rule_id: str | None = None) -> str:
+ base = f"/api/environments/{self.team.id}/error_tracking/bypass_rules/"
+ if rule_id:
+ return f"{base}{rule_id}/"
+ return base
+
+ def test_create_with_valid_filters_compiles_bytecode(self) -> None:
+ response = self.client.post(self._url(), data={"filters": VALID_FILTERS}, format="json")
+
+ assert response.status_code == status.HTTP_201_CREATED, response.json()
+ data = response.json()
+ assert data["filters"] == VALID_FILTERS
+ assert "sampling_rate" not in data
+
+ rule = ErrorTrackingBypassRule.objects.get(id=data["id"])
+ assert rule.bytecode is not None
+ assert len(rule.bytecode) > 0
+
+ def test_create_without_filters_returns_400(self) -> None:
+ response = self.client.post(self._url(), data={}, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "filters"
+ assert not ErrorTrackingBypassRule.objects.exists()
+
+ def test_create_invalid_filters_returns_400(self) -> None:
+ response = self.client.post(self._url(), data={"filters": {"not": "valid"}}, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == "filters"
+
+ @parameterized.expand(
+ [
+ ("empty_values", {"type": "AND", "values": []}),
+ ("empty_object_leaf", {"type": "AND", "values": [{}]}),
+ ("keyless_leaf", {"type": "AND", "values": [{"not": "valid"}]}),
+ ("empty_nested_group", {"type": "AND", "values": [{"type": "AND", "values": []}]}),
+ ]
+ )
+ def test_create_rejects_filters_without_values(self, _name: str, filters: dict) -> None:
+ # An empty or keyless filter would compile to a match-all bypass that disables all rate
+ # limiting for the project — the API must reject it, mirroring the UI's disabled Save button.
+ response = self.client.post(self._url(), data={"filters": filters}, format="json")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "filters"
+ assert not ErrorTrackingBypassRule.objects.exists()
+
+ def test_update_with_empty_filters_returns_400(self) -> None:
+ rule = ErrorTrackingBypassRule.objects.create(team=self.team, filters=VALID_FILTERS, bytecode=[], order_key=0)
+
+ response = self.client.patch(
+ self._url(str(rule.id)), data={"filters": {"type": "AND", "values": []}}, format="json"
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
+ assert response.json()["attr"] == "filters"
+ rule.refresh_from_db()
+ assert rule.filters == VALID_FILTERS
+
+ def test_update_recompiles_bytecode_and_clears_disabled_data(self) -> None:
+ rule = ErrorTrackingBypassRule.objects.create(
+ team=self.team,
+ filters={"type": "AND", "values": []},
+ bytecode=[],
+ order_key=0,
+ disabled_data={"message": "broke"},
+ )
+
+ response = self.client.patch(self._url(str(rule.id)), data={"filters": VALID_FILTERS}, format="json")
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ rule.refresh_from_db()
+ assert rule.filters == VALID_FILTERS
+ assert rule.bytecode
+ assert rule.disabled_data is None
+
+ def test_list_returns_only_team_rules(self) -> None:
+ ErrorTrackingBypassRule.objects.create(team=self.team, filters=VALID_FILTERS, bytecode=[], order_key=0)
+ other_team = self.create_team_with_organization(organization=self.organization)
+ ErrorTrackingBypassRule.objects.create(team=other_team, filters=VALID_FILTERS, bytecode=[], order_key=0)
+
+ response = self.client.get(self._url())
+
+ assert response.status_code == status.HTTP_200_OK
+ assert len(response.json()["results"]) == 1
+
+ def test_reorder_updates_order_keys(self) -> None:
+ first = self.client.post(self._url(), data={"filters": VALID_FILTERS}, format="json").json()["id"]
+ second = self.client.post(self._url(), data={"filters": VALID_FILTERS}, format="json").json()["id"]
+
+ response = self.client.patch(f"{self._url()}reorder/", data={"orders": {first: 1, second: 0}}, format="json")
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert ErrorTrackingBypassRule.objects.get(id=first).order_key == 1
+ assert ErrorTrackingBypassRule.objects.get(id=second).order_key == 0
+
+ def test_delete_removes_rule(self) -> None:
+ rule = ErrorTrackingBypassRule.objects.create(team=self.team, filters=VALID_FILTERS, bytecode=[], order_key=0)
+
+ response = self.client.delete(self._url(str(rule.id)))
+
+ assert response.status_code == status.HTTP_204_NO_CONTENT
+ assert not ErrorTrackingBypassRule.objects.filter(id=rule.id).exists()
+
+ def test_cannot_access_another_teams_rule(self) -> None:
+ other_team = self.create_team_with_organization(organization=self.organization)
+ other_rule = ErrorTrackingBypassRule.objects.create(
+ team=other_team, filters=VALID_FILTERS, bytecode=[], order_key=0
+ )
+
+ response = self.client.get(self._url(str(other_rule.id)))
+
+ assert response.status_code == status.HTTP_404_NOT_FOUND
diff --git a/products/error_tracking/frontend/generated/api.schemas.ts b/products/error_tracking/frontend/generated/api.schemas.ts
index 1f2f89e25d8d..9027b4819a92 100644
--- a/products/error_tracking/frontend/generated/api.schemas.ts
+++ b/products/error_tracking/frontend/generated/api.schemas.ts
@@ -382,6 +382,60 @@ export interface PatchedErrorTrackingAssignmentRuleApi {
readonly updated_at?: string
}
+export interface ErrorTrackingBypassRuleApi {
+ /** Unique identifier of the bypass rule. */
+ readonly id: string
+ /** Property-group filters that define which incoming error events bypass rate limiting. */
+ filters: unknown
+ /** Position of the rule in the team's ordered list. Rules are evaluated greedily in ascending order. */
+ order_key: number
+ /** Populated when the rule has been automatically disabled (for example, after its filters failed to evaluate during ingestion). Null while the rule is active. */
+ disabled_data: unknown
+ /** When the rule was created. */
+ readonly created_at: string
+ /** When the rule was last updated. */
+ readonly updated_at: string
+}
+
+export interface PaginatedErrorTrackingBypassRuleListApi {
+ count: number
+ /** @nullable */
+ next?: string | null
+ /** @nullable */
+ previous?: string | null
+ results: ErrorTrackingBypassRuleApi[]
+}
+
+export interface ErrorTrackingBypassRuleCreateRequestApi {
+ /** Property-group filters that define which incoming error events bypass rate limiting. Must contain at least one filter — empty rules are rejected. To stop rate limiting entirely, adjust the rate limit settings instead of creating a match-all bypass rule. */
+ filters: PropertyGroupFilterValueApi
+}
+
+export interface ErrorTrackingBypassRuleUpdateRequestApi {
+ /** Property-group filters that define which incoming error events bypass rate limiting. Must contain at least one filter. Omit to preserve the existing filters. */
+ filters?: PropertyGroupFilterValueApi
+}
+
+export interface PatchedErrorTrackingBypassRuleUpdateRequestApi {
+ /** Property-group filters that define which incoming error events bypass rate limiting. Must contain at least one filter. Omit to preserve the existing filters. */
+ filters?: PropertyGroupFilterValueApi
+}
+
+export interface PatchedErrorTrackingBypassRuleApi {
+ /** Unique identifier of the bypass rule. */
+ readonly id?: string
+ /** Property-group filters that define which incoming error events bypass rate limiting. */
+ filters?: unknown
+ /** Position of the rule in the team's ordered list. Rules are evaluated greedily in ascending order. */
+ order_key?: number
+ /** Populated when the rule has been automatically disabled (for example, after its filters failed to evaluate during ingestion). Null while the rule is active. */
+ disabled_data?: unknown
+ /** When the rule was created. */
+ readonly created_at?: string
+ /** When the rule was last updated. */
+ readonly updated_at?: string
+}
+
export interface ErrorTrackingExternalReferenceIntegrationResultApi {
/** ID of the integration backing this external reference. */
readonly id: number
@@ -1683,6 +1737,17 @@ export type ErrorTrackingAssignmentRulesListParams = {
offset?: number
}
+export type ErrorTrackingBypassRulesListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number
+}
+
export type ErrorTrackingExternalReferencesListParams = {
/**
* Number of results to return per page.
diff --git a/products/error_tracking/frontend/generated/api.ts b/products/error_tracking/frontend/generated/api.ts
index 63a1ff830b80..95a0f0b23f9f 100644
--- a/products/error_tracking/frontend/generated/api.ts
+++ b/products/error_tracking/frontend/generated/api.ts
@@ -13,6 +13,10 @@ import type {
ErrorTrackingAssignmentRuleCreateRequestApi,
ErrorTrackingAssignmentRuleUpdateRequestApi,
ErrorTrackingAssignmentRulesListParams,
+ ErrorTrackingBypassRuleApi,
+ ErrorTrackingBypassRuleCreateRequestApi,
+ ErrorTrackingBypassRuleUpdateRequestApi,
+ ErrorTrackingBypassRulesListParams,
ErrorTrackingExternalReferenceResultApi,
ErrorTrackingExternalReferencesListParams,
ErrorTrackingFingerprintApi,
@@ -61,6 +65,7 @@ import type {
ErrorTrackingSymbolSetsListParams,
GitProviderFileLinkResolveResponseApi,
PaginatedErrorTrackingAssignmentRuleListApi,
+ PaginatedErrorTrackingBypassRuleListApi,
PaginatedErrorTrackingExternalReferenceResultListApi,
PaginatedErrorTrackingFingerprintListApi,
PaginatedErrorTrackingIssueReadListApi,
@@ -72,6 +77,8 @@ import type {
PaginatedErrorTrackingSymbolSetListApi,
PatchedErrorTrackingAssignmentRuleApi,
PatchedErrorTrackingAssignmentRuleUpdateRequestApi,
+ PatchedErrorTrackingBypassRuleApi,
+ PatchedErrorTrackingBypassRuleUpdateRequestApi,
PatchedErrorTrackingGroupingRuleApi,
PatchedErrorTrackingGroupingRuleUpdateRequestApi,
PatchedErrorTrackingIssueReadApi,
@@ -234,6 +241,133 @@ export const errorTrackingAssignmentRulesReorderPartialUpdate = async (
})
}
+export const getErrorTrackingBypassRulesListUrl = (projectId: string, params?: ErrorTrackingBypassRulesListParams) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/error_tracking/bypass_rules/?${stringifiedParams}`
+ : `/api/projects/${projectId}/error_tracking/bypass_rules/`
+}
+
+export const errorTrackingBypassRulesList = async (
+ projectId: string,
+ params?: ErrorTrackingBypassRulesListParams,
+ options?: RequestInit
+): Promise<PaginatedErrorTrackingBypassRuleListApi> => {
+ return apiMutator<PaginatedErrorTrackingBypassRuleListApi>(getErrorTrackingBypassRulesListUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getErrorTrackingBypassRulesCreateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/error_tracking/bypass_rules/`
+}
+
+export const errorTrackingBypassRulesCreate = async (
+ projectId: string,
+ errorTrackingBypassRuleCreateRequestApi: ErrorTrackingBypassRuleCreateRequestApi,
+ options?: RequestInit
+): Promise<ErrorTrackingBypassRuleApi> => {
+ return apiMutator<ErrorTrackingBypassRuleApi>(getErrorTrackingBypassRulesCreateUrl(projectId), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(errorTrackingBypassRuleCreateRequestApi),
+ })
+}
+
+export const getErrorTrackingBypassRulesRetrieveUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/error_tracking/bypass_rules/${id}/`
+}
+
+export const errorTrackingBypassRulesRetrieve = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<ErrorTrackingBypassRuleApi> => {
+ return apiMutator<ErrorTrackingBypassRuleApi>(getErrorTrackingBypassRulesRetrieveUrl(projectId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getErrorTrackingBypassRulesUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/error_tracking/bypass_rules/${id}/`
+}
+
+export const errorTrackingBypassRulesUpdate = async (
+ projectId: string,
+ id: string,
+ errorTrackingBypassRuleUpdateRequestApi?: ErrorTrackingBypassRuleUpdateRequestApi,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getErrorTrackingBypassRulesUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(errorTrackingBypassRuleUpdateRequestApi),
+ })
+}
+
+export const getErrorTrackingBypassRulesPartialUpdateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/error_tracking/bypass_rules/${id}/`
+}
+
+export const errorTrackingBypassRulesPartialUpdate = async (
+ projectId: string,
+ id: string,
+ patchedErrorTrackingBypassRuleUpdateRequestApi?: PatchedErrorTrackingBypassRuleUpdateRequestApi,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getErrorTrackingBypassRulesPartialUpdateUrl(projectId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedErrorTrackingBypassRuleUpdateRequestApi),
+ })
+}
+
+export const getErrorTrackingBypassRulesDestroyUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/error_tracking/bypass_rules/${id}/`
+}
+
+export const errorTrackingBypassRulesDestroy = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getErrorTrackingBypassRulesDestroyUrl(projectId, id), {
+ ...options,
+ method: 'DELETE',
+ })
+}
+
+export const getErrorTrackingBypassRulesReorderPartialUpdateUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/error_tracking/bypass_rules/reorder/`
+}
+
+export const errorTrackingBypassRulesReorderPartialUpdate = async (
+ projectId: string,
+ patchedErrorTrackingBypassRuleApi?: NonReadonly<PatchedErrorTrackingBypassRuleApi>,
+ options?: RequestInit
+): Promise<void> => {
+ return apiMutator<void>(getErrorTrackingBypassRulesReorderPartialUpdateUrl(projectId), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedErrorTrackingBypassRuleApi),
+ })
+}
+
export const getErrorTrackingExternalReferencesListUrl = (
projectId: string,
params?: ErrorTrackingExternalReferencesListParams
diff --git a/products/error_tracking/frontend/generated/api.zod.ts b/products/error_tracking/frontend/generated/api.zod.ts
index 07ba0a180ac6..bf347be3ddee 100644
--- a/products/error_tracking/frontend/generated/api.zod.ts
+++ b/products/error_tracking/frontend/generated/api.zod.ts
@@ -101,6 +101,52 @@ export const ErrorTrackingAssignmentRulesReorderPartialUpdateBody = /* @__PURE__
disabled_data: zod.unknown().optional(),
})
+export const ErrorTrackingBypassRulesCreateBody = /* @__PURE__ */ zod.object({
+ filters: zod
+ .record(zod.string(), zod.unknown())
+ .describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
+ .describe(
+ 'Property-group filters that define which incoming error events bypass rate limiting. Must contain at least one filter — empty rules are rejected. To stop rate limiting entirely, adjust the rate limit settings instead of creating a match-all bypass rule.'
+ ),
+})
+
+export const ErrorTrackingBypassRulesUpdateBody = /* @__PURE__ */ zod.object({
+ filters: zod
+ .record(zod.string(), zod.unknown())
+ .describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
+ .optional()
+ .describe(
+ 'Property-group filters that define which incoming error events bypass rate limiting. Must contain at least one filter. Omit to preserve the existing filters.'
+ ),
+})
+
+export const ErrorTrackingBypassRulesPartialUpdateBody = /* @__PURE__ */ zod.object({
+ filters: zod
+ .record(zod.string(), zod.unknown())
+ .describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
+ .optional()
+ .describe(
+ 'Property-group filters that define which incoming error events bypass rate limiting. Must contain at least one filter. Omit to preserve the existing filters.'
+ ),
+})
+
+export const ErrorTrackingBypassRulesReorderPartialUpdateBody = /* @__PURE__ */ zod.object({
+ filters: zod
+ .unknown()
+ .optional()
+ .describe('Property-group filters that define which incoming error events bypass rate limiting.'),
+ order_key: zod
+ .number()
+ .optional()
+ .describe("Position of the rule in the team's ordered list. Rules are evaluated greedily in ascending order."),
+ disabled_data: zod
+ .unknown()
+ .optional()
+ .describe(
+ 'Populated when the rule has been automatically disabled (for example, after its filters failed to evaluate during ingestion). Null while the rule is active.'
+ ),
+})
+
export const ErrorTrackingExternalReferencesCreateBody = /* @__PURE__ */ zod.object({
integration_id: zod
.number()
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/bypass_rules/BypassRuleModal.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/bypass_rules/BypassRuleModal.tsx
new file mode 100644
index 000000000000..be913fc8fab7
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/bypass_rules/BypassRuleModal.tsx
@@ -0,0 +1,21 @@
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+
+import { RuleModal } from '../rules/RuleModal'
+import { bypassRuleModalLogic } from './bypassRuleModalLogic'
+
+export function BypassRuleModal(): JSX.Element {
+ return (
+ <RuleModal
+ logic={bypassRuleModalLogic}
+ ruleLabel="bypass"
+ description="Matching exceptions are always ingested, skipping rate limiting entirely."
+ pageKey="bypass-rule-modal"
+ width={800}
+ taxonomicGroupTypes={[
+ TaxonomicFilterGroupType.ErrorTrackingProperties,
+ TaxonomicFilterGroupType.EventProperties,
+ ]}
+ showTestButton={false}
+ />
+ )
+}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/bypass_rules/BypassRules.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/bypass_rules/BypassRules.tsx
new file mode 100644
index 000000000000..d6410f421105
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/bypass_rules/BypassRules.tsx
@@ -0,0 +1,21 @@
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+
+import { RuleList } from '../rules/RuleList'
+import { ErrorTrackingRuleType } from '../rules/types'
+import { BypassRuleModal } from './BypassRuleModal'
+import { bypassRuleModalLogic } from './bypassRuleModalLogic'
+
+export function BypassRules(): JSX.Element {
+ return (
+ <RuleList
+ ruleType={ErrorTrackingRuleType.Bypass}
+ modalLogic={bypassRuleModalLogic}
+ modal={<BypassRuleModal />}
+ taxonomicGroupTypes={[
+ TaxonomicFilterGroupType.ErrorTrackingProperties,
+ TaxonomicFilterGroupType.EventProperties,
+ ]}
+ pageKeyPrefix="bypass-rule"
+ />
+ )
+}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/bypass_rules/bypassRuleModalLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/bypass_rules/bypassRuleModalLogic.ts
new file mode 100644
index 000000000000..5810940ca330
--- /dev/null
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/bypass_rules/bypassRuleModalLogic.ts
@@ -0,0 +1,96 @@
+import { actions, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api from 'lib/api'
+
+import { FilterLogicalOperator, UniversalFiltersGroup } from '~/types'
+
+import { rulesLogic } from '../rules/rulesLogic'
+import { ErrorTrackingBypassRule, ErrorTrackingRuleType } from '../rules/types'
+import type { bypassRuleModalLogicType } from './bypassRuleModalLogicType'
+
+function emptyRule(orderKey: number = 0): ErrorTrackingBypassRule {
+ return {
+ id: 'new',
+ filters: { type: FilterLogicalOperator.Or, values: [] },
+ disabled_data: null,
+ order_key: orderKey,
+ }
+}
+
+export const bypassRuleModalLogic = kea<bypassRuleModalLogicType>([
+ path([
+ 'products',
+ 'error_tracking',
+ 'scenes',
+ 'ErrorTrackingConfigurationScene',
+ 'bypass_rules',
+ 'bypassRuleModalLogic',
+ ]),
+
+ actions({
+ openModal: (rule?: ErrorTrackingBypassRule) => ({ rule: rule ?? null }),
+ closeModal: true,
+ updateRule: (rule: ErrorTrackingBypassRule) => ({ rule }),
+ }),
+
+ reducers({
+ isOpen: [false, { openModal: () => true, closeModal: () => false }],
+ rule: [
+ emptyRule() as ErrorTrackingBypassRule,
+ {
+ openModal: (_: ErrorTrackingBypassRule, { rule }: { rule: ErrorTrackingBypassRule | null }) =>
+ rule ?? emptyRule(),
+ updateRule: (_: ErrorTrackingBypassRule, { rule }: { rule: ErrorTrackingBypassRule }) => rule,
+ },
+ ],
+ }),
+
+ loaders(({ values }) => ({
+ saving: [
+ false,
+ {
+ saveRule: async () => {
+ const rule = values.rule
+ if (rule.id === 'new') {
+ await api.errorTracking.createRule(ErrorTrackingRuleType.Bypass, rule)
+ } else {
+ await api.errorTracking.updateRule(ErrorTrackingRuleType.Bypass, rule)
+ }
+ return true
+ },
+ },
+ ],
+ deleting: [
+ false,
+ {
+ deleteRule: async () => {
+ const rule = values.rule
+ await api.errorTracking.deleteRule(ErrorTrackingRuleType.Bypass, rule.id)
+ return true
+ },
+ },
+ ],
+ })),
+
+ listeners(({ actions }) => ({
+ saveRuleSuccess: () => {
+ actions.closeModal()
+ rulesLogic({ ruleType: ErrorTrackingRuleType.Bypass }).actions.loadRules()
+ },
+ deleteRuleSuccess: () => {
+ actions.closeModal()
+ rulesLogic({ ruleType: ErrorTrackingRuleType.Bypass }).actions.loadRules()
+ },
+ })),
+
+ selectors({
+ hasFilters: [
+ (s) => [s.rule],
+ (rule: ErrorTrackingBypassRule): boolean => {
+ const filters = rule.filters as UniversalFiltersGroup
+ return (filters.values?.length ?? 0) > 0
+ },
+ ],
+ }),
+])
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitHistoryChart.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitHistoryChart.tsx
index e720f6f9fcfb..3901634f5e73 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitHistoryChart.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitHistoryChart.tsx
@@ -18,7 +18,12 @@ function fillHistoryBuckets(history: RateLimitHistoryBucket[], bucketMinutes: nu
})
return getBucketTimeline(bucketMinutes).map((ms) => {
const entry = byBucket.get(ms)
- return { bucket: dayjs(ms).toISOString(), recorded: entry?.recorded ?? 0, dropped: entry?.dropped ?? 0 }
+ return {
+ bucket: dayjs(ms).toISOString(),
+ recorded: entry?.recorded ?? 0,
+ dropped: entry?.dropped ?? 0,
+ bypassed: entry?.bypassed ?? 0,
+ }
})
}
@@ -36,9 +41,10 @@ export function RateLimitHistoryChart({
const labels = filled.map((b) => formatBucketLabel(b.bucket, bucketMinutes))
const recorded = filled.map((b) => b.recorded)
const dropped = filled.map((b) => b.dropped)
+ const bypassed = filled.map((b) => b.bypassed)
return {
- isEmpty: recorded.every((c) => c === 0) && dropped.every((c) => c === 0),
+ isEmpty: recorded.every((c) => c === 0) && dropped.every((c) => c === 0) && bypassed.every((c) => c === 0),
xData: {
column: {
name: 'bucket',
@@ -69,6 +75,16 @@ export function RateLimitHistoryChart({
data: dropped,
settings: { display: { displayType: 'bar' as const, color: getColorVar('danger') } },
},
+ {
+ column: {
+ name: 'bypassed',
+ type: { name: 'INTEGER' as const, isNumerical: true },
+ label: 'Bypassed',
+ dataIndex: 0,
+ },
+ data: bypassed,
+ settings: { display: { displayType: 'bar' as const, color: getColorVar('warning') } },
+ },
],
}
}, [history, bucketMinutes])
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitSettings.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitSettings.tsx
index d248e2689c1f..10f12e956588 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitSettings.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/RateLimitSettings.tsx
@@ -10,6 +10,7 @@ import { LemonField } from 'lib/lemon-ui/LemonField'
import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
+import { BypassRules } from '../bypass_rules/BypassRules'
import { IssueRateLimitSettings } from './IssueRateLimitSettings'
import { BUCKET_OPTIONS, rateLimitConfigLogic } from './rateLimitConfigLogic'
import { RateLimitHistoryChart } from './RateLimitHistoryChart'
@@ -17,11 +18,27 @@ import { formatTotalDuration, RateLimitSimulationChart } from './RateLimitSimula
export function RateLimitSettings(): JSX.Element {
const hasPerIssueRateLimit = useFeatureFlag('ERROR_TRACKING_RATE_LIMITING_PER_ISSUE')
+ const hasBypassRules = useFeatureFlag('ERROR_TRACKING_RATE_LIMITING_BYPASS')
return (
<div className="space-y-8">
<ProjectRateLimitSection />
{hasPerIssueRateLimit ? <IssueRateLimitSettings /> : null}
+ {hasBypassRules ? <BypassRulesSection /> : null}
+ </div>
+ )
+}
+
+function BypassRulesSection(): JSX.Element {
+ return (
+ <div className="space-y-4">
+ <div>
+ <h3 className="font-semibold text-base mb-1">Bypass rules</h3>
+ <p className="text-muted-foreground">
+ Exceptions matching a bypass rule are always ingested, skipping the rate limits above.
+ </p>
+ </div>
+ <BypassRules />
</div>
)
}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/issueRateLimitConfigLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/issueRateLimitConfigLogic.ts
index 3fa601d8fd3f..a294dc1c7f6a 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/issueRateLimitConfigLogic.ts
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/issueRateLimitConfigLogic.ts
@@ -12,6 +12,7 @@ import { HogQLQueryResponse, NodeKind, ProductKey } from '~/queries/schema/schem
import type { issueRateLimitConfigLogicType } from './issueRateLimitConfigLogicType'
import {
DEFAULT_BUCKET_MINUTES,
+ BYPASSED_METRIC_NAME,
DROPPED_METRIC_NAME,
EXCEPTIONS_APP_SOURCE,
ExceptionVolumeBucket,
@@ -195,11 +196,11 @@ export const issueRateLimitConfigLogic = kea<issueRateLimitConfigLogicType>([
FROM app_metrics
WHERE app_source = '${EXCEPTIONS_APP_SOURCE}'
AND app_source_id = {issueId}
- AND metric_name IN ('${RECORDED_METRIC_NAME}', '${DROPPED_METRIC_NAME}')
+ AND metric_name IN ('${RECORDED_METRIC_NAME}', '${DROPPED_METRIC_NAME}', '${BYPASSED_METRIC_NAME}')
AND timestamp >= now() - INTERVAL ${totalMinutes} MINUTE
GROUP BY bucket, metric_name
ORDER BY bucket
- LIMIT ${(option.bucketCount + 1) * 2}
+ LIMIT ${(option.bucketCount + 1) * 3}
`,
values: { issueId },
tags: { productKey: ProductKey.ERROR_TRACKING },
@@ -210,11 +211,13 @@ export const issueRateLimitConfigLogic = kea<issueRateLimitConfigLogicType>([
const byBucket = new Map<string, RateLimitHistoryBucket>()
for (const [bucket, metricName, count] of response.results ?? []) {
const key = String(bucket)
- const entry = byBucket.get(key) ?? { bucket: key, recorded: 0, dropped: 0 }
+ const entry = byBucket.get(key) ?? { bucket: key, recorded: 0, dropped: 0, bypassed: 0 }
if (metricName === RECORDED_METRIC_NAME) {
entry.recorded = Number(count)
} else if (metricName === DROPPED_METRIC_NAME) {
entry.dropped = Number(count)
+ } else if (metricName === BYPASSED_METRIC_NAME) {
+ entry.bypassed = Number(count)
}
byBucket.set(key, entry)
}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/rateLimitConfigLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/rateLimitConfigLogic.ts
index f59d18b24498..fe2bec69eaac 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/rateLimitConfigLogic.ts
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rate_limit/rateLimitConfigLogic.ts
@@ -50,6 +50,7 @@ export interface RateLimitHistoryBucket {
bucket: string
recorded: number
dropped: number
+ bypassed: number
}
export type RateLimitChartMode = 'simulation' | 'history'
@@ -66,6 +67,7 @@ export interface ChartLoadParams {
export const EXCEPTIONS_APP_SOURCE = 'exceptions'
export const RECORDED_METRIC_NAME = 'allowed'
export const DROPPED_METRIC_NAME = 'rate_limited'
+export const BYPASSED_METRIC_NAME = 'bypassed'
export const rateLimitConfigLogic = kea<rateLimitConfigLogicType>([
path([
@@ -166,11 +168,11 @@ export const rateLimitConfigLogic = kea<rateLimitConfigLogicType>([
FROM app_metrics
WHERE app_source = '${EXCEPTIONS_APP_SOURCE}'
AND app_source_id = '${appSourceId}'
- AND metric_name IN ('${RECORDED_METRIC_NAME}', '${DROPPED_METRIC_NAME}')
+ AND metric_name IN ('${RECORDED_METRIC_NAME}', '${DROPPED_METRIC_NAME}', '${BYPASSED_METRIC_NAME}')
AND timestamp >= now() - INTERVAL ${totalMinutes} MINUTE
GROUP BY bucket, metric_name
ORDER BY bucket
- LIMIT ${(option.bucketCount + 1) * 2}
+ LIMIT ${(option.bucketCount + 1) * 3}
`,
tags: { productKey: ProductKey.ERROR_TRACKING },
},
@@ -179,11 +181,13 @@ export const rateLimitConfigLogic = kea<rateLimitConfigLogicType>([
const byBucket = new Map<string, RateLimitHistoryBucket>()
for (const [bucket, metricName, count] of response.results ?? []) {
const key = String(bucket)
- const entry = byBucket.get(key) ?? { bucket: key, recorded: 0, dropped: 0 }
+ const entry = byBucket.get(key) ?? { bucket: key, recorded: 0, dropped: 0, bypassed: 0 }
if (metricName === RECORDED_METRIC_NAME) {
entry.recorded = Number(count)
} else if (metricName === DROPPED_METRIC_NAME) {
entry.dropped = Number(count)
+ } else if (metricName === BYPASSED_METRIC_NAME) {
+ entry.bypassed = Number(count)
}
byBucket.set(key, entry)
}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/RuleModal.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/RuleModal.tsx
index d4f1bc9cc223..27cf4d30a092 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/RuleModal.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/RuleModal.tsx
@@ -20,12 +20,13 @@ interface RuleModalProps {
width?: number
taxonomicGroupTypes: TaxonomicFilterGroupType[]
saveDisabledReason?: string
- suffix: (issuesLink: JSX.Element, dateRangeLabel: string) => JSX.Element
+ suffix?: (issuesLink: JSX.Element, dateRangeLabel: string) => JSX.Element
filterLabels?: ReactNode
extraFields?: ReactNode
footerExtra?: ReactNode
samplingRate?: number
filtersOptional?: boolean
+ showTestButton?: boolean
}
export function RuleModal({
@@ -42,6 +43,7 @@ export function RuleModal({
footerExtra,
samplingRate,
filtersOptional = false,
+ showTestButton = true,
}: RuleModalProps): JSX.Element {
const { isOpen, rule, hasFilters, matchResult, matchResultLoading, savingLoading, deletingLoading, dateRange } =
useValues(logic)
@@ -116,17 +118,19 @@ export function RuleModal({
{footerExtra}
</div>
<div className="flex gap-2">
- <LemonButton
- type="secondary"
- size="small"
- icon={matchResultLoading ? <Spinner textColored /> : <IconFlask />}
- disabledReason={
- !filtersOptional && !hasFilters ? 'Add at least one filter first' : undefined
- }
- onClick={loadMatchCount}
- >
- Test rule
- </LemonButton>
+ {showTestButton && (
+ <LemonButton
+ type="secondary"
+ size="small"
+ icon={matchResultLoading ? <Spinner textColored /> : <IconFlask />}
+ disabledReason={
+ !filtersOptional && !hasFilters ? 'Add at least one filter first' : undefined
+ }
+ onClick={loadMatchCount}
+ >
+ Test rule
+ </LemonButton>
+ )}
<LemonButton type="secondary" onClick={closeModal}>
Cancel
</LemonButton>
@@ -190,7 +194,7 @@ export function RuleModal({
{extraFields}
- {matchResult !== null && !matchResultLoading ? (
+ {matchResult !== null && !matchResultLoading && suffix ? (
<LemonBanner type={matchResult.exceptionCount === 0 ? 'error' : 'success'}>
<MatchResultBanner
matchResult={matchResult}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/rulesLogic.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/rulesLogic.tsx
index 6956440da6c6..7793151978be 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/rulesLogic.tsx
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/rulesLogic.tsx
@@ -35,6 +35,13 @@ function createNewRule(ruleType: ErrorTrackingRuleType, order_key: number): Erro
order_key,
sampling_rate: 1.0,
}
+ case 'bypass_rules':
+ return {
+ id: 'new',
+ disabled_data: null,
+ filters: { type: FilterLogicalOperator.Or, values: [] },
+ order_key,
+ }
default:
throw new Error(`Unsupported rule type: ${ruleType}`)
}
diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/types.ts b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/types.ts
index cf24fb35e44b..d6e31fba5e32 100644
--- a/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/types.ts
+++ b/products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/rules/types.ts
@@ -24,11 +24,18 @@ export type ErrorTrackingGroupingRule = ErrorTrackingBaseRule & {
issue?: { id: string; name: string | null } | null
}
-export type ErrorTrackingRule = ErrorTrackingSuppressionRule | ErrorTrackingGroupingRule | ErrorTrackingAssignmentRule
+export type ErrorTrackingBypassRule = ErrorTrackingBaseRule
+
+export type ErrorTrackingRule =
+ | ErrorTrackingSuppressionRule
+ | ErrorTrackingGroupingRule
+ | ErrorTrackingAssignmentRule
+ | ErrorTrackingBypassRule
export type ErrorTrackingRuleNew = ErrorTrackingRule & { id: 'new' }
export enum ErrorTrackingRuleType {
Assignment = 'assignment_rules',
+ Bypass = 'bypass_rules',
Grouping = 'grouping_rules',
Suppression = 'suppression_rules',
}
diff --git a/products/error_tracking/mcp/tools.yaml b/products/error_tracking/mcp/tools.yaml
index 58ee4f208e1e..109428c17e28 100644
--- a/products/error_tracking/mcp/tools.yaml
+++ b/products/error_tracking/mcp/tools.yaml
@@ -61,6 +61,27 @@ tools:
error-tracking-assignment-rules-update:
operation: error_tracking_assignment_rules_update
enabled: false
+ error-tracking-bypass-rules-create:
+ operation: error_tracking_bypass_rules_create
+ enabled: false
+ error-tracking-bypass-rules-destroy:
+ operation: error_tracking_bypass_rules_destroy
+ enabled: false
+ error-tracking-bypass-rules-list:
+ operation: error_tracking_bypass_rules_list
+ enabled: false
+ error-tracking-bypass-rules-partial-update:
+ operation: error_tracking_bypass_rules_partial_update
+ enabled: false
+ error-tracking-bypass-rules-reorder-partial-update:
+ operation: error_tracking_bypass_rules_reorder_partial_update
+ enabled: false
+ error-tracking-bypass-rules-retrieve:
+ operation: error_tracking_bypass_rules_retrieve
+ enabled: false
+ error-tracking-bypass-rules-update:
+ operation: error_tracking_bypass_rules_update
+ enabled: false
error-tracking-external-references-create:
operation: error_tracking_external_references_create
enabled: true
diff --git a/rust/cymbal/.sqlx/query-16ea3a42949e74f1b5cedf2125e1b7b90209c953e91329ced338ecdce594db76.json b/rust/cymbal/.sqlx/query-16ea3a42949e74f1b5cedf2125e1b7b90209c953e91329ced338ecdce594db76.json
new file mode 100644
index 000000000000..c868cb28751e
--- /dev/null
+++ b/rust/cymbal/.sqlx/query-16ea3a42949e74f1b5cedf2125e1b7b90209c953e91329ced338ecdce594db76.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE posthog_errortrackingbypassrule\n SET disabled_data = $1, updated_at = NOW()\n WHERE id = $2\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Jsonb",
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "16ea3a42949e74f1b5cedf2125e1b7b90209c953e91329ced338ecdce594db76"
+}
diff --git a/rust/cymbal/.sqlx/query-7e6a02ea3ed9fe8421fbacc75df7f2da7dafbb25e75c828d54dafd5ce76a446f.json b/rust/cymbal/.sqlx/query-65b2f7ee68c56eff74a3ea74e83e447a991530bf90b2341d42ae89fdbc3e7713.json
similarity index 82%
rename from rust/cymbal/.sqlx/query-7e6a02ea3ed9fe8421fbacc75df7f2da7dafbb25e75c828d54dafd5ce76a446f.json
rename to rust/cymbal/.sqlx/query-65b2f7ee68c56eff74a3ea74e83e447a991530bf90b2341d42ae89fdbc3e7713.json
index 0117fed9b6bb..a6e19de8d562 100644
--- a/rust/cymbal/.sqlx/query-7e6a02ea3ed9fe8421fbacc75df7f2da7dafbb25e75c828d54dafd5ce76a446f.json
+++ b/rust/cymbal/.sqlx/query-65b2f7ee68c56eff74a3ea74e83e447a991530bf90b2341d42ae89fdbc3e7713.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, team_id, order_key, bytecode, created_at, updated_at\n FROM posthog_errortrackingsuppressionrule\n WHERE team_id = $1 AND disabled_data IS NULL AND bytecode IS NOT NULL\n ",
+ "query": "\n SELECT id, team_id, order_key, bytecode, created_at, updated_at\n FROM posthog_errortrackingbypassrule\n WHERE team_id = $1 AND disabled_data IS NULL AND bytecode IS NOT NULL\n ",
"describe": {
"columns": [
{
@@ -48,5 +48,5 @@
false
]
},
- "hash": "7e6a02ea3ed9fe8421fbacc75df7f2da7dafbb25e75c828d54dafd5ce76a446f"
+ "hash": "65b2f7ee68c56eff74a3ea74e83e447a991530bf90b2341d42ae89fdbc3e7713"
}
diff --git a/rust/cymbal/src/core/metric_consts.rs b/rust/cymbal/src/core/metric_consts.rs
index d90cfceea2cd..e7c6c099cd21 100644
--- a/rust/cymbal/src/core/metric_consts.rs
+++ b/rust/cymbal/src/core/metric_consts.rs
@@ -130,6 +130,8 @@ pub const FINGERPRINT_GENERATOR_OPERATOR: &str = "cymbal_exception_fingerprint_g
pub const RULE_SUPPRESSED_EVENTS: &str = "cymbal_rule_suppressed_events";
pub const SUPPRESSION_RULES_TRIED: &str = "cymbal_suppression_rules_tried";
pub const SUPPRESSION_RULES_DISABLED: &str = "cymbal_suppression_rules_disabled";
+pub const BYPASS_RULES_TRIED: &str = "cymbal_bypass_rules_tried";
+pub const BYPASS_RULES_DISABLED: &str = "cymbal_bypass_rules_disabled";
// Remote resolution observability. Keep labels bounded: endpoint labels are
// limited to the discovered pod set, and protocol failures are classified by
diff --git a/rust/cymbal/src/modes/processing/config.rs b/rust/cymbal/src/modes/processing/config.rs
index 9b7461b5d161..61f5aa3779ba 100644
--- a/rust/cymbal/src/modes/processing/config.rs
+++ b/rust/cymbal/src/modes/processing/config.rs
@@ -110,6 +110,13 @@ pub struct ProcessingConfig {
// The maximum number of bytecode operations we'll store in the cache, across all rules, across all teams
pub max_suppression_rule_cache_size: u64,
+ #[envconfig(default = "300")]
+ pub bypass_rule_cache_ttl_secs: u64,
+
+ #[envconfig(default = "100000")]
+ // The maximum number of bytecode operations we'll store in the cache, across all rules, across all teams
+ pub max_bypass_rule_cache_size: u64,
+
#[envconfig(from = "ISSUE_BUCKETS_REDIS_URL", default = "redis://localhost:6379/")]
pub issue_buckets_redis_url: String,
diff --git a/rust/cymbal/src/modes/processing/rules/bypass.rs b/rust/cymbal/src/modes/processing/rules/bypass.rs
new file mode 100644
index 000000000000..b8230f20f164
--- /dev/null
+++ b/rust/cymbal/src/modes/processing/rules/bypass.rs
@@ -0,0 +1,179 @@
+use chrono::{DateTime, Utc};
+use common_types::TeamId;
+use hogvm::{ExecutionContext, Program, StepOutcome, VmError};
+use serde::Serialize;
+use serde_json::Value;
+use uuid::Uuid;
+
+use crate::metric_consts::{BYPASS_RULES_DISABLED, BYPASS_RULES_TRIED};
+
+/// A rate-limit bypass rule. When an incoming exception event matches an enabled
+/// rule, the rate-limiting stage keeps it and charges no tokens (neither the
+/// per-issue nor the project bucket), recording a "bypassed" outcome. Matching is
+/// identical to suppression rules — the bytecode runs against the event's
+/// `properties` — but there is no sampling: a match always bypasses.
+#[derive(Debug, Clone)]
+pub struct BypassRule {
+ pub id: Uuid,
+ pub team_id: TeamId,
+ pub order_key: i32,
+ pub bytecode: Value,
+ pub created_at: DateTime<Utc>,
+ pub updated_at: DateTime<Utc>,
+}
+
+impl BypassRule {
+ pub async fn load_for_team<'c, E>(conn: E, team_id: TeamId) -> Result<Vec<Self>, sqlx::Error>
+ where
+ E: sqlx::Executor<'c, Database = sqlx::Postgres>,
+ {
+ sqlx::query_as!(
+ BypassRule,
+ r#"
+ SELECT id, team_id, order_key, bytecode, created_at, updated_at
+ FROM posthog_errortrackingbypassrule
+ WHERE team_id = $1 AND disabled_data IS NULL AND bytecode IS NOT NULL
+ "#,
+ team_id
+ )
+ .fetch_all(conn)
+ .await
+ }
+
+ pub async fn disable<'c, E>(
+ &self,
+ conn: E,
+ message: String,
+ props: Value,
+ ) -> Result<(), sqlx::Error>
+ where
+ E: sqlx::Executor<'c, Database = sqlx::Postgres>,
+ {
+ #[derive(Serialize)]
+ struct DisabledData {
+ message: String,
+ props: Value,
+ }
+
+ let data = DisabledData { message, props };
+
+ sqlx::query!(
+ r#"
+ UPDATE posthog_errortrackingbypassrule
+ SET disabled_data = $1, updated_at = NOW()
+ WHERE id = $2
+ "#,
+ serde_json::to_value(data).expect("Can serialize"),
+ self.id
+ )
+ .execute(conn)
+ .await?;
+
+ metrics::counter!(BYPASS_RULES_DISABLED).increment(1);
+ Ok(())
+ }
+
+ /// Whether this rule matches the event's properties, meaning the event should
+ /// bypass rate limiting entirely.
+ pub fn try_match(&self, props: &Value) -> Result<bool, VmError> {
+ let rule_bytecode = match &self.bytecode {
+ Value::Array(ops) => ops,
+ _ => {
+ return Err(VmError::Other(format!(
+ "Invalid rule bytecode - expected array, got {:?}",
+ self.bytecode
+ )))
+ }
+ };
+
+ let globals = Value::Object(serde_json::Map::from_iter([(
+ "properties".to_string(),
+ props.clone(),
+ )]));
+ let program = Program::new(rule_bytecode.clone())?;
+ let context = ExecutionContext::with_defaults(program).with_globals(globals);
+ let mut vm = context.to_vm()?;
+
+ metrics::counter!(BYPASS_RULES_TRIED).increment(1);
+
+ let mut i = 0;
+ while i < context.max_steps {
+ let step_result = vm.step()?;
+ match step_result {
+ StepOutcome::Finished(Value::Bool(b)) => return Ok(b),
+ StepOutcome::Finished(res) => {
+ return Err(VmError::Other(format!(
+ "Bypass rule returned {res:?}, expected a boolean value"
+ )))
+ }
+ StepOutcome::NativeCall(name, args) => {
+ context.execute_native_function_call(&mut vm, &name, args)?
+ }
+ StepOutcome::Continue => {}
+ }
+ i += 1;
+ }
+
+ Err(VmError::OutOfResource("steps".to_string()))
+ }
+}
+
+#[cfg(test)]
+mod test {
+ use chrono::Utc;
+ use serde_json::{json, Value as JsonValue};
+ use uuid::Uuid;
+
+ use super::BypassRule;
+
+ fn rule_bytecode() -> JsonValue {
+ // return properties.test_value = 'test_value'
+ json!([
+ "_H",
+ 1,
+ 32,
+ "test_value",
+ 32,
+ "test_value",
+ 32,
+ "properties",
+ 1,
+ 2,
+ 11,
+ 38
+ ])
+ }
+
+ fn get_test_rule() -> BypassRule {
+ BypassRule {
+ id: Uuid::new_v4(),
+ team_id: 1,
+ order_key: 1,
+ bytecode: rule_bytecode(),
+ created_at: Utc::now(),
+ updated_at: Utc::now(),
+ }
+ }
+
+ #[test]
+ fn test_try_match_returns_true_on_match() {
+ let rule = get_test_rule();
+ let props = json!({"test_value": "test_value"});
+ assert!(rule.try_match(&props).unwrap());
+ }
+
+ #[test]
+ fn test_try_match_returns_false_on_no_match() {
+ let rule = get_test_rule();
+ let props = json!({"test_value": "other_value"});
+ assert!(!rule.try_match(&props).unwrap());
+ }
+
+ #[test]
+ fn test_try_match_returns_error_on_invalid_bytecode() {
+ let mut rule = get_test_rule();
+ rule.bytecode = json!("not_an_array");
+ let props = json!({"test_value": "test_value"});
+ assert!(rule.try_match(&props).is_err());
+ }
+}
diff --git a/rust/cymbal/src/modes/processing/rules/mod.rs b/rust/cymbal/src/modes/processing/rules/mod.rs
index 0b83c6f43534..39eac14bb080 100644
--- a/rust/cymbal/src/modes/processing/rules/mod.rs
+++ b/rust/cymbal/src/modes/processing/rules/mod.rs
@@ -3,6 +3,7 @@
//! together by `crate::modes::processing::teams::TeamManager`.
pub mod assignment;
+pub mod bypass;
pub mod grouping;
pub mod rate_limit;
pub mod spike;
diff --git a/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs b/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs
index f3f062a1e786..2ebe54f699d4 100644
--- a/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs
+++ b/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs
@@ -9,6 +9,7 @@ use futures::stream::{self, StreamExt};
use common_kafka::kafka_messages::app_metrics2::{AppMetric2, Kind, Source};
use common_kafka::kafka_producer::send_iter_to_kafka;
use common_kafka::APP_METRICS2_TOPIC;
+use hogvm::VmError;
use metrics::counter;
use tracing::warn;
use uuid::Uuid;
@@ -26,7 +27,9 @@ use crate::{
},
};
+use crate::modes::processing::rules::bypass::BypassRule;
use crate::modes::processing::rules::rate_limit::RateLimitSettings;
+use crate::modes::processing::types::exception_properties::ExceptionProperties;
pub use limiter::{RateLimitDecision, RedisRateLimiter, ScriptRunner, RATE_LIMIT_LUA};
@@ -44,6 +47,8 @@ enum LimitKind {
enum Outcome {
Allowed,
RateLimited,
+ // Matched a bypass rule: kept and charged no tokens, recorded so it surfaces in app metrics.
+ Bypassed,
}
impl LimitKind {
@@ -60,6 +65,7 @@ impl Outcome {
match self {
Outcome::Allowed => "allowed",
Outcome::RateLimited => "rate_limited",
+ Outcome::Bypassed => "bypassed",
}
}
}
@@ -115,13 +121,21 @@ impl Stage for RateLimitingStage {
.get_rate_limit_settings(&self.ctx.posthog_pool, team_ids)
.await;
- let outcomes = apply_rate_limits(
+ // Bypass rules exempt matching events from rate limiting: they're kept, never charged,
+ // and recorded as "bypassed" instead of being offered to the limiter below.
+ let (bypassed, bypass_outcomes) = self.apply_bypass(&settings, &items).await;
+
+ let mut outcomes = apply_rate_limits(
&limiter,
&settings,
self.ctx.rate_limiter_enabled_team_ids.as_ref(),
&mut items,
+ &bypassed,
)
.await;
+ for (key, count) in bypass_outcomes {
+ *outcomes.entry(key).or_insert(0) += count;
+ }
self.emit_metrics(&outcomes).await;
@@ -139,10 +153,15 @@ async fn apply_rate_limits(
settings: &HashMap<i32, RateLimitSettings>,
enabled_teams: Option<&HashSet<i32>>,
items: &mut [ExceptionEventPipelineItem],
+ bypassed: &HashSet<usize>,
) -> HashMap<OutcomeKey, u32> {
// Group surviving (Ok) events by (team_id, issue_id). Vec<usize> stays in input order.
+ // Bypassed events are skipped so they never charge a token bucket.
let mut groups: HashMap<(i32, Option<Uuid>), Vec<usize>> = HashMap::new();
for (idx, item) in items.iter().enumerate() {
+ if bypassed.contains(&idx) {
+ continue;
+ }
if let Ok(props) = item {
groups
.entry((props.team_id, props.issue_id))
@@ -245,6 +264,80 @@ async fn apply_rate_limits(
}
impl RateLimitingStage {
+ /// Evaluate bypass rules over the batch. An event whose team is subject to rate
+ /// limiting and which matches an enabled rule is exempted: its index is returned so
+ /// the limiter never charges it, and a `Bypassed` outcome is tallied (per-issue and/or
+ /// project, matching the team's configured limits) so it surfaces in app metrics.
+ async fn apply_bypass(
+ &self,
+ settings: &HashMap<i32, RateLimitSettings>,
+ items: &[ExceptionEventPipelineItem],
+ ) -> (HashSet<usize>, HashMap<OutcomeKey, u32>) {
+ let enabled_teams = self.ctx.rate_limiter_enabled_team_ids.as_ref();
+
+ // A team's events can only be "bypassed" if the team is actually rate-limited:
+ // allowlisted (when an allowlist is set) and with at least one configured limit.
+ let is_rate_limited = |team_id: i32| -> bool {
+ if enabled_teams.is_some_and(|allowed| !allowed.contains(&team_id)) {
+ return false;
+ }
+ settings
+ .get(&team_id)
+ .is_some_and(|s| s.per_issue().is_some() || s.project().is_some())
+ };
+
+ // Load rules once per eligible team present in the batch.
+ let eligible_teams: HashSet<i32> = items
+ .iter()
+ .filter_map(|item| item.as_ref().ok().map(|p| p.team_id))
+ .filter(|&team_id| is_rate_limited(team_id))
+ .collect();
+ let mut rules_by_team: HashMap<i32, Vec<BypassRule>> = HashMap::new();
+ for team_id in eligible_teams {
+ match self
+ .ctx
+ .team_manager
+ .get_bypass_rules(&self.ctx.posthog_pool, team_id)
+ .await
+ {
+ Ok(rules) if !rules.is_empty() => {
+ let mut rules = rules;
+ rules.sort_unstable_by_key(|r| r.order_key);
+ rules_by_team.insert(team_id, rules);
+ }
+ Ok(_) => {}
+ Err(e) => warn!("failed to load bypass rules for team {team_id}: {e}"),
+ }
+ }
+
+ if rules_by_team.is_empty() {
+ return (HashSet::new(), HashMap::new());
+ }
+
+ let (bypassed, outcomes, to_disable) =
+ evaluate_bypass_rules(items, &rules_by_team, settings, |rule, props_json| {
+ rule.try_match(props_json)
+ });
+
+ // Persist the disables the evaluation flagged. They're already deduped to one entry per
+ // broken rule, so this is at most one DB write + cache drop per rule for the whole batch.
+ for entry in to_disable {
+ if let Err(e) = entry
+ .rule
+ .disable(&self.ctx.posthog_pool, entry.error, entry.props_json)
+ .await
+ {
+ warn!("failed to disable bypass rule {}: {e}", entry.rule.id);
+ }
+ self.ctx
+ .team_manager
+ .bypass_rules
+ .invalidate(&entry.team_id);
+ }
+
+ (bypassed, outcomes)
+ }
+
async fn emit_metrics(&self, outcomes: &HashMap<OutcomeKey, u32>) {
if outcomes.is_empty() {
return;
@@ -363,6 +456,34 @@ fn classify_group(
}
}
+/// Tally a bypassed event under the limits the team has configured, so the "bypassed"
+/// series lines up with allowed/rate_limited in each chart: a per-issue row (keyed by the
+/// issue id) when the per-issue limit is on, and a project row when the project limit is on.
+fn tally_bypassed(
+ outcomes: &mut HashMap<OutcomeKey, u32>,
+ props: &ExceptionProperties,
+ settings: &HashMap<i32, RateLimitSettings>,
+) {
+ let Some(team_settings) = settings.get(&props.team_id) else {
+ return;
+ };
+ if team_settings.project().is_some() {
+ *outcomes
+ .entry((props.team_id, LimitKind::Project, None, Outcome::Bypassed))
+ .or_insert(0) += 1;
+ }
+ if props.issue_id.is_some() && team_settings.per_issue().is_some() {
+ *outcomes
+ .entry((
+ props.team_id,
+ LimitKind::PerIssue,
+ props.issue_id,
+ Outcome::Bypassed,
+ ))
+ .or_insert(0) += 1;
+ }
+}
+
fn add_outcome(
outcomes: &mut HashMap<OutcomeKey, u32>,
team_id: i32,
@@ -383,6 +504,85 @@ fn add_outcome(
}
}
+/// A broken bypass rule to disable after evaluation, captured once (on first failure) with the
+/// error and the props of the event that broke it.
+struct RuleToDisable<'a> {
+ rule: &'a BypassRule,
+ team_id: i32,
+ error: String,
+ props_json: serde_json::Value,
+}
+
+/// Pure per-batch evaluation of already-loaded bypass rules, split out from I/O (rule loading and
+/// disabling) so it can be unit-tested without a database or the HogVM. Returns the bypassed event
+/// indices, the "bypassed" tallies, and the broken rules to disable — deduped to one entry per
+/// rule: a rule that errors is tried once per batch and skipped for every later event, so it isn't
+/// re-disabled (and its cache re-invalidated) on each match. `match_fn` is [`BypassRule::try_match`]
+/// in production and a fake in tests.
+fn evaluate_bypass_rules<'a>(
+ items: &[ExceptionEventPipelineItem],
+ rules_by_team: &'a HashMap<i32, Vec<BypassRule>>,
+ settings: &HashMap<i32, RateLimitSettings>,
+ match_fn: impl Fn(&BypassRule, &serde_json::Value) -> Result<bool, VmError>,
+) -> (
+ HashSet<usize>,
+ HashMap<OutcomeKey, u32>,
+ Vec<RuleToDisable<'a>>,
+) {
+ let mut bypassed: HashSet<usize> = HashSet::new();
+ let mut outcomes: HashMap<OutcomeKey, u32> = HashMap::new();
+ let mut to_disable: Vec<RuleToDisable<'a>> = Vec::new();
+ let mut disabled_rules: HashSet<Uuid> = HashSet::new();
+
+ for (idx, item) in items.iter().enumerate() {
+ let Ok(props) = item else { continue };
+ let Some(rules) = rules_by_team.get(&props.team_id) else {
+ continue;
+ };
+ let props_json = match serde_json::to_value(props) {
+ Ok(v) => v,
+ Err(_) => continue,
+ };
+ for rule in rules {
+ if disabled_rules.contains(&rule.id) {
+ continue;
+ }
+ match match_fn(rule, &props_json) {
+ Ok(false) => continue,
+ Ok(true) => {
+ bypassed.insert(idx);
+ tally_bypassed(&mut outcomes, props, settings);
+ break;
+ }
+ // Step-budget exhaustion: skip this rule for this event, but keep trying it on
+ // later events — it isn't broken, just too expensive for this one.
+ Err(VmError::OutOfResource(resource)) if resource == "steps" => {
+ warn!(
+ rule_id = %rule.id,
+ team_id = %rule.team_id,
+ "bypass rule exceeded HogVM step budget for this event, skipping"
+ );
+ continue;
+ }
+ // Any other error means the rule is broken: flag it for disabling and skip it for
+ // the rest of the batch so it stops erroring on every later event.
+ Err(err) => {
+ disabled_rules.insert(rule.id);
+ to_disable.push(RuleToDisable {
+ rule,
+ team_id: props.team_id,
+ error: err.to_string(),
+ props_json: props_json.clone(),
+ });
+ continue;
+ }
+ }
+ }
+ }
+
+ (bypassed, outcomes, to_disable)
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -482,7 +682,7 @@ mod tests {
let mut cfg = HashMap::new();
cfg.insert(1, settings(Some(1), Some(1)));
- let outcomes = apply_rate_limits(&limiter, &cfg, None, &mut items).await;
+ let outcomes = apply_rate_limits(&limiter, &cfg, None, &mut items, &HashSet::new()).await;
// Redis errored, so the whole group is kept (fail open): nothing is
// flipped to Err, and no allowed/limited outcomes are tallied.
@@ -502,7 +702,7 @@ mod tests {
let mut cfg = HashMap::new();
cfg.insert(7, settings(Some(100), Some(100)));
- apply_rate_limits(&limiter, &cfg, None, &mut items).await;
+ apply_rate_limits(&limiter, &cfg, None, &mut items, &HashSet::new()).await;
assert!(items[0].is_ok()); // kept
assert!(matches!(items[1], Err(EventError::RateLimitedProject(7))));
@@ -524,7 +724,7 @@ mod tests {
let mut cfg = HashMap::new();
cfg.insert(7, settings(Some(100), Some(100)));
- let outcomes = apply_rate_limits(&limiter, &cfg, None, &mut items).await;
+ let outcomes = apply_rate_limits(&limiter, &cfg, None, &mut items, &HashSet::new()).await;
// Per-issue tallies are keyed by the individual issue id — one bucket per
// issue — so each gets its own bare-UUID `app_source_id` like Node.js.
@@ -556,7 +756,7 @@ mod tests {
(0..3).map(|_| event(42, Some(Uuid::now_v7()))).collect();
let cfg = HashMap::new(); // team 42 has no settings row
- let outcomes = apply_rate_limits(&limiter, &cfg, None, &mut items).await;
+ let outcomes = apply_rate_limits(&limiter, &cfg, None, &mut items, &HashSet::new()).await;
assert!(items.iter().all(|item| item.is_ok())); // opted-out team untouched
assert_eq!(runner.call_count(), 0); // and we never hit redis for it
@@ -576,7 +776,7 @@ mod tests {
cfg.insert(2, settings(Some(1), Some(1)));
let allowed: HashSet<i32> = [1].into_iter().collect();
- apply_rate_limits(&limiter, &cfg, Some(&allowed), &mut items).await;
+ apply_rate_limits(&limiter, &cfg, Some(&allowed), &mut items, &HashSet::new()).await;
assert!(items[0].is_err()); // team 1 is allowlisted -> rate-limited
assert!(items[1].is_ok()); // team 2 is not -> untouched despite having settings
@@ -646,4 +846,146 @@ mod tests {
assert_eq!(out.per_issue, Some((2, 0)));
assert_eq!(out.project, Some((2, 0)));
}
+
+ #[tokio::test]
+ async fn bypassed_events_are_kept_and_not_charged() {
+ // 5 events for one issue, 2 of them bypassed. Redis admits only 1 of the
+ // chargeable events, but the bypassed pair must survive regardless and never
+ // enter the bucket — so 3 events are kept (2 bypassed + 1 admitted).
+ let runner = Arc::new(FakeScriptRunner::returning(vec![1, 1]));
+ let limiter = limiter_with(runner.clone());
+ let issue = Uuid::now_v7();
+ let mut items: Vec<ExceptionEventPipelineItem> =
+ (0..5).map(|_| event(7, Some(issue))).collect();
+ let mut cfg = HashMap::new();
+ cfg.insert(7, settings(Some(100), Some(100)));
+ let bypassed: HashSet<usize> = [0, 1].into_iter().collect();
+
+ apply_rate_limits(&limiter, &cfg, None, &mut items, &bypassed).await;
+
+ // Bypassed indices are always kept.
+ assert!(items[0].is_ok());
+ assert!(items[1].is_ok());
+ // Only the 3 non-bypassed events were charged (admit 1 -> 2 dropped).
+ assert_eq!(items.iter().filter(|i| i.is_ok()).count(), 3);
+ }
+
+ #[test]
+ fn tally_bypassed_records_both_limits_when_configured() {
+ let issue = Uuid::now_v7();
+ let mut outcomes = HashMap::new();
+ let mut cfg = HashMap::new();
+ cfg.insert(7, settings(Some(100), Some(100)));
+ let item = event(7, Some(issue));
+ let props = item.as_ref().unwrap();
+
+ tally_bypassed(&mut outcomes, props, &cfg);
+
+ assert_eq!(
+ outcomes.get(&(7, LimitKind::PerIssue, Some(issue), Outcome::Bypassed)),
+ Some(&1)
+ );
+ assert_eq!(
+ outcomes.get(&(7, LimitKind::Project, None, Outcome::Bypassed)),
+ Some(&1)
+ );
+ }
+
+ #[test]
+ fn tally_bypassed_skips_unconfigured_limits() {
+ // Only a project limit configured, and an event with no issue id: a single
+ // project row, no per-issue row.
+ let mut outcomes = HashMap::new();
+ let mut cfg = HashMap::new();
+ cfg.insert(7, settings(None, Some(100)));
+ let item = event(7, None);
+ let props = item.as_ref().unwrap();
+
+ tally_bypassed(&mut outcomes, props, &cfg);
+
+ assert_eq!(
+ outcomes.get(&(7, LimitKind::Project, None, Outcome::Bypassed)),
+ Some(&1)
+ );
+ assert_eq!(outcomes.len(), 1);
+ }
+
+ fn bypass_rule(id: Uuid, team_id: i32, order_key: i32) -> BypassRule {
+ // Bytecode is irrelevant here — the tests drive matching through the fake `match_fn`.
+ BypassRule {
+ id,
+ team_id,
+ order_key,
+ bytecode: serde_json::Value::Array(vec![]),
+ created_at: Utc::now(),
+ updated_at: Utc::now(),
+ }
+ }
+
+ #[test]
+ fn evaluate_bypass_marks_matching_event_and_tallies() {
+ let issue = Uuid::now_v7();
+ let items = vec![event(7, Some(issue))];
+ let rules_by_team = HashMap::from([(7, vec![bypass_rule(Uuid::now_v7(), 7, 0)])]);
+ let cfg = HashMap::from([(7, settings(Some(100), Some(100)))]);
+
+ let (bypassed, outcomes, to_disable) =
+ evaluate_bypass_rules(&items, &rules_by_team, &cfg, |_rule, _props| Ok(true));
+
+ assert!(bypassed.contains(&0));
+ assert!(to_disable.is_empty());
+ // A bypassed event is tallied under each configured limit so it lines up in the charts.
+ assert_eq!(
+ outcomes.get(&(7, LimitKind::PerIssue, Some(issue), Outcome::Bypassed)),
+ Some(&1)
+ );
+ assert_eq!(
+ outcomes.get(&(7, LimitKind::Project, None, Outcome::Bypassed)),
+ Some(&1)
+ );
+ }
+
+ #[test]
+ fn evaluate_bypass_disables_broken_rule_once_per_batch() {
+ let rule_id = Uuid::now_v7();
+ let items: Vec<_> = (0..3).map(|_| event(7, Some(Uuid::now_v7()))).collect();
+ let rules_by_team = HashMap::from([(7, vec![bypass_rule(rule_id, 7, 0)])]);
+ let cfg = HashMap::from([(7, settings(Some(100), Some(100)))]);
+ let calls = AtomicUsize::new(0);
+
+ let (bypassed, _outcomes, to_disable) =
+ evaluate_bypass_rules(&items, &rules_by_team, &cfg, |_rule, _props| {
+ calls.fetch_add(1, Ordering::Relaxed);
+ Err(VmError::Other("boom".to_string()))
+ });
+
+ // The broken rule is flagged for disabling exactly once even though three events hit its
+ // team, and it is never re-run after the first failure — this is the per-batch dedup.
+ assert_eq!(to_disable.len(), 1);
+ assert_eq!(to_disable[0].rule.id, rule_id);
+ assert_eq!(calls.load(Ordering::Relaxed), 1);
+ // A broken rule bypasses nothing; its events fall through to normal rate limiting.
+ assert!(bypassed.is_empty());
+ }
+
+ #[test]
+ fn evaluate_bypass_step_budget_skips_without_disabling() {
+ let items: Vec<_> = (0..3).map(|_| event(7, Some(Uuid::now_v7()))).collect();
+ let rules_by_team = HashMap::from([(7, vec![bypass_rule(Uuid::now_v7(), 7, 0)])]);
+ let cfg = HashMap::from([(7, settings(Some(100), Some(100)))]);
+ let calls = AtomicUsize::new(0);
+
+ let (bypassed, outcomes, to_disable) =
+ evaluate_bypass_rules(&items, &rules_by_team, &cfg, |_rule, _props| {
+ calls.fetch_add(1, Ordering::Relaxed);
+ Err(VmError::OutOfResource("steps".to_string()))
+ });
+
+ // Step-budget exhaustion is per-event: unlike a broken rule, the rule is not disabled and
+ // is retried on every event.
+ assert!(to_disable.is_empty());
+ assert_eq!(calls.load(Ordering::Relaxed), 3);
+ assert!(bypassed.is_empty());
+ assert!(outcomes.is_empty());
+ }
}
diff --git a/rust/cymbal/src/modes/processing/teams.rs b/rust/cymbal/src/modes/processing/teams.rs
index 584e807640fe..ca04986f0271 100644
--- a/rust/cymbal/src/modes/processing/teams.rs
+++ b/rust/cymbal/src/modes/processing/teams.rs
@@ -8,7 +8,7 @@ use crate::{
error::UnhandledError, metric_consts::ANCILLARY_CACHE,
modes::processing::config::ProcessingConfig,
modes::processing::rules::assignment::AssignmentRule,
- modes::processing::rules::grouping::GroupingRule,
+ modes::processing::rules::bypass::BypassRule, modes::processing::rules::grouping::GroupingRule,
modes::processing::rules::rate_limit::RateLimitSettings,
modes::processing::rules::spike::SpikeDetectionConfig,
modes::processing::rules::suppression::SuppressionRule,
@@ -20,6 +20,7 @@ pub struct TeamManager {
pub assignment_rules: Cache<TeamId, Vec<AssignmentRule>>,
pub grouping_rules: Cache<TeamId, Vec<GroupingRule>>,
pub suppression_rules: Cache<TeamId, Vec<SuppressionRule>>,
+ pub bypass_rules: Cache<TeamId, Vec<BypassRule>>,
pub group_type_indices: Cache<TeamId, Vec<GroupType>>,
pub spike_detection_configs: Cache<TeamId, Option<SpikeDetectionConfig>>,
pub rate_limit_settings: Cache<TeamId, Option<RateLimitSettings>>,
@@ -62,6 +63,15 @@ impl TeamManager {
})
.build();
+ let bypass_rules = CacheBuilder::new(config.max_bypass_rule_cache_size)
+ .time_to_live(Duration::from_secs(config.bypass_rule_cache_ttl_secs))
+ .weigher(|_, v: &Vec<BypassRule>| {
+ v.iter()
+ .map(|rule| rule.bytecode.as_array().map_or(0, Vec::len) as u32)
+ .sum()
+ })
+ .build();
+
let spike_detection_configs = CacheBuilder::new(config.max_team_cache_size)
.time_to_live(Duration::from_secs(config.team_cache_ttl_secs))
.build();
@@ -75,6 +85,7 @@ impl TeamManager {
assignment_rules,
grouping_rules,
suppression_rules,
+ bypass_rules,
group_type_indices,
spike_detection_configs,
rate_limit_settings,
@@ -168,6 +179,26 @@ impl TeamManager {
Ok(rules)
}
+ pub async fn get_bypass_rules<'c, E>(
+ &self,
+ e: E,
+ team_id: TeamId,
+ ) -> Result<Vec<BypassRule>, UnhandledError>
+ where
+ E: sqlx::Executor<'c, Database = sqlx::Postgres>,
+ {
+ if let Some(rules) = self.bypass_rules.get(&team_id) {
+ metrics::counter!(ANCILLARY_CACHE, "type" => "bypass_rules", "outcome" => "hit")
+ .increment(1);
+ return Ok(rules.clone());
+ }
+ metrics::counter!(ANCILLARY_CACHE, "type" => "bypass_rules", "outcome" => "miss")
+ .increment(1);
+ let rules = BypassRule::load_for_team(e, team_id).await?;
+ self.bypass_rules.insert(team_id, rules.clone());
+ Ok(rules)
+ }
+
pub async fn get_spike_detection_config<'c, E>(
&self,
e: E,
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index b0db41315387..39782484b550 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -19081,6 +19081,31 @@ export namespace Schemas {
version?: number | null;
}
+ export interface ErrorTrackingBypassRule {
+ /** Unique identifier of the bypass rule. */
+ readonly id: string;
+ /** Property-group filters that define which incoming error events bypass rate limiting. */
+ filters: unknown;
+ /** Position of the rule in the team's ordered list. Rules are evaluated greedily in ascending order. */
+ order_key: number;
+ /** Populated when the rule has been automatically disabled (for example, after its filters failed to evaluate during ingestion). Null while the rule is active. */
+ disabled_data: unknown;
+ /** When the rule was created. */
+ readonly created_at: string;
+ /** When the rule was last updated. */
+ readonly updated_at: string;
+ }
+
+ export interface ErrorTrackingBypassRuleCreateRequest {
+ /** Property-group filters that define which incoming error events bypass rate limiting. Must contain at least one filter — empty rules are rejected. To stop rate limiting entirely, adjust the rate limit settings instead of creating a match-all bypass rule. */
+ filters: PropertyGroupFilterValue;
+ }
+
+ export interface ErrorTrackingBypassRuleUpdateRequest {
+ /** Property-group filters that define which incoming error events bypass rate limiting. Must contain at least one filter. Omit to preserve the existing filters. */
+ filters?: PropertyGroupFilterValue;
+ }
+
export interface ErrorTrackingDateRange {
/** Start of the date range as an ISO timestamp or relative date such as -7d. Defaults to -7d. */
date_from?: string;
@@ -31303,6 +31328,15 @@ export namespace Schemas {
results: ErrorTrackingAssignmentRule[];
}
+ export interface PaginatedErrorTrackingBypassRuleList {
+ count: number;
+ /** @nullable */
+ next?: string | null;
+ /** @nullable */
+ previous?: string | null;
+ results: ErrorTrackingBypassRule[];
+ }
+
export interface PaginatedErrorTrackingExternalReferenceResultList {
count: number;
/** @nullable */
@@ -36771,6 +36805,26 @@ export namespace Schemas {
assignee?: ErrorTrackingAssignmentRuleAssigneeRequest | null;
}
+ export interface PatchedErrorTrackingBypassRule {
+ /** Unique identifier of the bypass rule. */
+ readonly id?: string;
+ /** Property-group filters that define which incoming error events bypass rate limiting. */
+ filters?: unknown;
+ /** Position of the rule in the team's ordered list. Rules are evaluated greedily in ascending order. */
+ order_key?: number;
+ /** Populated when the rule has been automatically disabled (for example, after its filters failed to evaluate during ingestion). Null while the rule is active. */
+ disabled_data?: unknown;
+ /** When the rule was created. */
+ readonly created_at?: string;
+ /** When the rule was last updated. */
+ readonly updated_at?: string;
+ }
+
+ export interface PatchedErrorTrackingBypassRuleUpdateRequest {
+ /** Property-group filters that define which incoming error events bypass rate limiting. Must contain at least one filter. Omit to preserve the existing filters. */
+ filters?: PropertyGroupFilterValue;
+ }
+
/**
* @nullable
*/
@@ -55609,6 +55663,17 @@ export namespace Schemas {
offset?: number;
};
+ export type EnvironmentsErrorTrackingBypassRulesListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type EnvironmentsErrorTrackingExternalReferencesListParams = {
/**
* Number of results to return per page.
@@ -61759,6 +61824,17 @@ export namespace Schemas {
offset?: number;
};
+ export type ErrorTrackingBypassRulesListParams = {
+ /**
+ * Number of results to return per page.
+ */
+ limit?: number;
+ /**
+ * The initial index from which to return the results.
+ */
+ offset?: number;
+ };
+
export type ErrorTrackingExternalReferencesListParams = {
/**
* Number of results to return per page.