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(signals): assign one owner to every self-driving pr (#100901)

Julian Bez563c2d41ef5f
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index 89d15257882f..6ffcaef63226 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -1164,6 +1164,11 @@ class GitHubIntegrationBase:
"base_sha": base.get("sha"),
"repository": repo_path,
"author": user.get("login"),
+ "assignees": [
+ entry["login"]
+ for entry in (pr.get("assignees") or [])
+ if isinstance(entry, dict) and entry.get("login")
+ ],
"created_at": pr.get("created_at"),
"updated_at": pr.get("updated_at"),
"merged_at": pr.get("merged_at"),
@@ -1323,6 +1328,93 @@ class GitHubIntegrationBase:
]
return {"success": True, "assignees": assigned}
+ def is_assignable(self, repository: str, login: str) -> dict[str, Any]:
+ """Whether ``login`` can be assigned to issues and pull requests in ``repository``.
+
+ The add-assignees endpoint drops a login it cannot assign instead of failing, so a caller
+ that must know whether one specific person lands checks here first.
+ """
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+
+ response = self._installation_authenticated_get(
+ f"https://api.github.com/repos/{repo_path}/assignees/{login}",
+ endpoint="/repos/{owner}/{repo}/assignees/{assignee}",
+ )
+ if response is None:
+ return {"success": False, "error": "Network error checking assignee"}
+ if response.status_code == 204:
+ return {"success": True, "assignable": True}
+ if response.status_code == 404:
+ return {"success": True, "assignable": False}
+ return {
+ "success": False,
+ "error": f"Failed to check assignee: {response.text}",
+ "status_code": response.status_code,
+ }
+
+ def list_pull_request_files(self, repository: str, pr_number: int) -> dict[str, Any]:
+ """The paths of the first page of files a pull request changes, at most 100.
+
+ One page only, so a very large pull request costs one read. Callers that need every path
+ must not use this.
+ """
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+
+ response = self._installation_authenticated_get(
+ f"https://api.github.com/repos/{repo_path}/pulls/{pr_number}/files",
+ endpoint="/repos/{owner}/{repo}/pulls/{pull_number}/files",
+ params={"per_page": 100},
+ )
+ if response is None:
+ return {"success": False, "error": "Network error listing pull request files"}
+ if response.status_code != 200:
+ return {
+ "success": False,
+ "error": f"Failed to list pull request files: {response.text}",
+ "status_code": response.status_code,
+ }
+ try:
+ files = response.json()
+ except Exception:
+ return {"success": False, "error": "Failed to parse pull request files JSON"}
+ paths = [
+ entry["filename"]
+ for entry in (files if isinstance(files, list) else [])
+ if isinstance(entry, dict) and isinstance(entry.get("filename"), str)
+ ]
+ return {"success": True, "paths": paths}
+
+ 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.
+
+ Needs the app's organization members read permission. Without it GitHub answers 403, which
+ comes back as a failure.
+ """
+ responses, complete = self._installation_authenticated_get_pages(
+ f"https://api.github.com/orgs/{org}/teams/{team_slug}/members",
+ endpoint="/orgs/{org}/teams/{team_slug}/members",
+ params={"per_page": 100},
+ )
+ if not complete:
+ last = responses[-1] if responses else None
+ return {
+ "success": False,
+ "error": f"Failed to list team members: {last.text if last is not None else 'network error'}",
+ "status_code": last.status_code if last is not None else None,
+ }
+ logins: list[str] = []
+ for response in responses:
+ try:
+ members = response.json()
+ except Exception:
+ return {"success": False, "error": "Failed to parse team members JSON"}
+ logins.extend(
+ entry["login"]
+ for entry in (members if isinstance(members, list) else [])
+ if isinstance(entry, dict) and isinstance(entry.get("login"), str)
+ )
+ return {"success": True, "logins": logins}
+
def add_pull_request_assignees_from_url(self, pr_url: str, assignees: Iterable[str]) -> dict[str, Any]:
"""Add assignees to a pull request by its HTML URL."""
parsed = self.parse_pull_request_url(pr_url)
diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.py
index 30cea08d7a54..8372e85fdef7 100644
--- a/posthog/models/test/integration/test_github.py
+++ b/posthog/models/test/integration/test_github.py
@@ -940,6 +940,52 @@ class TestGitHubIntegrationModel(BaseTest):
assert result["success"] is False
assert result["status_code"] == 422
+ @parameterized.expand(
+ [
+ ("assignable", 204, {"success": True, "assignable": True}),
+ ("not_assignable", 404, {"success": True, "assignable": False}),
+ ]
+ )
+ def test_is_assignable_reads_the_assignees_endpoint(self, _name: str, status_code: int, expected: dict):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ with patch.object(
+ github, "_installation_authenticated_get", return_value=MagicMock(status_code=status_code)
+ ) as mock_get:
+ result = github.is_assignable("PostHog/posthog", "alice")
+ assert result == expected
+ assert mock_get.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/assignees/alice"
+
+ def test_is_assignable_reports_a_github_error(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ mock_response = MagicMock(status_code=403, text="Resource not accessible by integration")
+ with patch.object(github, "_installation_authenticated_get", return_value=mock_response):
+ result = github.is_assignable("PostHog/posthog", "alice")
+ assert result["success"] is False
+ assert result["status_code"] == 403
+
+ @parameterized.expand(
+ [
+ ("every_page_read", True, {"success": True, "logins": ["alice", "bob"]}),
+ # A partial member list would make a random pick skip part of the team.
+ ("a_page_failed", False, {"success": False}),
+ ]
+ )
+ def test_list_team_members_needs_every_page(self, _name: str, complete: bool, expected: dict):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration)
+ first = MagicMock(status_code=200)
+ first.json.return_value = [{"login": "alice"}]
+ second = MagicMock(status_code=200 if complete else 403, text="Resource not accessible by integration")
+ second.json.return_value = [{"login": "bob"}]
+ with patch.object(
+ github, "_installation_authenticated_get_pages", return_value=([first, second], complete)
+ ) as mock_pages:
+ result = github.list_team_members("PostHog", "team-devex")
+ assert {key: result[key] for key in expected} == expected
+ assert mock_pages.call_args.args[0] == "https://api.github.com/orgs/PostHog/teams/team-devex/members"
+
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/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index dfc88c2a5991..3e4a47e3e206 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -1265,6 +1265,19 @@ Once the pull request exists, `link_report_tracker_issues` (scheduled from the t
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.
+**One assignee 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:
+ - 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.
+
**Fleet steering in the task description** (`load_report_steering` in `backend/report_steering.py`).
Scouts read the team's steering notes at the start of every run, and the implementation run that acts on their report did not, so guidance like "this area is frozen" reached the agent that filed the report but never the agent that wrote the code. The description now carries it: the `HUMAN`-origin notes addressed to the whole fleet plus those addressed to the report's authoring scout (`scout_authorship.resolve_report_scout_skill`, the same emit-time resolution the dismissal path uses), newest first, capped at 10 notes and 1,000 characters each.
diff --git a/products/signals/backend/pr_owning_team.py b/products/signals/backend/pr_owning_team.py
new file mode 100644
index 000000000000..949caa5cca43
--- /dev/null
+++ b/products/signals/backend/pr_owning_team.py
@@ -0,0 +1,84 @@
+"""DRI candidates from the GitHub team that owns the files a pull request changes.
+
+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.
+"""
+
+from __future__ import annotations
+
+import re
+import random
+from collections import Counter
+
+import structlog
+
+from posthog.models.github_integration_base import PullRequestRef
+from posthog.models.integration import GitHubIntegration
+
+from products.engineering_analytics.backend.facade.api import resolve_path_owners
+from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM
+from products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users
+
+logger = structlog.get_logger(__name__)
+
+# The slug comes from the repository's own files and goes into a GitHub API path, so anything that
+# is not a plain GitHub team slug is refused.
+_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."""
+
+ def __init__(self, github: GitHubIntegration, *, team_id: int, report_id: str, parsed: PullRequestRef) -> None:
+ self.github = github
+ self.team_id = team_id
+ self.parsed = parsed
+ self.log = logger.bind(
+ team_id=team_id, report_id=report_id, repository=parsed.repository, pr_number=parsed.number
+ )
+
+ def _owning_team(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"))
+ return None
+ if not files["paths"]:
+ return None
+
+ ownership = resolve_path_owners(self.parsed.repository, files["paths"])
+ if not ownership.resolved:
+ return None
+ 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):
+ 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.
+
+ 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.
+ """
+ team_slug = self._owning_team()
+ if team_slug is None:
+ return []
+
+ members = self.github.list_team_members(self.parsed.owner, team_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"),
+ )
+ return []
+
+ logins = 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
diff --git a/products/signals/backend/report_claims.py b/products/signals/backend/report_claims.py
index 0b1a0bbdf7c2..eca3d63e27ba 100644
--- a/products/signals/backend/report_claims.py
+++ b/products/signals/backend/report_claims.py
@@ -1,18 +1,16 @@
from __future__ import annotations
from datetime import datetime
-from typing import TYPE_CHECKING
from uuid import UUID
from django.db.models import Exists, OuterRef, Q, QuerySet, Subquery
from posthog.dataclasses import frozen
+from posthog.models.user import User
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.models import SignalReportArtefact, SignalReportAssignment
-
-if TYPE_CHECKING:
- from posthog.models.user import User
+from products.tasks.backend.facade import api as tasks_facade
@frozen
@@ -83,6 +81,22 @@ def get_active_claim(*, team_id: int, report_id: str | UUID) -> ReportClaim | No
return get_active_claims(team_id=team_id, report_ids=[str(report_id)]).get(str(report_id))
+def responsible_user(claim: ReportClaim) -> User | None:
+ """The PostHog user who answers for a claim, or None when no person stands behind it.
+
+ A user claim and an external agent claim carry the user. An internal task claim carries only
+ the task, and the task runs as the user who started it, so that user answers for the claim.
+ """
+ if claim.actor_user is not None:
+ return claim.actor_user
+ if claim.actor_task_id is None:
+ return None
+ tasks = tasks_facade.get_tasks_by_ids([claim.actor_task_id], [claim.team_id])
+ if not tasks or tasks[0].created_by_id is None:
+ return None
+ return User.objects.filter(id=tasks[0].created_by_id).first()
+
+
def reports_with_active_claim(*, team_id: int, actor: ArtefactAttribution | None = None) -> Q:
claims = active_claims(team_id=team_id)
legacy = legacy_claims(team_id=team_id)
diff --git a/products/signals/backend/reviewer_pr_assignment.py b/products/signals/backend/reviewer_pr_assignment.py
index 0a587feacf6e..85cae5d802da 100644
--- a/products/signals/backend/reviewer_pr_assignment.py
+++ b/products/signals/backend/reviewer_pr_assignment.py
@@ -1,21 +1,35 @@
-"""Add a report's opted-in suggested reviewers as GitHub assignees on its implementation PR.
+"""Put a person on a report's implementation PR as its GitHub assignee.
A reviewer whose workflow is GitHub's "Assigned to me" never sees an inbox PR otherwise, because
-every self-driving pull request opens with no assignee. Opt-in only, through
-`SignalUserAutonomyConfig.github_assign_on_pull_request`, and best effort throughout: a GitHub
-failure must never break the claim, sync, or reviewer edit that triggered it.
+every self-driving pull request opens with no assignee. Two rules add assignees:
+
+- A suggested reviewer who opted in through `SignalUserAutonomyConfig.github_assign_on_pull_request`
+ is always added.
+- A pull request that still has no assignee after that gets exactly one directly responsible
+ individual (DRI): the person who claimed the report, else a random member of the GitHub team that
+ owns the changed files (see `pr_owning_team.py`), else the most relevant suggested reviewer.
+ A pull request that everybody could pick up is a pull request nobody picks up, and a wrong
+ owner costs one reassignment. The `signals-pr-dri-assignee` flag rolls this rule out per
+ organization.
+
+Best effort throughout: a GitHub failure must never break the claim, sync, or reviewer edit that
+triggered it.
"""
from __future__ import annotations
import json
+from typing import Any
+from django.conf import settings
from django.db import transaction
import structlog
+from posthog.models import Team
from posthog.models.github_integration_base import PullRequestRef
from posthog.models.integration import GitHubIntegration
+from posthog.ph_client import feature_enabled_or_false
from products.signals.backend.models import (
SignalReport,
@@ -23,13 +37,23 @@ from products.signals.backend.models import (
SignalReportAssignment,
SignalUserAutonomyConfig,
)
+from products.signals.backend.pr_owning_team import OwningTeamCandidates
+from products.signals.backend.report_claims import get_active_claim, responsible_user
from products.signals.backend.report_generation.resolve_reviewers import (
+ _normalized_reviewer_user_uuid,
+ get_org_member_github_logins_by_user_uuid,
normalized_github_logins_from_reviewer_payloads,
resolve_org_github_login_to_users,
)
logger = structlog.get_logger(__name__)
+PR_DRI_FEATURE_FLAG = "signals-pr-dri-assignee"
+
+# Each DRI candidate costs one GitHub read. This covers the claimant and three other candidates,
+# and stops a large team or a long scout reviewer list from turning one pull request into ten reads.
+MAX_DRI_CHECKS = 4
+
# Assign only while the pull request can still be reviewed. UNKNOWN is included because a PR whose
# state could not be read is far more often open than closed, and the task re-reads the real state
# from GitHub before it assigns.
@@ -74,11 +98,11 @@ def schedule_reviewer_pr_assignment(
)
-def opted_in_reviewer_logins(*, team_id: int, report_id: str) -> list[str]:
- """GitHub logins of the report's current suggested reviewers who opted in to PR assignment.
+def _latest_reviewer_rows(report_id: str) -> list[dict[str, Any]]:
+ """The rows of the report's latest `suggested_reviewers` artefact, in their stored order.
- Reads only the latest `suggested_reviewers` row, which is the live reviewer set, so a reviewer
- removed from the list is not assigned on the next pull request event.
+ Only the latest row is the live reviewer set, so a reviewer removed from the list is not
+ assigned on the next pull request event. The stored order is the relevance rank.
"""
latest = (
SignalReportArtefact.objects.filter(
@@ -96,8 +120,12 @@ def opted_in_reviewer_logins(*, team_id: int, report_id: str) -> list[str]:
return []
if not isinstance(payloads, list):
return []
+ return [row for row in payloads if isinstance(row, dict)]
+
- logins = normalized_github_logins_from_reviewer_payloads(payloads)
+def opted_in_reviewer_logins(*, team_id: int, report_id: str) -> list[str]:
+ """GitHub logins of the report's current suggested reviewers who opted in to PR assignment."""
+ logins = normalized_github_logins_from_reviewer_payloads(_latest_reviewer_rows(report_id))
if not logins:
return []
login_to_user = resolve_org_github_login_to_users(team_id, logins)
@@ -113,6 +141,59 @@ def opted_in_reviewer_logins(*, team_id: int, report_id: str) -> list[str]:
return sorted(login for login, user in login_to_user.items() if user.id in opted_in_user_ids)
+def _pr_dri_enabled(team_id: int) -> bool:
+ """Whether the organization has the DRI rule. On in DEBUG, and closed when the flag service fails."""
+ if settings.DEBUG:
+ return True
+ try:
+ organization_id = str(Team.objects.values_list("organization_id", flat=True).get(id=team_id))
+ return feature_enabled_or_false(
+ PR_DRI_FEATURE_FLAG,
+ organization_id,
+ groups={"organization": organization_id},
+ group_properties={"organization": {"id": organization_id}},
+ send_feature_flag_events=False,
+ )
+ except Exception:
+ logger.warning("signals.reviewer_pr_assignment.dri_flag_check_failed", team_id=team_id, exc_info=True)
+ return False
+
+
+def claimant_login(*, team_id: int, report_id: str) -> str | None:
+ """The GitHub login of the person who claimed the report, when that person can be assigned."""
+ claim = get_active_claim(team_id=team_id, report_id=report_id)
+ claimant = responsible_user(claim) if claim is not None else None
+ if claimant is None:
+ return None
+ return get_org_member_github_logins_by_user_uuid(team_id, [str(claimant.uuid)]).get(str(claimant.uuid))
+
+
+def ranked_reviewer_logins(*, team_id: int, report_id: str) -> list[str]:
+ """GitHub logins of the report's suggested reviewers, in their relevance order.
+
+ A reviewer must be a member of the organization with a connected GitHub account, so a login
+ from commit history that belongs to nobody in the organization is never assigned.
+ """
+ rows_with_uuid = [
+ (row, _normalized_reviewer_user_uuid(row.get("user_uuid"))) for row in _latest_reviewer_rows(report_id)
+ ]
+ login_by_uuid = get_org_member_github_logins_by_user_uuid(team_id, [uuid for _, uuid in rows_with_uuid if uuid])
+ # A row stored by uuid names the reviewer by that uuid, so its login is only read for a row without one.
+ member_logins = resolve_org_github_login_to_users(
+ team_id,
+ normalized_github_logins_from_reviewer_payloads(row for row, uuid in rows_with_uuid if uuid is None),
+ )
+
+ candidates: list[str | None] = []
+ for row, uuid in rows_with_uuid:
+ if uuid is not None:
+ candidates.append(login_by_uuid.get(uuid))
+ else:
+ login = str(row.get("github_login") or "").strip().lower()
+ candidates.append(login if login in member_logins else None)
+ return list(dict.fromkeys(login for login in candidates if login))
+
+
def _github_for_repository(*, team_id: int, report_id: str, repository: str) -> GitHubIntegration | None:
"""The team's GitHub integration for a repository, or None when there is none to call."""
try:
@@ -127,10 +208,10 @@ def _github_for_repository(*, team_id: int, report_id: str, repository: str) ->
return None
-def _pull_request_is_assignable(
+def _assignable_pull_request(
github: GitHubIntegration, *, team_id: int, report_id: str, parsed: PullRequestRef
-) -> bool:
- """Whether the pull request still accepts assignees.
+) -> dict[str, Any] | None:
+ """The pull request as GitHub reports it, or None when it no longer accepts assignees.
A pull request closed or merged since the assignment was queued must not be reopened in
somebody's assigned list, so this reads the state from GitHub rather than trusting the queued
@@ -146,7 +227,7 @@ def _pull_request_is_assignable(
repository=parsed.repository,
pr_number=parsed.number,
)
- return False
+ return None
if not pr.get("success"):
logger.warning(
"signals.reviewer_pr_assignment.pr_fetch_failed",
@@ -156,8 +237,10 @@ def _pull_request_is_assignable(
pr_number=parsed.number,
error=pr.get("error"),
)
- return False
- return not pr.get("merged") and pr.get("state") != "closed"
+ return None
+ if pr.get("merged") or pr.get("state") == "closed":
+ return None
+ return pr
def _add_assignees(
@@ -201,18 +284,77 @@ def _add_assignees(
return assigned
+def _first_assignable_login(
+ github: GitHubIntegration, *, team_id: int, report_id: str, parsed: PullRequestRef, candidates: list[str]
+) -> str | None:
+ """The first candidate GitHub can assign in the repository, or None.
+
+ The add-assignees call drops a login without push access instead of failing, so each candidate
+ is checked with a read before the one write. A failed check stops the walk, because a GitHub
+ error says nothing about whether the next candidate is a better owner.
+ """
+ log = logger.bind(team_id=team_id, report_id=report_id, repository=parsed.repository, pr_number=parsed.number)
+ for login in candidates[:MAX_DRI_CHECKS]:
+ try:
+ result = github.is_assignable(parsed.repository, login)
+ except Exception:
+ log.exception("signals.reviewer_pr_assignment.assignable_check_failed")
+ return None
+ if not result.get("success"):
+ log.warning("signals.reviewer_pr_assignment.assignable_check_failed", error=result.get("error"))
+ return None
+ if result.get("assignable"):
+ return login
+ log.info("signals.reviewer_pr_assignment.no_assignable_dri", candidates=len(candidates))
+ return None
+
+
+def _owning_team_logins(
+ github: GitHubIntegration, *, team_id: int, report_id: str, parsed: PullRequestRef
+) -> list[str]:
+ try:
+ return OwningTeamCandidates(github, team_id=team_id, report_id=report_id, parsed=parsed).logins()
+ except Exception:
+ logger.exception(
+ "signals.reviewer_pr_assignment.owning_team_failed",
+ team_id=team_id,
+ report_id=report_id,
+ repository=parsed.repository,
+ pr_number=parsed.number,
+ )
+ return []
+
+
+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.
+
+ 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.
+ """
+ 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)
+ )
+ return 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]:
- """Add the report's opted-in reviewers to its pull request. Returns the logins GitHub accepted.
+ """Put the report's opted-in reviewers, or else one DRI, on its pull request.
- Never unassigns: GitHub's add-assignees endpoint is additive, so a reviewer somebody assigned by
- hand stays on the pull request. Returns an empty list when there is nothing to do or the call
- failed, and raises nothing.
+ 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.
"""
if not SignalReport.objects.filter(id=report_id, team_id=team_id).exists():
return []
logins = opted_in_reviewer_logins(team_id=team_id, report_id=report_id)
- if not logins:
+ dri_enabled = _pr_dri_enabled(team_id)
+ if not logins and not dri_enabled:
return []
parsed = GitHubIntegration.parse_pull_request_url(pr_url)
@@ -223,7 +365,20 @@ def assign_reviewers_to_pull_request(*, team_id: int, report_id: str, pr_url: st
if github is None:
return []
- if not _pull_request_is_assignable(github, team_id=team_id, report_id=report_id, parsed=parsed):
+ pr = _assignable_pull_request(github, team_id=team_id, report_id=report_id, parsed=parsed)
+ if pr is None:
return []
- return _add_assignees(github, team_id=team_id, report_id=report_id, parsed=parsed, logins=logins)
+ assigned = (
+ _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"):
+ 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)
+ if dri is None:
+ return []
+ return _add_assignees(github, team_id=team_id, report_id=report_id, parsed=parsed, logins=[dri])
diff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.py
index 753addd0c4ca..8307c18ec838 100644
--- a/products/signals/backend/tasks.py
+++ b/products/signals/backend/tasks.py
@@ -555,7 +555,7 @@ def send_reviewer_added_slack_notifications(
)
@with_team_scope()
def assign_reviewers_on_implementation_pr(team_id: int, report_id: str, pr_url: str) -> None:
- """Add a report's opted-in suggested reviewers as GitHub assignees on its implementation PR.
+ """Put a report's opted-in reviewers, or else one DRI, on its implementation PR as GitHub assignees.
Runs on a worker because the GitHub calls (integration probe, PR read, assign) must not hold up
the claim, sync, or reviewer edit that queued it. Best-effort end to end, so the assigner
diff --git a/products/signals/backend/test/test_reviewer_pr_assignment.py b/products/signals/backend/test/test_reviewer_pr_assignment.py
index f87b6ff09a53..836aff713f38 100644
--- a/products/signals/backend/test/test_reviewer_pr_assignment.py
+++ b/products/signals/backend/test/test_reviewer_pr_assignment.py
@@ -8,6 +8,7 @@ from social_django.models import UserSocialAuth
from posthog.models import Organization, Team, User
from posthog.models.organization import OrganizationMembership
+from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM, PathOwnership
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.models import (
SignalReport,
@@ -17,6 +18,7 @@ from products.signals.backend.models import (
)
from products.signals.backend.report_assignments import (
claim_report,
+ claim_report_for_task,
sync_task_pull_request_to_assignments,
update_assignments_for_pull_request,
)
@@ -33,6 +35,12 @@ from products.tasks.backend.models import Task, TaskRun
PR_URL = "https://github.com/PostHog/posthog/pull/123"
[email protected](autouse=True)
+def dri_flag():
+ with patch("products.signals.backend.reviewer_pr_assignment.feature_enabled_or_false", return_value=False) as flag:
+ yield flag
+
+
@pytest.fixture
def org_and_team():
org = Organization.objects.create(name="pr-assign-org")
@@ -375,3 +383,196 @@ class TestPullRequestLinkingQueuesAssignment:
)
self.mock_delay.assert_called_once_with(team_id=team.id, report_id=str(report.id), pr_url=PR_URL)
+
+
+class TestDirectlyResponsibleIndividual:
+ @pytest.fixture(autouse=True)
+ def _flag_on(self, dri_flag):
+ dri_flag.return_value = True
+
+ @pytest.fixture(autouse=True)
+ def ownership(self):
+ with patch(
+ "products.signals.backend.pr_owning_team.resolve_path_owners",
+ return_value=PathOwnership(team_by_path={}, registry={}, resolved=False),
+ ) as resolve:
+ yield resolve
+
+ def _setup(self, org, team, reviewers: list[str], *, opted_in: tuple[str, ...] = ()) -> tuple[SignalReport, dict]:
+ users = {
+ login: _make_reviewer(org, login, opted_in=login in opted_in) for login in ("alice", "bob", "carol", "dave")
+ }
+ report = _make_report(team)
+ rows = [
+ {"user_uuid": str(users[entry.removeprefix("uuid:")].uuid), "github_login": None}
+ if entry.startswith("uuid:")
+ else {"github_login": entry}
+ for entry in reviewers
+ ]
+ SignalReportArtefact.objects.create(
+ team=team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content=json.dumps(rows),
+ )
+ return report, users
+
+ def _assign(self, team, report, github: MagicMock) -> list[list[str]]:
+ with patch(
+ "products.signals.backend.reviewer_pr_assignment.GitHubIntegration.first_for_team_repository",
+ return_value=github,
+ ):
+ assign_reviewers_to_pull_request(team_id=team.id, report_id=str(report.id), pr_url=PR_URL)
+ return [call.args[2] for call in github.add_pull_request_assignees.call_args_list]
+
+ def _github(self, *, existing_assignees: list[str], assignable: set[str] | None) -> MagicMock:
+ github = _open_pr_github()
+ github.get_pull_request.return_value = {
+ "success": True,
+ "state": "open",
+ "merged": False,
+ "assignees": existing_assignees,
+ }
+ github.is_assignable.side_effect = lambda _repo, login: {
+ "success": True,
+ "assignable": assignable is None or login in assignable,
+ }
+ github.list_pull_request_files.return_value = {"success": True, "paths": ["posthog/api/a.py"]}
+ return github
+
+ @pytest.mark.django_db
+ @pytest.mark.parametrize(
+ ("reviewers", "claimant", "expected_owner"),
+ [
+ (["alice", "bob"], None, "alice"),
+ (["alice"], "user", "carol"),
+ (["alice"], "task", "carol"),
+ (["uuid:bob", "alice"], None, "bob"),
+ (["stranger", "bob"], None, "bob"),
+ ([], None, None),
+ ],
+ ids=[
+ "top_reviewer",
+ "user_claimant_first",
+ "task_claimant_is_its_creator",
+ "reviewer_stored_by_uuid",
+ "non_member_skipped",
+ "nobody_to_assign",
+ ],
+ )
+ def test_the_owner_is_the_most_responsible_member(
+ self, org_and_team, reviewers: list[str], claimant: str | None, expected_owner: str | None
+ ):
+ org, team = org_and_team
+ report, users = self._setup(org, team, reviewers)
+ if claimant == "user":
+ claim_report(
+ report=report,
+ actor=ArtefactAttribution.from_user(users["carol"].id),
+ user=users["carol"],
+ was_impersonated=False,
+ )
+ elif claimant == "task":
+ task = Task.objects.create(
+ team=team, title="Implementation", description="", origin_product="signals", created_by=users["carol"]
+ )
+ claim_report_for_task(team_id=team.id, report_id=str(report.id), task_id=str(task.id))
+
+ calls = self._assign(team, report, self._github(existing_assignees=[], assignable=None))
+
+ assert calls == ([[expected_owner]] if expected_owner else [])
+
+ @pytest.mark.django_db
+ @pytest.mark.parametrize(
+ ("opted_in", "existing_assignees", "assignable", "expected_calls"),
+ [
+ ((), [], {"bob"}, [["bob"]]),
+ ((), [], set(), []),
+ (("bob",), [], None, [["bob"]]),
+ ((), ["someone"], None, []),
+ ],
+ ids=[
+ "unassignable_candidate_moves_on",
+ "nobody_assignable",
+ "opted_in_reviewer_is_enough",
+ "already_assigned",
+ ],
+ )
+ def test_a_pull_request_never_gets_a_second_owner(
+ self,
+ org_and_team,
+ opted_in: tuple[str, ...],
+ existing_assignees: list[str],
+ assignable: set[str] | None,
+ expected_calls: list[list[str]],
+ ):
+ org, team = org_and_team
+ report, _ = self._setup(org, team, ["alice", "bob"], opted_in=opted_in)
+
+ calls = self._assign(team, report, self._github(existing_assignees=existing_assignees, assignable=assignable))
+
+ assert calls == expected_calls
+
+ @pytest.mark.django_db
+ def test_a_failed_assignee_check_stops_the_walk(self, org_and_team):
+ org, team = org_and_team
+ report, _ = self._setup(org, team, ["alice", "bob"])
+ github = self._github(existing_assignees=[], assignable=None)
+ github.is_assignable.side_effect = None
+ github.is_assignable.return_value = {"success": False, "error": "Failed to check assignee"}
+
+ assert self._assign(team, report, github) == []
+ assert github.is_assignable.call_count == 1
+
+ @pytest.mark.django_db
+ @pytest.mark.parametrize(
+ ("team_by_path", "members", "claimant", "expected_owner"),
+ [
+ ({"a.py": "team-x", "b.py": "team-x", "c.py": "team-y"}, {"success": True}, False, "dave"),
+ ({"a.py": "team-x"}, {"success": True}, True, "carol"),
+ (None, {"success": True}, False, "alice"),
+ ({"a.py": UNOWNED_TEAM}, {"success": True}, False, "alice"),
+ ({"a.py": "team-x"}, {"success": False, "status_code": 403}, False, "alice"),
+ ({"a.py": "team-y"}, {"success": True}, False, "alice"),
+ ],
+ ids=[
+ "random_member_of_the_majority_team",
+ "claimant_before_the_team",
+ "no_owners_files_uses_reviewers",
+ "unowned_files_use_reviewers",
+ "unreadable_team_uses_reviewers",
+ "team_without_org_members_uses_reviewers",
+ ],
+ )
+ def test_the_owning_team_supplies_the_owner(
+ self,
+ org_and_team,
+ ownership,
+ team_by_path: dict[str, str] | None,
+ members: dict,
+ claimant: bool,
+ expected_owner: str,
+ ):
+ org, team = org_and_team
+ report, users = self._setup(org, team, ["alice"])
+ if claimant:
+ claim_report(
+ report=report,
+ actor=ArtefactAttribution.from_user(users["carol"].id),
+ user=users["carol"],
+ was_impersonated=False,
+ )
+ if team_by_path is not None:
+ ownership.return_value = PathOwnership(team_by_path=team_by_path, registry={}, resolved=True)
+ github = self._github(existing_assignees=[], assignable=None)
+ github.list_pull_request_files.return_value = {"success": True, "paths": list(team_by_path or ["a.py"])}
+ logins_by_team = {"team-x": ["bob", "dave", "stranger"], "team-y": ["stranger"]}
+ github.list_team_members.side_effect = lambda _org, slug: {**members, "logins": logins_by_team[slug]}
+
+ 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_owner]]
diff --git a/tach.toml b/tach.toml
index 394d773c5fe3..5c5ca5353d85 100644
--- a/tach.toml
+++ b/tach.toml
@@ -820,6 +820,8 @@ depends_on = [
"products.cdp",
"products.conversations",
"products.dashboards",
+ # Facade-only: the DRI pick on a self-driving pull request asks which team owns each of its files.
+ "products.engineering_analytics",
# Facade-only (enforced by data_catalog's [[interfaces]] block): the scout harness gates
# its catalog-first prompt rule on the data catalog flag.
"products.data_catalog",