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): add the ranking_score report artefact (#106137)

posthog[bot]402aa331562c
diff --git a/products/signals/backend/artefact_schemas.py b/products/signals/backend/artefact_schemas.py
index 7ca714f42aef..068c1b4d8fa3 100644
--- a/products/signals/backend/artefact_schemas.py
+++ b/products/signals/backend/artefact_schemas.py
@@ -22,7 +22,7 @@ import re
from collections.abc import Mapping
from datetime import datetime
from enum import Enum
-from typing import Any, Literal, cast
+from typing import Annotated, Any, Literal, cast
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field, RootModel, ValidationError, field_validator, model_validator
@@ -274,6 +274,140 @@ class ChannelAssignment(BaseModel):
channel_id: UUID | None = Field(description="Channel UUID, or null to leave the report unassigned.")
+# A scoring pass runs several models over one report (one served, the rest challengers), and every
+# one of them lands in a single row. The cap bounds that row, so a manifest that grew past what a
+# reader could order cannot make every report read expensive.
+MAX_RANKING_MODEL_RESULTS = 5
+# The serving manifest owns the role vocabulary, so `roles` stays free text. This is the one role
+# a reader of these rows acts on: the model whose scores the inbox would order on.
+RANKING_SERVED_ROLE = "served"
+
+
+class RankingModelResult(BaseModel):
+ """One model's part of a scoring pass.
+
+ The identity fields mirror the training dag's own columns and its `metadata.json`, so a stored
+ score joins to the model that wrote it without a lookup. A skipped result is kept rather than
+ dropped, because "this model could not score this report" is the coverage read the serving work
+ is measured on.
+ """
+
+ # Pydantic reserves the `model_` prefix for its own API, so the guard is lifted here. Renaming
+ # the fields would break the join to the dag, which is the reason they carry these names.
+ model_config = ConfigDict(protected_namespaces=())
+
+ model_name: str = Field(description="Feature family the model belongs to, e.g. `report_embeddings`.")
+ model_version: str = Field(description="Training partition the model was fit on, as `YYYY-MM-DD`.")
+ model_kind: str = Field(description="Learner the model store loads the booster with, e.g. `xgboost`.")
+ roles: list[str] = Field(
+ default_factory=list,
+ description=(
+ "Roles the serving manifest gave this model in the pass. Exactly one result in a pass "
+ "carries `served`; the rest are challengers."
+ ),
+ )
+ feature_schema_version: int = Field(
+ description="Feature contract version the scores were computed under, from the serving feature set."
+ )
+ status: Literal["scored", "skipped"] = Field(description="Whether this model produced probabilities.")
+ skip_reason: str | None = Field(
+ default=None, description="Why a skipped model produced no scores, e.g. a missing report vector."
+ )
+ # A head's score is consumed as a probability, by a threshold and by the composite score over
+ # the heads, so a raw margin stored here would be silently wrong rather than unusable. The
+ # bound belongs on the field so the generated schema carries it too.
+ scores: dict[str, Annotated[float, Field(ge=0.0, le=1.0)]] = Field(
+ default_factory=dict,
+ description="Outcome head name to its calibrated probability. Empty on a skipped model.",
+ )
+ metadata: dict[str, Any] = Field(
+ default_factory=dict,
+ description=(
+ "Copied from the model's metadata.json: training partition, feature set, per-head "
+ "readability and holdout summary, so a reader can judge a score without the model store."
+ ),
+ )
+
+ @property
+ def key(self) -> str:
+ return f"{self.model_name}@{self.model_version}"
+
+ @field_validator("model_name", "model_version", "model_kind")
+ @classmethod
+ def identity_must_not_be_empty(cls, v: str) -> str:
+ if not v.strip():
+ raise ValueError("must not be empty or whitespace-only")
+ return v
+
+ @model_validator(mode="after")
+ def status_agrees_with_the_scores(self) -> RankingModelResult:
+ # `status` and `scores` are two statements about the same thing, so a row that disagrees
+ # with itself is worse than a missing one: a scored result with no score reads as a model
+ # that ran, and `RankingScore` would accept it as the served entry, leaving a reader with
+ # a served model it can get no probability out of.
+ if self.status == "scored" and not self.scores:
+ raise ValueError("a scored model must carry at least one score")
+ if self.status == "skipped" and self.scores:
+ raise ValueError("a skipped model must carry no scores")
+ return self
+
+
+class RankingScore(BaseModel):
+ """Content schema for a `ranking_score` artefact: one scoring pass over one report.
+
+ A pass writes one artefact carrying every model it ran, so latest-row-wins gives a reader the
+ report's whole current score in one row. Splitting a pass over one row per model would make
+ "the current served score" a question about several rows, and a pass that scored a different
+ set of models than the last one would leave stale rows looking current.
+ """
+
+ scored_at: datetime = Field(description="When the sweep scored the report.")
+ embedding_inserted_at: datetime | None = Field(
+ default=None,
+ description=(
+ "Landing time of the report vector the pass scored, which is the sweep's idempotency "
+ "key. Absent when no model in the pass read a vector."
+ ),
+ )
+ manifest_version: str = Field(description="Version of the serving manifest that chose the models for the pass.")
+ served_key: str = Field(
+ description="Key in `results` of the model whose scores the inbox would order on, as `<model_name>@<model_version>`."
+ )
+ results: dict[str, RankingModelResult] = Field(
+ min_length=1,
+ max_length=MAX_RANKING_MODEL_RESULTS,
+ description="Every model the pass ran, keyed by `<model_name>@<model_version>`.",
+ )
+
+ @field_validator("manifest_version", "served_key")
+ @classmethod
+ def must_not_be_empty(cls, v: str) -> str:
+ if not v.strip():
+ raise ValueError("must not be empty or whitespace-only")
+ return v
+
+ @model_validator(mode="after")
+ def served_score_is_resolvable(self) -> RankingScore:
+ # A consumer reads the served score as `results[served_key]`, so each rule here closes one
+ # way that expression returns the wrong thing or nothing at all.
+ served_keys = []
+ for key, result in self.results.items():
+ if key != result.key:
+ raise ValueError(f"result key {key!r} does not match its model {result.key!r}")
+ if RANKING_SERVED_ROLE in result.roles:
+ served_keys.append(key)
+ if len(served_keys) != 1:
+ raise ValueError(f"exactly one result must carry the {RANKING_SERVED_ROLE!r} role, got {served_keys}")
+ if self.served_key not in self.results:
+ raise ValueError(f"served_key {self.served_key!r} is not a key of results")
+ served = self.results[self.served_key]
+ if RANKING_SERVED_ROLE not in served.roles:
+ raise ValueError(f"served_key {self.served_key!r} does not carry the {RANKING_SERVED_ROLE!r} role")
+ if served.status != "scored":
+ raise ValueError(f"served_key {self.served_key!r} is {served.status}, so the pass has no served score")
+ return self
+
+
# Reason code shared by the dismissal writer (the state API) and the corrections reader
# (`repo_corrections`), defined here so the two cannot drift apart.
DISMISSAL_REASON_WRONG_REPO = "wrong_repo"
@@ -859,6 +993,7 @@ StatusArtefactContent = (
| ChannelAssignment
| ImplementationDecision
| ImplementationDispatch
+ | RankingScore
)
LogArtefactContent = (
CodeReference
@@ -893,6 +1028,7 @@ ARTEFACT_CONTENT_SCHEMAS: Mapping[str, type[BaseModel]] = {
"repo_selection": RepoSelectionResult,
"suggested_reviewers": SuggestedReviewers,
"channel_assignment": ChannelAssignment,
+ "ranking_score": RankingScore,
"dismissal": Dismissal,
"code_reference": CodeReference,
"commit": Commit,
@@ -935,6 +1071,8 @@ _ARTEFACT_TYPE_BY_MODEL: Mapping[type[BaseModel], str] = {model: t for t, model
# it through the API would let a caller fabricate review receipts for reviews that never ran.
# Replacement decisions, reservations, and outcomes authorize GitHub closures. Only the server
# may write them; API writes would let callers fabricate automation provenance or completion.
+# `ranking_score` is model output: the scoring sweep is its only writer, so accepting it through
+# the API would let a caller fabricate a probability the model never produced.
NON_WRITABLE_ARTEFACT_TYPES: frozenset[str] = frozenset(
{
"task_run",
@@ -954,6 +1092,7 @@ NON_WRITABLE_ARTEFACT_TYPES: frozenset[str] = frozenset(
"implementation_dispatch",
"implementation_replacement",
"implementation_handover",
+ "ranking_score",
}
)
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index f0afa3ad6cf6..2cc249aa4479 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1229,13 +1229,15 @@ class SignalReportArtefact(UUIDModel):
IMPLEMENTATION_DISPATCH = "implementation_dispatch"
IMPLEMENTATION_REPLACEMENT = "implementation_replacement"
IMPLEMENTATION_HANDOVER = "implementation_handover"
+ RANKING_SCORE = "ranking_score"
# Every artefact is an append-only, point-in-time log entry — nothing is mutated in place by
# the producers. The two sets below classify *what an entry means*, not how it is written:
- # - status artefacts describe the report's current state (judgments, repo selection,
- # suggested reviewers, channel assignments). They are appended on each change; the
- # report's *current* status is the latest row of that type by `created_at` (the serializer
- # derives priority/actionability/reviewers with `order_by("-created_at")[:1]` subqueries).
+ # - status artefacts describe the report's current state (judgments and repo selection among
+ # them, and the model's current ranking score). They are appended on each change; the
+ # report's *current* status is the latest row of that type by `created_at`. A member does
+ # not have to reach the API: the serializer derives priority/actionability/reviewers with
+ # `order_by("-created_at")[:1]` subqueries, and the rest are read by the pipeline alone.
# - log artefacts record discrete work done on a report (code references, commits,
# task runs, notes, and title/summary edits). Appended via `add_log`.
# `signal_finding` is appended too, but its logical identity is `(report, content.signal_id)`:
@@ -1251,6 +1253,7 @@ class SignalReportArtefact(UUIDModel):
ArtefactType.CHANNEL_ASSIGNMENT,
ArtefactType.IMPLEMENTATION_DECISION,
ArtefactType.IMPLEMENTATION_DISPATCH,
+ ArtefactType.RANKING_SCORE,
}
)
# A `report_link` graph is written by hand or by an agent, one report at a time, so a real
diff --git a/products/signals/backend/test/test_artefact_schemas.py b/products/signals/backend/test/test_artefact_schemas.py
index 57b12bb20324..6911fb8e9e97 100644
--- a/products/signals/backend/test/test_artefact_schemas.py
+++ b/products/signals/backend/test/test_artefact_schemas.py
@@ -7,6 +7,7 @@ from pydantic import BaseModel, ValidationError
from products.signals.backend.artefact_schemas import (
ARTEFACT_CONTENT_SCHEMAS,
+ MAX_RANKING_MODEL_RESULTS,
ArtefactContentValidationError,
CodeReference,
Commit,
@@ -113,6 +114,46 @@ class TestArtefactSchemas(SimpleTestCase):
SummaryChange(old_summary="old", new_summary=" ")
+def _ranking_model_result(**overrides):
+ result = {
+ "model_name": "tabular",
+ "model_version": "2026-01-01",
+ "model_kind": "xgboost",
+ "roles": ["served"],
+ "feature_schema_version": 1,
+ "status": "scored",
+ "scores": {"open": 0.42, "pr_merged": 0.03},
+ "metadata": {"feature_set": "tabular"},
+ }
+ result.update(overrides)
+ return result
+
+
+def _skipped_challenger(**overrides):
+ return _ranking_model_result(
+ **{
+ "model_name": "report_embeddings",
+ "roles": ["challenger"],
+ "status": "skipped",
+ "skip_reason": "no report vector for this report yet",
+ "scores": {},
+ "metadata": {},
+ **overrides,
+ }
+ )
+
+
+def _ranking_score(**overrides):
+ content = {
+ "scored_at": "2026-01-02T03:04:05Z",
+ "manifest_version": "2026-01-02",
+ "served_key": "tabular@2026-01-01",
+ "results": {"tabular@2026-01-01": _ranking_model_result()},
+ }
+ content.update(overrides)
+ return content
+
+
class TestValidateArtefactContent(SimpleTestCase):
@parameterized.expand(
[
@@ -153,6 +194,15 @@ class TestValidateArtefactContent(SimpleTestCase):
"reason": "the fix lands second",
},
),
+ (
+ "ranking_score",
+ _ranking_score(
+ results={
+ "tabular@2026-01-01": _ranking_model_result(),
+ "report_embeddings@2026-01-01": _skipped_challenger(),
+ },
+ ),
+ ),
]
)
def test_accepts_valid_content_for_type(self, artefact_type, content):
@@ -175,6 +225,7 @@ class TestValidateArtefactContent(SimpleTestCase):
("task_run", {"task_id": "t1", "product": "Not Safe!", "type": "research"}),
("report_link", {"kind": "blocks", "report_id": "00000000-0000-0000-0000-000000000002"}),
("report_link", {"kind": "depends_on", "report_id": "report-2"}),
+ ("ranking_score", _ranking_score(served_key="tabular@2025-12-31")),
]
)
def test_rejects_invalid_content_for_type(self, artefact_type, content):
@@ -204,3 +255,65 @@ class TestValidateArtefactContent(SimpleTestCase):
with self.assertRaises(ArtefactContentValidationError):
artefact_type_for(NotAnArtefact())
+
+
+class TestRankingScore(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("served_key_not_in_results", {"served_key": "tabular@2025-12-31"}),
+ (
+ "served_model_did_not_score",
+ {"results": {"tabular@2026-01-01": _ranking_model_result(status="skipped", scores={})}},
+ ),
+ ("key_names_another_model", {"results": {"tabular@2025-12-31": _ranking_model_result()}}),
+ (
+ "no_served_role",
+ {"results": {"tabular@2026-01-01": _ranking_model_result(roles=["challenger"])}},
+ ),
+ (
+ "two_served_roles",
+ {
+ "results": {
+ "tabular@2026-01-01": _ranking_model_result(),
+ "report_embeddings@2026-01-01": _ranking_model_result(model_name="report_embeddings"),
+ }
+ },
+ ),
+ (
+ "score_above_one",
+ {"results": {"tabular@2026-01-01": _ranking_model_result(scores={"open": 1.4})}},
+ ),
+ (
+ "score_below_zero",
+ {"results": {"tabular@2026-01-01": _ranking_model_result(scores={"open": -0.1})}},
+ ),
+ (
+ "scored_model_carries_no_scores",
+ {"results": {"tabular@2026-01-01": _ranking_model_result(scores={})}},
+ ),
+ (
+ "skipped_model_carries_scores",
+ {
+ "results": {
+ "tabular@2026-01-01": _ranking_model_result(),
+ "report_embeddings@2026-01-01": _skipped_challenger(scores={"open": 0.1}),
+ }
+ },
+ ),
+ (
+ "more_models_than_the_cap",
+ {
+ "results": {"tabular@2026-01-01": _ranking_model_result()}
+ | {
+ f"tabular@2026-02-{day:02d}": _ranking_model_result(
+ model_version=f"2026-02-{day:02d}", roles=["challenger"]
+ )
+ for day in range(1, MAX_RANKING_MODEL_RESULTS + 1)
+ }
+ },
+ ),
+ ]
+ )
+ def test_rejects_a_pass_whose_served_score_cannot_be_read(self, _name, overrides):
+ with self.assertRaises(ArtefactContentValidationError):
+ parse_artefact_content("ranking_score", _ranking_score(**overrides))
diff --git a/products/signals/backend/test/test_signal_report_artefact_api.py b/products/signals/backend/test/test_signal_report_artefact_api.py
index c74303d505ea..9dc58803f2ce 100644
--- a/products/signals/backend/test/test_signal_report_artefact_api.py
+++ b/products/signals/backend/test/test_signal_report_artefact_api.py
@@ -1279,26 +1279,50 @@ class TestSignalReportArtefactLogWriteViewSet(APIBaseTest):
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
assert not SignalReportArtefact.objects.filter(report=report).exists()
- def test_post_rejects_system_generated_code_review_type(self):
- # code_review receipts are written only by the ReviewHog workflow; accepting them through the
- # API would let a caller fabricate review receipts for reviews that never ran. The payload is
- # schema-valid on purpose — the rejection must be type-based, not a validation accident.
- report = self._create_report()
- response = self.client.post(
- self._list_url(str(report.id)),
- data=json.dumps(
+ @parameterized.expand(
+ [
+ (
+ "code_review",
{
- "artefact_type": "code_review",
- "content": {
- "review_report_id": "11111111-1111-1111-1111-111111111111",
- "repository": "posthog/posthog",
- "head_sha": "abc123",
- "head_branch": "feat",
- "base_branch": "master",
- "outcome": "published",
+ "review_report_id": "11111111-1111-1111-1111-111111111111",
+ "repository": "posthog/posthog",
+ "head_sha": "abc123",
+ "head_branch": "feat",
+ "base_branch": "master",
+ "outcome": "published",
+ },
+ ),
+ (
+ "ranking_score",
+ {
+ "scored_at": "2026-01-02T03:04:05Z",
+ "manifest_version": "2026-01-02",
+ "served_key": "tabular@2026-01-01",
+ "results": {
+ "tabular@2026-01-01": {
+ "model_name": "tabular",
+ "model_version": "2026-01-01",
+ "model_kind": "xgboost",
+ "roles": ["served"],
+ "feature_schema_version": 1,
+ "status": "scored",
+ "scores": {"open": 0.42},
+ }
},
- }
+ },
),
+ ]
+ )
+ def test_post_rejects_system_generated_type(self, artefact_type, content):
+ # These types are written only by the pipeline that produces them: the ReviewHog workflow for
+ # a code_review receipt, the scoring sweep for a ranking_score. Accepting them through the API
+ # would let a caller fabricate a review that never ran or a probability no model produced. Each
+ # payload is schema-valid on purpose, so the rejection must be type-based rather than a
+ # validation accident.
+ report = self._create_report()
+ response = self.client.post(
+ self._list_url(str(report.id)),
+ data=json.dumps({"artefact_type": artefact_type, "content": content}),
content_type="application/json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()
diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.ts
index cbee06b42550..02c0834e466b 100644
--- a/products/signals/frontend/generated/api.schemas.ts
+++ b/products/signals/frontend/generated/api.schemas.ts
@@ -2479,6 +2479,7 @@ export interface SignalReportStateRequestApi {
* * `implementation_dispatch` - Implementation Dispatch
* * `implementation_replacement` - Implementation Replacement
* * `implementation_handover` - Implementation Handover
+ * * `ranking_score` - Ranking Score
*/
export type SignalReportArtefactArtefactTypeEnumApi =
(typeof SignalReportArtefactArtefactTypeEnumApi)[keyof typeof SignalReportArtefactArtefactTypeEnumApi]
@@ -2513,6 +2514,7 @@ export const SignalReportArtefactArtefactTypeEnumApi = {
ImplementationDispatch: 'implementation_dispatch',
ImplementationReplacement: 'implementation_replacement',
ImplementationHandover: 'implementation_handover',
+ RankingScore: 'ranking_score',
} as const
export type SignalReportArtefactApiContent = { [key: string]: unknown } | unknown[]
diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.ts
index 9f0eaff07608..2834cb9c43d9 100644
--- a/products/signals/frontend/generated/api.ts
+++ b/products/signals/frontend/generated/api.ts
@@ -931,7 +931,7 @@ export const getSignalsReportArtefactsDestroyUrl = (projectId: string, reportId:
}
/**
- * Delete an artefact, addressed by id. Deleting the latest row of a status type reverts the report's canonical status to the previous version (latest-wins over what remains). `task_run` artefacts are an append-only work log and cannot be deleted. Neither can the types this API cannot write, which the pipeline owns: `check_cancelled`, `check_expired`, `check_result`, `check_scheduled`, `code_review`, `implementation_decision`, `implementation_dispatch`, `implementation_handover`, `implementation_replacement`, `pull_request`, `report_link`, `summary_change`, `task_run`, `title_change`, `video_segment`, `work_claim`, `work_release`.
+ * Delete an artefact, addressed by id. Deleting the latest row of a status type reverts the report's canonical status to the previous version (latest-wins over what remains). `task_run` artefacts are an append-only work log and cannot be deleted. Neither can the types this API cannot write, which the pipeline owns: `check_cancelled`, `check_expired`, `check_result`, `check_scheduled`, `code_review`, `implementation_decision`, `implementation_dispatch`, `implementation_handover`, `implementation_replacement`, `pull_request`, `ranking_score`, `report_link`, `summary_change`, `task_run`, `title_change`, `video_segment`, `work_claim`, `work_release`.
* @summary Delete an artefact
*/
export const signalsReportArtefactsDestroy = async (
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e6f9b209ece2..ffcef9bcf6c8 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -65275,6 +65275,7 @@ export namespace Schemas {
* * `implementation_dispatch` - Implementation Dispatch
* * `implementation_replacement` - Implementation Replacement
* * `implementation_handover` - Implementation Handover
+ * * `ranking_score` - Ranking Score
*/
export type SignalReportArtefactArtefactTypeEnum = typeof SignalReportArtefactArtefactTypeEnum[keyof typeof SignalReportArtefactArtefactTypeEnum];
@@ -65309,6 +65310,7 @@ export namespace Schemas {
ImplementationDispatch: 'implementation_dispatch',
ImplementationReplacement: 'implementation_replacement',
ImplementationHandover: 'implementation_handover',
+ RankingScore: 'ranking_score',
} as const;
export type SignalActorKindEnum = typeof SignalActorKindEnum[keyof typeof SignalActorKindEnum];
diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.ts
index 0744198ef01f..625e2bb246f9 100644
--- a/services/mcp/src/generated/signals/api.ts
+++ b/services/mcp/src/generated/signals/api.ts
@@ -435,7 +435,7 @@ export const SignalsReportArtefactsPartialUpdateBody = () => zod
)
/**
- * Delete an artefact, addressed by id. Deleting the latest row of a status type reverts the report's canonical status to the previous version (latest-wins over what remains). `task_run` artefacts are an append-only work log and cannot be deleted. Neither can the types this API cannot write, which the pipeline owns: `check_cancelled`, `check_expired`, `check_result`, `check_scheduled`, `code_review`, `implementation_decision`, `implementation_dispatch`, `implementation_handover`, `implementation_replacement`, `pull_request`, `report_link`, `summary_change`, `task_run`, `title_change`, `video_segment`, `work_claim`, `work_release`.
+ * Delete an artefact, addressed by id. Deleting the latest row of a status type reverts the report's canonical status to the previous version (latest-wins over what remains). `task_run` artefacts are an append-only work log and cannot be deleted. Neither can the types this API cannot write, which the pipeline owns: `check_cancelled`, `check_expired`, `check_result`, `check_scheduled`, `code_review`, `implementation_decision`, `implementation_dispatch`, `implementation_handover`, `implementation_replacement`, `pull_request`, `ranking_score`, `report_link`, `summary_change`, `task_run`, `title_change`, `video_segment`, `work_claim`, `work_release`.
* @summary Delete an artefact
*/
export const SignalsReportArtefactsDestroyParams = () => zod.object({