: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): debounce research so bursts of signals share one run (#77847)
Joshua Snyder227e8ad4dce6
diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.pyindex 8dede15c5f76..beb84d1570ae 100644--- a/products/signals/backend/temporal/grouping.py+++ b/products/signals/backend/temporal/grouping.py@@ -56,6 +56,7 @@ from products.signals.backend.temporal.signal_queries import (from products.signals.backend.temporal.summary import SignalReportSummaryWorkflowfrom products.signals.backend.temporal.types import (RERESEARCH_MAX_SIGNALS,+ RESEARCH_DEBOUNCE_SECONDS,EmitSignalInputs,ExistingReportMatch,MatchedMetadata,@@ -679,6 +680,7 @@ class AssignAndEmitSignalOutput:promoted: booltimestamp: datetimerun_count: int+ research_debounce_seconds: int = 0@dataclass(frozen=True, kw_only=True, slots=True)@@ -990,6 +992,7 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> Aspromoted=db_result.promoted,timestamp=db_result.timestamp,run_count=db_result.run_count,+ research_debounce_seconds=RESEARCH_DEBOUNCE_SECONDS,)except Exception as e:logger.exception(@@ -1352,7 +1355,11 @@ async def _process_signal_batch(if assign_result.promoted:promoted_reports[assign_result.report_id] = (- SignalReportSummaryWorkflowInputs(team_id=signal.team_id, report_id=assign_result.report_id),+ SignalReportSummaryWorkflowInputs(+ team_id=signal.team_id,+ report_id=assign_result.report_id,+ debounce_seconds=assign_result.research_debounce_seconds,+ ),assign_result.run_count,)@@ -1396,11 +1403,10 @@ async def _process_signal_batch(task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,parent_close_policy=ParentClosePolicy.ABANDON,id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,- execution_timeout=timedelta(hours=1),+ execution_timeout=timedelta(hours=1, seconds=report_input.debounce_seconds),)except temporalio.exceptions.WorkflowAlreadyStartedError:- # Expected when CANDIDATE re-promotion fires against an in-flight workflow; no-op.- pass+ metrics.increment_research_run_collapsed()except Exception:# Log and continue: raising here would reprocess the whole batch and double-count# signals. The report stays CANDIDATE and re-promotes on the next matching signal.diff --git a/products/signals/backend/temporal/metrics.py b/products/signals/backend/temporal/metrics.pyindex 59500d3e87de..4c734ec91198 100644--- a/products/signals/backend/temporal/metrics.py+++ b/products/signals/backend/temporal/metrics.py@@ -76,6 +76,20 @@ def increment_ch_wait_timeout() -> None:).add(1)+def increment_research_run_collapsed() -> None:+ """Count a promotion that folded into an already-running research workflow instead of its own run.++ This is the research-debounce savings metric: with the debounce off it counts the rare race where+ a signal lands mid-run, and with it on it counts every signal that a waiting run absorbed.+ """+ if not _in_temporal_context():+ return+ get_metric_meter().create_counter(+ "signals_research_runs_collapsed_total",+ "Report promotions absorbed by an already-running research workflow",+ ).add(1)++def increment_scout_run(status: str) -> None:"""Count a scout run by terminal status."""if not _in_temporal_context():diff --git a/products/signals/backend/temporal/parallel_grouping.py b/products/signals/backend/temporal/parallel_grouping.pyindex f369ed1dc3b0..cff0898e5ba4 100644--- a/products/signals/backend/temporal/parallel_grouping.py+++ b/products/signals/backend/temporal/parallel_grouping.py@@ -391,7 +391,11 @@ async def _process_parallel_batch(if result.assign_result.promoted:promoted_reports[result.assign_result.report_id] = (- SignalReportSummaryWorkflowInputs(team_id=signal.team_id, report_id=result.assign_result.report_id),+ SignalReportSummaryWorkflowInputs(+ team_id=signal.team_id,+ report_id=result.assign_result.report_id,+ debounce_seconds=result.assign_result.research_debounce_seconds,+ ),result.assign_result.run_count,)diff --git a/products/signals/backend/temporal/summary.py b/products/signals/backend/temporal/summary.pyindex 81c6c0329460..73fea5616286 100644--- a/products/signals/backend/temporal/summary.py+++ b/products/signals/backend/temporal/summary.py@@ -159,6 +159,13 @@ class SignalReportSummaryWorkflow:# Bind team_id + report_id so all logs flow to the log_entries sink (the Temporal# structlog renderer skips producing when team_id isn't in the event dict).log = logger.bind(team_id=inputs.team_id, report_id=inputs.report_id)+ # Wait before researching so a burst of signals lands in one run. This workflow already holds+ # the report's workflow ID, so every signal arriving while it waits is swallowed by the+ # WorkflowAlreadyStartedError handler in grouping rather than spawning its own run, and the+ # fetch below then picks up the whole burst. patched(): in-flight histories predate the timer.+ if inputs.debounce_seconds and workflow.patched("signals-research-debounce"):+ log.info("Debouncing research", debounce_seconds=inputs.debounce_seconds)+ await workflow.sleep(timedelta(seconds=inputs.debounce_seconds))# If new signals arrived after the report was generated - loop back to process them alsomax_iterations = 10 # Basic safety guardfor _ in range(max_iterations):diff --git a/products/signals/backend/temporal/types.py b/products/signals/backend/temporal/types.pyindex 9f9b998abb0b..8aafa67daf2e 100644--- a/products/signals/backend/temporal/types.py+++ b/products/signals/backend/temporal/types.py@@ -7,6 +7,15 @@ from typing import Any, Optional# 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"))+# 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.+RESEARCH_DEBOUNCE_SECONDS = int(os.getenv("SIGNAL_RESEARCH_DEBOUNCE_SECONDS", "0"))+@dataclassclass EmitSignalInputs:@@ -138,6 +147,9 @@ class SignalReportSummaryWorkflowInputs:team_id: intreport_id: str+ # Seconds to wait before the first cycle, so a burst of signals is researched in one run rather+ # than one run each. Defaults to 0 so histories written before this field replay unchanged.+ debounce_seconds: int = 0@dataclass