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(cymbal): apply severity rules on issue creation (#86270)

Hugues Pouillot48fe15c2f073
diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.py
index 063783592583..db2bdcd51850 100644
--- a/products/error_tracking/backend/facade/api.py
+++ b/products/error_tracking/backend/facade/api.py
@@ -32,6 +32,7 @@ IssueNotFoundError = logic.ErrorTrackingIssueNotFoundError
ExternalReferenceValidationError = external_references.ErrorTrackingExternalReferenceValidationError
ReleaseHashInUseError = logic.ErrorTrackingReleaseHashInUseError
InvalidBytecodeError = rules.ErrorTrackingInvalidBytecodeError
+SeverityRuleLimitError = rules.ErrorTrackingSeverityRuleLimitError
SOURCE_MAPS_DOCS_URL = contracts.SOURCE_MAPS_DOCS_URL
diff --git a/products/error_tracking/backend/logic/rules.py b/products/error_tracking/backend/logic/rules.py
index b579ee3e5470..29f0b4959336 100644
--- a/products/error_tracking/backend/logic/rules.py
+++ b/products/error_tracking/backend/logic/rules.py
@@ -1,6 +1,7 @@
from typing import Any, TypeVar, cast
from uuid import UUID
+from django.db import transaction
from django.db.models import QuerySet
from products.error_tracking.backend.models import (
@@ -17,11 +18,19 @@ CLIENT_EVALUABLE_PROPERTIES = frozenset({"$exception_types", "$exception_values"
# Regex and numeric coercion differ between posthog-js and the server evaluator, so those rules stay server-side.
CLIENT_EVALUABLE_OPERATORS = frozenset({"exact", "is_not", "icontains", "not_icontains"})
+# Keep these limits in sync with rust/cymbal/src/modes/processing/rules/severity.rs.
+MAX_SEVERITY_RULES_PER_TEAM = 100
+MAX_SEVERITY_RULE_BYTECODE_OPS = 10_000
+
class ErrorTrackingInvalidBytecodeError(Exception):
pass
+class ErrorTrackingSeverityRuleLimitError(Exception):
+ pass
+
+
def _validate_rule_bytecode(bytecode: list[Any]) -> None:
from products.error_tracking.backend.hogvm_stl import RUST_HOGVM_STL # noqa: PLC0415
@@ -160,16 +169,35 @@ def get_severity_rule(team_id: int, rule_id: str) -> ErrorTrackingSeverityRule |
return ErrorTrackingSeverityRule.objects.filter(team_id=team_id, id=rule_id).first()
+def _validate_severity_rule_bytecode(bytecode: list[Any]) -> None:
+ if len(bytecode) > MAX_SEVERITY_RULE_BYTECODE_OPS:
+ raise ErrorTrackingSeverityRuleLimitError(
+ f"Severity rule bytecode cannot exceed {MAX_SEVERITY_RULE_BYTECODE_OPS} operations."
+ )
+
+
def create_severity_rule(
team_id: int, *, filters: dict, severity: str, order_key: int = 0
) -> ErrorTrackingSeverityRule:
- return ErrorTrackingSeverityRule.objects.create(
- team_id=team_id,
- filters=filters,
- bytecode=_rule_bytecode(team_id, filters),
- severity=severity,
- order_key=order_key,
- )
+ from posthog.models.team.team import Team # noqa: PLC0415
+
+ bytecode = _rule_bytecode(team_id, filters)
+ _validate_severity_rule_bytecode(bytecode)
+
+ # Serialize creates for this team so concurrent requests cannot all pass the count check.
+ with transaction.atomic():
+ Team.objects.select_for_update().only("id").get(id=team_id)
+ if ErrorTrackingSeverityRule.objects.filter(team_id=team_id).count() >= MAX_SEVERITY_RULES_PER_TEAM:
+ raise ErrorTrackingSeverityRuleLimitError(
+ f"A project can have at most {MAX_SEVERITY_RULES_PER_TEAM} severity rules."
+ )
+ return ErrorTrackingSeverityRule.objects.create(
+ team_id=team_id,
+ filters=filters,
+ bytecode=bytecode,
+ severity=severity,
+ order_key=order_key,
+ )
def update_severity_rule(
@@ -183,8 +211,10 @@ def update_severity_rule(
if rule is None:
return None
if filters is not None:
+ bytecode = _rule_bytecode(team_id, filters)
+ _validate_severity_rule_bytecode(bytecode)
rule.filters = filters
- rule.bytecode = _rule_bytecode(team_id, filters)
+ rule.bytecode = bytecode
rule.disabled_data = None
if severity is not None:
rule.severity = severity
diff --git a/products/error_tracking/backend/presentation/views/severity_rules.py b/products/error_tracking/backend/presentation/views/severity_rules.py
index 8b19fe3702ef..b3df38acf190 100644
--- a/products/error_tracking/backend/presentation/views/severity_rules.py
+++ b/products/error_tracking/backend/presentation/views/severity_rules.py
@@ -133,7 +133,7 @@ class ErrorTrackingSeverityRuleViewSet(TeamAndOrgViewSetMixin, viewsets.GenericV
filters=request.validated_data.get("filters"),
severity=request.validated_data.get("severity"),
)
- except error_tracking_api.InvalidBytecodeError as err:
+ except (error_tracking_api.InvalidBytecodeError, error_tracking_api.SeverityRuleLimitError) as err:
raise ValidationError(str(err)) from err
if rule is None:
raise NotFound()
@@ -174,7 +174,7 @@ class ErrorTrackingSeverityRuleViewSet(TeamAndOrgViewSetMixin, viewsets.GenericV
severity=request.validated_data["severity"],
order_key=request.validated_data["order_key"],
)
- except error_tracking_api.InvalidBytecodeError as err:
+ except (error_tracking_api.InvalidBytecodeError, error_tracking_api.SeverityRuleLimitError) as err:
raise ValidationError(str(err)) from err
posthoganalytics.capture(
"error_tracking_severity_rule_created",
diff --git a/products/error_tracking/backend/tests/api/test_severity_rules.py b/products/error_tracking/backend/tests/api/test_severity_rules.py
index 6846bd110e25..dca2e96118d0 100644
--- a/products/error_tracking/backend/tests/api/test_severity_rules.py
+++ b/products/error_tracking/backend/tests/api/test_severity_rules.py
@@ -3,6 +3,7 @@ from typing import Any
import pytest
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
from parameterized import parameterized
from rest_framework import status
@@ -11,6 +12,7 @@ from posthog.constants import AvailableFeature
from posthog.models.organization import OrganizationMembership
from posthog.models.user import User
+from products.error_tracking.backend.logic.rules import MAX_SEVERITY_RULE_BYTECODE_OPS, MAX_SEVERITY_RULES_PER_TEAM
from products.error_tracking.backend.models import ErrorTrackingSeverityRule
try:
@@ -73,6 +75,44 @@ class TestSeverityRuleAPI(APIBaseTest):
assert response.json()["attr"] == attr
assert not ErrorTrackingSeverityRule.objects.unscoped().exists()
+ def test_create_rejects_rule_above_project_limit(self) -> None:
+ ErrorTrackingSeverityRule.objects.unscoped().bulk_create(
+ [
+ ErrorTrackingSeverityRule(
+ team=self.team,
+ filters=VALID_FILTERS,
+ bytecode=[],
+ severity="low",
+ order_key=index,
+ )
+ for index in range(MAX_SEVERITY_RULES_PER_TEAM)
+ ]
+ )
+
+ response = self.client.post(
+ self._url(),
+ data={"filters": VALID_FILTERS, "severity": "critical"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert (
+ ErrorTrackingSeverityRule.objects.unscoped().filter(team=self.team).count() == MAX_SEVERITY_RULES_PER_TEAM
+ )
+
+ @patch("products.error_tracking.backend.logic.rules._rule_bytecode")
+ def test_create_rejects_oversized_bytecode(self, mock_rule_bytecode) -> None:
+ mock_rule_bytecode.return_value = [0] * (MAX_SEVERITY_RULE_BYTECODE_OPS + 1)
+
+ response = self.client.post(
+ self._url(),
+ data={"filters": VALID_FILTERS, "severity": "critical"},
+ format="json",
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert not ErrorTrackingSeverityRule.objects.unscoped().exists()
+
def test_update_recompiles_and_clears_disabled_data(self) -> None:
rule = ErrorTrackingSeverityRule.objects.unscoped().create(
team=self.team,
diff --git a/rust/cymbal/src/modes/processing/issue_resolution.rs b/rust/cymbal/src/modes/processing/issue_resolution.rs
index 824256210930..0bc2a0b20772 100644
--- a/rust/cymbal/src/modes/processing/issue_resolution.rs
+++ b/rust/cymbal/src/modes/processing/issue_resolution.rs
@@ -91,7 +91,7 @@ pub enum IssueStatus {
}
#[derive(Debug, Clone, Copy, PartialEq)]
-pub(crate) enum IssueSeverity {
+pub enum IssueSeverity {
Low,
Medium,
High,
@@ -214,6 +214,23 @@ impl Issue {
Ok(issue)
}
+ pub async fn apply_initial_severity<'c, E>(
+ &mut self,
+ severity: String,
+ executor: E,
+ ) -> Result<(), sqlx::Error>
+ where
+ E: sqlx::Executor<'c, Database = sqlx::Postgres>,
+ {
+ sqlx::query("UPDATE posthog_errortrackingissue SET severity = $1 WHERE id = $2")
+ .bind(&severity)
+ .bind(self.id)
+ .execute(executor)
+ .await?;
+ self.severity = Some(severity);
+ Ok(())
+ }
+
pub async fn maybe_reopen<'c, E>(&mut self, executor: E) -> Result<bool, UnhandledError>
where
E: sqlx::Executor<'c, Database = sqlx::Postgres>,
@@ -742,6 +759,30 @@ mod test {
}
}
+ #[sqlx::test(migrations = "./tests/test_migrations")]
+ async fn initial_severity_update_reaches_state_and_notification_payloads(pool: sqlx::PgPool) {
+ let mut issue = super::Issue::insert_new(
+ 1,
+ "TypeError".to_string(),
+ "Example".to_string(),
+ None,
+ &pool,
+ )
+ .await
+ .unwrap();
+
+ issue
+ .apply_initial_severity("critical".to_string(), &pool)
+ .await
+ .unwrap();
+
+ let state =
+ super::FingerprintIssueState::new(&issue, "fingerprint", None, chrono::Utc::now());
+ let snapshot = super::issue_snapshot(&issue);
+ assert_eq!(state.issue_severity.as_deref(), Some("critical"));
+ assert_eq!(snapshot.severity.as_deref(), Some("critical"));
+ }
+
#[tokio::test]
async fn stores_full_event_properties_as_raw_json_with_a_ttl() {
let redis = MockRedisClient::new();
diff --git a/rust/cymbal/src/modes/processing/rules/severity.rs b/rust/cymbal/src/modes/processing/rules/severity.rs
index 5db076835669..de6e41d70755 100644
--- a/rust/cymbal/src/modes/processing/rules/severity.rs
+++ b/rust/cymbal/src/modes/processing/rules/severity.rs
@@ -19,6 +19,13 @@ use crate::{
types::ProcessedExceptionProperties,
};
+// Keep these limits in sync with products/error_tracking/backend/logic/rules.py.
+pub const MAX_SEVERITY_RULES_PER_TEAM: usize = 100;
+pub const MAX_SEVERITY_RULE_BYTECODE_OPS: usize = 10_000;
+pub const MAX_SEVERITY_RULE_STEPS_PER_RULE: usize = 10_000;
+pub const MAX_SEVERITY_RULE_EVALUATION_STEPS_PER_EVENT: usize = 100_000;
+const AGGREGATE_STEP_BUDGET_RESOURCE: &str = "severity_rules_aggregate_steps";
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RuleSeverity {
Low,
@@ -63,9 +70,11 @@ impl SeverityRule {
FROM posthog_errortrackingseverityrule
WHERE team_id = $1 AND disabled_data IS NULL
ORDER BY order_key, created_at, id
+ LIMIT $2
"#,
)
.bind(team_id)
+ .bind(MAX_SEVERITY_RULES_PER_TEAM as i64)
.fetch_all(executor)
.await
}
@@ -124,9 +133,26 @@ impl SeverityRule {
&self,
issue: &Value,
properties: &Value,
+ ) -> Result<Option<RuleSeverity>, VmError> {
+ let mut remaining_steps = usize::MAX;
+ self.try_match_with_budget(issue, properties, &mut remaining_steps)
+ }
+
+ fn try_match_with_budget(
+ &self,
+ issue: &Value,
+ properties: &Value,
+ remaining_steps: &mut usize,
) -> Result<Option<RuleSeverity>, VmError> {
let rule_bytecode = match &self.bytecode {
- Value::Array(ops) => ops,
+ Value::Array(ops) if ops.len() <= MAX_SEVERITY_RULE_BYTECODE_OPS => ops,
+ Value::Array(ops) => {
+ return Err(VmError::Other(format!(
+ "Severity rule bytecode has {} operations, maximum is {}",
+ ops.len(),
+ MAX_SEVERITY_RULE_BYTECODE_OPS
+ )))
+ }
_ => {
return Err(VmError::Other(format!(
"Invalid rule bytecode - expected array, got {:?}",
@@ -140,14 +166,27 @@ impl SeverityRule {
("properties".to_string(), properties.clone()),
]));
let program = Program::new(rule_bytecode.clone())?;
- let context = ExecutionContext::with_defaults(program).with_globals(globals);
+ let context = ExecutionContext::with_defaults(program)
+ .with_globals(globals)
+ .with_max_steps(MAX_SEVERITY_RULE_STEPS_PER_RULE);
let mut vm = context.to_vm()?;
metrics::counter!(SEVERITY_RULES_TRIED).increment(1);
+ let step_limit = context.max_steps.min(*remaining_steps);
+ if step_limit == 0 {
+ return Err(VmError::OutOfResource(
+ AGGREGATE_STEP_BUDGET_RESOURCE.to_string(),
+ ));
+ }
+
let mut steps = 0;
- while steps < context.max_steps {
- match vm.step()? {
+ while steps < step_limit {
+ let outcome = vm.step()?;
+ steps += 1;
+ *remaining_steps -= 1;
+
+ match outcome {
StepOutcome::Finished(Value::Bool(true)) => {
return self.parsed_severity().map(Some)
}
@@ -162,10 +201,14 @@ impl SeverityRule {
}
StepOutcome::Continue => {}
}
- steps += 1;
}
- Err(VmError::OutOfResource("steps".to_string()))
+ let resource = if *remaining_steps == 0 {
+ AGGREGATE_STEP_BUDGET_RESOURCE
+ } else {
+ "steps"
+ };
+ Err(VmError::OutOfResource(resource.to_string()))
}
}
@@ -201,15 +244,25 @@ pub async fn try_severity_rules(
description: issue.description.clone(),
})?;
let properties_json = serde_json::to_value(exception_properties)?;
+ let mut remaining_steps = MAX_SEVERITY_RULE_EVALUATION_STEPS_PER_EVENT;
for rule in rules {
- match rule.try_match(&issue_json, &properties_json) {
+ match rule.try_match_with_budget(&issue_json, &properties_json, &mut remaining_steps) {
Ok(None) => continue,
Ok(Some(severity)) => {
metrics::counter!(SEVERITY_RULES_MATCHED).increment(1);
timing.label("outcome", "match").fin();
return Ok(Some(severity));
}
+ Err(VmError::OutOfResource(resource)) if resource == AGGREGATE_STEP_BUDGET_RESOURCE => {
+ tracing::warn!(
+ team_id = %rule.team_id,
+ max_steps = MAX_SEVERITY_RULE_EVALUATION_STEPS_PER_EVENT,
+ "severity rules exceeded aggregate HogVM step budget for this event"
+ );
+ timing.label("outcome", "budget_exhausted").fin();
+ return Ok(None);
+ }
Err(VmError::OutOfResource(resource)) if resource == "steps" => {
tracing::warn!(
rule_id = %rule.id,
diff --git a/rust/cymbal/src/modes/processing/stages/linking/issue.rs b/rust/cymbal/src/modes/processing/stages/linking/issue.rs
index cb1c2b31bfa8..34539445754d 100644
--- a/rust/cymbal/src/modes/processing/stages/linking/issue.rs
+++ b/rust/cymbal/src/modes/processing/stages/linking/issue.rs
@@ -15,6 +15,7 @@ use crate::{
},
metric_consts::{ISSUE_CREATED, ISSUE_LINKER_OPERATOR},
modes::processing::rules::assignment::{try_assignment_rules, Assignment},
+ modes::processing::rules::severity::try_severity_rules,
stages::linking::LinkingStage,
teams::TeamManager,
types::{
@@ -360,6 +361,13 @@ async fn resolve_issue(
}
} else {
metrics::counter!(ISSUE_CREATED).increment(1);
+ process_event_severity(
+ &mut txn,
+ &context.team_manager,
+ &mut issue,
+ event_properties,
+ )
+ .await?;
let assignment =
process_event_assignment(&mut txn, &context.team_manager, &issue, event_properties)
.await?;
@@ -391,6 +399,23 @@ async fn resolve_issue(
Ok(issue)
}
+async fn process_event_severity(
+ connection: &mut PgConnection,
+ team_manager: &TeamManager,
+ issue: &mut Issue,
+ exception_properties: &ExceptionEvent<Fingerprinted>,
+) -> Result<(), UnhandledError> {
+ let processed_properties = exception_properties.processed_properties(issue);
+ if let Some(severity) =
+ try_severity_rules(connection, team_manager, issue, &processed_properties).await?
+ {
+ issue
+ .apply_initial_severity(severity.to_string(), connection)
+ .await?;
+ }
+ Ok(())
+}
+
async fn process_event_assignment(
conn: &mut PgConnection,
team_manager: &TeamManager,
diff --git a/rust/cymbal/tests/event.rs b/rust/cymbal/tests/event.rs
index 72d0295f362f..3687ec6ab374 100644
--- a/rust/cymbal/tests/event.rs
+++ b/rust/cymbal/tests/event.rs
@@ -328,6 +328,22 @@ async fn insert_symbol_set_record(db: &PgPool, team_id: i32, chunk_id: &str) {
record.save(db).await.expect("Failed to insert record");
}
+async fn insert_severity_rule(db: &PgPool, severity: &str, bytecode: JsonValue) {
+ sqlx::query(
+ r#"
+ INSERT INTO posthog_errortrackingseverityrule
+ (id, team_id, filters, bytecode, severity, order_key, created_at, updated_at)
+ VALUES ($1, 1, '{}'::jsonb, $2, $3, 0, NOW(), NOW())
+ "#,
+ )
+ .bind(Uuid::now_v7())
+ .bind(bytecode)
+ .bind(severity)
+ .execute(db)
+ .await
+ .expect("Severity rule should be inserted");
+}
+
// Helper to extract exception list from response
fn extract_exception_list(response: &SuccessResponse) -> ExceptionList {
let event = response.first_event();
@@ -422,6 +438,63 @@ async fn new_issue_only_infers_confident_severity_without_overwriting_existing_s
assert_eq!(severity.as_deref(), Some("low"));
}
+#[sqlx::test(migrations = "./tests/test_migrations")]
+async fn severity_rule_overrides_inference_only_for_new_issue(db: PgPool) {
+ let harness = TestHarness::new(db);
+ insert_severity_rule(&harness.db, "critical", json!(["_H", 1, 29, 38])).await;
+ let mut input = make_event_with_options(
+ vec![make_exception("TypeError", "cannot read property")],
+ Some("severity-rule"),
+ Some(false),
+ );
+ input.properties["$exception_level"] = json!("error");
+
+ let (status, body): (_, SuccessResponse) = harness.post_event(&input).await;
+ assert!(status.is_success());
+ let issue_id = body.take_properties().issue_id();
+ let initial_severity: Option<String> =
+ sqlx::query_scalar("SELECT severity FROM posthog_errortrackingissue WHERE id = $1")
+ .bind(issue_id)
+ .fetch_one(&harness.db)
+ .await
+ .unwrap();
+ assert_eq!(initial_severity.as_deref(), Some("critical"));
+
+ sqlx::query("UPDATE posthog_errortrackingissue SET severity = 'low' WHERE id = $1")
+ .bind(issue_id)
+ .execute(&harness.db)
+ .await
+ .unwrap();
+ let (status, _): (_, SuccessResponse) = harness.post_event(&input).await;
+ assert!(status.is_success());
+ let existing_severity: Option<String> =
+ sqlx::query_scalar("SELECT severity FROM posthog_errortrackingissue WHERE id = $1")
+ .bind(issue_id)
+ .fetch_one(&harness.db)
+ .await
+ .unwrap();
+ assert_eq!(existing_severity.as_deref(), Some("low"));
+}
+
+#[sqlx::test(migrations = "./tests/test_migrations")]
+async fn unmatched_severity_rule_preserves_inference(db: PgPool) {
+ let harness = TestHarness::new(db);
+ insert_severity_rule(&harness.db, "low", json!(["_H", 1, 30, 38])).await;
+ let mut input = make_event(vec![make_exception("TypeError", "cannot read property")]);
+ input.properties["$exception_level"] = json!("fatal");
+
+ let (status, body): (_, SuccessResponse) = harness.post_event(&input).await;
+ assert!(status.is_success());
+ let issue_id = body.take_properties().issue_id();
+ let severity: Option<String> =
+ sqlx::query_scalar("SELECT severity FROM posthog_errortrackingissue WHERE id = $1")
+ .bind(issue_id)
+ .fetch_one(&harness.db)
+ .await
+ .unwrap();
+ assert_eq!(severity.as_deref(), Some("critical"));
+}
+
#[sqlx::test(migrations = "./tests/test_migrations")]
async fn processed_properties_wire_shape_is_stable(db: PgPool) {
let harness = TestHarness::new(db);
diff --git a/rust/cymbal/tests/severity_rules.rs b/rust/cymbal/tests/severity_rules.rs
index 8725e88a3c01..843efc3b1ea4 100644
--- a/rust/cymbal/tests/severity_rules.rs
+++ b/rust/cymbal/tests/severity_rules.rs
@@ -2,7 +2,11 @@ use chrono::Utc;
use cymbal::{
issue_resolution::{Issue, IssueStatus},
modes::processing::{
- rules::severity::{try_severity_rules, SeverityRule},
+ rules::severity::{
+ try_severity_rules, SeverityRule, MAX_SEVERITY_RULES_PER_TEAM,
+ MAX_SEVERITY_RULE_BYTECODE_OPS, MAX_SEVERITY_RULE_EVALUATION_STEPS_PER_EVENT,
+ MAX_SEVERITY_RULE_STEPS_PER_RULE,
+ },
ProcessingConfig,
},
teams::TeamManager,
@@ -90,6 +94,17 @@ fn supports_every_issue_severity() {
}
}
+#[test]
+fn rejects_oversized_bytecode() {
+ let issue = json!({"status": "active", "name": "TypeError", "description": "Example"});
+ let properties = serde_json::to_value(properties()).unwrap();
+ let oversized = json!(vec![0; MAX_SEVERITY_RULE_BYTECODE_OPS + 1]);
+
+ let result = rule(1, "high", 0, oversized).try_match(&issue, &properties);
+
+ assert!(result.is_err());
+}
+
#[sqlx::test(migrations = "./tests/test_migrations")]
async fn loads_only_enabled_rules_for_the_requested_team(db: PgPool) {
let enabled = rule(1, "high", 0, bytecode(true));
@@ -105,6 +120,19 @@ async fn loads_only_enabled_rules_for_the_requested_team(db: PgPool) {
assert_eq!(loaded[0].id, enabled.id);
}
+#[sqlx::test(migrations = "./tests/test_migrations")]
+async fn loads_at_most_the_per_team_rule_limit(db: PgPool) {
+ for order_key in 0..=MAX_SEVERITY_RULES_PER_TEAM {
+ let rule = rule(1, "high", order_key as i32, bytecode(false));
+ insert_rule(&db, &rule, false).await;
+ }
+
+ let loaded = SeverityRule::load_for_team(&db, 1).await.unwrap();
+
+ assert_eq!(loaded.len(), MAX_SEVERITY_RULES_PER_TEAM);
+ assert_eq!(loaded.last().unwrap().order_key, 99);
+}
+
#[sqlx::test(migrations = "./tests/test_migrations")]
async fn first_matching_rule_wins_and_no_match_preserves_fallback(db: PgPool) {
let config = ProcessingConfig::init_with_defaults().unwrap();
@@ -158,6 +186,32 @@ async fn exact_order_ties_use_rule_id(db: PgPool) {
assert_eq!(matched.unwrap().to_string(), "low");
}
+#[sqlx::test(migrations = "./tests/test_migrations")]
+async fn aggregate_step_budget_stops_evaluating_later_rules(db: PgPool) {
+ let config = ProcessingConfig::init_with_defaults().unwrap();
+ let manager = TeamManager::new(&config);
+ let team_id = 1;
+ let rules_to_exhaust_budget =
+ MAX_SEVERITY_RULE_EVALUATION_STEPS_PER_EVENT / MAX_SEVERITY_RULE_STEPS_PER_RULE;
+ let mut rules = (0..rules_to_exhaust_budget)
+ .map(|order_key| rule(team_id, "low", order_key as i32, json!(["_H", 1, 39, -2])))
+ .collect::<Vec<_>>();
+ rules.push(rule(
+ team_id,
+ "critical",
+ rules_to_exhaust_budget as i32,
+ bytecode(true),
+ ));
+ manager.severity_rules.insert(team_id, rules);
+ let mut conn = db.acquire().await.unwrap();
+
+ let matched = try_severity_rules(&mut conn, &manager, &issue(team_id), &properties())
+ .await
+ .unwrap();
+
+ assert!(matched.is_none());
+}
+
#[sqlx::test(migrations = "./tests/test_migrations")]
async fn invalid_rule_is_disabled_and_later_rule_still_matches(db: PgPool) {
let config = ProcessingConfig::init_with_defaults().unwrap();