:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(error-tracking): infer new issue severity with a decision model (#106741)
Hugues Pouillot1298298e2e1d
diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 70b2698b7608..895aba92fa3b 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -1201,11 +1201,13 @@ def _report_activity_log_write_failure(e: Exception, error_context: dict, deferrACTIVITY_LOG_WRITE_FAILURES.labels(deferred=str(deferred).lower()).inc()-def _handle_activity_log_transaction(create_fn, error_context: dict, *, using: str | None = None):+def _handle_activity_log_transaction(create_fn, error_context: dict, *, using: str | None = None, strict: bool = False):try:# Check if we're in a transaction, if yes, defer the activity log creation to the commit signal- if not transaction.get_autocommit(using=using) and getattr(- settings, "ACTIVITY_LOG_TRANSACTION_MANAGEMENT", True+ if (+ not strict+ and not transaction.get_autocommit(using=using)+ and getattr(settings, "ACTIVITY_LOG_TRANSACTION_MANAGEMENT", True)):# The transaction already committed by the time this callback runs, so its own guard# keeps a slow audit write from failing a request whose data is already durable.@@ -1223,6 +1225,8 @@ def _handle_activity_log_transaction(create_fn, error_context: dict, *, using: sreturn create_fn()except Exception as e:+ if strict:+ raise_report_activity_log_write_failure(e, error_context, deferred=False)if settings.TEST:raise@@ -1277,6 +1281,7 @@ def log_activity(# A product on its own database passes `router.db_for_write(Model)`, so the audit write waits# for that connection's commit and is dropped when it rolls back. `None` uses the default one.using: str | None = None,+ strict: bool = False,) -> ActivityLog | None:if client is None:client = activity_storage.get_client()@@ -1345,6 +1350,7 @@ def log_activity("activity": activity,},using=using,+ strict=strict,)except Exception as e:@@ -1357,7 +1363,7 @@ def log_activity(exception=e,)capture_exception(e)- if settings.TEST:+ if settings.TEST or strict:raisereturn Nonediff --git a/posthog/test/activity_logging/test_activity_logging.py b/posthog/test/activity_logging/test_activity_logging.pyindex 340047cc4fb4..0adaadc7aca2 100644--- a/posthog/test/activity_logging/test_activity_logging.py+++ b/posthog/test/activity_logging/test_activity_logging.py@@ -8,6 +8,7 @@ import pytestfrom posthog.test.base import APIBaseTest, BaseTestfrom unittest.mock import patch+from django.db import transactionfrom django.db.utils import IntegrityErrorfrom django.test import override_settingsfrom django.utils import timezone@@ -415,6 +416,23 @@ class TestActivityLogModel(BaseTest):self.assertEqual(warning.args[0], "activity_log.failed_to_write_to_activity_log")self.assertIsInstance(warning.kwargs["exception"], IntegrityError)+ def test_strict_write_failure_escapes_active_transaction(self) -> None:+ with self.settings(TEST=False, ACTIVITY_LOG_TRANSACTION_MANAGEMENT=True):+ with patch.object(ActivityLog.objects, "create", side_effect=IntegrityError("write timed out")):+ with self.assertRaises(IntegrityError):+ with transaction.atomic():+ log_activity(+ organization_id=self.organization.id,+ team_id=self.team.id,+ user=self.user,+ was_impersonated=False,+ item_id="12345",+ scope="FeatureFlag",+ activity="updated",+ detail=Detail(changes=[Change(type="FeatureFlag", field="active", action="created")]),+ strict=True,+ )+def test_does_not_throw_if_cannot_log_activity(self) -> None:# Assert on the module logger directly instead of assertLogs: the root logger sits at# ERROR under test settings, so whether the warning reaches a root handler depends ondiff --git a/products/error_tracking/backend/logic/severity_inference.py b/products/error_tracking/backend/logic/severity_inference.pynew file mode 100644index 000000000000..133c0ffe464a--- /dev/null+++ b/products/error_tracking/backend/logic/severity_inference.py@@ -0,0 +1,170 @@+from urllib.parse import urlparse+from uuid import UUID++from django.conf import settings+from django.db import transaction+from django.utils import timezone++import structlog++from posthog.dataclasses import frozen+from posthog.models.activity_logging.activity_log import Change, Detail, log_activity+from posthog.ph_client import feature_enabled_or_false++from products.error_tracking.backend.models import ErrorTrackingIssue, sync_issues_to_clickhouse+from products.ml_inference.backend.facade import api as ml_inference+from products.ml_inference.backend.facade.contracts import ChoiceAnswer, DecisionQuestion, DecisionRequest+from products.ml_inference.backend.facade.enums import DecisionQuestionType++logger = structlog.get_logger(__name__)++SEVERITY_INFERENCE_FLAG = "error-tracking-severity-inference"+SEVERITY_INFERENCE_MODEL = "posthog/hogference/jevk5-fp8-0.2"++_SEVERITY_QUESTION_ID = "severity"+_SEVERITY_QUESTION = DecisionQuestion(+ type=DecisionQuestionType.CHOICE,+ instructions="How severe is this error for the people using the application?",+ criteria={+ ErrorTrackingIssue.Severity.CRITICAL.value: "Crashes the app, loses data, or blocks a core flow such as sign-in, checkout or payment",+ ErrorTrackingIssue.Severity.HIGH.value: "Breaks a feature for the users who hit it, with no workaround",+ ErrorTrackingIssue.Severity.MEDIUM.value: "Degrades a feature, or the app recovers or retries on its own",+ ErrorTrackingIssue.Severity.LOW.value: "Noise with no user impact, such as expected errors, cancelled requests, or browser extension and third-party script errors",+ },+)+++def severity_inference_enabled(team_id: int) -> bool:+ # The analytics SDK is disabled in local dev, so the flag always reads as off there.+ if settings.DEBUG:+ return True+ try:+ return feature_enabled_or_false(+ SEVERITY_INFERENCE_FLAG,+ str(team_id),+ groups={"project": str(team_id)},+ group_properties={"project": {"id": str(team_id)}},+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ )+ except Exception:+ logger.exception("error_tracking_severity_inference_flag_check_failed", team_id=team_id)+ return False+++def build_severity_state(stacktrace: str, event_properties: dict[str, object]) -> str:+ lines = [stacktrace.rstrip("\n")]+ handled = _mechanism_handled(event_properties)+ if handled is not None:+ lines.append(f"Handled by the application: {'yes' if handled else 'no'}")+ level = event_properties.get("$exception_level")+ if isinstance(level, str) and level:+ lines.append(f"Level: {level}")+ page = _page_without_query(event_properties.get("$current_url"))+ if page:+ lines.append(f"Page: {page}")+ library = event_properties.get("$lib")+ if isinstance(library, str) and library:+ lines.append(f"SDK: {library}")+ return "\n".join(lines)+++def _mechanism_handled(event_properties: dict[str, object]) -> bool | None:+ # Same source as cymbal's severity heuristic: the first exception's mechanism, not `$exception_handled`.+ exception_list = event_properties.get("$exception_list")+ if not isinstance(exception_list, list) or not exception_list or not isinstance(exception_list[0], dict):+ return None+ mechanism = exception_list[0].get("mechanism")+ handled = mechanism.get("handled") if isinstance(mechanism, dict) else None+ return handled if isinstance(handled, bool) else None+++def _page_without_query(current_url: object) -> str | None:+ # URL userinfo, query strings, and fragments can carry secrets or personal data; the path names the feature.+ if not isinstance(current_url, str) or not current_url:+ return None+ try:+ parsed = urlparse(current_url)+ hostname = parsed.hostname+ port = parsed.port+ except ValueError:+ return None+ if not hostname:+ return None+ authority = f"[{hostname}]" if ":" in hostname else hostname+ if port is not None:+ authority = f"{authority}:{port}"+ return f"{authority}{parsed.path}"+++def infer_severity(team_id: int, state: str) -> ChoiceAnswer | None:+ """Ask the decision model for a severity. Raises the ml_inference gateway errors unchanged."""+ result = ml_inference.decide(+ DecisionRequest(+ team_id=team_id,+ state=state,+ questions={_SEVERITY_QUESTION_ID: _SEVERITY_QUESTION},+ model=SEVERITY_INFERENCE_MODEL,+ )+ )+ answer = result.answers.get(_SEVERITY_QUESTION_ID)+ if not isinstance(answer, ChoiceAnswer) or answer.choice not in ErrorTrackingIssue.Severity.values:+ logger.warning("error_tracking_severity_inference_unexpected_answer", team_id=team_id, answer=repr(answer))+ return None+ return answer+++@frozen+class InferredSeverityWrite:+ inferred_severity: str+ stored_severity: str | None++ @property+ def applied(self) -> bool:+ return self.stored_severity == self.inferred_severity+++def apply_inferred_severity(+ team_id: int, issue_id: UUID | str, *, expected: str | None, inferred: str+) -> InferredSeverityWrite:+ """Set a model-inferred severity unless the severity changed after ingestion set `expected`."""+ if expected != inferred:+ with transaction.atomic():+ # The conditional update keeps a severity that a person or a rule set while the model ran.+ updated = ErrorTrackingIssue.objects.filter(team_id=team_id, id=issue_id, severity=expected).update(+ severity=inferred, state_updated_at=timezone.now()+ )+ if updated:+ _log_inferred_severity(team_id, issue_id, expected=expected, inferred=inferred)++ write = InferredSeverityWrite(+ inferred_severity=inferred,+ stored_severity=ErrorTrackingIssue.objects.filter(team_id=team_id, id=issue_id)+ .values_list("severity", flat=True)+ .first(),+ )+ if write.applied:+ # Sync even when this call wrote nothing: a retry after a failed sync finds the severity+ # already stored, and the sync is idempotent.+ sync_issues_to_clickhouse(issue_ids=[issue_id], team_id=team_id)+ return write+++def _log_inferred_severity(team_id: int, issue_id: UUID | str, *, expected: str | None, inferred: str) -> None:+ issue = ErrorTrackingIssue.objects.select_related("team").get(team_id=team_id, id=issue_id)+ log_activity(+ organization_id=issue.team.organization_id,+ team_id=team_id,+ user=None,+ was_impersonated=False,+ item_id=str(issue.id),+ scope="ErrorTrackingIssue",+ activity="updated",+ strict=True,+ detail=Detail(+ name=issue.name,+ changes=[+ Change(type="ErrorTrackingIssue", field="severity", before=expected, after=inferred, action="changed")+ ],+ ),+ )diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_created/__init__.py b/products/error_tracking/backend/temporal/lifecycle/issue_created/__init__.pyindex 209e831926ad..295c7d020290 100644--- a/products/error_tracking/backend/temporal/lifecycle/issue_created/__init__.py+++ b/products/error_tracking/backend/temporal/lifecycle/issue_created/__init__.py@@ -3,6 +3,7 @@ from products.error_tracking.backend.temporal.lifecycle.issue_created.activitiesemit_issue_created_internal_event_activity,emit_issue_created_signal_activity,generate_issue_created_embedding_activity,+ infer_issue_created_severity_activity,merge_issue_created_fingerprint_activity,persist_issue_created_embedding_activity,)@@ -18,6 +19,7 @@ __all__ = ["emit_issue_created_internal_event_activity","emit_issue_created_signal_activity","generate_issue_created_embedding_activity",+ "infer_issue_created_severity_activity","merge_issue_created_fingerprint_activity","persist_issue_created_embedding_activity",]diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py b/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.pyindex eb78059a9067..97b0e4783dbc 100644--- a/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py+++ b/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py@@ -14,11 +14,18 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.api.embedding_worker import generate_embeddingfrom posthog.kafka_client.routing import producer_scopefrom posthog.kafka_client.topics import KAFKA_DOCUMENT_EMBEDDINGS_TOPIC+from posthog.llm.gateway_client import GatewayNotConfiguredErrorfrom posthog.models import Teamfrom posthog.temporal.common.posthog_client import is_expected_activity_failurefrom posthog.temporal.common.scoped import scoped_temporalfrom posthog.temporal.common.utils import close_db_connections+from products.error_tracking.backend.logic.severity_inference import (+ apply_inferred_severity,+ build_severity_state,+ infer_severity,+ severity_inference_enabled,+)from products.error_tracking.backend.temporal.fingerprint_embedding_result.activities import merge_similar_fingerprintsfrom products.error_tracking.backend.temporal.fingerprint_embedding_result.types import (FingerprintEmbeddingMergeResult,@@ -27,9 +34,12 @@ from products.error_tracking.backend.temporal.fingerprint_embedding_result.typesfrom products.error_tracking.backend.temporal.lifecycle.event_properties import fetch_event_propertiesfrom products.error_tracking.backend.temporal.lifecycle.issue_created.types import (EMBEDDING_SERVICE_UNAVAILABLE_ERROR_TYPE,+ SEVERITY_INFERENCE_UNAVAILABLE_ERROR_TYPE,GeneratedIssueEmbedding,IssueCreatedWorkflowInputs,IssueEmbeddingPreparationResult,+ IssueSeverityInferenceResult,+ SeverityInferenceSkipReason,)from products.error_tracking.backend.temporal.lifecycle.rendering import render_stacktracefrom products.error_tracking.backend.temporal.lifecycle.side_effects import (@@ -38,6 +48,11 @@ from products.error_tracking.backend.temporal.lifecycle.side_effects import (emit_issue_lifecycle_signal,produce_issue_lifecycle_internal_event,)+from products.ml_inference.backend.facade.contracts import (+ DecisionGatewayError,+ DecisionGatewayUnreachableError,+ DecisionsDisabledError,+)logger = structlog.get_logger(__name__)@@ -45,7 +60,13 @@ EMBEDDING_MODEL = "text-embedding-3-large-3072"EMBEDDING_RENDERING = "type_message_and_stack"EMBEDDING_MAX_TOKENS = 7000EMBEDDING_DISABLED_LIBRARIES = {"posthog-elixir"}+SEVERITY_INFERENCE_MAX_TOKENS = 2000+ERROR_TRACKING_SEVERITY_INFERENCE_OUTCOMES = Counter(+ "error_tracking_issue_created_severity_inference_total",+ "Issue-created severity inference attempts by outcome and by the severity stored afterwards",+ labelnames=("outcome", "severity"),+)ERROR_TRACKING_EMBEDDING_UNAVAILABLE = Counter("error_tracking_issue_created_embedding_unavailable_total","Issue-created embedding attempts that failed because the embedding service was unavailable",@@ -153,6 +174,108 @@ def generate_issue_created_embedding_activity(raise+def _severity_state(inputs: IssueCreatedWorkflowInputs) -> str | SeverityInferenceSkipReason:+ """Build the text the model reads, or say why this issue is not eligible."""+ if not severity_inference_enabled(inputs.team_id):+ return SeverityInferenceSkipReason.DISABLED+ try:+ team = Team.objects.select_related("organization").get(id=inputs.team_id)+ except Team.DoesNotExist:+ return SeverityInferenceSkipReason.TEAM_MISSING+ if not team.organization.is_ai_data_processing_approved:+ return SeverityInferenceSkipReason.AI_DATA_PROCESSING_NOT_APPROVED++ event_properties = fetch_event_properties(team, inputs)+ stacktrace = render_stacktrace(event_properties, SEVERITY_INFERENCE_MAX_TOKENS)+ if not stacktrace:+ return SeverityInferenceSkipReason.NO_EXCEPTION+ return build_severity_state(stacktrace, event_properties)+++def _decision_error_skip_reason(inputs: IssueCreatedWorkflowInputs, error: Exception) -> SeverityInferenceSkipReason:+ """Skip on a failure that a retry cannot fix. Raise a retryable error on a transient one."""+ match error:+ case DecisionsDisabledError() | GatewayNotConfiguredError():+ return SeverityInferenceSkipReason.DECISIONS_UNAVAILABLE+ case DecisionGatewayUnreachableError():+ raise ApplicationError(+ "Severity model is unreachable", type=SEVERITY_INFERENCE_UNAVAILABLE_ERROR_TYPE+ ) from error+ case DecisionGatewayError(status_code=status_code) if status_code == 429 or status_code >= 500:+ raise ApplicationError(+ f"Severity model returned status {status_code}", type=SEVERITY_INFERENCE_UNAVAILABLE_ERROR_TYPE+ ) from error+ case DecisionGatewayError(status_code=status_code):+ logger.warning(+ "error_tracking_severity_inference_rejected",+ team_id=inputs.team_id,+ issue_id=inputs.issue_id,+ status_code=status_code,+ )+ return SeverityInferenceSkipReason.GATEWAY_REJECTED+ raise error+++def _infer_issue_created_severity(inputs: IssueCreatedWorkflowInputs) -> IssueSeverityInferenceResult:+ state = _severity_state(inputs)+ if isinstance(state, SeverityInferenceSkipReason):+ return IssueSeverityInferenceResult(skipped_reason=state)+ try:+ answer = infer_severity(inputs.team_id, state)+ except (+ DecisionsDisabledError,+ GatewayNotConfiguredError,+ DecisionGatewayError,+ DecisionGatewayUnreachableError,+ ) as error:+ return IssueSeverityInferenceResult(skipped_reason=_decision_error_skip_reason(inputs, error))+ if answer is None:+ return IssueSeverityInferenceResult(skipped_reason=SeverityInferenceSkipReason.UNEXPECTED_ANSWER)++ logger.info(+ "error_tracking_severity_inferred",+ team_id=inputs.team_id,+ issue_id=inputs.issue_id,+ severity=answer.choice,+ confidence=answer.confidence,+ ingestion_severity=inputs.issue.severity,+ ingestion_severity_source=inputs.severity_source,+ )+ if answer.choice == inputs.issue.severity:+ return IssueSeverityInferenceResult(resolved=True, stored_severity=answer.choice)+ write = apply_inferred_severity(+ inputs.team_id, inputs.issue_id, expected=inputs.issue.severity, inferred=answer.choice+ )+ return IssueSeverityInferenceResult(+ resolved=True,+ stored_severity=write.stored_severity,+ skipped_reason=None if write.applied else SeverityInferenceSkipReason.SEVERITY_CHANGED,+ )++[email protected](capture_exceptions=False)+@close_db_connections+def infer_issue_created_severity_activity(inputs: IssueCreatedWorkflowInputs) -> IssueSeverityInferenceResult:+ ingestion_severity = inputs.issue.severity or "none"+ try:+ result = _infer_issue_created_severity(inputs)+ except ApplicationError as error:+ if error.type == SEVERITY_INFERENCE_UNAVAILABLE_ERROR_TYPE:+ ERROR_TRACKING_SEVERITY_INFERENCE_OUTCOMES.labels(outcome="unavailable", severity=ingestion_severity).inc()+ elif not is_expected_activity_failure(error):+ posthoganalytics.capture_exception(error)+ raise+ except Exception as error:+ if not is_expected_activity_failure(error):+ posthoganalytics.capture_exception(error)+ raise+ ERROR_TRACKING_SEVERITY_INFERENCE_OUTCOMES.labels(+ outcome=result.skipped_reason or "inferred", severity=result.stored_severity or ingestion_severity+ ).inc()+ return result++# The three activities below add no properties of their own, so the shared activity interceptor# is the better reporter: it knows which failures are expected.@activity.defn@@ -239,6 +362,7 @@ ACTIVITIES = [generate_issue_created_embedding_activity,persist_issue_created_embedding_activity,merge_issue_created_fingerprint_activity,+ infer_issue_created_severity_activity,emit_issue_created_internal_event_activity,emit_issue_created_signal_activity,]diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_created/test/test_workflow.py b/products/error_tracking/backend/temporal/lifecycle/issue_created/test/test_workflow.pyindex 45b36dc12ed7..a3d109bbd9d0 100644--- a/products/error_tracking/backend/temporal/lifecycle/issue_created/test/test_workflow.py+++ b/products/error_tracking/backend/temporal/lifecycle/issue_created/test/test_workflow.py@@ -16,6 +16,7 @@ from temporalio.worker import UnsandboxedWorkflowRunner, Workerfrom posthog.helpers.tiktoken_encoding import LLM_TOKEN_COUNT_PROXY_MODEL, get_tiktoken_encoding_for_model+from products.error_tracking.backend.logic.severity_inference import build_severity_statefrom products.error_tracking.backend.temporal.fingerprint_embedding_result.types import (FingerprintEmbeddingMergeResult,FingerprintEmbeddingResultInputs,@@ -26,17 +27,29 @@ from products.error_tracking.backend.temporal.lifecycle.event_properties import)from products.error_tracking.backend.temporal.lifecycle.issue_created.activities import (generate_issue_created_embedding_activity,+ infer_issue_created_severity_activity,)from products.error_tracking.backend.temporal.lifecycle.issue_created.types import (EMBEDDING_SERVICE_UNAVAILABLE_ERROR_TYPE,+ SEVERITY_INFERENCE_UNAVAILABLE_ERROR_TYPE,GeneratedIssueEmbedding,IssueCreatedSnapshot,IssueCreatedWorkflowInputs,IssueCreatedWorkflowResult,IssueEmbeddingPreparationResult,+ IssueSeverityInferenceResult,+ SeverityInferenceSkipReason,+ SeveritySource,)from products.error_tracking.backend.temporal.lifecycle.issue_created.workflow import ErrorTrackingIssueCreatedWorkflowfrom products.error_tracking.backend.temporal.lifecycle.rendering import decode_token_prefix, render_stacktrace+from products.ml_inference.backend.facade.contracts import (+ ChoiceAnswer,+ DecisionGatewayError,+ DecisionGatewayUnreachableError,+ DecisionResult,+ DecisionsDisabledError,+)def _inputs(fingerprint: str) -> IssueCreatedWorkflowInputs:@@ -77,6 +90,37 @@ def test_decode_token_prefix_does_not_emit_replacement_characters() -> None:assert decode_token_prefix(encoding, tokens, max_tokens=2) == "hello"+ "properties,expected",+ [+ (+ {+ "$exception_list": [{"type": "TypeError", "mechanism": {"handled": False}}],+ "$exception_handled": True,+ "$exception_level": "error",+ "$current_url": "https://app.example.com/checkout/pay?token=secret#step-2",+ "$lib": "web",+ },+ "TypeError: boom\nHandled by the application: no\nLevel: error\nPage: app.example.com/checkout/pay\nSDK: web",+ ),+ (+ {"$exception_list": [{"type": "TypeError"}], "$exception_handled": False, "$current_url": "not a url"},+ "TypeError: boom",+ ),+ (+ {"$current_url": "https://user:[email protected]:8443/checkout?token=secret"},+ "TypeError: boom\nPage: app.example.com:8443/checkout",+ ),+ (+ {"$current_url": "https://[malformed.example.com/checkout"},+ "TypeError: boom",+ ),+ ],+)+def test_severity_state(properties: dict[str, object], expected: str) -> None:+ assert build_severity_state("TypeError: boom\n", properties) == expected++def test_stacktrace_rendering_matches_cymbal_embedding_content() -> None:event_properties: dict[str, object] = {"$exception_list": [@@ -160,6 +204,110 @@ def test_embedding_failure_classification_and_capture(assert capture_exception.called is expect_captured+def _decision(choice: str) -> DecisionResult:+ return DecisionResult(+ model="severity-model",+ answers={"severity": ChoiceAnswer(choice=choice, confidence=0.9, probabilities={choice: 0.9})},+ input_tokens=10,+ )+++ "enabled,decide_outcome,expected_result,expected_error_type",+ [+ (+ False,+ _decision("critical"),+ IssueSeverityInferenceResult(skipped_reason=SeverityInferenceSkipReason.DISABLED),+ None,+ ),+ (+ True,+ _decision("critical"),+ IssueSeverityInferenceResult(resolved=True, stored_severity="critical"),+ None,+ ),+ (+ True,+ _decision("catastrophic"),+ IssueSeverityInferenceResult(skipped_reason=SeverityInferenceSkipReason.UNEXPECTED_ANSWER),+ None,+ ),+ (+ True,+ DecisionsDisabledError(1),+ IssueSeverityInferenceResult(skipped_reason=SeverityInferenceSkipReason.DECISIONS_UNAVAILABLE),+ None,+ ),+ (+ True,+ DecisionGatewayError(422, "bad request"),+ IssueSeverityInferenceResult(skipped_reason=SeverityInferenceSkipReason.GATEWAY_REJECTED),+ None,+ ),+ (True, DecisionGatewayError(429, "rate limited"), None, SEVERITY_INFERENCE_UNAVAILABLE_ERROR_TYPE),+ (True, DecisionGatewayError(503, "unavailable"), None, SEVERITY_INFERENCE_UNAVAILABLE_ERROR_TYPE),+ (True, DecisionGatewayUnreachableError("timeout"), None, SEVERITY_INFERENCE_UNAVAILABLE_ERROR_TYPE),+ ],+)+@patch("products.error_tracking.backend.temporal.lifecycle.issue_created.activities.posthoganalytics.capture_exception")+@patch(+ "products.error_tracking.backend.temporal.lifecycle.issue_created.activities.ERROR_TRACKING_SEVERITY_INFERENCE_OUTCOMES"+)+@patch("products.error_tracking.backend.temporal.lifecycle.issue_created.activities.logger")+@patch("products.error_tracking.backend.temporal.lifecycle.issue_created.activities.apply_inferred_severity")+@patch("products.error_tracking.backend.logic.severity_inference.ml_inference.decide")+@patch("products.error_tracking.backend.temporal.lifecycle.issue_created.activities.fetch_event_properties")+@patch("products.error_tracking.backend.temporal.lifecycle.issue_created.activities.Team.objects.select_related")+@patch("products.error_tracking.backend.temporal.lifecycle.issue_created.activities.severity_inference_enabled")+def test_severity_inference_outcomes(+ severity_inference_enabled: MagicMock,+ select_related: MagicMock,+ fetch_event_properties: MagicMock,+ decide: MagicMock,+ apply_inferred_severity: MagicMock,+ logger: MagicMock,+ inference_outcomes: MagicMock,+ capture_exception: MagicMock,+ enabled: bool,+ decide_outcome: DecisionResult | Exception,+ expected_result: IssueSeverityInferenceResult | None,+ expected_error_type: str | None,+) -> None:+ severity_inference_enabled.return_value = enabled+ select_related.return_value.get.return_value.organization.is_ai_data_processing_approved = True+ fetch_event_properties.return_value = {"$exception_list": [{"type": "TypeError", "value": "boom"}]}+ if isinstance(decide_outcome, Exception):+ decide.side_effect = decide_outcome+ else:+ decide.return_value = decide_outcome+ apply_inferred_severity.side_effect = lambda *args, inferred, **kwargs: SimpleNamespace(+ stored_severity=inferred, applied=True+ )+ inputs = dataclasses.replace(_inputs("fingerprint"), severity_source=SeveritySource.HEURISTIC)++ if expected_error_type is None:+ assert infer_issue_created_severity_activity(inputs) == expected_result+ else:+ with pytest.raises(ApplicationError) as error:+ infer_issue_created_severity_activity(inputs)+ assert error.value.type == expected_error_type+ assert not error.value.non_retryable+ if isinstance(decide_outcome, DecisionGatewayError) and decide_outcome.status_code == 422:+ warning = logger.warning.call_args+ assert warning.args[0] == "error_tracking_severity_inference_rejected"+ assert "detail" not in warning.kwargs+ if expected_result is None:+ expected_outcome = "unavailable"+ expected_severity = inputs.issue.severity or "none"+ else:+ expected_outcome = expected_result.skipped_reason or "inferred"+ expected_severity = expected_result.stored_severity or inputs.issue.severity or "none"+ inference_outcomes.labels.assert_called_once_with(outcome=expected_outcome, severity=expected_severity)+ inference_outcomes.labels.return_value.inc.assert_called_once_with()+ capture_exception.assert_not_called()++@override_settings(ERROR_TRACKING_EVENT_PROPERTIES_REDIS_URL="redis://event-properties")@patch("products.error_tracking.backend.temporal.lifecycle.event_properties.execute_hogql_query")@patch("products.error_tracking.backend.temporal.lifecycle.event_properties.get_client")@@ -197,8 +345,10 @@ def test_falls_back_to_clickhouse_when_valkey_payload_expired(async def test_only_notifies_for_an_issue_that_was_not_merged() -> None:alert_issue_ids: list[str] = []event_issue_ids: list[str] = []+ event_severities: dict[str, str | None] = {}signal_issue_ids: list[str] = []signal_attempts: dict[str, int] = {}+ inferred_issue_ids: list[str] = []@activity.defn(name="generate_issue_created_embedding_activity")async def generate(inputs: IssueCreatedWorkflowInputs) -> IssueEmbeddingPreparationResult:@@ -231,6 +381,17 @@ async def test_only_notifies_for_an_issue_that_was_not_merged() -> None:async def merge(inputs: FingerprintEmbeddingResultInputs) -> FingerprintEmbeddingMergeResult:return FingerprintEmbeddingMergeResult(merged_count=int(inputs.fingerprint == "merged"))+ @activity.defn(name="infer_issue_created_severity_activity")+ async def infer_severity(inputs: IssueCreatedWorkflowInputs) -> IssueSeverityInferenceResult:+ inferred_issue_ids.append(inputs.issue_id)+ if inputs.fingerprint == "inference-unavailable":+ raise ApplicationError("model unavailable", non_retryable=True)+ if inputs.fingerprint == "severity-changed":+ return IssueSeverityInferenceResult(+ resolved=True, stored_severity="low", skipped_reason=SeverityInferenceSkipReason.SEVERITY_CHANGED+ )+ return IssueSeverityInferenceResult(resolved=True, stored_severity="critical")+@activity.defn(name="dispatch_issue_created_alert_activity")async def dispatch_alert(inputs: IssueCreatedWorkflowInputs) -> None:alert_issue_ids.append(inputs.issue_id)@@ -238,6 +399,7 @@ async def test_only_notifies_for_an_issue_that_was_not_merged() -> None:@activity.defn(name="emit_issue_created_internal_event_activity")async def emit_event(inputs: IssueCreatedWorkflowInputs) -> None:event_issue_ids.append(inputs.issue_id)+ event_severities[inputs.issue_id] = inputs.issue.severity@activity.defn(name="emit_issue_created_signal_activity")async def emit_signal(inputs: IssueCreatedWorkflowInputs) -> None:@@ -252,12 +414,32 @@ async def test_only_notifies_for_an_issue_that_was_not_merged() -> None:environment.client,task_queue=task_queue,workflows=[ErrorTrackingIssueCreatedWorkflow],- activities=[generate, persist, merge, dispatch_alert, emit_event, emit_signal],+ activities=[generate, persist, merge, infer_severity, dispatch_alert, emit_event, emit_signal],workflow_runner=UnsandboxedWorkflowRunner(),):merged_inputs = _inputs("merged")unmerged_inputs = _inputs("unmerged")embedding_unavailable_inputs = _inputs("embedding-unavailable")+ heuristic_inputs = dataclasses.replace(_inputs("heuristic"), severity_source=SeveritySource.HEURISTIC)+ rule_inputs = dataclasses.replace(_inputs("rule"), severity_source=SeveritySource.RULE)+ inference_unavailable_inputs = dataclasses.replace(+ _inputs("inference-unavailable"), severity_source=SeveritySource.HEURISTIC+ )+ severity_changed_inputs = dataclasses.replace(+ _inputs("severity-changed"), severity_source=SeveritySource.HEURISTIC+ )+ for severity_inputs in (+ heuristic_inputs,+ rule_inputs,+ inference_unavailable_inputs,+ severity_changed_inputs,+ ):+ await environment.client.execute_workflow(+ ErrorTrackingIssueCreatedWorkflow.run,+ severity_inputs,+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )merged_result = await environment.client.execute_workflow(ErrorTrackingIssueCreatedWorkflow.run,merged_inputs,@@ -283,10 +465,23 @@ async def test_only_notifies_for_an_issue_that_was_not_merged() -> None:notified=True,embedding_skipped_reason="embedding_service_unavailable",)- assert alert_issue_ids == [unmerged_inputs.issue_id, embedding_unavailable_inputs.issue_id]- assert event_issue_ids == [unmerged_inputs.issue_id, embedding_unavailable_inputs.issue_id]- assert signal_issue_ids == [unmerged_inputs.issue_id, embedding_unavailable_inputs.issue_id]- assert signal_attempts == {- unmerged_inputs.issue_id: 2,- embedding_unavailable_inputs.issue_id: 2,- }+ severity_issue_ids = [+ heuristic_inputs.issue_id,+ rule_inputs.issue_id,+ inference_unavailable_inputs.issue_id,+ severity_changed_inputs.issue_id,+ ]+ notified_issue_ids = [*severity_issue_ids, unmerged_inputs.issue_id, embedding_unavailable_inputs.issue_id]+ assert alert_issue_ids == notified_issue_ids+ assert event_issue_ids == notified_issue_ids+ assert signal_issue_ids == notified_issue_ids+ assert signal_attempts == dict.fromkeys(notified_issue_ids, 2)+ assert inferred_issue_ids == [+ heuristic_inputs.issue_id,+ inference_unavailable_inputs.issue_id,+ severity_changed_inputs.issue_id,+ ]+ assert event_severities[heuristic_inputs.issue_id] == "critical"+ assert event_severities[rule_inputs.issue_id] == "high"+ assert event_severities[inference_unavailable_inputs.issue_id] == "high"+ assert event_severities[severity_changed_inputs.issue_id] == "low"diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_created/types.py b/products/error_tracking/backend/temporal/lifecycle/issue_created/types.pyindex 5400e5af8923..a955a796770a 100644--- a/products/error_tracking/backend/temporal/lifecycle/issue_created/types.py+++ b/products/error_tracking/backend/temporal/lifecycle/issue_created/types.py@@ -1,14 +1,38 @@import dataclasses+from enum import StrEnumfrom products.error_tracking.backend.temporal.fingerprint_embedding_result.types import FingerprintEmbeddingResultInputsfrom products.error_tracking.backend.temporal.lifecycle.types import LifecycleIssueSnapshotEMBEDDING_SERVICE_UNAVAILABLE_ERROR_TYPE = "EmbeddingServiceUnavailable"+SEVERITY_INFERENCE_UNAVAILABLE_ERROR_TYPE = "SeverityInferenceUnavailable"IssueCreatedSnapshot = LifecycleIssueSnapshot+class SeveritySource(StrEnum):+ """How cymbal chose the severity of a new issue. Mirrors `SeveritySource` in cymbal's notification.rs.++ Temporal rejects an input with an unknown value, so add a value here before cymbal sends it.+ """++ EVENT = "event"+ RULE = "rule"+ HEURISTIC = "heuristic"+++class SeverityInferenceSkipReason(StrEnum):+ DISABLED = "disabled"+ TEAM_MISSING = "team_missing"+ AI_DATA_PROCESSING_NOT_APPROVED = "ai_data_processing_not_approved"+ NO_EXCEPTION = "no_exception"+ DECISIONS_UNAVAILABLE = "decisions_unavailable"+ GATEWAY_REJECTED = "gateway_rejected"+ UNEXPECTED_ANSWER = "unexpected_answer"+ SEVERITY_CHANGED = "severity_changed"++@dataclasses.dataclass(frozen=True)class IssueCreatedWorkflowInputs:notification_id: str@@ -19,6 +43,17 @@ class IssueCreatedWorkflowInputs:event_uuid: strevent_timestamp: strassignee: str | None = None+ severity_source: SeveritySource | None = None++ def severity_is_overridable(self) -> bool:+ """A model may only replace a severity that no person chose: the level/handled heuristic, or none.++ A notification without a source can come from a cymbal that predates the field, where+ the severity can be an explicit event value or a rule. Only an empty severity is safe then.+ """+ if self.severity_source is None:+ return self.issue.severity is None+ return self.severity_source == SeveritySource.HEURISTIC@dataclasses.dataclass(frozen=True)@@ -34,6 +69,14 @@ class IssueEmbeddingPreparationResult:skipped_reason: str | None = None[email protected](frozen=True)+class IssueSeverityInferenceResult:+ # True when inference read the issue row. Downstream side effects must then carry `stored_severity`.+ resolved: bool = False+ stored_severity: str | None = None+ skipped_reason: SeverityInferenceSkipReason | None = None++@dataclasses.dataclass(frozen=True)class IssueCreatedWorkflowResult:merged: bool = Falsediff --git a/products/error_tracking/backend/temporal/lifecycle/issue_created/workflow.py b/products/error_tracking/backend/temporal/lifecycle/issue_created/workflow.pyindex bf7f0cd094c0..e8fb89fb4c9d 100644--- a/products/error_tracking/backend/temporal/lifecycle/issue_created/workflow.py+++ b/products/error_tracking/backend/temporal/lifecycle/issue_created/workflow.py@@ -1,5 +1,6 @@import jsonimport asyncio+import dataclassesfrom datetime import timedeltafrom temporalio import common, workflow@@ -14,25 +15,27 @@ from products.error_tracking.backend.temporal.lifecycle.issue_created.types impoIssueCreatedWorkflowInputs,IssueCreatedWorkflowResult,IssueEmbeddingPreparationResult,+ IssueSeverityInferenceResult,+)+from products.error_tracking.backend.temporal.lifecycle.policies import (+ ACTIVITY_RETRY_POLICY,+ ACTIVITY_START_TO_CLOSE_TIMEOUT,+ ALERT_DISPATCH_PATCH,+ ALERT_DISPATCH_RETRY_POLICY,+ ALERT_DISPATCH_SCHEDULE_TO_CLOSE_TIMEOUT,)WORKFLOW_NAME = "error-tracking-issue-created"-ACTIVITY_RETRY_POLICY = common.RetryPolicy(- initial_interval=timedelta(seconds=1),- maximum_interval=timedelta(seconds=15),- maximum_attempts=10,-)-ACTIVITY_START_TO_CLOSE_TIMEOUT = timedelta(minutes=5)-ALERT_DISPATCH_PATCH = "error-tracking-alert-dispatch-activity"-# Unlimited attempts inside the window: the start is cheap and idempotent, and only a-# Temporal outage longer than this loses the alert.-ALERT_DISPATCH_RETRY_POLICY = common.RetryPolicy(- initial_interval=timedelta(seconds=5),- maximum_interval=timedelta(minutes=1),- maximum_attempts=0,+SEVERITY_INFERENCE_PATCH = "error-tracking-severity-inference-activity"+SEVERITY_INFERENCE_RETRY_POLICY = common.RetryPolicy(+ initial_interval=timedelta(seconds=2),+ maximum_interval=timedelta(seconds=30),+ maximum_attempts=3,)-ALERT_DISPATCH_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(hours=1)+SEVERITY_INFERENCE_START_TO_CLOSE_TIMEOUT = timedelta(seconds=35)+# Alerts wait for inference, so a model outage must not hold them past this bound, retries included.+SEVERITY_INFERENCE_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(seconds=45)EMBEDDING_ACTIVITY_RETRY_POLICY = common.RetryPolicy(initial_interval=timedelta(seconds=1),maximum_interval=timedelta(seconds=15),@@ -107,6 +110,9 @@ class ErrorTrackingIssueCreatedWorkflow(PostHogWorkflow):if merge_result.merged_count > 0:return IssueCreatedWorkflowResult(merged=True)+ # Runs before the alert and the side effects so that they carry the inferred severity.+ inputs = await self._with_inferred_severity(inputs)+# Patched: executions in flight when this activity shipped replay the old sequence.# Dispatch runs alongside the other side effects and is always awaited, so a# failure on either side never suppresses the other. Its open-ended retry covers@@ -144,3 +150,31 @@ class ErrorTrackingIssueCreatedWorkflow(PostHogWorkflow):notified=True,embedding_skipped_reason=preparation.skipped_reason,)++ async def _with_inferred_severity(self, inputs: IssueCreatedWorkflowInputs) -> IssueCreatedWorkflowInputs:+ # The patch preserves deterministic replay for histories that do not contain this activity.+ if not inputs.severity_is_overridable() or not workflow.patched(SEVERITY_INFERENCE_PATCH):+ return inputs+ try:+ result = await workflow.execute_activity(+ "infer_issue_created_severity_activity",+ inputs,+ result_type=IssueSeverityInferenceResult,+ schedule_to_close_timeout=SEVERITY_INFERENCE_SCHEDULE_TO_CLOSE_TIMEOUT,+ start_to_close_timeout=SEVERITY_INFERENCE_START_TO_CLOSE_TIMEOUT,+ retry_policy=SEVERITY_INFERENCE_RETRY_POLICY,+ )+ except ActivityError:+ workflow.logger.warning("Severity inference failed; keeping the ingestion severity")+ (+ workflow.metric_meter()+ .create_counter(+ "error_tracking_issue_created_severity_inference_fail_open",+ "Issue-created workflows that kept the ingestion severity after inference failed",+ )+ .add(1)+ )+ return inputs+ if not result.resolved or result.stored_severity == inputs.issue.severity:+ return inputs+ return dataclasses.replace(inputs, issue=dataclasses.replace(inputs.issue, severity=result.stored_severity))diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_reopened/workflow.py b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/workflow.pyindex 466c7352e2b9..bc999d7f8def 100644--- a/products/error_tracking/backend/temporal/lifecycle/issue_reopened/workflow.py+++ b/products/error_tracking/backend/temporal/lifecycle/issue_reopened/workflow.py@@ -1,8 +1,7 @@import jsonimport asyncio-from datetime import timedelta-from temporalio import common, workflow+from temporalio import workflowfrom posthog.temporal.common.base import PostHogWorkflow@@ -11,25 +10,16 @@ from products.error_tracking.backend.temporal.lifecycle.issue_reopened.types impIssueReopenedWorkflowInputs,IssueReopenedWorkflowResult,)+from products.error_tracking.backend.temporal.lifecycle.policies import (+ ACTIVITY_RETRY_POLICY,+ ACTIVITY_START_TO_CLOSE_TIMEOUT,+ ALERT_DISPATCH_PATCH,+ ALERT_DISPATCH_RETRY_POLICY,+ ALERT_DISPATCH_SCHEDULE_TO_CLOSE_TIMEOUT,+)WORKFLOW_NAME = "error-tracking-issue-reopened"-ACTIVITY_RETRY_POLICY = common.RetryPolicy(- initial_interval=timedelta(seconds=1),- maximum_interval=timedelta(seconds=15),- maximum_attempts=10,-)-ACTIVITY_START_TO_CLOSE_TIMEOUT = timedelta(minutes=5)-ALERT_DISPATCH_PATCH = "error-tracking-alert-dispatch-activity"-# Unlimited attempts inside the window: the start is cheap and idempotent, and only a-# Temporal outage longer than this loses the alert.-ALERT_DISPATCH_RETRY_POLICY = common.RetryPolicy(- initial_interval=timedelta(seconds=5),- maximum_interval=timedelta(minutes=1),- maximum_attempts=0,-)-ALERT_DISPATCH_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(hours=1)-@workflow.defn(name=WORKFLOW_NAME)class ErrorTrackingIssueReopenedWorkflow(PostHogWorkflow):diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_spiking/workflow.py b/products/error_tracking/backend/temporal/lifecycle/issue_spiking/workflow.pyindex a00effeeb7c3..3b60983bbff0 100644--- a/products/error_tracking/backend/temporal/lifecycle/issue_spiking/workflow.py+++ b/products/error_tracking/backend/temporal/lifecycle/issue_spiking/workflow.py@@ -1,8 +1,7 @@import jsonimport asyncio-from datetime import timedelta-from temporalio import common, workflow+from temporalio import workflowfrom posthog.temporal.common.base import PostHogWorkflow@@ -12,26 +11,17 @@ from products.error_tracking.backend.temporal.lifecycle.issue_spiking.types impoIssueSpikingWorkflowResult,SpikeEventPersistenceResult,)+from products.error_tracking.backend.temporal.lifecycle.policies import (+ ACTIVITY_RETRY_POLICY,+ ACTIVITY_START_TO_CLOSE_TIMEOUT,+ ALERT_DISPATCH_PATCH,+ ALERT_DISPATCH_RETRY_POLICY,+ ALERT_DISPATCH_SCHEDULE_TO_CLOSE_TIMEOUT,+)from products.error_tracking.backend.temporal.lifecycle.types import SpikeEventPersistenceStatusWORKFLOW_NAME = "error-tracking-issue-spiking"-ACTIVITY_RETRY_POLICY = common.RetryPolicy(- initial_interval=timedelta(seconds=1),- maximum_interval=timedelta(seconds=15),- maximum_attempts=10,-)-ACTIVITY_START_TO_CLOSE_TIMEOUT = timedelta(minutes=5)-ALERT_DISPATCH_PATCH = "error-tracking-alert-dispatch-activity"-# Unlimited attempts inside the window: the start is cheap and idempotent, and only a-# Temporal outage longer than this loses the alert.-ALERT_DISPATCH_RETRY_POLICY = common.RetryPolicy(- initial_interval=timedelta(seconds=5),- maximum_interval=timedelta(minutes=1),- maximum_attempts=0,-)-ALERT_DISPATCH_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(hours=1)-@workflow.defn(name=WORKFLOW_NAME)class ErrorTrackingIssueSpikingWorkflow(PostHogWorkflow):diff --git a/products/error_tracking/backend/temporal/lifecycle/policies.py b/products/error_tracking/backend/temporal/lifecycle/policies.pynew file mode 100644index 000000000000..cf6c6aeba678--- /dev/null+++ b/products/error_tracking/backend/temporal/lifecycle/policies.py@@ -0,0 +1,19 @@+from datetime import timedelta++from temporalio import common++ACTIVITY_RETRY_POLICY = common.RetryPolicy(+ initial_interval=timedelta(seconds=1),+ maximum_interval=timedelta(seconds=15),+ maximum_attempts=10,+)+ACTIVITY_START_TO_CLOSE_TIMEOUT = timedelta(minutes=5)+ALERT_DISPATCH_PATCH = "error-tracking-alert-dispatch-activity"+# Unlimited attempts inside the window: the start is cheap and idempotent, and only a+# Temporal outage longer than this loses the alert.+ALERT_DISPATCH_RETRY_POLICY = common.RetryPolicy(+ initial_interval=timedelta(seconds=5),+ maximum_interval=timedelta(minutes=1),+ maximum_attempts=0,+)+ALERT_DISPATCH_SCHEDULE_TO_CLOSE_TIMEOUT = timedelta(hours=1)diff --git a/products/error_tracking/backend/tests/api/test_issue_state_sync.py b/products/error_tracking/backend/tests/api/test_issue_state_sync.pyindex fa2f73e1fb87..6c1bb862bf76 100644--- a/products/error_tracking/backend/tests/api/test_issue_state_sync.py+++ b/products/error_tracking/backend/tests/api/test_issue_state_sync.py@@ -1,9 +1,31 @@+import pytestfrom posthog.test.base import APIBaseTest, ClickhouseTestMixin+from unittest.mock import patch++from django.db.utils import IntegrityError++from parameterized import parameterized++from posthog.models.activity_logging.activity_log import ActivityLogfrom products.access_control.backend.models.role import Role+from products.error_tracking.backend.logic.severity_inference import apply_inferred_severityfrom products.error_tracking.backend.models import ErrorTrackingIssue, ErrorTrackingIssueFingerprintV2+class TestInferredSeverityWrite(APIBaseTest):+ def test_activity_log_failure_rolls_back_severity(self) -> None:+ issue = ErrorTrackingIssue.objects.create(team=self.team, severity="medium")++ with self.settings(TEST=False, ACTIVITY_LOG_TRANSACTION_MANAGEMENT=True):+ with patch.object(ActivityLog.objects, "create", side_effect=IntegrityError("write timed out")):+ with pytest.raises(IntegrityError):+ apply_inferred_severity(self.team.id, issue.id, expected="medium", inferred="critical")++ issue.refresh_from_db()+ assert issue.severity == "medium"++class TestIssueStateSync(ClickhouseTestMixin, APIBaseTest):def _create_issue(self, fingerprints=None, **kwargs) -> ErrorTrackingIssue:issue = ErrorTrackingIssue.objects.create(team=self.team, **kwargs)@@ -95,6 +117,27 @@ class TestIssueStateSync(ClickhouseTestMixin, APIBaseTest):assert len(rows) == 1assert rows[0][6] == "high"+ @parameterized.expand(+ [+ ("ingestion_severity_unchanged", "medium", "medium", "critical", ["critical"]),+ ("severity_changed_while_inferring", "medium", "low", "low", []),+ ("no_ingestion_severity", None, None, "critical", ["critical"]),+ ("retry_after_failed_clickhouse_sync", "medium", "critical", "critical", ["critical"]),+ ]+ )+ def test_inferred_severity_only_replaces_the_ingestion_severity(+ self, _name, expected, current, stored_severity, synced_severities+ ):+ issue = self._create_issue(fingerprints=["fp_1"], severity=current)++ write = apply_inferred_severity(self.team.id, issue.id, expected=expected, inferred="critical")++ assert write.stored_severity == stored_severity++ issue.refresh_from_db()+ assert issue.severity == stored_severity+ assert [row[6] for row in self._get_issue_state_rows()] == synced_severities+def test_bulk_status_change_syncs(self):issue_one = self._create_issue(fingerprints=["fp_one"])issue_two = self._create_issue(fingerprints=["fp_two"])diff --git a/rust/cymbal/src/core/types/notification.rs b/rust/cymbal/src/core/types/notification.rsindex 23522febaba1..ba10076b41d6 100644--- a/rust/cymbal/src/core/types/notification.rs+++ b/rust/cymbal/src/core/types/notification.rs@@ -200,6 +200,18 @@ impl IssueNotificationContext {}}+/// How ingestion chose the severity of a new issue. The issue-created workflow only+/// lets a model replace a `Heuristic` severity or a missing one.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum SeveritySource {+ /// The event carried an explicit `$issue_severity`.+ Event,+ Rule,+ /// Derived from the exception level and handled flag.+ Heuristic,+}+/// Payload for [`IngestionNotification::IssueCreated`].#[derive(Debug, Clone, Serialize, Deserialize)]pub struct IssueCreated {@@ -211,6 +223,8 @@ pub struct IssueCreated {pub event_uuid: Uuid,pub event_timestamp: String,pub assignee: Option<String>,+ #[serde(default)]+ pub severity_source: Option<SeveritySource>,}/// Payload for [`IngestionNotification::IssueReopened`].@@ -292,6 +306,7 @@ mod tests {event_uuid: Uuid::nil(),event_timestamp: "1970-01-01T00:00:00Z".to_string(),assignee: None,+ severity_source: Some(SeveritySource::Rule),});assert_eq!(notification.validate(), Ok(()));@@ -301,6 +316,7 @@ mod tests {assert_eq!(json["team_id"], 42);assert_eq!(json["fingerprint"], "abc");assert_eq!(json["issue"]["severity"], "high");+ assert_eq!(json["severity_source"], "rule");assert_eq!(json["event_properties"]["$exception_fingerprint"], "abc");// Round-trips back to the same JSON through the typed enum.diff --git a/rust/cymbal/src/modes/notifications/temporal.rs b/rust/cymbal/src/modes/notifications/temporal.rsindex 794c41dbb32c..76cba3bca344 100644--- a/rust/cymbal/src/modes/notifications/temporal.rs+++ b/rust/cymbal/src/modes/notifications/temporal.rs@@ -6,7 +6,9 @@ use serde::Serialize;use uuid::Uuid;use crate::core::error::UnhandledError;-use crate::core::types::notification::{IssueCreated, IssueReopened, IssueSnapshot, IssueSpiking};+use crate::core::types::notification::{+ IssueCreated, IssueReopened, IssueSnapshot, IssueSpiking, SeveritySource,+};use crate::modes::notifications::config::NotificationsConfig;#[derive(Clone, Copy)]@@ -144,6 +146,7 @@ struct IssueCreatedWorkflowInput<'a> {event_uuid: Uuid,event_timestamp: &'a str,assignee: Option<&'a str>,+ severity_source: Option<SeveritySource>,}impl<'a> From<&'a IssueCreated> for IssueCreatedWorkflowInput<'a> {@@ -157,6 +160,7 @@ impl<'a> From<&'a IssueCreated> for IssueCreatedWorkflowInput<'a> {event_uuid: notification.event_uuid,event_timestamp: ¬ification.event_timestamp,assignee: notification.assignee.as_deref(),+ severity_source: notification.severity_source,}}}@@ -282,6 +286,7 @@ mod tests {event_uuid: Uuid::now_v7(),event_timestamp: "2026-07-21T12:00:00Z".to_string(),assignee: None,+ severity_source: Some(SeveritySource::Heuristic),}}@@ -320,6 +325,9 @@ mod tests {serde_json::to_value(IssueReopenedWorkflowInput::from(&issue_reopened())).unwrap(),serde_json::to_value(IssueSpikingWorkflowInput::from(&issue_spiking())).unwrap(),];+ // The Python issue-created workflow reads this field by name to decide whether a+ // model may replace the severity.+ assert_eq!(values[0]["severity_source"], "heuristic");for value in values {assert_eq!(value["team_id"], 42);diff --git a/rust/cymbal/src/modes/processing/issue_resolution.rs b/rust/cymbal/src/modes/processing/issue_resolution.rsindex 366956345741..be0fec793d90 100644--- a/rust/cymbal/src/modes/processing/issue_resolution.rs+++ b/rust/cymbal/src/modes/processing/issue_resolution.rs@@ -10,7 +10,7 @@ use uuid::Uuid;use crate::core::types::notification::{IngestionNotification, IssueCreated, IssueNotificationContext, IssueReopened, IssueSnapshot,- IssueSpiking, NotificationMeta,+ IssueSpiking, NotificationMeta, SeveritySource,};use crate::modes::processing::rules::assignment::{Assignee, Assignment};use crate::types::ProcessedExceptionProperties;@@ -495,6 +495,7 @@ pub async fn send_issue_created_notification(processed_properties: ProcessedExceptionProperties,event_uuid: Uuid,event_timestamp: &DateTime<Utc>,+ severity_source: Option<SeveritySource>,) -> Result<(), UnhandledError> {let fingerprint = processed_properties.fingerprint().to_string();store_error_tracking_event_properties(@@ -516,6 +517,7 @@ pub async fn send_issue_created_notification(event_uuid,event_timestamp: event_timestamp.to_rfc3339(),assignee: assignment_to_string(assignment)?,+ severity_source,}),).awaitdiff --git a/rust/cymbal/src/modes/processing/stages/linking/issue.rs b/rust/cymbal/src/modes/processing/stages/linking/issue.rsindex 701ca6b8cafb..e6e5b5f4bfe3 100644--- a/rust/cymbal/src/modes/processing/stages/linking/issue.rs+++ b/rust/cymbal/src/modes/processing/stages/linking/issue.rs@@ -6,6 +6,7 @@ use sqlx::{Acquire, PgConnection};use tracing::debug;use uuid::Uuid;+use crate::core::types::notification::SeveritySource;use crate::{app_context::AppContext,error::UnhandledError,@@ -285,6 +286,17 @@ async fn resolve_issue(// back the transaction if the override insert fails (since that indicates someone else// beat us to creating this new issue). Then, possibly reopen the issue.+ let proposed_severity = event_properties.proposed_issue_severity();+ let heuristic_severity = infer_issue_severity(+ event_properties.exception_level(),+ event_properties.exception_handled(),+ );+ let mut severity_source = if proposed_severity.is_some() {+ Some(SeveritySource::Event)+ } else {+ heuristic_severity.map(|_| SeveritySource::Heuristic)+ };+// Start a transaction, so we can roll it back on override insert failurelet mut txn = conn.begin().await?;// Insert a new issue@@ -292,12 +304,7 @@ async fn resolve_issue(team_id,name.to_string(),description.to_string(),- event_properties.proposed_issue_severity().or_else(|| {- infer_issue_severity(- event_properties.exception_level(),- event_properties.exception_handled(),- )- }),+ proposed_severity.or(heuristic_severity),&mut *txn,).await?;@@ -363,13 +370,16 @@ async fn resolve_issue(}} else {metrics::counter!(ISSUE_CREATED).increment(1);- process_event_severity(+ if process_event_severity(&mut txn,&context.team_manager,&mut issue,event_properties,)- .await?;+ .await?+ {+ severity_source = Some(SeveritySource::Rule);+ }let assignment =process_event_assignment(&mut txn, &context.team_manager, &issue, event_properties).await?;@@ -399,6 +409,7 @@ async fn resolve_issue(processed_properties,event_properties.uuid(),&event_timestamp,+ severity_source,).await?;};@@ -406,24 +417,26 @@ async fn resolve_issue(Ok(issue)}+/// Returns whether a severity rule set the issue severity.async fn process_event_severity(connection: &mut PgConnection,team_manager: &TeamManager,issue: &mut Issue,exception_properties: &ExceptionEvent<Fingerprinted>,-) -> Result<(), UnhandledError> {+) -> Result<bool, UnhandledError> {if exception_properties.proposed_issue_severity().is_some() {- return Ok(());+ return Ok(false);}let processed_properties = exception_properties.processed_properties(issue);- if let Some(severity) =+ let Some(severity) =try_severity_rules(connection, team_manager, issue, &processed_properties).await?- {- issue- .apply_initial_severity(severity.to_string(), connection)- .await?;- }- Ok(())+ else {+ return Ok(false);+ };+ issue+ .apply_initial_severity(severity.to_string(), connection)+ .await?;+ Ok(true)}async fn process_event_assignment(diff --git a/tach.toml b/tach.tomlindex 53c42f248187..989857a68f6d 100644--- a/tach.toml+++ b/tach.toml@@ -446,6 +446,8 @@ depends_on = ["ee","posthog","products.cdp",+ # Facade-only: new issue severity inference calls the shared decision-model client.+ "products.ml_inference","products.notifications","products.signals","products.warehouse_sources", "products.access_control",