Skip to content

: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.

fix(signals): fail closed when the scout report safety model refuses (#122986)

posthog[bot]c98711a33b8e
diff --git a/products/signals/backend/scout_report/judge.py b/products/signals/backend/scout_report/judge.py
index e64712c02827..051ad6f6b438 100644
--- a/products/signals/backend/scout_report/judge.py
+++ b/products/signals/backend/scout_report/judge.py
@@ -22,8 +22,10 @@ from __future__ import annotations
import json
import uuid
+import logging
from collections.abc import Sequence
from dataclasses import dataclass
+from typing import Literal
from django.utils import timezone
@@ -33,9 +35,13 @@ from products.signals.backend.report_charts import ReportChart
from products.signals.backend.report_metrics import ReportMetric
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.llm import LLMRefusalError
+from products.signals.backend.temporal.metrics import increment_scout_report_safety_refusal
+from products.signals.backend.temporal.report_safety_judge import SafetyJudgeResponse, judge_report_safety
from products.signals.backend.temporal.types import SignalData
+logger = logging.getLogger(__name__)
+
@dataclass(frozen=True)
class ScoutReportJudgement:
@@ -62,6 +68,21 @@ def resolve_authored_report_status(*, safe: bool, actionability: ActionabilityCh
raise ValueError(f"unhandled actionability choice: {actionability}")
+SAFETY_REFUSAL_EXPLANATION = "The safety model refused to assess this content, so it is treated as unsafe."
+
+
+async def _judge_safety_fail_closed(
+ team_id: int, signals: list[SignalData], *, path: Literal["emit", "edit"]
+) -> SafetyJudgeResponse:
+ """Fail closed when the safety model refuses: a refusal gives no verdict, so the content counts as unsafe."""
+ try:
+ return await judge_report_safety(team_id=team_id, signals=signals)
+ except LLMRefusalError:
+ logger.warning("signals_scout: safety model refused a report", extra={"team_id": team_id, "path": path})
+ increment_scout_report_safety_refusal(path)
+ return SafetyJudgeResponse(choice=False, explanation=SAFETY_REFUSAL_EXPLANATION)
+
+
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
@@ -291,7 +312,7 @@ async def judge_scout_report(
*([tags_signal] if tags_signal is not None else []),
*_to_signal_data(signals),
]
- safety_response = await judge_report_safety(team_id=team_id, signals=safety_input)
+ safety_response = await _judge_safety_fail_closed(team_id, safety_input, path="emit")
safety = SafetyJudgment(
choice=safety_response.choice,
explanation=safety_response.explanation if not safety_response.choice else None,
@@ -358,7 +379,7 @@ async def judge_edited_report_content(
safety_input.append(tags_signal)
if not safety_input:
return SafetyJudgment(choice=True, explanation=None)
- safety_response = await judge_report_safety(team_id=team_id, signals=safety_input)
+ safety_response = await _judge_safety_fail_closed(team_id, safety_input, path="edit")
return SafetyJudgment(
choice=safety_response.choice,
explanation=safety_response.explanation if not safety_response.choice else None,
diff --git a/products/signals/backend/temporal/metrics.py b/products/signals/backend/temporal/metrics.py
index dea4b025d74b..03a354cfc75b 100644
--- a/products/signals/backend/temporal/metrics.py
+++ b/products/signals/backend/temporal/metrics.py
@@ -36,6 +36,14 @@ SCOUT_COORDINATOR_DISPATCHED = Counter(
["outcome"],
)
+SCOUT_REPORT_SAFETY_REFUSALS_METRIC = "signals_scout_report_safety_refusals_total"
+
+SCOUT_REPORT_SAFETY_REFUSALS = Counter(
+ SCOUT_REPORT_SAFETY_REFUSALS_METRIC,
+ "Scout report safety judge calls the model refused, by report path",
+ ["path"],
+)
+
FUNNEL_STAGE_EMITTED = "emitted"
FUNNEL_STAGE_GROUPED = "grouped"
FUNNEL_STAGE_PROMOTED = "promoted"
@@ -202,13 +210,13 @@ def increment_scout_run(status: str) -> None:
).add(1)
-def _push_coordinator_metric(name: str, value: float, attributes: dict[str, str]) -> None:
- """Push one coordinator counter into the PostHog Metrics product.
+def _push_posthog_metric(name: str, value: float, attributes: dict[str, str]) -> None:
+ """Push one counter into the PostHog Metrics product.
The SDK client is the only sink that carries a counter out of a Temporal worker into the
Metrics product: the worker exports no `prometheus_client` series there, and it has no OTLP
- push configured. Failures are swallowed, because this runs in the planning activity and a
- telemetry error that failed the tick would cause the dispatch stall these counters watch for.
+ push configured. Failures are swallowed, because callers run on paths that a telemetry error
+ must not fail, such as the coordinator planning activity and the scout report safety judge.
"""
try:
posthoganalytics.setup().metrics.count(name, value, attributes=attributes)
@@ -224,10 +232,10 @@ def increment_coordinator_tick(planned_count: int) -> None:
tells them apart.
"""
SCOUT_COORDINATOR_TICKS.inc()
- _push_coordinator_metric(SCOUT_COORDINATOR_TICKS_METRIC, 1, {})
+ _push_posthog_metric(SCOUT_COORDINATOR_TICKS_METRIC, 1, {})
# Zero is the reading that matters, so the series is kept alive rather than guarded away.
SCOUT_COORDINATOR_PLANNED.inc(planned_count)
- _push_coordinator_metric(SCOUT_COORDINATOR_PLANNED_METRIC, planned_count, {})
+ _push_posthog_metric(SCOUT_COORDINATOR_PLANNED_METRIC, planned_count, {})
# A labeled counter has no child series until code calls .labels(), and the dispatch counter is
# only touched after a dispatch. So warm both outcomes to zero every tick. A stall is a run of
# zero-plan ticks that never dispatch, which is exactly when the dispatch series would otherwise
@@ -239,4 +247,14 @@ def increment_coordinator_tick(planned_count: int) -> None:
def increment_coordinator_dispatch(outcome: str, count: int) -> None:
"""Count scout child workflows the coordinator dispatched, by outcome."""
SCOUT_COORDINATOR_DISPATCHED.labels(outcome=outcome).inc(count)
- _push_coordinator_metric(SCOUT_COORDINATOR_DISPATCHED_METRIC, count, {"outcome": outcome})
+ _push_posthog_metric(SCOUT_COORDINATOR_DISPATCHED_METRIC, count, {"outcome": outcome})
+
+
+def increment_scout_report_safety_refusal(path: str) -> None:
+ """Count a scout report safety judge call that the model refused, by report path (emit or edit).
+
+ The judge fails closed on a refusal, so no exception records it. This counter is the only signal.
+ It works outside Temporal because the scout report API calls the judge from a web request.
+ """
+ SCOUT_REPORT_SAFETY_REFUSALS.labels(path=path).inc()
+ _push_posthog_metric(SCOUT_REPORT_SAFETY_REFUSALS_METRIC, 1, {"path": path})
diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.py
index e307eb0871f6..d0cf5dbeb487 100644
--- a/products/signals/backend/test/test_scout_report_api.py
+++ b/products/signals/backend/test/test_scout_report_api.py
@@ -62,7 +62,9 @@ from products.signals.backend.scout_harness.tools.report import (
)
from products.signals.backend.scout_harness.tools.report_author import ScoutRunReportAuthor
from products.signals.backend.scout_report import ScoutReportSignal
+from products.signals.backend.scout_report.judge import SAFETY_REFUSAL_EXPLANATION
from products.signals.backend.task_run_artefacts import record_implementation_task
+from products.signals.backend.temporal.llm import LLMRefusalError
from products.signals.backend.temporal.report_safety_judge import SafetyJudgeResponse
from products.signals.backend.temporal.types import SignalData, render_signal_to_text
from products.signals.backend.test.report_metric_test_fixtures import trends_metric_query
@@ -82,6 +84,7 @@ CAPTURE_INTERNAL_PATH = "products.signals.backend.scout_harness.tools.report.cap
CONNECTED_REPOS_PATH = "products.signals.backend.scout_harness.tools.report._connected_repositories"
SET_REPOSITORY_PATH = "products.signals.backend.scout_harness.tools.report.set_scout_report_repository"
REVISION_COUNT_PATH = "products.signals.backend.scout_harness.tools.report.get_content_revision_count"
+REFUSAL_COUNTER_PATH = "products.signals.backend.scout_report.judge.increment_scout_report_safety_refusal"
_CONNECTED_REPOS = ["acme/widgets", "acme/gadgets"]
REPORT_TOOLS = ["emit_report", "edit_report"]
@@ -90,6 +93,16 @@ def _safe_judge(choice: bool = True, explanation: str = ""):
return patch(JUDGE_PATH, new=AsyncMock(return_value=SafetyJudgeResponse(choice=choice, explanation=explanation)))
+def _refusing_judge():
+ return patch(JUDGE_PATH, new=AsyncMock(side_effect=LLMRefusalError("Model refused the request")))
+
+
+UNSAFE_JUDGES = [
+ ("unsafe_verdict", lambda: _safe_judge(choice=False, explanation="prompt injection"), "prompt injection", False),
+ ("model_refusal", _refusing_judge, SAFETY_REFUSAL_EXPLANATION, True),
+]
+
+
class TestScoutReportAPI(APIBaseTest):
def setUp(self) -> None:
super().setUp()
@@ -367,16 +380,18 @@ class TestScoutReportAPI(APIBaseTest):
assert enqueue.call_args_list[2].kwargs["edit_note"] is None
assert enqueue.call_args_list[3].kwargs["edit_note"] is None
- def test_emit_report_unsafe_suppresses_but_returns_id(self) -> None:
+ @parameterized.expand(UNSAFE_JUDGES)
+ def test_emit_report_unsafe_suppresses_but_returns_id(self, _name, judge, explanation, refused) -> None:
run = _make_run(self.team)
config = run.scout_config
assert config is not None
config.output_destinations = {"slack": {"integration_id": 17, "channel": "CSCOUTS|#scout-findings"}}
config.save(update_fields=["output_destinations"])
with (
- _safe_judge(choice=False, explanation="prompt injection"),
+ judge(),
patch(EMBED_PATH),
patch("products.signals.backend.scout_harness.tools.report.queue_configured_scout_slack_delivery") as queue,
+ patch(REFUSAL_COUNTER_PATH) as refusal_counter,
):
response = self.client.post(
self._emit_url(str(run.id)),
@@ -387,8 +402,9 @@ class TestScoutReportAPI(APIBaseTest):
body = response.json()
assert body["emitted"] is False
assert body["report_status"] == SignalReport.Status.SUPPRESSED
- assert body["safety_explanation"] == "prompt injection"
+ assert body["safety_explanation"] == explanation
assert body["report_id"] is not None
+ assert [c.args for c in refusal_counter.call_args_list] == ([("emit",)] if refused else [])
queue.assert_not_called()
# The judge-rejected prompts must not persist: a suppressed report is still reachable from
# the Dismissed view, where a click would hand that wording to an action-capable agent run.
@@ -1242,14 +1258,15 @@ class TestScoutReportAPI(APIBaseTest):
# The gate rejects a foreign report before the judge, so a bad id never spends an LLM call.
judge_mock.assert_not_awaited()
- def test_unsafe_edit_is_rejected_and_report_keeps_its_content(self) -> None:
+ @parameterized.expand(UNSAFE_JUDGES)
+ def test_unsafe_edit_is_rejected_and_report_keeps_its_content(self, _name, judge, explanation, refused) -> None:
# `emit_report` judges everything it authors; before the edit path got the same judge, an
# unsafe summary or suggested prompt could land on a surfaced report by editing it in — and a
# suggested prompt's wording is handed to an agent run told to act on it.
run = _make_run(self.team)
with _safe_judge(), patch(EMBED_PATH):
created = self.client.post(self._emit_url(str(run.id)), data=self._payload(), format="json").json()
- with _safe_judge(choice=False, explanation="prompt injection"):
+ with judge(), patch(REFUSAL_COUNTER_PATH) as refusal_counter:
response = self.client.post(
self._edit_url(str(run.id)),
data={
@@ -1260,7 +1277,8 @@ class TestScoutReportAPI(APIBaseTest):
format="json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
- assert "safety judge" in response.content.decode()
+ assert f"edit rejected by the safety judge: {explanation}" in response.content.decode()
+ assert [c.args for c in refusal_counter.call_args_list] == ([("edit",)] if refused else [])
report = SignalReport.objects.get(id=created["report_id"])
assert report.summary == self._payload()["summary"]
assert report.suggested_prompts == []