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(hogai): return frozen dataclasses instead of tuples (#76142)

Arno Hillen7b11384c66dc
diff --git a/ee/api/session_summaries.py b/ee/api/session_summaries.py
index f13b3d473588..10a9b8227fcb 100644
--- a/ee/api/session_summaries.py
+++ b/ee/api/session_summaries.py
@@ -4,6 +4,7 @@ import json
import uuid
import asyncio
from collections.abc import AsyncGenerator
+from dataclasses import dataclass
from datetime import datetime
from typing import Any, cast
@@ -181,6 +182,14 @@ class SessionSummariesConfigSerializer(serializers.ModelSerializer):
return cleaned
+@dataclass(frozen=True, kw_only=True, slots=True)
+class ValidatedSummaryInput:
+ session_ids: list[str]
+ min_timestamp: datetime
+ max_timestamp: datetime
+ extra_summary_context: ExtraSummaryContext | None
+
+
class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
scope_object = "session_recording" # Keeping recording, as Replay is the main source of info for summary, for now
permission_classes = [IsAuthenticated]
@@ -203,11 +212,16 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
raise exceptions.ValidationError("Session summaries are only supported in PostHog Cloud")
return user
- def _validate_input(self, request: Request) -> tuple[list[str], datetime, datetime, ExtraSummaryContext | None]:
+ def _validate_input(self, request: Request) -> ValidatedSummaryInput:
"""Strict input validation for the group flow — needs all sessions to exist to compute timestamps."""
session_ids, extra_summary_context = self._parse_input(request)
- min_timestamp, max_timestamp = find_sessions_timestamps(session_ids=session_ids, team=self.team)
- return session_ids, min_timestamp, max_timestamp, extra_summary_context
+ timestamps = find_sessions_timestamps(session_ids=session_ids, team=self.team)
+ return ValidatedSummaryInput(
+ session_ids=session_ids,
+ min_timestamp=timestamps.min_timestamp,
+ max_timestamp=timestamps.max_timestamp,
+ extra_summary_context=extra_summary_context,
+ )
def _parse_input(self, request: Request) -> tuple[list[str], ExtraSummaryContext | None]:
"""Parse and validate request body without checking session existence.
@@ -224,12 +238,10 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
@staticmethod
async def _get_summary_from_progress_stream(
- session_ids: list[str],
+ *,
+ validated: ValidatedSummaryInput,
user: User,
team: Team,
- min_timestamp: datetime,
- max_timestamp: datetime,
- extra_summary_context: ExtraSummaryContext | None = None,
) -> tuple[EnrichedSessionGroupSummaryPatternsList, list[FailedSessionInfo]]:
"""Consume the workflow stream and return (patterns, failed_sessions) for the response."""
results: list[
@@ -239,32 +251,32 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
]
] = []
async for update_type, data in execute_summarize_session_group(
- session_ids=session_ids,
+ session_ids=validated.session_ids,
user=user,
team=team,
- min_timestamp=min_timestamp,
- max_timestamp=max_timestamp,
+ min_timestamp=validated.min_timestamp,
+ max_timestamp=validated.max_timestamp,
summary_title="Group summary", # Generic name, as no user input is provided (vs the chat)
- extra_summary_context=extra_summary_context,
+ extra_summary_context=validated.extra_summary_context,
):
if update_type == SessionSummaryStreamUpdate.SESSION_PROGRESS:
continue # The old consumers of this API don't expect this update type, as it's a PostHog AI chat feature
assert not isinstance(data, dict)
results.append((update_type, data))
if not results:
- error_message = f"No summaries were generated for the provided sessions (session ids: {logging_session_ids(session_ids)})"
+ error_message = f"No summaries were generated for the provided sessions (session ids: {logging_session_ids(validated.session_ids)})"
logger.exception(error_message)
raise exceptions.APIException(error_message)
# The last item in the result should be the summary, if not - raise an exception
last_result = results[-1]
summary_iteration = last_result[-1]
if not isinstance(summary_iteration, tuple) or len(summary_iteration) != 3:
- error_message = f"Unexpected result type ({type(summary_iteration)}) when generating summaries (session ids: {logging_session_ids(session_ids)}): {results}"
+ error_message = f"Unexpected result type ({type(summary_iteration)}) when generating summaries (session ids: {logging_session_ids(validated.session_ids)}): {results}"
logger.exception(error_message)
raise exceptions.APIException(error_message)
summary, _, failed_sessions = summary_iteration
if not summary or not isinstance(summary, EnrichedSessionGroupSummaryPatternsList):
- error_message = f"Unexpected result type ({type(summary)}) when generating summaries (session ids: {logging_session_ids(session_ids)}): {results}"
+ error_message = f"Unexpected result type ({type(summary)}) when generating summaries (session ids: {logging_session_ids(validated.session_ids)}): {results}"
logger.exception(error_message)
raise exceptions.APIException(error_message)
return summary, failed_sessions
@@ -277,7 +289,7 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
@action(methods=["POST"], detail=False, required_scopes=["session_recording:read"])
def create_session_summaries(self, request: Request, **kwargs) -> Response:
user = self._validate_user(request)
- session_ids, min_timestamp, max_timestamp, extra_summary_context = self._validate_input(request)
+ validated = self._validate_input(request)
summary_source = self._resolve_summary_source(request)
tracking_id = (
generate_tracking_id()
@@ -288,17 +300,14 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
tracking_id=tracking_id,
summary_source=summary_source,
summary_type="group",
- session_ids=session_ids,
+ session_ids=validated.session_ids,
)
# Summarize provided sessions
try:
summary, failed_sessions = async_to_sync(self._get_summary_from_progress_stream)(
- session_ids=session_ids,
+ validated=validated,
user=user,
team=self.team,
- min_timestamp=min_timestamp,
- max_timestamp=max_timestamp,
- extra_summary_context=extra_summary_context,
)
capture_session_summary_generated(
user=user,
@@ -306,7 +315,7 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
tracking_id=tracking_id,
summary_source=summary_source,
summary_type="group",
- session_ids=session_ids,
+ session_ids=validated.session_ids,
success=True,
failed_session_count=len(failed_sessions),
)
@@ -318,7 +327,7 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
return Response(response_body, status=status.HTTP_200_OK)
except Exception as err:
logger.exception(
- f"Failed to generate session group summary for sessions {logging_session_ids(session_ids)} from team {self.team.id} by user {user.id}: {err}",
+ f"Failed to generate session group summary for sessions {logging_session_ids(validated.session_ids)} from team {self.team.id} by user {user.id}: {err}",
team_id=self.team.id,
user_id=user.id,
error=str(err),
@@ -329,13 +338,13 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
tracking_id=tracking_id,
summary_source=summary_source,
summary_type="group",
- session_ids=session_ids,
+ session_ids=validated.session_ids,
success=False,
error_type=type(err).__name__,
error_message=str(err),
)
raise exceptions.APIException(
- f"Failed to generate session summaries for sessions {logging_session_ids(session_ids)}. Please try again later."
+ f"Failed to generate session summaries for sessions {logging_session_ids(validated.session_ids)}. Please try again later."
)
@staticmethod
@@ -431,9 +440,7 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
# Don't fail the whole batch if some sessions have no recording — partition them out and surface
# each missing session as a per-session error in the response (matches the partial-success contract
# this endpoint already had for downstream summary failures).
- found_session_ids, missing_session_ids = partition_sessions_by_recording_existence(
- session_ids=session_ids, team=self.team
- )
+ partition = partition_sessions_by_recording_existence(session_ids=session_ids, team=self.team)
tracking_id = generate_tracking_id()
capture_session_summary_started(
user=user,
@@ -446,16 +453,16 @@ class SessionSummariesViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
# Summarize provided sessions individually
try:
summaries: dict[str, dict[str, Any]] = {}
- if found_session_ids:
+ if partition.found_session_ids:
summaries.update(
async_to_sync(self._get_individual_summaries)(
- session_ids=found_session_ids,
+ session_ids=partition.found_session_ids,
user=user,
team=self.team,
extra_summary_context=extra_summary_context,
)
)
- for missing_id in missing_session_ids:
+ for missing_id in partition.missing_session_ids:
summaries[missing_id] = {
"error": "recording_not_found",
"error_message": (
diff --git a/ee/api/test/test_session_summaries.py b/ee/api/test/test_session_summaries.py
index 8f5d8fe00f5e..eff8394707d6 100644
--- a/ee/api/test/test_session_summaries.py
+++ b/ee/api/test/test_session_summaries.py
@@ -20,6 +20,10 @@ from ee.hogai.session_summaries.session_group.patterns import (
EnrichedSessionGroupSummaryPatternsList,
EnrichedSessionGroupSummaryPatternStats,
)
+from ee.hogai.session_summaries.session_group.summarize_session_group import (
+ SessionRecordingPartition,
+ SessionsTimestampRange,
+)
from ee.hogai.session_summaries.tests.conftest import get_mock_enriched_llm_json_response
@@ -104,9 +108,9 @@ class TestSessionSummariesAPI(APIBaseTest):
mock_capture_started: Mock,
mock_capture_generated: Mock,
) -> None:
- mock_find_sessions.return_value = (
- datetime(2024, 1, 1, 10, 0, 0),
- datetime(2024, 1, 1, 11, 0, 0),
+ mock_find_sessions.return_value = SessionsTimestampRange(
+ min_timestamp=datetime(2024, 1, 1, 10, 0, 0),
+ max_timestamp=datetime(2024, 1, 1, 11, 0, 0),
)
mock_result = self.create_mock_result()
mock_failed_sessions = [
@@ -262,9 +266,9 @@ class TestSessionSummariesAPI(APIBaseTest):
mock_execute: Mock,
mock_find_sessions: Mock,
) -> None:
- mock_find_sessions.return_value = (
- datetime(2024, 1, 1, 10, 0, 0),
- datetime(2024, 1, 1, 11, 0, 0),
+ mock_find_sessions.return_value = SessionsTimestampRange(
+ min_timestamp=datetime(2024, 1, 1, 10, 0, 0),
+ max_timestamp=datetime(2024, 1, 1, 11, 0, 0),
)
# Mock execution failure - create async generator that raises exception
@@ -298,7 +302,9 @@ class TestSessionSummariesAPI(APIBaseTest):
mock_execute: Mock,
mock_partition: Mock,
) -> None:
- mock_partition.return_value = (["session_1", "session_2"], [])
+ mock_partition.return_value = SessionRecordingPartition(
+ found_session_ids=["session_1", "session_2"], missing_session_ids=[]
+ )
mock_execute.side_effect = lambda session_id, **kwargs: get_mock_enriched_llm_json_response(session_id)
# Make request
url = f"/api/environments/{self.team.id}/session_summaries/create_session_summaries_individually/"
@@ -324,7 +330,9 @@ class TestSessionSummariesAPI(APIBaseTest):
if endpoint == "create_session_summaries":
sessions_lookup_patch = patch(
"ee.api.session_summaries.find_sessions_timestamps",
- return_value=(datetime(2024, 1, 1, 10, 0, 0), datetime(2024, 1, 1, 11, 0, 0)),
+ return_value=SessionsTimestampRange(
+ min_timestamp=datetime(2024, 1, 1, 10, 0, 0), max_timestamp=datetime(2024, 1, 1, 11, 0, 0)
+ ),
)
executor_patch = patch(
"ee.api.session_summaries.execute_summarize_session_group",
@@ -333,7 +341,7 @@ class TestSessionSummariesAPI(APIBaseTest):
else:
sessions_lookup_patch = patch(
"ee.api.session_summaries.partition_sessions_by_recording_existence",
- return_value=(["session1"], []),
+ return_value=SessionRecordingPartition(found_session_ids=["session1"], missing_session_ids=[]),
)
executor_patch = patch(
"ee.api.session_summaries.execute_summarize_session",
@@ -364,7 +372,9 @@ class TestSessionSummariesAPI(APIBaseTest):
mock_execute: Mock,
mock_partition: Mock,
) -> None:
- mock_partition.return_value = (["session_1", "session_2"], [])
+ mock_partition.return_value = SessionRecordingPartition(
+ found_session_ids=["session_1", "session_2"], missing_session_ids=[]
+ )
# Mock execute to succeed for first session, fail for second
def mock_execute_side_effect(session_id: str, **kwargs: Any) -> dict[str, Any]:
@@ -423,7 +433,7 @@ class TestSessionSummariesAPI(APIBaseTest):
mock_execute: Mock,
mock_partition: Mock,
) -> None:
- mock_partition.return_value = (["session_x"], [])
+ mock_partition.return_value = SessionRecordingPartition(found_session_ids=["session_x"], missing_session_ids=[])
mock_execute.side_effect = raised_exception
url = f"/api/environments/{self.team.id}/session_summaries/create_session_summaries_individually/"
@@ -442,7 +452,9 @@ class TestSessionSummariesAPI(APIBaseTest):
mock_execute: Mock,
mock_partition: Mock,
) -> None:
- mock_partition.return_value = (["session_1"], ["missing_session"])
+ mock_partition.return_value = SessionRecordingPartition(
+ found_session_ids=["session_1"], missing_session_ids=["missing_session"]
+ )
mock_execute.side_effect = lambda session_id, **kwargs: get_mock_enriched_llm_json_response(session_id)
url = f"/api/environments/{self.team.id}/session_summaries/create_session_summaries_individually/"
diff --git a/ee/hogai/api/serializers.py b/ee/hogai/api/serializers.py
index 236b15832f5f..31e9dd733abe 100644
--- a/ee/hogai/api/serializers.py
+++ b/ee/hogai/api/serializers.py
@@ -1,3 +1,4 @@
+from dataclasses import dataclass
from typing import Any
import pydantic
@@ -48,16 +49,21 @@ CONVERSATION_TYPE_MAP: dict[
}
-async def aget_conversation_state(
- conversation: Conversation, team: Any, user: Any
-) -> tuple[AssistantMaxGraphState | None, bool, dict[str, dict[str, Any]]]:
+@dataclass(frozen=True, kw_only=True, slots=True)
+class ConversationStateResult:
+ state: AssistantMaxGraphState | None
+ has_unsupported_content: bool
+ interrupt_payloads: dict[str, dict[str, Any]]
+
+
+async def aget_conversation_state(conversation: Conversation, team: Any, user: Any) -> ConversationStateResult:
"""Compile the LangGraph graph, replay the checkpoint, and validate the typed state.
Single source of truth for the LangGraph history read path — both the conversation
serializer (history-load) and the legacy-history converter (products/posthog_ai) call this so
the graph-compile + checkpoint-replay logic is never duplicated.
- Returns (state, has_unsupported_content, interrupt_payloads). `state` is None for born-sandbox
+ Returns a ConversationStateResult. `state` is None for born-sandbox
conversations (no checkpoint) and on any read/validation error — errors degrade gracefully
and are captured rather than raised so a bad checkpoint can't 500 a conversation load.
"""
@@ -67,7 +73,7 @@ async def aget_conversation_state(
if conversation.agent_runtime == Conversation.AgentRuntime.SANDBOX:
has_checkpoint = await sync_to_async(conversation.checkpoints.exists)()
if not has_checkpoint:
- return None, False, {}
+ return ConversationStateResult(state=None, has_unsupported_content=False, interrupt_payloads={})
try:
graph_class, state_class = CONVERSATION_TYPE_MAP[conversation.type] # type: ignore[index]
@@ -84,7 +90,9 @@ async def aget_conversation_state(
if proposal_id:
interrupt_payloads[proposal_id] = interrupt.value
- return state, False, interrupt_payloads
+ return ConversationStateResult(
+ state=state, has_unsupported_content=False, interrupt_payloads=interrupt_payloads
+ )
except pydantic.ValidationError as e:
capture_exception(
e,
@@ -94,7 +102,7 @@ async def aget_conversation_state(
"conversation_id": str(conversation.id),
},
)
- return None, True, {}
+ return ConversationStateResult(state=None, has_unsupported_content=True, interrupt_payloads={})
except Exception as e:
# Broad exception handler to gracefully degrade UI instead of 500s.
# Captures all errors (context access, graph compilation, validation, etc.) to PostHog.
@@ -106,7 +114,7 @@ async def aget_conversation_state(
"conversation_id": str(conversation.id),
},
)
- return None, False, {}
+ return ConversationStateResult(state=None, has_unsupported_content=False, interrupt_payloads={})
class TaskUserBasicInfoSerializer(DataclassSerializer):
@@ -310,14 +318,12 @@ class ConversationSerializer(ConversationMinimalSerializer):
# (rendered above the conversion divider). LangGraph conversations use the cached
# `messages_json` when present, else compile + replay the checkpoint.
if conversation.agent_runtime == Conversation.AgentRuntime.SANDBOX:
- state, _, _ = self._get_cached_state(conversation)
- return self._render_state_messages(state)
+ return self._render_state_messages(self._get_cached_state(conversation).state)
if conversation.messages_json is not None:
return conversation.messages_json
- state, _, _ = self._get_cached_state(conversation)
- return self._render_state_messages(state)
+ return self._render_state_messages(self._get_cached_state(conversation).state)
def _render_state_messages(self, state: AssistantMaxGraphState | None) -> list[dict[str, Any]]:
if state is None:
@@ -333,13 +339,12 @@ class ConversationSerializer(ConversationMinimalSerializer):
return []
def get_has_unsupported_content(self, conversation: Conversation) -> bool:
- _, has_unsupported_content, _ = self._get_cached_state(conversation)
- return has_unsupported_content
+ return self._get_cached_state(conversation).has_unsupported_content
def get_agent_mode(self, conversation: Conversation) -> str | None:
- state, _, _ = self._get_cached_state(conversation)
- if state:
- return state.agent_mode_or_default
+ result = self._get_cached_state(conversation)
+ if result.state:
+ return result.state.agent_mode_or_default
return None
def get_is_sandbox(self, conversation: Conversation) -> bool:
@@ -352,7 +357,7 @@ class ConversationSerializer(ConversationMinimalSerializer):
Combines metadata from conversation.approval_decisions with payload from checkpoint
interrupts (single source of truth for payload data).
"""
- _, _, interrupt_payloads = self._get_cached_state(conversation)
+ cached_state = self._get_cached_state(conversation)
result: list[dict[str, Any]] = []
for proposal_id, decision_data in conversation.approval_decisions.items():
@@ -366,7 +371,7 @@ class ConversationSerializer(ConversationMinimalSerializer):
continue
# Get payload from checkpoint interrupts (single source of truth)
- payload = interrupt_payloads.get(proposal_id, {}).get("payload", {})
+ payload = cached_state.interrupt_payloads.get(proposal_id, {}).get("payload", {})
result.append(
{
@@ -382,11 +387,9 @@ class ConversationSerializer(ConversationMinimalSerializer):
return result
- def _get_cached_state(
- self, conversation: Conversation
- ) -> tuple[AssistantMaxGraphState | None, bool, dict[str, dict[str, Any]]]:
+ def _get_cached_state(self, conversation: Conversation) -> ConversationStateResult:
if not hasattr(self, "_state_cache"):
- self._state_cache: dict[str, tuple[AssistantMaxGraphState | None, bool, dict[str, dict[str, Any]]]] = {}
+ self._state_cache: dict[str, ConversationStateResult] = {}
cache_key = str(conversation.id)
if cache_key not in self._state_cache:
@@ -394,13 +397,11 @@ class ConversationSerializer(ConversationMinimalSerializer):
return self._state_cache[cache_key]
- async def _aget_state(
- self, conversation: Conversation
- ) -> tuple[AssistantMaxGraphState | None, bool, dict[str, dict[str, Any]]]:
+ async def _aget_state(self, conversation: Conversation) -> ConversationStateResult:
"""Async implementation of state fetching with validation error detection.
Returns:
- Tuple of (state, has_unsupported_content, interrupt_payloads).
- interrupt_payloads is a dict mapping proposal_id to the interrupt value (including payload).
+ A ConversationStateResult; its interrupt_payloads maps proposal_id to the
+ interrupt value (including payload).
"""
return await aget_conversation_state(conversation, self.context["team"], self.context["user"])
diff --git a/ee/hogai/chat_agent/slash_commands/commands/usage/queries.py b/ee/hogai/chat_agent/slash_commands/commands/usage/queries.py
index 75a267b59f0e..e9b2e0afc44d 100644
--- a/ee/hogai/chat_agent/slash_commands/commands/usage/queries.py
+++ b/ee/hogai/chat_agent/slash_commands/commands/usage/queries.py
@@ -328,19 +328,25 @@ def _parse_period_datetime(value: object) -> datetime | None:
return parsed.astimezone(UTC)
-def _build_billing_period(start_value: object, end_value: object) -> tuple[datetime, datetime] | None:
+@dataclass(frozen=True, kw_only=True, slots=True)
+class BillingPeriod:
+ start: datetime
+ end: datetime
+
+
+def _build_billing_period(start_value: object, end_value: object) -> BillingPeriod | None:
start = _parse_period_datetime(start_value)
end = _parse_period_datetime(end_value)
if start is None or end is None or start >= end:
return None
- return start, end
+ return BillingPeriod(start=start, end=end)
def _get_billing_period_from_context(
billing_context: MaxBillingContext | dict[str, object] | None,
-) -> tuple[datetime, datetime] | None:
+) -> BillingPeriod | None:
if not billing_context:
return None
@@ -362,7 +368,7 @@ def _get_billing_period_from_context(
)
-def _get_billing_period_from_organization(team: "Team") -> tuple[datetime, datetime] | None:
+def _get_billing_period_from_organization(team: "Team") -> BillingPeriod | None:
usage = team.organization.usage
if not isinstance(usage, dict):
return None
@@ -377,12 +383,11 @@ def _get_billing_period_from_organization(team: "Team") -> tuple[datetime, datet
def get_ai_usage_period(team: "Team", billing_context: MaxBillingContext | dict[str, object] | None) -> AiUsagePeriod:
billing_period = _get_billing_period_from_context(billing_context) or _get_billing_period_from_organization(team)
if billing_period:
- period_start, period_end = billing_period
return AiUsagePeriod(
label="Billing period",
- start=period_start,
- end=period_end,
- query_start=max(period_start, get_ga_launch_date()),
+ start=billing_period.start,
+ end=billing_period.end,
+ query_start=max(billing_period.start, get_ga_launch_date()),
)
start = get_past_month_start()
diff --git a/ee/hogai/django_checkpoint/test/test_compaction.py b/ee/hogai/django_checkpoint/test/test_compaction.py
index 8de16cc2e552..6f1ab3363cf6 100644
--- a/ee/hogai/django_checkpoint/test/test_compaction.py
+++ b/ee/hogai/django_checkpoint/test/test_compaction.py
@@ -87,9 +87,9 @@ class TestCheckpointCompaction(NonAtomicBaseTest):
return parent.compile(checkpointer=checkpointer)
async def _message_contents(self, conversation: Conversation) -> list[str]:
- state, _, _ = await aget_conversation_state(conversation, self.team, self.user)
- assert state is not None, "UI load path returned no state"
- return [m.content for m in state.messages]
+ result = await aget_conversation_state(conversation, self.team, self.user)
+ assert result.state is not None, "UI load path returned no state"
+ return [m.content for m in result.state.messages]
async def test_compaction_handles_nested_subgraphs(self):
conversation = await Conversation.objects.acreate(user=self.user, team=self.team)
diff --git a/ee/hogai/llm_traces_summaries/tools/get_traces.py b/ee/hogai/llm_traces_summaries/tools/get_traces.py
index f7aba4fb2a12..bf29da178f7c 100644
--- a/ee/hogai/llm_traces_summaries/tools/get_traces.py
+++ b/ee/hogai/llm_traces_summaries/tools/get_traces.py
@@ -26,8 +26,8 @@ class LLMTracesSummarizerCollector:
query = self._get_traces_query(offset=0, date_range=date_range, limit=limit)
runner = TracesQueryRunner(query=query, team=self._team, user=self._user)
# Expecting to get all trace ids in a single query, as it should be lightweight-ish
- trace_ids, _, _ = runner._get_trace_ids()
- return trace_ids
+ trace_ids_result = runner._get_trace_ids()
+ return trace_ids_result.trace_ids
@staticmethod
def _get_traces_query(offset: int, date_range: DateRange, limit: int) -> TracesQuery:
diff --git a/ee/hogai/session_summaries/session_group/patterns.py b/ee/hogai/session_summaries/session_group/patterns.py
index ad3369f5a9e7..04f3e7cb4af6 100644
--- a/ee/hogai/session_summaries/session_group/patterns.py
+++ b/ee/hogai/session_summaries/session_group/patterns.py
@@ -300,9 +300,16 @@ def _enriched_event_from_session_summary_event(
return enriched_event
[email protected](frozen=True, kw_only=True, slots=True)
+class SegmentOutcome:
+ name: str
+ outcome: str
+ success: bool
+
+
def _get_segment_name_and_outcome_from_session_summary(
target_segment_index: int, session_summary: SessionSummarySerializer
-) -> tuple[str, str, bool]:
+) -> SegmentOutcome:
"""Return segment name and outcome for a given index."""
segment_name = segment_outcome = segment_success = None
for segment_state in session_summary.data["segments"]:
@@ -320,7 +327,7 @@ def _get_segment_name_and_outcome_from_session_summary(
msg = f"Segment name, outcome or success not found for segment index {target_segment_index} in session summary: {session_summary.data}"
logger.error(msg, signals_type="session-summaries")
raise ValueError(msg)
- return segment_name, segment_outcome, segment_success
+ return SegmentOutcome(name=segment_name, outcome=segment_outcome, success=segment_success)
def _enrich_pattern_assigned_event_with_session_summary_data(
@@ -361,16 +368,16 @@ def _enrich_pattern_assigned_event_with_session_summary_data(
for next_event in events_in_segment[event_index + 1 : event_index + 4]
]
segment_index = segment_key_actions["segment_index"]
- segment_name, segment_outcome, segment_success = _get_segment_name_and_outcome_from_session_summary(
+ segment = _get_segment_name_and_outcome_from_session_summary(
target_segment_index=segment_index, session_summary=session_summary
)
event_segment_context = PatternAssignedEventSegmentContext(
previous_events_in_segment=previous_events_in_segment,
target_event=current_event,
next_events_in_segment=next_events_in_segment,
- segment_name=segment_name,
- segment_outcome=segment_outcome,
- segment_success=segment_success,
+ segment_name=segment.name,
+ segment_outcome=segment.outcome,
+ segment_success=segment.success,
segment_index=segment_index,
session_start_time_str=(
db_summary.session_start_time.isoformat() if db_summary.session_start_time else None
diff --git a/ee/hogai/session_summaries/session_group/summarize_session_group.py b/ee/hogai/session_summaries/session_group/summarize_session_group.py
index 7367b8b8a71d..0db16d7e29f0 100644
--- a/ee/hogai/session_summaries/session_group/summarize_session_group.py
+++ b/ee/hogai/session_summaries/session_group/summarize_session_group.py
@@ -1,3 +1,4 @@
+from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Any
@@ -112,8 +113,14 @@ def generate_session_group_patterns_combination_prompt(
)
-def partition_sessions_by_recording_existence(session_ids: list[str], team: Team) -> tuple[list[str], list[str]]:
- """Split session_ids into (found, missing) based on whether a replay row exists for the team.
+@dataclass(frozen=True, kw_only=True, slots=True)
+class SessionRecordingPartition:
+ found_session_ids: list[str]
+ missing_session_ids: list[str]
+
+
+def partition_sessions_by_recording_existence(session_ids: list[str], team: Team) -> SessionRecordingPartition:
+ """Split session_ids into found/missing based on whether a replay row exists for the team.
Used by flows that want to surface per-session "no recording" errors instead of failing the
whole batch — see ``find_sessions_timestamps`` for the strict variant used by the group flow.
@@ -122,15 +129,20 @@ def partition_sessions_by_recording_existence(session_ids: list[str], team: Team
sessions_found = replay_events.sessions_found_with_timestamps(session_ids, team).session_ids
found = [sid for sid in session_ids if sid in sessions_found]
missing = [sid for sid in session_ids if sid not in sessions_found]
- return found, missing
+ return SessionRecordingPartition(found_session_ids=found, missing_session_ids=missing)
+
+
+@dataclass(frozen=True, kw_only=True, slots=True)
+class SessionsTimestampRange:
+ min_timestamp: datetime
+ max_timestamp: datetime
-def find_sessions_timestamps(session_ids: list[str], team: Team) -> tuple[datetime, datetime]:
+def find_sessions_timestamps(session_ids: list[str], team: Team) -> SessionsTimestampRange:
"""Validate that all session IDs exist and belong to the team and return min/max timestamps for the entire list of sessions"""
replay_events = SessionReplayEvents()
result = replay_events.sessions_found_with_timestamps(session_ids, team)
sessions_found = result.session_ids
- min_timestamp, max_timestamp = result.min_timestamp, result.max_timestamp
# Check for missing sessions. The replay_events table is the source of truth for "did we capture a recording";
# a missing row most commonly means the session never produced a recording or the recording has aged out
# of retention, not that the caller is hitting the wrong team.
@@ -143,8 +155,8 @@ def find_sessions_timestamps(session_ids: list[str], team: Team) -> tuple[dateti
logger.error(msg, team_id=team.id, signals_type="session-summaries")
raise exceptions.ValidationError(msg)
# Check for missing timestamps
- if min_timestamp is None or max_timestamp is None:
- msg = f"Failed to get min ({min_timestamp}) or max ({max_timestamp}) timestamps for sessions: {', '.join(session_ids)}"
+ if result.min_timestamp is None or result.max_timestamp is None:
+ msg = f"Failed to get min ({result.min_timestamp}) or max ({result.max_timestamp}) timestamps for sessions: {', '.join(session_ids)}"
logger.error(msg, team_id=team.id, signals_type="session-summaries")
raise exceptions.ValidationError(msg)
- return min_timestamp, max_timestamp
+ return SessionsTimestampRange(min_timestamp=result.min_timestamp, max_timestamp=result.max_timestamp)
diff --git a/ee/hogai/tools/replay/summarize_sessions.py b/ee/hogai/tools/replay/summarize_sessions.py
index 807a3ab82e08..f6d325cbc911 100644
--- a/ee/hogai/tools/replay/summarize_sessions.py
+++ b/ee/hogai/tools/replay/summarize_sessions.py
@@ -1,5 +1,6 @@
import json
import asyncio
+from dataclasses import dataclass
from textwrap import dedent
from typing import Any, Literal, cast
@@ -67,6 +68,13 @@ class SummarizeSessionsToolArgs(BaseModel):
)
+@dataclass(frozen=True, kw_only=True, slots=True)
+class SessionsSummaryResult:
+ summary_text: str
+ summary_id: str | None
+ failed_sessions: list[FailedSessionInfo]
+
+
class SummarizeSessionsTool(MaxTool):
name: Literal["summarize_sessions"] = "summarize_sessions"
description: str = dedent(
@@ -156,21 +164,21 @@ class SummarizeSessionsTool(MaxTool):
)
try:
# Summarize the sessions
- summaries_content, session_group_summary_id, failed_sessions = await self._summarize_sessions(
+ result = await self._summarize_sessions(
session_ids=session_ids,
summary_title=summary_title,
session_ids_source=llm_provided_session_ids_source,
)
content: str | None = None
artifact: dict | None = None
- if session_group_summary_id:
- content = summaries_content
+ if result.summary_id:
+ content = result.summary_text
artifact = {
"title": summary_title or "Sessions summary",
- "session_group_summary_id": session_group_summary_id,
+ "session_group_summary_id": result.summary_id,
}
else:
- content, artifact = summaries_content, None
+ content = result.summary_text
except Exception as err:
capture_session_summary_generated(
user=self._user,
@@ -192,7 +200,7 @@ class SummarizeSessionsTool(MaxTool):
summary_type=summary_type,
session_ids=session_ids,
success=True,
- failed_session_count=len(failed_sessions),
+ failed_session_count=len(result.failed_sessions),
)
return content, artifact
@@ -352,11 +360,11 @@ class SummarizeSessionsTool(MaxTool):
self,
session_ids: list[str],
summary_title: str | None,
- ) -> tuple[str, str, list[FailedSessionInfo]]:
- """Summarize sessions as a group. Returns (summary_str, summary_id, failed_sessions)."""
+ ) -> SessionsSummaryResult:
+ """Summarize sessions as a group. The result's summary_id is always set on this path."""
from ee.hogai.session_summaries.utils import logging_session_ids
- min_timestamp, max_timestamp = await database_sync_to_async(find_sessions_timestamps, thread_sensitive=False)(
+ timestamps = await database_sync_to_async(find_sessions_timestamps, thread_sensitive=False)(
session_ids=session_ids, team=self._team
)
trigger_session_id = self._get_trigger_session_id()
@@ -365,8 +373,8 @@ class SummarizeSessionsTool(MaxTool):
session_ids=session_ids,
user=self._user,
team=self._team,
- min_timestamp=min_timestamp,
- max_timestamp=max_timestamp,
+ min_timestamp=timestamps.min_timestamp,
+ max_timestamp=timestamps.max_timestamp,
summary_title=summary_title,
extra_summary_context=None,
trigger_session_id=trigger_session_id,
@@ -407,7 +415,11 @@ class SummarizeSessionsTool(MaxTool):
stringifier = SessionGroupSummaryStringifier(summary.model_dump(exclude_none=False))
summary_str = stringifier.stringify_patterns()
note = self._format_failed_sessions_note(failed_sessions, total_requested=len(session_ids))
- return note + summary_str, session_group_summary_id, failed_sessions
+ return SessionsSummaryResult(
+ summary_text=note + summary_str,
+ summary_id=session_group_summary_id,
+ failed_sessions=failed_sessions,
+ )
else:
msg = f"Unexpected update type ({update_type}) in session group summarization (session_ids: {logging_session_ids(session_ids)})." # type: ignore[unreachable]
logger.error(msg, signals_type="session-summaries")
@@ -419,9 +431,9 @@ class SummarizeSessionsTool(MaxTool):
async def _summarize_sessions(
self, session_ids: list[str], summary_title: str | None, *, session_ids_source: Literal["filters", "explicit"]
- ) -> tuple[str, str | None, list[FailedSessionInfo]]:
- """Returns (summary_str, summary_id, failed_sessions). summary_id and failed_sessions are
- only populated for the group path; the individual path logs per-session errors inline."""
+ ) -> SessionsSummaryResult:
+ """summary_id and failed_sessions are only populated for the group path; the individual
+ path logs per-session errors inline."""
# Fetch per-session metadata for the progress widget
metadata = await database_sync_to_async(self._get_session_metadata, thread_sensitive=False)(session_ids)
# Emit sessions_discovered for the frontend progress widget
@@ -444,13 +456,12 @@ class SummarizeSessionsTool(MaxTool):
# Process sessions based on count
if len(session_ids) <= GROUP_SUMMARIES_MIN_SESSIONS:
summaries_content = await self._summarize_sessions_individually(session_ids=session_ids)
- return summaries_content, None, []
+ return SessionsSummaryResult(summary_text=summaries_content, summary_id=None, failed_sessions=[])
# For large groups, process in detail, searching for patterns
- summaries_content, session_group_summary_id, failed_sessions = await self._summarize_sessions_as_group(
+ return await self._summarize_sessions_as_group(
session_ids=session_ids,
summary_title=summary_title,
)
- return summaries_content, session_group_summary_id, failed_sessions
def _validate_specific_session_ids(self, session_ids: list[str]) -> list[str] | None:
"""Validate that specific session IDs exist in the database."""
diff --git a/posthog/hogql_queries/ai/traces_query_runner.py b/posthog/hogql_queries/ai/traces_query_runner.py
index 1f6d8488aacc..8e74d1bef033 100644
--- a/posthog/hogql_queries/ai/traces_query_runner.py
+++ b/posthog/hogql_queries/ai/traces_query_runner.py
@@ -1,3 +1,4 @@
+from dataclasses import dataclass
from datetime import datetime, timedelta
from functools import cached_property
from typing import Any, cast
@@ -83,6 +84,13 @@ class TracesQueryDateRange(QueryDateRange):
return super().date_to() + timedelta(minutes=self.CAPTURE_RANGE_MINUTES)
+@dataclass(frozen=True, kw_only=True, slots=True)
+class TraceIdsResult:
+ trace_ids: list[str]
+ min_timestamp: datetime | None
+ max_timestamp: datetime | None
+
+
class TracesQueryRunner(AnalyticsQueryRunner[TracesQueryResponse]):
query: TracesQuery
cached_response: CachedTracesQueryResponse
@@ -148,7 +156,7 @@ class TracesQueryRunner(AnalyticsQueryRunner[TracesQueryResponse]):
},
)
- def _get_trace_ids(self) -> tuple[list[str], datetime | None, datetime | None]:
+ def _get_trace_ids(self) -> TraceIdsResult:
"""Execute a separate query to get relevant trace IDs and their time range."""
with self.timings.measure("traces_query_trace_ids_execute"), tags_context(product=Product.LLM_ANALYTICS):
trace_ids_result = execute_hogql_query(
@@ -163,21 +171,21 @@ class TracesQueryRunner(AnalyticsQueryRunner[TracesQueryResponse]):
# Extract trace IDs and time range from results
if not trace_ids_result.results or not trace_ids_result.results[0]:
- return [], None, None
+ return TraceIdsResult(trace_ids=[], min_timestamp=None, max_timestamp=None)
trace_ids_array, min_timestamp, max_timestamp = trace_ids_result.results[0]
# Filter out any null/empty trace IDs and convert to strings
trace_ids = [str(tid) for tid in (trace_ids_array or []) if tid]
- return trace_ids, min_timestamp, max_timestamp
+ return TraceIdsResult(trace_ids=trace_ids, min_timestamp=min_timestamp, max_timestamp=max_timestamp)
def _calculate(self):
# First, get the trace IDs and time range
- trace_ids, min_timestamp, max_timestamp = self._get_trace_ids()
+ trace_ids_result = self._get_trace_ids()
# If no trace IDs found, return empty results
- if not trace_ids:
+ if not trace_ids_result.trace_ids:
return TracesQueryResponse(
columns=[],
results=[],
@@ -188,14 +196,14 @@ class TracesQueryRunner(AnalyticsQueryRunner[TracesQueryResponse]):
)
# Store trace_ids for use in to_query
- self._trace_ids = trace_ids
+ self._trace_ids = trace_ids_result.trace_ids
# Create a narrowed date range if we have timestamps
- narrowed_date_range = self._create_narrowed_date_range(min_timestamp, max_timestamp)
+ narrowed_date_range = self._create_narrowed_date_range(trace_ids_result=trace_ids_result)
with self.timings.measure("traces_query_hogql_execute"), tags_context(product=Product.LLM_ANALYTICS):
query_result = self.paginator.execute_hogql_query(
- query=self._to_query_with_trace_ids(trace_ids),
+ query=self._to_query_with_trace_ids(trace_ids_result.trace_ids),
placeholders={
"filter_conditions": self._get_where_clause(date_range=narrowed_date_range),
},
@@ -239,8 +247,8 @@ class TracesQueryRunner(AnalyticsQueryRunner[TracesQueryResponse]):
"""Public method matching the base class signature."""
if self._trace_ids is None:
# If called before _calculate, run the trace_ids query
- trace_ids, _, _ = self._get_trace_ids()
- self._trace_ids = trace_ids if trace_ids else []
+ trace_ids_result = self._get_trace_ids()
+ self._trace_ids = trace_ids_result.trace_ids if trace_ids_result.trace_ids else []
return self._to_query_with_trace_ids(self._trace_ids)
@@ -390,18 +398,20 @@ class TracesQueryRunner(AnalyticsQueryRunner[TracesQueryResponse]):
# Minute-level precision for 10m capture range
return TracesQueryDateRange(self.query.dateRange, self.team, IntervalType.MINUTE, datetime.now())
- def _create_narrowed_date_range(
- self, min_timestamp: datetime | None, max_timestamp: datetime | None
- ) -> TracesQueryDateRange | None:
+ def _create_narrowed_date_range(self, *, trace_ids_result: TraceIdsResult) -> TracesQueryDateRange | None:
"""Create a narrowed date range based on the actual data timestamps."""
- if min_timestamp is None or max_timestamp is None:
+ if trace_ids_result.min_timestamp is None or trace_ids_result.max_timestamp is None:
return None
# Create a custom date range with the min/max timestamps
# The TracesQueryDateRange class will automatically add the 10-minute capture range buffer
# through its overridden date_from() and date_to() methods
narrowed_range = TracesQueryDateRange(
- DateRange(date_from=min_timestamp.isoformat(), date_to=max_timestamp.isoformat(), explicitDate=True),
+ DateRange(
+ date_from=trace_ids_result.min_timestamp.isoformat(),
+ date_to=trace_ids_result.max_timestamp.isoformat(),
+ explicitDate=True,
+ ),
self.team,
IntervalType.MINUTE,
datetime.now(),
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index e059676acd8b..a2721cd056d1 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -95,6 +95,19 @@ class GitHubCommitAttribution:
name: str | None = None
+@dataclass(frozen=True, kw_only=True, slots=True)
+class PullRequestRef:
+ """A pull request's coordinates, parsed from its GitHub HTML URL."""
+
+ owner: str
+ repo: str
+ number: int
+
+ @property
+ def repository(self) -> str:
+ return f"{self.owner}/{self.repo}"
+
+
class GitHubIntegrationError(Exception):
"""A GitHub API call failed for a non-rate-limit reason (bad response, auth failure, network
error after retry). Rate limits raise ``GitHubRateLimitError`` from ``posthog.egress.github``
@@ -845,8 +858,8 @@ class GitHubIntegrationBase:
return attributions
@staticmethod
- def parse_pull_request_url(pr_url: str) -> tuple[str, str, int] | None:
- """Parse a GitHub pull request URL into ``(owner, repo, pr_number)``.
+ def parse_pull_request_url(pr_url: str) -> PullRequestRef | None:
+ """Parse a GitHub pull request URL into a :class:`PullRequestRef`.
Returns ``None`` if the URL does not look like a GitHub PR URL.
"""
@@ -865,7 +878,7 @@ class GitHubIntegrationBase:
pr_number = int(pr_number_str)
except ValueError:
return None
- return owner, repo, pr_number
+ return PullRequestRef(owner=owner, repo=repo, number=pr_number)
def get_pull_request(self, repository: str, pr_number: int) -> dict[str, Any]:
"""Fetch a pull request by repository (``owner/repo`` or just ``repo``) and PR number."""
@@ -929,8 +942,7 @@ class GitHubIntegrationBase:
parsed = self.parse_pull_request_url(pr_url)
if parsed is None:
return {"success": False, "error": f"Invalid GitHub pull request URL: {pr_url}"}
- owner, repo, pr_number = parsed
- return self.get_pull_request(f"{owner}/{repo}", pr_number)
+ return self.get_pull_request(parsed.repository, parsed.number)
def close_pull_request(self, repository: str, pr_number: int) -> dict[str, Any]:
"""Close a pull request (``PATCH`` state=closed). ``repository`` is ``owner/repo`` or a bare repo.
@@ -966,8 +978,7 @@ class GitHubIntegrationBase:
parsed = self.parse_pull_request_url(pr_url)
if parsed is None:
return {"success": False, "error": f"Invalid GitHub pull request URL: {pr_url}"}
- owner, repo, pr_number = parsed
- return self.close_pull_request(f"{owner}/{repo}", pr_number)
+ return self.close_pull_request(parsed.repository, parsed.number)
def comment_on_pull_request(self, repository: str, pr_number: int, body: str) -> dict[str, Any]:
"""Post a comment on a pull request. ``repository`` is ``owner/repo`` or a bare repo.
@@ -996,8 +1007,7 @@ class GitHubIntegrationBase:
parsed = self.parse_pull_request_url(pr_url)
if parsed is None:
return {"success": False, "error": f"Invalid GitHub pull request URL: {pr_url}"}
- owner, repo, pr_number = parsed
- return self.comment_on_pull_request(f"{owner}/{repo}", pr_number, body)
+ return self.comment_on_pull_request(parsed.repository, parsed.number, body)
def get_pull_request_checks(self, repository: str, pr_number: int) -> dict[str, Any]:
"""Fetch the CI status for a PR — GitHub Actions check runs plus commit statuses from external
@@ -1380,11 +1390,10 @@ class GitHubIntegrationBase:
parsed = self.parse_pull_request_url(pr_url)
if parsed is None:
return {"success": False, "error": f"Invalid GitHub pull request URL: {pr_url}"}
- owner, repo, pr_number = parsed
data = self._gh_graphql(
self._PR_SNAPSHOT_QUERY,
- {"owner": owner, "repo": repo, "number": pr_number},
+ {"owner": parsed.owner, "repo": parsed.repo, "number": parsed.number},
endpoint="/graphql:pullRequestSnapshot",
)
pr = ((data or {}).get("repository") or {}).get("pullRequest")
diff --git a/posthog/models/integration.py b/posthog/models/integration.py
index 2239167d2ccb..1ed0903273ee 100644
--- a/posthog/models/integration.py
+++ b/posthog/models/integration.py
@@ -2023,7 +2023,7 @@ class SlackIntegration:
return config
-@dataclass(frozen=True)
+@dataclass(frozen=True, kw_only=True, slots=True)
class SlackRequestSignature:
signature: str
timestamp: str
diff --git a/posthog/models/organization.py b/posthog/models/organization.py
index 1168c28582ba..cd676b9d85fe 100644
--- a/posthog/models/organization.py
+++ b/posthog/models/organization.py
@@ -1,4 +1,5 @@
import sys
+from dataclasses import dataclass
from datetime import datetime, timedelta
from functools import cache as functools_cache
from typing import TYPE_CHECKING, Any, Literal, Optional, TypedDict, Union
@@ -64,6 +65,12 @@ class OrganizationUsageInfo(TypedDict):
period: list[str] | None
+@dataclass(frozen=True, kw_only=True, slots=True)
+class BillingPeriod:
+ start: datetime
+ end: datetime
+
+
class ProductFeature(TypedDict):
key: str
name: str
@@ -423,8 +430,7 @@ class Organization(ModelActivityMixin, UUIDTModel):
billing_period = self.current_billing_period
if billing_period:
- _start, end = billing_period
- billing_period_end_timestamp = int(end.timestamp())
+ billing_period_end_timestamp = int(billing_period.end.timestamp())
team_rows = [
(team_id, api_token) for team_id, api_token in self.teams.values_list("id", "api_token") if api_token
@@ -547,9 +553,9 @@ class Organization(ModelActivityMixin, UUIDTModel):
return result
@property
- def current_billing_period(self) -> tuple[datetime, datetime] | None:
+ def current_billing_period(self) -> BillingPeriod | None:
"""
- Returns the current billing period as a tuple of (start, end).
+ Returns the current billing period.
Returns None if usage data is not available or period is not set.
"""
if not self.usage or "period" not in self.usage:
@@ -562,7 +568,7 @@ class Organization(ModelActivityMixin, UUIDTModel):
start = dateutil.parser.isoparse(period[0])
end = dateutil.parser.isoparse(period[1])
- return (start, end)
+ return BillingPeriod(start=start, end=end)
except (ValueError, TypeError, KeyError) as e:
logger.warning(f"Failed to parse billing period for organization {self.id}: {e}")
return None
diff --git a/posthog/models/test/test_organization_model.py b/posthog/models/test/test_organization_model.py
index 963107d78aaf..cad025aae29b 100644
--- a/posthog/models/test/test_organization_model.py
+++ b/posthog/models/test/test_organization_model.py
@@ -10,7 +10,7 @@ from django.utils import timezone
from parameterized import parameterized
from posthog.models import Organization, OrganizationInvite
-from posthog.models.organization import OrganizationMembership
+from posthog.models.organization import BillingPeriod, OrganizationMembership
from posthog.plugins.test.mock import mocked_plugin_requests_get
from posthog.plugins.test.plugin_archives import HELLO_WORLD_PLUGIN_GITHUB_ZIP
@@ -201,11 +201,10 @@ class TestOrganization(BaseTest):
if should_return_period:
self.assertIsNotNone(result)
assert result is not None # Type narrowing for mypy
- self.assertIsInstance(result, tuple)
- self.assertEqual(len(result), 2)
- self.assertIsInstance(result[0], datetime)
- self.assertIsInstance(result[1], datetime)
- self.assertLess(result[0], result[1])
+ self.assertIsInstance(result, BillingPeriod)
+ self.assertIsInstance(result.start, datetime)
+ self.assertIsInstance(result.end, datetime)
+ self.assertLess(result.start, result.end)
else:
self.assertIsNone(result)
diff --git a/products/mcp_store/backend/oauth.py b/products/mcp_store/backend/oauth.py
index d4f22d0b8621..15a6e4e8a671 100644
--- a/products/mcp_store/backend/oauth.py
+++ b/products/mcp_store/backend/oauth.py
@@ -371,7 +371,7 @@ def register_dcr_client(metadata: dict, redirect_uri: str) -> DcrClientRegistrat
)
-@dataclass(frozen=True)
+@dataclass(frozen=True, kw_only=True, slots=True)
class PkcePair:
code_verifier: str = dataclasses.field(repr=False)
code_challenge: str
@@ -406,10 +406,18 @@ def _credential_auth_method(credentials: dict, auth_method_key: str, client_secr
return DEFAULT_CONFIDENTIAL_TOKEN_ENDPOINT_AUTH_METHOD if client_secret else "none"
-def resolve_installation_oauth_context(installation: MCPServerInstallation) -> tuple[dict, str, str | None, str]:
+@dataclass(frozen=True, kw_only=True, slots=True)
+class InstallationOAuthContext:
+ metadata: dict
+ client_id: str
+ client_secret: str | None
+ token_endpoint_auth_method: str
+
+
+def resolve_installation_oauth_context(installation: MCPServerInstallation) -> InstallationOAuthContext:
"""Resolve the OAuth metadata + client credentials for an installation.
- Returns ``(metadata, client_id, client_secret, token_endpoint_auth_method)``.
+ Returns an ``InstallationOAuthContext``.
Secrets come from the shared template when set, or from the installation's
encrypted ``sensitive_configuration`` for user-added servers.
@@ -430,7 +438,12 @@ def resolve_installation_oauth_context(installation: MCPServerInstallation) -> t
raise ValueError("Template missing OAuth metadata")
client_secret = credentials.get("client_secret") or None
auth_method = _credential_auth_method(credentials, "token_endpoint_auth_method", client_secret)
- return metadata, shared_client_id, client_secret, auth_method
+ return InstallationOAuthContext(
+ metadata=metadata,
+ client_id=shared_client_id,
+ client_secret=client_secret,
+ token_endpoint_auth_method=auth_method,
+ )
# DCR template: each installation ran discovery + DCR at install
# time. Both the metadata and the minted client live on the
# installation — the template is never written back to, so a
@@ -441,7 +454,12 @@ def resolve_installation_oauth_context(installation: MCPServerInstallation) -> t
if not metadata or not client_id:
raise ValueError("DCR template installation missing OAuth metadata or dcr_client_id")
auth_method = _credential_auth_method(sensitive, "dcr_token_endpoint_auth_method", client_secret)
- return metadata, client_id, client_secret, auth_method
+ return InstallationOAuthContext(
+ metadata=metadata,
+ client_id=client_id,
+ client_secret=client_secret,
+ token_endpoint_auth_method=auth_method,
+ )
metadata = dict(installation.oauth_metadata or {})
client_id = sensitive.get("dcr_client_id", "")
@@ -449,7 +467,12 @@ def resolve_installation_oauth_context(installation: MCPServerInstallation) -> t
if not metadata or not client_id:
raise ValueError("Installation missing OAuth metadata or client_id")
auth_method = _credential_auth_method(sensitive, "dcr_token_endpoint_auth_method", client_secret)
- return metadata, client_id, client_secret, auth_method
+ return InstallationOAuthContext(
+ metadata=metadata,
+ client_id=client_id,
+ client_secret=client_secret,
+ token_endpoint_auth_method=auth_method,
+ )
def _token_request_auth(
@@ -532,23 +555,21 @@ def refresh_installation_token(installation: MCPServerInstallation) -> dict:
raise TokenRefreshError("No refresh token available")
try:
- metadata, client_id, client_secret, token_endpoint_auth_method = resolve_installation_oauth_context(
- installation
- )
+ ctx = resolve_installation_oauth_context(installation)
except ValueError as exc:
raise TokenRefreshError(str(exc))
- token_url = metadata.get("token_endpoint", "")
+ token_url = ctx.metadata.get("token_endpoint", "")
if not token_url:
raise TokenRefreshError("Missing OAuth metadata for token refresh")
token_data = refresh_oauth_token(
token_url=token_url,
refresh_token=refresh_token_value,
- client_id=client_id,
- client_secret=client_secret,
- token_endpoint_auth_method=token_endpoint_auth_method,
- resource=oauth_resource(metadata),
+ client_id=ctx.client_id,
+ client_secret=ctx.client_secret,
+ token_endpoint_auth_method=ctx.token_endpoint_auth_method,
+ resource=oauth_resource(ctx.metadata),
)
# Preserve non-token keys (needs_reauth, dcr_client_id, dcr_client_secret, etc.) across refresh.
@@ -584,13 +605,11 @@ def exchange_oauth_token(
raise OAuthTokenExchangeError("Missing PKCE verifier")
try:
- metadata, client_id, client_secret, token_endpoint_auth_method = resolve_installation_oauth_context(
- installation
- )
+ ctx = resolve_installation_oauth_context(installation)
except ValueError as exc:
raise OAuthTokenExchangeError(str(exc))
- token_endpoint = metadata.get("token_endpoint", "")
+ token_endpoint = ctx.metadata.get("token_endpoint", "")
if not token_endpoint:
raise OAuthTokenExchangeError("Missing token_endpoint in OAuth metadata")
@@ -608,15 +627,15 @@ def exchange_oauth_token(
"grant_type": "authorization_code",
"code_verifier": pkce_verifier,
}
- if resource := oauth_resource(metadata):
+ if resource := oauth_resource(ctx.metadata):
form["resource"] = resource
try:
form, auth = _token_request_auth(
form,
- client_id=client_id,
- client_secret=client_secret,
- token_endpoint_auth_method=token_endpoint_auth_method,
+ client_id=ctx.client_id,
+ client_secret=ctx.client_secret,
+ token_endpoint_auth_method=ctx.token_endpoint_auth_method,
)
except ValueError as exc:
raise OAuthTokenExchangeError(str(exc))
diff --git a/products/mcp_store/backend/probe.py b/products/mcp_store/backend/probe.py
index b6f044561e3a..beade6beab73 100644
--- a/products/mcp_store/backend/probe.py
+++ b/products/mcp_store/backend/probe.py
@@ -250,6 +250,7 @@ def _build_authorize_url(metadata: dict, client_id: str) -> str | None:
if not isinstance(authorization_endpoint, str) or not authorization_endpoint:
return None
+ # The probe never exchanges the code, so the verifier is deliberately discarded.
code_challenge = generate_pkce().code_challenge
query_params = {
"client_id": client_id,
diff --git a/products/mcp_store/backend/test/test_oauth.py b/products/mcp_store/backend/test/test_oauth.py
index f37ca75aa39a..6bbb9dfe55ed 100644
--- a/products/mcp_store/backend/test/test_oauth.py
+++ b/products/mcp_store/backend/test/test_oauth.py
@@ -1091,12 +1091,12 @@ class TestResolveInstallationOauthContext(BaseTest):
sensitive_configuration={"access_token": "tok"},
)
- metadata, client_id, client_secret, auth_method = resolve_installation_oauth_context(installation)
+ ctx = resolve_installation_oauth_context(installation)
- assert metadata["token_endpoint"] == "https://auth.template.example.com/token"
- assert client_id == "template-client"
- assert client_secret == "template-secret"
- assert auth_method == "client_secret_basic"
+ assert ctx.metadata["token_endpoint"] == "https://auth.template.example.com/token"
+ assert ctx.client_id == "template-client"
+ assert ctx.client_secret == "template-secret"
+ assert ctx.token_endpoint_auth_method == "client_secret_basic"
def test_dcr_template_backed_install_returns_per_installation_metadata_and_creds(self):
# DCR templates carry no shared client_id AND no trusted metadata —
@@ -1125,12 +1125,12 @@ class TestResolveInstallationOauthContext(BaseTest):
},
)
- metadata, client_id, client_secret, auth_method = resolve_installation_oauth_context(installation)
+ ctx = resolve_installation_oauth_context(installation)
- assert metadata["token_endpoint"] == "https://auth.dcr-template.example.com/token"
- assert client_id == "minted-for-user"
- assert client_secret is None
- assert auth_method == "none"
+ assert ctx.metadata["token_endpoint"] == "https://auth.dcr-template.example.com/token"
+ assert ctx.client_id == "minted-for-user"
+ assert ctx.client_secret is None
+ assert ctx.token_endpoint_auth_method == "none"
def test_custom_install_returns_per_installation_dcr_creds(self):
installation = MCPServerInstallation.objects.create(
@@ -1145,12 +1145,12 @@ class TestResolveInstallationOauthContext(BaseTest):
},
)
- metadata, client_id, client_secret, auth_method = resolve_installation_oauth_context(installation)
+ ctx = resolve_installation_oauth_context(installation)
- assert metadata["token_endpoint"] == "https://auth.custom.example.com/token"
- assert client_id == "per-user-client"
- assert client_secret == "per-user-secret"
- assert auth_method == "client_secret_basic"
+ assert ctx.metadata["token_endpoint"] == "https://auth.custom.example.com/token"
+ assert ctx.client_id == "per-user-client"
+ assert ctx.client_secret == "per-user-secret"
+ assert ctx.token_endpoint_auth_method == "client_secret_basic"
def test_custom_install_without_secret_returns_none(self):
installation = MCPServerInstallation.objects.create(
@@ -1162,10 +1162,10 @@ class TestResolveInstallationOauthContext(BaseTest):
sensitive_configuration={"dcr_client_id": "public-client"},
)
- _metadata, _client_id, client_secret, auth_method = resolve_installation_oauth_context(installation)
+ ctx = resolve_installation_oauth_context(installation)
- assert client_secret is None
- assert auth_method == "none"
+ assert ctx.client_secret is None
+ assert ctx.token_endpoint_auth_method == "none"
class TestExchangeOauthToken(BaseTest):
diff --git a/products/posthog_ai/backend/context_wrapper.py b/products/posthog_ai/backend/context_wrapper.py
index f2ca8e91987e..61e8103c149f 100644
--- a/products/posthog_ai/backend/context_wrapper.py
+++ b/products/posthog_ai/backend/context_wrapper.py
@@ -172,14 +172,14 @@ class ContextService:
from ee.hogai.utils.types import AssistantState # noqa: PLC0415 — keeps LangGraph off the sandbox import path
started_at = time.monotonic()
- state, _, _ = await aget_conversation_state(conversation, team, user)
+ state_result = await aget_conversation_state(conversation, team, user)
# Legacy conversions are assistant conversations (see CONVERSATION_TYPE_MAP); the broad
# AssistantMaxGraphState union also admits TaxonomyAgentState, which carries no window anchor.
- if not isinstance(state, AssistantState):
+ if not isinstance(state_result.state, AssistantState):
return None
window = AnthropicConversationCompactionManager().get_messages_in_window(
- state.messages, state.root_conversation_start_id
+ state_result.state.messages, state_result.state.root_conversation_start_id
)
transcript = self._render_legacy_transcript(window)
@@ -188,7 +188,7 @@ class ContextService:
event="phai_legacy_conversion",
properties={
"conversation_id": str(conversation.id),
- "messages_total": len(state.messages),
+ "messages_total": len(state_result.state.messages),
"window_messages": len(window),
"duration_ms": int((time.monotonic() - started_at) * 1000),
},
diff --git a/products/posthog_ai/backend/tests/test_context_wrapper.py b/products/posthog_ai/backend/tests/test_context_wrapper.py
index 9e2d1356fde9..8705988e2512 100644
--- a/products/posthog_ai/backend/tests/test_context_wrapper.py
+++ b/products/posthog_ai/backend/tests/test_context_wrapper.py
@@ -15,6 +15,7 @@ from posthog.schema import (
from products.posthog_ai.backend.context_wrapper import AttachedContext, ContextService
from products.posthog_ai.backend.models.assistant import Conversation
+from ee.hogai.api.serializers import ConversationStateResult
from ee.hogai.utils.types import AssistantState
SERIALIZERS = "ee.hogai.api.serializers"
@@ -152,7 +153,7 @@ class TestResumedLegacyContext(APIBaseTest):
def _build(self, state):
async def _aget(conversation, team, user):
- return state, False, {}
+ return ConversationStateResult(state=state, has_unsupported_content=False, interrupt_payloads={})
with (
patch(f"{SERIALIZERS}.aget_conversation_state", side_effect=_aget),
diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.py
index f471d680ace0..9d7d1219acd1 100644
--- a/products/replay_vision/backend/quota.py
+++ b/products/replay_vision/backend/quota.py
@@ -88,7 +88,7 @@ def _current_period_bounds(organization: Organization | None, now: datetime) ->
"""The org's active billing period when synced and current, else the calendar month containing `now`."""
billing_period = organization.current_billing_period if organization else None
if billing_period:
- synced = BillingPeriod(start=_as_utc(billing_period[0]), end=_as_utc(billing_period[1]))
+ synced = BillingPeriod(start=_as_utc(billing_period.start), end=_as_utc(billing_period.end))
if synced.start <= now < synced.end:
return synced
return _current_month_bounds(now)
@@ -116,14 +116,13 @@ def credits_used_by_scanner(organization_id: UUID, scanner_ids: list[UUID]) -> d
if not scanner_ids:
return {}
period = current_period_bounds(organization_id)
- period_start, period_end = period.start, period.end
pairs = Counter(
ReplayObservation.objects.filter(
scanner_id__in=scanner_ids,
team__organization_id=organization_id,
status=ObservationStatus.SUCCEEDED,
- created_at__gte=period_start,
- created_at__lt=period_end,
+ created_at__gte=period.start,
+ created_at__lt=period.end,
).values_list("scanner_id", "scanner_snapshot__model")
)
totals: dict[UUID, ScannerSpend] = {}
@@ -175,12 +174,11 @@ def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:
organization = Organization.objects.filter(pk=organization_id).only("usage").first()
# Billing is the source of truth once synced, falling back to the env cap and calendar months otherwise.
period = _current_period_bounds(organization, now)
- period_start, period_end = period.start, period.end
# Permanently-spent (succeeded) from the immutable ledger; deletes can't refund it.
consumed = ReplayObservationUsage.objects.filter(
organization_id=organization_id,
- observation_created_at__gte=period_start,
- observation_created_at__lt=period_end,
+ observation_created_at__gte=period.start,
+ observation_created_at__lt=period.end,
).aggregate(total=Coalesce(Sum("credits"), Value(0), output_field=IntegerField()))["total"]
# In-flight rows aren't in the ledger yet (receipt is written on success), so reserve their credits live,
# priced from the frozen snapshot model exactly as the eventual receipt will be. One created just before
@@ -189,8 +187,8 @@ def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:
ReplayObservation.objects.filter(
team__organization_id=organization_id,
status__in=IN_FLIGHT_STATUSES,
- created_at__gte=period_start,
- created_at__lt=period_end,
+ created_at__gte=period.start,
+ created_at__lt=period.end,
).values_list("scanner_snapshot__model", flat=True)
)
in_flight = sum(observation_credits_for_model(model or "") * count for model, count in in_flight_models.items())
@@ -203,7 +201,7 @@ def compute_quota_snapshot(organization_id: UUID) -> QuotaSnapshot:
return QuotaSnapshot(
credit_limit=credit_limit,
credits_used=usage,
- period_start=period_start,
- period_end=period_end,
+ period_start=period.start,
+ period_end=period.end,
projected_monthly_credits=projected,
)
diff --git a/products/signals/backend/billing.py b/products/signals/backend/billing.py
index 58a11692e0bd..587f748f2419 100644
--- a/products/signals/backend/billing.py
+++ b/products/signals/backend/billing.py
@@ -46,6 +46,8 @@ from django.utils import timezone
from dateutil.relativedelta import relativedelta
+from posthog.models.organization import BillingPeriod
+
from products.signals.backend.artefact_schemas import TASK_RUN_TYPE_IMPLEMENTATION
from products.signals.backend.enums import SignalSourceProduct
from products.signals.backend.models import SignalReport, SignalReportRefund, SignalReportTask, SignalScoutRun
@@ -267,7 +269,7 @@ def refund_ineligibility_reason(
has_refund: bool,
billing_exempt: bool,
billable_run_at: datetime | None,
- period: tuple[datetime, datetime],
+ period: BillingPeriod,
) -> str | None:
"""Why a report can't be refunded right now, or None when a refund would be accepted.
@@ -281,8 +283,7 @@ def refund_ineligibility_reason(
return REFUND_INELIGIBLE_BILLING_EXEMPT
if billable_run_at is None:
return REFUND_INELIGIBLE_NO_BILLABLE_PR
- period_start, period_end = period
- if not (period_start <= billable_run_at < period_end):
+ if not (period.start <= billable_run_at < period.end):
return REFUND_INELIGIBLE_OUT_OF_PERIOD
return None
@@ -305,7 +306,7 @@ def credited_refund_credits_for_org(organization_id: str | uuid.UUID, begin: dat
)
-def current_billing_period_bounds(organization: "Organization") -> tuple[datetime, datetime]:
+def current_billing_period_bounds(organization: "Organization") -> BillingPeriod:
"""The org's current billing period `[start, end)`, falling back to the current UTC calendar
month when billing hasn't populated `organization.usage["period"]` (e.g. self-hosted or a
just-created org). Refund eligibility and the org-wide refund summary both key off this."""
@@ -314,7 +315,7 @@ def current_billing_period_bounds(organization: "Organization") -> tuple[datetim
return period
now = timezone.now()
start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
- return (start, start + relativedelta(months=1))
+ return BillingPeriod(start=start, end=start + relativedelta(months=1))
def get_signals_billing_credits_by_team(
@@ -387,8 +388,8 @@ def get_signals_billing_credits_by_team(
return list(totals.items())
-def period_billable_credits_for_org(organization_id: str | uuid.UUID, begin: datetime, end: datetime) -> int:
- """The org's billable signals credits for `[begin, end)` per the exact usage-report rules —
+def period_billable_credits_for_org(organization_id: str | uuid.UUID, *, period: BillingPeriod) -> int:
+ """The org's billable signals credits for `period` per the exact usage-report rules —
including PRs created today that haven't been reported to billing yet.
Powers the inbox usage widget's live PR count: the frontend takes the max of this and
@@ -397,5 +398,6 @@ def period_billable_credits_for_org(organization_id: str | uuid.UUID, begin: dat
refunds stay included here (usage is truthful) and are netted separately by the widget.
"""
return sum(
- credits for _, credits in get_signals_billing_credits_by_team(begin, end, organization_id=organization_id)
+ credits
+ for _, credits in get_signals_billing_credits_by_team(period.start, period.end, organization_id=organization_id)
)
diff --git a/products/signals/backend/implementation_pr.py b/products/signals/backend/implementation_pr.py
index d43edba24703..19a33599f704 100644
--- a/products/signals/backend/implementation_pr.py
+++ b/products/signals/backend/implementation_pr.py
@@ -106,19 +106,19 @@ def close_implementation_pr_for_report(
if parsed is None:
logger.warning("close_implementation_pr_unparseable_url", report_id=str(report_id), pr_url=pr_url)
return False
- owner, repo, pr_number = parsed
- repository = f"{owner}/{repo}"
- github = GitHubIntegration.first_for_team_repository(team_id, repository)
+ github = GitHubIntegration.first_for_team_repository(team_id, parsed.repository)
if github is None:
- logger.info("close_implementation_pr_no_integration", report_id=str(report_id), repository=repository)
+ logger.info(
+ "close_implementation_pr_no_integration", report_id=str(report_id), repository=parsed.repository
+ )
return False
# Only comment on and close a PR that's still open. A merged PR reports state "closed" with
# merged=True, and an already-closed PR reports state "closed" — in either case there's
# nothing to close, and leaving a comment would just be noise. If the state can't be
# confirmed, skip rather than risk commenting on a PR that already shipped.
- pr_status = github.get_pull_request(repository, pr_number)
+ pr_status = github.get_pull_request(parsed.repository, parsed.number)
if not pr_status.get("success"):
logger.warning(
"close_implementation_pr_status_fetch_failed",
@@ -139,7 +139,7 @@ def close_implementation_pr_for_report(
return False
# Explain first, close second — a failed comment shouldn't stop the close.
- comment_outcome = github.comment_on_pull_request(repository, pr_number, _PR_CLOSE_COMMENTS[reason])
+ comment_outcome = github.comment_on_pull_request(parsed.repository, parsed.number, _PR_CLOSE_COMMENTS[reason])
if not comment_outcome.get("success"):
logger.warning(
"close_implementation_pr_comment_failed",
@@ -149,7 +149,7 @@ def close_implementation_pr_for_report(
status_code=comment_outcome.get("status_code"),
)
- outcome = github.close_pull_request(repository, pr_number)
+ outcome = github.close_pull_request(parsed.repository, parsed.number)
if not outcome.get("success"):
logger.warning(
"close_implementation_pr_failed",
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index 8d0636cd00c1..6bbecd4ab720 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -13,6 +13,7 @@ from posthog.egress.github.transport import GitHubEgressBudgetExhausted, GitHubR
from posthog.event_usage import groups
from posthog.exceptions_capture import capture_exception
from posthog.models import Team
+from posthog.models.organization import BillingPeriod
from posthog.models.scoping import with_team_scope
from posthog.ph_client import ph_scoped_capture
from posthog.scoping_audit import skip_team_scope_audit
@@ -342,9 +343,9 @@ def sync_signals_refund_credit(self, refund_id: str) -> None:
# bounds here is exactly the drift that loses the credit. The fallback covers rows created
# before the bounds were snapshotted.
if refund.period_start is not None and refund.period_end is not None:
- period_start, period_end = refund.period_start, refund.period_end
+ period = BillingPeriod(start=refund.period_start, end=refund.period_end)
else:
- period_start, period_end = current_billing_period_bounds(organization)
+ period = current_billing_period_bounds(organization)
payload = {
"refund_id": str(refund.id),
"credits": refund.credits,
@@ -353,8 +354,8 @@ def sync_signals_refund_credit(self, refund_id: str) -> None:
"report_id": str(refund.report_id),
"pr_url": refund.pr_url,
"pr_run_created_at": refund.pr_run_created_at.isoformat(),
- "period_start": period_start.isoformat(),
- "period_end": period_end.isoformat(),
+ "period_start": period.start.isoformat(),
+ "period_end": period.end.isoformat(),
},
}
diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.py
index 289c72f7333f..663eff3950dc 100644
--- a/products/signals/backend/temporal/grouping.py
+++ b/products/signals/backend/temporal/grouping.py
@@ -680,15 +680,25 @@ class AssignAndEmitSignalOutput:
run_count: int
+@dataclass(frozen=True, kw_only=True, slots=True)
+class AssignAndEmitDbResult:
+ report_id: str
+ promoted: bool
+ timestamp: datetime
+ matched_deleted_report: bool
+ run_count: int
+ reresearch_capped: bool
+ report_status: str
+ report_signal_count: int
+
+
@temporalio.activity.defn
@scoped_temporal()
@close_db_connections
async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> AssignAndEmitSignalOutput:
match_result = input.match_result
- def do_assign_and_emit() -> tuple[str, bool, datetime, bool, int, bool, str, int]:
- """Returns (report_id, promoted, timestamp, matched_deleted_report, run_count,
- reresearch_capped, report_status, report_signal_count)."""
+ def do_assign_and_emit() -> AssignAndEmitDbResult:
with transaction.atomic():
promoted = False
@@ -729,7 +739,16 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As
timestamp=ts,
metadata=metadata,
)
- return report_id, False, ts, True, report.run_count, False, report.status, report.signal_count
+ return AssignAndEmitDbResult(
+ report_id=report_id,
+ promoted=False,
+ timestamp=ts,
+ matched_deleted_report=True,
+ run_count=report.run_count,
+ reresearch_capped=False,
+ report_status=report.status,
+ report_signal_count=report.signal_count,
+ )
# Resolved reports are terminal — never reopen them. When a signal would have grouped
# into an already-resolved report, the issue it fixed has recurred (or a related one
# has), so we start a fresh report and link it to the resolved report via a
@@ -828,43 +847,34 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As
timestamp=ts,
metadata=metadata,
)
- return (
- report_id,
- promoted,
- ts,
- False,
- report.run_count,
- reresearch_capped,
- report.status,
- report.signal_count,
+ return AssignAndEmitDbResult(
+ report_id=report_id,
+ promoted=promoted,
+ timestamp=ts,
+ matched_deleted_report=False,
+ run_count=report.run_count,
+ reresearch_capped=reresearch_capped,
+ report_status=report.status,
+ report_signal_count=report.signal_count,
)
try:
- (
- report_id,
- promoted,
- ts,
- matched_deleted,
- run_count,
- reresearch_capped,
- report_status,
- report_signal_count,
- ) = await database_sync_to_async(do_assign_and_emit, thread_sensitive=False)()
+ db_result = await database_sync_to_async(do_assign_and_emit, thread_sensitive=False)()
team = await Team.objects.select_related("organization").aget(pk=input.team_id)
# If we matched a deleted report, soft-delete all its stale signals in ClickHouse.
# This prevents data corruption where non-deleted signals for a deleted report
# keep attracting new signals into the dead group.
- if matched_deleted:
+ if db_result.matched_deleted_report:
await database_sync_to_async(soft_delete_report_signals, thread_sensitive=False)(
- report_id=report_id,
+ report_id=db_result.report_id,
team_id=input.team_id,
team=team,
)
logger.info(
"Soft-deleted stale signals for deleted report encountered during grouping",
- report_id=report_id,
+ report_id=db_result.report_id,
team_id=input.team_id,
signal_id=input.signal_id,
)
@@ -877,7 +887,7 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As
"source_product": input.source_product,
"source_type": input.source_type,
"source_id": input.source_id,
- "report_id": report_id,
+ "report_id": db_result.report_id,
},
groups=groups(team.organization, team),
)
@@ -885,7 +895,7 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As
posthoganalytics.capture_exception(e)
logger.exception(
"Failed to capture signal_matched_deleted_report event",
- report_id=report_id,
+ report_id=db_result.report_id,
team_id=input.team_id,
source_id=input.source_id,
)
@@ -898,9 +908,9 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As
"source_product": input.source_product,
"source_type": input.source_type,
"source_id": input.source_id,
- "report_id": report_id,
+ "report_id": db_result.report_id,
"is_new_report": isinstance(match_result, NewReportMatch),
- "promoted": promoted,
+ "promoted": db_result.promoted,
},
groups=groups(team.organization, team),
)
@@ -909,21 +919,21 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As
# Swallow the exception, to avoid breaking the flow over failed analytics event
logger.exception(
"Failed to capture signal_assigned_to_report event",
- report_id=report_id,
+ report_id=db_result.report_id,
team_id=input.team_id,
source_id=input.source_id,
)
# Over-cap signal on an already-researched report: assigned/emitted but no re-research
# spawned. Emitted so the saved re-research volume is trackable.
- if reresearch_capped:
+ if db_result.reresearch_capped:
try:
posthoganalytics.capture(
event="signal_report_reresearch_skipped",
distinct_id=str(team.uuid),
properties={
- "report_id": report_id,
- "signal_count": report_signal_count,
- "status": report_status,
+ "report_id": db_result.report_id,
+ "signal_count": db_result.report_signal_count,
+ "status": db_result.report_status,
"source_product": input.source_product,
"source_type": input.source_type,
"source_id": input.source_id,
@@ -935,25 +945,30 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As
posthoganalytics.capture_exception(e)
logger.exception(
"Failed to capture signal_report_reresearch_skipped event",
- report_id=report_id,
+ report_id=db_result.report_id,
team_id=input.team_id,
source_id=input.source_id,
)
- if not matched_deleted:
+ if not db_result.matched_deleted_report:
metrics.increment_funnel(metrics.FUNNEL_STAGE_GROUPED, input.source_product)
- if promoted:
+ if db_result.promoted:
metrics.increment_funnel(metrics.FUNNEL_STAGE_PROMOTED, input.source_product)
logger.debug(
- f"Assigned and emitted signal to report {report_id}",
- report_id=report_id,
+ f"Assigned and emitted signal to report {db_result.report_id}",
+ report_id=db_result.report_id,
team_id=input.team_id,
signal_id=input.signal_id,
- promoted=promoted,
+ promoted=db_result.promoted,
is_new_report=isinstance(match_result, NewReportMatch),
)
- return AssignAndEmitSignalOutput(report_id=report_id, promoted=promoted, timestamp=ts, run_count=run_count)
+ return AssignAndEmitSignalOutput(
+ report_id=db_result.report_id,
+ promoted=db_result.promoted,
+ timestamp=db_result.timestamp,
+ run_count=db_result.run_count,
+ )
except Exception as e:
logger.exception(
f"Failed to assign/emit signal: {e}",
diff --git a/products/signals/backend/temporal/parallel_grouping.py b/products/signals/backend/temporal/parallel_grouping.py
index 0712fac85034..f369ed1dc3b0 100644
--- a/products/signals/backend/temporal/parallel_grouping.py
+++ b/products/signals/backend/temporal/parallel_grouping.py
@@ -290,6 +290,15 @@ async def _process_signal_safe(
return None
+@dataclass(frozen=True, kw_only=True, slots=True)
+class ParallelBatchResult:
+ processed_signals: list[_ProcessedBatchSignal]
+ emitted_signals: list[tuple[str, AssignAndEmitSignalOutput]]
+ report_contexts: dict[str, ReportContext]
+ dropped_count: int
+ promoted_reports: dict[str, tuple[SignalReportSummaryWorkflowInputs, int]]
+
+
async def _process_parallel_batch(
batch_indices: list[int],
batch: list[EmitSignalInputs],
@@ -300,23 +309,13 @@ async def _process_parallel_batch(
signal_embeddings: list[list[float]],
processed_batch_signals: list[_ProcessedBatchSignal],
report_contexts: dict[str, ReportContext],
-) -> tuple[
- list[_ProcessedBatchSignal],
- list[tuple[str, AssignAndEmitSignalOutput]],
- dict[str, ReportContext],
- int,
- dict[str, tuple[SignalReportSummaryWorkflowInputs, int]],
-]:
+) -> ParallelBatchResult:
"""
Process a single parallel batch. All signals in batch_indices are processed
concurrently via asyncio.gather.
- Returns:
- - new_processed_signals: list of _ProcessedBatchSignal for successful signals
- - new_emitted_signals: list of (signal_id, AssignAndEmitSignalOutput)
- - updated report_contexts
- - dropped count
- - promoted_reports
+ Returns a ParallelBatchResult with the processed signals, emitted signals,
+ updated report_contexts, dropped count, and promoted reports.
"""
dropped = 0
new_processed_signals: list[_ProcessedBatchSignal] = []
@@ -396,7 +395,13 @@ async def _process_parallel_batch(
result.assign_result.run_count,
)
- return new_processed_signals, new_emitted_signals, report_contexts, dropped, promoted_reports
+ return ParallelBatchResult(
+ processed_signals=new_processed_signals,
+ emitted_signals=new_emitted_signals,
+ report_contexts=report_contexts,
+ dropped_count=dropped,
+ promoted_reports=promoted_reports,
+ )
async def process_sequential_phase_parallel(
@@ -446,7 +451,7 @@ async def process_sequential_phase_parallel(
accumulated_signals=len(all_processed_signals),
)
- new_processed, new_emitted, report_contexts, dropped, promoted = await _process_parallel_batch(
+ result = await _process_parallel_batch(
batch_indices=batch_indices,
batch=batch,
team_id=team_id,
@@ -458,10 +463,11 @@ async def process_sequential_phase_parallel(
report_contexts=report_contexts,
)
- all_processed_signals.extend(new_processed)
- all_emitted_signals.extend(new_emitted)
- all_promoted_reports.update(promoted)
- total_dropped += dropped
+ report_contexts = result.report_contexts
+ all_processed_signals.extend(result.processed_signals)
+ all_emitted_signals.extend(result.emitted_signals)
+ all_promoted_reports.update(result.promoted_reports)
+ total_dropped += result.dropped_count
return SequentialPhaseResult(
dropped=total_dropped,
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 7c3dcb32d6ba..97dddb30c6ed 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -2011,12 +2011,12 @@ class SignalReportViewSet(
# Computed once and frozen onto the refund row below: the credited-path sync must
# report the period the refund was accepted in, not whatever period is current when
# the Celery task eventually reaches billing.
- period_start, period_end = current_billing_period_bounds(self.organization)
+ period = current_billing_period_bounds(self.organization)
ineligibility = refund_ineligibility_reason(
has_refund=False, # the idempotent 200 above already handled existing refunds
billing_exempt=bool(report.billing_exempt_reason),
billable_run_at=billable_run.created_at if billable_run else None,
- period=(period_start, period_end),
+ period=period,
)
if ineligibility is not None:
return Response(
@@ -2054,8 +2054,8 @@ class SignalReportViewSet(
credits=SIGNALS_CREDITS_PER_REPORT_WITH_PR,
pr_url=billable_run.pr_url,
pr_run_created_at=billable_run.created_at,
- period_start=period_start,
- period_end=period_end,
+ period_start=period.start,
+ period_end=period.end,
)
except IntegrityError:
existing = SignalReportRefund.objects.filter(report_id=report.id).first()
@@ -2136,15 +2136,15 @@ class SignalReportViewSet(
if not self._signals_pr_refunds_enabled():
raise NotFound("PR refunds are not enabled for this organization.")
- period_start, period_end = current_billing_period_bounds(self.organization)
+ period = current_billing_period_bounds(self.organization)
aggregates = (
# Org-wide on purpose (unscoped + org filter): the usage this offsets is org-level.
SignalReportRefund.objects.unscoped()
.filter(
team__organization_id=self.organization.id,
billing_path=SignalReportRefund.BillingPath.CREDITED,
- pr_run_created_at__gte=period_start,
- pr_run_created_at__lt=period_end,
+ pr_run_created_at__gte=period.start,
+ pr_run_created_at__lt=period.end,
)
.aggregate(credited_refund_count=Count("id"), credited_credits=Sum("credits"))
)
@@ -2152,9 +2152,7 @@ class SignalReportViewSet(
{
"credited_refund_count": aggregates["credited_refund_count"] or 0,
"credited_credits": aggregates["credited_credits"] or 0,
- "period_billable_credits": period_billable_credits_for_org(
- self.organization.id, period_start, period_end
- ),
+ "period_billable_credits": period_billable_credits_for_org(self.organization.id, period=period),
}
)
@@ -2196,8 +2194,7 @@ class SignalReportViewSet(
parsed = GitHubIntegration.parse_pull_request_url(pr_url)
if parsed is None:
return None
- owner, repo, pr_number = parsed
- return f"{owner}/{repo}", pr_number
+ return parsed.repository, parsed.number
@extend_schema(
responses={
diff --git a/products/slack_app/backend/api.py b/products/slack_app/backend/api.py
index 16f225d3fea4..659c2f79f4e6 100644
--- a/products/slack_app/backend/api.py
+++ b/products/slack_app/backend/api.py
@@ -1590,27 +1590,35 @@ _ASSISTANT_MEMBER_JOIN_WELCOME = (
)
-def _assistant_event_fields(event: dict) -> tuple[str, str | None, str | None, str | None]:
- """(slack_user_id, dm_channel_id, thread_ts, viewed_channel_id) for assistant events.
+@dataclass(frozen=True, kw_only=True, slots=True)
+class AssistantEventFields:
+ slack_user_id: str
+ dm_channel_id: str | None
+ thread_ts: str | None
+ viewed_channel_id: str | None
+
+
+def _assistant_event_fields(event: dict) -> AssistantEventFields:
+ """Extract the assistant-surface fields for assistant events.
For `message` events the fields live at the top level; for `assistant_thread_*` events
they live under `assistant_thread` (with the viewed channel under `context`).
"""
if event.get("type") == "message":
ts = event.get("thread_ts") or event.get("ts")
- return (
- str(event.get("user") or ""),
- event.get("channel") if isinstance(event.get("channel"), str) else None,
- ts if isinstance(ts, str) else None,
- None,
+ return AssistantEventFields(
+ slack_user_id=str(event.get("user") or ""),
+ dm_channel_id=event.get("channel") if isinstance(event.get("channel"), str) else None,
+ thread_ts=ts if isinstance(ts, str) else None,
+ viewed_channel_id=None,
)
thread = event.get("assistant_thread") or {}
ctx = thread.get("context") or {}
- return (
- str(thread.get("user_id") or ""),
- thread.get("channel_id") if isinstance(thread.get("channel_id"), str) else None,
- thread.get("thread_ts") if isinstance(thread.get("thread_ts"), str) else None,
- ctx.get("channel_id") if isinstance(ctx.get("channel_id"), str) else None,
+ return AssistantEventFields(
+ slack_user_id=str(thread.get("user_id") or ""),
+ dm_channel_id=thread.get("channel_id") if isinstance(thread.get("channel_id"), str) else None,
+ thread_ts=thread.get("thread_ts") if isinstance(thread.get("thread_ts"), str) else None,
+ viewed_channel_id=ctx.get("channel_id") if isinstance(ctx.get("channel_id"), str) else None,
)
@@ -1715,7 +1723,7 @@ def _route_assistant_event(
) -> str:
"""Route DM / agent-container events through the same region + project resolution as mentions."""
event_type = event.get("type")
- slack_user_id, channel_id, thread_ts, ctx_channel = _assistant_event_fields(event)
+ fields = _assistant_event_fields(event)
# Only first-party human DMs proceed — ignore channel messages, bot echoes, and edits.
if event_type == "message" and (
@@ -1725,16 +1733,16 @@ def _route_assistant_event(
or not str(event.get("text") or "").strip()
):
return ROUTE_HANDLED_LOCALLY
- if not (slack_user_id and channel_id and thread_ts):
+ if not (fields.slack_user_id and fields.dm_channel_id and fields.thread_ts):
return ROUTE_HANDLED_LOCALLY
result = load_integrations(
slack_team_id=slack_team_id,
kinds=[SLACK_INTEGRATION_KIND],
- slack_user_id=slack_user_id,
+ slack_user_id=fields.slack_user_id,
user=None,
- channel=channel_id,
- thread_ts=thread_ts,
+ channel=fields.dm_channel_id,
+ thread_ts=fields.thread_ts,
)
region_route = resolve_region_or_terminal_route(
request,
@@ -1760,20 +1768,20 @@ def _route_assistant_event(
resolution = resolve_user_for_workspace(
workspace_result=result,
slack_team_id=slack_team_id,
- slack_user_id=slack_user_id,
+ slack_user_id=fields.slack_user_id,
event_id=event_id,
)
if resolution.user is None:
# Flag is on but the Slack user isn't a resolvable org member — tell them why (DMs only).
if event_type == "message":
- _post_assistant_unavailable(SlackIntegration(probe), channel_id, thread_ts)
+ _post_assistant_unavailable(SlackIntegration(probe), fields.dm_channel_id, fields.thread_ts)
return ROUTE_HANDLED_LOCALLY
posthog_user = resolution.user
if event_type == "assistant_thread_started":
- return _handle_assistant_thread_started(SlackIntegration(probe), channel_id, thread_ts)
+ return _handle_assistant_thread_started(SlackIntegration(probe), fields.dm_channel_id, fields.thread_ts)
if event_type == "assistant_thread_context_changed":
- _store_assistant_channel_context(probe.id, channel_id, thread_ts, ctx_channel)
+ _store_assistant_channel_context(probe.id, fields.dm_channel_id, fields.thread_ts, fields.viewed_channel_id)
return ROUTE_HANDLED_LOCALLY
# message.im — run the agent against the user's accessible default project, else ask them to pick.
@@ -1783,7 +1791,13 @@ def _route_assistant_event(
_post_pick_a_project_hint(SlackIntegration(accessible[0]), accessible, event)
return ROUTE_HANDLED_LOCALLY
return _handle_assistant_dm_message(
- event, mention_target, slack_team_id, event_id, channel_id, thread_ts, posthog_user=posthog_user
+ event,
+ mention_target,
+ slack_team_id,
+ event_id,
+ fields.dm_channel_id,
+ fields.thread_ts,
+ posthog_user=posthog_user,
)