:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): cap personal ranking builds per day and skip no-summary calls (#127411)
posthog[bot]6659f2c20964
diff --git a/products/signals/backend/management/AGENTS.md b/products/signals/backend/management/AGENTS.mdindex 3dd76a52a796..e962750edcdc 100644--- a/products/signals/backend/management/AGENTS.md+++ b/products/signals/backend/management/AGENTS.md@@ -299,13 +299,19 @@ Each entry takes a `source` (`for_you_recommended`, `for_you_updated`, `assigned`scored` and `priority` also take `actionable_only`, `has_pr` and `window_days`.The build logs and drops an invalid entry, and uses the default pools when no entry is valid.-A person with no ready activity summary still gets a list, marked `personalized: False`.+A person with no ready activity summary gets a list in model order with no model call, marked `personalized: False` and `fallback_reason: no_activity_summary`.When the model call fails or answers outside the schema, the list is in model order and `fallback_reason` says why.+The `personal inbox ranking built` event records `model_called`, so builds with and without a model call can be counted apart.+The command spends no build limit, so use it only for single runs.`GET /api/projects/:id/signals/reports/for_me/` (`../personal_ranking/serve.py`) serves the same list to the user it describes, when the flag is on for that user.It reuses the latest row for `freshness_minutes` while the input hash matches.Otherwise it queues one `build_personal_inbox_ranking` Celery task per person behind a cache lock, and serves the latest row as stale, or the candidates in inbox order with `fallback_reason: building`.It limits builds per person with `build_burst`, `builds_per_hour` and `builds_per_day` from the same payload.+`max_builds_per_day` (default 500, at most 10000) limits the builds that call the model across every person, in one Redis token bucket per region (`../personal_ranking/build_budget.py`).+A build with no ready activity summary, or for an organization that has not approved AI data processing, does not call the model and does not spend that limit.+When a limit refuses a build, the read serves the latest row as stale, or the candidates in inbox order with `fallback_reason: rate_limited`.+A scheduled caller must spend from the same bucket with `spend_shared_build` before it builds.## Tipsdiff --git a/products/signals/backend/management/commands/run_personal_inbox_ranking.py b/products/signals/backend/management/commands/run_personal_inbox_ranking.pyindex e97c41eaf258..1b010d275bad 100644--- a/products/signals/backend/management/commands/run_personal_inbox_ranking.py+++ b/products/signals/backend/management/commands/run_personal_inbox_ranking.py@@ -34,7 +34,8 @@ class Command(BaseCommand):team, user, focus=options["focus"], dry_run=options["dry_run"], limit=options["limit"], config=config)self.stdout.write(- f"status: {build.status}, personalized: {build.personalized}, fallback_reason: {build.fallback_reason}"+ f"status: {build.status}, personalized: {build.personalized}, fallback_reason: {build.fallback_reason}, "+ f"model_called: {build.model_called}")self.stdout.write(f"candidates: {len(build.candidates)}, tokens: {build.tokens_in}/{build.tokens_out}, "diff --git a/products/signals/backend/personal_ranking/build_budget.py b/products/signals/backend/personal_ranking/build_budget.pynew file mode 100644index 000000000000..d9b1315cc241--- /dev/null+++ b/products/signals/backend/personal_ranking/build_budget.py@@ -0,0 +1,38 @@+"""The daily limit on personal ranking builds that call the model, shared by every person in one region.++The `for_me` read spends one build here before it queues a build that may call the model. A scheduled caller+spends from the same bucket. Each region has its own Redis, so each region counts on its own.+"""++from django.conf import settings++import structlog++from posthog.token_bucket import BucketUnavailable, Budget, consume++from products.signals.backend.personal_ranking.config import PersonalRankingConfig++logger = structlog.get_logger(__name__)++_BUCKET_PREFIX = "personal_ranking_build_rate:shared"+# A build costs one token per hour of the day, and the bucket refills `max_builds_per_day` tokens an hour,+# so it refills exactly `max_builds_per_day` builds a day. A whole-token rate per build would round it up.+DAILY_BUILD_COST = 24+++def _key() -> str:+ return f"{_BUCKET_PREFIX}:{settings.CLOUD_DEPLOYMENT or 'local'}"+++def _budget(config: PersonalRankingConfig) -> Budget:+ return Budget(burst=config.max_builds_per_day * DAILY_BUILD_COST, per_hour=config.max_builds_per_day)+++def spend_shared_build(config: PersonalRankingConfig) -> int | None:+ """Spend one build of the shared daily limit. Returns None when allowed, else the seconds until the next build."""+ decision = consume(_key(), _budget(config), cost=DAILY_BUILD_COST)+ if isinstance(decision, BucketUnavailable):+ # Fail open, like the per-person buckets, so an unreachable Redis does not hide the list.+ logger.warning("signals.personal_ranking.shared_build_bucket_unavailable")+ return None+ return None if decision.allowed else decision.retry_afterdiff --git a/products/signals/backend/personal_ranking/config.py b/products/signals/backend/personal_ranking/config.pyindex b0b2790402b7..8871638bc8ad 100644--- a/products/signals/backend/personal_ranking/config.py+++ b/products/signals/backend/personal_ranking/config.py@@ -2,7 +2,8 @@A missing or unreadable payload gives the code defaults. An invalid field falls back to its default,a large one to its maximum, so no value is unbounded. `"enabled": false` in the payload is the kill-switch: it stops every build.+switch: it stops every build. `max_builds_per_day` limits the builds that call the model across every+person in one region.The optional `pools` list replaces the default candidate pools, in order. An invalid entry is droppedand logged. When no entry is valid, the build uses the default pools.@@ -118,6 +119,8 @@ class PersonalRankingConfig:build_burst: int = 2builds_per_hour: int = 12builds_per_day: int = 40+ # Builds that call the model, across every person in one region. Each region has its own Redis, so each counts on its own.+ max_builds_per_day: int = 500# Each build keeps this many of the person's newest rows and deletes the older ones.max_rows_per_person: int = 5@@ -149,6 +152,7 @@ _MAXIMUMS: dict[str, int] = {"build_burst": 20,"builds_per_hour": 120,"builds_per_day": 500,+ "max_builds_per_day": 10000,"max_rows_per_person": 100,"reason_max_chars": 500,}diff --git a/products/signals/backend/personal_ranking/logic.py b/products/signals/backend/personal_ranking/logic.pyindex a1b73fe2c764..e78083241c34 100644--- a/products/signals/backend/personal_ranking/logic.py+++ b/products/signals/backend/personal_ranking/logic.py@@ -2,7 +2,8 @@The call goes through `build_openai_client`, as the activity summary does. Any failure of the call orof its answer gives the list in model order with a `fallback_reason`, so a build never raises because-of the model.+of the model. A person with no ready activity summary gets the list in model order with no call, because+the model has nothing to personalize it with."""import json@@ -64,6 +65,7 @@ FALLBACK_MALFORMED = "malformed_output"FALLBACK_TRUNCATED = "truncated_output"FALLBACK_NO_CANDIDATES = "no_candidates"FALLBACK_AI_NOT_APPROVED = "ai_not_approved"+FALLBACK_NO_ACTIVITY_SUMMARY = "no_activity_summary"BuildStatus = Literal["ok", "fallback", "empty", "disabled"]@@ -97,6 +99,7 @@ class PersonalRankingBuild:input_hash: str | Noneactivity_summary_version: int | Nonemodel: str+ model_called: bool = Falsetokens_in: int | None = Nonetokens_out: int | None = Nonelatency_ms: int | None = None@@ -137,6 +140,14 @@ def model_order_reason(candidate: Candidate) -> str:return next((_NEEDS_YOU_REASONS[kind] for kind in candidate.needs_you), _MODEL_ORDER_REASON)+def may_call_model(team: Team, *, summary_ready: bool) -> bool:+ """Whether a build with candidates calls the model, as `build_personal_ranking` decides it.++ Only such a build spends the shared daily limit.+ """+ return summary_ready and team.organization.is_ai_data_processing_approved is True++def normalize_focus(focus: str | None, max_chars: int) -> str | None:text = cap(focus, max_chars) if focus else ""return text or None@@ -268,6 +279,7 @@ def _capture("status": build.status,"personalized": build.personalized,"fallback_reason": build.fallback_reason,+ "model_called": build.model_called,"model": build.model,"prompt_version": PROMPT_VERSION,"activity_summary_version": build.activity_summary_version,@@ -350,8 +362,8 @@ def build_personal_ranking(now = timezone.now()focus = normalize_focus(focus, config.focus_max_chars)summary = get_summary(team, user.id)- summary_ready = summary is not None and summary.status == ActivitySummaryStatus.READY- summary_version = summary.version if summary is not None and summary_ready else None+ ready_summary = summary if summary is not None and summary.status == ActivitySummaryStatus.READY else None+ summary_version = ready_summary.version if ready_summary is not None else Nonecandidates = gather_candidates(team, user, config, now=now)refs = [candidate.ref for candidate in candidates]model_reasons = {candidate.ref: model_order_reason(candidate) for candidate in candidates}@@ -363,13 +375,16 @@ def build_personal_ranking(if candidates and team.organization.is_ai_data_processing_approved is not True:# Report text never goes to the model without the organization's approval, so the list stays in model order.status, fallback_reason = "fallback", FALLBACK_AI_NOT_APPROVED- elif candidates:+ elif candidates and ready_summary is None:+ # With no summary the model cannot personalize the list, so the build skips the paid call.+ status, fallback_reason = "fallback", FALLBACK_NO_ACTIVITY_SUMMARY+ elif candidates and ready_summary is not None:messages: list[ChatCompletionMessageParam] = [{"role": "system", "content": system_prompt(config, limit)},{"role": "user","content": user_message(- render_person(summary, config),+ render_person(ready_summary, config),candidates,focus=focus,now=now,@@ -402,7 +417,7 @@ def build_personal_ranking(build = PersonalRankingBuild(status=status,- personalized=validated is not None and summary_ready,+ personalized=validated is not None,fallback_reason=fallback_reason,entries=validated.entriesif validated is not None@@ -414,6 +429,7 @@ def build_personal_ranking(input_hash=input_hash(candidates, activity_summary_version=summary_version, focus=focus),activity_summary_version=summary_version,model=config.model,+ model_called=call is not None,tokens_in=call.tokens_in if call is not None else None,tokens_out=call.tokens_out if call is not None else None,latency_ms=call.latency_ms if call is not None else None,diff --git a/products/signals/backend/personal_ranking/prompt.py b/products/signals/backend/personal_ranking/prompt.pyindex 8b3b6720de99..9a8d88a8036c 100644--- a/products/signals/backend/personal_ranking/prompt.py+++ b/products/signals/backend/personal_ranking/prompt.py@@ -8,11 +8,11 @@ import datetimefrom collections.abc import Sequencefrom typing import Any, Literal, get_args-from products.signals.backend.activity_summary.read import ActivitySummaryStatus, ActivitySummaryView+from products.signals.backend.activity_summary.read import ActivitySummaryViewfrom products.signals.backend.personal_ranking.candidates import Candidate, NeedsYouKindfrom products.signals.backend.personal_ranking.config import PersonalRankingConfig-PROMPT_VERSION = 5+PROMPT_VERSION = 6Tier = Literal["top", "worth_a_look", "later"]TIERS: tuple[Tier, ...] = get_args(Tier)@@ -94,7 +94,6 @@ The person block is an activity summary built from their recent PostHog activity- Themes are their recent areas of work. A strong theme seen recently counts more than a weak or old one.- Owns lists objects they made or keep changing. Watches lists objects they keep opening. A report about an object they own matters more than one they only watch.- Works in lists the PostHog products they use most.-When no activity summary is available, rank on the needs-you facts and the model's lift.The `model` line of a report holds the ranking model's predictions for three outcomes:- `open`: someone opens the report.@@ -150,9 +149,8 @@ def _works_in(computed: dict[str, Any] | None) -> list[str]:return [item for item in works_in if isinstance(item, str)][:_PRODUCT_LIMIT] if isinstance(works_in, list) else []-def render_person(summary: ActivitySummaryView | None, config: PersonalRankingConfig) -> str:- if summary is None or summary.status != ActivitySummaryStatus.READY:- return "No activity summary for this person. Rank on the needs-you facts and the ranking model."+def render_person(summary: ActivitySummaryView, config: PersonalRankingConfig) -> str:+ """The person block, from a ready activity summary. A build with no ready summary does not call the model."""lines = []if summary.headline:lines.append(f"Headline: {summary.headline}")diff --git a/products/signals/backend/personal_ranking/serve.py b/products/signals/backend/personal_ranking/serve.pyindex ebf0a4def782..9da2f0a19cfd 100644--- a/products/signals/backend/personal_ranking/serve.py+++ b/products/signals/backend/personal_ranking/serve.py@@ -4,8 +4,9 @@ A stored list is reused while it is younger than `freshness_minutes` and its inpinputs. Otherwise, and for every `refresh` or `focus` request, the read queues one background build per personand serves the latest stored list as stale, or the candidates in inbox order when there is none. The focus ispart of the hash, so an unfocused request never reuses a focused list. A lock lets one build per person run at a-time, and each queued build spends two per-person token buckets. `wait_seconds` waits a bounded time for the-queued build to store its list.+time, and each queued build spends two per-person token buckets. A build that may call the model also spends+the shared daily limit of the region (`build_budget.py`). `wait_seconds` waits a bounded time for the queued build+to store its list."""import time@@ -26,9 +27,15 @@ from posthog.token_bucket import BucketDecision, BucketUnavailable, Budget, consfrom products.signals.backend.activity_summary.read import ActivitySummaryStatus, get_summaryfrom products.signals.backend.models import PersonalInboxRanking+from products.signals.backend.personal_ranking.build_budget import DAILY_BUILD_COST, spend_shared_buildfrom products.signals.backend.personal_ranking.candidates import Candidate, gather_candidatesfrom products.signals.backend.personal_ranking.config import PersonalRankingConfig, read_config-from products.signals.backend.personal_ranking.logic import input_hash, model_order_reason, normalize_focus+from products.signals.backend.personal_ranking.logic import (+ input_hash,+ may_call_model,+ model_order_reason,+ normalize_focus,+)from products.signals.backend.personal_ranking.validation import model_orderfrom products.signals.backend.personal_ranking_tasks import (BUILD_LOCK_TTL_SECONDS,@@ -42,7 +49,6 @@ logger = structlog.get_logger(__name__)ServeStatus = Literal["ready", "unavailable"]_BUCKET_PREFIX = "personal_ranking_build_rate"-_DAILY_BUILD_COST = 24MAX_WAIT_SECONDS = 30_WAIT_POLL_SECONDS = 0.5@@ -121,17 +127,21 @@ UNAVAILABLE = ServedRanking()-def _spend_build(team_id: int, user_id: int, config: PersonalRankingConfig) -> int | None:- """Spend one build from both buckets. Returns None when allowed, else the seconds until the next build."""+def _spend_build(team_id: int, user_id: int, config: PersonalRankingConfig, *, calls_model: bool) -> int | None:+ """Spend one build from the per-person buckets, and from the shared limit when the build may call the model.++ Returns None when allowed, else the seconds until the next build.+ """hourly = Budget(burst=config.build_burst, per_hour=config.builds_per_hour)# A build costs one token per hour of the day, and the bucket refills `builds_per_day` tokens an hour,# so it refills exactly `builds_per_day` builds a day. A whole-token rate per build would round it up.- daily = Budget(burst=config.builds_per_day * _DAILY_BUILD_COST, per_hour=config.builds_per_day)+ daily = Budget(burst=config.builds_per_day * DAILY_BUILD_COST, per_hour=config.builds_per_day)hourly_key = f"{_BUCKET_PREFIX}:hour:{team_id}:{user_id}"+ daily_key = f"{_BUCKET_PREFIX}:day:{team_id}:{user_id}"hourly_decision = consume(hourly_key, hourly)if isinstance(hourly_decision, BucketDecision) and not hourly_decision.allowed:return hourly_decision.retry_after- daily_decision = consume(f"{_BUCKET_PREFIX}:day:{team_id}:{user_id}", daily, cost=_DAILY_BUILD_COST)+ daily_decision = consume(daily_key, daily, cost=DAILY_BUILD_COST)if isinstance(daily_decision, BucketDecision) and not daily_decision.allowed:if isinstance(hourly_decision, BucketDecision):refund(hourly_key, hourly)@@ -139,10 +149,18 @@ def _spend_build(team_id: int, user_id: int, config: PersonalRankingConfig) -> iif isinstance(hourly_decision, BucketUnavailable) or isinstance(daily_decision, BucketUnavailable):# Fail open, so an unreachable Redis does not hide the list.logger.warning("signals.personal_ranking.build_bucket_unavailable", team_id=team_id, user_id=user_id)+ if calls_model and (retry_after := spend_shared_build(config)) is not None:+ if isinstance(hourly_decision, BucketDecision):+ refund(hourly_key, hourly)+ if isinstance(daily_decision, BucketDecision):+ refund(daily_key, daily, cost=DAILY_BUILD_COST)+ return retry_afterreturn None-def _start_build(team: Team, user: User, config: PersonalRankingConfig, focus: str | None, limit: int) -> BuildStart:+def _start_build(+ team: Team, user: User, config: PersonalRankingConfig, focus: str | None, limit: int, *, calls_model: bool+) -> BuildStart:"""Queue one background build, unless one is already running for the person or the buckets refuse it."""lock_key = build_lock_key(team.id, user.id)locked = False@@ -150,7 +168,7 @@ def _start_build(team: Team, user: User, config: PersonalRankingConfig, focus: slocked = cache.add(lock_key, "1", timeout=BUILD_LOCK_TTL_SECONDS)if not locked:return "running"- if _spend_build(team.id, user.id, config) is not None:+ if _spend_build(team.id, user.id, config, calls_model=calls_model) is not None:cache.delete(lock_key)return "rate_limited"build_personal_inbox_ranking.delay(team.id, user.id, focus, limit)@@ -312,7 +330,8 @@ def serve_personal_ranking(latest = _latest_row(team, user)candidates = gather_candidates(team, user, config, now=now, with_sources=False)- current_hash = input_hash(candidates, activity_summary_version=_ready_summary_version(team, user), focus=focus)+ summary_version = _ready_summary_version(team, user)+ current_hash = input_hash(candidates, activity_summary_version=summary_version, focus=focus)current = (latest is not Noneand latest.created_at >= now - datetime.timedelta(minutes=config.freshness_minutes)@@ -321,7 +340,8 @@ def serve_personal_ranking(if latest is not None and current and not refresh and focus is None:return _serve_row(latest, candidates, limit=limit, cached=True, stale=False, building=False)- start = _start_build(team, user, config, focus, limit)+ calls_model = bool(candidates) and may_call_model(team, summary_ready=summary_version is not None)+ start = _start_build(team, user, config, focus, limit, calls_model=calls_model)building = start in ("started", "running")if building and wait_seconds:built = _wait_for_new_row(team, user, latest, wait_seconds)diff --git a/products/signals/backend/serializers.py b/products/signals/backend/serializers.pyindex 5dbbafe640e3..6d3bd282c8e2 100644--- a/products/signals/backend/serializers.py+++ b/products/signals/backend/serializers.py@@ -1572,7 +1572,7 @@ class PersonalRankingSerializer(serializers.Serializer):stale = serializers.BooleanField(help_text=("True when the list does not match your current inbox or focus. When `building` is true, a newer "- "list is on the way. Otherwise you reached the build limit, so try again later."+ "list is on the way. Otherwise a build limit was reached, so try again later."))building = serializers.BooleanField(@@ -1585,9 +1585,11 @@ class PersonalRankingSerializer(serializers.Serializer):allow_null=True,help_text=("Why the list is in inbox order and not ranked by the language model. building: no list is stored "- "yet and one is being built. rate_limited: no list is stored yet and you reached the build limit. "- "build_failed: no list is stored yet and the build could not start. llm_error, timeout, "- "malformed_output, truncated_output, no_candidates or ai_not_approved: the stored build fell back. "+ "yet and one is being built. rate_limited: no list is stored yet and a build limit was reached, "+ "either yours or the shared daily one. build_failed: no list is stored yet and the build could not "+ "start. no_activity_summary: you have no activity summary yet, so the model did not rank the list. "+ "llm_error, timeout, malformed_output, truncated_output, no_candidates or ai_not_approved: the stored "+ "build fell back. ""Null when the model ranked it."),)diff --git a/products/signals/backend/test/test_personal_ranking.py b/products/signals/backend/test/test_personal_ranking.pyindex 003e198296be..8b088c5c3527 100644--- a/products/signals/backend/test/test_personal_ranking.py+++ b/products/signals/backend/test/test_personal_ranking.py@@ -382,8 +382,15 @@ class TestBuildPersonalRanking(BaseTest):self.llm = MagicMock()scoped_capture = MagicMock()self.capture = scoped_capture.return_value.__enter__.return_value+ self.summary: ActivitySummaryView | None = ActivitySummaryView(+ status=ActivitySummaryStatus.READY, headline="Works on checkout", version=7+ )for target, value in (("products.signals.backend.personal_ranking.logic.build_openai_client", MagicMock(return_value=self.llm)),+ (+ "products.signals.backend.personal_ranking.logic.get_summary",+ MagicMock(side_effect=lambda *_: self.summary),+ ),("products.signals.backend.personal_ranking.logic.ph_scoped_capture", scoped_capture),("products.signals.backend.personal_ranking.candidates.fetch_source_products_for_reports",@@ -473,14 +480,8 @@ class TestBuildPersonalRanking(BaseTest):def _build(self, **kwargs: Any):return build_personal_ranking(self.team, self.user, config=PersonalRankingConfig(), **kwargs)- @parameterized.expand([("no_summary", False), ("ready_summary", True)])- def test_ranks_every_candidate_and_stores_one_row(self, _name: str, with_summary: bool) -> None:+ def test_ranks_every_candidate_and_stores_one_row(self) -> None:reports = self._setup_reports()- summary = (- ActivitySummaryView(status=ActivitySummaryStatus.READY, headline="Works on checkout", version=7)- if with_summary- else None- )def answer(**kwargs: Any) -> SimpleNamespace:prompt = kwargs["messages"][1]["content"]@@ -489,8 +490,7 @@ class TestBuildPersonalRanking(BaseTest):return _response(_answer([*ranked[:-1], _entry("c99", 1)]))self.create.side_effect = answer- with patch("products.signals.backend.personal_ranking.logic.get_summary", return_value=summary):- build = self._build(focus=" checkout bugs ")+ build = self._build(focus=" checkout bugs ")row = PersonalInboxRanking.objects.for_team(self.team.id).get()ranked_ids = [entry["report_id"] for entry in row.result["ranked"]]@@ -501,8 +501,8 @@ class TestBuildPersonalRanking(BaseTest):assert all(entry["reason"] for entry in row.result["ranked"])assert row.result["counts"]["unknown_refs"] == 1assert row.status == PersonalInboxRanking.Status.OK- assert row.personalized is with_summary- assert row.activity_summary_version == (7 if with_summary else None)+ assert row.personalized is True+ assert row.activity_summary_version == 7assert row.tokens_in == 1000needs_you = {candidate.report_id: candidate.needs_you for candidate in build.candidates}assert needs_you == {@@ -517,7 +517,7 @@ class TestBuildPersonalRanking(BaseTest):event = self.capture.call_args.kwargsassert event["event"] == BUILT_EVENTassert event["properties"]["ranking_id"] == str(row.id)- assert event["properties"]["personalized"] is with_summary+ assert (event["properties"]["personalized"], event["properties"]["model_called"]) == (True, True)assert event["properties"]["tier_counts"] == {"top": 0, "worth_a_look": 2, "later": 1}serialized = json.dumps(event["properties"])assert "Waiting" not in serialized and "reason c" not in serialized and "checkout" not in serialized@@ -528,14 +528,17 @@ class TestBuildPersonalRanking(BaseTest):("api_error", RuntimeError("gateway down"), "llm_error"),("malformed", _response("not json"), "malformed_output"),("truncated", _response(_answer([_entry("c1", 1)]), finish_reason="length"), "truncated_output"),- ("ai_not_approved", None, "ai_not_approved"),+ ("ai_not_approved", "not_approved", "ai_not_approved"),+ ("no_activity_summary", "no_summary", "no_activity_summary"),])def test_model_failure_falls_back_to_model_order(self, _name: str, outcome: Any, fallback_reason: str) -> None:self._setup_reports()- if outcome is None:+ if outcome == "not_approved":self.organization.is_ai_data_processing_approved = Falseself.organization.save(update_fields=["is_ai_data_processing_approved"])+ elif outcome == "no_summary":+ self.summary = Noneelif isinstance(outcome, Exception):self.create.side_effect = outcomeelse:@@ -551,7 +554,9 @@ class TestBuildPersonalRanking(BaseTest):row = PersonalInboxRanking.objects.for_team(self.team.id).get()assert row.fallback_reason == fallback_reasonassert len(row.result["ranked"]) == 3- if outcome is None:+ model_called = not isinstance(outcome, str)+ assert self.capture.call_args.kwargs["properties"]["model_called"] is model_called+ if not model_called:self.create.assert_not_called()def test_a_model_that_rejects_reasoning_effort_gets_calls_without_it(self) -> None:@@ -711,11 +716,13 @@ class TestForMeEndpoint(APIBaseTest):query = "&".join(f"{key}={value}" for key, value in params.items())return f"/api/projects/{self.team.id}/signals/reports/for_me/" + (f"?{query}" if query else "")- def _claimed_report(self, title: str) -> SignalReport:+ def _claimed_report(self, title: str, user: User | None = None) -> SignalReport:report = SignalReport.objects.create(team=self.team, title=title, summary=title, signal_count=1, total_weight=1.0, status="ready")- SignalReportAssignment.all_teams.create(team=self.team, report=report, actor_kind="user", actor_user=self.user)+ SignalReportAssignment.all_teams.create(+ team=self.team, report=report, actor_kind="user", actor_user=user or self.user+ )return reportdef _rows(self) -> int:@@ -818,6 +825,30 @@ class TestForMeEndpoint(APIBaseTest):traveller.shift(datetime.timedelta(hours=9))assert self._get(refresh="true")["building"] is True+ def test_shared_daily_limit_counts_only_builds_that_call_the_model(self) -> None:+ self.organization.is_ai_data_processing_approved = True+ self.organization.save()+ self.payload = {"build_burst": 10, "max_builds_per_day": 1}+ other = User.objects.create_and_join(self.organization, "[email protected]", "password")+ third = User.objects.create_and_join(self.organization, "[email protected]", "password")+ ready = ActivitySummaryView(status=ActivitySummaryStatus.READY, version=1)+ summaries = {self.user.id: ready, other.id: ready, third.id: None}+ for user in (self.user, other, third):+ self._claimed_report(f"Claimed by {user.email}", user)++ with patch(+ "products.signals.backend.personal_ranking.serve.get_summary",+ side_effect=lambda _team, user_id: summaries[user_id],+ ):+ assert self._get()["building"] is True+ self.client.force_login(other)+ body = self._get()+ assert (body["fallback_reason"], body["building"]) == ("rate_limited", False)+ self.client.force_login(third)+ assert self._get()["building"] is True++ assert [args[1] for args in self.queued] == [self.user.id, third.id]+def test_another_user_never_reads_your_list(self) -> None:self._get()self._run_builds()diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex c521aa5f0ada..a3b157fe57c6 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -6136,12 +6136,12 @@ export interface PersonalRankingApi {personalized: boolean/** True when the list is a stored one. False when it is the inbox order fallback or the new list that `wait_seconds` waited for. */cached: boolean- /** True when the list does not match your current inbox or focus. When `building` is true, a newer list is on the way. Otherwise you reached the build limit, so try again later. */+ /** True when the list does not match your current inbox or focus. When `building` is true, a newer list is on the way. Otherwise a build limit was reached, so try again later. */stale: boolean/** True when a new list is being built in the background. Call again in a few seconds, or pass `wait_seconds`, to get it. */building: boolean/**- * Why the list is in inbox order and not ranked by the language model. building: no list is stored yet and one is being built. rate_limited: no list is stored yet and you reached the build limit. build_failed: no list is stored yet and the build could not start. llm_error, timeout, malformed_output, truncated_output, no_candidates or ai_not_approved: the stored build fell back. Null when the model ranked it.+ * Why the list is in inbox order and not ranked by the language model. building: no list is stored yet and one is being built. rate_limited: no list is stored yet and a build limit was reached, either yours or the shared daily one. build_failed: no list is stored yet and the build could not start. no_activity_summary: you have no activity summary yet, so the model did not rank the list. llm_error, timeout, malformed_output, truncated_output, no_candidates or ai_not_approved: the stored build fell back. Null when the model ranked it.* @nullable*/fallback_reason: string | nulldiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 331e9f1fbf88..bf92dc030d7f 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -96433,12 +96433,12 @@ export namespace Schemas {personalized: boolean;/** True when the list is a stored one. False when it is the inbox order fallback or the new list that `wait_seconds` waited for. */cached: boolean;- /** True when the list does not match your current inbox or focus. When `building` is true, a newer list is on the way. Otherwise you reached the build limit, so try again later. */+ /** True when the list does not match your current inbox or focus. When `building` is true, a newer list is on the way. Otherwise a build limit was reached, so try again later. */stale: boolean;/** True when a new list is being built in the background. Call again in a few seconds, or pass `wait_seconds`, to get it. */building: boolean;/**- * Why the list is in inbox order and not ranked by the language model. building: no list is stored yet and one is being built. rate_limited: no list is stored yet and you reached the build limit. build_failed: no list is stored yet and the build could not start. llm_error, timeout, malformed_output, truncated_output, no_candidates or ai_not_approved: the stored build fell back. Null when the model ranked it.+ * Why the list is in inbox order and not ranked by the language model. building: no list is stored yet and one is being built. rate_limited: no list is stored yet and a build limit was reached, either yours or the shared daily one. build_failed: no list is stored yet and the build could not start. no_activity_summary: you have no activity summary yet, so the model did not rank the list. llm_error, timeout, malformed_output, truncated_output, no_candidates or ai_not_approved: the stored build fell back. Null when the model ranked it.* @nullable*/fallback_reason: string | null;