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): make clustering embedding rendering a fixed enum, ids to metadata (#63493)

Andrew Maguire12e673451a78
diff --git a/ee/hogai/llm_traces_summaries/tools/embed_summaries.py b/ee/hogai/llm_traces_summaries/tools/embed_summaries.py
index f2da55bb566e..bc05aa1a6e4f 100644
--- a/ee/hogai/llm_traces_summaries/tools/embed_summaries.py
+++ b/ee/hogai/llm_traces_summaries/tools/embed_summaries.py
@@ -98,7 +98,13 @@ class LLMTracesSummarizerEmbedder:
return result[0][0] > 0
def embed_document(
- self, content: str, document_id: str, document_type: str, rendering: str, product: str
+ self,
+ content: str,
+ document_id: str,
+ document_type: str,
+ rendering: str,
+ product: str,
+ metadata: dict | None = None,
) -> datetime:
timestamp = timezone.now()
payload = {
@@ -109,6 +115,7 @@ class LLMTracesSummarizerEmbedder:
"document_id": document_id,
"timestamp": timestamp.isoformat(),
"content": content,
+ "metadata": metadata or {},
"models": [self._embedding_model_name.value],
}
self._producer.produce(topic=DOCUMENT_EMBEDDINGS_TOPIC, data=payload)
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/constants.py b/posthog/temporal/ai_observability/evaluation_clustering/constants.py
index 28a43998b22b..bb40e1e661c7 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/constants.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/constants.py
@@ -51,6 +51,16 @@ CLUSTERING_CHILD_WORKFLOW_ID_PREFIX = "llma-evaluation-clustering-team"
AI_OBSERVABILITY_EVALUATION_DOCUMENT_TYPE = "llm-evaluation-detailed"
AI_OBSERVABILITY_EVALUATION_PRODUCT = "llm-analytics"
+# Fixed low-cardinality `rendering` value for eval embeddings. `rendering` is a
+# LowCardinality(String) column AND part of the document_embeddings sorting key, so it must
+# stay a small enum (the render mode) — never a per-run unique string. Job scoping lives in
+# the embedding `metadata` JSON (`{"job_id": ...}`) and is read back via JSONExtractString.
+AI_OBSERVABILITY_EVALUATION_RENDERING = "detailed"
+
+# Metadata key carrying the ClusteringJob id on each eval embedding, used by Stage B to scope
+# a read to one job's accumulated embeddings.
+AI_OBSERVABILITY_EVALUATION_JOB_ID_METADATA_KEY = "job_id"
+
# 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 by
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/data.py b/posthog/temporal/ai_observability/evaluation_clustering/data.py
index 5e632719f038..9515148a7f8e 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/data.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/data.py
@@ -3,8 +3,9 @@
Two queries:
- ``fetch_evaluation_embeddings`` — pulls accumulated eval embeddings for a job
- via ``endsWith(rendering, '_{job_id}')``, matching the Stage A rendering
- convention ``eval_{job_id}``.
+ via ``JSONExtractString(metadata, 'job_id')``, matching the Stage A metadata
+ convention ``{"job_id": ...}`` (with a transitional suffix match on legacy
+ ``rendering`` values — see the function docstring).
- ``fetch_evaluation_metadata`` — joins the sampled $ai_evaluation rows to their
target $ai_generation (via $ai_target_event_id) to surface both
eval-specific metadata (name/result/runtime/reasoning/judge_cost) and
@@ -90,9 +91,14 @@ def fetch_evaluation_embeddings(
) -> tuple[list[str], dict[str, list[float]]]:
"""Read up to max_samples eval embeddings accumulated by Stage A for this job.
- Stage A tags rows with ``rendering = eval_{job_id}``; we match by suffix so rows
- from the older ``{team_id}_{run_ts}_{job_id}`` format keep resolving. Random-order
- sampling bounds the read when a job has accumulated more than ``max_samples``.
+ Stage A scopes each embedding to its job via ``metadata.job_id``; we read that back
+ with ``JSONExtractString(metadata, 'job_id')``. Random-order sampling keeps the read
+ size bounded when a job has accumulated far more than ``max_samples`` over time.
+
+ Transitional dual-match: rows written before the metadata migration carry the job id
+ in ``rendering`` as ``{team_id}_{run_ts}_{job_id}`` (matched by suffix). Both predicates
+ are OR'd so no in-window embeddings are dropped while old rows age out under the table's
+ 3-month TTL. Drop the ``endsWith(rendering, ...)`` arm once that TTL has fully elapsed.
``window_start``/``window_end`` must align with the Stage B metadata lookup
window — otherwise the random sample can return older eval ids that the
@@ -112,7 +118,7 @@ def fetch_evaluation_embeddings(
FROM raw_document_embeddings
WHERE document_type = {document_type}
AND model_name = {model_name}
- AND endsWith(rendering, {job_id_suffix})
+ AND (JSONExtractString(metadata, 'job_id') = {job_id} OR endsWith(rendering, {job_id_suffix}))
AND length(embedding) > 0
AND timestamp >= {start_dt}
AND timestamp < {end_dt}
@@ -127,7 +133,7 @@ def fetch_evaluation_embeddings(
FROM raw_document_embeddings
WHERE document_type = {document_type}
AND model_name = {model_name}
- AND endsWith(rendering, {job_id_suffix})
+ AND (JSONExtractString(metadata, 'job_id') = {job_id} OR endsWith(rendering, {job_id_suffix}))
AND length(embedding) > 0
ORDER BY rand()
LIMIT {max_samples}
@@ -137,6 +143,7 @@ def fetch_evaluation_embeddings(
placeholders: dict[str, ast.Expr] = {
"document_type": ast.Constant(value=AI_OBSERVABILITY_EVALUATION_DOCUMENT_TYPE),
"model_name": ast.Constant(value=AI_OBSERVABILITY_EVALUATION_EMBEDDING_MODEL),
+ "job_id": ast.Constant(value=job_id),
"job_id_suffix": ast.Constant(value=f"_{job_id}"),
"max_samples": ast.Constant(value=max_samples),
}
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/sampling.py b/posthog/temporal/ai_observability/evaluation_clustering/sampling.py
index 0fd8f2518a14..1fd36eedf7c9 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/sampling.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/sampling.py
@@ -19,6 +19,8 @@ from posthog.sync import database_sync_to_async
from posthog.temporal.ai_observability.evaluation_clustering.constants import (
AI_OBSERVABILITY_EVALUATION_DOCUMENT_TYPE,
AI_OBSERVABILITY_EVALUATION_EMBEDDING_MODEL,
+ AI_OBSERVABILITY_EVALUATION_JOB_ID_METADATA_KEY,
+ AI_OBSERVABILITY_EVALUATION_RENDERING,
)
from posthog.temporal.ai_observability.evaluation_clustering.models import SamplerActivityInputs, SamplerActivityResult
from posthog.temporal.common.heartbeat import Heartbeater
@@ -163,10 +165,11 @@ def _sample_and_embed_sync(inputs: SamplerActivityInputs) -> SamplerActivityResu
)
return SamplerActivityResult(team_id=team.id, job_id=inputs.job_id, sampled=0, embedded=0)
- # `rendering` is LowCardinality and in the sorting key, so keep it low cardinality:
- # one stable value per job, not a fresh one per run. Stage B scopes by the
- # '_{job_id}' suffix, which also matches rows written in the older format.
- rendering = f"eval_{inputs.job_id}"
+ # `rendering` stays a fixed low-cardinality enum (the render mode). The job id that scopes
+ # Stage B's read is carried in the embedding `metadata` instead — see the column-cardinality
+ # note on AI_OBSERVABILITY_EVALUATION_RENDERING.
+ rendering = AI_OBSERVABILITY_EVALUATION_RENDERING
+ metadata = {AI_OBSERVABILITY_EVALUATION_JOB_ID_METADATA_KEY: inputs.job_id}
# Use the small (1536-dim) model — see AI_OBSERVABILITY_EVALUATION_EMBEDDING_MODEL in constants.py.
# The lazy import keeps EmbeddingModelName out of the module top-level (avoids pulling
# posthog.schema into the workflow-side graph via the activity module).
@@ -206,6 +209,7 @@ def _sample_and_embed_sync(inputs: SamplerActivityInputs) -> SamplerActivityResu
document_type=AI_OBSERVABILITY_EVALUATION_DOCUMENT_TYPE,
rendering=rendering,
product=LLM_TRACES_SUMMARIES_PRODUCT,
+ metadata=metadata,
)
embedded += 1
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_sampling.py b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_sampling.py
index f1008b56a07e..a78d57e34225 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_sampling.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_sampling.py
@@ -7,7 +7,10 @@ from unittest.mock import MagicMock, patch
from parameterized import parameterized
-from posthog.temporal.ai_observability.evaluation_clustering.constants import AI_OBSERVABILITY_EVALUATION_DOCUMENT_TYPE
+from posthog.temporal.ai_observability.evaluation_clustering.constants import (
+ AI_OBSERVABILITY_EVALUATION_DOCUMENT_TYPE,
+ AI_OBSERVABILITY_EVALUATION_RENDERING,
+)
from posthog.temporal.ai_observability.evaluation_clustering.models import SamplerActivityInputs
from posthog.temporal.ai_observability.evaluation_clustering.sampling import (
_compose_evaluation_text,
@@ -134,14 +137,15 @@ class TestSampleAndEmbedForJobActivity:
assert result.team_id == mock_team.id
assert result.job_id == "job-abc"
- # Every call used the eval document type and the low-cardinality job rendering
- expected_rendering = "eval_job-abc"
+ # Every call used the eval document type, the fixed low-cardinality rendering enum,
+ # and carried the job id in metadata (not in rendering) for Stage B to scope on.
calls = mock_embedder.embed_document.call_args_list
assert len(calls) == 3
for call in calls:
kwargs = call.kwargs
assert kwargs["document_type"] == AI_OBSERVABILITY_EVALUATION_DOCUMENT_TYPE
- assert kwargs["rendering"] == expected_rendering
+ assert kwargs["rendering"] == AI_OBSERVABILITY_EVALUATION_RENDERING
+ assert kwargs["metadata"] == {"job_id": "job-abc"}
assert "Evaluation:" in kwargs["content"]
# Third row's N/A verdict is surfaced in the composed text
diff --git a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_workflow.py b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_workflow.py
index 43d21b0ce8b6..ec98eeffdecf 100644
--- a/posthog/temporal/ai_observability/evaluation_clustering/tests/test_workflow.py
+++ b/posthog/temporal/ai_observability/evaluation_clustering/tests/test_workflow.py
@@ -125,9 +125,9 @@ class TestSamplerWorkflowWindowMath:
window_end = workflow.now() - SAMPLER_WINDOW_OFFSET_MINUTES
window_start = window_end - SAMPLER_WINDOW_MINUTES
- Asserts the start↔end span against the window constant so the wiring is
- verified independent of wall-clock time (the offset math is pinned by
- TestWindowMathFormula).
+ Asserts the derived window spans exactly SAMPLER_WINDOW_MINUTES; the absolute offset
+ from workflow.now() is pinned separately by TestWindowMathFormula. (Independent of
+ wall-clock because it only checks the span between the two derived bounds.)
"""
inputs = SamplerWorkflowInputs(team_id=7, job_id="j-derived", job_name="derived window")
diff --git a/posthog/temporal/ai_observability/trace_clustering/data.py b/posthog/temporal/ai_observability/trace_clustering/data.py
index 33c49f1ca9cc..e14d7f6aa02b 100644
--- a/posthog/temporal/ai_observability/trace_clustering/data.py
+++ b/posthog/temporal/ai_observability/trace_clustering/data.py
@@ -45,8 +45,15 @@ def fetch_item_embeddings_for_clustering(
"""Query item IDs and embeddings from document_embeddings table.
Two paths:
- - job_id present: filter by rendering suffix (batch_run_id = {team}_{ts}_{job_id})
+ - job_id present: scope to one ClusteringJob via ``metadata.job_id``
- no job_id: return all embeddings for the document type (legacy/unfiltered)
+
+ 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
+ suffix-matches the legacy ``rendering = {team}_{ts}_{job_id}`` form, and the batch_run_id
+ falls back to ``rendering`` when ``metadata.batch_run_id`` is absent. Both fallbacks can be
+ dropped once the table's 3-month TTL has cycled out all pre-migration rows.
"""
document_type = (
constants.LLMA_GENERATION_DOCUMENT_TYPE
@@ -57,14 +64,14 @@ def fetch_item_embeddings_for_clustering(
if job_id:
query = parse_select(
"""
- SELECT document_id, embedding, rendering
+ SELECT document_id, embedding, rendering, JSONExtractString(metadata, 'batch_run_id') AS meta_batch_run_id
FROM raw_document_embeddings
WHERE timestamp >= {start_dt}
AND timestamp < {end_dt}
AND product = {product}
AND document_type = {document_type}
AND length(embedding) > 0
- AND endsWith(rendering, {job_id_suffix})
+ AND (JSONExtractString(metadata, 'job_id') = {job_id} OR endsWith(rendering, {job_id_suffix}))
ORDER BY rand()
LIMIT {max_samples}
"""
@@ -72,7 +79,7 @@ def fetch_item_embeddings_for_clustering(
else:
query = parse_select(
"""
- SELECT document_id, embedding, rendering
+ SELECT document_id, embedding, rendering, JSONExtractString(metadata, 'batch_run_id') AS meta_batch_run_id
FROM raw_document_embeddings
WHERE timestamp >= {start_dt}
AND timestamp < {end_dt}
@@ -96,6 +103,7 @@ def fetch_item_embeddings_for_clustering(
}
if job_id:
+ placeholders["job_id"] = ast.Constant(value=job_id)
placeholders["job_id_suffix"] = ast.Constant(value=f"_{job_id}")
else:
placeholders["document_type_legacy"] = ast.Constant(value=constants.LLMA_TRACE_DOCUMENT_TYPE_LEGACY)
@@ -124,10 +132,15 @@ def fetch_item_embeddings_for_clustering(
embeddings_map: ItemEmbeddings = {}
batch_run_ids_map: ItemBatchRunIds = {}
- # Legacy rendering values that are NOT batch_run_ids
- legacy_rendering_values = {
+ # `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.
+ 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
}
for row in rows:
@@ -135,11 +148,14 @@ def fetch_item_embeddings_for_clustering(
item_ids.append(item_id)
embeddings_map[item_id] = row[1]
- # Only store as batch_run_id if it's not a legacy rendering constant
- # Legacy embeddings have rendering like "llma_trace_detailed"
- # New embeddings have rendering = batch_run_id (e.g., "1_2025-12-13T...")
+ # batch_run_id now lives in metadata; prefer it. Pre-migration rows carry it in
+ # `rendering` instead (rendering = batch_run_id, e.g. "1_2025-12-13T..._job"), so fall
+ # back to rendering when it isn't one of the known mode values.
rendering_value = row[2]
- if rendering_value and rendering_value not in legacy_rendering_values:
+ meta_batch_run_id = row[3]
+ if meta_batch_run_id:
+ batch_run_ids_map[item_id] = meta_batch_run_id
+ elif rendering_value and rendering_value not in non_batch_run_id_renderings:
batch_run_ids_map[item_id] = rendering_value
return item_ids, embeddings_map, batch_run_ids_map
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 f3da795f03e2..28dfa0cc81ff 100644
--- a/posthog/temporal/ai_observability/trace_clustering/tests/test_data.py
+++ b/posthog/temporal/ai_observability/trace_clustering/tests/test_data.py
@@ -28,10 +28,12 @@ def mock_team(db):
class TestFetchItemEmbeddingsForClustering:
@patch("posthog.temporal.ai_observability.trace_clustering.data.execute_hogql_query")
def test_returns_correct_structure(self, mock_execute, mock_team):
+ # Row shape: (document_id, embedding, rendering, meta_batch_run_id). Post-migration
+ # rendering is the summary mode and batch_run_id is read from metadata (column 4).
mock_result = MagicMock()
mock_result.results = [
- ("trace_1", [0.1, 0.2, 0.3], "batch_run_123"),
- ("trace_2", [0.4, 0.5, 0.6], "batch_run_123"),
+ ("trace_1", [0.1, 0.2, 0.3], "detailed", "batch_run_123"),
+ ("trace_2", [0.4, 0.5, 0.6], "detailed", "batch_run_123"),
]
mock_execute.return_value = mock_result
@@ -52,12 +54,33 @@ class TestFetchItemEmbeddingsForClustering:
"trace_2": "batch_run_123",
}
+ @patch("posthog.temporal.ai_observability.trace_clustering.data.execute_hogql_query")
+ def test_legacy_rows_fall_back_to_rendering_for_batch_run_id(self, mock_execute, mock_team):
+ # Pre-migration rows have empty metadata and carry the batch_run_id in `rendering`.
+ mock_result = MagicMock()
+ mock_result.results = [
+ ("trace_1", [0.1, 0.2], "1_2025-01-01T00:00:00_abc", ""),
+ ]
+ 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,
+ )
+
+ assert batch_run_ids == {"trace_1": "1_2025-01-01T00:00:00_abc"}
+
@patch("posthog.temporal.ai_observability.trace_clustering.data.execute_hogql_query")
def test_handles_legacy_rendering_values(self, mock_execute, mock_team):
+ # Mode-only renderings (legacy or current) with no metadata batch_run_id contribute no
+ # pairing key, so fetch_item_summaries falls back to accepting any matching summary.
mock_result = MagicMock()
mock_result.results = [
- ("trace_1", [0.1, 0.2], "llma_trace_detailed"),
- ("trace_2", [0.3, 0.4], "llma_trace_minimal"),
+ ("trace_1", [0.1, 0.2], "llma_trace_detailed", ""),
+ ("trace_2", [0.3, 0.4], "llma_trace_minimal", ""),
+ ("trace_3", [0.5, 0.6], "detailed", ""),
]
mock_execute.return_value = mock_result
@@ -68,14 +91,14 @@ class TestFetchItemEmbeddingsForClustering:
max_samples=100,
)
- # Legacy rendering values should NOT be stored as batch_run_ids
+ # Mode-only rendering values should NOT be stored as batch_run_ids
assert batch_run_ids == {}
- assert trace_ids == ["trace_1", "trace_2"]
+ assert trace_ids == ["trace_1", "trace_2", "trace_3"]
@patch("posthog.temporal.ai_observability.trace_clustering.data.execute_hogql_query")
def test_no_job_id_uses_legacy_query_with_document_type_fallback(self, mock_execute, mock_team):
mock_result = MagicMock()
- mock_result.results = [("trace_1", [0.1, 0.2], "batch_123")]
+ mock_result.results = [("trace_1", [0.1, 0.2], "detailed", "batch_123")]
mock_execute.return_value = mock_result
fetch_item_embeddings_for_clustering(
@@ -91,10 +114,10 @@ class TestFetchItemEmbeddingsForClustering:
assert "job_id_suffix" not in call_kwargs["placeholders"]
@patch("posthog.temporal.ai_observability.trace_clustering.data.execute_hogql_query")
- def test_job_id_filters_by_rendering_suffix(self, mock_execute, mock_team):
+ def test_job_id_filters_by_metadata_with_rendering_fallback(self, mock_execute, mock_team):
mock_result = MagicMock()
mock_result.results = [
- ("trace_1", [0.1, 0.2], "2_2025-01-01T00:00:00_abc-123"),
+ ("trace_1", [0.1, 0.2], "detailed", "2_abc-123"),
]
mock_execute.return_value = mock_result
@@ -107,6 +130,8 @@ class TestFetchItemEmbeddingsForClustering:
)
call_kwargs = mock_execute.call_args.kwargs
+ # job scoping reads metadata.job_id, with a transitional suffix match on legacy rendering
+ assert call_kwargs["placeholders"]["job_id"].value == "abc-123"
assert call_kwargs["placeholders"]["job_id_suffix"].value == "_abc-123"
# job_id path should not include legacy fallback placeholders
assert "document_type_legacy" not in call_kwargs["placeholders"]
@@ -134,7 +159,7 @@ class TestFetchItemEmbeddingsForClustering:
def test_single_query_for_all_cases(self, mock_execute, mock_team):
"""Both job_id and no-job_id paths use a single execute_hogql_query call."""
mock_result = MagicMock()
- mock_result.results = [("id_1", [0.1], "batch_1")]
+ mock_result.results = [("id_1", [0.1], "detailed", "batch_1")]
mock_execute.return_value = mock_result
fetch_item_embeddings_for_clustering(
diff --git a/posthog/temporal/ai_observability/trace_summarization/constants.py b/posthog/temporal/ai_observability/trace_summarization/constants.py
index 52dbc01fd2bd..7130b5b4eea0 100644
--- a/posthog/temporal/ai_observability/trace_summarization/constants.py
+++ b/posthog/temporal/ai_observability/trace_summarization/constants.py
@@ -119,6 +119,14 @@ EVENT_NAME_GENERATION_SUMMARY = "$ai_generation_summary" # For generation-level
# Document types for embeddings
GENERATION_DOCUMENT_TYPE = "llm-generation-summary-detailed" # For generation-level embeddings
+# Keys under which the summary embedding's `metadata` JSON carries the ids needed to stitch
+# clustering data back together. `rendering` stays a fixed low-cardinality enum (the summary
+# mode); these ids live in `metadata` instead and are read back via JSONExtractString in
+# trace_clustering/data.py. `batch_run_id` pairs an embedding to its summary event
+# ($ai_batch_run_id); `job_id` scopes a clustering read to one ClusteringJob.
+EMBEDDING_METADATA_BATCH_RUN_ID_KEY = "batch_run_id"
+EMBEDDING_METADATA_JOB_ID_KEY = "job_id"
+
# 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 2b23bd9649c9..c55e895763c0 100644
--- a/posthog/temporal/ai_observability/trace_summarization/summarize_and_save.py
+++ b/posthog/temporal/ai_observability/trace_summarization/summarize_and_save.py
@@ -110,11 +110,24 @@ def _save_generation_summary_event(
)
+def _embedding_metadata(batch_run_id: str, job_id: str) -> dict[str, str]:
+ """Ids carried in the embedding's `metadata` JSON so `rendering` can stay a fixed enum.
+
+ `batch_run_id` pairs the embedding to its summary event ($ai_batch_run_id); `job_id`
+ scopes a clustering read to one ClusteringJob (read back via JSONExtractString).
+ """
+ return {
+ constants.EMBEDDING_METADATA_BATCH_RUN_ID_KEY: batch_run_id,
+ constants.EMBEDDING_METADATA_JOB_ID_KEY: job_id,
+ }
+
+
def _embed_trace_summary(
summary_result: SummarizationResponse,
trace_id: str,
mode: str,
batch_run_id: str,
+ job_id: str,
team: Team,
) -> None:
summary_text = _format_summary_for_embedding(summary_result)
@@ -125,15 +138,18 @@ def _embed_trace_summary(
content=summary_text,
document_id=trace_id,
document_type=document_type_with_mode,
- rendering=batch_run_id,
+ rendering=mode,
product=LLM_TRACES_SUMMARIES_PRODUCT,
+ metadata=_embedding_metadata(batch_run_id, job_id),
)
def _embed_generation_summary(
summary_result: SummarizationResponse,
generation_id: str,
+ mode: str,
batch_run_id: str,
+ job_id: str,
team: Team,
) -> None:
summary_text = _format_summary_for_embedding(summary_result)
@@ -143,8 +159,9 @@ def _embed_generation_summary(
content=summary_text,
document_id=generation_id,
document_type=constants.GENERATION_DOCUMENT_TYPE,
- rendering=batch_run_id,
+ rendering=mode,
product="llm-analytics",
+ metadata=_embedding_metadata(batch_run_id, job_id),
)
@@ -232,11 +249,11 @@ async def summarize_and_save_activity(input: SummarizeAndSaveInput) -> Summariza
if is_generation:
assert input.generation_id is not None
await database_sync_to_async(_embed_generation_summary, thread_sensitive=False)(
- summary_result, input.generation_id, input.batch_run_id, team
+ summary_result, input.generation_id, input.mode, input.batch_run_id, input.job_id, team
)
else:
await database_sync_to_async(_embed_trace_summary, thread_sensitive=False)(
- summary_result, input.trace_id, input.mode, input.batch_run_id, team
+ summary_result, input.trace_id, input.mode, input.batch_run_id, input.job_id, team
)
embedding_requested = True
except Exception as e:
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 75c55ab1938d..dc117a9b8da2 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
@@ -95,7 +95,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 = "text_repr content"
mock_summarize.return_value = mock_summary
@@ -114,6 +114,14 @@ 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
+ 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,
+ }
+
@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_generation_summary_success(self, mock_team):