: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
import os
import json
import uuid
import asyncio
from collections import defaultdict
from dataclasses import asdict, dataclass
from datetime import datetime, timedelta
from typing import Literal, Optional, cast
from django.conf import settings
from django.db import transaction
from django.utils import timezone
import numpy as np
import structlog
import temporalio
import posthoganalytics
from pydantic import BaseModel, Field
from temporalio import workflow
from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
from temporalio.workflow import ParentClosePolicy
from posthog.schema import EmbeddingModelName
from posthog.api.embedding_worker import async_generate_embedding, emit_embedding_request
from posthog.dataclasses import frozen
from posthog.event_usage import groups
from posthog.models import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.common.scoped import scoped_temporal
from posthog.temporal.common.utils import close_db_connections
from products.signals.backend.artefact_attribution import ArtefactAttribution
from products.signals.backend.artefact_schemas import MAX_REPORT_LINK_REASON_LENGTH, ReportLink
from products.signals.backend.billing import BILLING_EXEMPT_SOURCE_PRODUCTS
from products.signals.backend.contracts import MonitoringUnresolvedSignalExtra
from products.signals.backend.daily_limit import capture_signal_report_daily_limit_paused, daily_report_limit_gate
from products.signals.backend.enums import ReportLinkKind, ReportLinkWritePath, SignalSourceProduct, SignalSourceType
from products.signals.backend.models import SignalEmissionRecord, SignalReport, SignalReportArtefact
from products.signals.backend.quota import capture_signal_report_quota_paused, self_driving_quota_gate
from products.signals.backend.receivers import _is_safety_suppressed
from products.signals.backend.recurrence import forks_recurrence
from products.signals.backend.report_merge import signal_target_report
from products.signals.backend.report_monitoring_signals import current_research_attempt
from products.signals.backend.signal_metadata import EMBEDDING_MODEL
from products.signals.backend.source_issues import open_report_for_source_issue, schedule_source_issue_writeback
from products.signals.backend.spend import begin_report_spend, complete_signal_pipeline, signal_spend_summaries
from products.signals.backend.spend_billing import system_source_exempt
from products.signals.backend.temporal import metrics
from products.signals.backend.temporal.drop_telemetry import capture_signal_dropped
from 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_refusal
from products.signals.backend.temporal.signal_queries import (
SIGNAL_DOCUMENT_PRODUCT,
SIGNAL_DOCUMENT_RENDERING,
SIGNAL_DOCUMENT_TYPE,
FetchSignalsForReportInput,
FetchSignalsForReportOutput,
FetchSignalTypeExamplesInput,
FetchSignalTypeExamplesOutput,
RunSignalSemanticSearchInput,
RunSignalSemanticSearchOutput,
WaitForClickHouseInput,
WaitForClickHouseMode,
WaitForClickHouseSignal,
fetch_signal_type_examples_activity,
fetch_signals_for_report_activity,
fetch_source_signal_matches,
run_signal_semantic_search_activity,
soft_delete_report_signals,
wait_for_signal_in_clickhouse_activity,
)
from products.signals.backend.temporal.summary import RESEARCH_SANDBOX_RETRY_BUDGET, SignalReportSummaryWorkflow
from products.signals.backend.temporal.types import (
IMPLEMENTATION_DEBOUNCE_SECONDS,
RESEARCH_DEBOUNCE_SECONDS,
EmitSignalInputs,
ExistingReportMatch,
MatchedMetadata,
MatchResult,
NewReportMatch,
NoMatchMetadata,
ReportContext,
SignalCandidate,
SignalData,
SignalReportSummaryWorkflowInputs,
SignalTypeExample,
SpecificityMetadata,
TeamSignalGroupingInput,
next_research_bucket,
)
logger = structlog.get_logger(__name__)
WEIGHT_THRESHOLD = float(os.getenv("SIGNAL_WEIGHT_THRESHOLD", "1.0"))
MAX_QUERIES = 3
@dataclass
class GenerateEmbeddingInput:
team_id: int
content: str
@dataclass
class GenerateEmbeddingOutput:
embedding: list[float]
@temporalio.activity.defn
@scoped_temporal()
@close_db_connections
async def get_embedding_activity(input: GenerateEmbeddingInput) -> GenerateEmbeddingOutput:
"""Generate embedding for signal content using the embedding worker API."""
try:
team = await Team.objects.aget(pk=input.team_id)
response = await async_generate_embedding(team, input.content, model=EMBEDDING_MODEL.value)
logger.debug(
f"Generated embedding for team {input.team_id}",
team_id=input.team_id,
content_length=len(input.content),
)
return GenerateEmbeddingOutput(embedding=response.embedding)
except Exception as e:
logger.exception(
f"Failed to generate embedding for team {input.team_id}: {e}",
team_id=input.team_id,
)
raise
MAX_SEARCH_QUERIES = 3
class QueryGenerationResponse(BaseModel):
# No upper bound: Claude 5 models return four or five queries however the prompt bounds the
# count, and a schema rejection costs a full retry. The caller keeps the first MAX_SEARCH_QUERIES.
queries: list[str] = Field(min_length=1)
QUERY_GENERATION_SYSTEM_PROMPT_TEMPLATE = """You are a signal grouping assistant. Your job is to generate search queries that will help find related signals in an embedding database.
Signals come from diverse sources: exceptions, experiments, insight alerts, session behaviour analysis, and more.
Related signals may be different types but connected by the same underlying cause, feature, or user journey. Note that "related" does not just mean "semantically similar", but "likely to share a common root cause or impact".
The signal database is heterogeneous — it contains many different signal types. Your queries should search ACROSS these types to find signals that share a common root cause, affected feature, or user journey with the new signal. Do NOT try to generate one query per signal type. Instead, generate queries that would surface related signals regardless of their type.
{examples_section}
Given a new signal, generate 1-3 search queries that would help find related signals. Each query should be a natural language description that captures a different angle of what might be related:
1. The specific feature, page, or component involved
2. The type of user behavior or technical issue
3. The broader category or business impact
Keep queries concise but descriptive - they have a maximum length of {max_query_tokens} tokens. Each query will be embedded and used for semantic similarity search.
Respond with a JSON object containing a "queries" array with 1-3 query strings. Return ONLY valid JSON, no other text."""
def _build_query_generation_system_prompt(signal_type_examples: list[SignalTypeExample]) -> str:
"""Build the query generation system prompt, optionally including signal type examples."""
if signal_type_examples:
lines = [
"Here are examples of signal types currently in the database, to help you understand what kinds of signals your queries might match against:\n"
]
for ex in signal_type_examples:
lines.append(f'- {ex.source_product} / {ex.source_type} (last seen: {ex.timestamp}): "{ex.content[:300]}"')
examples_section = "\n".join(lines)
else:
examples_section = ""
return QUERY_GENERATION_SYSTEM_PROMPT_TEMPLATE.format(
examples_section=examples_section,
max_query_tokens=MAX_QUERY_TOKENS,
)
@frozen
class GenerateSearchQueriesInput:
description: str
source_product: str
source_type: str
signal_type_examples: list[SignalTypeExample]
# 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_id: str | None = None
signal: EmitSignalInputs | None = None
async def generate_search_queries(input: GenerateSearchQueriesInput) -> list[str]:
"""
Use LLM to generate 1-3 search queries for finding related signals.
Returns queries truncated to fit within embedding token limits.
"""
system_prompt = _build_query_generation_system_prompt(input.signal_type_examples)
user_prompt = f"""NEW SIGNAL:
- Source: {input.source_product} / {input.source_type}
- Description: {input.description}"""
def validate(text: str) -> list[str]:
data = json.loads(text)
result = QueryGenerationResponse.model_validate(data)
return [truncate_query_to_token_limit(q) for q in result.queries[:MAX_SEARCH_QUERIES]]
return await call_llm(
team_id=input.team_id,
signal_id=input.signal_id,
system_prompt=system_prompt,
user_prompt=user_prompt,
validate=validate,
temperature=0.7,
stage="query_generation",
ai_product="signals_grouping",
)
@frozen
class GenerateSearchQueriesOutput:
queries: list[str]
quarantined: bool = False
@temporalio.activity.defn
@scoped_temporal()
@close_db_connections
async def generate_search_queries_activity(input: GenerateSearchQueriesInput) -> GenerateSearchQueriesOutput:
"""Use LLM to generate 1-3 search queries for finding related signals."""
try:
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,
source_type=input.source_type,
queries=queries,
)
return GenerateSearchQueriesOutput(queries=queries)
except Exception as e:
logger.exception(
f"Failed to generate search queries: {e}",
source_product=input.source_product,
source_type=input.source_type,
)
raise
class MatchFound(BaseModel):
reason: str
match_type: Literal["existing"]
signal_id: str
query_index: int
class NewGroup(BaseModel):
reason: str
match_type: Literal["new"]
title: str
summary: str
MatchResponse = MatchFound | NewGroup
def _parse_match_response(data: dict) -> MatchResponse:
"""Parse and validate match response using discriminated union."""
match_type = data.get("match_type")
if match_type == "existing":
return MatchFound.model_validate(data)
elif match_type == "new":
return NewGroup.model_validate(data)
else:
raise ValueError(f"Invalid match_type: {match_type}")
MATCHING_SYSTEM_PROMPT = """You are a signal grouping assistant. Your job is to determine if a new signal is related to an existing group of signals,
or if it should start a new group.
Signals come from diverse sources: exceptions, experiments, insight alerts, session behaviour analysis, and more.
Your task is to identify signals that are RELATED - they may be different signal types but connected by the same underlying cause, feature, or user journey.
IMPORTANT: Signals should be grouped if they are meaningfully related, not just superficially similar:
- An experiment reaching significance AND an error spike on the same feature SHOULD match (related by feature)
- A session behaviour anomaly AND an insight alert about the same user flow SHOULD match (related by user journey)
- Two "experiment reached significance" signals from DIFFERENT, unrelated experiments should NOT match
- Two signals about the SAME experiment (e.g., significance + follow-up analysis) SHOULD match
- Two error-tracking signals from the SAME underlying defect or resolved by the same fix applied at different call sites SHOULD match, even if they surface in different files, components, or pages (they resolve to one fix)
You will receive:
1. A new signal with its description and source information
2. Discovery strength: how many independent search queries found signals in each existing group (higher = stronger evidence)
3. Results from multiple search queries, each with candidate signals annotated with their group title and group size
IMPORTANT — use group context when deciding:
- Each candidate belongs to a group. The group title tells you the group's overall theme.
- Match the new signal to a GROUP's theme, not just to an individual candidate signal.
- A candidate that shares a keyword with the new signal but belongs to an unrelated group should NOT be matched.
- Groups found by multiple independent queries are more likely genuinely related.
If a candidate signal from ANY query is related to the new signal AND its group theme aligns, respond with:
{
"reason": "<Brief, less than 100 character sentence explaining what connects the signal to the group>",
"match_type": "existing",
"signal_id": "<the signal_id of the matching candidate>",
"query_index": <0-based index of the query that surfaced this candidate>
}
If no candidate is related (or all queries returned no results), respond with:
{
"reason": "<Brief, less than 100 character sentence explaining why none of the candidates are related>",
"match_type": "new",
"title": "<short title for a new report>",
"summary": "<1-2 sentence summary of what this signal group is about>"
}
IMPORTANT: The "reason" field MUST be the first key in your JSON response. Write your reasoning BEFORE making the match decision.
You must respond with valid JSON only, no other text."""
SPECIFICITY_CHECK_SYSTEM_PROMPT = """You are a senior engineer reviewing whether a group of signals belongs in a single pull request.
You will receive:
1. A group of existing signals (the current report)
2. A new signal being proposed for addition
Your job:
1. Write a single PR title (max 70 chars) that covers ALL signals in the group INCLUDING the new one.
2. Judge: would ONE focused change resolve every signal in the group? If a single fix — even one applied at several call sites — addresses them all, they belong in one PR.
Judge by the FIX, not by where the symptom appears. Signals that share a single root cause, or that one shared change would resolve, belong in ONE PR even when the error surfaces in different files, components, or pages. The same guard, the same null-check, the same handler fix applied across many call sites is still one pull request.
SPECIFIC — one root cause or one shared fix, so one engineer ships it in a single PR:
- "Fix date picker timezone handling in insights" — one component, one bug
- "Guard empty i18n translation keys in the missing-key handler" — one shared guard silences the empty-key errors surfacing across the calendar, settings, and event views
- "Treat handled 404s as null instead of reporting them" — one interceptor-level fix stops the 404 noise from several endpoints
- "Fix funnel conversion calculation for time-based bins" — one feature, one issue
Reject the group only when the signals need SEPARATE, unrelated fixes that no single engineer would take on together, such as "Fix various PostHog AI issues" or "Address feature flag and authentication concerns".
None of these are reasons to split:
- The same fix touches several files, call sites, or components
- The signals surface in different pages, views, or systems but share one root cause or one remedy
- The signals describe different symptoms of the same underlying behaviour
- The signals are separate defects in the same feature's logic: two accuracy gaps in one detector, two broken output formats of one exporter, two missing tables behind one product's queries. One engineer fixes both under one title.
When you are unsure, name the single change, or the single feature whose logic every signal lives in, that would resolve the group. If you can name it, they belong in one PR. Split only when the signals belong to different features or products, or when the new signal is too vague to tie to the group's fix.
The group can include a RESEARCHED CAUSE. This means that an engineer already investigated the group and named its cause and its fix. The group's PR is that fix. For such a group, the rule is stricter:
- Accept the new signal only when the researched fix also resolves it.
- Reject the new signal when it needs a different fix, even when it is in the same feature, on the same page, or in the same product area.
- A shared page, a shared HTTP status (such as a 404), or a shared error message is not a shared cause.
Respond with valid JSON only:
{"pr_title": "...", "specific_enough": true/false, "reason": "..."}"""
class SpecificityResult(BaseModel):
pr_title: str
specific_enough: bool
reason: str
MAX_SIGNALS_IN_SPECIFICITY_CONTEXT = 8
MAX_RESEARCHED_SUMMARY_CHARS = 2000
def _build_matching_prompt(
description: str,
source_product: str,
source_type: str,
queries: list[str],
query_results: list[list[SignalCandidate]],
report_contexts: dict[str, ReportContext],
) -> str:
"""Build matching prompt with group titles and multi-query agreement summary."""
report_query_hits: dict[str, set[int]] = defaultdict(set)
for query_idx, candidates in enumerate(query_results):
for c in candidates:
report_query_hits[c.report_id].add(query_idx)
prompt = f"""NEW SIGNAL:
- Source: {source_product} / {source_type}
- Description: {description}
DISCOVERY STRENGTH (groups found by multiple independent queries are more likely related):
"""
for report_id, query_indices in sorted(report_query_hits.items(), key=lambda x: -len(x[1])):
ctx = report_contexts.get(report_id)
title = ctx.title if ctx else "(untitled)"
size = ctx.signal_count if ctx else 0
prompt += f'- "{title}" ({size} signal{"s" if size != 1 else ""}): found by {len(query_indices)}/{len(queries)} queries\n'
prompt += "\nSEARCH RESULTS:\n"
for query_idx, (query, candidates) in enumerate(zip(queries, query_results)):
prompt += f'\n--- Query {query_idx}: "{query}" ---\n'
if not candidates:
prompt += "(no results)\n"
else:
for c in candidates:
ctx = report_contexts.get(c.report_id)
title = ctx.title if ctx else "(untitled)"
size = ctx.signal_count if ctx else 0
prompt += f"""- signal_id: {c.signal_id}
distance: {c.distance:.4f}
Source: {c.source_product} / {c.source_type}
Group: "{title}" ({size} signal{"s" if size != 1 else ""})
Description: {c.content}
"""
return prompt
def _build_specificity_prompt(
new_signal_description: str,
new_signal_source_product: str,
new_signal_source_type: str,
report_title: str,
group_signals: list[SignalData],
researched_summary: str | None = None,
) -> str:
"""Build prompt for the PR-specificity verification gate."""
prompt = f"""EXISTING GROUP:
- Title: {report_title or "(untitled)"}
"""
if researched_summary:
prompt += f"""- Researched cause: {researched_summary[:MAX_RESEARCHED_SUMMARY_CHARS]}
"""
prompt += f"""- Signals ({len(group_signals)} total):
"""
for i, sig in enumerate(group_signals[:MAX_SIGNALS_IN_SPECIFICITY_CONTEXT]):
prompt += f"""
Signal {i + 1}:
- Source: {sig.source_product} / {sig.source_type}
- Description: {sig.content[:500]}
"""
remaining = len(group_signals) - MAX_SIGNALS_IN_SPECIFICITY_CONTEXT
if remaining > 0:
prompt += f"\n ... and {remaining} more signals\n"
prompt += f"""
NEW SIGNAL PROPOSED FOR ADDITION:
- Source: {new_signal_source_product} / {new_signal_source_type}
- Description: {new_signal_description}
Write a PR title covering ALL the above signals (existing + new), then judge if it's specific enough for one pull request."""
return prompt
@frozen
class MatchSignalToReportInput:
description: str
source_product: str
source_type: str
queries: list[str]
query_results: list[list[SignalCandidate]]
report_contexts: dict[str, ReportContext]
# Optional with a default for deploy-time backward compatibility (see GenerateSearchQueriesInput).
team_id: int | None = None
signal_id: str | None = None
source_id: str | None = None
sync_with_source: bool = False
source_match_signal_id: str | None = None
source_match_report_id: str | None = None
# The issue URL of a GitHub issue signal, so an open report that names the issue as its source
# can take the signal before similarity matching runs.
source_issue_url: str | None = None
def source_issue_url_for_signal(source_product: str, source_type: str, extra: dict | None) -> str | None:
if source_product != SignalSourceProduct.GITHUB or source_type != SignalSourceType.ISSUE:
return None
url = (extra or {}).get("html_url")
return url if isinstance(url, str) and url else None
def _source_issue_match(team_id: int, url: str) -> ExistingReportMatch | None:
report = open_report_for_source_issue(team_id=team_id, url=url)
if report is None or report.triggering_signal_id is None:
return None
return ExistingReportMatch(
report_id=str(report.id),
match_metadata=MatchedMetadata(
parent_signal_id=str(report.triggering_signal_id),
match_query="source issue",
reason="The report names this GitHub issue as its source issue",
),
source_issue_matched=True,
)
async def _match_by_source_issue_or_similarity(input: MatchSignalToReportInput) -> MatchResult:
if input.team_id is not None and input.source_issue_url:
match = await database_sync_to_async(_source_issue_match, thread_sensitive=False)(
input.team_id, input.source_issue_url
)
if match is not None:
return match
return await match_signal_to_report(input)
async def match_signal_to_report(input: MatchSignalToReportInput) -> MatchResult:
"""
Determine if a new signal matches an existing report or needs a new one.
Returns:
ExistingReportMatch if a match is found, NewReportMatch otherwise
"""
candidates_by_id: dict[str, SignalCandidate] = {}
for candidates in input.query_results:
for c in candidates:
candidates_by_id[c.signal_id] = c
user_prompt = _build_matching_prompt(
input.description,
input.source_product,
input.source_type,
input.queries,
input.query_results,
input.report_contexts,
)
def validate(text: str) -> MatchResult:
data = json.loads(text)
result = _parse_match_response(data)
if isinstance(result, MatchFound):
matched = candidates_by_id.get(result.signal_id)
if matched is None:
raise ValueError(f"signal_id {result.signal_id} not found in candidates")
if result.query_index < 0 or result.query_index >= len(input.queries):
raise ValueError(f"query_index {result.query_index} out of range (0-{len(input.queries) - 1})")
return ExistingReportMatch(
report_id=matched.report_id,
match_metadata=MatchedMetadata(
parent_signal_id=result.signal_id,
match_query=input.queries[result.query_index],
reason=result.reason,
),
)
return NewReportMatch(
title=result.title,
summary=result.summary,
match_metadata=NoMatchMetadata(
reason=result.reason,
rejected_signal_ids=list(candidates_by_id.keys()),
),
)
return await call_llm(
team_id=input.team_id,
signal_id=input.signal_id,
system_prompt=MATCHING_SYSTEM_PROMPT,
user_prompt=user_prompt,
validate=validate,
temperature=0.2,
stage="match",
cache_system_prompt=True,
ai_product="signals_grouping",
)
@temporalio.activity.defn
@scoped_temporal()
@close_db_connections
async def match_signal_to_report_activity(input: MatchSignalToReportInput) -> MatchResult:
"""Determine if a new signal matches an existing report or needs a new one."""
try:
result: MatchResult
if input.source_match_signal_id and input.source_match_report_id:
result = ExistingReportMatch(
report_id=input.source_match_report_id,
match_metadata=MatchedMetadata(
parent_signal_id=input.source_match_signal_id,
match_query="source identity",
reason="Material update to the same source record",
),
source_synced=True,
)
elif input.sync_with_source and input.team_id is not None and input.source_id:
team = await Team.objects.aget(pk=input.team_id)
source_matches = await database_sync_to_async(fetch_source_signal_matches, thread_sensitive=False)(
team, [input.source_id], input.source_product, input.source_type
)
matches = source_matches.get(input.source_id, [])
if matches:
source_match = matches[0]
result = ExistingReportMatch(
report_id=source_match.report_id,
match_metadata=MatchedMetadata(
parent_signal_id=source_match.signal_id,
match_query="source identity",
reason="Material update to the same source record",
),
source_synced=True,
)
else:
result = await _match_by_source_issue_or_similarity(input)
else:
result = await _match_by_source_issue_or_similarity(input)
if isinstance(result, ExistingReportMatch) and input.team_id is not None:
report = await SignalReport.objects.filter(team_id=input.team_id, id=result.report_id).afirst()
if report is not None and report.status != SignalReport.Status.DELETED:
current = await database_sync_to_async(signal_target_report, thread_sensitive=False)(report)
if current.id != report.id:
result.report_id = str(current.id)
unsafe = await database_sync_to_async(_is_safety_suppressed, thread_sensitive=False)(
str(current.id), input.team_id
)
result.report_title = "" if unsafe else current.title
total_candidates = sum(len(r) for r in input.query_results)
logger.debug(
f"Match result: matched={isinstance(result, ExistingReportMatch)}",
query_count=len(input.queries),
total_candidates=total_candidates,
)
return result
except Exception as e:
logger.exception(
f"Failed to match signal with LLM: {e}",
source_product=input.source_product,
source_type=input.source_type,
source_id=input.source_id,
sync_with_source=input.sync_with_source,
)
raise
@dataclass
class FetchReportContextsInput:
team_id: int
report_ids: list[str]
@dataclass
class FetchReportContextsOutput:
contexts: dict[str, ReportContext]
@temporalio.activity.defn
@scoped_temporal()
@close_db_connections
async def fetch_report_contexts_activity(input: FetchReportContextsInput) -> FetchReportContextsOutput:
"""Fetch lightweight context (title, signal count) for reports from Postgres."""
if not input.report_ids:
return FetchReportContextsOutput(contexts={})
try:
reports = SignalReport.objects.filter(team_id=input.team_id, id__in=input.report_ids).values_list(
"id", "title", "signal_count"
)
contexts: dict[str, ReportContext] = {}
async for report_id, title, signal_count in reports:
rid = str(report_id)
contexts[rid] = ReportContext(
report_id=rid,
title=title or "(untitled)",
signal_count=signal_count,
)
logger.debug(
f"Fetched contexts for {len(contexts)}/{len(input.report_ids)} reports",
requested=len(input.report_ids),
found=len(contexts),
)
return FetchReportContextsOutput(contexts=contexts)
except Exception as e:
logger.exception(f"Failed to fetch report contexts: {e}")
raise
@dataclass(frozen=False)
class VerifyMatchSpecificityInput:
team_id: int
report_id: str
report_title: str
new_signal_description: str
new_signal_source_product: str
new_signal_source_type: str
group_signals: list[SignalData]
signal_id: str | None = None
@dataclass
class VerifyMatchSpecificityOutput:
pr_title: str
specific_enough: bool
reason: str
async def verify_match_specificity(
team_id: int,
new_signal_description: str,
new_signal_source_product: str,
new_signal_source_type: str,
report_title: str,
group_signals: list[SignalData],
signal_id: str | None = None,
researched_summary: str | None = None,
) -> VerifyMatchSpecificityOutput:
"""Verify that adding a signal to a group produces a specific-enough PR title."""
specificity_prompt = _build_specificity_prompt(
new_signal_description=new_signal_description,
new_signal_source_product=new_signal_source_product,
new_signal_source_type=new_signal_source_type,
report_title=report_title,
group_signals=group_signals,
researched_summary=researched_summary,
)
specificity = await call_llm(
team_id=team_id,
signal_id=signal_id,
system_prompt=SPECIFICITY_CHECK_SYSTEM_PROMPT,
user_prompt=specificity_prompt,
validate=lambda text: SpecificityResult.model_validate_json(text),
temperature=0.2,
stage="specificity",
cache_system_prompt=True,
ai_product="signals_grouping",
)
return VerifyMatchSpecificityOutput(
pr_title=specificity.pr_title,
specific_enough=specificity.specific_enough,
reason=specificity.reason,
)
def _has_completed_research(report: SignalReport) -> bool:
"""Whether a research pass completed on the report, so its title and summary describe the researched cause.
`researched_signal_count` alone does not prove this. A run that starts, and a snooze, move `signals_at_run`
before any research completes, so the reconstruction is positive while the summary is still the matcher's
first guess. Only a pass that reaches READY writes `signals_researched`. A report researched before that
column existed has it null, and only on a READY report is `signals_at_run` known to be a run's stamp.
"""
if report.researched_signal_count == 0:
return False
return report.signals_researched is not None or report.status in {
SignalReport.Status.READY,
SignalReport.Status.MONITORING,
}
def _researched_summary(team_id: int, report_id: str) -> str | None:
"""The summary of a report that a research pass completed, or None when no research pass covers it.
Before research, the summary is only the matcher's first guess, so it must not constrain later signals.
"""
report = SignalReport.objects.filter(team_id=team_id, id=report_id).first()
if report is None or not _has_completed_research(report) or not report.summary:
return None
if _is_safety_suppressed(report_id, team_id):
return None
return report.summary
@temporalio.activity.defn
@scoped_temporal()
@close_db_connections
async def verify_match_specificity_activity(input: VerifyMatchSpecificityInput) -> VerifyMatchSpecificityOutput:
"""Verify that adding a signal to a group produces a specific-enough PR title."""
try:
researched_summary = await database_sync_to_async(_researched_summary, thread_sensitive=False)(
input.team_id, input.report_id
)
result = await verify_match_specificity(
team_id=input.team_id,
new_signal_description=input.new_signal_description,
new_signal_source_product=input.new_signal_source_product,
new_signal_source_type=input.new_signal_source_type,
report_title=input.report_title,
group_signals=input.group_signals,
signal_id=input.signal_id,
researched_summary=researched_summary,
)
logger.debug(
f"Specificity check for report {input.report_id}: "
f'pr_title="{result.pr_title}", specific_enough={result.specific_enough}',
team_id=input.team_id,
report_id=input.report_id,
pr_title=result.pr_title,
specific_enough=result.specific_enough,
reason=result.reason,
)
return result
except Exception as e:
logger.exception(
f"Failed to verify match specificity for report {input.report_id}: {e}",
team_id=input.team_id,
report_id=input.report_id,
)
raise
@dataclass(frozen=False)
class AssignAndEmitSignalInput:
team_id: int
signal_id: str
description: str
weight: float
source_product: str
source_type: str
source_id: str
extra: dict
embedding: list[float]
match_result: MatchResult
timestamp: Optional[datetime] = None
updated_title: Optional[str] = None
remediation: Optional[dict] = None
sync_with_source: bool = False
@dataclass(frozen=False)
class AssignAndEmitSignalOutput:
report_id: str
promoted: bool
timestamp: datetime
run_count: int
research_debounce_seconds: int = 0
# The title the report holds after assignment. It differs from `updated_title` when assignment keeps a
# researched title. None when no title is known, which includes results recorded before this field existed.
report_title: Optional[str] = None
triggering_signal_id: str | None = None
@frozen
class AssignAndEmitDbResult:
report_id: str
promoted: bool
timestamp: datetime
matched_deleted_report: bool
run_count: int
reresearch_capped: bool
report_status: str
report_signal_count: int
promotion_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
report_title: Optional[str] = None
triggering_signal_id: str | None = None
def _link_check_follow_up(*, team_id: int, report_id: str, source_product: str, extra: dict) -> None:
"""Point a report born from a failed follow-up check at the report that check was written on.
A `metric_threshold` check that fails on a resolved report emits a `signals_check` signal, and
this is the report that signal landed on. Without the edge the fresh report carries neither the
verdict nor the report whose fix the check was measuring, so research starts from nothing.
Distinct from the `recurrence_of` row the resolved-report fork writes: that one says the issue
came back, this one says a measurement of the fix breached. A report can hold both.
Best-effort. The signal is already assigned, and losing the edge must not fail the assignment.
"""
if source_product != SignalSourceProduct.SIGNALS_CHECK:
return
origin_id = extra.get("report_id")
if not origin_id or str(origin_id) == report_id:
return
reason = (extra.get("explanation") or "")[:MAX_REPORT_LINK_REASON_LENGTH] or None
try:
SignalReportArtefact.add_log(
team_id=team_id,
report_id=report_id,
content=ReportLink(kind=ReportLinkKind.FOLLOW_UP_OF, report_id=str(origin_id), reason=reason),
attribution=ArtefactAttribution.system(),
write_path=ReportLinkWritePath.PIPELINE,
)
except Exception:
logger.exception(
"signals.report_check.follow_up_link_failed", report_id=report_id, team_id=team_id, origin_id=origin_id
)
async def _schedule_writeback_for_source_issue_signal(input: "AssignAndEmitSignalInput", report_id: str) -> None:
# The report names this issue as its source, and the issue only now reached the pipeline, so this
# is the first moment the writeback may comment on it. Best-effort, like the writeback itself.
extra = input.extra or {}
signal = {
"source_product": input.source_product,
"source_type": input.source_type,
"extra": {key: extra.get(key) for key in ("html_url", "state", "locked")},
}
try:
await database_sync_to_async(schedule_source_issue_writeback, thread_sensitive=False)(
team_id=input.team_id, report_id=report_id, signals=[signal]
)
except Exception:
logger.exception("Failed to schedule source issue writeback", report_id=report_id, team_id=input.team_id)
@temporalio.activity.defn
@scoped_temporal()
@close_db_connections
async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> AssignAndEmitSignalOutput:
match_result = input.match_result
def do_assign_and_emit(suppress_promotion: bool) -> AssignAndEmitDbResult:
spend = signal_spend_summaries(team_id=input.team_id, signal_ids=[input.signal_id]).get(input.signal_id)
with transaction.atomic():
promoted = False
promotion_suppressed = False
monitoring_billing_exemption = None
if (
input.source_product == SignalSourceProduct.SIGNALS_CHECK
and input.source_type == SignalSourceType.MONITORING_UNRESOLVED
):
payload = MonitoringUnresolvedSignalExtra.model_validate(input.extra)
attempt = current_research_attempt(
team_id=input.team_id, report_id=payload.report_id, attempt_id=payload.attempt_id, lock=True
)
if attempt is None or input.source_id != str(attempt.id):
raise ValueError("Monitoring research request is no longer current")
monitoring_billing_exemption = attempt.report.billing_exempt_reason
if isinstance(match_result, ExistingReportMatch):
report = SignalReport.objects.select_for_update().get(id=match_result.report_id, team_id=input.team_id)
# Soft-deleted reports shouldn't receive new signals at all. Generally, these
# won't be matched-to (since the associated signals are also deleted), but
# if a report is deleted while a signal that would match it is in-flight,
# this can happen. In these cases we skip the weight/count update and skip
# promotion, but we still emit the signal to ClickHouse, marked as deleted
# in metadata.
#
# We also soft-delete all stale signals for the deleted report (outside the
# transaction) so they stop showing up in semantic search and attracting
# future signals to the dead report.
if report.status == SignalReport.Status.DELETED:
report_id = str(report.id)
ts = input.timestamp or timezone.now()
metadata = {
"source_product": input.source_product,
"source_type": input.source_type,
"source_id": input.source_id,
"weight": input.weight,
"report_id": report_id,
"extra": input.extra,
"remediation": input.remediation,
"deleted": True,
"total_spend": spend.total_spend if spend else 0,
"spend_accounting_failed_stages": spend.failed_stages if spend else [],
}
metadata["match_metadata"] = asdict(match_result.match_metadata)
emit_embedding_request(
content=input.description,
team_id=input.team_id,
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,
metadata=metadata,
)
return AssignAndEmitDbResult(
report_id=report_id,
promoted=False,
timestamp=ts,
matched_deleted_report=True,
run_count=report.run_count,
reresearch_capped=False,
report_status=report.status,
report_signal_count=report.signal_count,
promotion_suppressed=False,
next_research_bucket=None,
)
# Wrong-repo feedback rejects the repository choice rather than the issue, so new
# evidence needs fresh research, just as it does after a fixed verdict.
report = signal_target_report(report, lock=True)
if forks_recurrence(report):
parent_report = report
# A failed report often holds only the matcher's first guess, so the fork keeps
# its content only when a research pass completed.
inherit_content = (
parent_report.status != SignalReport.Status.FAILED or _has_completed_research(parent_report)
) and not _is_safety_suppressed(str(parent_report.id), input.team_id)
report = SignalReport.objects.create(
team_id=input.team_id,
status=SignalReport.Status.POTENTIAL,
total_weight=input.weight,
signal_count=1,
title=parent_report.title if inherit_content else "",
summary=parent_report.summary if inherit_content else "",
billing_exempt_reason=monitoring_billing_exemption
or BILLING_EXEMPT_SOURCE_PRODUCTS.get(input.source_product),
)
SignalReportArtefact.add_log(
team_id=input.team_id,
report_id=str(report.id),
content=ReportLink(kind=ReportLinkKind.RECURRENCE_OF, report_id=str(parent_report.id)),
attribution=ArtefactAttribution.system(),
write_path=ReportLinkWritePath.PIPELINE,
)
else:
report.total_weight += input.weight
report.signal_count += 1
update_fields = ["total_weight", "signal_count", "updated_at"]
# A research pass writes the title together with the summary. A later signal must
# not rename the report away from the cause that the summary explains.
if input.updated_title and not _has_completed_research(report):
report.title = input.updated_title
update_fields.append("title")
report.save(update_fields=update_fields)
else:
report = SignalReport.objects.create(
team_id=input.team_id,
status=SignalReport.Status.POTENTIAL,
total_weight=input.weight,
signal_count=1,
title=match_result.title,
summary=match_result.summary,
# A report born from a PostHog-system signal (e.g. health checks) must never
# bill the customer. Only this founding signal decides: signals that join the
# report later (the branch above) leave the exemption unchanged either way.
billing_exempt_reason=monitoring_billing_exemption
or BILLING_EXEMPT_SOURCE_PRODUCTS.get(input.source_product),
)
# Persist source exemptions before a summary can see and finalize this trigger.
if system_source_exempt(input.source_product):
begin_report_spend(
team_id=input.team_id,
report_id=str(report.id),
signal_id=input.signal_id,
billing_exempt=True,
)
# Promotion rules by status:
# - SUPPRESSED: never promoted. Fixed and wrong-repo dismissals spawn a fresh report above.
# - FAILED: never promoted. Unless a pull request is open or merged, a new signal spawns a fresh report above.
# - 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 once the report has reached its next bucket in
# RESEARCH_SIGNAL_BUCKETS. Material revisions from a report's source bypass the
# buckets so the researched content stays current.
# - 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
source_refresh = isinstance(match_result, ExistingReportMatch) and match_result.source_synced
reresearch_capped = (
is_reresearch and not source_refresh and (bucket is None or report.signal_count < bucket)
)
if (
(is_reresearch and not reresearch_capped)
or report.status == SignalReport.Status.CANDIDATE
or (
report.status == SignalReport.Status.POTENTIAL
and report.total_weight >= WEIGHT_THRESHOLD
and report.signal_count >= report.signals_at_run
)
):
if suppress_promotion:
# The team's org is over its self-driving credits quota with enforcement on, or
# the team hit its daily report limit: the signal is still assigned, weighted,
# and emitted, but no summary run spawns. The status is left untouched, so the
# first matching signal after the limit lifts re-evaluates promotion under the
# same rules.
promotion_suppressed = True
else:
updated_fields = (
report.transition_to(SignalReport.Status.CANDIDATE)
if report.status != SignalReport.Status.CANDIDATE
else []
)
if updated_fields or report.triggering_signal_id is None:
report.triggering_signal_id = input.signal_id
report.save(update_fields=[*updated_fields, "triggering_signal_id"])
promoted = True
pending_bucket = next_research_bucket(report.researching_signal_count or 0)
if report.status == SignalReport.Status.IN_PROGRESS and (
source_refresh
or (
report.pending_triggering_signal_id is None
and pending_bucket is not None
and report.signal_count >= pending_bucket
)
):
displaced_signal_id = report.pending_triggering_signal_id
report.pending_triggering_signal_id = input.signal_id
report.save(update_fields=["pending_triggering_signal_id"])
if displaced_signal_id is not None and str(displaced_signal_id) != input.signal_id:
complete_signal_pipeline(
team_id=input.team_id,
signal_id=str(displaced_signal_id),
report_id=str(report.id),
)
report_id = str(report.id)
if input.sync_with_source:
SignalEmissionRecord.objects.update_or_create(
team_id=input.team_id,
source_product=input.source_product,
source_type=input.source_type,
source_id=input.source_id,
defaults={
"emitted_at": timezone.now(),
"signal_id": input.signal_id,
"report_id": report_id,
},
)
_link_check_follow_up(
team_id=input.team_id,
report_id=report_id,
source_product=input.source_product,
extra=input.extra,
)
metadata = {
"source_product": input.source_product,
"source_type": input.source_type,
"source_id": input.source_id,
"weight": input.weight,
"report_id": report_id,
"total_spend": spend.total_spend if spend else 0,
"spend_accounting_failed_stages": spend.failed_stages if spend else [],
"extra": input.extra,
"remediation": input.remediation,
}
metadata["match_metadata"] = asdict(match_result.match_metadata)
ts = input.timestamp or timezone.now()
emit_embedding_request(
content=input.description,
team_id=input.team_id,
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,
metadata=metadata,
)
return AssignAndEmitDbResult(
report_id=report_id,
promoted=promoted,
triggering_signal_id=str(report.triggering_signal_id) if report.triggering_signal_id else None,
timestamp=ts,
matched_deleted_report=False,
run_count=report.run_count,
reresearch_capped=reresearch_capped,
report_status=report.status,
report_signal_count=report.signal_count,
promotion_suppressed=promotion_suppressed,
next_research_bucket=bucket,
report_signals_researched=signals_researched,
report_title=report.title,
)
try:
team = await Team.objects.select_related("organization").aget(pk=input.team_id)
# Resolved before the assign transaction: the gates are Redis/Postgres + flag network I/O
# that must not run while holding the report row lock.
quota_gate = await database_sync_to_async(self_driving_quota_gate, thread_sensitive=False)(team)
daily_gate = await database_sync_to_async(daily_report_limit_gate, thread_sensitive=False)(team)
db_result = await database_sync_to_async(do_assign_and_emit, thread_sensitive=False)(
quota_gate.enforced or daily_gate.limited
)
# If we matched a deleted report, soft-delete all its stale signals in ClickHouse.
# This prevents data corruption where non-deleted signals for a deleted report
# keep attracting new signals into the dead group.
if db_result.matched_deleted_report:
await database_sync_to_async(soft_delete_report_signals, thread_sensitive=False)(
report_id=db_result.report_id,
team_id=input.team_id,
team=team,
)
logger.info(
"Soft-deleted stale signals for deleted report encountered during grouping",
report_id=db_result.report_id,
team_id=input.team_id,
signal_id=input.signal_id,
)
# Track signals deduped into a dismissed (deleted) reports
try:
posthoganalytics.capture(
event="signal_matched_deleted_report",
distinct_id=str(team.uuid),
properties={
"source_product": input.source_product,
"source_type": input.source_type,
"source_id": input.source_id,
"report_id": db_result.report_id,
},
groups=groups(team.organization, team),
)
except Exception as e:
posthoganalytics.capture_exception(e)
logger.exception(
"Failed to capture signal_matched_deleted_report event",
report_id=db_result.report_id,
team_id=input.team_id,
source_id=input.source_id,
)
else:
try:
posthoganalytics.capture(
event="signal_assigned_to_report",
distinct_id=str(team.uuid),
properties={
"source_product": input.source_product,
"source_type": input.source_type,
"source_id": input.source_id,
"report_id": db_result.report_id,
"is_new_report": isinstance(match_result, NewReportMatch),
"promoted": db_result.promoted,
},
groups=groups(team.organization, team),
)
if isinstance(match_result, ExistingReportMatch) and match_result.source_synced:
posthoganalytics.capture(
event="signal_source_report_refresh_requested",
distinct_id=str(team.uuid),
properties={
"source_product": input.source_product,
"source_type": input.source_type,
"source_id": input.source_id,
"report_id": db_result.report_id,
"previous_report_id": match_result.report_id,
"created_recurrence": db_result.report_id != match_result.report_id,
"promoted": db_result.promoted,
},
groups=groups(team.organization, team),
)
except Exception as e:
posthoganalytics.capture_exception(e)
# Swallow the exception, to avoid breaking the flow over failed analytics event
logger.exception(
"Failed to capture signal_assigned_to_report event",
report_id=db_result.report_id,
team_id=input.team_id,
source_id=input.source_id,
)
if isinstance(match_result, ExistingReportMatch) and match_result.source_issue_matched:
await _schedule_writeback_for_source_issue_signal(input, db_result.report_id)
# 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(
event="signal_report_reresearch_skipped",
distinct_id=str(team.uuid),
properties={
"report_id": db_result.report_id,
"signal_count": db_result.report_signal_count,
"status": db_result.report_status,
"source_product": input.source_product,
"source_type": input.source_type,
"source_id": input.source_id,
"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),
)
except Exception as e:
posthoganalytics.capture_exception(e)
logger.exception(
"Failed to capture signal_report_reresearch_skipped event",
report_id=db_result.report_id,
team_id=input.team_id,
source_id=input.source_id,
)
# Emitted only when the signal would have promoted the report, so the event volume
# measures withheld summary runs rather than every assignment on a limited team. Both
# events fire when both limits are hit, keeping each stream complete for its own gate.
if quota_gate.limited and (db_result.promoted or db_result.promotion_suppressed):
capture_signal_report_quota_paused(
team, report_id=db_result.report_id, stage="promotion", enforced=quota_gate.enforced
)
if daily_gate.limited and (db_result.promoted or db_result.promotion_suppressed):
capture_signal_report_daily_limit_paused(
team, report_id=db_result.report_id, stage="promotion", gate=daily_gate
)
if not db_result.matched_deleted_report:
metrics.increment_funnel(metrics.FUNNEL_STAGE_GROUPED, input.source_product)
if db_result.promoted:
metrics.increment_funnel(metrics.FUNNEL_STAGE_PROMOTED, input.source_product)
logger.debug(
f"Assigned and emitted signal to report {db_result.report_id}",
report_id=db_result.report_id,
team_id=input.team_id,
signal_id=input.signal_id,
promoted=db_result.promoted,
is_new_report=isinstance(match_result, NewReportMatch),
)
report_title = db_result.report_title
# The matcher blanks an unsafe report's title, so the batch context must not bring it back.
if report_title and await database_sync_to_async(_is_safety_suppressed, thread_sensitive=False)(
db_result.report_id, input.team_id
):
report_title = ""
return AssignAndEmitSignalOutput(
report_id=db_result.report_id,
promoted=db_result.promoted,
triggering_signal_id=db_result.triggering_signal_id,
timestamp=db_result.timestamp,
run_count=db_result.run_count,
research_debounce_seconds=RESEARCH_DEBOUNCE_SECONDS,
report_title=report_title,
)
except Exception as e:
logger.exception(
f"Failed to assign/emit signal: {e}",
team_id=input.team_id,
signal_id=input.signal_id,
)
raise
CONTINUE_AS_NEW_THRESHOLD = 20
BATCH_SIZE = 5
BATCH_DEBOUNCE_SECONDS = 5
TYPE_EXAMPLES_CACHE_TTL = timedelta(minutes=5)
@dataclass
class _ProcessedBatchSignal:
"""A signal processed earlier in the current batch, used to augment later signals' candidates."""
signal_id: str
report_id: str
content: str
source_product: str
source_type: str
embedding: list[float]
def _cosine_distance(a: list[float], b: list[float]) -> float:
"""Compute cosine distance between two embedding vectors."""
a_arr = np.asarray(a)
b_arr = np.asarray(b)
norm_a = np.linalg.norm(a_arr)
norm_b = np.linalg.norm(b_arr)
if norm_a == 0.0 or norm_b == 0.0:
return 1.0
return 1.0 - float(np.dot(a_arr, b_arr) / (norm_a * norm_b))
def _augment_candidates_with_batch(
query_embeddings: list[list[float]],
ch_candidates_per_query: list[list[SignalCandidate]],
processed_signals: list[_ProcessedBatchSignal],
limit: int = 10,
) -> list[list[SignalCandidate]]:
"""Augment CH search results with earlier-in-batch signals via local cosine distance."""
if not processed_signals:
return ch_candidates_per_query
augmented = []
for query_emb, ch_candidates in zip(query_embeddings, ch_candidates_per_query):
candidates = list(ch_candidates)
worst_distance = candidates[-1].distance if candidates else float("inf")
for ps in processed_signals:
dist = _cosine_distance(query_emb, ps.embedding)
if len(candidates) < limit or dist < worst_distance:
candidates.append(
SignalCandidate(
signal_id=ps.signal_id,
report_id=ps.report_id,
content=ps.content,
source_product=ps.source_product,
source_type=ps.source_type,
distance=dist,
)
)
candidates.sort(key=lambda c: c.distance)
augmented.append(candidates[:limit])
return augmented
@frozen
class SignalGroupingCompletion:
team_id: int
signal_id: str
report_id: str | None
billing_exempt: bool
@temporalio.activity.defn
@scoped_temporal()
@close_db_connections
async def complete_signal_grouping_activity(signals: list[SignalGroupingCompletion]) -> None:
for signal in signals:
await database_sync_to_async(complete_signal_pipeline)(
team_id=signal.team_id,
signal_id=signal.signal_id,
report_id=signal.report_id,
billing_exempt=signal.billing_exempt,
)
async def _complete_signal_batch(batch: list[EmitSignalInputs], reports: dict[str, str]) -> None:
if not workflow.patched("signals-owner-spend-grouping-completion"):
return
try:
await workflow.execute_activity(
complete_signal_grouping_activity,
[
SignalGroupingCompletion(
team_id=signal.team_id,
signal_id=signal.signal_id,
report_id=reports.get(signal.signal_id),
billing_exempt=system_source_exempt(signal.source_product),
)
for signal in batch
if signal.signal_id
],
start_to_close_timeout=timedelta(minutes=1),
schedule_to_close_timeout=timedelta(minutes=20),
retry_policy=RetryPolicy(initial_interval=timedelta(seconds=5), maximum_interval=timedelta(seconds=30)),
)
except temporalio.exceptions.ActivityError:
workflow.logger.exception("signals.spend.accounting_failed", extra={"stage": "grouping_completion"})
async def _process_signal_batch(
batch: list[EmitSignalInputs],
cached_type_examples: Optional[FetchSignalTypeExamplesOutput] = None,
) -> tuple[int, FetchSignalTypeExamplesOutput]:
"""
Process a batch of signals with parallel preparation (steps 1-4) and sequential
matching/assignment (steps 5-7). Returns (dropped_count, type_examples) — the
caller can cache the type_examples for subsequent batches.
Earlier signals in the batch are injected into later signals' candidate sets via
local cosine distance comparison, eliminating the need for per-signal CH waits
within a batch.
"""
team_id = batch[0].team_id
original_batch = batch
# Purely defensive
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) ===
try:
semantic_indices = [
i for i, signal in enumerate(batch) if not (signal.source_match_signal_id and signal.source_match_report_id)
]
# Step 1a: Fetch type examples if not cached (needed by query gen)
if cached_type_examples is not None:
type_examples_result = cached_type_examples
elif semantic_indices:
type_examples_result = await workflow.execute_activity(
fetch_signal_type_examples_activity,
FetchSignalTypeExamplesInput(team_id=team_id),
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(maximum_attempts=3),
)
else:
type_examples_result = FetchSignalTypeExamplesOutput(examples=[])
# Step 1b: Embed all signals + generate search queries in parallel
# (query gen needs type examples but NOT the signal embeddings)
semantic_signals = [batch[i] for i in semantic_indices]
query_inputs = semantic_signals
query_result_indices = list(range(len(semantic_signals)))
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 semantic_signals:
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(
get_embedding_activity,
GenerateEmbeddingInput(team_id=team_id, content=s.description),
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(maximum_attempts=3),
)
for s in batch
],
*[
workflow.execute_activity(
generate_search_queries_activity,
GenerateSearchQueriesInput(
signal_id=s.signal_id,
team_id=team_id,
description=s.description,
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 query_inputs
],
)
signal_embeddings = cast(list[GenerateEmbeddingOutput], step1b_results[: len(batch)])
query_outputs = cast(list[GenerateSearchQueriesOutput], step1b_results[len(batch) :])
query_gen_results = [GenerateSearchQueriesOutput(queries=[]) for _ in batch]
for batch_index, query_index in zip(semantic_indices, query_result_indices, strict=True):
query_gen_results[batch_index] = query_outputs[query_index]
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:
await _complete_signal_batch(original_batch, {})
return dropped, type_examples_result
# Step 3: Embed all queries across all signals (flatten → parallel embed)
all_queries_flat: list[tuple[int, str]] = []
for sig_idx, qr in enumerate(query_gen_results):
for q in qr.queries:
all_queries_flat.append((sig_idx, q))
all_query_embeddings: list[GenerateEmbeddingOutput] = list(
await asyncio.gather(
*[
workflow.execute_activity(
get_embedding_activity,
GenerateEmbeddingInput(team_id=team_id, content=q_text),
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(maximum_attempts=3),
)
for _, q_text in all_queries_flat
]
)
)
# Step 4: Semantic search for all queries (all parallel)
all_search_results: list[RunSignalSemanticSearchOutput] = list(
await asyncio.gather(
*[
workflow.execute_activity(
run_signal_semantic_search_activity,
RunSignalSemanticSearchInput(team_id=team_id, embedding=emb.embedding, limit=10),
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(maximum_attempts=3),
)
for emb in all_query_embeddings
]
)
)
# Regroup flat results back to per-signal
# Each query becomes an embedding vector for lookup
type EmbeddingVector = list[float]
# For each new signal, we generate a number N of query strings
type SignalQueries = list[str]
# For each new signal, we generate an embedding for each query (so N embeddings)
type SignalQueryEmbeddings = list[EmbeddingVector]
# For each new signal, for each query, we get a list of M candidates back (10 at time of writing)
type SignalQueryResults = list[SignalCandidate]
# For each new signal, we run each query, so we get N * M total candidates for matching (although we fold down overlap across queries)
type SignalMatchCandidates = list[SignalQueryResults]
per_signal_queries: list[SignalQueries] = [[] for _ in batch]
per_signal_query_embeddings: list[SignalQueryEmbeddings] = [[] for _ in batch]
per_signal_ch_results: list[SignalMatchCandidates] = [[] for _ in batch]
for flat_idx, (sig_idx, q_text) in enumerate(all_queries_flat):
per_signal_queries[sig_idx].append(q_text)
per_signal_query_embeddings[sig_idx].append(all_query_embeddings[flat_idx].embedding)
per_signal_ch_results[sig_idx].append(all_search_results[flat_idx].candidates)
# Step 4.5: Fetch report contexts for all CH candidates (group-aware matching)
all_candidate_report_ids = list(
{c.report_id for results in all_search_results for c in results.candidates}
| {signal.source_match_report_id for signal in batch if signal.source_match_report_id}
)
report_contexts_result: FetchReportContextsOutput = await workflow.execute_activity(
fetch_report_contexts_activity,
FetchReportContextsInput(team_id=team_id, report_ids=all_candidate_report_ids),
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(maximum_attempts=3),
)
report_contexts: dict[str, ReportContext] = report_contexts_result.contexts
except Exception as e:
# Nothing has been emitted yet, so the whole batch is explainable as dropped.
# The outer workflow handler can't emit these: it also catches post-emission
# failures (the CH wait in step 7), where signals were successfully assigned.
logger.exception(
"Failed to prepare signal batch",
team_id=team_id,
batch_size=len(batch),
)
await asyncio.gather(*(capture_signal_dropped(signal, e, stage="grouping_prep") for signal in batch))
raise
# === SEQUENTIAL PHASE (steps 5-7) ===
_PATCH_PARALLEL_SEQUENTIAL = "parallel-sequential-phase-v1"
_use_parallel_sequential = workflow.patched(_PATCH_PARALLEL_SEQUENTIAL)
processed_batch_signals: list[_ProcessedBatchSignal] = []
promoted_reports: dict[str, tuple[SignalReportSummaryWorkflowInputs, int]] = {}
emitted_signals: list[tuple[str, AssignAndEmitSignalOutput]] = []
if _use_parallel_sequential:
from products.signals.backend.temporal.parallel_grouping import process_sequential_phase_parallel
_par = await process_sequential_phase_parallel(
batch=batch,
team_id=team_id,
per_signal_queries=per_signal_queries,
per_signal_query_embeddings=per_signal_query_embeddings,
per_signal_ch_results=per_signal_ch_results,
signal_embeddings=[e.embedding for e in signal_embeddings],
report_contexts=report_contexts,
)
dropped += _par.dropped
promoted_reports = _par.promoted_reports
emitted_signals = _par.emitted_signals
for i, signal in enumerate(batch if not _use_parallel_sequential else []):
signal_id = signal.signal_id or str(uuid.uuid4())
try:
# Augment CH candidates with earlier-in-batch signals
augmented_results = _augment_candidates_with_batch(
per_signal_query_embeddings[i],
per_signal_ch_results[i],
processed_batch_signals,
limit=10,
)
# Step 5: Group-aware LLM match
match_result = await workflow.execute_activity(
match_signal_to_report_activity,
MatchSignalToReportInput(
signal_id=signal_id,
team_id=team_id,
description=signal.description,
source_product=signal.source_product,
source_type=signal.source_type,
queries=per_signal_queries[i],
query_results=augmented_results,
report_contexts=report_contexts,
source_id=signal.source_id,
sync_with_source=signal.sync_with_source,
source_match_signal_id=signal.source_match_signal_id,
source_match_report_id=signal.source_match_report_id,
),
start_to_close_timeout=timedelta(minutes=10),
retry_policy=RetryPolicy(maximum_attempts=5),
)
# Step 5.5: PR-specificity verification for existing matches
updated_title: Optional[str] = None
if isinstance(match_result, ExistingReportMatch) and not match_result.source_synced:
report_ctx = report_contexts.get(match_result.report_id)
report_title = (
match_result.report_title
if match_result.report_title is not None
else report_ctx.title
if report_ctx
else ""
)
group_signals_result: FetchSignalsForReportOutput = await workflow.execute_activity(
fetch_signals_for_report_activity,
FetchSignalsForReportInput(team_id=team_id, report_id=match_result.report_id),
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(maximum_attempts=3),
)
specificity_result: VerifyMatchSpecificityOutput = await workflow.execute_activity(
verify_match_specificity_activity,
VerifyMatchSpecificityInput(
signal_id=signal_id,
team_id=team_id,
report_id=match_result.report_id,
report_title=report_title,
new_signal_description=signal.description,
new_signal_source_product=signal.source_product,
new_signal_source_type=signal.source_type,
group_signals=group_signals_result.signals,
),
start_to_close_timeout=timedelta(minutes=10),
retry_policy=RetryPolicy(maximum_attempts=5),
)
specificity_meta = SpecificityMetadata(
pr_title=specificity_result.pr_title,
specific_enough=specificity_result.specific_enough,
reason=specificity_result.reason,
)
if specificity_result.specific_enough:
updated_title = specificity_result.pr_title
match_result.match_metadata.specificity = specificity_meta
else:
match_result = NewReportMatch(
title=signal.description.split("\n")[0],
summary=f"Split from group: {report_title}",
match_metadata=NoMatchMetadata(
reason=f'PR-specificity rejected: "{specificity_result.pr_title}" — {specificity_result.reason}',
specificity_rejection=specificity_meta,
),
)
# Step 6: Assign + emit
assign_result: AssignAndEmitSignalOutput = await workflow.execute_activity(
assign_and_emit_signal_activity,
AssignAndEmitSignalInput(
team_id=signal.team_id,
signal_id=signal_id,
description=signal.description,
weight=signal.weight,
source_product=signal.source_product,
source_type=signal.source_type,
source_id=signal.source_id,
extra=signal.extra,
embedding=signal_embeddings[i].embedding,
match_result=match_result,
updated_title=updated_title,
remediation=signal.remediation,
sync_with_source=signal.sync_with_source,
),
start_to_close_timeout=timedelta(minutes=5),
retry_policy=RetryPolicy(maximum_attempts=3),
)
# Track for augmenting later signals in the batch
processed_batch_signals.append(
_ProcessedBatchSignal(
signal_id=signal_id,
report_id=assign_result.report_id,
content=signal.description,
source_product=signal.source_product,
source_type=signal.source_type,
embedding=signal_embeddings[i].embedding,
)
)
emitted_signals.append((signal_id, assign_result))
# Update local report_contexts so later signals in the batch see this report
if isinstance(match_result, ExistingReportMatch):
old_ctx = report_contexts.get(assign_result.report_id)
report_contexts[assign_result.report_id] = ReportContext(
report_id=assign_result.report_id,
title=assign_result.report_title
if assign_result.report_title is not None
else updated_title or (old_ctx.title if old_ctx else ""),
signal_count=(old_ctx.signal_count if old_ctx else 0) + 1,
)
else:
report_contexts[assign_result.report_id] = ReportContext(
report_id=assign_result.report_id,
title=match_result.title,
signal_count=1,
)
if assign_result.promoted:
promoted_reports[assign_result.report_id] = (
SignalReportSummaryWorkflowInputs(
team_id=signal.team_id,
report_id=assign_result.report_id,
debounce_seconds=assign_result.research_debounce_seconds,
signal_id=assign_result.triggering_signal_id,
),
assign_result.run_count,
)
except Exception as e:
dropped += 1
logger.exception(
"Failed to process signal in batch",
team_id=team_id,
source_product=signal.source_product,
source_type=signal.source_type,
source_id=signal.source_id,
)
await capture_signal_dropped(signal, e, stage="grouping_sequential")
# Step 7: Wait for all emitted signals to land in CH so the next batch can find them
if emitted_signals:
await workflow.execute_activity(
wait_for_signal_in_clickhouse_activity,
WaitForClickHouseInput(
team_id=team_id,
signals=[
WaitForClickHouseSignal(signal_id=sid, timestamp=result.timestamp)
for sid, result in emitted_signals
],
max_wait_time_seconds=3600,
# 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),
retry_policy=RetryPolicy(maximum_attempts=2),
)
# Spawn summary workflows after CH wait. Stable ID + ALLOW_DUPLICATE: Temporal rejects concurrent
# starts with the same ID (caught below); re-spawning is allowed only if the previous run has closed.
for report_input, _run_count in promoted_reports.values():
try:
workflow_id = SignalReportSummaryWorkflow.workflow_id_for(report_input.team_id, report_input.report_id)
await workflow.start_child_workflow(
SignalReportSummaryWorkflow.run,
report_input,
id=workflow_id,
task_queue=settings.VIDEO_EXPORT_TASK_QUEUE,
parent_close_policy=ParentClosePolicy.ABANDON,
id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,
# The hour covers the research work; the two terms after it cover the workflow's own
# sleeps, which the hour was never sized for — the research debounce at entry and the
# implementation buffer at settle. A run that loops through several buffers can still
# outlive this; it's a backstop, and the report stays READY and re-promotes.
execution_timeout=timedelta(
hours=1, seconds=report_input.debounce_seconds + IMPLEMENTATION_DEBOUNCE_SECONDS
)
+ RESEARCH_SANDBOX_RETRY_BUDGET,
)
except temporalio.exceptions.WorkflowAlreadyStartedError:
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.
logger.exception(
"Failed to start summary workflow for promoted report; will retry on next signal",
team_id=report_input.team_id,
report_id=report_input.report_id,
)
await _complete_signal_batch(original_batch, {signal_id: result.report_id for signal_id, result in emitted_signals})
return dropped, type_examples_result
@temporalio.workflow.defn(name="team-signal-grouping")
class TeamSignalGroupingWorkflow:
"""
Long-running entity workflow that serializes signal grouping per team.
One instance per team (workflow ID: team-signal-grouping-{team_id}). Signals arrive
via @workflow.signal and are processed sequentially, eliminating race conditions
where concurrent workflows could assign related signals to different reports.
Uses continue_as_new after CONTINUE_AS_NEW_THRESHOLD signals to keep history bounded.
"""
def __init__(self) -> None:
self._signal_buffer: list[EmitSignalInputs] = []
self._signals_processed: int = 0
self._cached_type_examples: Optional[FetchSignalTypeExamplesOutput] = None
self._type_examples_fetched_at: Optional[datetime] = None
meter = workflow.metric_meter()
self._signals_received_counter = meter.create_counter(
"signals_grouping_signals_received",
"Total number of signals received for grouping",
)
self._buffer_size_gauge = meter.create_gauge(
"signals_grouping_buffer_size",
"Current number of signals buffered for processing",
)
self._signals_dropped_counter = meter.create_counter(
"signals_grouping_signals_dropped",
"Total number of signals dropped due to processing failure",
)
@staticmethod
def workflow_id_for(team_id: int) -> str:
return f"team-signal-grouping-{team_id}"
@temporalio.workflow.signal
async def submit_signal(self, signal: EmitSignalInputs) -> None:
# TODO - add some kind of limiting here, to prevent this growing forever
self._signal_buffer.append(signal)
self._signals_received_counter.add(1)
self._buffer_size_gauge.set(len(self._signal_buffer))
@temporalio.workflow.run
async def run(self, input: TeamSignalGroupingInput) -> None:
with posthoganalytics.new_context(capture_exceptions=False):
posthoganalytics.tag("team_id", input.team_id)
posthoganalytics.tag("product", "signals")
await self._run_impl(input)
async def _run_impl(self, input: TeamSignalGroupingInput) -> None:
self._signal_buffer.extend(input.pending_signals)
self._buffer_size_gauge.set(len(self._signal_buffer))
while True:
await workflow.wait_condition(lambda: len(self._signal_buffer) > 0)
# Debounce: wait briefly for more signals to accumulate
if len(self._signal_buffer) < BATCH_SIZE:
try:
await workflow.wait_condition(
lambda: len(self._signal_buffer) >= BATCH_SIZE,
timeout=timedelta(seconds=BATCH_DEBOUNCE_SECONDS),
)
except TimeoutError:
pass
batch: list[EmitSignalInputs] = []
while self._signal_buffer and len(batch) < BATCH_SIZE:
batch.append(self._signal_buffer.pop(0))
self._buffer_size_gauge.set(len(self._signal_buffer))
# Invalidate type examples cache if stale
now = workflow.now()
cached = self._cached_type_examples
if (
self._type_examples_fetched_at is not None
and (now - self._type_examples_fetched_at) > TYPE_EXAMPLES_CACHE_TTL
):
cached = None
try:
dropped, type_examples = await _process_signal_batch(batch, cached_type_examples=cached)
self._cached_type_examples = type_examples
self._type_examples_fetched_at = self._type_examples_fetched_at if cached is not None else now
self._signals_dropped_counter.add(dropped)
except Exception:
# Parallel phase failed — all signals in batch dropped
self._signals_dropped_counter.add(len(batch))
logger.exception(
"Failed to process signal batch",
team_id=input.team_id,
batch_size=len(batch),
)
self._signals_processed += len(batch)
if self._signals_processed >= CONTINUE_AS_NEW_THRESHOLD:
workflow.continue_as_new(
TeamSignalGroupingInput(
team_id=input.team_id,
pending_signals=list(self._signal_buffer),
)
)