: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(aio): send oversized eval and tagger events by reference (#111697)
Alessandro Pogliaghi483dd61e829c
diff --git a/nodejs/src/ai-observability/services/temporal.service.test.ts b/nodejs/src/ai-observability/services/temporal.service.test.tsindex 314c5240c5f9..d089b7960aeb 100644--- a/nodejs/src/ai-observability/services/temporal.service.test.ts+++ b/nodejs/src/ai-observability/services/temporal.service.test.ts@@ -3,7 +3,7 @@ import { Client, Connection, WorkflowExecutionAlreadyStartedError } from '@tempoimport { EncryptionCodec } from '~/common/temporal/codec'import { RawKafkaEvent } from '~/types'-import { TemporalService, resolveSettleConfig, workflowSafeId } from './temporal.service'+import { EVENT_REFERENCE_START_DELAY, TemporalService, resolveSettleConfig, workflowSafeId } from './temporal.service'import type { EvaluationWorkflowRuntime, TemporalServiceConfig } from './temporal.service'jest.mock('@temporalio/client')@@ -236,6 +236,50 @@ describe('TemporalService', () => {})})+ it.each([+ [+ 'run-evaluation',+ (event: RawKafkaEvent) => service.startEvaluationRunWorkflow('eval-123', event, 'llm_judge'),+ ],+ ['run-tagger', (event: RawKafkaEvent) => service.startTaggerRunWorkflow('tagger-123', event)],+ ])(+ 'starts %s with a delayed reference when the worker would encode the event over the payload limit',+ async (workflow, start) => {+ const oversizedOutput = 'é'.repeat(300_000)+ const events = [+ createMockEvent({+ properties: JSON.stringify({ $ai_trace_id: 'trace-1', $ai_output: oversizedOutput }),+ }),+ createMockEvent({+ properties: JSON.stringify({ $ai_trace_id: 12345, $ai_output: oversizedOutput }),+ }),+ createMockEvent({ properties: JSON.stringify({ $ai_trace_id: 'é'.repeat(300_000) }) }),+ ]+ const sameLengthAscii = createMockEvent({+ properties: JSON.stringify({ $ai_trace_id: 'trace-1', $ai_output: 'e'.repeat(300_000) }),+ })++ for (const event of [...events, sameLengthAscii]) {+ await start(event)+ }++ const calls = (mockClient.workflow.start as jest.Mock).mock.calls+ const reference = {+ uuid: 'event-456',+ team_id: 1,+ timestamp: '2024-01-01T00:00:00Z',+ awaiting_ingestion: true,+ }+ ;['trace-1', '12345', null].forEach((traceId, i) => {+ expect(calls[i][0]).toBe(workflow)+ expect(calls[i][1]).toEqual(expect.objectContaining({ startDelay: EVENT_REFERENCE_START_DELAY }))+ expect(calls[i][1].args[0].event_data).toEqual({ ...reference, trace_id: traceId })+ })+ expect(calls[3][1].args[0].event_data).toBe(sameLengthAscii)+ expect(calls[3][1]).not.toHaveProperty('startDelay')+ }+ )+it('generates deterministic tagger workflow IDs', async () => {const mockEvent = createMockEvent()diff --git a/nodejs/src/ai-observability/services/temporal.service.ts b/nodejs/src/ai-observability/services/temporal.service.tsindex 25d3a3d35516..b2db111d5b14 100644--- a/nodejs/src/ai-observability/services/temporal.service.ts+++ b/nodejs/src/ai-observability/services/temporal.service.ts@@ -5,6 +5,7 @@ import {TLSConfig,WorkflowExecutionAlreadyStartedError,WorkflowHandle,+ WorkflowStartOptions,} from '@temporalio/client'import * as crypto from 'crypto'import fs from 'fs/promises'@@ -12,6 +13,7 @@ import { Counter } from 'prom-client'import { EncryptionCodec } from '~/common/temporal/codec'import { isDevEnv } from '~/common/utils/env-utils'+import { parseJSON } from '~/common/utils/json-parse'import { logger } from '~/common/utils/logger'import { RawKafkaEvent } from '../../types'@@ -32,6 +34,75 @@ export type TemporalServiceConfig = Pick<const EVALUATION_TASK_QUEUE = isDevEnv() ? 'development-task-queue' : 'llm-analytics-evals-task-queue'+export const EVENT_REFERENCE_THRESHOLD_BYTES = 1024 * 1024++export const EVENT_REFERENCE_START_DELAY = '30 seconds'++export interface EventReference {+ uuid: string+ team_id: number+ timestamp: string+ trace_id: string | null+ awaiting_ingestion: true+}++export type WorkflowEventPayload = 'inline' | 'reference'++export interface WorkflowEventStart {+ eventData: RawKafkaEvent | EventReference+ payload: WorkflowEventPayload+ startOptions: Pick<WorkflowStartOptions, 'startDelay'>+}++export function asciiEscapedJsonSize(value: unknown): number {+ const json = JSON.stringify(value)+ let size = json.length+ for (let i = 0; i < json.length; i++) {+ if (json.charCodeAt(i) > 0x7f) {+ size += 5+ }+ }+ return size+}++function readTraceId(event: RawKafkaEvent): string | null {+ let traceId: unknown+ try {+ traceId = parseJSON(event.properties ?? '{}')?.$ai_trace_id+ } catch {+ return null+ }+ if (typeof traceId === 'number' && Number.isFinite(traceId)) {+ return String(traceId)+ }+ return typeof traceId === 'string' && traceId !== '' ? traceId : null+}++function toEventReference(event: RawKafkaEvent): EventReference {+ const reference: EventReference = {+ uuid: event.uuid,+ team_id: event.team_id,+ timestamp: event.timestamp,+ trace_id: readTraceId(event),+ awaiting_ingestion: true,+ }+ if (asciiEscapedJsonSize(reference) > EVENT_REFERENCE_THRESHOLD_BYTES) {+ return { ...reference, trace_id: null }+ }+ return reference+}++export function toWorkflowEventStart(event: RawKafkaEvent): WorkflowEventStart {+ if (asciiEscapedJsonSize(event) <= EVENT_REFERENCE_THRESHOLD_BYTES) {+ return { eventData: event, payload: 'inline', startOptions: {} }+ }+ return {+ eventData: toEventReference(event),+ payload: 'reference',+ startOptions: { startDelay: EVENT_REFERENCE_START_DELAY },+ }+}+const EVALUATION_WORKFLOW_PREFIXES = {hog: 'llma-hog-eval',llm_judge: 'llma-llm-eval',@@ -97,7 +168,7 @@ export function resolveSettleConfig(const temporalWorkflowsStarted = new Counter({name: 'evaluation_run_workflows_started',help: 'Number of evaluation run workflows started',- labelNames: ['status'],+ labelNames: ['status', 'payload'],})export interface AggregateEvaluationStart {@@ -233,12 +304,14 @@ export class TemporalService {}const prefix = getEvaluationWorkflowPrefix(evaluationRuntime)const workflowId = `${prefix}-${evaluationId}-${event.uuid}-ingestion`+ const { eventData, payload, startOptions } = toWorkflowEventStart(event)const handle = await client.workflow.start('run-evaluation', {+ ...startOptions,args: [{evaluation_id: evaluationId,- event_data: event,+ event_data: eventData,},],taskQueue: EVALUATION_TASK_QUEUE,@@ -248,7 +321,7 @@ export class TemporalService {workflowTaskTimeout: '2 minutes',})- temporalWorkflowsStarted.labels({ status: 'success' }).inc()+ temporalWorkflowsStarted.labels({ status: 'success', payload }).inc()logger.debug('Started evaluation run workflow', {workflowId,@@ -304,7 +377,7 @@ export class TemporalService {workflowTaskTimeout: '2 minutes',})- temporalWorkflowsStarted.labels({ status: 'success' }).inc()+ temporalWorkflowsStarted.labels({ status: 'success', payload: 'none' }).inc()logger.debug('Started aggregate evaluation workflow', {workflowId,@@ -319,7 +392,7 @@ export class TemporalService {return handle} catch (error) {if (error instanceof WorkflowExecutionAlreadyStartedError) {- temporalWorkflowsStarted.labels({ status: 'already_completed' }).inc()+ temporalWorkflowsStarted.labels({ status: 'already_completed', payload: 'none' }).inc()return null}throw error@@ -330,12 +403,14 @@ export class TemporalService {const client = await this.ensureConnected()const workflowId = `llma-tagger-${taggerId}-${event.uuid}-ingestion`+ const { eventData, payload, startOptions } = toWorkflowEventStart(event)const handle = await client.workflow.start('run-tagger', {+ ...startOptions,args: [{tagger_id: taggerId,- event_data: event,+ event_data: eventData,},],taskQueue: EVALUATION_TASK_QUEUE,@@ -345,7 +420,7 @@ export class TemporalService {workflowTaskTimeout: '2 minutes',})- temporalWorkflowsStarted.labels({ status: 'success' }).inc()+ temporalWorkflowsStarted.labels({ status: 'success', payload }).inc()logger.debug('Started tagger run workflow', {workflowId,diff --git a/posthog/temporal/ai_observability/evaluation_event_io.py b/posthog/temporal/ai_observability/evaluation_event_io.pyindex 89004fdc854b..f4022005251e 100644--- a/posthog/temporal/ai_observability/evaluation_event_io.py+++ b/posthog/temporal/ai_observability/evaluation_event_io.py@@ -1,4 +1,4 @@-from datetime import datetime+from datetime import datetime, timedeltafrom typing import Anyimport temporalio.activity@@ -10,9 +10,11 @@ from posthog.utils import ensure_utcfrom products.ai_observability.backend.ai_event_lookup import fetch_generation_event-# A generation can reach `events`, where a backfill finds it, before it reaches `ai_events`, where-# it is read, so a miss gets two retries before it fails the run.+# A generation can reach `events`, where a backfill finds it, or the scheduler's Kafka consumer+# before it reaches `ai_events`, where it is read, so a miss gets two retries before it fails the+# run. Only a live reference waits between them: a backfill miss is usually an expired row.GENERATION_NOT_FOUND_MAX_ATTEMPTS = 3+GENERATION_NOT_FOUND_RETRY_DELAY = timedelta(seconds=15)def as_utc_datetime(value: str | datetime) -> datetime:@@ -75,7 +77,8 @@ def hydrate_event_reference(event_data: dict[str, Any]) -> dict[str, Any]:Capture accepts an AI event up to 8 MiB while a Temporal payload is capped near 2 MiB, so alarge generation cannot cross the workflow boundary at all. A backfill dispatcher thereforeships the uuid, plus the timestamp and trace id that turn the read into a point lookup on the- ai_events sort key, and every activity that needs the body reads it here.+ ai_events sort key, and every activity that needs the body reads it here. The live scheduler+ sends the same reference, marked `awaiting_ingestion`, for an event over its size threshold."""if "properties" in event_data:return event_data@@ -89,6 +92,10 @@ def hydrate_event_reference(event_data: dict[str, Any]) -> dict[str, Any]:if event is None:if temporalio.activity.in_activity() and temporalio.activity.info().attempt < GENERATION_NOT_FOUND_MAX_ATTEMPTS:# Only the last miss reaches error tracking: an earlier one is usually the lag above.- raise NonReportableApplicationError("Generation not found", type="generation_not_found")+ raise NonReportableApplicationError(+ "Generation not found",+ type="generation_not_found",+ next_retry_delay=GENERATION_NOT_FOUND_RETRY_DELAY if event_data.get("awaiting_ingestion") else None,+ )raise ApplicationError("Generation not found", type="generation_not_found", non_retryable=True)return eventdiff --git a/posthog/temporal/ai_observability/run_tagger.py b/posthog/temporal/ai_observability/run_tagger.pyindex b5f8ba6d6bb5..df0c496e42fd 100644--- a/posthog/temporal/ai_observability/run_tagger.py+++ b/posthog/temporal/ai_observability/run_tagger.py@@ -13,7 +13,11 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.api.capture import CaptureInternalErrorfrom posthog.sync import database_sync_to_async-from posthog.temporal.ai_observability.evaluation_event_io import extract_event_io+from posthog.temporal.ai_observability.evaluation_event_io import (+ GENERATION_NOT_FOUND_MAX_ATTEMPTS,+ extract_event_io,+ hydrate_event_reference,+)from posthog.temporal.ai_observability.evaluation_workflow_activities import update_key_state_activityfrom posthog.temporal.ai_observability.message_utils import extract_text_from_messagesfrom posthog.temporal.ai_observability.model_resolution import ResolvedModel, model_spec@@ -237,7 +241,7 @@ def _resolve_model(model_configuration: dict[str, Any] | None, team_id: int) ->def execute_tagger_activity(inputs: ExecuteTaggerInputs) -> dict[str, Any]:"""Execute LLM tagger to classify the target event."""tagger = inputs.tagger- event_data = inputs.event_data+ event_data = hydrate_event_reference(inputs.event_data)tagger_config = tagger.get("tagger_config", {})prompt = tagger_config.get("prompt")@@ -491,6 +495,7 @@ async def execute_hog_tagger_activity(tagger: dict[str, Any], event_data: dict[stags_def = tagger_config.get("tags", [])valid_tag_names = {tag["name"] for tag in tags_def}+ event_data = await database_sync_to_async(hydrate_event_reference, thread_sensitive=False)(event_data)def _execute():return run_hog_tagger(bytecode, event_data, valid_tag_names)@@ -529,7 +534,7 @@ class EmitTaggerEventInputs:async def emit_tagger_event_activity(inputs: EmitTaggerEventInputs) -> None:"""Emit $ai_tag event via capture_internal."""tagger = inputs.tagger- event_data = inputs.event_data+ event_data = await database_sync_to_async(hydrate_event_reference, thread_sensitive=False)(inputs.event_data)result = inputs.resultstart_time = inputs.start_time@@ -651,12 +656,13 @@ class RunTaggerWorkflow(PostHogWorkflow):# Activity 2: Execute tagger based on typeif tagger_type == "hog":- # Hog taggers are deterministic — don't retry+ # Hog errors are non-retryable; the attempts only cover a referenced event that is not+ # in ai_events yet.result = await temporalio.workflow.execute_activity(execute_hog_tagger_activity,args=[tagger, inputs.event_data],- schedule_to_close_timeout=timedelta(seconds=30),- retry_policy=RetryPolicy(maximum_attempts=1),+ schedule_to_close_timeout=timedelta(minutes=2),+ retry_policy=RetryPolicy(maximum_attempts=GENERATION_NOT_FOUND_MAX_ATTEMPTS),)else:# LLM tagger@@ -720,7 +726,7 @@ class RunTaggerWorkflow(PostHogWorkflow):result=result,start_time=start_time,),- schedule_to_close_timeout=timedelta(seconds=30),+ schedule_to_close_timeout=timedelta(minutes=2),retry_policy=RetryPolicy(maximum_attempts=3),)diff --git a/posthog/temporal/ai_observability/test_run_evaluation.py b/posthog/temporal/ai_observability/test_run_evaluation.pyindex 2596214e25ae..0aa78e8920b4 100644--- a/posthog/temporal/ai_observability/test_run_evaluation.py+++ b/posthog/temporal/ai_observability/test_run_evaluation.py@@ -56,7 +56,7 @@ from .evaluation_errors import (status_reason_detail_for_terminal_user_error,terminal_user_error_result_from_application_error,)-from .evaluation_event_io import hydrate_event_reference+from .evaluation_event_io import GENERATION_NOT_FOUND_RETRY_DELAY, hydrate_event_referencefrom .evaluation_llm_judge import (JUDGE_EVENT_MAX_CHARS,NumericWithNAEvalResult,@@ -1822,6 +1822,7 @@ class TestRunEvaluationWorkflow:assert mock_fetch.call_count == 1+ @pytest.mark.parametrize("live", [pytest.param(True, id="live"), pytest.param(False, id="backfill")])@pytest.mark.parametrize("attempt,retryable",[@@ -1830,16 +1831,21 @@ class TestRunEvaluationWorkflow:pytest.param(3, False, id="last attempt"),],)- def test_a_missing_generation_gets_two_retries_before_it_fails_the_run(self, attempt: int, retryable: bool):+ def test_a_missing_generation_gets_two_retries_before_it_fails_the_run(+ self, attempt: int, retryable: bool, live: bool+ ):+ reference = {**THIN_REFERENCE, "awaiting_ingestion": True} if live else dict(THIN_REFERENCE)env = ActivityEnvironment()env.info = dataclasses.replace(env.info, attempt=attempt)with patch(HYDRATE_FETCH, return_value=None):with pytest.raises(ApplicationError) as raised:- env.run(hydrate_event_reference, dict(THIN_REFERENCE))+ env.run(hydrate_event_reference, reference)assert raised.value.type == "generation_not_found"assert raised.value.non_retryable is not retryableassert isinstance(raised.value, NonReportableError) is retryable+ expected_delay = GENERATION_NOT_FOUND_RETRY_DELAY if retryable and live else None+ assert raised.value.next_retry_delay == expected_delaydef test_parse_inputs(self):"""Test that parse_inputs correctly parses workflow inputs"""diff --git a/posthog/temporal/ai_observability/test_run_tagger.py b/posthog/temporal/ai_observability/test_run_tagger.pyindex 8a833ffb7d08..08d430650651 100644--- a/posthog/temporal/ai_observability/test_run_tagger.py+++ b/posthog/temporal/ai_observability/test_run_tagger.py@@ -8,7 +8,10 @@ import pytestfrom unittest.mock import MagicMock, patchimport httpx+from temporalio import activityfrom temporalio.exceptions import ActivityError, ApplicationError+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Workerfrom posthog.api.capture import CaptureInternalErrorfrom posthog.models import Organization, Team@@ -507,6 +510,120 @@ class TestRunTaggerWorkflow:await database_sync_to_async(tagger.refresh_from_db)()assert tagger.enabled is False+ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ @pytest.mark.parametrize("activity", ["llm", "hog", "emit"])+ async def test_tagger_activities_hydrate_a_reference(self, setup_data, activity: str):+ team = setup_data["team"]+ full_event = create_mock_event_data(+ team.id,+ uuid="g1",+ properties={+ "$ai_input": [{"role": "user", "content": "How do I set up billing?"}],+ "$ai_output_choices": [{"role": "assistant", "content": "In the settings."}],+ "$ai_trace_id": "t1",+ },+ )+ reference = {"uuid": "g1", "team_id": team.id, "timestamp": full_event["timestamp"], "trace_id": "t1"}+ tagger = {+ "id": str(setup_data["tagger"].id),+ "name": "Feature Tagger",+ "tagger_config": make_tagger_config(),+ "team_id": team.id,+ }++ with patch(+ "posthog.temporal.ai_observability.evaluation_event_io.fetch_generation_event", return_value=full_event+ ) as mock_fetch:+ if activity == "llm":+ mock_response = MagicMock(+ parsed=TagResult(tags=["billing"], reasoning="billing"),+ usage=MagicMock(input_tokens=1, output_tokens=1, total_tokens=2),+ )+ with (+ patch("posthog.temporal.ai_observability.run_tagger.Client") as mock_client_class,+ patch("posthog.temporal.ai_observability.model_resolution.EvaluationConfig") as mock_eval_config,+ ):+ mock_client_class.return_value.complete.return_value = mock_response+ mock_eval_config.objects.get_or_create.return_value = (_mock_config_with_active_key(), False)+ result = await database_sync_to_async(execute_tagger_activity)(+ ExecuteTaggerInputs(tagger=tagger, event_data=reference)+ )+ assert result["tags"] == ["billing"]+ elif activity == "hog":+ hog_tagger = make_hog_tagger_dict(team.id, source="return ['billing']")+ result = await execute_hog_tagger_activity(hog_tagger, reference)+ assert result["tags"] == ["billing"]+ else:+ with (+ patch(+ "posthog.temporal.ai_observability.team_capture.get_team_api_token",+ return_value=team.api_token,+ ),+ patch("posthog.temporal.ai_observability.team_capture.capture_ai_internal") as mock_capture,+ ):+ mock_capture.return_value = MagicMock(status_code=200, raise_for_status=MagicMock())+ await emit_tagger_event_activity(+ EmitTaggerEventInputs(+ tagger=tagger,+ event_data=reference,+ result={"tags": ["billing"], "reasoning": "billing", "is_hog": True},+ start_time=datetime(2024, 1, 1, 12, 0, 0),+ )+ )+ props = mock_capture.call_args[1]["properties"]+ assert props["$ai_target_event_id"] == "g1"+ assert props["$ai_trace_id"] == "t1"++ assert mock_fetch.call_count == 1++ @pytest.mark.asyncio+ @pytest.mark.django_db(transaction=True)+ async def test_the_hog_tagger_waits_for_a_live_reference_to_reach_clickhouse(self, setup_data):+ team = setup_data["team"]+ full_event = create_mock_event_data(team.id, uuid="g1", properties={"$ai_trace_id": "t1"})+ reference = {+ "uuid": "g1",+ "team_id": team.id,+ "timestamp": full_event["timestamp"],+ "trace_id": "t1",+ "awaiting_ingestion": True,+ }+ hog_tagger = make_hog_tagger_dict(team.id, source="return ['billing']")+ emitted: list[dict[str, Any]] = []++ @activity.defn(name="fetch_tagger_activity")+ async def mock_fetch_tagger(inputs: RunTaggerInputs) -> dict[str, Any]:+ return hog_tagger++ @activity.defn(name="emit_tagger_event_activity")+ async def mock_emit_tagger_event(inputs: EmitTaggerEventInputs) -> None:+ emitted.append(inputs.result)++ task_queue = str(uuid.uuid4())+ with patch(+ "posthog.temporal.ai_observability.evaluation_event_io.fetch_generation_event",+ side_effect=[None, full_event],+ ) as mock_fetch:+ async with await WorkflowEnvironment.start_time_skipping() as env:+ async with Worker(+ env.client,+ task_queue=task_queue,+ workflows=[RunTaggerWorkflow],+ activities=[mock_fetch_tagger, execute_hog_tagger_activity, mock_emit_tagger_event],+ workflow_runner=UnsandboxedWorkflowRunner(),+ ):+ result = await env.client.execute_workflow(+ RunTaggerWorkflow.run,+ RunTaggerInputs(tagger_id=hog_tagger["id"], event_data=reference),+ id=str(uuid.uuid4()),+ task_queue=task_queue,+ )++ assert mock_fetch.call_count == 2+ assert result["tags"] == ["billing"]+ assert emitted[0]["tags"] == ["billing"]+def test_parse_inputs(self):event_data = create_mock_event_data(team_id=1)inputs = ["tagger-123", json.dumps(event_data)]