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): score inbox reports on a schedule with the ranking sweep (#106907)

posthog[bot]9f0483baac9e
diff --git a/posthog/settings/object_storage.py b/posthog/settings/object_storage.py
index a467f8a61818..2becf5d81575 100644
--- a/posthog/settings/object_storage.py
+++ b/posthog/settings/object_storage.py
@@ -113,6 +113,16 @@ INBOX_RANKING_SERVED_FAMILY = os.getenv("INBOX_RANKING_SERVED_FAMILY", "report_e
# Scorer (products/signals/backend/ranking/scorer.py): report ids per ClickHouse vector read. A
# larger call is paged at this size.
INBOX_RANKING_SCORING_BATCH_SIZE = get_from_env("INBOX_RANKING_SCORING_BATCH_SIZE", 500, type_cast=int)
+# Scoring sweep (products/signals/backend/ranking/sweep.py). Off by default: the schedule still
+# ticks, but the activity returns before it reads or writes anything. The max age keeps the vector
+# read inside a few weekly partitions and well inside the 3-month vector TTL. The per-tick cap
+# makes the first run after enabling drain the backlog over several ticks.
+INBOX_RANKING_SCORING_ENABLED = get_from_env("INBOX_RANKING_SCORING_ENABLED", False, type_cast=str_to_bool)
+INBOX_RANKING_SCORING_INTERVAL_MINUTES = get_from_env("INBOX_RANKING_SCORING_INTERVAL_MINUTES", 15, type_cast=int)
+INBOX_RANKING_SCORING_MAX_AGE_DAYS = get_from_env("INBOX_RANKING_SCORING_MAX_AGE_DAYS", 30, type_cast=int)
+INBOX_RANKING_SCORING_MAX_REPORTS_PER_TICK = get_from_env(
+ "INBOX_RANKING_SCORING_MAX_REPORTS_PER_TICK", 2000, type_cast=int
+)
# Shadow dag (products/signals/dags/inbox_ranking/shadow): how many daily scores partitions back
# the read looks for a score that already existed when a list was served. A report is scored on
# the day it is born, so this bounds how old a report can be and still be graded.
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index f6a02809850f..4571507c4de1 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -130,6 +130,7 @@ from products.replay_vision.backend.temporal.vision_alerts.schedule import creat
from products.review_hog.backend.temporal.outcomes_schedule import create_review_hog_finding_outcomes_schedule
from products.security.backend.facade.temporal import create_sync_access_rules_schedule
from products.signals.backend.emission.conversations_schedule import create_conversations_signals_coordinator_schedule
+from products.signals.backend.ranking.schedule import create_inbox_ranking_scoring_schedule
from products.signals.backend.temporal.agentic.schedule import (
create_scout_suggestions_coordinator_schedule,
create_signals_scout_coordinator_schedule,
@@ -950,6 +951,7 @@ schedules = [
create_run_investigation_safety_net_schedule,
create_cleanup_alert_checks_schedule,
create_signals_scout_coordinator_schedule,
+ create_inbox_ranking_scoring_schedule,
create_scout_suggestions_coordinator_schedule,
create_support_reply_coordinator_schedule,
create_channel_summary_coordinator_schedule,
diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.py
index 45ecc494a3b3..086fafd4dfbb 100644
--- a/posthog/temporal/tests/ai/test_module_integrity.py
+++ b/posthog/temporal/tests/ai/test_module_integrity.py
@@ -107,6 +107,7 @@ class TestSignalsProductModuleIntegrity:
"ScoutSuggestionsCoordinatorWorkflow",
"CustomSignalAgentWorkflow",
"SignalReportInboxNotificationWorkflow",
+ "InboxRankingScoringWorkflow",
]
actual_workflow_names = [w.__name__ for w in SIGNALS_PRODUCT_WORKFLOWS]
assert len(actual_workflow_names) == len(expected_workflows), (
@@ -172,6 +173,7 @@ class TestSignalsProductModuleIntegrity:
"stamp_dispatched_signals_scout_runs_activity",
"run_due_signal_report_checks_activity",
"run_signals_scout_activity",
+ "score_inbox_reports_activity",
"resume_signals_scout_workflow_step",
"plan_scout_suggestion_runs_activity",
"run_scout_suggestions_activity",
diff --git a/products/signals/backend/models.py b/products/signals/backend/models.py
index 2cc249aa4479..6251737e5e93 100644
--- a/products/signals/backend/models.py
+++ b/products/signals/backend/models.py
@@ -1256,6 +1256,9 @@ class SignalReportArtefact(UUIDModel):
ArtefactType.RANKING_SCORE,
}
)
+ # Rows the scoring sweep writes on every text edit and every new serving manifest. They record
+ # no activity a user can see, so the artefact count and the artefact log leave them out.
+ SYSTEM_SCORING_ARTEFACT_TYPES: frozenset[str] = frozenset({ArtefactType.RANKING_SCORE})
# A `report_link` graph is written by hand or by an agent, one report at a time, so a real
# chain is a handful of reports deep. The budgets guard the cycle walk on the write path
# against a graph that grew past anything a reader could order. Rows and levels are bounded
@@ -1359,12 +1362,16 @@ class SignalReportArtefact(UUIDModel):
The inbox list renders this count for every row it returns. A correlated subquery makes
Postgres count a report's artefacts before the page limit applies, so the whole team's
- reports get counted to render 25. Reports with no artefacts are omitted.
+ reports get counted to render 25. Reports with no artefacts are omitted, and so are
+ `SYSTEM_SCORING_ARTEFACT_TYPES` rows.
"""
if not report_ids:
return {}
rows = (
- cls.objects.filter(report_id__in=report_ids).values("report_id").annotate(artefact_count=models.Count("*"))
+ cls.objects.filter(report_id__in=report_ids)
+ .exclude(type__in=cls.SYSTEM_SCORING_ARTEFACT_TYPES)
+ .values("report_id")
+ .annotate(artefact_count=models.Count("*"))
)
return {str(row["report_id"]): row["artefact_count"] for row in rows}
diff --git a/products/signals/backend/ranking/inventory.py b/products/signals/backend/ranking/inventory.py
new file mode 100644
index 000000000000..8d59a1a3d20d
--- /dev/null
+++ b/products/signals/backend/ranking/inventory.py
@@ -0,0 +1,44 @@
+"""Which reports count as inbox inventory.
+
+The dataset dag's daily spine and the scoring sweep share this definition. The sweep must score
+the population the dag trains on, or the model trains on one inventory and serves another.
+"""
+
+import datetime
+
+from django.db.models import Q
+
+from products.signals.backend.models import SignalReport
+
+# Statuses a report can be authored straight into and still be in the inbox (`create_scout_report`
+# and `create_custom_agent_ready_report`), which is how a report reaches the spine without a
+# promotion. Suppressed and deleted are absent on purpose: authored-then-hidden is not inventory.
+BORN_VISIBLE_STATUSES = (
+ SignalReport.Status.READY,
+ SignalReport.Status.PENDING_INPUT,
+ SignalReport.Status.IN_PROGRESS,
+ SignalReport.Status.RESOLVED,
+)
+
+# Inventory a user can still act on, which the sweep scores. A resolved report stays in the spine
+# because its history matters for labels, but there is nothing left to rank.
+SCORABLE_STATUSES = (
+ SignalReport.Status.READY,
+ SignalReport.Status.PENDING_INPUT,
+ SignalReport.Status.IN_PROGRESS,
+)
+
+
+def spine_report_filter(snapshot_end: datetime.datetime) -> Q:
+ """Reports that were in the inbox before the cutoff.
+
+ Two ways in, because not every visible report was promoted: the pipeline promotes a `potential`
+ report and stamps promoted_at, but the scout and custom-agent authoring paths create a report
+ already in a visible status and never stamp it. Keying only on promotion dropped every
+ directly-authored report until a user happened to interact with it, biasing the inventory toward
+ reports that already had engagement — the wrong bias for a ranking model. A never-promoted report
+ is only eligible while it is still visible, so a promotion after the cutoff (promoted_at set, not
+ null) still cannot leak in through the second branch."""
+ return Q(promoted_at__isnull=False, promoted_at__lt=snapshot_end) | Q(
+ promoted_at__isnull=True, status__in=BORN_VISIBLE_STATUSES, created_at__lt=snapshot_end
+ )
diff --git a/products/signals/backend/ranking/schedule.py b/products/signals/backend/ranking/schedule.py
new file mode 100644
index 000000000000..fe4118a3b1bf
--- /dev/null
+++ b/products/signals/backend/ranking/schedule.py
@@ -0,0 +1,47 @@
+"""Schedule registration for the inbox ranking scoring sweep."""
+
+from dataclasses import asdict
+from datetime import timedelta
+
+from django.conf import settings
+
+from temporalio.client import (
+ Client,
+ Schedule,
+ ScheduleActionStartWorkflow,
+ ScheduleIntervalSpec,
+ ScheduleOverlapPolicy,
+ SchedulePolicy,
+ ScheduleSpec,
+)
+
+from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule
+
+from products.signals.backend.ranking.sweep import SCORING_WORKFLOW_NAME, ScoreInboxReportsInput
+
+INBOX_RANKING_SCORING_SCHEDULE_ID = "inbox-ranking-scoring-sweep-schedule"
+
+
+async def create_inbox_ranking_scoring_schedule(client: Client) -> None:
+ """Create or update the sweep schedule on the signals task queue.
+
+ The schedule exists in every environment. `INBOX_RANKING_SCORING_ENABLED` gates the work, so
+ turning the sweep on or off needs no schedule change. SKIP on overlap: a slow tick leaves the
+ rest to the next one, and two sweeps must not score the same batch at the same time.
+ """
+ interval = timedelta(minutes=settings.INBOX_RANKING_SCORING_INTERVAL_MINUTES)
+ schedule = Schedule(
+ action=ScheduleActionStartWorkflow(
+ SCORING_WORKFLOW_NAME,
+ asdict(ScoreInboxReportsInput()),
+ id=INBOX_RANKING_SCORING_SCHEDULE_ID,
+ task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,
+ execution_timeout=interval,
+ ),
+ spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=interval)]),
+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),
+ )
+ if await a_schedule_exists(client, INBOX_RANKING_SCORING_SCHEDULE_ID):
+ await a_update_schedule(client, INBOX_RANKING_SCORING_SCHEDULE_ID, schedule)
+ else:
+ await a_create_schedule(client, INBOX_RANKING_SCORING_SCHEDULE_ID, schedule, trigger_immediately=False)
diff --git a/products/signals/backend/ranking/scorer.py b/products/signals/backend/ranking/scorer.py
index ea96727b3ed3..409414429e3d 100644
--- a/products/signals/backend/ranking/scorer.py
+++ b/products/signals/backend/ranking/scorer.py
@@ -17,6 +17,7 @@ import pandas as pd
import structlog
from posthog.dataclasses import frozen
+from posthog.ph_client import ScopedCapture
from products.signals.backend.artefact_schemas import RankingModelResult, RankingScore
from products.signals.backend.ranking.features import (
@@ -27,7 +28,7 @@ from products.signals.backend.ranking.features import (
FeatureSet,
ReportEmbeddingsFeatureSet,
)
-from products.signals.backend.ranking.model_store import LoadedModel, load_serving_set
+from products.signals.backend.ranking.model_store import LoadedModel, ServingSet, load_serving_set
from products.signals.backend.ranking.serving_manifest import ServingManifestEntry
from products.signals.backend.ranking.sinks import persist_scores
from products.signals.backend.report_embedding_reader import ReportVector, latest_report_vectors
@@ -83,6 +84,20 @@ def _served_extra(feature_set: FeatureSet) -> str | None:
return extra if extra in RENDERING_BY_EXTRA else None
+def _served_model_extra(served: LoadedModel) -> str:
+ extra = _served_extra(served.feature_set)
+ if extra is None:
+ raise ScoringError(
+ f"served model {served.entry.key} is on feature set {served.feature_set.name}, not served yet"
+ )
+ return extra
+
+
+def served_rendering(serving: ServingSet) -> str:
+ """The rendering the served model reads, so the vector a served score depends on."""
+ return RENDERING_BY_EXTRA[_served_model_extra(serving.served)]
+
+
def _extras_frame(report_ids: Sequence[str], vectors: Mapping[str, ReportVector]) -> pd.DataFrame:
present = [report_id for report_id in report_ids if report_id in vectors]
return pd.DataFrame(
@@ -152,15 +167,25 @@ def _unloaded_result(entry: ServingManifestEntry, reason: str) -> RankingModelRe
def score_reports(
- team_id: int, report_ids: Sequence[str], *, persist: bool, now: datetime
+ team_id: int,
+ report_ids: Sequence[str],
+ *,
+ persist: bool,
+ now: datetime,
+ serving: ServingSet | None = None,
+ capture: ScopedCapture | None = None,
) -> list[ReportScoringOutcome]:
"""One outcome per distinct report id, in the order given.
A report with no current vector for the served model gets no score and `reason="no_vector"`,
so the caller can try it again later. A challenger with no vector is a skipped result inside
the score. `persist=False` returns the scores and writes nothing.
+
+ A caller that scores many teams passes the `serving` set it loaded and one `capture`, so each
+ team does not read the manifest from object storage again or flush its own events.
"""
- serving = load_serving_set()
+ if serving is None:
+ serving = load_serving_set()
if serving is None:
logger.info("inbox_ranking_scoring_skipped", team_id=team_id, reason="no serving manifest is published")
return []
@@ -168,11 +193,7 @@ def score_reports(
if not ids:
return []
served = serving.served
- served_extra = _served_extra(served.feature_set)
- if served_extra is None:
- raise ScoringError(
- f"served model {served.entry.key} is on feature set {served.feature_set.name}, not served yet"
- )
+ served_extra = _served_model_extra(served)
models = [served, *serving.others]
needed_extras = {extra for model in models if (extra := _served_extra(model.feature_set)) is not None}
@@ -204,5 +225,7 @@ def score_reports(
outcomes.append(ReportScoringOutcome(report_id=report_id, score=score, reason=None))
if persist:
- persist_scores(team_id, [(outcome.report_id, outcome.score) for outcome in outcomes if outcome.score])
+ persist_scores(
+ team_id, [(outcome.report_id, outcome.score) for outcome in outcomes if outcome.score], capture=capture
+ )
return outcomes
diff --git a/products/signals/backend/ranking/sinks.py b/products/signals/backend/ranking/sinks.py
index 9a060e2fcea3..9538c4904591 100644
--- a/products/signals/backend/ranking/sinks.py
+++ b/products/signals/backend/ranking/sinks.py
@@ -6,10 +6,11 @@ every other ranking event.
"""
from collections.abc import Sequence
+from contextlib import nullcontext
from django.conf import settings
-from posthog.ph_client import ph_scoped_capture
+from posthog.ph_client import ScopedCapture, ph_scoped_capture
from products.signals.backend.artefact_schemas import RankingScore
from products.signals.backend.models import SignalActorKind, SignalReport, SignalReportArtefact
@@ -18,10 +19,14 @@ REPORT_SCORED_EVENT = "inbox_ranking_report_scored"
DISTINCT_ID = "inbox_ranking_scoring"
-def persist_scores(team_id: int, scores: Sequence[tuple[str, RankingScore]]) -> int:
+def persist_scores(
+ team_id: int, scores: Sequence[tuple[str, RankingScore]], *, capture: ScopedCapture | None = None
+) -> int:
"""Write one artefact per `(report_id, score)` of the team, then capture its events.
- A report id that is not one of the team's reports is dropped. Returns the rows written.
+ A report id that is not one of the team's reports is dropped. Returns the rows written. Without
+ `capture`, the call opens its own scope, which blocks on a flush when it closes. A caller that
+ persists many teams passes one `capture` for all of them, so it pays that flush once.
"""
report_ids = [report_id for report_id, _ in scores]
owned = {
@@ -41,10 +46,10 @@ def persist_scores(team_id: int, scores: Sequence[tuple[str, RankingScore]]) ->
for report_id, score in kept
]
)
- with ph_scoped_capture() as capture:
+ 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():
- capture(
+ active_capture(
distinct_id=DISTINCT_ID,
event=REPORT_SCORED_EVENT,
properties={
diff --git a/products/signals/backend/ranking/sweep.py b/products/signals/backend/ranking/sweep.py
new file mode 100644
index 000000000000..b3b0322517e8
--- /dev/null
+++ b/products/signals/backend/ranking/sweep.py
@@ -0,0 +1,300 @@
+"""The scoring sweep: a scheduled Temporal workflow that scores the inbox reports that are due.
+
+A report is due when its score is missing or out of date. The served model reads only the report's
+vector, so the vector log is the change signal, not `SignalReport.updated_at`: a scout edit saves
+`update_fields=["title", "summary"]` and leaves `updated_at` alone, and the grouping pipeline
+moves `updated_at` with no text change. A new vector lands only when a rendering's text changes.
+
+Nothing reads the `ranking_score` artefacts to order the inbox yet.
+"""
+
+import time
+import uuid
+import datetime
+from collections import defaultdict
+from collections.abc import Iterator, Sequence
+from typing import Any, cast
+
+from django.conf import settings
+from django.utils import timezone
+
+import pydantic
+import structlog
+from temporalio import activity, workflow
+from temporalio.common import RetryPolicy
+
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.client.connection import Workload
+from posthog.clickhouse.query_tagging import Feature, Product, tag_queries
+from posthog.dataclasses import frozen
+from posthog.ph_client import ph_scoped_capture
+from posthog.sync import database_sync_to_async
+from posthog.temporal.common.scoped import scoped_temporal
+from posthog.temporal.common.utils import close_db_connections
+
+from products.signals.backend.artefact_schemas import RankingScore
+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.report_embedding_reader import REPORT_EMBEDDINGS_TABLE
+from products.signals.backend.report_embeddings import EMBEDDING_DOCUMENT_TYPE, EMBEDDING_PRODUCT
+
+logger = structlog.get_logger(__name__)
+
+SCORING_WORKFLOW_NAME = "inbox-ranking-scoring-sweep"
+
+# Report ids per Postgres lookup, so a large vector feed does not become one huge `IN` list.
+_POSTGRES_BATCH_SIZE = 5000
+
+_ACTIVITY_TIMEOUT = datetime.timedelta(minutes=10)
+# The activity timeout does not stop the scoring thread, and the schedule's SKIP stops guarding it
+# when the workflow closes. The pass starts no new team after this budget, which is below the
+# timeout, so only the team in progress can run past it and into the next tick.
+_TIME_BUDGET = datetime.timedelta(minutes=8)
+
+# `timestamp` is the report's `created_at` and the partition key, so the lower bound prunes the
+# read to a few weekly partitions. The query does not read the `embedding` column.
+CANDIDATE_VECTORS_SQL = f"""
+SELECT
+ team_id,
+ document_id,
+ max(inserted_at) AS vector_inserted_at
+FROM {REPORT_EMBEDDINGS_TABLE}
+WHERE product = %(product)s
+ AND document_type = %(document_type)s
+ AND rendering = %(rendering)s
+ AND timestamp >= %(since)s
+GROUP BY team_id, document_id
+HAVING argMax(JSONExtractBool(metadata, 'deleted'), inserted_at) = 0
+"""
+
+# The scan is cross-team, so it cannot use the `team_id` sort-key prefix, and its cost grows with the
+# whole window. The time cap sits well inside `_TIME_BUDGET`, so a slow scan fails the tick with an
+# error instead of running into the activity timeout. It throws because a partial GROUP BY would
+# give a wrong newest-vector time.
+CANDIDATE_VECTORS_QUERY_SETTINGS: dict[str, int | str] = {
+ "max_execution_time": 180,
+ "timeout_overflow_mode": "throw",
+}
+
+
+@frozen
+class ScoringCandidate:
+ team_id: int
+ report_id: str
+ vector_inserted_at: datetime.datetime
+
+
+@frozen
+class ScoreInboxReportsInput:
+ # A manual run can override the per-tick cap.
+ limit: int | None = None
+
+
+@frozen
+class ScoreInboxReportsResult:
+ candidates: int = 0
+ scored: int = 0
+ no_vector: int = 0
+ teams: int = 0
+ failed_teams: int = 0
+ # Teams not started because the time budget ran out. The next tick scores them.
+ deferred_teams: int = 0
+ manifest_version: str | None = None
+ # "disabled" or "no manifest". None when the pass ran.
+ skipped_reason: str | None = None
+
+
+def _batches(items: Sequence[str]) -> Iterator[Sequence[str]]:
+ for start in range(0, len(items), _POSTGRES_BATCH_SIZE):
+ yield items[start : start + _POSTGRES_BATCH_SIZE]
+
+
+def _utc(value: datetime.datetime) -> datetime.datetime:
+ # ClickHouse returns a naive DateTime in UTC.
+ return value.replace(tzinfo=datetime.UTC) if value.tzinfo is None else value.astimezone(datetime.UTC)
+
+
+def _live_vectors(since: datetime.datetime, rendering: str) -> dict[str, tuple[int, datetime.datetime]]:
+ """Report id to `(team_id, newest vector time)`, for each report whose newest row is live."""
+ tag_queries(product=Product.SIGNALS, feature=Feature.ENRICHMENT, query_type="inbox_ranking_sweep_candidates")
+ rows = cast(
+ list[tuple[Any, ...]],
+ sync_execute(
+ CANDIDATE_VECTORS_SQL,
+ {
+ "product": EMBEDDING_PRODUCT,
+ "document_type": EMBEDDING_DOCUMENT_TYPE,
+ "rendering": rendering,
+ "since": since.astimezone(datetime.UTC).replace(tzinfo=None),
+ },
+ settings=CANDIDATE_VECTORS_QUERY_SETTINGS,
+ workload=Workload.OFFLINE,
+ )
+ or [],
+ )
+ vectors: dict[str, tuple[int, datetime.datetime]] = {}
+ for team_id, document_id, inserted_at in rows:
+ try:
+ report_id = str(uuid.UUID(str(document_id)))
+ except ValueError:
+ # A document id that is not a report UUID would fail the Postgres lookup.
+ continue
+ vectors[report_id] = (int(team_id), _utc(inserted_at))
+ return vectors
+
+
+def _scorable_report_teams(
+ report_ids: Sequence[str], now: datetime.datetime, since: datetime.datetime
+) -> dict[str, int]:
+ teams: dict[str, int] = {}
+ for batch in _batches(report_ids):
+ rows = (
+ # nosemgrep: idor-lookup-without-team (system sweep with no user input; report teams are checked against vector teams before scoring)
+ SignalReport.objects.filter(spine_report_filter(now))
+ .filter(id__in=batch, status__in=SCORABLE_STATUSES, created_at__gte=since)
+ .values_list("id", "team_id")
+ )
+ teams.update({str(report_id): team_id for report_id, team_id in rows})
+ return teams
+
+
+def _latest_scores(report_ids: Sequence[str]) -> dict[str, RankingScore | None]:
+ """The latest `ranking_score` of each report that has one. A row that no longer parses is None."""
+ scores: dict[str, RankingScore | None] = {}
+ for batch in _batches(report_ids):
+ rows = (
+ SignalReportArtefact.objects.filter(
+ report_id__in=batch, type=SignalReportArtefact.ArtefactType.RANKING_SCORE
+ )
+ .order_by("report_id", "-created_at")
+ .distinct("report_id")
+ .values_list("report_id", "content")
+ )
+ for report_id, content in rows:
+ try:
+ scores[str(report_id)] = RankingScore.model_validate_json(content)
+ except pydantic.ValidationError:
+ scores[str(report_id)] = None
+ return scores
+
+
+def _is_due(score: RankingScore | None, vector_inserted_at: datetime.datetime, manifest_version: str) -> bool:
+ 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
+ )
+
+
+def reports_due_for_scoring(
+ now: datetime.datetime, *, manifest_version: str, rendering: str, limit: int
+) -> list[ScoringCandidate]:
+ """In-window scorable reports whose score is missing, older than their vector, or from another manifest.
+
+ 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
+ not retried every tick. It comes back when a new vector lands.
+ """
+ since = now - datetime.timedelta(days=settings.INBOX_RANKING_SCORING_MAX_AGE_DAYS)
+ vectors = _live_vectors(since, rendering)
+ report_teams = _scorable_report_teams(list(vectors), now, since)
+ kept = [report_id for report_id, team_id in report_teams.items() if vectors[report_id][0] == team_id]
+ latest = _latest_scores(kept)
+
+ due: list[tuple[datetime.datetime | None, ScoringCandidate]] = []
+ 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):
+ 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))
+ due.sort(key=lambda item: (item[0] is not None, item[0] or now, item[1].report_id))
+ return [candidate for _, candidate in due[:limit]]
+
+
+def score_inbox_reports(limit: int | None = None) -> ScoreInboxReportsResult:
+ if not settings.INBOX_RANKING_SCORING_ENABLED:
+ 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()
+ if serving is None:
+ return ScoreInboxReportsResult(skipped_reason="no manifest")
+ manifest_version = serving.manifest.manifest_version
+ now = timezone.now()
+ candidates = reports_due_for_scoring(
+ now,
+ manifest_version=manifest_version,
+ rendering=scorer.served_rendering(serving),
+ limit=limit or settings.INBOX_RANKING_SCORING_MAX_REPORTS_PER_TICK,
+ )
+ ids_by_team: dict[int, list[str]] = defaultdict(list)
+ for candidate in candidates:
+ ids_by_team[candidate.team_id].append(candidate.report_id)
+
+ scored = no_vector = failed_teams = deferred_teams = 0
+ with ph_scoped_capture() as capture:
+ for team_id, report_ids in ids_by_team.items():
+ if time.monotonic() >= deadline:
+ deferred_teams += 1
+ continue
+ try:
+ outcomes = scorer.score_reports(
+ team_id, report_ids, persist=True, now=now, serving=serving, capture=capture
+ )
+ except (scorer.ScoringError, ModelLoadError):
+ # A pass without a served score is worse than no pass.
+ raise
+ except Exception:
+ logger.exception("inbox_ranking_sweep_team_failed", team_id=team_id)
+ failed_teams += 1
+ continue
+ scored += sum(1 for outcome in outcomes if outcome.score is not None)
+ no_vector += sum(1 for outcome in outcomes if outcome.reason == scorer.NO_VECTOR)
+
+ result = ScoreInboxReportsResult(
+ candidates=len(candidates),
+ scored=scored,
+ no_vector=no_vector,
+ teams=len(ids_by_team),
+ failed_teams=failed_teams,
+ deferred_teams=deferred_teams,
+ manifest_version=manifest_version,
+ )
+ logger.info(
+ "inbox_ranking_sweep_finished",
+ candidates=result.candidates,
+ scored=result.scored,
+ no_vector=result.no_vector,
+ teams=result.teams,
+ failed_teams=result.failed_teams,
+ deferred_teams=result.deferred_teams,
+ manifest_version=result.manifest_version,
+ )
+ return result
+
+
+@scoped_temporal()
+@close_db_connections
+async def score_inbox_reports_activity(input: ScoreInboxReportsInput) -> ScoreInboxReportsResult:
+ return await database_sync_to_async(score_inbox_reports, thread_sensitive=False)(input.limit)
+
+
[email protected](name=SCORING_WORKFLOW_NAME)
+class InboxRankingScoringWorkflow:
+ @workflow.run
+ async def run(self, inputs: ScoreInboxReportsInput) -> ScoreInboxReportsResult:
+ return await workflow.execute_activity(
+ score_inbox_reports_activity,
+ inputs,
+ start_to_close_timeout=_ACTIVITY_TIMEOUT,
+ # No retry: a timed-out attempt keeps running in its thread, so a second attempt could
+ # score the same batch at the same time. The next tick finds what this one left,
+ # because the vector comparison finds it again.
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
diff --git a/products/signals/backend/temporal/__init__.py b/products/signals/backend/temporal/__init__.py
index d851f08e75c5..fdc685dd7946 100644
--- a/products/signals/backend/temporal/__init__.py
+++ b/products/signals/backend/temporal/__init__.py
@@ -1,3 +1,4 @@
+from products.signals.backend.ranking.sweep import InboxRankingScoringWorkflow, score_inbox_reports_activity
from products.signals.backend.temporal.agentic.report import run_agentic_report_activity
from products.signals.backend.temporal.agentic.scout_coordinator import (
SignalsScoutCoordinatorWorkflow,
@@ -89,6 +90,7 @@ from products.signals.backend.temporal.summary import (
)
WORKFLOWS = [
+ InboxRankingScoringWorkflow,
BackfillErrorTrackingWorkflow,
TeamSignalGroupingWorkflow,
TeamSignalGroupingV2Workflow,
@@ -108,6 +110,7 @@ WORKFLOWS = [
]
ACTIVITIES = [
+ score_inbox_reports_activity,
dispatch_inbox_slack_notifications_activity,
get_inbox_notification_state_activity,
send_report_github_comments_activity,
diff --git a/products/signals/backend/test/test_ranking_scoring.py b/products/signals/backend/test/test_ranking_scoring.py
index 6a94f2887521..258df5368527 100644
--- a/products/signals/backend/test/test_ranking_scoring.py
+++ b/products/signals/backend/test/test_ranking_scoring.py
@@ -2,7 +2,7 @@ import json
import datetime
from collections.abc import Iterator, Mapping, Sequence
from contextlib import contextmanager
-from typing import Any
+from typing import Any, cast
from posthog.test.base import BaseTest, ClickhouseTestMixin
from unittest.mock import patch
@@ -215,23 +215,37 @@ class _FakeVectors:
class _Captured:
def __init__(self) -> None:
self.events: list[dict[str, Any]] = []
+ self.scopes = 0
+
+ def record(self, **kwargs: Any) -> None:
+ self.events.append(kwargs)
@contextmanager
def __call__(self) -> Iterator[Any]:
- yield lambda **kwargs: self.events.append(kwargs)
+ self.scopes += 1
+ yield self.record
class _ScorerTestMixin(_StoreTestMixin):
def _score(
- self, report_ids: Sequence[str], vectors: Mapping[str, Mapping[str, ReportVector]], *, persist: bool
+ self,
+ report_ids: Sequence[str],
+ vectors: Mapping[str, Mapping[str, ReportVector]],
+ *,
+ persist: bool,
+ shared_pass: bool = False,
) -> tuple[list[scorer.ReportScoringOutcome], _FakeVectors, _Captured]:
fake_vectors = _FakeVectors(vectors)
captured = _Captured()
+ serving = load_serving_set() if shared_pass else None
+ capture = cast(Any, captured.record) if shared_pass else None
with (
patch.object(scorer, "latest_report_vectors", fake_vectors),
patch("products.signals.backend.ranking.sinks.ph_scoped_capture", captured),
):
- outcomes = score_reports(self.team_id, report_ids, persist=persist, now=NOW)
+ outcomes = score_reports(
+ self.team_id, report_ids, persist=persist, now=NOW, serving=serving, capture=capture
+ )
return outcomes, fake_vectors, captured
team_id = 1
@@ -331,7 +345,8 @@ class TestScorerPersists(_ScorerTestMixin, BaseTest):
def _report(self, team_id: int) -> str:
return str(SignalReport.objects.create(team_id=team_id, status=SignalReport.Status.READY, title="A").id)
- def test_persist_writes_one_valid_row_per_scored_report_of_the_team(self) -> None:
+ @parameterized.expand([("own_scope", False), ("shared_pass", True)])
+ def test_persist_writes_one_valid_row_per_scored_report_of_the_team(self, _name: str, shared_pass: bool) -> None:
self.team_id = self.team.id
served = self._served()
title = self._challenger("title_embeddings", TITLE_EMBEDDINGS_FEATURE_SET)
@@ -348,6 +363,7 @@ class TestScorerPersists(_ScorerTestMixin, BaseTest):
EMBEDDING_RENDERING_TITLE: {scored: vector},
},
persist=True,
+ shared_pass=shared_pass,
)
assert {outcome.report_id: outcome.reason for outcome in outcomes} == {
@@ -364,6 +380,8 @@ class TestScorerPersists(_ScorerTestMixin, BaseTest):
(event["event"], event["properties"]["report_id"], event["properties"]["model_key"])
for event in captured.events
) == sorted([(REPORT_SCORED_EVENT, scored, served.key), (REPORT_SCORED_EVENT, scored, title.key)])
+ assert self.store.reads.count(serving_manifest_key(PREFIX)) == 1
+ assert captured.scopes == (0 if shared_pass else 1)
def test_without_persist_nothing_is_written_or_captured(self) -> None:
self.team_id = self.team.id
diff --git a/products/signals/backend/test/test_ranking_sweep.py b/products/signals/backend/test/test_ranking_sweep.py
new file mode 100644
index 000000000000..5c282175dd32
--- /dev/null
+++ b/products/signals/backend/test/test_ranking_sweep.py
@@ -0,0 +1,291 @@
+import json
+import datetime
+from collections.abc import Iterator
+from contextlib import contextmanager
+from types import SimpleNamespace
+from typing import Any
+
+from posthog.test.base import BaseTest, ClickhouseTestMixin
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase, override_settings
+
+from parameterized import parameterized
+
+from posthog.clickhouse.client import sync_execute
+from posthog.models import Team
+
+from products.signals.backend.artefact_schemas import RankingModelResult, RankingScore
+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.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
+from products.signals.backend.report_embeddings import EMBEDDING_RENDERING_TITLE_SUMMARY
+
+MANIFEST = "manifest-b"
+OLD_MANIFEST = "manifest-a"
+
+
+def _score(*, embedding_inserted_at: datetime.datetime, manifest_version: str, scored_at: datetime.datetime) -> str:
+ served = RankingModelResult(
+ model_name="report_embeddings",
+ model_version="2026-09-01",
+ model_kind="xgboost",
+ roles=["served"],
+ feature_schema_version=1,
+ status="scored",
+ scores={"open": 0.5},
+ )
+ return RankingScore(
+ scored_at=scored_at,
+ embedding_inserted_at=embedding_inserted_at,
+ manifest_version=manifest_version,
+ served_key=served.key,
+ results={served.key: served},
+ ).model_dump_json()
+
+
+class TestReportsDueForScoring(ClickhouseTestMixin, BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ sync_execute(f"TRUNCATE TABLE {REPORT_EMBEDDINGS_TABLE}", flush=False, team_id=self.team.pk)
+ # Whole seconds: the vector table keeps inserted_at at millisecond precision.
+ self.now = datetime.datetime.now(datetime.UTC).replace(microsecond=0)
+
+ def _report(self, *, status: str = SignalReport.Status.READY, age_days: int = 2, team: Team | None = None) -> str:
+ report = SignalReport.objects.create(team=team or self.team, status=status, title="t", summary="s")
+ SignalReport.objects.filter(id=report.id).update(created_at=self.now - datetime.timedelta(days=age_days))
+ return str(report.id)
+
+ def _vector(
+ self, report_id: str, *, hours_ago: int, deleted: bool = False, team_id: int | None = None
+ ) -> datetime.datetime:
+ report = SignalReport.objects.get(id=report_id)
+ inserted_at = self.now - datetime.timedelta(hours=hours_ago)
+ sync_execute(
+ f"""
+ INSERT INTO {REPORT_EMBEDDINGS_TABLE} (
+ team_id, product, document_type, rendering, document_id,
+ timestamp, inserted_at, content, metadata, embedding,
+ _timestamp, _offset, _partition
+ ) VALUES
+ """,
+ [
+ (
+ team_id or report.team_id,
+ "signals",
+ "report",
+ EMBEDDING_RENDERING_TITLE_SUMMARY,
+ report_id,
+ report.created_at.replace(tzinfo=None),
+ inserted_at.replace(tzinfo=None),
+ "a report",
+ json.dumps({"deleted": deleted}),
+ [0.0] * EMBEDDING_DIMENSIONS,
+ inserted_at.replace(tzinfo=None),
+ 0,
+ 0,
+ )
+ ],
+ flush=False,
+ team_id=self.team.pk,
+ )
+ return inserted_at
+
+ def _scored(
+ self, report_id: str, *, vector_at: datetime.datetime, manifest: str = MANIFEST, hours_ago: int = 1
+ ) -> None:
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report_id=report_id,
+ type=SignalReportArtefact.ArtefactType.RANKING_SCORE,
+ content=_score(
+ embedding_inserted_at=vector_at,
+ manifest_version=manifest,
+ scored_at=self.now - datetime.timedelta(hours=hours_ago),
+ ),
+ )
+
+ 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
+ )
+ return [candidate.report_id for candidate in candidates]
+
+ def test_due_reports_are_the_in_window_scorable_ones_whose_score_is_missing_or_stale(self) -> None:
+ unscored = self._report()
+ self._vector(unscored, hours_ago=5)
+
+ current = self._report()
+ self._scored(current, vector_at=self._vector(current, hours_ago=5))
+
+ edited = self._report()
+ self._scored(edited, vector_at=self._vector(edited, hours_ago=5))
+ edited_report = SignalReport.objects.get(id=edited)
+ updated_at = edited_report.updated_at
+ edited_report.title, edited_report.summary = "new title", "new summary"
+ edited_report.save(update_fields=["title", "summary"])
+ self._vector(edited, hours_ago=2)
+ assert SignalReport.objects.get(id=edited).updated_at == updated_at
+
+ other_manifest = self._report()
+ self._scored(other_manifest, vector_at=self._vector(other_manifest, hours_ago=5), manifest=OLD_MANIFEST)
+
+ retracted = self._report()
+ self._vector(retracted, hours_ago=5)
+ self._vector(retracted, hours_ago=2, deleted=True)
+ resolved = self._report(status=SignalReport.Status.RESOLVED)
+ self._vector(resolved, hours_ago=5)
+ suppressed = self._report(status=SignalReport.Status.SUPPRESSED)
+ self._vector(suppressed, hours_ago=5)
+ too_old = self._report(age_days=40)
+ self._vector(too_old, hours_ago=5)
+ self._report()
+ other_team = Team.objects.create(organization=self.organization)
+ 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])
+
+ 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()
+ self._scored(recently_scored, vector_at=self._vector(recently_scored, hours_ago=5), manifest=OLD_MANIFEST)
+ self._scored(
+ long_ago_scored, vector_at=self._vector(long_ago_scored, hours_ago=5), manifest=OLD_MANIFEST, hours_ago=3
+ )
+ self._vector(unscored, hours_ago=5)
+
+ assert self._due(limit=2) == [unscored, long_ago_scored]
+
+
+class TestScoreInboxReports(SimpleTestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.serving = SimpleNamespace(manifest=SimpleNamespace(manifest_version=MANIFEST))
+ 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.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()
+ self.capture_scopes = 0
+ self._patch(sweep, "ph_scoped_capture", new=self._capture_scope)
+ self.failing_teams: dict[int, Exception] = {}
+ settings_override = override_settings(INBOX_RANKING_SCORING_ENABLED=True)
+ settings_override.enable()
+ self.addCleanup(settings_override.disable)
+
+ def _patch(self, target: Any, name: str, **kwargs: Any) -> MagicMock:
+ patcher = patch.object(target, name, **kwargs)
+ mock = patcher.start()
+ self.addCleanup(patcher.stop)
+ return mock
+
+ @contextmanager
+ def _capture_scope(self) -> Iterator[MagicMock]:
+ self.capture_scopes += 1
+ yield self.capture
+
+ def _outcomes(
+ self,
+ team_id: int,
+ report_ids: list[str],
+ *,
+ persist: bool,
+ now: datetime.datetime,
+ serving: Any = None,
+ capture: Any = None,
+ ) -> list:
+ if team_id in self.failing_teams:
+ raise self.failing_teams[team_id]
+ return [
+ ReportScoringOutcome(report_id=report_id, score=None, reason=NO_VECTOR)
+ if report_id.startswith("novec")
+ else ReportScoringOutcome(report_id=report_id, score=MagicMock(), reason=None)
+ for report_id in report_ids
+ ]
+
+ def _candidates(self, *pairs: tuple[int, str]) -> None:
+ at = datetime.datetime(2026, 9, 1, tzinfo=datetime.UTC)
+ self.due.return_value = [
+ ScoringCandidate(team_id=team_id, report_id=report_id, vector_inserted_at=at)
+ for team_id, report_id in pairs
+ ]
+
+ def test_disabled_reads_and_writes_nothing(self) -> None:
+ with override_settings(INBOX_RANKING_SCORING_ENABLED=False):
+ result = score_inbox_reports()
+
+ assert result.skipped_reason == "disabled"
+ self.load_serving_set.assert_not_called()
+ self.due.assert_not_called()
+ self.score_reports.assert_not_called()
+
+ def test_no_manifest_scores_nothing(self) -> None:
+ self.load_serving_set.return_value = None
+
+ result = score_inbox_reports()
+
+ assert result.skipped_reason == "no manifest"
+ self.due.assert_not_called()
+ self.score_reports.assert_not_called()
+
+ def test_one_persisted_call_per_team_with_that_teams_ids_only(self) -> None:
+ self._candidates((1, "a"), (2, "b"), (1, "novec-c"))
+
+ result = score_inbox_reports()
+
+ assert sorted(
+ (call.args[0], call.args[1], call.kwargs["persist"]) for call in self.score_reports.call_args_list
+ ) == [(1, ["a", "novec-c"], True), (2, ["b"], True)]
+ assert all(
+ call.kwargs["serving"] is self.serving and call.kwargs["capture"] is self.capture
+ for call in self.score_reports.call_args_list
+ )
+ assert (self.load_serving_set.call_count, self.capture_scopes) == (1, 1)
+ assert (result.candidates, result.scored, result.no_vector, result.teams, result.failed_teams) == (
+ 3,
+ 2,
+ 1,
+ 2,
+ 0,
+ )
+ assert (result.manifest_version, result.skipped_reason) == (MANIFEST, None)
+
+ def test_one_teams_error_is_counted_and_the_next_team_is_scored(self) -> None:
+ self._candidates((1, "a"), (2, "b"))
+ self.failing_teams[1] = RuntimeError("boom")
+
+ result = score_inbox_reports()
+
+ assert (result.scored, result.teams, result.failed_teams) == (1, 2, 1)
+
+ def test_teams_left_when_the_time_budget_runs_out_are_deferred_to_the_next_tick(self) -> None:
+ self._candidates((1, "a"), (2, "b"), (3, "c"))
+ clock = [0.0]
+ self._patch(sweep, "time", new=SimpleNamespace(monotonic=lambda: clock[0]))
+
+ def slow_first_team(team_id: int, report_ids: list[str], **kwargs: Any) -> list:
+ clock[0] += sweep._TIME_BUDGET.total_seconds()
+ return self._outcomes(team_id, report_ids, **kwargs)
+
+ self.score_reports.side_effect = slow_first_team
+
+ result = score_inbox_reports()
+
+ assert [call.args[0] for call in self.score_reports.call_args_list] == [1]
+ assert (result.scored, result.teams, result.failed_teams, result.deferred_teams) == (1, 3, 0, 2)
+
+ @parameterized.expand(
+ [("scoring_error", ScoringError("no served score")), ("served_model_load", ModelLoadError("no booster"))]
+ )
+ def test_a_scoring_error_aborts_the_run(self, _name: str, error: Exception) -> None:
+ self._candidates((1, "a"), (2, "b"))
+ self.failing_teams[1] = error
+
+ with self.assertRaises(type(error)):
+ score_inbox_reports()
+
+ assert self.score_reports.call_count == 1
diff --git a/products/signals/backend/test/test_signal_report_api.py b/products/signals/backend/test/test_signal_report_api.py
index 32387f82f1d1..f0b845fa31a4 100644
--- a/products/signals/backend/test/test_signal_report_api.py
+++ b/products/signals/backend/test/test_signal_report_api.py
@@ -47,6 +47,8 @@ from products.signals.backend.artefact_schemas import (
NoteArtefact,
PriorityAssessment,
PullRequestLink,
+ RankingModelResult,
+ RankingScore,
ReportLink,
)
from products.signals.backend.enums import ReportLinkKind, ReportPriority
@@ -711,6 +713,26 @@ class TestSignalReportListAPI(APIBaseTest):
report = self._create_report()
self._priority_artefact(report, priority="P1")
self._actionability_artefact(report, actionability="immediately_actionable")
+ served = RankingModelResult(
+ model_name="report_embeddings",
+ model_version="2026-09-01",
+ model_kind="xgboost",
+ roles=["served"],
+ feature_schema_version=1,
+ status="scored",
+ scores={"open": 0.5},
+ )
+ SignalReportArtefact.objects.create(
+ team=self.team,
+ report=report,
+ type=SignalReportArtefact.ArtefactType.RANKING_SCORE,
+ content=RankingScore(
+ scored_at=timezone.now(),
+ manifest_version="manifest",
+ served_key=served.key,
+ results={served.key: served},
+ ).model_dump_json(),
+ )
list_response = self.client.get(self._list_url())
assert list_response.status_code == status.HTTP_200_OK
diff --git a/products/signals/backend/views.py b/products/signals/backend/views.py
index 78314dce819f..e8194dad98b7 100644
--- a/products/signals/backend/views.py
+++ b/products/signals/backend/views.py
@@ -1160,6 +1160,7 @@ class SignalReportViewSet(
# so the main query doesn't LEFT JOIN + GROUP BY the full artefact table
artefact_count_subquery = Subquery(
SignalReportArtefact.objects.filter(report_id=OuterRef("id"))
+ .exclude(type__in=SignalReportArtefact.SYSTEM_SCORING_ARTEFACT_TYPES)
.values("report_id")
.annotate(count=Count("*"))
.values("count"),
@@ -4673,7 +4674,9 @@ class SignalReportArtefactViewSet(
).exclude(report__status=SignalReport.Status.DELETED)
def list(self, request, *args, **kwargs):
- queryset = self.filter_queryset(self.get_queryset())
+ queryset = self.filter_queryset(self.get_queryset()).exclude(
+ type__in=SignalReportArtefact.SYSTEM_SCORING_ARTEFACT_TYPES
+ )
# Surface legacy `SignalReportTask` associations as synthetic `task_run` artefacts so a
# report's research / implementation runs appear in the log even before the backfill has
# converted its gate rows. Merged into the materialized log (de-duplicated against the real
diff --git a/products/signals/dags/inbox_ranking/dataset/dag.py b/products/signals/dags/inbox_ranking/dataset/dag.py
index 90c1afbe24bb..9ee4d1081638 100644
--- a/products/signals/dags/inbox_ranking/dataset/dag.py
+++ b/products/signals/dags/inbox_ranking/dataset/dag.py
@@ -47,8 +47,6 @@ import datetime
from collections.abc import Iterator
from typing import Any, cast
-from django.db.models import Q
-
import dagster
import pyarrow as pa
@@ -58,6 +56,7 @@ from posthog.clickhouse.query_tagging import Feature, Product, get_query_tags, t
from posthog.dags.common import dagster_tags
from products.signals.backend.models import SignalReport, SignalReportArtefact
+from products.signals.backend.ranking.inventory import spine_report_filter
from products.signals.backend.report_embeddings import (
EMBEDDING_DOCUMENT_TYPE,
EMBEDDING_PRODUCT,
@@ -109,16 +108,6 @@ from products.signals.dags.inbox_ranking.dataset.queries import (
FEATURE_SCHEMA_VERSION = 6
-# Statuses a report can be authored straight into and still be in the inbox (`create_scout_report`
-# and `create_custom_agent_ready_report`), which is how a report reaches the spine without a
-# promotion. Suppressed and deleted are absent on purpose: authored-then-hidden is not inventory.
-BORN_VISIBLE_STATUSES = (
- SignalReport.Status.READY,
- SignalReport.Status.PENDING_INPUT,
- SignalReport.Status.IN_PROGRESS,
- SignalReport.Status.RESOLVED,
-)
-
STATE_TABLE = "inbox_report_state"
EMBEDDINGS_TABLE = "inbox_report_embeddings"
TITLE_EMBEDDINGS_TABLE = "inbox_report_title_embeddings"
@@ -394,21 +383,6 @@ def _artefact_judgments(report_ids: list[str], snapshot_end: datetime.datetime)
return judgments
-def spine_report_filter(snapshot_end: datetime.datetime) -> Q:
- """Reports that were in the inbox before the cutoff.
-
- Two ways in, because not every visible report was promoted: the pipeline promotes a `potential`
- report and stamps promoted_at, but the scout and custom-agent authoring paths create a report
- already in a visible status and never stamp it. Keying only on promotion dropped every
- directly-authored report until a user happened to interact with it, biasing the inventory toward
- reports that already had engagement — the wrong bias for a ranking model. A never-promoted report
- is only eligible while it is still visible, so a promotion after the cutoff (promoted_at set, not
- null) still cannot leak in through the second branch."""
- return Q(promoted_at__isnull=False, promoted_at__lt=snapshot_end) | Q(
- promoted_at__isnull=True, status__in=BORN_VISIBLE_STATUSES, created_at__lt=snapshot_end
- )
-
-
@dagster.asset(name=STATE_TABLE, **COMMON_ASSET_KWARGS)
def inbox_report_state(context: dagster.AssetExecutionContext) -> None:
if skip_unconfigured(context):
diff --git a/products/signals/dags/inbox_ranking/tests/test_dataset.py b/products/signals/dags/inbox_ranking/tests/test_dataset.py
index 85149f99de56..ac2e53d49c47 100644
--- a/products/signals/dags/inbox_ranking/tests/test_dataset.py
+++ b/products/signals/dags/inbox_ranking/tests/test_dataset.py
@@ -10,6 +10,7 @@ from parameterized import parameterized
from products.event_definitions.backend.models.property_definition import PropertyDefinition
from products.signals.backend.models import SignalReport
+from products.signals.backend.ranking.inventory import spine_report_filter
from products.signals.backend.report_embeddings import EMBEDDING_RENDERING_TITLE, EMBEDDING_RENDERING_TITLE_SUMMARY
from products.signals.dags.inbox_ranking import common
from products.signals.dags.inbox_ranking.dataset import dag, queries
@@ -19,7 +20,6 @@ from products.signals.dags.inbox_ranking.dataset.dag import (
MODEL_DATA_SCHEMA,
assemble_model_rows,
label_provenance_ok,
- spine_report_filter,
)
from products.signals.dags.inbox_ranking.dataset.queries import (
IMPRESSIONS_SQL,