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): order today reports with the inbox priority sort (#118446)

Shy Alter4e63f214c35e
diff --git a/frontend/src/scenes/project-homepage/today/todayLogic.ts b/frontend/src/scenes/project-homepage/today/todayLogic.ts
index b2e2106ecf38..407f1bbbbfb1 100644
--- a/frontend/src/scenes/project-homepage/today/todayLogic.ts
+++ b/frontend/src/scenes/project-homepage/today/todayLogic.ts
@@ -407,7 +407,7 @@ export const todayLogic = kea<todayLogicType>([
return { results: [], count: 0 }
}
// The person's own reports, ranked and counted.
- // A P0 nobody owns ranks above every one of them, so Today leaves it to the Inbox.
+ // A P0 nobody owns belongs to the project, so Today leaves it to the Inbox.
let response
try {
response = await signalsReportsForYouRetrieve(String(values.currentProjectId), {
diff --git a/products/signals/backend/briefing_reports.py b/products/signals/backend/briefing_reports.py
index 24ba95779e78..1a9739cd7a1a 100644
--- a/products/signals/backend/briefing_reports.py
+++ b/products/signals/backend/briefing_reports.py
@@ -1,24 +1,19 @@
"""Reports that matter to one person, for the Today briefing.
-This module answers "which reports relate to this person, and how", and orders them with the
-served ranking model. The Today briefing and the inbox `for_you` list share this order.
+This module answers "which reports relate to this person, and how". The inbox `for_you` list
+orders these reports with the inbox priority order.
"""
import re
-from bisect import bisect_left
-from collections.abc import Mapping, Sequence
+from collections.abc import Sequence
from datetime import datetime
from enum import StrEnum
-from typing import Any
from django.db.models import Case, CharField, F, Func, JSONField, OuterRef, Q, QuerySet, Subquery, Value, When
from django.db.models.functions import Cast
-import pydantic
-import structlog
-
from posthog.dataclasses import frozen
-from posthog.models import Team, User
+from posthog.models import User
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.artefact_schemas import ActionabilityChoice, priority_from_judgment
@@ -33,25 +28,11 @@ from products.signals.backend.report_content_gates import team_report_monitoring
from products.signals.backend.report_lifecycle import effective_report_status
from products.signals.backend.report_metric_access import ReportMetricAccessPolicy
from products.signals.backend.report_metrics import ReportMetricSnapshot, saved_metric_snapshots
-from products.signals.backend.signal_metadata import fetch_source_products_for_reports
from products.signals.backend.suggested_reviewer_index import report_ids_naming_reviewers
-logger = structlog.get_logger(__name__)
-
_OPEN_STATUSES = (SignalReport.Status.READY, SignalReport.Status.PENDING_INPUT)
-_SUMMARY_LIMIT = 300
# The hover card shows more of the summary than the briefing writer reads.
SUMMARY_LEAD_LIMIT = 450
-PR_MERGED_HEAD = "pr_merged"
-ACTION_HEAD = "action"
-DISMISS_WRONG_HEAD = "dismiss_wrong"
-# A report the model expects to be dismissed as wrong at this many times the head's base rate is
-# left out. The rule only applies to a model that saved a classification threshold for the head,
-# because a raw probability is not calibrated and changes meaning with each model version.
-DISMISS_WRONG_HIDE_LIFT = 3.0
-# A bound on the candidates the briefing reads, so one person with a very large inbox cannot make
-# it slow. It is far above the number of open reports a person usually has.
-_CANDIDATE_LIMIT = 500
class BriefingReportRelation(StrEnum):
@@ -64,26 +45,6 @@ class BriefingReportRelation(StrEnum):
URGENT_UNOWNED = "urgent_unowned"
-_PRIORITY_ORDER = {"P0": 0, "P1": 1, "P2": 2, "P3": 3, "P4": 4}
-
-
-@frozen
-class BriefingReport:
- report_id: str
- relation: BriefingReportRelation
- title: str
- summary: str
- status: str
- priority: str | None
- has_implementation_pr: bool
- # The products the report's signals came from, sorted, the way the inbox list shows them.
- source_products: list[str]
- updated_at: datetime
- # The served ranking model's chance that the report ends with a merged PR. None when the
- # report has no score yet, or the model's pr_merged head is not readable.
- pr_merged_probability: float | None
-
-
# The implementation pull request states a briefing shows. `unknown` reads as no state.
IMPLEMENTATION_PR_STATES: tuple[str, ...] = tuple(
state for state in SignalReportAssignment.PrState.values if state != SignalReportAssignment.PrState.UNKNOWN
@@ -133,33 +94,12 @@ def _priorities(team_id: int, report_ids: Sequence[str]) -> dict[str, str]:
return latest
-@frozen
-class _ServedScores:
- """The readable heads of a report's latest served score that the briefing ranks on."""
-
- pr_merged: float | None
- action: float | None
- dismiss_wrong_lift: float | None
-
-
-_NO_SCORES = _ServedScores(pr_merged=None, action=None, dismiss_wrong_lift=None)
-
-
def _json_object_content() -> Q:
# Content is written from a pydantic schema. The guard only keeps a legacy or truncated row out
# of the jsonb cast, because a failed cast fails the whole query.
return Q(content__startswith="{", content__endswith="}")
-def _content_path(*path: str | Func) -> Func:
- return Func(
- Cast(F("content"), output_field=JSONField()),
- *(Value(key) if isinstance(key, str) else key for key in path),
- function="jsonb_extract_path",
- output_field=JSONField(),
- )
-
-
def _latest_priority() -> Subquery:
"""The priority of each report's latest priority judgment, as text. The latest row decides, so
a malformed latest row reads as no priority, as `priority_from_judgment` reads it."""
@@ -182,77 +122,6 @@ def _latest_priority() -> Subquery:
)
-def _latest_served_heads() -> Subquery:
- """The scores, lifts and head metadata of the served model in each report's latest ranking score.
-
- The score content also holds every other model the pass ran, so Postgres extracts only these
- three keys and the query does not send the whole content for each candidate.
- """
- served_key = Func(
- Cast(F("content"), output_field=JSONField()),
- Value("served_key"),
- function="jsonb_extract_path_text",
- output_field=CharField(),
- )
- heads = Func(
- Cast(Value("scores"), output_field=CharField()),
- _content_path("results", served_key, "scores"),
- Cast(Value("lifts"), output_field=CharField()),
- _content_path("results", served_key, "lifts"),
- Cast(Value("heads"), output_field=CharField()),
- _content_path("results", served_key, "metadata", "heads"),
- function="jsonb_build_object",
- output_field=JSONField(),
- )
- return Subquery(
- SignalReportArtefact.objects.filter(
- report_id=OuterRef("id"), type=SignalReportArtefact.ArtefactType.RANKING_SCORE
- )
- .order_by("-created_at")
- .annotate(_heads=Case(When(_json_object_content(), then=heads), default=Value(None), output_field=JSONField()))
- .values("_heads")[:1],
- output_field=JSONField(),
- )
-
-
-class _ServedHeads(pydantic.BaseModel):
- """The shape `_latest_served_heads` returns. A key the served model does not carry is JSON null."""
-
- scores: dict[str, float] | None = None
- lifts: dict[str, float] | None = None
- heads: list[dict[str, Any]] | None = None
-
-
-def _served_scores(heads: dict[str, Any] | None) -> _ServedScores:
- """The readable heads from the output of `_latest_served_heads`.
-
- A head without a holdout AUC is not readable, so its probability is left out rather than
- trusted. The inbox serializer applies the same readability rule.
- """
- from products.signals.backend.ranking.model_contract import ( # noqa: PLC0415 — keeps numpy and pandas off the facade import path
- head_lifts,
- readable_head_names,
- )
-
- if heads is None:
- return _NO_SCORES
- try:
- served = _ServedHeads.model_validate(heads)
- scores = served.scores or {}
- metadata = {"heads": served.heads or []}
- readable = readable_head_names(metadata)
- # A score written before lifts were stored carries the metadata to compute them.
- lifts = served.lifts or head_lifts(scores, metadata)
- except (pydantic.ValidationError, KeyError, TypeError, ValueError):
- logger.warning("signals.briefing.ranking_score_unreadable")
- return _NO_SCORES
- return _ServedScores(
- pr_merged=scores.get(PR_MERGED_HEAD) if PR_MERGED_HEAD in readable else None,
- action=scores.get(ACTION_HEAD) if ACTION_HEAD in readable else None,
- dismiss_wrong_lift=lifts.get(DISMISS_WRONG_HEAD) if DISMISS_WRONG_HEAD in readable else None,
- )
-
-
def _open_reports(team_id: int) -> QuerySet[SignalReport]:
"""The reports the briefing may show and count: open, judged actionable, not already addressed."""
return (
@@ -293,75 +162,6 @@ def report_ids_naming_user(*, team_id: int, user: User, report_ids: Sequence[str
return {str(row["report_id"]) for row in naming}
-def _source_products(team_id: int, report_ids: Sequence[str]) -> dict[str, list[str]]:
- """Per report, the products its signals came from. A ClickHouse failure costs the colors, not the reports."""
- if not report_ids:
- return {}
- try:
- metadata = fetch_source_products_for_reports(Team.objects.get(id=team_id), list(report_ids))
- except Exception:
- logger.warning("signals.briefing.source_products_unavailable", team_id=team_id, exc_info=True)
- return {}
- return {report_id: meta.source_products for report_id, meta in metadata.items()}
-
-
-@frozen
-class _BriefingCandidate:
- report_id: str
- relation: BriefingReportRelation
- priority: str | None
- updated_at: datetime
- scores: _ServedScores
-
-
-def _percentile_ranks(values: Mapping[str, float]) -> dict[str, float]:
- """Each value's share of the other values below it, from 0 for the lowest to 1 for the highest."""
- ordered = sorted(values.values())
- denominator = max(len(ordered) - 1, 1)
- return {key: bisect_left(ordered, value) / denominator for key, value in values.items()}
-
-
-def _likely_dismissed_as_wrong(candidate: _BriefingCandidate) -> bool:
- # A P0 always shows, because a missed real P0 costs more than one wrong item in the list.
- lift = candidate.scores.dismiss_wrong_lift
- return candidate.priority != "P0" and lift is not None and lift >= DISMISS_WRONG_HIDE_LIFT
-
-
-def _briefing_pick(candidates: Sequence[_BriefingCandidate]) -> list[_BriefingCandidate]:
- """The candidates in one order, without the ones likely dismissed as wrong.
-
- P0 first. Then by the higher of two percentile ranks among the candidates: the chance of a
- merged PR, and the chance that someone acts on the report (creates a PR or starts a discussion).
- A report that needs a decision rather than code has a low merge chance, so the action chance
- lets it rank too. The heads are not calibrated to each other, so they are compared by rank,
- not by value. Ties go to the higher sum of the two ranks, then priority, then newest. A report
- with neither score follows the scored ones.
-
- The order does not depend on the relation, so the top N reports are always the first N of the
- same list.
- """
- kept = [c for c in candidates if not _likely_dismissed_as_wrong(c)]
- merge_ranks = _percentile_ranks({c.report_id: c.scores.pr_merged for c in kept if c.scores.pr_merged is not None})
- action_ranks = _percentile_ranks({c.report_id: c.scores.action for c in kept if c.scores.action is not None})
-
- def order(candidate: _BriefingCandidate) -> tuple[float, ...]:
- ranks = [r[candidate.report_id] for r in (merge_ranks, action_ranks) if candidate.report_id in r]
- return (
- 0 if candidate.priority == "P0" else 1,
- 0 if ranks else 1,
- -max(ranks, default=0.0),
- -sum(ranks),
- _priority_order(candidate),
- -candidate.updated_at.timestamp(),
- )
-
- return sorted(kept, key=order)
-
-
-def _priority_order(candidate: _BriefingCandidate) -> int:
- return _PRIORITY_ORDER.get(candidate.priority or "", 5)
-
-
def _relation_to_person(team_id: int, user: User, *, include_unowned: bool) -> Case:
"""A report's strongest `BriefingReportRelation` to the person, or NULL when it has none.
@@ -398,8 +198,8 @@ def _relation_to_person(team_id: int, user: User, *, include_unowned: bool) -> C
return Case(*branches, default=Value(None), output_field=CharField())
-def _reports_for_person(team_id: int, user: User, *, include_unowned: bool) -> QuerySet[SignalReport]:
- """The open reports that are for this person: the set the briefing ranks and the Inbox counts."""
+def reports_for_person(team_id: int, user: User, *, include_unowned: bool) -> QuerySet[SignalReport]:
+ """The open reports that are for this person: the set the inbox `for_you` list ranks and counts."""
return (
_open_reports(team_id)
.annotate(briefing_priority=_latest_priority())
@@ -408,79 +208,6 @@ def _reports_for_person(team_id: int, user: User, *, include_unowned: bool) -> Q
)
-def reports_for_briefing(
- *,
- team_id: int,
- user_id: int,
- limit: int | None = None,
- include_unowned: bool = True,
- offset: int = 0,
- exclude_report_ids: Sequence[str] = (),
-) -> list[BriefingReport]:
- """Open, actionable reports for one person, in briefing order, each tagged with its strongest relation.
-
- A report appears once, under the first `BriefingReportRelation` that matches. One query reads
- every candidate with its relation, priority and served scores, up to `_CANDIDATE_LIMIT`, so the
- model ranks the whole set and not only the newest reports. Urgent-unowned keeps only P0.
- `_briefing_pick` orders the candidates. The excluded reports leave the list after it is ordered,
- so the rest keep their order, and `offset` and `limit` then take one page of it. Priority does
- not decide which reports make the page: it only orders the page for display, P0 first and
- reports without a priority last, keeping the ranked order within a priority.
-
- `include_unowned` false drops the urgent-unowned relation, so the result holds only reports the
- person is named on or claimed. The Today briefing asks for that: a P0 nobody owns sorts above
- every other item, because P0 is the first key in `_briefing_pick` and is exempt from the
- dismiss-wrong filter, so one unowned report would take the top of every briefing in the project.
- """
- rows = (
- _reports_for_person(team_id, User.objects.get(id=user_id), include_unowned=include_unowned)
- .annotate(briefing_heads=_latest_served_heads())
- .order_by("-updated_at")
- .values_list("id", "updated_at", "briefing_relation", "briefing_priority", "briefing_heads")[:_CANDIDATE_LIMIT]
- )
- candidates = [
- _BriefingCandidate(
- report_id=str(report_id),
- relation=BriefingReportRelation(relation_value),
- priority=priority,
- updated_at=updated_at,
- scores=_served_scores(heads),
- )
- for report_id, updated_at, relation_value, priority, heads in rows
- ]
- excluded = set(exclude_report_ids)
- ranked = [candidate for candidate in _briefing_pick(candidates) if candidate.report_id not in excluded]
- page = ranked[offset:] if limit is None else ranked[offset : offset + limit]
- chosen = sorted(page, key=_priority_order)
- chosen_ids = [candidate.report_id for candidate in chosen]
- reports = {
- str(report.id): report
- for report in SignalReport.objects.filter(team_id=team_id, id__in=chosen_ids).annotate(
- has_implementation_pr=Case(
- When(implementation_pr_report_filter(team_id=team_id), then=Value(True)),
- default=Value(False),
- )
- )
- }
- source_products = _source_products(team_id, chosen_ids)
- return [
- BriefingReport(
- report_id=candidate.report_id,
- relation=candidate.relation,
- title=_trimmed(report.title, 200) or "Untitled report",
- summary=_trimmed(report.summary, _SUMMARY_LIMIT),
- status=report.effective_status,
- priority=candidate.priority,
- has_implementation_pr=report.has_implementation_pr,
- source_products=source_products.get(candidate.report_id, []),
- updated_at=report.updated_at,
- pr_merged_probability=candidate.scores.pr_merged,
- )
- for candidate in chosen
- if (report := reports.get(candidate.report_id)) is not None
- ]
-
-
@frozen
class OpenReportCounts:
for_person: int
@@ -492,7 +219,7 @@ def open_report_counts(
) -> OpenReportCounts:
"""How many open, actionable reports the project has, and how many of them are for this person.
- `for_person` counts the same set `reports_for_briefing` ranks, so a "more for you" number agrees
+ `for_person` counts the set `reports_for_person` returns, so a "more for you" number agrees
with the list it follows; pass the `include_unowned` the list was built with to keep that true.
`in_project` ignores the relation either way, so a P0 nobody owns is still counted there.
`exclude_report_ids` leaves out the reports already on screen; one that is resolved or not for the
@@ -500,7 +227,7 @@ def open_report_counts(
"""
excluded = list(exclude_report_ids)
in_project = _open_reports(team_id).exclude(id__in=excluded).count()
- for_person = _reports_for_person(team_id, user, include_unowned=include_unowned).exclude(id__in=excluded).count()
+ for_person = reports_for_person(team_id, user, include_unowned=include_unowned).exclude(id__in=excluded).count()
return OpenReportCounts(for_person=for_person, in_project=in_project)
diff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.py
index ca7465ba77d1..8a03f04d37a2 100644
--- a/products/signals/backend/facade/api.py
+++ b/products/signals/backend/facade/api.py
@@ -36,15 +36,12 @@ from products.signals.backend.artefact_schemas import (
)
from products.signals.backend.briefing_reports import (
IMPLEMENTATION_PR_STATES as IMPLEMENTATION_PR_STATES,
- # Re-exported for the Today briefing, which ranks these reports next to other products' items.
- BriefingReport as BriefingReport,
BriefingReportDetails as BriefingReportDetails,
BriefingReportRelation as BriefingReportRelation,
OpenReportCounts as OpenReportCounts,
open_report_counts as open_report_counts,
report_details as report_details,
report_ids_naming_user as report_ids_naming_user,
- reports_for_briefing as reports_for_briefing,
)
from products.signals.backend.contracts import DIRECT_STEERABLE_SOURCES, SIGNAL_VARIANT_LOOKUP, SignalRemediation
from products.signals.backend.enums import SIGNAL_SOURCE_PRODUCT_LABELS, SignalSourceProduct
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index f0e2e2a59266..b38c2eac2b35 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -1945,8 +1945,7 @@ class SignalReportsForYouQuerySerializer(serializers.Serializer):
default=True,
help_text=(
"Whether to include P0 reports that nobody owns. These belong to the project rather than to "
- "one person, and they rank above everything else, so a surface that only shows a person's own "
- "work passes false. Defaults to true."
+ "one person, so a surface that only shows a person's own work passes false. Defaults to true."
),
)
@@ -1955,12 +1954,10 @@ class SignalReportsForYouResponseSerializer(serializers.Serializer):
results = SignalReportListSerializer(
many=True,
help_text=(
- "One page of the open, actionable reports that matter most to the current user. The ranking "
- "model picks which reports make the page; the page is then in display order: by priority, P0 "
- "first and reports without a priority last, then best first within a priority. They are "
- "reports waiting for their input, reports they claimed, reports naming them as a reviewer, "
- "and P0 reports that nobody owns unless `include_unowned` is false. The Today briefing ranks "
- "reports the same way."
+ "One page of the open, actionable reports that matter most to the current user, in the inbox "
+ "priority order: priority, then status, then most recently updated. They are reports waiting for their input, reports they claimed, "
+ "reports naming them as a reviewer, and P0 reports that nobody owns unless `include_unowned` "
+ "is false. The Today briefing ranks reports the same way."
),
)
count = serializers.IntegerField(
diff --git a/products/signals/backend/test/test_briefing_reports.py b/products/signals/backend/test/test_briefing_reports.py
index 72f63475832e..14a1a433c2c8 100644
--- a/products/signals/backend/test/test_briefing_reports.py
+++ b/products/signals/backend/test/test_briefing_reports.py
@@ -1,6 +1,6 @@
import json
import time
-from datetime import UTC, datetime, timedelta
+from datetime import timedelta
from types import SimpleNamespace
from typing import cast
@@ -17,23 +17,17 @@ from rest_framework.request import Request
from posthog.models import Team
-from products.signals.backend.artefact_schemas import ActionabilityChoice, RankingModelResult, RankingScore
+from products.signals.backend.artefact_schemas import ActionabilityChoice
from products.signals.backend.briefing_reports import (
- BriefingReportRelation,
- _briefing_pick,
- _BriefingCandidate,
- _ServedScores,
open_report_counts,
report_details,
- reports_for_briefing,
+ reports_for_person,
summary_lead,
)
from products.signals.backend.models import SignalReport, SignalReportArtefact
from products.signals.backend.report_metric_access import ReportMetricAccessPolicy
from products.signals.backend.test.report_metric_test_fixtures import trends_metric_query
-SOURCE_PRODUCTS = "products.signals.backend.briefing_reports.fetch_source_products_for_reports"
-
class TestReportsForBriefing(BaseTest):
def _urgent_report(self, title: str) -> SignalReport:
@@ -72,30 +66,6 @@ class TestReportsForBriefing(BaseTest):
)
return report
- def _score(self, report: SignalReport, pr_merged: float, *, readable: bool, age: timedelta) -> None:
- served = RankingModelResult(
- model_name="report_embeddings",
- model_version="2026-09-01",
- model_kind="xgboost",
- roles=["served"],
- feature_schema_version=1,
- status="scored",
- scores={"open": 0.5, "pr_merged": pr_merged},
- metadata={"heads": [{"head": "open", "readable": True}, {"head": "pr_merged", "readable": readable}]},
- )
- artefact = SignalReportArtefact.objects.create(
- team=self.team,
- report=report,
- type=SignalReportArtefact.ArtefactType.RANKING_SCORE,
- content=RankingScore(
- scored_at=datetime(2026, 9, 20, 12, 0, tzinfo=UTC),
- manifest_version="manifest",
- served_key=served.key,
- results={served.key: served},
- ).model_dump_json(),
- )
- SignalReportArtefact.objects.filter(pk=artefact.pk).update(created_at=timezone.now() - age)
-
@parameterized.expand(
[
("ready", SignalReport.Status.READY, False, "ready"),
@@ -212,7 +182,7 @@ class TestReportsForBriefing(BaseTest):
self._named_report("Mine")
self._urgent_report("Nobody's P0")
- reports = reports_for_briefing(team_id=self.team.id, user_id=self.user.id, include_unowned=include_unowned)
+ reports = reports_for_person(self.team.id, self.user, include_unowned=include_unowned)
assert {report.title for report in reports} == expected
@@ -224,175 +194,6 @@ class TestReportsForBriefing(BaseTest):
assert (counts.in_project, counts.for_person) == (2, 1)
- def test_merge_chance_comes_from_the_latest_readable_served_score(self) -> None:
- rescored = self._urgent_report("Rescored")
- self._score(rescored, 0.1, readable=True, age=timedelta(days=2))
- self._score(rescored, 0.7, readable=True, age=timedelta(hours=1))
- unreadable = self._urgent_report("Unreadable head")
- self._score(unreadable, 0.9, readable=False, age=timedelta(hours=1))
- unscored = self._urgent_report("Unscored")
- truncated = self._urgent_report("Truncated score")
- self._score(truncated, 0.8, readable=True, age=timedelta(days=1))
- SignalReportArtefact.objects.create(
- team=self.team,
- report=truncated,
- type=SignalReportArtefact.ArtefactType.RANKING_SCORE,
- content='{"scored_at": "2026-09-20T12:00:00Z", "results": {',
- )
-
- reports = reports_for_briefing(team_id=self.team.id, user_id=self.user.id)
-
- assert {report.relation for report in reports} == {BriefingReportRelation.URGENT_UNOWNED}
- assert {report.title: report.pr_merged_probability for report in reports} == {
- rescored.title: 0.7,
- unreadable.title: None,
- unscored.title: None,
- truncated.title: None,
- }
-
- def test_query_count_does_not_grow_with_the_candidates(self) -> None:
- def queries() -> int:
- with CaptureQueriesContext(connection) as captured:
- reports_for_briefing(team_id=self.team.id, user_id=self.user.id, limit=5)
- return len(captured.captured_queries)
-
- self._score(self._urgent_report("First"), 0.5, readable=True, age=timedelta(hours=1))
- with patch(SOURCE_PRODUCTS, return_value={}):
- one_candidate = queries()
- for index in range(6):
- self._score(self._urgent_report(f"More {index}"), 0.5, readable=True, age=timedelta(hours=1))
- seven_candidates = queries()
-
- assert seven_candidates == one_candidate
-
- def test_an_older_report_with_a_high_merge_chance_beats_newer_ones(self) -> None:
- reports = []
- for index in range(6):
- report = SignalReport.objects.create(
- team=self.team,
- status=SignalReport.Status.READY,
- title=f"Report {index}",
- summary="Summary",
- signal_count=1,
- total_weight=1.0,
- )
- SignalReportArtefact.objects.create(
- team=self.team,
- report=report,
- type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
- content=json.dumps([{"github_login": "reviewer", "user_uuid": str(self.user.uuid)}]),
- )
- self._score(report, 0.9 if index == 5 else 0.1, readable=True, age=timedelta(hours=1))
- reports.append(report)
- for index, report in enumerate(reports):
- SignalReport.objects.filter(pk=report.pk).update(updated_at=timezone.now() - timedelta(days=index))
-
- [top] = reports_for_briefing(team_id=self.team.id, user_id=self.user.id, limit=1)
-
- assert (top.title, top.relation) == ("Report 5", BriefingReportRelation.SUGGESTED_REVIEWER)
-
- def test_the_model_picks_the_reports_and_priority_only_orders_them(self) -> None:
- for title, priority, pr_merged in [
- ("A", None, 0.9),
- ("B", "P3", 0.8),
- ("C", "P2", 0.7),
- ("D", None, 0.6),
- ("E", "P3", 0.5),
- ("Sixth P1", "P1", 0.1),
- ]:
- report = self._named_report(title)
- self._score(report, pr_merged, readable=True, age=timedelta(hours=1))
- if priority is not None:
- SignalReportArtefact.objects.create(
- team=self.team,
- report=report,
- type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,
- content=json.dumps({"priority": priority}),
- )
-
- with patch(SOURCE_PRODUCTS, return_value={}):
- top = reports_for_briefing(team_id=self.team.id, user_id=self.user.id, limit=5)
- next_page = reports_for_briefing(team_id=self.team.id, user_id=self.user.id, limit=5, offset=4)
-
- assert [report.title for report in top] == ["C", "B", "E", "A", "D"]
- assert [report.title for report in next_page] == ["Sixth P1", "E"]
-
-
-_Spec = tuple[str, BriefingReportRelation, str | None, float | None, float | None, float | None]
-WAITING = BriefingReportRelation.WAITING_FOR_YOU
-REVIEW = BriefingReportRelation.SUGGESTED_REVIEWER
-
-
-def _candidates(specs: list[_Spec]) -> list[_BriefingCandidate]:
- return [
- _BriefingCandidate(
- report_id=report_id,
- relation=relation,
- priority=priority,
- updated_at=datetime(2026, 9, 29, tzinfo=UTC),
- scores=_ServedScores(pr_merged=pr_merged, action=action, dismiss_wrong_lift=dismiss_wrong_lift),
- )
- for report_id, relation, priority, pr_merged, action, dismiss_wrong_lift in specs
- ]
-
-
-class TestBriefingPick(SimpleTestCase):
- @parameterized.expand(
- [
- (
- "merge chance decides across relations",
- [
- ("w1", WAITING, "P1", 0.02, None, None),
- ("s1", REVIEW, "P3", 0.4, None, None),
- ("c1", BriefingReportRelation.CLAIMED, "P3", 0.1, None, None),
- ],
- ["s1", "c1", "w1"],
- ),
- (
- "a high action chance ranks a report with a low merge chance",
- [
- ("merge", REVIEW, "P3", 0.3, 0.1, None),
- ("middle", REVIEW, "P3", 0.2, 0.2, None),
- ("act", WAITING, "P2", 0.01, 0.9, None),
- ],
- ["act", "merge", "middle"],
- ),
- (
- "the two heads compare by rank, not by value",
- [
- ("merge", REVIEW, "P3", 0.05, 0.001, None),
- ("act", REVIEW, "P2", 0.01, 0.5, None),
- ("low", REVIEW, "P3", 0.02, 0.2, None),
- ],
- ["act", "merge", "low"],
- ),
- (
- "P0 comes first",
- [
- ("s1", REVIEW, "P1", 0.9, 0.9, None),
- ("u1", BriefingReportRelation.URGENT_UNOWNED, "P0", 0.01, None, None),
- ],
- ["u1", "s1"],
- ),
- (
- "unscored reports follow scored ones",
- [("a", REVIEW, "P1", None, None, None), ("b", REVIEW, "P3", None, 0.1, None)],
- ["b", "a"],
- ),
- (
- "a report likely dismissed as wrong is hidden unless it is P0",
- [
- ("s1", REVIEW, "P2", 0.9, None, 5.0),
- ("s2", REVIEW, "P2", 0.1, None, 1.0),
- ("u1", BriefingReportRelation.URGENT_UNOWNED, "P0", 0.1, None, 5.0),
- ],
- ["u1", "s2"],
- ),
- ]
- )
- def test_briefing_pick(self, _name: str, specs: list[_Spec], expected: list[str]) -> None:
- assert [c.report_id for c in _briefing_pick(_candidates(specs))] == expected
-
class TestSummaryLead(SimpleTestCase):
@parameterized.expand(
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index b9d850d969a2..fa85e9703ac6 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -1624,7 +1624,6 @@ class TestSignalReportListAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
body = response.json()
- # Neither report has a score or a priority, so the newest comes first.
assert [row["id"] for row in body["results"]] == [str(reviewing.id)]
assert body["count"] == 2
@@ -1676,6 +1675,41 @@ class TestSignalReportListAPI(APIBaseTest):
assert [row["id"] for row in page["results"]] == [by_priority[None]]
assert page["count"] == 2
+ def test_for_you_uses_the_inbox_control_order_without_joining_the_sort_experiment(self):
+ titles: dict[str, str] = {}
+ for title, priority, open_score in [
+ ("P0 low score", "P0", 0.15),
+ ("P2 high score", "P2", 0.85),
+ ("P1 unscored", "P1", None),
+ ]:
+ report = self._create_report(title=title)
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.SUGGESTED_REVIEWERS,
+ content=json.dumps([{"user_uuid": str(self.user.uuid)}]),
+ )
+ self._priority_artefact(report, priority=priority)
+ if open_score is not None:
+ self._ranking_score_artefact(report, scores={"open": open_score})
+ titles[str(report.id)] = title
+ flag = "products.signals.backend.ranking.inbox_sort.posthoganalytics.get_feature_flag"
+
+ with patch(flag, return_value="control"):
+ inbox = self.client.get(self._list_url(sort="recommended", suggested_reviewers=str(self.user.uuid)))
+ with patch(flag, return_value="open") as get_flag:
+ for_you = self.client.get(f"{self._list_url()}for_you/?limit=20")
+
+ assert inbox.status_code == status.HTTP_200_OK
+ assert for_you.status_code == status.HTTP_200_OK
+ get_flag.assert_not_called()
+ assert [titles[row["id"]] for row in for_you.json()["results"]] == [
+ "P0 low score",
+ "P1 unscored",
+ "P2 high score",
+ ]
+ assert for_you.json()["results"] == inbox.json()["results"]
+
def test_is_suggested_reviewer_uses_latest_reviewers_row(self):
# suggested_reviewers is append-only: an older row listing the user must not keep them
# flagged after a newer row drops them (latest-wins).
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 4a4bf3d23105..4bcff6f67dbe 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -118,7 +118,7 @@ from products.signals.backend.billing import (
refund_ineligibility_reason,
report_pr_is_merged,
)
-from products.signals.backend.briefing_reports import open_report_counts, reports_for_briefing
+from products.signals.backend.briefing_reports import open_report_counts, reports_for_person
from products.signals.backend.dismissal_notes import forward_dismissal_note
from products.signals.backend.enums import ReportPriority
from products.signals.backend.facade.api import emit_signal
@@ -2030,7 +2030,7 @@ class SignalReportViewSet(
def filter_queryset(self, queryset):
queryset = super().filter_queryset(queryset)
- if self.action != "list":
+ if self.action not in {"list", "for_you"}:
# A by-ID lookup has nothing to order. More importantly, keeping list ordering here
# forces every detail request to compute status/priority/reviewer annotations that
# cannot affect which primary-key row is returned.
@@ -2059,6 +2059,9 @@ class SignalReportViewSet(
@cached_property
def _inbox_ranker(self) -> InboxRanker | None:
+ if self.action == "for_you":
+ # The recommended sort experiment covers the web inbox only, so `for_you` uses its control order.
+ return "priority"
params = self.request.query_params
if params.get("ordering") is not None or params.get("sort") != "recommended":
return None
@@ -2666,8 +2669,8 @@ class SignalReportViewSet(
summary="List the reports that matter most to the current user",
description=(
"One page of the open, actionable reports for the current user, and how many there are in "
- "total. The ranking picks the page and priority orders it for display. Uses the same ranking and count as the Today briefing, so this is the short "
- "list to show someone who asks what needs them. Pass `exclude` to leave out reports already "
+ "total, in the inbox priority order: priority, then status, then most recently updated. Uses the "
+ "same ranking and count as the Today briefing, so this is the short list to show someone who asks what needs them. Pass `exclude` to leave out reports already "
"on screen and `offset` to get the next page. Pass `include_unowned=false` to leave out the "
"P0 reports nobody owns, which belong to the project rather than to this person."
),
@@ -2677,19 +2680,12 @@ class SignalReportViewSet(
user = cast(User, request.user)
query = request.validated_query_data
excluded = [str(report_id) for report_id in query["exclude"]]
- ranked_ids = [
- report.report_id
- for report in reports_for_briefing(
- team_id=self.team_id,
- user_id=user.id,
- limit=query["limit"],
- include_unowned=query["include_unowned"],
- offset=query["offset"],
- exclude_report_ids=excluded,
- )
- ]
- by_id = {str(report.id): report for report in self.get_queryset().filter(id__in=ranked_ids)}
- reports = [by_id[report_id] for report_id in ranked_ids if report_id in by_id]
+ for_person = reports_for_person(self.team_id, user, include_unowned=query["include_unowned"])
+ queryset = (
+ self.filter_queryset(self.get_queryset()).filter(id__in=for_person.values("id")).exclude(id__in=excluded)
+ )
+ offset = query["offset"]
+ reports = list(queryset[offset : offset + query["limit"]])
counts = open_report_counts(
team_id=self.team_id, user=user, exclude_report_ids=excluded, include_unowned=query["include_unowned"]
)
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index 9653eb691206..829b839498e9 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -3278,7 +3278,7 @@ export interface SignalReportBulkStateResponseApi {
}
export interface SignalReportsForYouResponseApi {
- /** One page of the open, actionable reports that matter most to the current user. The ranking model picks which reports make the page; the page is then in display order: by priority, P0 first and reports without a priority last, then best first within a priority. They are reports waiting for their input, reports they claimed, reports naming them as a reviewer, and P0 reports that nobody owns unless `include_unowned` is false. The Today briefing ranks reports the same way. */
+ /** One page of the open, actionable reports that matter most to the current user, in the inbox priority order: priority, then status, then most recently updated. They are reports waiting for their input, reports they claimed, reports naming them as a reviewer, and P0 reports that nobody owns unless `include_unowned` is false. The Today briefing ranks reports the same way. */
results: SignalReportListApi[]
/** How many open, actionable reports are for the current user, on every page together, without the `exclude` ids. Counted over the same set as `results`, so it follows `include_unowned` too. */
count: number
@@ -8011,7 +8011,7 @@ export type SignalsReportsForYouRetrieveParams = {
*/
exclude?: string[]
/**
- * Whether to include P0 reports that nobody owns. These belong to the project rather than to one person, and they rank above everything else, so a surface that only shows a person's own work passes false. Defaults to true.
+ * Whether to include P0 reports that nobody owns. These belong to the project rather than to one person, so a surface that only shows a person's own work passes false. Defaults to true.
*/
include_unowned?: boolean
/**
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index f5dc1aa2ec20..7f86cfd7e36d 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -1276,7 +1276,7 @@ export const getSignalsReportsForYouRetrieveUrl = (projectId: string, params?: S
}
/**
- * One page of the open, actionable reports for the current user, and how many there are in total. The ranking picks the page and priority orders it for display. Uses the same ranking and count as the Today briefing, so this is the short list to show someone who asks what needs them. Pass `exclude` to leave out reports already on screen and `offset` to get the next page. Pass `include_unowned=false` to leave out the P0 reports nobody owns, which belong to the project rather than to this person.
+ * One page of the open, actionable reports for the current user, and how many there are in total, in the inbox priority order: priority, then status, then most recently updated. Uses the same ranking and count as the Today briefing, so this is the short list to show someone who asks what needs them. Pass `exclude` to leave out reports already on screen and `offset` to get the next page. Pass `include_unowned=false` to leave out the P0 reports nobody owns, which belong to the project rather than to this person.
* @summary List the reports that matter most to the current user
*/
export const signalsReportsForYouRetrieve = async (
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 3a80392b826f..5b0d6d34ce6d 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -102038,7 +102038,7 @@ export namespace Schemas {
}
export interface SignalReportsForYouResponse {
- /** One page of the open, actionable reports that matter most to the current user. The ranking model picks which reports make the page; the page is then in display order: by priority, P0 first and reports without a priority last, then best first within a priority. They are reports waiting for their input, reports they claimed, reports naming them as a reviewer, and P0 reports that nobody owns unless `include_unowned` is false. The Today briefing ranks reports the same way. */
+ /** One page of the open, actionable reports that matter most to the current user, in the inbox priority order: priority, then status, then most recently updated. They are reports waiting for their input, reports they claimed, reports naming them as a reviewer, and P0 reports that nobody owns unless `include_unowned` is false. The Today briefing ranks reports the same way. */
results: SignalReportList[];
/** How many open, actionable reports are for the current user, on every page together, without the `exclude` ids. Counted over the same set as `results`, so it follows `include_unowned` too. */
count: number;
@@ -129729,7 +129729,7 @@ export namespace Schemas {
*/
exclude?: string[];
/**
- * Whether to include P0 reports that nobody owns. These belong to the project rather than to one person, and they rank above everything else, so a surface that only shows a person's own work passes false. Defaults to true.
+ * Whether to include P0 reports that nobody owns. These belong to the project rather than to one person, so a surface that only shows a person's own work passes false. Defaults to true.
*/
include_unowned?: boolean;
/**