Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(error-tracking): judge auto-merges beyond the distance threshold (#117014)

Hugues Pouillotbd1a99afc1e2
diff --git a/products/error_tracking/backend/temporal/fingerprint_embedding_result/activities.py b/products/error_tracking/backend/temporal/fingerprint_embedding_result/activities.py
index a95316631737..739892089357 100644
--- a/products/error_tracking/backend/temporal/fingerprint_embedding_result/activities.py
+++ b/products/error_tracking/backend/temporal/fingerprint_embedding_result/activities.py
@@ -1,3 +1,4 @@
+import math
import time
import uuid
from datetime import datetime, timedelta
@@ -6,6 +7,7 @@ from django.conf import settings
from django.utils.dateparse import parse_datetime
from posthog.hogql import ast
+from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
@@ -23,6 +25,16 @@ from products.error_tracking.backend.models import (
ErrorTrackingIssueFingerprintV2,
ErrorTrackingIssueMergeResult,
)
+from products.error_tracking.backend.temporal.fingerprint_embedding_result.judge import (
+ DEFAULT_AUTO_MERGE_CONFIG,
+ JUDGE_MODEL,
+ JUDGE_PROMPT_VERSION,
+ AutoMergeConfig,
+ JudgeUnavailableError,
+ JudgeVerdict,
+ ask_judge,
+ load_auto_merge_config,
+)
from products.error_tracking.backend.temporal.fingerprint_embedding_result.types import (
AutoMergeOutcome,
AutoMergeReopenedTarget,
@@ -32,7 +44,6 @@ from products.error_tracking.backend.temporal.fingerprint_embedding_result.types
)
from products.error_tracking.backend.temporal.lifecycle.types import LifecycleIssueSnapshot
-AUTO_MERGE_DISTANCE_THRESHOLD = 0.019
NIL_UUID = "00000000-0000-0000-0000-000000000000"
CLOSEST_FINGERPRINTS_QUERY_BY_MODEL = {
@@ -63,6 +74,32 @@ CLOSEST_FINGERPRINTS_QUERY_BY_MODEL = {
}
+FINGERPRINT_DOCUMENT_QUERY_BY_MODEL = {
+ "text-embedding-3-large-3072": """
+ SELECT document_id, argMax(content, inserted_at) AS content
+ FROM document_embeddings_text_embedding_3_large_3072
+ WHERE document_type = 'fingerprint'
+ AND product = 'error_tracking'
+ AND rendering = {rendering}
+ AND team_id = {team_id}
+ AND document_id = {fingerprint}
+ AND timestamp >= {min_timestamp}
+ GROUP BY document_id
+ """,
+ "text-embedding-3-small-1536": """
+ SELECT document_id, argMax(content, inserted_at) AS content
+ FROM document_embeddings_text_embedding_3_small_1536
+ WHERE document_type = 'fingerprint'
+ AND product = 'error_tracking'
+ AND rendering = {rendering}
+ AND team_id = {team_id}
+ AND document_id = {fingerprint}
+ AND timestamp >= {min_timestamp}
+ GROUP BY document_id
+ """,
+}
+
+
class TargetFingerprintEmbeddingNotFoundError(RuntimeError):
pass
@@ -230,28 +267,178 @@ def _reopened_target(
)
+def _merge_into_candidate(
+ team: Team,
+ fingerprint: str,
+ source_fingerprint: ErrorTrackingIssueFingerprintV2,
+ target_fingerprint: ErrorTrackingIssueFingerprintV2,
+ candidate: SimilarFingerprintDistance,
+ event_reference: str,
+ decision_properties: dict[str, object],
+) -> AutoMergeOutcome:
+ source_issue_id = source_fingerprint.issue_id
+ target_issue_id = target_fingerprint.issue_id
+ target_issue = target_fingerprint.issue
+ merge_outcome = target_issue.merge(
+ issue_ids=[source_issue_id],
+ expected_fingerprint_issue_ids={
+ fingerprint: source_issue_id,
+ candidate.fingerprint: target_issue_id,
+ },
+ )
+ if merge_outcome.result == ErrorTrackingIssueMergeResult.NO_SOURCE_ISSUES:
+ return AutoMergeOutcome()
+ if merge_outcome.result != ErrorTrackingIssueMergeResult.MERGED:
+ raise StaleAutoMergeStateError(f"Fingerprint issue ownership changed before auto-merge for team {team.id}")
+
+ capture = ph_background_capture()
+ capture(
+ distinct_id=str(team.uuid),
+ event="error_tracking_issue_merged",
+ groups=groups(team=team),
+ properties={
+ "merge_source": "auto",
+ "source_issue_id": str(source_issue_id),
+ "target_issue_id": str(target_issue_id),
+ "source_fingerprint": fingerprint,
+ "target_fingerprint": candidate.fingerprint,
+ "distance": candidate.distance,
+ **decision_properties,
+ },
+ )
+ reopened_target = (
+ _reopened_target(target_issue, event_reference=event_reference) if merge_outcome.reopened else None
+ )
+ return AutoMergeOutcome(merged_count=1, reopened_target=reopened_target)
+
+
+def _fetch_fingerprint_document(
+ team: Team, inputs: FingerprintEmbeddingResultInputs, fingerprint: str, *, timeout_seconds: float
+) -> str | None:
+ """The text that was embedded for a fingerprint, within the nearest-neighbour search window."""
+ query = parse_select(
+ _model_specific_query(FINGERPRINT_DOCUMENT_QUERY_BY_MODEL, inputs.model_name),
+ placeholders={
+ "rendering": ast.Constant(value=inputs.rendering),
+ "team_id": ast.Constant(value=team.id),
+ "fingerprint": ast.Constant(value=fingerprint),
+ "min_timestamp": ast.Constant(value=_parse_timestamp(inputs.timestamp) - timedelta(days=30)),
+ },
+ )
+ response = execute_hogql_query(
+ query=query,
+ team=team,
+ query_type="ErrorTrackingAutoMergeJudgeDocument",
+ workload=Workload.OFFLINE,
+ ch_user=ClickHouseUser.ERROR_TRACKING,
+ settings=HogQLGlobalSettings(max_execution_time=max(1, math.ceil(timeout_seconds))),
+ )
+ return next((row[1] for row in response.results if row[1]), None)
+
+
+def _judge(
+ team: Team, inputs: FingerprintEmbeddingResultInputs, candidate: SimilarFingerprintDistance, config: AutoMergeConfig
+) -> JudgeVerdict:
+ """Judge one pair within the judge timeout. Raises JudgeUnavailableError with the reason when it can't."""
+ # Consent can be withdrawn between embedding and this (possibly retried) activity.
+ if not team.organization.is_ai_data_processing_approved:
+ raise JudgeUnavailableError("ai_processing_not_approved")
+ # One budget for the lookup and the inference, so a slow ClickHouse can't hold the activity longer.
+ deadline = time.monotonic() + config.judge_timeout_seconds
+ try:
+ candidate_document = _fetch_fingerprint_document(
+ team, inputs, candidate.fingerprint, timeout_seconds=config.judge_timeout_seconds
+ )
+ except Exception as err:
+ if is_expected_activity_failure(err):
+ raise
+ capture_exception(err, additional_properties={"team_id": team.id, "fingerprint": inputs.fingerprint})
+ raise JudgeUnavailableError("document_fetch_failed") from err
+ # The source text arrives with the inputs: ClickHouse may not have ingested it yet.
+ if not inputs.content or not candidate_document:
+ raise JudgeUnavailableError("missing_document")
+ remaining_seconds = deadline - time.monotonic()
+ if remaining_seconds <= 0:
+ raise JudgeUnavailableError("judge_timeout")
+ return ask_judge(team.id, inputs.content, candidate_document, remaining_seconds)
+
+
+def _judge_candidate(
+ team: Team,
+ inputs: FingerprintEmbeddingResultInputs,
+ candidate: SimilarFingerprintDistance,
+ config: AutoMergeConfig,
+) -> float | None:
+ """Ask the judge about one candidate and report the verdict. Returns the score, or None when unavailable.
+
+ A judge failure never fails the activity: the fingerprint just stays unmerged, as it would today.
+ """
+ score: float | None = None
+ latency_ms: float | None = None
+ error: str | None = None
+ try:
+ verdict = _judge(team, inputs, candidate, config)
+ score, latency_ms = verdict.score, verdict.latency_ms
+ except JudgeUnavailableError as err:
+ error = str(err)
+
+ capture = ph_background_capture()
+ capture(
+ distinct_id=str(team.uuid),
+ event="error_tracking_auto_merge_judged",
+ groups=groups(team=team),
+ properties={
+ "source_fingerprint": inputs.fingerprint,
+ "target_fingerprint": candidate.fingerprint,
+ "distance": candidate.distance,
+ "judge_score": score,
+ "judge_latency_ms": latency_ms,
+ "judge_error": error,
+ "judge_model": JUDGE_MODEL,
+ "judge_prompt_version": JUDGE_PROMPT_VERSION,
+ "judge_cutoff": config.judge_cutoff,
+ "judge_max_distance": config.judge_max_distance,
+ "judge_shadow": config.judge_shadow,
+ "auto_merge_threshold": config.auto_merge_threshold,
+ "would_merge": score is not None and score >= config.judge_cutoff,
+ },
+ )
+ return score
+
+
def _merge_fingerprint_into_closest_issue(
team: Team,
fingerprint: str,
closest_fingerprints: list[SimilarFingerprintDistance],
expected_source_issue_id: str | None = None,
event_reference: str = "",
+ config: AutoMergeConfig = DEFAULT_AUTO_MERGE_CONFIG,
+ judge_inputs: FingerprintEmbeddingResultInputs | None = None,
) -> AutoMergeOutcome:
+ """Merge into the nearest neighbour in another issue: directly below the threshold, else if the judge agrees.
+
+ `judge_inputs` carries what the judge needs (model, rendering, source text); without it only the
+ distance rule applies.
+ """
team_id = team.id
if not settings.ERROR_TRACKING_AUTO_MERGE_ENABLED:
return AutoMergeOutcome()
- eligible_fingerprints = [
- candidate for candidate in closest_fingerprints if candidate.distance < AUTO_MERGE_DISTANCE_THRESHOLD
+ judging = config.judge_enabled and judge_inputs is not None
+ candidates = [
+ candidate
+ for candidate in closest_fingerprints
+ if candidate.distance < config.auto_merge_threshold
+ or (judging and candidate.distance <= config.judge_max_distance)
]
- if not eligible_fingerprints:
+ if not candidates:
return AutoMergeOutcome()
fingerprints_by_value = {
row.fingerprint: row
for row in ErrorTrackingIssueFingerprintV2.objects.filter(
team_id=team_id,
- fingerprint__in=[fingerprint, *(candidate.fingerprint for candidate in eligible_fingerprints)],
+ fingerprint__in=[fingerprint, *(candidate.fingerprint for candidate in candidates)],
)
.select_related("issue")
.order_by("fingerprint", "id")
@@ -270,44 +457,32 @@ def _merge_fingerprint_into_closest_issue(
# completed, so allow the issue-created side effects instead of exhausting activity retries.
return AutoMergeOutcome()
- for candidate in eligible_fingerprints:
+ # Candidates come nearest first, so a distance merge always wins over a judged one.
+ for candidate in candidates:
target_fingerprint = fingerprints_by_value.get(candidate.fingerprint)
if target_fingerprint is None or source_fingerprint.issue_id == target_fingerprint.issue_id:
continue
-
- source_issue_id = source_fingerprint.issue_id
- target_issue_id = target_fingerprint.issue_id
- target_issue = target_fingerprint.issue
- merge_outcome = target_issue.merge(
- issue_ids=[source_issue_id],
- expected_fingerprint_issue_ids={
- fingerprint: source_issue_id,
- candidate.fingerprint: target_issue_id,
- },
- )
- if merge_outcome.result == ErrorTrackingIssueMergeResult.NO_SOURCE_ISSUES:
- return AutoMergeOutcome()
- if merge_outcome.result != ErrorTrackingIssueMergeResult.MERGED:
- raise StaleAutoMergeStateError(f"Fingerprint issue ownership changed before auto-merge for team {team_id}")
-
- capture = ph_background_capture()
- capture(
- distinct_id=str(team.uuid),
- event="error_tracking_issue_merged",
- groups=groups(team=team),
- properties={
- "merge_source": "auto",
- "source_issue_id": str(source_issue_id),
- "target_issue_id": str(target_issue_id),
- "source_fingerprint": fingerprint,
- "target_fingerprint": candidate.fingerprint,
- "distance": candidate.distance,
- },
- )
- reopened_target = (
- _reopened_target(target_issue, event_reference=event_reference) if merge_outcome.reopened else None
+ if candidate.distance < config.auto_merge_threshold:
+ decision: dict[str, object] = {
+ "merge_decision": "distance",
+ "auto_merge_threshold": config.auto_merge_threshold,
+ }
+ elif judge_inputs is not None:
+ score = _judge_candidate(team, judge_inputs, candidate, config)
+ if score is None or score < config.judge_cutoff or config.judge_shadow:
+ return AutoMergeOutcome()
+ decision = {
+ "merge_decision": "judge",
+ "judge_score": score,
+ "judge_cutoff": config.judge_cutoff,
+ "judge_model": JUDGE_MODEL,
+ "judge_prompt_version": JUDGE_PROMPT_VERSION,
+ }
+ else:
+ continue
+ return _merge_into_candidate(
+ team, fingerprint, source_fingerprint, target_fingerprint, candidate, event_reference, decision
)
- return AutoMergeOutcome(merged_count=1, reopened_target=reopened_target)
return AutoMergeOutcome()
@@ -338,6 +513,11 @@ def merge_similar_fingerprints(
closest_fingerprints,
inputs.source_issue_id,
event_reference=_event_reference(inputs),
+ # Only read the flag when there is something to decide.
+ config=load_auto_merge_config(team)
+ if settings.ERROR_TRACKING_AUTO_MERGE_ENABLED and closest_fingerprints
+ else DEFAULT_AUTO_MERGE_CONFIG,
+ judge_inputs=inputs,
)
return FingerprintEmbeddingMergeResult(
diff --git a/products/error_tracking/backend/temporal/fingerprint_embedding_result/judge.py b/products/error_tracking/backend/temporal/fingerprint_embedding_result/judge.py
new file mode 100644
index 000000000000..f264e22dd6b8
--- /dev/null
+++ b/products/error_tracking/backend/temporal/fingerprint_embedding_result/judge.py
@@ -0,0 +1,211 @@
+"""LLM judge for auto-merging fingerprints whose nearest neighbour is too far for a distance-only merge.
+
+The rule: merge automatically when the embedding distance is below `auto_merge_threshold`; between
+that and `judge_max_distance`, ask Jeeves (a small classifier on the PostHog AI gateway) whether
+the two error documents are the same issue and merge when its probability reaches `judge_cutoff`.
+
+Every knob comes from the `error-tracking-auto-merge-config` feature flag payload, evaluated per
+team, so thresholds can change without a deploy. With no payload the behaviour is today's
+distance-only rule. `judge_shadow` scores and reports without merging, to evaluate settings on
+live traffic first.
+
+The prompt version is recorded on every judged and merged event, so a prompt change can be
+compared against the previous one on live traffic.
+"""
+
+import time
+import dataclasses
+
+import structlog
+import posthoganalytics
+
+from posthog.llm.system_one import NoulAnswer, NoulQuestion, SystemOneNotConfigured, SystemOneRequestFailed
+from posthog.llm.system_one_client import build_system_one_client
+from posthog.models import Team
+
+logger = structlog.get_logger(__name__)
+
+AUTO_MERGE_CONFIG_FLAG = "error-tracking-auto-merge-config"
+DEFAULT_AUTO_MERGE_THRESHOLD = 0.019
+JUDGE_MODEL = "posthog/hogference/jeeves-0.1"
+JUDGE_PROMPT_VERSION = "v4"
+JUDGE_QUESTION_KEY = "same_issue"
+MAX_DOCUMENT_CHARS = 6000 # what the judge was evaluated with
+
+
[email protected](frozen=True)
+class AutoMergeConfig:
+ # Merge without the judge when the nearest-neighbour distance is strictly below this.
+ auto_merge_threshold: float = DEFAULT_AUTO_MERGE_THRESHOLD
+ judge_enabled: bool = False
+ # Ask the judge for distances in [auto_merge_threshold, judge_max_distance].
+ judge_max_distance: float = 0.1
+ # Merge when the judge's P(same issue) is at least this.
+ judge_cutoff: float = 0.9
+ # Score and report, but never merge on the judge's verdict.
+ judge_shadow: bool = True
+ judge_timeout_seconds: float = 10.0
+
+
+# Today's distance-only rule: what every team gets without a flag payload.
+DEFAULT_AUTO_MERGE_CONFIG = AutoMergeConfig()
+
+
+def _bounded(value: object, default: float, low: float, high: float) -> float:
+ if isinstance(value, bool) or not isinstance(value, int | float) or not low <= value <= high:
+ return default
+ return float(value)
+
+
+def parse_auto_merge_config(payload: object) -> AutoMergeConfig:
+ """Build the config from a flag payload, keeping the default for any missing or invalid field."""
+ payload = payload if isinstance(payload, dict) else {}
+ raw_judge = payload.get("judge")
+ judge: dict[str, object] = raw_judge if isinstance(raw_judge, dict) else {}
+ defaults = AutoMergeConfig()
+ config = AutoMergeConfig(
+ auto_merge_threshold=_bounded(payload.get("auto_merge_threshold"), defaults.auto_merge_threshold, 0, 1),
+ judge_enabled=judge.get("enabled") is True,
+ judge_max_distance=_bounded(judge.get("max_distance"), defaults.judge_max_distance, 0, 1),
+ judge_cutoff=_bounded(judge.get("cutoff"), defaults.judge_cutoff, 0, 1),
+ judge_shadow=judge.get("shadow") is not False,
+ judge_timeout_seconds=_bounded(judge.get("timeout_seconds"), defaults.judge_timeout_seconds, 0.1, 60),
+ )
+ if config.judge_max_distance < config.auto_merge_threshold:
+ # An inverted band would judge nothing; make the misconfiguration visible instead of silent.
+ logger.warning("error_tracking_auto_merge_config_inverted_band", payload=payload)
+ return dataclasses.replace(config, judge_enabled=False)
+ return config
+
+
+def load_auto_merge_config(team: Team) -> AutoMergeConfig:
+ """Read the per-team config from the feature flag payload; fall back to today's rule on any failure."""
+ try:
+ payload = posthoganalytics.get_feature_flag_payload(
+ AUTO_MERGE_CONFIG_FLAG,
+ str(team.uuid),
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ group_properties={"organization": {"id": str(team.organization_id)}, "project": {"id": str(team.id)}},
+ # The hot path runs for every new fingerprint: never block on a remote /flags call.
+ only_evaluate_locally=True,
+ send_feature_flag_events=False,
+ )
+ except Exception as err:
+ logger.warning("error_tracking_auto_merge_config_unavailable", team_id=team.id, error=str(err))
+ return AutoMergeConfig()
+ return parse_auto_merge_config(payload)
+
+
+# Shared same-issue rubric. It encodes the grouping decisions: not-found paths and assets are one
+# issue, chunk-load failures are one issue, transient transport failures group by the failure,
+# React minified errors split on code/args/route, injected scripts group across pages.
+JUDGE_QUESTION = """\
+Do these two error documents represent the SAME underlying issue, i.e. would a developer fixing one \
+consider the other a duplicate that should be grouped with it, because one fix resolves both?
+How to decide:
+1. Find the THROW SITE of each document: the error type, the message, and the application frames \
+nearest to where the error was raised. Frames are usually listed from the outermost caller first to \
+the throw site last (numbered frames: #00 is the throw site).
+2. If the throw sites match, the documents are the SAME issue even when they differ in:
+- dynamic values anywhere: IDs, URLs and URL path segments, numbers, percentages, timestamps, memory \
+addresses, thread/process names, session ids, user input, in any language;
+- line/column numbers, build hashes in file names, bundler module ids and chunk names, and minified \
+frame names (1–3 character identifiers such as iu, o6, fT that change between builds);
+- the outer callers above the throw site, extra or missing frames at the bottom of the stack, stacks \
+truncated at a different depth (e.g. stack overflows), and frames inside framework or runtime \
+internals (React reconciler/scheduler, webpack runtime, unsymbolicated VM addresses);
+- a frame whose "file" is a page URL (/shop vs /games): it is the same inline, injected or \
+single-page-app script running on another page; compare its function names instead. When those \
+frames have no function names, they count as the same script only if the message is identical and \
+the frame shape matches; inline event handlers (onclick, ...) belong to their own page and are not shared;
+- the variable part of a templated message when the error type, template and throw site match: the \
+requested path or asset in not-found / failed-to-load errors (404 for /a vs /b, ASSET_LOAD_FAILED for \
+different assets), or a list of rejected fields from the same validator. When the variable part is \
+itself an error message, compare that inner error as its own throw site;
+- which chunk or module failed in chunk / dynamic-import load failures (ChunkLoadError, "error loading \
+dynamically imported module"): one issue (deploy skew or network);
+- which caller hit the same failing dependency in transient transport-level failures (no HTTP \
+response: network error, aborted request, timeout, DNS or TLS failure, connection pool exhausted, or \
+HTTP 502/503/504): group by the failure, not by the caller. An HTTP 4xx or 500 response is never transient;
+- which hook or component hit a null React dispatcher ("reading 'useState'", 'useContext', ... thrown \
+inside React's hook exports): one issue (duplicate React copy or hook called outside render);
+- the page on which a browser- or extension-injected script failed (window.ethereum, __firefox__, \
+_AutofillCallbackHandler).
+3. They are DIFFERENT issues when the throw sites differ:
+- different meaningful application files, components, handlers or functions nearest the throw site \
+(when the error is raised inside framework or library code, the first application frames calling into \
+it decide), e.g. OrderSummary.tsx vs OrderHistory.tsx, component Pricing vs Checkout, even with an \
+identical message: the same failure in two places needs two fixes. Named frames without a file \
+(Pricing, loadPricingPlans) are application frames, not minified names;
+- with no application frames at all, the library frame that calls into the framework stands in for \
+the application frame (react-use-websocket vs jotai calling into react-dom);
+- names that come from the application's own code differ: the undefined identifier (googletag vs \
+jQuery is not defined), the missing property, key or module, a nested error class in the message \
+(NetworkError vs AbortError), a different HTTP status (404 vs 401, 500 vs 503) or an HTTP status vs a \
+network error, or a different operation;
+- React minified errors (e.g. #418) with a different error code, OR different args (text vs HTML), OR \
+different route-specific files or components (billing-*.js vs reports-*.js): any one of these makes \
+them different;
+- the error type or root message differs in meaning, not just in dynamic values.
+
+Examples (SAME): "Page not found: /config.js" vs "Page not found: /wp-json/x" with the same stack; \
+"Failed to load asset at path: /Game/Items/BP_Key" vs "/Game/BP_Key"; the same recursion frames on \
+/shop vs /games; a connection-pool-exhausted error reached from two different request handlers; a \
+validation error listing different rejected fields from the same validator.
+Examples (DIFFERENT): "googletag is not defined" vs "jQuery is not defined"; "status code 404" vs \
+"Network Error"; the same TypeError thrown in component Pricing vs component Checkout.
+
+Before deciding, name the throw site of each document. Then check the DIFFERENT rules in step 3 \
+first: if any one applies, answer DIFFERENT. Only otherwise check the SAME rules in step 2: if they \
+explain every difference, answer SAME. Product decisions in step 2 (e.g. different missing assets or \
+404 paths are one issue) override the intuition that each needs its own fix."""
+
+
+TRUNCATION_MARKER = "\n[... frames omitted ...]\n"
+
+
+def _truncate(document: str) -> str:
+ """Keep the message (start) and the throw site (end): frames run outermost first, so the end matters."""
+ if len(document) <= MAX_DOCUMENT_CHARS:
+ return document
+ head = MAX_DOCUMENT_CHARS // 4
+ tail = MAX_DOCUMENT_CHARS - head - len(TRUNCATION_MARKER)
+ return document[:head] + TRUNCATION_MARKER + document[-tail:]
+
+
+def judge_state(document: str, candidate_document: str) -> str:
+ return (
+ "Two error documents from the same application were assigned different grouping "
+ "fingerprints. Each is an error type + message followed by a stack trace.\n\n"
+ f"<document_a>\n{_truncate(document)}\n</document_a>\n\n"
+ f"<document_b>\n{_truncate(candidate_document)}\n</document_b>"
+ )
+
+
+class JudgeUnavailableError(RuntimeError):
+ pass
+
+
[email protected](frozen=True)
+class JudgeVerdict:
+ score: float
+ latency_ms: float
+
+
+def ask_judge(team_id: int, document: str, candidate_document: str, timeout_seconds: float) -> JudgeVerdict:
+ """Ask Jeeves for P(same issue). Raises JudgeUnavailableError when it can't answer."""
+ start = time.monotonic()
+ try:
+ client = build_system_one_client(
+ model=JUDGE_MODEL, ai_product="error_tracking", team_id=team_id, timeout=timeout_seconds
+ )
+ result = client.decide(
+ state=judge_state(document, candidate_document),
+ questions={JUDGE_QUESTION_KEY: NoulQuestion(instructions=JUDGE_QUESTION)},
+ )
+ except (SystemOneNotConfigured, SystemOneRequestFailed) as err:
+ raise JudgeUnavailableError(str(err)) from err
+ answer = result.answers.get(JUDGE_QUESTION_KEY)
+ if not isinstance(answer, NoulAnswer):
+ raise JudgeUnavailableError("Judge refused or gave no answer")
+ return JudgeVerdict(score=answer.probability, latency_ms=(time.monotonic() - start) * 1000)
diff --git a/products/error_tracking/backend/temporal/fingerprint_embedding_result/test/test_judge.py b/products/error_tracking/backend/temporal/fingerprint_embedding_result/test/test_judge.py
new file mode 100644
index 000000000000..823c116a0b80
--- /dev/null
+++ b/products/error_tracking/backend/temporal/fingerprint_embedding_result/test/test_judge.py
@@ -0,0 +1,286 @@
+import uuid
+import dataclasses
+from typing import NamedTuple
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from django.test import override_settings
+
+from parameterized import parameterized
+from temporalio.exceptions import CancelledError
+
+from posthog.llm.system_one import (
+ NoulAnswer,
+ RefusalAnswer,
+ SystemOneNotConfigured,
+ SystemOneRequestFailed,
+ SystemOneResult,
+)
+
+from products.error_tracking.backend.models import ErrorTrackingIssueMergeOutcome, ErrorTrackingIssueMergeResult
+from products.error_tracking.backend.temporal.fingerprint_embedding_result.activities import (
+ _fetch_fingerprint_document,
+ _merge_fingerprint_into_closest_issue,
+)
+from products.error_tracking.backend.temporal.fingerprint_embedding_result.judge import (
+ AutoMergeConfig,
+ JudgeUnavailableError,
+ JudgeVerdict,
+ ask_judge,
+ judge_state,
+ load_auto_merge_config,
+ parse_auto_merge_config,
+)
+from products.error_tracking.backend.temporal.fingerprint_embedding_result.types import (
+ FingerprintEmbeddingResultInputs,
+ SimilarFingerprintDistance,
+)
+
+ACTIVITIES = "products.error_tracking.backend.temporal.fingerprint_embedding_result.activities"
+JUDGE = "products.error_tracking.backend.temporal.fingerprint_embedding_result.judge"
+
+JUDGE_ON = AutoMergeConfig(
+ auto_merge_threshold=0.005, judge_enabled=True, judge_max_distance=0.3, judge_cutoff=0.8, judge_shadow=False
+)
+
+
+def _inputs(content: str | None = "Error: a") -> FingerprintEmbeddingResultInputs:
+ return FingerprintEmbeddingResultInputs(
+ team_id=2,
+ fingerprint="test-fingerprint",
+ rendering="type_message_and_stack",
+ timestamp="2026-06-08T00:00:00Z",
+ model_name="text-embedding-3-large-3072",
+ embedding=[0.1],
+ content=content,
+ )
+
+
+class TestAutoMergeConfig:
+ def test_no_payload_keeps_todays_rule(self) -> None:
+ assert parse_auto_merge_config(None) == AutoMergeConfig(auto_merge_threshold=0.019, judge_enabled=False)
+
+ def test_full_payload(self) -> None:
+ payload = {
+ "auto_merge_threshold": 0.005,
+ "judge": {"enabled": True, "max_distance": 0.3, "cutoff": 0.8, "shadow": False, "timeout_seconds": 5},
+ }
+
+ assert parse_auto_merge_config(payload) == AutoMergeConfig(
+ auto_merge_threshold=0.005,
+ judge_enabled=True,
+ judge_max_distance=0.3,
+ judge_cutoff=0.8,
+ judge_shadow=False,
+ judge_timeout_seconds=5.0,
+ )
+
+ @parameterized.expand(
+ [
+ ("out_of_range", {"auto_merge_threshold": 2}, "auto_merge_threshold", 0.019),
+ ("not_a_number", {"judge": {"cutoff": "0.8"}}, "judge_cutoff", 0.9),
+ ("enabled_must_be_true", {"judge": {"enabled": "yes"}}, "judge_enabled", False),
+ ("shadow_unless_false", {"judge": {"shadow": 0}}, "judge_shadow", True),
+ ]
+ )
+ def test_invalid_field_keeps_its_default(self, _name: str, payload: dict, field: str, expected: object) -> None:
+ assert getattr(parse_auto_merge_config(payload), field) == expected
+
+ def test_inverted_band_disables_the_judge(self) -> None:
+ payload = {"auto_merge_threshold": 0.05, "judge": {"enabled": True, "max_distance": 0.01}}
+
+ assert parse_auto_merge_config(payload).judge_enabled is False
+
+ def test_flag_failure_keeps_todays_rule(self) -> None:
+ with patch(f"{JUDGE}.posthoganalytics.get_feature_flag_payload", side_effect=RuntimeError("boom")):
+ config = load_auto_merge_config(MagicMock(id=1, uuid=uuid.uuid4(), organization_id=uuid.uuid4()))
+
+ assert config == AutoMergeConfig()
+
+
+class TestAskJudge:
+ def _ask(self, result: SystemOneResult | Exception) -> tuple[JudgeVerdict, MagicMock, MagicMock]:
+ client = MagicMock()
+ if isinstance(result, Exception):
+ client.decide.side_effect = result
+ else:
+ client.decide.return_value = result
+ with patch(f"{JUDGE}.build_system_one_client", return_value=client) as build:
+ verdict = ask_judge(7, "Error: a", "Error: b", timeout_seconds=3)
+ return verdict, build, client
+
+ def test_returns_the_noul_probability(self) -> None:
+ verdict, build, client = self._ask(
+ SystemOneResult(model="jeeves-0.1", answers={"same_issue": NoulAnswer(probability=0.87)}, input_tokens=10)
+ )
+
+ assert verdict.score == pytest.approx(0.87)
+ assert build.call_args.kwargs == {
+ "model": "posthog/hogference/jeeves-0.1",
+ "ai_product": "error_tracking",
+ "team_id": 7,
+ "timeout": 3,
+ }
+ assert "<document_a>\nError: a\n</document_a>" in client.decide.call_args.kwargs["state"]
+
+ @parameterized.expand(
+ [
+ ("refusal", SystemOneResult(model="jeeves-0.1", answers={"same_issue": RefusalAnswer()}, input_tokens=1)),
+ ("not_configured", SystemOneNotConfigured("no gateway")),
+ ("request_failed", SystemOneRequestFailed("rate limited", status_code=429)),
+ ]
+ )
+ def test_no_answer_is_unavailable(self, _name: str, result: SystemOneResult | Exception) -> None:
+ with pytest.raises(JudgeUnavailableError):
+ self._ask(result)
+
+ def test_long_documents_keep_the_message_and_the_throw_site(self) -> None:
+ document = "TypeError: boom\n" + "outer frame\n" * 1000 + "throwSite in app.js line 1"
+
+ state = judge_state(document, "short")
+
+ assert "TypeError: boom" in state
+ assert "throwSite in app.js line 1" in state
+
+
+class MergeRun(NamedTuple):
+ merged_count: int
+ target_issue: MagicMock
+ judge: MagicMock
+ fetch: MagicMock
+ events: dict[str, dict]
+
+
+class TestMergeWithJudge:
+ def _merge(
+ self,
+ distance: float,
+ config: AutoMergeConfig = JUDGE_ON,
+ score: float | Exception = 0.95,
+ neighbour_document: str | None | Exception = "Error: b",
+ inputs: FingerprintEmbeddingResultInputs | None = None,
+ consent: bool = True,
+ ) -> MergeRun:
+ source = MagicMock(issue_id=uuid.uuid4(), fingerprint="test-fingerprint")
+ target_issue = MagicMock()
+ target_issue.merge.return_value = ErrorTrackingIssueMergeOutcome(ErrorTrackingIssueMergeResult.MERGED)
+ target = MagicMock(issue_id=uuid.uuid4(), issue=target_issue, fingerprint="candidate")
+ query = MagicMock()
+ query.select_related.return_value.order_by.return_value = [target, source]
+ capture = MagicMock()
+ judge = MagicMock()
+ if isinstance(score, Exception):
+ judge.side_effect = score
+ else:
+ judge.return_value = JudgeVerdict(score=score, latency_ms=12.0)
+ fetch = MagicMock()
+ if isinstance(neighbour_document, Exception):
+ fetch.side_effect = neighbour_document
+ else:
+ fetch.return_value = neighbour_document
+ with (
+ override_settings(ERROR_TRACKING_AUTO_MERGE_ENABLED=True),
+ patch(f"{ACTIVITIES}.ErrorTrackingIssueFingerprintV2.objects.filter", return_value=query),
+ patch(f"{ACTIVITIES}.ph_background_capture", return_value=capture),
+ patch(f"{ACTIVITIES}.groups", return_value={}),
+ patch(f"{ACTIVITIES}._fetch_fingerprint_document", fetch),
+ patch(f"{ACTIVITIES}.capture_exception"),
+ patch(f"{ACTIVITIES}.ask_judge", judge),
+ ):
+ result = _merge_fingerprint_into_closest_issue(
+ team=MagicMock(id=2, uuid=uuid.uuid4(), organization=MagicMock(is_ai_data_processing_approved=consent)),
+ fingerprint="test-fingerprint",
+ closest_fingerprints=[SimilarFingerprintDistance(fingerprint="candidate", distance=distance)],
+ config=config,
+ judge_inputs=inputs or _inputs(),
+ )
+ events = {call.kwargs["event"]: call.kwargs["properties"] for call in capture.call_args_list}
+ return MergeRun(result.merged_count, target_issue, judge, fetch, events)
+
+ def test_below_the_threshold_merges_without_the_judge(self) -> None:
+ run = self._merge(0.004)
+
+ assert run.merged_count == 1
+ run.judge.assert_not_called()
+ assert run.events["error_tracking_issue_merged"]["merge_decision"] == "distance"
+
+ def test_judge_merges_at_the_cutoff(self) -> None:
+ run = self._merge(0.05, score=0.8)
+
+ assert run.merged_count == 1
+ assert run.fetch.call_args.args[2] == "candidate"
+ assert run.judge.call_args.args[1:3] == ("Error: a", "Error: b")
+ merged = run.events["error_tracking_issue_merged"]
+ assert (merged["merge_decision"], merged["judge_score"]) == ("judge", 0.8)
+
+ def test_judge_below_the_cutoff_does_not_merge(self) -> None:
+ run = self._merge(0.05, score=0.79)
+
+ assert run.merged_count == 0
+ assert run.events["error_tracking_auto_merge_judged"]["would_merge"] is False
+ assert "error_tracking_issue_merged" not in run.events
+
+ def test_shadow_mode_reports_but_never_merges(self) -> None:
+ run = self._merge(0.05, config=dataclasses.replace(JUDGE_ON, judge_shadow=True), score=0.99)
+
+ assert run.merged_count == 0
+ run.target_issue.merge.assert_not_called()
+ assert run.events["error_tracking_auto_merge_judged"]["would_merge"] is True
+
+ def test_beyond_the_cap_is_never_judged(self) -> None:
+ run = self._merge(0.31)
+
+ assert run.merged_count == 0
+ run.judge.assert_not_called()
+ assert run.events == {}
+
+ @parameterized.expand(
+ [
+ ("no_ai_consent", {"consent": False}, "ai_processing_not_approved"),
+ ("fetch_failed", {"neighbour_document": RuntimeError("clickhouse timeout")}, "document_fetch_failed"),
+ ("no_neighbour_document", {"neighbour_document": None}, "missing_document"),
+ ("no_source_text", {"inputs": _inputs(content=None)}, "missing_document"),
+ ("judge_unavailable", {"score": JudgeUnavailableError("timeout")}, "timeout"),
+ ]
+ )
+ def test_unavailable_judge_leaves_the_fingerprint_unmerged(self, _name: str, kwargs: dict, error: str) -> None:
+ run = self._merge(0.05, **kwargs)
+
+ assert run.merged_count == 0
+ run.target_issue.merge.assert_not_called()
+ judged = run.events["error_tracking_auto_merge_judged"]
+ assert (judged["judge_score"], judged["judge_error"]) == (None, error)
+
+ def test_lookup_and_inference_share_the_judge_timeout(self) -> None:
+ with patch(f"{ACTIVITIES}.time.monotonic", side_effect=[100.0, 104.0]):
+ run = self._merge(0.05)
+
+ assert run.fetch.call_args.kwargs == {"timeout_seconds": 10.0}
+ assert run.judge.call_args.args[3] == pytest.approx(6.0)
+
+ def test_exhausted_budget_skips_the_inference(self) -> None:
+ with patch(f"{ACTIVITIES}.time.monotonic", side_effect=[100.0, 111.0]):
+ run = self._merge(0.05)
+
+ run.judge.assert_not_called()
+ assert run.events["error_tracking_auto_merge_judged"]["judge_error"] == "judge_timeout"
+
+ def test_cancellation_during_the_document_fetch_is_reraised(self) -> None:
+ with pytest.raises(CancelledError):
+ self._merge(0.05, neighbour_document=CancelledError("Cancelled"))
+
+ def test_document_query_uses_the_model_table_and_search_window(self) -> None:
+ with (
+ patch(f"{ACTIVITIES}.parse_select") as parse_select,
+ patch(
+ f"{ACTIVITIES}.execute_hogql_query", return_value=MagicMock(results=[("candidate", "Error: b")])
+ ) as execute,
+ ):
+ document = _fetch_fingerprint_document(MagicMock(id=2), _inputs(), "candidate", timeout_seconds=2.5)
+
+ assert document == "Error: b"
+ assert execute.call_args.kwargs["settings"].max_execution_time == 3
+ query = parse_select.call_args.args[0]
+ assert "FROM document_embeddings_text_embedding_3_large_3072" in query
+ assert "timestamp >= {min_timestamp}" in query
diff --git a/products/error_tracking/backend/temporal/fingerprint_embedding_result/types.py b/products/error_tracking/backend/temporal/fingerprint_embedding_result/types.py
index e2439cd85ce8..9c32b7968285 100644
--- a/products/error_tracking/backend/temporal/fingerprint_embedding_result/types.py
+++ b/products/error_tracking/backend/temporal/fingerprint_embedding_result/types.py
@@ -14,6 +14,8 @@ class FingerprintEmbeddingResultInputs:
source_issue_id: str | None = None
event_uuid: str | None = None
event_timestamp: str | None = None
+ # The text that was embedded, so the judge doesn't read it back before ClickHouse has ingested it.
+ content: str | None = None
@dataclasses.dataclass(frozen=True)
diff --git a/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py b/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py
index 34d32ecc78cd..12595c7a958d 100644
--- a/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py
+++ b/products/error_tracking/backend/temporal/lifecycle/issue_created/activities.py
@@ -152,6 +152,7 @@ def _prepare_issue_created_embedding(inputs: IssueCreatedWorkflowInputs) -> Issu
source_issue_id=inputs.issue_id,
event_uuid=inputs.event_uuid,
event_timestamp=inputs.event_timestamp,
+ content=content,
),
content=content,
),