: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
chore(devex): pass evaluation and grouping inputs as dataclasses (#83656)
Arno Hillendfabbeea6d59
diff --git a/posthog/tasks/alerts/test/alert_check_helpers.py b/posthog/tasks/alerts/test/alert_check_helpers.pyindex 5e4b827f97fa..39dcc6378d75 100644--- a/posthog/tasks/alerts/test/alert_check_helpers.py+++ b/posthog/tasks/alerts/test/alert_check_helpers.py@@ -24,17 +24,7 @@ def run_alert_check(alert_id: str) -> None:should_run_metrics_investigation = Falsewith transaction.atomic():- alert_check, notify = alert_utils.add_alert_check(- alert,- value=result.value if result else None,- breaches=result.breaches if result else None,- error=error,- anomaly_scores=result.anomaly_scores if result else None,- triggered_points=result.triggered_points if result else None,- triggered_dates=result.triggered_dates if result else None,- interval=result.interval if result else None,- triggered_metadata=result.triggered_metadata if result else None,- )+ alert_check, notify = alert_utils.add_alert_check(alert, result, error)# Claim the cooldown slot inside the transaction (read-then-write stays# consistent with the check insert), mirroring the detector path.diff --git a/posthog/tasks/alerts/utils.py b/posthog/tasks/alerts/utils.pyindex f77663cb6d11..e120cdf39bd3 100644--- a/posthog/tasks/alerts/utils.py+++ b/posthog/tasks/alerts/utils.py@@ -1,6 +1,5 @@from collections.abc import Collectionfrom contextlib import ExitStack-from dataclasses import dataclassfrom datetime import UTC, datetimefrom zoneinfo import ZoneInfo@@ -11,6 +10,7 @@ import structlogfrom posthog.schema import AlertCalculationInterval, AlertState, ChartDisplayType, NodeKind, TrendsQuery+from posthog.dataclasses import frozenfrom posthog.ph_client import ph_background_capturefrom posthog.rbac.user_access_control import UserAccessControlfrom posthog.slo.context import get_current_slo@@ -48,7 +48,7 @@ logger = structlog.get_logger(__name__)INSIGHT_ALERT_FIRING_EVENT = "$insight_alert_firing"-@dataclass+@frozenclass AlertEvaluationResult:value: float | Nonebreaches: list[str] | None@@ -445,14 +445,8 @@ def record_alert_delivery(def add_alert_check(alert: AlertConfiguration,- value: float | None,- breaches: list[str] | None,+ evaluation_result: AlertEvaluationResult | None,error: dict | None,- anomaly_scores: list[float | None] | None = None,- triggered_points: list[int] | None = None,- triggered_dates: list[str] | None = None,- interval: str | None = None,- triggered_metadata: dict | None = None,) -> tuple[AlertCheck, bool]:"""Persist an AlertCheck row and return it plus a decision on whether notification is needed.@@ -460,10 +454,12 @@ def add_alert_check(successful delivery and treats a non-empty value as the idempotency sentinel on retry.``last_notified_at`` is likewise set by the notify activity on success, not here."""+ # Evaluation never ran (query error): record an all-empty result so the check row still lands.+ result = evaluation_result if evaluation_result is not None else AlertEvaluationResult(value=None, breaches=None)error_message = error.get("message") if error else Noneoutcome = evaluate_alert_check(alert,- threshold_breached=bool(breaches),+ threshold_breached=bool(result.breaches),error_message=error_message,now=datetime.now(UTC),)@@ -475,16 +471,16 @@ def add_alert_check(alert_check = AlertCheck.objects.create(alert_configuration=alert,- calculated_value=value,+ calculated_value=result.value,condition=alert.condition,targets_notified={},state=alert.state,- triggered_metadata=triggered_metadata,+ triggered_metadata=result.triggered_metadata,error=error,- anomaly_scores=anomaly_scores,- triggered_points=triggered_points,- triggered_dates=triggered_dates,- interval=interval,+ anomaly_scores=result.anomaly_scores,+ triggered_points=result.triggered_points,+ triggered_dates=result.triggered_dates,+ interval=result.interval,)alert.save(update_fields=[*state_fields, "last_checked_at", "next_check_at"])diff --git a/posthog/temporal/alerts/activities.py b/posthog/temporal/alerts/activities.pyindex a25e9ac3fcb9..c1a3bbd5ee73 100644--- a/posthog/temporal/alerts/activities.py+++ b/posthog/temporal/alerts/activities.py@@ -208,7 +208,7 @@ def _write_errored_alert_check(alert: AlertConfiguration, error: dict) -> tuple[Both evaluate_alert's failure path and the retry-exhausted record_failed_evaluation activity gothrough here, so the errored-check write stays in one place."""- return add_alert_check(alert, None, None, error)+ return add_alert_check(alert, None, error)@temporalio.activity.defn@@ -245,14 +245,12 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRealert_config_type=(alert.config or {}).get("type"),)- value: float | None = Nonebreaches: list[str] | None = Noneerror: dict | None = Nonealert_evaluation_result = Nonetry:alert_evaluation_result = check_alert_for_insight(alert)- value = alert_evaluation_result.valuebreaches = alert_evaluation_result.breachesexcept CH_TRANSIENT_ERRORS:raise@@ -319,12 +317,6 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRenew_state=AlertState.ERRORED,)- anomaly_scores = alert_evaluation_result.anomaly_scores if alert_evaluation_result else None- triggered_points = alert_evaluation_result.triggered_points if alert_evaluation_result else None- triggered_dates = alert_evaluation_result.triggered_dates if alert_evaluation_result else None- interval = alert_evaluation_result.interval if alert_evaluation_result else None- triggered_metadata = alert_evaluation_result.triggered_metadata if alert_evaluation_result else None-should_start_investigation = Falseshould_gate_notification = Falseshould_run_metrics_investigation = False@@ -335,17 +327,7 @@ async def evaluate_alert(inputs: EvaluateAlertActivityInputs) -> EvaluateAlertRe.get(id=inputs.alert_id))previous_state = alert.state- alert_check, should_notify = add_alert_check(- alert,- value,- breaches,- error,- anomaly_scores,- triggered_points,- triggered_dates,- interval,- triggered_metadata,- )+ alert_check, should_notify = add_alert_check(alert, alert_evaluation_result, error)if should_trigger_investigation(alert,diff --git a/posthog/test/dataclass_frozen_baseline.txt b/posthog/test/dataclass_frozen_baseline.txtindex 7691452fe92e..24cdd090ae39 100644--- a/posthog/test/dataclass_frozen_baseline.txt+++ b/posthog/test/dataclass_frozen_baseline.txt@@ -56,7 +56,6 @@1 posthog/storage/hypercache_verifier.py1 posthog/tasks/alerts/detector.py1 posthog/tasks/alerts/detectors/base.py-1 posthog/tasks/alerts/utils.py1 posthog/taxonomy/property_definition_api.py1 posthog/temporal/ai/anomaly_investigation/notebook.py1 posthog/temporal/ai/anomaly_investigation/runner.py@@ -1373,7 +1372,7 @@10 products/tasks/backend/temporal/process_task/activities/provision_sandbox.py104 posthog/hogql/ast.py12 ee/clickhouse/materialized_columns/columns.py-12 products/signals/backend/temporal/grouping.py+10 products/signals/backend/temporal/grouping.py14 products/marketing_analytics/backend/hogql_queries/adapters/base.py16 posthog/temporal/ai_observability/eval_reports/types.py17 products/exports/backend/temporal/subscriptions/types.pydiff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.pyindex 71c9e47313f4..3fcc7a894a63 100644--- a/products/signals/backend/temporal/grouping.py+++ b/products/signals/backend/temporal/grouping.py@@ -158,23 +158,28 @@ def _build_query_generation_system_prompt(signal_type_examples: list[SignalTypeE)-async def generate_search_queries(- team_id: int | None,- description: str,- source_product: str,- source_type: str,- signal_type_examples: list[SignalTypeExample] | None = None,-) -> list[str]:+@frozen+class GenerateSearchQueriesInput:+ description: str+ source_product: str+ source_type: str+ signal_type_examples: list[SignalTypeExample]+ # Optional with a default so workflows mid-flight across a deploy (whose activity input was+ # serialized before this field existed) still deserialize; missing => gateway key owner's team.+ team_id: int | None = None+++async def generate_search_queries(input: GenerateSearchQueriesInput) -> list[str]:"""Use LLM to generate 1-3 search queries for finding related signals.Returns queries truncated to fit within embedding token limits."""- system_prompt = _build_query_generation_system_prompt(signal_type_examples or [])+ system_prompt = _build_query_generation_system_prompt(input.signal_type_examples)user_prompt = f"""NEW SIGNAL:-- Source: {source_product} / {source_type}-- Description: {description}"""+- Source: {input.source_product} / {input.source_type}+- Description: {input.description}"""def validate(text: str) -> list[str]:data = json.loads(text)@@ -182,7 +187,7 @@ async def generate_search_queries(return [truncate_query_to_token_limit(q) for q in result.queries]return await call_llm(- team_id=team_id,+ team_id=input.team_id,system_prompt=system_prompt,user_prompt=user_prompt,validate=validate,@@ -192,17 +197,6 @@ async def generate_search_queries()-@dataclass-class GenerateSearchQueriesInput:- description: str- source_product: str- source_type: str- signal_type_examples: list[SignalTypeExample]- # Optional with a default so workflows mid-flight across a deploy (whose activity input was- # serialized before this field existed) still deserialize; missing => gateway key owner's team.- team_id: int | None = None--@dataclassclass GenerateSearchQueriesOutput:queries: list[str]@@ -214,13 +208,7 @@ class GenerateSearchQueriesOutput:async def generate_search_queries_activity(input: GenerateSearchQueriesInput) -> GenerateSearchQueriesOutput:"""Use LLM to generate 1-3 search queries for finding related signals."""try:- queries = await generate_search_queries(- team_id=input.team_id,- description=input.description,- source_product=input.source_product,- source_type=input.source_type,- signal_type_examples=input.signal_type_examples,- )+ queries = await generate_search_queries(input)logger.debug(f"Generated {len(queries)} search queries",source_product=input.source_product,@@ -428,15 +416,19 @@ Write a PR title covering ALL the above signals (existing + new), then judge ifreturn prompt-async def match_signal_to_report(- team_id: int | None,- description: str,- source_product: str,- source_type: str,- queries: list[str],- query_results: list[list[SignalCandidate]],- report_contexts: dict[str, ReportContext],-) -> MatchResult:+@frozen+class MatchSignalToReportInput:+ description: str+ source_product: str+ source_type: str+ queries: list[str]+ query_results: list[list[SignalCandidate]]+ report_contexts: dict[str, ReportContext]+ # Optional with a default for deploy-time backward compatibility (see GenerateSearchQueriesInput).+ team_id: int | None = None+++async def match_signal_to_report(input: MatchSignalToReportInput) -> MatchResult:"""Determine if a new signal matches an existing report or needs a new one.@@ -444,12 +436,17 @@ async def match_signal_to_report(ExistingReportMatch if a match is found, NewReportMatch otherwise"""candidates_by_id: dict[str, SignalCandidate] = {}- for candidates in query_results:+ for candidates in input.query_results:for c in candidates:candidates_by_id[c.signal_id] = cuser_prompt = _build_matching_prompt(- description, source_product, source_type, queries, query_results, report_contexts+ input.description,+ input.source_product,+ input.source_type,+ input.queries,+ input.query_results,+ input.report_contexts,)def validate(text: str) -> MatchResult:@@ -460,13 +457,13 @@ async def match_signal_to_report(matched = candidates_by_id.get(result.signal_id)if matched is None:raise ValueError(f"signal_id {result.signal_id} not found in candidates")- if result.query_index < 0 or result.query_index >= len(queries):- raise ValueError(f"query_index {result.query_index} out of range (0-{len(queries) - 1})")+ if result.query_index < 0 or result.query_index >= len(input.queries):+ raise ValueError(f"query_index {result.query_index} out of range (0-{len(input.queries) - 1})")return ExistingReportMatch(report_id=matched.report_id,match_metadata=MatchedMetadata(parent_signal_id=result.signal_id,- match_query=queries[result.query_index],+ match_query=input.queries[result.query_index],reason=result.reason,),)@@ -481,7 +478,7 @@ async def match_signal_to_report()return await call_llm(- team_id=team_id,+ team_id=input.team_id,system_prompt=MATCHING_SYSTEM_PROMPT,user_prompt=user_prompt,validate=validate,@@ -491,33 +488,13 @@ async def match_signal_to_report()-@dataclass-class MatchSignalToReportInput:- description: str- source_product: str- source_type: str- queries: list[str]- query_results: list[list[SignalCandidate]]- report_contexts: dict[str, ReportContext]- # Optional with a default for deploy-time backward compatibility — see GenerateSearchQueriesInput.- team_id: int | None = None--@temporalio.activity.defn@scoped_temporal()@close_db_connectionsasync def match_signal_to_report_activity(input: MatchSignalToReportInput) -> MatchResult:"""Determine if a new signal matches an existing report or needs a new one."""try:- result = await match_signal_to_report(- team_id=input.team_id,- description=input.description,- source_product=input.source_product,- source_type=input.source_type,- queries=input.queries,- query_results=input.query_results,- report_contexts=input.report_contexts,- )+ result = await match_signal_to_report(input)total_candidates = sum(len(r) for r in input.query_results)logger.debug(f"Match result: matched={isinstance(result, ExistingReportMatch)}",diff --git a/products/signals/eval/eval_grouping_e2e.py b/products/signals/eval/eval_grouping_e2e.pyindex 618240804001..5d138c4d0b59 100644--- a/products/signals/eval/eval_grouping_e2e.py+++ b/products/signals/eval/eval_grouping_e2e.py@@ -43,6 +43,8 @@ from products.signals.backend.emission.pipeline import (summarize_long_descriptions as _summarize_long_descriptions,)from products.signals.backend.temporal.grouping import (+ GenerateSearchQueriesInput,+ MatchSignalToReportInput,generate_search_queries,match_signal_to_report,verify_match_specificity,@@ -178,11 +180,13 @@ class EvalGroupingPipeline:"""Generate search queries and compute all embeddings. No store mutations."""queries = await generate_search_queries(- team_id=EVAL_TEAM_ID,- description=description,- source_product=case.signal.config.source_product,- source_type=case.signal.config.source_type,- signal_type_examples=self.store.get_type_examples(),+ GenerateSearchQueriesInput(+ team_id=EVAL_TEAM_ID,+ description=description,+ source_product=case.signal.config.source_product,+ source_type=case.signal.config.source_type,+ signal_type_examples=self.store.get_type_examples(),+ ))all_embeddings = await asyncio.gather(@@ -206,13 +210,15 @@ class EvalGroupingPipeline:candidates = [self.store.search(emb) for emb in query_embeddings]match_result = await match_signal_to_report(- team_id=EVAL_TEAM_ID,- description=description,- source_product=case.signal.config.source_product,- source_type=case.signal.config.source_type,- queries=queries,- query_results=candidates,- report_contexts=self.report_store.get_contexts(),+ MatchSignalToReportInput(+ team_id=EVAL_TEAM_ID,+ description=description,+ source_product=case.signal.config.source_product,+ source_type=case.signal.config.source_type,+ queries=queries,+ query_results=candidates,+ report_contexts=self.report_store.get_contexts(),+ ))specificity_match_result = match_result