:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(devex): let products declare their own today highlight sources (#118760)
Julian Bezead8ec65bcd8
diff --git a/posthog/products.py b/posthog/products.pyindex 2810acef8442..1726692f6521 100644--- a/posthog/products.py+++ b/posthog/products.py@@ -3,6 +3,7 @@ import importlibimport importlib.utilfrom collections import defaultdictfrom collections.abc import Iterator+from importlib.machinery import PathFinderfrom pathlib import Pathfrom types import ModuleTypefrom typing import TYPE_CHECKING, Optional@@ -26,21 +27,41 @@ def product_app_names() -> list[str]:return [app_config.name for app_config in apps.get_app_configs() if is_product_module(app_config.name)]+def _has_submodule(app_name: str, submodule: str) -> bool:+ """Whether `<app_name>.<submodule>` exists, found on disk without importing any of it.++ `find_spec` on a dotted name imports every parent package first, so a nested lookup+ ("facade.x") would run each product's `facade/__init__.py`, and raise for a product+ without one. PathFinder searches one package directory at a time instead.+ """+ app_spec = importlib.util.find_spec(app_name)+ locations = app_spec.submodule_search_locations if app_spec else None+ name = app_name+ for part in submodule.split("."):+ if locations is None:+ return False+ name = f"{name}.{part}"+ spec = PathFinder.find_spec(name, locations)+ if spec is None:+ return False+ locations = spec.submodule_search_locations+ return True++def load_product_modules(submodule: str) -> Iterator[ModuleType]:"""Import `<product app>.<submodule>` for every product that has one.How core picks up per-product declarations (`routes`, `data_freshness`, ...) without a- hand-maintained list. `find_spec` rather than try/except so a real ImportError inside a- product's module surfaces instead of reading as "this product doesn't have one".+ hand-maintained list. The lookup imports nothing, so a real ImportError inside a product's+ module surfaces from the import itself instead of reading as "this product doesn't have one".Products are imported dynamically here, so the core->product edges are invisible to importtooling (tach/grimp). Accepted on purpose, as the alternative duplicates PRODUCTS_APPS."""for app_name in product_app_names():- module_name = f"{app_name}.{submodule}"- if importlib.util.find_spec(module_name) is None:+ if not _has_submodule(app_name, submodule):continue- yield importlib.import_module(module_name)+ yield importlib.import_module(f"{app_name}.{submodule}")# This module loads at django.setup() via the file-system product list; posthog.schemadiff --git a/posthog/test/test_products.py b/posthog/test/test_products.pyindex f1b74c9d0558..731ba7559613 100644--- a/posthog/test/test_products.py+++ b/posthog/test/test_products.py@@ -2,7 +2,7 @@ from django.test import SimpleTestCasefrom posthog.schema import ProductKey-from posthog.products import Products+from posthog.products import Products, load_product_modulesclass TestProducts(SimpleTestCase):@@ -71,3 +71,10 @@ class TestProducts(SimpleTestCase):assert Trueexcept Exception as e:raise AssertionError(f"Products.reload() raised an exception: {e}") from e+++class TestLoadProductModules(SimpleTestCase):+ def test_a_nested_submodule_skips_products_without_the_parent_package(self) -> None:+ modules = list(load_product_modules("facade.today_highlights"))++ self.assertTrue(all(module.__name__.endswith(".backend.facade.today_highlights") for module in modules))diff --git a/products/today/AGENTS.md b/products/today/AGENTS.mdnew file mode 100644index 000000000000..26939790f899--- /dev/null+++ b/products/today/AGENTS.md@@ -0,0 +1,40 @@+# Today++## Highlight sources ("For you today")++Today ranks facts that other products find and shows the best few.+The product that owns the data owns its source: the query, the thresholds, and the copy.+Today owns the contract, the ranking, and the shared helpers.++**A new source lives in its own product, never in `products/today/`.**++1. Put the rule in the product's internals, for example `products/<x>/backend/today_highlights.py`.+ It takes a `HighlightContext` and returns `HighlightFindings`.+2. Declare it in `products/<x>/backend/facade/today_highlights.py`:++ ```python+ from products.today.backend.facade.contracts import HighlightSource++ from ..today_highlights import find_stale_things++ HIGHLIGHT_SOURCES = (HighlightSource(name="stale_things", find=find_stale_things, scopes=("thing:read",)),)+ ```++3. Add `"products.today"` to the product's `depends_on` in `tach.toml`. Today gets no new dependency.+4. Test the rule in the product, with `products.today.backend.facade.testing.highlight_context`.++Today finds the declaration through `posthog.products.load_product_modules`, so a new source changes no file in Today.+The registry raises on a missing declaration, an unusable entry, or a source name that another product already uses.++Import only from Today's facade:++- `facade/contracts.py`: `HighlightCandidate`, `HighlightFindings`, `HighlightContext`, `HighlightSource`, `HighlightMetric`, `DailyValueNotReady`+- `facade/enums.py`: `HighlightLabel`, `HighlightUnit`, `HighlightInterval`+- `facade/highlight_helpers.py`: number and text formatting, `uses_product`, and trend detection++`HighlightContext.daily()` caches one value per team, property restrictions and day, so every viewer with the same restrictions shares it.+Never compute a per-viewer value there without the user id in its name.++**Status:** `backend/logic/highlight_sources/` is deprecated.+The sources in it still load, through legacy aliases in `logic/highlight_types.py`, until each one moves into its product.+Do not add a file there and do not copy those files as an example.diff --git a/products/today/CLAUDE.md b/products/today/CLAUDE.mdnew file mode 120000index 000000000000..47dc3e3d863c--- /dev/null+++ b/products/today/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/products/today/backend/facade/contracts.py b/products/today/backend/facade/contracts.pyindex f538c44716cd..ed722409ccd4 100644--- a/products/today/backend/facade/contracts.py+++ b/products/today/backend/facade/contracts.py@@ -1,11 +1,14 @@"""Contract types for today: what the product returns to its API, MCP tools and other products."""+from collections.abc import Callablefrom dataclasses import fieldfrom datetime import date, datetime-from typing import Any+from typing import TYPE_CHECKING, Any, Protocol, TypeVarfrom pydantic.dataclasses import dataclass+from posthog.dataclasses import frozen+from .enums import (CitedSource,FigureSourceKind,@@ -19,6 +22,11 @@ from .enums import (KeyClauseRole,)+if TYPE_CHECKING:+ from posthog.models import Team, User++T = TypeVar("T")+@dataclass(frozen=True)class PullRequestLink:@@ -191,3 +199,79 @@ class Highlights:refresh_at: datetimepulse: list[HighlightMetric]items: list[HighlightItem]+++class DailyValueNotReady(Exception):+ """A source raises this when a value it needs is still being computed. Today retries the source soon."""+++@frozen+class HighlightCandidate:+ """One fact a source offers to "For you today". Today ranks every candidate and shows the best few."""++ key: str+ label: HighlightLabel+ # Today shows at most two items of one family, so a product cannot fill the list alone.+ family: str+ importance: float+ relevance: float+ title: str+ detail: str+ url: str | None = None+ series: list[float] | None = None+ # Items of different families that share a ref are about the same object, so Today shows one of them.+ ref: str | None = None+ # Today sets this to the name of the source that found the item.+ source: str = ""+++@frozen+class HighlightDetection:+ """A notable move in a series, as `highlight_helpers.detect` reports it."""++ kind: str+ strength: float+ direction: int+ pct: float | None = None+ now: float | None = None+ usual: float | None = None+ weekday: str | None = None+ same_weekday: bool = False+++@frozen+class HighlightFindings:+ items: tuple[HighlightCandidate, ...] = ()+ pulse: tuple[HighlightMetric, ...] = ()+++class HighlightContext(Protocol):+ """What Today gives a source's `find`: the viewer, their local day, and Today's cache and error guard."""++ team: "Team"+ user: "User"+ today: date++ def allows(self, *required: str) -> bool: ...++ # Caches one value per team, property restrictions and day, so every viewer with the same+ # restrictions shares it. Never compute a per-viewer value here. Prefix `name` with the source name.+ def daily(self, name: str, compute: Callable[[], T]) -> T: ...++ def guard(self, name: str, provider: Callable[[], T], default: T) -> T: ...+++@frozen+class HighlightSource:+ """A product's contribution to "For you today".++ A product declares its sources in `HIGHLIGHT_SOURCES` in `backend/facade/today_highlights.py`.+ Today finds that module by name, so a new source changes no file in Today.+ """++ # Unique across products. Today keys stored results and the frontend icon by it.+ name: str+ find: Callable[[HighlightContext], HighlightFindings]+ # Today skips the source when the viewer's API scopes or access controls do not cover these.+ scopes: tuple[str, ...] = ()+ pulse_order: int = 0diff --git a/products/today/backend/facade/highlight_helpers.py b/products/today/backend/facade/highlight_helpers.pynew file mode 100644index 000000000000..5bd4b803d7ec--- /dev/null+++ b/products/today/backend/facade/highlight_helpers.py@@ -0,0 +1,19 @@+"""Shared helpers for highlight sources: number and text formatting, product use, and trend detection."""++from ..logic.highlight_rules import exact, human, short, users, uses_product+from ..logic.highlight_trends import BAD_METRIC, MONEY, UNCLEAR_LABEL, UNKNOWN_DIRECTION, complete, detect, stale++__all__ = [+ "BAD_METRIC",+ "MONEY",+ "UNCLEAR_LABEL",+ "UNKNOWN_DIRECTION",+ "complete",+ "detect",+ "exact",+ "human",+ "short",+ "stale",+ "users",+ "uses_product",+]diff --git a/products/today/backend/facade/testing.py b/products/today/backend/facade/testing.pynew file mode 100644index 000000000000..7f17eddb4627--- /dev/null+++ b/products/today/backend/facade/testing.py@@ -0,0 +1,15 @@+"""Test-support facade for today.++A product tests its highlight sources with the context Today runs them with, without importing Today's internals.+"""++from datetime import date++from posthog.models import Team, User++from ..logic.highlight_types import Context+from .contracts import HighlightContext+++def highlight_context(*, team: Team, user: User, today: date, scopes: frozenset[str] | None = None) -> HighlightContext:+ return Context(team, user, today, scopes)diff --git a/products/today/backend/logic/highlight_registry.py b/products/today/backend/logic/highlight_registry.pyindex dab386884efa..8ae68c148339 100644--- a/products/today/backend/logic/highlight_registry.py+++ b/products/today/backend/logic/highlight_registry.py@@ -1,15 +1,57 @@import pkgutilimport importlib+from collections.abc import Iteratorfrom functools import cache-from typing import cast+from types import ModuleType+from posthog.products import load_product_modules++from ..facade.contracts import HighlightSourcefrom . import highlight_sources-from .highlight_types import Source++SOURCES_MODULE = "facade.today_highlights"+SOURCES_ATTRIBUTE = "HIGHLIGHT_SOURCES"+++class HighlightRegistryError(Exception):+ pass+++def _legacy_modules() -> Iterator[ModuleType]:+ for name in sorted(module.name for module in pkgutil.iter_modules(highlight_sources.__path__)):+ yield importlib.import_module(f"{highlight_sources.__name__}.{name}")+++def _declared(module: ModuleType) -> object:+ if module.__name__.startswith(f"{highlight_sources.__name__}."):+ source = getattr(module, "SOURCE", None)+ return None if source is None else (source,)+ return getattr(module, SOURCES_ATTRIBUTE, None)@cache-def load_sources() -> tuple[Source, ...]:- return tuple(- cast(Source, importlib.import_module(f"{highlight_sources.__name__}.{name}").SOURCE)- for name in sorted(module.name for module in pkgutil.iter_modules(highlight_sources.__path__))- )+def load_sources() -> tuple[HighlightSource, ...]:+ """Every source that a product declares in `backend/facade/today_highlights.py`, sorted by name.++ A product depends on Today's facade to declare a source, so Today needs no import of that product.+ Sources still in the legacy `highlight_sources/` package declare a module-level `SOURCE` and load too.+ A broken declaration raises instead of dropping the source without a trace.+ """+ sources: dict[str, HighlightSource] = {}+ owners: dict[str, str] = {}+ for module in [*load_product_modules(SOURCES_MODULE), *_legacy_modules()]:+ declared = _declared(module)+ if not isinstance(declared, tuple | list):+ raise HighlightRegistryError(f"{module.__name__}.{SOURCES_ATTRIBUTE} must be a tuple of HighlightSource")+ for source in declared:+ if not isinstance(source, HighlightSource) or not source.name or not callable(source.find):+ raise HighlightRegistryError(+ f"{module.__name__} declares {source!r}, which is not a usable HighlightSource"+ )+ if source.name in sources:+ raise HighlightRegistryError(+ f"{module.__name__} and {owners[source.name]} both declare the source name {source.name!r}"+ )+ sources[source.name] = source+ owners[source.name] = module.__name__+ return tuple(sources[name] for name in sorted(sources))diff --git a/products/today/backend/logic/highlight_rules.py b/products/today/backend/logic/highlight_rules.pyindex 2010453e29b1..80f5f252dda2 100644--- a/products/today/backend/logic/highlight_rules.py+++ b/products/today/backend/logic/highlight_rules.py@@ -2,7 +2,7 @@ import refrom posthog.models.file_system.starred_products import has_starred_product-from .highlight_types import Context+from ..facade.contracts import HighlightContextdef human(value: float) -> str:@@ -36,5 +36,5 @@ def short(text: str, limit: int = 60) -> str:return text[:limit].rsplit(" ", 1)[0].rstrip(",;:(-– ")-def uses_product(context: Context, *product_paths: str) -> bool:+def uses_product(context: HighlightContext, *product_paths: str) -> bool:return has_starred_product(context.user, context.team, list(product_paths))diff --git a/products/today/backend/logic/highlight_sources/__init__.py b/products/today/backend/logic/highlight_sources/__init__.pyindex e69de29bb2d1..2135e1b95106 100644--- a/products/today/backend/logic/highlight_sources/__init__.py+++ b/products/today/backend/logic/highlight_sources/__init__.py@@ -0,0 +1,5 @@+"""Deprecated: sources that still live inside Today.++New sources belong in their own product: `HIGHLIGHT_SOURCES` in `products/<x>/backend/facade/today_highlights.py`.+The modules here move out into their products, after which this package goes away.+"""diff --git a/products/today/backend/logic/highlight_trends.py b/products/today/backend/logic/highlight_trends.pyindex a79f6f067719..02d2183cfe3b 100644--- a/products/today/backend/logic/highlight_trends.py+++ b/products/today/backend/logic/highlight_trends.py@@ -3,7 +3,7 @@ import mathimport statisticsfrom datetime import date, timedelta-from posthog.dataclasses import frozen+from ..facade.contracts import HighlightDetectionWEEKDAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]BAD_METRIC = re.compile(@@ -18,18 +18,6 @@ MONEY = re.compile(r"(?i)(revenue|\barr\b|\bmrr\b|\bnrr\b|spend|cost|usd|\$(?![aMAX_FILLED_DAYS = 120-@frozen-class Detection:- kind: str- strength: float- direction: int- pct: float | None = None- now: float | None = None- usual: float | None = None- weekday: str | None = None- same_weekday: bool = False--def complete(points: list[tuple[date, float]], period: str, today: date) -> list[tuple[date, float]]:if period == "day":return [(d, v) for d, v in points if d < today]@@ -80,18 +68,18 @@ def zscore(last: float, prior: list[float]) -> float | None:def detect(points: list[tuple[date, float]], period: str, today: date, average: bool = False-) -> tuple[list[Detection], list[float]]:+) -> tuple[list[HighlightDetection], list[float]]:usable = complete(points, period, today)- found: list[Detection] = []+ found: list[HighlightDetection] = []if period == "day":usable = fill_days(usable)daily = [v for _, v in usable]if len(daily) >= 17 and all(v == 0 for v in daily[-3:]) and statistics.mean(daily[-17:-3]) >= 100:- found.append(Detection(kind="went_quiet", strength=0.7, direction=-1))+ found.append(HighlightDetection(kind="went_quiet", strength=0.7, direction=-1))found.extend(_same_weekday(usable))values = windows(usable, period, average)if len(values) >= 6 and all(v == 0 for v in values[-6:]) and any(v != 0 for v in values[:-6]):- found.append(Detection(kind="flatline", strength=0.6, direction=-1))+ found.append(HighlightDetection(kind="flatline", strength=0.6, direction=-1))if len(values) < 4 or values[-1] == 0:return found, valueslast, previous = values[-1], values[-2]@@ -99,7 +87,7 @@ def detect(change_z = zscore(changes[-1], changes[:-1]) if len(changes) >= 4 and previous else Noneif change_z is not None and abs(change_z) >= 2 and abs(changes[-1]) >= 0.1:found.append(- Detection(+ HighlightDetection(kind="spike",strength=min(1.0, 0.6 + 0.1 * (abs(change_z) - 2)),direction=1 if changes[-1] > 0 else -1,@@ -115,14 +103,14 @@ def detect(history = [values[i] - values[i - 1] for i in range(max(1, len(values) - 9), len(values) - 3)]usual = (sum(1 for h in history if h > 0) - sum(1 for h in history if h < 0)) if len(history) >= 3 else 0if usual * direction <= 0:- found.append(Detection(kind="trend", strength=0.6, direction=direction))+ found.append(HighlightDetection(kind="trend", strength=0.6, direction=direction))earlier = statistics.mean(values[:-1][-3:])if earlier > 0 and (last / earlier >= 3 or last / earlier <= 1 / 3) and max(last, earlier) >= 100:- found.append(Detection(kind="level_shift", strength=0.8, direction=1 if last > earlier else -1))+ found.append(HighlightDetection(kind="level_shift", strength=0.8, direction=1 if last > earlier else -1))return found, values-def _same_weekday(usable: list[tuple[date, float]]) -> list[Detection]:+def _same_weekday(usable: list[tuple[date, float]]) -> list[HighlightDetection]:start = next((i for i, (_, v) in enumerate(usable) if v != 0), 0)days = usable[start:]if len(days) < 8:@@ -137,7 +125,7 @@ def _same_weekday(usable: list[tuple[date, float]]) -> list[Detection]:if abs(last_value - mean) < max(5, 3 * math.sqrt(max(mean, 1))):return []return [- Detection(+ HighlightDetection(kind="same_weekday",strength=0.7,direction=1 if last_value > mean else -1,diff --git a/products/today/backend/logic/highlight_types.py b/products/today/backend/logic/highlight_types.pyindex 3380af22d54a..68ca6c3e4282 100644--- a/products/today/backend/logic/highlight_types.py+++ b/products/today/backend/logic/highlight_types.py@@ -1,5 +1,6 @@from collections.abc import Callablefrom datetime import date+from functools import cached_propertyfrom typing import TypeVar, castfrom django.core.cache import cache@@ -8,7 +9,6 @@ import structlogfrom posthog.hogql.errors import ExposedHogQLError-from posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Team, Userfrom posthog.scopes import APIScopeObject, scopes_not_covered@@ -21,8 +21,17 @@ from products.access_control.backend.facade.user_access_control import (UserAccessControl,)-from ..facade import contracts-from ..facade.enums import HighlightLabel+from ..facade.contracts import (+ DailyValueNotReady,+ HighlightCandidate,+ HighlightContext,+ HighlightFindings,+ HighlightSource,+)++# Legacy names for the sources still in highlight_sources/. New sources use the facade contract.+Candidate = HighlightCandidate+Found = HighlightFindingslogger = structlog.get_logger(__name__)T = TypeVar("T")@@ -32,43 +41,15 @@ DAILY_CACHE_SECONDS = 24 * 60 * 60DAILY_LOCK_SECONDS = 30-class DailyValueNotReady(Exception):- pass--def property_restrictions(team: Team, user: User) -> str:return restriction_fingerprint(get_restricted_properties_with_group_type_index_for_team(user=user, team_id=team.id))[:16]-@frozen-class Candidate:- key: str- label: HighlightLabel- family: str- importance: float- relevance: float- title: str- detail: str- url: str | None = None- series: list[float] | None = None- ref: str | None = None- source: str = ""-- @property- def score(self) -> float:- floor = 0.5 if self.importance >= 0.9 else 0.2- return self.importance * (floor + (1 - floor) * self.relevance)---@frozen-class Found:- items: tuple[Candidate, ...] = ()- pulse: tuple[contracts.HighlightMetric, ...] = ()--class Context:+ """Today's `HighlightContext`. A source sees only the protocol, so these internals stay private."""+def __init__(self, team: Team, user: User, today: date, scopes: frozenset[str] | None = None) -> None:self.team = teamself.user = user@@ -76,7 +57,11 @@ class Context:self.scopes = scopesself.failures: list[str] = []self.access = UserAccessControl(user=user, team=team)- self.restrictions = property_restrictions(team, user)++ @cached_property+ def restrictions(self) -> str:+ # Only daily() reads this. Computing it on first use keeps the context free to build in a source's tests.+ return property_restrictions(self.team, self.user)def allows(self, *required: str) -> bool:covered = self.scopes is None or "*" in self.scopes or not scopes_not_covered(self.scopes, required)@@ -120,9 +105,13 @@ class Context:return default-@frozen-class Source:- name: str- find: Callable[[Context], Found]- scopes: tuple[str, ...] = ()- pulse_order: int = 0+def Source( # noqa: N802 - keeps the legacy name the sources in highlight_sources/ call+ *, name: str, find: Callable[[Context], HighlightFindings], scopes: tuple[str, ...] = (), pulse_order: int = 0+) -> HighlightSource:+ # A legacy source reads Today's own Context. Today always calls it with one, so the cast holds.+ return HighlightSource(+ name=name,+ find=cast(Callable[[HighlightContext], HighlightFindings], find),+ scopes=scopes,+ pulse_order=pulse_order,+ )diff --git a/products/today/backend/logic/highlights.py b/products/today/backend/logic/highlights.pyindex 24be14d50330..9436bf133a80 100644--- a/products/today/backend/logic/highlights.py+++ b/products/today/backend/logic/highlights.py@@ -22,6 +22,7 @@ from posthog.temporal.common.client import sync_connectfrom posthog.week_start_day import WeekStartDayfrom ..facade import contracts+from ..facade.contracts import HighlightCandidate, HighlightFindings, HighlightSourcefrom ..facade.enums import HighlightInterval, HighlightLabel, HighlightPriority, HighlightsStatusfrom ..models import TodayHighlightsfrom ..temporal.inputs import (@@ -33,7 +34,7 @@ from ..temporal.inputs import (highlights_workflow_id,)from .highlight_registry import load_sources-from .highlight_types import CACHE_SECONDS, Candidate, Context, Found, Source, property_restrictions+from .highlight_types import CACHE_SECONDS, Context, property_restrictionslogger = structlog.get_logger(__name__)@@ -47,7 +48,7 @@ PULSE_TILES = 4URGENT_RISK_SCORE = 0.75MINOR_OPPORTUNITY_SCORE = 0.4-_FOUND = TypeAdapter(Found)+_FINDINGS = TypeAdapter(HighlightFindings)_HIGHLIGHTS = TypeAdapter(contracts.Highlights)@@ -129,9 +130,9 @@ def run_source(inputs: HighlightSourceInputs) -> HighlightSourceResult:if source is None or not context.allows(*source.scopes):return HighlightSourceResult(source_name=inputs.source_name, found=None, failed=False)with tags_context(product=Product.TODAY, feature=Feature.QUERY, team_id=context.team.id):- found = context.guard(source.name, partial(source.find, context), Found())+ found = context.guard(source.name, partial(source.find, context), HighlightFindings())return HighlightSourceResult(- source_name=source.name, found=_FOUND.dump_json(found).decode(), failed=bool(context.failures)+ source_name=source.name, found=_FINDINGS.dump_json(found).decode(), failed=bool(context.failures))@@ -139,7 +140,7 @@ def finalize(inputs: FinalizeHighlightsInputs) -> None:row = TodayHighlights.objects.for_team(inputs.team_id).filter(id=inputs.highlights_id).first()if row is None:return- found = {result.source_name: _FOUND.validate_json(result.found) for result in inputs.results if result.found}+ found = {result.source_name: _FINDINGS.validate_json(result.found) for result in inputs.results if result.found}highlights = build_highlights(load_sources(), found, Team.objects.get(id=inputs.team_id), row.local_day)failed = [result for result in inputs.results if result.failed]usable = bool(highlights.items or highlights.pulse)@@ -163,7 +164,7 @@ def delete_for_teams(team_ids: list[int]) -> None:def build_highlights(- sources: Sequence[Source], found: Mapping[str, Found], team: Team, day: date+ sources: Sequence[HighlightSource], found: Mapping[str, HighlightFindings], team: Team, day: date) -> contracts.Highlights:pulse = [metric@@ -189,8 +190,13 @@ def _refresh_at(team: Team, day: date) -> datetime:return datetime.combine(day + timedelta(days=1), time.min, team.timezone_info)-def _item(candidate: Candidate) -> contracts.HighlightItem:- score = round(candidate.score, 3)+def _score(candidate: HighlightCandidate) -> float:+ floor = 0.5 if candidate.importance >= 0.9 else 0.2+ return candidate.importance * (floor + (1 - floor) * candidate.relevance)+++def _item(candidate: HighlightCandidate) -> contracts.HighlightItem:+ score = round(_score(candidate), 3)return contracts.HighlightItem(key=candidate.key,source=candidate.source,@@ -221,10 +227,10 @@ def _period_starts(metric: contracts.HighlightMetric, team: Team, day: date) ->return [day - timedelta(days=days) for days in back]-def rank(candidates: list[Candidate]) -> list[Candidate]:- shown: list[Candidate] = []- for candidate in sorted(candidates, key=lambda c: -c.score):- if candidate.score < MIN_SCORE or len(shown) == MAX_ITEMS:+def rank(candidates: list[HighlightCandidate]) -> list[HighlightCandidate]:+ shown: list[HighlightCandidate] = []+ for candidate in sorted(candidates, key=lambda c: -_score(c)):+ if _score(candidate) < MIN_SCORE or len(shown) == MAX_ITEMS:breakif sum(1 for s in shown if s.family == candidate.family) >= MAX_PER_FAMILY:continuediff --git a/products/today/backend/tests/test_highlight_data_catalog_approvals.py b/products/today/backend/tests/test_highlight_data_catalog_approvals.pyindex 8c4b0ce0a178..3f695b6d2e95 100644--- a/products/today/backend/tests/test_highlight_data_catalog_approvals.py+++ b/products/today/backend/tests/test_highlight_data_catalog_approvals.py@@ -52,7 +52,7 @@ class TestDataCatalogApprovalsHighlight(SimpleTestCase):item = found.items[0]assert (item.title, item.detail, item.url) == (title, detail, url)assert item.label == HighlightLabel.OPPORTUNITY- assert item.score == 0.5+ assert (item.importance, item.relevance) == (0.5, 1.0)assert registered.scopes == ("data_catalog:read", "data_catalog_approval:write")def test_a_user_who_cannot_approve_gets_no_item(self) -> None:diff --git a/products/today/backend/tests/test_highlights.py b/products/today/backend/tests/test_highlights.pyindex 198ed857fd9c..e5b969a5292a 100644--- a/products/today/backend/tests/test_highlights.py+++ b/products/today/backend/tests/test_highlights.py@@ -1,6 +1,7 @@from dataclasses import replacefrom datetime import UTC, date, datetime, timedeltafrom functools import partial+from types import SimpleNamespacefrom typing import Anyfrom zoneinfo import ZoneInfo@@ -20,6 +21,12 @@ from posthog.models import Team, Userfrom products.access_control.backend.facade.testing import create_access_controlfrom products.today.backend.facade import contracts+from products.today.backend.facade.contracts import (+ HighlightCandidate,+ HighlightContext,+ HighlightFindings,+ HighlightSource,+)from products.today.backend.facade.enums import (HighlightInterval,HighlightLabel,@@ -27,8 +34,8 @@ from products.today.backend.facade.enums import (HighlightsStatus,HighlightUnit,)-from products.today.backend.logic import highlight_types, highlights-from products.today.backend.logic.highlight_types import Candidate, Context, Found, Source+from products.today.backend.logic import highlight_registry, highlight_types, highlights+from products.today.backend.logic.highlight_types import Contextfrom products.today.backend.logic.highlights import MAX_ITEMS, rankfrom products.today.backend.models import TodayHighlightsfrom products.today.backend.temporal.inputs import (@@ -38,12 +45,14 @@ from products.today.backend.temporal.inputs import ()DAY = date(2026, 10, 13)-FOUND = TypeAdapter(Found)+FOUND = TypeAdapter(HighlightFindings)HIGHLIGHTS = TypeAdapter(contracts.Highlights)-def candidate(key: str, family: str, importance: float, title: str | None = None, ref: str | None = None) -> Candidate:- return Candidate(+def candidate(+ key: str, family: str, importance: float, title: str | None = None, ref: str | None = None+) -> HighlightCandidate:+ return HighlightCandidate(key=key,label=HighlightLabel.RISK,family=family,@@ -63,7 +72,7 @@ def metric(key: str) -> contracts.HighlightMetric:ALERT_RESULT = HighlightSourceResult(source_name="alerts",- found=FOUND.dump_json(Found(items=(candidate("alert", "alerts", 0.8),))).decode(),+ found=FOUND.dump_json(HighlightFindings(items=(candidate("alert", "alerts", 0.8),))).decode(),failed=False,)FAILED_RESULT = HighlightSourceResult(source_name="errors", found=None, failed=True)@@ -128,18 +137,18 @@ class TestHighlightRanking(SimpleTestCase):class TestBuildHighlights(SimpleTestCase):def test_the_pulse_follows_the_source_order_and_the_items_follow_priority(self) -> None:sources = (- Source(name="key_metrics", find=lambda _c: Found(), pulse_order=2),- Source(name="routine", find=lambda _c: Found(), pulse_order=1),- Source(name="experiments", find=lambda _c: Found()),- Source(name="alerts", find=lambda _c: Found()),+ HighlightSource(name="key_metrics", find=lambda _c: HighlightFindings(), pulse_order=2),+ HighlightSource(name="routine", find=lambda _c: HighlightFindings(), pulse_order=1),+ HighlightSource(name="experiments", find=lambda _c: HighlightFindings()),+ HighlightSource(name="alerts", find=lambda _c: HighlightFindings()),)found = {- "key_metrics": Found(pulse=(metric("k1"), metric("k2"), metric("k3"))),- "routine": Found(pulse=(metric("r1"), metric("r2"))),- "experiments": Found(+ "key_metrics": HighlightFindings(pulse=(metric("k1"), metric("k2"), metric("k3"))),+ "routine": HighlightFindings(pulse=(metric("r1"), metric("r2"))),+ "experiments": HighlightFindings(items=(replace(candidate("win", "experiments", 0.9), label=HighlightLabel.OPPORTUNITY),)),- "alerts": Found(items=(candidate("alert", "alerts", 0.5),)),+ "alerts": HighlightFindings(items=(candidate("alert", "alerts", 0.5),)),}built = highlights.build_highlights(sources, found, Team(timezone="Europe/Prague"), DAY)@@ -171,17 +180,19 @@ class TestBuildHighlights(SimpleTestCase):self, _name: str, interval: HighlightInterval, week_start_day: int | None, count: int, expected: list[date]) -> None:tile = replace(metric("k"), series=[1.0] * count, interval=interval)- source = Source(name="metrics", find=lambda _c: Found())+ source = HighlightSource(name="metrics", find=lambda _c: HighlightFindings())built = highlights.build_highlights(- (source,), {"metrics": Found(pulse=(tile,))}, Team(week_start_day=week_start_day), DAY+ (source,), {"metrics": HighlightFindings(pulse=(tile,))}, Team(week_start_day=week_start_day), DAY)self.assertEqual(built.pulse[0].period_starts, expected)class TestRunSource(BaseTest):- def _run(self, source: Source, user: User | None = None, scopes: list[str] | None = None) -> HighlightSourceResult:+ def _run(+ self, source: HighlightSource, user: User | None = None, scopes: list[str] | None = None+ ) -> HighlightSourceResult:inputs = HighlightSourceInputs(team_id=self.team.id,user_id=(user or self.user).id,@@ -203,8 +214,10 @@ class TestRunSource(BaseTest):def test_a_source_runs_only_when_the_credential_covers_its_scopes(self, _name: str, scopes: list[str] | None, runs: bool) -> None:- source = Source(- name="alerts", find=lambda _c: Found(items=(candidate("alert", "alerts", 0.8),)), scopes=("alert:read",)+ source = HighlightSource(+ name="alerts",+ find=lambda _c: HighlightFindings(items=(candidate("alert", "alerts", 0.8),)),+ scopes=("alert:read",),)result = self._run(source, scopes=scopes)@@ -228,9 +241,9 @@ class TestRunSource(BaseTest):self.organization.save()if access_level:create_access_control(team_id=self.team.id, resource=resource, access_level=access_level)- source = Source(+ source = HighlightSource(name="errors",- find=lambda _c: Found(items=(candidate("error", "errors", 0.8),)),+ find=lambda _c: HighlightFindings(items=(candidate("error", "errors", 0.8),)),scopes=("warehouse_view:read",) if resource == "warehouse_objects" else ("error_tracking:read",),)@@ -239,12 +252,12 @@ class TestRunSource(BaseTest):self.assertEqual(result.found is not None, runs)def test_a_broken_source_reports_a_failure_instead_of_raising(self) -> None:- def broken(_context: Context) -> Found:+ def broken(_context: HighlightContext) -> HighlightFindings:raise ValueError("boom")- result = self._run(Source(name="broken", find=broken))+ result = self._run(HighlightSource(name="broken", find=broken))- self.assertEqual((result.failed, FOUND.validate_json(result.found or "")), (True, Found()))+ self.assertEqual((result.failed, FOUND.validate_json(result.found or "")), (True, HighlightFindings()))class TestFinalizeHighlights(BaseTest):@@ -406,3 +419,36 @@ class TestDailyCache(BaseTest):found = context.guard("value", lambda: context.daily("value", compute), 0)self.assertEqual((found, calls, context.failures, captured.call_count), (0, [], ["value"], 0))+++def declaring(*sources: object) -> SimpleNamespace:+ return SimpleNamespace(__name__="products.example.backend.facade.today_highlights", HIGHLIGHT_SOURCES=sources)+++def declaring_one(source: object) -> SimpleNamespace:+ return SimpleNamespace(__name__="products.example.backend.facade.today_highlights", HIGHLIGHT_SOURCES=source)+++class TestLoadSources(SimpleTestCase):+ @parameterized.expand(+ [+ ("no declaration", SimpleNamespace(__name__="products.example.backend.facade.today_highlights")),+ (+ "a single source without a tuple",+ declaring_one(HighlightSource(name="alerts", find=lambda _c: HighlightFindings())),+ ),+ ("not a source", declaring("alerts")),+ ("an empty name", declaring(HighlightSource(name="", find=lambda _c: HighlightFindings()))),+ (+ "a name taken twice",+ declaring(+ HighlightSource(name="alerts", find=lambda _c: HighlightFindings()),+ HighlightSource(name="alerts", find=lambda _c: HighlightFindings()),+ ),+ ),+ ]+ )+ def test_a_broken_declaration_raises(self, _name: str, module: SimpleNamespace) -> None:+ with patch.object(highlight_registry, "load_product_modules", return_value=[module]):+ with self.assertRaises(highlight_registry.HighlightRegistryError):+ highlight_registry.load_sources.__wrapped__()