Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(signals): reassess the automatic pr owner (#122214)

posthog[bot]7448c2f45ad9
diff --git a/docs/internal/signals-pr-lifecycle.md b/docs/internal/signals-pr-lifecycle.md
index 5e40ea45bc1a..d416dd980250 100644
--- a/docs/internal/signals-pr-lifecycle.md
+++ b/docs/internal/signals-pr-lifecycle.md
@@ -317,7 +317,7 @@ flowchart LR
C --> D[(suggested_reviewers)]
D --> E[Inbox report]
D --> F[Check personal settings, accounts, and GitHub access]
- F --> G[First eligible recipient becomes PR owner]
+ F --> G[Assign or replace one PR owner]
E --> H[Human edit and reason]
H --> I[(Existing corrections and notes)]
I --> A
@@ -341,14 +341,17 @@ The report remains the source of the assignment. Logs record unavailable account
The worker rechecks the report state, personal settings, account links, project access, GitHub state, and delivery controls before assigning.
Queued work and retries use the current personal setting.
-Existing GitHub assignees and manual unassignment remain authoritative. Incomplete human-edit history blocks automatic assignment.
+Each successful automatic assignment records its owner and origin. A later reviewer edit, claim, or verified PR refresh can reassess that owner.
+The worker replaces owners only when GitHub's current assignees exactly match its latest record; extra assignees, manual removal, and unknown-origin assignments remain authoritative.
+It adds the replacement before removing the previous automatic owner and stops if GitHub reports a concurrent assignee change.
+If no report recipient qualifies, it clears only its recorded automatic assignment. A failed eligibility lookup leaves the assignment unchanged.
+Incomplete human-edit history blocks automatic assignment.
The legacy DRI path also respects report exclusions and rechecks human choices before assignment.
Claimants and suggested reviewers must be active project members to receive assignments or review requests.
-This first version selects an owner only when the PR is unassigned. Synchronizing later report edits to an already assigned PR remains follow-up work.
-That work must preserve human GitHub changes and use the same ordered report candidates.
+
GitHub's final read and write are not atomic, so a small external race remains.
-There is no separate PR model call, evidence collector, decision cache, or assignment artefact.
+There is no separate PR model call, evidence collector, or decision cache. The internal `pr_owner_assignment` artefact stores delivery provenance and is not writable through the generic API.
The existing task permission checks remain separate. Report assignment does not authorize an agent to run under that person's account.
GitHub review requests still use the current report list, subject to the existing request policy.
@@ -364,9 +367,9 @@ The live trial remains pending; automated delivery tests do not establish resear
exposes project members and known GitHub accounts to agents. Personal GitHub integrations and GitHub OAuth provide identity links;
some existing lookup paths also use the GitHub App installer identity. Report recipients can use PostHog user UUIDs without GitHub accounts.
-The PR worker uses current personal GitHub integrations and OAuth links. It does not use the team installer identity as a personal link or discover new accounts.
-Verified discovery for unlinked accounts remains future work. It should extend the existing member tools, record the source and age of each link,
-and reject uncertain or conflicting matches. Similar names alone do not prove an identity.
+The PR worker uses current personal GitHub integrations and OAuth links. Before assigning a linked account, it verifies the stable GitHub user ID against the repository collaborator record.
+The provenance record stores the link source, verification time, and a 30-day expiry. An expired proof is refreshed on the next reassessment trigger.
+It does not use the team installer identity as a personal link or discover new accounts. Similar names alone do not prove an identity.
Access loss removes an ineligible report recipient on the next protected reviewer write. A team move with access retained changes selection evidence;
it does not cancel a human pin. No general process currently finds and reassesses all old reports after organization changes.
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.py
index a0398e8d3f25..378f010b7b0a 100644
--- a/posthog/models/github_integration_base.py
+++ b/posthog/models/github_integration_base.py
@@ -917,6 +917,22 @@ class GitHubIntegrationBase:
logger.warning("GitHubIntegration: installation PATCH failed", url=url, exc_info=True)
return None
+ def _installation_authenticated_delete(
+ self,
+ url: str,
+ *,
+ endpoint: str,
+ json_body: Mapping[str, object],
+ timeout: int = 10,
+ ) -> requests.Response | None:
+ """DELETE with installation auth for GitHub endpoints that accept a JSON body."""
+ path = url.removeprefix("https://api.github.com")
+ try:
+ return self.api_request("DELETE", path, endpoint=endpoint, json_body=json_body, timeout=timeout)
+ except GitHubIntegrationError:
+ logger.warning("GitHubIntegration: installation DELETE failed", url=url, exc_info=True)
+ return None
+
def _installation_authenticated_post(
self,
url: str,
@@ -1487,6 +1503,37 @@ class GitHubIntegrationBase:
]
return {"success": True, "assignees": assigned}
+ def remove_pull_request_assignees(
+ self, repository: str, pr_number: int, assignees: Iterable[str]
+ ) -> dict[str, Any]:
+ """Remove named assignees from a pull request and return the remaining assignees."""
+ unwanted = list(dict.fromkeys(login for login in assignees if login))[:MAX_PR_ASSIGNEES]
+ if not unwanted:
+ return {"success": True, "assignees": []}
+
+ repo_path = repository if "/" in repository else f"{self.organization()}/{repository}"
+ response = self._installation_authenticated_delete(
+ f"https://api.github.com/repos/{repo_path}/issues/{pr_number}/assignees",
+ endpoint="/repos/{owner}/{repo}/issues/{issue_number}/assignees",
+ json_body={"assignees": unwanted},
+ )
+ if response is None:
+ return {"success": False, "error": "Network error unassigning pull request"}
+ if response.status_code != 200:
+ return {
+ "success": False,
+ "error": f"Failed to unassign pull request: {response.text}",
+ "status_code": response.status_code,
+ }
+ try:
+ issue = response.json()
+ except Exception:
+ issue = {}
+ remaining = [
+ entry["login"] for entry in (issue.get("assignees") or []) if isinstance(entry, dict) and entry.get("login")
+ ]
+ return {"success": True, "assignees": remaining}
+
def request_pull_request_reviews(self, repository: str, pr_number: int, reviewers: Iterable[str]) -> dict[str, Any]:
"""Request reviews from GitHub users on a pull request."""
wanted = list(dict.fromkeys(login for login in reviewers if login))
diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.py
index 99a81b1eda74..167df67ab11b 100644
--- a/posthog/models/test/integration/test_github.py
+++ b/posthog/models/test/integration/test_github.py
@@ -1298,6 +1298,19 @@ class TestGitHubIntegrationModel(BaseTest):
assert mock_post.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/issues/123/assignees"
assert mock_post.call_args.kwargs["json_body"] == {"assignees": ["alice", "outsider"]}
+ def test_remove_pull_request_assignees_deletes_from_issues_endpoint(self):
+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})
+ github = GitHubIntegration(integration, source="test", priority=Priority.CRITICAL)
+ response = MagicMock(status_code=200)
+ response.json.return_value = {"assignees": [{"login": "bob"}]}
+
+ with patch.object(github, "_installation_authenticated_delete", return_value=response) as mock_delete:
+ result = github.remove_pull_request_assignees("PostHog/posthog", 123, ["alice"])
+
+ assert result == {"success": True, "assignees": ["bob"]}
+ assert mock_delete.call_args.args[0] == "https://api.github.com/repos/PostHog/posthog/issues/123/assignees"
+ assert mock_delete.call_args.kwargs["json_body"] == {"assignees": ["alice"]}
+
@parameterized.expand(
[
("empty", []),
diff --git a/products/signals/backend/artefact_schemas.py b/products/signals/backend/artefact_schemas.py
index cb2872589344..8ab3a3f98b53 100644
--- a/products/signals/backend/artefact_schemas.py
+++ b/products/signals/backend/artefact_schemas.py
@@ -306,6 +306,34 @@ class ReviewerState(BaseModel):
corrections_id: UUID | None = None
+class PROwnerIdentityProof(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ source: Literal["github_user_integration", "github_oauth"]
+ user_uuid: UUID
+ github_user_id: int
+ verified_at: datetime
+ expires_at: datetime
+
+
+class PROwnerIdentity(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ login: str = Field(pattern=r"^[a-z0-9](?:-?[a-z0-9]){0,38}$")
+ proof: PROwnerIdentityProof | None = None
+
+
+class PROwnerAssignment(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ repository: str
+ pr_number: int = Field(gt=0)
+ owners: tuple[PROwnerIdentity, ...]
+ origin: Literal["report", "claim", "legacy"]
+ assigned_at: datetime
+ replaced_logins: tuple[str, ...] = ()
+
+
class ReviewerCorrections(BaseModel):
model_config = ConfigDict(extra="forbid", frozen=True)
@@ -1234,6 +1262,7 @@ StatusArtefactContent = (
)
LogArtefactContent = (
CodeReference
+ | PROwnerAssignment
| Commit
| TaskRunArtefact
| NoteArtefact
@@ -1268,6 +1297,7 @@ ARTEFACT_CONTENT_SCHEMAS: Mapping[str, type[BaseModel]] = {
"repo_selection": RepoSelectionResult,
"suggested_reviewers": SuggestedReviewers,
"reviewer_corrections": ReviewerCorrections,
+ "pr_owner_assignment": PROwnerAssignment,
"channel_assignment": ChannelAssignment,
"ranking_score": RankingScore,
"dismissal": Dismissal,
@@ -1323,6 +1353,7 @@ _ARTEFACT_TYPE_BY_MODEL: Mapping[type[BaseModel], str] = {model: t for t, model
NON_WRITABLE_ARTEFACT_TYPES: frozenset[str] = frozenset(
{
"reviewer_corrections",
+ "pr_owner_assignment",
"task_run",
"video_segment",
"title_change",
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index aca7224158f2..e0f8e9a49ade 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1393,6 +1393,7 @@ class SignalReportArtefact(UUIDModel):
REPO_SELECTION = "repo_selection"
SUGGESTED_REVIEWERS = "suggested_reviewers"
REVIEWER_CORRECTIONS = "reviewer_corrections"
+ PR_OWNER_ASSIGNMENT = "pr_owner_assignment"
CHANNEL_ASSIGNMENT = "channel_assignment"
DISMISSAL = "dismissal"
CODE_REFERENCE = "code_reference"
@@ -1452,7 +1453,9 @@ class SignalReportArtefact(UUIDModel):
# no activity a user can see, so the artefact count leaves them out, and the artefact log shows
# them to staff only.
SYSTEM_SCORING_ARTEFACT_TYPES: frozenset[str] = frozenset({ArtefactType.RANKING_SCORE})
- INTERNAL_ARTEFACT_TYPES: frozenset[str] = frozenset({ArtefactType.REVIEWER_CORRECTIONS})
+ INTERNAL_ARTEFACT_TYPES: frozenset[str] = frozenset(
+ {ArtefactType.REVIEWER_CORRECTIONS, ArtefactType.PR_OWNER_ASSIGNMENT}
+ )
# A `report_link` graph is written by hand or by an agent, one report at a time, so a real
# chain is a handful of reports deep. The budgets guard the cycle walk on the write path
# against a graph that grew past anything a reader could order. Rows and levels are bounded
@@ -1463,6 +1466,7 @@ class SignalReportArtefact(UUIDModel):
MAX_REPORT_LINK_GRAPH_LEVELS = 50
LOG_ARTEFACT_TYPES: frozenset[str] = frozenset(
{
+ ArtefactType.PR_OWNER_ASSIGNMENT,
ArtefactType.CODE_REFERENCE,
ArtefactType.COMMIT,
ArtefactType.TASK_RUN,
diff --git a/products/signals/backend/pr_owner_assignments.py b/products/signals/backend/pr_owner_assignments.py
new file mode 100644
index 000000000000..009c291831c5
--- /dev/null
+++ b/products/signals/backend/pr_owner_assignments.py
@@ -0,0 +1,119 @@
+from __future__ import annotations
+
+from datetime import timedelta
+from typing import Literal
+
+from django.utils import timezone
+
+from posthog.dataclasses import frozen
+from posthog.models.user import User
+from posthog.models.user_integration import UserIntegration
+
+from products.signals.backend.artefact_attribution import ArtefactAttribution
+from products.signals.backend.artefact_schemas import PROwnerAssignment, PROwnerIdentity, PROwnerIdentityProof
+from products.signals.backend.models import SignalReportArtefact
+from products.signals.backend.report_generation.resolve_reviewers import resolve_org_github_login_to_users
+
+IDENTITY_PROOF_TTL = timedelta(days=30)
+PROwnerOrigin = Literal["report", "claim", "legacy"]
+
+
+@frozen
+class OwnerIdentity:
+ linked_user: bool
+ proof: PROwnerIdentityProof | None
+
+
+class PROwnerAssignmentService:
+ def __init__(self, *, team_id: int, report_id: str, repository: str, pr_number: int) -> None:
+ self.team_id = team_id
+ self.report_id = report_id
+ self.repository = repository
+ self.pr_number = pr_number
+
+ def latest(self) -> PROwnerAssignment | None:
+ rows = SignalReportArtefact.objects.filter(
+ team_id=self.team_id,
+ report_id=self.report_id,
+ type=SignalReportArtefact.ArtefactType.PR_OWNER_ASSIGNMENT,
+ ).order_by("-created_at", "-id")[:20]
+ for row in rows:
+ assignment = PROwnerAssignment.model_validate_json(row.content)
+ if assignment.repository == self.repository and assignment.pr_number == self.pr_number:
+ return assignment
+ return None
+
+ def identities_for(self, logins: list[str]) -> dict[str, OwnerIdentity]:
+ members = resolve_org_github_login_to_users(self.team_id, logins)
+ return {login: self._identity_for_member(login, members.get(login)) for login in logins}
+
+ def _identity_for_member(self, login: str, member: User | None) -> OwnerIdentity:
+ if member is None:
+ return OwnerIdentity(linked_user=False, proof=None)
+
+ source = self._identity_source(member, login)
+ if source is None:
+ return OwnerIdentity(linked_user=True, proof=None)
+ source_name, github_user_id = source
+ now = timezone.now()
+ return OwnerIdentity(
+ linked_user=True,
+ proof=PROwnerIdentityProof(
+ source=source_name,
+ user_uuid=member.uuid,
+ github_user_id=github_user_id,
+ verified_at=now,
+ expires_at=now + IDENTITY_PROOF_TTL,
+ ),
+ )
+
+ @staticmethod
+ def _identity_source(
+ member: User, login: str
+ ) -> tuple[Literal["github_user_integration", "github_oauth"], int] | None:
+ integrations = getattr(member, "_prefetched_github_user_integrations", None)
+ if integrations is None:
+ integrations = member.integrations.filter(kind=UserIntegration.IntegrationKind.GITHUB)
+ for integration in integrations:
+ github_user = integration.config.get("github_user")
+ if not isinstance(github_user, dict) or str(github_user.get("login") or "").lower() != login:
+ continue
+ try:
+ return "github_user_integration", int(github_user["id"])
+ except (KeyError, TypeError, ValueError):
+ return None
+
+ social_accounts = getattr(member, "_prefetched_github_social_auth", None)
+ if social_accounts is None:
+ social_accounts = member.social_auth.filter(provider="github")
+ for account in social_accounts:
+ if str((account.extra_data or {}).get("login") or "").lower() != login:
+ continue
+ try:
+ return "github_oauth", int(account.uid)
+ except (TypeError, ValueError):
+ return None
+ return None
+
+ def record(
+ self,
+ *,
+ identities: dict[str, PROwnerIdentityProof | None],
+ origin: PROwnerOrigin,
+ replaced_logins: list[str] | None = None,
+ ) -> PROwnerAssignment:
+ assignment = PROwnerAssignment(
+ repository=self.repository,
+ pr_number=self.pr_number,
+ owners=tuple(PROwnerIdentity(login=login, proof=proof) for login, proof in identities.items()),
+ origin=origin,
+ assigned_at=timezone.now(),
+ replaced_logins=tuple(replaced_logins or ()),
+ )
+ SignalReportArtefact.add_log(
+ team_id=self.team_id,
+ report_id=self.report_id,
+ content=assignment,
+ attribution=ArtefactAttribution.system(),
+ )
+ return assignment
diff --git a/products/signals/backend/pull_requests.py b/products/signals/backend/pull_requests.py
index 9a8cab8ed1a1..831d7756a79d 100644
--- a/products/signals/backend/pull_requests.py
+++ b/products/signals/backend/pull_requests.py
@@ -153,18 +153,23 @@ def link_pull_request(
.exists()
):
from products.signals.backend.pull_request_label import schedule_pull_request_label
- from products.signals.backend.reviewer_pr_assignment import schedule_reviewer_pr_assignment
from products.signals.backend.reviewer_pr_ready import schedule_open_pull_request_ready
- schedule_reviewer_pr_assignment(
- team_id=report.team_id, report_id=str(report.id), pr_url=pr.url, pr_state=pr.state
- )
schedule_open_pull_request_ready(
team_id=report.team_id, report_id=str(report.id), pr_url=pr.url, pr_state=pr.state
)
schedule_pull_request_label(
team_id=report.team_id, report_id=str(report.id), pr_url=pr.url, pr_state=pr.state
)
+ if notify_reviewers and state_source != PullRequestStateSource.LEGACY_ASSIGNMENT:
+ # Every verified PR refresh can change paths, ownership, membership, or linked identities.
+ # The assignment worker is bounded and replaces only the owners named by its own latest
+ # provenance record, so repeated webhook deliveries are safe reassessment triggers.
+ from products.signals.backend.reviewer_pr_assignment import schedule_reviewer_pr_assignment
+
+ schedule_reviewer_pr_assignment(
+ team_id=report.team_id, report_id=str(report.id), pr_url=pr.url, pr_state=pr.state
+ )
if state_source != PullRequestStateSource.LEGACY_ASSIGNMENT:
schedule_participant_refresh(pr)
return pr
diff --git a/products/signals/backend/reviewer_pr_assignment.py b/products/signals/backend/reviewer_pr_assignment.py
index bc3837f5758a..1cefded84be8 100644
--- a/products/signals/backend/reviewer_pr_assignment.py
+++ b/products/signals/backend/reviewer_pr_assignment.py
@@ -3,7 +3,7 @@
With research selection and the assignment writer enabled, the first eligible saved report
reviewer becomes the PR's single owner. Personal preferences and GitHub access checks can
reject a person but never select someone outside the report.
-Existing GitHub assignments and manual unassignment remain authoritative.
+Manual GitHub assignments and removals remain authoritative.
Other projects retain the legacy DRI and opt-in policies. Task execution permission is
separate from report and PR assignment. GitHub failures must not break report writes.
@@ -17,18 +17,23 @@ from uuid import UUID
from django.conf import settings
from django.db import transaction
+from django.utils import timezone
import structlog
from pydantic import ValidationError
+from posthog.dataclasses import frozen
from posthog.egress.limiter.policies import Priority
+from posthog.event_usage import groups
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 posthog.ph_client import feature_enabled_or_false, ph_scoped_capture
from products.signals.backend.artefact_schemas import (
TASK_RUN_TYPE_IMPLEMENTATION,
+ PROwnerAssignment,
+ PROwnerIdentityProof,
SuggestedReviewerEntry,
TaskRunArtefact,
)
@@ -44,6 +49,7 @@ from products.signals.backend.models import (
SignalReportAssignment,
SignalUserAutonomyConfig,
)
+from products.signals.backend.pr_owner_assignments import PROwnerAssignmentService, PROwnerOrigin
from products.signals.backend.pr_owning_team import OwningTeam, OwningTeamResolver
from products.signals.backend.report_claims import get_active_claim, responsible_user
from products.signals.backend.report_content_gates import team_research_reviewer_selection_enabled
@@ -404,17 +410,37 @@ def _request_reviews(
return requested
-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.
+@frozen
+class AssignableOwner:
+ login: str
+ identity: PROwnerIdentityProof | 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.
- """
+
+@frozen
+class OwnerApplicationState:
+ allowed: bool
+ previous: PROwnerAssignment | None
+ reason: str
+
+
+def _assignable_owners(
+ github: GitHubIntegration,
+ *,
+ team_id: int,
+ report_id: str,
+ parsed: PullRequestRef,
+ candidates: list[str],
+ assignments: PROwnerAssignmentService,
+ limit: int | None = None,
+ first_only: bool = False,
+) -> list[AssignableOwner] | None:
+ """Candidates whose repository access and linked identity GitHub verifies."""
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]:
+ bounded_candidates = candidates[:limit] if limit is not None else candidates
+ identities = assignments.identities_for(bounded_candidates)
+ owners: list[AssignableOwner] = []
+ for login in bounded_candidates:
+ identity = identities[login]
try:
result = github.is_assignable(parsed.repository, login)
except Exception:
@@ -423,10 +449,197 @@ def _first_assignable_login(
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
+ if not result.get("assignable"):
+ continue
+ if not identity.linked_user:
+ owners.append(AssignableOwner(login=login, identity=None))
+ if first_only:
+ return owners
+ continue
+ if identity.proof is None:
+ log.info("signals.pr_owner.identity_unverified")
+ continue
+ try:
+ permission = github.get_collaborator_permission(
+ parsed.repository,
+ login,
+ expected_user_id=identity.proof.github_user_id,
+ )
+ except Exception:
+ log.exception("signals.pr_owner.identity_check_failed")
+ return None
+ if permission in {"admin", "write"}:
+ owners.append(AssignableOwner(login=login, identity=identity.proof))
+ if first_only:
+ return owners
+ return owners
+
+
+def _owner_application_state(
+ github: GitHubIntegration,
+ *,
+ team_id: int,
+ report_id: str,
+ parsed: PullRequestRef,
+ pr: dict[str, Any],
+ assignments: PROwnerAssignmentService,
+) -> OwnerApplicationState:
+ current = {str(login).lower() for login in pr.get("assignees") or []}
+ previous = assignments.latest()
+ if previous is not None:
+ automatic = {owner.login for owner in previous.owners}
+ if current == automatic:
+ return OwnerApplicationState(allowed=True, previous=previous, reason="automatic_owners")
+ reason = "manually_unassigned" if not current else "assignees_changed"
+ return OwnerApplicationState(allowed=False, previous=previous, reason=reason)
+ if current:
+ return OwnerApplicationState(allowed=False, previous=None, reason="unknown_assignment_origin")
+ if _was_unassigned_by_hand(github, team_id=team_id, report_id=report_id, parsed=parsed):
+ return OwnerApplicationState(allowed=False, previous=None, reason="manually_unassigned")
+ return OwnerApplicationState(allowed=True, previous=None, reason="unassigned")
+
+
+def _capture_owner_reassessment(
+ *,
+ team_id: int,
+ report_id: str,
+ previous: PROwnerAssignment,
+ outcome: str,
+ reason: str,
+ origin: PROwnerOrigin | None = None,
+ verified_count: int = 0,
+) -> None:
+ try:
+ team = Team.objects.select_related("organization").get(id=team_id)
+ with ph_scoped_capture() as capture:
+ capture(
+ distinct_id=str(team.organization_id),
+ event="signals_pr_owner_reassessed",
+ properties={
+ "team_id": team_id,
+ "report_id": report_id,
+ "outcome": outcome,
+ "reason": reason,
+ "previous_origin": previous.origin,
+ "previous_owner_count": len(previous.owners),
+ **({"origin": origin} if origin else {}),
+ "identity_verified_count": verified_count,
+ },
+ groups=groups(organization=team.organization, team=team),
+ )
+ except Exception:
+ logger.exception("signals.pr_owner.reassessment_capture_failed", team_id=team_id, report_id=report_id)
+
+
+def _remove_assignees(
+ github: GitHubIntegration,
+ *,
+ team_id: int,
+ report_id: str,
+ parsed: PullRequestRef,
+ logins: list[str],
+) -> list[str] | None:
+ try:
+ result = github.remove_pull_request_assignees(parsed.repository, parsed.number, logins)
+ except Exception:
+ logger.exception("signals.pr_owner.unassign_failed", team_id=team_id, report_id=report_id)
+ return None
+ if not result.get("success"):
+ logger.warning(
+ "signals.pr_owner.unassign_failed",
+ team_id=team_id,
+ report_id=report_id,
+ error=result.get("error"),
+ )
+ return [] if result.get("status_code") is not None else None
+ return [str(login).lower() for login in result.get("assignees") or []]
+
+
+def _apply_automatic_owners(
+ github: GitHubIntegration,
+ *,
+ team_id: int,
+ report_id: str,
+ parsed: PullRequestRef,
+ assignments: PROwnerAssignmentService,
+ application: OwnerApplicationState,
+ owners: list[AssignableOwner],
+ origin: PROwnerOrigin,
+) -> list[str]:
+ previous = application.previous
+ previous_logins = [owner.login for owner in previous.owners] if previous else []
+ wanted = [owner.login for owner in owners]
+ previous_set = set(previous_logins)
+ wanted_set = set(wanted)
+ identities = {owner.login: owner.identity for owner in owners}
+ verified_count = sum(identity is not None for identity in identities.values())
+
+ if previous_set == wanted_set:
+ if previous is not None and any(
+ owner.proof is not None and owner.proof.expires_at <= timezone.now() for owner in previous.owners
+ ):
+ assignments.record(identities=identities, origin=origin)
+ if previous is not None:
+ _capture_owner_reassessment(
+ team_id=team_id,
+ report_id=report_id,
+ previous=previous,
+ outcome="unchanged",
+ reason="same_candidates",
+ origin=origin,
+ verified_count=verified_count,
+ )
+ return []
+
+ added = [login for login in wanted if login not in previous_set]
+ if added:
+ assigned = _add_assignees(github, team_id=team_id, report_id=report_id, parsed=parsed, logins=added)
+ expected = previous_set | set(added)
+ if assigned is None or {login.lower() for login in assigned} != expected:
+ if assigned is not None:
+ _remove_assignees(github, team_id=team_id, report_id=report_id, parsed=parsed, logins=added)
+ if previous is not None:
+ _capture_owner_reassessment(
+ team_id=team_id,
+ report_id=report_id,
+ previous=previous,
+ outcome="protected",
+ reason="assignees_changed_during_reassessment",
+ origin=origin,
+ verified_count=verified_count,
+ )
+ return []
+
+ removed = [login for login in previous_logins if login not in wanted_set]
+ if removed:
+ remaining = _remove_assignees(github, team_id=team_id, report_id=report_id, parsed=parsed, logins=removed)
+ if remaining is None or set(remaining) != wanted_set:
+ if added:
+ _remove_assignees(github, team_id=team_id, report_id=report_id, parsed=parsed, logins=added)
+ if previous is not None:
+ _capture_owner_reassessment(
+ team_id=team_id,
+ report_id=report_id,
+ previous=previous,
+ outcome="protected",
+ reason="assignees_changed_during_reassessment",
+ origin=origin,
+ verified_count=verified_count,
+ )
+ return []
+
+ assignments.record(identities=identities, origin=origin, replaced_logins=previous_logins)
+ if previous is not None:
+ _capture_owner_reassessment(
+ team_id=team_id,
+ report_id=report_id,
+ previous=previous,
+ outcome="reassigned",
+ reason="candidates_changed",
+ origin=origin,
+ verified_count=verified_count,
+ )
+ return added
def _owning_team(
@@ -528,7 +741,29 @@ def _report_assignee_logins(team: Team, snapshot: ReviewerSnapshot, *, require_o
def _assign_report_reviewers(
github: GitHubIntegration, *, team_id: int, report_id: str, parsed: PullRequestRef, pr: dict[str, Any]
) -> list[str]:
- if pr.get("assignees") or _was_unassigned_by_hand(github, team_id=team_id, report_id=report_id, parsed=parsed):
+ assignments = PROwnerAssignmentService(
+ team_id=team_id,
+ report_id=report_id,
+ repository=parsed.repository,
+ pr_number=parsed.number,
+ )
+ application = _owner_application_state(
+ github,
+ team_id=team_id,
+ report_id=report_id,
+ parsed=parsed,
+ pr=pr,
+ assignments=assignments,
+ )
+ if not application.allowed:
+ if application.previous is not None:
+ _capture_owner_reassessment(
+ team_id=team_id,
+ report_id=report_id,
+ previous=application.previous,
+ outcome="protected",
+ reason=application.reason,
+ )
return []
log = logger.bind(team_id=team_id, report_id=report_id)
@@ -544,22 +779,31 @@ def _assign_report_reviewers(
selected=len(snapshot.reviewers),
linked=len(candidates),
)
- assignable: list[str] = []
- for login in candidates[:MAX_REPORT_ASSIGNEE_CHECKS]:
- result = github.is_assignable(parsed.repository, login)
- if not result.get("success"):
- log.warning("signals.reviewer_pr_assignment.assignable_check_failed")
- return []
- if result.get("assignable"):
- assignable.append(login)
- break
- if not assignable:
+ owners = _assignable_owners(
+ github,
+ team_id=team_id,
+ report_id=report_id,
+ parsed=parsed,
+ candidates=candidates,
+ assignments=assignments,
+ limit=MAX_REPORT_ASSIGNEE_CHECKS,
+ first_only=True,
+ )
+ if owners is None:
return []
current_pr = _assignable_pull_request(github, team_id=team_id, report_id=report_id, parsed=parsed)
- if current_pr is None or current_pr.get("assignees"):
+ if current_pr is None:
return []
- if _was_unassigned_by_hand(github, team_id=team_id, report_id=report_id, parsed=parsed):
+ current_application = _owner_application_state(
+ github,
+ team_id=team_id,
+ report_id=report_id,
+ parsed=parsed,
+ pr=current_pr,
+ assignments=assignments,
+ )
+ if not current_application.allowed or current_application.previous != application.previous:
return []
current = ReviewerRules.read_for_report(team_id=team_id, report_id=report_id)
if current.state != snapshot.state or _report_assignee_logins(team, current) != candidates:
@@ -570,7 +814,16 @@ def _assign_report_reviewers(
and assignment_side_effects_enabled(team_id)
):
return []
- return _add_assignees(github, team_id=team_id, report_id=report_id, parsed=parsed, logins=assignable) or []
+ return _apply_automatic_owners(
+ github,
+ team_id=team_id,
+ report_id=report_id,
+ parsed=parsed,
+ assignments=assignments,
+ application=current_application,
+ owners=owners,
+ origin="report",
+ )
except Exception:
log.exception("signals.reviewer_pr_assignment.report_assignment_failed")
return []
@@ -579,9 +832,8 @@ def _assign_report_reviewers(
def assign_reviewers_to_pull_request(*, team_id: int, report_id: str, pr_url: str) -> list[str]:
"""Apply the shared report assignment, or the legacy DRI/opt-in policy, and request reviews.
- Returns the assignees GitHub accepted. Never unassigns: the add-assignees endpoint is additive,
- so a person 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 newly added assignees. An empty result can also mean a recorded automatic owner
+ was cleared. Manual assignments remain authoritative.
"""
if not assignment_side_effects_allowed(team_id=team_id, report_id=report_id):
return []
@@ -595,7 +847,7 @@ def assign_reviewers_to_pull_request(*, team_id: int, report_id: str, pr_url: st
logins = [] if shared_assignment else opted_in_assignee_logins(team_id=team_id, report_id=report_id)
reviewers = ranked_reviewer_logins(team_id=team_id, report_id=report_id)
dri_enabled = _pr_dri_enabled(team_id)
- if not reviewers and not logins and not dri_enabled:
+ if not reviewers and not logins and not dri_enabled and not shared_assignment:
return []
parsed = GitHubIntegration.parse_pull_request_url(pr_url)
@@ -671,14 +923,30 @@ def _assign_one_dri(
opted_in: set[str],
reviewers: list[str],
) -> list[str]:
- """Put exactly one directly responsible individual on a pull request that has none.
-
- A pull request somebody already assigned has an owner, and a pull request somebody unassigned by
- hand was a decision a later report event must not undo. Both are left alone.
- """
- if pr.get("assignees"):
- return []
- if _was_unassigned_by_hand(github, team_id=team_id, report_id=report_id, parsed=parsed):
+ """Assign one DRI, replacing only a prior owner this worker recorded."""
+ assignments = PROwnerAssignmentService(
+ team_id=team_id,
+ report_id=report_id,
+ repository=parsed.repository,
+ pr_number=parsed.number,
+ )
+ application = _owner_application_state(
+ github,
+ team_id=team_id,
+ report_id=report_id,
+ parsed=parsed,
+ pr=pr,
+ assignments=assignments,
+ )
+ if not application.allowed:
+ if application.previous is not None:
+ _capture_owner_reassessment(
+ team_id=team_id,
+ report_id=report_id,
+ previous=application.previous,
+ outcome="protected",
+ reason=application.reason,
+ )
return []
snapshot = ReviewerRules.read_for_report(team_id=team_id, report_id=report_id)
@@ -702,13 +970,31 @@ def _assign_one_dri(
),
)
]
- dri = _first_assignable_login(github, team_id=team_id, report_id=report_id, parsed=parsed, candidates=candidates)
- if dri is None:
+ owners = _assignable_owners(
+ github,
+ team_id=team_id,
+ report_id=report_id,
+ parsed=parsed,
+ candidates=candidates,
+ assignments=assignments,
+ limit=MAX_DRI_CHECKS,
+ first_only=True,
+ )
+ if not owners:
return []
+ owner = owners[0]
current_pr = _assignable_pull_request(github, team_id=team_id, report_id=report_id, parsed=parsed)
- if current_pr is None or current_pr.get("assignees"):
+ if current_pr is None:
return []
- if _was_unassigned_by_hand(github, team_id=team_id, report_id=report_id, parsed=parsed):
+ current_application = _owner_application_state(
+ github,
+ team_id=team_id,
+ report_id=report_id,
+ parsed=parsed,
+ pr=current_pr,
+ assignments=assignments,
+ )
+ if not current_application.allowed or current_application.previous != application.previous:
return []
current = ReviewerRules.read_for_report(team_id=team_id, report_id=report_id)
if (
@@ -717,4 +1003,13 @@ def _assign_one_dri(
or ranked_reviewer_logins(team_id=team_id, report_id=report_id) != reviewers
):
return []
- return _add_assignees(github, team_id=team_id, report_id=report_id, parsed=parsed, logins=[dri]) or []
+ return _apply_automatic_owners(
+ github,
+ team_id=team_id,
+ report_id=report_id,
+ parsed=parsed,
+ assignments=assignments,
+ application=current_application,
+ owners=[owner],
+ origin="claim" if claimant == owner.login else "legacy",
+ )
diff --git a/products/signals/backend/test/test_report_pr_assignment.py b/products/signals/backend/test/test_report_pr_assignment.py
index 93db21756eb2..a18f6247fb46 100644
--- a/products/signals/backend/test/test_report_pr_assignment.py
+++ b/products/signals/backend/test/test_report_pr_assignment.py
@@ -9,7 +9,12 @@ from posthog.models.organization import OrganizationMembership
from products.access_control.backend.models.access_control import AccessControl
from products.signals.backend.artefact_attribution import ArtefactAttribution
-from products.signals.backend.artefact_schemas import ReviewerEdit, SuggestedReviewerEntry, SuggestedReviewers
+from products.signals.backend.artefact_schemas import (
+ PROwnerAssignment,
+ ReviewerEdit,
+ SuggestedReviewerEntry,
+ SuggestedReviewers,
+)
from products.signals.backend.models import SignalReport, SignalReportArtefact, SignalUserAutonomyConfig
from products.signals.backend.report_assignments import claim_report
from products.signals.backend.reviewer_pr_assignment import assign_reviewers_to_pull_request
@@ -43,12 +48,30 @@ class TestReportPRAssignment:
def github(self) -> MagicMock:
github = _open_pr_github()
- github.was_ever_unassigned.return_value = _NOT_UNASSIGNED
- github.is_assignable.return_value = {"success": True, "assignable": True}
- github.add_pull_request_assignees.side_effect = lambda _repo, _number, logins: {
+ assignee_state: list[str] = []
+ github.assignee_state = assignee_state
+ github.get_pull_request.side_effect = lambda *_args: {
"success": True,
- "assignees": logins,
+ "state": "open",
+ "draft": False,
+ "merged": False,
+ "assignees": list(assignee_state),
+ "requested_reviewers": [],
}
+ github.was_ever_unassigned.return_value = _NOT_UNASSIGNED
+ github.is_assignable.return_value = {"success": True, "assignable": True}
+ github.get_collaborator_permission.return_value = "write"
+
+ def add_assignees(_repo, _number, logins):
+ assignee_state[:] = list(dict.fromkeys([*assignee_state, *logins]))
+ return {"success": True, "assignees": list(assignee_state)}
+
+ def remove_assignees(_repo, _number, logins):
+ assignee_state[:] = [login for login in assignee_state if login not in logins]
+ return {"success": True, "assignees": list(assignee_state)}
+
+ github.add_pull_request_assignees.side_effect = add_assignees
+ github.remove_pull_request_assignees.side_effect = remove_assignees
return github
def assign(self, report: SignalReport, github: MagicMock) -> list[str]:
@@ -130,14 +153,14 @@ class TestReportPRAssignment:
report = _make_report(team, [] if protection == "empty" else ["selected"])
github = self.github()
if protection == "assigned":
- github.get_pull_request.return_value["assignees"] = ["manual-owner"]
+ github.assignee_state[:] = ["manual-owner"]
elif protection == "unassigned":
github.was_ever_unassigned.return_value = {"success": True, "unassigned": True}
elif protection == "history-unavailable":
github.was_ever_unassigned.return_value = {"success": False}
elif protection == "needs-review":
report.artefacts.filter(type="suggested_reviewers").update(actor_kind="user", created_by=reviewer)
- github.get_pull_request.return_value["assignees"] = ["selected"]
+ github.assignee_state[:] = ["selected"]
assert self.assign(report, github) == []
github.add_pull_request_assignees.assert_not_called()
@@ -197,7 +220,7 @@ class TestReportPRAssignment:
elif change == "preference":
SignalUserAutonomyConfig.objects.filter(user=selected).update(github_assign_on_pull_request=False)
elif change == "github":
- github.get_pull_request.return_value["assignees"] = ["manual-owner"]
+ github.assignee_state[:] = ["manual-owner"]
return {"success": True, "assignable": True}
github.is_assignable.side_effect = check
@@ -221,10 +244,14 @@ class TestReportPRAssignment:
selected = _make_reviewer(org, "selected", opted_in=True)
report = _make_report(team, ["selected"])
github = self.github()
- github.add_pull_request_assignees.side_effect = [
- {"success": False, "status_code": 503},
- {"success": True, "assignees": ["selected"]},
- ]
+ add_assignees = github.add_pull_request_assignees.side_effect
+
+ def fail_once(repository: str, number: int, logins: list[str]) -> dict[str, object]:
+ if github.add_pull_request_assignees.call_count == 1:
+ return {"success": False, "status_code": 503}
+ return add_assignees(repository, number, logins)
+
+ github.add_pull_request_assignees.side_effect = fail_once
assert self.assign(report, github) == []
@@ -232,3 +259,69 @@ class TestReportPRAssignment:
assert self.assign(report, github) == (["selected"] if opted_in else [])
assert github.add_pull_request_assignees.call_count == (2 if opted_in else 1)
+
+ @pytest.mark.parametrize("next_reviewers", [["second", "opted-out", "replacement"], ["opted-out"], []])
+ def test_report_assignment_replaces_only_the_recorded_automatic_owner(
+ self, org_and_team: tuple[Organization, Team], next_reviewers: list[str]
+ ) -> None:
+ org, team = org_and_team
+ for login in ["first", "second", "replacement"]:
+ _make_reviewer(org, login, opted_in=True)
+ _make_reviewer(org, "opted-out", opted_in=False)
+ report = _make_report(team, ["first", "second"])
+ github = self.github()
+
+ assert self.assign(report, github) == ["first"]
+ SignalReportArtefact.objects.create(
+ team=team,
+ report=report,
+ type="suggested_reviewers",
+ content=json.dumps([{"github_login": login} for login in next_reviewers]),
+ )
+ expected = ["second"] if "second" in next_reviewers else []
+ assert self.assign(report, github) == expected
+ assert github.assignee_state == expected
+
+ assignment = PROwnerAssignment.model_validate_json(
+ report.artefacts.filter(type="pr_owner_assignment").latest("created_at").content
+ )
+ assert [owner.login for owner in assignment.owners] == expected
+ assert assignment.replaced_logins == ("first",)
+ assert all(owner.proof is not None for owner in assignment.owners)
+ github.remove_pull_request_assignees.assert_called_once_with("PostHog/posthog", 123, ["first"])
+
+ @pytest.mark.parametrize("manual_state", [[], ["first", "manual-owner"]])
+ def test_manual_assignment_changes_block_report_reassessment(self, org_and_team, manual_state):
+ org, team = org_and_team
+ for login in ["first", "replacement"]:
+ _make_reviewer(org, login, opted_in=True)
+ report = _make_report(team, ["first"])
+ github = self.github()
+
+ assert self.assign(report, github) == ["first"]
+ github.assignee_state[:] = manual_state
+ SignalReportArtefact.objects.create(
+ team=team,
+ report=report,
+ type="suggested_reviewers",
+ content=json.dumps([{"github_login": "replacement"}]),
+ )
+
+ assert self.assign(report, github) == []
+ assert report.artefacts.filter(type="pr_owner_assignment").count() == 1
+ github.remove_pull_request_assignees.assert_not_called()
+
+ def test_linked_report_owner_must_match_the_stable_github_identity(self, org_and_team):
+ org, team = org_and_team
+ selected = _make_reviewer(org, "selected", opted_in=True)
+ report = _make_report(team, ["selected"])
+ github = self.github()
+ github.get_collaborator_permission.return_value = "none"
+
+ assert self.assign(report, github) == []
+ github.get_collaborator_permission.assert_called_once_with(
+ "PostHog/posthog",
+ "selected",
+ expected_user_id=int(selected.social_auth.get(provider="github").uid),
+ )
+ github.add_pull_request_assignees.assert_not_called()
diff --git a/products/signals/backend/test/test_reviewer_pr_assignment.py b/products/signals/backend/test/test_reviewer_pr_assignment.py
index 98db4d4e4ada..1417d5f2f807 100644
--- a/products/signals/backend/test/test_reviewer_pr_assignment.py
+++ b/products/signals/backend/test/test_reviewer_pr_assignment.py
@@ -12,7 +12,7 @@ from posthog.ownership.paths import UNOWNED_TEAM, PathOwnership
from products.access_control.backend.models.access_control import AccessControl
from products.signals.backend.artefact_attribution import ArtefactAttribution
-from products.signals.backend.artefact_schemas import ReviewerCorrections, SuggestedReviewerEntry
+from products.signals.backend.artefact_schemas import PROwnerAssignment, ReviewerCorrections, SuggestedReviewerEntry
from products.signals.backend.models import (
SignalReport,
SignalReportArtefact,
@@ -61,7 +61,7 @@ def org_and_team():
def _make_reviewer(org: Organization, login: str, *, opted_in: bool) -> User:
user = User.objects.create(email=f"{login}@example.com", first_name="Reviewer")
OrganizationMembership.objects.create(user=user, organization=org)
- UserSocialAuth.objects.create(user=user, provider="github", uid=f"gh-{login}", extra_data={"login": login})
+ UserSocialAuth.objects.create(user=user, provider="github", uid=str(100_000 + user.id), extra_data={"login": login})
SignalUserAutonomyConfig.objects.create(user=user, github_assign_on_pull_request=opted_in)
return user
@@ -493,7 +493,7 @@ class TestPullRequestLinkingQueuesAssignment:
self.mock_delay.assert_called_once_with(team_id=team.id, report_id=str(report.id), pr_url=PR_URL)
@pytest.mark.django_db(transaction=True)
- def test_reclaiming_the_same_pull_request_does_not_requeue(self, org_and_team):
+ def test_reclaiming_the_same_pull_request_reassesses_the_owner(self, org_and_team):
_, team = org_and_team
report = _make_report(team)
user = User.objects.create(email="[email protected]")
@@ -512,10 +512,10 @@ class TestPullRequestLinkingQueuesAssignment:
release=False,
)
- assert self.mock_delay.call_count == 1
+ assert self.mock_delay.call_count == 2
@pytest.mark.django_db(transaction=True)
- def test_syncing_a_task_pull_request_queues_assignment_once(self, org_and_team):
+ def test_syncing_a_task_pull_request_reassesses_each_verified_snapshot(self, org_and_team):
_, team = org_and_team
report = _make_report(team)
task = Task.objects.create(team=team, title="Implementation", description="", origin_product="signals")
@@ -524,7 +524,8 @@ class TestPullRequestLinkingQueuesAssignment:
for _ in range(2):
sync_task_pull_request_to_assignments(team_id=team.id, task_id=str(task.id), pr_url=PR_URL, pr_state="open")
- self.mock_delay.assert_called_once_with(team_id=team.id, report_id=str(report.id), pr_url=PR_URL)
+ assert self.mock_delay.call_count == 2
+ self.mock_delay.assert_called_with(team_id=team.id, report_id=str(report.id), pr_url=PR_URL)
@pytest.mark.django_db(transaction=True)
def test_a_merged_task_pull_request_is_not_queued(self, org_and_team):
@@ -611,22 +612,34 @@ class TestDirectlyResponsibleIndividual:
def _github(self, *, existing_assignees: list[str], assignable: set[str] | None) -> MagicMock:
github = _open_pr_github()
- github.get_pull_request.return_value = {
+ assignee_state = list(existing_assignees)
+ github.assignee_state = assignee_state
+ github.get_pull_request.side_effect = lambda *_args: {
"success": True,
"state": "open",
"merged": False,
- "assignees": existing_assignees,
+ "assignees": list(assignee_state),
}
github.is_assignable.side_effect = lambda _repo, login: {
"success": True,
"assignable": assignable is None or login in assignable,
}
+ github.get_collaborator_permission.side_effect = lambda _repo, login, **_kwargs: (
+ "write" if assignable is None or login in assignable else "none"
+ )
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,
- }
+
+ def add_assignees(_repo, _number, logins):
+ assignee_state[:] = list(dict.fromkeys([*assignee_state, *logins]))
+ return {"success": True, "assignees": list(assignee_state)}
+
+ def remove_assignees(_repo, _number, logins):
+ assignee_state[:] = [login for login in assignee_state if login not in logins]
+ return {"success": True, "assignees": list(assignee_state)}
+
+ github.add_pull_request_assignees.side_effect = add_assignees
+ github.remove_pull_request_assignees.side_effect = remove_assignees
return github
def _team_x(self, github: MagicMock) -> None:
@@ -749,11 +762,98 @@ class TestDirectlyResponsibleIndividual:
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"}
+ github.get_collaborator_permission.side_effect = RuntimeError("Failed to check assignee")
+
+ assert self._assign(team, report, github) == []
+ assert github.get_collaborator_permission.call_count == 1
+
+ @pytest.mark.django_db
+ def test_a_linked_login_must_still_name_the_same_github_account(self, org_and_team):
+ org, team = org_and_team
+ report, users = self._setup(org, team, ["alice"])
+ github = self._github(existing_assignees=[], assignable=None)
+ github.get_collaborator_permission.return_value = "none"
+ github.get_collaborator_permission.side_effect = None
assert self._assign(team, report, github) == []
- assert github.is_assignable.call_count == 1
+ github.get_collaborator_permission.assert_called_once_with(
+ "PostHog/posthog",
+ "alice",
+ expected_user_id=int(users["alice"].social_auth.get(provider="github").uid),
+ )
+ github.add_pull_request_assignees.assert_not_called()
+
+ @pytest.mark.django_db
+ @pytest.mark.parametrize(
+ ("live_change", "change_during_remove", "expected_adds", "expected_owner"),
+ [
+ (None, False, [["alice"], ["bob"]], "bob"),
+ ([], False, [["alice"]], "alice"),
+ (["alice", "teammate"], False, [["alice"]], "alice"),
+ (None, True, [["alice"], ["bob"]], "alice"),
+ ],
+ ids=[
+ "automatic_owner_replaced",
+ "manual_unassignment_preserved",
+ "additional_assignee_preserved",
+ "concurrent_additional_assignee_preserved",
+ ],
+ )
+ def test_only_the_last_automatic_owner_can_be_reassessed(
+ self,
+ org_and_team,
+ live_change: list[str] | None,
+ change_during_remove: bool,
+ expected_adds: list[list[str]],
+ expected_owner: str,
+ ):
+ org, team = org_and_team
+ report, _ = self._setup(org, team, ["alice", "bob"])
+ github = self._github(existing_assignees=[], assignable=None)
+
+ self._assign(team, report, github)
+ if live_change is not None:
+ github.assignee_state[:] = live_change
+ SignalReportArtefact.objects.create(
+ team=team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content=json.dumps([{"github_login": "bob"}, {"github_login": "alice"}]),
+ )
+ if change_during_remove:
+ original_remove = github.remove_pull_request_assignees.side_effect
+
+ def remove_with_concurrent_assignee(repository: str, number: int, logins: list[str]) -> dict[str, object]:
+ if logins == ["alice"]:
+ github.assignee_state.append("teammate")
+ return original_remove(repository, number, logins)
+
+ github.remove_pull_request_assignees.side_effect = remove_with_concurrent_assignee
+ calls = self._assign(team, report, github)
+
+ assert calls == expected_adds
+ assignments = [
+ PROwnerAssignment.model_validate_json(content)
+ for content in report.artefacts.filter(type="pr_owner_assignment")
+ .order_by("created_at", "id")
+ .values_list("content", flat=True)
+ ]
+ assert [owner.login for owner in assignments[-1].owners] == [expected_owner]
+ if live_change is None and not change_during_remove:
+ assert assignments[-1].replaced_logins == ("alice",)
+ assert assignments[-1].owners[0].proof is not None
+ assert assignments[-1].owners[0].proof.source == "github_oauth"
+ github.remove_pull_request_assignees.assert_called_once_with("PostHog/posthog", 123, ["alice"])
+ elif change_during_remove:
+ assert len(assignments) == 1
+ assert github.assignee_state == ["teammate"]
+ assert [call.args[2] for call in github.remove_pull_request_assignees.call_args_list] == [
+ ["alice"],
+ ["bob"],
+ ]
+ else:
+ assert len(assignments) == 1
+ github.remove_pull_request_assignees.assert_not_called()
@pytest.mark.django_db
@pytest.mark.parametrize("correction", ["needs-review", "excluded-uuid", "excluded-login"])
@@ -814,11 +914,12 @@ class TestDirectlyResponsibleIndividual:
def check(_repo: str, _login: str) -> dict[str, bool]:
if change == "assigned":
- github.get_pull_request.return_value["assignees"] = ["manual-owner"]
+ github.assignee_state[:] = ["manual-owner"]
elif change == "unassigned":
github.was_ever_unassigned.return_value = {"success": True, "unassigned": True}
elif change == "closed":
- github.get_pull_request.return_value["state"] = "closed"
+ github.get_pull_request.side_effect = None
+ github.get_pull_request.return_value = {"success": True, "state": "closed"}
elif change == "history-unavailable":
github.was_ever_unassigned.return_value = {"success": False}
elif change == "report":
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index f4dfccf08471..006d80eda3b8 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -5248,8 +5248,9 @@ def append_suggested_reviewers(
actor_user_id=attribution.user_id,
)
- # Only on an add: assignment is additive, so a removal leaves the pull request alone.
- if added_github_logins:
+ # A changed reviewer set may change the automatic PR owners in either direction.
+ # The worker protects human and unknown-origin assignments before it mutates GitHub.
+ if added_entries or removed_payloads:
for pr in fetch_implementation_prs_for_reports([str(report_id)], team_id=team.id).get(
str(report_id), []
):
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 15dd3ffb8ee0..f89a196c5ada 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -4380,6 +4380,7 @@ export interface SignalReportStateRequestApi {
* * `repo_selection` - Repo Selection
* * `suggested_reviewers` - Suggested Reviewers
* * `reviewer_corrections` - Reviewer Corrections
+ * * `pr_owner_assignment` - Pr Owner Assignment
* * `channel_assignment` - Channel Assignment
* * `dismissal` - Dismissal
* * `code_reference` - Code Reference
@@ -4420,6 +4421,7 @@ export const SignalReportArtefactArtefactTypeEnumApi = {
RepoSelection: 'repo_selection',
SuggestedReviewers: 'suggested_reviewers',
ReviewerCorrections: 'reviewer_corrections',
+ PrOwnerAssignment: 'pr_owner_assignment',
ChannelAssignment: 'channel_assignment',
Dismissal: 'dismissal',
CodeReference: 'code_reference',
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 767cfb375355..87056e4bb24f 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -1207,7 +1207,7 @@ export const getSignalsReportArtefactsDestroyUrl = (projectId: string, reportId:
}
/**
- * Delete an artefact, addressed by id. Deleting the latest row of a status type reverts the report's canonical status to the previous version (latest-wins over what remains). `task_run` artefacts are an append-only work log and cannot be deleted. Neither can the types this API cannot write, which the pipeline owns: `autostart_skip`, `check_cancelled`, `check_expired`, `check_observation`, `check_result`, `check_scheduled`, `code_review`, `impact_measurement_plan`, `implementation_decision`, `implementation_dispatch`, `implementation_handover`, `implementation_replacement`, `pull_request`, `ranking_score`, `report_link`, `reviewer_corrections`, `summary_change`, `task_run`, `title_change`, `video_segment`, `work_claim`, `work_release`.
+ * Delete an artefact, addressed by id. Deleting the latest row of a status type reverts the report's canonical status to the previous version (latest-wins over what remains). `task_run` artefacts are an append-only work log and cannot be deleted. Neither can the types this API cannot write, which the pipeline owns: `autostart_skip`, `check_cancelled`, `check_expired`, `check_observation`, `check_result`, `check_scheduled`, `code_review`, `impact_measurement_plan`, `implementation_decision`, `implementation_dispatch`, `implementation_handover`, `implementation_replacement`, `pr_owner_assignment`, `pull_request`, `ranking_score`, `report_link`, `reviewer_corrections`, `summary_change`, `task_run`, `title_change`, `video_segment`, `work_claim`, `work_release`.
* @summary Delete an artefact
*/
export const signalsReportArtefactsDestroy = async (
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d1213a08b97d..411b1d2d25cf 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -77446,6 +77446,7 @@ export namespace Schemas {
* * `repo_selection` - Repo Selection
* * `suggested_reviewers` - Suggested Reviewers
* * `reviewer_corrections` - Reviewer Corrections
+ * * `pr_owner_assignment` - Pr Owner Assignment
* * `channel_assignment` - Channel Assignment
* * `dismissal` - Dismissal
* * `code_reference` - Code Reference
@@ -77486,6 +77487,7 @@ export namespace Schemas {
RepoSelection: 'repo_selection',
SuggestedReviewers: 'suggested_reviewers',
ReviewerCorrections: 'reviewer_corrections',
+ PrOwnerAssignment: 'pr_owner_assignment',
ChannelAssignment: 'channel_assignment',
Dismissal: 'dismissal',
CodeReference: 'code_reference',
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 3ac31568d6d6..666eef008d14 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -932,7 +932,7 @@ export const SignalsReportArtefactsPartialUpdateBody = () => zod
)
/**
- * Delete an artefact, addressed by id. Deleting the latest row of a status type reverts the report's canonical status to the previous version (latest-wins over what remains). `task_run` artefacts are an append-only work log and cannot be deleted. Neither can the types this API cannot write, which the pipeline owns: `autostart_skip`, `check_cancelled`, `check_expired`, `check_observation`, `check_result`, `check_scheduled`, `code_review`, `impact_measurement_plan`, `implementation_decision`, `implementation_dispatch`, `implementation_handover`, `implementation_replacement`, `pull_request`, `ranking_score`, `report_link`, `reviewer_corrections`, `summary_change`, `task_run`, `title_change`, `video_segment`, `work_claim`, `work_release`.
+ * Delete an artefact, addressed by id. Deleting the latest row of a status type reverts the report's canonical status to the previous version (latest-wins over what remains). `task_run` artefacts are an append-only work log and cannot be deleted. Neither can the types this API cannot write, which the pipeline owns: `autostart_skip`, `check_cancelled`, `check_expired`, `check_observation`, `check_result`, `check_scheduled`, `code_review`, `impact_measurement_plan`, `implementation_decision`, `implementation_dispatch`, `implementation_handover`, `implementation_replacement`, `pr_owner_assignment`, `pull_request`, `ranking_score`, `report_link`, `reviewer_corrections`, `summary_change`, `task_run`, `title_change`, `video_segment`, `work_claim`, `work_release`.
* @summary Delete an artefact
*/
export const SignalsReportArtefactsDestroyParams = () => zod.object({