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): expose the served inbox ranking score to staff (#107078)

posthog[bot]d2ecb8d52361
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 6251737e5e93..ce6a1ecce379 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1257,7 +1257,8 @@ class SignalReportArtefact(UUIDModel):
}
)
# Rows the scoring sweep writes on every text edit and every new serving manifest. They record
- # no activity a user can see, so the artefact count and the artefact log leave them out.
+ # no activity a user can see, so the artefact count leaves them out, and the artefact log shows
+ # them to staff only.
SYSTEM_SCORING_ARTEFACT_TYPES: frozenset[str] = frozenset({ArtefactType.RANKING_SCORE})
# A `report_link` graph is written by hand or by an agent, one report at a time, so a real
# chain is a handful of reports deep. The budgets guard the cycle walk on the write path
diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.py
index e48ce3efa854..cdc629c507ce 100644
--- a/products/signals/backend/serializers.py
+++ b/products/signals/backend/serializers.py
@@ -7,6 +7,7 @@ from typing import TYPE_CHECKING, cast
from django.db.models import TextChoices
from django.utils import timezone
+import structlog
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_field, extend_schema_serializer
from rest_framework import serializers
@@ -48,7 +49,7 @@ if TYPE_CHECKING:
from products.signals.backend.implementation_pr import ImplementationPr
from products.signals.backend.report_claims import ReportClaim
-from .artefact_schemas import NON_WRITABLE_ARTEFACT_TYPES
+from .artefact_schemas import NON_WRITABLE_ARTEFACT_TYPES, RankingScore
from .daily_limit import reports_generated_today, team_day_start
from .models import (
GITHUB_LABEL_NAME_MAX_LENGTH,
@@ -85,6 +86,8 @@ from .report_metrics import (
)
from .tracker_issues import TRACKER_TARGET_REQUIRED_FIELDS, issue_reference, validated_github_repository
+logger = structlog.get_logger(__name__)
+
DEFAULT_SESSION_ANALYSIS_SAMPLE_RATE = 0.1
@@ -1085,6 +1088,24 @@ class ReportMetricListSerializer(ReportMetricSerializer):
query = None # type: ignore[assignment] # removes the inherited field from the list projection
+class ReportRankingSerializer(serializers.Serializer):
+ served_key = serializers.CharField(
+ help_text="Key of the served model in the scoring pass, as `<model_name>@<model_version>`."
+ )
+ model_name = serializers.CharField(help_text="Feature family of the served model.")
+ model_version = serializers.CharField(help_text="Training partition of the served model, as `YYYY-MM-DD`.")
+ manifest_version = serializers.CharField(help_text="Version of the serving manifest that chose the model.")
+ scored_at = serializers.DateTimeField(help_text="When the scoring sweep scored the report.")
+ scores = serializers.DictField(
+ child=serializers.FloatField(),
+ help_text="Outcome head name to its calibrated probability. Empty when the served model skipped the report.",
+ )
+ readable_heads = serializers.ListField(
+ child=serializers.CharField(),
+ help_text="Heads whose holdout AUC the training run could read. Treat scores of other heads with caution.",
+ )
+
+
class SignalReportSerializer(serializers.ModelSerializer):
artefact_count = serializers.IntegerField(read_only=True)
charts = ReportChartSerializer(
@@ -1201,6 +1222,12 @@ class SignalReportSerializer(serializers.ModelSerializer):
"The general view lists every report regardless of this value."
),
)
+ ranking = serializers.SerializerMethodField(
+ help_text=(
+ "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."
+ ),
+ )
collapsed_note_count = serializers.SerializerMethodField(
help_text=(
"How many scout notes this report received beyond the few its work log keeps as entries. "
@@ -1248,6 +1275,7 @@ class SignalReportSerializer(serializers.ModelSerializer):
"refund_ineligibility_reason",
"billing_exempt_reason",
"channel_id",
+ "ranking",
]
read_only_fields = fields
extra_kwargs = {
@@ -1367,6 +1395,47 @@ class SignalReportSerializer(serializers.ModelSerializer):
value = data.get("repository")
return value if isinstance(value, str) and value else None
+ @extend_schema_field(ReportRankingSerializer(allow_null=True))
+ def get_ranking(self, obj: SignalReport) -> dict | None:
+ request = self.context.get("request")
+ if request is None or not request.user.is_staff:
+ return None
+
+ from products.signals.backend.ranking.model_contract import ( # noqa: PLC0415 — keeps numpy and pandas off the API import path
+ readable_head_names,
+ )
+
+ prefetched = getattr(obj, "prefetched_ranking_score_artefacts", None)
+ if prefetched is not None:
+ art = prefetched[0] if prefetched else None
+ else:
+ art = (
+ obj.artefacts.filter(type=SignalReportArtefact.ArtefactType.RANKING_SCORE)
+ .order_by("-created_at")
+ .first()
+ )
+ if art is None:
+ return None
+ try:
+ score = RankingScore.model_validate_json(art.content)
+ served = score.results[score.served_key]
+ heads = readable_head_names(served.metadata)
+ if not all(isinstance(head, str) and head for head in heads):
+ raise ValueError("readable head names must be non-empty strings")
+ readable_heads = sorted(heads)
+ except (ValueError, KeyError, TypeError, AttributeError):
+ logger.warning("signals.ranking_score.invalid_content", report_id=str(obj.id), artefact_id=str(art.id))
+ return None
+ return {
+ "served_key": score.served_key,
+ "model_name": served.model_name,
+ "model_version": served.model_version,
+ "manifest_version": score.manifest_version,
+ "scored_at": score.scored_at,
+ "scores": served.scores,
+ "readable_heads": readable_heads,
+ }
+
def get_source_products(self, obj: SignalReport) -> list[str]:
source_products_map: dict[str, list[str]] | None = self.context.get("source_products_map")
if source_products_map is not None:
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index f0b845fa31a4..d94a32d35485 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -1,6 +1,6 @@
import json
import uuid
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from typing import TYPE_CHECKING, cast
from urllib.parse import urlencode
@@ -713,6 +713,24 @@ class TestSignalReportListAPI(APIBaseTest):
report = self._create_report()
self._priority_artefact(report, priority="P1")
self._actionability_artefact(report, actionability="immediately_actionable")
+ self._ranking_score_artefact(report)
+
+ list_response = self.client.get(self._list_url())
+ assert list_response.status_code == status.HTTP_200_OK
+ row = next(r for r in list_response.json()["results"] if r["id"] == str(report.id))
+ assert row["artefact_count"] == 2
+
+ response = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{report.id}/")
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["artefact_count"] == 2
+
+ def _ranking_score_artefact(
+ self,
+ report: SignalReport,
+ content: str | None = None,
+ scores: dict[str, float] | None = None,
+ heads: list[dict] | None = None,
+ ) -> SignalReportArtefact:
served = RankingModelResult(
model_name="report_embeddings",
model_version="2026-09-01",
@@ -720,28 +738,84 @@ class TestSignalReportListAPI(APIBaseTest):
roles=["served"],
feature_schema_version=1,
status="scored",
- scores={"open": 0.5},
+ scores=scores or {"open": 0.5, "merged": 0.2},
+ metadata={"heads": heads or [{"head": "open", "readable": True}, {"head": "merged", "readable": False}]},
)
- SignalReportArtefact.objects.create(
- team=self.team,
- report=report,
- type=SignalReportArtefact.ArtefactType.RANKING_SCORE,
- content=RankingScore(
- scored_at=timezone.now(),
+ challenger = RankingModelResult(
+ model_name="report_tabular",
+ model_version="2026-09-10",
+ model_kind="xgboost",
+ roles=["challenger"],
+ feature_schema_version=1,
+ status="scored",
+ scores={"open": 0.9},
+ )
+ if content is None:
+ 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(),
+ results={served.key: served, challenger.key: challenger},
+ ).model_dump_json()
+ return SignalReportArtefact.objects.create(
+ team=self.team, report=report, type=SignalReportArtefact.ArtefactType.RANKING_SCORE, content=content
)
+ @parameterized.expand(
+ [
+ (
+ "staff_sees_the_served_result",
+ True,
+ None,
+ None,
+ {
+ "served_key": "report_embeddings@2026-09-01",
+ "model_name": "report_embeddings",
+ "model_version": "2026-09-01",
+ "manifest_version": "manifest",
+ "scored_at": "2026-09-20T12:00:00Z",
+ "scores": {"open": 0.5, "merged": 0.2},
+ "readable_heads": ["open"],
+ },
+ ),
+ ("non_staff_sees_nothing", False, None, None, None),
+ ("invalid_content_reads_as_none", True, '{"served_key": "missing"}', None, None),
+ ("null_readable_head_reads_as_none", True, None, [{"head": None, "readable": True}], None),
+ ]
+ )
+ def test_ranking_field_in_the_list_and_the_detail(self, _name, is_staff, content, heads, expected):
+ self.user.is_staff = is_staff
+ self.user.save()
+ report = self._create_report()
+ stale = self._ranking_score_artefact(report, scores={"open": 0.9})
+ SignalReportArtefact.objects.filter(pk=stale.pk).update(created_at=timezone.now() - timedelta(days=1))
+ self._ranking_score_artefact(report, content=content, heads=heads)
+ unscored = self._create_report(title="Unscored")
+
list_response = self.client.get(self._list_url())
assert list_response.status_code == status.HTTP_200_OK
- row = next(r for r in list_response.json()["results"] if r["id"] == str(report.id))
- assert row["artefact_count"] == 2
+ rows = {row["id"]: row for row in list_response.json()["results"]}
+ assert rows[str(report.id)]["ranking"] == expected
+ assert rows[str(unscored.id)]["ranking"] is None
response = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{report.id}/")
assert response.status_code == status.HTTP_200_OK
- assert response.json()["artefact_count"] == 2
+ assert response.json()["ranking"] == expected
+
+ @parameterized.expand([("staff", True, ["ranking_score"]), ("non_staff", False, [])])
+ def test_artefact_routes_show_ranking_scores_to_staff_only(self, _name, is_staff, expected_types):
+ self.user.is_staff = is_staff
+ self.user.save()
+ report = self._create_report()
+ artefact = self._ranking_score_artefact(report)
+ url = f"/api/projects/{self.team.id}/signals/reports/{report.id}/artefacts/"
+
+ response = self.client.get(url)
+ assert response.status_code == status.HTTP_200_OK
+ assert [row["type"] for row in response.json()["results"]] == expected_types
+
+ detail = self.client.get(f"{url}{artefact.id}/")
+ assert detail.status_code == (status.HTTP_200_OK if is_staff else status.HTTP_404_NOT_FOUND)
def test_filter_by_channel_id_narrows_to_that_space(self):
channel = Channel.objects.create(team=self.team, name="Reports")
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index e8194dad98b7..4fed170ee1ea 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -1107,6 +1107,7 @@ class SignalReportViewSet(
qs = self._annotate_channel_id(qs)
qs = self._apply_signal_report_status_filter(qs)
qs = self._prefetch_signal_report_priority_artefacts(qs)
+ qs = self._prefetch_signal_report_ranking_score(qs)
qs = self._annotate_is_suggested_reviewer(qs)
return annotate_first_billable_pr_run_at(qs)
qs = queryset
@@ -1144,6 +1145,7 @@ class SignalReportViewSet(
# `bulk_state` answers with one outcome per id, never a serialized report, and the list
# ordering that reads this value does not apply to it either.
qs = self._annotate_is_suggested_reviewer(qs)
+ qs = self._prefetch_signal_report_ranking_score(qs)
if self.action not in self._MULTI_REPORT_ACTIONS:
# This correlated subquery costs one walk per matching row. Multi-row actions do
# without it: `list` serves the value from a batched page lookup, and `bulk_state`
@@ -1709,6 +1711,20 @@ class SignalReportViewSet(
),
)
+ def _prefetch_signal_report_ranking_score(self, queryset):
+ # Scores are internal model output, so only staff requests pay for the lookup.
+ if not self.request.user.is_staff:
+ return queryset
+ return queryset.prefetch_related(
+ Prefetch(
+ "artefacts",
+ queryset=SignalReportArtefact.objects.filter(
+ type=SignalReportArtefact.ArtefactType.RANKING_SCORE
+ ).order_by("-created_at")[:1],
+ to_attr="prefetched_ranking_score_artefacts",
+ ),
+ )
+
def _annotate_is_suggested_reviewer(self, queryset):
# Annotate is_suggested_reviewer by resolving the current user's GitHub login
# and matching it against the indexed reviewer rows. This stays fresh
@@ -4668,15 +4684,17 @@ class SignalReportArtefactViewSet(
def safely_get_queryset(self, queryset):
# Mirror SignalReportViewSet: a deleted parent report is unreachable, so
# its artefacts must be too (otherwise a known UUID would bypass deletion).
- return queryset.filter(
+ queryset = queryset.filter(
report_id=self._validated_report_id(),
team=self.team,
).exclude(report__status=SignalReport.Status.DELETED)
+ # Scoring rows are staff-only on every artefact route, not only in the log.
+ if not self.request.user.is_staff:
+ queryset = queryset.exclude(type__in=SignalReportArtefact.SYSTEM_SCORING_ARTEFACT_TYPES)
+ return queryset
def list(self, request, *args, **kwargs):
- queryset = self.filter_queryset(self.get_queryset()).exclude(
- type__in=SignalReportArtefact.SYSTEM_SCORING_ARTEFACT_TYPES
- )
+ queryset = self.filter_queryset(self.get_queryset())
# Surface legacy `SignalReportTask` associations as synthetic `task_run` artefacts so a
# report's research / implementation runs appear in the log even before the backfill has
# converted its gate rows. Merged into the materialized log (de-duplicated against the real
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index d3b64d6832ad..66dc26061048 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -527,6 +527,28 @@ export const SignalReportBillingExemptReasonEnumApi = {
PosthogSystem: 'posthog_system',
} as const
+/**
+ * Outcome head name to its calibrated probability. Empty when the served model skipped the report.
+ */
+export type ReportRankingApiScores = { [key: string]: number }
+
+export interface ReportRankingApi {
+ /** Key of the served model in the scoring pass, as `<model_name>@<model_version>`. */
+ served_key: string
+ /** Feature family of the served model. */
+ model_name: string
+ /** Training partition of the served model, as `YYYY-MM-DD`. */
+ model_version: string
+ /** Version of the serving manifest that chose the model. */
+ manifest_version: string
+ /** When the scoring sweep scored the report. */
+ scored_at: string
+ /** Outcome head name to its calibrated probability. Empty when the served model skipped the report. */
+ scores: ReportRankingApiScores
+ /** Heads whose holdout AUC the training run could read. Treat scores of other heads with caution. */
+ readable_heads: string[]
+}
+
export interface SignalReportListApi {
readonly id: string
/** @nullable */
@@ -631,6 +653,8 @@ export interface SignalReportListApi {
* @nullable
*/
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
}
export interface PaginatedSignalReportListListApi {
@@ -817,6 +841,8 @@ export interface SignalReportApi {
* @nullable
*/
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
}
/**
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 2a83cf04902d..9b6acefe21c6 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -66799,6 +66799,28 @@ export namespace Schemas {
PosthogSystem: 'posthog_system',
} as const;
+ /**
+ * Outcome head name to its calibrated probability. Empty when the served model skipped the report.
+ */
+ export type ReportRankingScores = {[key: string]: number};
+
+ export interface ReportRanking {
+ /** Key of the served model in the scoring pass, as `<model_name>@<model_version>`. */
+ served_key: string;
+ /** Feature family of the served model. */
+ model_name: string;
+ /** Training partition of the served model, as `YYYY-MM-DD`. */
+ model_version: string;
+ /** Version of the serving manifest that chose the model. */
+ manifest_version: string;
+ /** When the scoring sweep scored the report. */
+ scored_at: string;
+ /** Outcome head name to its calibrated probability. Empty when the served model skipped the report. */
+ scores: ReportRankingScores;
+ /** Heads whose holdout AUC the training run could read. Treat scores of other heads with caution. */
+ readable_heads: string[];
+ }
+
export interface SignalReportList {
readonly id: string;
/** @nullable */
@@ -66903,6 +66925,8 @@ export namespace Schemas {
* @nullable
*/
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;
}
export interface PaginatedSignalReportListList {
@@ -86263,6 +86287,8 @@ export namespace Schemas {
* @nullable
*/
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;
}
/**