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(stamphog): keep approvals across a clean merge of the base branch (#111776)

Julian Bezc510e7785744
diff --git a/products/stamphog/AGENTS.md b/products/stamphog/AGENTS.md
index 95c7654c6b3b..015542cc2a41 100644
--- a/products/stamphog/AGENTS.md
+++ b/products/stamphog/AGENTS.md
@@ -46,7 +46,11 @@ head-changing event must retract standing approvals itself:
The one deliberate exception is **approval retention**.
A head-changing delivery whose push left the PR's own diff byte-identical skips both the retraction and the review (`_standing_approval_retention` in the Celery task, deciding through [`logic/approval_retention.py`](backend/logic/approval_retention.py)).
It is content-based rather than commit-based: the PR's own unified diff at the approved head against the same at the current head.
-So a merge of the base branch that touches none of the PR's files retains, and a merge that resolves a conflict inside one of them re-reviews.
+So a merge of the base branch that touches none of the PR's files retains.
+A base merge that also edits a PR file changes the diff text, because the PR's hunks move. It still retains through `base_merge_is_clean`, which proves two things.
+The lineage proof: the head has exactly two parents, the first is an approved or already retained head, and the second is an ancestor of the payload's base sha.
+The content proof: every file that differs between the two diffs is exactly the `git merge-file` result of the merge base, the approved parent and the base parent.
+A conflict resolution, or any other content that the author put in the merge commit, fails that proof and re-reviews.
Comparing the diff text rather than per-file blob shas is deliberate, because the text carries file modes and renames, and a blob sha covers contents only.
The one thing the text does not carry is binary content, which git renders as `Binary files ... differ` over an abbreviated blob id, so a diff mentioning one is refused rather than compared.
diff --git a/products/stamphog/backend/logic/approval_retention.py b/products/stamphog/backend/logic/approval_retention.py
index 5eb9e9a5f953..fc38a0591f8c 100644
--- a/products/stamphog/backend/logic/approval_retention.py
+++ b/products/stamphog/backend/logic/approval_retention.py
@@ -6,8 +6,12 @@ wrong for the push that dominates a long-lived PR: a merge of the base branch. S
change the PR's own diff, but it still costs the PR its merge readiness. It also forces a full
sandboxed review to derive the same verdict again.
-Retention answers one question, and it never judges whether a given file matters. The question is
-whether the PR's own diff is byte-identical to the diff that was approved.
+Retention never judges whether a given file matters. It retains on one of two proofs:
+
+- The PR's own diff is byte-identical to the diff that was approved.
+- The new head is a merge of the base branch into an approved head, and the merge adds nothing of its
+ own. See `base_merge_is_clean`. This proof covers a base merge that also changed a file the PR
+ edits, which moves the PR's hunks and so changes its diff text.
Three properties of that comparison are necessary for safety. A review finding caused each one:
@@ -25,6 +29,13 @@ somewhere in this repository. Plain Markdown is executable too, because it ships
from __future__ import annotations
import re
+import tempfile
+import subprocess
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from products.stamphog.backend.logic.github_client import StamphogGitHubClient
# Heads that a run's approval covers in addition to the head it was posted at. The merge handler
# matches an approving run on head_sha alone, so without this record a retained PR merges as
@@ -35,8 +46,30 @@ RETAINED_HEADS_KEY = "retained_head_shas"
# the merged head, so the oldest entries are safe to drop.
MAX_RETAINED_HEADS = 50
-# The only reason an approval survives a push. The webhook skip log records this value.
+# The reasons that an approval survives a push. The webhook skip log records the value.
UNCHANGED_DIFF = "unchanged_diff"
+CLEAN_BASE_MERGE = "clean_base_merge"
+
+# Each file that both sides of a base merge changed costs four contents reads. Past this bound the
+# push gets a normal review.
+MAX_MERGED_FILES = 20
+
+_MERGE_FILE_TIMEOUT_SECONDS = 10
+
+# GitHub compare statuses that make the base sha an ancestor of the head sha.
+_DESCENDANT_STATUSES = frozenset({"ahead", "identical"})
+
+_FILE_HEADER_RE = re.compile(r"^(?=diff --git )", re.MULTILINE)
+
+# The only per-file header that the three-way proof accepts: a regular file at an unquoted path, with
+# no mode change, rename, copy, creation or deletion. git quotes a path with unusual characters, and
+# that quote fails the match.
+_PLAIN_EDIT_HEADER_RE = re.compile(
+ r"\Adiff --git a/(?P<path>[^\n]+) b/(?P=path)\n"
+ r"index [0-9a-f]+\.\.[0-9a-f]+ (?P<mode>100644|100755)\n"
+ r"--- a/(?P=path)\n"
+ r"\+\+\+ b/(?P=path)\n"
+)
# git renders a binary change as this line over an abbreviated blob id, and never as content. Two
@@ -59,3 +92,118 @@ def approved_diff_unchanged(approved_diff: str, current_diff: str) -> bool:
if _BINARY_MARKER_RE.search(approved_diff) or _BINARY_MARKER_RE.search(current_diff):
return False
return approved_diff == current_diff
+
+
+def _file_sections(diff: str) -> dict[str, str] | None:
+ """The diff split per file and keyed by its `diff --git` line, or None for an unexpected shape."""
+ sections: dict[str, str] = {}
+ for chunk in _FILE_HEADER_RE.split(diff):
+ if not chunk:
+ continue
+ header = chunk.split("\n", 1)[0]
+ if not header.startswith("diff --git ") or header in sections:
+ return None
+ sections[header] = chunk
+ return sections
+
+
+def files_needing_merge_proof(pr_side_diff: str, merged_diff: str) -> list[str] | None:
+ """The paths whose content in a merge commit only a three-way merge can account for.
+
+ ``pr_side_diff`` is the PR's own diff at the approved parent of the merge, and ``merged_diff`` is
+ the diff from the base parent to the merge commit. A file whose section is byte-identical in both
+ diffs needs no proof: the base side did not change it, and the merge kept the PR's version. Any
+ other file must be a plain edit on both sides. Returns None when the merge cannot be proven at
+ all: different file sets, a binary change, a mode change, a rename, a creation, a deletion, or
+ more than MAX_MERGED_FILES files to prove.
+ """
+ if not pr_side_diff.strip() or not merged_diff.strip():
+ return None
+ if _BINARY_MARKER_RE.search(pr_side_diff) or _BINARY_MARKER_RE.search(merged_diff):
+ return None
+ pr_side = _file_sections(pr_side_diff)
+ merged = _file_sections(merged_diff)
+ # A file in only one diff is content that the merge added or dropped on its own.
+ if pr_side is None or merged is None or pr_side.keys() != merged.keys():
+ return None
+ paths: list[str] = []
+ for header, section in pr_side.items():
+ if merged[header] == section:
+ continue
+ pr_side_match = _PLAIN_EDIT_HEADER_RE.match(section)
+ merged_match = _PLAIN_EDIT_HEADER_RE.match(merged[header])
+ if pr_side_match is None or merged_match is None or pr_side_match["mode"] != merged_match["mode"]:
+ return None
+ paths.append(pr_side_match["path"])
+ if len(paths) > MAX_MERGED_FILES:
+ return None
+ return paths
+
+
+def clean_three_way_merge(base: str, ours: str, theirs: str) -> str | None:
+ """The result of `git merge-file` on three file versions, or None when the merge has a conflict.
+
+ git's own merge can use a different diff algorithm and produce different text. That difference
+ can only refuse a genuine merge, and it cannot accept an edited one, because the caller accepts
+ a merge commit only when its content is exactly a clean merge of the two parents.
+ """
+ with tempfile.TemporaryDirectory(prefix="stamphog-merge-") as temp_dir:
+ root = Path(temp_dir)
+ paths: list[str] = []
+ for name, text in (("ours", ours), ("base", base), ("theirs", theirs)):
+ path = root / name
+ path.write_bytes(text.encode("utf-8"))
+ paths.append(str(path))
+ completed = subprocess.run(
+ ["git", "merge-file", "-p", *paths],
+ capture_output=True,
+ timeout=_MERGE_FILE_TIMEOUT_SECONDS,
+ check=False,
+ )
+ # A positive exit code counts the conflicts, and a negative one is an error.
+ if completed.returncode != 0:
+ return None
+ return completed.stdout.decode("utf-8")
+
+
+def base_merge_is_clean(
+ client: StamphogGitHubClient, repo: str, *, approved_heads: set[str], head_sha: str, base_sha: str
+) -> bool:
+ """Whether ``head_sha`` merges the base branch into an approved head and adds nothing of its own.
+
+ The proof has two parts:
+
+ - Lineage. The head has exactly two parents. The first is an approved head. The second is an
+ ancestor of ``base_sha``, so it is base-branch content and not a commit that the author made.
+ - Content. Every file is either identical to the approved parent's version, as
+ `files_needing_merge_proof` shows from the two diffs, or exactly the clean three-way merge of
+ the approved parent's version and the base parent's version.
+
+ A conflict resolution fails the proof, because the author wrote that content.
+ """
+ parents = client.get_commit_parents(repo, head_sha)
+ if len(parents) != 2:
+ return False
+ pr_parent, base_parent = parents
+ if pr_parent not in approved_heads:
+ return False
+ if client.compare_commits(repo, base_parent, base_sha).status not in _DESCENDANT_STATUSES:
+ return False
+ merge_base = client.compare_commits(repo, base_parent, pr_parent).merge_base_sha
+ if not merge_base:
+ return False
+
+ # Three-dot compares, so the first diff starts at the merge base and the second at the base parent.
+ paths = files_needing_merge_proof(
+ client.compare_diff(repo, base_parent, pr_parent), client.compare_diff(repo, base_parent, head_sha)
+ )
+ if paths is None:
+ return False
+ for path in paths:
+ versions = [client.get_file_at_ref(repo, path, ref) for ref in (merge_base, pr_parent, base_parent, head_sha)]
+ if any(version is None or version.kind != "file" for version in versions):
+ return False
+ base, ours, theirs, merged = (version.text for version in versions if version is not None)
+ if clean_three_way_merge(base, ours, theirs) != merged:
+ return False
+ return True
diff --git a/products/stamphog/backend/logic/github_client.py b/products/stamphog/backend/logic/github_client.py
index 670820c0569c..275ed2a07c19 100644
--- a/products/stamphog/backend/logic/github_client.py
+++ b/products/stamphog/backend/logic/github_client.py
@@ -381,6 +381,15 @@ class RepoPathEntry:
text: str
+@frozen
+class CommitComparison:
+ """The history summary of a two-commit compare."""
+
+ # GitHub's relation of the head to the base: "ahead", "behind", "identical" or "diverged".
+ status: str
+ merge_base_sha: str
+
+
class StamphogGitHubClient:
"""Installation-scoped GitHub client for one Stamphog App installation.
@@ -758,6 +767,45 @@ class StamphogGitHubClient:
response.close()
return b"".join(chunks).decode("utf-8", errors="replace")
+ def get_commit_parents(self, repo: str, sha: str) -> list[str]:
+ """The parent shas of a commit, in git's order, so a merge commit lists its first parent first."""
+ path = f"/repos/{repo}/git/commits/{sha}"
+ response = self._request("GET", path, endpoint="/repos/{owner}/{repo}/git/commits/{commit_sha}")
+ if response.status_code != 200:
+ raise StamphogGitHubError(
+ f"Failed to fetch commit {sha} in {repo}: {response.text[:300]}", status_code=response.status_code
+ )
+ data = self._json(response, path)
+ parents = data.get("parents") if isinstance(data, dict) else None
+ if not isinstance(parents, list):
+ raise StamphogGitHubError(f"Unexpected commit payload for {sha} in {repo}")
+ return [str(parent.get("sha") or "") for parent in parents if isinstance(parent, dict)]
+
+ def compare_commits(self, repo: str, base_sha: str, head_sha: str) -> CommitComparison:
+ """How ``head_sha`` relates to ``base_sha`` in history, and their merge base.
+
+ The status is GitHub's: ``ahead`` or ``identical`` means that ``base_sha`` is an ancestor of
+ ``head_sha``. The endpoint also returns the changed files, which this method does not read.
+ """
+ path = f"/repos/{repo}/compare/{base_sha}...{head_sha}"
+ # One commit per page, because only the summary fields are read.
+ response = self._request(
+ "GET", path, endpoint="/repos/{owner}/{repo}/compare/{basehead}", params={"per_page": 1}
+ )
+ if response.status_code != 200:
+ raise StamphogGitHubError(
+ f"Failed to compare {base_sha}...{head_sha} in {repo}: {response.text[:300]}",
+ status_code=response.status_code,
+ )
+ data = self._json(response, path)
+ if not isinstance(data, dict):
+ raise StamphogGitHubError(f"Unexpected compare payload for {base_sha}...{head_sha} in {repo}")
+ merge_base = data.get("merge_base_commit")
+ return CommitComparison(
+ status=str(data.get("status") or ""),
+ merge_base_sha=str((merge_base or {}).get("sha") or "") if isinstance(merge_base, dict) else "",
+ )
+
def get_pr_reviews(self, repo: str, number: int) -> list[dict]:
"""Fetch the PR's top-level reviews, paginating through GitHub's list endpoint.
diff --git a/products/stamphog/backend/tasks/tasks.py b/products/stamphog/backend/tasks/tasks.py
index 78c90debdb61..d7e1be80fd85 100644
--- a/products/stamphog/backend/tasks/tasks.py
+++ b/products/stamphog/backend/tasks/tasks.py
@@ -36,10 +36,12 @@ from products.stamphog.backend.facade.enums import (
)
from products.stamphog.backend.facade.inbox_hooks import get_inbox_acting_reviewer_resolver
from products.stamphog.backend.logic.approval_retention import (
+ CLEAN_BASE_MERGE,
MAX_RETAINED_HEADS,
RETAINED_HEADS_KEY,
UNCHANGED_DIFF,
approved_diff_unchanged,
+ base_merge_is_clean,
)
from products.stamphog.backend.logic.approvals import dismiss_stale_approvals_for_head
from products.stamphog.backend.logic.audiences import ResolvedAudience, resolve_audiences
@@ -541,15 +543,16 @@ def _retract_approvals_on_base_retarget(repo_config: StamphogRepoConfig, pr: dic
)
-def _standing_approval_retention(repo_config: StamphogRepoConfig, pr: dict[str, Any]) -> bool:
- """Whether a standing approval survives this push, rather than being dismissed and re-reviewed.
+def _standing_approval_retention(repo_config: StamphogRepoConfig, pr: dict[str, Any]) -> str | None:
+ """Why a standing approval survives this push, or None when it is dismissed and re-reviewed.
Compares the PR's own diff at the head that the approval was posted for against its diff at the
head that this delivery carries. ``compare_diff`` reads both sides from commit shas that the
payload and the run already fixed, so a contributor cannot point either side at content that the
- PR is not on.
+ PR is not on. When the two diffs differ, the push still retains if it is a clean merge of the
+ base branch into an approved head, see ``base_merge_is_clean``.
- Returns False for everything ambiguous: no PR row, no standing approval, an approval already at
+ Returns None for everything ambiguous: no PR row, no standing approval, an approval already at
this head, a run with no recorded base sha, an empty diff on either side, or any GitHub error. A
diff too large for GitHub to render is one such error. A same-head re-review is allowed to void
the approval on purpose.
@@ -559,7 +562,7 @@ def _standing_approval_retention(repo_config: StamphogRepoConfig, pr: dict[str,
head_sha = (pr.get("head") or {}).get("sha") or ""
base_sha = (pr.get("base") or {}).get("sha") or ""
if pr_number is None or not head_sha or not base_sha:
- return False
+ return None
# Writer pin for the same reason that _retract_stale_approvals_on_skip uses one. This read
# decides whether an approval stands, and a lagged reader that misses the approving run falls
@@ -571,7 +574,7 @@ def _standing_approval_retention(repo_config: StamphogRepoConfig, pr: dict[str,
.first()
)
if pull_request is None:
- return False
+ return None
standing = (
ReviewRun.objects.for_team(team_id)
@@ -586,13 +589,13 @@ def _standing_approval_retention(repo_config: StamphogRepoConfig, pr: dict[str,
.first()
)
if standing is None or standing.posted_review_id is None or not standing.head_sha:
- return False
+ return None
approved_pr = (standing.output or {}).get("pr")
approved_base = (approved_pr or {}).get("base") if isinstance(approved_pr, dict) else None
approved_base_sha = (approved_base or {}).get("sha") if isinstance(approved_base, dict) else ""
if not approved_base_sha:
- return False
+ return None
client = StamphogGitHubClient(repo_config.installation_id)
# posted_review_id records that stamphog approved, and not that the approval still stands. A
@@ -601,14 +604,29 @@ def _standing_approval_retention(repo_config: StamphogRepoConfig, pr: dict[str,
# unreadable or unconfigured identity yields an empty list, which falls through to the review.
active_ids = {review.get("id") for review in client.list_own_active_approvals(repo_config.repository, pr_number)}
if standing.posted_review_id not in active_ids:
- return False
+ return None
approved_diff = client.compare_diff(repo_config.repository, approved_base_sha, standing.head_sha)
current_diff = client.compare_diff(repo_config.repository, base_sha, head_sha)
- if not approved_diff_unchanged(approved_diff, current_diff):
- return False
+ if approved_diff_unchanged(approved_diff, current_diff):
+ reason = UNCHANGED_DIFF
+ elif base_merge_is_clean(
+ client,
+ repo_config.repository,
+ approved_heads={standing.head_sha, *_retained_heads(standing)},
+ head_sha=head_sha,
+ base_sha=base_sha,
+ ):
+ reason = CLEAN_BASE_MERGE
+ else:
+ return None
_record_retained_head(standing, head_sha)
- return True
+ return reason
+
+
+def _retained_heads(run: ReviewRun) -> list[str]:
+ stored = (run.output or {}).get(RETAINED_HEADS_KEY) or []
+ return [sha for sha in stored if isinstance(sha, str)]
def _record_retained_head(run: ReviewRun, head_sha: str) -> None:
@@ -619,8 +637,7 @@ def _record_retained_head(run: ReviewRun, head_sha: str) -> None:
because ``merged_at`` makes the redelivery a no-op. The reviewed head stays on ``head_sha``
itself, which the dismissal sweep and ``post_verdict``'s guards read.
"""
- stored = (run.output or {}).get(RETAINED_HEADS_KEY) or []
- retained = [sha for sha in stored if isinstance(sha, str)]
+ retained = _retained_heads(run)
if head_sha in retained:
return
retained.append(head_sha)
@@ -1207,18 +1224,18 @@ def process_pull_request_event(payload: dict[str, Any], delivery_id: str) -> Non
# their head-pinning carve-out untouched.
if action in _HEAD_CHANGING_ACTIONS and inbox_review is None:
try:
- retained = _standing_approval_retention(repo_config, pr)
+ retention_reason = _standing_approval_retention(repo_config, pr)
except Exception:
# This is an optimization, so it must never cost a review. An unreachable GitHub or an
# unexpected payload falls through to the full path, and never retries or retains.
logger.warning("stamphog_pr_event_retention_check_failed", delivery_id=delivery_id, exc_info=True)
- retained = False
- if retained:
+ retention_reason = None
+ if retention_reason is not None:
logger.info(
"stamphog_pr_event_approval_retained",
repo=repo,
pr_number=pr_number,
- reason=UNCHANGED_DIFF,
+ reason=retention_reason,
)
if delivery_id:
_mark_pr_event_processed(delivery_id)
diff --git a/products/stamphog/backend/tests/test_logic.py b/products/stamphog/backend/tests/test_logic.py
index f67c5fe97cdb..2c993c0c5d19 100644
--- a/products/stamphog/backend/tests/test_logic.py
+++ b/products/stamphog/backend/tests/test_logic.py
@@ -1,6 +1,9 @@
import json
+import tempfile
import threading
+import subprocess
from collections.abc import Callable
+from pathlib import Path
from typing import cast
import pytest
@@ -14,13 +17,15 @@ from parameterized import parameterized
from posthog.egress.github.transport import GitHubRateLimitError
from products.stamphog.backend.facade.enums import AudienceReason, ReviewMode, ReviewTrigger
-from products.stamphog.backend.logic.approval_retention import approved_diff_unchanged
+from products.stamphog.backend.logic.approval_retention import approved_diff_unchanged, base_merge_is_clean
from products.stamphog.backend.logic.audiences import resolve_audiences
from products.stamphog.backend.logic.digest import DigestPRSummary, DigestSummary, _build_selection_prompt
from products.stamphog.backend.logic.digest_config import RepoDigestConfig, load_repo_digest_config
from products.stamphog.backend.logic.familiarity_facts import FamiliarityStatus, ReviewHistory, fetch_review_history
from products.stamphog.backend.logic.github_client import (
MAX_COMPARE_DIFF_BYTES,
+ CommitComparison,
+ RepoPathEntry,
StamphogGitHubClient,
StamphogGitHubError,
_build_app_jwt,
@@ -1062,3 +1067,141 @@ class ApprovalRetentionTests(SimpleTestCase):
# Two blanks compare equal. Retention on that evidence would treat an unreadable answer as
# "nothing changed".
assert approved_diff_unchanged(approved, current) is False
+
+
+class _LocalGitClient:
+ def __init__(self, root: Path) -> None:
+ self.root = root
+ identity = {"GIT_AUTHOR_NAME": "dev", "GIT_AUTHOR_EMAIL": "[email protected]"}
+ self.env = {**identity, "GIT_COMMITTER_NAME": "dev", "GIT_COMMITTER_EMAIL": "[email protected]"}
+
+ def git(self, *args: str, stdin: str | None = None, env: dict[str, str] | None = None) -> str:
+ return subprocess.run(
+ ["git", *args],
+ cwd=self.root,
+ input=stdin,
+ env={"PATH": "/usr/bin:/bin:/usr/local/bin", **self.env, **(env or {})},
+ capture_output=True,
+ text=True,
+ check=True,
+ ).stdout
+
+ def _is_ancestor(self, ancestor: str, descendant: str) -> bool:
+ return (
+ subprocess.run(["git", "merge-base", "--is-ancestor", ancestor, descendant], cwd=self.root).returncode == 0
+ )
+
+ def get_commit_parents(self, repo: str, sha: str) -> list[str]:
+ return self.git("rev-list", "--parents", "-n", "1", sha).split()[1:]
+
+ def compare_commits(self, repo: str, base_sha: str, head_sha: str) -> CommitComparison:
+ if base_sha == head_sha:
+ status = "identical"
+ elif self._is_ancestor(base_sha, head_sha):
+ status = "ahead"
+ elif self._is_ancestor(head_sha, base_sha):
+ status = "behind"
+ else:
+ status = "diverged"
+ return CommitComparison(status=status, merge_base_sha=self.git("merge-base", base_sha, head_sha).strip())
+
+ def compare_diff(self, repo: str, base_sha: str, head_sha: str) -> str:
+ return self.git("diff", "--no-color", f"{base_sha}...{head_sha}")
+
+ def get_file_at_ref(self, repo: str, path: str, ref: str) -> RepoPathEntry | None:
+ try:
+ return RepoPathEntry(kind="file", text=self.git("show", f"{ref}:{path}"))
+ except subprocess.CalledProcessError:
+ return None
+
+
+def _lines(**edits: str) -> str:
+ lines = [f"line {n}" for n in range(1, 31)]
+ for name, text in edits.items():
+ lines[int(name.removeprefix("line")) - 1] = text
+ return "\n".join(lines) + "\n"
+
+
+class BaseMergeProofTests(SimpleTestCase):
+ # Commits are built with plumbing so each test states its parents exactly, which is what lets a
+ # test hand-craft a merge commit with genuine parents and edited content.
+ def setUp(self) -> None:
+ temp_dir = tempfile.TemporaryDirectory()
+ self.addCleanup(temp_dir.cleanup)
+ self.repo = _LocalGitClient(Path(temp_dir.name))
+ self.repo.git("init", "-q")
+ self.base = self._commit({"app.py": _lines()}, [])
+
+ def _commit(self, files: dict[str, str], parents: list[str]) -> str:
+ index = {"GIT_INDEX_FILE": str(self.repo.root / "test-index")}
+ self.repo.git("read-tree", "--empty", env=index)
+ for name, text in files.items():
+ blob = self.repo.git("hash-object", "-w", "--stdin", stdin=text).strip()
+ self.repo.git("update-index", "--add", "--cacheinfo", f"100644,{blob},{name}", env=index)
+ tree = self.repo.git("write-tree", env=index).strip()
+ return self.repo.git("commit-tree", tree, *(arg for sha in parents for arg in ("-p", sha)), "-m", "c").strip()
+
+ def _branches(self, master_edit: dict[str, str]) -> tuple[str, str]:
+ approved = self._commit({"app.py": _lines(line25="pr change")}, [self.base])
+ master = self._commit({"app.py": _lines(**master_edit)}, [self.base])
+ return approved, master
+
+ def _proven(self, approved: str, head: str, base_sha: str) -> bool:
+ return base_merge_is_clean(
+ cast(StamphogGitHubClient, self.repo),
+ "o/r",
+ approved_heads={approved},
+ head_sha=head,
+ base_sha=base_sha,
+ )
+
+ def test_genuine_merge_that_moves_the_pr_hunk_retains(self) -> None:
+ # Master edits the PR's file outside the PR's hunk, so the hunk's context and blob ids change.
+ # The PR's own diff text is no longer byte-identical, but the merge adds nothing of its own.
+ approved, master = self._branches({"line2": "master change"})
+ tree = self.repo.git("merge-tree", "--write-tree", approved, master).splitlines()[0]
+ head = self.repo.git("commit-tree", tree, "-p", approved, "-p", master, "-m", "merge").strip()
+
+ approved_diff = self.repo.compare_diff("o/r", self.base, approved)
+ assert approved_diff_unchanged(approved_diff, self.repo.compare_diff("o/r", master, head)) is False
+ assert self._proven(approved, head, master) is True
+
+ @parameterized.expand(
+ [
+ (
+ "edit_hidden_in_the_merge",
+ {"line2": "master change"},
+ {"app.py": _lines(line2="master change", line25="pr change", line11="unreviewed")},
+ ),
+ (
+ "file_added_in_the_merge",
+ {"line2": "master change"},
+ {"app.py": _lines(line2="master change", line25="pr change"), "new.py": "unreviewed\n"},
+ ),
+ (
+ "conflict_resolved_by_the_author",
+ {"line25": "master change"},
+ {"app.py": _lines(line25="resolved by the author")},
+ ),
+ ]
+ )
+ def test_author_content_inside_the_merge_commit_is_not_retained(
+ self, _name: str, master_edit: dict[str, str], merged_files: dict[str, str]
+ ) -> None:
+ # The merge commit has genuine parents, so only the content check stands between content that
+ # the author wrote and a standing approval.
+ approved, master = self._branches(master_edit)
+ head = self._commit(merged_files, [approved, master])
+
+ assert self._proven(approved, head, master) is False
+
+ @parameterized.expand([("unapproved_first_parent",), ("base_parent_not_on_base_branch",)])
+ def test_merge_with_untrusted_lineage_is_not_retained(self, name: str) -> None:
+ # A base sha that predates the merged parent means that parent is not base-branch content.
+ approved, master = self._branches({"line2": "master change"})
+ head = self._commit({"app.py": _lines(line2="master change", line25="pr change")}, [approved, master])
+
+ if name == "unapproved_first_parent":
+ assert self._proven(self.base, head, master) is False
+ else:
+ assert self._proven(approved, head, self.base) is False
diff --git a/products/stamphog/backend/tests/test_tasks.py b/products/stamphog/backend/tests/test_tasks.py
index 70b712612e65..4754c580bed8 100644
--- a/products/stamphog/backend/tests/test_tasks.py
+++ b/products/stamphog/backend/tests/test_tasks.py
@@ -1302,27 +1302,32 @@ def _approved_run(team_id: int) -> None:
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
@pytest.mark.parametrize(
- "same_diff,expect_retained",
- [(True, True), (False, False)],
- ids=["identical_diff_retains", "changed_diff_dismisses"],
+ "same_diff,clean_base_merge,expect_retained",
+ [(True, False, True), (False, False, False), (False, True, True)],
+ ids=["identical_diff_retains", "changed_diff_dismisses", "clean_base_merge_retains"],
)
-def test_push_retains_the_approval_only_when_the_diff_is_identical(team, repo_config, same_diff, expect_retained):
+def test_push_retains_the_approval_only_when_the_diff_is_identical(
+ team, repo_config, same_diff, clean_base_merge, expect_retained
+):
# A merge of the base branch does not change any blob in the PR's own diff, so there is nothing
# new to review, and a dismissal would drop the PR out of merge readiness. A blob that did move
# is content that the approval no longer covers, and that case keeps the stale-approval
- # invariant intact.
+ # invariant intact, unless the push is a proven clean merge of the base branch.
#
# Each case uses its own delivery id, because _mark_pr_event_processed writes to the
# process-wide cache. A shared id would let the first case remove the second case's deliveries
# as duplicates.
current_diff = _APPROVED if same_diff else _APPROVED.replace("+added", "+something else")
- _run_task(_pr_payload(), f"delivery-retention-approved-{same_diff}", team.id)
+ _run_task(_pr_payload(), f"delivery-retention-approved-{same_diff}-{clean_base_merge}", team.id)
_approved_run(team.id)
- with patch("products.stamphog.backend.tasks.tasks.dismiss_stale_approvals_for_head", return_value=1) as dismiss:
+ with (
+ patch("products.stamphog.backend.tasks.tasks.dismiss_stale_approvals_for_head", return_value=1) as dismiss,
+ patch("products.stamphog.backend.tasks.tasks.base_merge_is_clean", return_value=clean_base_merge),
+ ):
mock_execute = _run_task(
_pr_payload(action="synchronize", head_sha="sha-2"),
- f"delivery-retention-push-{same_diff}",
+ f"delivery-retention-push-{same_diff}-{clean_base_merge}",
team.id,
compare_diffs=[_APPROVED, current_diff],
)