: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): use recently-seen store to gate ClickHouse wait polling (#68885)
Oliver Browne225125a7d72c
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex b79c2b858c68..ec7994fff190 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -730,7 +730,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`): polls for all 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 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`.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/deletion.py b/products/signals/backend/temporal/deletion.pyindex 9cd9b40d745f..9f4a73eb234a 100644--- a/products/signals/backend/temporal/deletion.py+++ b/products/signals/backend/temporal/deletion.py@@ -17,6 +17,7 @@ from products.signals.backend.temporal.signal_queries import (FetchSignalsForReportInput,FetchSignalsForReportOutput,WaitForClickHouseInput,+ WaitForClickHouseMode,WaitForClickHouseSignal,fetch_signals_for_report_activity,wait_for_signal_in_clickhouse_activity,@@ -94,10 +95,14 @@ class SignalReportDeletionWorkflow:WaitForClickHouseSignal(signal_id=s.signal_id,timestamp=s.timestamp,+ inserted_at=s.inserted_at,)for s in fetch_result.signals],max_wait_time_seconds=3600,+ # The report is soft-deleted either way; briefly-stale signal rows in+ # semantic search are acceptable, so don't burn ClickHouse queries here.+ mode=WaitForClickHouseMode.OPTIMISTIC,),start_to_close_timeout=timedelta(hours=1, minutes=5),heartbeat_timeout=timedelta(minutes=2),diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.pyindex beb84d1570ae..374b9e7652df 100644--- a/products/signals/backend/temporal/grouping.py+++ b/products/signals/backend/temporal/grouping.py@@ -39,6 +39,9 @@ from products.signals.backend.temporal import metricsfrom products.signals.backend.temporal.drop_telemetry import capture_signal_droppedfrom products.signals.backend.temporal.llm import MAX_QUERY_TOKENS, call_llm, truncate_query_to_token_limitfrom products.signals.backend.temporal.signal_queries import (+ SIGNAL_DOCUMENT_PRODUCT,+ SIGNAL_DOCUMENT_RENDERING,+ SIGNAL_DOCUMENT_TYPE,FetchSignalsForReportInput,FetchSignalsForReportOutput,FetchSignalTypeExamplesInput,@@ -46,6 +49,7 @@ from products.signals.backend.temporal.signal_queries import (RunSignalSemanticSearchInput,RunSignalSemanticSearchOutput,WaitForClickHouseInput,+ WaitForClickHouseMode,WaitForClickHouseSignal,fetch_signal_type_examples_activity,fetch_signals_for_report_activity,@@ -736,9 +740,9 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> Asemit_embedding_request(content=input.description,team_id=input.team_id,- product="signals",- document_type="signal",- rendering="plain",+ product=SIGNAL_DOCUMENT_PRODUCT,+ document_type=SIGNAL_DOCUMENT_TYPE,+ rendering=SIGNAL_DOCUMENT_RENDERING,document_id=input.signal_id,models=[m.value for m in EmbeddingModelName],timestamp=ts,@@ -853,9 +857,9 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> Asemit_embedding_request(content=input.description,team_id=input.team_id,- product="signals",- document_type="signal",- rendering="plain",+ product=SIGNAL_DOCUMENT_PRODUCT,+ document_type=SIGNAL_DOCUMENT_TYPE,+ rendering=SIGNAL_DOCUMENT_RENDERING,document_id=input.signal_id,models=[m.value for m in EmbeddingModelName],timestamp=ts,@@ -1385,6 +1389,9 @@ 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,),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 4c734ec91198..f8600d023de8 100644--- a/products/signals/backend/temporal/metrics.py+++ b/products/signals/backend/temporal/metrics.py@@ -76,6 +76,36 @@ def increment_ch_wait_timeout() -> None:).add(1)+def increment_recently_seen_lookup(result: str) -> None:+ """Count recently-seen cache lookups by result."""+ if not _in_temporal_context():+ return+ get_metric_meter({"result": result}).create_counter(+ "signals_recently_seen_lookups_total",+ "Recently-seen cache lookups by result",+ ).add(1)+++def increment_ch_wait_query(mode: str, reason: str) -> None:+ """Count ClickHouse confirmation queries by wait mode and reason."""+ if not _in_temporal_context():+ return+ get_metric_meter({"mode": mode, "reason": reason}).create_counter(+ "signals_ch_wait_queries_total",+ "ClickHouse confirmation queries issued by signals waits",+ ).add(1)+++def increment_ch_wait_completion(mode: str, result: str) -> None:+ """Count wait completions by mode and completion path."""+ if not _in_temporal_context():+ return+ get_metric_meter({"mode": mode, "result": result}).create_counter(+ "signals_ch_wait_completions_total",+ "Signals consistency waits by completion result",+ ).add(1)++def increment_research_run_collapsed() -> None:"""Count a promotion that folded into an already-running research workflow instead of its own run.diff --git a/products/signals/backend/temporal/reingestion.py b/products/signals/backend/temporal/reingestion.pyindex 4abbc472fa88..83ee31b48cc0 100644--- a/products/signals/backend/temporal/reingestion.py+++ b/products/signals/backend/temporal/reingestion.py@@ -26,9 +26,13 @@ from products.signals.backend.temporal.clickhouse import execute_hogql_query_witfrom products.signals.backend.temporal.grouping_v2 import TeamSignalGroupingV2Workflowfrom products.signals.backend.temporal.signal_queries import (_DEDUPED_SIGNALS_SUBQUERY,+ SIGNAL_DOCUMENT_PRODUCT,+ SIGNAL_DOCUMENT_RENDERING,+ SIGNAL_DOCUMENT_TYPE,FetchSignalsForReportInput,FetchSignalsForReportOutput,WaitForClickHouseInput,+ WaitForClickHouseMode,WaitForClickHouseSignal,_ensure_tz_aware,fetch_signals_for_report_activity,@@ -176,7 +180,8 @@ async def process_team_signals_batch_activity(input: ProcessTeamSignalsBatchInpudocument_id,content,metadata,- timestamp+ timestamp,+ latest_inserted_atFROM ({_DEDUPED_SIGNALS_SUBQUERY})WHERE NOT JSONExtractBool(metadata, 'deleted')ORDER BY timestamp DESC, document_id DESC@@ -191,7 +196,7 @@ async def process_team_signals_batch_activity(input: ProcessTeamSignalsBatchInpusignals: list[SignalData] = []for row in result.results or []:- document_id, content, metadata_str, timestamp_raw = row+ document_id, content, metadata_str, timestamp_raw, inserted_at_raw = rowmetadata = json.loads(metadata_str)signals.append(SignalData(@@ -202,6 +207,7 @@ async def process_team_signals_batch_activity(input: ProcessTeamSignalsBatchInpusource_id=metadata.get("source_id", ""),weight=metadata.get("weight", 0.0),timestamp=_ensure_tz_aware(timestamp_raw),+ inserted_at=_ensure_tz_aware(inserted_at_raw),extra=metadata.get("extra", {}),remediation=metadata.get("remediation"),metadata=dict(metadata),@@ -224,9 +230,9 @@ async def process_team_signals_batch_activity(input: ProcessTeamSignalsBatchInpuawait sync_to_async(emit_embedding_request, thread_sensitive=False)(content=signal.content,team_id=input.team_id,- product="signals",- document_type="signal",- rendering="plain",+ product=SIGNAL_DOCUMENT_PRODUCT,+ document_type=SIGNAL_DOCUMENT_TYPE,+ rendering=SIGNAL_DOCUMENT_RENDERING,document_id=signal.signal_id,models=[m.value for m in EmbeddingModelName],timestamp=signal.timestamp,@@ -248,9 +254,17 @@ async def process_team_signals_batch_activity(input: ProcessTeamSignalsBatchInpuWaitForClickHouseInput(team_id=input.team_id,signals=[- WaitForClickHouseSignal(signal_id=signal.signal_id, timestamp=signal.timestamp) for signal in signals+ WaitForClickHouseSignal(+ signal_id=signal.signal_id,+ timestamp=signal.timestamp,+ inserted_at=signal.inserted_at,+ )+ for signal in signals],max_wait_time_seconds=3600,+ # Bulk reprocessing is non-interactive: let the store gate the polling, but+ # confirm in ClickHouse before the next batch re-reads these rows.+ mode=WaitForClickHouseMode.CH_CONFIRMED,))@@ -388,10 +402,12 @@ class SignalReportReingestionWorkflow:WaitForClickHouseSignal(signal_id=s.signal_id,timestamp=s.timestamp,+ inserted_at=s.inserted_at,)for s in fetch_result.signals],max_wait_time_seconds=3600,+ mode=WaitForClickHouseMode.CH_CONFIRMED,),start_to_close_timeout=timedelta(hours=1, minutes=5),heartbeat_timeout=timedelta(minutes=5),diff --git a/products/signals/backend/temporal/signal_queries.py b/products/signals/backend/temporal/signal_queries.pyindex f564f54f2500..90f5ac61aa5b 100644--- a/products/signals/backend/temporal/signal_queries.py+++ b/products/signals/backend/temporal/signal_queries.py@@ -2,6 +2,7 @@ import jsonimport asynciofrom dataclasses import dataclassfrom datetime import UTC, datetime, timedelta+from enum import StrEnumfrom typing import Unionimport structlog@@ -12,7 +13,7 @@ from posthog.schema import EmbeddingModelNamefrom posthog.hogql import astfrom posthog.hogql.query import execute_hogql_query-from posthog.api.embedding_worker import emit_embedding_request+from posthog.api.embedding_worker import DocumentKey, async_get_recently_seen_documents, emit_embedding_requestfrom posthog.clickhouse.query_tagging import Feature, Product, tag_queriesfrom posthog.models import Teamfrom posthog.temporal.common.scoped import scoped_temporal@@ -28,6 +29,23 @@ logger = structlog.get_logger(__name__)WAIT_POLL_INTERVAL_SECONDS = 10+# Every signal document is emitted under this key triple — the recently-seen lookup in+# wait_for_signal_in_clickhouse_activity relies on exact key equality with the emit sites.+SIGNAL_DOCUMENT_PRODUCT = "signals"+SIGNAL_DOCUMENT_TYPE = "signal"+SIGNAL_DOCUMENT_RENDERING = "plain"++# For this long, ClickHouse is polled only when the recently-seen store confirms the+# emission (or on the final attempt) — the wait is store-exclusive to keep ClickHouse+# load off the polling path. After it, ClickHouse also polls on the fallback cadence+# below, because the store is best-effort (writes never block ingestion, and the+# in-memory backend is per-pod), so a negative answer can't gate ClickHouse forever.+CH_CONFIRM_GRACE_PERIOD_SECONDS = 300++# Fallback cadence once the grace period has elapsed without store confirmation: the+# store keeps polling every attempt, ClickHouse only every Nth — 3x fewer CH queries.+CH_CONFIRM_EVERY_N_ATTEMPTS = 3+def _ensure_tz_aware(value: Union[datetime, str]) -> datetime:"""Coerce a ClickHouse timestamp (usually a datetime, occasionally a string) to a tz-aware datetime."""@@ -68,7 +86,7 @@ def _deduped_signals_subquery(]if include_embedding:selected_columns.append("argMax(embedding, inserted_at) as embedding")- selected_columns.append("argMax(timestamp, inserted_at) as timestamp")+ selected_columns.extend(["argMax(timestamp, inserted_at) as timestamp", "max(inserted_at) as latest_inserted_at"])selected_columns_sql = ",\n ".join(selected_columns)if extra_where:@@ -142,7 +160,8 @@ def _signals_for_report_query(*, include_deleted: bool = False, limit: int | Nondocument_id,content,metadata,- timestamp+ timestamp,+ latest_inserted_atFROM ({_deduped_signals_subquery(candidate_document_filter="JSONExtractString(metadata, 'report_id') = {report_id}")})WHERE JSONExtractString(metadata, 'report_id') = {{report_id}}{deleted_filter}ORDER BY timestamp ASC{limit_clause}@@ -157,8 +176,8 @@ def _report_placeholders(report_id: str) -> dict:def _parse_signal_row(row: tuple) -> SignalData:- """Turn a (document_id, content, metadata_str, timestamp) row into a SignalData."""- document_id, content, metadata_str, timestamp_raw = row+ """Turn a ClickHouse document embedding row into a SignalData."""+ document_id, content, metadata_str, timestamp_raw, inserted_at_raw = rowtimestamp_raw = _ensure_tz_aware(timestamp_raw)# Purposefully throw here if we fail - we rely on metadata being correct, and it's not llm generated, so# no defensive parsing, we want to fail loudly.@@ -171,6 +190,7 @@ def _parse_signal_row(row: tuple) -> SignalData:source_id=metadata.get("source_id", ""),weight=metadata.get("weight", 0.0),timestamp=timestamp_raw,+ inserted_at=_ensure_tz_aware(inserted_at_raw),extra=metadata.get("extra", {}),remediation=metadata.get("remediation"),)@@ -197,16 +217,16 @@ def soft_delete_report_signals(report_id: str, team_id: int, team: Team) -> None)for row in result.results or []:- document_id, content, metadata_str, timestamp_raw = row+ document_id, content, metadata_str, timestamp_raw, _inserted_at_raw = rowmetadata = json.loads(metadata_str)metadata["deleted"] = Trueemit_embedding_request(content=content,team_id=team_id,- product="signals",- document_type="signal",- rendering="plain",+ product=SIGNAL_DOCUMENT_PRODUCT,+ document_type=SIGNAL_DOCUMENT_TYPE,+ rendering=SIGNAL_DOCUMENT_RENDERING,document_id=document_id,models=[m.value for m in EmbeddingModelName],timestamp=_ensure_tz_aware(timestamp_raw),@@ -385,6 +405,24 @@ async def run_signal_semantic_search_activity(input: RunSignalSemanticSearchInpuclass WaitForClickHouseSignal:signal_id: strtimestamp: datetime+ inserted_at: datetime | None = None+++class WaitForClickHouseMode(StrEnum):+ """How much the wait trusts the recently-seen store vs ClickHouse.++ OPTIMISTIC: return as soon as the store confirms the emission, without querying+ ClickHouse at all — cheapest and fastest, but blind to the Kafka-to-ClickHouse+ insert gap. ClickHouse still polls on the post-grace fallback cadence when the+ store never confirms.++ CH_CONFIRMED: a store confirmation triggers an immediate ClickHouse confirm, and+ ClickHouse stays authoritative — the store only decides when to start querying.++ """++ OPTIMISTIC = "optimistic"+ CH_CONFIRMED = "ch_confirmed"@dataclass@@ -392,18 +430,73 @@ class WaitForClickHouseInput:team_id: intsignals: list[WaitForClickHouseSignal]max_wait_time_seconds: int = 3600+ mode: WaitForClickHouseMode = WaitForClickHouseMode.CH_CONFIRMED+++async def _all_signals_recently_seen(team_id: int, signals: list[WaitForClickHouseSignal]) -> bool:+ """Check the embedding worker's recently-seen store for every signal's emission.++ True only when each document is present and, when its current ClickHouse inserted_at+ is known, the worker emitted it after that version. False on any miss, stale record,+ or store error.++ A True result is not proof of ClickHouse visibility: "seen" means committed to the+ output Kafka topic. WaitForClickHouseMode decides how much the caller trusts it.+ """+ documents = [+ DocumentKey(+ product=SIGNAL_DOCUMENT_PRODUCT,+ document_type=SIGNAL_DOCUMENT_TYPE,+ rendering=SIGNAL_DOCUMENT_RENDERING,+ document_id=s.signal_id,+ )+ for s in signals+ ]+ try:+ seen = await async_get_recently_seen_documents(documents, team_id=team_id)+ except Exception:+ metrics.increment_recently_seen_lookup("error")+ logger.warning(+ "Recently-seen lookup failed; scheduled ClickHouse fallback remains active",+ team_id=team_id,+ exc_info=True,+ )+ return False++ for document, signal in zip(documents, signals):+ emitted_at = seen.get(document)+ if emitted_at is None:+ metrics.increment_recently_seen_lookup("pending")+ return False+ if signal.inserted_at is not None and emitted_at <= _ensure_tz_aware(signal.inserted_at):+ metrics.increment_recently_seen_lookup("pending")+ return False+ metrics.increment_recently_seen_lookup("confirmed")+ return True@temporalio.activity.defn@scoped_temporal()@close_db_connectionsasync def wait_for_signal_in_clickhouse_activity(input: WaitForClickHouseInput) -> None:- """Poll ClickHouse until all emitted signals appear, or give up after max_wait_time_seconds.-- Filters on inserted_at >= (now - 30 minutes) to avoid matching stale rows from a- previous emission of the same document_id (e.g. deleted then reingested). The window- is generous because signals are emitted during the sequential phase before this- activity starts, so early signals may already be minutes old.+ """Wait until all emitted signals are processed, or give up after max_wait_time_seconds.++ Two-tier poll, tuned by input.mode (see WaitForClickHouseMode). Every attempt checks+ the embedding worker's recently-seen store (a cheap key-value lookup): a store+ confirmation ends the wait outright in OPTIMISTIC mode, or triggers the ClickHouse+ confirmation query in CH_CONFIRMED mode. For the first+ CH_CONFIRM_GRACE_PERIOD_SECONDS the wait is otherwise store-exclusive; after that,+ ClickHouse also polls on every CH_CONFIRM_EVERY_N_ATTEMPTS-th attempt (a third of+ the store's rate) as a fallback for when the store is lossy, plus once on the+ final attempt before giving up. The store only tracks the worker's Kafka commit,+ which precedes the ClickHouse insert — modes trade that gap against ClickHouse+ load.++ The ClickHouse query filters on inserted_at >= (now - 30 minutes) to avoid matching+ stale rows from a previous emission of the same document_id (e.g. deleted then+ reingested). The window is generous because signals are emitted during the+ sequential phase before this activity starts, so early signals may already be+ minutes old."""if not input.signals:return@@ -443,29 +536,57 @@ async def wait_for_signal_in_clickhouse_activity(input: WaitForClickHouseInput)expected_count = len(signal_ids)+ store_confirmed = Falsefor attempt in range(max_attempts):temporalio.activity.heartbeat(attempt)- result = await execute_hogql_query_with_retry(- query_type="SignalsWaitForClickHouse",- query=query,- team=team,- placeholders=placeholders,- heartbeat_fn=temporalio.activity.heartbeat,+ if not store_confirmed:+ store_confirmed = await _all_signals_recently_seen(input.team_id, input.signals)+ if store_confirmed:+ logger.debug(+ f"Recently-seen store confirmed all {expected_count} signal(s) after {attempt + 1} attempt(s)",+ signal_ids=signal_ids,+ team_id=input.team_id,+ )+ if input.mode == WaitForClickHouseMode.OPTIMISTIC:+ metrics.increment_ch_wait_completion(input.mode.value, "recently_seen")+ return++ past_grace_period = attempt * WAIT_POLL_INTERVAL_SECONDS >= CH_CONFIRM_GRACE_PERIOD_SECONDS+ ch_confirm_due = (+ store_confirmed+ or (past_grace_period and attempt % CH_CONFIRM_EVERY_N_ATTEMPTS == CH_CONFIRM_EVERY_N_ATTEMPTS - 1)+ or attempt == max_attempts - 1)+ if ch_confirm_due:+ if store_confirmed:+ query_reason = "store_confirmed"+ elif attempt == max_attempts - 1:+ query_reason = "final"+ else:+ query_reason = "fallback"+ metrics.increment_ch_wait_query(input.mode.value, query_reason)+ result = await execute_hogql_query_with_retry(+ query_type="SignalsWaitForClickHouse",+ query=query,+ team=team,+ placeholders=placeholders,+ heartbeat_fn=temporalio.activity.heartbeat,+ )- # Heartbeat immediately after the query completes — the query itself runs in- # sync_to_async and can't heartbeat during execution, so this ensures we don't- # hit the heartbeat timeout when queries are slow.- temporalio.activity.heartbeat(attempt)+ # Heartbeat immediately after the query completes — the query itself runs in+ # sync_to_async and can't heartbeat during execution, so this ensures we don't+ # hit the heartbeat timeout when queries are slow.+ temporalio.activity.heartbeat(attempt)- if result.results and result.results[0][0] >= expected_count:- logger.debug(- f"All {expected_count} signal(s) found in ClickHouse after {attempt + 1} attempt(s)",- signal_ids=signal_ids,- team_id=input.team_id,- )- return+ if result.results and result.results[0][0] >= expected_count:+ logger.debug(+ f"All {expected_count} signal(s) found in ClickHouse after {attempt + 1} attempt(s)",+ signal_ids=signal_ids,+ team_id=input.team_id,+ )+ metrics.increment_ch_wait_completion(input.mode.value, "clickhouse")+ return# Sleep in chunks so we keep heartbeating during the poll intervalremaining = WAIT_POLL_INTERVAL_SECONDS@@ -476,6 +597,7 @@ async def wait_for_signal_in_clickhouse_activity(input: WaitForClickHouseInput)temporalio.activity.heartbeat(attempt)metrics.increment_ch_wait_timeout()+ metrics.increment_ch_wait_completion(input.mode.value, "timeout")logger.warning(f"Not all signals found in ClickHouse after {input.max_wait_time_seconds}s, proceeding anyway",signal_ids=signal_ids,@@ -543,7 +665,7 @@ def fetch_signals_for_report_sync(team: Team, report_id: str) -> list[dict]:signals_list = []for row in result.results or []:- document_id, content, metadata_str, timestamp = row+ document_id, content, metadata_str, timestamp, _inserted_at = rowmetadata = json.loads(metadata_str)signals_list.append({diff --git a/products/signals/backend/temporal/types.py b/products/signals/backend/temporal/types.pyindex 8aafa67daf2e..301c831093d0 100644--- a/products/signals/backend/temporal/types.py+++ b/products/signals/backend/temporal/types.py@@ -189,7 +189,10 @@ class SignalTypeExample:@dataclassclass SignalData:- """Data about a signal fetched from ClickHouse."""+ """Normalized signal data used by report workflows.++ ClickHouse-backed instances include `inserted_at`; synthetic or adapted instances may omit it.+ """signal_id: strcontent: str@@ -198,6 +201,7 @@ class SignalData:source_id: strweight: floattimestamp: datetime+ inserted_at: Optional[datetime] = Noneextra: dict = field(default_factory=dict)metadata: dict[str, Any] = field(default_factory=dict)# Optional fix guidance (separate from `extra`); see EmitSignalInputs.remediation.diff --git a/products/signals/backend/test/test_wait_for_signal_in_clickhouse.py b/products/signals/backend/test/test_wait_for_signal_in_clickhouse.pynew file mode 100644index 000000000000..35e4db4c3707--- /dev/null+++ b/products/signals/backend/test/test_wait_for_signal_in_clickhouse.py@@ -0,0 +1,163 @@+import uuid+from datetime import timedelta+from types import SimpleNamespace++import pytest+from unittest.mock import AsyncMock, MagicMock, patch++from django.utils import timezone++from temporalio.testing import ActivityEnvironment++from products.signals.backend.temporal.signal_queries import (+ WaitForClickHouseInput,+ WaitForClickHouseMode,+ WaitForClickHouseSignal,+ wait_for_signal_in_clickhouse_activity,+)++MODULE = "products.signals.backend.temporal.signal_queries"++TEAM_ID = 1+++def _signals(count: int, *, include_inserted_at: bool = True) -> list[WaitForClickHouseSignal]:+ now = timezone.now()+ return [+ WaitForClickHouseSignal(+ signal_id=str(uuid.uuid4()),+ timestamp=now,+ inserted_at=now if include_inserted_at else None,+ )+ for _ in range(count)+ ]+++def _ch_result(count: int) -> SimpleNamespace:+ return SimpleNamespace(results=[[count]])+++def _store_returning(offset: timedelta | None):+ # Answers the lookup relative to the document's expected inserted_at+ # (None means "never emitted" for every document).+ async def lookup(documents, *, team_id):+ if offset is None:+ return dict.fromkeys(documents)+ return {d: timezone.now() + offset for d in documents}++ return lookup+++async def _store_raising(documents, *, team_id):+ raise RuntimeError("worker down")+++def _team_model_mock() -> MagicMock:+ team = MagicMock(name="Team")+ team.objects.aget = AsyncMock(return_value=MagicMock(pk=TEAM_ID))+ return team+++async def _run(+ signals: list[WaitForClickHouseSignal],+ max_wait_time_seconds: int = 600,+ mode: WaitForClickHouseMode = WaitForClickHouseMode.CH_CONFIRMED,+) -> None:+ env = ActivityEnvironment()+ await env.run(+ wait_for_signal_in_clickhouse_activity,+ WaitForClickHouseInput(+ team_id=TEAM_ID, signals=signals, max_wait_time_seconds=max_wait_time_seconds, mode=mode+ ),+ )+++ "mode,expected_ch_queries",+ [+ pytest.param(WaitForClickHouseMode.OPTIMISTIC, 0, id="optimistic_trusts_store_and_skips_clickhouse"),+ pytest.param(WaitForClickHouseMode.CH_CONFIRMED, 1, id="ch_confirmed_runs_single_confirm"),+ ],+)+async def test_store_confirmation_short_circuits(mode, expected_ch_queries):+ signals = _signals(2)+ with (+ patch(f"{MODULE}.Team", _team_model_mock()),+ patch(f"{MODULE}.async_get_recently_seen_documents", side_effect=_store_returning(timedelta(0))) as store,+ patch(f"{MODULE}.execute_hogql_query_with_retry", AsyncMock(return_value=_ch_result(2))) as ch,+ patch(f"{MODULE}.asyncio.sleep", AsyncMock()) as sleep,+ ):+ await _run(signals, mode=mode)++ # The store confirmed on the first attempt: optimistic mode must return without+ # touching ClickHouse at all, ch_confirmed with exactly one confirm query — and+ # neither should sleep through a poll interval.+ assert ch.await_count == expected_ch_queries+ assert store.call_count == 1+ assert sleep.await_count == 0+++async def test_signal_without_inserted_at_accepts_any_store_hit():+ signals = _signals(1, include_inserted_at=False)+ with (+ patch(f"{MODULE}.Team", _team_model_mock()),+ patch(f"{MODULE}.async_get_recently_seen_documents", side_effect=_store_returning(timedelta(days=-1))) as store,+ patch(f"{MODULE}.execute_hogql_query_with_retry", AsyncMock(return_value=_ch_result(1))) as ch,+ patch(f"{MODULE}.asyncio.sleep", AsyncMock()) as sleep,+ ):+ await _run(signals, mode=WaitForClickHouseMode.OPTIMISTIC)++ assert ch.await_count == 0+ assert store.call_count == 1+ assert sleep.await_count == 0+++ "store_behavior",+ [+ pytest.param(_store_returning(None), id="never_emitted"),+ pytest.param(_store_returning(timedelta(hours=-1)), id="stale_record_from_earlier_emission"),+ pytest.param(_store_raising, id="store_unavailable"),+ ],+)+async def test_unconfirmed_store_defers_clickhouse_until_grace_period_elapses(store_behavior):+ signals = _signals(1)+ with (+ patch(f"{MODULE}.Team", _team_model_mock()),+ patch(f"{MODULE}.async_get_recently_seen_documents", side_effect=store_behavior) as store,+ patch(f"{MODULE}.execute_hogql_query_with_retry", AsyncMock(return_value=_ch_result(1))) as ch,+ patch(f"{MODULE}.asyncio.sleep", AsyncMock()),+ patch(f"{MODULE}.metrics.increment_ch_wait_timeout") as timeout_metric,+ ):+ await _run(signals, max_wait_time_seconds=660)++ # The store never confirms, so ClickHouse must not be touched during the 5-minute+ # grace period, then must run on the every-3rd-attempt fallback — its positive+ # answer ends the wait. With 10s attempts the first eligible fallback is attempt 32+ # (>=300s elapsed and on cadence), so exactly 33 store polls precede the single+ # ClickHouse query; an early ClickHouse poll would return sooner and shrink the+ # store count, and a store-gated ClickHouse would never run and time out instead.+ assert ch.await_count == 1+ assert store.call_count == 33+ timeout_metric.assert_not_called()+++async def test_gives_up_after_max_wait_and_records_timeout():+ signals = _signals(1)+ with (+ patch(f"{MODULE}.Team", _team_model_mock()),+ patch(f"{MODULE}.async_get_recently_seen_documents", side_effect=_store_returning(None)),+ patch(f"{MODULE}.execute_hogql_query_with_retry", AsyncMock(return_value=_ch_result(0))) as ch,+ patch(f"{MODULE}.asyncio.sleep", AsyncMock()),+ patch(f"{MODULE}.metrics.increment_ch_wait_timeout") as timeout_metric,+ ):+ await _run(signals, max_wait_time_seconds=30)++ # A wait shorter than the grace period still checks ClickHouse once, on the final+ # attempt, before giving up and recording the timeout.+ assert ch.await_count == 1+ timeout_metric.assert_called_once()