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 an inbox ranking override flag for serving and promotion (#111581)

posthog[bot]5920920ed93c
diff --git a/products/signals/backend/ranking/model_store.py b/products/signals/backend/ranking/model_store.py
index b7390dc34d19..a4b6212c65db 100644
--- a/products/signals/backend/ranking/model_store.py
+++ b/products/signals/backend/ranking/model_store.py
@@ -35,9 +35,13 @@ from products.signals.backend.ranking.model_contract import (
model_mismatch,
trained_head_files,
)
+from products.signals.backend.ranking.overrides import RankingOverrides
from products.signals.backend.ranking.serving_manifest import (
DEFAULT_MODEL_KIND,
+ MANIFEST_SERVED_ROLE,
METADATA_FILE,
+ SERVED_OVERRIDE_ROLE,
+ SERVED_ROLE,
ServingManifest,
ServingManifestEntry,
serving_manifest_key,
@@ -71,6 +75,8 @@ class ServingSet:
others: Sequence[LoadedModel]
# Model key to the reason the entry could not be loaded.
skipped: Mapping[str, str]
+ # The overrides whose `served` key this set serves. None when the manifest's served model serves.
+ served_override: RankingOverrides | None = None
class ModelKindHandler(Protocol):
@@ -166,12 +172,16 @@ def clear_model_cache() -> None:
_cache.clear()
-def load_serving_set() -> ServingSet | None:
+def load_serving_set(overrides: RankingOverrides | None = None) -> ServingSet | None:
"""Every model the manifest names, or None when no manifest is published yet.
A served entry that fails to load raises, because a pass without a served score is worse than
no pass. Any other entry that fails is recorded in `skipped`, and the scorer writes it as a
skipped result, so the coverage of each model stays readable.
+
+ A `served` override moves the served role to another model the manifest names. An override
+ that cannot apply is logged and the manifest's served model serves, so a bad override never
+ stops a pass.
"""
raw_manifest = object_storage.read(serving_manifest_key(settings.INBOX_RANKING_DATASET_S3_PREFIX), missing_ok=True)
if raw_manifest is None:
@@ -188,4 +198,56 @@ def load_serving_set() -> ServingSet | None:
except ModelLoadError as error:
logger.warning("inbox_ranking_model_skipped", model_key=entry.key, reason=str(error))
skipped[entry.key] = str(error)
- return ServingSet(manifest=manifest, served=served, others=others, skipped=skipped)
+ serving = ServingSet(manifest=manifest, served=served, others=others, skipped=skipped)
+ if overrides is None or overrides.served is None or overrides.served == manifest.served.key:
+ return serving
+ rejection = served_override_rejection(serving, overrides.served)
+ if rejection is not None:
+ logger.warning(
+ "inbox_ranking_override_rejected",
+ override_served=overrides.served,
+ manifest_served=manifest.served.key,
+ reason=rejection,
+ )
+ return serving
+ return _with_served_override(serving, overrides)
+
+
+def served_override_rejection(serving: ServingSet, key: str) -> str | None:
+ """Why the model `key` cannot take the served role this pass, or None when it can.
+
+ Only a model the manifest names and the pass loaded qualifies, so an override never makes a
+ pod load a model it did not already hold. The model must also have every head the manifest's
+ served model has, because consumers read `p_<head>` off the served score.
+ """
+ if key in serving.skipped:
+ return f"{key} did not load: {serving.skipped[key]}"
+ model = next((model for model in serving.others if model.entry.key == key), None)
+ if model is None:
+ return f"{key} is not in the serving manifest"
+ missing_heads = sorted(set(serving.served.entry.heads) - set(model.entry.heads))
+ if missing_heads:
+ return f"{key} has no head for {missing_heads}"
+ return None
+
+
+def _with_served_override(serving: ServingSet, overrides: RankingOverrides) -> ServingSet:
+ def roles(entry: ServingManifestEntry) -> list[str]:
+ if entry.key == overrides.served:
+ return [SERVED_ROLE, SERVED_OVERRIDE_ROLE, *entry.roles]
+ if SERVED_ROLE in entry.roles:
+ return [MANIFEST_SERVED_ROLE, *(role for role in entry.roles if role != SERVED_ROLE)]
+ return list(entry.roles)
+
+ entries = [entry.model_copy(update={"roles": roles(entry)}) for entry in serving.manifest.models]
+ manifest = serving.manifest.model_copy(update={"models": entries})
+ by_key = {entry.key: entry for entry in entries}
+ loaded = [serving.served, *serving.others]
+ served = next(model for model in loaded if model.entry.key == overrides.served)
+ return ServingSet(
+ manifest=manifest,
+ served=replace(served, entry=by_key[served.entry.key]),
+ others=[replace(model, entry=by_key[model.entry.key]) for model in loaded if model is not served],
+ skipped=serving.skipped,
+ served_override=overrides,
+ )
diff --git a/products/signals/backend/ranking/overrides.py b/products/signals/backend/ranking/overrides.py
new file mode 100644
index 000000000000..cce5ba1b040a
--- /dev/null
+++ b/products/signals/backend/ranking/overrides.py
@@ -0,0 +1,155 @@
+"""Temporary owner overrides of ranking serving and promotion, read from one feature flag payload.
+
+An owner sets the `inbox-ranking-overrides` payload only to intervene, and every payload expires on
+its own. The scoring sweep reads `served`, and the training dag reads `pin` and `promotion`. Both
+parse the payload here, so the two cannot disagree about what a payload means.
+
+The parser is fail-safe. An absent, expired or invalid payload, or a failed flag lookup, gives
+`NO_OVERRIDES`, and the sweep and the dag then run as they do with no flag. An invalid payload is
+ignored as a whole and is never partly applied.
+"""
+
+import re
+import json
+import datetime
+from collections.abc import Mapping
+from dataclasses import field
+from typing import Any, Literal
+
+import pydantic
+import structlog
+import posthoganalytics
+
+from posthog.dataclasses import frozen
+
+logger = structlog.get_logger(__name__)
+
+RANKING_OVERRIDES_FLAG = "inbox-ranking-overrides"
+# The flag is evaluated once per pass or run for this id, so an override applies to every report.
+RANKING_OVERRIDES_DISTINCT_ID = "internal_inbox_ranking_overrides"
+
+# A forgotten override must not change serving or promotion for longer than this.
+MAX_OVERRIDE_LIFETIME = datetime.timedelta(days=14)
+
+PromotionGate = Literal["min_days", "ece", "min_holdout_positives"]
+
+# A model key is also a path segment in the dataset bucket, so the format is strict.
+_MODEL_KEY_PATTERN = re.compile(r"^[a-z0-9_]+@\d{4}-\d{2}-\d{2}$")
+
+
+class InvalidOverrides(ValueError):
+ pass
+
+
+class _PromotionPayload(pydantic.BaseModel):
+ model_config = pydantic.ConfigDict(extra="forbid")
+
+ freeze: list[str] = []
+ force: list[str] = []
+ skip_gates: dict[str, list[PromotionGate]] = {}
+
+
+class _OverridesPayload(pydantic.BaseModel):
+ model_config = pydantic.ConfigDict(extra="forbid")
+
+ expires_at: pydantic.AwareDatetime
+ served: str | None = None
+ pin: list[str] = []
+ promotion: _PromotionPayload = _PromotionPayload()
+
+ @pydantic.field_validator("served")
+ @classmethod
+ def served_is_a_model_key(cls, v: str | None) -> str | None:
+ if v is not None and not _MODEL_KEY_PATTERN.match(v):
+ raise ValueError(f"{v!r} is not a `<model_name>@<YYYY-MM-DD>` model key")
+ return v
+
+ @pydantic.field_validator("pin")
+ @classmethod
+ def pins_are_model_keys(cls, v: list[str]) -> list[str]:
+ for key in v:
+ if not _MODEL_KEY_PATTERN.match(key):
+ raise ValueError(f"{key!r} is not a `<model_name>@<YYYY-MM-DD>` model key")
+ return v
+
+
+@frozen
+class PromotionOverride:
+ """One family's promotion override. `freeze` wins, so a frozen family has no force and no waived gate."""
+
+ freeze: bool = False
+ force: bool = False
+ skip_gates: frozenset[str] = frozenset()
+
+
+@frozen
+class RankingOverrides:
+ # None only on `NO_OVERRIDES`.
+ expires_at: datetime.datetime | None = None
+ served: str | None = None
+ pin: tuple[str, ...] = ()
+ freeze: frozenset[str] = frozenset()
+ force: frozenset[str] = frozenset()
+ skip_gates: Mapping[str, frozenset[str]] = field(default_factory=dict)
+
+ def promotion_for(self, family: str) -> PromotionOverride:
+ if family in self.freeze:
+ return PromotionOverride(freeze=True)
+ return PromotionOverride(force=family in self.force, skip_gates=self.skip_gates.get(family, frozenset()))
+
+
+NO_OVERRIDES = RankingOverrides()
+
+
+def _validated(payload: Mapping[str, Any], now: datetime.datetime) -> RankingOverrides:
+ try:
+ parsed = _OverridesPayload.model_validate(payload)
+ except pydantic.ValidationError as error:
+ raise InvalidOverrides(str(error)) from error
+ if parsed.expires_at > now + MAX_OVERRIDE_LIFETIME:
+ raise InvalidOverrides(f"expires_at {parsed.expires_at.isoformat()} is more than 14 days ahead")
+ return RankingOverrides(
+ expires_at=parsed.expires_at,
+ served=parsed.served,
+ pin=tuple(dict.fromkeys(parsed.pin)),
+ freeze=frozenset(parsed.promotion.freeze),
+ force=frozenset(parsed.promotion.force),
+ skip_gates={family: frozenset(gates) for family, gates in parsed.promotion.skip_gates.items()},
+ )
+
+
+def parse_overrides(payload: Any, *, now: datetime.datetime) -> RankingOverrides:
+ """The overrides a payload sets, or `NO_OVERRIDES` when it is empty, expired or invalid."""
+ if payload is None or payload == {}:
+ return NO_OVERRIDES
+ if not isinstance(payload, Mapping):
+ logger.warning("inbox_ranking_override_invalid", reason="the payload is not a JSON object")
+ return NO_OVERRIDES
+ try:
+ overrides = _validated(payload, now)
+ except InvalidOverrides as error:
+ logger.warning("inbox_ranking_override_invalid", reason=str(error))
+ return NO_OVERRIDES
+ if overrides.expires_at is not None and overrides.expires_at <= now:
+ logger.warning("inbox_ranking_override_expired", expires_at=overrides.expires_at.isoformat())
+ return NO_OVERRIDES
+ return overrides
+
+
+def read_ranking_overrides(now: datetime.datetime) -> RankingOverrides:
+ """The current overrides. Blocks on the flag lookup, so call it off the event loop.
+
+ The flag is evaluated, not only its payload read, so a disabled flag sets no override.
+ """
+ try:
+ payload = posthoganalytics.get_feature_flag_payload(RANKING_OVERRIDES_FLAG, RANKING_OVERRIDES_DISTINCT_ID)
+ except Exception as error:
+ logger.warning("inbox_ranking_override_lookup_failed", error=repr(error))
+ return NO_OVERRIDES
+ if isinstance(payload, str):
+ try:
+ payload = json.loads(payload)
+ except ValueError:
+ logger.warning("inbox_ranking_override_invalid", reason="the payload is not valid JSON")
+ return NO_OVERRIDES
+ return parse_overrides(payload, now=now)
diff --git a/products/signals/backend/ranking/scorer.py b/products/signals/backend/ranking/scorer.py
index b8a1eb4f888b..85cec399ec4f 100644
--- a/products/signals/backend/ranking/scorer.py
+++ b/products/signals/backend/ranking/scorer.py
@@ -228,6 +228,9 @@ def score_reports(
if persist:
persist_scores(
- team_id, [(outcome.report_id, outcome.score) for outcome in outcomes if outcome.score], capture=capture
+ team_id,
+ [(outcome.report_id, outcome.score) for outcome in outcomes if outcome.score],
+ capture=capture,
+ served_override=serving.served_override,
)
return outcomes
diff --git a/products/signals/backend/ranking/serving_manifest.py b/products/signals/backend/ranking/serving_manifest.py
index d93fcf2f62b0..d15f6b9f7c03 100644
--- a/products/signals/backend/ranking/serving_manifest.py
+++ b/products/signals/backend/ranking/serving_manifest.py
@@ -26,6 +26,14 @@ SERVED_ROLE = RANKING_SERVED_ROLE
DAILY_CANDIDATE_ROLE = "daily_candidate"
# Another family's champion, scored alongside so a later interleaving needs no rescoring.
CROSS_FAMILY_ROLE = "cross_family"
+# A model an owner keeps in the manifest through the `pin` override, so a `served` override can
+# name it, for example to roll back to an older champion.
+PINNED_ROLE = "pinned"
+# The sweep gives these two roles for one pass when a `served` override applies. A published
+# manifest never carries them. The override model keeps `served` and gains `served_override`, so a
+# reader can tell its scores apart, and the manifest's own served model loses `served`.
+SERVED_OVERRIDE_ROLE = "served_override"
+MANIFEST_SERVED_ROLE = "manifest_served"
# The learner a model store loads the booster with. Every family is per-head XGBoost today, and a
# model published before the field existed is one of those, so this is also the read fallback.
diff --git a/products/signals/backend/ranking/sinks.py b/products/signals/backend/ranking/sinks.py
index 7a094ccb8cb5..18e9cfc16593 100644
--- a/products/signals/backend/ranking/sinks.py
+++ b/products/signals/backend/ranking/sinks.py
@@ -15,13 +15,18 @@ from posthog.ph_client import ScopedCapture, ph_scoped_capture
from products.signals.backend.artefact_schemas import RankingModelResult, RankingScore
from products.signals.backend.models import SignalActorKind, SignalReport, SignalReportArtefact
from products.signals.backend.ranking.model_contract import classification_thresholds, head_lifts, readable_head_names
+from products.signals.backend.ranking.overrides import RankingOverrides
REPORT_SCORED_EVENT = "inbox_ranking_report_scored"
DISTINCT_ID = "inbox_ranking_scoring"
def persist_scores(
- team_id: int, scores: Sequence[tuple[str, RankingScore]], *, capture: ScopedCapture | None = None
+ team_id: int,
+ scores: Sequence[tuple[str, RankingScore]],
+ *,
+ capture: ScopedCapture | None = None,
+ served_override: RankingOverrides | None = None,
) -> int:
"""Write one artefact per `(report_id, score)` of the team, then capture its events.
@@ -47,6 +52,9 @@ def persist_scores(
for report_id, score in kept
]
)
+ override_expires_at = (
+ served_override.expires_at.isoformat() if served_override and served_override.expires_at else None
+ )
with ph_scoped_capture() if capture is None else nullcontext(capture) as active_capture:
for report_id, score in kept:
for model_key, result in score.results.items():
@@ -68,6 +76,8 @@ def persist_scores(
"embedding_inserted_at": score.embedding_inserted_at.isoformat()
if score.embedding_inserted_at
else None,
+ "override_served": served_override.served if served_override else None,
+ "override_expires_at": override_expires_at,
**{f"p_{head}": probability for head, probability in result.scores.items()},
**classification_properties(result),
},
diff --git a/products/signals/backend/ranking/sweep.py b/products/signals/backend/ranking/sweep.py
index 60cca1131144..a2e603da04b7 100644
--- a/products/signals/backend/ranking/sweep.py
+++ b/products/signals/backend/ranking/sweep.py
@@ -37,7 +37,8 @@ from posthog.temporal.common.utils import close_db_connections
from products.signals.backend.models import SignalReport, SignalReportArtefact
from products.signals.backend.ranking import scorer
from products.signals.backend.ranking.inventory import SCORABLE_STATUSES, spine_report_filter
-from products.signals.backend.ranking.model_store import ModelLoadError, load_serving_set
+from products.signals.backend.ranking.model_store import ModelLoadError, ServingSet, load_serving_set
+from products.signals.backend.ranking.overrides import RankingOverrides, read_ranking_overrides
from products.signals.backend.report_embedding_reader import REPORT_EMBEDDINGS_TABLE
from products.signals.backend.report_embeddings import EMBEDDING_DOCUMENT_TYPE, EMBEDDING_PRODUCT
@@ -119,6 +120,7 @@ class _ScoreStamp(pydantic.BaseModel):
scored_at: datetime.datetime
embedding_inserted_at: datetime.datetime | None = None
manifest_version: str
+ served_key: str
def _batches(items: Sequence[str], size: int = _POSTGRES_BATCH_SIZE) -> Iterator[Sequence[str]]:
@@ -201,19 +203,24 @@ def _latest_scores(report_ids: Sequence[str]) -> dict[str, _ScoreStamp | None]:
return scores
-def _is_due(score: _ScoreStamp | None, vector_inserted_at: datetime.datetime, manifest_version: str) -> bool:
+def _is_due(
+ score: _ScoreStamp | None, vector_inserted_at: datetime.datetime, manifest_version: str, served_key: str
+) -> bool:
+ # A `served` override changes the served model and leaves `manifest_version` as it is, so the
+ # served key is compared too. Setting or removing an override then rescores every report.
return (
score is None
or score.embedding_inserted_at is None
or vector_inserted_at > score.embedding_inserted_at
or score.manifest_version != manifest_version
+ or score.served_key != served_key
)
def reports_due_for_scoring(
- now: datetime.datetime, *, manifest_version: str, rendering: str, limit: int
+ now: datetime.datetime, *, manifest_version: str, served_key: str, rendering: str, limit: int
) -> list[ScoringCandidate]:
- """In-window scorable reports whose score is missing, older than their vector, or from another manifest.
+ """In-window scorable reports whose score is missing, older than their vector, or from another manifest or served model.
Unscored reports come first, then the oldest scores, so no report starves under the cap. A
report with no live vector is never a candidate, so a safety-suppressed or retracted report is
@@ -229,7 +236,7 @@ def reports_due_for_scoring(
for report_id in kept:
team_id, vector_inserted_at = vectors[report_id]
score = latest.get(report_id)
- if not _is_due(score, vector_inserted_at, manifest_version):
+ if not _is_due(score, vector_inserted_at, manifest_version, served_key):
continue
candidate = ScoringCandidate(team_id=team_id, report_id=report_id, vector_inserted_at=vector_inserted_at)
due.append((score.scored_at if score else None, candidate))
@@ -237,21 +244,41 @@ def reports_due_for_scoring(
return [candidate for _, candidate in due[:limit]]
+def _load_serving(overrides: RankingOverrides) -> ServingSet | None:
+ """The serving set with the `served` override applied when it can be served, else without it."""
+ serving = load_serving_set(overrides)
+ if serving is None or serving.served_override is None:
+ return serving
+ try:
+ scorer.served_rendering(serving)
+ except scorer.ScoringError as error:
+ logger.warning(
+ "inbox_ranking_override_rejected",
+ override_served=serving.served_override.served,
+ reason=str(error),
+ )
+ return load_serving_set()
+ return serving
+
+
def score_inbox_reports(limit: int | None = None) -> ScoreInboxReportsResult:
if not settings.INBOX_RANKING_SCORING_ENABLED:
logger.info("inbox_ranking_sweep_skipped", skipped_reason="disabled")
return ScoreInboxReportsResult(skipped_reason="disabled")
deadline = time.monotonic() + _TIME_BUDGET.total_seconds()
- # A served model that does not load raises here and aborts the run.
- serving = load_serving_set()
+ now = timezone.now()
+ # A served model that does not load raises here and aborts the run. A served override that
+ # does not load only logs.
+ serving = _load_serving(read_ranking_overrides(now))
if serving is None:
logger.info("inbox_ranking_sweep_skipped", skipped_reason="no manifest")
return ScoreInboxReportsResult(skipped_reason="no manifest")
manifest_version = serving.manifest.manifest_version
- now = timezone.now()
+ override = serving.served_override
candidates = reports_due_for_scoring(
now,
manifest_version=manifest_version,
+ served_key=serving.manifest.served.key,
rendering=scorer.served_rendering(serving),
limit=limit or settings.INBOX_RANKING_SCORING_MAX_REPORTS_PER_TICK,
)
@@ -320,6 +347,8 @@ def score_inbox_reports(limit: int | None = None) -> ScoreInboxReportsResult:
deferred_teams=result.deferred_teams,
deferred_reports=result.deferred_reports,
manifest_version=result.manifest_version,
+ override_served=override.served if override else None,
+ override_expires_at=override.expires_at.isoformat() if override and override.expires_at else None,
peak_rss_mb=_peak_rss_mb(),
)
return result
diff --git a/products/signals/backend/test/test_ranking_scoring.py b/products/signals/backend/test/test_ranking_scoring.py
index def1c7779a52..7d3d6d913a11 100644
--- a/products/signals/backend/test/test_ranking_scoring.py
+++ b/products/signals/backend/test/test_ranking_scoring.py
@@ -29,11 +29,15 @@ from products.signals.backend.ranking.features import (
FeatureSet,
)
from products.signals.backend.ranking.model_store import ModelLoadError, load_serving_set
+from products.signals.backend.ranking.overrides import RankingOverrides
from products.signals.backend.ranking.scorer import NO_VECTOR, score_reports
from products.signals.backend.ranking.serving_manifest import (
CROSS_FAMILY_ROLE,
DAILY_CANDIDATE_ROLE,
+ MANIFEST_SERVED_ROLE,
METADATA_FILE,
+ PINNED_ROLE,
+ SERVED_OVERRIDE_ROLE,
SERVED_ROLE,
ServingManifest,
ServingManifestEntry,
@@ -200,6 +204,60 @@ class TestModelStore(_StoreTestMixin, SimpleTestCase):
assert serving.others == []
assert reason in serving.skipped[challenger.key]
+ @parameterized.expand(
+ [
+ ("not_in_the_manifest", None, "is not in the serving manifest"),
+ ("files_missing", {"missing_heads": ["thumbs_up"]}, "did not load"),
+ ("missing_a_served_head", {"heads": ["open"]}, "has no head for ['thumbs_up']"),
+ ]
+ )
+ def test_a_served_override_that_cannot_apply_keeps_the_manifest_served_model(
+ self, _name: str, override_kwargs: dict | None, reason: str
+ ) -> None:
+ served = self._served()
+ entries = [served]
+ override_key = model_key("report_embeddings", OLDER_VERSION)
+ if override_kwargs is not None:
+ heads = override_kwargs.pop("heads", None)
+ pinned = self.store.publish_model(
+ "report_embeddings",
+ REPORT_EMBEDDINGS_FEATURE_SET,
+ version=OLDER_VERSION,
+ roles=[PINNED_ROLE],
+ **override_kwargs,
+ )
+ entries.append(pinned.model_copy(update={"heads": heads}) if heads else pinned)
+ self.store.publish_manifest(entries)
+
+ with patch.object(model_store, "logger") as logger:
+ serving = load_serving_set(RankingOverrides(served=override_key))
+
+ assert serving is not None
+ assert serving.served.entry.key == served.key
+ assert serving.served_override is None
+ [warning] = [
+ call for call in logger.warning.call_args_list if call.args[0] == "inbox_ranking_override_rejected"
+ ]
+ assert reason in warning.kwargs["reason"]
+
+ def test_a_served_override_moves_the_served_role_and_keeps_scoring_the_manifest_served_model(self) -> None:
+ served = self._served()
+ pinned = self.store.publish_model(
+ "report_embeddings", REPORT_EMBEDDINGS_FEATURE_SET, version=OLDER_VERSION, roles=[PINNED_ROLE]
+ )
+ self.store.publish_manifest([served, pinned])
+ overrides = RankingOverrides(served=pinned.key)
+
+ serving = load_serving_set(overrides)
+
+ assert serving is not None
+ assert serving.served_override == overrides
+ assert serving.manifest.served.key == pinned.key
+ assert serving.served.entry.roles == [SERVED_ROLE, SERVED_OVERRIDE_ROLE, PINNED_ROLE]
+ assert [(model.entry.key, model.entry.roles) for model in serving.others] == [
+ (served.key, [MANIFEST_SERVED_ROLE])
+ ]
+
def test_a_loaded_key_is_not_read_again_but_takes_the_new_roles(self) -> None:
served = self._served()
self.store.publish_manifest([served])
diff --git a/products/signals/backend/test/test_ranking_sweep.py b/products/signals/backend/test/test_ranking_sweep.py
index c7909ac295da..8ac0fd744cdb 100644
--- a/products/signals/backend/test/test_ranking_sweep.py
+++ b/products/signals/backend/test/test_ranking_sweep.py
@@ -20,6 +20,7 @@ from products.signals.backend.models import SignalReport, SignalReportArtefact
from products.signals.backend.ranking import scorer, sweep
from products.signals.backend.ranking.features import EMBEDDING_DIMENSIONS
from products.signals.backend.ranking.model_store import ModelLoadError
+from products.signals.backend.ranking.overrides import NO_OVERRIDES, RankingOverrides, parse_overrides
from products.signals.backend.ranking.scorer import NO_VECTOR, ReportScoringOutcome, ScoringError
from products.signals.backend.ranking.sweep import ScoringCandidate, reports_due_for_scoring, score_inbox_reports
from products.signals.backend.report_embedding_reader import REPORT_EMBEDDINGS_TABLE
@@ -27,12 +28,20 @@ from products.signals.backend.report_embeddings import EMBEDDING_RENDERING_TITLE
MANIFEST = "manifest-b"
OLD_MANIFEST = "manifest-a"
+SERVED_VERSION = "2026-09-01"
+SERVED_KEY = f"report_embeddings@{SERVED_VERSION}"
-def _score(*, embedding_inserted_at: datetime.datetime, manifest_version: str, scored_at: datetime.datetime) -> str:
+def _score(
+ *,
+ embedding_inserted_at: datetime.datetime,
+ manifest_version: str,
+ scored_at: datetime.datetime,
+ served_version: str = SERVED_VERSION,
+) -> str:
served = RankingModelResult(
model_name="report_embeddings",
- model_version="2026-09-01",
+ model_version=served_version,
model_kind="xgboost",
roles=["served"],
feature_schema_version=1,
@@ -48,6 +57,10 @@ def _score(*, embedding_inserted_at: datetime.datetime, manifest_version: str, s
).model_dump_json()
+def _raise(error: Exception) -> Any:
+ raise error
+
+
class TestReportsDueForScoring(ClickhouseTestMixin, BaseTest):
def setUp(self) -> None:
super().setUp()
@@ -96,7 +109,13 @@ class TestReportsDueForScoring(ClickhouseTestMixin, BaseTest):
return inserted_at
def _scored(
- self, report_id: str, *, vector_at: datetime.datetime, manifest: str = MANIFEST, hours_ago: int = 1
+ self,
+ report_id: str,
+ *,
+ vector_at: datetime.datetime,
+ manifest: str = MANIFEST,
+ hours_ago: int = 1,
+ served_version: str = SERVED_VERSION,
) -> None:
SignalReportArtefact.objects.create(
team=self.team,
@@ -106,12 +125,17 @@ class TestReportsDueForScoring(ClickhouseTestMixin, BaseTest):
embedding_inserted_at=vector_at,
manifest_version=manifest,
scored_at=self.now - datetime.timedelta(hours=hours_ago),
+ served_version=served_version,
),
)
def _due(self, limit: int = 100) -> list[str]:
candidates = reports_due_for_scoring(
- self.now, manifest_version=MANIFEST, rendering=EMBEDDING_RENDERING_TITLE_SUMMARY, limit=limit
+ self.now,
+ manifest_version=MANIFEST,
+ served_key=SERVED_KEY,
+ rendering=EMBEDDING_RENDERING_TITLE_SUMMARY,
+ limit=limit,
)
return [candidate.report_id for candidate in candidates]
@@ -134,6 +158,10 @@ class TestReportsDueForScoring(ClickhouseTestMixin, BaseTest):
other_manifest = self._report()
self._scored(other_manifest, vector_at=self._vector(other_manifest, hours_ago=5), manifest=OLD_MANIFEST)
+ # A served override changes the served model under the same manifest version.
+ other_served = self._report()
+ self._scored(other_served, vector_at=self._vector(other_served, hours_ago=5), served_version="2026-08-25")
+
retracted = self._report()
self._vector(retracted, hours_ago=5)
self._vector(retracted, hours_ago=2, deleted=True)
@@ -148,7 +176,7 @@ class TestReportsDueForScoring(ClickhouseTestMixin, BaseTest):
wrong_team = self._report(team=other_team)
self._vector(wrong_team, hours_ago=5, team_id=self.team.pk)
- assert sorted(self._due()) == sorted([unscored, edited, other_manifest])
+ assert sorted(self._due()) == sorted([unscored, edited, other_manifest, other_served])
def test_the_cap_keeps_unscored_reports_first_then_the_oldest_scores(self) -> None:
recently_scored, long_ago_scored, unscored = self._report(), self._report(), self._report()
@@ -164,9 +192,13 @@ class TestReportsDueForScoring(ClickhouseTestMixin, BaseTest):
class TestScoreInboxReports(SimpleTestCase):
def setUp(self) -> None:
super().setUp()
- self.serving = SimpleNamespace(manifest=SimpleNamespace(manifest_version=MANIFEST))
+ self.serving = SimpleNamespace(
+ manifest=SimpleNamespace(manifest_version=MANIFEST, served=SimpleNamespace(key=SERVED_KEY)),
+ served_override=None,
+ )
+ self._patch(sweep, "read_ranking_overrides", return_value=NO_OVERRIDES)
self.load_serving_set = self._patch(sweep, "load_serving_set", return_value=self.serving)
- self._patch(scorer, "served_rendering", return_value=EMBEDDING_RENDERING_TITLE_SUMMARY)
+ self.served_rendering = self._patch(scorer, "served_rendering", return_value=EMBEDDING_RENDERING_TITLE_SUMMARY)
self.due = self._patch(sweep, "reports_due_for_scoring", return_value=[])
self.score_reports = self._patch(scorer, "score_reports", side_effect=self._outcomes)
self.capture = MagicMock()
@@ -306,6 +338,28 @@ class TestScoreInboxReports(SimpleTestCase):
2,
)
+ def test_a_served_override_the_scorer_cannot_serve_falls_back_to_the_manifest(self) -> None:
+ # A tabular override loads, but no pass can serve it, so taking it would stop every pass.
+ overridden = SimpleNamespace(
+ manifest=SimpleNamespace(manifest_version=MANIFEST, served=SimpleNamespace(key="tabular_xgb@2026-09-01")),
+ served_override=RankingOverrides(served="tabular_xgb@2026-09-01"),
+ )
+ self.load_serving_set.side_effect = [overridden, self.serving]
+ self.served_rendering.side_effect = lambda serving: (
+ _raise(ScoringError("not served yet")) if serving is overridden else EMBEDDING_RENDERING_TITLE_SUMMARY
+ )
+ self._candidates((1, "a"))
+
+ score_inbox_reports()
+
+ assert self.score_reports.call_args.kwargs["serving"] is self.serving
+ assert self.due.call_args.kwargs["served_key"] == SERVED_KEY
+ self.logger.warning.assert_any_call(
+ "inbox_ranking_override_rejected",
+ override_served="tabular_xgb@2026-09-01",
+ reason="not served yet",
+ )
+
@parameterized.expand(
[("scoring_error", ScoringError("no served score")), ("served_model_load", ModelLoadError("no booster"))]
)
@@ -317,3 +371,94 @@ class TestScoreInboxReports(SimpleTestCase):
score_inbox_reports()
assert self.score_reports.call_count == 1
+
+
+NOW = datetime.datetime(2026, 10, 4, 12, 0, tzinfo=datetime.UTC)
+EXPIRES = "2026-10-11T00:00:00Z"
+
+
+class TestParseOverrides(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("absent", None, NO_OVERRIDES, None),
+ ("empty", {}, NO_OVERRIDES, None),
+ ("not_an_object", ["report_embeddings@2026-10-03"], NO_OVERRIDES, "inbox_ranking_override_invalid"),
+ (
+ "missing_expiry",
+ {"served": "report_embeddings@2026-10-03"},
+ NO_OVERRIDES,
+ "inbox_ranking_override_invalid",
+ ),
+ (
+ "expired",
+ {"expires_at": "2026-10-04T11:00:00Z", "served": "report_embeddings@2026-10-03"},
+ NO_OVERRIDES,
+ "inbox_ranking_override_expired",
+ ),
+ (
+ "too_far_ahead",
+ {"expires_at": "2026-10-19T00:00:00Z", "served": "report_embeddings@2026-10-03"},
+ NO_OVERRIDES,
+ "inbox_ranking_override_invalid",
+ ),
+ (
+ "unknown_gate",
+ {"expires_at": EXPIRES, "promotion": {"skip_gates": {"report_embeddings": ["auc"]}}},
+ NO_OVERRIDES,
+ "inbox_ranking_override_invalid",
+ ),
+ (
+ "unknown_key",
+ {"expires_at": EXPIRES, "serve": "report_embeddings@2026-10-03"},
+ NO_OVERRIDES,
+ "inbox_ranking_override_invalid",
+ ),
+ (
+ "pin_not_a_model_key",
+ {"expires_at": EXPIRES, "pin": ["../champion.json"]},
+ NO_OVERRIDES,
+ "inbox_ranking_override_invalid",
+ ),
+ (
+ "valid",
+ {
+ "expires_at": EXPIRES,
+ "served": "report_embeddings@2026-10-03",
+ "pin": ["report_embeddings@2026-09-26"],
+ "promotion": {
+ "freeze": ["tabular_xgb"],
+ "force": ["report_embeddings"],
+ "skip_gates": {"report_embeddings": ["min_days", "ece"]},
+ },
+ },
+ RankingOverrides(
+ expires_at=datetime.datetime(2026, 10, 11, tzinfo=datetime.UTC),
+ served="report_embeddings@2026-10-03",
+ pin=("report_embeddings@2026-09-26",),
+ freeze=frozenset({"tabular_xgb"}),
+ force=frozenset({"report_embeddings"}),
+ skip_gates={"report_embeddings": frozenset({"min_days", "ece"})},
+ ),
+ None,
+ ),
+ ]
+ )
+ def test_parse_overrides(self, _name: str, payload: Any, expected: RankingOverrides, warning: str | None) -> None:
+ with patch("products.signals.backend.ranking.overrides.logger") as logger:
+ assert parse_overrides(payload, now=NOW) == expected
+ assert [call.args[0] for call in logger.warning.call_args_list] == ([warning] if warning else [])
+
+ def test_freeze_wins_over_force_and_skip_gates(self) -> None:
+ overrides = parse_overrides(
+ {
+ "expires_at": EXPIRES,
+ "promotion": {
+ "freeze": ["report_embeddings"],
+ "force": ["report_embeddings"],
+ "skip_gates": {"report_embeddings": ["ece"]},
+ },
+ },
+ now=NOW,
+ )
+ promotion = overrides.promotion_for("report_embeddings")
+ assert (promotion.freeze, promotion.force, promotion.skip_gates) == (True, False, frozenset())
diff --git a/products/signals/dags/inbox_ranking/README.md b/products/signals/dags/inbox_ranking/README.md
index f5a4ca01ea72..720841bdc375 100644
--- a/products/signals/dags/inbox_ranking/README.md
+++ b/products/signals/dags/inbox_ranking/README.md
@@ -106,12 +106,58 @@ s3://<object-storage bucket>/<prefix>/serving/
└── manifest.json # the models one scoring pass runs
```
-The manifest holds one entry per model with its `roles`: `served` for the champion of `INBOX_RANKING_SERVED_FAMILY`, `daily_candidate` for that family's candidate on this partition when it is a different, readable model, and `cross_family` for every other family's champion that has a readable head. A pass scores all of them, so an online paired read and a later interleaving need no rescoring; the entry count is capped at the `ranking_score` artefact's own limit, dropping `cross_family` entries first. The schema, the role names and the object keys live in `products/signals/backend/ranking/serving_manifest.py`, and its validators run at write time, so the dag refuses a manifest the sweep could not act on. A model version is immutable, so a version already in the store is not copied again, and `manifest.json` is written last: a failed copy leaves the previous manifest and the previous models serving. No family has a champion until the first promotion, so until then the asset writes nothing and says why.
+The manifest holds one entry per model with its `roles`: `served` for the champion of `INBOX_RANKING_SERVED_FAMILY`, `daily_candidate` for that family's candidate on this partition when it is a different, readable model, `pinned` for each model the `pin` override keeps (see [Overrides](#overrides)), and `cross_family` for every other family's champion that has a readable head. A pass scores all of them, so an online paired read and a later interleaving need no rescoring; the entry count is capped at the `ranking_score` artefact's own limit, dropping `cross_family` entries first and `pinned` entries next. The schema, the role names and the object keys live in `products/signals/backend/ranking/serving_manifest.py`, and its validators run at write time, so the dag refuses a manifest the sweep could not act on. A model version is immutable, so a version already in the store is not copied again, and `manifest.json` is written last: a failed copy leaves the previous manifest and the previous models serving. No family has a champion until the first promotion, so until then the asset writes nothing and says why.
A region that does not train serves the same models through a mirror. When `INBOX_RANKING_SERVING_MIRROR_BUCKET` is set, the asset repeats the publish into that bucket after the primary publish succeeds, in the same order and with the same skip of versions already there. A mirror failure does not fail the asset: it logs, and the `inbox_ranking_serving_manifest_published` event carries `mirror_published=false`. The property is absent when no mirror is set.
The reader is `score_reports` in `products/signals/backend/ranking/scorer.py`. It loads every model the manifest names through `model_store.py`, reads each report's latest vector once per rendering, builds each model's matrix with its own `FeatureSet.build_matrix`, and writes one `ranking_score` artefact per report plus one `inbox_ranking_report_scored` event per report and model. The dag and the reader decide whether a model can be scored with the same functions, in `products/signals/backend/ranking/model_contract.py`. A served model that cannot load stops the pass. Any other model that cannot load, or has no vector for a report, is a `skipped` result. The embedding families are the only ones served, so a tabular entry is a `skipped` result too. No scheduled caller runs the reader yet.
+### Overrides
+
+An owner can change serving and promotion without a training run, through the payload of the `inbox-ranking-overrides` feature flag in the internal PostHog project. The flag is inert by default. When the flag is off, the payload is empty, or the lookup fails, the sweep and the dag run as they do without the flag. The parser is `products/signals/backend/ranking/overrides.py`, and the sweep and the dag share it.
+
+Every key is optional, but no key applies without `expires_at`:
+
+```json
+{
+ "expires_at": "2026-10-11T00:00:00Z",
+ "served": "report_embeddings@2026-10-03",
+ "pin": ["report_embeddings@2026-09-26"],
+ "promotion": {
+ "freeze": ["report_embeddings"],
+ "force": ["report_embeddings"],
+ "skip_gates": { "report_embeddings": ["min_days", "ece", "min_holdout_positives"] }
+ }
+}
+```
+
+| Key | Read by | Effect |
+| ---------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `expires_at` | sweep and dag | Required. After this time the sweep and the dag ignore the payload and log `inbox_ranking_override_expired`. A payload with no `expires_at`, or one more than 14 days ahead, is invalid. |
+| `served` | sweep, once per pass | Gives this model key the `served` role for the pass. The key must name a model in the current manifest, a pinned one included. No `champion.json` changes, and removing the key reverts on the next tick. |
+| `pin` | dag (`inbox_ranking_serving_manifest`) | Keeps these model keys in the manifest with the `pinned` role, so a `served` override survives the next manifest rewrite and can roll back to an older model. |
+| `promotion.freeze` | dag (`inbox_ranking_model_champion`) | For these families, the run trains, grades and records the decision, but never writes `champion.json`. |
+| `promotion.force` | dag (`inbox_ranking_model_champion`) | For these families, the run promotes the day's candidate when `decide_promotion` refuses it. The candidate must still be newer than the champion and have a readable head. This is a lasting champion change. |
+| `promotion.skip_gates` | dag (`inbox_ranking_model_champion`) | Waives named checks of `decide_promotion` for one family: `min_days` (the `INBOX_RANKING_PROMOTION_MIN_DAYS` wait), `ece` (`ECE_TOLERANCE`), `min_holdout_positives` (a head whose candidate holdout is too thin to read does not block). |
+
+`freeze` wins over `force` and `skip_gates` for the same family. `force` and `skip_gates` still need `INBOX_RANKING_AUTO_PROMOTE` on, so the flag cannot promote where promotion is off. An unknown key, an unknown gate, or a model key that is not `<model_name>@<YYYY-MM-DD>` makes the whole payload invalid: it is never partly applied, and `inbox_ranking_override_invalid` logs the reason.
+
+The worst result of a bad payload is a warning, never a stopped pass or an unpublished manifest:
+
+- A `served` key that is not in the manifest, that did not load (missing files, a feature contract mismatch, an untrained head), that has fewer heads than the manifest's served model, or that the sweep cannot serve (a tabular model) is rejected. The sweep logs `inbox_ranking_override_rejected` and scores with the manifest's served model. The override only moves the `served` role among models the pods already load, so it never adds memory.
+- A pinned key whose `metadata.json` or boosters are missing in the dataset bucket, or that fails `model_mismatch`, is dropped before composition. The manifest still publishes, and the asset metadata lists `pinned_keys` and `dropped_pins` with reasons.
+
+During a `served` override, the override model carries the roles `served` and `served_override`, and the manifest's served model carries `manifest_served` in place of `served`. The sweep compares the served key on the latest `ranking_score` with the effective one, so setting or removing an override rescores every report in the window. The `inbox_ranking_sweep_finished` log and each `inbox_ranking_report_scored` event carry `override_served` and `override_expires_at`. The `inbox_ranking_promotion_decided` event carries `override` (`frozen`, `forced`, `skipped_gates` or null) and `override_skipped_gates`, next to the `reason` the rule gave, so a forced promotion still records why the rule refused it.
+
+Examples, each with an `expires_at` at most 14 days ahead:
+
+- Serve today's candidate now: set `served` to the `daily_candidate` key of the current manifest.
+- Roll back to an older champion: add its key to `pin`, wait for the next manifest run (or rematerialize `inbox_ranking_serving_manifest`), then set `served` to the same key.
+- Pause promotion while a regression is investigated: `"promotion": {"freeze": ["report_embeddings"]}`.
+- Promote a candidate the rule refused for a harmless reason: `"promotion": {"force": ["report_embeddings"]}`, or the narrower `skip_gates` with the gate that refused it.
+
+Both regions read the same flag, so one override applies everywhere, if the region's `posthoganalytics` client evaluates flags in the internal project. A region that cannot read the flag runs with no override. Nothing deletes old model prefixes in the dataset bucket or old `serving/models/<key>/` copies. If the bucket has a lifecycle rule, a rollback through `pin` works only while the model files are still there.
+
### Outcome heads
| Head | Cohort at the horizon | Horizon (days) |
diff --git a/products/signals/dags/inbox_ranking/tests/test_training.py b/products/signals/dags/inbox_ranking/tests/test_training.py
index cfd1673c24e4..1e41467376b2 100644
--- a/products/signals/dags/inbox_ranking/tests/test_training.py
+++ b/products/signals/dags/inbox_ranking/tests/test_training.py
@@ -47,10 +47,12 @@ from products.signals.backend.ranking.model_contract import (
readable_head_names,
trained_head_files,
)
+from products.signals.backend.ranking.overrides import PromotionOverride, RankingOverrides
from products.signals.backend.ranking.serving_manifest import (
CROSS_FAMILY_ROLE,
DAILY_CANDIDATE_ROLE,
DEFAULT_MODEL_KIND,
+ PINNED_ROLE,
SERVED_ROLE,
ServingManifest,
ServingManifestEntry,
@@ -76,6 +78,7 @@ from products.signals.dags.inbox_ranking.training.dag import (
_EXTRA_SNAPSHOT_TABLES,
METADATA_FILE,
_delete_other_objects,
+ _pinned_models,
_publish_manifest,
_train_candidate,
candidate_metadata,
@@ -118,6 +121,8 @@ from products.signals.dags.inbox_ranking.training.promotion import (
AUC_TOLERANCE,
ECE_TOLERANCE,
PromotionDecision,
+ PromotionOutcome,
+ apply_promotion_override,
decide_promotion,
)
from products.signals.dags.inbox_ranking.training.served import served_events, served_metadata, served_score_rows
@@ -1383,12 +1388,33 @@ class _ModelStoreS3:
def __init__(self, objects: dict[str, bytes]):
self.objects = objects
+ def head_object(self, *, Bucket, Key):
+ if Key not in self.objects:
+ raise ClientError({"Error": {"Code": "404"}}, "HeadObject")
+ return {"ContentLength": len(self.objects[Key])}
+
def get_object(self, *, Bucket, Key):
if Key not in self.objects:
raise ClientError({"Error": {"Code": "NoSuchKey"}}, "GetObject")
return {"Body": io.BytesIO(self.objects[Key])}
+class _DeniedPrefixS3(_ModelStoreS3):
+ def __init__(self, objects: dict[str, bytes], *, denied_prefix: str):
+ super().__init__(objects)
+ self.denied_prefix = denied_prefix
+
+ def head_object(self, *, Bucket, Key):
+ if Key.startswith(self.denied_prefix):
+ raise ClientError({"Error": {"Code": "AccessDenied"}}, "HeadObject")
+ return super().head_object(Bucket=Bucket, Key=Key)
+
+ def get_object(self, *, Bucket, Key):
+ if Key.startswith(self.denied_prefix):
+ raise ClientError({"Error": {"Code": "AccessDenied"}}, "GetObject")
+ return super().get_object(Bucket=Bucket, Key=Key)
+
+
def test_load_unseen_models_skips_a_family_with_nothing_to_score_that_day(monkeypatch):
# A family registered before its first trainer run, or one whose candidate failed, must cost only its own line.
partition_key = "2026-08-19"
@@ -1514,6 +1540,7 @@ def test_training_events_carry_the_dashboard_contract(monkeypatch):
run_id="run-1",
model_name=TABULAR_MODEL_NAME,
decision=PromotionDecision(promote=True, reason="no champion yet", skipped_heads=("discuss",)),
+ outcome=PromotionOutcome(promote=True, override=None),
promoted=False,
champion_version="none",
incumbent_champion_version="none",
@@ -1823,6 +1850,132 @@ def test_decide_promotion_refuses_a_worse_calibrated_candidate(candidate_ece, ch
assert expected_promote or "open calibration regressed" in decision.reason
+_RECENT_CHAMPION = {**_metadata("d1", open=0.70), "promoted_at": "2026-08-19T00:00:00+00:00"}
+
+
+ "gate,candidate,champion,grades,expected_reason",
+ [
+ ("min_days", _metadata("d2", open=0.70), _RECENT_CHAMPION, {}, "less than 3d ago"),
+ (
+ "ece",
+ {
+ "model_version": "d2",
+ "heads": [{**_head("open", 0.70, readable=True), "holdout_expected_calibration_error": 0.3}],
+ },
+ {**_metadata("d1", open=0.70), "promoted_at": "2026-08-10T00:00:00+00:00"},
+ {"open": _grade(auc=0.70, ece=0.05, positives=60)},
+ "open calibration regressed",
+ ),
+ (
+ "min_holdout_positives",
+ {
+ "model_version": "d2",
+ "heads": [
+ _head("open", 0.70, readable=True),
+ {**_head("discuss", 0.60, readable=False), "holdout_positives": 4},
+ ],
+ },
+ {**_metadata("d1", open=0.70, discuss=0.70), "promoted_at": "2026-08-10T00:00:00+00:00"},
+ {},
+ "discuss readable on champion but not on candidate",
+ ),
+ ],
+)
+def test_a_skipped_gate_waives_only_that_check(gate, candidate, champion, grades, expected_reason):
+ kwargs = {
+ "now": NOW,
+ "min_days_between": 3,
+ "champion_grades": grades,
+ "min_holdout_positives": {"open": 50, "discuss": 30},
+ }
+ refused = decide_promotion(candidate, champion, **kwargs)
+ assert not refused.promote and expected_reason in refused.reason
+
+ assert decide_promotion(candidate, champion, **kwargs, skip_gates={gate}).promote
+ other_gates = {"min_days", "ece", "min_holdout_positives"} - {gate}
+ assert not decide_promotion(candidate, champion, **kwargs, skip_gates=other_gates).promote
+
+
+def test_a_waived_holdout_floor_still_blocks_a_head_the_candidate_lost():
+ candidate = _metadata("d2", open=0.70)
+ champion = {**_metadata("d1", open=0.70, action=0.65), "promoted_at": "2026-08-10T00:00:00+00:00"}
+
+ decision = decide_promotion(candidate, champion, now=NOW, min_days_between=3, skip_gates={"min_holdout_positives"})
+
+ assert not decision.promote
+
+
+_REFUSED = PromotionDecision(promote=False, reason="open regressed: 0.600 vs champion 0.700")
+_PROMOTED = PromotionDecision(promote=True, reason="candidate at or above champion on every readable head")
+_OLDER_CHAMPION = {**_metadata("2026-08-10", open=0.70), "promoted_at": "2026-08-10T00:00:00+00:00"}
+
+
+ "decision,candidate,override,expected",
+ [
+ (
+ _PROMOTED,
+ _metadata("2026-08-19", open=0.70),
+ PromotionOverride(),
+ PromotionOutcome(promote=True, override=None),
+ ),
+ (
+ _PROMOTED,
+ _metadata("2026-08-19", open=0.70),
+ PromotionOverride(freeze=True),
+ PromotionOutcome(promote=False, override="frozen"),
+ ),
+ (
+ _REFUSED,
+ _metadata("2026-08-19", open=0.60),
+ PromotionOverride(force=True),
+ PromotionOutcome(promote=True, override="forced"),
+ ),
+ # Force never moves the pointer backwards, or onto a model with nothing readable.
+ (
+ _REFUSED,
+ _metadata("2026-08-10", open=0.90),
+ PromotionOverride(force=True),
+ PromotionOutcome(promote=False, override=None),
+ ),
+ (
+ _REFUSED,
+ _metadata("2026-08-19", open=None),
+ PromotionOverride(force=True),
+ PromotionOutcome(promote=False, override=None),
+ ),
+ (
+ _REFUSED,
+ _metadata("2026-08-19", open=0.60),
+ PromotionOverride(skip_gates=frozenset({"ece"})),
+ PromotionOutcome(promote=False, override="skipped_gates"),
+ ),
+ ],
+ ids=["none", "freeze", "force", "force_not_newer", "force_unreadable", "skip_gates"],
+)
+def test_apply_promotion_override(decision, candidate, override, expected):
+ assert apply_promotion_override(decision, candidate, _OLDER_CHAMPION, override) == expected
+
+
+def test_a_forced_promotion_records_the_reason_the_rule_refused_it():
+ event = promotion_event(
+ partition_key="2026-08-19",
+ run_id="run-1",
+ model_name=EMBEDDINGS_MODEL_NAME,
+ decision=_REFUSED,
+ outcome=PromotionOutcome(promote=True, override="forced"),
+ promoted=True,
+ champion_version="2026-08-19",
+ incumbent_champion_version="2026-08-10",
+ champion_aucs={},
+ champion_eces={},
+ )
+ assert {"would_promote": False, "promoted": True, "reason": _REFUSED.reason, "override": "forced"}.items() <= (
+ event.properties.items()
+ )
+
+
class _FakeS3:
def __init__(self, keys: list[str]):
self.keys = set(keys)
@@ -2681,6 +2834,39 @@ def test_the_cap_drops_cross_family_entries_before_the_paired_read():
]
+def test_a_pinned_model_is_kept_and_capped_before_the_paired_read():
+ families = [
+ FamilyModels(
+ name=EMBEDDINGS_MODEL_NAME,
+ candidate=_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-19"),
+ champion=_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-15"),
+ ),
+ FamilyModels(
+ name=TABULAR_MODEL_NAME, candidate=None, champion=_serving_metadata(TABULAR_MODEL_NAME, "2026-08-10")
+ ),
+ ]
+ pinned = [_serving_metadata(EMBEDDINGS_MODEL_NAME, f"2026-08-0{day}", readable=False) for day in range(1, 5)]
+ # A pin of a model the manifest already names gains no second entry.
+ pinned.append(_serving_metadata(EMBEDDINGS_MODEL_NAME, "2026-08-19"))
+
+ decision = compose_manifest(
+ families,
+ served_family=EMBEDDINGS_MODEL_NAME,
+ prefix="inbox_ranking",
+ now=datetime.datetime(2026, 8, 19, 6, tzinfo=datetime.UTC),
+ pinned=pinned,
+ )
+
+ assert decision.manifest is not None
+ assert [(entry.roles[0], entry.model_version) for entry in decision.manifest.models] == [
+ (SERVED_ROLE, "2026-08-15"),
+ (DAILY_CANDIDATE_ROLE, "2026-08-19"),
+ (PINNED_ROLE, "2026-08-01"),
+ (PINNED_ROLE, "2026-08-02"),
+ (PINNED_ROLE, "2026-08-03"),
+ ]
+
+
def test_a_model_published_before_model_kind_existed_reads_as_xgboost():
# Every champion promoted so far was written without the field; reading it as missing would
# leave the model store with nothing to dispatch on.
@@ -2736,6 +2922,7 @@ def _run_serving_manifest(
store: _AppObjectStore,
dataset_objects: dict[str, bytes] | None = None,
mirror: _AppObjectStore | None = None,
+ dataset_client: _ModelStoreS3 | None = None,
) -> _FakeClient:
partition_key = "2026-08-19"
prefix = settings.INBOX_RANKING_DATASET_S3_PREFIX
@@ -2745,7 +2932,7 @@ def _run_serving_manifest(
"products.signals.dags.inbox_ranking.training.dag.MODEL_FAMILIES",
(ModelFamily(name=EMBEDDINGS_MODEL_NAME, feature_set=REPORT_EMBEDDINGS_FEATURE_SET),),
)
- client = (
+ client = dataset_client or (
_ModelStoreS3(dataset_objects) if dataset_objects is not None else _serving_dataset_s3(prefix, partition_key)
)
monkeypatch.setattr("products.signals.dags.inbox_ranking.training.dag.s3_client", lambda: client)
@@ -2860,6 +3047,45 @@ def test_no_manifest_is_written_when_the_served_family_has_no_champion(monkeypat
assert store.objects == {}
+def test_a_missing_pin_is_dropped_and_the_manifest_still_publishes(monkeypatch):
+ prefix = settings.INBOX_RANKING_DATASET_S3_PREFIX
+ client = _serving_dataset_s3(prefix, "2026-08-19")
+ pin_version = "2026-08-01"
+ pin_metadata = {
+ **_serving_metadata(EMBEDDINGS_MODEL_NAME, pin_version, heads=("open",)),
+ "feature_set": REPORT_EMBEDDINGS_FEATURE_SET.name,
+ "feature_schema_version": REPORT_EMBEDDINGS_FEATURE_SET.schema_version,
+ "feature_names": list(REPORT_EMBEDDINGS_FEATURE_SET.feature_names),
+ }
+ # The metadata is there, but the booster is not, so a copy of this pin would fail the publish.
+ client.objects[model_object_key(prefix, EMBEDDINGS_MODEL_NAME, pin_version, METADATA_FILE)] = json.dumps(
+ pin_metadata
+ ).encode()
+ missing_key = model_key(EMBEDDINGS_MODEL_NAME, pin_version)
+ absent_key = model_key(EMBEDDINGS_MODEL_NAME, "2026-07-01")
+ denied_key = model_key(EMBEDDINGS_MODEL_NAME, "2026-06-01")
+ pins = (missing_key, absent_key, denied_key)
+ monkeypatch.setattr(
+ "products.signals.dags.inbox_ranking.training.dag.read_ranking_overrides",
+ lambda now: RankingOverrides(pin=pins),
+ )
+ denied_client = _DeniedPrefixS3(
+ client.objects, denied_prefix=model_object_key(prefix, EMBEDDINGS_MODEL_NAME, "2026-06-01", "")
+ )
+ store = _AppObjectStore()
+
+ _run_serving_manifest(monkeypatch, store, dataset_client=denied_client)
+
+ manifest = ServingManifest.model_validate_json(store.objects[serving_manifest_key(prefix)])
+ assert not set(pins) & {entry.key for entry in manifest.models}
+ assert manifest.served.key == model_key(EMBEDDINGS_MODEL_NAME, "2026-08-15")
+ _, dropped = _pinned_models(denied_client, "bucket", prefix, pins)
+ assert dropped.keys() == set(pins)
+ assert "missing boosters" in dropped[missing_key]
+ assert METADATA_FILE in dropped[absent_key]
+ assert "AccessDenied" in dropped[denied_key]
+
+
def test_the_serving_prefix_layout_is_stable():
# The scoring sweep resolves these keys, so a change here is a change to the serving contract.
assert serving_manifest_key("inbox_ranking") == "inbox_ranking/serving/manifest.json"
diff --git a/products/signals/dags/inbox_ranking/training/dag.py b/products/signals/dags/inbox_ranking/training/dag.py
index 282a83119431..d1970b7cfbc0 100644
--- a/products/signals/dags/inbox_ranking/training/dag.py
+++ b/products/signals/dags/inbox_ranking/training/dag.py
@@ -76,6 +76,7 @@ from products.signals.backend.ranking.model_contract import (
readable_head_names,
trained_head_files,
)
+from products.signals.backend.ranking.overrides import RankingOverrides, read_ranking_overrides
from products.signals.backend.ranking.serving_manifest import DEFAULT_MODEL_KIND, ServingManifest, serving_manifest_key
from products.signals.dags.inbox_ranking.common import (
DATASET_VERSION,
@@ -123,7 +124,7 @@ from products.signals.dags.inbox_ranking.training.heads import (
HEADS_BY_HORIZON,
HEADS_BY_NAME,
)
-from products.signals.dags.inbox_ranking.training.promotion import decide_promotion
+from products.signals.dags.inbox_ranking.training.promotion import apply_promotion_override, decide_promotion
from products.signals.dags.inbox_ranking.training.serving import FamilyModels, compose_manifest
from products.signals.dags.inbox_ranking.training.telemetry import (
HeadExampleCounts,
@@ -747,10 +748,11 @@ def inbox_ranking_model_champion(context: dagster.AssetExecutionContext) -> None
partition_key = context.partition_key
bucket, prefix, client = dataset_bucket(), settings.INBOX_RANKING_DATASET_S3_PREFIX, s3_client()
+ overrides = read_ranking_overrides(datetime.datetime.now(datetime.UTC))
metadata: dict[str, dagster.MetadataValue] = {}
decided = 0
for family in MODEL_FAMILIES:
- family_metadata = _decide_champion(context, client, bucket, prefix, partition_key, family)
+ family_metadata = _decide_champion(context, client, bucket, prefix, partition_key, family, overrides)
if family_metadata is None:
continue
decided += 1
@@ -769,6 +771,7 @@ def _decide_champion(
prefix: str,
partition_key: str,
family: ModelFamily,
+ overrides: RankingOverrides,
) -> dict[str, dagster.MetadataValue] | None:
"""One family's promotion decision against its own pointer, or None when the family has no
candidate for the partition."""
@@ -821,6 +824,7 @@ def _decide_champion(
f"{family.name} champion {champion['model_version']} on this holdout: "
f"AUC {champion_aucs}, ECE {champion_eces}"
)
+ promotion_override = overrides.promotion_for(family.name)
decision = decide_promotion(
candidate,
champion,
@@ -828,13 +832,16 @@ def _decide_champion(
min_days_between=settings.INBOX_RANKING_PROMOTION_MIN_DAYS,
champion_grades=champion_grades,
min_holdout_positives={name: head.min_holdout_positives for name, head in HEADS_BY_NAME.items()},
+ skip_gates=promotion_override.skip_gates,
)
+ outcome = apply_promotion_override(decision, candidate, champion, promotion_override)
context.log.info(
- f"{family.name} promotion decision for dt={partition_key}: promote={decision.promote} ({decision.reason})"
+ f"{family.name} promotion decision for dt={partition_key}: promote={decision.promote} ({decision.reason}), "
+ f"override={outcome.override}, outcome promote={outcome.promote}"
)
promoted = False
- if decision.promote and settings.INBOX_RANKING_AUTO_PROMOTE:
+ if outcome.promote and settings.INBOX_RANKING_AUTO_PROMOTE:
_put_json(
client,
bucket,
@@ -846,7 +853,7 @@ def _decide_champion(
},
)
promoted = True
- elif decision.promote:
+ elif outcome.promote:
context.log.info(f"INBOX_RANKING_AUTO_PROMOTE is off; the {family.name} candidate would have been promoted")
# The paired AUCs belong to the incumbent: after a promotion `champion_version` names the
@@ -862,11 +869,13 @@ def _decide_champion(
run_id=context.run.run_id,
model_name=family.name,
decision=decision,
+ outcome=outcome,
promoted=promoted,
champion_version=champion_version,
incumbent_champion_version=incumbent_champion_version,
champion_aucs=champion_aucs,
champion_eces=champion_eces,
+ skipped_gates=promotion_override.skip_gates,
)
],
)
@@ -874,6 +883,7 @@ def _decide_champion(
f"{family.name}_would_promote": dagster.MetadataValue.bool(decision.promote),
f"{family.name}_promoted": dagster.MetadataValue.bool(promoted),
f"{family.name}_reason": dagster.MetadataValue.text(decision.reason),
+ f"{family.name}_override": dagster.MetadataValue.text(outcome.override or "none"),
f"{family.name}_skipped_heads": dagster.MetadataValue.json(list(decision.skipped_heads)),
**{
f"{family.name}_champion_{head}_auc_on_this_holdout": dagster.MetadataValue.float(auc)
@@ -917,6 +927,10 @@ def _publish_manifest(
) -> dict[str, dagster.MetadataValue]:
bucket, prefix, client = dataset_bucket(), settings.INBOX_RANKING_DATASET_S3_PREFIX, s3_client()
served_family = settings.INBOX_RANKING_SERVED_FAMILY
+ overrides = read_ranking_overrides(datetime.datetime.now(datetime.UTC))
+ pinned, dropped_pins = _pinned_models(client, bucket, prefix, overrides.pin)
+ for key, reason in dropped_pins.items():
+ context.log.warning(f"pinned model {key} dropped: {reason}")
families = [
FamilyModels(
@@ -929,8 +943,17 @@ def _publish_manifest(
for family in MODEL_FAMILIES
]
decision = compose_manifest(
- families, served_family=served_family, prefix=prefix, now=datetime.datetime.now(datetime.UTC)
+ families, served_family=served_family, prefix=prefix, now=datetime.datetime.now(datetime.UTC), pinned=pinned
)
+ manifest_keys = {entry.key for entry in decision.manifest.models} if decision.manifest else set()
+ if decision.manifest is not None:
+ for key in overrides.pin:
+ if key not in dropped_pins and key not in manifest_keys:
+ dropped_pins[key] = "over the manifest entry cap"
+ pin_metadata = {
+ "pinned_keys": dagster.MetadataValue.json(sorted(set(overrides.pin) & manifest_keys)),
+ "dropped_pins": dagster.MetadataValue.json(dropped_pins),
+ }
if decision.manifest is None:
context.log.warning(f"no serving manifest for dt={partition_key}: {decision.reason}")
capture_training_events(
@@ -946,7 +969,7 @@ def _publish_manifest(
)
],
)
- return {"published": dagster.MetadataValue.bool(False)}
+ return {"published": dagster.MetadataValue.bool(False), **pin_metadata}
manifest = decision.manifest
manifest_key = serving_manifest_key(prefix)
@@ -985,10 +1008,67 @@ def _publish_manifest(
"entries_copied": dagster.MetadataValue.int(len(publication.copied)),
"entries_already_present": dagster.MetadataValue.int(len(publication.present)),
"bytes_copied": dagster.MetadataValue.int(publication.bytes_copied),
+ **pin_metadata,
**mirror_metadata,
}
+def _object_exists(client, bucket: str, key: str) -> bool:
+ try:
+ client.head_object(Bucket=bucket, Key=key)
+ except ClientError as error:
+ if error.response.get("Error", {}).get("Code") in ("404", "NoSuchKey", "NotFound"):
+ return False
+ raise
+ return True
+
+
+def _pinned_models(
+ client, bucket: str, prefix: str, keys: Sequence[str]
+) -> tuple[list[dict[str, Any]], dict[str, str]]:
+ """The metadata of each pinned model this build can serve, and the reason each other pin is dropped.
+
+ `publish_serving_models` fails the whole manifest when a file it copies is missing, so a pin
+ is checked here, before composition. A bad pin then costs only itself.
+ """
+ pinned: list[dict[str, Any]] = []
+ dropped: dict[str, str] = {}
+ for key in keys:
+ try:
+ metadata, reason = _pin_metadata(client, bucket, prefix, key)
+ # S3 answers 403, not 404, for a missing key when the role cannot list the prefix, and a
+ # pin must cost only itself, so every read error drops the pin.
+ except (ClientError, ValueError) as error:
+ metadata, reason = None, f"could not read the model: {error!r}"
+ if metadata is None:
+ dropped[key] = reason or "unknown"
+ continue
+ pinned.append(metadata)
+ return pinned, dropped
+
+
+def _pin_metadata(client, bucket: str, prefix: str, key: str) -> tuple[dict[str, Any] | None, str | None]:
+ """The metadata of one pinned model, or None and the reason it cannot be served."""
+ model_name, model_version = key.split("@", 1)
+ metadata = _read_json_if_exists(client, bucket, model_object_key(prefix, model_name, model_version, METADATA_FILE))
+ if metadata is None:
+ return None, f"no {METADATA_FILE} in the dataset bucket"
+ if (metadata.get("model_name"), metadata.get("model_version")) != (model_name, model_version):
+ return None, f"{METADATA_FILE} describes another model"
+ mismatch = model_mismatch(metadata)
+ if mismatch is not None:
+ return None, mismatch
+ heads = trained_head_files(metadata, HEADS_BY_NAME)
+ missing = [
+ f"{head}.ubj"
+ for head in sorted(heads)
+ if not _object_exists(client, bucket, model_object_key(prefix, model_name, model_version, f"{head}.ubj"))
+ ]
+ if not heads or missing:
+ return None, f"missing boosters {missing}" if missing else "no trained head"
+ return metadata, None
+
+
def _publish_mirror(
context: dagster.AssetExecutionContext, client, bucket: str, prefix: str, manifest: ServingManifest
) -> bool | None:
diff --git a/products/signals/dags/inbox_ranking/training/promotion.py b/products/signals/dags/inbox_ranking/training/promotion.py
index 3d0c422d585d..b7ff5a5c035d 100644
--- a/products/signals/dags/inbox_ranking/training/promotion.py
+++ b/products/signals/dags/inbox_ranking/training/promotion.py
@@ -17,14 +17,19 @@ A paired grade also says how many positives the shared holdout holds. Below the
`min_holdout_positives` neither model can be read on it, so the head is skipped, not counted as a
regression. A head the candidate did not train still blocks: a candidate must not replace a champion
by losing a head the champion serves.
+
+An owner can change one family's outcome through the `promotion` override (see
+`products/signals/backend/ranking/overrides.py`). `skip_gates` waives named checks inside the rule,
+and `apply_promotion_override` applies `freeze` and `force` to the rule's decision.
"""
import datetime
-from collections.abc import Mapping
+from collections.abc import Collection, Mapping
from typing import Any
from posthog.dataclasses import frozen
+from products.signals.backend.ranking.overrides import PromotionOverride
from products.signals.dags.inbox_ranking.training.train import HoldoutGrade
# A candidate may be this much worse than the champion on a readable head and still promote: at
@@ -44,6 +49,13 @@ class PromotionDecision:
skipped_heads: tuple[str, ...] = ()
+@frozen
+class PromotionOutcome:
+ promote: bool
+ # "frozen", "forced" or "skipped_gates" when an override applied, else None.
+ override: str | None
+
+
def _readable_aucs(metadata: Mapping[str, Any]) -> dict[str, float]:
return {
head["head"]: float(head["holdout_auc"])
@@ -60,7 +72,11 @@ def decide_promotion(
min_days_between: int,
champion_grades: Mapping[str, HoldoutGrade] | None = None,
min_holdout_positives: Mapping[str, int] | None = None,
+ skip_gates: Collection[str] = (),
) -> PromotionDecision:
+ """`skip_gates` waives `min_days` (the wait since the last promotion), `ece` (the calibration
+ check) and `min_holdout_positives` (a head whose candidate holdout has fewer positives than its
+ minimum is skipped rather than blocking)."""
candidate_aucs = _readable_aucs(candidate)
candidate_heads = {head["head"]: head for head in candidate.get("heads", [])}
if not candidate_aucs:
@@ -78,12 +94,20 @@ def decide_promotion(
)
promoted_at = datetime.datetime.fromisoformat(champion["promoted_at"])
- if now - promoted_at < datetime.timedelta(days=min_days_between):
+ if "min_days" not in skip_gates and now - promoted_at < datetime.timedelta(days=min_days_between):
return PromotionDecision(
promote=False, reason=f"champion {champion['model_version']} promoted less than {min_days_between}d ago"
)
skipped: list[str] = []
for head, stored_auc in _readable_aucs(champion).items():
+ candidate_positives = candidate_heads.get(head, {}).get("holdout_positives")
+ if (
+ "min_holdout_positives" in skip_gates
+ and candidate_positives is not None
+ and candidate_positives < (min_holdout_positives or {}).get(head, 0)
+ ):
+ skipped.append(head)
+ continue
grade = (champion_grades or {}).get(head)
if grade is None:
# No shared holdout: readability was read on two different holdouts, so compare it as stored.
@@ -110,7 +134,12 @@ def decide_promotion(
champion_ece = grade.expected_calibration_error if grade is not None else None
raw_ece = candidate_heads.get(head, {}).get("holdout_expected_calibration_error")
candidate_ece = float(raw_ece) if raw_ece is not None else None
- if champion_ece is not None and candidate_ece is not None and candidate_ece > champion_ece + ECE_TOLERANCE:
+ if (
+ "ece" not in skip_gates
+ and champion_ece is not None
+ and candidate_ece is not None
+ and candidate_ece > champion_ece + ECE_TOLERANCE
+ ):
return PromotionDecision(
promote=False,
reason=f"{head} calibration regressed: ECE {candidate_ece:.3f} vs champion {champion_ece:.3f}",
@@ -122,3 +151,26 @@ def decide_promotion(
skipped_heads=tuple(skipped),
)
return PromotionDecision(promote=True, reason="candidate at or above champion on every readable head")
+
+
+def apply_promotion_override(
+ decision: PromotionDecision,
+ candidate: Mapping[str, Any],
+ champion: Mapping[str, Any] | None,
+ override: PromotionOverride,
+) -> PromotionOutcome:
+ """The rule's decision with `freeze` or `force` applied.
+
+ `force` still needs a readable head on a candidate newer than the champion, so it can never
+ move the pointer backwards or onto a model with nothing to read.
+ """
+ if override.freeze:
+ return PromotionOutcome(promote=False, override="frozen")
+ if (
+ override.force
+ and not decision.promote
+ and _readable_aucs(candidate)
+ and (champion is None or candidate["model_version"] > champion["model_version"])
+ ):
+ return PromotionOutcome(promote=True, override="forced")
+ return PromotionOutcome(promote=decision.promote, override="skipped_gates" if override.skip_gates else None)
diff --git a/products/signals/dags/inbox_ranking/training/serving.py b/products/signals/dags/inbox_ranking/training/serving.py
index 2c6f61cafddd..6064246a6128 100644
--- a/products/signals/dags/inbox_ranking/training/serving.py
+++ b/products/signals/dags/inbox_ranking/training/serving.py
@@ -6,7 +6,8 @@ picks the set the scoring sweep runs. This module is that choice as pure functio
The served entry is the champion of one family, so the served model only ever changes through a
promotion. The other entries are there so one pass produces several scores: an online paired read
-and a later interleaving then need no rescoring of the same reports.
+and a later interleaving then need no rescoring of the same reports. A pinned entry is there so an
+owner's `served` override can name it.
"""
import datetime
@@ -21,6 +22,7 @@ from products.signals.backend.ranking.serving_manifest import (
CROSS_FAMILY_ROLE,
DAILY_CANDIDATE_ROLE,
DEFAULT_MODEL_KIND,
+ PINNED_ROLE,
SERVED_ROLE,
ServingManifest,
ServingManifestEntry,
@@ -83,7 +85,10 @@ def compose_manifest(
served_family: str,
prefix: str,
now: datetime.datetime,
+ pinned: Sequence[Mapping[str, Any]] = (),
) -> ManifestDecision:
+ """`pinned` holds the metadata of the models the `pin` override keeps. The caller checks that
+ their files exist, because a manifest that names a missing file is never published."""
by_name = {family.name: family for family in families}
served_models = by_name.get(served_family)
if served_models is None:
@@ -115,6 +120,16 @@ def compose_manifest(
if daily is not None:
entries.append(daily)
+ for metadata in pinned:
+ pin = _entry(
+ metadata,
+ roles=[PINNED_ROLE],
+ labels={"reason": "pinned by the inbox-ranking-overrides flag"},
+ prefix=prefix,
+ )
+ if pin is not None and pin.key not in {entry.key for entry in entries}:
+ entries.append(pin)
+
for family in families:
if family.name == served_family or family.champion is None or not readable_head_names(family.champion):
continue
@@ -124,11 +139,12 @@ def compose_manifest(
labels={"reason": f"champion of {family.name}"},
prefix=prefix,
)
- if cross is not None:
+ if cross is not None and cross.key not in {entry.key for entry in entries}:
entries.append(cross)
# The served entry and the paired candidate are the reads the sweep exists for, so the cap
- # falls on the cross-family entries. They are last in `entries`, in family registration order.
+ # falls on the pinned and cross-family entries, cross-family first. They are last in
+ # `entries`, the cross-family ones in family registration order.
return ManifestDecision(
manifest=ServingManifest(manifest_version=now.isoformat(), models=entries[:MAX_RANKING_MODEL_RESULTS]),
reason="composed",
diff --git a/products/signals/dags/inbox_ranking/training/telemetry.py b/products/signals/dags/inbox_ranking/training/telemetry.py
index 2dae1cb5197f..7a1e105a2e18 100644
--- a/products/signals/dags/inbox_ranking/training/telemetry.py
+++ b/products/signals/dags/inbox_ranking/training/telemetry.py
@@ -9,7 +9,7 @@ fails an asset.
"""
import datetime
-from collections.abc import Mapping, Sequence
+from collections.abc import Collection, Mapping, Sequence
from typing import Any
import dagster
@@ -22,7 +22,7 @@ from posthog.ph_client import get_client
from products.signals.backend.ranking.serving_manifest import ServingManifest
from products.signals.dags.inbox_ranking.common import snapshot_bounds
from products.signals.dags.inbox_ranking.training.examples import ConsentExclusion
-from products.signals.dags.inbox_ranking.training.promotion import PromotionDecision
+from products.signals.dags.inbox_ranking.training.promotion import PromotionDecision, PromotionOutcome
from products.signals.dags.inbox_ranking.training.unseen import CANDIDATE_ROLE, HeadGrade
# Not a person: one fixed id for the whole dag, and no person profile is created for it. Local dev
@@ -150,15 +150,19 @@ def promotion_event(
run_id: str,
model_name: str,
decision: PromotionDecision,
+ outcome: PromotionOutcome,
promoted: bool,
champion_version: str,
incumbent_champion_version: str,
champion_aucs: Mapping[str, float],
champion_eces: Mapping[str, float],
+ skipped_gates: Collection[str] = (),
) -> TrainingEvent:
"""`champion_aucs` and `champion_eces` were scored by the incumbent on this candidate's holdout; after a promotion
`champion_version` is the candidate, so the incumbent is carried separately. Every version here
- belongs to `model_name`: promotion compares a candidate to the champion of its own family."""
+ belongs to `model_name`: promotion compares a candidate to the champion of its own family.
+
+ `reason` is always the rule's reason, so a forced promotion still records why the rule refused it."""
return TrainingEvent(
event=PROMOTION_DECIDED_EVENT,
properties={
@@ -168,6 +172,8 @@ def promotion_event(
"would_promote": decision.promote,
"promoted": promoted,
"reason": decision.reason,
+ "override": outcome.override,
+ "override_skipped_gates": sorted(skipped_gates),
"skipped_heads": list(decision.skipped_heads),
"champion_version": champion_version,
"incumbent_champion_version": incumbent_champion_version,