: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): mark inbox ranking scores stale after a report edit (#112545)
posthog[bot]8e6224d9e82b
diff --git a/products/signals/backend/ranking/staleness.py b/products/signals/backend/ranking/staleness.pynew file mode 100644index 000000000000..8cc153c8d007--- /dev/null+++ b/products/signals/backend/ranking/staleness.py@@ -0,0 +1,95 @@+"""When a served ranking score no longer describes the report's text.++A score is stale when the report's title or summary was edited after the vector the score read.+Only the two edit paths (the report PATCH and the scout `edit_report` tool) write the edit+artefacts, so the pipeline's own rewrites never mark a score stale.++The time a score is compared against is the landing time of the vector it read, not `scored_at`.+`scored_at` is the start of the sweep pass, and a team's vectors are read later in the pass. An+edit that is indexed in that gap gives a score on the new text with a `scored_at` before the edit.+The vector lands after the commit of the edit that produced it, so a vector newer than the edit+holds the edited text. A score with no vector time falls back to `scored_at`.++The serializer and the model sort both use this rule. Keep `is_stale_score` and+`annotate_stale_score` in step.+"""++from datetime import datetime++from django.db.models import Case, CharField, DateTimeField, Exists, F, Func, JSONField, OuterRef, QuerySet, Value, When+from django.db.models.functions import Cast, Coalesce++from products.signals.backend.artefact_schemas import RankingScore+from products.signals.backend.models import SignalReportArtefact++EDIT_ARTEFACT_TYPES: tuple[str, ...] = (+ SignalReportArtefact.ArtefactType.TITLE_CHANGE,+ SignalReportArtefact.ArtefactType.SUMMARY_CHANGE,+)++# The ISO 8601 form pydantic writes for an aware datetime. A naive value has no fixed instant, so it+# is not read. One cast error in the sort subquery would fail the whole list, so the value is+# parsed by a silent jsonpath `datetime()`, which gives NULL for an impossible date or time.+# That parser does not accept a `Z` offset, so `Z` becomes `+00:00` first.+_ISO_TIMESTAMP_PATTERN = r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$"+_SAFE_TIMESTAMP_TEMPLATE = (+ "(jsonb_path_query_first(to_jsonb(regexp_replace(%(expressions)s, 'Z$', '+00:00')), "+ "'$.datetime()', '{}', true) #>> '{}')"+)+++def score_read_at(score: RankingScore) -> datetime:+ """The time of the text the score describes."""+ return score.embedding_inserted_at or score.scored_at+++def is_stale_score(score: RankingScore, latest_edit_at: datetime | None) -> bool:+ read_at = score_read_at(score)+ # The sort does not read a naive time, so it is not stale here either.+ if latest_edit_at is None or read_at.tzinfo is None:+ return False+ return latest_edit_at > read_at+++def annotate_stale_score(scores: QuerySet[SignalReportArtefact]) -> QuerySet[SignalReportArtefact]:+ """Annotate `ranking_score` artefacts with `_score_is_stale`: true when an edit artefact is newer than the score.++ A row whose content is not a JSON object, or whose time does not parse, reads as not stale.+ """+ content = Cast(F("content"), output_field=JSONField())+ read_at_text = Coalesce(+ Func(content, Value("embedding_inserted_at"), function="jsonb_extract_path_text", output_field=CharField()),+ Func(content, Value("scored_at"), function="jsonb_extract_path_text", output_field=CharField()),+ output_field=CharField(),+ )+ return (+ scores.annotate(+ _score_read_at_text=Case(+ When(content__startswith="{", then=read_at_text),+ default=Value(None),+ output_field=CharField(),+ )+ )+ .annotate(+ _score_read_at=Case(+ When(+ _score_read_at_text__regex=_ISO_TIMESTAMP_PATTERN,+ then=Cast(+ Func(F("_score_read_at_text"), template=_SAFE_TIMESTAMP_TEMPLATE, output_field=CharField()),+ output_field=DateTimeField(),+ ),+ ),+ default=Value(None),+ output_field=DateTimeField(),+ )+ )+ .annotate(+ _score_is_stale=Exists(+ SignalReportArtefact.objects.filter(+ report_id=OuterRef("report_id"),+ type__in=EDIT_ARTEFACT_TYPES,+ created_at__gt=OuterRef("_score_read_at"),+ )+ )+ )+ )diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex 066afd9db114..7124d2820e3c 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -71,6 +71,7 @@ from .models import (SignalUserAutonomyConfig,)from .pull_request_label import DEFAULT_PULL_REQUEST_LABEL+from .ranking.staleness import EDIT_ARTEFACT_TYPES, is_stale_scorefrom .report_charts import CHART_SIZES, MAX_CHART_CAPTION_LENGTH, MAX_CHART_ID_LENGTH, MAX_CHART_TITLE_LENGTHfrom .report_generation.resolve_reviewers import enrich_reviewer_dicts_with_org_members, trusted_manual_reviewer_addersfrom .report_metric_access import ReportMetricAccessPolicy@@ -1164,6 +1165,12 @@ class ReportRankingSerializer(serializers.Serializer):child=serializers.CharField(),help_text="Heads whose holdout AUC the training run could read. Treat scores of other heads with caution.",)+ stale = serializers.BooleanField(+ help_text=(+ "True when the report's title or summary was edited after the text this score read. The score "+ "describes the old text: the inbox hides its lift and the model sort treats the report as unscored."+ ),+ )class SignalReportSerializer(serializers.ModelSerializer):@@ -1480,6 +1487,16 @@ class SignalReportSerializer(serializers.ModelSerializer):)if art is None:return None+ prefetched_edits = getattr(obj, "prefetched_latest_edit_artefacts", None)+ if prefetched_edits is not None:+ latest_edit_at = prefetched_edits[0].created_at if prefetched_edits else None+ else:+ latest_edit_at = (+ obj.artefacts.filter(type__in=EDIT_ARTEFACT_TYPES)+ .order_by("-created_at")+ .values_list("created_at", flat=True)+ .first()+ )try:score = RankingScore.model_validate_json(art.content)served = score.results[score.served_key]@@ -1501,6 +1518,7 @@ class SignalReportSerializer(serializers.ModelSerializer):"scores": served.scores,"lifts": lifts,"readable_heads": readable_heads,+ "stale": is_stale_score(score, latest_edit_at),}def get_source_products(self, obj: SignalReport) -> list[str]:diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.pyindex 7a8ff85fb6bd..ede810d74f11 100644--- a/products/signals/backend/test/test_signal_report_api.py+++ b/products/signals/backend/test/test_signal_report_api.py@@ -731,6 +731,7 @@ class TestSignalReportListAPI(APIBaseTest):scores: dict[str, float] | None = None,heads: list[dict] | None = None,lifts: dict[str, float] | None = None,+ embedding_inserted_at: datetime | None = None,) -> SignalReportArtefact:served = RankingModelResult(model_name="report_embeddings",@@ -755,6 +756,7 @@ class TestSignalReportListAPI(APIBaseTest):if content is None:content = RankingScore(scored_at=datetime(2026, 9, 20, 12, 0, tzinfo=UTC),+ embedding_inserted_at=embedding_inserted_at,manifest_version="manifest",served_key=served.key,results={served.key: served, challenger.key: challenger},@@ -780,6 +782,7 @@ class TestSignalReportListAPI(APIBaseTest):"scores": {"open": 0.5, "merged": 0.2},"lifts": {"open": 2.5},"readable_heads": ["open"],+ "stale": False,},),(@@ -800,6 +803,7 @@ class TestSignalReportListAPI(APIBaseTest):"scores": {"open": 0.5, "merged": 0.2},"lifts": {"open": 2.0},"readable_heads": ["open"],+ "stale": False,},),("non_staff_sees_nothing", False, None, None, None, None),@@ -826,6 +830,65 @@ class TestSignalReportListAPI(APIBaseTest):assert response.status_code == status.HTTP_200_OKassert response.json()["ranking"] == expected+ @parameterized.expand(+ [+ ("edit_before_the_scored_vector", datetime(2026, 9, 20, 11, 0, tzinfo=UTC), 10, False),+ ("edit_after_the_vector_before_scored_at", datetime(2026, 9, 20, 11, 0, tzinfo=UTC), 11, True),+ ("edit_after_scored_at_without_a_vector_time", None, 13, True),+ ("edit_before_scored_at_without_a_vector_time", None, 11, False),+ ("naive_vector_time_reads_as_not_stale", datetime(2026, 9, 20, 11, 0), 13, False),+ ]+ )+ def test_ranking_score_is_stale_after_a_newer_edit(self, _name, embedding_inserted_at, edit_hour, expected_stale):+ self.user.is_staff = True+ self.user.save()+ edited = self._create_report(title="Edited")+ other = self._create_report(title="Other")+ self._ranking_score_artefact(edited, scores={"open": 0.9}, embedding_inserted_at=embedding_inserted_at)+ self._ranking_score_artefact(other, scores={"open": 0.1})+ older_edit = SignalReportArtefact.objects.create(+ team=self.team,+ report=edited,+ type=SignalReportArtefact.ArtefactType.SUMMARY_CHANGE,+ content=json.dumps({"old_summary": "a", "new_summary": "b"}),+ )+ latest_edit = SignalReportArtefact.objects.create(+ team=self.team,+ report=edited,+ type=SignalReportArtefact.ArtefactType.TITLE_CHANGE,+ content=json.dumps({"old_title": "Old", "new_title": "Edited"}),+ )+ SignalReportArtefact.objects.filter(pk=older_edit.pk).update(created_at=datetime(2026, 9, 20, 9, 0, tzinfo=UTC))+ SignalReportArtefact.objects.filter(pk=latest_edit.pk).update(+ created_at=datetime(2026, 9, 20, edit_hour, 30, tzinfo=UTC)+ )++ list_response = self.client.get(self._list_url(status="ready", ordering="-ranking_open,status,-updated_at"))+ assert list_response.status_code == status.HTTP_200_OK+ rows = list_response.json()["results"]+ by_id = {row["id"]: row for row in rows}+ assert by_id[str(edited.id)]["ranking"]["stale"] is expected_stale+ assert by_id[str(other.id)]["ranking"]["stale"] is False+ ids = [row["id"] for row in rows]+ expected_order = [str(other.id), str(edited.id)] if expected_stale else [str(edited.id), str(other.id)]+ assert ids == expected_order++ response = self.client.get(f"/api/projects/{self.team.id}/signals/reports/{edited.id}/")+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["ranking"]["stale"] is expected_stale++ def test_patch_response_marks_the_score_stale(self):+ self.user.is_staff = True+ self.user.save()+ report = self._create_report()+ self._ranking_score_artefact(report, embedding_inserted_at=datetime(2026, 9, 20, 11, 0, tzinfo=UTC))++ response = self.client.patch(+ f"/api/projects/{self.team.id}/signals/reports/{report.id}/", data={"title": "New title"}, format="json"+ )+ assert response.status_code == status.HTTP_200_OK+ assert response.json()["ranking"]["stale"] is True+@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@@ -1095,6 +1158,17 @@ class TestSignalReportListAPI(APIBaseTest):self._ranking_score_artefact(no_head, scores={"open": 0.5})stale = self._ranking_score_artefact(low, scores={"pr_merged": 0.99})SignalReportArtefact.objects.filter(pk=stale.pk).update(created_at=timezone.now() - timedelta(days=1))+ impossible_time = self._create_report(title="Impossible time")+ impossible_score = self._ranking_score_artefact(impossible_time, scores={"pr_merged": 0.4})+ SignalReportArtefact.objects.filter(pk=impossible_score.pk).update(+ content=impossible_score.content.replace("2026-09-20T12:00:00Z", "2026-02-31T12:00:00Z")+ )+ SignalReportArtefact.objects.create(+ team=self.team,+ report=impossible_time,+ type=SignalReportArtefact.ArtefactType.TITLE_CHANGE,+ content=json.dumps({"old_title": "Old", "new_title": "Impossible time"}),+ )bad_latest = self._create_report(title="Bad latest")older_valid = self._ranking_score_artefact(bad_latest, scores={"pr_merged": 0.99})SignalReportArtefact.objects.filter(pk=older_valid.pk).update(created_at=timezone.now() - timedelta(days=1))@@ -1103,9 +1177,9 @@ class TestSignalReportListAPI(APIBaseTest):response = self.client.get(self._list_url(status="ready", ordering=f"{ordering},status,-updated_at"))assert response.status_code == status.HTTP_200_OKids = [r["id"] for r in response.json()["results"]]- scored = [str(high.id), str(low.id)] if ordering.startswith("-") else [str(low.id), str(high.id)]- assert ids[:2] == scored- assert set(ids[2:]) == {str(unscored.id), str(no_head.id), str(bad_latest.id)}+ scored = [str(high.id), str(impossible_time.id), str(low.id)]+ 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([diff --git a/products/signals/backend/views.py b/products/signals/backend/views.pyindex 65e9e6fa5eb3..e8d959e8eeb1 100644--- a/products/signals/backend/views.py+++ b/products/signals/backend/views.py@@ -135,6 +135,7 @@ from products.signals.backend.models import ()from products.signals.backend.pull_requests import import_report_pull_requestsfrom products.signals.backend.quota import self_driving_quota_enforcement_enabled, self_driving_quota_gate+from products.signals.backend.ranking.staleness import EDIT_ARTEFACT_TYPES, annotate_stale_scorefrom products.signals.backend.repo_corrections import sanitized_repositoryfrom products.signals.backend.report_assignments import InvalidPullRequestUrl, ReportClaimConflict, claim_reportfrom products.signals.backend.report_check_authoring import (@@ -1739,6 +1740,7 @@ class SignalReportViewSet(# A value that is not a JSON number reads as NULL, so one bad row cannot fail the list.# The guard is in the CASE, not the filter: the latest artefact decides, as it does for the# `ranking` field, so a bad latest row makes the report unscored rather than older-scored.+ # A stale score (the report was edited after the text it scored) also sorts as unscored.ordered_fields = {clause.lstrip("-") for clause in self._parse_signal_report_ordering()}for field, head in self._RANKING_ORDERING_HEADS.items():annotation = self._SIGNAL_REPORT_ORDERING_FIELDS[field]@@ -1749,11 +1751,12 @@ class SignalReportViewSet(content, Value("served_key"), function="jsonb_extract_path_text", output_field=CharField())latest_score = Subquery(- SignalReportArtefact.objects.filter(- report_id=OuterRef("id"),- type=SignalReportArtefact.ArtefactType.RANKING_SCORE,+ annotate_stale_score(+ SignalReportArtefact.objects.filter(+ report_id=OuterRef("id"),+ type=SignalReportArtefact.ArtefactType.RANKING_SCORE,+ ).order_by("-created_at"))- .order_by("-created_at").annotate(_score=Case(When(@@ -1775,7 +1778,11 @@ class SignalReportViewSet(.annotate(_score_type=Func(F("_score"), function="jsonb_typeof", output_field=CharField())).annotate(_score_value=Case(- When(_score_type="number", then=Cast(F("_score"), output_field=FloatField())),+ When(+ _score_type="number",+ _score_is_stale=False,+ then=Cast(F("_score"), output_field=FloatField()),+ ),default=Value(None),output_field=FloatField(),)@@ -1839,6 +1846,13 @@ class SignalReportViewSet().order_by("-created_at")[:1],to_attr="prefetched_ranking_score_artefacts",),+ Prefetch(+ "artefacts",+ queryset=SignalReportArtefact.objects.filter(type__in=EDIT_ARTEFACT_TYPES)+ .only("id", "report", "created_at")+ .order_by("-created_at")[:1],+ to_attr="prefetched_latest_edit_artefacts",+ ),)def _annotate_is_suggested_reviewer(self, queryset):@@ -2092,6 +2106,8 @@ class SignalReportViewSet(content=content,attribution=attribution,)+ # The prefetch predates these edits, so the response would mark a now-stale score fresh.+ report.__dict__.pop("prefetched_latest_edit_artefacts", None)return Response(SignalReportSerializer(report, context=self._enriched_report_context(report)).data)@validated_request(diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 04278d775546..9b65cfa430be 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -605,6 +605,8 @@ export interface ReportRankingApi {lifts: ReportRankingApiLifts/** Heads whose holdout AUC the training run could read. Treat scores of other heads with caution. */readable_heads: string[]+ /** True when the report's title or summary was edited after the text this score read. The score describes the old text: the inbox hides its lift and the model sort treats the report as unscored. */+ stale: boolean}export interface SignalReportListApi {diff --git a/products/signals/frontend/inbox/components/cards/ReportCard.test.tsx b/products/signals/frontend/inbox/components/cards/ReportCard.test.tsxindex f2dd9eea3dec..e232d3a7c21c 100644--- a/products/signals/frontend/inbox/components/cards/ReportCard.test.tsx+++ b/products/signals/frontend/inbox/components/cards/ReportCard.test.tsx@@ -392,6 +392,7 @@ describe('ReportCard', () => {scores: { pr_merged: 0.41, action: 0.062 },lifts: { pr_merged: 2.7 },readable_heads: ['action', 'pr_merged'],+ stale: false,},})const { container } = render(<ReportCard report={report} rankingSortField={sortField} />)@@ -409,6 +410,23 @@ describe('ReportCard', () => {const { rerender } = render(<ReportCard report={makeReport('r-2')} rankingSortField="ranking_pr_merged" />)expect(screen.getByText('Not scored')).toBeInTheDocument()+ const stale = makeReport('r-2', {+ ranking: {+ served_key: 'report_embeddings@2026-09-30',+ model_name: 'report_embeddings',+ model_version: '2026-09-30',+ manifest_version: 'manifest',+ scored_at: '2026-09-30T12:00:00Z',+ scores: { pr_merged: 0.41 },+ lifts: { pr_merged: 2.7 },+ readable_heads: ['pr_merged'],+ stale: true,+ },+ })+ rerender(<ReportCard report={stale} rankingSortField="ranking_pr_merged" />)+ expect(screen.getByText('Edited since scored')).toBeInTheDocument()+ expect(screen.queryByText('2.7x merge')).not.toBeInTheDocument()+rerender(<ReportCard report={makeReport('r-2')} />)expect(screen.queryByText('Not scored')).not.toBeInTheDocument()})diff --git a/products/signals/frontend/inbox/components/cards/ReportCardRankingTag.tsx b/products/signals/frontend/inbox/components/cards/ReportCardRankingTag.tsxindex 1b2fdbb20f44..d8d8b514d038 100644--- a/products/signals/frontend/inbox/components/cards/ReportCardRankingTag.tsx+++ b/products/signals/frontend/inbox/components/cards/ReportCardRankingTag.tsx@@ -51,7 +51,7 @@ function RankingTooltip({)}-/** The active model sort's lift for one report, in the card's meta row. Falls back to the probability when the head has no lift. */+/** The active model sort's lift for one report, in the card's meta row. Falls back to the probability when the head has no lift, and shows no score when the report was edited after it was scored. */export function ReportCardRankingTag({report,sortField,@@ -69,6 +69,15 @@ export function ReportCardRankingTag({</LemonTag>)}+ if (report.ranking.stale) {+ return (+ <Tooltip title="The title or summary changed after this report was scored, so the score describes the old text.">+ <LemonTag size="small" type="muted" className="cursor-help" data-attr="inbox-ranking-tag">+ Edited since scored+ </LemonTag>+ </Tooltip>+ )+ }return (<Tooltip title={<RankingTooltip ranking={report.ranking} head={head} />}><LemonTag size="small" className="cursor-help tabular-nums" data-attr="inbox-ranking-tag">diff --git a/products/signals/frontend/inbox/inboxAnalytics.test.ts b/products/signals/frontend/inbox/inboxAnalytics.test.tsindex 566c72996d45..c4fd85c5c683 100644--- a/products/signals/frontend/inbox/inboxAnalytics.test.ts+++ b/products/signals/frontend/inbox/inboxAnalytics.test.ts@@ -129,6 +129,7 @@ describe('inboxAnalytics', () => {scores: { pr_merged: 0.4 },lifts: {},readable_heads: ['pr_merged'],+ stale: false,},}),makeReport({ id: 'b', priority: null, actionability: null, source_products: ['error_tracking'] }),diff --git a/products/signals/frontend/inbox/utils/reportOrdering.ts b/products/signals/frontend/inbox/utils/reportOrdering.tsindex d1fd12ca3923..99506b3b6ce4 100644--- a/products/signals/frontend/inbox/utils/reportOrdering.ts+++ b/products/signals/frontend/inbox/utils/reportOrdering.ts@@ -47,8 +47,11 @@ function timestampKey(value: string): string {return value.includes('.') ? value : value.replace(/(Z|[+-]\d\d:?\d\d)$/, '.000000$1')}-/** The served probability a model sort orders by, or null when the report has no score for that head. */+/** The served probability a model sort orders by, or null when the report has no score for that head or the score is stale. */export function rankingSortScore(report: SignalReport, field: InboxRankingSortField): number | null {+ if (report.ranking?.stale) {+ return null+ }const score = report.ranking?.scores[RANKING_SORT_HEADS[field].head]return typeof score === 'number' ? score : null}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 1bd90285d30e..211881381d4f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -71150,6 +71150,8 @@ export namespace Schemas {lifts: ReportRankingLifts;/** Heads whose holdout AUC the training run could read. Treat scores of other heads with caution. */readable_heads: string[];+ /** True when the report's title or summary was edited after the text this score read. The score describes the old text: the inbox hides its lift and the model sort treats the report as unscored. */+ stale: boolean;}export interface SignalReportList {