: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
fix(signals): stop failing new reports before their signals reach ClickHouse (#84115)
Andrew Maguire0a2fe739271e
diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.pyindex 4e89613db0a0..7eb3d6ca1a9e 100644--- a/posthog/temporal/tests/ai/test_module_integrity.py+++ b/posthog/temporal/tests/ai/test_module_integrity.py@@ -143,6 +143,7 @@ class TestSignalsProductModuleIntegrity:"mark_report_pending_input_activity","mark_report_ready_activity","publish_report_completed_activity",+ "report_has_assigned_signals_activity","revert_report_to_candidate_activity","delete_team_reports_activity","get_grouping_paused_state_activity",diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex 4f1c20dc294e..f0dfbaadad13 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -155,6 +155,9 @@ Defined in `backend/temporal/summary.py`.The gate re-runs before repository selection (`pre_repo_selection`) and before agentic research (`pre_research`) — a block there reverts the report `in_progress → candidate` via `revert_report_to_candidate_activity` before exiting, so a promotion rule can pick it up again.All three sites are gated with `workflow.patched("self-driving-quota-gates")`.1. **Fetch signals** for the report from ClickHouse → `fetch_signals_for_report_activity`+ An empty result is retried up to `EMPTY_FETCH_RETRY_ATTEMPTS` times at `EMPTY_FETCH_RETRY_INTERVAL`, since freshly emitted signals can trail the run into ClickHouse.+ If it stays empty, `report_has_assigned_signals_activity` checks Postgres `signal_count`: signals assigned but not yet visible → the workflow exits and the report stays `candidate` for re-promotion; none assigned → `failed` with `failure_reason=no_signals_found`.+ Gated with `workflow.patched("signals-empty-fetch-retry")`.2. **Mark in-progress** in Postgres and advance `signals_at_run` by 3 → `mark_report_in_progress_activity`3. **Safety judge** → `report_safety_judge_activity`- Evaluates the underlying signals for prompt injection / manipulation attempts@@ -730,7 +733,7 @@ All Signals queries filter to `product = 'signals'` and `document_type = 'signal1. **Fetch signal type examples** (`fetch_signal_type_examples_activity`): fetches one example signal per unique `(source_product, source_type)` pair from the last month, selecting the most recent example per type. Used to give the search-query generation LLM context about heterogeneous signal types.2. **Semantic search** (`run_signal_semantic_search_activity`): uses `cosineDistance(embedding, {embedding})` to find nearest neighbors with a non-empty `report_id`, limited to the last month.3. **Fetch for report** (`fetch_signals_for_report_activity`): fetches all non-deleted signals for a report, ordered by timestamp ascending.-4. **Wait for ClickHouse** (`wait_for_signal_in_clickhouse_activity`): a two-tier poll tuned by `WaitForClickHouseMode`. Every attempt first checks the embedding worker's recently-seen store (a cheap key-value lookup over `posthog.api.embedding_worker.async_get_recently_seen_documents`). When a document already exists in ClickHouse, its cached `emitted_at` must be later than that document's latest `inserted_at`; newly created documents only require a cache hit. Once the store confirms every signal, the wait either ends outright (`optimistic` — grouping and report deletion) or runs the ClickHouse confirmation query (`ch_confirmed` — reprocessing). For the first 5 minutes the wait is otherwise store-exclusive; after that ClickHouse also polls on every 3rd attempt (a third of the store's rate) as a fallback, since the store is best-effort. The ClickHouse query counts emitted `document_id`s within a widened timestamp range (`min(timestamp)-2m` to `max(timestamp)+2m`) and `inserted_at >= now() - 30 minutes`, which avoids matching stale earlier emissions of the same IDs while tolerating precision loss and queueing delay. This query intentionally does **not** filter on `deleted`.+4. **Wait for ClickHouse** (`wait_for_signal_in_clickhouse_activity`): a two-tier poll tuned by `WaitForClickHouseMode`. Every attempt first checks the embedding worker's recently-seen store (a cheap key-value lookup over `posthog.api.embedding_worker.async_get_recently_seen_documents`). When a document already exists in ClickHouse, its cached `emitted_at` must be later than that document's latest `inserted_at`; newly created documents only require a cache hit. Once the store confirms every signal, the wait either ends outright (`optimistic` — grouping batches that promoted no report, and report deletion) or runs the ClickHouse confirmation query (`ch_confirmed` — reprocessing, and grouping batches that promoted a report, since the summary workflow spawned right after reads those rows from ClickHouse). For the first 5 minutes the wait is otherwise store-exclusive; after that ClickHouse also polls on every 3rd attempt (a third of the store's rate) as a fallback, since the store is best-effort. The ClickHouse query counts emitted `document_id`s within a widened timestamp range (`min(timestamp)-2m` to `max(timestamp)+2m`) and `inserted_at >= now() - 30 minutes`, which avoids matching stale earlier emissions of the same IDs while tolerating precision loss and queueing delay. This query intentionally does **not** filter on `deleted`.5. **Filter reports by source product** (`fetch_report_ids_for_source_products`): used by the list API’s `source_product` filter. Note that it currently has a hard `LIMIT 300`.`execute_hogql_query_with_retry()` in `backend/temporal/clickhouse.py` wraps transient ClickHouse failures with heartbeat-safe retry behavior for activities.diff --git a/products/signals/backend/temporal/__init__.py b/products/signals/backend/temporal/__init__.pyindex 5d297ee92e59..34b8617bc26b 100644--- a/products/signals/backend/temporal/__init__.py+++ b/products/signals/backend/temporal/__init__.py@@ -70,6 +70,7 @@ from products.signals.backend.temporal.summary import (mark_report_pending_input_activity,mark_report_ready_activity,publish_report_completed_activity,+ report_has_assigned_signals_activity,reset_report_to_potential_activity,revert_report_to_candidate_activity,)@@ -120,6 +121,7 @@ ACTIVITIES = [mark_report_pending_input_activity,mark_report_ready_activity,publish_report_completed_activity,+ report_has_assigned_signals_activity,revert_report_to_candidate_activity,delete_team_reports_activity,get_grouping_paused_state_activity,diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.pyindex 3fcc7a894a63..df358917db9a 100644--- a/products/signals/backend/temporal/grouping.py+++ b/products/signals/backend/temporal/grouping.py@@ -1367,9 +1367,11 @@ async def _process_signal_batch(for sid, result in emitted_signals],max_wait_time_seconds=3600,- # Fresh emissions: the store's confirmation is enough for the next batch's- # semantic search — don't spend ClickHouse queries on the happy path.- mode=WaitForClickHouseMode.OPTIMISTIC,+ # The summary workflows spawned below read these rows from ClickHouse as their first+ # step, so a batch that promoted a report must confirm visibility there; the store's+ # Kafka-commit confirmation only precedes the insert. Batches that promote nothing+ # only need the rows for the next batch's semantic search, where optimism is fine.+ mode=(WaitForClickHouseMode.CH_CONFIRMED if promoted_reports else WaitForClickHouseMode.OPTIMISTIC),),start_to_close_timeout=timedelta(hours=1, minutes=5),heartbeat_timeout=timedelta(minutes=2),diff --git a/products/signals/backend/temporal/metrics.py b/products/signals/backend/temporal/metrics.pyindex f8600d023de8..0e5a1f37f587 100644--- a/products/signals/backend/temporal/metrics.py+++ b/products/signals/backend/temporal/metrics.py@@ -120,6 +120,26 @@ def increment_research_run_collapsed() -> None:).add(1)+def increment_report_fetch_recovered(attempt: int) -> None:+ """Count a research run whose signals only became readable in ClickHouse on a retried fetch."""+ if not _in_temporal_context():+ return+ get_metric_meter({"attempt": str(attempt)}).create_counter(+ "signals_report_fetch_recovered_total",+ "Report signal fetches that succeeded only after retrying an empty read",+ ).add(1)+++def increment_report_run_deferred(reason: str) -> None:+ """Count a research run that exited without researching or failing, leaving the report to re-promote."""+ if not _in_temporal_context():+ return+ get_metric_meter({"reason": reason}).create_counter(+ "signals_report_runs_deferred_total",+ "Report research runs deferred to a later promotion by reason",+ ).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/summary.py b/products/signals/backend/temporal/summary.pyindex 73fea5616286..cc52920b0e4f 100644--- a/products/signals/backend/temporal/summary.py+++ b/products/signals/backend/temporal/summary.py@@ -17,6 +17,7 @@ from temporalio import workflowfrom temporalio.common import RetryPolicy, WorkflowIDReusePolicyfrom temporalio.workflow import ParentClosePolicy+from posthog.dataclasses import frozenfrom posthog.event_usage import groupsfrom posthog.kafka_client.routing import get_producerfrom posthog.kafka_client.topics import KAFKA_SIGNALS_REPORT_COMPLETED@@ -61,6 +62,12 @@ from products.signals.backend.temporal.types import (logger = structlog.get_logger(__name__)+# A freshly promoted report's signals can trail its summary run into ClickHouse by a few seconds+# (the emit -> embed -> insert path is asynchronous), so an empty first fetch is retried before it+# is trusted. Six 10s attempts comfortably covers observed p99 ingestion lag.+EMPTY_FETCH_RETRY_ATTEMPTS = 6+EMPTY_FETCH_RETRY_INTERVAL = timedelta(seconds=10)+def _capture_report_event(event: str,@@ -195,6 +202,33 @@ class SignalReportSummaryWorkflow:retry_policy=RetryPolicy(maximum_attempts=3),)+ async def _fetch_signals(+ self, inputs: SignalReportSummaryWorkflowInputs, log: FilteringBoundLogger+ ) -> FetchSignalsForReportOutput:+ fetch_input = FetchSignalsForReportInput(team_id=inputs.team_id, report_id=inputs.report_id)+ fetch_result: FetchSignalsForReportOutput = await workflow.execute_activity(+ fetch_signals_for_report_activity,+ fetch_input,+ start_to_close_timeout=timedelta(minutes=5),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ # patched(): histories recorded before the retry loop have no timers to replay.+ if fetch_result.signals or not workflow.patched("signals-empty-fetch-retry"):+ return fetch_result+ for attempt in range(1, EMPTY_FETCH_RETRY_ATTEMPTS + 1):+ log.info("No signals visible in ClickHouse yet, retrying fetch", attempt=attempt)+ await workflow.sleep(EMPTY_FETCH_RETRY_INTERVAL)+ fetch_result = await workflow.execute_activity(+ fetch_signals_for_report_activity,+ fetch_input,+ start_to_close_timeout=timedelta(minutes=5),+ retry_policy=RetryPolicy(maximum_attempts=3),+ )+ if fetch_result.signals:+ metrics.increment_report_fetch_recovered(attempt)+ return fetch_result+ return fetch_result+async def _run_once(self, inputs: SignalReportSummaryWorkflowInputs, log: FilteringBoundLogger) -> bool:"""Run a single report generation cycle. Returns True if new signals arrived and another cycle is needed."""# 0. Quota gate: a team whose org is over its self-driving credits quota gets no new research or PRs. The@@ -207,13 +241,21 @@ class SignalReportSummaryWorkflow:log.info("Report run paused: org over self-driving credits quota", stage="summary_entry")return False# 1. Fetch signals for the report- fetch_result: FetchSignalsForReportOutput = await workflow.execute_activity(- fetch_signals_for_report_activity,- FetchSignalsForReportInput(team_id=inputs.team_id, report_id=inputs.report_id),- start_to_close_timeout=timedelta(minutes=5),- retry_policy=RetryPolicy(maximum_attempts=3),- )+ fetch_result = await self._fetch_signals(inputs, log)if not fetch_result.signals:+ # patched(): same marker as the retry loop, so pre-patch histories replay straight to failure.+ if workflow.patched("signals-empty-fetch-retry") and await workflow.execute_activity(+ report_has_assigned_signals_activity,+ ReportHasAssignedSignalsInput(team_id=inputs.team_id, report_id=inputs.report_id),+ start_to_close_timeout=timedelta(minutes=1),+ retry_policy=RetryPolicy(maximum_attempts=3),+ ):+ # Signals are assigned in Postgres but not yet readable in ClickHouse. Failing here+ # would be terminal, so leave the report as it is: grouping re-promotes a candidate+ # on the next matching signal, and that run sees the rows.+ log.warning("Report has assigned signals that are not yet visible in ClickHouse, deferring run")+ metrics.increment_report_run_deferred("signals_not_visible")+ return Falselog.error("No signals found for report, marking as failed")await workflow.execute_activity(mark_report_failed_activity,@@ -503,6 +545,23 @@ async def check_report_quota_gate_activity(input: CheckReportQuotaGateInput) ->return False+@frozen+class ReportHasAssignedSignalsInput:+ team_id: int+ report_id: str+++@scoped_temporal()+@close_db_connections+async def report_has_assigned_signals_activity(input: ReportHasAssignedSignalsInput) -> bool:+ """Whether grouping has assigned any signal to the report. Postgres `signal_count` is written at+ assignment time, before the signal reaches ClickHouse, so it tells an ingestion-lag empty fetch+ apart from a report that genuinely has nothing to research.+ """+ return await SignalReport.objects.filter(id=input.report_id, team_id=input.team_id, signal_count__gt=0).aexists()++@dataclassclass RevertReportToCandidateInput:team_id: intdiff --git a/products/signals/backend/test/test_summary_quota_gate.py b/products/signals/backend/test/test_summary_workflow.pysimilarity index 74%rename from products/signals/backend/test/test_summary_quota_gate.pyrename to products/signals/backend/test/test_summary_workflow.pyindex 903f81a7f13e..a447d5208f02 100644--- a/products/signals/backend/test/test_summary_quota_gate.py+++ b/products/signals/backend/test/test_summary_workflow.py@@ -25,25 +25,28 @@ from products.signals.backend.temporal.agentic.select_repository import SelectRefrom products.signals.backend.temporal.report_safety_judge import SafetyJudgeInput, SafetyJudgeOutputfrom products.signals.backend.temporal.signal_queries import FetchSignalsForReportInput, FetchSignalsForReportOutputfrom products.signals.backend.temporal.summary import (+ EMPTY_FETCH_RETRY_ATTEMPTS,CheckReportQuotaGateInput,MarkReportFailedInput,MarkReportInProgressInput,+ ReportHasAssignedSignalsInput,ResetReportToPotentialInput,RevertReportToCandidateInput,SignalReportSummaryWorkflow,check_report_quota_gate_activity,+ report_has_assigned_signals_activity,revert_report_to_candidate_activity,)from products.signals.backend.temporal.types import SignalData, SignalReportSummaryWorkflowInputsSUMMARY_MODULE_PATH = "products.signals.backend.temporal.summary"-TASK_QUEUE = "test-summary-quota-queue"+TASK_QUEUE = "test-summary-workflow-queue"@pytest_asyncio.fixtureasync def aorganization():organization = await sync_to_async(Organization.objects.create)(- name=f"SelfDrivingSummaryQuotaOrg-{random.randint(1, 99999)}",+ name=f"SummaryWorkflowOrg-{random.randint(1, 99999)}",)yield organizationawait sync_to_async(organization.delete)()@@ -53,7 +56,7 @@ async def aorganization():async def ateam(aorganization):team = await sync_to_async(Team.objects.create)(organization=aorganization,- name=f"SelfDrivingSummaryQuotaTeam-{random.randint(1, 99999)}",+ name=f"SummaryWorkflowTeam-{random.randint(1, 99999)}",)yield teamawait sync_to_async(team.delete)()@@ -143,10 +146,20 @@ async def test_revert_noops_when_report_is_not_in_progress(ateam, status):class _Recorder:- def __init__(self, gate_answers: dict[str, bool]) -> None:- self.gate_answers = gate_answers+ def __init__(+ self,+ gate_answers: dict[str, bool] | None = None,+ # Signals returned by successive fetches; the last entry repeats once exhausted.+ fetch_results: list[list[SignalData]] | None = None,+ has_assigned_signals: bool = True,+ ) -> None:+ self.gate_answers = gate_answers or {}+ self.fetch_results = fetch_results or [[_signal_data()]]+ self.has_assigned_signals = has_assigned_signalsself.gate_checks: list[str] = []self.fetches = 0+ self.assigned_signal_checks = 0+ self.failure_reasons: list[str | None] = []self.marks_in_progress = 0self.safety_checks = 0self.repo_selections = 0@@ -176,8 +189,14 @@ async def _run_summary_workflow(recorder: _Recorder) -> None:@activity.defn(name="fetch_signals_for_report_activity")async def fake_fetch(input: FetchSignalsForReportInput) -> FetchSignalsForReportOutput:+ signals = recorder.fetch_results[min(recorder.fetches, len(recorder.fetch_results) - 1)]recorder.fetches += 1- return FetchSignalsForReportOutput(signals=[_signal_data()])+ return FetchSignalsForReportOutput(signals=signals)++ @activity.defn(name="report_has_assigned_signals_activity")+ async def fake_has_assigned_signals(input: ReportHasAssignedSignalsInput) -> bool:+ recorder.assigned_signal_checks += 1+ return recorder.has_assigned_signals@activity.defn(name="mark_report_in_progress_activity")async def fake_mark_in_progress(input: MarkReportInProgressInput) -> None:@@ -218,6 +237,7 @@ async def _run_summary_workflow(recorder: _Recorder) -> None:@activity.defn(name="mark_report_failed_activity")async def fake_failed(input: MarkReportFailedInput) -> None:recorder.failures += 1+ recorder.failure_reasons.append(input.failure_reason)# The production self-driving worker runs with the pydantic data converter; the default converter# mangles the enum/pydantic payloads these activities exchange (RepoSelectionResult,@@ -230,6 +250,7 @@ async def _run_summary_workflow(recorder: _Recorder) -> None:activities=[fake_quota,fake_fetch,+ fake_has_assigned_signals,fake_mark_in_progress,fake_safety,fake_select_repo,@@ -244,7 +265,7 @@ async def _run_summary_workflow(recorder: _Recorder) -> None:env.client.execute_workflow(SignalReportSummaryWorkflow.run,SignalReportSummaryWorkflowInputs(team_id=1, report_id=str(uuid.uuid4())),- id=f"summary-quota-{uuid.uuid4()}",+ id=f"summary-workflow-{uuid.uuid4()}",task_queue=TASK_QUEUE,),timeout=30,@@ -284,3 +305,60 @@ async def test_open_gates_let_the_run_flow_through():assert recorder.researches == 1assert recorder.reverts == 0assert recorder.failures == 0+++# ---------------------------------------------------------------------------+# Empty fetch: ClickHouse lag must not fail a report that has signals assigned+# ---------------------------------------------------------------------------+++async def test_empty_first_fetch_is_retried_and_run_proceeds():+ recorder = _Recorder(fetch_results=[[], [], [_signal_data()]])+ await _run_summary_workflow(recorder)+ assert recorder.fetches == 3+ assert recorder.researches == 1+ assert recorder.failures == 0+ assert recorder.assigned_signal_checks == 0+++async def test_persistently_empty_fetch_leaves_report_for_repromotion_when_signals_are_assigned():+ recorder = _Recorder(fetch_results=[[]], has_assigned_signals=True)+ await _run_summary_workflow(recorder)+ assert recorder.fetches == 1 + EMPTY_FETCH_RETRY_ATTEMPTS+ assert recorder.assigned_signal_checks == 1+ # Neither researched nor failed: the report stays where it is and grouping re-promotes it.+ assert recorder.marks_in_progress == 0+ assert recorder.researches == 0+ assert recorder.failures == 0+++async def test_persistently_empty_fetch_fails_report_with_no_assigned_signals():+ recorder = _Recorder(fetch_results=[[]], has_assigned_signals=False)+ await _run_summary_workflow(recorder)+ assert recorder.fetches == 1 + EMPTY_FETCH_RETRY_ATTEMPTS+ assert recorder.researches == 0+ assert recorder.failure_reasons == ["no_signals_found"]+++# ---------------------------------------------------------------------------+# report_has_assigned_signals_activity+# ---------------------------------------------------------------------------++[email protected]("signal_count,expected", [(0, False), (1, True)])+async def test_report_has_assigned_signals_reads_postgres_signal_count(ateam, signal_count, expected):+ report = await database_sync_to_async(SignalReport.objects.create)(+ team=ateam,+ status=SignalReport.Status.CANDIDATE,+ total_weight=1.0,+ signal_count=signal_count,+ )+ result = await report_has_assigned_signals_activity(+ ReportHasAssignedSignalsInput(team_id=ateam.id, report_id=str(report.id))+ )+ assert result is expected