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.

6.9 KB
Raw Blame
import json
from datetime import datetime, timedelta
from uuid import UUID

from posthog.schema import DateRange, ErrorTrackingOrderBy, ErrorTrackingQuery

from posthog.hogql_queries.query_runner import get_query_runner
from posthog.models import Team, User
from posthog.sync import database_sync_to_async

from products.error_tracking.backend.facade import (
    api as error_tracking_api,
    contracts as error_tracking_contracts,
)

from .prompts import ERROR_TRACKING_ISSUE_CONTEXT_TEMPLATE


class ErrorTrackingIssueContext:
    """
    Context class for error tracking issues used across the assistant.

    Provides methods to fetch issue data and format it for AI consumption.
    This class is used by the ReadDataTool to provide issue context without
    invoking nested LLM calls.
    """

    def __init__(
        self,
        team: Team,
        user: User,
        issue_id: str,
        issue_name: str | None = None,
    ):
        self._team = team
        self._user = user
        self._issue_id = issue_id
        self._issue_name = issue_name

    def _get_issue_sync(self) -> error_tracking_contracts.ErrorTrackingIssue | None:
        try:
            issue_id = UUID(self._issue_id)
        except ValueError:
            return None

        try:
            return error_tracking_api.get_issue(issue_id=issue_id, team_id=self._team.id)
        except error_tracking_api.IssueNotFoundError:
            return None

    async def aget_issue(self) -> error_tracking_contracts.ErrorTrackingIssue | None:
        """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, 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, 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=date_range,
            orderBy=ErrorTrackingOrderBy.FIRST_SEEN,
            limit=1,
            volumeResolution=1,
            withAggregations=False,
            withFirstEvent=True,
            withLastEvent=False,
        )

        runner = get_query_runner(query, self._team, user=self._user)
        result = runner.calculate()

        if result.results and len(result.results) > 0:
            first_result = result.results[0]
            if hasattr(first_result, "model_dump"):
                first_result = first_result.model_dump()
            if isinstance(first_result, dict):
                return first_result.get("first_event")
            return None

        return None

    def format_stacktrace(self, event: dict | None) -> str | None:
        """Format the exception list into a readable stack trace string."""
        if not event:
            return None

        properties = event.get("properties", {})
        if isinstance(properties, str):
            try:
                properties = json.loads(properties)
            except json.JSONDecodeError:
                return None
        exception_list = properties.get("$exception_list", [])

        if not exception_list:
            return None

        lines: list[str] = []

        for i, exception in enumerate(exception_list):
            exc_type = exception.get("type", "Unknown")
            exc_value = exception.get("value", "")

            lines.append(f"Exception {i + 1}: {exc_type}")
            if exc_value:
                lines.append(f"Message: {exc_value}")
            lines.append("")

            stacktrace = exception.get("stacktrace", {})
            frames = stacktrace.get("frames", []) if stacktrace else []

            if frames:
                lines.append("Stack trace (most recent call last):")
                for frame in reversed(frames):
                    in_app = frame.get("in_app", False)
                    marker = "[IN-APP]" if in_app else ""

                    filename = frame.get("source", "unknown")
                    lineno = frame.get("line", "?")
                    colno = frame.get("column")
                    function = frame.get("resolved_name") or frame.get("mangled_name") or "<unknown>"

                    location = f"{filename}:{lineno}"
                    if colno:
                        location += f":{colno}"

                    lines.append(f"  {marker} at {function} ({location})")

                    context_line = frame.get("context_line")
                    if context_line:
                        lines.append(f"       > {context_line.strip()}")

                lines.append("")

        return "\n".join(lines) if lines else None

    async def execute_and_format(self) -> str:
        """
        Execute the context gathering and format results for AI consumption.

        Returns a formatted string with all issue context including stacktrace.
        """
        issue = await self.aget_issue()
        if issue is None:
            return f"Error tracking issue with ID '{self._issue_id}' not found."

        issue_name = self._issue_name or issue.name or f"Issue {self._issue_id}"

        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."

        stacktrace = self.format_stacktrace(first_event)
        if not stacktrace:
            return f"No stack trace available for issue '{issue_name}'."

        return ERROR_TRACKING_ISSUE_CONTEXT_TEMPLATE.format(
            issue_id=self._issue_id,
            issue_name=issue_name,
            issue_status=issue.status,
            issue_description=issue.description or "No description available.",
            stacktrace=stacktrace,
        )