: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): run research at signal buckets instead of every signal (#86407)
Georgiy Tarasov3378f1be2656
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex 58c5eeb87b45..b8b6c7f2e572 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -216,11 +216,15 @@ Bulk sync (`sync_full_cache`) fans the per-repo sync out via `run_parallel_with_#### Re-promotion-Reports are re-promoted when new evidence arrives. A `READY` / `RESOLVED` report re-promotes on every new matching signal (so research reruns with the latest evidence), and a report reset to `potential` re-promotes once it clears the `signals_at_run` snooze gate again.+Reports are re-promoted when new evidence arrives. A `READY` report re-promotes when a new matching signal carries it to its next research bucket, and a report reset to `potential` re-promotes once it clears the `signals_at_run` snooze gate again.-**Re-research cap.** The research activity reads every non-deleted signal, so re-research cost scales with report size. Once an already-researched report exceeds `RERESEARCH_MAX_SIGNALS` (`SIGNAL_RERESEARCH_MAX_SIGNALS`, default 10), `READY` re-promotion is suppressed: new signals are still assigned, weighted, and emitted, but no new summary run spawns. The cap is enforced in two places: the grouping promotion gate (`assign_and_emit_signal_activity`), which fires the `signal_report_reresearch_skipped` event per suppressed signal so the saved volume is trackable, and the summary self-loop (`mark_report_ready_activity`), which stops an in-flight run from looping into another research pass (no event — this is a rare mid-run edge).+**Research buckets.** The research activity reads every non-deleted signal, so re-research cost scales with report size, and a report that re-researched on every signal spent most of its runs re-reading a report that had barely moved. Instead, a report researches at the cumulative signal counts in `RESEARCH_SIGNAL_BUCKETS` (`SIGNAL_RESEARCH_SIGNAL_BUCKETS`, default `1,2,4,10`), which by their number also cap it at four research passes. Between buckets, and past the last one, new signals are still assigned, weighted, and emitted, but no new summary run spawns.-The cap covers **only** the `READY` / `RESOLVED` path (the one that re-promotes on every signal). Re-promotions through the `potential` gate stay uncapped — first research, `candidate` self-heal, snooze return, and a not-actionable reset re-accumulating weight — because they are weight / `signals_at_run`-gated rather than per-signal, so strong new evidence can still resurface a large report.+`next_research_bucket(signals_researched)` is the single predicate, enforced in two places: the grouping promotion gate (`assign_and_emit_signal_activity`), which fires `signal_report_reresearch_skipped` per withheld signal with a `skip_reason` of `below_next_bucket` or `buckets_exhausted` so the saved volume is trackable, and the summary self-loop (`mark_report_ready_activity`), which decides whether signals that landed mid-run are worth another pass.++`SignalReport.signals_researched` is the count the report's last **completed** pass covered, written when a run reaches `READY`. It is null until then, and `researched_signal_count` reconstructs it from the `signals_at_run` stamp for reports researched before the column existed, so the backlog carries no backfill. Reading it makes the predicate skip buckets the report is already past, so a report whose first pass ran at 5 signals waits for 10 rather than firing passes 2 and 3 back to back on the same evidence. Two properties follow from measuring completed work rather than attempts. A run that pauses on a quota gate before researching leaves the value untouched, so it costs the report nothing. And promotion tests the count the report has _reached_ against its next bucket rather than the crossing itself, so a bucket reached while the quota or daily-report gate suppressed promotion is still claimable on the next signal instead of being skipped for the report's life.++Buckets gate **only** the `READY` re-research path. Re-promotions through the `potential` gate stay uncapped — first research, `candidate` self-heal, snooze return, and a not-actionable reset re-accumulating weight — because they are weight / `signals_at_run`-gated rather than per-signal, so strong new evidence can still resurface a large report.On re-promotion:@@ -371,9 +375,10 @@ potential → candidate → in_progress → ready→ potential (reset by actionability judge)→ candidate (mid-run quota pause; re-promotes on the next matching signal)-# Re-promotion: READY reports are re-promoted to candidate on each new matching signal,-# triggering a new summary run that reuses the previous repo selection and findings for-# already-seen signals. Suppressed once signal_count > RERESEARCH_MAX_SIGNALS (see Re-research cap).+# Re-promotion: a READY report is re-promoted to candidate by the signal that carries it to its+# next bucket in RESEARCH_SIGNAL_BUCKETS, triggering a new summary run that reuses the previous+# repo selection and findings for already-seen signals. Suppressed between buckets and once every+# bucket is used (see Research buckets).# RESOLVED is terminal and never re-promotes: a recurrence spawns a fresh report, linked back to the# resolved one via a related_to artefact (assign_and_emit_signal_activity).ready → candidatediff --git a/products/signals/backend/migrations/0111_signalreport_signals_researched.py b/products/signals/backend/migrations/0111_signalreport_signals_researched.pynew file mode 100644index 000000000000..9e3155799a0f--- /dev/null+++ b/products/signals/backend/migrations/0111_signalreport_signals_researched.py@@ -0,0 +1,15 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("signals", "0110_signalreportartefact_team_type_recent_idx"),+ ]++ operations = [+ migrations.AddField(+ model_name="signalreport",+ name="signals_researched",+ field=models.IntegerField(blank=True, null=True),+ ),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex b49db24cccda..35273f6f3b02 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0110_signalreportartefact_team_type_recent_idx+0111_signalreport_signals_researcheddiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex 510b59b5a4a1..e44058b07859 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -202,6 +202,12 @@ class SignalUserAutonomyConfig(UUIDModel):verbose_name_plural = "Signal user autonomy configs"+# What a summary run adds to `signal_count` when it stamps `signals_at_run` on the way into+# `in_progress`, so the report does not re-promote on the first few signals that land during the+# run. `SignalReport.researched_signal_count` subtracts it to recover the count a run started on.+SIGNALS_AT_RUN_INCREMENT = 3++class InvalidStatusTransition(Exception):def __init__(self, from_status: str, to_status: str):self.from_status = from_status@@ -247,6 +253,12 @@ class SignalReport(UUIDModel):signals_at_run = models.IntegerField(default=0)# How many times the summary workflow has run for this report (incremented on each CANDIDATE -> IN_PROGRESS).run_count = models.IntegerField(default=0)+ # The cumulative signal count the last *completed* research pass covered, and the only input to+ # when the next pass runs (see next_research_bucket). Written when a run reaches READY, not when+ # it starts, so a run that pauses on the quota gate before researching anything costs the report+ # nothing. Null means no completed pass has recorded it, which covers reports researched before+ # the column existed; read `researched_signal_count`, which reconstructs it from `signals_at_run`.+ signals_researched = models.IntegerField(null=True, blank=True)# LLM-generated during signal matchingtitle = models.TextField(null=True, blank=True)@@ -305,6 +317,21 @@ class SignalReport(UUIDModel):),]+ @property+ def researched_signal_count(self) -> int:+ """The cumulative signal count the last completed research pass covered.++ `signals_researched` is null until a run reaches READY under code that writes it, so a report+ researched before the column existed is read back from `signals_at_run`: every run stamps it+ as the starting count plus `SIGNALS_AT_RUN_INCREMENT`, and a READY report always carries a+ run's stamp rather than a snooze's, because a snooze moves the report to POTENTIAL and only+ another run returns it to READY. The next completed pass writes the column and retires the+ reconstruction for that report.+ """+ if self.signals_researched is not None:+ return self.signals_researched+ return max(self.signals_at_run - SIGNALS_AT_RUN_INCREMENT, 0)+def transition_to(self,new_status: "SignalReport.Status",diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.pyindex e56bc3af0985..46848031554b 100644--- a/products/signals/backend/temporal/grouping.py+++ b/products/signals/backend/temporal/grouping.py@@ -62,7 +62,6 @@ from products.signals.backend.temporal.signal_queries import (from products.signals.backend.temporal.summary import SignalReportSummaryWorkflowfrom products.signals.backend.temporal.types import (IMPLEMENTATION_DEBOUNCE_SECONDS,- RERESEARCH_MAX_SIGNALS,RESEARCH_DEBOUNCE_SECONDS,EmitSignalInputs,ExistingReportMatch,@@ -77,6 +76,7 @@ from products.signals.backend.temporal.types import (SignalTypeExample,SpecificityMetadata,TeamSignalGroupingInput,+ next_research_bucket,)logger = structlog.get_logger(__name__)@@ -678,6 +678,12 @@ class AssignAndEmitDbResult:report_status: strreport_signal_count: intpromotion_suppressed: bool+ # Cumulative signal count the report must reach for its next research pass, or None when its+ # last pass already covered the final bucket. Carried out of the transaction only so the skip+ # event can report it.+ next_research_bucket: Optional[int] = None+ # What the report's last completed pass covered, for the same reason.+ report_signals_researched: int = 0@temporalio.activity.defn@@ -738,6 +744,7 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> Asreport_status=report.status,report_signal_count=report.signal_count,promotion_suppressed=False,+ next_research_bucket=None,)# Resolved reports are terminal — never reopen them. When a signal would have grouped# into an already-resolved report, the issue it fixed has recurred (or a related one@@ -789,11 +796,20 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As# - RESOLVED: terminal — never receives new signals (a recurrence spawns a fresh report above).# - POTENTIAL: promote once total_weight >= WEIGHT_THRESHOLD and signal_count >= signals_at_run# (snooze gate, defaults to 0). Uncapped — a report's first research always runs.- # - READY: re-research on every new signal, but only while signal_count <= RERESEARCH_MAX_SIGNALS;- # past the cap, signals are collected, not researched.+ # - READY: re-research once the report has reached its next bucket in+ # RESEARCH_SIGNAL_BUCKETS. Between buckets, and past the last one, signals are+ # collected, not researched.# - CANDIDATE: re-promote to self-heal failed spawns (uncapped; concurrent runs blocked by Temporal).+ #+ # The bucket is measured against what the last completed pass actually covered, so a+ # bucket the report is already past is skipped rather than firing a pass immediately on+ # top of the previous one. Testing the reached count against that bucket, rather than+ # the crossing itself, is what lets a report still claim a bucket it reached while+ # promotion was suppressed.+ signals_researched = report.researched_signal_count+ bucket = next_research_bucket(signals_researched)is_reresearch = report.status == SignalReport.Status.READY- reresearch_capped = is_reresearch and report.signal_count > RERESEARCH_MAX_SIGNALS+ reresearch_capped = is_reresearch and (bucket is None or report.signal_count < bucket)if ((is_reresearch and not reresearch_capped)or report.status == SignalReport.Status.CANDIDATE@@ -856,6 +872,8 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> Asreport_status=report.status,report_signal_count=report.signal_count,promotion_suppressed=promotion_suppressed,+ next_research_bucket=bucket,+ report_signals_researched=signals_researched,)try:@@ -929,8 +947,9 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> Asteam_id=input.team_id,source_id=input.source_id,)- # Over-cap signal on an already-researched report: assigned/emitted but no re-research- # spawned. Emitted so the saved re-research volume is trackable.+ # A signal on an already-researched report that did not spawn re-research, because the+ # report is either between buckets or past its last one. Emitted so the withheld+ # re-research volume is trackable, split by which of the two reasons held it back.if db_result.reresearch_capped:try:posthoganalytics.capture(@@ -943,7 +962,12 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> As"source_product": input.source_product,"source_type": input.source_type,"source_id": input.source_id,- "threshold": RERESEARCH_MAX_SIGNALS,+ "run_count": db_result.run_count,+ "signals_researched": db_result.report_signals_researched,+ "next_bucket": db_result.next_research_bucket,+ "skip_reason": (+ "buckets_exhausted" if db_result.next_research_bucket is None else "below_next_bucket"+ ),},groups=groups(team.organization, team),)diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.pyindex 8a48f3646427..29ce328fb3f3 100644--- a/products/signals/backend/temporal/summary.py+++ b/products/signals/backend/temporal/summary.py@@ -29,7 +29,7 @@ from posthog.temporal.common.utils import close_db_connectionsfrom products.signals.backend.auto_start import maybe_autostart_from_report_artefactsfrom products.signals.backend.daily_limit import capture_signal_report_daily_limit_paused, daily_report_limit_gate-from products.signals.backend.models import SignalReport, SignalTeamConfig+from products.signals.backend.models import SIGNALS_AT_RUN_INCREMENT, SignalReport, SignalTeamConfigfrom products.signals.backend.quota import (capture_signal_report_quota_paused,record_quota_check_failed_open,@@ -60,9 +60,9 @@ from products.signals.backend.temporal.signal_queries import (from products.signals.backend.temporal.types import (IMPLEMENTATION_DEBOUNCE_SECONDS,NEW_SELF_DRIVING_GRACE,- RERESEARCH_MAX_SIGNALS,SignalData,SignalReportSummaryWorkflowInputs,+ next_research_bucket,)logger = structlog.get_logger(__name__)@@ -720,7 +720,9 @@ async def mark_report_in_progress_activity(input: MarkReportInProgressInput) ->report = SignalReport.objects.select_for_update().get(id=input.report_id, team_id=input.team_id)if report.status == SignalReport.Status.IN_PROGRESS:return report.run_count, True- updated_fields = report.transition_to(SignalReport.Status.IN_PROGRESS, signals_at_run_increment=3)+ updated_fields = report.transition_to(+ SignalReport.Status.IN_PROGRESS, signals_at_run_increment=SIGNALS_AT_RUN_INCREMENT+ )report.save(update_fields=updated_fields)return report.run_count, False@@ -790,6 +792,11 @@ async def mark_report_ready_activity(input: MarkReportReadyInput) -> bool:# Previous attempt took the re-promotion branch; preserve has_new_signals=True.return True, report.run_count, Trueupdated_fields = report.transition_to(SignalReport.Status.READY, title=input.title, summary=input.summary)+ # The pass is only now known to have covered anything, so this is where the count the+ # bucket schedule reads is written. A run that failed or paused earlier leaves the+ # previous value standing and so leaves the report's next bucket where it was.+ report.signals_researched = input.processed_signal_count+ updated_fields = [*updated_fields, "signals_researched"]if input.charts is not None:report.charts = input.chartsupdated_fields = [*updated_fields, "charts"]@@ -797,9 +804,13 @@ async def mark_report_ready_activity(input: MarkReportReadyInput) -> bool:report.suggested_prompts = input.suggested_promptsupdated_fields = [*updated_fields, "suggested_prompts"]report.save(update_fields=updated_fields)- # Loop to re-research only if new signals arrived and we're within the cap; past- # RERESEARCH_MAX_SIGNALS the report stays READY instead of re-running over a large set.- has_new_signals = input.processed_signal_count < report.signal_count <= RERESEARCH_MAX_SIGNALS+ # Loop to re-research only if the signals that arrived during the run carried the report+ # to its next bucket. Same predicate as the grouping promotion gate, so a signal landing+ # mid-run is researched on the schedule it would have had if it had landed after. The+ # bucket is strictly above what this run processed, so reaching it also means new+ # signals arrived.+ bucket = next_research_bucket(report.researched_signal_count)+ has_new_signals = bucket is not None and report.signal_count >= bucketif has_new_signals:# If more signals arrived while the report was being processed, we want to# re-promote it back to candidate and loop to also process new signalsdiff --git a/products/signals/backend/temporal/types.py b/products/signals/backend/temporal/types.pyindex 6e81262c4fdb..b0e83a4d1283 100644--- a/products/signals/backend/temporal/types.py+++ b/products/signals/backend/temporal/types.py@@ -3,26 +3,55 @@ from dataclasses import dataclass, fieldfrom datetime import datetime, timedeltafrom typing import Any, Optional-# Above this many assigned signals, an already-researched (READY/RESOLVED) report stops-# re-researching on new signals; signals are still assigned. See assign_and_emit_signal_activity.-RERESEARCH_MAX_SIGNALS = int(os.getenv("SIGNAL_RERESEARCH_MAX_SIGNALS", "10"))++def _parse_research_signal_buckets(raw: str) -> tuple[int, ...]:+ """Parse a comma-separated bucket list into a sorted, deduplicated, strictly positive tuple."""+ buckets = {int(part) for part in (item.strip() for item in raw.split(",")) if part}+ return tuple(sorted(b for b in buckets if b > 0))+++# Cumulative assigned-signal counts at which a report researches, and by their number the most+# research passes any report gets. Between buckets, and past the last one, signals are still+# assigned and emitted but no research spawns. The defaults widen as they go because the+# signals-per-report distribution has a long tail: most reports never leave the first bucket, so+# most of the research this withholds would have re-read a report that barely moved. Empty disables+# research entirely, so keep at least one bucket.+RESEARCH_SIGNAL_BUCKETS = _parse_research_signal_buckets(os.getenv("SIGNAL_RESEARCH_SIGNAL_BUCKETS", "1,2,4,10"))+++def next_research_bucket(signals_researched: int) -> Optional[int]:+ """The cumulative signal count at which a report's next research pass runs, or None for no pass.++ `signals_researched` is the count the report's last completed pass covered, so buckets it is+ already past are skipped instead of firing back to back — a report whose first pass ran at 5+ signals waits for 10, not for 2. Running out of buckets is also what caps the total: a report+ researched at the last bucket has no bucket above it, so it never researches again.++ Reading the completed count rather than a count of attempts is what keeps a run that pauses+ before researching — the quota gates in the summary workflow — from spending a pass, and what+ keeps a bucket crossing withheld by those gates claimable on the next signal.+ """+ return next((bucket for bucket in RESEARCH_SIGNAL_BUCKETS if bucket > signals_researched), None)+# How long a research run waits before starting, so signals arriving in a burst are researched-# together instead of once each. A report re-promotes on *every* new signal, and ~46% of signals join-# a report within 5 minutes of the previous one, so most research today re-reads the same report for-# one extra signal. The waiting workflow already owns the report's workflow ID, so signals landing-# during the wait collapse into it (see the WorkflowAlreadyStartedError handler in grouping) and the-# run then covers the whole burst. Applies to a report's first research too, so sibling signals join-# that run rather than forcing an immediate re-research. 0 disables the wait.+# together instead of once each. Signals cluster in time — a large share join a report within five+# minutes of the previous one — so a burst that straddles a bucket would otherwise research on the+# signal that crossed it and leave its siblings for the next bucket. The waiting workflow already+# owns the report's workflow ID, so signals landing during the wait collapse into it (see the+# WorkflowAlreadyStartedError handler in grouping) and the run then covers the whole burst. Applies+# to a report's first research too, so sibling signals join that run rather than spending the+# report's next bucket immediately after. 0 disables the wait.RESEARCH_DEBOUNCE_SECONDS = int(os.getenv("SIGNAL_RESEARCH_DEBOUNCE_SECONDS", "0"))# How long a report waits after research settles (READY, no pending signals) before its-# implementation task starts. A report re-promotes on every new signal, so a signal landing just-# after research finishes would otherwise ship a PR for a summary that's about to be rewritten by-# the re-research. The wait lets that late signal fold into a re-research run instead. The waiting-# run still owns the report's workflow ID, so a signal arriving during the wait collapses into it-# (see the WorkflowAlreadyStartedError handler in grouping) and re-promotes the report to CANDIDATE;-# the run then loops to re-research rather than implement. 0 disables the wait.+# implementation task starts. A report re-promotes when a signal carries it to its next research+# bucket, so a signal landing just after research finishes would otherwise ship a PR for a summary+# that's about to be rewritten by the re-research. The wait lets that late signal fold into a+# re-research run instead. The waiting run still owns the report's workflow ID, so a signal arriving+# during the wait collapses into it (see the WorkflowAlreadyStartedError handler in grouping) and+# re-promotes the report to CANDIDATE; the run then loops to re-research rather than implement.+# 0 disables the wait.IMPLEMENTATION_DEBOUNCE_SECONDS = int(os.getenv("SIGNAL_IMPLEMENTATION_DEBOUNCE_SECONDS", "900"))# Orgs new to self-driving skip the implementation buffer: a team whose signals config was createddiff --git a/products/signals/backend/test/test_assign_and_emit_signal.py b/products/signals/backend/test/test_assign_and_emit_signal.pyindex 6f65826321bc..9e42e4f61551 100644--- a/products/signals/backend/test/test_assign_and_emit_signal.py+++ b/products/signals/backend/test/test_assign_and_emit_signal.py@@ -23,11 +23,11 @@ from products.signals.backend.temporal.grouping import (assign_and_emit_signal_activity,)from products.signals.backend.temporal.types import (- RERESEARCH_MAX_SIGNALS,ExistingReportMatch,MatchedMetadata,NewReportMatch,NoMatchMetadata,+ next_research_bucket,)GROUPING_MODULE_PATH = "products.signals.backend.temporal.grouping"@@ -353,13 +353,15 @@ async def test_candidate_repromotion_does_not_advance_run_count(ateam):@pytest.mark.asyncio@pytest.mark.django_db-async def test_ready_repromotes_to_candidate_on_any_signal(ateam):- """A READY report re-promotes on every signal regardless of weight thresholds."""+async def test_ready_repromotes_to_candidate_on_a_bucket_regardless_of_weight(ateam):+ """Re-research is gated on the signal count reaching the next bucket, not on weight: a tiny+ signal that lands on a bucket still re-promotes, and the transition preserves title/summary."""report = await database_sync_to_async(SignalReport.objects.create)(team=ateam,status=SignalReport.Status.READY,total_weight=1.5,- signal_count=2,+ signal_count=1,+ run_count=1,title="original title",summary="original summary",)@@ -420,41 +422,124 @@ async def test_resolved_match_spawns_new_report_and_leaves_resolved_untouched(at# ----------------------------------------------------------------------------# Re-research cap: already-researched reports stop re-researching past RERESEARCH_MAX_SIGNALS+# Research buckets: a READY report re-researches only at RESEARCH_SIGNAL_BUCKETS, at most once each# ---------------------------------------------------------------------------+ ("signals_researched", "expected"),+ [+ (0, 1),+ (1, 2),+ (2, 4),+ (4, 10),+ # Past the last bucket: the report never researches again however many signals arrive.+ (10, None),+ (40, None),+ # First pass ran late (the weight threshold held the report back), so buckets 2 and 4 are+ # already behind it — the next pass waits for 10 rather than firing twice back to back.+ (5, 10),+ ],+)+def test_next_research_bucket(signals_researched: int, expected: int | None):+ assert next_research_bucket(signals_researched) == expected++@pytest.mark.asyncio@pytest.mark.django_db-async def test_reresearch_allowed_up_to_cap(ateam):- """At the boundary (the new signal brings signal_count exactly to RERESEARCH_MAX_SIGNALS), a- READY report still re-promotes — the cap only bites once signal_count exceeds it."""+ ("signals_researched", "run_count", "starting_signal_count", "expected_promoted"),+ [+ # The signal that reaches a bucket promotes; the ones below it do not. Walking the default+ # 1,2,4,10 buckets end to end is what would catch a regression to the old+ # re-research-on-every-signal behavior.+ (1, 1, 1, True),+ (2, 2, 2, False),+ (2, 2, 3, True),+ (4, 3, 4, False),+ (4, 3, 6, False),+ (4, 3, 8, False),+ (4, 3, 9, True),+ # Researched at the last bucket: nothing re-promotes, however many signals arrive.+ (10, 4, 10, False),+ (10, 4, 40, False),+ # A report already past a bucket when its pass completed skips that bucket rather than+ # firing on top of the pass that just covered it.+ (5, 2, 5, False),+ (5, 2, 9, True),+ # Attempts are not passes: runs that burned run_count without reaching READY (the summary+ # workflow's quota gates revert to CANDIDATE and keep the counter) must not cap the report.+ (1, 9, 1, True),+ ],+)+async def test_ready_report_re_promotes_only_on_a_bucket(+ ateam, signals_researched: int, run_count: int, starting_signal_count: int, expected_promoted: bool+):report = await database_sync_to_async(SignalReport.objects.create)(team=ateam,status=SignalReport.Status.READY,- total_weight=1.5,- signal_count=RERESEARCH_MAX_SIGNALS - 1,+ total_weight=2.0,+ signal_count=starting_signal_count,+ run_count=run_count,+ signals_researched=signals_researched,)- input_ = _build_input(ateam.id, _existing_match(str(report.id)), weight=0.1)+ input_ = _build_input(ateam.id, _existing_match(str(report.id)), weight=0.5)result = await assign_and_emit_signal_activity(input_)- assert result.promoted is True+ assert result.promoted is expected_promotedrefreshed = await database_sync_to_async(SignalReport.objects.get)(id=report.id)- assert refreshed.status == SignalReport.Status.CANDIDATE- assert refreshed.signal_count == RERESEARCH_MAX_SIGNALS+ expected_status = SignalReport.Status.CANDIDATE if expected_promoted else SignalReport.Status.READY+ assert refreshed.status == expected_status+++ ("signals_at_run", "starting_signal_count", "expected_promoted"),+ [+ # Researched before the column existed: the count the last run started on is read back from+ # its signals_at_run stamp. Reading the null column as 0 would put the whole READY backlog+ # at bucket 1 and re-research it on its next signal.+ (13, 12, False),+ (10, 8, False),+ (10, 9, True),+ (4, 1, True),+ # Created READY outside the summary workflow, with no run stamp at all.+ (0, 0, True),+ ],+)+async def test_ready_report_without_a_recorded_pass_reads_the_run_stamp(+ ateam, signals_at_run: int, starting_signal_count: int, expected_promoted: bool+):+ report = await database_sync_to_async(SignalReport.objects.create)(+ team=ateam,+ status=SignalReport.Status.READY,+ total_weight=2.0,+ signal_count=starting_signal_count,+ signals_at_run=signals_at_run,+ run_count=1,+ signals_researched=None,+ )+ input_ = _build_input(ateam.id, _existing_match(str(report.id)), weight=0.5)++ result = await assign_and_emit_signal_activity(input_)++ assert result.promoted is expected_promoted@pytest.mark.asyncio@pytest.mark.django_db-async def test_reresearch_capped_past_threshold_still_assigns_signal(ateam, patch_side_effects):- """Past the cap, a READY report stops re-researching: promoted=False and status is unchanged,- but the signal is still counted, weighted, and emitted (not marked deleted)."""+async def test_signal_between_buckets_is_still_assigned(ateam, patch_side_effects):+ """Withholding research must not withhold the signal: it is still counted, weighted, and emitted+ to ClickHouse (not marked deleted), so the next bucket can be reached."""report = await database_sync_to_async(SignalReport.objects.create)(team=ateam,status=SignalReport.Status.READY,total_weight=2.0,- signal_count=RERESEARCH_MAX_SIGNALS, # post-increment lands at cap + 1+ signal_count=4,+ run_count=3,+ signals_researched=4,title="original title",summary="original summary",)@@ -464,9 +549,8 @@ async def test_reresearch_capped_past_threshold_still_assigns_signal(ateam, patcassert result.promoted is Falserefreshed = await database_sync_to_async(SignalReport.objects.get)(id=report.id)- assert refreshed.status == SignalReport.Status.READYassert refreshed.promoted_at is None- assert refreshed.signal_count == RERESEARCH_MAX_SIGNALS + 1+ assert refreshed.signal_count == 5assert refreshed.total_weight == pytest.approx(2.5)emit_kwargs = patch_side_effects["emit"].call_args.kwargsassert emit_kwargs["metadata"].get("deleted") is not True@@ -474,23 +558,36 @@ async def test_reresearch_capped_past_threshold_still_assigns_signal(ateam, patc@pytest.mark.asyncio@pytest.mark.django_db-async def test_reresearch_capped_emits_skipped_event(ateam, patch_side_effects):- """Crossing the cap fires signal_report_reresearch_skipped (after signal_assigned_to_report) so- the saved re-research volume is trackable as an insight."""+ ("signals_researched", "starting_signal_count", "expected_reason", "expected_next_bucket"),+ [+ (4, 4, "below_next_bucket", 10),+ (10, 10, "buckets_exhausted", None),+ ],+)+async def test_withheld_research_emits_skipped_event(+ ateam,+ patch_side_effects,+ signals_researched: int,+ starting_signal_count: int,+ expected_reason: str,+ expected_next_bucket: int | None,+):+ """signal_report_reresearch_skipped is how the withheld research volume is measured, and+ skip_reason is what separates a report waiting for its next bucket from one that is done."""report = await database_sync_to_async(SignalReport.objects.create)(team=ateam,status=SignalReport.Status.READY,total_weight=2.0,- signal_count=RERESEARCH_MAX_SIGNALS,+ signal_count=starting_signal_count,+ run_count=3,+ signals_researched=signals_researched,)input_ = _build_input(ateam.id, _existing_match(str(report.id)), weight=0.5)result = await assign_and_emit_signal_activity(input_)- # The report was genuinely capped (not re-promoted), and the event reflects that.assert result.promoted is False- refreshed = await database_sync_to_async(SignalReport.objects.get)(id=report.id)- assert refreshed.status == SignalReport.Status.READYevents = [call.kwargs["event"] for call in patch_side_effects["capture"].call_args_list]assert events == ["signal_assigned_to_report", "signal_report_reresearch_skipped"]skipped = next(@@ -499,21 +596,61 @@ async def test_reresearch_capped_emits_skipped_event(ateam, patch_side_effects):if c.kwargs["event"] == "signal_report_reresearch_skipped")assert skipped["report_id"] == str(report.id)- assert skipped["signal_count"] == RERESEARCH_MAX_SIGNALS + 1+ assert skipped["signal_count"] == starting_signal_count + 1assert skipped["status"] == SignalReport.Status.READY- assert skipped["threshold"] == RERESEARCH_MAX_SIGNALS+ assert skipped["run_count"] == 3+ assert skipped["signals_researched"] == signals_researched+ assert skipped["skip_reason"] == expected_reason+ assert skipped["next_bucket"] == expected_next_bucketassert skipped["source_id"] == input_.source_id@pytest.mark.asyncio@pytest.mark.django_db-async def test_reresearch_within_cap_does_not_emit_skipped_event(ateam, patch_side_effects):- """A READY report within the cap re-promotes normally and fires only signal_assigned_to_report."""+async def test_bucket_reached_under_suppression_is_claimed_by_the_next_signal(ateam):+ """A quota-suppressed crossing must not cost the report that bucket. Promotion compares the+ count the report has reached against its next bucket, so the bucket stays claimable until a+ pass actually covers it — where testing the crossing itself would hand bucket 2 to the+ suppressed signal and leave every later signal measuring against bucket 4."""+ report = await database_sync_to_async(SignalReport.objects.create)(+ team=ateam,+ status=SignalReport.Status.READY,+ total_weight=2.0,+ signal_count=1,+ run_count=1,+ signals_researched=1,+ )++ with patch(+ f"{GROUPING_MODULE_PATH}.self_driving_quota_gate",+ return_value=SelfDrivingQuotaGate(limited=True, enforced=True),+ ):+ suppressed = await assign_and_emit_signal_activity(+ _build_input(ateam.id, _existing_match(str(report.id)), weight=0.5)+ )++ assert suppressed.promoted is False+ refreshed = await database_sync_to_async(SignalReport.objects.get)(id=report.id)+ assert refreshed.status == SignalReport.Status.READY+ assert refreshed.signal_count == 2++ claimed = await assign_and_emit_signal_activity(_build_input(ateam.id, _existing_match(str(report.id)), weight=0.5))++ assert claimed.promoted is True+ refreshed = await database_sync_to_async(SignalReport.objects.get)(id=report.id)+ assert refreshed.status == SignalReport.Status.CANDIDATE+++async def test_promotion_on_a_bucket_does_not_emit_skipped_event(ateam, patch_side_effects):+ """A report that reaches its next bucket re-promotes normally and fires only the assign event."""report = await database_sync_to_async(SignalReport.objects.create)(team=ateam,status=SignalReport.Status.READY,total_weight=1.5,- signal_count=2,+ signal_count=1,+ run_count=1,)input_ = _build_input(ateam.id, _existing_match(str(report.id)), weight=0.5)@@ -531,14 +668,14 @@ async def test_reresearch_within_cap_does_not_emit_skipped_event(ateam, patch_si@pytest.mark.asyncio@pytest.mark.django_db-async def test_potential_promotes_past_cap_for_first_research(ateam):- """The cap only applies to re-research. A POTENTIAL report that grew past RERESEARCH_MAX_SIGNALS- without ever being researched still promotes for its first research."""+async def test_potential_promotes_past_last_bucket_for_first_research(ateam):+ """Buckets only gate re-research. A POTENTIAL report that grew past the last bucket without ever+ being researched still promotes for its first pass."""report = await database_sync_to_async(SignalReport.objects.create)(team=ateam,status=SignalReport.Status.POTENTIAL,total_weight=WEIGHT_THRESHOLD,- signal_count=RERESEARCH_MAX_SIGNALS + 5,+ signal_count=15,)input_ = _build_input(ateam.id, _existing_match(str(report.id)), weight=0.5)diff --git a/products/signals/backend/test/test_report_telemetry.py b/products/signals/backend/test/test_report_telemetry.pyindex 8d67c65b3e14..8500a78a8ada 100644--- a/products/signals/backend/test/test_report_telemetry.py+++ b/products/signals/backend/test/test_report_telemetry.py@@ -16,7 +16,6 @@ from products.signals.backend.temporal.summary import (mark_report_ready_activity,reset_report_to_potential_activity,)-from products.signals.backend.temporal.types import RERESEARCH_MAX_SIGNALSPIPELINE_MODULE_PATH = "products.signals.backend.temporal.summary"@@ -304,42 +303,33 @@ async def test_reset_to_potential_is_idempotent_when_already_potential(ateam):@pytest.mark.asyncio@pytest.mark.django_db-async def test_ready_loops_when_new_signals_within_cap(ateam):- """New signals arrived mid-run and the report is within the cap: re-promote to CANDIDATE and loop."""- report = await database_sync_to_async(SignalReport.objects.create)(- team=ateam,- status=SignalReport.Status.IN_PROGRESS,- signal_count=RERESEARCH_MAX_SIGNALS,- total_weight=2.0,- )- report_id = str(report.id)-- with patch(f"{PIPELINE_MODULE_PATH}.posthoganalytics.capture"):- has_new_signals = await mark_report_ready_activity(- MarkReportReadyInput(- team_id=ateam.id,- report_id=report_id,- title="title",- summary="summary",- processed_signal_count=1,- source_products=["zendesk"],- )- )-- assert has_new_signals is True- refreshed = await database_sync_to_async(SignalReport.objects.get)(id=report_id)- assert refreshed.status == SignalReport.Status.CANDIDATE---async def test_ready_does_not_loop_when_new_signals_past_cap(ateam):- """New signals arrived mid-run but the report is past the cap: stay READY rather than looping- into another full research run."""+ ("run_count", "processed_signal_count", "signal_count", "expected_loop"),+ [+ # Signals landed mid-run and carried the report to its next bucket: loop rather than make+ # them wait for a signal that arrives after the run.+ (1, 1, 2, True),+ (1, 1, 9, True),+ # Signals landed but the report is still short of its next bucket, so the run settles.+ (2, 2, 3, False),+ (3, 4, 9, False),+ # No new signals at all.+ (2, 2, 2, False),+ # This pass covered the last bucket: the report stays READY however far past it grew.+ (4, 10, 15, False),+ # Attempts are not passes: a report whose run_count was spent on runs that paused before+ # researching still loops when this pass leaves it at a bucket.+ (9, 1, 2, True),+ ],+)+async def test_ready_loops_only_when_the_run_reached_the_next_bucket(+ ateam, run_count: int, processed_signal_count: int, signal_count: int, expected_loop: bool+):report = await database_sync_to_async(SignalReport.objects.create)(team=ateam,status=SignalReport.Status.IN_PROGRESS,- signal_count=RERESEARCH_MAX_SIGNALS + 5,+ signal_count=signal_count,+ run_count=run_count,total_weight=2.0,)report_id = str(report.id)@@ -351,11 +341,15 @@ async def test_ready_does_not_loop_when_new_signals_past_cap(ateam):report_id=report_id,title="title",summary="summary",- processed_signal_count=RERESEARCH_MAX_SIGNALS,+ processed_signal_count=processed_signal_count,source_products=["zendesk"],))- assert has_new_signals is False+ assert has_new_signals is expected_looprefreshed = await database_sync_to_async(SignalReport.objects.get)(id=report_id)- assert refreshed.status == SignalReport.Status.READY+ expected_status = SignalReport.Status.CANDIDATE if expected_loop else SignalReport.Status.READY+ assert refreshed.status == expected_status+ # Stamped by the pass that just completed, so the next bucket is measured against what this run+ # actually covered rather than against how many times the workflow has started.+ assert refreshed.signals_researched == processed_signal_count