: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): preserve refused signals for review after three attempts (#113689)
posthog[bot]20283a27840f
diff --git a/docs/internal/self-driving-temporal-worker-runbook.md b/docs/internal/self-driving-temporal-worker-runbook.mdindex 5b3a303f2ef3..ef41e8a2e5a0 100644--- a/docs/internal/self-driving-temporal-worker-runbook.md+++ b/docs/internal/self-driving-temporal-worker-runbook.md@@ -118,6 +118,38 @@ Do these steps in this order, so that no run is left without a worker.## Troubleshooting+### Signals blocked by query-generation refusals++Grouping runs on the video-export fleet. A model refusal during query generation can block the other signals in its stored batch.++The grouping activity allows three refusals per unchanged signal payload. It saves the refusal count in object storage between activity and batch retries. After the third refusal, it preserves the full signal under `signals/refusal_review/<team_id>/<payload_hash>.json`, with status `needs_review`. It removes that signal from grouping and processes the other signals. A later read of the same batch skips the saved signal without another model call. A successful retry clears the temporary refusal record. Other empty responses and transport errors still fail the activity.++Search worker logs for `signals_grouping.signal_preserved_for_review`. The log contains the team and object key, without the signal description. In an authorized production Django shell, use `posthog.storage.object_storage.read(object_key)` to read the record. The record contains private customer content. Do not copy it into a public issue or pull request. Storage lifecycle rules still apply to these records.++Check the saved signal's source, description, extra fields, and remediation before deciding whether to change it or leave it out.++Do not use the source's normal emission path to replay a saved signal. Some sources, for example pganalyze, record each emitted source ID and do not fetch it again. pganalyze also uses the source ID as the emitter idempotency key. `emit_signal()` returns without a new emitter when a completed emitter has the same key, even when the payload changed. To replay a saved signal, call `emit_signal()` directly in an authorized Django shell:++1. Read the record and take its `signal` object. Keep `source_product`, `source_type`, and `source_id` unchanged, so that the signal stays linked to its source.+2. Correct `description`, `extra`, or `remediation` if the review found a problem. A changed payload has a different hash, so it starts with a new refusal record.+3. If the payload is unchanged, delete the review record with `object_storage.delete(object_key)` before you emit. Otherwise grouping finds three saved refusals and skips the signal again without a model call.+4. Choose a new replay key, for example `<source_id>:refusal-replay:1`. Do not use the source ID or an earlier replay key.+5. Call `async_to_sync(emit_signal)(...)` from `products.signals.backend.facade.api`. Pass the team, the signal fields, `remediation=SignalRemediation.model_validate(...)` or `None`, and `idempotency_key=<replay key>`.+6. Make sure that a new emitter workflow exists. Get its ID with `SignalEmitterWorkflow.workflow_id_for(team_id, f"{source_product}:{source_type}:{replay_key}")`, then run `temporal workflow describe --workflow-id <id>`. `emit_signal()` returns nothing in every case. It also returns without an emitter when the organization has not approved AI data processing, the source is off, or team steering filters the signal.++Deleting the record alone does not put the signal back in the queue.++After deployment, an existing blocked grouping workflow adopts the new path on its next run after `continue_as_new`. Do not restart or terminate it to apply this change. Verify that review records appear, healthy signals reach assignment, and the waiting-batch count falls. A saved refusal does not prove that the rest of the pipeline recovered.++#### Before deployment++Do not pause grouping to remove signals from stored batches by hand.+The pause loop in `TeamSignalGroupingV2Workflow` does not catch the timeout of its 30-second wait.+A pause longer than 30 seconds fails the workflow.+The failed run loses its pending batch keys.+`unpause()` then starts a new run without those keys.+Deploy the automatic refusal path instead.+**Runs stay in `Running` with no activity progress.**No worker polls `self-driving-task-queue` in that region.Check the pod status of the charts release, then run check 1.diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.pyindex d75a94eb211c..9ae4c6fc06e2 100644--- a/products/signals/backend/temporal/grouping.py+++ b/products/signals/backend/temporal/grouping.py@@ -44,6 +44,7 @@ from products.signals.backend.signal_metadata import EMBEDDING_MODELfrom 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_limit+from products.signals.backend.temporal.refusal_review import generate_queries_or_preserve_refusalfrom products.signals.backend.temporal.signal_queries import (SIGNAL_DOCUMENT_PRODUCT,SIGNAL_DOCUMENT_RENDERING,@@ -178,6 +179,7 @@ class GenerateSearchQueriesInput:# Optional with a default so workflows mid-flight across a deploy (whose activity input was# serialized before this field existed) still deserialize; missing => gateway key owner's team.team_id: int | None = None+ signal: EmitSignalInputs | None = Noneasync def generate_search_queries(input: GenerateSearchQueriesInput) -> list[str]:@@ -208,9 +210,10 @@ async def generate_search_queries(input: GenerateSearchQueriesInput) -> list[str)-@dataclass+@frozenclass GenerateSearchQueriesOutput:queries: list[str]+ quarantined: bool = False@temporalio.activity.defn@@ -219,7 +222,13 @@ class GenerateSearchQueriesOutput:async def generate_search_queries_activity(input: GenerateSearchQueriesInput) -> GenerateSearchQueriesOutput:"""Use LLM to generate 1-3 search queries for finding related signals."""try:- queries = await generate_search_queries(input)+ queries: list[str] | None+ if input.signal is None:+ queries = await generate_search_queries(input)+ else:+ queries = await generate_queries_or_preserve_refusal(input.signal, lambda: generate_search_queries(input))+ if queries is None:+ return GenerateSearchQueriesOutput(queries=[], quarantined=True)logger.debug(f"Generated {len(queries)} search queries",source_product=input.source_product,@@ -1172,6 +1181,7 @@ async def _process_signal_batch(if not all(signal.team_id == team_id for signal in batch):raise ValueError("All signals in a batch must belong to the same team")dropped = 0+ isolate_refusals = workflow.patched("signals-query-refusal-review-v1")# === PARALLEL PHASE (steps 1-4) ===@@ -1189,6 +1199,20 @@ async def _process_signal_batch(# Step 1b: Embed all signals + generate search queries in parallel# (query gen needs type examples but NOT the signal embeddings)+ query_inputs = batch+ query_result_indices = list(range(len(batch)))+ if isolate_refusals:+ query_inputs = []+ query_result_indices = []+ payload_indices: dict[str, int] = {}+ # Duplicate payloads must share a query activity so their refusal counts cannot race.+ for signal in batch:+ payload = json.dumps(asdict(signal), sort_keys=True)+ if payload not in payload_indices:+ payload_indices[payload] = len(query_inputs)+ query_inputs.append(signal)+ query_result_indices.append(payload_indices[payload])+step1b_results = await asyncio.gather(*[workflow.execute_activity(@@ -1208,15 +1232,26 @@ async def _process_signal_batch(source_product=s.source_product,source_type=s.source_type,signal_type_examples=type_examples_result.examples,+ signal=s if isolate_refusals else None,),start_to_close_timeout=timedelta(minutes=10),retry_policy=RetryPolicy(maximum_attempts=5),)- for s in batch+ for s in query_inputs],)signal_embeddings = cast(list[GenerateEmbeddingOutput], step1b_results[: len(batch)])- query_gen_results = cast(list[GenerateSearchQueriesOutput], step1b_results[len(batch) :])+ query_outputs = cast(list[GenerateSearchQueriesOutput], step1b_results[len(batch) :])+ query_gen_results = [query_outputs[i] for i in query_result_indices]++ if isolate_refusals:+ retained_indices = [i for i, result in enumerate(query_gen_results) if not result.quarantined]+ dropped = len(batch) - len(retained_indices)+ batch = [batch[i] for i in retained_indices]+ signal_embeddings = [signal_embeddings[i] for i in retained_indices]+ query_gen_results = [query_gen_results[i] for i in retained_indices]+ if not batch:+ return dropped, type_examples_result# Step 3: Embed all queries across all signals (flatten → parallel embed)all_queries_flat: list[tuple[int, str]] = []diff --git a/products/signals/backend/temporal/llm.py b/products/signals/backend/temporal/llm.pyindex 4be341c549ab..fab9a7300387 100644--- a/products/signals/backend/temporal/llm.py+++ b/products/signals/backend/temporal/llm.py@@ -110,15 +110,22 @@ class EmptyLLMResponseError(Exception):pass+class LLMRefusalError(EmptyLLMResponseError):+ pass++def _extract_text_content(response: Message) -> str:"""Extract text content from Anthropic response."""if not isinstance(response, Message):raise TypeError(f"Expected Anthropic Message response, got {type(response).__name__}")+ if response.stop_reason == "refusal":+ raise LLMRefusalError("Model refused the request")+for block in reversed(response.content):if block.type == "text":return block.text- raise EmptyLLMResponseError("No text content in response")+ raise EmptyLLMResponseError(f"No text content in response (stop_reason={response.stop_reason})")# I could not for the life of me get thinking claude to stop outputting markdown.diff --git a/products/signals/backend/temporal/refusal_review.py b/products/signals/backend/temporal/refusal_review.pynew file mode 100644index 000000000000..3094557bbb61--- /dev/null+++ b/products/signals/backend/temporal/refusal_review.py@@ -0,0 +1,62 @@+import json+import hashlib+from collections.abc import Awaitable, Callable+from dataclasses import asdict+from datetime import UTC, datetime++import structlog+from asgiref.sync import sync_to_async++from posthog.storage import object_storage++from products.signals.backend.temporal import llm+from products.signals.backend.temporal.types import EmitSignalInputs++logger = structlog.get_logger(__name__)++MAX_REFUSAL_ATTEMPTS = 3+++def refusal_review_key(signal: EmitSignalInputs) -> str:+ fingerprint = hashlib.sha256(json.dumps(asdict(signal), sort_keys=True).encode()).hexdigest()+ return f"signals/refusal_review/{signal.team_id}/{fingerprint}.json"+++async def generate_queries_or_preserve_refusal(+ signal: EmitSignalInputs, generate: Callable[[], Awaitable[list[str]]]+) -> list[str] | None:+ key = refusal_review_key(signal)+ raw = await sync_to_async(object_storage.read, thread_sensitive=False)(key, missing_ok=True)+ attempts = int(json.loads(raw)["attempts"]) if raw is not None else 0++ # Persist the count between batch retries: another signal can fail after this one finishes.+ while attempts < MAX_REFUSAL_ATTEMPTS:+ try:+ queries = await generate()+ except llm.LLMRefusalError:+ attempts += 1+ await sync_to_async(object_storage.write, thread_sensitive=False)(+ key,+ json.dumps(+ {+ "signal": asdict(signal),+ "reason": "query_generation_refusal",+ "attempts": attempts,+ "status": "needs_review" if attempts == MAX_REFUSAL_ATTEMPTS else "retrying",+ "updated_at": datetime.now(UTC).isoformat(),+ }+ ),+ )+ else:+ if attempts:+ await sync_to_async(object_storage.delete, thread_sensitive=False)(key)+ return queries++ logger.warning(+ "signals_grouping.signal_preserved_for_review",+ team_id=signal.team_id,+ object_key=key,+ reason="query_generation_refusal",+ attempts=attempts,+ )+ return Nonediff --git a/products/signals/backend/test/test_generate_search_queries.py b/products/signals/backend/test/test_generate_search_queries.pyindex 7dd4590dae67..6e78af3153c6 100644--- a/products/signals/backend/test/test_generate_search_queries.py+++ b/products/signals/backend/test/test_generate_search_queries.py@@ -1,13 +1,18 @@import jsonimport pytest-from unittest.mock import patch+from unittest.mock import AsyncMock, MagicMock, patch++from anthropic.types import Message, TextBlock, Usagefrom products.signals.backend.temporal.grouping import (MAX_SEARCH_QUERIES,GenerateSearchQueriesInput,generate_search_queries,+ generate_search_queries_activity,)+from products.signals.backend.temporal.llm import EmptyLLMResponseError+from products.signals.backend.temporal.types import EmitSignalInputsMODULE_PATH = "products.signals.backend.temporal.grouping"@@ -32,3 +37,59 @@ async def test_generate_search_queries_keeps_the_first_three_without_a_retry(retassert result == queries[:MAX_SEARCH_QUERIES]assert call_llm.call_count == 1+++async def test_generate_search_queries_leaves_empty_response_handling_to_the_activity() -> None:+ with patch(f"{MODULE_PATH}.call_llm", side_effect=EmptyLLMResponseError("No text content in response")):+ with pytest.raises(EmptyLLMResponseError):+ await generate_search_queries(+ GenerateSearchQueriesInput(+ description="Date picker shows the wrong day",+ source_product="test",+ source_type="ticket",+ signal_type_examples=[],+ )+ )++[email protected]("refusals", [2, 3])+async def test_activity_preserves_only_signals_that_exhaust_refusal_attempts(refusals: int) -> None:+ refused = Message(+ id="msg_test",+ content=[],+ stop_reason="refusal",+ model="claude-sonnet-5-5",+ role="assistant",+ type="message",+ usage=Usage(input_tokens=1, output_tokens=0),+ )+ accepted = refused.model_copy(+ update={"content": [TextBlock(type="text", text='{"queries": ["date picker"]}')], "stop_reason": "end_turn"}+ )+ client = MagicMock()+ client.messages.create = AsyncMock(side_effect=[refused] * refusals + [accepted])+ signal = EmitSignalInputs(+ team_id=1, source_product="test", source_type="ticket", source_id="example", description="Date picker fails"+ )+ with (+ patch("products.signals.backend.temporal.llm.build_async_anthropic_client", return_value=client),+ patch("products.signals.backend.temporal.refusal_review.object_storage.read", return_value=None),+ patch("products.signals.backend.temporal.refusal_review.object_storage.write"),+ patch("products.signals.backend.temporal.refusal_review.object_storage.delete"),+ ):+ result = await generate_search_queries_activity(+ GenerateSearchQueriesInput(+ team_id=1,+ description=signal.description,+ source_product=signal.source_product,+ source_type=signal.source_type,+ signal_type_examples=[],+ signal=signal,+ )+ )++ assert result.quarantined is (refusals == 3)+ assert result.queries == ([] if refusals == 3 else ["date picker"])+ assert client.messages.create.await_count == 3diff --git a/products/signals/backend/test/test_grouping_refusal_batch.py b/products/signals/backend/test/test_grouping_refusal_batch.pynew file mode 100644index 000000000000..14b1613d9af1--- /dev/null+++ b/products/signals/backend/test/test_grouping_refusal_batch.py@@ -0,0 +1,84 @@+from datetime import UTC, datetime++import pytest+from unittest.mock import patch++from products.signals.backend.temporal import grouping+from products.signals.backend.temporal.signal_queries import (+ FetchSignalTypeExamplesOutput,+ RunSignalSemanticSearchOutput,+)+from products.signals.backend.temporal.types import EmitSignalInputs, NewReportMatch, NoMatchMetadata+++ "quarantined,isolate_refusals,duplicate",+ [+ ((True, False), True, False),+ ((False, True), True, False),+ ((True, True), True, False),+ ((False, False), False, False),+ ((True, False), True, True),+ ],+)+async def test_quarantined_signals_do_not_block_healthy_batch_members(+ quarantined: tuple[bool, bool], isolate_refusals: bool, duplicate: bool+) -> None:+ batch = [+ EmitSignalInputs(team_id=1, source_product="test", source_type="issue", source_id=str(i), description=str(i))+ for i in range(2)+ ]+ if duplicate:+ batch.append(batch[0])+ query_requests: list[str] = []+ emitted: list[grouping.AssignAndEmitSignalInput] = []++ async def execute(activity: object, input: object, **kwargs: object) -> object:+ if activity == grouping.get_embedding_activity:+ assert isinstance(input, grouping.GenerateEmbeddingInput)+ return grouping.GenerateEmbeddingOutput(embedding=[float(input.content)])+ if activity == grouping.generate_search_queries_activity:+ assert isinstance(input, grouping.GenerateSearchQueriesInput)+ assert (input.signal is not None) is isolate_refusals+ query_requests.append(input.description)+ i = int(input.description)+ return grouping.GenerateSearchQueriesOutput(+ queries=[] if quarantined[i] else [str(i)], quarantined=quarantined[i]+ )+ if activity == grouping.run_signal_semantic_search_activity:+ return RunSignalSemanticSearchOutput(candidates=[])+ if activity == grouping.fetch_report_contexts_activity:+ return grouping.FetchReportContextsOutput(contexts={})+ if activity == grouping.match_signal_to_report_activity:+ assert isinstance(input, grouping.MatchSignalToReportInput)+ assert input.queries == [input.description]+ return NewReportMatch(+ title="Example report", summary="Example summary", match_metadata=NoMatchMetadata(reason="new")+ )+ if activity == grouping.assign_and_emit_signal_activity:+ assert isinstance(input, grouping.AssignAndEmitSignalInput)+ assert input.embedding == [float(input.description)]+ emitted.append(input)+ return grouping.AssignAndEmitSignalOutput(+ report_id="report", promoted=False, timestamp=datetime.now(UTC), run_count=0+ )+ if activity == grouping.wait_for_signal_in_clickhouse_activity:+ return None+ raise AssertionError(f"Unexpected activity: {activity}")++ with (+ patch.object(grouping.workflow, "execute_activity", side_effect=execute),+ patch.object(+ grouping.workflow,+ "patched",+ side_effect=lambda name: isolate_refusals and name == "signals-query-refusal-review-v1",+ ),+ ):+ dropped, _ = await grouping._process_signal_batch(batch, FetchSignalTypeExamplesOutput(examples=[]))++ assert dropped == sum(quarantined[int(signal.source_id)] for signal in batch)+ assert [signal.source_id for signal in emitted] == [+ signal.source_id for signal in batch if not quarantined[int(signal.source_id)]+ ]+ assert len(query_requests) == 2diff --git a/products/signals/backend/test/test_llm.py b/products/signals/backend/test/test_llm.pyindex afaf857eaeb9..b5c9ed3bc4c7 100644--- a/products/signals/backend/test/test_llm.py+++ b/products/signals/backend/test/test_llm.py@@ -32,6 +32,20 @@ def _mock_anthropic_client() -> MagicMock:return client[email protected]("has_text", [False, True])+async def test_explicit_refusal_is_not_treated_as_text(has_text: bool) -> None:+ response = _text_response("refused")+ response.stop_reason = "refusal"+ if not has_text:+ response.content = []+ client = _mock_anthropic_client()+ client.messages.create.return_value = response+ with patch(f"{MODULE_PATH}.get_async_anthropic_gateway_client", return_value=client):+ with pytest.raises(llm.LLMRefusalError):+ await call_llm(team_id=1, system_prompt="s", user_prompt="u", validate=lambda text: text)++@pytest.mark.asyncio@override_settings(AI_GATEWAY_URL="https://ai-gateway.example/v1", AI_GATEWAY_API_KEY="phs_test")async def test_gateway_mode_omits_legacy_stage_header():diff --git a/products/signals/backend/test/test_refusal_review.py b/products/signals/backend/test/test_refusal_review.pynew file mode 100644index 000000000000..a097768a054b--- /dev/null+++ b/products/signals/backend/test/test_refusal_review.py@@ -0,0 +1,88 @@+import json+from collections.abc import Generator++import pytest+from unittest.mock import AsyncMock, patch++from products.signals.backend.temporal import llm+from products.signals.backend.temporal.refusal_review import generate_queries_or_preserve_refusal, refusal_review_key+from products.signals.backend.temporal.types import EmitSignalInputs++MODULE = "products.signals.backend.temporal.refusal_review"+++def stored_records() -> Generator[dict[str, str]]:+ records: dict[str, str] = {}+ with (+ patch(f"{MODULE}.object_storage.read", side_effect=lambda key, **kwargs: records.get(key)),+ patch(f"{MODULE}.object_storage.write", side_effect=lambda key, value: records.__setitem__(key, value)),+ patch(f"{MODULE}.object_storage.delete", side_effect=lambda key: records.pop(key)),+ ):+ yield records+++def make_signal() -> EmitSignalInputs:+ return EmitSignalInputs(+ team_id=1,+ source_product="test",+ source_type="issue",+ source_id="example-1",+ description="The settings page does not save a new display name.",+ extra={"url": "https://example.com/issues/1"},+ remediation={"instructions": "Check the save action."},+ )++[email protected]("refusals", [1, 2])+async def test_noisy_refusal_can_recover_before_review(stored_records: dict[str, str], refusals: int) -> None:+ signal = make_signal()+ generate = AsyncMock(side_effect=[llm.LLMRefusalError()] * refusals + [["settings save"]])++ assert await generate_queries_or_preserve_refusal(signal, generate) == ["settings save"]+ assert generate.await_count == refusals + 1+ assert not stored_records+++async def test_three_refusals_preserve_the_signal_and_skip_batch_retries(stored_records: dict[str, str]) -> None:+ signal = make_signal()+ generate = AsyncMock(side_effect=llm.LLMRefusalError())++ assert await generate_queries_or_preserve_refusal(signal, generate) is None+ record = json.loads(stored_records[refusal_review_key(signal)])+ assert record["status"] == "needs_review"+ assert record["attempts"] == 3+ assert EmitSignalInputs(**record["signal"]) == signal+ assert await generate_queries_or_preserve_refusal(signal, generate) is None+ assert generate.await_count == 3+++async def test_refusal_count_survives_an_unrelated_failure(stored_records: dict[str, str]) -> None:+ signal = make_signal()+ generate = AsyncMock(side_effect=[llm.LLMRefusalError(), ConnectionError()])+ with pytest.raises(ConnectionError):+ await generate_queries_or_preserve_refusal(signal, generate)++ generate = AsyncMock(side_effect=llm.LLMRefusalError())+ assert await generate_queries_or_preserve_refusal(signal, generate) is None+ assert generate.await_count == 2++[email protected]("error", [llm.EmptyLLMResponseError(), ConnectionError()])+async def test_other_errors_still_fail_the_activity(stored_records: dict[str, str], error: Exception) -> None:+ generate = AsyncMock(side_effect=error)+ with pytest.raises(type(error)):+ await generate_queries_or_preserve_refusal(make_signal(), generate)+ assert not stored_records+++async def test_storage_failure_cannot_remove_the_signal(stored_records: dict[str, str]) -> None:+ generate = AsyncMock(side_effect=llm.LLMRefusalError())+ with patch(f"{MODULE}.object_storage.write", side_effect=ConnectionError()), pytest.raises(ConnectionError):+ await generate_queries_or_preserve_refusal(make_signal(), generate)+ assert not stored_records