: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 the dri pick from overriding what people decided (#102201)
Julian Bezdcf340255938
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex edf881433b56..f16138b9366b 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -1385,6 +1385,37 @@ class GitHubIntegrationBase:]return {"success": True, "paths": paths}+ def was_ever_unassigned(self, repository: str, issue_number: int) -> dict[str, Any]:+ """Whether anybody ever removed an assignee from an issue or pull request.++ Reads every page of the issue events, so a failed page comes back as a failure rather than as+ "never unassigned".+ """+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"++ responses, complete = self._installation_authenticated_get_pages(+ f"https://api.github.com/repos/{repo_path}/issues/{issue_number}/events",+ endpoint="/repos/{owner}/{repo}/issues/{issue_number}/events",+ params={"per_page": 100},+ )+ if not complete:+ last = responses[-1] if responses else None+ return {+ "success": False,+ "error": f"Failed to list issue events: {last.text if last is not None else 'network error'}",+ "status_code": last.status_code if last is not None else None,+ }+ for response in responses:+ try:+ events = response.json()+ except Exception:+ return {"success": False, "error": "Failed to parse issue events JSON"}+ if not isinstance(events, list):+ return {"success": False, "error": "Issue events JSON is not a list"}+ if any(isinstance(event, dict) and event.get("event") == "unassigned" for event in events):+ return {"success": True, "unassigned": True}+ return {"success": True, "unassigned": False}+def list_team_members(self, org: str, team_slug: str) -> dict[str, Any]:"""The logins of every member of a GitHub team, including members of its child teams.diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.pyindex 7e9b9b45fd70..025dfcea3337 100644--- a/posthog/models/test/integration/test_github.py+++ b/posthog/models/test/integration/test_github.py@@ -1004,6 +1004,30 @@ class TestGitHubIntegrationModel(BaseTest):assert {key: result[key] for key in expected} == expectedassert mock_pages.call_args.args[0] == "https://api.github.com/orgs/PostHog/teams/team-devex/members"+ @parameterized.expand(+ [+ ("unassigned_on_a_later_page", True, "unassigned", {"success": True, "unassigned": True}),+ ("never_unassigned", True, "labeled", {"success": True, "unassigned": False}),+ ("a_page_failed", False, "labeled", {"success": False}),+ ("a_page_is_not_a_list", True, None, {"success": False}),+ ]+ )+ def test_was_ever_unassigned_reads_every_page(+ self, _name: str, complete: bool, last_event: str | None, expected: dict+ ):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ first = MagicMock(status_code=200)+ first.json.return_value = [{"event": "assigned"}]+ second = MagicMock(status_code=200 if complete else 502, text="Bad gateway")+ second.json.return_value = [{"event": last_event}] if last_event else {"message": "Moved"}+ with patch.object(+ github, "_installation_authenticated_get_pages", return_value=([first, second], complete)+ ) as mock_pages:+ result = github.was_ever_unassigned("PostHog/posthog", 42)+ assert {key: result[key] for key in expected} == expected+ assert mock_pages.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/issues/42/events"+def test_add_pull_request_assignees_from_url_parses_and_posts(self):integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})github = GitHubIntegration(integration)diff --git a/products/engineering_analytics/backend/logic/ownership.py b/products/engineering_analytics/backend/logic/ownership.pyindex d470300c03b1..8e53f5eb300e 100644--- a/products/engineering_analytics/backend/logic/ownership.py+++ b/products/engineering_analytics/backend/logic/ownership.py@@ -71,6 +71,10 @@ class OwnershipUnavailable(Exception):"""The repository's ownership files could not be read, so no attribution is trustworthy."""+class NoRootOwnersFile(OwnershipUnavailable):+ """The repository answers with no root owners file, which is normal for most repositories."""++class RepoFiles(OwnershipSource, Protocol):"""An ownership source that also answers which paths the repository holds, in batches."""@@ -221,6 +225,10 @@ def resolve_path_owners(repository: str, paths: Sequence[str], files: RepoFilesreader = files if files is not None else GitHubRepoFiles(repository)try:return _own_paths(repository, reader, list(dict.fromkeys(paths)))+ except NoRootOwnersFile:+ # Most repositories declare no owners.yaml, so this is no error for a caller to act on.+ logger.info("repo_path_ownership_no_root_file", repository=repository)+ return PathOwnership(team_by_path=dict.fromkeys(paths, UNOWNED_TEAM), registry={}, resolved=False)except OwnershipUnavailable:logger.exception("repo_path_ownership_unavailable", repository=repository)return PathOwnership(team_by_path=dict.fromkeys(paths, UNOWNED_TEAM), registry={}, resolved=False)@@ -229,7 +237,7 @@ def resolve_path_owners(repository: str, paths: Sequence[str], files: RepoFilesdef _own_paths(repository: str, files: RepoFiles, paths: list[str]) -> PathOwnership:root = files.read(_ROOT_OWNERS_FILE)if root is None:- raise OwnershipUnavailable(f"{repository} has no root {_ROOT_OWNERS_FILE}")+ raise NoRootOwnersFile(f"{repository} has no root {_ROOT_OWNERS_FILE}")resolver = OwnersResolver(source=files)files.read_all(resolver.ownership_file_paths(paths))owners = resolver.map(paths)diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex 9f3829897143..fdef471f502a 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -1279,18 +1279,23 @@ Once the pull request exists, `link_report_tracker_issues` (scheduled from the tAn 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.-**One assignee per pull request** (`backend/reviewer_pr_assignment.py`).+**One DRI per pull request** (`backend/reviewer_pr_assignment.py`).Every self-driving pull request opens with no assignee, so it never reaches a GitHub "Assigned to me" view. `schedule_reviewer_pr_assignment` runs when a pull request first reaches a report and applies two rules on a worker:- A suggested reviewer who turned on `SignalUserAutonomyConfig.github_assign_on_pull_request` is always added.-- A pull request that still has no assignee gets exactly one directly responsible individual (DRI). The claimant of the report comes first (for a task claim, the user who started the task). The next candidates come from one of two sources:+- A pull request that nobody assigned by hand gets exactly one directly responsible individual (DRI), unless an opted-in reviewer already owns it. An opted-in reviewer owns it only as the claimant or as a member of the owning team, because a reviewer who opted in is often suggested for other teams' code too. The claimant of the report comes first (for a task claim, the user who started the task). The next candidates come from one of two sources:- When the repository declares its ownership in `owners.yaml` files, the candidates are the members of the GitHub team that owns most of the changed files, in random order (`backend/pr_owning_team.py`). The engineering analytics facade (`resolve_path_owners`) resolves the team. GitHub teams are the canonical team identity, so the team members come from GitHub's team members API. That call needs the organization members read permission on the GitHub app.- Otherwise, or when that team has no candidate, the candidates are the suggested reviewers in rank order.A candidate must be an organization member with a connected GitHub account. Each candidate is checked with GitHub's read-only assignee check first, because the add-assignees call drops a login without push access instead of failing. A candidate GitHub cannot assign moves the walk to the next one, for up to four checks, and a failed check stops it.-The DRI rule is involuntary on purpose. A pull request that several people could pick up diffuses responsibility, and a wrong owner costs one reassignment. It rolls out per organization behind the `signals-pr-dri-assignee` flag. Assignment is additive: nobody is unassigned, and a pull request somebody already assigned gets no DRI.+The DRI rule is involuntary on purpose. A pull request that several people could pick up diffuses responsibility, and a wrong owner costs one reassignment. It rolls out per organization behind the `signals-pr-dri-assignee` flag. Assignment is additive: nobody is unassigned, and a pull request somebody already assigned gets no DRI. A pull request that somebody ever unassigned by hand gets no DRI either, because a later report event must not undo that decision. When the result of the opted-in assignment call is unknown (a request that failed in transit), no DRI is added on top of it.++> [!WARNING]+> Keep the `signals-pr-dri-assignee` flag on the PostHog organization only until a team-level off switch exists in the inbox settings. Assigning people on a customer's GitHub is that team's decision, and today a team cannot turn the rule off: removing `owners.yaml` only changes who gets picked.++The ownership lookup reads `owners.yaml` only, and only for a public repository, because the engineering analytics lookup reads files anonymously. A repository with only CODEOWNERS, or a private repository, falls back to the suggested reviewers. The planned `owners_yaml` resolver adapter covers both: CODEOWNERS as a second format behind the same resolver interface, and files read through the GitHub app.**Fleet steering in the task description** (`load_report_steering` in `backend/report_steering.py`).diff --git a/products/signals/backend/pr_owning_team.py b/products/signals/backend/pr_owning_team.pyindex 949caa5cca43..0f386c7cb17b 100644--- a/products/signals/backend/pr_owning_team.py+++ b/products/signals/backend/pr_owning_team.py@@ -1,8 +1,8 @@-"""DRI candidates from the GitHub team that owns the files a pull request changes.+"""The GitHub team that owns the files a pull request changes, and its members as DRI candidates.A repository that declares its ownership in `owners.yaml` files names a GitHub team for each path.That team answers for the code today, which commit history does not tell. A repository without-those files gets no candidates here, and the caller uses the suggested reviewers instead.+those files gets no team here, and the caller uses the suggested reviewers instead."""from __future__ import annotations@@ -13,6 +13,7 @@ from collections import Counterimport structlog+from posthog.dataclasses import frozenfrom posthog.models.github_integration_base import PullRequestReffrom posthog.models.integration import GitHubIntegration@@ -27,8 +28,15 @@ logger = structlog.get_logger(__name__)_TEAM_SLUG_RE = re.compile(r"^[A-Za-z0-9._-]+$")-class OwningTeamCandidates:- """The members of the team that owns most of a pull request's files, as DRI candidates."""+@frozen+class OwningTeam:+ slug: str+ # Organization members of the team with a connected GitHub account, in random order.+ logins: tuple[str, ...]+++class OwningTeamResolver:+ """Finds the team that owns most of a pull request's files, and its members."""def __init__(self, github: GitHubIntegration, *, team_id: int, report_id: str, parsed: PullRequestRef) -> None:self.github = github@@ -38,7 +46,7 @@ class OwningTeamCandidates:team_id=team_id, report_id=report_id, repository=parsed.repository, pr_number=parsed.number)- def _owning_team(self) -> str | None:+ def _team_slug(self) -> str | None:files = self.github.list_pull_request_files(self.parsed.repository, self.parsed.number)if not files.get("success"):self.log.warning("signals.pr_owning_team.files_fetch_failed", error=files.get("error"))@@ -52,33 +60,30 @@ class OwningTeamCandidates:counts = Counter(team for team in ownership.team_by_path.values() if team != UNOWNED_TEAM)if not counts:return None- team_slug = counts.most_common(1)[0][0]- if not _TEAM_SLUG_RE.match(team_slug):+ slug = counts.most_common(1)[0][0]+ if not _TEAM_SLUG_RE.match(slug):self.log.warning("signals.pr_owning_team.invalid_team_slug")return None- return team_slug-- def logins(self) -> list[str]:- """Team members who are organization members with a connected GitHub account, in random order.+ return slug- Empty when the repository declares no ownership, no team owns the files, or GitHub does not- list the team. A missing organization members permission on the GitHub app is that last case.+ def resolve(self) -> OwningTeam | None:+ """The owning team, or None when the repository declares no ownership, no team owns the files,+ or GitHub does not list the team. A missing organization members permission on the GitHub app+ is that last case."""- team_slug = self._owning_team()- if team_slug is None:- return []+ slug = self._team_slug()+ if slug is None:+ return None- members = self.github.list_team_members(self.parsed.owner, team_slug)+ members = self.github.list_team_members(self.parsed.owner, slug)if not members.get("success"):self.log.warning(- "signals.pr_owning_team.members_fetch_failed",- team_slug=team_slug,- status_code=members.get("status_code"),+ "signals.pr_owning_team.members_fetch_failed", team_slug=slug, status_code=members.get("status_code"))- return []+ return Nonelogins = list(resolve_org_github_login_to_users(self.team_id, members["logins"]))# TODO: prefer the member with the fewest open self-driving pull requests, to spread the load.random.shuffle(logins)- self.log.info("signals.pr_owning_team.resolved", team_slug=team_slug, candidates=len(logins))- return logins+ self.log.info("signals.pr_owning_team.resolved", team_slug=slug, candidates=len(logins))+ return OwningTeam(slug=slug, logins=tuple(logins))diff --git a/products/signals/backend/reviewer_pr_assignment.py b/products/signals/backend/reviewer_pr_assignment.pyindex 85cae5d802da..cc17b86152b9 100644--- a/products/signals/backend/reviewer_pr_assignment.py+++ b/products/signals/backend/reviewer_pr_assignment.py@@ -37,7 +37,7 @@ from products.signals.backend.models import (SignalReportAssignment,SignalUserAutonomyConfig,)-from products.signals.backend.pr_owning_team import OwningTeamCandidates+from products.signals.backend.pr_owning_team import OwningTeam, OwningTeamResolverfrom products.signals.backend.report_claims import get_active_claim, responsible_userfrom products.signals.backend.report_generation.resolve_reviewers import (_normalized_reviewer_user_uuid,@@ -245,42 +245,28 @@ def _assignable_pull_request(def _add_assignees(github: GitHubIntegration, *, team_id: int, report_id: str, parsed: PullRequestRef, logins: list[str]-) -> list[str]:- """Add the logins to the pull request. Returns the logins GitHub accepted, or none on failure."""+) -> list[str] | None:+ """Add the logins to the pull request.++ Returns the pull request's assignees as GitHub reports them after the call, an empty list when+ GitHub refused the call, and None when the outcome is unknown. A request that failed in transit+ may still have reached GitHub, so the caller must not assign anybody else on top of it.+ """+ log = logger.bind(team_id=team_id, report_id=report_id, repository=parsed.repository, pr_number=parsed.number)try:result = github.add_pull_request_assignees(parsed.repository, parsed.number, logins)except Exception:- logger.exception(- "signals.reviewer_pr_assignment.assign_failed",- team_id=team_id,- report_id=report_id,- repository=parsed.repository,- pr_number=parsed.number,- )- return []+ log.exception("signals.reviewer_pr_assignment.assign_failed")+ return Noneif not result.get("success"):- logger.warning(- "signals.reviewer_pr_assignment.assign_failed",- team_id=team_id,- report_id=report_id,- repository=parsed.repository,- pr_number=parsed.number,- error=result.get("error"),- )- return []+ log.warning("signals.reviewer_pr_assignment.assign_failed", error=result.get("error"))+ # The client reports a status code only for a response GitHub sent.+ return [] if result.get("status_code") is not None else Noneassigned = list(result.get("assignees") or [])# Counts only: GitHub logins are member PII and must not reach logs. A `requested` above# `assigned` means GitHub dropped a login, usually one without push access to the repository.- logger.info(- "signals.reviewer_pr_assignment.assigned",- team_id=team_id,- report_id=report_id,- repository=parsed.repository,- pr_number=parsed.number,- requested=len(logins),- assigned=len(assigned),- )+ log.info("signals.reviewer_pr_assignment.assigned", requested=len(logins), assigned=len(assigned))return assigned@@ -309,11 +295,11 @@ def _first_assignable_login(return None-def _owning_team_logins(+def _owning_team(github: GitHubIntegration, *, team_id: int, report_id: str, parsed: PullRequestRef-) -> list[str]:+) -> OwningTeam | None:try:- return OwningTeamCandidates(github, team_id=team_id, report_id=report_id, parsed=parsed).logins()+ return OwningTeamResolver(github, team_id=team_id, report_id=report_id, parsed=parsed).resolve()except Exception:logger.exception("signals.reviewer_pr_assignment.owning_team_failed",@@ -322,32 +308,48 @@ def _owning_team_logins(repository=parsed.repository,pr_number=parsed.number,)- return []+ return None-def dri_candidate_logins(- github: GitHubIntegration, *, team_id: int, report_id: str, parsed: PullRequestRef-) -> list[str]:- """GitHub logins that can own the report's pull request, the most responsible first.+def _was_unassigned_by_hand(github: GitHubIntegration, *, team_id: int, report_id: str, parsed: PullRequestRef) -> bool:+ """Whether somebody removed an assignee from the pull request. A failed read counts as yes.- The claimant comes first, because to claim a report is to take the work on. Next come the- members of the GitHub team that owns the changed files, when the repository declares its- ownership in `owners.yaml`. The suggested reviewers take their place when there is no such team.+ A person who unassigned the DRI made a decision, and a later report event must not undo it."""- claimant = claimant_login(team_id=team_id, report_id=report_id)- others = _owning_team_logins(github, team_id=team_id, report_id=report_id, parsed=parsed) or (- ranked_reviewer_logins(team_id=team_id, report_id=report_id)- )+ try:+ result = github.was_ever_unassigned(parsed.repository, parsed.number)+ except Exception:+ logger.exception("signals.reviewer_pr_assignment.events_fetch_failed", team_id=team_id, report_id=report_id)+ return True+ if not result.get("success"):+ logger.warning(+ "signals.reviewer_pr_assignment.events_fetch_failed",+ team_id=team_id,+ report_id=report_id,+ error=result.get("error"),+ )+ return True+ return bool(result.get("unassigned"))+++def dri_candidate_logins(*, claimant: str | None, team: OwningTeam | None, reviewers: list[str]) -> list[str]:+ """GitHub logins that can own the pull request, the most responsible first.++ The claimant comes first, because to claim a report is to take the work on. The members of the+ team that owns the changed files come next. The suggested reviewers take their place when no+ ownership source names a team.+ """+ others = team.logins if team is not None and team.logins else reviewersreturn list(dict.fromkeys(login for login in (claimant, *others) if login))def assign_reviewers_to_pull_request(*, team_id: int, report_id: str, pr_url: str) -> list[str]:- """Put the report's opted-in reviewers, or else one DRI, on its pull request.+ """Put the report's opted-in reviewers, and one DRI when they do not own the code, on its pull request.Returns the pull request's assignees after the last call GitHub accepted. Never unassigns:GitHub's add-assignees endpoint is additive, so a person somebody assigned by hand stays on the- pull request, and a pull request that already has an assignee gets no DRI. Returns an empty- list when there is nothing to do or the call failed, and raises nothing.+ pull request, and a pull request that somebody assigned or unassigned by hand gets no DRI.+ Returns an empty list when there is nothing to do or the call failed, and raises nothing."""if not SignalReport.objects.filter(id=report_id, team_id=team_id).exists():return []@@ -372,13 +374,39 @@ def assign_reviewers_to_pull_request(*, team_id: int, report_id: str, pr_url: stassigned = (_add_assignees(github, team_id=team_id, report_id=report_id, parsed=parsed, logins=logins) if logins else [])- if not dri_enabled or assigned or pr.get("assignees"):+ if assigned is None:+ return []+ # An assignee who is not an opted-in reviewer came from a person or from an earlier DRI pick, so+ # the pull request already has its owner. GitHub returns the full assignee list after the call,+ # which also shows a person who assigned somebody while the call ran.+ opted_in = {login.lower() for login in logins}+ owned_elsewhere = any(login.lower() not in opted_in for login in (*(pr.get("assignees") or []), *assigned))+ if not dri_enabled or owned_elsewhere:+ return assigned++ claimant = claimant_login(team_id=team_id, report_id=report_id)+ team = _owning_team(github, team_id=team_id, report_id=report_id, parsed=parsed)+ # An opted-in reviewer owns the pull request only as its claimant or as a member of the owning+ # team. A reviewer who opted in is often suggested for other teams' code too.+ owners = {login.lower() for login in (claimant, *(team.logins if team else ())) if login}+ assigned_lower = {login.lower() for login in assigned}+ if assigned and (not owners or assigned_lower & owners):+ return assigned+ if _was_unassigned_by_hand(github, team_id=team_id, report_id=report_id, parsed=parsed):return assigned# One owner rather than every candidate, because each person on a shared assignment reads the# pull request as somebody else's job.- candidates = dri_candidate_logins(github, team_id=team_id, report_id=report_id, parsed=parsed)- dri = _first_assignable_login(github, team_id=team_id, report_id=report_id, parsed=parsed, candidates=candidates)+ candidates = dri_candidate_logins(+ claimant=claimant, team=team, reviewers=ranked_reviewer_logins(team_id=team_id, report_id=report_id)+ )+ dri = _first_assignable_login(+ github,+ team_id=team_id,+ report_id=report_id,+ parsed=parsed,+ candidates=[login for login in candidates if login not in assigned_lower],+ )if dri is None:- return []- return _add_assignees(github, team_id=team_id, report_id=report_id, parsed=parsed, logins=[dri])+ return assigned+ return _add_assignees(github, team_id=team_id, report_id=report_id, parsed=parsed, logins=[dri]) or assigneddiff --git a/products/signals/backend/test/test_reviewer_pr_assignment.py b/products/signals/backend/test/test_reviewer_pr_assignment.pyindex 836aff713f38..4ed95ebc6d31 100644--- a/products/signals/backend/test/test_reviewer_pr_assignment.py+++ b/products/signals/backend/test/test_reviewer_pr_assignment.py@@ -33,11 +33,16 @@ from products.signals.backend.task_run_artefacts import record_implementation_tafrom products.tasks.backend.models import Task, TaskRunPR_URL = "https://github.com/PostHog/posthog/pull/123"+_NOT_UNASSIGNED = {"success": True, "unassigned": False}@pytest.fixture(autouse=True)def dri_flag():- with patch("products.signals.backend.reviewer_pr_assignment.feature_enabled_or_false", return_value=False) as flag:+ # The rule is always on in DEBUG, so DEBUG is pinned off for the flag to decide.+ with (+ patch("products.signals.backend.reviewer_pr_assignment.settings.DEBUG", False),+ patch("products.signals.backend.reviewer_pr_assignment.feature_enabled_or_false", return_value=False) as flag,+ ):yield flag@@ -438,8 +443,16 @@ class TestDirectlyResponsibleIndividual:"assignable": assignable is None or login in assignable,}github.list_pull_request_files.return_value = {"success": True, "paths": ["posthog/api/a.py"]}+ github.was_ever_unassigned.return_value = {"success": True, "unassigned": False}+ github.add_pull_request_assignees.side_effect = lambda _repo, _number, logins: {+ "success": True,+ "assignees": logins,+ }return github+ def _team_x(self, github: MagicMock) -> None:+ github.list_team_members.return_value = {"success": True, "logins": ["bob", "dave", "stranger"]}+@pytest.mark.django_db@pytest.mark.parametrize(("reviewers", "claimant", "expected_owner"),@@ -576,3 +589,53 @@ class TestDirectlyResponsibleIndividual:calls = self._assign(team, report, github)assert calls == [[expected_owner]]++ @pytest.mark.django_db+ @pytest.mark.parametrize(+ ("opted_in", "existing_assignees", "add_result", "events", "expected_calls"),+ [+ (("alice",), [], None, _NOT_UNASSIGNED, [["alice"], ["dave"]]),+ (("alice",), ["alice"], None, _NOT_UNASSIGNED, [["alice"], ["dave"]]),+ (("alice",), [], {"success": True, "assignees": ["alice", "someone"]}, _NOT_UNASSIGNED, [["alice"]]),+ (("bob",), [], None, _NOT_UNASSIGNED, [["bob"]]),+ (("alice",), [], {"success": False, "error": "Network error"}, _NOT_UNASSIGNED, [["alice"]]),+ ((), [], None, {"success": True, "unassigned": True}, []),+ ((), [], None, {"success": False, "error": "Failed to list issue events"}, []),+ ],+ ids=[+ "opted_in_reviewer_outside_the_owning_team_gets_a_dri_beside_them",+ "an_earlier_opted_in_assignment_is_not_a_hand_assignment",+ "a_hand_assignment_during_the_call_counts",+ "opted_in_reviewer_in_the_owning_team_is_the_owner",+ "unknown_assignment_outcome_adds_nobody_else",+ "a_hand_unassigned_pull_request_stays_unassigned",+ "unreadable_events_count_as_unassigned",+ ],+ )+ def test_the_dri_respects_what_already_happened(+ self,+ org_and_team,+ ownership,+ opted_in: tuple[str, ...],+ existing_assignees: list[str],+ add_result: dict | None,+ events: dict,+ expected_calls: list[list[str]],+ ):+ org, team = org_and_team+ report, _ = self._setup(org, team, ["alice", "bob"], opted_in=opted_in)+ ownership.return_value = PathOwnership(team_by_path={"posthog/api/a.py": "team-x"}, registry={}, resolved=True)+ github = self._github(existing_assignees=existing_assignees, assignable=None)+ self._team_x(github)+ github.was_ever_unassigned.return_value = events+ if add_result is not None:+ github.add_pull_request_assignees.side_effect = None+ github.add_pull_request_assignees.return_value = add_result++ with patch(+ "products.signals.backend.pr_owning_team.random.shuffle",+ side_effect=lambda logins: logins.sort(reverse=True),+ ):+ calls = self._assign(team, report, github)++ assert calls == expected_calls