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): match setup-flow scout pauses by their mcp activity log (#107735)

posthog[bot]5555f743753c
diff --git a/products/signals/backend/management/AGENTS.md b/products/signals/backend/management/AGENTS.md
index 334fe629347b..4bdc7b24119a 100644
--- a/products/signals/backend/management/AGENTS.md
+++ b/products/signals/backend/management/AGENTS.md
@@ -203,7 +203,10 @@ Idempotent. It recomputes each report from its artefacts and writes only the row
An older self-driving setup flow switched off every scout the user did not pick, including operational scouts such as inbox validation.
Those rows look like a person's pause, so the coordinator's reconcile leaves them alone.
-`resume_setup_paused_operational_scouts` resumes only operational rows paused without an attributed user within `--max-gap-seconds` (default 300) of creation.
+The setup flow paused them over MCP on the user's own session, so `status_changed_by` holds the user and cannot tell the two apart.
+`resume_setup_paused_operational_scouts` resumes only operational rows whose pause has an `mcp` activity log entry within a few seconds of `status_changed_at`.
+It leaves pauses from the UI, the system, a scout, or with no log entry alone, and prints how many paused rows each source holds.
+Pass `--max-gap-seconds` to also require that the pause landed soon after creation. It is off by default.
It skips withheld scouts and does not go past the enabled-scout cap.
```bash
diff --git a/products/signals/backend/management/commands/resume_setup_paused_operational_scouts.py b/products/signals/backend/management/commands/resume_setup_paused_operational_scouts.py
index 59fd4696dbaa..6fa4ceadcd71 100644
--- a/products/signals/backend/management/commands/resume_setup_paused_operational_scouts.py
+++ b/products/signals/backend/management/commands/resume_setup_paused_operational_scouts.py
@@ -10,8 +10,9 @@ from products.signals.backend.scout_harness.config_registry import resume_setup_
class Command(BaseCommand):
help = (
"Resume operational scouts (such as inbox validation) that the old self-driving setup flow "
- "switched off seconds after the seed. A pause a person made is left alone. Dry run unless "
- "--apply is passed. Safe to rerun: a resumed row no longer matches."
+ "switched off over MCP. A pause the activity log attributes to another client, or does not "
+ "record, is left alone. Dry run unless --apply is passed. Safe to rerun: a resumed row no "
+ "longer matches."
)
def add_arguments(self, parser: ArgumentParser) -> None:
@@ -23,20 +24,23 @@ class Command(BaseCommand):
parser.add_argument(
"--max-gap-seconds",
type=int,
- default=300,
- help="Longest time between the seed and the pause for the pause to count as the setup flow's.",
+ default=None,
+ help="Optional. Longest time between the seed and the pause for the pause to count as the setup flow's.",
)
parser.add_argument("--show-team-ids", type=int, default=20, help="How many team ids to print.")
def handle(self, *args: object, **options: object) -> None:
apply = bool(options["apply"])
+ max_gap_seconds = cast(int | None, options["max_gap_seconds"])
summary = resume_setup_paused_operational_scouts(
apply=apply,
team_id=cast(int | None, options["team_id"]),
batch_size=max(1, min(cast(int, options["batch_size"]), 5000)),
- max_gap=timedelta(seconds=max(0, cast(int, options["max_gap_seconds"]))),
+ max_gap=None if max_gap_seconds is None else timedelta(seconds=max(0, max_gap_seconds)),
)
self.stdout.write("Mode: apply" if apply else "Mode: dry run (pass --apply to write)")
+ sources = ", ".join(f"{source} {count}" for source, count in sorted(summary.pause_sources.items()))
+ self.stdout.write(f"Pause sources: {sources or 'none'}. Only mcp pauses are selected.")
for skill_name, count in sorted(summary.selected.items()):
line = f"{skill_name}: selected {count}, withheld {summary.skipped_withheld[skill_name]}"
if apply:
diff --git a/products/signals/backend/scout_harness/config_registry.py b/products/signals/backend/scout_harness/config_registry.py
index 24cd92f66a52..dc6c3b6b10dc 100644
--- a/products/signals/backend/scout_harness/config_registry.py
+++ b/products/signals/backend/scout_harness/config_registry.py
@@ -19,14 +19,16 @@ from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from django.db import transaction
-from django.db.models import Exists, F, OuterRef, Q, QuerySet
+from django.db.models import CharField, Exists, F, OuterRef, Q, QuerySet, Subquery
+from django.db.models.functions import Cast
from django.utils import timezone
import structlog
from croniter import CroniterError, croniter
-from posthog.models.activity_logging.activity_log import Trigger
+from posthog.models.activity_logging.activity_log import ActivityLog, Trigger
from posthog.models.activity_logging.model_activity import ActivityTriggerContext
+from posthog.models.activity_logging.utils import SCOUT_CLIENT_PREFIX
from products.signals.backend.models import SignalScoutConfig
from products.signals.backend.scout_harness.lazy_seed import (
@@ -71,6 +73,11 @@ _CRON_SAMPLE_OCCURRENCES = 100
_OPERATIONAL_RECONCILE_JOB_TYPE = "signals_scout_operational_reconcile"
_SETUP_PAUSE_RESUME_JOB_TYPE = "signals_scout_setup_pause_resume"
+# The client the old setup flow's config writes carry in the activity log.
+SETUP_FLOW_CLIENT = "mcp"
+# The log entry is written in the same save that stamps `status_changed_at`, so the two differ by
+# milliseconds. The window only absorbs clock and transaction delay.
+_SETUP_PAUSE_LOG_WINDOW = timedelta(seconds=10)
def cron_schedule_error(value: str) -> str | None:
@@ -557,30 +564,79 @@ def _resume_operational_config(config: SignalScoutConfig, *, max_enabled_scouts:
)
-def setup_paused_operational_configs(*, max_gap: timedelta, team_id: int | None = None) -> QuerySet[SignalScoutConfig]:
- """Operational scout configs that a setup flow switched off right after the seed.
+def _setup_pause_candidates(*, max_gap: timedelta | None, team_id: int | None) -> QuerySet[SignalScoutConfig]:
+ """Paused operational scout configs, each annotated with the activity log entry of its pause.
- The setup flow wrote `enabled: false` through the config API without a user attribution,
- seconds after the seed created the row. That leaves a `paused_by_user` row with no
- `status_changed_by` and a `status_changed_at` close to `created_at`. A person's pause carries
- an attribution, or lands long after the seed, so it does not match.
+ The entry is the `updated` log for the row within `_SETUP_PAUSE_LOG_WINDOW` of
+ `status_changed_at`. `max_gap` optionally limits the rows to pauses that landed soon after the seed.
"""
+ pause_log = ActivityLog.objects.filter(
+ team_id=OuterRef("team_id"),
+ scope="SignalScoutConfig",
+ item_id=Cast(OuterRef("pk"), output_field=CharField()),
+ activity="updated",
+ created_at__gte=OuterRef("status_changed_at") - _SETUP_PAUSE_LOG_WINDOW,
+ created_at__lte=OuterRef("status_changed_at") + _SETUP_PAUSE_LOG_WINDOW,
+ ).order_by("-created_at")
configs = (
SignalScoutConfig.all_teams.filter(
skill_name__in=canonical_operational_scout_names(),
status=SignalScoutConfig.Status.PAUSED_BY_USER,
- status_changed_by__isnull=True,
status_changed_at__isnull=False,
- status_changed_at__lte=F("created_at") + max_gap,
)
.filter(_harness_seeded_skill_exists())
+ .annotate(
+ pause_log_exists=Exists(pause_log),
+ pause_log_client=Subquery(pause_log.values("client")[:1]),
+ pause_log_is_system=Subquery(pause_log.values("is_system")[:1]),
+ )
.order_by("team_id", "skill_name")
)
+ if max_gap is not None:
+ configs = configs.filter(status_changed_at__lte=F("created_at") + max_gap)
if team_id is not None:
configs = configs.filter(team_id=team_id)
return configs
+def _pause_source(*, log_exists: bool, client: str | None, is_system: bool | None) -> str:
+ if not log_exists:
+ return "no_log"
+ if client == SETUP_FLOW_CLIENT:
+ return SETUP_FLOW_CLIENT
+ if client is not None and client.startswith(SCOUT_CLIENT_PREFIX):
+ return "scout"
+ if is_system:
+ return "system"
+ if client is None:
+ # The web app sends no client header, so a pause made in the UI lands here.
+ return "ui"
+ return "other"
+
+
+def setup_paused_operational_configs(
+ *, max_gap: timedelta | None = None, team_id: int | None = None
+) -> QuerySet[SignalScoutConfig]:
+ """Operational scout configs that a setup flow switched off right after the seed.
+
+ The setup flow wrote `enabled: false` through the config API over MCP, on the user's own
+ session. So the row carries the user in `status_changed_by`, the same as a manual pause. The
+ activity log entry of the pause tells them apart: only the setup flow's entry has the `mcp` client.
+ """
+ return _setup_pause_candidates(max_gap=max_gap, team_id=team_id).filter(Q(pause_log_client=SETUP_FLOW_CLIENT))
+
+
+def setup_pause_sources(*, max_gap: timedelta | None = None, team_id: int | None = None) -> Counter[str]:
+ """How many paused operational scouts each pause source holds, to show what the selection skips."""
+ rows = _setup_pause_candidates(max_gap=max_gap, team_id=team_id).values_list(
+ F("pause_log_exists"), F("pause_log_client"), F("pause_log_is_system")
+ )
+ return Counter(
+ _pause_source(log_exists=log_exists, client=client, is_system=is_system)
+ for log_exists, client, is_system in rows
+ )
+
+
def resume_setup_paused_operational_config(config: SignalScoutConfig, *, max_enabled_scouts: int) -> bool:
"""Put one setup-paused operational scout back to `active`, exempt from the inactivity sweep.
@@ -596,7 +652,6 @@ def resume_setup_paused_operational_config(config: SignalScoutConfig, *, max_ena
if (
locked is None
or locked.status != SignalScoutConfig.Status.PAUSED_BY_USER
- or locked.status_changed_by_id is not None
or locked.status_changed_at != config.status_changed_at
):
return False
@@ -640,18 +695,19 @@ class ResumeSummary:
resumed: Counter[str] = field(default_factory=Counter)
skipped_withheld: Counter[str] = field(default_factory=Counter)
not_resumed: Counter[str] = field(default_factory=Counter)
+ pause_sources: Counter[str] = field(default_factory=Counter)
team_ids: list[int] = field(default_factory=list)
def resume_setup_paused_operational_scouts(
- *, apply: bool, team_id: int | None, batch_size: int, max_gap: timedelta
+ *, apply: bool, team_id: int | None, batch_size: int, max_gap: timedelta | None = None
) -> ResumeSummary:
# One flag read for the whole run, so every team resolves its holdback and cap from one payload.
payload = _read_flag_payload()
team_configs = _canonicalize_team_config_keys(_team_configs(payload))
default_team_config = _default_team_config(payload)
- summary = ResumeSummary()
+ summary = ResumeSummary(pause_sources=setup_pause_sources(max_gap=max_gap, team_id=team_id))
seen_team_ids: set[int] = set()
# A pk cursor rather than re-reading the first page: a row this run skips still matches.
after_pk = None
diff --git a/products/signals/backend/test/test_resume_setup_paused_operational_scouts.py b/products/signals/backend/test/test_resume_setup_paused_operational_scouts.py
index d81946245f56..8c30193b1d43 100644
--- a/products/signals/backend/test/test_resume_setup_paused_operational_scouts.py
+++ b/products/signals/backend/test/test_resume_setup_paused_operational_scouts.py
@@ -1,13 +1,16 @@
from datetime import timedelta
+from io import StringIO
from typing import Any
-from posthog.test.base import BaseTest
+from posthog.test.base import APIBaseTest
from unittest.mock import patch
from django.core.management import call_command
from parameterized import parameterized
+from posthog.models.activity_logging.activity_log import ActivityLog
+
from products.signals.backend.models import SignalScoutConfig
from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY
from products.skills.backend.models.skills import LLMSkill
@@ -16,33 +19,42 @@ _OPERATIONAL_SCOUT = "signals-scout-inbox-validation"
_READ_PAYLOAD = "products.signals.backend.scout_harness.config_registry._read_flag_payload"
-class TestResumeSetupPausedOperationalScouts(BaseTest):
+class TestResumeSetupPausedOperationalScouts(APIBaseTest):
def _paused_config(
- self, skill_name: str = _OPERATIONAL_SCOUT, *, gap: timedelta = timedelta(seconds=10), by_user: bool = False
+ self, skill_name: str = _OPERATIONAL_SCOUT, *, client: str | None = "mcp", log: bool = True
) -> SignalScoutConfig:
LLMSkill.objects.create(
team=self.team, name=skill_name, description="d", body="b", metadata={"seeded_by": HARNESS_SEEDED_BY}
)
config = SignalScoutConfig.objects.create(team=self.team, skill_name=skill_name, enabled=True)
- SignalScoutConfig.all_teams.filter(pk=config.pk).update(
- enabled=False,
- status=SignalScoutConfig.Status.PAUSED_BY_USER,
- status_changed_at=config.created_at + gap,
- status_changed_by=self.user if by_user else None,
+ headers = {"X-PostHog-Client": client} if client else {}
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/signals/scout/configs/{config.id}/",
+ data={"enabled": False},
+ format="json",
+ headers=headers,
)
+ assert response.status_code == 200, response.json()
+ if not log:
+ ActivityLog.objects.filter(scope="SignalScoutConfig", item_id=str(config.id)).delete()
config.refresh_from_db()
+ assert config.status == SignalScoutConfig.Status.PAUSED_BY_USER
+ assert config.status_changed_by_id == self.user.id
return config
- def _run(self, *args: str, payload: dict[str, Any] | None = None) -> None:
+ def _run(self, *args: str, payload: dict[str, Any] | None = None) -> str:
+ out = StringIO()
with patch(_READ_PAYLOAD, return_value=payload):
- call_command("resume_setup_paused_operational_scouts", *args)
+ call_command("resume_setup_paused_operational_scouts", *args, stdout=out)
+ return out.getvalue()
- def test_dry_run_changes_nothing_and_apply_resumes_the_setup_pause(self) -> None:
+ def test_dry_run_changes_nothing_and_apply_resumes_the_mcp_pause(self) -> None:
config = self._paused_config()
- self._run()
+ output = self._run()
config.refresh_from_db()
assert config.status == SignalScoutConfig.Status.PAUSED_BY_USER
+ assert "Pause sources: mcp 1" in output
self._run("--apply", "--team-id", str(self.team.id))
config.refresh_from_db()
@@ -52,19 +64,34 @@ class TestResumeSetupPausedOperationalScouts(BaseTest):
@parameterized.expand(
[
- ("attributed_pause", {"by_user": True}),
- ("late_pause", {"gap": timedelta(hours=1)}),
- ("specialist", {"skill_name": "signals-scout-general"}),
+ ("ui_pause", {"client": None}, "ui 1"),
+ ("no_log_entry", {"log": False}, "no_log 1"),
+ ("specialist", {"skill_name": "signals-scout-general"}, "none"),
]
)
- def test_apply_leaves_pauses_the_setup_flow_did_not_make(self, _name: str, kwargs: dict[str, Any]) -> None:
+ def test_apply_leaves_pauses_the_setup_flow_did_not_make(
+ self, _name: str, kwargs: dict[str, Any], sources: str
+ ) -> None:
config = self._paused_config(**kwargs)
- self._run("--apply")
+ output = self._run("--apply")
config.refresh_from_db()
assert config.status == SignalScoutConfig.Status.PAUSED_BY_USER
assert config.enabled is False
+ assert f"Pause sources: {sources}" in output
+
+ def test_max_gap_leaves_a_late_mcp_pause(self) -> None:
+ config = self._paused_config()
+ assert config.status_changed_at is not None
+ SignalScoutConfig.all_teams.filter(pk=config.pk).update(
+ created_at=config.status_changed_at - timedelta(hours=1)
+ )
+
+ self._run("--apply", "--max-gap-seconds", "300")
+
+ config.refresh_from_db()
+ assert config.status == SignalScoutConfig.Status.PAUSED_BY_USER
def test_apply_leaves_a_withheld_scout_paused(self) -> None:
config = self._paused_config()