: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
fix(llma): scope eval clustering embeddings per job in document_id (#63511)
Andrew Maguire75826de7c514
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/constants.py b/posthog/temporal/ai_observability/evaluation_clustering/constants.pyindex 3d5eff6a4ee0..9568b5536848 100644--- a/posthog/temporal/ai_observability/evaluation_clustering/constants.py+++ b/posthog/temporal/ai_observability/evaluation_clustering/constants.py@@ -61,6 +61,14 @@ AI_OBSERVABILITY_EVALUATION_RENDERING = "detailed"# a read to one job's accumulated embeddings.AI_OBSERVABILITY_EVALUATION_JOB_ID_METADATA_KEY = "job_id"+# Stage A appends the job id to the event uuid in `document_id` (joined by this delimiter) so two+# jobs that sample the same $ai_evaluation event on the same day produce distinct rows. document_id+# is the only non-LowCardinality component of the embeddings ReplacingMergeTree key, so without+# this the rows would share a key and collapse on merge — only one job's metadata.job_id survives+# and the other job silently loses those embeddings. Stage B strips it back to the bare event uuid+# (UUIDs contain no ":", so a single split recovers it) before joining to $ai_evaluation.+AI_OBSERVABILITY_EVALUATION_DOCUMENT_ID_JOB_DELIMITER = "::"+# Embedding model. Eval text representations are short (typically <1000 chars:# evaluator name + one-line description + verdict + reasoning), so the 1536-dim# small model is the default choice over the 3072-dim large model used bydiff --git a/posthog/temporal/ai_observability/evaluation_clustering/data.py b/posthog/temporal/ai_observability/evaluation_clustering/data.pyindex 895486ec2984..695eb70c4f2e 100644--- a/posthog/temporal/ai_observability/evaluation_clustering/data.py+++ b/posthog/temporal/ai_observability/evaluation_clustering/data.py@@ -32,6 +32,7 @@ from posthog.hogql_queries.ai.ai_table_resolver import query_ai_eventsfrom posthog.hogql_queries.ai.trace_id_resolver import resolve_trace_ids_for_generation_uuidsfrom posthog.models.team import Teamfrom posthog.temporal.ai_observability.evaluation_clustering.constants import (+ AI_OBSERVABILITY_EVALUATION_DOCUMENT_ID_JOB_DELIMITER,AI_OBSERVABILITY_EVALUATION_DOCUMENT_TYPE,AI_OBSERVABILITY_EVALUATION_EMBEDDING_MODEL,)@@ -95,6 +96,11 @@ def fetch_evaluation_embeddings(with ``JSONExtractString(metadata, 'job_id')``. Random-order sampling keeps the readsize bounded when a job has accumulated far more than ``max_samples`` over time.+ The returned ``document_id`` is ``{event_uuid}::{job_id}`` for rows Stage A wrote per+ (event, job) — we strip it back to the bare event uuid so the downstream metadata join keys+ on the real ``$ai_evaluation`` uuid. Pre-suffix rows carry a bare uuid and pass through+ unchanged (the split is a no-op).+Transitional dual-match: rows written before the metadata migration carry the job idin ``rendering`` as ``{team_id}_{run_ts}_{job_id}`` (matched by suffix). Both predicatesare OR'd so no in-window embeddings are dropped while old rows age out under the table's@@ -161,12 +167,14 @@ def fetch_evaluation_embeddings()rows = result.results or []- eval_ids: list[str] = []+ # document_id is `{event_uuid}::{job_id}` (or a bare uuid for pre-suffix rows). Strip back to+ # the event uuid; UUIDs contain no ":", so a single split recovers it. Dedupe via the dict in+ # case a transition window briefly holds both a bare and a suffixed row for the same event.embeddings: dict[str, list[float]] = {}for row in rows:- eval_id = row[0]- eval_ids.append(eval_id)+ eval_id = row[0].split(AI_OBSERVABILITY_EVALUATION_DOCUMENT_ID_JOB_DELIMITER, 1)[0]embeddings[eval_id] = row[1]+ eval_ids: list[str] = list(embeddings.keys())logger.info("fetch_evaluation_embeddings_result", job_id=job_id, num_rows=len(rows), team_id=team.id)return eval_ids, embeddingsdiff --git a/posthog/temporal/ai_observability/evaluation_clustering/sampling.py b/posthog/temporal/ai_observability/evaluation_clustering/sampling.pyindex 1fd36eedf7c9..910979388036 100644--- a/posthog/temporal/ai_observability/evaluation_clustering/sampling.py+++ b/posthog/temporal/ai_observability/evaluation_clustering/sampling.py@@ -17,6 +17,7 @@ from posthog.clickhouse.query_tagging import Feature, Product, tags_contextfrom posthog.models.team import Teamfrom posthog.sync import database_sync_to_asyncfrom posthog.temporal.ai_observability.evaluation_clustering.constants import (+ AI_OBSERVABILITY_EVALUATION_DOCUMENT_ID_JOB_DELIMITER,AI_OBSERVABILITY_EVALUATION_DOCUMENT_TYPE,AI_OBSERVABILITY_EVALUATION_EMBEDDING_MODEL,AI_OBSERVABILITY_EVALUATION_JOB_ID_METADATA_KEY,@@ -199,13 +200,17 @@ def _sample_and_embed_sync(inputs: SamplerActivityInputs) -> SamplerActivityResureasoning=row[4],description=descriptions_by_id.get(eval_id),)- # Use the eval event UUID as document_id so repeated runs over the same window- # would land the same row (idempotent at the document level). A collision is fine —- # ClickHouse will just see the same (team_id, product, document_type, document_id)- # tuple with a new timestamp/rendering.+ # Scope document_id per (event, job): the job id is appended to the event uuid so two jobs+ # that sample the same event on the same day don't share a ReplacingMergeTree key and+ # collapse, which would drop a job's embeddings (see the delimiter note in constants).+ # Stage B strips it back to the bare uuid. Still idempotent per job: the same job re-running+ # the same window lands the same row.+ document_id = (+ f"{event_uuid or str(uuid4())}{AI_OBSERVABILITY_EVALUATION_DOCUMENT_ID_JOB_DELIMITER}{inputs.job_id}"+ )embedder.embed_document(content=content,- document_id=event_uuid or str(uuid4()),+ document_id=document_id,document_type=AI_OBSERVABILITY_EVALUATION_DOCUMENT_TYPE,rendering=rendering,product=LLM_TRACES_SUMMARIES_PRODUCT,diff --git a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_data.py b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_data.pyindex 36611b410ea5..6efd32656cf4 100644--- a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_data.py+++ b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_data.py@@ -74,6 +74,34 @@ class TestFetchEvaluationEmbeddings:assert eval_ids == []assert embeddings == {}+ def test_strips_job_suffix_from_document_id(self, mock_team):+ # Stage A writes document_id as `{event_uuid}::{job_id}`; the read must recover the bare+ # event uuid so the downstream metadata join keys on the real $ai_evaluation uuid.+ with patch("posthog.temporal.ai_observability.evaluation_clustering.data.execute_hogql_query") as mock_execute:+ mock_execute.return_value.results = [+ ["event-uuid-1::job-abc", [0.1, 0.2]],+ ["event-uuid-2::job-abc", [0.3, 0.4]],+ ]++ eval_ids, embeddings = fetch_evaluation_embeddings(team=mock_team, job_id="job-abc", max_samples=100)++ assert eval_ids == ["event-uuid-1", "event-uuid-2"]+ assert embeddings == {"event-uuid-1": [0.1, 0.2], "event-uuid-2": [0.3, 0.4]}++ def test_dedupes_bare_and_suffixed_rows_for_same_event(self, mock_team):+ # During the transition a bare-uuid (pre-fix) row and a suffixed row can both match; they+ # strip to the same event uuid and must collapse to one entry.+ with patch("posthog.temporal.ai_observability.evaluation_clustering.data.execute_hogql_query") as mock_execute:+ mock_execute.return_value.results = [+ ["event-uuid-1", [0.1, 0.2]],+ ["event-uuid-1::job-abc", [0.1, 0.2]],+ ]++ eval_ids, embeddings = fetch_evaluation_embeddings(team=mock_team, job_id="job-abc", max_samples=100)++ assert eval_ids == ["event-uuid-1"]+ assert embeddings == {"event-uuid-1": [0.1, 0.2]}+class TestFetchEvaluationMetadata:def test_empty_input_returns_empty(self, mock_team):diff --git a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_sampling.py b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_sampling.pyindex a78d57e34225..344fd5b67f15 100644--- a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_sampling.py+++ b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_sampling.py@@ -148,6 +148,11 @@ class TestSampleAndEmbedForJobActivity:assert kwargs["metadata"] == {"job_id": "job-abc"}assert "Evaluation:" in kwargs["content"]+ # document_id is scoped per (event, job) so two jobs sampling the same event don't collapse+ # to one ReplacingMergeTree row; Stage B strips the suffix back to the event uuid.+ document_ids = [call.kwargs["document_id"] for call in calls]+ assert document_ids == ["uuid-1::job-abc", "uuid-2::job-abc", "uuid-3::job-abc"]+# Third row's N/A verdict is surfaced in the composed textna_content = calls[2].kwargs["content"]assert "Verdict: n/a" in na_content