:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(max): scan a narrow window around first_seen for issue stack traces (#64664)
Catalin Irimieccf24dbbb2c9
diff --git a/ee/hogai/context/error_tracking/context.py b/ee/hogai/context/error_tracking/context.pyindex d791a0a558a4..efef6d2ec0ca 100644--- a/ee/hogai/context/error_tracking/context.py+++ b/ee/hogai/context/error_tracking/context.py@@ -1,4 +1,5 @@import json+from datetime import datetime, timedeltafrom uuid import UUIDfrom posthog.schema import DateRange, ErrorTrackingOrderBy, ErrorTrackingQuery@@ -49,16 +50,36 @@ class ErrorTrackingIssueContext:"""Fetch the issue from the error tracking facade using async."""return await database_sync_to_async(self._get_issue_sync)()- async def aget_first_event(self) -> dict | None:- """Fetch the first event for the issue to get stack trace data."""- return await database_sync_to_async(self._get_first_event_sync)()+ async def aget_first_event(self, first_seen: datetime | None = None) -> dict | None:+ """Fetch a representative early event for the issue to get stack trace data."""+ return await database_sync_to_async(self._get_first_event_sync)(first_seen)- def _get_first_event_sync(self) -> dict | None:- """Synchronous implementation of get_first_event."""+ def _get_first_event_sync(self, first_seen: datetime | None = None) -> dict | None:+ """Fetch an early event for the issue (for stack-trace context, not a precise audit).++ Fetching the event reads its full properties blob, so scan a narrow ±1h window+ around first_seen instead of all time. This returns the earliest event *within the+ window*; if first_seen is import/ingestion-skewed away from the event timestamps an+ even-earlier event could sit outside it, but any event this close to first_seen is an+ equally good stack trace for the assistant. Only when the window is empty do we fall+ back to the full history so a stack trace is still surfaced.+ """+ if first_seen is not None:+ event = self._query_first_event(+ DateRange(+ date_from=(first_seen - timedelta(hours=1)).isoformat(),+ date_to=(first_seen + timedelta(hours=1)).isoformat(),+ )+ )+ if event is not None:+ return event+ return self._query_first_event(DateRange(date_from="all"))++ def _query_first_event(self, date_range: DateRange) -> dict | None:query = ErrorTrackingQuery(kind="ErrorTrackingQuery",issueId=self._issue_id,- dateRange=DateRange(date_from="all"),+ dateRange=date_range,orderBy=ErrorTrackingOrderBy.FIRST_SEEN,limit=1,volumeResolution=1,@@ -147,7 +168,7 @@ class ErrorTrackingIssueContext:issue_name = self._issue_name or issue.name or f"Issue {self._issue_id}"- first_event = await self.aget_first_event()+ first_event = await self.aget_first_event(issue.first_seen)if first_event is None:return f"No events found for issue '{issue_name}'. Cannot provide stack trace data."diff --git a/ee/hogai/context/error_tracking/test/test_context.py b/ee/hogai/context/error_tracking/test/test_context.pyindex 8ea8a1e66030..40e5aa6f1ee3 100644--- a/ee/hogai/context/error_tracking/test/test_context.py+++ b/ee/hogai/context/error_tracking/test/test_context.py@@ -124,6 +124,43 @@ class TestErrorTrackingIssueContext(ClickhouseTestMixin, APIBaseTest):self.assertIsNone(issue)+ @patch.object(ErrorTrackingIssueContext, "_query_first_event")+ async def test_first_event_window_hit_skips_fallback(self, mock_query):+ mock_query.return_value = {"properties": {"$exception_list": []}}+ context = self._create_context(self.issue_id_one)+ first_seen = now() - relativedelta(hours=3)++ event = await context.aget_first_event(first_seen)++ self.assertIsNotNone(event)+ # Window hit → only the narrow ±1h lookup runs, no full-history fallback.+ self.assertEqual(mock_query.call_count, 1)+ window = mock_query.call_args.args[0]+ self.assertEqual(window.date_from, (first_seen - relativedelta(hours=1)).isoformat())+ self.assertEqual(window.date_to, (first_seen + relativedelta(hours=1)).isoformat())++ @patch.object(ErrorTrackingIssueContext, "_query_first_event")+ async def test_first_event_falls_back_to_all_time_when_window_misses(self, mock_query):+ mock_query.side_effect = [None, {"properties": {"$exception_list": []}}]+ context = self._create_context(self.issue_id_one)++ event = await context.aget_first_event(now() - relativedelta(hours=3))++ self.assertIsNotNone(event)+ # Window missed → second lookup spans the full history.+ self.assertEqual(mock_query.call_count, 2)+ self.assertEqual(mock_query.call_args_list[1].args[0].date_from, "all")++ @patch.object(ErrorTrackingIssueContext, "_query_first_event")+ async def test_first_event_without_first_seen_uses_all_time(self, mock_query):+ mock_query.return_value = {"properties": {"$exception_list": []}}+ context = self._create_context(self.issue_id_one)++ await context.aget_first_event(None)++ self.assertEqual(mock_query.call_count, 1)+ self.assertEqual(mock_query.call_args.args[0].date_from, "all")+async def test_format_stacktrace_correctly(self):context = self._create_context(self.issue_id_one)