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(mcp-analytics): add failure-class classifier command (#79333)

Lucas Faria8688abc5a5ab
diff --git a/products/mcp_analytics/backend/failure_classification.py b/products/mcp_analytics/backend/failure_classification.py
new file mode 100644
index 000000000000..966124335721
--- /dev/null
+++ b/products/mcp_analytics/backend/failure_classification.py
@@ -0,0 +1,220 @@
+"""Classify MCP tool-call failure messages into a fixed set of causes.
+
+Staff-tool support code for ``classify_mcp_failures``: normalizes raw error messages into
+fingerprints (pure, no LLM) and classifies fingerprints in batches via an LLM call, mirroring the
+pattern in ``intent_generation.py``.
+"""
+
+import re
+from enum import StrEnum
+
+from django.conf import settings
+
+import openai
+import structlog
+import posthoganalytics
+from posthoganalytics.ai.openai import OpenAI
+from pydantic import BaseModel, ValidationError
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.models.team.team import Team
+
+logger = structlog.get_logger(__name__)
+
+
+class FailureClassificationUnavailable(RuntimeError):
+ pass
+
+
+FAILURE_CLASS_MODEL = "gpt-5.6-luna"
+CLASSIFY_BATCH_SIZE = 25
+FINGERPRINT_MAX_CHARS = 200
+_QUOTED_VALUE_MAX_CHARS = 80
+
+
+class FailureClass(StrEnum):
+ INPUT_SCHEMA_MISMATCH = "input_schema_mismatch"
+ OUTPUT_SCHEMA_VIOLATION = "output_schema_violation"
+ UNKNOWN_TOOL = "unknown_tool"
+ TIMEOUT = "timeout"
+ UPSTREAM_5XX = "upstream_5xx"
+ TRANSPORT_FAILURE = "transport_failure"
+ RESOURCE_NOT_FOUND = "resource_not_found"
+ EMPTY_RESULT_AS_ERROR = "empty_result_as_error"
+ STATE_CONFLICT = "state_conflict"
+ MISSING_PRECONDITION = "missing_precondition"
+ AUTH_OR_PERMISSION = "auth_or_permission"
+ ENTITLEMENT_GAP = "entitlement_gap"
+ RATE_LIMITED = "rate_limited"
+ INTERNAL_ERROR = "internal_error"
+
+
+FAILURE_CLASSES: tuple[str, ...] = tuple(cls.value for cls in FailureClass)
+
+_UUID_RE = re.compile(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", re.IGNORECASE)
+_EMAIL_RE = re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.-]+\b")
+_URL_RE = re.compile(r"\bhttps?://\S+", re.IGNORECASE)
+_ISO_DATE_RE = re.compile(
+ r"\b\d{4}-\d{2}-\d{2}(?:[t ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:z|[+-]\d{2}:?\d{2})?)?\b", re.IGNORECASE
+)
+_DOUBLE_QUOTED_RE = re.compile(rf'"[^"]{{0,{_QUOTED_VALUE_MAX_CHARS}}}"')
+_SINGLE_QUOTED_RE = re.compile(rf"'[^']{{0,{_QUOTED_VALUE_MAX_CHARS}}}'")
+_NUMBER_RE = re.compile(r"\d+")
+_WHITESPACE_RE = re.compile(r"\s+")
+
+
+def normalize_fingerprint(msg: str) -> str:
+ """Collapse a raw error message into a stable fingerprint for grouping.
+
+ Strips values that vary per-occurrence (IDs, timestamps, quoted literals, numbers) but leaves
+ the message's language and wording untouched — a translated message must stay a distinct
+ fingerprint from its English twin, since fingerprinting is grouping, not classification.
+ """
+ normalized = msg.lower()
+ normalized = _URL_RE.sub(" ", normalized)
+ normalized = _EMAIL_RE.sub(" ", normalized)
+ normalized = _UUID_RE.sub(" ", normalized)
+ normalized = _ISO_DATE_RE.sub(" ", normalized)
+ normalized = _DOUBLE_QUOTED_RE.sub(" ", normalized)
+ normalized = _SINGLE_QUOTED_RE.sub(" ", normalized)
+ normalized = _NUMBER_RE.sub(" ", normalized)
+ normalized = _WHITESPACE_RE.sub(" ", normalized).strip()
+ return normalized[:FINGERPRINT_MAX_CHARS]
+
+
+SYSTEM_PROMPT = f"""You classify MCP tool-call failure messages into exactly one of these {len(FAILURE_CLASSES)} \
+classes:
+
+- input_schema_mismatch: caller's arguments rejected against the tool's declared input contract \
+— "Invalid arguments: expected array, received undefined", "The <field> field is required"
+- output_schema_violation: the server's own response violates its declared output schema — \
+"Output validation error: invalid structured content"
+- unknown_tool: a tool that doesn't exist was called — "Unknown tool: <name>", JSON-RPC -32601
+- timeout: the operation ran out of time — "timed out after 45s"
+- upstream_5xx: a dependency behind the server failed — "API request failed: 503"
+- transport_failure: network-level failure — "fetch failed", "connection reset"
+- resource_not_found: the referenced entity doesn't exist — "Resource does not exist — verify the ID"
+- empty_result_as_error: a search legitimately found nothing but was surfaced as an error — "No \
+matching records found; adjust your query"
+- state_conflict: entity exists but its current state forbids the operation — "already exists", \
+"not in draft status"
+- missing_precondition: one-time setup never done — "no account connected", "sender email must \
+be verified"
+- auth_or_permission: identity/credential/scope problem — 401/403, "insufficient scopes", \
+"read-only key"
+- entitlement_gap: authentication fine, the caller's plan doesn't include this — "not available \
+on the free tier", "upgrade your plan"
+- rate_limited: throttled on volume/speed — 429, "retry after N seconds"
+- internal_error: the message carries no diagnosable cause — "tool failed", "[object Object]", \
+bare stack fragments
+
+Boundary rules:
+1. Trust the message over the JSON-RPC code: "-32602: Tool X not found" is unknown_tool; \
+"-32602: Output validation error" is output_schema_violation.
+2. 429 + "upgrade your plan" is entitlement_gap, not rate_limited. "Retry after N seconds" is \
+rate_limited.
+3. 403 + "requires premium/subscription" is entitlement_gap, not auth_or_permission.
+4. missing_precondition vs state_conflict: would retrying tomorrow with no setup action still \
+fail? Yes = missing_precondition; depends on a live entity's current state = state_conflict.
+5. resource_not_found vs empty_result_as_error: lookup by identifier that missed = \
+resource_not_found; search/filter with zero rows = empty_result_as_error.
+6. "The X field is required" at call time is input_schema_mismatch unless the requirement is \
+business-conditional.
+7. Language is irrelevant: a translated message classifies the same as its English twin.
+8. A field's NAME never picks the class ("timeout seconds field must not be greater than 25" is \
+input_schema_mismatch, not timeout).
+9. If the message carries an upsell anywhere ("here are your options", plan limits), \
+entitlement_gap wins. If genuinely no cause is recoverable, internal_error — never guess.
+
+Each input line is numbered. Return exactly one classification per input line, in the same order, \
+as JSON of exactly this shape:
+{{"classifications": [{{"line_number": 1, "failure_class": "<one of the 14 class names>"}}, ...]}}"""
+
+# The LLM reads the raw representative message, never the normalized fingerprint: normalization
+# strips numbers, so the status and JSON-RPC codes the boundary rules pivot on (429, 403, -32601)
+# would be gone before classification. The fingerprint is only the grouping/cache key.
+MESSAGE_MAX_CHARS = 400
+
+
+class FingerprintClassification(BaseModel):
+ line_number: int
+ failure_class: FailureClass
+
+
+class ClassificationBatch(BaseModel):
+ classifications: list[FingerprintClassification]
+
+
+def _build_batch_prompt(messages: list[str]) -> str:
+ numbered = "\n".join(f"{i + 1}. {message[:MESSAGE_MAX_CHARS]}" for i, message in enumerate(messages))
+ return f"Failure messages:\n{numbered}"
+
+
+def _call_llm(client: OpenAI, messages: list[str], team: Team) -> ClassificationBatch:
+ response = client.chat.completions.create( # type: ignore
+ model=FAILURE_CLASS_MODEL,
+ temperature=0,
+ timeout=30,
+ messages=[
+ {"role": "system", "content": SYSTEM_PROMPT},
+ {"role": "user", "content": _build_batch_prompt(messages)},
+ ],
+ response_format={"type": "json_object"},
+ user=f"team/{team.id}/mcp-analytics-failure-classifier",
+ posthog_properties={"ai_product": "mcp_analytics", "ai_feature": "failure-classification"},
+ )
+ content = response.choices[0].message.content if response.choices else None
+ if not content:
+ raise ValueError("LLM returned an empty classification response")
+ return ClassificationBatch.model_validate_json(content)
+
+
+def _classify_batch(client: OpenAI, batch: list[tuple[str, str]], team: Team) -> dict[str, str]:
+ """Classify one (fingerprint, message) batch, retrying once on a malformed or invalid-class response."""
+ messages = [message for _, message in batch]
+ for attempt in range(2):
+ try:
+ parsed = _call_llm(client, messages, team)
+ except (openai.OpenAIError, ValidationError, ValueError):
+ if attempt == 1:
+ break
+ continue
+ # Valid JSON with missing/duplicate/out-of-range line numbers is as malformed as a
+ # schema violation: it must consume the retry, not silently orphan inputs.
+ returned_lines = sorted(item.line_number for item in parsed.classifications)
+ if returned_lines != list(range(1, len(batch) + 1)):
+ if attempt == 1:
+ break
+ continue
+ by_line = {item.line_number: item.failure_class.value for item in parsed.classifications}
+ return {fingerprint: by_line[i + 1] for i, (fingerprint, _) in enumerate(batch)}
+ logger.warning("mcp_analytics.failure_classifier.batch_failed", team_id=team.id, batch_size=len(batch))
+ return dict.fromkeys((fingerprint for fingerprint, _ in batch), FailureClass.INTERNAL_ERROR.value)
+
+
+def classify_fingerprints(messages_by_fingerprint: dict[str, str], team: Team) -> dict[str, str]:
+ """Classify each fingerprint into one of the 14 failure classes via batched LLM calls.
+
+ ``messages_by_fingerprint`` maps each fingerprint to its representative raw message — the LLM
+ reads the message (see the note above ``MESSAGE_MAX_CHARS``), the fingerprint keys the result.
+ One call per batch of ``CLASSIFY_BATCH_SIZE``. A batch that fails validation is retried once;
+ if it still fails, every fingerprint in that batch is marked ``internal_error`` rather than
+ left unclassified.
+ """
+ if not messages_by_fingerprint:
+ return {}
+
+ # Failure messages are customer-authored text, so shipping them to the LLM needs the
+ # organization's AI data processing consent, same as intent generation.
+ if not team.organization.is_ai_data_processing_approved:
+ raise FailureClassificationUnavailable("AI data processing is not approved for this organization")
+
+ client = OpenAI(posthog_client=posthoganalytics.default_client, base_url=settings.OPENAI_BASE_URL)
+ items = list(messages_by_fingerprint.items())
+ result: dict[str, str] = {}
+ with tags_context(
+ product=Product.MCP_ANALYTICS, feature=Feature.QUERY, team_id=team.id, name="mcp_analytics_failure_classifier"
+ ):
+ for start in range(0, len(items), CLASSIFY_BATCH_SIZE):
+ result.update(_classify_batch(client, items[start : start + CLASSIFY_BATCH_SIZE], team))
+ return result
diff --git a/products/mcp_analytics/backend/management/commands/classify_mcp_failures.py b/products/mcp_analytics/backend/management/commands/classify_mcp_failures.py
new file mode 100644
index 000000000000..69feb7433694
--- /dev/null
+++ b/products/mcp_analytics/backend/management/commands/classify_mcp_failures.py
@@ -0,0 +1,222 @@
+"""Staff tool: classify recent MCP tool-call failures by cause and print a breakdown.
+
+Thin and throwaway-grade on purpose — no caching tables, no snapshots, no feature flag. Reads
+``$mcp_tool_call`` failures from ClickHouse, groups raw messages into normalized fingerprints, and
+classifies each fingerprint with a batched LLM call (see ``failure_classification.py``).
+"""
+
+import csv
+from collections import defaultdict
+from dataclasses import dataclass, field
+from datetime import timedelta
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandParser
+from django.utils import timezone
+
+from posthog.hogql import ast
+from posthog.hogql.parser import parse_select
+from posthog.hogql.query import execute_hogql_query
+
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.models.team.team import Team
+from posthog.security.spreadsheet_safety import sanitize_formula_injection
+
+from products.mcp_analytics.backend.constants import MCP_TOOL_CALL_EVENT
+from products.mcp_analytics.backend.failure_classification import (
+ FailureClass,
+ FailureClassificationUnavailable,
+ classify_fingerprints,
+ normalize_fingerprint,
+)
+
+EXAMPLE_MAX_CHARS = 80
+
+
+def _clean(value: str) -> str:
+ """Raw messages carry tabs and newlines; keep the TSV/stdout tables one row per record.
+
+ Values are event-sender-controlled, so exported cells also get formula-injection
+ sanitization — staff will open this file in a spreadsheet.
+ """
+ flattened = value.replace("\t", " ").replace("\n", " | ").replace("\r", "")
+ sanitized: str = sanitize_formula_injection(flattened)
+ return sanitized
+
+
+_FAILURES_SQL = """
+SELECT
+ toString(properties.$mcp_tool_name) AS tool,
+ toString(properties.$mcp_error_message) AS message,
+ count() AS events,
+ uniq(distinct_id) AS users
+FROM events
+WHERE event = {event}
+ AND timestamp >= {date_from}
+ AND toBool(properties.$mcp_is_error)
+ AND isNotNull(properties.$mcp_error_message)
+GROUP BY tool, message
+ORDER BY events DESC
+"""
+
+
+@dataclass
+class FingerprintAggregate:
+ events: int = 0
+ # Summed per-(tool, message) uniq counts: a user who hit several raw messages sharing one
+ # fingerprint is counted once per message, so this is an upper bound. An exact uniq would
+ # need the fingerprinting pushed into SQL, duplicating normalize_fingerprint and inviting
+ # drift; a bound is enough for ranking in a staff tool.
+ users_upper_bound: int = 0
+ tools: set[str] = field(default_factory=set)
+ example_message: str = ""
+ example_events: int = 0
+
+
+def fetch_failure_rows(team: Team, days: int) -> list[tuple[str, str, int, int]]:
+ """Return (tool, raw_message, event_count, user_count) rows for the team's recent failures."""
+ query = parse_select(
+ _FAILURES_SQL,
+ placeholders={
+ "event": ast.Constant(value=MCP_TOOL_CALL_EVENT),
+ "date_from": ast.Constant(value=timezone.now() - timedelta(days=days)),
+ },
+ )
+ with tags_context(
+ product=Product.MCP_ANALYTICS, feature=Feature.QUERY, team_id=team.id, name="classify_mcp_failures_command"
+ ):
+ response = execute_hogql_query(query=query, team=team)
+ return [
+ (str(row[0] or ""), str(row[1] or ""), int(row[2] or 0), int(row[3] or 0)) for row in (response.results or [])
+ ]
+
+
+def aggregate_by_fingerprint(
+ rows: list[tuple[str, str, int, int]], max_fingerprints: int
+) -> dict[str, FingerprintAggregate]:
+ """Group raw (tool, message) rows into fingerprints, keeping a representative message each.
+
+ ``rows`` come from ClickHouse ordered by event count descending, so the first raw message seen
+ for a fingerprint is its most common phrasing — that's what gets kept as the example.
+ """
+ aggregates: dict[str, FingerprintAggregate] = {}
+ for tool, message, events, users in rows:
+ fingerprint = normalize_fingerprint(message)
+ if not fingerprint:
+ continue
+ aggregate = aggregates.get(fingerprint)
+ if aggregate is None:
+ if len(aggregates) >= max_fingerprints:
+ continue
+ aggregate = FingerprintAggregate()
+ aggregates[fingerprint] = aggregate
+ aggregate.events += events
+ aggregate.users_upper_bound += users
+ if tool:
+ aggregate.tools.add(tool)
+ if events > aggregate.example_events:
+ aggregate.example_message = message
+ aggregate.example_events = events
+ return aggregates
+
+
+class Command(BaseCommand):
+ help = "Classify MCP tool-call failures by cause and print a per-class breakdown."
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ parser.add_argument("--team-id", type=int, required=True, help="Team ID to classify failures for.")
+ parser.add_argument("--days", type=int, default=30, help="Lookback window in days (default: 30).")
+ parser.add_argument(
+ "--max-fingerprints", type=int, default=500, help="Cap on distinct fingerprints classified (default: 500)."
+ )
+ parser.add_argument("--output", type=str, default=None, help="Optional TSV path for per-fingerprint rows.")
+ parser.add_argument("--dry-run", action="store_true", help="Skip the LLM; print fingerprint counts only.")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ team_id: int = options["team_id"]
+ days: int = options["days"]
+ max_fingerprints: int = options["max_fingerprints"]
+ output: str | None = options["output"]
+ dry_run: bool = options["dry_run"]
+
+ try:
+ team = Team.objects.get(pk=team_id)
+ except Team.DoesNotExist:
+ self.stderr.write(self.style.ERROR(f"Team {team_id} does not exist."))
+ return
+
+ rows = fetch_failure_rows(team, days)
+ total_failures = sum(row[2] for row in rows)
+ aggregates = aggregate_by_fingerprint(rows, max_fingerprints)
+
+ self.stdout.write(f"Total failures: {total_failures}")
+ self.stdout.write(f"Distinct fingerprints: {len(aggregates)}")
+
+ if dry_run:
+ self._print_dry_run(aggregates)
+ return
+
+ try:
+ classifications = classify_fingerprints(
+ {fingerprint: aggregate.example_message for fingerprint, aggregate in aggregates.items()}, team
+ )
+ except FailureClassificationUnavailable as e:
+ self.stderr.write(self.style.ERROR(f"Cannot classify: {e}"))
+ return
+ self._print_breakdown(aggregates, classifications, total_failures)
+ if output:
+ self._write_tsv(output, aggregates, classifications)
+
+ def _print_dry_run(self, aggregates: dict[str, FingerprintAggregate]) -> None:
+ self.stdout.write("\nfingerprint\tevents\tusers_upper_bound\texample")
+ for fingerprint, aggregate in sorted(aggregates.items(), key=lambda item: item[1].events, reverse=True):
+ example = _clean(aggregate.example_message)[:EXAMPLE_MAX_CHARS]
+ self.stdout.write(f"{fingerprint}\t{aggregate.events}\t{aggregate.users_upper_bound}\t{example}")
+
+ def _print_breakdown(
+ self,
+ aggregates: dict[str, FingerprintAggregate],
+ classifications: dict[str, str],
+ total_failures: int,
+ ) -> None:
+ by_class: dict[str, list[str]] = defaultdict(list)
+ for fingerprint in aggregates:
+ failure_class = classifications.get(fingerprint, FailureClass.INTERNAL_ERROR.value)
+ by_class[failure_class].append(fingerprint)
+
+ self.stdout.write("\nclass\tevents\tshare%\tfingerprints\texample")
+ rows = []
+ for failure_class, fingerprints in by_class.items():
+ events = sum(aggregates[f].events for f in fingerprints)
+ share = round(events * 100.0 / total_failures, 1) if total_failures else 0.0
+ example_fingerprint = max(fingerprints, key=lambda f: aggregates[f].events)
+ example = _clean(aggregates[example_fingerprint].example_message)[:EXAMPLE_MAX_CHARS]
+ rows.append((failure_class, events, share, len(fingerprints), example))
+
+ for failure_class, events, share, fingerprint_count, example in sorted(
+ rows, key=lambda row: row[1], reverse=True
+ ):
+ self.stdout.write(f"{failure_class}\t{events}\t{share}\t{fingerprint_count}\t{example}")
+
+ def _write_tsv(
+ self,
+ output: str,
+ aggregates: dict[str, FingerprintAggregate],
+ classifications: dict[str, str],
+ ) -> None:
+ with open(output, "w", newline="") as f:
+ writer = csv.writer(f, delimiter="\t", lineterminator="\n")
+ writer.writerow(["fingerprint", "class", "events", "users_upper_bound", "tools", "example"])
+ for fingerprint, aggregate in sorted(aggregates.items(), key=lambda item: item[1].events, reverse=True):
+ failure_class = classifications.get(fingerprint, FailureClass.INTERNAL_ERROR.value)
+ writer.writerow(
+ [
+ _clean(fingerprint),
+ failure_class,
+ aggregate.events,
+ aggregate.users_upper_bound,
+ _clean(",".join(sorted(aggregate.tools))),
+ _clean(aggregate.example_message)[:EXAMPLE_MAX_CHARS],
+ ]
+ )
+ self.stdout.write(f"\nWrote {len(aggregates)} rows to {output}")
diff --git a/products/mcp_analytics/backend/tests/test_failure_classification.py b/products/mcp_analytics/backend/tests/test_failure_classification.py
new file mode 100644
index 000000000000..837a13090ab2
--- /dev/null
+++ b/products/mcp_analytics/backend/tests/test_failure_classification.py
@@ -0,0 +1,146 @@
+"""Tests for failure fingerprinting and LLM-backed classification.
+
+Fingerprinting is a pure function — covered without Django. Classification hits an LLM boundary,
+which is mocked; no test calls the real API.
+"""
+
+import json
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from products.mcp_analytics.backend.failure_classification import (
+ CLASSIFY_BATCH_SIZE,
+ FailureClass,
+ FailureClassificationUnavailable,
+ classify_fingerprints,
+ normalize_fingerprint,
+)
+
+
+class TestNormalizeFingerprint:
+ @parameterized.expand(
+ [
+ (
+ "uuid",
+ "Resource 123e4567-e89b-12d3-a456-426614174000 not found",
+ "resource not found",
+ ),
+ ("email", "No account for [email protected]", "no account for"),
+ ("url", "fetch failed: https://api.example.com/v1/things?id=1", "fetch failed:"),
+ (
+ "double_quoted_value",
+ 'Invalid arguments: "some-tool-name" is not a valid tool',
+ "invalid arguments: is not a valid tool",
+ ),
+ ("single_quoted_value", "Field 'email' is required", "field is required"),
+ ("numbers", "timed out after 45000ms, retried 3 times", "timed out after ms, retried times"),
+ ("iso_date", "Rate limited until 2026-08-06T12:00:00Z", "rate limited until"),
+ ("whitespace", "tool failed\n\nwith no cause", "tool failed with no cause"),
+ ]
+ )
+ def test_strips_variable_content(self, _name: str, raw: str, expected: str) -> None:
+ assert normalize_fingerprint(raw) == expected
+
+ def test_truncates_to_200_chars(self) -> None:
+ assert len(normalize_fingerprint("x" * 500)) == 200
+
+ def test_translation_stays_a_distinct_fingerprint(self) -> None:
+ # Fingerprinting groups occurrences of the same wording; it must not merge a message
+ # with its translation, which classify_fingerprints treats as separate inputs.
+ english = normalize_fingerprint("The email field is required")
+ portuguese = normalize_fingerprint("O campo email é obrigatório")
+
+ assert english != portuguese
+
+
+def _openai_response(content: str) -> MagicMock:
+ response = MagicMock()
+ response.choices = [MagicMock(message=MagicMock(content=content))]
+ return response
+
+
+def _classification_payload(fingerprints: list[str], failure_class: str) -> str:
+ return json.dumps(
+ {"classifications": [{"line_number": i + 1, "failure_class": failure_class} for i in range(len(fingerprints))]}
+ )
+
+
+class TestClassifyFingerprints(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.is_ai_data_processing_approved = True
+ self.organization.save()
+
+ def test_raises_without_ai_processing_consent(self) -> None:
+ self.organization.is_ai_data_processing_approved = False
+ self.organization.save()
+ with patch("products.mcp_analytics.backend.failure_classification.OpenAI") as mock_openai_cls:
+ with self.assertRaises(FailureClassificationUnavailable):
+ classify_fingerprints({"a fingerprint": "a raw message"}, self.team)
+
+ mock_openai_cls.return_value.chat.completions.create.assert_not_called()
+
+ def test_returns_mapping_from_fingerprint_to_class(self) -> None:
+ items = {
+ "timed out after seconds": "Error: timed out after 45 seconds",
+ "resource not found": "Resource 123 not found",
+ }
+ payload = json.dumps(
+ {
+ "classifications": [
+ {"line_number": 1, "failure_class": "timeout"},
+ {"line_number": 2, "failure_class": "resource_not_found"},
+ ]
+ }
+ )
+ with patch("products.mcp_analytics.backend.failure_classification.OpenAI") as mock_openai_cls:
+ mock_create = mock_openai_cls.return_value.chat.completions.create
+ mock_create.return_value = _openai_response(payload)
+ result = classify_fingerprints(items, self.team)
+
+ assert result == {"timed out after seconds": "timeout", "resource not found": "resource_not_found"}
+ # The prompt must carry the raw message (with its numbers), not the stripped fingerprint —
+ # the boundary rules pivot on codes like 429/-32601 that normalization removes.
+ prompt = mock_create.call_args.kwargs["messages"][1]["content"]
+ assert "timed out after 45 seconds" in prompt
+
+ def test_batches_at_25_fingerprints(self) -> None:
+ items = {f"fingerprint {i}": f"raw message {i}" for i in range(CLASSIFY_BATCH_SIZE + 1)}
+ keys = list(items)
+ with patch("products.mcp_analytics.backend.failure_classification.OpenAI") as mock_openai_cls:
+ mock_create = mock_openai_cls.return_value.chat.completions.create
+ mock_create.side_effect = [
+ _openai_response(_classification_payload(keys[:CLASSIFY_BATCH_SIZE], "internal_error")),
+ _openai_response(_classification_payload(keys[CLASSIFY_BATCH_SIZE:], "internal_error")),
+ ]
+ result = classify_fingerprints(items, self.team)
+
+ assert mock_create.call_count == 2
+ assert len(result) == len(items)
+
+ @parameterized.expand(
+ [
+ ("invalid_class", [{"line_number": 1, "failure_class": "not_a_real_class"}]),
+ (
+ "duplicate_line_numbers",
+ [{"line_number": 1, "failure_class": "timeout"}, {"line_number": 1, "failure_class": "rate_limited"}],
+ ),
+ ("missing_line", []),
+ ("out_of_range_line", [{"line_number": 7, "failure_class": "timeout"}]),
+ ]
+ )
+ def test_malformed_response_is_retried_then_marked_internal_error(
+ self, _name: str, classifications: list[dict[str, object]]
+ ) -> None:
+ items = {"some fingerprint": "some raw message"}
+ payload = json.dumps({"classifications": classifications})
+ with patch("products.mcp_analytics.backend.failure_classification.OpenAI") as mock_openai_cls:
+ mock_create = mock_openai_cls.return_value.chat.completions.create
+ mock_create.side_effect = [_openai_response(payload), _openai_response(payload)]
+ result = classify_fingerprints(items, self.team)
+
+ assert mock_create.call_count == 2
+ assert result == {"some fingerprint": FailureClass.INTERNAL_ERROR.value}