:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signals): keep merged pull request diffs available (#104639)
Dylan Martin7af9307723c5
diff --git a/posthog/models/integration/github.py b/posthog/models/integration/github.pyindex 7865ae1e922a..99d50cdd1236 100644--- a/posthog/models/integration/github.py+++ b/posthog/models/integration/github.py@@ -42,6 +42,15 @@ _GITHUB_LOGIN_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,3# Upper bound on the diff text we return, to keep a pathological diff (generated/vendored# files) from bloating the JSON response and worker memory. ~1 MB of text._MAX_DIFF_CHARS = 1_000_000+++def _bounded_diff_response(diff_text: str) -> dict[str, Any]:+ truncated = len(diff_text) > _MAX_DIFF_CHARS+ if truncated:+ diff_text = diff_text[:_MAX_DIFF_CHARS] + "\n\n… diff truncated (too large to display in full) …\n"+ return {"success": True, "diff": diff_text, "truncated": truncated}++_MAX_FILE_CONTENTS_BYTES = 10 * 1024 * 1024@@ -854,11 +863,26 @@ class GitHubIntegration(GitHubIntegrationBase):# Cap the diff we return: a branch touching generated/vendored files can produce a diff of# many MB, which would bloat the JSON response and worker memory. Truncate with a marker so# the consumer can tell the diff was cut rather than silently showing a partial diff.- diff_text = response.text- truncated = len(diff_text) > _MAX_DIFF_CHARS- if truncated:- diff_text = diff_text[:_MAX_DIFF_CHARS] + "\n\n… diff truncated (too large to display in full) …\n"- return {"success": True, "diff": diff_text, "truncated": truncated}+ return _bounded_diff_response(response.text)++ def get_pull_request_diff(self, repository: str, pr_number: int) -> dict[str, Any]:+ """Return the durable unified diff GitHub stores for a pull request."""+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"+ if not _is_safe_github_repo_path(repo_path) or pr_number < 1:+ return {"success": False, "error": "Invalid pull request reference.", "status_code": 400}++ try:+ response = self.api_request(+ "GET",+ f"/repos/{repo_path}/pulls/{pr_number}",+ endpoint="/repos/{owner}/{repo}/pulls/{pull_number}",+ headers={"Accept": "application/vnd.github.diff"},+ )+ except GitHubIntegrationError:+ return {"success": False, "error": "Could not reach GitHub.", "status_code": 502}+ if response.status_code != 200:+ return {"success": False, "error": response.text, "status_code": response.status_code}+ return _bounded_diff_response(response.text)def update_file(self, repository: str, file_path: str, content: str, commit_message: str, branch: str, sha: str | None = Nonediff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.pyindex cb434ef5203c..6749d3d19da3 100644--- a/posthog/models/test/integration/test_github.py+++ b/posthog/models/test/integration/test_github.py@@ -384,6 +384,21 @@ class TestGitHubIntegrationModel(BaseTest):assert result["success"] is Falseassert result["status_code"] == 502+ def test_get_pull_request_diff_uses_the_durable_pr_endpoint(self):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ mock_response = MagicMock(status_code=200, text="diff --git a b")+ with patch.object(github, "api_request", return_value=mock_response) as mock_get:+ result = github.get_pull_request_diff("PostHog/posthog", 42)++ assert result == {"success": True, "diff": "diff --git a b", "truncated": False}+ mock_get.assert_called_once_with(+ "GET",+ "/repos/PostHog/posthog/pulls/42",+ endpoint="/repos/{owner}/{repo}/pulls/{pull_number}",+ headers={"Accept": "application/vnd.github.diff"},+ )+def _github_for_org(self) -> GitHubIntegration:integration = self.create_integration(config={"account": {"name": "PostHog"}}, sensitive_config={"access_token": "ACCESS_TOKEN"}diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex 9240a6e9dc3a..e48ce3efa854 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -2221,13 +2221,11 @@ class SignalReportArtefactWriteResponseSerializer(serializers.Serializer):class CommitDiffResponseSerializer(serializers.Serializer):- """Response for the `commit` artefact diff endpoint — the commit's branch rendered against the- repository default branch."""+ """Response for the `commit` artefact diff endpoint."""diff = serializers.CharField(read_only=True,- help_text="Unified diff (patch) text of the branch against the repository default branch, "- "from the GitHub compare API.",+ help_text="Unified diff (patch) text from the linked pull request or branch comparison.",)truncated = serializers.BooleanField(read_only=True,diff --git a/products/signals/backend/test/test_signal_report_artefact_api.py b/products/signals/backend/test/test_signal_report_artefact_api.pyindex 9dc58803f2ce..73e4af5f019b 100644--- a/products/signals/backend/test/test_signal_report_artefact_api.py+++ b/products/signals/backend/test/test_signal_report_artefact_api.py@@ -27,11 +27,14 @@ from products.signals.backend.artefact_schemas import (TaskRunArtefact,)from products.signals.backend.enums import ReportLinkKind+from products.signals.backend.implementation_pr import ImplementationPrfrom products.signals.backend.models import (ArtefactAttribution,+ SignalActorKind,SignalReport,SignalReportArtefact,SignalReportAssignment,+ SignalReportPullRequest,SignalReportSuggestedReviewer,)from products.signals.backend.reviewer_correction_notes import ForwardedCorrectionNotes@@ -1849,12 +1852,16 @@ class TestSignalReportCommitDiff(APIBaseTest):total_weight=1.0,)- def _create_commit_artefact(self, report: SignalReport, content: dict | list | None = None) -> SignalReportArtefact:+ def _create_commit_artefact(+ self, report: SignalReport, content: dict | list | None = None, task: Task | None = None+ ) -> SignalReportArtefact:return SignalReportArtefact.objects.create(team=self.team,report=report,type=SignalReportArtefact.ArtefactType.COMMIT,content=json.dumps(content if content is not None else _COMMIT_CONTENT),+ task=task,+ actor_kind=SignalActorKind.TASK if task else None,)def test_diff_rejects_non_commit_artefact(self):@@ -1904,6 +1911,100 @@ class TestSignalReportCommitDiff(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json() == {"diff": "diff --git a b", "truncated": False}+ def test_diff_uses_linked_pr_after_its_branch_is_deleted(self):+ report = self._create_report()+ task = Task.objects.create(team=self.team, title="Implementation", description="", origin_product="signals")+ artefact = self._create_commit_artefact(report, task=task)+ pull_request = SignalReportPullRequest.objects.create(+ team=self.team,+ repository="PostHog/posthog",+ number=42,+ url="https://github.com/PostHog/posthog/pull/42",+ state=SignalReportPullRequest.State.MERGED,+ )+ SignalReportArtefact.objects.create(+ team=self.team,+ report=report,+ type=SignalReportArtefact.ArtefactType.PULL_REQUEST,+ content=json.dumps({"url": pull_request.url}),+ task=task,+ actor_kind=SignalActorKind.TASK,+ pull_request=pull_request,+ )+ github = self._mock_github({"success": False, "error": "Not Found", "status_code": 404})+ github.return_value.get_pull_request_diff.return_value = {+ "success": True,+ "diff": "diff --git durable-pr",+ "truncated": False,+ }++ response = self.client.get(self._diff_url(str(report.id), str(artefact.id)))++ assert response.status_code == status.HTTP_200_OK+ assert response.json() == {"diff": "diff --git durable-pr", "truncated": False}+ github.return_value.get_pull_request_diff.assert_called_once_with("PostHog/posthog", 42)+ github.return_value.get_diff.assert_not_called()++ def test_diff_uses_unique_pr_when_deduplication_keeps_another_task(self):+ report = self._create_report()+ task = Task.objects.create(team=self.team, title="Implementation", description="", origin_product="signals")+ other_task = Task.objects.create(+ team=self.team, title="Earlier implementation", description="", origin_product="signals"+ )+ artefact = self._create_commit_artefact(report, task=task)+ github = self._mock_github({"success": False, "error": "Not Found", "status_code": 404})+ github.return_value.get_pull_request_diff.return_value = {+ "success": True,+ "diff": "diff --git durable-pr",+ "truncated": False,+ }+ with patch(+ "products.signals.backend.views.fetch_implementation_prs_for_reports",+ return_value={+ str(report.id): [+ ImplementationPr(+ url="https://github.com/PostHog/posthog/pull/42",+ merged=True,+ task_id=str(other_task.id),+ )+ ]+ },+ ):+ response = self.client.get(self._diff_url(str(report.id), str(artefact.id)))++ assert response.status_code == status.HTTP_200_OK+ github.return_value.get_pull_request_diff.assert_called_once_with("PostHog/posthog", 42)+ github.return_value.get_pull_request.assert_not_called()+ github.return_value.get_diff.assert_not_called()++ def test_diff_disambiguates_stacked_prs_by_branch(self):+ report = self._create_report()+ artefact = self._create_commit_artefact(report)+ github = self._mock_github({"success": False, "error": "Not Found", "status_code": 404})+ github.return_value.get_pull_request.side_effect = [+ {"success": True, "head_branch": "posthog-code/other"},+ {"success": True, "head_branch": _COMMIT_CONTENT["branch"]},+ ]+ github.return_value.get_pull_request_diff.return_value = {+ "success": True,+ "diff": "diff --git stacked-pr",+ "truncated": False,+ }+ with patch(+ "products.signals.backend.views.fetch_implementation_prs_for_reports",+ return_value={+ str(report.id): [+ ImplementationPr(url="https://github.com/PostHog/posthog/pull/41", merged=False),+ ImplementationPr(url="https://github.com/PostHog/posthog/pull/42", merged=True),+ ]+ },+ ):+ response = self.client.get(self._diff_url(str(report.id), str(artefact.id)))++ assert response.status_code == status.HTTP_200_OK+ github.return_value.get_pull_request_diff.assert_called_once_with("PostHog/posthog", 42)+ github.return_value.get_diff.assert_not_called()+def test_diff_maps_upstream_404(self):report = self._create_report()artefact = self._create_commit_artefact(report)diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex d6b67ad7acf6..0b4593b79586 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -254,6 +254,36 @@ _PR_CI_STATUS_TERMINAL_REPORT_STATUSES = frozenset()+def _pull_request_ref_for_commit(+ artefact: SignalReportArtefact,+ repository: str,+ branch: str,+ github: GitHubIntegration,+) -> PullRequestRef | None:+ """Find the report PR that contains the commit artefact's branch."""+ candidates: dict[int, tuple[PullRequestRef, str | None]] = {}+ prs = fetch_implementation_prs_for_reports([str(artefact.report_id)], team_id=artefact.team_id).get(+ str(artefact.report_id), []+ )+ for pr in prs:+ parsed = GitHubIntegration.parse_pull_request_url(pr.url)+ if parsed is not None and parsed.repository.lower() == repository.lower():+ candidates.setdefault(parsed.number, (parsed, pr.task_id))+ if len(candidates) == 1:+ return next(iter(candidates.values()))[0]++ task_id = str(artefact.task_id) if artefact.task_id else None+ task_matches = [candidate for candidate, candidate_task_id in candidates.values() if candidate_task_id == task_id]+ if task_id is not None and len(task_matches) == 1:+ return task_matches[0]++ for candidate, _ in candidates.values():+ details = github.get_pull_request(repository, candidate.number)+ if details.get("success") and details.get("head_branch") == branch:+ return candidate+ return None++def parse_pr_ci_status_report_ids(raw: str | None) -> list[uuid.UUID]:"""Parse the batch CI-status endpoint's comma-separated `report_ids`.@@ -4984,7 +5014,7 @@ class SignalReportArtefactViewSet(responses={200: OpenApiResponse(response=CommitDiffResponseSerializer,- description="The branch's unified diff against the repository default branch.",+ description="The pull request diff, or the branch diff when no pull request is linked.",),400: OpenApiResponse(description="Artefact is not a commit, or is missing repository/branch."),404: OpenApiResponse(description="Artefact not found, or no GitHub integration can access the repository."),@@ -4992,9 +5022,9 @@ class SignalReportArtefactViewSet(},summary="Fetch the diff for a commit artefact",description=(- "Fetch the unified diff of a `commit` artefact's branch against the repository default "- "branch via the team's GitHub integration — using the branch's current tip so the diff "- "reflects the latest state of the work, not just the single recorded commit."+ "Fetch the unified diff for a `commit` artefact via the team's GitHub integration. "+ "A commit linked to a report pull request uses GitHub's durable pull request diff. "+ "A commit without that link compares the branch's current tip with the default branch."),parameters=[_REPORT_ID_PARAMETER],operation_id="signals_report_artefacts_diff",@@ -5036,6 +5066,38 @@ class SignalReportArtefactViewSet({"error": f"No GitHub integration can access '{repository}'."},status=status.HTTP_404_NOT_FOUND,)+ try:+ pull_request = _pull_request_ref_for_commit(artefact, str(repository), str(branch), github)+ except GitHubRateLimitError as e:+ return github_rate_limited_response(e)+ except Exception: # noqa: BLE001 — the branch comparison below is the safe fallback+ logger.warning(+ "signals pull request lookup errored; falling back to branch",+ repository=repository,+ branch=branch,+ )+ pull_request = None+ if pull_request is not None:+ try:+ pr_result = github.get_pull_request_diff(str(repository), pull_request.number)+ except GitHubRateLimitError as e:+ return github_rate_limited_response(e)+ except Exception: # noqa: BLE001 — the branch comparison below is the safe fallback+ logger.warning(+ "signals pull request diff fetch errored; falling back to branch",+ repository=repository,+ pr_number=pull_request.number,+ )+ else:+ if pr_result.get("success"):+ return Response(+ CommitDiffResponseSerializer(+ {+ "diff": pr_result["diff"],+ "truncated": pr_result.get("truncated", False),+ }+ ).data+ )try:# Diff the commit's branch against the repo default branch, using each branch's current# tip (no SHA pinning) so the diff stays useful as the branch keeps moving after the@@ -5077,10 +5139,12 @@ class SignalReportArtefactViewSet(status=status.HTTP_502_BAD_GATEWAY,)return Response(- {- "diff": result["diff"],- "truncated": result.get("truncated", False),- }+ CommitDiffResponseSerializer(+ {+ "diff": result["diff"],+ "truncated": result.get("truncated", False),+ }+ ).data)diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 02c0834e466b..19835b4dd04f 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -2619,11 +2619,10 @@ export interface PatchedSignalReportArtefactLogUpdateApi {}/**- * Response for the `commit` artefact diff endpoint — the commit's branch rendered against the- * repository default branch.+ * Response for the `commit` artefact diff endpoint.*/export interface CommitDiffResponseApi {- /** Unified diff (patch) text of the branch against the repository default branch, from the GitHub compare API. */+ /** Unified diff (patch) text from the linked pull request or branch comparison. */readonly diff: string/** True when the diff was too large to return in full and has been truncated. */readonly truncated: booleandiff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 2834cb9c43d9..3cab09684c9b 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -951,7 +951,7 @@ export const getSignalsReportArtefactsDiffUrl = (projectId: string, reportId: st}/**- * Fetch the unified diff of a `commit` artefact's branch against the repository default branch via the team's GitHub integration — using the branch's current tip so the diff reflects the latest state of the work, not just the single recorded commit.+ * Fetch the unified diff for a `commit` artefact via the team's GitHub integration. A commit linked to a report pull request uses GitHub's durable pull request diff. A commit without that link compares the branch's current tip with the default branch.* @summary Fetch the diff for a commit artefact*/export const signalsReportArtefactsDiff = async (diff --git a/products/signals/frontend/inbox/components/detail/PullRequestDiffPanel.tsx b/products/signals/frontend/inbox/components/detail/PullRequestDiffPanel.tsxindex 88a253579bdb..eebe346650da 100644--- a/products/signals/frontend/inbox/components/detail/PullRequestDiffPanel.tsx+++ b/products/signals/frontend/inbox/components/detail/PullRequestDiffPanel.tsx@@ -82,11 +82,11 @@ export function PullRequestDiffPending({ artefactsLoaded }: { artefactsLoaded: b/*** The report's branch as a git-branch tag. Rendered in the "Files changed" section header, so the section- * signals which branch the diff comes from.+ * signals which change the diff comes from.*/export function PullRequestBranchTag({ commit }: { commit: CommitContent }): JSX.Element {return (- <Tooltip title={`Comparing ${commit.repository}@${commit.branch} against the default branch`}>+ <Tooltip title={`Changes on ${commit.repository}@${commit.branch}`}><LemonTag type="muted" className="font-mono min-w-0"><IconGitBranch className="shrink-0" /><span className="truncate">{commit.branch}</span>@@ -96,11 +96,11 @@ export function PullRequestBranchTag({ commit }: { commit: CommitContent }): JSX}/**- * "Files changed" section body: the report's branch diff against the repository default branch, rendered- * GitHub-style and read-only. The section header carries the branch tag; this toolbar balances diff stats on the- * left with the unified/split toggle on the right. The diff itself is loaded by `inboxReportDetailLogic`+ * "Files changed" section body: the report's pull request or pre-PR branch diff, rendered GitHub-style and+ * read-only. The section header carries the branch tag; this toolbar balances diff stats on the left with the+ * unified/split toggle on the right. The diff itself is loaded by `inboxReportDetailLogic`* (keyed to the report, cascading off the artefact load) — this component just renders the current- * state, tracking the branch tip as the work moves.+ * state, tracking the change as the work moves.*/export function PullRequestDiffPanel({ report, commit }: { report: SignalReport; commit: CommitContent }): JSX.Element {const logicProps = useMemo(() => ({ reportId: report.id, report }), [report])@@ -229,7 +229,7 @@ function DiffToolbarSummary({return (<spanclassName="min-w-0 truncate font-mono text-xs text-tertiary"- title={`Comparing ${commit.repository}@${commit.branch} against the default branch`}+ title={`Changes on ${commit.repository}@${commit.branch}`}>{commit.repository}</span>diff --git a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.tsindex ac074011d94e..cc942e19393b 100644--- a/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts+++ b/products/signals/frontend/inbox/logics/inboxReportDetailLogic.ts@@ -830,10 +830,10 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([},},],- // The report's branch diff (its `commit` artefact's branch vs the repo default branch), rendered- // in the "Files changed" section. Loaded here rather than in the component so the fetch is keyed- // to the report and cascades off the artefact load — once artefacts resolve we know the latest- // commit artefact, and re-fetch only when a *new* commit lands (not on every 5s activity poll).+ // The report's pull request or pre-PR branch diff, rendered in the "Files changed" section. Loaded+ // here rather than in the component so the fetch is keyed to the report and cascades off the+ // artefact load — once artefacts resolve we know the latest commit artefact, and re-fetch only when+ // a *new* commit lands (not on every 5s activity poll).reportDiff: [null as CommitDiffResponseApi | null,{@@ -993,15 +993,13 @@ export const inboxReportDetailLogic = kea<inboxReportDetailLogicType>([setFeedbackNoteSubmitting: (_, { submitting }) => submitting,},],- // Human-readable diff-load failure (kea-loaders only exposes a boolean loading flag). A failed- // compare usually means the branch was merged, deleted, or force-rewritten away.+ // Human-readable diff-load failure (kea-loaders only exposes a boolean loading flag).reportDiffError: [null as string | null,{loadReportDiff: () => null,loadReportDiffSuccess: () => null,- loadReportDiffFailure: () =>- "Couldn't load the diff. The branch may have been merged, deleted, or rewritten.",+ loadReportDiffFailure: () => "Couldn't load the diff. Try again, or open the pull request on GitHub.",},],// The commit artefact the current `reportDiff` was loaded for, so the artefact poll re-fetchesdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 53d3de640988..b6a721391fbe 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -21669,11 +21669,10 @@ export namespace Schemas {}/**- * Response for the `commit` artefact diff endpoint — the commit's branch rendered against the- * repository default branch.+ * Response for the `commit` artefact diff endpoint.*/export interface CommitDiffResponse {- /** Unified diff (patch) text of the branch against the repository default branch, from the GitHub compare API. */+ /** Unified diff (patch) text from the linked pull request or branch comparison. */readonly diff: string;/** True when the diff was too large to return in full and has been truncated. */readonly truncated: boolean;