:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): scout report write service + storage (1/3) (#66130)
Andrew Maguire1b2df3e11482
diff --git a/products/signals/backend/migrations/0051_signalscoutrun_emitted_report_ids.py b/products/signals/backend/migrations/0051_signalscoutrun_emitted_report_ids.pynew file mode 100644index 000000000000..dc8f3feb392f--- /dev/null+++ b/products/signals/backend/migrations/0051_signalscoutrun_emitted_report_ids.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.14 on 2026-06-24 20:52++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("signals", "0050_alter_signalscoutconfig_run_interval_minutes"),+ ]++ operations = [+ migrations.AddField(+ model_name="signalscoutrun",+ name="emitted_report_ids",+ field=models.JSONField(blank=True, db_default=[], default=list, null=True),+ ),+ ]diff --git a/products/signals/backend/migrations/max_migration.txt b/products/signals/backend/migrations/max_migration.txtindex ac7ce066dc47..347232852127 100644--- a/products/signals/backend/migrations/max_migration.txt+++ b/products/signals/backend/migrations/max_migration.txt@@ -1 +1 @@-0050_alter_signalscoutconfig_run_interval_minutes+0051_signalscoutrun_emitted_report_idsdiff --git a/products/signals/backend/models.py b/products/signals/backend/models.pyindex dfea2e574cda..ce3768ad7527 100644--- a/products/signals/backend/models.py+++ b/products/signals/backend/models.py@@ -382,6 +382,29 @@ class SignalReport(UUIDModel):return S(prior)return S.POTENTIAL+ def update_authored_content(self, *, title: str | None = None, summary: str | None = None) -> list[str]:+ """Rewrite an agent-authored report's `title`/`summary` in place, independent of status.++ The pipeline only ever sets title/summary as a side effect of the `IN_PROGRESS -> READY`+ (or `-> PENDING_INPUT`) transition — there is no path to edit them on an already-surfaced+ report. The scout report-authoring channel needs one: `emit_report` writes them at creation+ (a report born READY, not transitioned there) and `edit_report` rewrites them afterwards.++ Only the provided fields change; passing neither is a no-op. Returns the modified field names+ (with `updated_at`) for a targeted `save(update_fields=...)`; does NOT call `.save()` — the+ caller owns the write so it can batch this with other changes in one transaction.+ """+ updated_fields: set[str] = set()+ if title is not None:+ self.title = title+ updated_fields.add("title")+ if summary is not None:+ self.summary = summary+ updated_fields.add("summary")+ if updated_fields:+ updated_fields.add("updated_at")+ return list(updated_fields)+@staticmethoddef _merge_task_runs(artefact_rows: "list[tuple[datetime, str]]",@@ -1119,6 +1142,13 @@ class SignalScoutRun(TeamScopedRootMixin, UUIDModel):# to its `Signal` rows (`source_id = run:<run_id>:finding:<finding_id>`) without a# ClickHouse scan. Parallel to `emitted_count` (`len(emitted_finding_ids) == emitted_count`).emitted_finding_ids = models.JSONField(null=True, blank=True, default=list, db_default=[])+ # The `SignalReport` ids a run authored directly via `emit_report` (the second emit channel),+ # in emit order. Parallel to `emitted_finding_ids` but for the report-authoring path: a scout+ # that opts into `emit_report` writes a full report rather than a weak signal, so its output+ # isn't a `finding_id` -> signal but a `report_id` the run owns. Lets "which reports did this+ # run create/edit?" be a column lookup. Nullable with a `[]` db_default so the AddField stays+ # non-blocking on the populated table — new and historical rows both read `[]`.+ emitted_report_ids = models.JSONField(null=True, blank=True, default=list, db_default=[])created_at = models.DateTimeField(auto_now_add=True)class Meta:diff --git a/products/signals/backend/scout_harness/tools/runs.py b/products/signals/backend/scout_harness/tools/runs.pyindex 11684353bbcd..d4676ea35887 100644--- a/products/signals/backend/scout_harness/tools/runs.py+++ b/products/signals/backend/scout_harness/tools/runs.py@@ -20,6 +20,8 @@ from dataclasses import asdict, dataclass, fieldfrom datetime import datetimefrom typing import TYPE_CHECKING, Any+from django.db.models import Q+from products.signals.backend.models import SignalScoutRunfrom products.tasks.backend.facade import api as tasks_facade@@ -52,6 +54,10 @@ class RunSummary:summary: stremitted_count: int = 0emitted_finding_ids: list[str] = field(default_factory=list)+ # Reports authored via the `emit_report` channel — separate from `emitted_count`/`emitted_finding_ids`+ # (which count weak `emit_signal` findings), so a run that only authored a report still reads as+ # having emitted something.+ emitted_report_ids: list[str] = field(default_factory=list)task_id: str | None = Nonetask_run_id: str | None = Nonetask_url: str | None = None@@ -83,6 +89,10 @@ class RunDetail:summary: stremitted_count: int = 0emitted_finding_ids: list[str] = field(default_factory=list)+ # Reports authored via the `emit_report` channel — separate from `emitted_count`/`emitted_finding_ids`+ # (which count weak `emit_signal` findings), so a run that only authored a report still reads as+ # having emitted something.+ emitted_report_ids: list[str] = field(default_factory=list)task_id: str | None = Nonetask_run_id: str | None = Nonetask_url: str | None = None@@ -115,8 +125,9 @@ def search_recent_runs(`text` is a case-insensitive substring match on the agent's end-of-run`summary` — the primary dedupe path for runs that didn't emit findings.`emitted` filters on emit outcome: `True` keeps only runs that emitted at least- one finding (`emitted_count > 0`), `False` keeps only runs that emitted nothing;- omit it for both. `skill_name` is an exact-match filter that narrows the dump to+ one finding *or* authored a report (`emitted_count > 0` or a non-empty+ `emitted_report_ids`), `False` keeps only runs that emitted nothing on either+ channel; omit it for both. `skill_name` is an exact-match filter that narrows the dump toa single scout — the primary scoping path for a specialist deduping against itsown past work; pair it with `skill_version` to pin a specific version. Resultsare capped at `MAX_RUN_SEARCH_LIMIT`.@@ -130,7 +141,13 @@ def search_recent_runs(if text:qs = qs.filter(summary__icontains=text)if emitted is not None:- qs = qs.filter(emitted_count__gt=0) if emitted else qs.filter(emitted_count=0)+ # A run "emitted" if it surfaced a weak finding (emitted_count) or authored a report+ # (emitted_report_ids). Treat null/[] report lists as empty for the negative case.+ emitted_a_report = ~Q(emitted_report_ids=[]) & ~Q(emitted_report_ids__isnull=True)+ if emitted:+ qs = qs.filter(Q(emitted_count__gt=0) | emitted_a_report)+ else:+ qs = qs.filter(emitted_count=0).filter(Q(emitted_report_ids=[]) | Q(emitted_report_ids__isnull=True))if skill_name:qs = qs.filter(skill_name=skill_name)if skill_version is not None:@@ -167,6 +184,7 @@ def _to_summary(row: SignalScoutRun, *, team_id: int) -> RunSummary:summary=row.summary,emitted_count=row.emitted_count or 0,emitted_finding_ids=list(row.emitted_finding_ids or []),+ emitted_report_ids=list(row.emitted_report_ids or []),task_id=task_id,task_run_id=task_run_id,task_url=_build_task_url(team_id=team_id, task_id=task_id, task_run_id=task_run_id),diff --git a/products/signals/backend/scout_report/__init__.py b/products/signals/backend/scout_report/__init__.pynew file mode 100644index 000000000000..767cab3e6e6f--- /dev/null+++ b/products/signals/backend/scout_report/__init__.py@@ -0,0 +1,29 @@+"""Direct report-authoring write paths for the scout `emit_report` / `edit_report` channel.++See `persistence.py` for the design: an opted-in scout authors a `SignalReport` directly (plus its+backing `document_embeddings` signal rows) instead of routing a weak signal through the grouping+pipeline. This package is the sanctioned write service the harness tools (Phase 3) call — harness+code never touches `SignalReport` or the embeddings pipeline directly.+"""++from products.signals.backend.scout_report.persistence import (+ MAX_REPORT_SIGNALS,+ InvalidScoutReportError,+ PersistedScoutReport,+ ScoutReportSignal,+ append_report_note,+ create_scout_report,+ soft_delete_scout_signal,+ update_scout_report,+)++__all__ = [+ "MAX_REPORT_SIGNALS",+ "InvalidScoutReportError",+ "PersistedScoutReport",+ "ScoutReportSignal",+ "append_report_note",+ "create_scout_report",+ "soft_delete_scout_signal",+ "update_scout_report",+]diff --git a/products/signals/backend/scout_report/judge.py b/products/signals/backend/scout_report/judge.pynew file mode 100644index 000000000000..66e29e708987--- /dev/null+++ b/products/signals/backend/scout_report/judge.py@@ -0,0 +1,117 @@+"""Safety + actionability gating for scout-authored reports, before they surface in the inbox.++`custom_agent/` writes its reports straight to READY because it is an engineering-only surface. Scouts+are customer-facing, so a scout-authored report passes the same prompt-injection **safety judge** the+pipeline runs (decision #3) before it can surface. Actionability is supplied by the scout itself — it+authored the report and made the actionability call, exactly as `custom_agent` carries its own+`ActionabilityAssessment` — rather than re-derived by a second sandbox research pass (which the+pipeline's actionability judge requires and which would defeat the point of direct authorship).++The two combine into the status the report is born at:++ unsafe -> SUPPRESSED (never surface a report whose signals look adversarial)+ safe + immediately_actionable -> READY+ safe + requires_human_input -> PENDING_INPUT+ safe + not_actionable -> SUPPRESSED++The mapping is a pure function (`resolve_authored_report_status`) so it is unit-tested without the LLM;+`judge_scout_report` wraps it with the actual safety-judge call.+"""++from __future__ import annotations++import uuid+from dataclasses import dataclass++from django.utils import timezone++from products.signals.backend.artefact_schemas import ActionabilityAssessment, ActionabilityChoice, SafetyJudgment+from products.signals.backend.models import SignalReport+from products.signals.backend.scout_harness.tools.emit import SOURCE_PRODUCT, SOURCE_TYPE+from products.signals.backend.scout_report.persistence import ScoutReportSignal+from products.signals.backend.temporal.report_safety_judge import judge_report_safety+from products.signals.backend.temporal.types import SignalData+++@dataclass(frozen=True)+class ScoutReportJudgement:+ """The verdict that decides whether (and how) an authored report surfaces."""++ status: SignalReport.Status+ safety: SafetyJudgment+ actionability: ActionabilityAssessment+++def resolve_authored_report_status(*, safe: bool, actionability: ActionabilityChoice) -> SignalReport.Status:+ """Pure status mapping for an authored report (see module docstring). Unsafe always wins —+ an adversarial-looking report is suppressed regardless of how actionable the scout judged it."""+ if not safe:+ return SignalReport.Status.SUPPRESSED+ match actionability:+ case ActionabilityChoice.IMMEDIATELY_ACTIONABLE:+ return SignalReport.Status.READY+ case ActionabilityChoice.REQUIRES_HUMAN_INPUT:+ return SignalReport.Status.PENDING_INPUT+ case ActionabilityChoice.NOT_ACTIONABLE:+ return SignalReport.Status.SUPPRESSED+ case _:+ raise ValueError(f"unhandled actionability choice: {actionability}")+++def _report_content_signal(title: str, summary: str) -> SignalData:+ """Wrap the authored `title` + `summary` as a `SignalData` so the safety judge evaluates the exact+ prose that will surface (and feed autostart), not just the backing evidence. Prompt-injection can+ land in the report body itself while the evidence descriptions look benign — this makes the judge+ see the report text too, so an unsafe title/summary suppresses the report."""+ return SignalData(+ signal_id=str(uuid.uuid4()),+ content=f"{title}\n\n{summary}",+ source_product=SOURCE_PRODUCT,+ source_type=SOURCE_TYPE,+ source_id="report_content",+ weight=0.0,+ timestamp=timezone.now(),+ extra={},+ )+++def _to_signal_data(signals: list[ScoutReportSignal]) -> list[SignalData]:+ """Adapt the authored-report signals into the `SignalData` shape the safety judge renders."""+ return [+ SignalData(+ signal_id=signal.document_id or str(uuid.uuid4()),+ content=signal.description,+ source_product=SOURCE_PRODUCT,+ source_type=SOURCE_TYPE,+ source_id=signal.source_id,+ weight=signal.weight,+ timestamp=signal.timestamp or timezone.now(),+ extra=dict(signal.extra),+ )+ for signal in signals+ ]+++async def judge_scout_report(+ *,+ team_id: int,+ title: str,+ summary: str,+ signals: list[ScoutReportSignal],+ actionability: ActionabilityAssessment,+) -> ScoutReportJudgement:+ """Run the safety judge on the authored report and resolve the birth status.++ The judge sees the authored `title`/`summary` *and* the backing observations — so prompt-injection+ in the report prose itself (not just the evidence) is caught before the report can surface or feed+ autostart. The safety judge is a plain LLM call (`judge_report_safety`) — no Temporal workflow, no+ sandbox — so this runs inline on whatever worker is authoring the report.+ """+ safety_input = [_report_content_signal(title, summary), *_to_signal_data(signals)]+ safety_response = await judge_report_safety(team_id=team_id, signals=safety_input)+ safety = SafetyJudgment(+ choice=safety_response.choice,+ explanation=safety_response.explanation if not safety_response.choice else None,+ )+ status = resolve_authored_report_status(safe=safety_response.choice, actionability=actionability.actionability)+ return ScoutReportJudgement(status=status, safety=safety, actionability=actionability)diff --git a/products/signals/backend/scout_report/persistence.py b/products/signals/backend/scout_report/persistence.pynew file mode 100644index 000000000000..3cf0a5415e8b--- /dev/null+++ b/products/signals/backend/scout_report/persistence.py@@ -0,0 +1,454 @@+"""Direct report-authoring write paths for the scout `emit_report` / `edit_report` channel.++This is the second emit channel for Signals scouts. The first one (`scout_harness/tools/emit.py`)+forwards a weak signal through `emit_signal()` and lets the grouping pipeline decide whether it+becomes a report. Here an opted-in scout has already done the research and authors the `SignalReport`+itself — so we write the report directly (like `custom_agent/persistence.py`), bypassing the+embedding-NN matcher and the promotion state machine.++The report is NOT signal-less, though. Writing it WITHOUT backing signals would break every read-side+consumer that derives state from a report's signals (source filter/chips, the `/signals/` tab, the+inbox-validation scout, snooze accounting). So we reuse the grouping pipeline's *storage substrate* —+not its matcher: each constituent observation the agent supplies is written to `document_embeddings`+as a normal `signals/signal` row with `report_id` pre-set in `metadata`, exactly the shape+`assign_and_emit_signal_activity` writes (minus the match step). The embedding worker generates the+vectors from the Kafka message, same as the pipeline. This makes an agentic report indistinguishable+from a pipeline report to read-side machinery.++Consistency caveat (documented, accepted): the signal rows go Kafka -> MV -> ClickHouse and are NOT+atomic with the Postgres report write. A read immediately after `create_scout_report` may see+`signal_count=N` in Postgres but zero rows in ClickHouse for ~1s. Callers (and the emit-and-inspect+test loop) must tolerate this lag.+"""++from __future__ import annotations++import uuid+import logging+from collections.abc import Sequence+from dataclasses import dataclass, field+from datetime import datetime++from django.db import transaction+from django.utils import timezone++from posthog.schema import EmbeddingModelName++from posthog.api.embedding_worker import emit_embedding_request++from products.signals.backend.artefact_schemas import (+ ActionabilityAssessment,+ NoteArtefact,+ PriorityAssessment,+ SafetyJudgment,+ SuggestedReviewers,+)+from products.signals.backend.models import ArtefactAttribution, SignalReport, SignalReportArtefact, SignalScoutRun+from products.signals.backend.report_generation.select_repo import RepoSelectionResult+from products.signals.backend.scout_harness.tools.emit import SCOUT_SIGNAL_WEIGHT, SOURCE_PRODUCT, SOURCE_TYPE++logger = logging.getLogger(__name__)++# Matches the grouping pipeline's signal rows (`assign_and_emit_signal_activity`): a scout-authored+# report's backing rows live in the same `document_embeddings` space so read-side queries that filter+# by `(product, document_type)` see them identically.+_EMBEDDING_PRODUCT = "signals"+_EMBEDDING_DOCUMENT_TYPE = "signal"+_EMBEDDING_RENDERING = "plain"++# Defensive cap: a single authored report shouldn't carry an unbounded evidence list. The agent groups+# its own observations; this is a harness circuit breaker, mirroring `MAX_EVIDENCE_ENTRIES` on emit.+MAX_REPORT_SIGNALS = 50+++class InvalidScoutReportError(ValueError):+ """The caller tried to author/edit a report with an invalid shape (empty title, no signals, ...)."""+++@dataclass(frozen=True)+class ScoutReportSignal:+ """One observation backing an authored report — written as a `signals/signal` embedding row.++ `description` is the text that gets embedded and rendered to the research/safety surfaces.+ `source_id` is a stable identifier for the observation within the report (so a later+ `edit_report` can address it for soft-delete). `document_id` is the ClickHouse row id; left+ unset it is generated, but an edit that soft-deletes a prior signal must pass the original+ `document_id` so the ReplacingMergeTree supersedes the live row rather than adding a sibling.+ """++ description: str+ source_id: str+ weight: float = SCOUT_SIGNAL_WEIGHT+ timestamp: datetime | None = None+ extra: dict = field(default_factory=dict)+ document_id: str | None = None+++@dataclass(frozen=True)+class PersistedScoutReport:+ report_id: str+ signal_count: int+ total_weight: float+ # The ClickHouse `document_id`s written for the backing signals, in input order. Lets a caller+ # (and the run tally) tie the report back to its signal rows without a scan, and gives a later+ # `edit_report` the ids it needs to soft-delete a specific observation.+ signal_document_ids: list[str]+++def create_scout_report(+ *,+ team_id: int,+ title: str,+ summary: str,+ signals: Sequence[ScoutReportSignal],+ attribution: ArtefactAttribution,+ status: SignalReport.Status = SignalReport.Status.READY,+ safety: SafetyJudgment | None = None,+ actionability: ActionabilityAssessment | None = None,+ repo_selection: RepoSelectionResult | None = None,+ priority: PriorityAssessment | None = None,+ suggested_reviewers: SuggestedReviewers | None = None,+ emit_signals: bool = True,+ run: SignalScoutRun | None = None,+) -> PersistedScoutReport:+ """Author a `SignalReport` directly plus its backing signal rows, in one report-owning transaction.++ The Postgres report row (with `signal_count`/`total_weight` set to match the supplied signals) is+ written inside `transaction.atomic()`. The backing signal rows are emitted to Kafka *after* the+ block commits — never inside it — so a rolled-back report never leaves orphan signals pointing at+ a `report_id` that doesn't exist. This function owns its transaction boundary; do not wrap it in an+ outer atomic block (that would defer the commit and the emits past your control).++ `status` is the status the report is born at. It defaults to READY (the custom-agent precedent);+ the safety/actionability judge (`judge.py`) is what chooses READY vs SUPPRESSED vs PENDING_INPUT+ and passes the resolved status here. `safety` / `actionability`, when provided, are written as the+ report's status artefacts (the same `safety_judgment` / `actionability_judgment` types the pipeline+ writes) so the verdict that set the status is auditable on the report, not just implicit in it.++ `repo_selection` / `priority` / `suggested_reviewers`, when provided, are written as the same+ status artefacts a pipeline report carries (`repo_selection` / `priority_judgment` /+ `suggested_reviewers`). They are what `auto_start.maybe_autostart_from_report_artefacts` reads to+ open a draft PR — the autostart hook itself is fired by the caller *after* this returns (never+ in-txn, since it spawns a Task), so the `suggested_reviewers` append opts out of the model's+ autostart re-evaluation hook, mirroring `create_custom_agent_ready_report`.++ `emit_signals` gates whether the backing observations are written to `document_embeddings`. It+ defaults to True; callers pass False for a report the safety judge marked unsafe (born SUPPRESSED)+ so the adversarial-looking descriptions are never indexed — an unsafe report's signals must not+ become semantic-search candidates or matching context for unrelated signals, mirroring how the+ pipeline buffer drops unsafe signals before grouping. The report row still records the authored+ `signal_count`/`total_weight`; it just stays invisible with no indexed evidence.+ """+ _validate_create_inputs(title, summary, signals)+ # Defense-in-depth: refuse to author against a run another team owns, so the tally write below+ # can't corrupt a foreign team's `emitted_report_ids`. The harness tool already gates this with+ # `_assert_team_owns_run`; this guards a future direct caller that bypasses it (mirrors `emit`).+ if run is not None and run.team_id != team_id:+ raise RuntimeError(f"create_scout_report: team {team_id} does not own run {run.id} (team {run.team_id})")++ document_ids = [s.document_id or str(uuid.uuid4()) for s in signals]+ total_weight = sum(s.weight for s in signals)++ with transaction.atomic():+ report = SignalReport.objects.create(+ team_id=team_id,+ status=status,+ title=title,+ summary=summary,+ signal_count=len(signals),+ total_weight=total_weight,+ )+ report_id = str(report.id)+ # Provenance: every authored report carries a note marking it scout-authored, attributed to+ # the scout's task. This keeps an agentic report auditable as NOT pipeline-generated (a+ # concern raised by edit_report's any-report reach) and gives it a non-empty work log so it+ # isn't evidence-less in the UI. Written in-txn with the report so the two never diverge.+ SignalReportArtefact.append(+ team_id=team_id,+ report_id=report_id,+ content=NoteArtefact(note=_provenance_note_text(run), author=_provenance_author(run)),+ attribution=attribution,+ reevaluate_autostart=False,+ )+ # The judge verdicts that set `status`, recorded as the report's status artefacts so the+ # decision is auditable on the report (and so the inbox derives the same actionability/safety+ # state a pipeline report would). Written in-txn with the report for the same no-divergence reason.+ if safety is not None:+ SignalReportArtefact.append_status(+ team_id=team_id, report_id=report_id, content=safety, attribution=attribution+ )+ if actionability is not None:+ SignalReportArtefact.append_status(+ team_id=team_id, report_id=report_id, content=actionability, attribution=attribution+ )+ # Autostart inputs (mirroring `create_custom_agent_ready_report`): the repo the fix lands in,+ # the priority, and the suggested reviewers. The reviewers append opts out of the autostart+ # re-eval hook — autostart is fired explicitly by the caller after commit, never in-txn.+ if repo_selection is not None:+ SignalReportArtefact.append_status(+ team_id=team_id, report_id=report_id, content=repo_selection, attribution=attribution+ )+ if priority is not None:+ SignalReportArtefact.append_status(+ team_id=team_id, report_id=report_id, content=priority, attribution=attribution+ )+ if suggested_reviewers is not None and len(suggested_reviewers.root) > 0:+ SignalReportArtefact.append_status(+ team_id=team_id,+ report_id=report_id,+ content=suggested_reviewers,+ attribution=attribution,+ reevaluate_autostart=False,+ )++ # Committed: now emit the backing signals (unless suppressed-unsafe — see `emit_signals`).+ # Sequential (not on_commit) so the call is observable and so a Kafka failure surfaces to the+ # caller rather than being swallowed by a commit hook.+ if emit_signals:+ for signal, document_id in zip(signals, document_ids):+ _emit_bound_signal(team_id=team_id, report_id=report_id, signal=signal, document_id=document_id)++ if run is not None:+ _record_report_emit(team_id=team_id, run_id=run.id, report_id=report_id)++ logger.info(+ "signals_scout.emit_report: created",+ extra={"team_id": team_id, "report_id": report_id, "signal_count": len(signals)},+ )+ return PersistedScoutReport(+ report_id=report_id,+ signal_count=len(signals),+ total_weight=total_weight,+ signal_document_ids=document_ids,+ )+++def update_scout_report(+ *,+ team_id: int,+ report_id: str,+ title: str | None = None,+ summary: str | None = None,+ attribution: ArtefactAttribution | None = None,+ author: str | None = None,+) -> list[str]:+ """Rewrite an existing report's `title`/`summary` in place (the `edit_report` content path).++ Team-scoped fail-closed: a `report_id` the team doesn't own raises, never silently no-ops. Returns+ the modified field names. Title/summary edits are best-effort authorship — the pipeline may later+ re-research and overwrite them (decision #6); that is documented in the scout-facing contract.++ When `attribution` is supplied and the content actually changes, an audit note is appended to the+ report's work log recording who rewrote what — `edit_report` can target ANY inbox report (pipeline-+ authored included), so a core-content rewrite must leave a durable, attributable trail, not just a+ silent field mutation.+ """+ if title is None and summary is None:+ return []+ _validate_report_id(report_id)+ _validate_optional_text("title", title)+ _validate_optional_text("summary", summary)++ with transaction.atomic():+ report = SignalReport.objects.select_for_update().filter(team_id=team_id, id=report_id).first()+ if report is None:+ raise InvalidScoutReportError(f"report {report_id} not found for team {team_id}")+ updated_fields = report.update_authored_content(title=title, summary=summary)+ if updated_fields:+ report.save(update_fields=updated_fields)+ if attribution is not None:+ SignalReportArtefact.add_log(+ team_id=team_id,+ report_id=report_id,+ content=NoteArtefact(note=_content_edit_note(updated_fields), author=author),+ attribution=attribution,+ )++ logger.info(+ "signals_scout.edit_report: content updated",+ extra={"team_id": team_id, "report_id": report_id, "fields": updated_fields},+ )+ return updated_fields+++def append_report_note(+ *,+ team_id: int,+ report_id: str,+ note: str,+ attribution: ArtefactAttribution,+ author: str | None = None,+) -> str:+ """Append a free-form `note` artefact to an existing report (the `edit_report` annotate path).++ Team-scoped fail-closed: a `report_id` the team doesn't own raises. `edit_report` can target ANY+ inbox report (decision #2), pipeline-authored ones included, so the note is attributed (to the+ scout's task) to keep the edit auditable and distinguishable from pipeline output. Returns the+ report_id on success.+ """+ if not note or not note.strip():+ raise InvalidScoutReportError("note must not be empty")+ _validate_report_id(report_id)+ with transaction.atomic():+ # Existence is the team-scoped gate; the artefact append itself is keyed by report_id.+ if not SignalReport.objects.filter(team_id=team_id, id=report_id).exists():+ raise InvalidScoutReportError(f"report {report_id} not found for team {team_id}")+ SignalReportArtefact.add_log(+ team_id=team_id,+ report_id=report_id,+ content=NoteArtefact(note=note, author=author),+ attribution=attribution,+ )+ logger.info("signals_scout.edit_report: note appended", extra={"team_id": team_id, "report_id": report_id})+ return report_id+++def soft_delete_scout_signal(+ *,+ team_id: int,+ report_id: str,+ document_id: str,+ description: str,+ timestamp: datetime,+ source_id: str,+ weight: float = SCOUT_SIGNAL_WEIGHT,+ extra: dict | None = None,+) -> None:+ """Soft-delete a backing signal by re-emitting its `document_id` with `metadata.deleted=True`.++ The embeddings table is a ReplacingMergeTree keyed on `document_id`; re-emitting the same id with a+ later `inserted_at` supersedes the live row. The original `timestamp` is preserved (the table+ partitions on it) so the tombstone lands in the same partition as the row it replaces — matching+ how the grouping pipeline soft-deletes stale signals on a deleted report.++ Team-scoped fail-closed, like the other edit paths: validate the `report_id` and confirm the team+ owns it before emitting the tombstone, so a caller with a foreign `report_id` + known `document_id`+ can't soft-delete another tenant's backing signal.+ """+ _validate_report_id(report_id)+ if not SignalReport.objects.filter(team_id=team_id, id=report_id).exists():+ raise InvalidScoutReportError(f"report {report_id} not found for team {team_id}")+ metadata = _signal_metadata(report_id=report_id, source_id=source_id, weight=weight, extra=extra)+ metadata["deleted"] = True+ emit_embedding_request(+ content=description,+ team_id=team_id,+ product=_EMBEDDING_PRODUCT,+ document_type=_EMBEDDING_DOCUMENT_TYPE,+ rendering=_EMBEDDING_RENDERING,+ document_id=document_id,+ models=[m.value for m in EmbeddingModelName],+ timestamp=timestamp,+ metadata=metadata,+ )+++def _emit_bound_signal(+ *,+ team_id: int,+ report_id: str,+ signal: ScoutReportSignal,+ document_id: str,+) -> None:+ """Write one backing signal row to `document_embeddings`, mirroring `assign_and_emit_signal_activity`+ minus the matcher. `report_id` in metadata is what binds it to the report on the read side."""+ metadata = _signal_metadata(+ report_id=report_id, source_id=signal.source_id, weight=signal.weight, extra=signal.extra+ )+ emit_embedding_request(+ content=signal.description,+ team_id=team_id,+ product=_EMBEDDING_PRODUCT,+ document_type=_EMBEDDING_DOCUMENT_TYPE,+ rendering=_EMBEDDING_RENDERING,+ document_id=document_id,+ models=[m.value for m in EmbeddingModelName],+ timestamp=signal.timestamp or timezone.now(),+ metadata=metadata,+ )+++def _signal_metadata(*, report_id: str, source_id: str, weight: float, extra: dict | None) -> dict:+ """The `metadata` JSON for a backing signal row. Keys match the grouping pipeline's so the same+ `JSONExtractString(metadata, ...)` read queries resolve a scout-authored signal identically.+ `match_metadata` is intentionally omitted — these rows never went through the matcher."""+ return {+ "source_product": SOURCE_PRODUCT,+ "source_type": SOURCE_TYPE,+ "source_id": source_id,+ "weight": weight,+ "report_id": report_id,+ "extra": extra or {},+ "remediation": None,+ }+++def _record_report_emit(*, team_id: int, run_id: uuid.UUID, report_id: str) -> None:+ """Append `report_id` to the run's `emitted_report_ids` tally so "which reports did this run+ author?" is a column lookup. Best-effort and observability only (mirrors `emit._record_emit`):+ the report has already been created by the time this runs, so any failure here is swallowed rather+ than surfaced as a false emit failure. Runs under `select_for_update` so the read-modify-write on+ the JSON list is safe, and scopes the lookup to `team_id` via the fail-closed manager so the tally+ write can never touch a foreign team's run even if the caller's ownership guard regresses."""+ try:+ with transaction.atomic():+ run = SignalScoutRun.objects.for_team(team_id).select_for_update().filter(pk=run_id).first()+ if run is None:+ logger.warning("signals_scout.emit_report: run %s gone, skipping report tally", run_id)+ return+ report_ids = [*(run.emitted_report_ids or []), report_id]+ run.emitted_report_ids = report_ids+ run.save(update_fields=["emitted_report_ids"])+ except Exception:+ logger.exception("signals_scout.emit_report: failed to record report emit for run %s", run_id)+++def _provenance_note_text(run: SignalScoutRun | None) -> str:+ if run is not None:+ return f"Authored directly by the `{run.skill_name}` Signals scout via emit_report."+ return "Authored directly by a Signals scout via emit_report."+++def _provenance_author(run: SignalScoutRun | None) -> str:+ return run.skill_name if run is not None else "signals_scout"+++def _validate_create_inputs(title: str, summary: str, signals: Sequence[ScoutReportSignal]) -> None:+ if not title or not title.strip():+ raise InvalidScoutReportError("title must not be empty")+ if not summary or not summary.strip():+ raise InvalidScoutReportError("summary must not be empty")+ if not signals:+ raise InvalidScoutReportError("a report must be backed by at least one signal")+ if len(signals) > MAX_REPORT_SIGNALS:+ raise InvalidScoutReportError(f"report has {len(signals)} signals, max is {MAX_REPORT_SIGNALS}")+ for signal in signals:+ if not signal.description or not signal.description.strip():+ raise InvalidScoutReportError("every backing signal must have a non-empty description")+ if signal.weight < 0.0:+ raise InvalidScoutReportError(f"signal weight must be non-negative, got {signal.weight}")+ # Reject duplicate caller-supplied `document_id`s. The embeddings table is a ReplacingMergeTree+ # keyed on `document_id`, so two rows sharing one id would collapse to one — the report would claim+ # `signal_count=N` while a read resolves fewer. Unset ids are generated fresh and never collide.+ supplied_ids = [s.document_id for s in signals if s.document_id is not None]+ if len(supplied_ids) != len(set(supplied_ids)):+ raise InvalidScoutReportError("backing signals must have unique document_ids")+++def _validate_optional_text(field_name: str, value: str | None) -> None:+ if value is not None and not value.strip():+ raise InvalidScoutReportError(f"{field_name} must not be empty when provided")+++def _content_edit_note(updated_fields: list[str]) -> str:+ return f"Edited report {' and '.join(updated_fields)} via edit_report."+++def _validate_report_id(report_id: str) -> None:+ """Reject a malformed `report_id` at the service boundary with a caller error, so the later+ `id=report_id` filter doesn't raise Django's UUID `ValidationError` as an uncaught 500. Covers+ both the DRF path (CharField) and the async Temporal path, which don't go through a UUID field."""+ try:+ uuid.UUID(str(report_id))+ except (ValueError, AttributeError, TypeError):+ raise InvalidScoutReportError(f"report_id is not a valid UUID: {report_id!r}")diff --git a/products/signals/backend/test/test_scout_harness_tools.py b/products/signals/backend/test/test_scout_harness_tools.pyindex 418c650fa242..8c5a40ee3dd3 100644--- a/products/signals/backend/test/test_scout_harness_tools.py+++ b/products/signals/backend/test/test_scout_harness_tools.py@@ -211,6 +211,20 @@ class TestSearchRecentRuns(BaseTest):assert len(hits) == 2+ @parameterized.expand([("emitted_true", True), ("emitted_false", False)])+ def test_emitted_filter_counts_report_only_runs(self, _name: str, emitted: bool) -> None:+ # A run that only authored a report (emitted_count stays 0) must still read as "emitted",+ # so the report channel isn't invisible to the emitted-run history/dedupe view.+ report_run = _create_run(self.team, emitted_report_ids=["r-1"])+ quiet = _create_run(self.team)++ hits = search_recent_runs(team_id=self.team.id, emitted=emitted)++ expected = report_run if emitted else quiet+ assert [h.run_id for h in hits] == [str(expected.id)]+ if emitted:+ assert hits[0].emitted_report_ids == ["r-1"]+def test_skill_name_filter_scopes_to_one_scout(self) -> None:errors = _create_run(self.team, skill_name="signals-scout-errors")_create_run(self.team, skill_name="signals-scout-llm")diff --git a/products/signals/backend/test/test_scout_report_persistence.py b/products/signals/backend/test/test_scout_report_persistence.pynew file mode 100644index 000000000000..cfb425f60768--- /dev/null+++ b/products/signals/backend/test/test_scout_report_persistence.py@@ -0,0 +1,281 @@+from contextlib import AbstractContextManager+from datetime import UTC, datetime++import pytest+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.apps import apps++from parameterized import parameterized++from posthog.models import Organization, Team+from posthog.models.scoping import team_scope++from products.signals.backend.artefact_schemas import ActionabilityAssessment, ActionabilityChoice, SafetyJudgment+from products.signals.backend.models import (+ ArtefactAttribution,+ SignalReport,+ SignalReportArtefact,+ SignalScoutConfig,+ SignalScoutRun,+)+from products.signals.backend.scout_harness.tools.emit import SOURCE_PRODUCT, SOURCE_TYPE+from products.signals.backend.scout_report import (+ InvalidScoutReportError,+ ScoutReportSignal,+ create_scout_report,+ soft_delete_scout_signal,+ update_scout_report,+)+from products.signals.backend.scout_report.judge import resolve_authored_report_status++PERSISTENCE_MODULE = "products.signals.backend.scout_report.persistence"+++class TestScoutReportPersistence(BaseTest):+ _team_scope_cm: AbstractContextManager[None] | None = None++ def setUp(self) -> None:+ super().setUp()+ cm = team_scope(self.team.id)+ cm.__enter__()+ self._team_scope_cm = cm+ patcher = patch(f"{PERSISTENCE_MODULE}.emit_embedding_request")+ self.emit_mock = patcher.start()+ self.addCleanup(patcher.stop)++ def tearDown(self) -> None:+ if self._team_scope_cm is not None:+ self._team_scope_cm.__exit__(None, None, None)+ self._team_scope_cm = None+ super().tearDown()++ def _make_run(self) -> SignalScoutRun:+ Task = apps.get_model("tasks", "Task")+ TaskRun = apps.get_model("tasks", "TaskRun")+ task = Task.objects.create(+ team=self.team,+ title="scout run",+ description="scout run",+ origin_product=Task.OriginProduct.SIGNALS_SCOUT,+ )+ task_run = TaskRun.objects.create(task=task, team=self.team)+ config = SignalScoutConfig.objects.create(team=self.team, skill_name="signals-scout-health-checks")+ run = SignalScoutRun.objects.create(+ task_run=task_run,+ team=self.team,+ scout_config=config,+ skill_name="signals-scout-health-checks",+ skill_version=1,+ )+ return run++ def test_create_writes_report_with_bound_signals_metadata(self) -> None:+ # The load-bearing contract (decision #5): each backing signal is written to the embeddings+ # pipeline with report_id pre-set, as a signals/signal row, so every read-side consumer+ # (source filter/chips, /signals/ tab, inbox-validation) resolves it like a pipeline signal.+ # Dropping report_id, or changing product/document_type, silently breaks all of them.+ run = self._make_run()+ task_id = str(run.task_run.task_id)+ result = create_scout_report(+ team_id=self.team.id,+ title="Checkout API p99 latency regressed",+ summary="The checkout endpoint p99 doubled after the 4.2 deploy.",+ signals=[+ ScoutReportSignal(description="p99 doubled on /checkout", source_id="obs-1", weight=1.0),+ ScoutReportSignal(description="error rate up 3x", source_id="obs-2", weight=0.5),+ ],+ attribution=ArtefactAttribution.from_task(task_id),+ run=run,+ )++ report = SignalReport.objects.get(id=result.report_id)+ assert report.status == SignalReport.Status.READY+ assert report.title == "Checkout API p99 latency regressed"+ # signal_count / total_weight must be real (not 0) — snooze re-promotion accounting reads them.+ assert report.signal_count == 2+ assert report.total_weight == 1.5++ assert self.emit_mock.call_count == 2+ first = self.emit_mock.call_args_list[0].kwargs+ assert first["product"] == "signals"+ assert first["document_type"] == "signal"+ assert first["rendering"] == "plain"+ assert first["metadata"]["report_id"] == result.report_id+ assert first["metadata"]["source_product"] == SOURCE_PRODUCT+ assert first["metadata"]["source_type"] == SOURCE_TYPE+ assert first["metadata"]["source_id"] == "obs-1"+ assert first["metadata"]["weight"] == 1.0+ assert "match_metadata" not in first["metadata"] # never went through the matcher+ # Each backing row gets a distinct ClickHouse document_id.+ doc_ids = [call.kwargs["document_id"] for call in self.emit_mock.call_args_list]+ assert len(set(doc_ids)) == 2+ assert result.signal_document_ids == doc_ids++ # Provenance: a note artefact marks the report scout-authored and is attributed to the task.+ note = SignalReportArtefact.objects.get(report_id=result.report_id, type=SignalReportArtefact.ArtefactType.NOTE)+ assert str(note.task_id) == task_id++ run.refresh_from_db()+ assert run.emitted_report_ids == [result.report_id]++ @parameterized.expand(+ [+ ("empty_title", "", "summary", [ScoutReportSignal(description="d", source_id="s")]),+ ("empty_summary", "title", " ", [ScoutReportSignal(description="d", source_id="s")]),+ ("no_signals", "title", "summary", []),+ ("blank_signal_description", "title", "summary", [ScoutReportSignal(description=" ", source_id="s")]),+ ]+ )+ def test_create_rejects_invalid_shape(self, _name, title, summary, signals) -> None:+ with pytest.raises(InvalidScoutReportError):+ create_scout_report(+ team_id=self.team.id,+ title=title,+ summary=summary,+ signals=signals,+ attribution=ArtefactAttribution.system(),+ )+ assert SignalReport.objects.filter(team_id=self.team.id).count() == 0+ self.emit_mock.assert_not_called()++ def test_update_rewrites_title_and_summary(self) -> None:+ result = create_scout_report(+ team_id=self.team.id,+ title="old title",+ summary="old summary",+ signals=[ScoutReportSignal(description="d", source_id="s")],+ attribution=ArtefactAttribution.system(),+ )+ updated = update_scout_report(+ team_id=self.team.id, report_id=result.report_id, title="new title", summary="new summary"+ )+ assert set(updated) == {"title", "summary", "updated_at"}+ report = SignalReport.objects.get(id=result.report_id)+ assert report.title == "new title"+ assert report.summary == "new summary"++ def test_update_fails_closed_on_cross_team_report(self) -> None:+ # edit_report can target any inbox report (decision #2) — so the team scope is the only thing+ # standing between a scout and another team's report. A cross-team id must raise, not no-op.+ other_org = Organization.objects.create(name="other")+ other_team = Team.objects.create(organization=other_org, name="other")+ with team_scope(other_team.id):+ other_report = create_scout_report(+ team_id=other_team.id,+ title="theirs",+ summary="theirs",+ signals=[ScoutReportSignal(description="d", source_id="s")],+ attribution=ArtefactAttribution.system(),+ )+ with pytest.raises(InvalidScoutReportError):+ update_scout_report(team_id=self.team.id, report_id=other_report.report_id, title="hijacked")+ assert SignalReport.objects.get(id=other_report.report_id).title == "theirs"++ @parameterized.expand(+ [+ # Unsafe always suppresses, regardless of the scout's actionability call.+ ("unsafe_immediately", False, ActionabilityChoice.IMMEDIATELY_ACTIONABLE, SignalReport.Status.SUPPRESSED),+ ("unsafe_human", False, ActionabilityChoice.REQUIRES_HUMAN_INPUT, SignalReport.Status.SUPPRESSED),+ ("unsafe_not_actionable", False, ActionabilityChoice.NOT_ACTIONABLE, SignalReport.Status.SUPPRESSED),+ # Safe routes on actionability.+ ("safe_immediately", True, ActionabilityChoice.IMMEDIATELY_ACTIONABLE, SignalReport.Status.READY),+ ("safe_human", True, ActionabilityChoice.REQUIRES_HUMAN_INPUT, SignalReport.Status.PENDING_INPUT),+ ("safe_not_actionable", True, ActionabilityChoice.NOT_ACTIONABLE, SignalReport.Status.SUPPRESSED),+ ]+ )+ def test_resolve_authored_report_status(self, _name, safe, actionability, expected) -> None:+ assert resolve_authored_report_status(safe=safe, actionability=actionability) == expected++ def test_create_records_safety_and_actionability_artefacts(self) -> None:+ # The judge verdicts that set the status are persisted as the report's status artefacts, so the+ # inbox derives the same safety/actionability state a pipeline report would.+ result = create_scout_report(+ team_id=self.team.id,+ title="t",+ summary="s",+ signals=[ScoutReportSignal(description="d", source_id="obs")],+ attribution=ArtefactAttribution.system(),+ status=SignalReport.Status.PENDING_INPUT,+ safety=SafetyJudgment(choice=True, explanation=None),+ actionability=ActionabilityAssessment(+ explanation="needs a product decision",+ actionability=ActionabilityChoice.REQUIRES_HUMAN_INPUT,+ already_addressed=False,+ ),+ )+ report = SignalReport.objects.get(id=result.report_id)+ assert report.status == SignalReport.Status.PENDING_INPUT+ types = set(SignalReportArtefact.objects.filter(report_id=result.report_id).values_list("type", flat=True))+ assert SignalReportArtefact.ArtefactType.SAFETY_JUDGMENT in types+ assert SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT in types++ def test_soft_delete_re_emits_tombstone_preserving_id_and_timestamp(self) -> None:+ # Soft-delete is a re-emit of the same document_id with metadata.deleted=True; the original+ # timestamp must be preserved so the tombstone lands in the same ReplacingMergeTree partition+ # and supersedes the live row rather than adding a sibling. The target report must be one the+ # team owns (team-scoped fail-closed), so author a real report first.+ report = create_scout_report(+ team_id=self.team.id,+ title="Checkout API p99 latency regressed",+ summary="The checkout endpoint p99 doubled after the 4.2 deploy.",+ signals=[ScoutReportSignal(description="p99 doubled on /checkout", source_id="obs-1", weight=1.0)],+ attribution=ArtefactAttribution.system(),+ )+ document_id = report.signal_document_ids[0]+ self.emit_mock.reset_mock()++ ts = datetime(2026, 6, 1, 12, 0, tzinfo=UTC)+ soft_delete_scout_signal(+ team_id=self.team.id,+ report_id=report.report_id,+ document_id=document_id,+ description="p99 doubled on /checkout",+ timestamp=ts,+ source_id="obs-1",+ )+ kwargs = self.emit_mock.call_args.kwargs+ assert kwargs["document_id"] == document_id+ assert kwargs["timestamp"] == ts+ assert kwargs["metadata"]["deleted"] is True+ assert kwargs["metadata"]["report_id"] == report.report_id++ def test_create_rejects_duplicate_supplied_document_ids(self) -> None:+ # Two backing signals sharing a document_id would collapse in the ReplacingMergeTree, leaving+ # the report claiming more evidence than reads can resolve — reject at validation time.+ with pytest.raises(InvalidScoutReportError):+ create_scout_report(+ team_id=self.team.id,+ title="t",+ summary="s",+ signals=[+ ScoutReportSignal(description="a", source_id="obs-1", document_id="dup"),+ ScoutReportSignal(description="b", source_id="obs-2", document_id="dup"),+ ],+ attribution=ArtefactAttribution.system(),+ )++ def test_soft_delete_rejects_report_another_team_owns(self) -> None:+ # Fail-closed: a report_id the team doesn't own must raise before any tombstone is emitted,+ # so a foreign report_id + known document_id can't soft-delete another tenant's signal.+ other_team = Team.objects.create(organization=Organization.objects.create(name="other"), name="other")+ with team_scope(other_team.id):+ foreign = create_scout_report(+ team_id=other_team.id,+ title="Other team report",+ summary="Belongs to a different tenant.",+ signals=[ScoutReportSignal(description="obs", source_id="obs-x", weight=1.0)],+ attribution=ArtefactAttribution.system(),+ )+ self.emit_mock.reset_mock()+ with pytest.raises(InvalidScoutReportError):+ soft_delete_scout_signal(+ team_id=self.team.id,+ report_id=foreign.report_id,+ document_id=foreign.signal_document_ids[0],+ description="obs",+ timestamp=datetime(2026, 6, 1, 12, 0, tzinfo=UTC),+ source_id="obs-x",+ )+ self.emit_mock.assert_not_called()