: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): keep later signals on a report's researched cause (#114388)
posthog[bot]bf743fd79021
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txtindex 7371f549b82d..995a0f4342bb 100644--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt@@ -1297,7 +1297,7 @@1 products/web_analytics/backend/test/test_digest_notification_workflows.py1 products/web_analytics/backend/test/test_weekly_digest_workflows.py10 posthog/temporal/ai_observability/trace_summarization/models.py-10 products/signals/backend/temporal/grouping.py+9 products/signals/backend/temporal/grouping.py10 products/signals/backend/temporal/summary.py10 products/tasks/backend/temporal/process_task/activities/provision_sandbox.py104 posthog/hogql/ast.pydiff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex 86c22b1822f3..d246edfa7bd8 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -1225,6 +1225,8 @@ The validator ensures the returned `signal_id` and `query_index` are valid for tA second grouping-time LLM check used before broadening an existing report too aggressively.+After a research pass completes on a report, the check also receives the report's summary as the researched cause. A new signal joins only when the fix that the research describes also resolves it. A shared page, HTTP status, or product area is not enough. The check can rename a report only before its first research pass. After that pass, the research owns the title, so the title and the summary continue to describe the same cause.+### Safety filter (`backend/temporal/safety_filter.py`)Per-signal safety classifier that runs in the buffer workflow before signals are flushed to object storage.diff --git a/products/signals/backend/temporal/grouping.py b/products/signals/backend/temporal/grouping.pyindex 9ae4c6fc06e2..66175927d16b 100644--- a/products/signals/backend/temporal/grouping.py+++ b/products/signals/backend/temporal/grouping.py@@ -346,6 +346,11 @@ None of these are reasons to split: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": "..."}"""@@ -357,6 +362,7 @@ class SpecificityResult(BaseModel):MAX_SIGNALS_IN_SPECIFICITY_CONTEXT = 8+MAX_RESEARCHED_SUMMARY_CHARS = 2000def _build_matching_prompt(@@ -412,11 +418,16 @@ def _build_specificity_prompt(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)"}-- Signals ({len(group_signals)} total):+"""+ 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"""@@ -610,6 +621,7 @@ async def verify_match_specificity(new_signal_source_type: str,report_title: str,group_signals: list[SignalData],+ 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(@@ -618,6 +630,7 @@ async def verify_match_specificity(new_signal_source_type=new_signal_source_type,report_title=report_title,group_signals=group_signals,+ researched_summary=researched_summary,)specificity = await call_llm(@@ -638,12 +651,41 @@ async def verify_match_specificity()+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 == SignalReport.Status.READY+++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_connectionsasync 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,@@ -651,6 +693,7 @@ async def verify_match_specificity_activity(input: VerifyMatchSpecificityInput)new_signal_source_type=input.new_signal_source_type,report_title=input.report_title,group_signals=input.group_signals,+ researched_summary=researched_summary,)logger.debug(@@ -689,13 +732,16 @@ class AssignAndEmitSignalInput:remediation: Optional[dict] = None-@dataclass+@dataclass(frozen=False)class AssignAndEmitSignalOutput:report_id: strpromoted: booltimestamp: datetimerun_count: intresearch_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@frozen@@ -715,6 +761,7 @@ class AssignAndEmitDbResult: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] = Nonedef _link_check_follow_up(*, team_id: int, report_id: str, source_product: str, extra: dict) -> None:@@ -845,7 +892,9 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> Asreport.total_weight += input.weightreport.signal_count += 1update_fields = ["total_weight", "signal_count", "updated_at"]- if input.updated_title:+ # 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_titleupdate_fields.append("title")report.save(update_fields=update_fields)@@ -953,6 +1002,7 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> Aspromotion_suppressed=promotion_suppressed,next_research_bucket=bucket,report_signals_researched=signals_researched,+ report_title=report.title,)try:@@ -1083,12 +1133,19 @@ async def assign_and_emit_signal_activity(input: AssignAndEmitSignalInput) -> Aspromoted=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,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(@@ -1471,7 +1528,9 @@ async def _process_signal_batch(old_ctx = report_contexts.get(assign_result.report_id)report_contexts[assign_result.report_id] = ReportContext(report_id=assign_result.report_id,- title=updated_title or (old_ctx.title if old_ctx else ""),+ 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:diff --git a/products/signals/backend/temporal/parallel_grouping.py b/products/signals/backend/temporal/parallel_grouping.pyindex 5e1c157f88c3..3dc95c64af58 100644--- a/products/signals/backend/temporal/parallel_grouping.py+++ b/products/signals/backend/temporal/parallel_grouping.py@@ -381,7 +381,9 @@ async def _process_parallel_batch(old_ctx = report_contexts.get(result.assign_result.report_id)report_contexts[result.assign_result.report_id] = ReportContext(report_id=result.assign_result.report_id,- title=result.updated_title or (old_ctx.title if old_ctx else ""),+ title=result.assign_result.report_title+ if result.assign_result.report_title is not None+ else result.updated_title or (old_ctx.title if old_ctx else ""),signal_count=(old_ctx.signal_count if old_ctx else 0) + 1,)else:diff --git a/products/signals/backend/test/test_assign_and_emit_signal.py b/products/signals/backend/test/test_assign_and_emit_signal.pyindex bbe9fcc186c5..a93b68fe7200 100644--- a/products/signals/backend/test/test_assign_and_emit_signal.py+++ b/products/signals/backend/test/test_assign_and_emit_signal.py@@ -24,8 +24,11 @@ from products.signals.backend.temporal.grouping import (WEIGHT_THRESHOLD,AssignAndEmitSignalInput,MatchSignalToReportInput,+ SpecificityResult,+ VerifyMatchSpecificityInput,assign_and_emit_signal_activity,match_signal_to_report_activity,+ verify_match_specificity_activity,)from products.signals.backend.temporal.types import (ExistingReportMatch,@@ -1021,6 +1024,97 @@ async def test_non_promoting_states_increment_counters_but_do_not_promote(ateam,assert refreshed.signal_count == 3+ ("status", "signals_at_run", "signals_researched", "unsafe", "expected_title"),+ [+ (SignalReport.Status.POTENTIAL, 0, None, False, "specificity title"),+ # A first run stamps signals_at_run when it starts, before its research completes.+ (SignalReport.Status.IN_PROGRESS, 7, None, False, "specificity title"),+ (SignalReport.Status.READY, 7, 4, False, "researched title"),+ (SignalReport.Status.READY, 7, 4, True, "researched title"),+ ],+)+async def test_specificity_title_only_renames_unresearched_reports(+ ateam, status, signals_at_run, signals_researched, unsafe, expected_title+):+ report = await database_sync_to_async(SignalReport.objects.create)(+ team=ateam,+ status=status,+ total_weight=0.5,+ signal_count=4,+ signals_at_run=signals_at_run,+ signals_researched=signals_researched,+ title="researched title",+ summary="researched summary",+ )+ if unsafe:+ await database_sync_to_async(SignalReportArtefact.objects.create)(+ team=ateam,+ report=report,+ type=SignalReportArtefact.ArtefactType.SAFETY_JUDGMENT,+ content='{"choice": false}',+ )+ input_ = _build_input(ateam.id, _existing_match(str(report.id)))+ input_.updated_title = "specificity title"++ result = await assign_and_emit_signal_activity(input_)++ refreshed = await database_sync_to_async(SignalReport.objects.get)(id=report.id)+ assert refreshed.title == expected_title+ assert result.report_title == ("" if unsafe else expected_title)+ assert refreshed.signal_count == 5+++ ("status", "signals_at_run", "signals_researched", "expect_summary_in_prompt"),+ [+ (SignalReport.Status.POTENTIAL, 0, None, False),+ # A first run stamps signals_at_run when it starts, before its research completes.+ (SignalReport.Status.IN_PROGRESS, 7, None, False),+ (SignalReport.Status.READY, 7, 4, True),+ # Researched before signals_researched existed: only the READY run stamp proves the pass.+ (SignalReport.Status.READY, 7, None, True),+ ],+)+async def test_specificity_gate_judges_against_the_researched_cause(+ ateam, status, signals_at_run, signals_researched, expect_summary_in_prompt+):+ report_title = "Handle failed source config loads"+ report = await database_sync_to_async(SignalReport.objects.create)(+ team=ateam,+ status=status,+ total_weight=0.5,+ signal_count=4,+ signals_at_run=signals_at_run,+ signals_researched=signals_researched,+ title=report_title,+ summary="The settings page crashes when the source config request fails.",+ )+ call_llm = AsyncMock(return_value=SpecificityResult(pr_title="t", specific_enough=False, reason="r"))++ with patch(f"{GROUPING_MODULE_PATH}.call_llm", call_llm):+ await verify_match_specificity_activity(+ VerifyMatchSpecificityInput(+ team_id=ateam.id,+ report_id=str(report.id),+ report_title=report_title,+ new_signal_description="Saving an autonomy setting returns a 500",+ new_signal_source_product="session_replay",+ new_signal_source_type="observation",+ group_signals=[],+ )+ )++ user_prompt = call_llm.call_args.kwargs["user_prompt"]+ assert ("The settings page crashes when the source config request fails." in user_prompt) is (+ expect_summary_in_prompt+ )++# ---------------------------------------------------------------------------# DELETED report short-circuit# ---------------------------------------------------------------------------