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.

chore(ai-observability): return frozen dataclasses instead of tuples (#76136)

Arno Hillen0dba816ebefc
diff --git a/posthog/llm/gateway_client.py b/posthog/llm/gateway_client.py
index c96ada6a63ce..0e6d251d8e63 100644
--- a/posthog/llm/gateway_client.py
+++ b/posthog/llm/gateway_client.py
@@ -1,5 +1,6 @@
import json
from collections.abc import Mapping
+from dataclasses import dataclass
from typing import Literal
from urllib.parse import urlparse
from uuid import UUID, uuid5
@@ -204,8 +205,14 @@ def _gateway_misconfig(url: str, api_key: str) -> str | None:
return None
-def resolve_ai_gateway_config() -> tuple[str, str] | None:
- """Return the validated (url, api_key) for the internal Go ai-gateway, or None.
+@dataclass(frozen=True, kw_only=True, slots=True)
+class AIGatewayConfig:
+ url: str
+ api_key: str
+
+
+def resolve_ai_gateway_config() -> AIGatewayConfig | None:
+ """Return the validated AIGatewayConfig for the internal Go ai-gateway, or None.
None when neither env var is set (the caller uses its normal path), and ALSO when the config
is half-applied or the URL is malformed: that logs a warning and returns None so the caller
@@ -219,7 +226,7 @@ def resolve_ai_gateway_config() -> tuple[str, str] | None:
if misconfig:
logger.warning("ai_gateway_misconfigured_falling_back", reason=misconfig)
return None
- return url, api_key
+ return AIGatewayConfig(url=url, api_key=api_key)
def _ai_property_headers(**labels: str | None) -> dict[str, str] | None:
@@ -330,10 +337,9 @@ def build_openai_client(
"""
gateway = resolve_ai_gateway_config()
if gateway:
- url, api_key = gateway
return OpenAI(
- api_key=api_key,
- base_url=url,
+ api_key=gateway.api_key,
+ base_url=gateway.url,
default_headers=ai_gateway_headers(
ai_product=ai_product,
trace_id=trace_id,
@@ -358,10 +364,9 @@ def build_async_openai_client(
"""Async variant of :func:`build_openai_client`."""
gateway = resolve_ai_gateway_config()
if gateway:
- url, api_key = gateway
return AsyncOpenAI(
- api_key=api_key,
- base_url=url,
+ api_key=gateway.api_key,
+ base_url=gateway.url,
default_headers=ai_gateway_headers(
ai_product=ai_product,
trace_id=trace_id,
@@ -402,7 +407,6 @@ def build_async_anthropic_client(
"""
gateway = resolve_ai_gateway_config()
if gateway:
- url, api_key = gateway
default_headers = {
**(
_ai_property_headers(
@@ -415,8 +419,8 @@ def build_async_anthropic_client(
**_ai_trace_headers(team_id),
}
return AsyncAnthropic(
- api_key=api_key,
- base_url=_anthropic_gateway_base_url(url),
+ api_key=gateway.api_key,
+ base_url=_anthropic_gateway_base_url(gateway.url),
default_headers=default_headers or None,
http_client=httpx.AsyncClient(trust_env=False),
)
diff --git a/posthog/llm/test_gateway_client.py b/posthog/llm/test_gateway_client.py
index f14cea725ca9..f6df21db9a40 100644
--- a/posthog/llm/test_gateway_client.py
+++ b/posthog/llm/test_gateway_client.py
@@ -7,6 +7,7 @@ from unittest.mock import patch
from django.test import override_settings
from posthog.llm.gateway_client import (
+ AIGatewayConfig,
Product,
build_async_anthropic_client,
build_async_openai_client,
@@ -192,7 +193,7 @@ class TestResolveAIGatewayConfig:
@override_settings(AI_GATEWAY_URL=AI_GATEWAY_URL, AI_GATEWAY_API_KEY=AI_GATEWAY_KEY)
def test_returns_pair_when_both_set(self):
- assert resolve_ai_gateway_config() == (AI_GATEWAY_URL, AI_GATEWAY_KEY)
+ assert resolve_ai_gateway_config() == AIGatewayConfig(url=AI_GATEWAY_URL, api_key=AI_GATEWAY_KEY)
@pytest.mark.parametrize(
"url,key,reason",
diff --git a/posthog/storage/llm_prompt_cache.py b/posthog/storage/llm_prompt_cache.py
index 66a98686110d..f02caec28245 100644
--- a/posthog/storage/llm_prompt_cache.py
+++ b/posthog/storage/llm_prompt_cache.py
@@ -140,29 +140,27 @@ def _load_prompt_cache(cache_key: KeyType) -> dict[str, Any] | HyperCacheStoreMi
if parsed_key is None:
return HyperCacheStoreMissing()
- team_id, prompt_name, version, label_name = parsed_key
-
try:
- if label_name is not None:
- labeled_prompt = _get_labeled_prompt_from_db(team_id, prompt_name, label_name)
+ if parsed_key.label is not None:
+ labeled_prompt = _get_labeled_prompt_from_db(parsed_key.team_id, parsed_key.prompt_name, parsed_key.label)
if labeled_prompt is None:
return HyperCacheStoreMissing()
- return _serialize_labeled_prompt(labeled_prompt, label_name)
+ return _serialize_labeled_prompt(labeled_prompt, parsed_key.label)
- if version is None:
- prompt = _get_latest_prompt_from_db(team_id, prompt_name)
+ if parsed_key.version is None:
+ prompt = _get_latest_prompt_from_db(parsed_key.team_id, parsed_key.prompt_name)
if prompt is None:
return HyperCacheStoreMissing()
return serialize_prompt(prompt, include_internal=True)
- prompt = _get_prompt_version_from_db(team_id, prompt_name, version)
+ prompt = _get_prompt_version_from_db(parsed_key.team_id, parsed_key.prompt_name, parsed_key.version)
if prompt is None:
return HyperCacheStoreMissing()
return serialize_prompt_version(prompt, include_internal=True)
except _TRANSIENT_DB_ERRORS as err:
- _record_prompt_db_unavailable(err, prompt_name)
- raise PromptCacheDatabaseUnavailable(f"Prompt database unavailable loading {prompt_name}") from err
+ _record_prompt_db_unavailable(err, parsed_key.prompt_name)
+ raise PromptCacheDatabaseUnavailable(f"Prompt database unavailable loading {parsed_key.prompt_name}") from err
llm_prompts_hypercache = HyperCache(
diff --git a/posthog/storage/llm_prompt_cache_keys.py b/posthog/storage/llm_prompt_cache_keys.py
index 90f9cbe1e9d1..04d00ae03e08 100644
--- a/posthog/storage/llm_prompt_cache_keys.py
+++ b/posthog/storage/llm_prompt_cache_keys.py
@@ -1,3 +1,5 @@
+from dataclasses import dataclass
+
from posthog.models.team.team import Team
from posthog.storage.hypercache import KeyType
@@ -20,8 +22,16 @@ def prompt_label_cache_key(team: Team | str | int, prompt_name: str, label_name:
return f"{_prompt_cache_key_prefix(team, prompt_name)}:label:{label_name}"
-def parse_prompt_cache_key(cache_key: KeyType) -> tuple[int, str, int | None, str | None] | None:
- """Parse a prompt cache key into (team_id, prompt_name, version, label).
+@dataclass(frozen=True, kw_only=True, slots=True)
+class ParsedPromptCacheKey:
+ team_id: int
+ prompt_name: str
+ version: int | None = None
+ label: str | None = None
+
+
+def parse_prompt_cache_key(cache_key: KeyType) -> ParsedPromptCacheKey | None:
+ """Parse a prompt cache key into a ParsedPromptCacheKey.
Latest keys have version=None and label=None; version and label keys carry
exactly one of the two.
@@ -43,7 +53,7 @@ def parse_prompt_cache_key(cache_key: KeyType) -> tuple[int, str, int | None, st
return None
if len(parts) == 3 and parts[2] == "latest":
- return team_id, prompt_name, None, None
+ return ParsedPromptCacheKey(team_id=team_id, prompt_name=prompt_name)
if len(parts) == 4 and parts[2] == "v":
try:
@@ -52,9 +62,9 @@ def parse_prompt_cache_key(cache_key: KeyType) -> tuple[int, str, int | None, st
return None
if version < 1:
return None
- return team_id, prompt_name, version, None
+ return ParsedPromptCacheKey(team_id=team_id, prompt_name=prompt_name, version=version)
if len(parts) == 4 and parts[2] == "label" and parts[3]:
- return team_id, prompt_name, None, parts[3]
+ return ParsedPromptCacheKey(team_id=team_id, prompt_name=prompt_name, label=parts[3])
return None
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
index 0163b397cc17..f11c2f816a26 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/test/test_tools.py
@@ -142,21 +142,21 @@ class TestWidenedTsWindow(SimpleTestCase):
"period_start": "2026-04-08T14:00:00+00:00",
"period_end": "2026-04-08T15:00:00+00:00",
}
- ts_start, ts_end = _widened_ts_window(state)
- self.assertEqual(ts_start, dt.datetime(2026, 4, 1, 14, 0, tzinfo=dt.UTC))
- self.assertEqual(ts_end, dt.datetime(2026, 4, 9, 15, 0, tzinfo=dt.UTC))
+ window = _widened_ts_window(state)
+ self.assertEqual(window.ts_start, dt.datetime(2026, 4, 1, 14, 0, tzinfo=dt.UTC))
+ self.assertEqual(window.ts_end, dt.datetime(2026, 4, 9, 15, 0, tzinfo=dt.UTC))
def test_falls_back_to_sentinels_on_missing_keys(self):
- ts_start, ts_end = _widened_ts_window({})
+ window = _widened_ts_window({})
# Wide sentinel bounds so a bad state doesn't prevent partition pruning
- self.assertEqual(ts_start.year, 2020)
- self.assertEqual(ts_end.year, 2099)
+ self.assertEqual(window.ts_start.year, 2020)
+ self.assertEqual(window.ts_end.year, 2099)
def test_falls_back_on_malformed_timestamps(self):
state = {"period_start": "not-a-timestamp", "period_end": "also-bad"}
- ts_start, ts_end = _widened_ts_window(state)
- self.assertEqual(ts_start.year, 2020)
- self.assertEqual(ts_end.year, 2099)
+ window = _widened_ts_window(state)
+ self.assertEqual(window.ts_start.year, 2020)
+ self.assertEqual(window.ts_end.year, 2099)
class TestSummaryMetrics(SimpleTestCase):
diff --git a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
index 317743a7958b..340e7c6d4b35 100644
--- a/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
+++ b/posthog/temporal/ai_observability/eval_reports/report_agent/tools.py
@@ -12,6 +12,7 @@ import json
import time
import random
from collections.abc import Callable
+from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING, Annotated, Literal, TypeVar
@@ -188,8 +189,14 @@ def _outcome_for_result(output_type: str, result: object, applicable: object = N
return None
-def _widened_ts_window(state: dict) -> tuple[datetime, datetime]:
- """Return (ts_start, ts_end) datetimes widened for target lookups.
+@dataclass(frozen=True, kw_only=True, slots=True)
+class TimestampWindow:
+ ts_start: datetime
+ ts_end: datetime
+
+
+def _widened_ts_window(state: dict) -> TimestampWindow:
+ """Return the (ts_start, ts_end) window widened for target lookups.
Target events can predate their evaluations, so widen the start by 7 days.
End is period_end + 1 day for evaluation lag. Falls back to wide sentinel
@@ -203,7 +210,7 @@ def _widened_ts_window(state: dict) -> tuple[datetime, datetime]:
ts_end = _ch_ts((datetime.fromisoformat(state["period_end"]) + timedelta(days=1)).isoformat())
except (ValueError, TypeError, KeyError):
ts_end = _ch_ts(_TARGET_LOOKUP_TS_END_SENTINEL)
- return ts_start, ts_end
+ return TimestampWindow(ts_start=ts_start, ts_end=ts_end)
# Query timeouts and per-query memory limits need a narrower query, so retrying
@@ -681,12 +688,12 @@ def sample_generation_details(
from posthog.models import Team
team = Team.objects.get(id=state["team_id"])
- ts_start, ts_end = _widened_ts_window(state)
+ window = _widened_ts_window(state)
trace_id_by_uuid = resolve_trace_ids_for_generation_uuids(
team=team,
generation_uuids=ids_to_fetch,
- ts_start=ts_start,
- ts_end=ts_end,
+ ts_start=window.ts_start,
+ ts_end=window.ts_end,
query_type="EvalReportAgentTraceIdResolve",
)
trace_ids = sorted({tid for tid in trace_id_by_uuid.values() if tid})
@@ -778,18 +785,18 @@ def get_generation_detail(
from posthog.models import Team
team = Team.objects.get(id=team_id)
- ts_start, ts_end = _widened_ts_window(state)
+ window = _widened_ts_window(state)
shared_placeholders = {
"generation_id": ast.Constant(value=generation_id),
- "ts_start": ast.Constant(value=ts_start),
- "ts_end": ast.Constant(value=ts_end),
+ "ts_start": ast.Constant(value=window.ts_start),
+ "ts_end": ast.Constant(value=window.ts_end),
}
trace_id_by_uuid = resolve_trace_ids_for_generation_uuids(
team=team,
generation_uuids=[generation_id],
- ts_start=ts_start,
- ts_end=ts_end,
+ ts_start=window.ts_start,
+ ts_end=window.ts_end,
query_type="EvalReportAgentTraceIdResolve",
)
trace_id = trace_id_by_uuid.get(generation_id)
@@ -940,13 +947,13 @@ def get_generation_text_repr(
return json.dumps({"error": "Invalid generation ID format"})
team = Team.objects.get(id=state["team_id"])
- ts_start, ts_end = _widened_ts_window(state)
+ window = _widened_ts_window(state)
trace_id_by_uuid = resolve_trace_ids_for_generation_uuids(
team=team,
generation_uuids=[generation_id],
- ts_start=ts_start,
- ts_end=ts_end,
+ ts_start=window.ts_start,
+ ts_end=window.ts_end,
query_type="EvalReportAgentTraceIdResolve",
)
trace_id = trace_id_by_uuid.get(generation_id)
@@ -1150,8 +1157,8 @@ def _fetch_session_detail(state: dict, session_id: object, max_traces: int) -> d
"error": "Session ID is not available for this evaluation report",
}
- widened_start, widened_end = _widened_ts_window(state)
- ts_start = widened_start - timedelta(days=_SESSION_EXTRA_LOOKBACK_DAYS)
+ window = _widened_ts_window(state)
+ ts_start = window.ts_start - timedelta(days=_SESSION_EXTRA_LOOKBACK_DAYS)
try:
team = Team.objects.get(id=state["team_id"])
@@ -1161,7 +1168,7 @@ def _fetch_session_detail(state: dict, session_id: object, max_traces: int) -> d
placeholders={
"target_session_id": ast.Constant(value=normalized_session_id),
"ts_start": ast.Constant(value=ts_start),
- "ts_end": ast.Constant(value=widened_end),
+ "ts_end": ast.Constant(value=window.ts_end),
"limit": ast.Constant(value=max_traces + 1),
},
)
diff --git a/posthog/temporal/ai_observability/evaluation_event_io.py b/posthog/temporal/ai_observability/evaluation_event_io.py
index 2abe2825df0f..582ce02f073e 100644
--- a/posthog/temporal/ai_observability/evaluation_event_io.py
+++ b/posthog/temporal/ai_observability/evaluation_event_io.py
@@ -1,10 +1,17 @@
+from dataclasses import dataclass
from typing import Any
-def extract_event_io(event_type: str, properties: dict[str, Any]) -> tuple[Any, Any]:
+@dataclass(frozen=True, kw_only=True, slots=True)
+class EventIO:
+ input_raw: Any
+ output_raw: Any
+
+
+def extract_event_io(event_type: str, properties: dict[str, Any]) -> EventIO:
"""Extract raw input and output values from event properties.
- Returns (input_raw, output_raw) for use in Hog eval globals and preview display.
+ Returns an `EventIO` for use in Hog eval globals and preview display.
Invariant: `properties` must already contain the heavy `$ai_*` keys when present
on the source event. Heavy columns live only on the dedicated `ai_events` table —
@@ -28,7 +35,7 @@ def extract_event_io(event_type: str, properties: dict[str, Any]) -> tuple[Any,
else:
input_raw = properties.get("$ai_input_state", "")
output_raw = properties.get("$ai_output_state", "")
- return input_raw, output_raw
+ return EventIO(input_raw=input_raw, output_raw=output_raw)
def extract_event_tools(properties: dict[str, Any]) -> Any:
diff --git a/posthog/temporal/ai_observability/evaluation_hog.py b/posthog/temporal/ai_observability/evaluation_hog.py
index 38c94a8fa2fb..c0b77bc7c2d4 100644
--- a/posthog/temporal/ai_observability/evaluation_hog.py
+++ b/posthog/temporal/ai_observability/evaluation_hog.py
@@ -129,18 +129,18 @@ def build_hog_event_global(
`evaluation_events`. The trace-only `events` compatibility global disables them so saved
source keeps its original shape and memory cost.
"""
- input_raw, output_raw = extract_event_io(event_type, properties)
+ io = extract_event_io(event_type, properties)
event_global: dict[str, Any] = {
"uuid": event_uuid,
"event": event_type,
"timestamp": timestamp,
- "input": coerce_hog_io_value(input_raw),
- "output": coerce_hog_io_value(output_raw),
+ "input": coerce_hog_io_value(io.input_raw),
+ "output": coerce_hog_io_value(io.output_raw),
"properties": {key: value for key, value in properties.items() if key not in HEAVY_PROPERTY_NAMES},
}
if include_text:
- event_global["input_text"] = _extract_hog_message_text(input_raw)
- event_global["output_text"] = _extract_hog_output_text(output_raw)
+ event_global["input_text"] = _extract_hog_message_text(io.input_raw)
+ event_global["output_text"] = _extract_hog_output_text(io.output_raw)
return event_global
@@ -301,12 +301,12 @@ def run_hog_eval(bytecode: list, event_data: dict[str, Any], allows_na: bool = F
properties = json.loads(properties)
event_type = event_data["event"]
- input_raw, output_raw = extract_event_io(event_type, properties)
+ io = extract_event_io(event_type, properties)
globals_dict: dict[str, Any] = {
# Generation-only compatibility globals kept for saved Hog source.
- "input": coerce_hog_io_value(input_raw),
- "output": coerce_hog_io_value(output_raw),
+ "input": coerce_hog_io_value(io.input_raw),
+ "output": coerce_hog_io_value(io.output_raw),
"properties": properties,
"event": {
"uuid": event_data.get("uuid", ""),
diff --git a/posthog/temporal/ai_observability/evaluation_llm_judge.py b/posthog/temporal/ai_observability/evaluation_llm_judge.py
index f50d6b5ff7e2..ddaf71dd29b0 100644
--- a/posthog/temporal/ai_observability/evaluation_llm_judge.py
+++ b/posthog/temporal/ai_observability/evaluation_llm_judge.py
@@ -242,11 +242,11 @@ def _execute_llm_judge_activity(inputs: ExecuteLLMJudgeInputs) -> EvaluationActi
if _is_errored_trace(properties):
return _build_errored_trace_result(allows_na)
- input_raw, output_raw = extract_event_io(event_type, properties)
+ io = extract_event_io(event_type, properties)
tools_raw = extract_event_tools(properties)
- input_data = extract_text_from_messages(input_raw)
- output_data = extract_text_from_messages(output_raw)
+ input_data = extract_text_from_messages(io.input_raw)
+ output_data = extract_text_from_messages(io.output_raw)
tools_data = format_tool_definitions(tools_raw)
system_prompt = build_system_prompt(prompt, allows_na)
diff --git a/posthog/temporal/ai_observability/evaluation_sentiment.py b/posthog/temporal/ai_observability/evaluation_sentiment.py
index be1cd486e385..5a91a0ac6a4e 100644
--- a/posthog/temporal/ai_observability/evaluation_sentiment.py
+++ b/posthog/temporal/ai_observability/evaluation_sentiment.py
@@ -90,10 +90,10 @@ async def execute_sentiment_eval_activity(
if isinstance(properties, str):
properties = json.loads(properties)
- input_raw, _output_raw = extract_event_io(event_data["event"], properties)
+ io = extract_event_io(event_data["event"], properties)
event_uuid = event_data["uuid"]
trace_id = properties.get("$ai_trace_id", event_uuid)
- user_messages = extract_sentiment_eval_messages(input_raw)
+ user_messages = extract_sentiment_eval_messages(io.input_raw)
if not user_messages:
return _skipped_sentiment_activity_result(
"no_user_messages", "No user messages found; sentiment evaluation skipped."
diff --git a/posthog/temporal/ai_observability/llm_endpoint.py b/posthog/temporal/ai_observability/llm_endpoint.py
index a4257fe21de3..68b6e4ef4de3 100644
--- a/posthog/temporal/ai_observability/llm_endpoint.py
+++ b/posthog/temporal/ai_observability/llm_endpoint.py
@@ -43,11 +43,10 @@ def build_langchain_chat_client(
gateway = resolve_ai_gateway_config()
if gateway:
- url, api_key = gateway
return ChatOpenAI(
model=model,
- api_key=api_key,
- base_url=url,
+ api_key=gateway.api_key,
+ base_url=gateway.url,
timeout=timeout,
max_retries=2,
default_headers=ai_gateway_headers(
diff --git a/posthog/temporal/ai_observability/run_aggregate_evaluation.py b/posthog/temporal/ai_observability/run_aggregate_evaluation.py
index d251aa48bf37..50daba23b155 100644
--- a/posthog/temporal/ai_observability/run_aggregate_evaluation.py
+++ b/posthog/temporal/ai_observability/run_aggregate_evaluation.py
@@ -18,7 +18,7 @@ import json
import asyncio
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
-from typing import Any
+from typing import Any, Literal
import temporalio
from temporalio.common import RetryPolicy
@@ -299,8 +299,16 @@ def resolve_poll_interval(primary_seconds: int, poll_budget_seconds: int) -> int
return max(primary_seconds // 4, budget_floor, 10)
-def resolve_settle_plan(settle: dict[str, Any] | None, target: str = "trace") -> tuple[str, int, int]:
- """Resolve the settle config into (strategy, primary_seconds, max_age_seconds).
+@dataclass(frozen=True, kw_only=True, slots=True)
+class SettlePlan:
+ strategy: Literal["inactivity", "fixed_window"]
+ # The quiet period under inactivity, the window under fixed_window.
+ primary_seconds: int
+ max_age_seconds: int
+
+
+def resolve_settle_plan(settle: dict[str, Any] | None, target: str = "trace") -> SettlePlan:
+ """Resolve the settle config into a SettlePlan.
Deterministic and exception-free on purpose: the serializer already validated the stored
config, so anything malformed here is a payload bug — falling back to defaults keeps a bad
@@ -312,9 +320,9 @@ def resolve_settle_plan(settle: dict[str, Any] | None, target: str = "trace") ->
if strategy == "inactivity":
quiet = _clamp(config.get("quiet_period_seconds"), *bounds["quiet"])
max_age = _clamp(config.get("max_age_seconds"), *bounds["max_age"])
- return ("inactivity", quiet, max(max_age, quiet))
+ return SettlePlan(strategy="inactivity", primary_seconds=quiet, max_age_seconds=max(max_age, quiet))
window = _clamp(config.get("window_seconds"), *bounds["window"])
- return ("fixed_window", window, window)
+ return SettlePlan(strategy="fixed_window", primary_seconds=window, max_age_seconds=window)
@dataclass
@@ -386,16 +394,16 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):
"A session-target evaluation needs an $ai_session_id", type="missing_ai_session_id", non_retryable=True
)
- strategy, primary_seconds, max_age_seconds = resolve_settle_plan(inputs.settle, inputs.target)
+ plan = resolve_settle_plan(inputs.settle, inputs.target)
is_session = inputs.target == "session" and inputs.ai_session_id is not None
- if strategy == "inactivity":
+ if plan.strategy == "inactivity":
# Sleep past the lag margin too: a probe at exactly quiet_period can never pass
# the `quiet_period + margin` settled bar, so it would burn a poll for nothing.
- initial_sleep_seconds = min(primary_seconds + INGESTION_LAG_MARGIN_SECONDS, max_age_seconds)
+ initial_sleep_seconds = min(plan.primary_seconds + INGESTION_LAG_MARGIN_SECONDS, plan.max_age_seconds)
await asyncio.sleep(initial_sleep_seconds)
- poll_budget_seconds = max_age_seconds - initial_sleep_seconds
+ poll_budget_seconds = plan.max_age_seconds - initial_sleep_seconds
if poll_budget_seconds > 0:
- poll_interval = resolve_poll_interval(primary_seconds, poll_budget_seconds)
+ poll_interval = resolve_poll_interval(plan.primary_seconds, poll_budget_seconds)
retry_policy = RetryPolicy(
initial_interval=timedelta(seconds=poll_interval),
backoff_coefficient=1.0,
@@ -408,8 +416,8 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):
CheckSessionSettledInputs(
team_id=inputs.team_id,
session_id=inputs.ai_session_id,
- quiet_period_seconds=primary_seconds,
- lookback_seconds=int(session_fetch_lookback(max_age_seconds).total_seconds()),
+ quiet_period_seconds=plan.primary_seconds,
+ lookback_seconds=int(session_fetch_lookback(plan.max_age_seconds).total_seconds()),
),
start_to_close_timeout=timedelta(seconds=30),
schedule_to_close_timeout=timedelta(seconds=poll_budget_seconds),
@@ -421,7 +429,7 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):
CheckTraceSettledInputs(
team_id=inputs.team_id,
trace_id=inputs.trace_id,
- quiet_period_seconds=primary_seconds,
+ quiet_period_seconds=plan.primary_seconds,
),
start_to_close_timeout=timedelta(seconds=30),
schedule_to_close_timeout=timedelta(seconds=poll_budget_seconds),
@@ -436,13 +444,13 @@ class RunAggregateEvaluationWorkflow(PostHogWorkflow):
# Temporal stops polling once the next retry would overrun schedule-to-close, so it
# can give up as much as one poll_interval before max_age. Wait out the remainder so
# we always honor the full max-age window before grading a still-active unit.
- remaining = max_age_seconds - (temporalio.workflow.now() - window_start).total_seconds()
+ remaining = plan.max_age_seconds - (temporalio.workflow.now() - window_start).total_seconds()
if remaining > 0:
await asyncio.sleep(remaining)
else:
raise
- elif primary_seconds:
- await asyncio.sleep(primary_seconds)
+ elif plan.primary_seconds:
+ await asyncio.sleep(plan.primary_seconds)
eval_start = temporalio.workflow.now()
diff --git a/posthog/temporal/ai_observability/run_session_evaluation.py b/posthog/temporal/ai_observability/run_session_evaluation.py
index 9f9ed9b7c1e8..dd09261f1185 100644
--- a/posthog/temporal/ai_observability/run_session_evaluation.py
+++ b/posthog/temporal/ai_observability/run_session_evaluation.py
@@ -566,10 +566,10 @@ def _session_io_preview(traces: list[LLMTrace]) -> tuple[str, str]:
output_preview = ""
for trace in traces:
for event in trace.events or []:
- input_raw, output_raw = extract_event_io(event.event, event.properties)
+ io = extract_event_io(event.event, event.properties)
if not input_preview:
- input_preview = extract_text_from_messages(input_raw)[:200]
- output_text = extract_text_from_messages(output_raw)[:200]
+ input_preview = extract_text_from_messages(io.input_raw)[:200]
+ output_text = extract_text_from_messages(io.output_raw)[:200]
if output_text:
output_preview = output_text
return input_preview, output_preview
diff --git a/posthog/temporal/ai_observability/run_tagger.py b/posthog/temporal/ai_observability/run_tagger.py
index b511633bb1d6..4c842faaa09c 100644
--- a/posthog/temporal/ai_observability/run_tagger.py
+++ b/posthog/temporal/ai_observability/run_tagger.py
@@ -223,9 +223,9 @@ async def execute_tagger_activity(inputs: ExecuteTaggerInputs) -> dict[str, Any]
if isinstance(properties, str):
properties = json.loads(properties)
- input_raw, output_raw = extract_event_io(event_type, properties)
- input_data = extract_text_from_messages(input_raw)
- output_data = extract_text_from_messages(output_raw)
+ io = extract_event_io(event_type, properties)
+ input_data = extract_text_from_messages(io.input_raw)
+ output_data = extract_text_from_messages(io.output_raw)
system_prompt = build_tagger_system_prompt(prompt, tags, min_tags, max_tags)
tag_names = [tag["name"] for tag in tags]
@@ -353,10 +353,10 @@ def run_hog_tagger(bytecode: list, event_data: dict[str, Any], valid_tag_names:
properties = json.loads(properties)
event_type = event_data["event"]
- input_raw, output_raw = extract_event_io(event_type, properties)
+ io = extract_event_io(event_type, properties)
- input_val = json.dumps(input_raw) if isinstance(input_raw, list | dict) else (input_raw or "")
- output_val = json.dumps(output_raw) if isinstance(output_raw, list | dict) else (output_raw or "")
+ input_val = json.dumps(io.input_raw) if isinstance(io.input_raw, list | dict) else (io.input_raw or "")
+ output_val = json.dumps(io.output_raw) if isinstance(io.output_raw, list | dict) else (io.output_raw or "")
globals_dict: dict[str, Any] = {
"input": input_val,
diff --git a/posthog/temporal/ai_observability/run_trace_evaluation.py b/posthog/temporal/ai_observability/run_trace_evaluation.py
index 4756983df2d9..85c265318b31 100644
--- a/posthog/temporal/ai_observability/run_trace_evaluation.py
+++ b/posthog/temporal/ai_observability/run_trace_evaluation.py
@@ -342,10 +342,10 @@ def _trace_io_preview(trace: LLMTrace) -> tuple[str, str]:
input_preview = ""
output_preview = ""
for event in trace.events or []:
- input_raw, output_raw = extract_event_io(event.event, event.properties)
+ io = extract_event_io(event.event, event.properties)
if not input_preview:
- input_preview = extract_text_from_messages(input_raw)[:200]
- output_text = extract_text_from_messages(output_raw)[:200]
+ input_preview = extract_text_from_messages(io.input_raw)[:200]
+ output_text = extract_text_from_messages(io.output_raw)[:200]
if output_text:
output_preview = output_text
return input_preview, output_preview
diff --git a/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py b/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
index e74c31b1b90c..66b0093ef0d1 100644
--- a/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
+++ b/posthog/temporal/ai_observability/test_run_aggregate_evaluation.py
@@ -20,6 +20,7 @@ from posthog.temporal.ai_observability.run_aggregate_evaluation import (
CheckTraceSettledInputs,
RunAggregateEvaluationInputs,
RunAggregateEvaluationWorkflow,
+ SettlePlan,
check_session_settled_activity,
check_trace_settled_activity,
resolve_poll_interval,
@@ -89,26 +90,41 @@ class TestResolveSettlePlan:
@pytest.mark.parametrize(
"settle,expected",
[
- (None, ("fixed_window", 1800, 1800)),
- ({}, ("fixed_window", 1800, 1800)),
- ({"strategy": "fixed_window", "window_seconds": 60}, ("fixed_window", 60, 60)),
+ (None, SettlePlan(strategy="fixed_window", primary_seconds=1800, max_age_seconds=1800)),
+ ({}, SettlePlan(strategy="fixed_window", primary_seconds=1800, max_age_seconds=1800)),
+ (
+ {"strategy": "fixed_window", "window_seconds": 60},
+ SettlePlan(strategy="fixed_window", primary_seconds=60, max_age_seconds=60),
+ ),
# Legacy sub-floor values are bumped to the floor (the old workflow only re-clamped the max).
- ({"window_seconds": 0}, ("fixed_window", 10, 10)),
- ({"window_seconds": 99999}, ("fixed_window", 7200, 7200)),
- ({"strategy": "inactivity"}, ("inactivity", 300, 7200)),
+ ({"window_seconds": 0}, SettlePlan(strategy="fixed_window", primary_seconds=10, max_age_seconds=10)),
+ (
+ {"window_seconds": 99999},
+ SettlePlan(strategy="fixed_window", primary_seconds=7200, max_age_seconds=7200),
+ ),
+ ({"strategy": "inactivity"}, SettlePlan(strategy="inactivity", primary_seconds=300, max_age_seconds=7200)),
(
{"strategy": "inactivity", "quiet_period_seconds": 120, "max_age_seconds": 600},
- ("inactivity", 120, 600),
+ SettlePlan(strategy="inactivity", primary_seconds=120, max_age_seconds=600),
),
# Sub-floor and above-ceiling quiet_period_seconds are clamped the same way as window_seconds.
- ({"strategy": "inactivity", "quiet_period_seconds": 5}, ("inactivity", 10, 7200)),
- ({"strategy": "inactivity", "quiet_period_seconds": 5000}, ("inactivity", 1800, 7200)),
+ (
+ {"strategy": "inactivity", "quiet_period_seconds": 5},
+ SettlePlan(strategy="inactivity", primary_seconds=10, max_age_seconds=7200),
+ ),
+ (
+ {"strategy": "inactivity", "quiet_period_seconds": 5000},
+ SettlePlan(strategy="inactivity", primary_seconds=1800, max_age_seconds=7200),
+ ),
# max_age below quiet period is coerced up so the loop's min() can't fire before one quiet period.
(
{"strategy": "inactivity", "quiet_period_seconds": 600, "max_age_seconds": 60},
- ("inactivity", 600, 600),
+ SettlePlan(strategy="inactivity", primary_seconds=600, max_age_seconds=600),
+ ),
+ (
+ {"strategy": "bogus", "window_seconds": 60},
+ SettlePlan(strategy="fixed_window", primary_seconds=60, max_age_seconds=60),
),
- ({"strategy": "bogus", "window_seconds": 60}, ("fixed_window", 60, 60)),
],
)
def test_resolves_and_clamps(self, settle, expected):
@@ -118,19 +134,34 @@ class TestResolveSettlePlan:
"settle,expected",
[
# Absent strategy resolves to the session default, not the trace default.
- (None, ("inactivity", 3600, 86400)),
- ({}, ("inactivity", 3600, 86400)),
+ (None, SettlePlan(strategy="inactivity", primary_seconds=3600, max_age_seconds=86400)),
+ ({}, SettlePlan(strategy="inactivity", primary_seconds=3600, max_age_seconds=86400)),
# Session-sized values survive; the trace ceilings would have crushed these to 1800/7200.
(
{"strategy": "inactivity", "quiet_period_seconds": 86400, "max_age_seconds": 604800},
- ("inactivity", 86400, 604800),
+ SettlePlan(strategy="inactivity", primary_seconds=86400, max_age_seconds=604800),
+ ),
+ (
+ {"strategy": "inactivity", "quiet_period_seconds": 3600},
+ SettlePlan(strategy="inactivity", primary_seconds=3600, max_age_seconds=86400),
),
- ({"strategy": "inactivity", "quiet_period_seconds": 3600}, ("inactivity", 3600, 86400)),
# Session ceilings still clamp above their own bounds.
- ({"strategy": "inactivity", "quiet_period_seconds": 999999}, ("inactivity", 86400, 86400)),
- ({"strategy": "inactivity", "max_age_seconds": 9999999}, ("inactivity", 3600, 604800)),
- ({"strategy": "fixed_window", "window_seconds": 604800}, ("fixed_window", 604800, 604800)),
- ({"strategy": "fixed_window", "window_seconds": 9999999}, ("fixed_window", 604800, 604800)),
+ (
+ {"strategy": "inactivity", "quiet_period_seconds": 999999},
+ SettlePlan(strategy="inactivity", primary_seconds=86400, max_age_seconds=86400),
+ ),
+ (
+ {"strategy": "inactivity", "max_age_seconds": 9999999},
+ SettlePlan(strategy="inactivity", primary_seconds=3600, max_age_seconds=604800),
+ ),
+ (
+ {"strategy": "fixed_window", "window_seconds": 604800},
+ SettlePlan(strategy="fixed_window", primary_seconds=604800, max_age_seconds=604800),
+ ),
+ (
+ {"strategy": "fixed_window", "window_seconds": 9999999},
+ SettlePlan(strategy="fixed_window", primary_seconds=604800, max_age_seconds=604800),
+ ),
],
)
def test_resolves_and_clamps_for_session_target(self, settle, expected):
diff --git a/products/ai_observability/backend/api/evaluations.py b/products/ai_observability/backend/api/evaluations.py
index 14c86ecab6a5..47f807a94a83 100644
--- a/products/ai_observability/backend/api/evaluations.py
+++ b/products/ai_observability/backend/api/evaluations.py
@@ -1308,9 +1308,9 @@ class EvaluationViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, Forbi
result = run_hog_eval(bytecode, event_data, allows_na=allows_na)
- input_raw, output_raw = extract_event_io(event_type, properties)
- input_preview = extract_text_from_messages(input_raw)[:200]
- output_preview = extract_text_from_messages(output_raw)[:200]
+ io = extract_event_io(event_type, properties)
+ input_preview = extract_text_from_messages(io.input_raw)[:200]
+ output_preview = extract_text_from_messages(io.output_raw)[:200]
results.append(
{
diff --git a/products/ai_observability/backend/api/taggers.py b/products/ai_observability/backend/api/taggers.py
index d9e6a19b995c..54c0dd0c5e64 100644
--- a/products/ai_observability/backend/api/taggers.py
+++ b/products/ai_observability/backend/api/taggers.py
@@ -614,9 +614,9 @@ class TaggerViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDes
result = run_hog_tagger(bytecode, event_data, valid_tag_names)
- input_raw, output_raw = extract_event_io(event_type, properties)
- input_preview = extract_text_from_messages(input_raw)[:200]
- output_preview = extract_text_from_messages(output_raw)[:200]
+ io = extract_event_io(event_type, properties)
+ input_preview = extract_text_from_messages(io.input_raw)[:200]
+ output_preview = extract_text_from_messages(io.output_raw)[:200]
results.append(
{