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): Limit breadth of area to nominate reviewers for (#75764)

Michael Matlokab03873554660
diff --git a/products/signals/backend/report_generation/resolve_reviewers.py b/products/signals/backend/report_generation/resolve_reviewers.py
index 3c59ec4906c8..6cf7560b0a44 100644
--- a/products/signals/backend/report_generation/resolve_reviewers.py
+++ b/products/signals/backend/report_generation/resolve_reviewers.py
@@ -47,6 +47,11 @@ STALE_BLAME_MULTIPLIER = 0.15
# Caps activity-only fallbacks below blame candidates: they only win when every blame author is stale.
ACTIVITY_ONLY_SCORE_CAP = 0.25
ACTIVITY_BONUS_SATURATION_COMMITS = 10
+# Above this many recent contributors, an area is a crowd rather than an ownership signal.
+# Sized above a product-sized area and below a repo-sized one; a small team's whole repository
+# stays under it, which is intended. Must stay under MAX_CONTRIBUTORS_PER_AREA, which truncates
+# the list this counts.
+MAX_CONTRIBUTORS_FOR_OWNERSHIP = 30
GitHubLoginFieldLookup = Literal[
"extra_data__login",
"config__github_user__login",
@@ -232,16 +237,6 @@ def _rank_scored_candidates(
) -> list[_ResolvedReviewer]:
scores = _score_candidates(login_weights, activity_by_login)
- # Activity-only owners are a last resort: only surface them when no weighted (blame/agent)
- # candidate is still active in the area, so we don't pad noise next to a live reviewer.
- # Recency, not map membership, decides "active" — the cached area map can be stale.
- def _weighted_candidate_still_active(login: str) -> bool:
- activity = activity_by_login.get(login)
- return activity is not None and activity.days_since_last_commit < ACTIVITY_WINDOW_DAYS
-
- if any(_weighted_candidate_still_active(login) for login in login_weights):
- scores = {login: score for login, score in scores.items() if login in login_weights}
-
def rank_key(item: tuple[str, float]) -> tuple[float, int, str]:
login, score = item
activity = activity_by_login.get(login)
@@ -288,6 +283,10 @@ class _AreaContributor:
last_commit_sha: str
last_commit_url: str
area: str # the area of the evidence (freshest) commit, for evidence wording
+ # True if *any* area this contributor was drawn from is focused enough to count as owned.
+ # Not tied to the evidence area: a crowded area still supplies recency, it just proposes
+ # nobody, and it must not cancel a claim earned in a focused one.
+ is_likely_owner_of_area: bool
def _relevant_area_activity(
@@ -300,8 +299,9 @@ def _relevant_area_activity(
Cache-only; a missing or stale map schedules an async rebuild and this report falls
back to whatever is cached (possibly nothing). An area with no active contributors
falls back up its chain (parent directory, then repo-wide) — someone active nearby
- beats nobody. Returns an empty dict when nothing is known — callers must treat that
- as "no signal", not "nobody is active".
+ beats nobody. Levels above ``MAX_CONTRIBUTORS_FOR_OWNERSHIP`` contributors still supply
+ recency, but imply no ownership. Returns an empty dict when nothing is known — callers
+ must treat that as "no signal", not "nobody is active".
"""
areas = areas_for_paths(touched_paths)
if not areas:
@@ -320,9 +320,10 @@ def _relevant_area_activity(
if level is None or level in used_levels:
continue
used_levels.add(level)
+ is_likely_owner_of_area = len(activity_by_area[level]) <= MAX_CONTRIBUTORS_FOR_OWNERSHIP
for contributor in activity_by_area[level]:
existing = merged.get(contributor.login)
- merged[contributor.login] = _merge_contributor(existing, contributor, level, now)
+ merged[contributor.login] = _merge_contributor(existing, contributor, level, now, is_likely_owner_of_area)
return merged
@@ -341,6 +342,7 @@ def _merge_contributor(
incoming: ContributorActivity,
area: str,
now: datetime,
+ is_likely_owner_of_area: bool,
) -> _AreaContributor:
days_since = max(0.0, (now - incoming.last_commit_at).total_seconds() / 86400)
if existing is None:
@@ -351,9 +353,11 @@ def _merge_contributor(
last_commit_sha=incoming.last_commit_sha,
last_commit_url=incoming.last_commit_url,
area=area,
+ is_likely_owner_of_area=is_likely_owner_of_area,
)
# Evidence follows the freshest commit, so sha/url/area always agree with
- # days_since_last_commit.
+ # 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
return _AreaContributor(
name=existing.name or incoming.name,
@@ -362,6 +366,7 @@ def _merge_contributor(
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,
+ is_likely_owner_of_area=existing.is_likely_owner_of_area or is_likely_owner_of_area,
)
@@ -378,32 +383,50 @@ def _recency_multiplier(days_since_last_commit: float | None) -> float:
return 1.0 - progress * (1.0 - RECENCY_DECAY_FLOOR)
+def _has_live_reviewer(
+ login_weights: Counter[str],
+ activity_by_login: dict[str, _AreaContributor],
+) -> bool:
+ """Whether a candidate with a blame or agent-proposed weight is still committing in the report's areas.
+
+ Recency decides, not membership in the cached map: it is served while a rebuild is
+ scheduled, so an entry can have aged past the window.
+ """
+ for login in login_weights:
+ activity = activity_by_login.get(login)
+ if activity is not None and activity.days_since_last_commit < ACTIVITY_WINDOW_DAYS:
+ return True
+ return False
+
+
def _score_candidates(
login_weights: Counter[str],
activity_by_login: dict[str, _AreaContributor],
) -> dict[str, float]:
"""Blend blame weights with area recency; add capped activity-only fallbacks.
- Invariants: a freshly-active area contributor always outranks a blame author who is
- gone from the area (their base starts above the stale floor), and never outranks the
- *top-weighted* blame author while that author is active in the window (the cap sits
- below the decay floor). Lower-weighted active blame authors can still be outranked by
- a very active area owner — deliberate: weight-1 blame is one marginal commit, not a
- stronger claim than sustained area ownership. With no activity data at all, blame
- weights pass through unchanged (legacy behavior).
+ Blame and agent-proposed weights decay toward the stale floor as their author's last
+ commit in the area recedes. Area contributors are proposed in their own right only as a
+ last resort: no live reviewer, and an area focused enough to imply ownership. Their base
+ starts above the stale floor, so they outrank authors who have left the area. With no
+ activity data at all, blame weights pass through unchanged (legacy behavior).
"""
if not activity_by_login:
return {login: float(weight) for login, weight in login_weights.items()}
- max_blame_weight = float(max(login_weights.values(), default=0)) or 1.0
scores: dict[str, float] = {}
for login, weight in login_weights.items():
activity = activity_by_login.get(login)
multiplier = _recency_multiplier(activity.days_since_last_commit if activity else None)
scores[login] = float(weight) * multiplier
+ if _has_live_reviewer(login_weights, activity_by_login):
+ return scores
+
+ # If not, nobody the report points at is around to review, so fall back to area contributors.
+ max_blame_weight = float(max(login_weights.values(), default=0)) or 1.0
for login, activity in activity_by_login.items():
- if login in scores:
+ if login in scores or not activity.is_likely_owner_of_area:
continue
saturation = min(activity.commit_count, ACTIVITY_BONUS_SATURATION_COMMITS) / ACTIVITY_BONUS_SATURATION_COMMITS
base = STALE_BLAME_MULTIPLIER + (ACTIVITY_ONLY_SCORE_CAP - STALE_BLAME_MULTIPLIER) * saturation
diff --git a/products/signals/backend/test/test_resolve_reviewers.py b/products/signals/backend/test/test_resolve_reviewers.py
index e8b51ef250f0..40878ac5c6ba 100644
--- a/products/signals/backend/test/test_resolve_reviewers.py
+++ b/products/signals/backend/test/test_resolve_reviewers.py
@@ -18,6 +18,7 @@ from posthog.models.user_integration import UserIntegration
from products.signals.backend.models import SignalRepositoryAreaActivity
from products.signals.backend.report_generation.repo_activity import ACTIVITY_WINDOW_DAYS, ContributorActivity
from products.signals.backend.report_generation.resolve_reviewers import (
+ MAX_CONTRIBUTORS_FOR_OWNERSHIP,
RECENCY_DECAY_FLOOR,
RECENCY_FULL_WEIGHT_DAYS,
STALE_BLAME_MULTIPLIER,
@@ -132,6 +133,23 @@ def test_skips_users_outside_organization(organization, team):
# ── recency-aware scoring ─────────────────────────────────────────────────────
+def _area_contributor(
+ *,
+ days_since_last_commit: float,
+ commit_count: int = 12,
+ is_likely_owner_of_area: bool = True,
+) -> _AreaContributor:
+ return _AreaContributor(
+ name=None,
+ commit_count=commit_count,
+ days_since_last_commit=days_since_last_commit,
+ last_commit_sha="a" * 7,
+ last_commit_url="https://github.com/acme/app/commit/aaaaaaa",
+ area="products/signals",
+ is_likely_owner_of_area=is_likely_owner_of_area,
+ )
+
+
class TestRecencyScoring:
def test_recency_multiplier_shape(self):
assert _recency_multiplier(None) == STALE_BLAME_MULTIPLIER
@@ -151,106 +169,87 @@ class TestRecencyScoring:
def test_stale_blame_author_loses_to_active_area_contributor(self):
weights = Counter({"old-timer": 10})
- activity = {
- "active-owner": _AreaContributor(
- name="Active Owner",
- commit_count=12,
- days_since_last_commit=2,
- last_commit_sha="a" * 7,
- last_commit_url="https://github.com/acme/app/commit/aaaaaaa",
- area="products/signals",
- ),
- }
+ activity = {"active-owner": _area_contributor(days_since_last_commit=2)}
scores = _score_candidates(weights, activity)
# old-timer authored the blame commits but has no recent commits in the area.
assert scores["active-owner"] > scores["old-timer"]
- def test_recently_active_blame_author_beats_activity_only_contributor(self):
- def contributor(days_since: float) -> _AreaContributor:
- return _AreaContributor(
- name=None,
- commit_count=12,
- days_since_last_commit=days_since,
- last_commit_sha="b" * 7,
- last_commit_url="https://github.com/acme/app/commit/bbbbbbb",
- area="products/signals",
- )
-
+ def test_active_blame_author_suppresses_activity_only_candidates(self):
weights = Counter({"active-author": 10})
activity = {
- "active-author": contributor(days_since=5),
- "bystander": contributor(days_since=1),
+ "active-author": _area_contributor(days_since_last_commit=5),
+ "bystander": _area_contributor(days_since_last_commit=1),
}
scores = _score_candidates(weights, activity)
- assert scores["active-author"] > scores["bystander"]
+ # The blame author is the live reviewer, so the fresher bystander is not proposed.
+ assert set(scores) == {"active-author"}
def test_lightly_active_contributor_beats_stale_blame_even_with_tiny_blame_weight(self):
# Regression: a single old blame commit (weight 1) used to crush activity-only
# candidates via the cap, so the long-gone author still won the assign.
weights = Counter({"long-gone": 1})
+ activity = {"light-owner": _area_contributor(days_since_last_commit=1, commit_count=3)}
+
+ scores = _score_candidates(weights, activity)
+
+ assert scores["light-owner"] > scores["long-gone"]
+
+ def test_crowded_area_nominates_nobody_but_still_decays_blame(self):
+ weights = Counter({"old-timer": 10})
+ # The blame author is past the window, so only the crowded area keeps the stranger out.
activity = {
- "light-owner": _AreaContributor(
- name=None,
- commit_count=3,
- days_since_last_commit=1,
- last_commit_sha="c" * 7,
- last_commit_url="",
- area="posthog/migrations",
+ "old-timer": _area_contributor(
+ days_since_last_commit=ACTIVITY_WINDOW_DAYS + 5, is_likely_owner_of_area=False
),
+ "prolific-stranger": _area_contributor(days_since_last_commit=1, is_likely_owner_of_area=False),
}
scores = _score_candidates(weights, activity)
- assert scores["light-owner"] > scores["long-gone"]
+ assert set(scores) == {"old-timer"}
+ assert scores["old-timer"] < 10.0
def test_half_stale_bystander_does_not_beat_stale_blame(self):
weights = Counter({"long-gone": 1})
- activity = {
- "half-stale": _AreaContributor(
- name=None,
- commit_count=3,
- days_since_last_commit=70,
- last_commit_sha="c" * 7,
- last_commit_url="",
- area="posthog/migrations",
- ),
- }
+ activity = {"half-stale": _area_contributor(days_since_last_commit=70, commit_count=3)}
scores = _score_candidates(weights, activity)
assert scores["long-gone"] >= scores["half-stale"]
+def _seed_area(team: Team, area: str, entries: list[tuple[str, int, int]]) -> None:
+ """Seed one refreshed area row from (login, commit_count, days_ago) entries."""
+ with team_scope(team.id, canonical=True):
+ SignalRepositoryAreaActivity.objects.create(
+ team=team,
+ repository="acme/app",
+ area=area,
+ contributors=[
+ {
+ "login": login,
+ "name": login.title(),
+ "commit_count": count,
+ "last_commit_at": (timezone.now() - timedelta(days=days_ago)).isoformat(),
+ "last_commit_sha": "a" * 7,
+ "last_commit_url": "https://github.com/acme/app/commit/aaaaaaa",
+ }
+ for login, count, days_ago in entries
+ ],
+ refreshed_at=timezone.now(),
+ )
+
+
@pytest.mark.django_db
class TestAreaWalkUp:
def test_empty_area_falls_back_to_parent_then_repo_wide(self, team):
- def _row(area: str, logins: list[str]) -> None:
- SignalRepositoryAreaActivity.objects.create(
- team=team,
- repository="acme/app",
- area=area,
- contributors=[
- {
- "login": login,
- "name": login.title(),
- "commit_count": 3,
- "last_commit_at": timezone.now().isoformat(),
- "last_commit_sha": "a" * 7,
- "last_commit_url": "https://github.com/acme/app/commit/aaaaaaa",
- }
- for login in logins
- ],
- refreshed_at=timezone.now(),
- )
-
- with team_scope(team.id, canonical=True):
- _row("products/dead", []) # refreshed, nobody active
- _row("products", ["parent-owner"])
- _row("*", ["repo-regular"])
+ _seed_area(team, "products/dead", []) # refreshed, nobody active
+ _seed_area(team, "products", [("parent-owner", 3, 0)])
+ _seed_area(team, "*", [("repo-regular", 3, 0)])
with patch("products.signals.backend.report_generation.resolve_reviewers._schedule_activity_rebuild"):
merged = _relevant_area_activity(team.id, "acme/app", ["products/dead/models.py"])
@@ -266,31 +265,44 @@ class TestAreaWalkUp:
assert set(merged) == {"repo-regular"}
+ @pytest.mark.parametrize(
+ ("contributor_count", "is_likely_owner_of_area"),
+ [(MAX_CONTRIBUTORS_FOR_OWNERSHIP, True), (MAX_CONTRIBUTORS_FOR_OWNERSHIP + 1, False)],
+ )
+ def test_ownership_needs_a_focused_area(self, team, contributor_count, is_likely_owner_of_area):
+ _seed_area(team, "products/tasks", [(f"dev-{i}", 3, 0) for i in range(contributor_count)])
-class TestRankAssigneeCandidates:
- def _seed_area(self, team, area: str, entries: list[tuple[str, int, int]]) -> None:
- with team_scope(team.id, canonical=True):
- SignalRepositoryAreaActivity.objects.create(
- team=team,
- repository="acme/app",
- area=area,
- contributors=[
- {
- "login": login,
- "name": login.title(),
- "commit_count": count,
- "last_commit_at": (timezone.now() - timedelta(days=days_ago)).isoformat(),
- "last_commit_sha": "a" * 7,
- "last_commit_url": "https://github.com/acme/app/commit/aaaaaaa",
- }
- for login, count, days_ago in entries
- ],
- refreshed_at=timezone.now(),
+ with patch("products.signals.backend.report_generation.resolve_reviewers._schedule_activity_rebuild"):
+ merged = _relevant_area_activity(team.id, "acme/app", ["products/tasks/management/commands/demo.py"])
+
+ assert len(merged) == contributor_count
+ assert all(contributor.is_likely_owner_of_area is is_likely_owner_of_area for contributor in merged.values())
+
+ def test_fresher_crowded_commit_does_not_erase_focused_area_ownership(self, team):
+ _seed_area(team, "products/signals", [("alice", 4, 10)])
+ _seed_area(
+ team,
+ "*",
+ [("alice", 9, 1), *[(f"dev-{i}", 3, 2) for i in range(MAX_CONTRIBUTORS_FOR_OWNERSHIP)]],
+ )
+
+ with patch("products.signals.backend.report_generation.resolve_reviewers._schedule_activity_rebuild"):
+ merged = _relevant_area_activity(
+ team.id, "acme/app", ["products/signals/backend/models.py", "bin/deploy.sh"]
)
+ # Evidence still follows alice's freshest commit, which landed repo-wide...
+ assert merged["alice"].area == "*"
+ assert merged["alice"].days_since_last_commit == pytest.approx(1, abs=0.01)
+ # ...but the claim she earned in products/signals survives it.
+ assert merged["alice"].is_likely_owner_of_area
+ assert not merged["dev-0"].is_likely_owner_of_area
+
+
+class TestRankAssigneeCandidates:
def test_stale_agent_candidate_demoted_below_active_area_owner(self, team):
- self._seed_area(team, "products/signals", [("active-owner", 12, 2)])
+ _seed_area(team, "products/signals", [("active-owner", 12, 2)])
with patch("products.signals.backend.report_generation.resolve_reviewers._schedule_activity_rebuild"):
ranked = rank_assignee_candidates(
@@ -304,7 +316,7 @@ class TestRankAssigneeCandidates:
assert ranked[1].commits == []
def test_active_agent_candidate_keeps_top_spot(self, team):
- self._seed_area(team, "products/signals", [("agent-pick", 5, 3), ("bystander", 12, 1)])
+ _seed_area(team, "products/signals", [("agent-pick", 5, 3), ("bystander", 12, 1)])
with patch("products.signals.backend.report_generation.resolve_reviewers._schedule_activity_rebuild"):
ranked = rank_assignee_candidates(
@@ -316,7 +328,7 @@ class TestRankAssigneeCandidates:
assert [candidate.login for candidate in ranked] == ["agent-pick"]
def test_paths_alone_yield_activity_candidates(self, team):
- self._seed_area(team, "products/signals", [("area-owner", 8, 1)])
+ _seed_area(team, "products/signals", [("area-owner", 8, 1)])
with patch("products.signals.backend.report_generation.resolve_reviewers._schedule_activity_rebuild"):
ranked = rank_assignee_candidates(team.id, "acme/app", [], ["products/signals/backend/models.py"])