: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
feat(aio): link the trace git branch to its pull request (#124373)
Carlos Marchala6fb09efa5f5
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 3975b426b985..f92164cdd950 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -9858,6 +9858,10 @@ snapshots:hash: v1.k794b7964.f48c22bbab5113e9ef6290dad04daae1285be7f8932d41fa8ace16ace664e502.oxJblySth_77826dzwFkmd_PGo7EfwpvdJx8GlFzrgwscenes-app-ai-observability-trace-view-trace-summary-bar--with-git-branch--light:hash: v1.k794b7964.f6e85ad3ddc7ab047875da5570247b6bab1038c36f5ec2bd3d6be709296f9595.Z2RX9IwREaeGSEESRc0k_qVZIf3cwVzLtss3gO9CGh0+ scenes-app-ai-observability-trace-view-trace-summary-bar--with-git-pull-request--dark:+ hash: v1.k794b7964.3898a78f0ae1df05d168f0bd5141ff00fe86ab527d56a1265e1b8b807c6cec80.RG2f4f9FNB5YlMKxZmBFQoraqFGMBj-h_7iTIU2lYxY+ scenes-app-ai-observability-trace-view-trace-summary-bar--with-git-pull-request--light:+ hash: v1.k794b7964.eaf79306fee6ddfb770c8ed6216b5c1fb405266fc380226a8797c451c71f9b2e.uho7yUBTzgiIlwOnKbWiACUZCzRDUWv2Yic_unklIswscenes-app-ai-observability-trace-view-trace-summary-bar--with-thumbs-feedback--dark:hash: v1.k794b7964.7362a5c721272d156b1af5133afcdd78e0672d8336d622d54deaf29226d0d699.1p5tXtQY1JGCciuOqhrEfLLBXzdiFwOJv__OVCg0Cvoscenes-app-ai-observability-trace-view-trace-summary-bar--with-thumbs-feedback--light:diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.tsindex 38863a07b555..97c0e599b9f2 100644--- a/frontend/src/initKea.ts+++ b/frontend/src/initKea.ts@@ -143,6 +143,7 @@ const ERROR_FILTER_ALLOW_LIST_BY_LOGIC_PATH: Record<string, string> = {// The trace view's Summary mode shows the errorloadSummary: 'products.ai_observability.frontend.redesign.trace.traceSummaryLogic',requestSummary: 'products.ai_observability.frontend.redesign.trace.traceSummaryLogic',+ loadTracePullRequest: 'products.ai_observability.frontend.redesign.trace.traceGitPullRequestLogic', // The trace view's git chip stays plain when the read fails}// A keyed logic's path ends with its key, so match the owner path as a prefix.diff --git a/products/ai_observability/backend/facade/api.py b/products/ai_observability/backend/facade/api.pyindex cb9cdc72aef7..0356bd70d663 100644--- a/products/ai_observability/backend/facade/api.py+++ b/products/ai_observability/backend/facade/api.py@@ -1,11 +1,14 @@from collections.abc import Sequencefrom datetime import date, datetime+from typing import TYPE_CHECKINGfrom posthog.schema import HogQLPropertyFilterfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Team, User+from products.engineering_analytics.backend.facade import api as engineering_analytics_api+from products.engineering_analytics.backend.facade.contracts import BranchPRMatch, GitHubSourceNotConnectedErrorfrom products.surveys.backend.facade.api import (LinkedSurveyAnswer,LinkedSurveyResponse,@@ -52,6 +55,7 @@ from ..logic.traces.trace import Tracefrom ..logic.traces.trace_queries import (load_trace,load_trace_feedback_rows,+ load_trace_git_rows,load_trace_node,load_trace_root,load_trace_search,@@ -62,6 +66,9 @@ from ..logic.traces.usage import Usagefrom ..temporal.trace_summary_client import start_trace_summaryfrom . import contracts+if TYPE_CHECKING:+ from products.access_control.backend.facade.user_access_control import UserAccessControl+class TraceNotFoundError(Exception):pass@@ -415,6 +422,36 @@ def _to_evaluation_summary(summary: EvaluationSummary) -> contracts.TraceEvaluat)+def get_trace_pull_request(+ team: Team,+ user: User | None,+ user_access_control: "UserAccessControl | None",+ trace_id: str,+ timestamp_hint: datetime | None,+) -> contracts.TracePullRequestLookup:+ ref = GitRef.from_rows(load_trace_git_rows(team, user, trace_id, timestamp_hint))+ # A default branch is the head of unrelated pull requests, such as fork and release ones, so it links to none.+ if ref is None or ref.is_default_branch:+ return contracts.TracePullRequestLookup(pull_request=None)+ try:+ matches = engineering_analytics_api.resolve_branch(+ team=team,+ branch=ref.branch,+ repo=ref.repo,+ timestamp=ref.seen_at,+ user_access_control=user_access_control,+ )+ # The repo stamp comes from an SDK, so a value that is not owner/name reads as no match, not a failure.+ except (GitHubSourceNotConnectedError, ValueError):+ return contracts.TracePullRequestLookup(pull_request=None)+ return contracts.TracePullRequestLookup(pull_request=_to_pull_request(matches[0]) if matches else None)+++def _to_pull_request(match: BranchPRMatch) -> contracts.TracePullRequest:+ owner, _, name = match.repo.partition("/")+ return contracts.TracePullRequest(repo_owner=owner, repo_name=name, number=match.number, title=match.title)++def evaluations_period(team: Team, date_from: date | datetime | None, date_to: date | datetime | None) -> PeriodBounds:"""Raises `InvalidPeriodError` for a period that is empty, longer than 91 days or out of range."""return PeriodBounds.from_request(date_from, date_to, team.timezone_info)diff --git a/products/ai_observability/backend/facade/contracts.py b/products/ai_observability/backend/facade/contracts.pyindex 59c1461ffe2e..ade1f3510e3a 100644--- a/products/ai_observability/backend/facade/contracts.py+++ b/products/ai_observability/backend/facade/contracts.py@@ -364,6 +364,20 @@ class TraceSummaryRun:groups: dict[str, str]+class TracePullRequest(Contract):+ repo_owner: str = Field(description="The owner of the pull request's repository.")+ repo_name: str = Field(description="The name of the pull request's repository.")+ number: int = Field(description="The pull request number.")+ title: str | None = Field(description="The pull request title, or null when the synced data has none.")+++class TracePullRequestLookup(Contract):+ pull_request: TracePullRequest | None = Field(+ description="The pull request the trace's git branch belongs to, ranked by engineering analytics, or null "+ "when the trace has no branch, the project has no GitHub source, or no pull request matches."+ )++AttentionReason = Literal["errored", "silent", "worse"]BucketStatus = Literal["none", "dip", "normal"]Interval = Literal["hour", "day"]diff --git a/products/ai_observability/backend/logic/traces/git.py b/products/ai_observability/backend/logic/traces/git.pyindex 4ca5606cdac7..8710b748e56b 100644--- a/products/ai_observability/backend/logic/traces/git.py+++ b/products/ai_observability/backend/logic/traces/git.py@@ -1,17 +1,25 @@from collections.abc import Iterablefrom datetime import datetime-from typing import TYPE_CHECKING, Self+from typing import Protocol, Selffrom posthog.dataclasses import frozen-if TYPE_CHECKING:- from .trace_queries import TraceEventRow-# The repo's real default branch is not known here, so these two names stand in for it._DEFAULT_BRANCHES = frozenset({"main", "master"})-def _stamp_order(row: "TraceEventRow") -> tuple[datetime, str]:+class GitStamp(Protocol):+ @property+ def uuid(self) -> str: ...+ @property+ def timestamp(self) -> datetime: ...+ @property+ def git_branch(self) -> str | None: ...+ @property+ def git_repo(self) -> str | None: ...+++def _stamp_order(row: GitStamp) -> tuple[datetime, str]:# Ties break on the uuid so every read of the same rows picks the same event.return (row.timestamp, row.uuid)@@ -22,8 +30,12 @@ class GitRef:repo: str | Noneseen_at: datetime+ @property+ def is_default_branch(self) -> bool:+ return self.branch in _DEFAULT_BRANCHES+@classmethod- def from_rows(cls, rows: Iterable["TraceEventRow"]) -> Self | None:+ def from_rows(cls, rows: Iterable[GitStamp]) -> Self | None:"""The branch the trace's work ran on. A coding agent often starts on the default branch and creates thefeature branch during the trace, so the latest stamp on another branch wins. A trace that never leaves thedefault branch keeps its first stamp."""diff --git a/products/ai_observability/backend/logic/traces/trace_queries.py b/products/ai_observability/backend/logic/traces/trace_queries.pyindex 2d7ef41fdf9b..4c6666ae71e9 100644--- a/products/ai_observability/backend/logic/traces/trace_queries.py+++ b/products/ai_observability/backend/logic/traces/trace_queries.py@@ -67,6 +67,14 @@ class TraceEventRow:git_repo: str | None+@frozen+class GitStampRow:+ uuid: str+ timestamp: datetime+ git_branch: str | None+ git_repo: str | None++@frozenclass PersonRow:distinct_id: str@@ -169,9 +177,9 @@ def _filter_conditions() -> ast.Placeholder:return ast.Placeholder(expr=ast.Field(chain=["filter_conditions"]))-def _trace_rows_query() -> ast.SelectQuery:+def _trace_rows_query(columns: Sequence[str] = tuple(_SELECTED)) -> ast.SelectQuery:return ast.SelectQuery(- select=_select(),+ select=_select({column: _SELECTED[column] for column in columns}),select_from=_ai_events(),where=ast.And(exprs=[_event_in(TRACE_EVENT_NAMES), _filter_conditions()]),order_by=[ast.OrderExpr(expr=ast.Field(chain=["timestamp"]), order="ASC")],@@ -180,6 +188,19 @@ def _trace_rows_query() -> ast.SelectQuery:)+def _git_stamps_query() -> ast.SelectQuery:+ # The stamps come from the same first events load_trace reads, so the chip and its pull request agree on a trace+ # longer than MAX_TRACE_EVENTS.+ columns = ("uuid", "timestamp", "git_branch", "git_repo")+ # HogQL makes `!=` true for NULL, so a missing branch is folded into the empty string first.+ branch = ast.Call(name="ifNull", args=[ast.Field(chain=["git_branch"]), ast.Constant(value="")])+ return ast.SelectQuery(+ select=[ast.Field(chain=[column]) for column in columns],+ select_from=ast.JoinExpr(table=_trace_rows_query(columns)),+ where=ast.Call(name="notEmpty", args=[branch]),+ )++def _node_query(selection: ast.Expr) -> ast.SelectQuery:return ast.SelectQuery(select=[ast.Field(chain=[column]) for column in _NODE_COLUMNS],@@ -647,3 +668,14 @@ def load_trace_search(if match_count:counts[row.uuid] = int(match_count)return LoadedTraceSearch(rows=tuple(rows), counts=counts)+++def load_trace_git_rows(+ team: Team, user: User | None, trace_id: str, timestamp_hint: datetime | None+) -> tuple[GitStampRow, ...]:+ return tuple(+ GitStampRow(uuid=str(uuid), timestamp=timestamp, git_branch=read_text(branch), git_repo=read_text(repo))+ for uuid, timestamp, branch, repo in _read_trace(+ "ai_trace_git", _git_stamps_query, team, user, trace_id, timestamp_hint, widen_unhinted=False+ )+ )diff --git a/products/ai_observability/backend/presentation/views.py b/products/ai_observability/backend/presentation/views.pyindex cf86aef4746f..2271727a4473 100644--- a/products/ai_observability/backend/presentation/views.py+++ b/products/ai_observability/backend/presentation/views.py@@ -14,7 +14,7 @@ from posthog.api.mixins import ValidatedRequest, validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.clickhouse.query_tagging import Feature, tag_queriesfrom posthog.models.user import User-from posthog.permissions import get_authenticator_scopes+from posthog.permissions import PostHogFeatureFlagPermission, get_authenticator_scopesfrom posthog.rate_limit import (AIObservabilitySummarizationBurstThrottle,AIObservabilitySummarizationDailyThrottle,@@ -22,6 +22,8 @@ from posthog.rate_limit import ()from posthog.scopes import scopes_not_covered+from products.engineering_analytics.backend.facade.contracts import ENGINEERING_ANALYTICS_FEATURE_FLAG+from ..facade import api, contractsfrom .query_concurrency import query_concurrency_slotsfrom .trace_ids import MalformedTraceIdSegmentError, decode_trace_id_segment@@ -93,6 +95,9 @@ class TraceViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):# Traces are project-wide data, so a grant on a single llm_analytics object must not open them.requires_resource_level_access = Trueserializer_class = _FallbackSerializer+ permission_classes = [PostHogFeatureFlagPermission]+ # Other actions are absent from the map, so the permission lets them through.+ posthog_feature_flag = {ENGINEERING_ANALYTICS_FEATURE_FLAG: ["pull_request"]}def _read[T](self, request: ValidatedRequest, read: Callable[[User | None, datetime | None], T]) -> T:tag_queries(feature=Feature.QUERY)@@ -331,3 +336,34 @@ class TraceViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):return Response({"detail": "No summary yet."}, status=status.HTTP_404_NOT_FOUND)response_status = pending_status if summary.status == "pending" else status.HTTP_200_OKreturn Response(summary.model_dump(mode="json", by_alias=True), status=response_status)++ @validated_request(+ query_serializer=TraceQuerySerializer,+ parameters=[TRACE_ID_PARAMETER],+ responses={+ 200: OpenApiResponse(response=contracts.TracePullRequestLookup),+ 400: OpenApiResponse(description="The timestamp hint or the encoded trace id is malformed."),+ 403: OpenApiResponse(+ description="The engineering-analytics feature flag is off for the project, or the API key lacks a scope."+ ),+ 429: THROTTLED_RESPONSE,+ },+ operation_id="ai_observability_traces_pull_request_retrieve",+ )+ @action(+ detail=True,+ methods=["GET"],+ # The read opens engineering analytics data, so a key needs that product's scope as well.+ required_scopes=["llm_analytics:read", "engineering_analytics:read"],+ )+ def pull_request(self, request: ValidatedRequest, pk: str, **kwargs: Any) -> Response:+ """The pull request the trace's git branch belongs to, from engineering analytics."""+ try:+ trace_id = decode_trace_id_segment(pk)+ except MalformedTraceIdSegmentError:+ return Response({"detail": "Malformed encoded trace id."}, status=status.HTTP_400_BAD_REQUEST)+ lookup = self._read(+ request,+ lambda user, hint: api.get_trace_pull_request(self.team, user, self.user_access_control, trace_id, hint),+ )+ return Response(lookup.model_dump(mode="json", by_alias=True))diff --git a/products/ai_observability/backend/tests/logic/traces/test_trace_queries.py b/products/ai_observability/backend/tests/logic/traces/test_trace_queries.pyindex f627a28d9f88..ae039249bac6 100644--- a/products/ai_observability/backend/tests/logic/traces/test_trace_queries.py+++ b/products/ai_observability/backend/tests/logic/traces/test_trace_queries.py@@ -2,6 +2,7 @@ import jsonfrom datetime import UTC, datetime, timedeltafrom posthog.test.base import BaseTest, ClickhouseTestMixin, _create_person+from unittest.mock import patchfrom parameterized import parameterized@@ -11,12 +12,15 @@ from posthog.models.ai_events.sql import AI_EVENTS_MV_SQLfrom posthog.models.ai_events.test_util import bulk_create_ai_eventsfrom posthog.models.event.util import bulk_create_events+from products.ai_observability.backend.logic.traces import trace_queriesfrom products.ai_observability.backend.logic.traces.trace_queries import (+ GitStampRow,SearchNeedles,TraceRootLookup,is_truthy_json,load_trace,load_trace_feedback_rows,+ load_trace_git_rows,load_trace_node,load_trace_root,load_trace_search,@@ -315,6 +319,41 @@ class TestLoadTraceNode(TraceEventsMixin, ClickhouseTestMixin, BaseTest):assert row is not None and row.uuid == NODE+class TestLoadTraceGitRows(TraceEventsMixin, ClickhouseTestMixin, BaseTest):+ def test_reads_only_this_traces_stamped_events(self) -> None:+ stamped = "00000000-0000-0000-0000-000000000001"+ bulk_create_ai_events(+ [+ self._event(stamped, properties={"$ai_git_branch": "feat/rag"}),+ self._event("00000000-0000-0000-0000-000000000002"),+ self._event("00000000-0000-0000-0000-000000000003", properties={"$ai_git_branch": ""}),+ self._event(+ "00000000-0000-0000-0000-000000000004", trace_id="other", properties={"$ai_git_branch": "feat/x"}+ ),+ ]+ )++ assert [row.uuid for row in load_trace_git_rows(self.team, None, "trace-1", T0)] == [stamped]++ def test_reads_stamps_only_from_the_events_the_trace_loads(self) -> None:+ bulk_create_ai_events(+ [+ self._event(NODE, properties={"$ai_git_branch": "feat/one", "$ai_git_repo": "acme/app"}),+ self._event("00000000-0000-0000-0000-000000000002", timestamp=T0 + timedelta(seconds=1)),+ self._event(+ "00000000-0000-0000-0000-000000000003",+ timestamp=T0 + timedelta(seconds=2),+ properties={"$ai_git_branch": "feat/two"},+ ),+ ]+ )++ with patch.object(trace_queries, "MAX_TRACE_EVENTS", 2):+ rows = load_trace_git_rows(self.team, None, "trace-1", T0)++ assert rows == (GitStampRow(uuid=NODE, timestamp=T0, git_branch="feat/one", git_repo="acme/app"),)++class TestEventsFallback(TraceEventsMixin, ClickhouseTestMixin, BaseTest):@parameterized.expand([("with a hint", T0), ("without a hint", None)])def test_falls_back_to_events(self, _name: str, timestamp_hint: datetime | None) -> None:@@ -352,19 +391,21 @@ class TestEventsFallback(TraceEventsMixin, ClickhouseTestMixin, BaseTest):assert load_trace(self.team, None, "trace-1", None).rows == ()- def test_node_and_root_fall_back_to_events(self) -> None:+ def test_point_reads_fall_back_to_events(self) -> None:bulk_create_events([- self._event(NODE, properties={"$ai_span_name": "old"}),+ self._event(NODE, properties={"$ai_span_name": "old", "$ai_git_branch": "feat/rag"}),self._event(TRACE_EVENT, event="$ai_trace", timestamp=T0 + timedelta(seconds=1)),])row = load_trace_node(self.team, None, "trace-1", NODE, T0)root = load_trace_root(self.team, None, "trace-1", T0)+ git_rows = load_trace_git_rows(self.team, None, "trace-1", T0)assert row is not None and row.properties["$ai_span_name"] == "old"assert root.trace_event is not None and root.trace_event.uuid == TRACE_EVENT+ assert [(git_row.uuid, git_row.git_branch) for git_row in git_rows] == [(NODE, "feat/rag")]@parameterized.expand([("with a hint", T0, 1), ("without a hint", None, 0)])def test_feedback_falls_back_to_events_only_with_a_hint(@@ -382,11 +423,17 @@ class TestEventsFallback(TraceEventsMixin, ClickhouseTestMixin, BaseTest):assert [(row.metric_name, row.metric_value_json) for row in rows] == [("helpfulness", "0")] * expected- def test_node_and_root_without_a_hint_never_scan_events(self) -> None:- bulk_create_events([self._event(NODE), self._event(TRACE_EVENT, event="$ai_trace")])+ def test_point_reads_without_a_hint_never_scan_events(self) -> None:+ bulk_create_events(+ [+ self._event(NODE, properties={"$ai_git_branch": "feat/rag"}),+ self._event(TRACE_EVENT, event="$ai_trace"),+ ]+ )assert load_trace_node(self.team, None, "trace-1", NODE, None) is Noneassert load_trace_root(self.team, None, "trace-1", None) == TraceRootLookup(trace_event=None, trace_found=False)+ assert load_trace_git_rows(self.team, None, "trace-1", None) == ()def test_search_falls_back_to_events_with_a_hint_only(self) -> None:bulk_create_events([self._event(NODE, properties={"$ai_span_name": "Fetch invoice"})])diff --git a/products/ai_observability/backend/tests/test_facade_api.py b/products/ai_observability/backend/tests/test_facade_api.pyindex 69f3e9566ead..98c2f0562813 100644--- a/products/ai_observability/backend/tests/test_facade_api.py+++ b/products/ai_observability/backend/tests/test_facade_api.py@@ -3,7 +3,7 @@ from datetime import UTC, datetime, timedeltaimport pytestfrom posthog.test.base import BaseTest, ClickhouseTestMixin-from unittest.mock import call, patch+from unittest.mock import MagicMock, call, patchfrom parameterized import parameterized@@ -28,8 +28,10 @@ from products.ai_observability.backend.logic.traces.summary_store import (summary_key,write_summary,)-from products.ai_observability.backend.logic.traces.trace_queries import FeedbackEventRow, LoadedTrace+from products.ai_observability.backend.logic.traces.trace_queries import FeedbackEventRow, LoadedTrace, TraceEventRowfrom products.ai_observability.backend.models.evaluations import Evaluation+from products.engineering_analytics.backend.facade import api as engineering_analytics_api+from products.engineering_analytics.backend.facade.contracts import BranchPRMatch, GitHubSourceNotConnectedErrorfrom products.event_definitions.backend.models.property_definition import PropertyDefinitionfrom products.surveys.backend.facade.api import (LinkedSurveyAnswer,@@ -51,6 +53,11 @@ from .logic.traces.rows import (from .property_access import hide_event_propertyT0 = datetime(2026, 9, 1, 10, 0, tzinfo=UTC)+TEAM = object()+ACCESS = object()+T1 = T0 + timedelta(seconds=30)+STAMPED = (make_row(uuid="gen-uuid", git_branch="feat/rag", git_repo="acme/app", timestamp=T1),)+ANSWER_BILLING = BranchPRMatch(repo="acme/app", number=42, title="Answer billing questions", state="open")READY_SUMMARY = ReadySummary(title="Refund request",bullets=(SummaryItem(text="The user asks for a refund.", node_id="gen-1"),),@@ -506,3 +513,65 @@ class TestTraceSummary(BaseTest):with pytest.raises(api.AIDataProcessingNotApprovedError):self._request(regenerate=True)assert self.jobs == []+++class TestGetTracePullRequest:+ def _lookup(+ self, rows: tuple[TraceEventRow, ...], **resolve: object+ ) -> tuple[contracts.TracePullRequestLookup, MagicMock]:+ resolve_branch = MagicMock(**resolve)+ with (+ patch.object(api, "load_trace_git_rows", return_value=rows),+ patch.object(engineering_analytics_api, "resolve_branch", resolve_branch),+ ):+ lookup = api.get_trace_pull_request(+ team=TEAM, # type: ignore[arg-type]+ user=None,+ user_access_control=ACCESS, # type: ignore[arg-type]+ trace_id="trace-1",+ timestamp_hint=T0,+ )+ return lookup, resolve_branch++ def test_resolves_the_latest_branch_with_its_repo_time_and_the_viewers_access(self) -> None:+ rows = (make_row(uuid="span-uuid", git_branch="main", timestamp=T0), *STAMPED)+ other = BranchPRMatch(repo="acme/app", number=7, title=None, state="closed")++ lookup, resolve = self._lookup(rows, return_value=[ANSWER_BILLING, other])++ assert resolve.call_args.kwargs == {+ "team": TEAM,+ "branch": "feat/rag",+ "repo": "acme/app",+ "timestamp": T1,+ "user_access_control": ACCESS,+ }+ assert lookup.pull_request == contracts.TracePullRequest(+ repo_owner="acme", repo_name="app", number=42, title="Answer billing questions"+ )++ @parameterized.expand(+ [+ ("the trace has no branch", (), {"return_value": [ANSWER_BILLING]}, False),+ ("the project has no GitHub source", STAMPED, {"side_effect": GitHubSourceNotConnectedError()}, True),+ (+ "the repo stamp is malformed",+ STAMPED,+ {"side_effect": ValueError("repo must be in 'owner/name' format")},+ True,+ ),+ ("no pull request matches", STAMPED, {"return_value": []}, True),+ (+ "the trace never left the default branch",+ (make_row(uuid="span-uuid", git_branch="main", git_repo="acme/app", timestamp=T0),),+ {"return_value": [ANSWER_BILLING]},+ False,+ ),+ ]+ )+ def test_no_pull_request_when(+ self, _name: str, rows: tuple[TraceEventRow, ...], resolve: dict[str, object], resolves: bool+ ) -> None:+ lookup, resolve_branch = self._lookup(rows, **resolve)++ assert (lookup.pull_request, resolve_branch.called) == (None, resolves)diff --git a/products/ai_observability/backend/tests/test_trace_views.py b/products/ai_observability/backend/tests/test_trace_views.pyindex ecd8c1fefb96..ad4506ec89ae 100644--- a/products/ai_observability/backend/tests/test_trace_views.py+++ b/products/ai_observability/backend/tests/test_trace_views.py@@ -1,9 +1,10 @@import base64from datetime import UTC, datetime, timedelta+from typing import TYPE_CHECKINGfrom urllib.parse import urlencodefrom posthog.test.base import APIBaseTest, ClickhouseTestMixin-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom parameterized import parameterized@@ -24,10 +25,15 @@ from products.ai_observability.backend.logic.traces import trace_queriesfrom products.ai_observability.backend.logic.traces.summary import ReadySummary, SummaryItemfrom products.ai_observability.backend.logic.traces.summary_store import summary_key, write_summaryfrom products.ai_observability.backend.models.review_queues import ReviewQueue+from products.engineering_analytics.backend.facade import api as engineering_analytics_api+from products.engineering_analytics.backend.facade.contracts import ENGINEERING_ANALYTICS_FEATURE_FLAG, BranchPRMatchfrom products.event_definitions.backend.models.property_definition import PropertyDefinitionfrom .logic.traces.rows import make_cluster, make_cluster_run_event, make_evaluation_result_event+if TYPE_CHECKING:+ from rest_framework.response import _MonkeyPatchedResponse+T0 = datetime(2026, 9, 1, 10, 0, tzinfo=UTC)GENERATION = "00000000-0000-0000-0000-000000000001"TRACE_EVENT = "00000000-0000-0000-0000-000000000002"@@ -676,3 +682,63 @@ class TestTraceSummaryViews(APIBaseTest):assert self.client.post(self._url(), {}, format="json").status_code == 200assert self.client.post(self._url(), {}, format="json").status_code == 429assert self.client.get(self._url()).status_code == 200+++PULL_REQUEST_MATCH = BranchPRMatch(repo="acme/app", number=42, title="Answer billing questions", state="open")+++class TestTracePullRequestView(ClickhouseTestMixin, APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ _create_trace(self.team, extra_properties={"$ai_git_branch": "feat/rag", "$ai_git_repo": "acme/app"})++ def _get(+ self, segment: str = _encode("trace-1"), *, flag: bool = True, headers: dict[str, str] | None = None+ ) -> tuple["_MonkeyPatchedResponse", MagicMock]:+ def only_engineering_analytics(key: str, *args: object, **kwargs: object) -> bool:+ return flag and key == ENGINEERING_ANALYTICS_FEATURE_FLAG++ with (+ patch("posthoganalytics.feature_enabled", side_effect=only_engineering_analytics),+ patch.object(engineering_analytics_api, "resolve_branch", return_value=[PULL_REQUEST_MATCH]) as resolve,+ ):+ response = self.client.get(+ f"/api/projects/{self.team.id}/ai_observability/traces/{segment}/pull_request/",+ {"timestamp_hint": T0.isoformat()},+ headers=headers or {},+ )+ return response, resolve++ def test_returns_the_pull_request_in_camel_case(self) -> None:+ response, _resolve = self._get()++ assert (response.status_code, response.json()) == (+ 200,+ {+ "pullRequest": {+ "repoOwner": "acme",+ "repoName": "app",+ "number": 42,+ "title": "Answer billing questions",+ }+ },+ )++ def test_requires_the_engineering_analytics_flag(self) -> None:+ response, resolve = self._get(flag=False)++ assert (response.status_code, resolve.called) == (403, False)++ @parameterized.expand([(["llm_analytics:read"], 403), (["llm_analytics:read", "engineering_analytics:read"], 200)])+ def test_an_api_key_needs_both_scopes(self, scopes: list[str], expected_status: int) -> None:+ key = self.create_personal_api_key_with_scopes(scopes)+ self.client.logout()++ response, _resolve = self._get(headers={"authorization": f"Bearer {key}"})++ assert response.status_code == expected_status, response.content++ def test_rejects_an_unencoded_trace_id(self) -> None:+ response, resolve = self._get("trace-1")++ assert (response.status_code, resolve.called) == (400, False)diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex 492fdfa88426..c352b9432d93 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -1666,6 +1666,22 @@ export interface TraceNodeDetailApi {event: TraceNodeEventApi | null}+export interface TracePullRequestApi {+ /** The owner of the pull request's repository. */+ repoOwner: string+ /** The name of the pull request's repository. */+ repoName: string+ /** The pull request number. */+ number: number+ /** The pull request title, or null when the synced data has none. */+ title: string | null+}++export interface TracePullRequestLookupApi {+ /** The pull request the trace's git branch belongs to, ranked by engineering analytics, or null when the trace has no branch, the project has no GitHub source, or no pull request matches. */+ pullRequest: TracePullRequestApi | null+}+export interface TraceSearchMatchApi {/** A step whose stored data contains the query. The root's id is the trace id. */nodeId: string@@ -5755,6 +5771,13 @@ export type AiObservabilityTracesNodesRetrieveParams = {timestamp_hint?: string}+export type AiObservabilityTracesPullRequestRetrieveParams = {+ /**+ * When the trace happened, as carried by links into it. Lets a trace older than the AI events retention load from the shared events table.+ */+ timestamp_hint?: string+}+export type AiObservabilityTracesSearchRetrieveParams = {/*** The text to find in the trace's steps, ignoring case.diff --git a/products/ai_observability/frontend/generated/api.ts b/products/ai_observability/frontend/generated/api.tsindex fa106e06b304..f554149f0054 100644--- a/products/ai_observability/frontend/generated/api.ts+++ b/products/ai_observability/frontend/generated/api.ts@@ -19,6 +19,7 @@ import type {AiObservabilityTracesClustersRetrieveParams,AiObservabilityTracesFeedbackRetrieveParams,AiObservabilityTracesNodesRetrieveParams,+ AiObservabilityTracesPullRequestRetrieveParams,AiObservabilityTracesRetrieveParams,AiObservabilityTracesSearchRetrieveParams,AiObservabilityTracesSummaryCreateParams,@@ -157,6 +158,7 @@ import type {TraceEvaluationResultsApi,TraceFeedbackApi,TraceNodeDetailApi,+ TracePullRequestLookupApi,TraceReviewApi,TraceReviewCreateApi,TraceSearchResultsApi,@@ -817,6 +819,44 @@ export const aiObservabilityTracesNodesRetrieve = async (})}+export const getAiObservabilityTracesPullRequestRetrieveUrl = (+ projectId: string,+ id: string,+ params?: AiObservabilityTracesPullRequestRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/ai_observability/traces/${id}/pull_request/?${stringifiedParams}`+ : `/api/projects/${projectId}/ai_observability/traces/${id}/pull_request/`+}++/**+ * The pull request the trace's git branch belongs to, from engineering analytics.+ */+export const aiObservabilityTracesPullRequestRetrieve = async (+ projectId: string,+ id: string,+ params?: AiObservabilityTracesPullRequestRetrieveParams,+ options?: RequestInit+): Promise<TracePullRequestLookupApi> => {+ return apiMutator<TracePullRequestLookupApi>(+ getAiObservabilityTracesPullRequestRetrieveUrl(projectId, id, params),+ {+ ...options,+ method: 'GET',+ }+ )+}+export const getAiObservabilityTracesSearchRetrieveUrl = (projectId: string,id: string,diff --git a/products/ai_observability/frontend/redesign/trace/adapter/toGitPullRequestLink.ts b/products/ai_observability/frontend/redesign/trace/adapter/toGitPullRequestLink.tsnew file mode 100644index 000000000000..91401f82c62f--- /dev/null+++ b/products/ai_observability/frontend/redesign/trace/adapter/toGitPullRequestLink.ts@@ -0,0 +1,12 @@+import { urls } from 'scenes/urls'++import type { TracePullRequestApi } from '../../../generated/api.schemas'+import { GitPullRequestLink } from '../types'++export function toGitPullRequestLink(pullRequest: TracePullRequestApi): GitPullRequestLink {+ return {+ number: pullRequest.number,+ title: pullRequest.title,+ href: urls.engineeringAnalyticsPullRequest(pullRequest.repoOwner, pullRequest.repoName, pullRequest.number),+ }+}diff --git a/products/ai_observability/frontend/redesign/trace/adapter/traceSceneWiring.test.tsx b/products/ai_observability/frontend/redesign/trace/adapter/traceSceneWiring.test.tsxindex 0e0b5d73d00d..fd94a31f1d8f 100644--- a/products/ai_observability/frontend/redesign/trace/adapter/traceSceneWiring.test.tsx+++ b/products/ai_observability/frontend/redesign/trace/adapter/traceSceneWiring.test.tsx@@ -3,6 +3,7 @@ import { router } from 'kea-router'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { addProjectIdIfMissing } from 'lib/utils/kea-router'import { urls } from 'scenes/urls'import { useMocks } from '~/mocks/jest'@@ -29,6 +30,7 @@ import {const FLAG = FEATURE_FLAGS.AI_OBSERVABILITY_TRACE_REDESIGNconst DATASETS_FLAG = FEATURE_FLAGS.LLM_ANALYTICS_DATASETS+const ENGINEERING_ANALYTICS_FLAG = FEATURE_FLAGS.ENGINEERING_ANALYTICSjest.mock('~/queries/query', () => ({ ...jest.requireActual('~/queries/query'), performQuery: jest.fn() }))jest.mock('../../../utils', () => ({@@ -42,6 +44,7 @@ const EVALUATIONS_URL = '/api/projects/:team_id/ai_observability/traces/:id/evalconst CLUSTERS_URL = '/api/projects/:team_id/ai_observability/traces/:id/clusters/'const FEEDBACK_URL = '/api/projects/:team_id/ai_observability/traces/:id/feedback/'const DATASETS_URL = '/api/projects/:team_id/datasets/'+const PULL_REQUEST_URL = '/api/projects/:team_id/ai_observability/traces/:id/pull_request/'const SEARCH_URL = '/api/projects/:team_id/ai_observability/traces/:id/search/'const SUMMARY_URL = '/api/projects/:team_id/ai_observability/traces/:id/summary/'const answeredGeneration = makeNodeDetail({@@ -257,19 +260,39 @@ describe('TraceScene', () => {expect(await findByText('Cites a source')).toBeTruthy()})- it('shows the trace git branch in the summary bar', async () => {- useMocks({- get: {- [TRACE_URL]: () => [- 200,- makeTraceResource({ defaultNodeId: 'gen-2', git: { branch: 'feat/rag', repo: 'acme/app' } }),- ],- },- })- const { findByText } = renderNewView()-- expect(await findByText('feat/rag')).toBeTruthy()- })+ it.each([+ [true, urls.engineeringAnalyticsPullRequest('acme', 'app', 42)],+ [false, null],+ ])(+ 'shows the trace git branch, linked to its pull request when engineering analytics is on (%s)',+ async (enabled, expectedHref) => {+ useMocks({+ get: {+ [TRACE_URL]: () => [+ 200,+ makeTraceResource({+ defaultNodeId: 'gen-2',+ git: { branch: 'feat/rag', repo: 'acme/app' },+ }),+ ],+ [PULL_REQUEST_URL]: () => [+ 200,+ { pullRequest: { repoOwner: 'acme', repoName: 'app', number: 42, title: null } },+ ],+ },+ })+ const { findByText, container } = renderNewView({ [ENGINEERING_ANALYTICS_FLAG]: enabled })++ expect(await findByText('feat/rag')).toBeTruthy()+ await waitFor(() =>+ expect(+ container+ .querySelector('[data-attr="trace-view-git-pull-request-link"]')+ ?.getAttribute('href') ?? null+ ).toBe(expectedHref && addProjectIdIfMissing(expectedHref))+ )+ }+ )it.each([true, false])('offers add to dataset on the step only when datasets are on (%s)', async (enabled) => {const { findByText, queryByText } = renderNewView({ [DATASETS_FLAG]: enabled })diff --git a/products/ai_observability/frontend/redesign/trace/adapter/traceViewAdapterLogic.ts b/products/ai_observability/frontend/redesign/trace/adapter/traceViewAdapterLogic.tsindex b02dc70412bd..49cfd9b48b64 100644--- a/products/ai_observability/frontend/redesign/trace/adapter/traceViewAdapterLogic.ts+++ b/products/ai_observability/frontend/redesign/trace/adapter/traceViewAdapterLogic.ts@@ -18,6 +18,7 @@ import type {TraceEvaluationResultsApi,TraceFeedbackApi,TraceNodeApi,+ TracePullRequestApi,TraceSearchResultsApi,TraceTimelineRowApi,} from '../../../generated/api.schemas'@@ -28,6 +29,7 @@ import type { TraceSearchBoxData } from '../components/TraceSearchBox'import { TraceSummaryBarProps } from '../components/TraceSummaryBar'import { traceClustersLogic } from '../traceClustersLogic'import { traceFeedbackLogic } from '../traceFeedbackLogic'+import { traceGitPullRequestLogic } from '../traceGitPullRequestLogic'import { SEARCH_DEBOUNCE_MS, traceSearchLogic } from '../traceSearchLogic'import { traceSummaryLogic } from '../traceSummaryLogic'import { TraceViewStatus, traceViewLogic } from '../traceViewLogic'@@ -54,6 +56,7 @@ import { toClustersChip } from './toClustersChip'import { toDatasetItemSource } from './toDatasetItemSource'import { firstFailingNodeId, toEvalOutcomesByNode, toEvalsChip } from './toEvalSummary'import { stepFeedbackOf, toFeedbackChip, toFeedbackMode, toStepFeedback } from './toFeedback'+import { toGitPullRequestLink } from './toGitPullRequestLink'import { toBackLink, toHeader } from './toHeader'import { NodeDetailData, toNodeDetail } from './toNodeDetail'import { steppedMatchId, toMatchingNodeIds, toSearchBox } from './toSearch'@@ -87,6 +90,7 @@ export interface traceViewAdapterLogicValues {clusters: TraceClusterApi[] | null // traceClustersLogictraceFeedback: TraceFeedbackApi | null // traceFeedbackLogictraceFeedbackFailed: boolean // traceFeedbackLogic+ pullRequest: TracePullRequestApi | null // traceGitPullRequestLogicquery: string // traceSearchLogicsearchFailure: TraceSearchFailure | null // traceSearchLogicsearchResults: TraceSearchResultsApi | null // traceSearchLogic@@ -290,7 +294,7 @@ export interface traceViewAdapterLogicMeta {clustersChip: (clusters: TraceClusterApi[] | null) => TraceClustersChipProps | nullevalsChip: (evaluationResults: TraceEvaluationResultsApi | null) => EvalsChipData | nullevalOutcomesByNode: (evaluationResults: TraceEvaluationResultsApi | null) => Record<string, EvalRollupOutcome>- gitBranch: (trace: TraceApi | null) => GitBranchChipProps | null+ gitBranch: (trace: TraceApi | null, pullRequest: TracePullRequestApi | null) => GitBranchChipProps | nullcanViewInThread: (selectedNodeId: string, threadNodeIds: string[], traceId: string) => booleanfeedbackChip: (traceFeedback: TraceFeedbackApi | null) => FeedbackChipData | nullfeedbackCount: (traceFeedback: TraceFeedbackApi | null) => number | null@@ -379,6 +383,8 @@ export const traceViewAdapterLogic = kea<traceViewAdapterLogicType>([['state as summaryState', 'requesting as summaryRequesting', 'requestError as summaryRequestError'],aiConsentLogic,['dataProcessingAccepted as summaryConsentGiven'],+ traceGitPullRequestLogic({ traceId: props.traceId, timestampHint: props.timestampHint }),+ ['pullRequest'],],actions: [aiObservabilityTraceLogic,@@ -578,7 +584,13 @@ export const traceViewAdapterLogic = kea<traceViewAdapterLogicType>([(evaluationResults: TraceEvaluationResultsApi | null): Record<string, EvalRollupOutcome> =>evaluationResults ? toEvalOutcomesByNode(evaluationResults.summary) : {},],- gitBranch: [(s) => [s.trace], (trace: TraceApi | null): GitBranchChipProps | null => trace?.git ?? null],+ gitBranch: [+ (s) => [s.trace, s.pullRequest],+ (trace: TraceApi | null, pullRequest: TracePullRequestApi | null): GitBranchChipProps | null =>+ trace?.git+ ? { ...trace.git, pullRequest: pullRequest ? toGitPullRequestLink(pullRequest) : null }+ : null,+ ],canViewInThread: [(s, p) => [s.selectedNodeId, s.threadNodeIds, p.traceId],(selectedNodeId: string, threadNodeIds: string[], traceId: string): boolean =>diff --git a/products/ai_observability/frontend/redesign/trace/components/GitBranchChip.test.tsx b/products/ai_observability/frontend/redesign/trace/components/GitBranchChip.test.tsxnew file mode 100644index 000000000000..fda2792dee09--- /dev/null+++ b/products/ai_observability/frontend/redesign/trace/components/GitBranchChip.test.tsx@@ -0,0 +1,31 @@+import { cleanup, render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'++import { initKeaTests } from '~/test/init'++import { GitBranchChip } from './GitBranchChip'++const PULL_REQUEST = { number: 42, title: 'Answer billing questions', href: '/engineering-analytics/pull-requests/42' }++describe('GitBranchChip', () => {+ beforeEach(() => {+ initKeaTests()+ })++ afterEach(() => {+ cleanup()+ })++ it('opens its tooltip on hover once the pull request arrives after the chip rendered', async () => {+ const { rerender } = render(<GitBranchChip branch="feat/rag" repo="acme/app" pullRequest={null} />)+ rerender(<GitBranchChip branch="feat/rag" repo="acme/app" pullRequest={PULL_REQUEST} />)++ await userEvent.hover(screen.getByText('feat/rag'))++ expect(+ await screen.findByText(+ 'Git branch feat/rag in acme/app. Opens pull request #42 in engineering analytics: Answer billing questions'+ )+ ).toBeTruthy()+ })+})diff --git a/products/ai_observability/frontend/redesign/trace/components/GitBranchChip.tsx b/products/ai_observability/frontend/redesign/trace/components/GitBranchChip.tsxindex 239c7601e102..076433570f6d 100644--- a/products/ai_observability/frontend/redesign/trace/components/GitBranchChip.tsx+++ b/products/ai_observability/frontend/redesign/trace/components/GitBranchChip.tsx@@ -1,16 +1,40 @@import { IconGitBranch } from '@posthog/icons'-import { LemonTag, Tooltip } from '@posthog/lemon-ui'+import { LemonTag, Link, Tooltip } from '@posthog/lemon-ui'import type { TraceGitApi } from '../../../generated/api.schemas'+import { GitPullRequestLink } from '../types'-export type GitBranchChipProps = TraceGitApi+export interface GitBranchChipProps extends TraceGitApi {+ pullRequest: GitPullRequestLink | null+}++function tooltipTitle({ branch, repo, pullRequest }: GitBranchChipProps): string {+ const location = repo ? `Git branch ${branch} in ${repo}` : `Git branch ${branch}`+ if (!pullRequest) {+ return location+ }+ const title = pullRequest.title ? `: ${pullRequest.title}` : ''+ return `${location}. Opens pull request #${pullRequest.number} in engineering analytics${title}`+}-export function GitBranchChip({ branch, repo }: GitBranchChipProps): JSX.Element {+export function GitBranchChip(props: GitBranchChipProps): JSX.Element {+ const { branch, pullRequest } = props+ const tag = (+ <LemonTag icon={<IconGitBranch />} weight="normal" data-attr="trace-view-git-branch-chip">+ <span className="block max-w-60 truncate font-mono">{branch}</span>+ </LemonTag>+ )return (- <Tooltip title={repo ? `Git branch ${branch} in ${repo}` : `Git branch ${branch}`}>- <LemonTag icon={<IconGitBranch />} weight="normal" data-attr="trace-view-git-branch-chip">- <span className="block max-w-60 truncate font-mono">{branch}</span>- </LemonTag>+ // The pull request arrives after the chip renders, which swaps the trigger element. The tooltip attaches its+ // hover listeners to the first element only, so it remounts for the new one.+ <Tooltip key={pullRequest ? 'linked' : 'plain'} title={tooltipTitle(props)}>+ {pullRequest ? (+ <Link to={pullRequest.href} subtle data-attr="trace-view-git-pull-request-link">+ {tag}+ </Link>+ ) : (+ tag+ )}</Tooltip>)}diff --git a/products/ai_observability/frontend/redesign/trace/components/TraceSummaryBar.stories.tsx b/products/ai_observability/frontend/redesign/trace/components/TraceSummaryBar.stories.tsxindex a102b0dc46b3..42fb937690f0 100644--- a/products/ai_observability/frontend/redesign/trace/components/TraceSummaryBar.stories.tsx+++ b/products/ai_observability/frontend/redesign/trace/components/TraceSummaryBar.stories.tsx@@ -38,11 +38,29 @@ export const WithThumbsFeedback: Story = {export const WithGitBranch: Story = {...wide,- args: { git: { branch: 'feat/billing-answers', repo: 'acme/support-bot' } },+ args: { git: { branch: 'feat/billing-answers', repo: 'acme/support-bot', pullRequest: null } },}export const NarrowWithLongGitBranch: Story = {decorators: [withWidth(420)],args: {- git: { branch: 'carol/feat-answer-billing-questions-with-invoice-history-and-seat-changes', repo: null },+ git: {+ branch: 'carol/feat-answer-billing-questions-with-invoice-history-and-seat-changes',+ repo: null,+ pullRequest: null,+ },+ },+}+export const WithGitPullRequest: Story = {+ ...wide,+ args: {+ git: {+ branch: 'feat/billing-answers',+ repo: 'acme/support-bot',+ pullRequest: {+ number: 42,+ title: 'Answer billing questions',+ href: '/engineering-analytics/repos/acme/support-bot/pull-requests/42',+ },+ },},}diff --git a/products/ai_observability/frontend/redesign/trace/traceGitPullRequestLogic.test.ts b/products/ai_observability/frontend/redesign/trace/traceGitPullRequestLogic.test.tsnew file mode 100644index 000000000000..ea1f7d8ea33b--- /dev/null+++ b/products/ai_observability/frontend/redesign/trace/traceGitPullRequestLogic.test.ts@@ -0,0 +1,109 @@+import { expectLogic } from 'kea-test-utils'++import { FEATURE_FLAGS } from 'lib/constants'+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'++import type { TraceGitApi, TracePullRequestApi } from '../../generated/api.schemas'+import { decodeIdSegment, makeTraceResource } from './adapter/testFixtures'+import { traceGitPullRequestLogic } from './traceGitPullRequestLogic'+import { traceViewLogic } from './traceViewLogic'++const TRACE_URL = '/api/projects/:team_id/ai_observability/traces/:id/'+const EVALUATIONS_URL = '/api/projects/:team_id/ai_observability/traces/:id/evaluations/'+const PULL_REQUEST_URL = '/api/projects/:team_id/ai_observability/traces/:id/pull_request/'+const FLAG = FEATURE_FLAGS.ENGINEERING_ANALYTICS+const GIT: TraceGitApi = { branch: 'feat/rag', repo: 'acme/app' }+const PULL_REQUEST: TracePullRequestApi = {+ repoOwner: 'acme',+ repoName: 'app',+ number: 42,+ title: 'Answer billing questions',+}+const CREATED_AT = makeTraceResource().createdAt++describe('traceGitPullRequestLogic', () => {+ let requests: { traceId: string; timestampHint: string | null }[]+ let pullRequestStatus: number+ let traceBranch: TraceGitApi | null++ function setFlag(enabled: boolean): void {+ featureFlagLogic.actions.setFeatureFlags(enabled ? [FLAG] : [], { [FLAG]: enabled })+ }++ async function mountedLogic(git: TraceGitApi | null): Promise<ReturnType<typeof traceGitPullRequestLogic.build>> {+ traceBranch = git+ const props = { traceId: 'trace-1', timestampHint: null }+ const logic = traceGitPullRequestLogic(props)+ logic.mount()+ await expectLogic(traceViewLogic(props)).toDispatchActions(['loadTraceSuccess'])+ await expectLogic(logic).toFinishAllListeners()+ return logic+ }++ beforeEach(() => {+ requests = []+ pullRequestStatus = 200+ traceBranch = null+ useMocks({+ get: {+ [TRACE_URL]: () => [200, makeTraceResource({ git: traceBranch })],+ [EVALUATIONS_URL]: () => [200, { results: [] }],+ [PULL_REQUEST_URL]: ({ request, params }) => {+ requests.push({+ traceId: decodeIdSegment(String(params.id)),+ timestampHint: new URL(request.url).searchParams.get('timestamp_hint'),+ })+ return pullRequestStatus === 200+ ? [200, { pullRequest: PULL_REQUEST }]+ : [pullRequestStatus, { detail: 'nope' }]+ },+ },+ })+ initKeaTests()+ featureFlagLogic.mount()+ })++ afterEach(() => {+ jest.restoreAllMocks()+ })++ it.each([+ ['the flag is on and the trace has a branch', true, GIT, 1],+ ['the flag is off', false, GIT, 0],+ ['the trace has no branch', true, null, 0],+ ])('reads the pull request when %s', async (_description, flagOn, git, expectedRequests) => {+ setFlag(flagOn)++ const logic = await mountedLogic(git)++ expect(requests).toEqual(Array(expectedRequests).fill({ traceId: 'trace-1', timestampHint: CREATED_AT }))+ expect(logic.values.pullRequest).toEqual(expectedRequests ? PULL_REQUEST : null)+ })++ it('reads it once when the flags arrive after the trace', async () => {+ setFlag(false)+ const logic = await mountedLogic(GIT)++ setFlag(true)+ setFlag(true)+ await expectLogic(logic).toFinishAllListeners()++ expect(requests).toHaveLength(1)+ })++ it('keeps the plain chip when the read fails', async () => {+ const toast = jest.spyOn(lemonToast, 'error')+ pullRequestStatus = 500+ setFlag(true)++ const logic = await mountedLogic(GIT)++ expect(requests).toHaveLength(1)+ expect(logic.values.pullRequest).toBeNull()+ expect(toast).not.toHaveBeenCalled()+ })+})diff --git a/products/ai_observability/frontend/redesign/trace/traceGitPullRequestLogic.ts b/products/ai_observability/frontend/redesign/trace/traceGitPullRequestLogic.tsnew file mode 100644index 000000000000..8c992b682b07--- /dev/null+++ b/products/ai_observability/frontend/redesign/trace/traceGitPullRequestLogic.ts@@ -0,0 +1,94 @@+import { MakeLogicType, connect, kea, key, path, props, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'++import { ApiConfig } from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { aiObservabilityTracesPullRequestRetrieve } from '../../generated/api'+import type { TraceApi, TracePullRequestApi } from '../../generated/api.schemas'+import { encodeTraceIdSegment } from './traceIdSegment'+import { TraceViewLogicProps, traceViewLogic } from './traceViewLogic'++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface traceGitPullRequestLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogic+ trace: TraceApi | null // traceViewLogic+ pullRequest: TracePullRequestApi | null+ pullRequestLoading: boolean+ pullRequestTimestampHint: string | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface traceGitPullRequestLogicActions {+ loadTracePullRequest: (timestampHint: string) => string+ loadTracePullRequestFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadTracePullRequestSuccess: (+ pullRequest: TracePullRequestApi | null,+ payload?: string+ ) => {+ pullRequest: TracePullRequestApi | null+ payload?: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface traceGitPullRequestLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ pullRequestTimestampHint: (trace: TraceApi | null, featureFlags: FeatureFlagsSet) => string | null+ }+}++export type traceGitPullRequestLogicType = MakeLogicType<+ traceGitPullRequestLogicValues,+ traceGitPullRequestLogicActions,+ TraceViewLogicProps,+ traceGitPullRequestLogicMeta+>++export const traceGitPullRequestLogic = kea<traceGitPullRequestLogicType>([+ path((key) => ['products', 'ai_observability', 'frontend', 'redesign', 'trace', 'traceGitPullRequestLogic', key]),+ props({} as TraceViewLogicProps),+ key((props) => props.traceId),+ connect((props: TraceViewLogicProps) => ({+ values: [traceViewLogic(props), ['trace'], featureFlagLogic, ['featureFlags']],+ })),+ loaders(({ props }) => ({+ pullRequest: [+ null as TracePullRequestApi | null,+ {+ loadTracePullRequest: async (timestampHint: string): Promise<TracePullRequestApi | null> => {+ const { pullRequest } = await aiObservabilityTracesPullRequestRetrieve(+ String(ApiConfig.getCurrentProjectId()),+ encodeTraceIdSegment(props.traceId),+ { timestamp_hint: timestampHint }+ )+ return pullRequest+ },+ },+ ],+ })),+ selectors({+ pullRequestTimestampHint: [+ (s) => [s.trace, s.featureFlags],+ (trace: TraceApi | null, featureFlags: FeatureFlagsSet): string | null =>+ trace?.git && featureFlags[FEATURE_FLAGS.ENGINEERING_ANALYTICS] ? trace.createdAt : null,+ ],+ }),+ // Flags can arrive after the trace on a deep link, so the read waits for both rather than for either action.+ subscriptions(({ actions }) => ({+ pullRequestTimestampHint: (pullRequestTimestampHint: string | null) => {+ if (pullRequestTimestampHint) {+ actions.loadTracePullRequest(pullRequestTimestampHint)+ }+ },+ })),+])diff --git a/products/ai_observability/frontend/redesign/trace/types.ts b/products/ai_observability/frontend/redesign/trace/types.tsindex 9eacda449170..6eaf429ca548 100644--- a/products/ai_observability/frontend/redesign/trace/types.ts+++ b/products/ai_observability/frontend/redesign/trace/types.ts@@ -128,6 +128,12 @@ export interface LabeledLink {href: string}+export interface GitPullRequestLink {+ number: number+ title: string | null+ href: string+}+export type TraceSearchStatus = 'idle' | 'loading' | 'ready' | 'error'export type TraceSearchFailure = 'too_slow' | 'failed'diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f8e1fec4519b..d5b72306e06d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -122523,6 +122523,22 @@ export namespace Schemas {event: TraceNodeEvent | null;}+ export interface TracePullRequest {+ /** The owner of the pull request's repository. */+ repoOwner: string;+ /** The name of the pull request's repository. */+ repoName: string;+ /** The pull request number. */+ number: number;+ /** The pull request title, or null when the synced data has none. */+ title: string | null;+ }++ export interface TracePullRequestLookup {+ /** The pull request the trace's git branch belongs to, ranked by engineering analytics, or null when the trace has no branch, the project has no GitHub source, or no pull request matches. */+ pullRequest: TracePullRequest | null;+ }+export interface TraceReviewCreate {/*** Trace ID for the review. Only one active review can exist per trace and team.@@ -131076,6 +131092,13 @@ export namespace Schemas {timestamp_hint?: string;};+ export type AiObservabilityTracesPullRequestRetrieveParams = {+ /**+ * When the trace happened, as carried by links into it. Lets a trace older than the AI events retention load from the shared events table.+ */+ timestamp_hint?: string;+ };+export type AiObservabilityTracesSearchRetrieveParams = {/*** The text to find in the trace's steps, ignoring case.diff --git a/tach.toml b/tach.tomlindex 3554fa53f2a7..1eb8a172edbc 100644--- a/tach.toml+++ b/tach.toml@@ -589,6 +589,8 @@ depends_on = ["products.workflows", "products.access_control",# Evaluations and taggers compile Hog through products.cdp.backend.validation and filters."products.cdp",+ # Facade only: the trace view links a trace's git branch to its pull request.+ "products.engineering_analytics",# Trace feedback reads trace-linked survey responses through the surveys facade."products.surveys",]