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.

fix(signals): stop sending if-match on pr body edits (#104387)

Julian Bezb6efbdb61644
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index 38259ac5eabf..722b2d82a88d 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -785,16 +785,13 @@ class GitHubIntegrationBase:
*,
endpoint: str,
json_body: Mapping[str, object],
- headers: dict[str, str] | None = None,
timeout: int = 10,
) -> requests.Response | None:
"""PATCH with installation token via :meth:`api_request`; ``None`` instead of raising, for the
success/error-dict verbs built on top."""
path = url.removeprefix("https://api.github.com")
try:
- return self.api_request(
- "PATCH", path, endpoint=endpoint, json_body=json_body, headers=headers, timeout=timeout
- )
+ return self.api_request("PATCH", path, endpoint=endpoint, json_body=json_body, timeout=timeout)
except GitHubIntegrationError:
logger.warning("GitHubIntegration: installation PATCH failed", url=url, exc_info=True)
return None
@@ -1180,7 +1177,6 @@ class GitHubIntegrationBase:
"additions": pr.get("additions", 0),
"deletions": pr.get("deletions", 0),
"changed_files": pr.get("changed_files", 0),
- "etag": response.headers.get("ETag"),
}
def get_pull_request_from_url(self, pr_url: str) -> dict[str, Any]:
@@ -1219,17 +1215,17 @@ class GitHubIntegrationBase:
return {"success": True, "number": pr.get("number", pr_number), "state": pr.get("state")}
- def update_pull_request_body(
- self, repository: str, pr_number: int, body: str, *, expected_etag: str | None = None
- ) -> dict[str, Any]:
- """Replace a pull request's description. ``repository`` is ``owner/repo`` or a bare repo."""
+ def update_pull_request_body(self, repository: str, pr_number: int, body: str) -> dict[str, Any]:
+ """Replace a pull request's description. ``repository`` is ``owner/repo`` or a bare repo.
+
+ GitHub rejects ``If-Match`` on this endpoint with a 400, so the write cannot be conditional.
+ """
repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
response = self._installation_authenticated_patch(
f"https://api.github.com/repos/{repo_path}/pulls/{pr_number}",
endpoint="/repos/{owner}/{repo}/pulls/{pull_number}",
json_body={"body": body},
- headers={"If-Match": expected_etag} if expected_etag else None,
)
if response is None:
return {"success": False, "error": "Network error updating pull request"}
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index da426b443ccc..5bcc7349e847 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -1307,7 +1307,7 @@ Some teams cannot merge a pull request unless a tracked work item points at it.
The create never raises. A provider failure is stored on the row as `status=failed` with a short reason, which the report surfaces next to the pull request, and the run opens its pull request either way.
-Once the pull request exists, `link_report_tracker_issues` (scheduled from the task-run PR sync receiver) writes the Origin section and then appends the reference to the pull request body, behind an HTML-comment marker so the append happens once. Both edits go through `edit_pull_request_body` in `backend/pull_request_body.py`, one after the other, so they never race on the body's etag. GitHub gets `Closes #n`; the other providers get the issue link. A Linear issue also gets the pull request as an attachment, best effort, because the scope for it may not be granted.
+Once the pull request exists, `link_report_tracker_issues` (scheduled from the task-run PR sync receiver) writes the Origin section and then appends the reference to the pull request body, behind an HTML-comment marker so the append happens once. Both edits go through `edit_pull_request_body` in `backend/pull_request_body.py`, one after the other, so they never race on the same body. GitHub rejects `If-Match` on a pull request update, so each edit reads the body again before it writes and retries when the body changed. GitHub gets `Closes #n`; the other providers get the issue link. A Linear issue also gets the pull request as an attachment, best effort, because the scope for it may not be granted.
An irreversible end closes the tracker issue: a resolve asked for through the state API, a merged pull request (closed as done), or a deleted report. A suppressed or snoozed report keeps its issue open, because both come back, and so does a failed run, because its report stays in the inbox and the work item is still real.
diff --git a/products/signals/backend/pull_request_body.py b/products/signals/backend/pull_request_body.py
index 01f3ebfeeb77..e55b29f2a76a 100644
--- a/products/signals/backend/pull_request_body.py
+++ b/products/signals/backend/pull_request_body.py
@@ -1,8 +1,9 @@
"""Backend edits to a self-driving pull request's description.
The agent writes the description, and the backend then adds sections it must not paraphrase, such
-as the tracker issue reference and the Origin section. Every such edit reads the current body and
-writes it back under the body's etag, so an edit never overwrites a change the agent made in between.
+as the tracker issue reference and the Origin section. GitHub has no conditional write for a pull
+request body, so every edit reads the body again right before the write and backs off when it changed.
+A change that lands between that second read and the write can still get lost.
"""
from collections.abc import Callable
@@ -20,11 +21,23 @@ class BodyEditOutcome(StrEnum):
WRITTEN = "written"
# Nothing to write, or the URL is not a GitHub pull request. A retry cannot change that.
SKIPPED = "skipped"
- # GitHub refused, the repository access check failed, or the body changed after the read.
+ # GitHub refused, the repository access check failed, or the body changed during the edit.
# A retry can succeed.
FAILED = "failed"
+def _read_body(
+ github: GitHubIntegration, repository: str, number: int, *, report_id: str, pr_url: str, log_event: str
+) -> str | None:
+ pull_request = github.get_pull_request(repository, number)
+ if not pull_request.get("success"):
+ logger.warning(
+ f"{log_event}_pr_fetch_failed", report_id=report_id, pr_url=pr_url, error=pull_request.get("error")
+ )
+ return None
+ return pull_request.get("body") or ""
+
+
def edit_pull_request_body(
*, team_id: int, report_id: str, pr_url: str, edit: Callable[[str, str], str | None], log_event: str
) -> BodyEditOutcome:
@@ -42,23 +55,26 @@ def edit_pull_request_body(
logger.info(f"{log_event}_no_integration", report_id=report_id, pr_url=pr_url)
return BodyEditOutcome.FAILED
- pull_request = github.get_pull_request(parsed.repository, parsed.number)
- if not pull_request.get("success"):
- logger.warning(
- f"{log_event}_pr_fetch_failed", report_id=report_id, pr_url=pr_url, error=pull_request.get("error")
- )
+ body = _read_body(github, parsed.repository, parsed.number, report_id=report_id, pr_url=pr_url, log_event=log_event)
+ if body is None:
return BodyEditOutcome.FAILED
-
- body = pull_request.get("body") or ""
updated = edit(body, parsed.repository)
if updated is None:
return BodyEditOutcome.SKIPPED
if updated == body:
return BodyEditOutcome.WRITTEN
- outcome = github.update_pull_request_body(
- parsed.repository, parsed.number, updated, expected_etag=pull_request.get("etag")
+ # `edit` can take seconds (the Origin section queries ClickHouse), and the agent can edit the body in that time.
+ latest = _read_body(
+ github, parsed.repository, parsed.number, report_id=report_id, pr_url=pr_url, log_event=log_event
)
+ if latest is None:
+ return BodyEditOutcome.FAILED
+ if latest != body:
+ logger.info(f"{log_event}_pr_body_changed", report_id=report_id, pr_url=pr_url)
+ return BodyEditOutcome.FAILED
+
+ outcome = github.update_pull_request_body(parsed.repository, parsed.number, updated)
if not outcome.get("success"):
logger.warning(f"{log_event}_pr_update_failed", report_id=report_id, pr_url=pr_url, error=outcome.get("error"))
return BodyEditOutcome.FAILED
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index dac77583f512..eab3c77a5055 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -170,7 +170,7 @@ def link_report_tracker_issues(self, team_id: int, task_id: str, pr_url: str) ->
"""Write a task's new pull request body: the Origin section and the tracker issue cross-reference.
Both edits share this task so they run in sequence. Two tasks would race on the same body and
- keep failing each other's etag check.
+ keep failing each other's changed-body check.
"""
report_ids = (
SignalReport.objects.filter(team_id=team_id)
diff --git a/products/signals/backend/test/test_pr_origin.py b/products/signals/backend/test/test_pr_origin.py
index ac08b60ad2e1..adc3cfe66252 100644
--- a/products/signals/backend/test/test_pr_origin.py
+++ b/products/signals/backend/test/test_pr_origin.py
@@ -232,9 +232,7 @@ class TestPullRequestOrigin(BaseTest):
"first_for_team_repository",
return_value=GitHubIntegration.__new__(GitHubIntegration),
),
- patch.object(
- GitHubIntegration, "get_pull_request", return_value={"success": True, "body": "", "etag": "e"}
- ),
+ patch.object(GitHubIntegration, "get_pull_request", return_value={"success": True, "body": ""}),
patch.object(GitHubIntegration, "update_pull_request_body", return_value={"success": True}) as update,
):
outcome = write_origin_section(
diff --git a/products/signals/backend/test/test_tracker_issues.py b/products/signals/backend/test/test_tracker_issues.py
index baa4b27c2e70..2d85c9f13560 100644
--- a/products/signals/backend/test/test_tracker_issues.py
+++ b/products/signals/backend/test/test_tracker_issues.py
@@ -2,7 +2,7 @@ from datetime import timedelta
from typing import Any
import pytest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from django.utils import timezone
@@ -200,6 +200,44 @@ def test_link_pull_request_appends_the_reference_once(team):
issue_url="https://github.com/acme/web/issues/12",
)
pr_url = "https://github.com/acme/web/pull/50"
+ pull_request: dict[str, Any] = {"number": 50, "body": "Fixes the thing"}
+
+ # GitHub sends an ETag on the GET but rejects a conditional header on the PATCH.
+ def fake_github(method: str, path: str, *, headers: dict[str, str] | None = None, **kwargs: Any) -> MagicMock:
+ if method == "GET":
+ return MagicMock(status_code=200, headers={"ETag": '"v1"'}, json=MagicMock(return_value=pull_request))
+ if any(name.lower().startswith("if-") for name in headers or {}):
+ return MagicMock(status_code=400, text="Conditional request headers are not allowed in unsafe requests")
+ pull_request["body"] = kwargs["json_body"]["body"]
+ return MagicMock(status_code=200)
+
+ with (
+ patch.object(
+ GitHubIntegration, "first_for_team_repository", return_value=GitHubIntegration.__new__(GitHubIntegration)
+ ),
+ patch.object(GitHubIntegration, "api_request", side_effect=fake_github),
+ ):
+ assert link_pull_request_to_tracker_issue(team_id=team.id, report_id=str(report.id), pr_url=pr_url) is True
+ assert link_pull_request_to_tracker_issue(team_id=team.id, report_id=str(report.id), pr_url=pr_url) is False
+
+ assert pull_request["body"].count(PR_BODY_MARKER) == 1
+ assert "Closes #12" in pull_request["body"]
+ tracker.refresh_from_db()
+ assert tracker.pr_linked_at is not None
+
+
+def test_link_pull_request_backs_off_when_the_body_changes_during_the_edit(team):
+ _connect_tracker(team, "github")
+ report = _make_report(team)
+ tracker = SignalReportTrackerIssue.all_teams.create(
+ team=team,
+ report=report,
+ provider="github",
+ status=SignalReportTrackerIssue.Status.CREATED,
+ external_context={"repository": "acme/web", "number": 12},
+ issue_url="https://github.com/acme/web/issues/12",
+ )
with (
patch.object(
@@ -208,20 +246,21 @@ def test_link_pull_request_appends_the_reference_once(team):
patch.object(
GitHubIntegration,
"get_pull_request",
- return_value={"success": True, "body": "Fixes the thing", "etag": '"version-1"'},
+ side_effect=[
+ {"success": True, "body": "Fixes the thing"},
+ {"success": True, "body": "Fixes the thing, rewritten by the agent"},
+ ],
),
patch.object(GitHubIntegration, "update_pull_request_body", return_value={"success": True}) as update,
):
- assert link_pull_request_to_tracker_issue(team_id=team.id, report_id=str(report.id), pr_url=pr_url) is True
- assert link_pull_request_to_tracker_issue(team_id=team.id, report_id=str(report.id), pr_url=pr_url) is False
+ linked = link_pull_request_to_tracker_issue(
+ team_id=team.id, report_id=str(report.id), pr_url="https://github.com/acme/web/pull/50"
+ )
- assert update.call_count == 1
- body = update.call_args.args[2]
- assert PR_BODY_MARKER in body
- assert "Closes #12" in body
- assert update.call_args.kwargs["expected_etag"] == '"version-1"'
+ assert linked is False
+ update.assert_not_called()
tracker.refresh_from_db()
- assert tracker.pr_linked_at is not None
+ assert tracker.pr_linked_at is None
@pytest.mark.django_db