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.

fix(llma): scope trace clustering embeddings per job in document_id (#63518)

Andrew Maguire2ffa0638658d
diff --git a/posthog/temporal/ai_observability/trace_clustering/data.py b/posthog/temporal/ai_observability/trace_clustering/data.py
index e14d7f6aa02b..d0ee3ae71793 100644
--- a/posthog/temporal/ai_observability/trace_clustering/data.py
+++ b/posthog/temporal/ai_observability/trace_clustering/data.py
@@ -25,6 +25,9 @@ from posthog.temporal.ai_observability.trace_clustering.models import (
ItemId,
ItemSummaries,
)
+from posthog.temporal.ai_observability.trace_summarization.constants import EMBEDDING_DOCUMENT_ID_JOB_DELIMITER
+
+from products.ai_observability.backend.summarization.models import SummarizationMode
logger = structlog.get_logger(__name__)
@@ -48,6 +51,12 @@ def fetch_item_embeddings_for_clustering(
- job_id present: scope to one ClusteringJob via ``metadata.job_id``
- no job_id: return all embeddings for the document type (legacy/unfiltered)
+ Each embedding's ``document_id`` is ``{item_id}::{job_id}`` (Stage A scopes it per job so
+ overlapping jobs don't collapse on the ReplacingMergeTree key — see
+ EMBEDDING_DOCUMENT_ID_JOB_DELIMITER). We strip it back to the bare ``item_id`` here and dedupe,
+ so a trace summarized by several jobs yields one clustering item. Pre-suffix rows carry a bare
+ id and pass through unchanged.
+
The ``batch_run_id`` used to pair each embedding with its summary event now lives in the
embedding's ``metadata`` JSON (read via JSONExtractString); ``rendering`` is just the
summary mode. Transitional fallbacks keep pre-migration rows working: the job filter also
@@ -132,20 +141,22 @@ def fetch_item_embeddings_for_clustering(
embeddings_map: ItemEmbeddings = {}
batch_run_ids_map: ItemBatchRunIds = {}
- # `rendering` values that are NOT batch_run_ids: the current mode enum (post-migration
- # rendering = the summary mode) plus the older legacy render modes. A row whose rendering
- # is one of these and whose metadata lacks a batch_run_id contributes no pairing key, so
- # fetch_item_summaries falls back to accepting any matching summary.
+ # `rendering` values that are NOT batch_run_ids: the current summary-mode enum plus the older
+ # legacy render modes. A row whose rendering is one of these and whose metadata lacks a
+ # batch_run_id contributes no pairing key, so fetch_item_summaries accepts any matching summary.
non_batch_run_id_renderings = {
constants.LLMA_TRACE_RENDERING_LEGACY, # "llma_trace_detailed"
- "llma_trace_minimal", # Other legacy mode
- "detailed", # SummarizationMode.DETAILED — current rendering value
- "minimal", # SummarizationMode.MINIMAL — current rendering value
+ "llma_trace_minimal", # legacy minimal rendering
+ *(mode.value for mode in SummarizationMode), # current rendering values
}
for row in rows:
- item_id = row[0]
- item_ids.append(item_id)
+ # document_id is `{item_id}::{job_id}` (or a bare id for pre-suffix rows). Strip back to the
+ # item id; ids contain no ":", so a single split recovers it. Dedupe so a trace summarized
+ # by multiple jobs (or a bare + suffixed row in transition) yields one clustering item.
+ item_id = row[0].split(EMBEDDING_DOCUMENT_ID_JOB_DELIMITER, 1)[0]
+ if item_id not in embeddings_map:
+ item_ids.append(item_id)
embeddings_map[item_id] = row[1]
# batch_run_id now lives in metadata; prefer it. Pre-migration rows carry it in
diff --git a/posthog/temporal/ai_observability/trace_clustering/tests/test_data.py b/posthog/temporal/ai_observability/trace_clustering/tests/test_data.py
index 28dfa0cc81ff..4fcd485a3144 100644
--- a/posthog/temporal/ai_observability/trace_clustering/tests/test_data.py
+++ b/posthog/temporal/ai_observability/trace_clustering/tests/test_data.py
@@ -137,6 +137,30 @@ class TestFetchItemEmbeddingsForClustering:
assert "document_type_legacy" not in call_kwargs["placeholders"]
assert "rendering_legacy" not in call_kwargs["placeholders"]
+ @patch("posthog.temporal.ai_observability.trace_clustering.data.execute_hogql_query")
+ def test_strips_and_dedupes_job_suffix_from_document_id(self, mock_execute, mock_team):
+ # document_id is `{item_id}::{job_id}`; the read recovers the bare item id and dedupes a
+ # trace summarized by multiple jobs (and a bare pre-suffix row) into one clustering item.
+ mock_result = MagicMock()
+ mock_result.results = [
+ ("trace_1::job-a", [0.1, 0.2], "detailed", "batch_1"),
+ ("trace_1::job-b", [0.1, 0.2], "detailed", "batch_2"),
+ ("trace_2::job-a", [0.3, 0.4], "detailed", "batch_1"),
+ ("trace_3", [0.5, 0.6], "detailed", "batch_1"), # pre-suffix bare id
+ ]
+ mock_execute.return_value = mock_result
+
+ trace_ids, embeddings_map, _batch_run_ids = fetch_item_embeddings_for_clustering(
+ team=mock_team,
+ window_start=datetime(2025, 1, 1, tzinfo=UTC),
+ window_end=datetime(2025, 1, 8, tzinfo=UTC),
+ max_samples=100,
+ job_id="job-a",
+ )
+
+ assert trace_ids == ["trace_1", "trace_2", "trace_3"]
+ assert embeddings_map == {"trace_1": [0.1, 0.2], "trace_2": [0.3, 0.4], "trace_3": [0.5, 0.6]}
+
@patch("posthog.temporal.ai_observability.trace_clustering.data.execute_hogql_query")
def test_returns_empty_when_no_results(self, mock_execute, mock_team):
mock_result = MagicMock()
diff --git a/posthog/temporal/ai_observability/trace_summarization/constants.py b/posthog/temporal/ai_observability/trace_summarization/constants.py
index 7130b5b4eea0..8f22edbc26fa 100644
--- a/posthog/temporal/ai_observability/trace_summarization/constants.py
+++ b/posthog/temporal/ai_observability/trace_summarization/constants.py
@@ -127,6 +127,14 @@ GENERATION_DOCUMENT_TYPE = "llm-generation-summary-detailed" # For generation-l
EMBEDDING_METADATA_BATCH_RUN_ID_KEY = "batch_run_id"
EMBEDDING_METADATA_JOB_ID_KEY = "job_id"
+# The summary embedding's `document_id` is `{item_id}::{job_id}` — the clustering job id is
+# appended to the trace/generation id (joined by this delimiter). `document_id` is the only
+# non-LowCardinality component of the document_embeddings ReplacingMergeTree key, so scoping per
+# job here keeps two jobs that summarize the same item on the same day in distinct rows instead of
+# collapsing them on merge (which would drop a job's embeddings). Stage B strips it back to the
+# bare item id (item ids contain no ":", so a single split recovers it) before pairing summaries.
+EMBEDDING_DOCUMENT_ID_JOB_DELIMITER = "::"
+
# Generation-level configuration
DEFAULT_MAX_GENERATIONS_PER_WINDOW = 20 # Higher than traces - generations are simpler units
diff --git a/posthog/temporal/ai_observability/trace_summarization/summarize_and_save.py b/posthog/temporal/ai_observability/trace_summarization/summarize_and_save.py
index c55e895763c0..80cefb44c4e8 100644
--- a/posthog/temporal/ai_observability/trace_summarization/summarize_and_save.py
+++ b/posthog/temporal/ai_observability/trace_summarization/summarize_and_save.py
@@ -122,6 +122,13 @@ def _embedding_metadata(batch_run_id: str, job_id: str) -> dict[str, str]:
}
+def _embedding_document_id(item_id: str, job_id: str) -> str:
+ """Scope the embedding's `document_id` per (item, job) so overlapping jobs don't collapse on
+ the document_embeddings ReplacingMergeTree key — see EMBEDDING_DOCUMENT_ID_JOB_DELIMITER.
+ """
+ return f"{item_id}{constants.EMBEDDING_DOCUMENT_ID_JOB_DELIMITER}{job_id}"
+
+
def _embed_trace_summary(
summary_result: SummarizationResponse,
trace_id: str,
@@ -136,7 +143,7 @@ def _embed_trace_summary(
embedder = LLMTracesSummarizerEmbedder(team=team)
embedder.embed_document(
content=summary_text,
- document_id=trace_id,
+ document_id=_embedding_document_id(trace_id, job_id),
document_type=document_type_with_mode,
rendering=mode,
product=LLM_TRACES_SUMMARIES_PRODUCT,
@@ -157,7 +164,7 @@ def _embed_generation_summary(
embedder = LLMTracesSummarizerEmbedder(team=team)
embedder.embed_document(
content=summary_text,
- document_id=generation_id,
+ document_id=_embedding_document_id(generation_id, job_id),
document_type=constants.GENERATION_DOCUMENT_TYPE,
rendering=mode,
product="llm-analytics",
diff --git a/posthog/temporal/ai_observability/trace_summarization/tests/test_summarize_and_save.py b/posthog/temporal/ai_observability/trace_summarization/tests/test_summarize_and_save.py
index dc117a9b8da2..5bb0805152a7 100644
--- a/posthog/temporal/ai_observability/trace_summarization/tests/test_summarize_and_save.py
+++ b/posthog/temporal/ai_observability/trace_summarization/tests/test_summarize_and_save.py
@@ -114,13 +114,15 @@ class TestSummarizeAndSaveActivity:
assert call_kwargs["properties"]["$ai_clustering_job_name"] == input_data.job_name
mock_delete.assert_called_once()
- # rendering stays the low-cardinality mode enum; batch_run_id + job_id live in metadata
+ # rendering stays the low-cardinality mode enum; batch_run_id + job_id live in metadata,
+ # and document_id is scoped per (item, job) so overlapping jobs don't collapse on the RMT key
embed_kwargs = mock_embedder_class.return_value.embed_document.call_args.kwargs
assert embed_kwargs["rendering"] == input_data.mode
assert embed_kwargs["metadata"] == {
"batch_run_id": input_data.batch_run_id,
"job_id": input_data.job_id,
}
+ assert embed_kwargs["document_id"] == f"{input_data.trace_id}::{input_data.job_id}"
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
@@ -143,7 +145,7 @@ class TestSummarizeAndSaveActivity:
) as mock_create_event,
patch(
"posthog.temporal.ai_observability.trace_summarization.summarize_and_save.LLMTracesSummarizerEmbedder"
- ),
+ ) as mock_embedder_class,
):
mock_load.return_value = "generation text repr"
mock_summarize.return_value = mock_summary
@@ -159,6 +161,16 @@ class TestSummarizeAndSaveActivity:
assert call_kwargs["properties"]["$ai_clustering_job_id"] == input_data.job_id
assert call_kwargs["properties"]["$ai_clustering_job_name"] == input_data.job_name
+ # rendering stays the low-cardinality mode enum; ids live in metadata; document_id is
+ # scoped per (generation, job) so overlapping jobs don't collapse on the RMT key
+ embed_kwargs = mock_embedder_class.return_value.embed_document.call_args.kwargs
+ assert embed_kwargs["rendering"] == input_data.mode
+ assert embed_kwargs["metadata"] == {
+ "batch_run_id": input_data.batch_run_id,
+ "job_id": input_data.job_id,
+ }
+ assert embed_kwargs["document_id"] == f"{generation_id}::{input_data.job_id}"
+
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_embedding_failure_captured_not_fatal(self, mock_team):