: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
chore(signals): add a report author to the scout emit path (#109083)
posthog[bot]603a6db472a1
diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.pyindex 3eb4b1b7bc3b..77ab96a0e0dc 100644--- a/products/signals/backend/scout_harness/tools/report.py+++ b/products/signals/backend/scout_harness/tools/report.py@@ -89,10 +89,10 @@ from products.signals.backend.scout_harness.tools.emit import (# Shared harness gates/attribution — the report channel applies the same preflight as emit._assert_team_owns_run,_preflight_emit_gates,- _resolve_task_id,remediation_for_skip,)from products.signals.backend.scout_harness.tools.notes import MAX_NOTE_CONTENT_LENGTH+from products.signals.backend.scout_harness.tools.report_author import ReportAuthor, ScoutRunReportAuthorfrom products.signals.backend.scout_report import (INFERRED_REPOSITORY_REASON,MAX_REPORT_SIGNALS,@@ -567,9 +567,9 @@ def _gate_skip_result(preflight: str) -> EmitReportResult:def _emit_idempotency_key(- *, run: SignalScoutRun, supplied: str | None, title: str, summary: str, evidence: list[ReportEvidence]+ *, author: ReportAuthor, supplied: str | None, title: str, summary: str, evidence: list[ReportEvidence]) -> str:- """The key this emission is stored under, always scoped to the authoring run.+ """The key this emission is stored under, always scoped to the author (for a scout, the authoring run).A supplied key is the caller's own name for the emission, so a retry that rewords the report stillresolves to the first one. Without a key the report's identity is the key, which still covers the@@ -583,11 +583,11 @@ def _emit_idempotency_key(raise InvalidScoutReportError("idempotency_key must not be blank")if len(key) > MAX_IDEMPOTENCY_KEY_LENGTH:raise InvalidScoutReportError(f"idempotency_key must be at most {MAX_IDEMPOTENCY_KEY_LENGTH} characters")- return f"{run.id}:key:{key}"+ return f"{author.idempotency_scope}:key:{key}"content = json.dumps([title, summary, [[item.source_id, item.description] for item in evidence]], separators=(",", ":"))- return f"{run.id}:auto:{hashlib.sha256(content.encode()).hexdigest()}"+ return f"{author.idempotency_scope}:auto:{hashlib.sha256(content.encode()).hexdigest()}"def _replay_result(existing: ExistingScoutReport) -> EmitReportResult:@@ -613,10 +613,6 @@ def _emit_result(persisted_report_id: str, judgement: ScoutReportJudgement) -> E)-def _attribution_for(task_id: str | None) -> ArtefactAttribution:- return ArtefactAttribution.from_task(task_id) if task_id is not None else ArtefactAttribution.system()--def _build_priority(priority: str | None, explanation: str | None) -> PriorityAssessment | None:"""Build the `priority_judgment` artefact content from scout-supplied inputs, or None to omit it.@@ -1072,19 +1068,6 @@ def _report_classification_props(effective_title: str | None) -> dict[str, Any]:}-def _report_event_base(run: SignalScoutRun) -> dict[str, Any]:- """Shared dimensions for the report-channel lifecycle events, mirroring the `signals_scout_run_*`- events so the two join on `run_id` / `task_run_id` — a report event sits under the run that authored- it. All fields are plain columns on the bridge row (no FK query)."""- return {- "skill_name": run.skill_name,- "skill_version": run.skill_version,- "scout_config_id": str(run.scout_config_id) if run.scout_config_id else None,- "run_id": str(run.id),- "task_run_id": str(run.task_run_id) if run.task_run_id else None,- }--# Customer-facing copies of the report-channel lifecycle events, captured into the scout's *own team*# project (via `capture_internal`) — distinct from the `signals_scout_report_*` events above, which go to# PostHog's internal analytics via the `posthoganalytics` SDK. Landing them in the team's own event stream@@ -1235,7 +1218,7 @@ async def _forward_report_event_async(team: Team, forward: _ReportForward | Nonedef _capture_report_emitted(*,team: Team,- run: SignalScoutRun,+ author: ReportAuthor,result: EmitReportResult,evidence_count: int,title: str,@@ -1278,7 +1261,7 @@ def _capture_report_emitted(else:outcome = "suppressed"properties = {- **_report_event_base(run),+ **author.event_properties(),**_report_classification_props(title),"report_id": result.report_id,"status": result.status,@@ -1309,14 +1292,14 @@ def _capture_report_emitted(except Exception:logger.warning("signals_scout: failed to capture report-emitted analytics event",- extra={"team_id": team.id, "run_id": str(run.id), "skill_name": run.skill_name},+ extra={"team_id": team.id, **author.log_extra()},)if result.skipped_reason in _INACTIVE_SKIP_REASONS:return Nonereturn _ReportForward(event_name=CUSTOMER_REPORT_EMITTED_EVENT,- distinct_id=f"signals_scout:{run.skill_name}",- event_uuid=_report_event_uuid("emit", run.id, result.report_id, title),+ distinct_id=author.distinct_id,+ event_uuid=_report_event_uuid("emit", author.idempotency_scope, result.report_id, title),properties=properties,)@@ -1351,8 +1334,9 @@ def _capture_report_edited(streams stay quiet rather than telling a CDP destination a report changed when it didn't."""if not result.changed:return None+ author = ScoutRunReportAuthor(run=run)properties = {- **_report_event_base(run),+ **author.event_properties(),**_report_classification_props(result.report_title),"report_id": result.report_id,"updated_fields": result.updated_fields,@@ -1388,7 +1372,7 @@ def _capture_report_edited(except Exception:logger.warning("signals_scout: failed to capture report-edited analytics event",- extra={"team_id": team.id, "run_id": str(run.id), "skill_name": run.skill_name},+ extra={"team_id": team.id, **author.log_extra()},)# Sort `updated_fields` so a retried edit that changed the same set hashes to one `event_uuid` — the# set's iteration order isn't guaranteed stable across worker processes, and an unstable key would@@ -1458,7 +1442,7 @@ def _capture_report_edited(parts.append(f"links:{json.dumps(written, separators=(',', ':'))}")return _ReportForward(event_name=CUSTOMER_REPORT_EDITED_EVENT,- distinct_id=f"signals_scout:{run.skill_name}",+ distinct_id=author.distinct_id,event_uuid=_report_event_uuid(*parts,structured=charts is not None@@ -1475,7 +1459,7 @@ def _capture_report_edited(async def emit_report(*,team: Team,- run: SignalScoutRun,+ author: ReportAuthor,title: str,summary: str,evidence: list[ReportEvidence],@@ -1508,7 +1492,7 @@ async def emit_report(`idempotency_key` names this emission, so a retry after a timeout returns the first report insteadof a twin (see `_emit_idempotency_key`). One is derived from the content when the caller suppliesnone, so a resent call is safe either way."""- _assert_team_owns_run(team, run)+ author.assert_owned_by(team)_validate_emit_inputs(title, summary, evidence)chart_contents = _build_charts(charts)# Off the loop because the gate reads a feature flag, which can block on the flag service.@@ -1524,13 +1508,15 @@ async def emit_report(explanation=actionability_explanation, choice=actionability, already_addressed=already_addressed)priority_assessment = _build_priority(priority, priority_explanation)- emit_key = _emit_idempotency_key(run=run, supplied=idempotency_key, title=title, summary=summary, evidence=evidence)+ emit_key = _emit_idempotency_key(+ author=author, supplied=idempotency_key, title=title, summary=summary, evidence=evidence+ )async def finish(result: EmitReportResult) -> EmitReportResult:# Every exit reports the same call, so the capture and the fan-out sit here, not beside each return.forward = await database_sync_to_async(_capture_report_emitted, thread_sensitive=False)(team=team,- run=run,+ author=author,result=result,evidence_count=len(evidence),title=title,@@ -1558,17 +1544,16 @@ async def emit_report(# Resolves user_uuid → github_login (a DB read), so bridge it off the event loop. Runs before the# safety judge so an unresolvable reviewer fails fast rather than after paying for the LLM call.reviewers = await database_sync_to_async(_build_suggested_reviewers, thread_sensitive=False)(- team, suggested_reviewers, skill_name=run.skill_name+ team, suggested_reviewers, skill_name=author.skill_name)- preflight = await database_sync_to_async(_preflight_emit_gates, thread_sensitive=False)(team, run)+ preflight = await database_sync_to_async(author.preflight_skip_reason, thread_sensitive=False)(team)if preflight is not None:return await finish(_gate_skip_result(preflight))await database_sync_to_async(_assert_emit_link_targets_live, thread_sensitive=False)(team, built_links)- task_id = await database_sync_to_async(_resolve_task_id, thread_sensitive=False)(run)- attribution = _attribution_for(task_id)+ attribution = await database_sync_to_async(author.attribution, thread_sensitive=False)()judgement = await judge_scout_report(team_id=team.id,title=title,@@ -1598,7 +1583,7 @@ async def emit_report(# Re-stamp owner provenance from the live owner set after the judge wait (see# `_stamp_owner_provenance`) — autostart trusts the stored stamp.reviewers = await database_sync_to_async(_stamp_owner_provenance, thread_sensitive=False)(- team, reviewers, skill_name=run.skill_name+ team, reviewers, skill_name=author.skill_name)try:persisted = await database_sync_to_async(create_scout_report, thread_sensitive=False)(@@ -1624,7 +1609,7 @@ async def emit_report(# Don't index the backing observations of a safety-suppressed (unsafe) report — they'd# otherwise become semantic-search / matching context despite never surfacing.emit_signals=judgement.safety.choice,- run=run,+ run=author.scout_run,idempotency_key=emit_key,)except ScoutReportAlreadyEmittedError as already_emitted:@@ -1632,14 +1617,15 @@ async def emit_report(# report is the answer, and the Slack delivery and autostart below are its business, not ours.return await finish(_replay_result(already_emitted.existing))if surfaced:- await database_sync_to_async(queue_configured_scout_slack_delivery, thread_sensitive=False)(- run_id=run.id,- output_type="report",- output_id=persisted.report_id,- # A report is emitted once, so its id is the natural idempotency key (mirrors- # findings using the emission id); edits keep per-delivery ids since each notifies.- delivery_id=persisted.report_id,- )+ if author.scout_run is not None:+ await database_sync_to_async(queue_configured_scout_slack_delivery, thread_sensitive=False)(+ run_id=author.scout_run.id,+ output_type="report",+ output_id=persisted.report_id,+ # A report is emitted once, so its id is the natural idempotency key (mirrors+ # findings using the emission id); edits keep per-delivery ids since each notifies.+ delivery_id=persisted.report_id,+ )await _maybe_autostart_report(team_id=team.id, report_id=persisted.report_id)return await finish(_emit_result(persisted.report_id, judgement))@@ -1647,7 +1633,7 @@ async def emit_report(def emit_report_sync(*,team: Team,- run: SignalScoutRun,+ author: ReportAuthor,title: str,summary: str,evidence: list[ReportEvidence],@@ -1669,7 +1655,7 @@ def emit_report_sync(selection, and the autostart hand-off are bridged via `async_to_sync` (each runs before/after thereport transaction, so they don't share its connection). Wrapping the whole async function insteadwould run every DB op on a separate connection, which a request's transaction can't see."""- _assert_team_owns_run(team, run)+ author.assert_owned_by(team)_validate_emit_inputs(title, summary, evidence)chart_contents = _build_charts(charts)metric_contents = _build_metrics(_allowed_metrics(team, metrics))@@ -1683,13 +1669,15 @@ def emit_report_sync(explanation=actionability_explanation, choice=actionability, already_addressed=already_addressed)priority_assessment = _build_priority(priority, priority_explanation)- emit_key = _emit_idempotency_key(run=run, supplied=idempotency_key, title=title, summary=summary, evidence=evidence)+ emit_key = _emit_idempotency_key(+ author=author, supplied=idempotency_key, title=title, summary=summary, evidence=evidence+ )def finish(result: EmitReportResult) -> EmitReportResult:# The sync twin of `emit_report.finish` — see there for why the capture lives in one place.forward = _capture_report_emitted(team=team,- run=run,+ author=author,result=result,evidence_count=len(evidence),title=title,@@ -1711,16 +1699,15 @@ def emit_report_sync(if existing is not None:return finish(_replay_result(existing))- reviewers = _build_suggested_reviewers(team, suggested_reviewers, skill_name=run.skill_name)+ reviewers = _build_suggested_reviewers(team, suggested_reviewers, skill_name=author.skill_name)- preflight = _preflight_emit_gates(team, run)+ preflight = author.preflight_skip_reason(team)if preflight is not None:return finish(_gate_skip_result(preflight))_assert_emit_link_targets_live(team, built_links)- task_id = _resolve_task_id(run)- attribution = _attribution_for(task_id)+ attribution = author.attribution()judgement = async_to_sync(judge_scout_report)(team_id=team.id,title=title,@@ -1749,7 +1736,7 @@ def emit_report_sync(if surfaced and reviewers is not None:# Re-stamp owner provenance from the live owner set after the judge wait (see# `_stamp_owner_provenance`) — autostart trusts the stored stamp.- reviewers = _stamp_owner_provenance(team, reviewers, skill_name=run.skill_name)+ reviewers = _stamp_owner_provenance(team, reviewers, skill_name=author.skill_name)try:persisted = create_scout_report(team_id=team.id,@@ -1774,19 +1761,20 @@ def emit_report_sync(# Don't index the backing observations of a safety-suppressed (unsafe) report — they'd# otherwise become semantic-search / matching context despite never surfacing.emit_signals=judgement.safety.choice,- run=run,+ run=author.scout_run,idempotency_key=emit_key,)except ScoutReportAlreadyEmittedError as already_emitted:# As in `emit_report`: a concurrent retry won the insert, so hand back its report.return finish(_replay_result(already_emitted.existing))if surfaced:- queue_configured_scout_slack_delivery(- run_id=run.id,- output_type="report",- output_id=persisted.report_id,- delivery_id=persisted.report_id,- )+ if author.scout_run is not None:+ queue_configured_scout_slack_delivery(+ run_id=author.scout_run.id,+ output_type="report",+ output_id=persisted.report_id,+ delivery_id=persisted.report_id,+ )async_to_sync(_maybe_autostart_report)(team_id=team.id, report_id=persisted.report_id)return finish(_emit_result(persisted.report_id, judgement))@@ -1825,7 +1813,7 @@ def _do_edit_report(if corroboration_only and not append_note:raise InvalidScoutReportError("corroboration_only requires append_note")- attribution = _attribution_for(_resolve_task_id(run))+ attribution = ScoutRunReportAuthor(run=run).attribution()updated_fields: list[str] = []note_appended = Falserepository_set = Falsediff --git a/products/signals/backend/scout_harness/tools/report_author.py b/products/signals/backend/scout_harness/tools/report_author.pynew file mode 100644index 000000000000..f73ea0a0b82a--- /dev/null+++ b/products/signals/backend/scout_harness/tools/report_author.py@@ -0,0 +1,109 @@+"""Who authors a report through the report channel.++`emit_report` reads every author-specific value through `ReportAuthor`: the idempotency scope, the+telemetry identity, the preflight gates, and the artefact attribution. A scout run is the only author+that exists. Another author, such as a user who calls the channel over the MCP, implements the same+protocol, so the emit path does not fork on who wrote the report.+"""++from __future__ import annotations++from typing import Any, Protocol++from posthog.dataclasses import frozen+from posthog.models import Team++from products.signals.backend.models import ArtefactAttribution, SignalScoutRun+from products.signals.backend.scout_harness.tools.emit import (+ _assert_team_owns_run,+ _preflight_emit_gates,+ _resolve_task_id,+)+++class ReportAuthor(Protocol):+ @property+ def scout_run(self) -> SignalScoutRun | None:+ """The run behind the report. It feeds the run's report tally, the provenance note, the+ `task_run` artefact, and the scout's configured Slack destination. None when no scout run+ authors the report, which skips all four."""+ ...++ @property+ def skill_name(self) -> str | None:+ """The skill whose owners get reviewer provenance stamps. None stamps no one."""+ ...++ @property+ def idempotency_scope(self) -> str:+ """The prefix of the stored emit key. A retry resolves to the first report only inside one+ scope, so two authors never replay each other's reports."""+ ...++ @property+ def distinct_id(self) -> str:+ """The distinct id of the customer-facing copy of the report events."""+ ...++ def event_properties(self) -> dict[str, Any]: ...++ def log_extra(self) -> dict[str, Any]: ...++ def assert_owned_by(self, team: Team) -> None: ...++ def preflight_skip_reason(self, team: Team) -> str | None:+ """The `skipped_reason` of the first gate that drops the emit, or None. Reads the DB, so call+ it on a sync thread."""+ ...++ def attribution(self) -> ArtefactAttribution:+ """Who the report's artefacts are attributed to. Reads the DB, so call it on a sync thread."""+ ...+++@frozen+class ScoutRunReportAuthor:+ run: SignalScoutRun++ @property+ def scout_run(self) -> SignalScoutRun | None:+ return self.run++ @property+ def skill_name(self) -> str | None:+ return self.run.skill_name++ @property+ def idempotency_scope(self) -> str:+ # Stored keys and event uuids hash this value. Changing its format lets a retry that crosses+ # a deploy author a second report and fire a second customer-facing event.+ return str(self.run.id)++ @property+ def distinct_id(self) -> str:+ return f"signals_scout:{self.run.skill_name}"++ def event_properties(self) -> dict[str, Any]:+ """Shared dimensions for the report-channel lifecycle events, mirroring the `signals_scout_run_*`+ events so the two join on `run_id` / `task_run_id` — a report event sits under the run that authored+ it. All fields are plain columns on the bridge row (no FK query)."""+ return {+ "skill_name": self.run.skill_name,+ "skill_version": self.run.skill_version,+ "scout_config_id": str(self.run.scout_config_id) if self.run.scout_config_id else None,+ "run_id": str(self.run.id),+ "task_run_id": str(self.run.task_run_id) if self.run.task_run_id else None,+ }++ def log_extra(self) -> dict[str, Any]:+ return {"run_id": str(self.run.id), "skill_name": self.run.skill_name}++ def assert_owned_by(self, team: Team) -> None:+ _assert_team_owns_run(team, self.run)++ def preflight_skip_reason(self, team: Team) -> str | None:+ return _preflight_emit_gates(team, self.run)++ def attribution(self) -> ArtefactAttribution:+ task_id = _resolve_task_id(self.run)+ return ArtefactAttribution.from_task(task_id) if task_id is not None else ArtefactAttribution.system()diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex eef65a035faa..5b0b0c776468 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -209,6 +209,7 @@ from products.signals.backend.scout_harness.tools.report import (edit_report_sync,emit_report_sync,)+from products.signals.backend.scout_harness.tools.report_author import ScoutRunReportAuthorfrom products.signals.backend.scout_harness.tools.runs import (DEFAULT_FINDINGS_WINDOW_HOURS,DEFAULT_RUNS_PER_SCOUT,@@ -1240,7 +1241,7 @@ class SignalScoutRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):# `run.team` is the canonical (parent) team the run was resolved on; a child-environment# request's `self.team` would mismatch the run's owner and trip `_assert_team_owns_run`.team=run.team,- run=run,+ author=ScoutRunReportAuthor(run=run),title=data["title"],summary=data["summary"],evidence=evidence,diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.pyindex 06fa15037583..2e7fa6cfa8a7 100644--- a/products/signals/backend/test/test_scout_report_api.py+++ b/products/signals/backend/test/test_scout_report_api.py@@ -261,6 +261,8 @@ class TestScoutReportAPI(APIBaseTest):assert retry["report_id"] == first["report_id"]assert retry["idempotent_replay"] is Trueassert SignalReport.objects.filter(team=self.team).count() == 1+ # A retry that crosses a deploy looks the report up by this stored key, so its format must not drift.+ assert SignalReport.objects.get(team=self.team).scout_idempotency_key == f"{run.id}:key:checkout-p99"def test_emit_report_still_authors_a_second_report_for_a_different_finding(self) -> None:# The barrier must not swallow a real second finding: one run routinely reports more than one@@ -1926,6 +1928,7 @@ class TestScoutReportAPI(APIBaseTest):)assert forward.kwargs["token"] == self.team.api_tokenassert forward.kwargs["process_person_profile"] is False+ assert forward.kwargs["distinct_id"] == f"signals_scout:{run.skill_name}"expected_url = None if expected_outcome == "gate_skipped" else f"/inbox/reports/{body['report_id']}"if expected_url is None:assert forward.kwargs["properties"]["report_url"] is None