Skip to content

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

feat(signals): resolve a recommended inbox sort from a user flag (#115448)

posthog[bot]565e58833dc1
diff --git a/products/signals/backend/ranking/inbox_sort.py b/products/signals/backend/ranking/inbox_sort.py
new file mode 100644
index 000000000000..47d387504a08
--- /dev/null
+++ b/products/signals/backend/ranking/inbox_sort.py
@@ -0,0 +1,78 @@
+"""Resolve the `recommended` inbox sort to a ranker, and give each row a coarse merge key.
+
+A multivariate flag keyed by the requesting user picks the ranker. `control`, an unknown variant, or a flag that is
+off or fails to evaluate gives the priority order. `test` orders by the served `fixed` head first.
+
+The merge key lets a client merge rows from the two rankers without the raw score. It is the score
+decile then the priority rank, so it never says more about the score than one decimal place. The
+`fixed` ranker sorts by the same decile, so the row order does not say more either. Keep
+`score_decile` and `inbox_merge_key` in step.
+"""
+
+from typing import Literal
+
+from django.db.models import Case, F, FloatField, Value, When
+from django.db.models.functions import Floor
+
+import structlog
+import posthoganalytics
+
+from posthog.models.team import Team
+from posthog.models.user import User
+
+from products.signals.backend.models import AutonomyPriority
+
+logger = structlog.get_logger(__name__)
+
+RECOMMENDED_INBOX_SORT_FLAG = "signals-inbox-recommended-sort"
+
+InboxRanker = Literal["priority", "fixed"]
+
+PRIORITY_ORDERING = "priority,status,-updated_at"
+RANKER_ORDERINGS: dict[InboxRanker, str] = {
+ "priority": PRIORITY_ORDERING,
+ "fixed": "-ranking_fixed,priority,status,-updated_at",
+}
+
+_DECILES = 10
+_PRIORITY_SLOTS = len(AutonomyPriority.values) + 1
+
+
+def resolve_recommended_ranker(team: Team, user: User) -> InboxRanker:
+ if not user.distinct_id:
+ return "priority"
+ try:
+ variant = posthoganalytics.get_feature_flag(
+ RECOMMENDED_INBOX_SORT_FLAG,
+ # Keyed by user so the exposure joins to the user's inbox events in the experiment.
+ user.distinct_id,
+ # The web and desktop clients register the project group by uuid, so all clients get the same variant.
+ groups={"project": str(team.uuid)},
+ group_properties={"project": {"id": team.id, "uuid": str(team.uuid)}},
+ )
+ except Exception:
+ logger.exception("signals.inbox_sort.flag_failed", team_id=team.id, user_id=user.id)
+ return "priority"
+ return "fixed" if variant == "test" else "priority"
+
+
+def score_decile(field: str) -> Case:
+ """The SQL form of the decile in `inbox_merge_key`. NULL stays NULL."""
+ return Case(
+ When(**{f"{field}__isnull": True}, then=Value(None)),
+ When(**{f"{field}__lt": 0}, then=Value(0.0)),
+ When(**{f"{field}__gte": (_DECILES - 1) / _DECILES}, then=Value(float(_DECILES - 1))),
+ default=Floor(F(field) * _DECILES),
+ output_field=FloatField(),
+ )
+
+
+def inbox_merge_key(score: float | None, priority_rank: int | None) -> int:
+ """Lower keys rank first. A report without a score sorts after every scored report."""
+ if score is None:
+ decile_rank = _DECILES
+ else:
+ decile = min(max(int(score * _DECILES), 0), _DECILES - 1)
+ decile_rank = _DECILES - 1 - decile
+ priority = _PRIORITY_SLOTS - 1 if priority_rank is None else min(max(priority_rank, 0), _PRIORITY_SLOTS - 1)
+ return decile_rank * _PRIORITY_SLOTS + priority
diff --git a/products/signals/backend/scout_report/trial_inbox.py b/products/signals/backend/scout_report/trial_inbox.py
index 2567f97dd1f9..74c45e1f3246 100644
--- a/products/signals/backend/scout_report/trial_inbox.py
+++ b/products/signals/backend/scout_report/trial_inbox.py
@@ -294,6 +294,7 @@ class TrialInboxReads:
self.overlay(report, live.get(report.source_report_id or "")),
include_source_metadata=include_source_metadata,
)
+ document["inbox_merge_key"] = None
if document.get("status") not in statuses:
continue
if search and not any(search in str(document.get(field, "")).casefold() for field in ("title", "summary")):
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index 450c5844f510..dc36505d779c 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -79,6 +79,7 @@ from .models import (
SignalUserAutonomyConfig,
)
from .pull_request_label import DEFAULT_PULL_REQUEST_LABEL
+from .ranking.inbox_sort import inbox_merge_key
from .ranking.staleness import EDIT_ARTEFACT_TYPES, is_stale_score
from .report_charts import CHART_SIZES, MAX_CHART_CAPTION_LENGTH, MAX_CHART_ID_LENGTH, MAX_CHART_TITLE_LENGTH
from .report_generation.resolve_reviewers import enrich_reviewer_dicts_with_org_members, trusted_manual_reviewer_adders
@@ -1820,6 +1821,24 @@ class SignalReportListSerializer(SignalReportSerializer):
"comparisons are available from the report detail endpoint."
),
)
+ inbox_merge_key = serializers.SerializerMethodField(
+ help_text=(
+ "Coarse sort key from the ranker named by the list response's ranker field, for sort=recommended "
+ "only. Lower keys rank first. It is the ranking score decile, then the priority as a tiebreak. "
+ "Reports without a usable score sort after scored ones. Null for every other sort."
+ ),
+ )
+
+ class Meta(SignalReportSerializer.Meta):
+ fields = [*SignalReportSerializer.Meta.fields, "inbox_merge_key"]
+ read_only_fields = fields
+
+ def get_inbox_merge_key(self, obj: SignalReport) -> int | None:
+ ranker = self.context.get("inbox_ranker")
+ if ranker is None:
+ return None
+ score = getattr(obj, "ranking_fixed_score", None) if ranker == "fixed" else None
+ return inbox_merge_key(score, getattr(obj, "priority_sort_rank", None))
class SignalReportListQuerySerializer(serializers.Serializer):
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index dd1abd6a1402..97a81d07fda1 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -1261,6 +1261,81 @@ class TestSignalReportListAPI(APIBaseTest):
assert ids[:3] == (scored if ordering.startswith("-") else scored[::-1])
assert set(ids[3:]) == {str(unscored.id), str(no_head.id), str(bad_latest.id)}
+ @parameterized.expand(
+ [
+ ("flag_off", {"return_value": None}),
+ ("control", {"return_value": "control"}),
+ ("unknown_variant", {"return_value": "test-2"}),
+ ("flag_error", {"side_effect": RuntimeError("flags down")}),
+ ]
+ )
+ def test_recommended_sort_uses_priority_order_unless_the_flag_serves_test(self, _name, flag_result):
+ p2 = self._create_report(title="P2")
+ p0 = self._create_report(title="P0")
+ no_priority = self._create_report(title="No priority")
+ self._priority_artefact(p2, priority="P2")
+ self._priority_artefact(p0, priority="P0")
+ self._ranking_score_artefact(p2, scores={"fixed": 0.9})
+
+ with patch("products.signals.backend.ranking.inbox_sort.posthoganalytics.get_feature_flag", **flag_result):
+ response = self.client.get(self._list_url(status="ready", sort="recommended"))
+
+ assert response.status_code == status.HTTP_200_OK
+ body = response.json()
+ assert body["ranker"] == "priority"
+ assert [(r["id"], r["inbox_merge_key"]) for r in body["results"]] == [
+ (str(p0.id), 60),
+ (str(p2.id), 62),
+ (str(no_priority.id), 65),
+ ]
+
+ def test_recommended_sort_test_variant_ranks_by_fixed_head_without_showing_scores_to_non_staff(self):
+ self.user.is_staff = False
+ self.user.save()
+ low_p0 = self._create_report(title="Low P0")
+ high_p3 = self._create_report(title="High P3")
+ same_decile_p0 = self._create_report(title="Same decile P0")
+ unscored_p1 = self._create_report(title="Unscored P1")
+ stale_p0 = self._create_report(title="Stale P0")
+ for report, priority in (
+ (low_p0, "P0"),
+ (high_p3, "P3"),
+ (same_decile_p0, "P0"),
+ (unscored_p1, "P1"),
+ (stale_p0, "P0"),
+ ):
+ self._priority_artefact(report, priority=priority)
+ self._ranking_score_artefact(low_p0, scores={"fixed": 0.1234})
+ self._ranking_score_artefact(high_p3, scores={"fixed": 0.8765})
+ self._ranking_score_artefact(same_decile_p0, scores={"fixed": 0.8123})
+ self._ranking_score_artefact(stale_p0, scores={"fixed": 0.9876})
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=stale_p0,
+ type=SignalReportArtefact.ArtefactType.TITLE_CHANGE,
+ content=json.dumps({"old_title": "Old", "new_title": "Stale P0"}),
+ )
+
+ with patch(
+ "products.signals.backend.ranking.inbox_sort.posthoganalytics.get_feature_flag", return_value="test"
+ ) as get_flag:
+ response = self.client.get(self._list_url(status="ready", sort="recommended"))
+
+ assert response.status_code == status.HTTP_200_OK
+ assert get_flag.call_args.args[1] == self.user.distinct_id
+ body = response.json()
+ assert body["ranker"] == "fixed"
+ assert [(r["id"], r["inbox_merge_key"]) for r in body["results"]] == [
+ (str(same_decile_p0.id), 6),
+ (str(high_p3.id), 9),
+ (str(low_p0.id), 48),
+ (str(stale_p0.id), 60),
+ (str(unscored_p1.id), 61),
+ ]
+ assert all(r["ranking"] is None for r in body["results"])
+ for raw_score in ("0.1234", "0.8123", "0.8765", "0.9876"):
+ assert raw_score not in response.content.decode()
+
@parameterized.expand(
[
("ordering", {"ordering": "-ranking_open,status"}, "ordering"),
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 087d8578f682..82daf477fe8c 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -4,7 +4,7 @@ import uuid
from collections import defaultdict
from collections.abc import Callable, Iterable, Sequence
from datetime import UTC, timedelta
-from functools import partial
+from functools import cached_property, partial
from typing import Any, cast
from django.conf import settings
@@ -44,6 +44,7 @@ from pydantic import ValidationError as PydanticValidationError
from rest_framework import exceptions, mixins, serializers, status, viewsets
from rest_framework.decorators import action
from rest_framework.exceptions import NotFound
+from rest_framework.pagination import LimitOffsetPagination
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
@@ -144,6 +145,13 @@ from products.signals.backend.models import (
)
from products.signals.backend.pull_requests import import_report_pull_requests
from products.signals.backend.quota import self_driving_quota_enforcement_enabled, self_driving_quota_gate
+from products.signals.backend.ranking.inbox_sort import (
+ PRIORITY_ORDERING,
+ RANKER_ORDERINGS,
+ InboxRanker,
+ resolve_recommended_ranker,
+ score_decile,
+)
from products.signals.backend.ranking.staleness import EDIT_ARTEFACT_TYPES, annotate_stale_score
from products.signals.backend.receivers import capture_verdict_reason_added_analytics
from products.signals.backend.repo_corrections import sanitized_repository
@@ -1121,6 +1129,21 @@ class SignalReportReingestionStatusSerializer(serializers.Serializer):
report_id = serializers.UUIDField(help_text="Report being re-ingested.")
+class SignalReportListPagination(LimitOffsetPagination):
+ def get_paginated_response_schema(self, schema):
+ paginated = super().get_paginated_response_schema(schema)
+ paginated["properties"]["ranker"] = {
+ "type": "string",
+ "nullable": True,
+ "description": (
+ "The ranker that ordered the page when sort=recommended: priority, or fixed for the served "
+ "ranking model's fixed head. Null for every other sort. Each row's inbox_merge_key belongs "
+ "to this ranker."
+ ),
+ }
+ return paginated
+
+
@extend_schema_view(
destroy=extend_schema(
summary="Delete a signal report",
@@ -1144,11 +1167,14 @@ class SignalReportViewSet(
permission_classes = [IsAuthenticated, APIScopePermission]
scope_object = "task"
queryset = SignalReport.objects.all()
+ pagination_class = SignalReportListPagination
# Shared Q for "ready but not actionable" — used in status ranking and suggested-reviewer suppression.
_Q_READY_NOT_ACTIONABLE = Q(status=SignalReport.Status.READY) & Q(latest_actionability="not_actionable")
_DEFAULT_SIGNAL_REPORT_ORDERING = "-is_suggested_reviewer,status,-updated_at"
_INBOX_SORT_ORDERINGS = {
- "priority": "priority,status,-updated_at",
+ "priority": PRIORITY_ORDERING,
+ # A feature flag resolves this preset per user. See `_inbox_ranker`.
+ "recommended": PRIORITY_ORDERING,
"last_updated": "-updated_at,status",
"newest": "-created_at,status,-updated_at",
"oldest": "created_at,status,-updated_at",
@@ -1992,7 +2018,7 @@ class SignalReportViewSet(
return queryset
return self._apply_signal_report_ordering(queryset)
- def _parse_ordering_string(self, raw: str) -> list[str]:
+ def _parse_ordering_string(self, raw: str, *, allow_ranking: bool = False) -> list[str]:
parts = [p.strip() for p in raw.split(",") if p.strip()]
clauses: list[str] = []
for part in parts:
@@ -2001,7 +2027,7 @@ class SignalReportViewSet(
db_field = self._SIGNAL_REPORT_ORDERING_FIELDS.get(name)
if db_field is None:
continue
- if name in self._RANKING_ORDERING_HEADS and not self.request.user.is_staff:
+ if name in self._RANKING_ORDERING_HEADS and not allow_ranking and not self.request.user.is_staff:
# The serializer hides ranking scores from non-staff users, and the order would leak them.
raise serializers.ValidationError({"ordering": f"Ordering by {name} is only available to staff."})
clause = f"-{db_field}" if descending else db_field
@@ -2012,7 +2038,18 @@ class SignalReportViewSet(
def _default_signal_report_ordering_clauses(self) -> list[str]:
return self._parse_ordering_string(self._DEFAULT_SIGNAL_REPORT_ORDERING)
+ @cached_property
+ def _inbox_ranker(self) -> InboxRanker | None:
+ params = self.request.query_params
+ if params.get("ordering") is not None or params.get("sort") != "recommended":
+ return None
+ return resolve_recommended_ranker(self.team, cast(User, self.request.user))
+
def _parse_signal_report_ordering(self) -> list[str]:
+ ranker = self._inbox_ranker
+ if ranker is not None:
+ # The preset exposes only the score decile, through `inbox_merge_key`, so non-staff users may use it.
+ return self._parse_ordering_string(RANKER_ORDERINGS[ranker], allow_ranking=True)
raw = self.request.query_params.get("ordering")
if raw is None:
inbox_sort = self.request.query_params.get("sort")
@@ -2038,9 +2075,11 @@ class SignalReportViewSet(
for clause in clauses:
name = clause.lstrip("-")
if name in ranking_annotations:
+ # The recommended preset sorts by the score decile, so the order shows no more than `inbox_merge_key`.
+ expression = score_decile(name) if self._inbox_ranker is not None else F(name)
# Unscored reports sort after every scored report, in both directions.
order_by.append(
- F(name).desc(nulls_last=True) if clause.startswith("-") else F(name).asc(nulls_last=True)
+ expression.desc(nulls_last=True) if clause.startswith("-") else expression.asc(nulls_last=True)
)
else:
order_by.append(clause)
@@ -2415,7 +2454,10 @@ class SignalReportViewSet(
location=OpenApiParameter.QUERY,
required=False,
description=(
- "Inbox sort preset: priority, last_updated, newest, or oldest. Ignored when ordering is supplied."
+ "Inbox sort preset: priority, recommended, last_updated, newest, or oldest. Ignored when "
+ "ordering is supplied. recommended resolves per project to a ranker: the priority order, or "
+ "the served ranking model's fixed head with unscored and stale reports in priority order "
+ "after the scored ones. The response's ranker field names the one used."
),
),
OpenApiParameter(
@@ -2482,9 +2524,14 @@ class SignalReportViewSet(
def list(self, request: ValidatedRequest, *args, **kwargs):
count_only: bool = request.validated_query_data["count_only"]
include_source_metadata: bool = request.validated_query_data["include_source_metadata"]
+ if count_only:
+ # A count orders nothing, so it must not record a flag exposure for the ranker.
+ self._inbox_ranker = None
with trial_state_errors():
store = trial_store_for_request(request, self.team_id)
if store is not None:
+ # Private trial reads compare against the priority order, never a flag arm.
+ self._inbox_ranker = None
return TrialInboxReads(self, store).list(
count_only=count_only, include_source_metadata=include_source_metadata
)
@@ -2530,7 +2577,9 @@ class SignalReportViewSet(
data = self._render_report_rows(reports, include_source_metadata=include_source_metadata)
if page is not None:
- return self.get_paginated_response(data)
+ response = self.get_paginated_response(data)
+ response.data["ranker"] = self._inbox_ranker
+ return response
return Response(data)
def _render_report_rows(
@@ -2584,6 +2633,7 @@ class SignalReportViewSet(
"implementation_pr_state_map": {rid: pr.state for rid, pr in implementation_pr_by_report.items()},
"implementation_pr_merged_ids": {rid for rid, pr in implementation_pr_by_report.items() if pr.merged},
"first_billable_pr_run_at_map": first_billable_pr_run_at_map,
+ "inbox_ranker": self._inbox_ranker,
}
serializer = self.get_serializer(reports, many=True, context=context)
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index b8af40daafaf..b9cd60c70f43 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -781,6 +781,11 @@ export interface SignalReportListApi {
readonly channel_id: string | null
/** The served model's score from the latest ranking score artefact. Staff only: null for other users, and null when the report has no score. */
readonly ranking: ReportRankingApi | null
+ /**
+ * Coarse sort key from the ranker named by the list response's ranker field, for sort=recommended only. Lower keys rank first. It is the ranking score decile, then the priority as a tiebreak. Reports without a usable score sort after scored ones. Null for every other sort.
+ * @nullable
+ */
+ readonly inbox_merge_key: number | null
}
export interface PaginatedSignalReportListListApi {
@@ -790,6 +795,11 @@ export interface PaginatedSignalReportListListApi {
/** @nullable */
previous?: string | null
results: SignalReportListApi[]
+ /**
+ * The ranker that ordered the page when sort=recommended: priority, or fixed for the served ranking model's fixed head. Null for every other sort. Each row's inbox_merge_key belongs to this ranker.
+ * @nullable
+ */
+ ranker?: string | null
}
/**
@@ -7796,7 +7806,7 @@ export type SignalsReportsListParams = {
*/
search?: string
/**
- * Inbox sort preset: priority, last_updated, newest, or oldest. Ignored when ordering is supplied.
+ * Inbox sort preset: priority, recommended, last_updated, newest, or oldest. Ignored when ordering is supplied. recommended resolves per project to a ranker: the priority order, or the served ranking model's fixed head with unscored and stale reports in priority order after the scored ones. The response's ranker field names the one used.
*/
sort?: string
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index fa5d5b980398..1f432a8cb54c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -73731,6 +73731,11 @@ export namespace Schemas {
readonly channel_id: string | null;
/** The served model's score from the latest ranking score artefact. Staff only: null for other users, and null when the report has no score. */
readonly ranking: ReportRanking | null;
+ /**
+ * Coarse sort key from the ranker named by the list response's ranker field, for sort=recommended only. Lower keys rank first. It is the ranking score decile, then the priority as a tiebreak. Reports without a usable score sort after scored ones. Null for every other sort.
+ * @nullable
+ */
+ readonly inbox_merge_key: number | null;
}
export interface PaginatedSignalReportListList {
@@ -73740,6 +73745,11 @@ export namespace Schemas {
/** @nullable */
previous?: string | null;
results: SignalReportList[];
+ /**
+ * The ranker that ordered the page when sort=recommended: priority, or fixed for the served ranking model's fixed head. Null for every other sort. Each row's inbox_merge_key belongs to this ranker.
+ * @nullable
+ */
+ ranker?: string | null;
}
/**
@@ -129045,7 +129055,7 @@ export namespace Schemas {
*/
search?: string;
/**
- * Inbox sort preset: priority, last_updated, newest, or oldest. Ignored when ordering is supplied.
+ * Inbox sort preset: priority, recommended, last_updated, newest, or oldest. Ignored when ordering is supplied. recommended resolves per project to a ranker: the priority order, or the served ranking model's fixed head with unscored and stale reports in priority order after the scored ones. The response's ranker field names the one used.
*/
sort?: string;
/**
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 96332c68950a..71fb47157cd5 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -239,7 +239,9 @@ export const SignalsReportsListQueryParams = () => zod.object({
sort: zod
.string()
.optional()
- .describe('Inbox sort preset: priority, last_updated, newest, or oldest. Ignored when ordering is supplied.'),
+ .describe(
+ "Inbox sort preset: priority, recommended, last_updated, newest, or oldest. Ignored when ordering is supplied. recommended resolves per project to a ranker: the priority order, or the served ranking model's fixed head with unscored and stale reports in priority order after the scored ones. The response's ranker field names the one used."
+ ),
source_id: zod
.string()
.optional()
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-list.json
index f727682ad5ee..cb03efdbc05b 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/inbox-reports-list.json
@@ -75,7 +75,7 @@
"type": "string"
},
"sort": {
- "description": "Inbox sort preset: priority, last_updated, newest, or oldest. Ignored when ordering is supplied.",
+ "description": "Inbox sort preset: priority, recommended, last_updated, newest, or oldest. Ignored when ordering is supplied. recommended resolves per project to a ranker: the priority order, or the served ranking model's fixed head with unscored and stale reports in priority order after the scored ones. The response's ranker field names the one used.",
"type": "string"
},
"source_id": {