:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signals): exclude departed commit authors from suggested reviewers (#100967)
posthog[bot]4bbbb86f8252
diff --git a/posthog/models/github_integration_base.py b/posthog/models/github_integration_base.pyindex 01cb7729e862..89d15257882f 100644--- a/posthog/models/github_integration_base.py+++ b/posthog/models/github_integration_base.py@@ -98,6 +98,17 @@ class GitHubCommitAuthor:is_bot: bool = False+@frozen+class GitHubAuthorLastCommit:+ """When an account last landed a commit on a repository's default branch.++ ``last_commit_at`` is None when GitHub answered and the account has no commit there. A+ caller that could not ask GitHub at all gets no instance, so the two cases stay apart.+ """++ last_commit_at: datetime | None++@dataclass(frozen=True)class GitHubCommitAttribution:"""GitHub's own commit→account attribution, from the commits listing."""@@ -940,6 +951,60 @@ class GitHubIntegrationBase:is_bot=author.get("type") == "Bot",)+ def get_author_last_commit(self, repository: str, login: str) -> GitHubAuthorLastCommit | None:+ """When ``login`` last committed to ``repository``'s default branch.++ Returns None when GitHub could not be asked or did not answer in a readable shape, so a+ caller can hold its behavior instead of acting on a failed probe. Rate limits raise+ ``GitHubRateLimitError`` (from ``api_request``).+ """+ response = self._installation_authenticated_get(+ f"https://api.github.com/repos/{repository}/commits",+ endpoint="/repos/{owner}/{repo}/commits",+ params={"author": login, "per_page": 1},+ )+ if response is None:+ return None+ if response.status_code != 200:+ logger.info(+ "GitHub API non-200 for author last-commit lookup",+ status_code=response.status_code,+ repository=repository,+ )+ return None+ try:+ body = response.json()+ except Exception:+ logger.warning(+ "GitHubIntegration: failed to parse author last-commit JSON", repository=repository, exc_info=True+ )+ return None+ if not isinstance(body, list):+ return None+ if not body:+ return GitHubAuthorLastCommit(last_commit_at=None)+ commit = body[0].get("commit") if isinstance(body[0], dict) else None+ if not isinstance(commit, dict):+ return None+ author = commit.get("author")+ committer = commit.get("committer")+ raw_date = (author.get("date") if isinstance(author, dict) else None) or (+ committer.get("date") if isinstance(committer, dict) else None+ )+ if not isinstance(raw_date, str):+ return None+ try:+ parsed = datetime.fromisoformat(raw_date)+ except ValueError:+ logger.warning(+ "GitHubIntegration: unparseable author last-commit date", repository=repository, exc_info=True+ )+ return None+ # Every GitHub commit date carries a zone; a naive one would break the caller's arithmetic.+ if parsed.tzinfo is None:+ return None+ return GitHubAuthorLastCommit(last_commit_at=parsed)+def list_commit_attributions(self,repository: str,diff --git a/posthog/models/test/integration/test_github.py b/posthog/models/test/integration/test_github.pyindex 4399734b9bcf..30cea08d7a54 100644--- a/posthog/models/test/integration/test_github.py+++ b/posthog/models/test/integration/test_github.py@@ -210,6 +210,50 @@ class TestGitHubIntegrationModel(BaseTest):integration.refresh_from_db()assert integration.sensitive_config == {"token": "REFRESH", "access_token": "FULL_TOKEN"}+ @parameterized.expand(+ [+ # An answer GitHub gave: the account committed, and this is when.+ (+ "dated_commit",+ 200,+ [{"commit": {"author": {"date": "2021-02-09T10:00:00Z"}}}],+ datetime(2021, 2, 9, 10, tzinfo=UTC),+ ),+ # Also an answer: the account has no commit on the default branch.+ ("no_commits", 200, [], None),+ ]+ )+ def test_author_last_commit_reports_what_github_answered(self, _name, status_code, body, expected):+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ mock_response = MagicMock(status_code=status_code)+ mock_response.json.return_value = body++ with patch.object(github, "api_request", return_value=mock_response):+ result = github.get_author_last_commit("PostHog/posthog", "octocat")++ assert result is not None+ assert result.last_commit_at == expected++ @parameterized.expand(+ [+ ("non_200", 404, []),+ ("not_a_list", 200, {"message": "nope"}),+ ("undated_commit", 200, [{"commit": {}}]),+ ("author_not_a_dict", 200, [{"commit": {"author": "octocat"}}]),+ ]+ )+ def test_author_last_commit_says_nothing_when_github_did_not_answer(self, _name, status_code, body):+ # A caller drops a reviewer on a dated answer, so a failed lookup must not read as+ # "this account never committed".+ integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})+ github = GitHubIntegration(integration)+ mock_response = MagicMock(status_code=status_code)+ mock_response.json.return_value = body++ with patch.object(github, "api_request", return_value=mock_response):+ assert github.get_author_last_commit("PostHog/posthog", "octocat") is None+def test_get_diff_compares_branch_tips(self):integration = self.create_integration(sensitive_config={"access_token": "ACCESS_TOKEN"})github = GitHubIntegration(integration)diff --git a/products/signals/backend/report_generation/author_activity.py b/products/signals/backend/report_generation/author_activity.pynew file mode 100644index 000000000000..d8b4858947ac--- /dev/null+++ b/products/signals/backend/report_generation/author_activity.py@@ -0,0 +1,101 @@+"""Whether a commit author still works on a repository, for reviewer routing.++Commit authorship outlives a person, so blame evidence alone can name a reviewer who left.+The area-activity cache (``repo_activity``) answers the same question inside its own 90-day+window; this module covers the rest of the year by asking GitHub for the author's last commit+anywhere in the repository. A verdict is cached, and an author GitHub cannot speak for is kept,+so a failed lookup never removes a candidate.+"""++from __future__ import annotations++import logging+from collections import Counter+from concurrent.futures import ThreadPoolExecutor, as_completed++from django.core.cache import cache+from django.utils import timezone++from posthog.egress.github.transport import GitHubRateLimitError+from posthog.models.integration import GitHubIntegration++from products.signals.backend.report_generation.repo_activity import days_since++logger = logging.getLogger(__name__)++# A commit author who has not touched the repository within this window is treated as gone,+# not as a quiet owner. Set well above the 90-day area-activity window so that an author who+# merely moved to another part of the repository still counts.+AUTHOR_ACTIVITY_WINDOW_DAYS = 365+# A verdict this old is still good: the window is a year, so a day's drift cannot flip one.+# It keeps a retried or repeated report off GitHub's rate-limit budget.+AUTHOR_ACTIVITY_CACHE_TTL_SECONDS = 60 * 60 * 24+# GitHub calls run in parallel, bounded the same way the commit-author lookups are.+MAX_PROBE_WORKERS = 5+++def _cache_key(repository: str, login: str) -> str:+ return f"signals:author_inactive:{repository}:{login}"+++def without_inactive_authors(+ github: GitHubIntegration,+ repository: str,+ login_weights: Counter[str],+ *,+ proven_active: set[str],+) -> Counter[str]:+ """``login_weights`` without the authors who stopped committing to ``repository``.++ ``proven_active`` names the logins a caller already knows are current, so they cost no+ lookup. A stored verdict answers for the rest before GitHub is asked.+ """+ keys = {login: _cache_key(repository, login) for login in login_weights if login not in proven_active}+ if not keys:+ return login_weights++ cached = cache.get_many(list(keys.values()))+ inactive = {login for login, key in keys.items() if cached.get(key) is True}+ unknown = [login for login, key in keys.items() if key not in cached]+ if unknown:+ inactive |= _probe_inactive_authors(github, repository, unknown)++ if not inactive:+ return login_weights+ logger.info("Dropped %d inactive commit author(s) for %s", len(inactive), repository)+ return Counter({login: weight for login, weight in login_weights.items() if login not in inactive})+++def _probe_inactive_authors(github: GitHubIntegration, repository: str, logins: list[str]) -> set[str]:+ """Which of ``logins`` GitHub reports as having stopped committing to ``repository``.++ An author GitHub cannot speak for — a failed probe, a throttled one, or an account with no+ attributed commit on the default branch — is left out, because a probe that did not answer+ must not remove a candidate. Every answer GitHub gave is cached, so a retried report does not+ re-ask; a probe that did not answer is not, so the next report tries again.+ """+ now = timezone.now()+ inactive: set[str] = set()+ with ThreadPoolExecutor(max_workers=min(len(logins), MAX_PROBE_WORKERS)) as pool:+ future_to_login = {pool.submit(github.get_author_last_commit, repository, login): login for login in logins}+ for future in as_completed(future_to_login):+ login = future_to_login[future]+ try:+ last_commit = future.result()+ except GitHubRateLimitError:+ logger.info("GitHub rate limited during author activity probe for %s", repository)+ continue+ except Exception:+ logger.warning("Author activity probe failed for %s", repository, exc_info=True)+ continue+ if last_commit is None:+ continue+ if last_commit.last_commit_at is None:+ # GitHub answered, and no commit is attributed to the account, so the author stands.+ cache.set(_cache_key(repository, login), False, AUTHOR_ACTIVITY_CACHE_TTL_SECONDS)+ continue+ is_inactive = days_since(last_commit.last_commit_at, now) > AUTHOR_ACTIVITY_WINDOW_DAYS+ cache.set(_cache_key(repository, login), is_inactive, AUTHOR_ACTIVITY_CACHE_TTL_SECONDS)+ if is_inactive:+ inactive.add(login)+ return inactivediff --git a/products/signals/backend/report_generation/repo_activity.py b/products/signals/backend/report_generation/repo_activity.pyindex e0dea6676f40..841bed1054c8 100644--- a/products/signals/backend/report_generation/repo_activity.py+++ b/products/signals/backend/report_generation/repo_activity.py@@ -45,6 +45,11 @@ MAX_CONTRIBUTORS_PER_AREA = 50REPO_WIDE_AREA = "*"+def days_since(moment: datetime, now: datetime) -> float:+ """Days between ``moment`` and ``now``, clamped at zero so a clock-skewed future date reads as today."""+ return max(0.0, (now - moment).total_seconds() / 86400)++@dataclass(frozen=True)class ContributorActivity:login: strdiff --git a/products/signals/backend/report_generation/resolve_reviewers.py b/products/signals/backend/report_generation/resolve_reviewers.pyindex c9aba3dc964e..48ec50c6c383 100644--- a/products/signals/backend/report_generation/resolve_reviewers.py+++ b/products/signals/backend/report_generation/resolve_reviewers.py@@ -26,12 +26,14 @@ from posthog.models.user import Userfrom posthog.models.user_integration import UserIntegrationfrom products.signals.backend.contracts import RelevantCommit+from products.signals.backend.report_generation.author_activity import without_inactive_authorsfrom products.signals.backend.report_generation.repo_activity import (ACTIVITY_WINDOW_DAYS,REPO_WIDE_AREA,ContributorActivity,area_fallback_chain,areas_for_paths,+ days_since,get_area_activity,repository_activity_needs_rebuild,)@@ -79,6 +81,7 @@ ReviewerResolutionOutcome = Literal["github_rate_limited","no_commit_authors","only_bot_authors",+ "only_inactive_authors","no_candidates",]@@ -97,6 +100,9 @@ class ReviewerResolutionDiagnostics:lookups_rate_limited: int = 0bot_author_count: int = 0blame_login_count: int = 0+ # Blame authors dropped because their last commit in the repository is older than+ # AUTHOR_ACTIVITY_WINDOW_DAYS. Counted before the fallbacks that may replace them.+ inactive_author_count: int = 0touched_path_count: int = 0activity_login_count: int = 0@@ -321,6 +327,9 @@ def resolve_suggested_reviewers_with_diagnostics() -> ReviewerResolution:"""Resolve commit hashes to up to 3 reviewers, preferring recently-active owners.+ A commit author who has not committed to the repository for ``AUTHOR_ACTIVITY_WINDOW_DAYS``+ is dropped before scoring — see ``_without_inactive_authors``.+Blame candidates (commit authors, weighted by finding position) are recency-shapedagainst cached area activity, and recently-active area contributors enter as cappedfallbacks — see ``_score_candidates``. With no activity data available at all, scoring@@ -391,8 +400,14 @@ def resolve_suggested_reviewers_with_diagnostics(touched_paths = [path for info in author_results.values() if info is not None for path in info.file_paths]activity_by_login = _relevant_area_activity(team_id, repository, touched_paths)+ proven_active = {+ login for login, activity in activity_by_login.items() if activity.days_since_last_commit < ACTIVITY_WINDOW_DAYS+ }+ active_login_weights = without_inactive_authors(github, repository, login_weights, proven_active=proven_active)+ inactive_author_count = len(login_weights) - len(active_login_weights)+reviewers = _rank_scored_candidates(- login_weights, activity_by_login, login_commits, login_names, allow_crowd_fallback=True+ active_login_weights, activity_by_login, login_commits, login_names, allow_crowd_fallback=True)lookups_resolved = sum(1 for info in author_results.values() if info is not None)outcome: ReviewerResolutionOutcome@@ -407,6 +422,8 @@ def resolve_suggested_reviewers_with_diagnostics(outcome = "no_commit_authors"elif not login_weights:outcome = "only_bot_authors"+ elif not active_login_weights:+ outcome = "only_inactive_authors"else:outcome = "no_candidates"return ReviewerResolution(@@ -420,6 +437,7 @@ def resolve_suggested_reviewers_with_diagnostics(lookups_rate_limited=lookups_rate_limited,bot_author_count=bot_author_count,blame_login_count=len(login_weights),+ inactive_author_count=inactive_author_count,touched_path_count=len(touched_paths),activity_login_count=len(activity_by_login),),@@ -577,12 +595,12 @@ def _merge_contributor(now: datetime,is_likely_owner_of_area: bool,) -> _AreaContributor:- days_since = max(0.0, (now - incoming.last_commit_at).total_seconds() / 86400)+ days_since_commit = days_since(incoming.last_commit_at, now)if existing is None:return _AreaContributor(name=incoming.name,commit_count=incoming.commit_count,- days_since_last_commit=days_since,+ days_since_last_commit=days_since_commit,last_commit_sha=incoming.last_commit_sha,last_commit_url=incoming.last_commit_url,area=area,@@ -591,11 +609,11 @@ def _merge_contributor(# Evidence follows the freshest commit, so sha/url/area always agree with# days_since_last_commit. Ownership does not: it accumulates, so a fresher commit in a# crowded level can't erase a claim earned in a focused one.- keep_incoming_evidence = days_since < existing.days_since_last_commit+ keep_incoming_evidence = days_since_commit < existing.days_since_last_commitreturn _AreaContributor(name=existing.name or incoming.name,commit_count=existing.commit_count + incoming.commit_count,- days_since_last_commit=min(existing.days_since_last_commit, days_since),+ days_since_last_commit=min(existing.days_since_last_commit, days_since_commit),last_commit_sha=incoming.last_commit_sha if keep_incoming_evidence else existing.last_commit_sha,last_commit_url=incoming.last_commit_url if keep_incoming_evidence else existing.last_commit_url,area=area if keep_incoming_evidence else existing.area,diff --git a/products/signals/backend/test/test_resolve_reviewers.py b/products/signals/backend/test/test_resolve_reviewers.pyindex ad33f3658180..340ed3ba3eb0 100644--- a/products/signals/backend/test/test_resolve_reviewers.py+++ b/products/signals/backend/test/test_resolve_reviewers.py@@ -4,19 +4,21 @@ from datetime import timedeltaimport pytestfrom unittest.mock import patch+from django.core.cache import cachefrom django.utils import timezonefrom social_django.models import UserSocialAuthfrom posthog.egress.github.transport import GitHubRateLimitErrorfrom posthog.models import Organization, Team, User-from posthog.models.github_integration_base import GitHubCommitAuthor+from posthog.models.github_integration_base import GitHubAuthorLastCommit, GitHubCommitAuthorfrom posthog.models.integration import Integrationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.scoping import team_scopefrom posthog.models.user_integration import UserIntegrationfrom products.signals.backend.models import SignalRepositoryAreaActivity+from products.signals.backend.report_generation.author_activity import AUTHOR_ACTIVITY_WINDOW_DAYSfrom products.signals.backend.report_generation.repo_activity import ACTIVITY_WINDOW_DAYS, ContributorActivityfrom products.signals.backend.report_generation.resolve_reviewers import (MAX_CONTRIBUTORS_FOR_OWNERSHIP,@@ -35,6 +37,12 @@ from products.signals.backend.report_generation.resolve_reviewers import ()[email protected](autouse=True)+def clear_caches():+ # The resolver caches its author-activity verdicts, which would otherwise carry between tests.+ cache.clear()++@pytest.fixturedef organization():org = Organization.objects.create(name="test-resolve-reviewers-org")@@ -404,6 +412,10 @@ class TestResolveSuggestedReviewersEndToEnd:file_paths=("products/signals/backend/models.py",),)+ def get_author_last_commit(self, repository, login):+ # Still committing, just not in this area — demoted, not excluded.+ return GitHubAuthorLastCommit(last_commit_at=timezone.now() - timedelta(days=120))+activity = {"products/signals": [ContributorActivity(@@ -550,6 +562,9 @@ class TestResolveSuggestedReviewersEndToEnd:file_paths=("products/signals/backend/models.py",),)+ def get_author_last_commit(self, repository, login):+ return GitHubAuthorLastCommit(last_commit_at=timezone.now() - timedelta(days=120))+# The blame author is in the area cache but their last commit has aged past the window# (the cache is served while a rebuild is scheduled). They are not a live reviewer, so the# fresh area owner must still surface rather than being suppressed by a stale cache entry.@@ -595,6 +610,187 @@ class TestResolveSuggestedReviewersEndToEnd:assert logins.index("fresh-owner") < logins.index("aged-author")+class TestDepartedCommitAuthors:+ """Commit authorship outlives a person, so a blame author is probed for recent repository work."""++ @staticmethod+ def _fake_github(blame_login: str, last_commit_at, *, probed: list[str] | None = None, raises=None):+ class FakeGitHub:+ def get_commit_author_info(self, repository, sha):+ return GitHubCommitAuthor(+ login=blame_login,+ name="Blame Author",+ commit_url=f"https://github.com/acme/app/commit/{sha}",+ file_paths=("products/signals/backend/models.py",),+ )++ def get_author_last_commit(self, repository, login):+ if probed is not None:+ probed.append(login)+ if raises is not None:+ raise raises+ return last_commit_at++ return FakeGitHub()++ @staticmethod+ def _resolve(team, github, activity):+ with (+ patch(+ "products.signals.backend.report_generation.resolve_reviewers.GitHubIntegration.first_for_team_repository",+ return_value=github,+ ),+ patch(+ "products.signals.backend.report_generation.resolve_reviewers.get_area_activity",+ return_value=activity,+ ),+ patch(+ "products.signals.backend.report_generation.resolve_reviewers.repository_activity_needs_rebuild",+ return_value=False,+ ),+ ):+ return resolve_suggested_reviewers_with_diagnostics(team.id, "acme/app", {"d" * 7: "introduced the bug"})++ @staticmethod+ def _active_owner_activity():+ return {+ "products/signals": [+ ContributorActivity(+ login="active-owner",+ name="Active Owner",+ commit_count=15,+ last_commit_at=timezone.now() - timedelta(days=2),+ last_commit_sha="c" * 7,+ last_commit_url="https://github.com/acme/app/commit/ccccccc",+ ),+ ]+ }++ def test_author_who_left_the_repository_is_replaced_by_an_active_owner(self, team):+ # The reported regression: a years-old commit still routed its author onto a report, and+ # the person had long since stopped committing.+ github = self._fake_github(+ "departed-author",+ GitHubAuthorLastCommit(last_commit_at=timezone.now() - timedelta(days=AUTHOR_ACTIVITY_WINDOW_DAYS + 30)),+ )++ resolution = self._resolve(team, github, self._active_owner_activity())++ assert [r.login for r in resolution.reviewers] == ["active-owner"]+ assert resolution.diagnostics.inactive_author_count == 1++ def test_the_only_candidate_leaving_names_its_cause(self, team):+ github = self._fake_github(+ "departed-author",+ GitHubAuthorLastCommit(last_commit_at=timezone.now() - timedelta(days=AUTHOR_ACTIVITY_WINDOW_DAYS + 1)),+ )++ resolution = self._resolve(team, github, {})++ assert resolution.reviewers == []+ assert resolution.diagnostics.outcome == "only_inactive_authors"+ assert resolution.diagnostics.blame_login_count == 1+ assert resolution.diagnostics.inactive_author_count == 1++ @pytest.mark.parametrize(+ ("case", "probe_result", "raises"),+ [+ ("still_committing", GitHubAuthorLastCommit(last_commit_at=timezone.now() - timedelta(days=200)), None),+ ("probe_could_not_answer", None, None),+ ("no_attributed_commit", GitHubAuthorLastCommit(last_commit_at=None), None),+ ("probe_rate_limited", None, GitHubRateLimitError("rate limited")),+ ],+ )+ def test_author_is_kept_unless_github_shows_them_gone(self, team, case, probe_result, raises):+ github = self._fake_github("blame-author", probe_result, raises=raises)++ resolution = self._resolve(team, github, self._active_owner_activity())++ assert "blame-author" in [r.login for r in resolution.reviewers]+ assert resolution.diagnostics.inactive_author_count == 0++ def test_cached_area_activity_spares_the_probe(self, team):+ probed: list[str] = []+ activity = {+ "products/signals": [+ ContributorActivity(+ login="blame-author",+ name="Blame Author",+ commit_count=8,+ last_commit_at=timezone.now() - timedelta(days=3),+ last_commit_sha="a" * 7,+ last_commit_url="https://github.com/acme/app/commit/aaaaaaa",+ ),+ ]+ }+ github = self._fake_github("blame-author", None, probed=probed)++ resolution = self._resolve(team, github, activity)++ assert [r.login for r in resolution.reviewers] == ["blame-author"]+ assert probed == []++ def test_a_stored_verdict_answers_for_a_second_report(self, team):+ probed: list[str] = []+ github = self._fake_github(+ "departed-author",+ GitHubAuthorLastCommit(last_commit_at=timezone.now() - timedelta(days=AUTHOR_ACTIVITY_WINDOW_DAYS + 30)),+ probed=probed,+ )++ first = self._resolve(team, github, self._active_owner_activity())+ second = self._resolve(team, github, self._active_owner_activity())++ assert probed == ["departed-author"]+ assert [r.login for r in first.reviewers] == [r.login for r in second.reviewers]+ assert second.diagnostics.inactive_author_count == 1++ def test_an_unattributed_account_is_asked_about_once(self, team):+ # GitHub answered, so the answer caches even though it keeps the author. Leaving the key+ # absent would re-ask on every later report for the same repository.+ probed: list[str] = []+ github = self._fake_github("blame-author", GitHubAuthorLastCommit(last_commit_at=None), probed=probed)++ first = self._resolve(team, github, self._active_owner_activity())+ second = self._resolve(team, github, self._active_owner_activity())++ assert probed == ["blame-author"]+ assert "blame-author" in [r.login for r in second.reviewers]+ assert first.diagnostics.inactive_author_count == 0+ assert second.diagnostics.inactive_author_count == 0++ def test_agent_proposed_candidates_are_not_probed(self, team):+ # Only commit evidence claims someone owns an area because they once wrote it. A manually+ # named or agent-proposed reviewer is an ownership statement in its own right, so this path+ # must keep its candidates and make no activity probe.+ probed: list[str] = []+ github = self._fake_github(+ "named-reviewer",+ GitHubAuthorLastCommit(last_commit_at=timezone.now() - timedelta(days=AUTHOR_ACTIVITY_WINDOW_DAYS + 30)),+ probed=probed,+ )++ with (+ patch(+ "products.signals.backend.report_generation.resolve_reviewers.GitHubIntegration.first_for_team_repository",+ return_value=github,+ ),+ patch(+ "products.signals.backend.report_generation.resolve_reviewers.get_area_activity",+ return_value={},+ ),+ patch(+ "products.signals.backend.report_generation.resolve_reviewers.repository_activity_needs_rebuild",+ return_value=False,+ ),+ ):+ ranked = rank_assignee_candidates(team.id, "acme/app", ["named-reviewer"], [])++ assert [r.login for r in ranked] == ["named-reviewer"]+ assert probed == []++@pytest.mark.django_dbclass TestResolveSuggestedReviewersDiagnostics:@pytest.mark.parametrize(diff --git a/products/signals/backend/test/test_reviewer_scenarios.py b/products/signals/backend/test/test_reviewer_scenarios.pyindex c27281bfeb0f..70a527f8f07f 100644--- a/products/signals/backend/test/test_reviewer_scenarios.py+++ b/products/signals/backend/test/test_reviewer_scenarios.py@@ -13,10 +13,11 @@ from datetime import timedeltaimport pytestfrom unittest.mock import patch+from django.core.cache import cachefrom django.utils import timezonefrom posthog.models import Organization, Team-from posthog.models.github_integration_base import GitHubCommitAttribution, GitHubCommitAuthor+from posthog.models.github_integration_base import GitHubAuthorLastCommit, GitHubCommitAttribution, GitHubCommitAuthorfrom products.signals.backend.report_generation.repo_activity import rebuild_repository_activityfrom products.signals.backend.report_generation.resolve_reviewers import (@@ -79,6 +80,16 @@ BLAME = {}+# What GitHub answers when asked for each persona's last commit anywhere in the repository.+# The founder's is years old, which is what marks them as gone rather than merely quiet.+LAST_COMMIT_DAYS_AGO = {+ FOUNDER[0].lower(): 1200,+ MAINTAINER[0].lower(): 1,+ NEW_JOINER[0].lower(): 2,+ NEIGHBOUR[0].lower(): 1,+}++class FakeBlameGitHub:def get_commit_author_info(self, repository, sha):login, _email = BLAME[sha]@@ -90,6 +101,18 @@ class FakeBlameGitHub:is_bot=login.endswith("[bot]"),)+ def get_author_last_commit(self, repository, login):+ days_ago = LAST_COMMIT_DAYS_AGO.get(login.lower())+ if days_ago is None:+ return GitHubAuthorLastCommit(last_commit_at=None)+ return GitHubAuthorLastCommit(last_commit_at=timezone.now() - timedelta(days=days_ago))++[email protected](autouse=True)+def clear_caches():+ # The resolver caches its author-activity verdicts, which would otherwise carry between tests.+ cache.clear()+@pytest.fixturedef organization():@@ -139,13 +162,14 @@ def _resolve(team, blame_shas: list[str]):@pytest.mark.django_dbclass TestReviewerScenarios:- def test_active_maintainer_outranks_departed_founder(self, seeded_team):+ def test_departed_founder_is_not_suggested(self, seeded_team):reviewers = _resolve(seeded_team, ["f" * 40, "e" * 40, "d" * 40])logins = [r.login for r in reviewers]- # The founder owns the two strongest blame commits but left months ago; the- # maintainer holds weaker blame and current area activity.- assert logins.index("mariusandra") < logins.index("departedfounder")+ # The founder owns the two strongest blame commits, but their last commit anywhere in+ # the repository is years old, so they cannot act on the report at all.+ assert "departedfounder" not in logins+ assert "mariusandra" in loginsdef test_mixed_case_blame_login_is_one_active_candidate(self, seeded_team):reviewers = _resolve(seeded_team, ["d" * 40])@@ -163,8 +187,7 @@ class TestReviewerScenarios:# Everyone in blame is gone; the area's actual current contributors fill in.assert "mariusandra" in loginsassert "new-joiner" in logins- if "departedfounder" in logins:- assert logins.index("mariusandra") < logins.index("departedfounder")+ assert "departedfounder" not in loginsdef test_bots_never_suggested(self, seeded_team):# The bot is both the busiest area committer and a blame author.