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.

feat(engineering-analytics): attribute llm token spend to prs by branch (#69962)

Julian Bez1e487389e9d7
diff --git a/frontend/src/taxonomy/core-filter-definitions-by-group.json b/frontend/src/taxonomy/core-filter-definitions-by-group.json
index 29055a258b3f..e149174386e0 100644
--- a/frontend/src/taxonomy/core-filter-definitions-by-group.json
+++ b/frontend/src/taxonomy/core-filter-definitions-by-group.json
@@ -385,6 +385,20 @@
],
"label": "AI framework (LLM)"
},
+ "$ai_git_branch": {
+ "description": "The git branch checked out when the AI generation ran.",
+ "examples": [
+ "feat/my-feature"
+ ],
+ "label": "AI git branch"
+ },
+ "$ai_git_repo": {
+ "description": "The repository that AI interacted with, as owner/name.",
+ "examples": [
+ "PostHog/posthog"
+ ],
+ "label": "AI git repository"
+ },
"$ai_http_status": {
"description": "The HTTP status code of the request made to the LLM API.",
"examples": [
@@ -4758,6 +4772,20 @@
],
"label": "AI framework (LLM)"
},
+ "$ai_git_branch": {
+ "description": "The git branch checked out when the AI generation ran.",
+ "examples": [
+ "feat/my-feature"
+ ],
+ "label": "AI git branch"
+ },
+ "$ai_git_repo": {
+ "description": "The repository that AI interacted with, as owner/name.",
+ "examples": [
+ "PostHog/posthog"
+ ],
+ "label": "AI git repository"
+ },
"$ai_http_status": {
"description": "The HTTP status code of the request made to the LLM API.",
"examples": [
diff --git a/posthog/taxonomy/taxonomy.py b/posthog/taxonomy/taxonomy.py
index b8fc2b61e105..c3e259f0b82f 100644
--- a/posthog/taxonomy/taxonomy.py
+++ b/posthog/taxonomy/taxonomy.py
@@ -2591,6 +2591,16 @@ CORE_FILTER_DEFINITIONS_BY_GROUP: dict[str, dict[str, CoreFilterDefinition]] = {
"description": "The AI framework used to produce this event.",
"examples": ["langchain", "llamaindex", "openai"],
},
+ "$ai_git_branch": {
+ "label": "AI git branch",
+ "description": "The git branch checked out when the AI generation ran.",
+ "examples": ["feat/my-feature"],
+ },
+ "$ai_git_repo": {
+ "label": "AI git repository",
+ "description": "The repository that AI interacted with, as owner/name.",
+ "examples": ["PostHog/posthog"],
+ },
"$ai_lib": {
"label": "AI library (LLM)",
"description": "The name of the SDK or library that sent this AI event.",
diff --git a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
index f1afaf5ec470..bcb38c1c6d06 100644
--- a/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTraceScene.tsx
@@ -61,6 +61,8 @@ import { lemonToast } from '~/lib/lemon-ui/LemonToast/LemonToast'
import { LLMTrace, LLMTraceEvent } from '~/queries/schema/schema-general'
import { AccessControlLevel, AccessControlResourceType, SidePanelTab } from '~/types'
+import type { BranchPRMatchApi } from 'products/engineering_analytics/frontend/generated/api.schemas'
+
import { EnrichedTraceTreeNode, findNodeForEvent, aiObservabilityTraceDataLogic } from './aiObservabilityTraceDataLogic'
import { DisplayOption, TraceViewMode, aiObservabilityTraceLogic } from './aiObservabilityTraceLogic'
import { ClustersTabContent } from './components/ClustersTabContent'
@@ -996,6 +998,42 @@ function TraceWorkflowPanel({ traceId }: { traceId: string }): JSX.Element {
)
}
+function TraceGitChip({
+ branch,
+ repo,
+ branchPRMatches,
+}: {
+ branch: string
+ repo: string | null
+ branchPRMatches: BranchPRMatchApi[]
+}): JSX.Element {
+ // Repo lives in the tooltip only; the chip content is the branch name.
+ const repoPrefix = repo ? `${repo} - ` : ''
+
+ // The loader gates on the engineering-analytics flag, so a populated match already implies it's on.
+ // While the resolution request is in flight (or stale for this branch) matches is empty, so this
+ // renders the plain chip.
+ const match = branchPRMatches[0]
+ if (match) {
+ const [owner, name] = match.repo.split('/')
+ const prTitle = match.title ? `: ${match.title}` : ''
+ const tooltip = `${repoPrefix}Branch - click to view PR #${match.number} in engineering analytics${prTitle}`
+ return (
+ <Chip title="Branch" tooltipTitle={tooltip}>
+ <Link to={urls.engineeringAnalyticsPullRequest(owner, name, match.number)} subtle>
+ <span className="font-mono">{branch}</span>
+ </Link>
+ </Chip>
+ )
+ }
+
+ return (
+ <Chip title="Branch" tooltipTitle={repoPrefix ? `${repoPrefix}Branch` : 'Branch'}>
+ <span className="font-mono">{branch}</span>
+ </Chip>
+ )
+}
+
function TraceMetadata({
trace,
metricEvents,
@@ -1014,6 +1052,8 @@ function TraceMetadata({
showBillingInfo?: boolean
}): JSX.Element {
const { personsCache } = useValues(llmPersonsLazyLoaderLogic)
+ const { traceGitMetadata } = useValues(aiObservabilityTraceDataLogic)
+ const { branchPRMatches } = useValues(aiObservabilityTraceLogic)
const sentimentResult = trace.sentiment
const traceCostContext = costContextFromTrace(trace)
@@ -1040,6 +1080,13 @@ function TraceMetadata({
</Link>
</Chip>
)}
+ {traceGitMetadata?.branch && (
+ <TraceGitChip
+ branch={traceGitMetadata.branch}
+ repo={traceGitMetadata.repo}
+ branchPRMatches={branchPRMatches}
+ />
+ )}
<UsageChip event={trace} />
{traceCostContext && (
<CostChip
diff --git a/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts b/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts
index 17db99421350..8f7ff336f502 100644
--- a/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts
+++ b/products/ai_observability/frontend/aiObservabilityTraceDataLogic.ts
@@ -19,7 +19,7 @@ import {
import { InsightLogicProps } from '~/types'
import type { aiObservabilityTraceDataLogicType } from './aiObservabilityTraceDataLogicType'
-import { aiObservabilityTraceLogic } from './aiObservabilityTraceLogic'
+import { type TraceGitMetadata, aiObservabilityTraceLogic } from './aiObservabilityTraceLogic'
import { llmPersonsLazyLoaderLogic } from './llmPersonsLazyLoaderLogic'
import { captureNormalizationFailure, normalizeMessages } from './messageNormalization'
import {
@@ -180,6 +180,43 @@ export function reportTraceNormalizationFailures(trace: LLMTrace): void {
}
}
+function nonEmptyStringProp(value: unknown): string | null {
+ return typeof value === 'string' && value.length > 0 ? value : null
+}
+
+// Default-branch names to look past when a trace spans a branch switch. The frontend doesn't know
+// the repo's real base ref; these cover GitHub's defaults, and a trace stamped only with them still
+// surfaces that stamp via the fallback below.
+const DEFAULT_BRANCHES = new Set(['master', 'main'])
+
+// A coding agent often starts a session on the default branch and creates the feature branch
+// mid-trace, so the first stamped event can carry master/main while the work (and the PR the spend
+// belongs to) lives on a later stamp. Prefer the latest non-default branch stamp — the branch the
+// trace's most recent work happened on — and fall back to the first stamped event when the trace
+// never left the default branch.
+export function deriveTraceGitMetadata(trace: LLMTrace | undefined): TraceGitMetadata | null {
+ if (!trace) {
+ return null
+ }
+ // The trace's capture time scopes branch→PR resolution to the moment the work ran, so a reused
+ // branch name resolves to the PR active then rather than whichever PR is newest now.
+ const timestamp = nonEmptyStringProp(trace.createdAt)
+ let first: TraceGitMetadata | null = null
+ let lastFeature: TraceGitMetadata | null = null
+ for (const event of trace.events) {
+ const branch = nonEmptyStringProp(event.properties.$ai_git_branch)
+ const repo = nonEmptyStringProp(event.properties.$ai_git_repo)
+ if (!branch && !repo) {
+ continue
+ }
+ first = first ?? { branch, repo, timestamp }
+ if (branch && !DEFAULT_BRANCHES.has(branch)) {
+ lastFeature = { branch, repo, timestamp }
+ }
+ }
+ return lastFeature ?? first
+}
+
export const aiObservabilityTraceDataLogic = kea<aiObservabilityTraceDataLogicType>([
path(['scenes', 'ai-observability', 'aiObservabilityTraceDataLogic']),
props({} as TraceDataLogicProps),
@@ -343,6 +380,7 @@ export const aiObservabilityTraceDataLogic = kea<aiObservabilityTraceDataLogicTy
(trace): LLMTraceEvent[] | undefined =>
trace?.events.filter((event) => event.event === '$ai_feedback' && event.properties.$ai_feedback_text),
],
+ traceGitMetadata: [(s) => [s.trace], (trace): TraceGitMetadata | null => deriveTraceGitMetadata(trace)],
metricsAndFeedbackEvents: [
(s) => [s.metricEvents, s.feedbackEvents],
(metricEvents, feedbackEvents): { metric: string; value: any }[] =>
@@ -498,7 +536,7 @@ export const aiObservabilityTraceDataLogic = kea<aiObservabilityTraceDataLogicTy
actions.setEventId(mostRelevantEvent.id)
}
},
- trace: (trace: LLMTrace | undefined) => {
+ trace: (trace: LLMTrace | undefined, oldTrace: LLMTrace | undefined) => {
if (trace?.createdAt && props.traceId) {
aiObservabilityTraceLogic.actions.loadNeighbors(props.traceId, trace.createdAt)
}
@@ -507,6 +545,14 @@ export const aiObservabilityTraceDataLogic = kea<aiObservabilityTraceDataLogicTy
llmPersonsLazyLoaderLogic.actions.ensurePersonLoaded(trace.distinctId)
}
+ // Resolve the branch to a PR only when the branch or repo actually changed — re-dispatching
+ // on an unrelated trace update would refire the same resolution request.
+ const gitMetadata = values.traceGitMetadata
+ const previous = deriveTraceGitMetadata(oldTrace)
+ if (gitMetadata?.branch !== previous?.branch || gitMetadata?.repo !== previous?.repo) {
+ aiObservabilityTraceLogic.actions.loadBranchPRMatches(gitMetadata)
+ }
+
actions.reportSingleTraceLoadIfReady()
},
})),
diff --git a/products/ai_observability/frontend/aiObservabilityTraceLogic.ts b/products/ai_observability/frontend/aiObservabilityTraceLogic.ts
index 2f2c4fcc6a44..e86fdcb8ae82 100644
--- a/products/ai_observability/frontend/aiObservabilityTraceLogic.ts
+++ b/products/ai_observability/frontend/aiObservabilityTraceLogic.ts
@@ -3,7 +3,7 @@ import { loaders } from 'kea-loaders'
import { combineUrl, router, urlToAction } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
-import api from 'lib/api'
+import api, { ApiConfig } from 'lib/api'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs } from 'lib/dayjs'
@@ -28,6 +28,9 @@ import {
} from '~/queries/schema/schema-general'
import { ActivityScope, AnyPropertyFilter, Breadcrumb, InsightLogicProps } from '~/types'
+import { engineeringAnalyticsResolveBranch } from 'products/engineering_analytics/frontend/generated/api'
+import type { BranchPRMatchApi } from 'products/engineering_analytics/frontend/generated/api.schemas'
+
import { aiObservabilitySharedLogic } from './aiObservabilitySharedLogic'
import type { aiObservabilityTraceLogicType } from './aiObservabilityTraceLogicType'
import { buildAiObservabilityStorageConfig } from './preferenceStorage'
@@ -78,6 +81,32 @@ export function getDataNodeLogicProps({
export type AIObservabilityTraceLogicProps = Record<string, never>
+/** Git ref stamped on a trace's events by a coding-agent session (branch-only MVP; either field may be null). */
+export interface TraceGitMetadata {
+ branch: string | null
+ repo: string | null
+ /** The trace's capture time, threaded to resolve_branch so a reused branch name resolves to the PR
+ * that was active when the trace ran, not whichever PR is newest now. */
+ timestamp: string | null
+}
+
+/** A branch→PR resolution tagged with the request it resolved for, so a result left over from a
+ * previously viewed trace can be ignored until the reload for the new trace finishes. */
+export interface BranchPRResolution {
+ key: string | null
+ matches: BranchPRMatchApi[]
+ /** True when the resolve was skipped because feature flags had not loaded yet — retried once they do. */
+ gated?: boolean
+}
+
+/** Identity of one resolution request. Branch alone is not enough: two traces can carry the same
+ * branch name in different repos, and a branch-only guard would link one repo's chip to the other's PR. */
+export function branchPRResolutionKey(gitMetadata: TraceGitMetadata | null): string | null {
+ return gitMetadata?.branch ? `${gitMetadata.repo ?? ''}::${gitMetadata.branch}` : null
+}
+
+const projectId = (): string => String(ApiConfig.getCurrentProjectId())
+
export const aiObservabilityTraceLogic = kea<aiObservabilityTraceLogicType>([
path(['scenes', 'ai-observability', 'aiObservabilityTraceLogic']),
props({} as AIObservabilityTraceLogicProps),
@@ -120,6 +149,19 @@ export const aiObservabilityTraceLogic = kea<aiObservabilityTraceLogicType>([
reducers(() => ({
traceId: ['' as string, { setTraceId: (_, { traceId }) => traceId }],
+ // The branch+repo the loader is currently resolving for. Updates synchronously when the load is
+ // dispatched (before the request resolves), so the branchPRMatches selector can drop a
+ // resolution still tagged with the previously viewed trace's branch/repo.
+ resolvingKey: [
+ null as string | null,
+ { loadBranchPRMatches: (_, gitMetadata: TraceGitMetadata | null) => branchPRResolutionKey(gitMetadata) },
+ ],
+ // The metadata of the latest resolve request, kept so a resolve skipped while feature flags
+ // were still loading can be re-dispatched once they arrive (see the featureFlags subscription).
+ lastGitMetadata: [
+ null as TraceGitMetadata | null,
+ { loadBranchPRMatches: (_, gitMetadata: TraceGitMetadata | null) => gitMetadata },
+ ],
eventId: [null as string | null, { setEventId: (_, { eventId }) => eventId }],
highlightMessageIndex: [
null as number | null,
@@ -313,9 +355,61 @@ export const aiObservabilityTraceLogic = kea<aiObservabilityTraceLogicType>([
},
},
],
+ branchPRResolution: [
+ { key: null, matches: [] } as BranchPRResolution,
+ {
+ loadBranchPRMatches: async (gitMetadata: TraceGitMetadata | null, breakpoint) => {
+ // Tag the result with the branch+repo it resolved for, so a stale in-flight result from
+ // the previously viewed trace can be discarded (see the branchPRMatches selector).
+ const key = branchPRResolutionKey(gitMetadata)
+ const branch = gitMetadata?.branch ?? null
+
+ if (!branch) {
+ return { key, matches: [] }
+ }
+
+ // Gated on engineering analytics: only that product can turn a git branch into a PR link.
+ // Flags may not have loaded yet (deep link straight to a trace) — mark the skip as
+ // gated so the featureFlags subscription retries once they arrive.
+ if (!values.featureFlags?.[FEATURE_FLAGS.ENGINEERING_ANALYTICS]) {
+ return { key, matches: [], gated: !Object.keys(values.featureFlags ?? {}).length }
+ }
+
+ await breakpoint(100)
+
+ // A failed resolution just means no PR link, the chip renders plain and never blocks the header.
+ let matches: BranchPRMatchApi[]
+ try {
+ matches = await engineeringAnalyticsResolveBranch(projectId(), {
+ branch,
+ repo: gitMetadata?.repo ?? undefined,
+ timestamp: gitMetadata?.timestamp ?? undefined,
+ })
+ } catch {
+ matches = []
+ }
+
+ // Also on the failure path: a stale request failing after a newer load resolved must not
+ // overwrite the newer resolution.
+ breakpoint()
+
+ return { key, matches }
+ },
+ },
+ ],
})),
selectors({
+ // Only surface matches once the stored resolution matches the branch+repo currently being
+ // resolved. On a trace switch traceGitMetadata (and resolvingKey) update immediately while the
+ // loader still holds the previous trace's matches, so this drops them until the reload lands —
+ // the chip never links the new trace's text to another branch's (or same-named branch in
+ // another repo's) PR.
+ branchPRMatches: [
+ (s) => [s.branchPRResolution, s.resolvingKey],
+ (resolution, resolvingKey): BranchPRMatchApi[] =>
+ resolution.key === resolvingKey ? resolution.matches : [],
+ ],
inputMessageShowStates: [(s) => [s.messageShowStates], (messageStates) => messageStates.input],
outputMessageShowStates: [(s) => [s.messageShowStates], (messageStates) => messageStates.output],
query: [
@@ -450,7 +544,14 @@ export const aiObservabilityTraceLogic = kea<aiObservabilityTraceLogicType>([
},
})),
- subscriptions(({ actions }) => ({
+ subscriptions(({ actions, values }) => ({
+ featureFlags: (featureFlags: Record<string, unknown>) => {
+ // A resolve skipped because flags had not loaded yet (deep link straight to a trace)
+ // is retried once they arrive — otherwise the chip stays permanently unlinked.
+ if (featureFlags?.[FEATURE_FLAGS.ENGINEERING_ANALYTICS] && values.branchPRResolution.gated) {
+ actions.loadBranchPRMatches(values.lastGitMetadata)
+ }
+ },
traceId: (traceId: string) => {
if (traceId) {
actions.loadCommentCount()
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.md
index 1adc37fdc8a3..d7e95dfad6dc 100644
--- a/products/engineering_analytics/SPEC.md
+++ b/products/engineering_analytics/SPEC.md
@@ -301,7 +301,9 @@ Use the current default; revisit when the relevant data lands (§9).
- Commits-till-merged — same; comes with the lifecycle-event data.
- Provider Protocol — wait for a second provider. The read-layer boundary is already drawn to make extraction mechanical.
- Stateful / persisted UI (saved views, persisted filters) — a separate decision once the read-only scene proves out.
-- Cost attribution (agent-token and CI-minute cost per PR) — deferred. Token cost is an LLM analytics join: the `$ai_*_cost_usd` properties on generation events, resolved to a PR by **branch** (head ref → `github_pull_requests.head.ref`), not `head_sha` — the PR snapshot is current-state-only, so a SHA join matches only the latest push and drops every earlier one (undercount). The agent can stamp the branch at capture time even though the PR doesn't exist yet. The grouping is LLM analytics' own; this product owns the branch→PR join plus outcome/lifecycle enrichment. The lever is _cost per outcome_, which needs the lifecycle + git history data above (revert/fixup graph, changed files). See README → "What pays for the destination".
+- Cost attribution (agent-token and CI-minute cost per PR). Token cost is an LLM analytics join: the `$ai_*_cost_usd` properties on generation events, resolved to a PR by **branch** (head ref → `github_pull_requests.head.ref`), not `head_sha` — the PR snapshot is current-state-only, so a SHA join matches only the latest push and drops every earlier one (undercount). The agent can stamp the branch at capture time even though the PR doesn't exist yet. _(Changed — reason: the cost lens on the PR page needs the PR lifetime window + head_ref, both owned here, so this product now owns the branch→PR token-spend rollup on `pr_cost` — the `llm_spend` component. LLM analytics keeps the trace-level cost surfaces.)_ The lever is _cost per outcome_, which needs the lifecycle + git history data above (revert/fixup graph, changed files). See README → "What pays for the destination".
+ `llm_spend` attribution propagates within an AI session (`$ai_session_id`, falling back to `$ai_trace_id`), not just per-event: when a session's first non-base-branch stamp is the PR's head ref, the pre-branch lead-in (unstamped or base-ref-stamped events) counts too, and later unstamped events follow the most recently stamped branch. The full rule — and why base-ref stamps are neutral — is stated once in `logic/queries/llm_spend.py`; the PR-lifetime window + repo guard stay the outer filter on every counted event.
+ The branch → PR resolution this join relies on exists as the `resolve_branch` endpoint: a cross-product caller (LLM analytics) passes a git branch and gets back the PR(s) it belongs to, resolving against `head.ref` — the one place that attribution is defined, so callers don't re-derive it. It is the read seam for linking a git branch to a PR.
## 9. Data sources
diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.py
index e297cab8c4ca..0dc200247393 100644
--- a/products/engineering_analytics/backend/facade/api.py
+++ b/products/engineering_analytics/backend/facade/api.py
@@ -24,6 +24,7 @@ from posthog.models.team import Team
from products.engineering_analytics.backend import logic
from products.engineering_analytics.backend.facade.contracts import (
+ BranchPRMatch,
CICardSummary,
CIFailureLogs,
CurrentBranchHealth,
@@ -48,20 +49,29 @@ from products.engineering_analytics.backend.facade.contracts import (
)
if TYPE_CHECKING:
+ from datetime import datetime
+
from posthog.rbac.user_access_control import UserAccessControl
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
def _authorized_source(
- team: Team, source_id: str | None, user_access_control: "UserAccessControl | None"
+ team: Team,
+ source_id: str | None,
+ user_access_control: "UserAccessControl | None",
+ repo: str | None = None,
) -> "CuratedGitHubSource":
"""Resolve this caller's curated read handle — the single place source selection and per-source
warehouse access control happen. ``user_access_control`` (None for system/Temporal/CLI contexts)
filters out sources the requesting user can't access; ``source_id`` selects a specific source,
- else the oldest connected. Raises ``GitHubSourceNotConnectedError`` / ``ValueError`` (bad source_id).
+ else the oldest connected. ``repo`` ('owner/name'), when the caller already scopes to one repo,
+ prefers the source connected for that repo — so a team with one source per repository reads the
+ right one. Raises ``GitHubSourceNotConnectedError`` / ``ValueError`` (bad source_id).
"""
- return logic.CuratedGitHubSource.for_team(team, source_id=source_id, user_access_control=user_access_control)
+ return logic.CuratedGitHubSource.for_team(
+ team, source_id=source_id, repo=repo, user_access_control=user_access_control
+ )
def get_pr_lifecycle(
@@ -73,7 +83,7 @@ def get_pr_lifecycle(
user_access_control: "UserAccessControl | None" = None,
) -> PRLifecycle | None:
return logic.build_pr_lifecycle(
- curated=_authorized_source(team, source_id, user_access_control), pr_number=pr_number, repo=repo
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo), pr_number=pr_number, repo=repo
)
@@ -86,7 +96,7 @@ def get_pr_cost(
user_access_control: "UserAccessControl | None" = None,
) -> PRCostSummary:
return logic.build_pr_cost(
- curated=_authorized_source(team, source_id, user_access_control), pr_number=pr_number, repo=repo
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo), pr_number=pr_number, repo=repo
)
@@ -109,7 +119,30 @@ def list_pr_runs(
user_access_control: "UserAccessControl | None" = None,
) -> list[WorkflowRunDetail]:
return logic.build_pr_runs(
- curated=_authorized_source(team, source_id, user_access_control), pr_number=pr_number, repo=repo
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo), pr_number=pr_number, repo=repo
+ )
+
+
+def resolve_branch(
+ *,
+ team: Team,
+ branch: str | None = None,
+ repo: str | None = None,
+ timestamp: "datetime | None" = None,
+ source_id: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
+) -> list[BranchPRMatch]:
+ """Resolve a git branch to the pull request(s) it belongs to — the cross-product link seam
+ (LLM analytics links a git branch to a PR detail page). ``branch`` is required; ``repo``
+ ('owner/name') optionally narrows to one repository. ``timestamp`` (the trace's capture time)
+ prefers the PR that was active at that moment when a branch name was reused across PRs over
+ time — a ranking hint only, never a filter.
+ """
+ return logic.build_resolve_branch(
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),
+ branch=branch,
+ repo=repo,
+ timestamp=timestamp,
)
@@ -122,7 +155,7 @@ def get_ci_failure_logs(
user_access_control: "UserAccessControl | None" = None,
) -> CIFailureLogs:
return logic.build_ci_failure_logs(
- curated=_authorized_source(team, source_id, user_access_control), pr_number=pr_number, repo=repo
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo), pr_number=pr_number, repo=repo
)
@@ -138,7 +171,7 @@ def list_workflow_runs(
user_access_control: "UserAccessControl | None" = None,
) -> list[WorkflowRunDetail]:
return logic.build_workflow_run_list(
- curated=_authorized_source(team, source_id, user_access_control),
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),
repo=repo,
workflow_name=workflow_name,
date_from=date_from,
@@ -159,7 +192,7 @@ def get_workflow_run_activity(
user_access_control: "UserAccessControl | None" = None,
) -> WorkflowRunActivity:
return logic.build_workflow_run_activity(
- curated=_authorized_source(team, source_id, user_access_control),
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),
repo=repo,
workflow_name=workflow_name,
date_from=date_from,
@@ -180,7 +213,7 @@ def get_workflow_runner_costs(
user_access_control: "UserAccessControl | None" = None,
) -> list[WorkflowRunnerCost]:
return logic.build_workflow_runner_costs(
- curated=_authorized_source(team, source_id, user_access_control),
+ curated=_authorized_source(team, source_id, user_access_control, repo=repo),
repo=repo,
workflow_name=workflow_name,
date_from=date_from,
diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.py
index 6c43552d0cdc..c07befcda2ca 100644
--- a/products/engineering_analytics/backend/facade/contracts.py
+++ b/products/engineering_analytics/backend/facade/contracts.py
@@ -345,6 +345,23 @@ class RunCost:
estimated_cost_usd: float | None
+@dataclass(frozen=True)
+class PRLLMSpend:
+ """Agent LLM token spend attributed to one PR, summed over the ``$ai_generation`` events stamped
+ with the PR's git branch (``$ai_git_branch``).
+
+ Attribution is by branch, not head SHA: a coding agent stamps the branch at capture time — before
+ the PR exists — and the ``github_pull_requests`` snapshot keeps only the latest head, so a SHA join
+ would drop every push but the last. Surfaced as ``PRCostSummary.llm_spend``, and None there when no
+ generation matched (so the UI hides the row rather than showing a $0 line).
+ """
+
+ cost_usd: float
+ input_tokens: int
+ output_tokens: int
+ generations: int
+
+
@dataclass(frozen=True)
class PRCostSummary:
"""Estimated CI spend for one PR, summed over the jobs of all its workflow runs.
@@ -375,6 +392,10 @@ class PRCostSummary:
# Same spend broken down per workflow run, keyed by (run_id, run_attempt), so the expanded runs
# table under a workflow can show a per-run cost column (rolling up to the per-workflow figure).
by_run: list[RunCost]
+ # Agent LLM token spend attributed to this PR by git branch ($ai_git_branch), or None when no
+ # $ai_generation matched — independent of the CI cost figures above, so it can be present even when
+ # jobs_available is False (the two spend sources sync separately).
+ llm_spend: PRLLMSpend | None = None
@dataclass(frozen=True)
@@ -576,6 +597,19 @@ class PullRequestList:
limit: int
+@dataclass(frozen=True)
+class BranchPRMatch:
+ """A pull request a git branch resolves to — the cross-product link seam so a caller
+ (e.g. the LLM analytics UI) can turn a git branch into a PR detail link. ``repo`` is 'owner/name'.
+ ``title`` / ``state`` are null only when the snapshot carries no value for them.
+ """
+
+ repo: str
+ number: int
+ title: str | None
+ state: str | None
+
+
@dataclass(frozen=True)
class CICardSummary:
"""Headline counts for the open-PR backlog. ``failing_ci`` rests on the
diff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.py
index fc9103b9a5d5..d5287f9cebad 100644
--- a/products/engineering_analytics/backend/logic/__init__.py
+++ b/products/engineering_analytics/backend/logic/__init__.py
@@ -7,13 +7,17 @@ table names), then returns canonical contract types. The curated query builders
only in canonical types.
"""
+from dataclasses import replace
from datetime import datetime
from typing import TYPE_CHECKING
+import structlog
+
from posthog.models.team import Team
from posthog.utils import relative_date_parse
from products.engineering_analytics.backend.facade.contracts import (
+ BranchPRMatch,
CICardSummary,
CIFailureLogs,
CurrentBranchHealth,
@@ -47,6 +51,7 @@ from products.engineering_analytics.backend.logic.queries.ci_failure_logs import
from products.engineering_analytics.backend.logic.queries.current_branch_health import query_current_branch_health
from products.engineering_analytics.backend.logic.queries.flaky_tests import query_flaky_tests
from products.engineering_analytics.backend.logic.queries.job_aggregates import query_job_aggregates
+from products.engineering_analytics.backend.logic.queries.llm_spend import query_pr_llm_spend
from products.engineering_analytics.backend.logic.queries.master_failures import query_master_failures
from products.engineering_analytics.backend.logic.queries.pr_cost import (
query_author_workflow_costs,
@@ -63,6 +68,7 @@ from products.engineering_analytics.backend.logic.queries.repo_overview import (
query_repo_series,
)
from products.engineering_analytics.backend.logic.queries.repo_run_activity import query_repo_run_activity
+from products.engineering_analytics.backend.logic.queries.resolve_branch import query_resolve_branch
from products.engineering_analytics.backend.logic.queries.workflow_health import query_workflow_health
from products.engineering_analytics.backend.logic.queries.workflow_jobs import query_workflow_jobs
from products.engineering_analytics.backend.logic.queries.workflow_run import query_workflow_run
@@ -73,6 +79,8 @@ from products.engineering_analytics.backend.logic.sources import list_github_sou
if TYPE_CHECKING:
from posthog.rbac.user_access_control import UserAccessControl
+logger = structlog.get_logger(__name__)
+
# Default recency window when a caller omits date_from. Relative strings (-30d) and
# ISO8601 are both accepted and resolved against the team's timezone.
_DEFAULT_WINDOW = "-30d"
@@ -112,6 +120,20 @@ def build_pr_runs(*, curated: CuratedGitHubSource, pr_number: int, repo: str | N
return query_pr_runs(curated=curated, pr_number=pr_number, repo_owner=owner, repo_name=name)
+def build_resolve_branch(
+ *, curated: CuratedGitHubSource, branch: str | None, repo: str | None, timestamp: datetime | None = None
+) -> list[BranchPRMatch]:
+ resolved_branch = (branch or "").strip()
+ if not resolved_branch:
+ raise ValueError("provide a branch to resolve")
+ # repo is an optional narrowing filter: absent -> (None, None); malformed (bare org) -> raises.
+ owner, name = _split_repo(repo)
+ # timestamp (the trace's capture time) only reorders results toward the PR active then; never filters.
+ return query_resolve_branch(
+ curated=curated, branch=resolved_branch, repo_owner=owner, repo_name=name, timestamp=timestamp
+ )
+
+
def build_ci_failure_logs(*, curated: CuratedGitHubSource, pr_number: int, repo: str | None) -> CIFailureLogs:
owner, name = _split_repo(repo)
if not (owner and name):
@@ -123,7 +145,19 @@ def build_pr_cost(*, curated: CuratedGitHubSource, pr_number: int, repo: str | N
owner, name = _split_repo(repo)
if not (owner and name):
raise ValueError("repo must be in 'owner/name' format")
- return query_pr_cost(curated=curated, pr_number=pr_number, repo_owner=owner, repo_name=name)
+ # LLM token spend is an additive component joined by branch from the events table, merged onto the
+ # CI cost summary. Kept sequential: HogQL table resolution reads warehouse metadata through the
+ # request's DB connection, which worker threads don't share.
+ summary = query_pr_cost(curated=curated, pr_number=pr_number, repo_owner=owner, repo_name=name)
+ # The spend join scans the events table across the PR's whole lifetime, so a long-lived PR on an
+ # AI-heavy team can time out; the enrichment is optional, so it degrades to null instead of
+ # taking the whole cost summary down with it.
+ try:
+ llm_spend = query_pr_llm_spend(curated=curated, pr_number=pr_number, repo_owner=owner, repo_name=name)
+ except Exception:
+ logger.warning("engineering_analytics.pr_llm_spend_failed", pr_number=pr_number, exc_info=True)
+ llm_spend = None
+ return replace(summary, llm_spend=llm_spend)
def build_workflow_run(*, curated: CuratedGitHubSource, run_id: int) -> WorkflowRunDetail | None:
diff --git a/products/engineering_analytics/backend/logic/queries/_curated.py b/products/engineering_analytics/backend/logic/queries/_curated.py
index 402b8dd52202..3e6f03f5e0ec 100644
--- a/products/engineering_analytics/backend/logic/queries/_curated.py
+++ b/products/engineering_analytics/backend/logic/queries/_curated.py
@@ -61,11 +61,18 @@ class CuratedGitHubSource:
@classmethod
def for_team(
- cls, team: Team, *, source_id: str | None = None, user_access_control: "UserAccessControl | None" = None
+ cls,
+ team: Team,
+ *,
+ source_id: str | None = None,
+ repo: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
) -> "CuratedGitHubSource":
return cls(
team=team,
- tables=resolve_github_tables(team=team, source_id=source_id, user_access_control=user_access_control),
+ tables=resolve_github_tables(
+ team=team, source_id=source_id, repo=repo, user_access_control=user_access_control
+ ),
user_access_control=user_access_control,
)
diff --git a/products/engineering_analytics/backend/logic/queries/_pr_header.py b/products/engineering_analytics/backend/logic/queries/_pr_header.py
new file mode 100644
index 000000000000..10ffc4251a63
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/_pr_header.py
@@ -0,0 +1,37 @@
+"""Shared fetch-one-PR-row query used by the per-PR queries.
+
+``pr_lifecycle`` and ``llm_spend`` both pull the newest matching PR row keyed on
+``(number, repo_owner, repo_name)`` and differ only in the columns they select. Centralizing the
+WHERE/ORDER/LIMIT tail and the placeholders (same idea as ``_run_detail``'s column list) keeps the
+row-selection rule — the newest-snapshot tie-break — defined once, so a future change can't drift
+between the two call sites.
+
+Duplicate snapshot rows of one PR share the same ``created_at`` (the PR's creation time), so ordering
+on it alone lets an arbitrary/stale row win. ``updated_at`` (the snapshot's last-write time) breaks the
+tie toward the freshest row; it can be NULL on a malformed snapshot, so ``created_at`` stays the
+secondary key.
+"""
+
+from posthog.hogql import ast
+
+# The newest PR row for (number, repo_owner, repo_name). Callers pass their own SELECT column list and
+# fill __PR_SOURCE__ with the curated subquery. {value} placeholders survive for parse_select.
+_TAIL = """
+ FROM __PR_SOURCE__ AS pr
+ WHERE number = {pr_number} AND repo_owner = {repo_owner} AND repo_name = {repo_name}
+ ORDER BY updated_at DESC, created_at DESC
+ LIMIT 1
+"""
+
+
+def pr_header_query(select_clause: str) -> str:
+ """Wrap a SELECT column list into the shared newest-PR-row fetch (WHERE/ORDER/LIMIT)."""
+ return f"SELECT {select_clause}\n{_TAIL}"
+
+
+def pr_header_placeholders(*, pr_number: int, repo_owner: str, repo_name: str) -> dict[str, ast.Expr]:
+ return {
+ "pr_number": ast.Constant(value=pr_number),
+ "repo_owner": ast.Constant(value=repo_owner),
+ "repo_name": ast.Constant(value=repo_name),
+ }
diff --git a/products/engineering_analytics/backend/logic/queries/llm_spend.py b/products/engineering_analytics/backend/logic/queries/llm_spend.py
new file mode 100644
index 000000000000..9d38b8609b43
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/llm_spend.py
@@ -0,0 +1,174 @@
+"""HogQL for the agent LLM token spend attributed to one PR.
+
+Attribution is by git **branch**, not head SHA: a coding agent stamps ``$ai_git_branch`` on its
+``$ai_generation`` events at capture time — before the PR exists — and the ``github_pull_requests``
+snapshot keeps only the latest head, so a head-SHA join would drop every push but the last (SPEC §7).
+Reads the ``events`` table directly (not the warehouse) through the same curated read handle, so the
+team scope and warehouse ACL bypass rules stay in one place.
+
+**Attribution rule (session propagation).** A per-event branch stamp alone under-counts: an agent
+explores, runs tools, and thinks *before* it creates the feature branch, and those early generations
+are stamped with whatever branch was checked out at the time — typically the base branch (agents stamp
+every event, so pre-branch work carries the base ref, not a blank). To credit that lead-in to the PR
+it became, spend is grouped by AI session (``$ai_session_id``, falling back to ``$ai_trace_id``) and,
+for a session whose first non-base branch stamp is this PR's head ref H, the following count toward H:
+
+1. any event stamped H directly (the plain branch rule, always preserved);
+2. the prefix — events before that first feature stamp that are unstamped or stamped with the base ref
+ M — because that is the pre-branch exploration that produced the branch (base-ref stamps are neutral
+ here for exactly that reason: they are what an always-stamping agent writes before the branch exists);
+3. carry-forward — an unstamped event after the first feature stamp counts for whichever branch was most
+ recently stamped at-or-before it, covering generations the agent emits without re-stamping the branch.
+
+Base-ref stamps at or after the first feature stamp are neutral, not credited: switching back to the
+base branch ends attribution. Events stamped with any other branch never count toward H. Events with no
+session and no trace id have no group, so they can only count via their own direct H stamp. The window
+and repo guard stay the OUTER filter on every counted event: only in-window candidates form the groups.
+"""
+
+from datetime import timedelta
+
+from django.utils import timezone
+
+from posthog.hogql import ast
+
+from products.engineering_analytics.backend.facade.contracts import PRLLMSpend
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries._pr_header import pr_header_placeholders, pr_header_query
+
+# Tokens are spent before a PR opens (the agent runs, then the PR is created), so the window reaches
+# back this far from created_at. The tradeoff: head_branch is reused across PRs over time, so a
+# recycled branch can pull in a neighbouring PR's spend — bounded by capping the window at the PR's
+# own open→merge/close life (below).
+_LEAD_DAYS = 14
+
+_HEADER = pr_header_query("head_branch, base_branch, created_at, merged_at, closed_at")
+
+# The repo guard keeps events that stamped no $ai_git_repo (older agents that only carried the branch)
+# while still rejecting a same-named branch in a different repo once the repo is stamped. The compare
+# is case-insensitive: GitHub repo names are, and the stamped slug comes from a clone URL whose casing
+# need not match GitHub's canonical full_name. coalesce collapses both NULL (property absent) and ''
+# to the pass-through case. The group key is the AI session, falling back to the trace id; empty
+# properties are treated as absent everywhere (nullIf on '').
+_CANDIDATES = """
+ candidates AS (
+ SELECT
+ timestamp AS ts,
+ coalesce(properties.$ai_git_branch, '') AS branch,
+ coalesce(nullIf(properties.$ai_session_id, ''), nullIf(properties.$ai_trace_id, ''), '') AS group_key,
+ toFloat(properties.$ai_total_cost_usd) AS cost,
+ toInt(properties.$ai_input_tokens) AS input_tokens,
+ toInt(properties.$ai_output_tokens) AS output_tokens
+ FROM events
+ WHERE event = '$ai_generation'
+ AND (coalesce(properties.$ai_git_repo, '') = '' OR lower(properties.$ai_git_repo) = {repo_full})
+ AND timestamp >= {window_start}
+ AND timestamp <= {window_end}
+ )
+"""
+
+# Eligible groups only: a group counts toward H once it holds at least one H stamp (the HAVING). Per
+# group, `stamps` is the timestamp-sorted array of (ts, branch) for its stamped events; `feature` is
+# the first stamp whose branch is not the base ref M — the "first feature stamp" that anchors the
+# prefix (before it) and the carry-forward (at/after it).
+_GROUP_STAMPS = """
+ group_stamps AS (
+ SELECT
+ group_key,
+ stamps,
+ tupleElement(feature, 1) AS feature_ts,
+ tupleElement(feature, 2) AS feature_branch
+ FROM (
+ SELECT
+ group_key,
+ arraySort(x -> tupleElement(x, 1), groupArray(tuple(ts, branch))) AS stamps,
+ arrayFirst(s -> tupleElement(s, 2) != {base}, stamps) AS feature
+ FROM candidates
+ WHERE branch != '' AND group_key != ''
+ GROUP BY group_key
+ HAVING countIf(branch = {branch}) > 0
+ )
+ )
+"""
+
+# One pass over candidates (ClickHouse re-evaluates a WITH subquery per reference, so a UNION of
+# candidate scans would read events once per arm). Each candidate row counts at most once, when any
+# rule matches: its own H stamp (rule 1), or — via its eligible group's stamps — the prefix (rule 2)
+# or the carry-forward (rule 3). LEFT ANY JOIN because group_stamps is unique per key; ungrouped rows
+# and rows in ineligible groups join to nothing (g.group_key = ''), so only rule 1 can pass for them.
+# Every counted event flows from `candidates`, which already pins the window and repo guard.
+_SPEND = """
+ WITH
+ __CANDIDATES__,
+ __GROUP_STAMPS__
+ SELECT
+ sum(c.cost) AS cost_usd,
+ sum(c.input_tokens) AS input_tokens,
+ sum(c.output_tokens) AS output_tokens,
+ count() AS generations
+ FROM candidates AS c
+ LEFT ANY JOIN group_stamps AS g ON c.group_key = g.group_key
+ WHERE c.branch = {branch}
+ OR (g.group_key != ''
+ AND (
+ ((c.branch = '' OR c.branch = {base}) AND c.ts < g.feature_ts AND g.feature_branch = {branch})
+ OR (c.branch = '' AND c.ts >= g.feature_ts
+ AND tupleElement(arrayLast(s -> tupleElement(s, 1) <= c.ts, g.stamps), 2) = {branch})
+ ))
+""".replace("__CANDIDATES__", _CANDIDATES).replace("__GROUP_STAMPS__", _GROUP_STAMPS)
+
+
+def query_pr_llm_spend(
+ *,
+ curated: CuratedGitHubSource,
+ pr_number: int,
+ repo_owner: str,
+ repo_name: str,
+) -> PRLLMSpend | None:
+ header = curated.run(
+ _HEADER.replace("__PR_SOURCE__", curated.pr_source()),
+ query_type="engineering_analytics.pr_llm_spend.header",
+ placeholders=pr_header_placeholders(pr_number=pr_number, repo_owner=repo_owner, repo_name=repo_name),
+ )
+ if not header.results:
+ return None
+ head_branch, base_branch, created_at, merged_at, closed_at = header.results[0]
+ # No branch means nothing to join on; no created_at means the window can't be placed (created_at
+ # comes from parseDateTimeBestEffort, which yields NULL on a malformed value).
+ if not head_branch or created_at is None:
+ return None
+ # A PR whose head is its own base (a fork PR from default to default) can't be branch-attributed:
+ # the direct rule would sweep every default-branch generation in the window onto it. No
+ # attribution beats wrong attribution.
+ if head_branch == base_branch:
+ return None
+
+ # Open PRs are still accruing spend, so cap at now(); a closed/merged PR caps at its close.
+ window_end = merged_at or closed_at or timezone.now()
+ response = curated.run(
+ _SPEND,
+ query_type="engineering_analytics.pr_llm_spend",
+ placeholders={
+ "branch": ast.Constant(value=head_branch),
+ # base_branch can be empty on a malformed snapshot; '' is a branch no event ever stamps, so
+ # the base-neutral prefix rule simply falls back to "unstamped only", never mis-crediting.
+ "base": ast.Constant(value=base_branch or ""),
+ "repo_full": ast.Constant(value=f"{repo_owner}/{repo_name}".lower()),
+ "window_start": ast.Constant(value=created_at - timedelta(days=_LEAD_DAYS)),
+ "window_end": ast.Constant(value=window_end),
+ },
+ )
+ rows = response.results or []
+ if not rows:
+ return None
+ cost_usd, input_tokens, output_tokens, generations = rows[0]
+ generations = int(generations or 0)
+ # None when nothing matched, so the endpoint returns llm_spend=null and the UI hides the row.
+ if generations == 0:
+ return None
+ return PRLLMSpend(
+ cost_usd=float(cost_usd or 0.0),
+ input_tokens=int(input_tokens or 0),
+ output_tokens=int(output_tokens or 0),
+ generations=generations,
+ )
diff --git a/products/engineering_analytics/backend/logic/queries/pr_lifecycle.py b/products/engineering_analytics/backend/logic/queries/pr_lifecycle.py
index 1ea4711f62db..3dce7ee5d949 100644
--- a/products/engineering_analytics/backend/logic/queries/pr_lifecycle.py
+++ b/products/engineering_analytics/backend/logic/queries/pr_lifecycle.py
@@ -22,20 +22,18 @@ from products.engineering_analytics.backend.facade.contracts import (
RepoRef,
)
from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries._pr_header import pr_header_placeholders, pr_header_query
# The curated subqueries and the repo filter are filled with str.replace (trusted
# constants), leaving the HogQL {value} placeholders untouched for parse_select.
-_HEADER = """
- SELECT
+_HEADER = pr_header_query(
+ """
id, number, title, state, is_draft,
created_at, merged_at, closed_at,
author_handle, author_avatar_url, is_bot,
repo_owner, repo_name, head_sha
- FROM __PR_SOURCE__ AS pr
- WHERE number = {pr_number} AND repo_owner = {repo_owner} AND repo_name = {repo_name}
- ORDER BY created_at DESC
- LIMIT 1
-"""
+ """
+)
_RUNS = """
SELECT id, workflow_name, status, conclusion, run_started_at, updated_at
@@ -52,11 +50,7 @@ def query_pr_lifecycle(
repo_owner: str,
repo_name: str,
) -> PRLifecycle | None:
- placeholders: dict[str, ast.Expr] = {
- "pr_number": ast.Constant(value=pr_number),
- "repo_owner": ast.Constant(value=repo_owner),
- "repo_name": ast.Constant(value=repo_name),
- }
+ placeholders = pr_header_placeholders(pr_number=pr_number, repo_owner=repo_owner, repo_name=repo_name)
header_sql = _HEADER.replace("__PR_SOURCE__", curated.pr_source())
header = curated.run(
header_sql,
diff --git a/products/engineering_analytics/backend/logic/queries/resolve_branch.py b/products/engineering_analytics/backend/logic/queries/resolve_branch.py
new file mode 100644
index 000000000000..acb940272916
--- /dev/null
+++ b/products/engineering_analytics/backend/logic/queries/resolve_branch.py
@@ -0,0 +1,99 @@
+"""HogQL resolution of a git branch to the pull request(s) it belongs to.
+
+Powers the cross-product branch → PR link: another product (the LLM analytics UI)
+turns a git branch into a PR detail link without re-deriving PostHog's PR↔CI attribution.
+
+Matched directly against the PR snapshot's source branch (``head_branch`` = ``head.ref`` on
+the curated PR source), open PRs first then most recently updated. A branch is reused across
+PRs over time, so ordering surfaces the current one first, and the scan is time-bounded (a
+resolving trace is recent). When a ``timestamp`` is passed (the trace's capture time), a PR whose
+lifetime window contains that moment ranks ahead of one whose window doesn't — so a reused branch
+resolves to the PR that was active when the trace was captured, not whichever PR is newest now.
+This is ranking only, never a filter: the open-first / most-recently-updated order stays as the
+tiebreaker, and with no timestamp the behavior is unchanged. Results are capped — a reused branch
+can span several PRs, so the return is a possibly-empty, possibly-multi set.
+"""
+
+from datetime import datetime
+
+from posthog.hogql import ast
+
+from products.engineering_analytics.backend.facade.contracts import BranchPRMatch
+from products.engineering_analytics.backend.logic.queries._curated import CuratedGitHubSource
+from products.engineering_analytics.backend.logic.queries.llm_spend import _LEAD_DAYS
+
+# A branch usually resolves to one PR; cap low so a reused branch stays bounded.
+_LIMIT = 5
+
+# When a trace timestamp is passed, rank a PR whose lifetime window contains it ahead of one whose
+# window doesn't. The window opens _LEAD_DAYS before created_at because agent work (and its trace)
+# starts before the PR is opened; this lead-in must match llm_spend's spend-attribution window, so
+# the constant is imported rather than duplicated. Inserted only when a timestamp is given.
+_TS_RANK = (
+ f"(pr.created_at - INTERVAL {_LEAD_DAYS} DAY <= {{ts}} "
+ "AND {ts} <= coalesce(pr.merged_at, pr.closed_at, now())) DESC, "
+)
+
+# Match the PR snapshot's source branch directly; open first, then most recently updated. The
+# recency bound keeps the snapshot scan cheap — a trace resolving here was captured recently, so a
+# PR untouched for over a year can't be the one it means.
+_BRANCH_SELECT = f"""
+ SELECT
+ pr.repo_owner AS repo_owner,
+ pr.repo_name AS repo_name,
+ pr.number AS number,
+ pr.title AS title,
+ pr.state AS state
+ FROM __PR_SOURCE__ AS pr
+ WHERE pr.head_branch = {{branch}} AND pr.updated_at >= now() - INTERVAL 1 YEAR __REPO__
+ ORDER BY __TS_RANK__ pr.state = 'open' DESC, pr.updated_at DESC
+ LIMIT {_LIMIT}
+"""
+
+
+def query_resolve_branch(
+ *,
+ curated: CuratedGitHubSource,
+ branch: str,
+ repo_owner: str | None,
+ repo_name: str | None,
+ timestamp: datetime | None = None,
+) -> list[BranchPRMatch]:
+ placeholders: dict[str, ast.Expr] = {"branch": ast.Constant(value=branch)}
+ repo_clause = _repo_clause("pr", repo_owner, repo_name, placeholders)
+ ts_rank = ""
+ if timestamp is not None:
+ placeholders["ts"] = ast.Constant(value=timestamp)
+ ts_rank = _TS_RANK
+ response = curated.run(
+ _BRANCH_SELECT.replace("__PR_SOURCE__", curated.pr_source())
+ .replace("__REPO__", repo_clause)
+ .replace("__TS_RANK__", ts_rank),
+ query_type="engineering_analytics.resolve_branch",
+ placeholders=placeholders,
+ )
+ return [_to_match(row) for row in (response.results or [])]
+
+
+def _repo_clause(alias: str, repo_owner: str | None, repo_name: str | None, placeholders: dict[str, ast.Expr]) -> str:
+ """Optional 'owner/name' narrowing on the given alias; a no-op filter when no repo was passed.
+
+ Case-insensitive: GitHub repo names are, and the caller's slug comes from a clone URL whose
+ casing need not match GitHub's canonical ``full_name``.
+ """
+ if not (repo_owner and repo_name):
+ return ""
+ placeholders["repo_owner"] = ast.Constant(value=repo_owner.lower())
+ placeholders["repo_name"] = ast.Constant(value=repo_name.lower())
+ return f"AND lower({alias}.repo_owner) = {{repo_owner}} AND lower({alias}.repo_name) = {{repo_name}}"
+
+
+def _to_match(row: tuple) -> BranchPRMatch:
+ repo_owner, repo_name, number, title, state = row
+ return BranchPRMatch(
+ repo=f"{repo_owner}/{repo_name}",
+ number=int(number),
+ # The '' state default comes back empty — normalize to None.
+ title=title or None,
+ state=state or None,
+ )
diff --git a/products/engineering_analytics/backend/logic/sources.py b/products/engineering_analytics/backend/logic/sources.py
index 8155058b1f4d..ea9200b1576e 100644
--- a/products/engineering_analytics/backend/logic/sources.py
+++ b/products/engineering_analytics/backend/logic/sources.py
@@ -12,7 +12,8 @@ and threaded down into the builders, so a request hits the warehouse models a si
A team can connect GitHub more than once (e.g. one source per repository). A caller may pass
``source_id`` to read a specific source; otherwise the oldest connected source with both
-endpoints synced is used.
+endpoints synced is used, or — when a ``repo`` ('owner/name') is passed — the source whose
+``job_inputs.repository`` matches that repo, so a repo-scoped call reads the right source.
"""
import re
@@ -60,7 +61,11 @@ class GitHubTables:
def resolve_github_tables(
- *, team: Team, source_id: str | None = None, user_access_control: "UserAccessControl | None" = None
+ *,
+ team: Team,
+ source_id: str | None = None,
+ repo: str | None = None,
+ user_access_control: "UserAccessControl | None" = None,
) -> GitHubTables:
"""Resolve the team's curated GitHub table names from its warehouse models.
@@ -71,15 +76,23 @@ def resolve_github_tables(
presentation layer maps it to a 400, so the UI prompts to connect a source and an agent gets
an actionable error), or ``ValueError`` when ``source_id`` is not a UUID.
+ ``repo`` ('owner/name') scopes a repo-specific call — a team with one source per repository
+ otherwise always resolves the oldest, so a repo-scoped read (e.g. ``resolve_branch``) would
+ search the wrong repo's tables. When ``repo`` is given (and ``source_id`` is not), sources
+ whose ``job_inputs.repository`` equals it (case-insensitively) are tried first; the remaining
+ sources still follow as a fallback, since the ``repository`` input can be empty and the
+ per-source data may still hold the repo.
+
``user_access_control`` enforces the requesting user's per-source warehouse RBAC (applied in
``_github_sources``): a denied ``source_id`` raises (400) and the default-oldest path skips it.
The curated HogQL runs team-scoped with no user and HogQL does not enforce per-user ACL on
warehouse tables, so honoring it here is the only way the read path can. ``None`` (system/
Temporal/CLI contexts with no request user) skips filtering — team scoping still holds.
"""
- sources = _github_sources(team, user_access_control)
+ queryset = _github_sources(team, user_access_control)
if source_id is not None:
- sources = sources.filter(id=_as_source_uuid(source_id))
+ queryset = queryset.filter(id=_as_source_uuid(source_id))
+ sources: list[ExternalDataSource] = _repo_first(queryset, repo) if repo and source_id is None else list(queryset)
for source in sources:
tables = _synced_table_names(team=team, source=source)
pull_requests = tables.get(PULL_REQUESTS_SCHEMA)
@@ -141,6 +154,24 @@ def list_github_sources(*, team: Team, user_access_control: "UserAccessControl |
]
+def _repo_first(sources: QuerySet[ExternalDataSource], repo: str) -> list[ExternalDataSource]:
+ """Sources whose ``job_inputs.repository`` matches ``repo`` (case-insensitive), then the rest.
+
+ Both groups keep the queryset's oldest-first order, so among equal candidates the established
+ connection still wins; the non-matching tail is a fallback for sources with an empty
+ ``repository`` input whose data may still hold the repo.
+ """
+ wanted = repo.casefold()
+ matching: list[ExternalDataSource] = []
+ others: list[ExternalDataSource] = []
+ for source in sources:
+ if _source_repository(source).casefold() == wanted:
+ matching.append(source)
+ else:
+ others.append(source)
+ return matching + others
+
+
def _github_sources(team: Team, user_access_control: "UserAccessControl | None" = None) -> QuerySet[ExternalDataSource]:
"""The team's non-deleted GitHub sources the caller may access, oldest first — the order
``resolve_github_tables`` defaults from, so a picker's first entry matches the default source.
diff --git a/products/engineering_analytics/backend/logic/views/pull_requests.py b/products/engineering_analytics/backend/logic/views/pull_requests.py
index 1d7837b43200..abbe45a05822 100644
--- a/products/engineering_analytics/backend/logic/views/pull_requests.py
+++ b/products/engineering_analytics/backend/logic/views/pull_requests.py
@@ -52,9 +52,12 @@ def build_query(table_name: str) -> str:
if(merged_at IS NOT NULL, 'merged', raw_state) AS state,
is_draft,
created_at,
+ updated_at,
merged_at,
closed_at,
head_sha,
+ head_branch,
+ base_branch,
if(merged_at IS NOT NULL, dateDiff('second', created_at, merged_at), NULL) AS open_to_merge_seconds
FROM (
SELECT
@@ -70,7 +73,13 @@ def build_query(table_name: str) -> str:
splitByChar('/', ifNull(JSONExtractString(base, 'repo', 'full_name'), '')) AS repo_parts,
ifNull(labels, '[]') AS labels_json,
JSONExtractString(head, 'sha') AS head_sha,
+ -- head.ref is the PR's source branch — the key a branch → PR resolution matches on.
+ JSONExtractString(head, 'ref') AS head_branch,
+ -- base.ref is the branch the PR merges into (usually the default branch); the LLM-spend
+ -- session join treats it as neutral, since agents stamp pre-branch exploration with it.
+ JSONExtractString(base, 'ref') AS base_branch,
parseDateTimeBestEffort(created_at) AS created_at,
+ parseDateTimeBestEffort(updated_at) AS updated_at,
parseDateTimeBestEffort(merged_at) AS merged_at,
parseDateTimeBestEffort(closed_at) AS closed_at
FROM {table_name}
diff --git a/products/engineering_analytics/backend/presentation/serializers.py b/products/engineering_analytics/backend/presentation/serializers.py
index c46b561d464d..b71ad3275449 100644
--- a/products/engineering_analytics/backend/presentation/serializers.py
+++ b/products/engineering_analytics/backend/presentation/serializers.py
@@ -11,6 +11,7 @@ from rest_framework_dataclasses.serializers import DataclassSerializer
from products.engineering_analytics.backend.facade.contracts import (
Author,
+ BranchPRMatch,
CICardSummary,
CIFailureLogLine,
CIFailureLogs,
@@ -27,6 +28,7 @@ from products.engineering_analytics.backend.facade.contracts import (
PRCostSummary,
PRLifecycle,
PRLifecycleEvent,
+ PRLLMSpend,
PullRequest,
PullRequestList,
PullRequestListItem,
@@ -339,11 +341,34 @@ class RunCostSerializer(DataclassSerializer):
}
+class PRLLMSpendSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = PRLLMSpend
+ extra_kwargs = {
+ "cost_usd": {
+ "help_text": "Total agent LLM token cost in USD attributed to this PR "
+ "(sum of $ai_total_cost_usd over the matched $ai_generation events).",
+ },
+ "input_tokens": {"help_text": "Total input (prompt) tokens across the attributed generations."},
+ "output_tokens": {"help_text": "Total output (completion) tokens across the attributed generations."},
+ "generations": {
+ "help_text": "Number of $ai_generation events attributed to this PR by git branch ($ai_git_branch).",
+ },
+ }
+
+
class PRCostSummarySerializer(DataclassSerializer):
by_workflow = WorkflowCostSerializer(many=True, help_text="Same spend broken down per workflow.")
by_run = RunCostSerializer(
many=True, help_text="Same spend broken down per workflow run, keyed by (run_id, run_attempt)."
)
+ llm_spend = PRLLMSpendSerializer(
+ required=False,
+ allow_null=True,
+ help_text="Agent LLM token spend attributed to this PR by git branch ($ai_git_branch), or null when "
+ "no generation matched — independent of the CI cost figures, so it can be present even when "
+ "jobs_available is false. The UI hides the row when null.",
+ )
class Meta:
dataclass = PRCostSummary
@@ -516,6 +541,23 @@ class PullRequestListSerializer(DataclassSerializer):
}
+class BranchPRMatchSerializer(DataclassSerializer):
+ class Meta:
+ dataclass = BranchPRMatch
+ extra_kwargs = {
+ "repo": {"help_text": "Repository the pull request belongs to, as 'owner/name'."},
+ "number": {"help_text": "Pull request number within the repository — pair with `repo` to link to it."},
+ "title": {
+ "help_text": "Pull request title, or null when the snapshot carries no title.",
+ "allow_null": True,
+ },
+ "state": {
+ "help_text": "Derived PR state ('open', 'closed', 'merged'), or null when the snapshot carries no state.",
+ "allow_null": True,
+ },
+ }
+
+
class CICardSummarySerializer(DataclassSerializer):
class Meta:
dataclass = CICardSummary
diff --git a/products/engineering_analytics/backend/presentation/views.py b/products/engineering_analytics/backend/presentation/views.py
index 85959ec36301..0d9dccb793f9 100644
--- a/products/engineering_analytics/backend/presentation/views.py
+++ b/products/engineering_analytics/backend/presentation/views.py
@@ -12,9 +12,11 @@ contract. These same endpoints back both the MCP tools and the UI:
- ``quarantine`` — the repo's checked-in flaky-test quarantine file.
"""
+from datetime import datetime
+
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_schema
-from rest_framework import status, viewsets
+from rest_framework import serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.request import Request
from rest_framework.response import Response
@@ -32,6 +34,7 @@ from products.engineering_analytics.backend.facade.contracts import (
WorkflowHealthRunScope,
)
from products.engineering_analytics.backend.presentation.serializers import (
+ BranchPRMatchSerializer,
CICardSummarySerializer,
CIFailureLogsSerializer,
CurrentBranchHealthSerializer,
@@ -139,6 +142,17 @@ def _optional_int_param(request: Request, name: str) -> int | None:
raise ValueError(f"{name} must be an integer") from None
+def _optional_datetime_param(request: Request, name: str) -> datetime | None:
+ """Optional ISO8601 datetime query param; None when absent/blank, ValueError when present but unparseable."""
+ raw = request.query_params.get(name)
+ if not raw:
+ return None
+ try:
+ return serializers.DateTimeField().to_internal_value(raw)
+ except serializers.ValidationError:
+ raise ValueError(f"{name} must be an ISO8601 datetime") from None
+
+
def _bool_param(request: Request, name: str, *, default: bool) -> bool:
"""Optional boolean query param; the default when absent/blank, ValueError when present but not true/false."""
raw = request.query_params.get(name)
@@ -166,6 +180,7 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
"pull_requests",
"workflow_health",
"pr_lifecycle",
+ "resolve_branch",
"quarantine",
"pr_runs",
"ci_failure_logs",
@@ -358,6 +373,64 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
return Response({"detail": "Pull request not found"}, status=status.HTTP_404_NOT_FOUND)
return Response(PRLifecycleSerializer(instance=result).data)
+ @extend_schema(
+ operation_id="engineering_analytics_resolve_branch",
+ parameters=[
+ OpenApiParameter(
+ name="branch",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=True,
+ description="Git branch (the PR's head ref) to resolve. Open PRs are returned first, then most "
+ "recently updated.",
+ ),
+ OpenApiParameter(
+ name="repo",
+ type=OpenApiTypes.STR,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Optional 'owner/name' repository to narrow matching to a single repo.",
+ ),
+ OpenApiParameter(
+ name="timestamp",
+ type=OpenApiTypes.DATETIME,
+ location=OpenApiParameter.QUERY,
+ required=False,
+ description="Optional ISO8601 timestamp, e.g. the trace's capture time. When a branch name has been "
+ "reused across PRs over time, the PR whose lifetime window contains this moment is ranked first so the "
+ "result matches the PR that was active when the trace was captured. A preference only, not a filter; "
+ "omit to rank purely by open state then recency.",
+ ),
+ _SOURCE_ID,
+ ],
+ responses={
+ 200: BranchPRMatchSerializer(many=True),
+ 400: OpenApiResponse(description="Branch missing/empty, or invalid repo/timestamp/source_id."),
+ },
+ description=(
+ "Resolve a git branch to the pull request(s) it belongs to — the cross-product link seam so another "
+ "product (the LLM analytics UI) can turn a git branch into a PR detail link. Matches the PR's head ref, "
+ "open PRs first then most recently updated. Pass `timestamp` (the trace's capture time) to prefer the PR "
+ "that was active at that moment when a branch name has been reused across PRs. `branch` is required. "
+ "Returns a possibly-empty, possibly-multi list — an empty list is a valid 200 (the caller renders a plain "
+ "chip)."
+ ),
+ )
+ @action(detail=False, methods=["get"], pagination_class=None)
+ def resolve_branch(self, request: Request, **kwargs) -> Response:
+ try:
+ matches = api.resolve_branch(
+ team=self.team,
+ branch=request.query_params.get("branch") or None,
+ repo=request.query_params.get("repo") or None,
+ timestamp=_optional_datetime_param(request, "timestamp"),
+ source_id=request.query_params.get("source_id") or None,
+ user_access_control=self.user_access_control,
+ )
+ except ValueError as exc:
+ return _bad_request(exc, fallback="Provide a branch")
+ return Response(BranchPRMatchSerializer(instance=matches, many=True).data)
+
@extend_schema(
operation_id="engineering_analytics_pr_runs",
parameters=[
@@ -482,7 +555,8 @@ class EngineeringAnalyticsViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe
"Estimated CI cost for a pull request, summed over the jobs of all its workflow runs. "
"Billable self-hosted Linux runners only — provider-hosted (free GitHub-hosted) and non-Linux "
"jobs are excluded. Every figure is zero/null with `jobs_available` false when the job-level "
- "source isn't synced yet."
+ "source isn't synced yet. `llm_spend` carries the agent LLM token spend attributed to the PR "
+ "by git branch, or null when no `$ai_generation` event matched."
),
)
@action(detail=False, methods=["get"], pagination_class=None)
diff --git a/products/engineering_analytics/backend/tests/test_logic.py b/products/engineering_analytics/backend/tests/test_logic.py
index 48523a7204cb..4c7c0038da00 100644
--- a/products/engineering_analytics/backend/tests/test_logic.py
+++ b/products/engineering_analytics/backend/tests/test_logic.py
@@ -5,7 +5,7 @@ from types import SimpleNamespace
from typing import Any
import pytest
-from posthog.test.base import BaseTest, ClickhouseTestMixin
+from posthog.test.base import BaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
from unittest import mock
from django.utils import timezone
@@ -159,9 +159,21 @@ class _WarehouseMixin(ClickhouseTestMixin, BaseTest):
super().setUp()
self._github_source: ExternalDataSource | None = None
- def _create_table(self, base_name: str, columns: dict, rows: list[dict[str, Any]]) -> None:
- if self._github_source is None:
- self._github_source = create_github_source(self.team)
+ def _create_table(
+ self,
+ base_name: str,
+ columns: dict,
+ rows: list[dict[str, Any]],
+ *,
+ source: ExternalDataSource | None = None,
+ prefix: str = GITHUB_SOURCE_PREFIX,
+ ) -> None:
+ # Defaults to the mixin's single shared source; pass source + prefix to seed a second
+ # source (e.g. one GitHub source per repository) under a distinct table prefix.
+ if source is None:
+ if self._github_source is None:
+ self._github_source = create_github_source(self.team)
+ source = self._github_source
df = pd.DataFrame(rows, columns=list(columns.keys()))
tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False)
df.to_csv(tmp.name, index=False)
@@ -174,14 +186,14 @@ class _WarehouseMixin(ClickhouseTestMixin, BaseTest):
table_columns=columns,
test_bucket=TEST_BUCKET,
team=self.team,
- source=self._github_source,
- source_prefix=GITHUB_SOURCE_PREFIX,
+ source=source,
+ source_prefix=prefix,
)
except PermissionError as err:
self.skipTest(f"object storage unavailable: {err}")
self.addCleanup(cleanup)
# base_name is "github_<endpoint>"; the synced schema/endpoint is its suffix.
- link_schema(self.team, self._github_source, name=base_name.removeprefix("github_"), table=table)
+ link_schema(self.team, source, name=base_name.removeprefix("github_"), table=table)
class TestPRLifecycleMapping(BaseTest):
@@ -417,6 +429,34 @@ class TestEndpointMapping(BaseTest):
assert items[1].last_failure_at is None
+class TestResolveBranchMapping(BaseTest):
+ """Row mapping for resolve_branch (query method mocked, no warehouse). A GitHub source is
+ connected (ORM only) so the resolver succeeds before the mocked query runs."""
+
+ def setUp(self) -> None:
+ super().setUp()
+ connect_github_source_without_data(self.team)
+
+ def test_maps_rows_and_normalizes_empty_fields(self) -> None:
+ # branch columns: repo_owner, repo_name, number, title, state. The second row carries an empty
+ # title / null state -> both normalize to None.
+ rows = [("PostHog", "posthog", 42, "Fix bug", "merged"), ("PostHog", "posthog", 7, "", None)]
+ with mock.patch(_RUN_QUERY, return_value=_resp(rows)) as run:
+ matches = api.resolve_branch(team=self.team, branch="feat/x")
+ assert [(m.repo, m.number, m.title, m.state) for m in matches] == [
+ ("PostHog/posthog", 42, "Fix bug", "merged"),
+ ("PostHog/posthog", 7, None, None),
+ ]
+ assert run.call_count == 1
+
+ @parameterized.expand([("branch_none", None), ("branch_blank", " ")])
+ def test_rejects_missing_branch(self, _name: str, branch: str | None) -> None:
+ # Validation raises before any query is issued (source resolution still succeeds first).
+ with mock.patch(_RUN_QUERY) as run, self.assertRaises(ValueError):
+ api.resolve_branch(team=self.team, branch=branch)
+ run.assert_not_called()
+
+
class TestCostPerMergeSeries(BaseTest):
"""The cost-per-merged-PR trend on the repo hub: bucketing, zero-fill, and the cost/merge
division guard. The two warehouse scans are mocked (curated fully faked), so this tests the
@@ -532,6 +572,14 @@ class TestResolveGitHubTables(BaseTest):
pull_requests="myprefixgithub_pull_requests", workflow_runs="myprefixgithub_workflow_runs"
)
+ def test_repo_scoped_resolution_survives_non_dict_job_inputs(self) -> None:
+ # job_inputs is an EncryptedJSONField that can hold any JSON value; the repo-first ordering
+ # must treat a non-dict as "no repository input", not crash the whole resolution.
+ source = self._connect(prefix="weird", schemas=self._BOTH_SYNCED)
+ ExternalDataSource.objects.filter(pk=source.pk).update(job_inputs=["not", "a", "dict"])
+ tables = resolve_github_tables(team=self.team, repo="PostHog/posthog")
+ assert tables.pull_requests == "weirdgithub_pull_requests"
+
def test_raises_without_a_github_source(self) -> None:
with self.assertRaises(GitHubSourceNotConnectedError):
resolve_github_tables(team=self.team)
@@ -891,6 +939,46 @@ class TestEndpointsWarehouse(_WarehouseMixin, BaseTest):
assert {i.number for i in api.list_pull_requests(team=self.team, author="alice").items} == {81}
assert {i.number for i in api.list_pull_requests(team=self.team, author="bob").items} == {82}
+ def test_resolve_branch_orders_open_first(self) -> None:
+ # The branch path matches the PR head ref (head.ref); open PRs come before merged/closed ones,
+ # and PRs on other branches are excluded.
+ self._create_table(
+ "github_pull_requests",
+ _PULL_REQUESTS_COLUMNS,
+ [
+ _pr_row(62, "bob", "closed", 0, _ago(6), merged_at=_ago(1), head_sha="sha62", head_ref="feat/login"),
+ _pr_row(61, "alice", "open", 0, _ago(2), head_sha="sha61", head_ref="feat/login"),
+ _pr_row(63, "carol", "open", 0, _ago(1), head_sha="sha63", head_ref="other"),
+ ],
+ )
+ # Source resolution requires the workflow_runs schema synced too (SPEC: both endpoints
+ # required together), even though the branch path only reads the PR snapshot.
+ self._create_table("github_workflow_runs", _WORKFLOW_RUNS_COLUMNS, [])
+ matches = api.resolve_branch(team=self.team, branch="feat/login")
+ assert [m.number for m in matches] == [61, 62] # only feat/login PRs, open first
+ # A branch matching no PR resolves to nothing (empty list, not an error).
+ assert api.resolve_branch(team=self.team, branch="feat/nothing") == []
+
+ def test_resolve_branch_prefers_pr_active_at_timestamp(self) -> None:
+ # Same head ref reused across PRs over time: an old one merged months ago and a newer open one.
+ self._create_table(
+ "github_pull_requests",
+ _PULL_REQUESTS_COLUMNS,
+ [
+ _pr_row(
+ 70, "bob", "closed", 0, _ago(120), merged_at=_ago(110), head_sha="sha70", head_ref="feat/reuse"
+ ),
+ _pr_row(71, "alice", "open", 0, _ago(2), head_sha="sha71", head_ref="feat/reuse"),
+ ],
+ )
+ self._create_table("github_workflow_runs", _WORKFLOW_RUNS_COLUMNS, [])
+ # No timestamp: open PR wins on the open-first/recency fallback.
+ assert [m.number for m in api.resolve_branch(team=self.team, branch="feat/reuse")] == [71, 70]
+ # A timestamp inside the old PR's lifetime window ranks it first, even though the newer PR is open.
+ during_old = timezone.now() - timedelta(days=112)
+ matches = api.resolve_branch(team=self.team, branch="feat/reuse", timestamp=during_old)
+ assert [m.number for m in matches] == [70, 71]
+
def test_workflow_health_aggregates(self) -> None:
self._seed()
items = api.list_workflow_health(team=self.team, date_from="-30d")
@@ -1541,3 +1629,287 @@ class TestEndpointsWarehouse(_WarehouseMixin, BaseTest):
by_repo = {(item.repo.owner, item.repo.name): item for item in result.items}
assert (by_repo[("PostHog", "posthog")].pushes, by_repo[("PostHog", "posthog")].rerun_cycles) == (1, 0)
assert (by_repo[("PostHog", "posthog.com")].pushes, by_repo[("PostHog", "posthog.com")].rerun_cycles) == (2, 1)
+
+
+class TestPRLLMSpendWarehouse(_WarehouseMixin, BaseTest):
+ """LLM token spend attributed to a PR by git branch, over a real warehouse PR row plus
+ $ai_generation events. Skips when object storage is unreachable."""
+
+ def _generation(
+ self,
+ *,
+ branch: str | None,
+ days_ago: float,
+ cost: float,
+ input_tokens: int = 0,
+ output_tokens: int = 0,
+ repo: str | None = None,
+ session: str | None = None,
+ trace: str | None = None,
+ event: str = "$ai_generation",
+ ) -> None:
+ # branch=None seeds an unstamped generation (no $ai_git_branch), the transient state the
+ # carry-forward and prefix rules attribute; session/trace set the grouping key.
+ props: dict[str, Any] = {
+ "$ai_total_cost_usd": cost,
+ "$ai_input_tokens": input_tokens,
+ "$ai_output_tokens": output_tokens,
+ }
+ if branch is not None:
+ props["$ai_git_branch"] = branch
+ if repo is not None:
+ props["$ai_git_repo"] = repo
+ if session is not None:
+ props["$ai_session_id"] = session
+ if trace is not None:
+ props["$ai_trace_id"] = trace
+ _create_event(
+ event=event,
+ team=self.team,
+ distinct_id="agent-1",
+ properties=props,
+ timestamp=timezone.now() - timedelta(days=days_ago),
+ )
+
+ def _seed_pr(self, number: int, head_ref: str, *, base_ref: str = "master") -> None:
+ # A merged PR fixes the window to [created - 14d, merged] = [_ago(19), _ago(1)]. The runs table
+ # must exist for the source to resolve even though LLM spend never reads it (mixin gotcha).
+ self._create_table(
+ "github_pull_requests",
+ _PULL_REQUESTS_COLUMNS,
+ [
+ _pr_row(
+ number,
+ "alice",
+ "closed",
+ 0,
+ _ago(5),
+ merged_at=_ago(1),
+ head_sha=f"sha{number}",
+ head_ref=head_ref,
+ base_ref=base_ref,
+ )
+ ],
+ )
+ self._create_table(
+ "github_workflow_runs",
+ _WORKFLOW_RUNS_COLUMNS,
+ [_run_row(number * 100, "CI", f"sha{number}", "completed", "success", _ago(4), _ago(4), pr_number=number)],
+ )
+
+ def test_llm_spend_attributes_by_branch_within_window(self) -> None:
+ branch = "feat/tokens"
+ self._seed_pr(80, branch)
+ # Matches: on-branch, in-window; one with no repo stamped, one with the repo stamped in clone-URL
+ # casing (the repo compare is case-insensitive, like GitHub repo names).
+ self._generation(branch=branch, days_ago=4, cost=1.0, input_tokens=100, output_tokens=50)
+ self._generation(
+ branch=branch, days_ago=10, cost=2.0, input_tokens=200, output_tokens=80, repo="posthog/POSTHOG"
+ )
+ # Excluded: wrong repo, wrong branch, before the lead window, after merge, wrong event type.
+ self._generation(branch=branch, days_ago=4, cost=99.0, repo="other/repo")
+ self._generation(branch="other-branch", days_ago=4, cost=99.0)
+ self._generation(branch=branch, days_ago=25, cost=99.0)
+ self._generation(branch=branch, days_ago=0, cost=99.0)
+ self._generation(branch=branch, days_ago=4, cost=99.0, event="$ai_embedding")
+ flush_persons_and_events()
+
+ cost = api.get_pr_cost(team=self.team, pr_number=80, repo="PostHog/posthog")
+ assert cost.llm_spend is not None
+ assert cost.llm_spend.generations == 2
+ assert cost.llm_spend.cost_usd == pytest.approx(3.0)
+ assert cost.llm_spend.input_tokens == 300
+ assert cost.llm_spend.output_tokens == 130
+
+ def test_llm_spend_none_when_head_is_base(self) -> None:
+ self._seed_pr(84, "master", base_ref="master")
+ self._generation(branch="master", days_ago=4, cost=5.0)
+ flush_persons_and_events()
+
+ cost = api.get_pr_cost(team=self.team, pr_number=84, repo="PostHog/posthog")
+ assert cost.llm_spend is None
+
+ def test_llm_spend_failure_degrades_to_none(self) -> None:
+ # The spend join is an optional enrichment; a query failure (e.g. a timeout on an AI-heavy
+ # team) must not take the whole cost summary down with it.
+ self._seed_pr(85, "feat/degrade")
+ with mock.patch(
+ "products.engineering_analytics.backend.logic.query_pr_llm_spend",
+ side_effect=Exception("clickhouse timeout"),
+ ):
+ cost = api.get_pr_cost(team=self.team, pr_number=85, repo="PostHog/posthog")
+ assert cost.llm_spend is None
+
+ def test_llm_spend_none_when_no_generations(self) -> None:
+ # Open PR whose branch no event carries — spend stays null so the UI hides the row.
+ self._create_table(
+ "github_pull_requests",
+ _PULL_REQUESTS_COLUMNS,
+ [_pr_row(81, "alice", "open", 0, _ago(2), head_sha="sha81", head_ref="feat/empty")],
+ )
+ self._create_table(
+ "github_workflow_runs",
+ _WORKFLOW_RUNS_COLUMNS,
+ [_run_row(8100, "CI", "sha81", "completed", "success", _ago(1), _ago(1), pr_number=81)],
+ )
+ cost = api.get_pr_cost(team=self.team, pr_number=81, repo="PostHog/posthog")
+ assert cost.llm_spend is None
+
+ @parameterized.expand(
+ [
+ # first feature stamp == H: the base-stamped prefix and the H events all credit H.
+ ("first_feature_is_head", "feat/tokens", 4, pytest.approx(14.0)),
+ # first feature stamp == a different branch: the prefix belongs to that branch, so only
+ # the later direct-H stamp credits H (guards against prefix-stealing).
+ ("first_feature_is_other", "feat/other", 1, pytest.approx(8.0)),
+ ]
+ )
+ def test_prefix_credits_head_only_when_first_feature_branch_is_head(
+ self, _name: str, first_feature: str, expected_generations: int, expected_cost: Any
+ ) -> None:
+ head = "feat/tokens"
+ self._seed_pr(82, head, base_ref="master")
+ # Same session: base-stamped exploration, then the first feature stamp, then a direct H stamp.
+ self._generation(branch="master", days_ago=10, cost=1.0, session="s1")
+ self._generation(branch="master", days_ago=9, cost=1.0, session="s1")
+ self._generation(branch=first_feature, days_ago=8, cost=4.0, session="s1")
+ self._generation(branch=head, days_ago=6, cost=8.0, session="s1")
+ flush_persons_and_events()
+
+ cost = api.get_pr_cost(team=self.team, pr_number=82, repo="PostHog/posthog")
+ assert cost.llm_spend is not None
+ assert cost.llm_spend.generations == expected_generations
+ assert cost.llm_spend.cost_usd == expected_cost
+
+ def test_carry_forward_follows_latest_stamp_until_a_branch_switch(self) -> None:
+ self._seed_pr(83, "feat/tokens", base_ref="master")
+ # H stamp, then an unstamped event that carries H forward, then a switch to another branch whose
+ # later unstamped event must NOT credit H.
+ self._generation(branch="feat/tokens", days_ago=10, cost=1.0, session="s2")
+ self._generation(branch=None, days_ago=9, cost=2.0, session="s2")
+ self._generation(branch="feat/other", days_ago=8, cost=99.0, session="s2")
+ self._generation(branch=None, days_ago=7, cost=99.0, session="s2")
+ flush_persons_and_events()
+
+ cost = api.get_pr_cost(team=self.team, pr_number=83, repo="PostHog/posthog")
+ assert cost.llm_spend is not None
+ assert cost.llm_spend.generations == 2
+ assert cost.llm_spend.cost_usd == pytest.approx(3.0)
+
+ def test_out_of_window_events_excluded_even_in_an_eligible_session(self) -> None:
+ self._seed_pr(84, "feat/tokens", base_ref="master")
+ # In-window H stamp makes the session eligible; an unstamped event after the merge would carry H
+ # forward if the window were dropped from the group scan, so it guards that outer-window filter.
+ self._generation(branch="feat/tokens", days_ago=4, cost=1.0, session="s3")
+ self._generation(branch=None, days_ago=0, cost=99.0, session="s3")
+ self._generation(branch="feat/tokens", days_ago=25, cost=99.0, session="s3")
+ flush_persons_and_events()
+
+ cost = api.get_pr_cost(team=self.team, pr_number=84, repo="PostHog/posthog")
+ assert cost.llm_spend is not None
+ assert cost.llm_spend.generations == 1
+ assert cost.llm_spend.cost_usd == pytest.approx(1.0)
+
+ def test_ungrouped_events_count_only_via_a_direct_head_stamp(self) -> None:
+ self._seed_pr(85, "feat/tokens", base_ref="master")
+ # No session and no trace id: no group, so neither prefix nor carry-forward applies — only the
+ # event stamped H directly counts.
+ self._generation(branch="feat/tokens", days_ago=8, cost=5.0)
+ self._generation(branch="master", days_ago=9, cost=99.0)
+ self._generation(branch=None, days_ago=7, cost=99.0)
+ flush_persons_and_events()
+
+ cost = api.get_pr_cost(team=self.team, pr_number=85, repo="PostHog/posthog")
+ assert cost.llm_spend is not None
+ assert cost.llm_spend.generations == 1
+ assert cost.llm_spend.cost_usd == pytest.approx(5.0)
+
+ def test_session_with_only_base_stamps_is_not_eligible(self) -> None:
+ self._seed_pr(86, "feat/tokens", base_ref="master")
+ # A session that never stamps the head ref is not eligible, so its base-stamped exploration
+ # credits nothing and spend stays null.
+ self._generation(branch="master", days_ago=10, cost=99.0, session="s4")
+ self._generation(branch=None, days_ago=9, cost=99.0, session="s4")
+ flush_persons_and_events()
+
+ cost = api.get_pr_cost(team=self.team, pr_number=86, repo="PostHog/posthog")
+ assert cost.llm_spend is None
+
+ def test_newest_snapshot_by_updated_at_drives_attribution(self) -> None:
+ # Two snapshot rows for the same PR share created_at (the PR's creation time); only updated_at
+ # separates the stale row from the fresh one. The header must pick the freshest so its head_ref
+ # — not the stale row's — drives the branch attribution. Ordering on created_at alone left the
+ # winner arbitrary and could credit the stale branch.
+ created = _ago(5)
+ self._create_table(
+ "github_pull_requests",
+ _PULL_REQUESTS_COLUMNS,
+ [
+ _pr_row(90, "alice", "closed", 0, created, merged_at=_ago(3), head_sha="sha90a", head_ref="feat/stale"),
+ _pr_row(90, "alice", "closed", 0, created, merged_at=_ago(1), head_sha="sha90b", head_ref="feat/fresh"),
+ ],
+ )
+ self._create_table(
+ "github_workflow_runs",
+ _WORKFLOW_RUNS_COLUMNS,
+ [_run_row(9000, "CI", "sha90b", "completed", "success", _ago(4), _ago(4), pr_number=90)],
+ )
+ self._generation(branch="feat/fresh", days_ago=4, cost=3.0, input_tokens=30, output_tokens=10)
+ self._generation(branch="feat/stale", days_ago=4, cost=99.0)
+ flush_persons_and_events()
+
+ cost = api.get_pr_cost(team=self.team, pr_number=90, repo="PostHog/posthog")
+ assert cost.llm_spend is not None
+ assert cost.llm_spend.generations == 1
+ assert cost.llm_spend.cost_usd == pytest.approx(3.0)
+
+
+class TestMultiSourceResolutionWarehouse(_WarehouseMixin, BaseTest):
+ """A team with one GitHub source per repository: a repo-scoped read must resolve the source
+ connected for that repo, not the oldest one. Skips when object storage is unreachable."""
+
+ def _connect_source(self, *, source_id: str, prefix: str, repository: str) -> ExternalDataSource:
+ return ExternalDataSource.objects.create(
+ team=self.team,
+ source_id=source_id,
+ connection_id=source_id,
+ status=ExternalDataSource.Status.COMPLETED,
+ source_type=ExternalDataSourceType.GITHUB,
+ prefix=prefix,
+ job_inputs={"repository": repository},
+ )
+
+ def test_resolve_branch_targets_the_repo_scoped_source(self) -> None:
+ # Both sources are fully synced, so oldest-first would search repo A and miss the PR that only
+ # exists in the newer repo B. The repo hint routes resolution to B.
+ older = self._connect_source(source_id="src-a", prefix="repoa", repository="PostHog/posthog")
+ newer = self._connect_source(source_id="src-b", prefix="repob", repository="PostHog/posthog.com")
+ # Source A (older, other repo): synced but holds no PR on the branch.
+ self._create_table("github_pull_requests", _PULL_REQUESTS_COLUMNS, [], source=older, prefix="repoa")
+ self._create_table("github_workflow_runs", _WORKFLOW_RUNS_COLUMNS, [], source=older, prefix="repoa")
+ # Source B (newer, target repo): holds the feat/login PR.
+ self._create_table(
+ "github_pull_requests",
+ _PULL_REQUESTS_COLUMNS,
+ [
+ _pr_row(
+ 61,
+ "alice",
+ "open",
+ 0,
+ _ago(2),
+ head_sha="sha61",
+ head_ref="feat/login",
+ full_name="PostHog/posthog.com",
+ )
+ ],
+ source=newer,
+ prefix="repob",
+ )
+ self._create_table("github_workflow_runs", _WORKFLOW_RUNS_COLUMNS, [], source=newer, prefix="repob")
+
+ # Clone-URL casing: both the source hint and the repo filter compare case-insensitively.
+ matches = api.resolve_branch(team=self.team, branch="feat/login", repo="posthog/POSTHOG.com")
+ assert [(m.repo, m.number) for m in matches] == [("PostHog/posthog.com", 61)]
+ # Without the repo hint the oldest source (A) is searched and the PR is missed.
+ assert api.resolve_branch(team=self.team, branch="feat/login") == []
diff --git a/products/engineering_analytics/backend/tests/test_presentation.py b/products/engineering_analytics/backend/tests/test_presentation.py
index 55c5dce0d795..6eade795e7b1 100644
--- a/products/engineering_analytics/backend/tests/test_presentation.py
+++ b/products/engineering_analytics/backend/tests/test_presentation.py
@@ -333,6 +333,29 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST
+ def test_resolve_branch_serializes(self) -> None:
+ matches = [
+ contracts.BranchPRMatch(repo="PostHog/posthog", number=42, title="Fix bug", state="merged"),
+ contracts.BranchPRMatch(repo="PostHog/posthog", number=7, title=None, state=None),
+ ]
+ with mock.patch(f"{_VIEWS}.resolve_branch", return_value=matches) as resolve:
+ response = self.client.get(self._url("resolve_branch"), {"branch": "feat/x", "repo": "PostHog/posthog"})
+
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert [(m["number"], m["repo"], m["title"], m["state"]) for m in body] == [
+ (42, "PostHog/posthog", "Fix bug", "merged"),
+ (7, "PostHog/posthog", None, None),
+ ]
+ assert resolve.call_args.kwargs["branch"] == "feat/x"
+ assert resolve.call_args.kwargs["repo"] == "PostHog/posthog"
+
+ def test_resolve_branch_400_when_branch_missing(self) -> None:
+ # Validation lives in the facade; a request with no branch surfaces as a 400 (source connected in setUp).
+ response = self.client.get(self._url("resolve_branch"))
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
def test_workflow_run_serializes(self) -> None:
with mock.patch(f"{_VIEWS}.get_workflow_run", return_value=_workflow_run()) as get:
response = self.client.get(self._url("workflow_run"), {"run_id": "7777"})
@@ -424,6 +447,7 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
by_run=[
contracts.RunCost(run_id=9100, run_attempt=1, billable_minutes=2510.0, estimated_cost_usd=61.2),
],
+ llm_spend=contracts.PRLLMSpend(cost_usd=1.5, input_tokens=1200, output_tokens=340, generations=4),
)
with mock.patch(f"{_VIEWS}.get_pr_cost", return_value=summary) as getter:
response = self.client.get(self._url("pr_cost"), {"pr_number": "10", "repo": "PostHog/posthog"})
@@ -432,6 +456,12 @@ class TestEngineeringAnalyticsAPI(APIBaseTest):
body = response.json()
assert body["billable_minutes"] == 2510.0 and body["unsettled_jobs"] == 2
assert body["by_run"][0]["run_id"] == 9100 and body["by_run"][0]["estimated_cost_usd"] == 61.2
+ assert body["llm_spend"] == {
+ "cost_usd": 1.5,
+ "input_tokens": 1200,
+ "output_tokens": 340,
+ "generations": 4,
+ }
assert getter.call_args.kwargs["pr_number"] == 10
assert getter.call_args.kwargs["repo"] == "PostHog/posthog"
diff --git a/products/engineering_analytics/backend/tests/test_views.py b/products/engineering_analytics/backend/tests/test_views.py
index 89b40bb9e25e..a99375a6d573 100644
--- a/products/engineering_analytics/backend/tests/test_views.py
+++ b/products/engineering_analytics/backend/tests/test_views.py
@@ -91,8 +91,8 @@ def _user(login: str) -> str:
return f'{{"login": "{login}", "avatar_url": "https://avatars/{login}"}}'
-def _base(full_name: str) -> str:
- return f'{{"repo": {{"full_name": "{full_name}"}}}}'
+def _base(full_name: str, ref: str = "") -> str:
+ return f'{{"ref": "{ref}", "repo": {{"full_name": "{full_name}"}}}}'
def _labels(*names: str) -> str:
@@ -108,6 +108,8 @@ def _pr_row(
*,
merged_at: str | None = None,
head_sha: str = "",
+ head_ref: str = "",
+ base_ref: str = "",
full_name: str = "PostHog/posthog",
labels: tuple[str, ...] = (),
) -> dict[str, Any]:
@@ -122,8 +124,8 @@ def _pr_row(
"merged_at": merged_at,
"closed_at": merged_at,
"user": _user(login),
- "head": f'{{"sha": "{head_sha}"}}',
- "base": _base(full_name),
+ "head": f'{{"sha": "{head_sha}", "ref": "{head_ref}"}}',
+ "base": _base(full_name, base_ref),
"labels": _labels(*labels),
}
@@ -268,7 +270,8 @@ class TestEngineeringAnalyticsViews(ClickhouseTestMixin, BaseTest):
raw = (
"(SELECT 100 AS id, 5 AS number, 'PR 5' AS title, 'open' AS state, false AS draft, "
f"nullIf('', '') AS user, '{head_json}' AS head, '{base_json}' AS base, '[]' AS labels, "
- "'2026-01-10 10:00:00' AS created_at, nullIf('', '') AS merged_at, nullIf('', '') AS closed_at)"
+ "'2026-01-10 10:00:00' AS created_at, '2026-01-10 10:00:00' AS updated_at, "
+ "nullIf('', '') AS merged_at, nullIf('', '') AS closed_at)"
)
rows = self._select(
f"SELECT author_handle, author_avatar_url, is_bot FROM ({pull_requests.build_query(raw)}) AS pr"
diff --git a/products/engineering_analytics/frontend/generated/api.schemas.ts b/products/engineering_analytics/frontend/generated/api.schemas.ts
index 8cd72c99fb53..69dce82a4852 100644
--- a/products/engineering_analytics/frontend/generated/api.schemas.ts
+++ b/products/engineering_analytics/frontend/generated/api.schemas.ts
@@ -207,11 +207,24 @@ export interface RunCostApi {
estimated_cost_usd: number | null
}
+export interface PRLLMSpendApi {
+ /** Total agent LLM token cost in USD attributed to this PR (sum of $ai_total_cost_usd over the matched $ai_generation events). */
+ cost_usd: number
+ /** Total input (prompt) tokens across the attributed generations. */
+ input_tokens: number
+ /** Total output (completion) tokens across the attributed generations. */
+ output_tokens: number
+ /** Number of $ai_generation events attributed to this PR by git branch ($ai_git_branch). */
+ generations: number
+}
+
export interface PRCostSummaryApi {
/** Same spend broken down per workflow. */
by_workflow: WorkflowCostApi[]
/** Same spend broken down per workflow run, keyed by (run_id, run_attempt). */
by_run: RunCostApi[]
+ /** Agent LLM token spend attributed to this PR by git branch ($ai_git_branch), or null when no generation matched — independent of the CI cost figures, so it can be present even when jobs_available is false. The UI hides the row when null. */
+ llm_spend?: PRLLMSpendApi | null
/** False when the job-level source (github_workflow_jobs) isn't synced — every figure is then zero/null and the cost cards should be hidden. */
jobs_available: boolean
/** Billable CI minutes: each costed (self-hosted) job's elapsed time, summed. Parallel jobs add up, so this is compute time spent, not wall-clock run duration. */
@@ -785,6 +798,23 @@ export interface WorkflowRunActivityApi {
limit: number
}
+export interface BranchPRMatchApi {
+ /** Repository the pull request belongs to, as 'owner/name'. */
+ repo: string
+ /** Pull request number within the repository — pair with `repo` to link to it. */
+ number: number
+ /**
+ * Pull request title, or null when the snapshot carries no title.
+ * @nullable
+ */
+ title: string | null
+ /**
+ * Derived PR state ('open', 'closed', 'merged'), or null when the snapshot carries no state.
+ * @nullable
+ */
+ state: string | null
+}
+
export interface RunFailureLogsApi {
/** Failed CI jobs of this run with their thinned failure logs, grouped by job. */
jobs: CIJobFailureLogApi[]
@@ -1160,6 +1190,25 @@ export type EngineeringAnalyticsRepoRunActivityParams = {
source_id?: string
}
+export type EngineeringAnalyticsResolveBranchParams = {
+ /**
+ * Git branch (the PR's head ref) to resolve. Open PRs are returned first, then most recently updated.
+ */
+ branch: string
+ /**
+ * Optional 'owner/name' repository to narrow matching to a single repo.
+ */
+ repo?: string
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string
+ /**
+ * Optional ISO8601 timestamp, e.g. the trace's capture time. When a branch name has been reused across PRs over time, the PR whose lifetime window contains this moment is ranked first so the result matches the PR that was active when the trace was captured. A preference only, not a filter; omit to rank purely by open state then recency.
+ */
+ timestamp?: string
+}
+
export type EngineeringAnalyticsRunFailureLogsParams = {
/**
* Workflow run id whose failure logs to fetch.
diff --git a/products/engineering_analytics/frontend/generated/api.ts b/products/engineering_analytics/frontend/generated/api.ts
index 12b7b84147ab..80a3f978c313 100644
--- a/products/engineering_analytics/frontend/generated/api.ts
+++ b/products/engineering_analytics/frontend/generated/api.ts
@@ -9,6 +9,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
+ BranchPRMatchApi,
CICardSummaryApi,
CIFailureLogsApi,
CurrentBranchHealthApi,
@@ -26,6 +27,7 @@ import type {
EngineeringAnalyticsQuarantineParams,
EngineeringAnalyticsRepoOverviewParams,
EngineeringAnalyticsRepoRunActivityParams,
+ EngineeringAnalyticsResolveBranchParams,
EngineeringAnalyticsRunFailureLogsParams,
EngineeringAnalyticsWorkflowHealthParams,
EngineeringAnalyticsWorkflowJobsParams,
@@ -298,7 +300,7 @@ export const getEngineeringAnalyticsPrCostUrl = (projectId: string, params: Engi
}
/**
- * Estimated CI cost for a pull request, summed over the jobs of all its workflow runs. Billable self-hosted Linux runners only — provider-hosted (free GitHub-hosted) and non-Linux jobs are excluded. Every figure is zero/null with `jobs_available` false when the job-level source isn't synced yet.
+ * Estimated CI cost for a pull request, summed over the jobs of all its workflow runs. Billable self-hosted Linux runners only — provider-hosted (free GitHub-hosted) and non-Linux jobs are excluded. Every figure is zero/null with `jobs_available` false when the job-level source isn't synced yet. `llm_spend` carries the agent LLM token spend attributed to the PR by git branch, or null when no `$ai_generation` event matched.
*/
export const engineeringAnalyticsPrCost = async (
projectId: string,
@@ -528,6 +530,39 @@ export const engineeringAnalyticsRepoRunActivity = async (
})
}
+export const getEngineeringAnalyticsResolveBranchUrl = (
+ projectId: string,
+ params: EngineeringAnalyticsResolveBranchParams
+) => {
+ 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}/engineering_analytics/resolve_branch/?${stringifiedParams}`
+ : `/api/projects/${projectId}/engineering_analytics/resolve_branch/`
+}
+
+/**
+ * Resolve a git branch to the pull request(s) it belongs to — the cross-product link seam so another product (the LLM analytics UI) can turn a git branch into a PR detail link. Matches the PR's head ref, open PRs first then most recently updated. Pass `timestamp` (the trace's capture time) to prefer the PR that was active at that moment when a branch name has been reused across PRs. `branch` is required. Returns a possibly-empty, possibly-multi list — an empty list is a valid 200 (the caller renders a plain chip).
+ */
+export const engineeringAnalyticsResolveBranch = async (
+ projectId: string,
+ params: EngineeringAnalyticsResolveBranchParams,
+ options?: RequestInit
+): Promise<BranchPRMatchApi[]> => {
+ return apiMutator<BranchPRMatchApi[]>(getEngineeringAnalyticsResolveBranchUrl(projectId, params), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getEngineeringAnalyticsRunFailureLogsUrl = (
projectId: string,
params: EngineeringAnalyticsRunFailureLogsParams
diff --git a/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
index 807cf21f0f51..797286ca56d5 100644
--- a/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
+++ b/products/engineering_analytics/frontend/scenes/PullRequestDetailScene.tsx
@@ -35,7 +35,7 @@ import { RunConclusionTag } from '../components/runTables'
import { RepoScopeChip, ScopeBar } from '../components/ScopeBar'
import { Section } from '../components/Section'
import type { WorkflowJobApi } from '../generated/api.schemas'
-import { compactUsd } from '../lib/format'
+import { compactCount, compactUsd } from '../lib/format'
import { githubCommitUrl, githubPrUrl } from '../lib/github'
import { LifecycleSummary, WorkflowRun, isPassingConclusion } from '../lib/lifecycle'
import { PushRound, pushRoundColor, pushRoundOf, pushRoundVerdictLabel } from '../lib/pushRounds'
@@ -832,6 +832,16 @@ export function PullRequestDetailScene(): JSX.Element {
sub={prCost?.jobs_available ? undefined : 'Job-level source not synced'}
loading={prCostLoading && !prCost}
/>
+ {prCost?.llm_spend && (
+ <MetricTile
+ label="LLM spend"
+ tooltip="Token spend from AI coding/review sessions on this PR's branch, including spend from the same session before the branch was created."
+ value={compactUsd(prCost.llm_spend.cost_usd)}
+ sub={`${compactCount(
+ prCost.llm_spend.input_tokens + prCost.llm_spend.output_tokens
+ )} tokens · ${pluralize(prCost.llm_spend.generations, 'generation')}`}
+ />
+ )}
</div>
</>
) : (
diff --git a/products/engineering_analytics/mcp/tools.yaml b/products/engineering_analytics/mcp/tools.yaml
index 0f0a0680034c..eb2cebb55970 100644
--- a/products/engineering_analytics/mcp/tools.yaml
+++ b/products/engineering_analytics/mcp/tools.yaml
@@ -100,6 +100,9 @@ tools:
engineering-analytics-repo-run-activity:
operation: engineering_analytics_repo_run_activity
enabled: false
+ engineering-analytics-resolve-branch:
+ operation: engineering_analytics_resolve_branch
+ enabled: false
engineering-analytics-run-failure-logs:
operation: engineering_analytics_run_failure_logs
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 49e3e0c18587..737ea8724a1e 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -12228,6 +12228,23 @@ export namespace Schemas {
false_label?: string;
}
+ export interface BranchPRMatch {
+ /** Repository the pull request belongs to, as 'owner/name'. */
+ repo: string;
+ /** Pull request number within the repository — pair with `repo` to link to it. */
+ number: number;
+ /**
+ * Pull request title, or null when the snapshot carries no title.
+ * @nullable
+ */
+ title: string | null;
+ /**
+ * Derived PR state ('open', 'closed', 'merged'), or null when the snapshot carries no state.
+ * @nullable
+ */
+ state: string | null;
+ }
+
export interface BreakdownItem {
label: string;
value: string | number;
@@ -35124,11 +35141,24 @@ export namespace Schemas {
estimated_cost_usd: number | null;
}
+ export interface PRLLMSpend {
+ /** Total agent LLM token cost in USD attributed to this PR (sum of $ai_total_cost_usd over the matched $ai_generation events). */
+ cost_usd: number;
+ /** Total input (prompt) tokens across the attributed generations. */
+ input_tokens: number;
+ /** Total output (completion) tokens across the attributed generations. */
+ output_tokens: number;
+ /** Number of $ai_generation events attributed to this PR by git branch ($ai_git_branch). */
+ generations: number;
+ }
+
export interface PRCostSummary {
/** Same spend broken down per workflow. */
by_workflow: WorkflowCost[];
/** Same spend broken down per workflow run, keyed by (run_id, run_attempt). */
by_run: RunCost[];
+ /** Agent LLM token spend attributed to this PR by git branch ($ai_git_branch), or null when no generation matched — independent of the CI cost figures, so it can be present even when jobs_available is false. The UI hides the row when null. */
+ llm_spend?: PRLLMSpend | null;
/** False when the job-level source (github_workflow_jobs) isn't synced — every figure is then zero/null and the cost cards should be hidden. */
jobs_available: boolean;
/** Billable CI minutes: each costed (self-hosted) job's elapsed time, summed. Parallel jobs add up, so this is compute time spent, not wall-clock run duration. */
@@ -69915,6 +69945,25 @@ export namespace Schemas {
source_id?: string;
};
+ export type EngineeringAnalyticsResolveBranchParams = {
+ /**
+ * Git branch (the PR's head ref) to resolve. Open PRs are returned first, then most recently updated.
+ */
+ branch: string;
+ /**
+ * Optional 'owner/name' repository to narrow matching to a single repo.
+ */
+ repo?: string;
+ /**
+ * Connected GitHub data warehouse source to read from. Defaults to the oldest connected GitHub source when the team has more than one.
+ */
+ source_id?: string;
+ /**
+ * Optional ISO8601 timestamp, e.g. the trace's capture time. When a branch name has been reused across PRs over time, the PR whose lifetime window contains this moment is ranked first so the result matches the PR that was active when the trace was captured. A preference only, not a filter; omit to rank purely by open state then recency.
+ */
+ timestamp?: string;
+ };
+
export type EngineeringAnalyticsRunFailureLogsParams = {
/**
* Workflow run id whose failure logs to fetch.
diff --git a/services/mcp/src/generated/engineering_analytics/api.ts b/services/mcp/src/generated/engineering_analytics/api.ts
index 457e4eef2afb..497e7b412200 100644
--- a/services/mcp/src/generated/engineering_analytics/api.ts
+++ b/services/mcp/src/generated/engineering_analytics/api.ts
@@ -71,7 +71,7 @@ export const EngineeringAnalyticsFlakyTestsQueryParams = /* @__PURE__ */ zod.obj
})
/**
- * Estimated CI cost for a pull request, summed over the jobs of all its workflow runs. Billable self-hosted Linux runners only — provider-hosted (free GitHub-hosted) and non-Linux jobs are excluded. Every figure is zero/null with `jobs_available` false when the job-level source isn't synced yet.
+ * Estimated CI cost for a pull request, summed over the jobs of all its workflow runs. Billable self-hosted Linux runners only — provider-hosted (free GitHub-hosted) and non-Linux jobs are excluded. Every figure is zero/null with `jobs_available` false when the job-level source isn't synced yet. `llm_spend` carries the agent LLM token spend attributed to the PR by git branch, or null when no `$ai_generation` event matched.
*/
export const EngineeringAnalyticsPrCostParams = /* @__PURE__ */ zod.object({
project_id: zod