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.

perf(signals): index suggested reviewers for the inbox filter (#104619)

posthog[bot]9e8156383053
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index d8041ffa67d6..d376521783f4 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -351,6 +351,7 @@ rules:
|SignalReportAssignment
|SignalReportRefund
|SignalReportSlackThread
+ |SignalReportSuggestedReviewer
|SignalReportTask
|SignalReportTrackerIssue
|SignalRepositoryAreaActivity
@@ -769,6 +770,7 @@ rules:
|SignalReportAssignment
|SignalReportRefund
|SignalReportSlackThread
+ |SignalReportSuggestedReviewer
|SignalReportTask
|SignalReportTrackerIssue
|SignalRepositoryAreaActivity
diff --git a/posthog/test/repo_invariants/setup_receivers_baseline.txt b/posthog/test/repo_invariants/setup_receivers_baseline.txt
index 15cb48eb277f..783cd6f048ae 100644
--- a/posthog/test/repo_invariants/setup_receivers_baseline.txt
+++ b/posthog/test/repo_invariants/setup_receivers_baseline.txt
@@ -102,6 +102,7 @@ post_delete:products.managed_warehouse.backend.models._observe_duckgres_server_d
post_delete:products.replay_vision.backend.media_expiry.expire_media_asset
post_delete:products.signals.backend.receivers.mark_scout_suggestions_stale_on_fleet_change
post_delete:products.signals.backend.receivers.reconcile_report_embedding_on_verdict_deleted
+post_delete:products.signals.backend.receivers.sync_suggested_reviewer_index_on_delete
post_delete:products.signals.backend.receivers.tombstone_report_embedding_on_hard_delete
post_delete:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_change
post_delete:products.surveys.backend.models.survey_changed
@@ -221,6 +222,7 @@ post_save:products.signals.backend.receivers.reconcile_report_embedding_on_verdi
post_save:products.signals.backend.receivers.schedule_handover_for_report_change
post_save:products.signals.backend.receivers.schedule_handover_for_work_change
post_save:products.signals.backend.receivers.schedule_implementation_handover
+post_save:products.signals.backend.receivers.sync_suggested_reviewer_index_on_save
post_save:products.signals.backend.receivers.sync_task_run_pr_to_assignments
post_save:products.signals.backend.receivers.tombstone_report_embedding_on_delete
post_save:products.slack_app.backend.signals.invalidate_repo_list_on_user_github_change
diff --git a/products/signals/backend/management/commands/backfill_suggested_reviewer_index.py b/products/signals/backend/management/commands/backfill_suggested_reviewer_index.py
new file mode 100644
index 000000000000..ee2036724cb3
--- /dev/null
+++ b/products/signals/backend/management/commands/backfill_suggested_reviewer_index.py
@@ -0,0 +1,46 @@
+from argparse import ArgumentParser
+from collections.abc import Iterator
+from typing import cast
+
+from django.core.management.base import BaseCommand
+
+from products.signals.backend.models import SignalReportArtefact
+from products.signals.backend.suggested_reviewer_index import sync_suggested_reviewer_index
+
+
+def backfill_suggested_reviewer_index(*, team_id: int, after: str | None, batch_size: int) -> Iterator[tuple[int, str]]:
+ while True:
+ artefacts = SignalReportArtefact.objects.filter(
+ team_id=team_id, type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS
+ ).order_by("report_id")
+ if after:
+ artefacts = artefacts.filter(report_id__gt=after)
+ report_ids = list(artefacts.values_list("report_id", flat=True).distinct()[:batch_size])
+ if not report_ids:
+ return
+ for report_id in report_ids:
+ sync_suggested_reviewer_index(team_id=team_id, report_id=str(report_id))
+ after = str(report_ids[-1])
+ yield len(report_ids), after
+
+
+class Command(BaseCommand):
+ help = (
+ "Rebuild the indexed suggested-reviewer rows from the reviewer artefact log, for every "
+ "report in a project that has one. Each report is rewritten from its current artefact, so "
+ "this both backfills reports written before the index existed and repairs a report whose "
+ "rows drifted. Safe to rerun."
+ )
+
+ def add_arguments(self, parser: ArgumentParser) -> None:
+ parser.add_argument("--team-id", type=int, required=True)
+ parser.add_argument("--after", help="Resume after this report UUID.")
+ parser.add_argument("--batch-size", type=int, default=100)
+
+ def handle(self, *args: object, **options: object) -> None:
+ for count, cursor in backfill_suggested_reviewer_index(
+ team_id=cast(int, options["team_id"]),
+ after=cast(str | None, options["after"]),
+ batch_size=max(1, min(cast(int, options["batch_size"]), 1000)),
+ ):
+ self.stdout.write(f"Rebuilt {count} reports; resume with --after {cursor}")
diff --git a/products/signals/backend/migrations/0150_signalreportsuggestedreviewer.py b/products/signals/backend/migrations/0150_signalreportsuggestedreviewer.py
new file mode 100644
index 000000000000..e5b306cf6cc9
--- /dev/null
+++ b/products/signals/backend/migrations/0150_signalreportsuggestedreviewer.py
@@ -0,0 +1,81 @@
+# Generated by Django 5.2.17 on 2026-09-22 16:45
+
+import django.db.models.manager
+import django.db.models.deletion
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1374_teamheatmapconfig_capture_enforcement_started_at_and_more"),
+ ("signals", "0149_signalteamconfig_pull_request_label_and_more"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="SignalReportSuggestedReviewer",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("user_uuid", models.UUIDField(blank=True, null=True)),
+ (
+ "github_login",
+ models.CharField(blank=True, max_length=255, null=True),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "artefact",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="signals.signalreportartefact",
+ ),
+ ),
+ (
+ "report",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="suggested_reviewer_index",
+ to="signals.signalreport",
+ ),
+ ),
+ (
+ "team",
+ models.ForeignKey(
+ db_constraint=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to="posthog.team",
+ ),
+ ),
+ ],
+ options={
+ "verbose_name": "Signal report suggested reviewer",
+ "verbose_name_plural": "Signal report suggested reviewers",
+ "default_manager_name": "all_teams",
+ "indexes": [
+ models.Index(
+ fields=["team", "user_uuid", "report"],
+ name="signals_sugg_rev_uuid_idx",
+ ),
+ models.Index(
+ fields=["team", "github_login", "report"],
+ name="signals_sugg_rev_login_idx",
+ ),
+ models.Index(fields=["report"], name="signals_sugg_rev_report_idx"),
+ ],
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ ]
diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txt
index 6ba6ae4976f5..4884601e9875 100644
--- a/products/signals/backend/migrations/max_migration.txt
+++ b/products/signals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0149_signalteamconfig_pull_request_label_and_more
+0150_signalreportsuggestedreviewer
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 3d51f8c8d025..185597fdd739 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1724,6 +1724,45 @@ class SignalReportArtefact(UUIDModel):
self._schedule_autostart_reevaluation(team_id=self.team_id, report_id=str(self.report_id))
+class SignalReportSuggestedReviewer(TeamScopedRootMixin, UUIDModel):
+ """One reviewer identity from a report's current `suggested_reviewers` artefact, in columns.
+
+ The artefact log stays canonical. It stores the reviewer list as JSON in a `TextField`, so
+ asking "which reports name this person?" costs a jsonb cast for every reviewer artefact the
+ team ever wrote, and no index can serve it. The inbox asks that question in its default scope,
+ on the list and on each section count, so the cost grew with the log rather than with the page.
+ These rows answer the same question from an index. A report has one row per identity in its
+ newest reviewers artefact, and the rows are rewritten whenever that artefact changes.
+ """
+
+ # See SignalReportRefund.all_teams for rationale.
+ all_teams = models.Manager() # noqa: DJ012
+
+ team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, db_constraint=False, related_name="+")
+ report = models.ForeignKey(SignalReport, on_delete=models.CASCADE, related_name="suggested_reviewer_index")
+ # The artefact these rows were derived from, so a reader can tell which version they reflect.
+ artefact = models.ForeignKey(SignalReportArtefact, on_delete=models.CASCADE, related_name="+")
+ # An entry identifies its person by uuid, by login, or by both — one of the two is always set.
+ user_uuid = models.UUIDField(null=True, blank=True)
+ # Lowercased on write: GitHub logins are case-insensitive, and both readers look them up with
+ # `login.lower()`.
+ github_login = models.CharField(max_length=255, null=True, blank=True)
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ default_manager_name = "all_teams"
+ indexes = [
+ # The two reviewer lookups, one per identity kind. `report` is in the index so the
+ # list filter reads the report ids without touching the heap.
+ models.Index(fields=["team", "user_uuid", "report"], name="signals_sugg_rev_uuid_idx"),
+ models.Index(fields=["team", "github_login", "report"], name="signals_sugg_rev_login_idx"),
+ # Rewriting a report's rows deletes what is there first.
+ models.Index(fields=["report"], name="signals_sugg_rev_report_idx"),
+ ]
+ verbose_name = "Signal report suggested reviewer"
+ verbose_name_plural = "Signal report suggested reviewers"
+
+
class SignalReportTask(UUIDModel):
"""Legacy task↔report link. Still the auto-start idempotency gate (an `implementation` row),
but being migrated out in favour of `task_run` artefacts.
diff --git a/products/signals/backend/receivers.py b/products/signals/backend/receivers.py
index cdc11f8f72e6..62a4b4051ea9 100644
--- a/products/signals/backend/receivers.py
+++ b/products/signals/backend/receivers.py
@@ -29,6 +29,7 @@ from products.signals.backend.report_embeddings import (
render_report_documents,
)
from products.signals.backend.scout_harness.suggestions import mark_stale_if_fleet_changed
+from products.signals.backend.suggested_reviewer_index import sync_suggested_reviewer_index
from products.tasks.backend.facade.task_run_signals import connect_task_run_post_save
if TYPE_CHECKING:
@@ -860,3 +861,37 @@ def mark_scout_suggestions_stale_on_fleet_change(sender: Any, instance: Any, **k
mark_stale_if_fleet_changed(instance.team_id)
except Exception:
logger.warning("scout_suggestions: failed to mark batch stale", team_id=instance.team_id, exc_info=True)
+
+
+@receiver(post_save, sender=SignalReportArtefact)
+def sync_suggested_reviewer_index_on_save(
+ sender: type[SignalReportArtefact],
+ instance: SignalReportArtefact,
+ created: bool,
+ **kwargs: Any,
+) -> None:
+ """Rebuild the report's reviewer index whenever a reviewers row is written.
+
+ Not gated on `created`: `update_content` edits a reviewers row in place, and editing the
+ current row changes the report's reviewer set.
+ """
+ if instance.type != SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS:
+ return
+ sync_suggested_reviewer_index(team_id=instance.team_id, report_id=str(instance.report_id))
+
+
+@receiver(post_delete, sender=SignalReportArtefact)
+def sync_suggested_reviewer_index_on_delete(
+ sender: type[SignalReportArtefact],
+ instance: SignalReportArtefact,
+ origin: Any = None,
+ **kwargs: Any,
+) -> None:
+ """Deleting the current reviewers row reverts the set to the previous one, or to none.
+
+ Skipped for a cascade: the index rows go down with the report that owns them, so rebuilding
+ per artefact on the way down would only spend queries to reach the same empty state.
+ """
+ if instance.type != SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS or not _deleted_directly(origin):
+ return
+ sync_suggested_reviewer_index(team_id=instance.team_id, report_id=str(instance.report_id))
diff --git a/products/signals/backend/suggested_reviewer_index.py b/products/signals/backend/suggested_reviewer_index.py
new file mode 100644
index 000000000000..5f34bd58c487
--- /dev/null
+++ b/products/signals/backend/suggested_reviewer_index.py
@@ -0,0 +1,123 @@
+"""Keep `SignalReportSuggestedReviewer` in step with the reviewer artefact log, and read it.
+
+The artefact log is canonical and stays that way. This module owns the derived, indexed copy of
+one question it answers slowly — "which reports name this person as a reviewer?" — plus the two
+matching rules the inbox reads it with.
+"""
+
+from __future__ import annotations
+
+import uuid as uuid_module
+
+from django.db import transaction
+from django.db.models import Q, QuerySet
+
+import structlog
+from pydantic import ValidationError
+
+from products.signals.backend.artefact_schemas import SuggestedReviewers
+from products.signals.backend.models import SignalReportArtefact, SignalReportSuggestedReviewer
+
+logger = structlog.get_logger(__name__)
+
+
+# A tie needs at most a handful of rows, and a report's reviewer history is short, so reading the
+# newest few and grouping in Python costs one query where a timestamp lookup would cost two.
+_TIE_SCAN_LIMIT = 20
+
+
+def _current_reviewer_artefacts(team_id: int, report_id: str) -> list[SignalReportArtefact]:
+ """The report's live reviewer artefacts: the newest row, plus any row written at the same
+ instant. The predicate this replaces ("no newer row of this type exists") also kept every row
+ at the maximum timestamp, so a tie must stay a union rather than become a pick.
+ """
+ newest_first = list(
+ SignalReportArtefact.objects.filter(
+ team_id=team_id,
+ report_id=report_id,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ ).order_by("-created_at")[:_TIE_SCAN_LIMIT]
+ )
+ if not newest_first:
+ return []
+ latest = newest_first[0].created_at
+ return [artefact for artefact in newest_first if artefact.created_at == latest]
+
+
+def _rows_for_artefact(artefact: SignalReportArtefact) -> list[SignalReportSuggestedReviewer]:
+ try:
+ entries = SuggestedReviewers.model_validate_json(artefact.content).root
+ except ValidationError:
+ # A row the current schema cannot read names nobody. The artefact still holds the truth,
+ # so a later edit that parses restores the index.
+ logger.warning(
+ "signals_suggested_reviewer_index_unparseable_artefact",
+ team_id=artefact.team_id,
+ report_id=str(artefact.report_id),
+ artefact_id=str(artefact.id),
+ )
+ return []
+ rows: list[SignalReportSuggestedReviewer] = []
+ seen: set[tuple[str | None, str | None]] = set()
+ for entry in entries:
+ login = entry.github_login.lower() if entry.github_login else None
+ identity = (entry.user_uuid, login)
+ if identity in seen:
+ continue
+ seen.add(identity)
+ rows.append(
+ SignalReportSuggestedReviewer(
+ team_id=artefact.team_id,
+ report_id=artefact.report_id,
+ artefact_id=artefact.id,
+ user_uuid=uuid_module.UUID(entry.user_uuid) if entry.user_uuid else None,
+ github_login=login,
+ )
+ )
+ return rows
+
+
+def sync_suggested_reviewer_index(*, team_id: int, report_id: str) -> None:
+ """Rewrite a report's index rows from its current reviewer artefacts.
+
+ Called from every path that can change which artefact is current — an append, an edit in
+ place, a delete — so the index never needs a reader to fall back to the log.
+ """
+ rows: list[SignalReportSuggestedReviewer] = []
+ for artefact in _current_reviewer_artefacts(team_id, report_id):
+ rows.extend(_rows_for_artefact(artefact))
+ with transaction.atomic():
+ SignalReportSuggestedReviewer.objects.for_team(team_id).filter(report_id=report_id).delete()
+ if rows:
+ SignalReportSuggestedReviewer.objects.for_team(team_id).bulk_create(rows)
+
+
+def _identity_filter(user_uuids: list[str], github_logins: list[str], *, logins_match_unidentified_only: bool) -> Q:
+ identity = Q(user_uuid__in=user_uuids) if user_uuids else Q(pk__in=[])
+ if github_logins:
+ login_match = Q(github_login__in=[login.lower() for login in github_logins])
+ if logins_match_unidentified_only:
+ login_match &= Q(user_uuid__isnull=True)
+ identity |= login_match
+ return identity
+
+
+def report_ids_naming_reviewers(
+ *,
+ team_id: int,
+ user_uuids: list[str],
+ github_logins: list[str],
+ logins_match_unidentified_only: bool,
+) -> QuerySet:
+ """Report ids whose current reviewer set names any of these identities.
+
+ `logins_match_unidentified_only` keeps the two callers' rules apart. The list filter resolves
+ a login from the requested uuid, so a login may only stand in for an entry that carries no
+ uuid of its own — otherwise a login GitHub has since reassigned would route another person's
+ reports. The "is this me?" annotation has the user's own login in hand and matches it either
+ way.
+ """
+ identity = _identity_filter(
+ user_uuids, github_logins, logins_match_unidentified_only=logins_match_unidentified_only
+ )
+ return SignalReportSuggestedReviewer.objects.for_team(team_id).filter(identity).values("report_id")
diff --git a/products/signals/backend/test/test_signal_report_artefact_api.py b/products/signals/backend/test/test_signal_report_artefact_api.py
index d4af68ad1f95..c74303d505ea 100644
--- a/products/signals/backend/test/test_signal_report_artefact_api.py
+++ b/products/signals/backend/test/test_signal_report_artefact_api.py
@@ -4,6 +4,8 @@ import uuid
from posthog.test.base import APIBaseTest
from unittest.mock import AsyncMock, patch
+from django.core.management import call_command
+
from parameterized import parameterized
from rest_framework import status
from social_django.models import UserSocialAuth
@@ -30,6 +32,7 @@ from products.signals.backend.models import (
SignalReport,
SignalReportArtefact,
SignalReportAssignment,
+ SignalReportSuggestedReviewer,
)
from products.signals.backend.reviewer_correction_notes import ForwardedCorrectionNotes
@@ -86,6 +89,11 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
_attach_github_login(user, github_login, uid=f"gh-{email}")
return user
+ def _reviewer_filter_matches(self, report: SignalReport, reviewer: User) -> bool:
+ response = self.client.get(f"/api/projects/{self.team.id}/signals/reports/?suggested_reviewers={reviewer.uuid}")
+ assert response.status_code == status.HTTP_200_OK
+ return str(report.id) in {row["id"] for row in response.json()["results"]}
+
def _latest_reviewers(self, report: SignalReport) -> list:
# suggested_reviewers is append-only: the current reviewers are the latest row's content.
artefact = (
@@ -950,6 +958,34 @@ class TestSignalReportArtefactViewSet(APIBaseTest):
assert str(report.id) in {row["id"] for row in original_response.json()["results"]}
assert str(report.id) not in {row["id"] for row in replacement_response.json()["results"]}
+ def test_filter_follows_the_reviewers_row_that_survives_a_delete(self):
+ alice = self._create_org_member("[email protected]", github_login="alice")
+ bob = self._create_org_member("[email protected]", github_login="bob")
+ report = self._create_report()
+ self._create_artefact(report, content=[{"user_uuid": str(alice.uuid)}])
+ current = self._create_artefact(report, content=[{"user_uuid": str(bob.uuid)}])
+
+ assert self._reviewer_filter_matches(report, bob)
+ assert not self._reviewer_filter_matches(report, alice)
+
+ delete_response = self.client.delete(self._detail_url(str(report.id), str(current.id)))
+ assert delete_response.status_code == status.HTTP_204_NO_CONTENT
+
+ assert self._reviewer_filter_matches(report, alice)
+ assert not self._reviewer_filter_matches(report, bob)
+
+ def test_backfill_command_restores_the_filter_for_a_report_missing_its_rows(self):
+ # The state every report written before the reviewer index existed starts in.
+ alice = self._create_org_member("[email protected]", github_login="alice")
+ report = self._create_report()
+ self._create_artefact(report, content=[{"user_uuid": str(alice.uuid)}])
+ SignalReportSuggestedReviewer.all_teams.filter(report_id=report.id).delete()
+ assert not self._reviewer_filter_matches(report, alice)
+
+ call_command("backfill_suggested_reviewer_index", "--team-id", str(self.team.id))
+
+ assert self._reviewer_filter_matches(report, alice)
+
def test_diff_with_non_dict_content_returns_400_not_500(self):
# Log content is stored as arbitrary JSON; a non-object commit payload must not 500.
report = self._create_report()
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index faf4b27ceeca..649c48bc7d0b 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -191,6 +191,7 @@ from products.signals.backend.slack_notification_targets import (
saved_notification_integration,
validate_slack_notification_target,
)
+from products.signals.backend.suggested_reviewer_index import report_ids_naming_reviewers
from products.signals.backend.task_attribution import TASK_ID_HEADER, resolve_request_attribution
from products.signals.backend.tasks import send_reviewer_added_slack_notifications, sync_signals_refund_credit
from products.signals.backend.temporal.backfill_error_tracking import (
@@ -1290,34 +1291,6 @@ class SignalReportViewSet(
report_ids_with_prefix = fetch_report_ids_for_scout_prefix(self.team, scout_prefix)
return queryset.filter(id__in=report_ids_with_prefix)
- def _current_suggested_reviewer_artefacts(self, scope: Q, where: str, params: list[str]):
- """Current reviewer artefacts in `scope` that match the parameterized predicate.
-
- suggested_reviewers is append-only, so only the newest row is the live reviewer set —
- older versions remain as history and must not match. A row is current iff no newer row of
- the same type exists for its report.
- """
- has_newer = Exists(
- SignalReportArtefact.objects.filter(
- report_id=OuterRef("report_id"),
- type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
- created_at__gt=OuterRef("created_at"),
- )
- )
- reviewer_artefacts = SignalReportArtefact.objects.filter(
- scope,
- type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
- )
- # nosemgrep: python.django.security.audit.query-set-extra.avoid-query-set-extra (parameterized via params)
- reviewer_artefacts = reviewer_artefacts.extra(where=[where], params=params)
- return reviewer_artefacts.filter(~has_newer)
-
- def _reports_with_suggested_reviewers(self, where: str, params: list[str]):
- return self._current_suggested_reviewer_artefacts(Q(team=self.team), where, params).values("report_id")
-
- def _report_has_suggested_reviewer(self, where: str, params: list[str]):
- return Exists(self._current_suggested_reviewer_artefacts(Q(report_id=OuterRef("id")), where, params))
-
def _implementation_pr_report_filter(self):
return implementation_pr_report_filter(team_id=self.team.id)
@@ -1405,20 +1378,16 @@ class SignalReportViewSet(
reviewer_github_logins = list(
get_org_member_github_logins_by_user_uuid(self.team.id, reviewer_user_uuids).values()
)
- uuid_filters = [json.dumps([{"user_uuid": user_uuid}]) for user_uuid in reviewer_user_uuids]
- if not uuid_filters and not reviewer_github_logins:
+ if not reviewer_user_uuids and not reviewer_github_logins:
return queryset.none()
- reviewer_clauses = ["content::jsonb @> %s::jsonb"] * len(uuid_filters)
- reviewer_params: list[str] = list(uuid_filters)
- for github_login in reviewer_github_logins:
- reviewer_clauses.append(
- "EXISTS (SELECT 1 FROM jsonb_array_elements(content::jsonb) reviewer "
- "WHERE lower(reviewer->>'github_login') = %s "
- "AND NULLIF(reviewer->>'user_uuid', '') IS NULL)"
+ return queryset.filter(
+ id__in=report_ids_naming_reviewers(
+ team_id=self.team.id,
+ user_uuids=reviewer_user_uuids,
+ github_logins=reviewer_github_logins,
+ logins_match_unidentified_only=True,
)
- reviewer_params.append(github_login)
- reviewer_where = " OR ".join(reviewer_clauses)
- return queryset.filter(id__in=self._reports_with_suggested_reviewers(reviewer_where, reviewer_params))
+ )
def _apply_signal_report_inbox_scope_filter(self, queryset):
scope = self.request.query_params.get("scope")
@@ -1698,7 +1667,7 @@ class SignalReportViewSet(
def _annotate_is_suggested_reviewer(self, queryset):
# Annotate is_suggested_reviewer by resolving the current user's GitHub login
- # and checking jsonb containment on the artefact content list. This stays fresh
+ # and matching it against the indexed reviewer rows. This stays fresh
# even when a user connects their GitHub account after the report was generated.
# Never true for ready + not_actionable — there is nothing actionable to review.
# Failed reports are excluded too — pipelines that errored should not bubble as "needs your review".
@@ -1706,16 +1675,16 @@ class SignalReportViewSet(
# account is stored by uuid alone, and entries predating `user_uuid` carry only a login.
user = cast(User, self.request.user)
github_login = self._get_github_login(user)
- identity_filters = [json.dumps([{"user_uuid": str(user.uuid)}])]
- if github_login:
- # github_login comes from our own UserSocialAuth DB, not user input.
- identity_filters.append(json.dumps([{"github_login": github_login}]))
- identity_where = " OR ".join(["content::jsonb @> %s::jsonb"] * len(identity_filters))
-
+ matching_report_ids = report_ids_naming_reviewers(
+ team_id=self.team.id,
+ user_uuids=[str(user.uuid)],
+ github_logins=[github_login] if github_login else [],
+ logins_match_unidentified_only=False,
+ )
names_the_user = (
- Q(id__in=self._reports_with_suggested_reviewers(identity_where, identity_filters))
+ Q(id__in=matching_report_ids)
if self.action == "list"
- else Q(self._report_has_suggested_reviewer(identity_where, identity_filters))
+ else Q(Exists(matching_report_ids.filter(report_id=OuterRef("id"))))
)
return queryset.annotate(
is_suggested_reviewer=Case(