:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): rank briefing reports by merge and action chance (#110657)
Vojta Bartoš62dea3abf920
diff --git a/products/signals/backend/briefing_reports.py b/products/signals/backend/briefing_reports.pyindex 2351a8ff9e7b..b7ffbd75b647 100644--- a/products/signals/backend/briefing_reports.py+++ b/products/signals/backend/briefing_reports.py@@ -1,15 +1,18 @@"""Reports that matter to one person, for the Today briefing.-The briefing ranks items across products, so this module only answers "which reports relate to this-person, and how". It does not order across relations; the caller does that.+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."""import re-from collections.abc import Sequence+from bisect import bisect_left+from collections.abc import Mapping, Sequencefrom datetime import datetimefrom enum import StrEnum+from typing import Any-from django.db.models import Count, Q, QuerySet+from django.db.models import Case, CharField, Count, F, Func, JSONField, OuterRef, Q, QuerySet, Subquery, Value, When+from django.db.models.functions import Castimport pydanticimport structlog@@ -18,7 +21,7 @@ from posthog.dataclasses import frozenfrom posthog.models import Team, Userfrom products.signals.backend.artefact_attribution import ArtefactAttribution-from products.signals.backend.artefact_schemas import ActionabilityChoice, RankingScore, priority_from_judgment+from products.signals.backend.artefact_schemas import ActionabilityChoice, priority_from_judgmentfrom products.signals.backend.implementation_pr import (fetch_implementation_pr_state_for_reports,implementation_pr_report_filter,@@ -38,6 +41,15 @@ _SUMMARY_LIMIT = 300# The hover card shows more of the summary than the briefing writer reads.SUMMARY_LEAD_LIMIT = 450PR_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 = 500class BriefingReportRelation(StrEnum):@@ -50,7 +62,6 @@ class BriefingReportRelation(StrEnum):URGENT_UNOWNED = "urgent_unowned"-_RELATION_ORDER = {relation: index for index, relation in enumerate(BriefingReportRelation)}_PRIORITY_ORDER = {"P0": 0, "P1": 1, "P2": 2, "P3": 3, "P4": 4}@@ -118,28 +129,124 @@ def _priorities(report_ids: Sequence[str]) -> dict[str, str]:return latest-def _pr_merged_probabilities(report_ids: Sequence[str]) -> dict[str, float]:- """The served model's `pr_merged` probability from each report's latest score.+@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."""+ priority = Func(+ Cast(F("content"), output_field=JSONField()),+ Value("priority"),+ function="jsonb_extract_path_text",+ output_field=CharField(),+ )+ return Subquery(+ SignalReportArtefact.objects.filter(+ report_id=OuterRef("id"), type=SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT+ )+ .order_by("-created_at")+ .annotate(+ _priority=Case(When(_json_object_content(), then=priority), default=Value(None), output_field=CharField())+ )+ .values("_priority")[:1],+ output_field=CharField(),+ )+++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 thantrusted. 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,)- probabilities: dict[str, float] = {}- for report_id, content in _latest_artefacts(report_ids, SignalReportArtefact.ArtefactType.RANKING_SCORE).items():- try:- score = RankingScore.model_validate_json(content)- except pydantic.ValidationError:- logger.warning("signals.briefing.ranking_score_unreadable", report_id=report_id)- continue- served = score.results[score.served_key]- probability = served.scores.get(PR_MERGED_HEAD)- if probability is not None and PR_MERGED_HEAD in readable_head_names(served.metadata):- probabilities[report_id] = probability- return probabilities+ 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]:@@ -175,100 +282,139 @@ def _source_products(team_id: int, report_ids: Sequence[str]) -> dict[str, list[return {report_id: meta.source_products for report_id, meta in metadata.items()}-def _briefing_order(- relation: BriefingReportRelation, priority: str | None, merge_chance: float | None, updated_at: datetime-) -> tuple[float, ...]:- """Relation first. Inside a relation: P0, then the higher chance of a merged PR, then priority,- then newest. A report without a score follows the scored ones, so with no scores at all the- order falls back to priority."""- return (- _RELATION_ORDER[relation],- 0 if priority == "P0" else 1,- 0 if merge_chance is not None else 1,- -(merge_chance or 0.0),- _PRIORITY_ORDER.get(priority or "", 5),- -updated_at.timestamp(),- )+@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], limit: int | None) -> 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 `limit` or 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.get(candidate.priority or "", 5),+ -candidate.updated_at.timestamp(),+ )+ ranked = sorted(kept, key=order)+ return ranked if limit is None else ranked[:limit]-def reports_for_briefing(- *, team_id: int, user_id: int, limit_per_relation: int = 5, limit: int | None = None-) -> list[BriefingReport]:++def reports_for_briefing(*, team_id: int, user_id: int, limit: int | None = None) -> 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. Each relation- contributes its newest `limit_per_relation` rows (more for urgent-unowned, which is filtered to- P0 afterwards) to the candidate set; `limit` then keeps the best of the ranked set.+ 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 and `limit` keeps the best of them."""- open_reports = _open_reports(team_id)names_me = _names_person(team_id, User.objects.get(id=user_id))claimed = reports_with_active_claim(team_id=team_id, actor=ArtefactAttribution.from_user(user_id))unowned = ~reports_with_active_claim(team_id=team_id) & ~implementation_pr_report_filter(team_id=team_id, active_only=True)- buckets: list[tuple[BriefingReportRelation, Q]] = [- (BriefingReportRelation.WAITING_FOR_YOU, names_me & Q(status=SignalReport.Status.PENDING_INPUT)),- (BriefingReportRelation.CLAIMED, claimed),- (BriefingReportRelation.SUGGESTED_REVIEWER, names_me & Q(status=SignalReport.Status.READY)),- (- BriefingReportRelation.URGENT_UNOWNED,+ relation = Case(+ When(+ names_me & Q(status=SignalReport.Status.PENDING_INPUT), then=Value(BriefingReportRelation.WAITING_FOR_YOU)+ ),+ When(claimed, then=Value(BriefingReportRelation.CLAIMED)),+ When(names_me & Q(status=SignalReport.Status.READY), then=Value(BriefingReportRelation.SUGGESTED_REVIEWER)),+ When(unowned& Q(status=SignalReport.Status.READY,latest_actionability=ActionabilityChoice.IMMEDIATELY_ACTIONABLE.value,+ briefing_priority="P0",),+ then=Value(BriefingReportRelation.URGENT_UNOWNED),),- ]- seen: set[str] = set()- picked: list[tuple[BriefingReportRelation, SignalReport]] = []- for relation, condition in buckets:- # Urgent-unowned is only meaningful at P0, which is filtered after the priority lookup,- # so it reads a wider page than the other buckets.- page = limit_per_relation * 4 if relation == BriefingReportRelation.URGENT_UNOWNED else limit_per_relation- for report in open_reports.filter(condition).order_by("-updated_at")[:page]:- key = str(report.id)- if key not in seen:- seen.add(key)- picked.append((relation, report))- # Priorities decide which urgent-unowned rows survive, so they load for every picked row; the- # other lookups only feed the rows that make it into the result.- priorities = _priorities([str(report.id) for _, report in picked])- chosen = [- (relation, report)- for relation, report in picked- if relation != BriefingReportRelation.URGENT_UNOWNED or priorities.get(str(report.id)) == "P0"- ]- merge_chances = _pr_merged_probabilities([str(report.id) for _, report in chosen])- # Rank the whole candidate set before any limit, so a sixth report that waits for the person- # outranks the first claimed one instead of falling off its own bucket.- chosen.sort(- key=lambda pair: _briefing_order(- pair[0], priorities.get(str(pair[1].id)), merge_chances.get(str(pair[1].id)), pair[1].updated_at- )+ default=Value(None),+ output_field=CharField(),)- if limit is not None:- chosen = chosen[:limit]- chosen_ids = [str(report.id) for _, report in chosen]- source_products = _source_products(team_id, chosen_ids)- with_pr = set(- SignalReport.objects.filter(team_id=team_id, id__in=chosen_ids)- .filter(implementation_pr_report_filter(team_id=team_id))- .values_list("id", flat=True)+ rows = (+ _open_reports(team_id)+ .annotate(briefing_priority=_latest_priority())+ .annotate(briefing_relation=relation)+ .filter(briefing_relation__isnull=False)+ .annotate(briefing_heads=_latest_served_heads())+ .order_by("-updated_at")+ .values_list("id", "updated_at", "briefing_relation", "briefing_priority", "briefing_heads")[:_CANDIDATE_LIMIT]+ )+ chosen = _briefing_pick(+ [+ _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+ ],+ limit,)+ 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=str(report.id),- relation=relation,+ report_id=candidate.report_id,+ relation=candidate.relation,title=_trimmed(report.title, 200) or "Untitled report",summary=_trimmed(report.summary, _SUMMARY_LIMIT),status=report.status,- priority=priorities.get(str(report.id)),- has_implementation_pr=report.id in with_pr,- source_products=source_products.get(str(report.id), []),+ 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=merge_chances.get(str(report.id)),+ pr_merged_probability=candidate.scores.pr_merged,)- for relation, report in chosen+ for candidate in chosen+ if (report := reports.get(candidate.report_id)) is not None]diff --git a/products/signals/backend/test/test_briefing_reports.py b/products/signals/backend/test/test_briefing_reports.pyindex 6ead6f9ad248..04dcbef8118e 100644--- a/products/signals/backend/test/test_briefing_reports.py+++ b/products/signals/backend/test/test_briefing_reports.py@@ -5,8 +5,11 @@ from types import SimpleNamespacefrom typing import castfrom posthog.test.base import BaseTest+from unittest.mock import patch+from django.db import connectionfrom django.test import SimpleTestCase+from django.test.utils import CaptureQueriesContextfrom django.utils import timezonefrom parameterized import parameterized@@ -15,7 +18,9 @@ from rest_framework.request import Requestfrom products.signals.backend.artefact_schemas import ActionabilityChoice, RankingModelResult, RankingScorefrom products.signals.backend.briefing_reports import (BriefingReportRelation,- _briefing_order,+ _briefing_pick,+ _BriefingCandidate,+ _ServedScores,open_report_counts,report_details,reports_for_briefing,@@ -25,6 +30,8 @@ from products.signals.backend.models import SignalReport, SignalReportArtefactfrom products.signals.backend.report_metric_access import ReportMetricAccessPolicyfrom 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:@@ -135,6 +142,14 @@ class TestReportsForBriefing(BaseTest):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)@@ -143,53 +158,140 @@ class TestReportsForBriefing(BaseTest):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-class TestBriefingOrder(SimpleTestCase):+ 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)+++_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([(- "a report waiting for the person beats one they claimed",+ "merge chance decides across relations",[- ("a", "P3", 0.9, BriefingReportRelation.CLAIMED),- ("b", "P1", 0.1, BriefingReportRelation.WAITING_FOR_YOU),+ ("w1", WAITING, "P1", 0.02, None, None),+ ("s1", REVIEW, "P3", 0.4, None, None),+ ("c1", BriefingReportRelation.CLAIMED, "P3", 0.1, None, None),],- ["b", "a"],+ ["s1", "c1", "w1"],),(- "merge chance beats priority inside a relation",+ "a high action chance ranks a report with a low merge chance",[- ("a", "P2", 0.8, BriefingReportRelation.SUGGESTED_REVIEWER),- ("b", "P1", 0.2, BriefingReportRelation.SUGGESTED_REVIEWER),+ ("merge", REVIEW, "P3", 0.3, 0.1, None),+ ("middle", REVIEW, "P3", 0.2, 0.2, None),+ ("act", WAITING, "P2", 0.01, 0.9, None),],- ["a", "b"],+ ["act", "merge", "middle"],),(- "P0 stays first",+ "the two heads compare by rank, not by value",[- ("b", "P1", 0.9, BriefingReportRelation.SUGGESTED_REVIEWER),- ("a", "P0", 0.05, BriefingReportRelation.SUGGESTED_REVIEWER),+ ("merge", REVIEW, "P3", 0.05, 0.001, None),+ ("act", REVIEW, "P2", 0.01, 0.5, None),+ ("low", REVIEW, "P3", 0.02, 0.2, None),],- ["a", "b"],+ ["act", "merge", "low"],),(- "unscored reports follow scored ones",+ "P0 comes first",[- ("a", "P1", None, BriefingReportRelation.SUGGESTED_REVIEWER),- ("b", "P3", 0.1, BriefingReportRelation.SUGGESTED_REVIEWER),+ ("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_order(- self, _name: str, reports: list[tuple[str, str, float | None, BriefingReportRelation]], expected: list[str]- ) -> None:- updated_at = datetime(2026, 9, 29, tzinfo=UTC)- ordered = sorted(reports, key=lambda r: _briefing_order(r[3], r[1], r[2], updated_at))+ 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), limit=None)] == expected++ def test_the_top_n_is_always_the_first_n_of_the_same_list(self) -> None:+ candidates = _candidates(+ [+ ("w1", WAITING, "P2", 0.05, 0.6, None),+ ("w2", WAITING, "P3", None, None, None),+ ("s1", REVIEW, "P3", 0.3, 0.1, None),+ ("s2", REVIEW, "P1", 0.2, None, None),+ ("c1", BriefingReportRelation.CLAIMED, "P4", 0.25, 0.3, None),+ ]+ )+ full = [c.report_id for c in _briefing_pick(candidates, limit=None)]- assert [report_id for report_id, *_ in ordered] == expected+ for limit in range(1, len(candidates) + 1):+ assert [c.report_id for c in _briefing_pick(candidates, limit=limit)] == full[:limit]class TestSummaryLead(SimpleTestCase):diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.pyindex c83ad9759230..fe670fa71393 100644--- a/products/signals/backend/test/test_signal_report_api.py+++ b/products/signals/backend/test/test_signal_report_api.py@@ -1237,15 +1237,16 @@ class TestSignalReportListAPI(APIBaseTest):)return report- waiting = report_naming_me("Waits for my input", SignalReport.Status.PENDING_INPUT)- report_naming_me("Names me as reviewer", SignalReport.Status.READY)+ report_naming_me("Waits for my input", SignalReport.Status.PENDING_INPUT)+ reviewing = report_naming_me("Names me as reviewer", SignalReport.Status.READY)self._create_report(title="Someone else's report")response = self.client.get(f"{self._list_url()}for_you/?limit=1")assert response.status_code == status.HTTP_200_OKbody = response.json()- assert [row["id"] for row in body["results"]] == [str(waiting.id)]+ # 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"] == 2def test_is_suggested_reviewer_uses_latest_reviewers_row(self):diff --git a/products/today/backend/logic/generate.py b/products/today/backend/logic/generate.pyindex 4323c08a578b..396ccc197916 100644--- a/products/today/backend/logic/generate.py+++ b/products/today/backend/logic/generate.py@@ -57,9 +57,7 @@ def _prepare(team_id: int, briefing_id: str) -> _PreparedRun | None:return Nonebriefing.status = BriefingStatus.WRITINGbriefing.save(update_fields=["status"])- reports = signals.reports_for_briefing(- team_id=team.id, user_id=user.id, limit_per_relation=MAX_ITEMS, limit=MAX_ITEMS- )+ reports = signals.reports_for_briefing(team_id=team.id, user_id=user.id, limit=MAX_ITEMS)fact_sheet = fact_sheet_for_reports(reports, team.id)summaries = {item.key: report.summary for item, report in zip(fact_sheet.items, reports, strict=True)}prompt = build_prompt(briefing, user, fact_sheet, summaries, recent_ready_briefings(briefing, RECENT_BRIEFINGS))