:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signals): run scout pre-checks as the scout's acting user (#115160)
posthog[bot]c5b9ea156264
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.mdindex 9d5f6292980e..567914eea9b0 100644--- a/products/signals/backend/scout_harness/AGENTS.md+++ b/products/signals/backend/scout_harness/AGENTS.md@@ -36,6 +36,8 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick eResolves a scout's `LLMSkill` row from the team's rows by name, under any valid scout name. Defines `SIGNALS_SCOUT_SKILL_PREFIX` — kept for the canonical on-disk paths, auto-registration, and display-name stripping, not as a naming requirement — and `LoadedSkill` (body + version + allowed_tools + origin + authors), plus `REPORT_CHANNEL_TOOLS` / `skill_uses_report_channel` — the shared report-channel opt-in predicate the runner (scope posture) and prompt builder (persona fork) both resolve from.`resolve_skill_authors` prefers the skill's **explicit owner set** (`LLMSkillOwner`, keyed on the logical `(team, name)` so it never drifts when the body is edited) — returned as `role="owner"`, seed-creator first. Only when a skill has no explicit owners does it fall back to reconstructing authorship from version rows (distinct non-null `created_by`: creator = earliest first-authored, then editors by last-edit recency, capped). Both paths are restricted to `team.all_users_with_access()` so a revoked user's profile stops flowing into a privileged prompt.`resolve_skill_owner_user_uuids` exposes the owner set (seed-creator first) to the report tools' reviewer provenance stamp (`is_skill_owner`). Author resolution is opt-in via `load_skill_for_run(..., include_authors=True)` — only the runner's prompt-building path pays for it; the report-authorization gate in `views.py` loads the skill per report write just to check `allowed_tools` and skips it.+- `acting_user.py`+ `resolve_scout_run_acting_user` is the one answer to who a run acts as: the trial's user, else `skill_loader.resolve_scout_acting_user_id`, else the team fallback (`resolve_acting_user_id_for_team`, flagged `is_team_fallback` so the runner withholds the write grant). The runner and `precheck.py` both call it, so a scheduled pre-check reads exactly the tables its run can read. A query with no user loses every access-scoped `system.*` table and every warehouse table. The pre-check dry run runs as the requester instead, so a config editor cannot read through the acting user's access.- `lazy_seed.py`Canonical skill sync. Reads `products/signals/skills/signals-scout-*/` from disk and reconciles them against the team's `LLMSkill` rows: creates missing rows, updates ones the team hasn't edited, leaves diverged / hand-authored rows alone, tombstones rows whose canonical skill was deleted. Only rows tagged `metadata.seeded_by="signals_scout_harness"` are ever updated. Called both lazily (coordinator tick, runner cold-start) and explicitly via the `sync_signals_scout_skills` management command.It also parses the retirement marker (`canonical_deprecation_for`, see `deprecation.py`) and the three config-shaping frontmatter keys, none of which enters the content hash (all belong to the config, not the skill row): `scout-tags` (`canonical_config_tags_for`), `scout-role` (`is_operational_scout`), and `scout-display-name` (`canonical_display_name_for`). `scout-display-name` is the label the scout ships under, and every canonical scout states one, because the clients' fallback sentence-cases the slug and turns `signals-scout-apm` into "Apm". `scout-role: operational` marks a scout that watches the self-driving system itself rather than a product surface — the fleet's follow-up validation scout — and an unknown value fails the parse rather than falling back, since a silently downgraded operational scout is the silencing the role exists to prevent.diff --git a/products/signals/backend/scout_harness/acting_user.py b/products/signals/backend/scout_harness/acting_user.pynew file mode 100644index 000000000000..8a172cfdfb97--- /dev/null+++ b/products/signals/backend/scout_harness/acting_user.py@@ -0,0 +1,43 @@+"""The user a scout run acts as.++The runner and the pre-check both resolve it here. The pre-check reads project data as this user,+so it can read the same tables the run can read, and no more.+"""++from __future__ import annotations++from posthog.dataclasses import frozen+from posthog.models.team.team import Team++from products.signals.backend.models import SignalScoutConfig+from products.signals.backend.scout_harness.skill_loader import resolve_scout_acting_user_id+++@frozen+class ScoutActingUser:+ user_id: int+ # True when no scout-level identity resolved and the team-level default stands in. That member+ # never approved the scout's write grant.+ is_team_fallback: bool = False+++def resolve_scout_run_acting_user(+ team: Team, skill_name: str, config: SignalScoutConfig | None, *, trial_user_id: int | None = None+) -> ScoutActingUser | None:+ """The trial's user, else the scout's own identity, else the team-level default.++ Returns None when no member of the project can act, in which case the run does not start.+ """+ # Deferred: the pre-check imports this module, and the scout scheduler imports the pre-check+ # while the temporal package that defines this function is still loading.+ from products.signals.backend.temporal.agentic import resolve_acting_user_id_for_team # noqa: PLC0415++ if trial_user_id is not None:+ return ScoutActingUser(user_id=trial_user_id)+ user_id = resolve_scout_acting_user_id(team, skill_name, config)+ if user_id is not None:+ return ScoutActingUser(user_id=user_id)+ fallback_id = resolve_acting_user_id_for_team(team.id)+ if fallback_id is None:+ return None+ return ScoutActingUser(user_id=fallback_id, is_team_fallback=True)diff --git a/products/signals/backend/scout_harness/precheck.py b/products/signals/backend/scout_harness/precheck.pyindex afeab4cbf302..f659fc7acdf5 100644--- a/products/signals/backend/scout_harness/precheck.py+++ b/products/signals/backend/scout_harness/precheck.py@@ -15,6 +15,10 @@ being quiet.A query error never turns the scout off: the run continues as if there were no pre-check.+A scheduled pre-check runs as the scout's acting user (`acting_user.resolve_scout_run_acting_user`),+so it can read the same tables the run can read. A query with no user loses every access-scoped+`system.*` table and every warehouse table. The dry run runs as the person who asked for it.+The query comes from the first source that applies (`resolve_effective_precheck`):1. `precheck_disabled` on the config: no pre-check, the scout runs every due tick.@@ -50,9 +54,10 @@ from posthog.clickhouse.workload import Workloadfrom posthog.dataclasses import frozenfrom posthog.errors import ExposedCHQueryErrorfrom posthog.event_usage import groups-from posthog.models import Team+from posthog.models import Team, Userfrom products.signals.backend.models import SignalScoutConfig, SignalScoutRun+from products.signals.backend.scout_harness.acting_user import resolve_scout_run_acting_userfrom products.signals.backend.scout_harness.lazy_seed import canonical_precheck_query_for, scout_skill_originfrom products.signals.backend.scout_harness.limits import MAX_PRECHECK_ROWS_BYTES, SCOUT_TRIAL_METADATA_KEYfrom products.signals.backend.scout_harness.team_limits import (@@ -119,6 +124,9 @@ class PrecheckDryRunResult:rows_text: str = ""# Set only for an error the person who wrote the query can act on, such as a syntax error.error: str | None = None+ # The user scheduled runs check the query as, set only when that is not the requester. Their+ # access can differ, so a table the dry run reads can still fail on a scheduled run.+ acting_user_id: int | None = Nonedef parse_precheck_query(query: str) -> ast.SelectQuery | ast.SelectSetQuery:@@ -199,6 +207,8 @@ def evaluate_scout_precheck(team_id: int, skill_name: str, now: datetime | None"skill_name","created_at","status",+ "enabled_by",+ "created_by","precheck_query","precheck_disabled","run_interval_minutes",@@ -214,15 +224,26 @@ def evaluate_scout_precheck(team_id: int, skill_name: str, now: datetime | Noneif effective.query is None:return None+ team = Team.objects.select_related("organization").get(pk=team_id)+ acting_user = resolve_scout_run_acting_user(team, skill_name, config)+ user = User.objects.filter(pk=acting_user.user_id).first() if acting_user is not None else None+ # With no member to act as, the run does not start either, so there is nothing to gate.+ if user is None:+ logger.info(+ "signals_scout: no acting user for the pre-check, skipping it",+ team_id=team_id,+ skill_name=skill_name,+ )+ return None+now = now or timezone.now()since = precheck_since(config)- team = Team.objects.select_related("organization").get(pk=team_id)interval_minutes = precheck_interval_minutes(config, team, now)started = time.monotonic()error_type: str | None = Nonetry:- found = _run_query(team, effective.query, since=since, now=now, interval_minutes=interval_minutes)+ found = _run_query(team, user, effective.query, since=since, now=now, interval_minutes=interval_minutes)except Exception as error:error_type = type(error).__name__logger.warning(@@ -242,6 +263,7 @@ def evaluate_scout_precheck(team_id: int, skill_name: str, now: datetime | Noneconfig=config,result=result,effective=effective,+ acting_user_id=user.pk,duration_ms=round((time.monotonic() - started) * 1000),error_type=error_type,)@@ -249,14 +271,20 @@ def evaluate_scout_precheck(team_id: int, skill_name: str, now: datetime | Nonedef dry_run_scout_precheck(- team: Team, config: SignalScoutConfig, query: str, now: datetime | None = None+ team: Team, config: SignalScoutConfig, query: str, *, user: User, now: datetime | None = None) -> PrecheckDryRunResult:- """Run a pre-check query the way the next scheduled run would, and change nothing."""+ """Run a pre-check query the way the next scheduled run would, and change nothing.++ The query runs as `user`, never as the acting user. Otherwise anyone who can edit the scout+ could read tables through the acting user's access that they cannot read themselves.+ """now = now or timezone.now()since = precheck_since(config)interval_minutes = precheck_interval_minutes(config, team, now)+ acting_user = resolve_scout_run_acting_user(team, config.skill_name, config)+ acting_user_id = acting_user.user_id if acting_user is not None and acting_user.user_id != user.pk else Nonetry:- found = _run_query(team, query, since=since, now=now, interval_minutes=interval_minutes)+ found = _run_query(team, user, query, since=since, now=now, interval_minutes=interval_minutes)except Exception as error:logger.info("signals_scout: pre-check dry run failed",@@ -274,6 +302,7 @@ def dry_run_scout_precheck(now=now,interval_minutes=interval_minutes,error=message,+ acting_user_id=acting_user_id,)result = _result_from_rows(found)return PrecheckDryRunResult(@@ -285,6 +314,7 @@ def dry_run_scout_precheck(row_count=len(found.rows),columns=tuple(str(column) for column in found.columns),rows_text=_render_rows(found),+ acting_user_id=acting_user_id,)@@ -309,7 +339,9 @@ def _result_from_rows(found: _PrecheckRows) -> PrecheckResult:return PrecheckResult(outcome="run", reason="rows", row_count=len(found.rows), rows_text=_render_rows(found))-def _run_query(team: Team, query: str, *, since: datetime, now: datetime, interval_minutes: int) -> _PrecheckRows:+def _run_query(+ team: Team, user: User, query: str, *, since: datetime, now: datetime, interval_minutes: int+) -> _PrecheckRows:parsed = parse_select(query, placeholders=_placeholders(since=since, now=now, interval_minutes=interval_minutes))capped = _cap_rows(parsed)with tags_context(product=Product.SIGNALS, feature=Feature.ENRICHMENT, team_id=team.pk):@@ -317,6 +349,7 @@ def _run_query(team: Team, query: str, *, since: datetime, now: datetime, intervquery_type="scout_precheck",query=capped,team=team,+ user=user,workload=Workload.OFFLINE,settings=HogQLGlobalSettings(max_execution_time=PRECHECK_TIMEOUT_S),)@@ -360,6 +393,7 @@ def _capture_precheck_evaluated(config: SignalScoutConfig,result: PrecheckResult,effective: EffectivePrecheck,+ acting_user_id: int,duration_ms: int,error_type: str | None,) -> None:@@ -374,7 +408,10 @@ def _capture_precheck_evaluated("reason": result.reason,"row_count": result.row_count,"duration_ms": duration_ms,+ # The exception class, so a denied table (`TableAccessDeniedError`) reads apart from+ # a syntax error or a timeout."error_type": error_type,+ "acting_user_id": acting_user_id,"query_source": effective.source,"rollout_bucket": effective.rollout_bucket,},diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.pyindex 953adb47c6e7..5cca5870265c 100644--- a/products/signals/backend/scout_harness/runner.py+++ b/products/signals/backend/scout_harness/runner.py@@ -34,6 +34,7 @@ from products.data_catalog.backend.facade.api import approved_metric_names_for_tfrom products.mcp_store.backend.facade.api import get_sandbox_mcp_server_namesfrom products.signals.backend.agent_runtime import STEP_SCOUT, AgentRuntime, resolve_agent_runtimefrom products.signals.backend.models import SignalScoutConfig, SignalScoutRun+from products.signals.backend.scout_harness.acting_user import resolve_scout_run_acting_userfrom products.signals.backend.scout_harness.derived_metadata import stamp_derived_metadatafrom products.signals.backend.scout_harness.lazy_seed import canonical_skill_names, sync_canonical_skillsfrom products.signals.backend.scout_harness.limits import (@@ -60,7 +61,6 @@ from products.signals.backend.scout_harness.skill_loader import (LoadedSkill,load_skill_for_run,resolve_report_channel_variant,- resolve_scout_acting_user_id,skill_uses_report_channel,)from products.signals.backend.scout_harness.team_limits import (@@ -79,7 +79,6 @@ from products.signals.backend.scout_harness.trial_state import SCOUT_TRIAL_METADfrom products.signals.backend.temporal.agentic import (SIGNALS_REPORT_RESEARCH_ENV_NAME,get_or_create_signals_sandbox_env,- resolve_acting_user_id_for_team,)from products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.agents import (@@ -397,26 +396,10 @@ async def _arun_signals_scout(# into `_spawn_and_run` and booked a bogus `failed`). The only remaining short-circuit is the# genuine "no member can act" case; like the withheld / in-flight skips it leaves no row, no# lifecycle event, and a `skip_reason` the coordinator can surface — not a failure.- user_id = (- trial.user_id- if trial is not None- else await database_sync_to_async(resolve_scout_acting_user_id, thread_sensitive=False)(- team, skill.name, config- )+ acting_user = await database_sync_to_async(resolve_scout_run_acting_user, thread_sensitive=False)(+ team, skill.name, config, trial_user_id=trial.user_id if trial is not None else None)- if user_id is None:- user_id = await database_sync_to_async(resolve_acting_user_id_for_team, thread_sensitive=False)(team.id)- if user_id is not None and _granted_write_scopes(config):- # The grant was approved for the person the runs act as. The team fallback is a member- # who never approved it, so this run holds only the fleet posture. Cleared in memory- # only: the runner never saves the config row, so the grant is back the moment the- # author's identity resolves again.- logger.info(- "signals_scout: withholding write access, acting user is the team fallback",- extra={"team_id": team_id, "skill_name": skill.name, "user_id": user_id},- )- config.write_scopes = []- if user_id is None:+ if acting_user is None:logger.info("signals_scout: skipping run, no active user to act as for team",extra={"team_id": team_id, "skill_name": skill.name},@@ -431,6 +414,17 @@ async def _arun_signals_scout(skill_version=skill.version,skip_reason="no active user to act as for team",)+ if acting_user.is_team_fallback and _granted_write_scopes(config):+ # The grant was approved for the person the runs act as. The team fallback is a member+ # who never approved it, so this run holds only the fleet posture. Cleared in memory+ # only: the runner never saves the config row, so the grant is back the moment the+ # author's identity resolves again.+ logger.info(+ "signals_scout: withholding write access, acting user is the team fallback",+ extra={"team_id": team_id, "skill_name": skill.name, "user_id": acting_user.user_id},+ )+ config.write_scopes = []+ user_id = acting_user.user_idstarted = time.monotonic()# Pre-mint the bridge row's UUID so the prompt can reference it before the rowdiff --git a/products/signals/backend/scout_harness/serializers.py b/products/signals/backend/scout_harness/serializers.pyindex 3f3b4e7ae5b5..fe8fc79dd502 100644--- a/products/signals/backend/scout_harness/serializers.py+++ b/products/signals/backend/scout_harness/serializers.py@@ -4255,6 +4255,15 @@ class SignalScoutPrecheckTestSerializer(serializers.Serializer):"failures read as a general message. Null when the query ran."),)+ acting_user = UserBasicSerializer(+ allow_null=True,+ read_only=True,+ help_text=(+ "The member scheduled runs check the query as, when that is not you. The test runs with your "+ "access, so a table you can read can still fail on a scheduled run, and the run then starts "+ "as if there were no pre-check. Null when scheduled runs check it as you."+ ),+ )class SignalScoutCreateSerializer(serializers.Serializer):diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 7ee46f81ae8a..9c3fe6d95eeb 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -3819,8 +3819,11 @@ class SignalScoutConfigViewSet(ScoutTrialConfigMixin, TeamAndOrgViewSetMixin, vi).queryif not query:raise exceptions.ValidationError({"precheck_query": "This scout has no pre-check query. Give one to test."})- result = dry_run_scout_precheck(team, config, query)- return Response(SignalScoutPrecheckTestSerializer(dataclasses.asdict(result)).data)+ result = dry_run_scout_precheck(team, config, query, user=cast(User, request.user))+ acting_user = User.objects.filter(pk=result.acting_user_id).first() if result.acting_user_id else None+ return Response(+ SignalScoutPrecheckTestSerializer({**dataclasses.asdict(result), "acting_user": acting_user}).data+ )@extend_schema(request=None,diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pyindex 51a091265e11..08f8dd43cd1c 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -1694,7 +1694,7 @@ async def test_successful_run_creates_bridge_row_pointing_at_task_run(return_value="env-id",),patch(- "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ "products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team",return_value=42,),):@@ -1979,7 +1979,7 @@ async def test_run_tags_session_with_scout_attribution(ateam, aerrors_skill):return_value="env-id",),patch(- "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ "products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team",return_value=42,),):@@ -2021,7 +2021,7 @@ async def test_run_acts_as_the_skill_creator_when_one_resolves(ateam, aorganizatreturn_value="env-id",),patch(- "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ "products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team",return_value=42,),):@@ -2063,7 +2063,7 @@ async def test_run_passes_the_per_scout_server_selection_and_no_credential_ownerreturn_value="env-id",),patch(- "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ "products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team",return_value=42,),):@@ -2118,7 +2118,7 @@ async def test_run_clones_the_scouts_pinned_repositories_when_a_token_can_be_minreturn_value="env-id",),patch(- "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ "products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team",return_value=42,),patch(@@ -2198,11 +2198,11 @@ async def test_run_mints_the_scouts_granted_write_scopes_and_stamps_them_on_the_return_value="env-id",),patch(- "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ "products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team",return_value=42,),patch(- "products.signals.backend.scout_harness.runner.resolve_scout_acting_user_id",+ "products.signals.backend.scout_harness.acting_user.resolve_scout_acting_user_id",return_value=42 if acting_user_resolves else None,),):@@ -2256,7 +2256,7 @@ async def test_catalog_nudge_follows_the_projects_approved_metrics(ateam, aerrorreturn_value="env-id",),patch(- "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ "products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team",return_value=acting_user.id,),):@@ -2306,7 +2306,7 @@ async def test_mounted_mcp_server_names_reach_the_prompt(ateam, aerrors_skill, rreturn_value="env-id",),patch(- "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ "products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team",return_value=42,),):@@ -2359,7 +2359,7 @@ async def test_sandbox_env_matches_config_network_access(),patch("products.signals.backend.scout_harness.runner.get_or_create_signals_sandbox_env", env_mock),patch(- "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ "products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team",return_value=42,),):@@ -2574,7 +2574,7 @@ async def test_run_pins_sandbox_to_resolved_scout_model(return_value="env-id",),patch(- "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ "products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team",return_value=42,),patch("products.signals.backend.scout_harness.runner.posthoganalytics.capture") as capture,@@ -2637,7 +2637,7 @@ async def test_failed_run_returns_failed_outcome_and_skips_bridge_insert(ateam,return_value="env-id",),patch(- "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ "products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team",return_value=42,),):@@ -2666,7 +2666,7 @@ async def test_successful_run_captures_run_finished_event(ateam, aerrors_skill):return_value="env-id",),patch(- "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ "products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team",return_value=42,),patch("products.signals.backend.scout_harness.runner.posthoganalytics.capture") as capture,@@ -2710,7 +2710,7 @@ async def test_successful_run_captures_run_started_event(ateam, aerrors_skill):return_value="env-id",),patch(- "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ "products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team",return_value=42,),patch("products.signals.backend.scout_harness.runner.posthoganalytics.capture") as capture,@@ -2788,7 +2788,7 @@ async def test_failed_run_captures_run_finished_event(return_value="env-id",),patch(- "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ "products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team",return_value=42,),patch("products.signals.backend.scout_harness.runner.posthoganalytics.capture") as capture,@@ -2820,7 +2820,7 @@ def _stubbed_spawn_dependencies():return_value="env-id",),patch(- "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ "products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team",return_value=42,),):@@ -2922,7 +2922,7 @@ async def test_run_skipped_when_no_acting_user(ateam, aerrors_skill):# lacking GitHub is NOT this case — it resolves an org member and runs; see the resolver tests.)with (patch(- "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",+ "products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team",return_value=None,),patch("products.signals.backend.scout_harness.runner.posthoganalytics.capture") as capture,@@ -2947,7 +2947,7 @@ async def test_cancelled_run_captures_run_finished_event(ateam, aerrors_skill):raise asyncio.CancelledError("worker is shutting down")with (- patch("products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team", return_value=42),+ patch("products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team", return_value=42),patch("products.signals.backend.scout_harness.runner._spawn_and_run", side_effect=fake_spawn),patch("products.signals.backend.scout_harness.runner.posthoganalytics.capture") as capture,):@@ -3054,7 +3054,7 @@ async def test_skip_if_running_lock_keys_on_team_and_skill_not_just_team(ateam,return "ok"with (- patch("products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team", return_value=42),+ patch("products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team", return_value=42),patch("products.signals.backend.scout_harness.runner._spawn_and_run", side_effect=fake_spawn),):result = await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")@@ -3098,7 +3098,7 @@ async def test_stale_in_progress_run_is_reaped_and_unblocks_dispatch(ateam, aerrreturn "ok", str(task_run.id)with (- patch("products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team", return_value=42),+ patch("products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team", return_value=42),patch("products.signals.backend.scout_harness.runner._spawn_and_run", side_effect=fake_spawn),):result = await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")@@ -3224,7 +3224,7 @@ async def test_cancelled_run_re_raises(ateam, aerrors_skill):raise asyncio.CancelledError("worker is shutting down")with (- patch("products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team", return_value=42),+ patch("products.signals.backend.temporal.agentic.resolve_acting_user_id_for_team", return_value=42),patch("products.signals.backend.scout_harness.runner._spawn_and_run", side_effect=fake_spawn),):with pytest.raises(asyncio.CancelledError):diff --git a/products/signals/backend/test/test_scout_precheck.py b/products/signals/backend/test/test_scout_precheck.pyindex 4c024383bf32..ccdda371afcc 100644--- a/products/signals/backend/test/test_scout_precheck.py+++ b/products/signals/backend/test/test_scout_precheck.py@@ -10,7 +10,7 @@ from django.test import SimpleTestCasefrom parameterized import parameterizedfrom rest_framework import status-from posthog.models import Team+from posthog.models import OrganizationMembership, Team, Userfrom products.signals.backend.models import SignalScoutConfig, SignalScoutRunfrom products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY@@ -25,6 +25,8 @@ from products.skills.backend.models.skills import LLMSkillNOW = datetime(2026, 10, 9, 12, 0, 0, tzinfo=UTC)SKILL = "signals-scout-errors"NEW_EVENTS_QUERY = "SELECT event FROM events WHERE event = 'boom' AND timestamp > {since} AND timestamp <= {now}"+# An access-scoped system table: a query with no user is denied it.+DASHBOARDS_QUERY = "SELECT count() FROM system.dashboards"SURVEYS_SKILL = "signals-scout-surveys"ROLLOUT_PERCENT = "products.signals.backend.scout_harness.precheck.precheck_default_rollout_percent"@@ -99,6 +101,15 @@ class TestEvaluateScoutPrecheck(ClickhouseTestMixin, BaseTest):assert result.row_count == PRECHECK_MAX_ROWSassert result.rows_text is not None and len(result.rows_text.splitlines()) == PRECHECK_MAX_ROWS+ def test_reads_access_scoped_system_tables_as_the_acting_user(self) -> None:+ self._config(DASHBOARDS_QUERY)++ result, capture = self._evaluate()++ assert result is not None+ assert (result.outcome, result.reason) == ("skip", "false_value")+ assert capture.call_args.kwargs["properties"]["acting_user_id"] == self.user.pk+def test_query_error_runs_the_scout(self) -> None:self._config("SELECT nope FROM not_a_table WHERE timestamp > {since}")@@ -130,11 +141,14 @@ class TestEvaluateScoutPrecheck(ClickhouseTestMixin, BaseTest):@parameterized.expand([- ("no_query", None, SignalScoutConfig.Status.ACTIVE),- ("breaker_probe", "SELECT 1 WHERE 0", SignalScoutConfig.Status.PAUSED_BY_SYSTEM),+ ("no_query", None, SignalScoutConfig.Status.ACTIVE, True),+ ("breaker_probe", "SELECT 1 WHERE 0", SignalScoutConfig.Status.PAUSED_BY_SYSTEM, True),+ ("no_member_can_act", "SELECT 1 WHERE 0", SignalScoutConfig.Status.ACTIVE, False),])- def test_no_precheck(self, _name, query, status) -> None:+ def test_no_precheck(self, _name, query, status, has_member) -> None:+ if not has_member:+ OrganizationMembership.objects.filter(organization=self.organization).delete()config = self._config(query)SignalScoutConfig.all_teams.filter(pk=config.pk).update(status=status,@@ -264,6 +278,15 @@ class TestScoutPrecheckTestAPI(ClickhouseTestMixin, APIBaseTest):0,False,),+ (+ "reads_system_tables_as_the_requester",+ None,+ {"precheck_query": DASHBOARDS_QUERY},+ False,+ "false_value",+ 1,+ False,+ ),("query_error_runs_the_scout",None,@@ -287,9 +310,19 @@ class TestScoutPrecheckTestAPI(ClickhouseTestMixin, APIBaseTest):data = response.json()assert (data["would_run"], data["reason"], data["row_count"]) == (would_run, reason, row_count)assert (data["error"] is not None) is has_error+ assert data["acting_user"] is Nonestart.assert_not_called()assert not SignalScoutRun.all_teams.filter(team=self.team).exists()+ def test_precheck_test_names_the_acting_user_when_it_is_someone_else(self) -> None:+ other = User.objects.create_and_join(self.organization, "[email protected]", None)+ SignalScoutConfig.all_teams.filter(pk=self.config.pk).update(enabled_by=other)++ response = self.client.post(self._url("precheck_test/"), {"precheck_query": NEW_EVENTS_QUERY}, format="json")++ assert response.status_code == status.HTTP_200_OK, response.json()+ assert response.json()["acting_user"]["id"] == other.id+def test_precheck_test_without_any_query_is_rejected(self) -> None:response = self.client.post(self._url("precheck_test/"), {}, format="json")diff --git a/products/signals/frontend/generated/api.schemas.ts b/products/signals/frontend/generated/api.schemas.tsindex 525ecd1064b9..b87f2635724d 100644--- a/products/signals/frontend/generated/api.schemas.ts+++ b/products/signals/frontend/generated/api.schemas.ts@@ -4164,6 +4164,8 @@ export interface SignalScoutPrecheckTestApi {* @nullable*/error: string | null+ /** The member scheduled runs check the query as, when that is not you. The test runs with your access, so a table you can read can still fail on a scheduled run, and the run then starts as if there were no pre-check. Null when scheduled runs check it as you. */+ readonly acting_user: UserBasicApi | null}/**diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutPrecheckSection.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutPrecheckSection.tsxindex ae05935e6593..1f89f05768c6 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutPrecheckSection.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutPrecheckSection.tsx@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react'import { LemonButton, LemonCollapse, LemonDialog, LemonTag, LemonTextArea } from '@posthog/lemon-ui'import { humanFriendlyDetailedTime } from 'lib/utils/datetime'+import { fullNameOrEmail } from 'lib/utils/strings'import type {PatchedSignalScoutConfigUpdateApi as SignalScoutConfigUpdate,@@ -173,6 +174,13 @@ export function ScoutPrecheckSection({{result.error ? (<span className="text-[11.5px] text-danger">{result.error}</span>) : null}+ {result.acting_user ? (+ <span className="text-[11.5px] text-muted">+ This test used your access. Scheduled runs check the query as{' '}+ {fullNameOrEmail(result.acting_user)}, who may not be able to read the+ same tables.+ </span>+ ) : null}<span className="text-[11.5px] text-muted">{'{since}'} is {humanFriendlyDetailedTime(result.since)}.{' '}{'{interval_minutes}'} is {result.interval_minutes}.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 787e19530118..e470df6e222a 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -100623,6 +100623,8 @@ export namespace Schemas {* @nullable*/error: string | null;+ /** The member scheduled runs check the query as, when that is not you. The test runs with your access, so a table you can read can still fail on a scheduled run, and the run then starts as if there were no pre-check. Null when scheduled runs check it as you. */+ readonly acting_user: UserBasic | null;}export interface SignalScoutPrecheckTestRequest {