: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 scouts for teams without a github integration (#65785)
Andrew Maguirecf9ec4d57912
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.pyindex d066613b694c..718ccad493b9 100644--- a/products/signals/backend/scout_harness/runner.py+++ b/products/signals/backend/scout_harness/runner.py@@ -25,7 +25,7 @@ from products.signals.backend.scout_harness.team_limits import withheld_skills_ffrom products.signals.backend.temporal.agentic import (SIGNALS_REPORT_RESEARCH_ENV_NAME,get_or_create_signals_sandbox_env,- resolve_user_id_for_team,+ resolve_acting_user_id_for_team,)from products.tasks.backend.facade import api as tasks_facadefrom products.tasks.backend.facade.agents import CustomPromptSandboxContext, MultiTurnSession@@ -168,6 +168,30 @@ async def arun_signals_scout(skip_reason="prior run still in progress",)+ # Resolve the acting user up front. Scouts don't clone a repo on the cadence path, so they+ # don't need a GitHub integration — `resolve_acting_user_id_for_team` prefers the GitHub+ # creator when present but falls back to any active org member, so a team that never connected+ # GitHub still runs (these dominated the fleet failure rate when the run instead crashed ~5s+ # into `_spawn_and_run` and booked a bogus `failed`). The only remaining short-circuit is the+ # genuine "no active user to act as" 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 = await database_sync_to_async(resolve_acting_user_id_for_team, thread_sensitive=False)(team.id)+ if user_id 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},+ )+ return RunResult(+ run_id=None,+ task_run_id=None,+ status=None,+ last_message=None,+ runtime_s=0.0,+ skill_name=skill.name,+ skill_version=skill.version,+ skip_reason="no active user to act as for team",+ )+started = time.monotonic()# Pre-mint the bridge row's UUID so the prompt can reference it before the row# exists. The TaskRun is created inside `MultiTurnSession.start`; the bridge row is@@ -184,6 +208,7 @@ async def arun_signals_scout(skill=skill,repository=repository,verbose=verbose,+ user_id=user_id,)runtime_s = time.monotonic() - startedemitted_count, _ = await database_sync_to_async(_read_run_metrics, thread_sensitive=False)(@@ -208,7 +233,7 @@ async def arun_signals_scout(skill_name=skill.name,skill_version=skill.version,)- except Exception:+ except Exception as exc:runtime_s = time.monotonic() - started# A failure before the on_task_run_created hook fires means no row was persisted —# don't hand callers a run_id that resolves to nothing.@@ -246,6 +271,8 @@ async def arun_signals_scout(status=tasks_facade.TaskRunStatus.FAILED.value,runtime_s=runtime_s,emitted_count=emitted_count,+ error_type=type(exc).__name__,+ error_message=str(exc)[:300],)return RunResult(run_id=str(run_id) if row_persisted else None,@@ -299,12 +326,13 @@ async def _spawn_and_run(skill: LoadedSkill,repository: str | None,verbose: bool,+ user_id: int,) -> tuple[str, str]:"""Spawn the sandbox, create the bridge row before the first turn, run the agent.- Returns `(last_message, task_run_id)`.+ `user_id` is the acting user resolved (and validated non-None) by the caller. Returns+ `(last_message, task_run_id)`."""- user_id = await database_sync_to_async(resolve_user_id_for_team, thread_sensitive=False)(team.id)sandbox_env_id = await database_sync_to_async(get_or_create_signals_sandbox_env, thread_sensitive=False)(team.id,SIGNALS_SCOUT_SANDBOX_ENV_NAME,@@ -653,6 +681,8 @@ def _capture_run_finished(status: str,runtime_s: float,emitted_count: int | None,+ error_type: str | None = None,+ error_message: str | None = None,) -> None:"""Emit the scout-owned per-run analytics event.@@ -662,21 +692,32 @@ def _capture_run_finished(emit volume — keyed on the team so it joins both to the emit-side `signal_emitted`events and to the team-level experiment exposure. Best-effort: a capture failure mustnever fail or mask the run outcome.++ On `status='failed'`, `error_type` (the exception class) and a truncated `error_message`+ are attached so the failure rate is breakable down by cause without digging into worker+ logs — the bulk of scout failures fail in this layer before the `process-task` workflow's+ own `task_run_failed` event ever fires, so this is the only event that carries their reason."""+ properties: dict[str, Any] = {+ "skill_name": skill.name,+ "skill_version": skill.version,+ "scout_config_id": str(config.id),+ "run_id": str(run_id),+ "task_run_id": task_run_id,+ "status": status,+ "runtime_seconds": round(runtime_s, 1),+ "emitted_count": emitted_count,+ }+ # Only attach failure context on failed runs — keeps successful / cancelled events clean+ # rather than carrying explicit-null error fields on every event.+ if error_type is not None:+ properties["error_type"] = error_type+ properties["error_message"] = error_messagetry:posthoganalytics.capture(event="signals_scout_run_finished",distinct_id=str(team.uuid),- properties={- "skill_name": skill.name,- "skill_version": skill.version,- "scout_config_id": str(config.id),- "run_id": str(run_id),- "task_run_id": task_run_id,- "status": status,- "runtime_seconds": round(runtime_s, 1),- "emitted_count": emitted_count,- },+ properties=properties,groups=groups(team.organization, team),)except Exception:diff --git a/products/signals/backend/temporal/agentic/__init__.py b/products/signals/backend/temporal/agentic/__init__.pyindex 1019b2c71512..9fb4d7565ea2 100644--- a/products/signals/backend/temporal/agentic/__init__.py+++ b/products/signals/backend/temporal/agentic/__init__.py@@ -75,3 +75,34 @@ def resolve_user_id_for_team(team_id: int, github: GitHubIntegrationBase | Noneif not membership:raise RuntimeError(f"No active users in organization '{team.organization.name}' (team {team.id})")return membership.user_id+++def resolve_acting_user_id_for_team(team_id: int) -> int | None:+ """Resolve the user a Signals scout sandbox acts as, *without* requiring GitHub.++ `resolve_user_id_for_team` gates on a GitHub integration because the repo-cloning callers+ (report generation, repo selection, custom agent) need those credentials. The scout cadence+ path never clones a repo — `user_id` only scopes the sandbox connection token / MCP identity —+ so a GitHub integration is the wrong precondition there. Prefer the GitHub-integration creator+ when one exists (stable attribution, matches the other surfaces), otherwise fall back to any+ active org member.++ Returns ``None`` only when the org has no active member to act as — a genuine "can't run yet"+ that the scheduled caller short-circuits on, rather than crashing deep in the spawn path and+ booking a bogus `failed` outcome. Genuine errors (missing team, DB failures) still propagate.+ """+ team = Team.objects.select_related("organization").get(id=team_id)+ github = resolve_team_github_integration(team_id, team=team)+ if github is not None:+ try:+ return resolve_user_id_for_team(team_id, github=github)+ except RuntimeError:+ # Integration present but its user is unusable — fall through to any active member.+ pass+ membership = (+ OrganizationMembership.objects.select_related("user")+ .filter(organization=team.organization, user__is_active=True)+ .order_by("id")+ .first()+ )+ return membership.user_id if membership else Nonediff --git a/products/signals/backend/test/test_resolve_user_id.py b/products/signals/backend/test/test_resolve_user_id.pyindex 015193b4ad2c..9f93543ca76b 100644--- a/products/signals/backend/test/test_resolve_user_id.py+++ b/products/signals/backend/test/test_resolve_user_id.py@@ -5,7 +5,7 @@ from posthog.models.integration import Integrationfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.user_integration import UserIntegration-from products.signals.backend.temporal.agentic import resolve_user_id_for_team+from products.signals.backend.temporal.agentic import resolve_acting_user_id_for_team, resolve_user_id_for_team@pytest.fixture@@ -131,3 +131,33 @@ def test_raises_when_team_has_no_github_source_at_all(organization, team):with pytest.raises(RuntimeError, match="No GitHub integration"):resolve_user_id_for_team(team.id)+++def test_acting_user_falls_back_to_active_member_without_github(organization, team):+ # The scout path has no repo to clone, so it must NOT require GitHub: a team with an active+ # org member but no integration resolves that member instead of failing. This is the fix for+ # the teams that were crashing every scheduled run on the GitHub precondition.+ member = _create_user("[email protected]", organization)++ assert resolve_acting_user_id_for_team(team.id) == member.id+++def test_acting_user_returns_none_when_no_active_member(organization, team):+ # The only genuine "can't run" case — no active user to act as. Returning None (not raising)+ # is what lets the scheduled caller short-circuit to a skip instead of a bogus failed run.+ _create_user("[email protected]", organization, is_active=False)++ assert resolve_acting_user_id_for_team(team.id) is None+++def test_acting_user_prefers_github_creator_when_present(organization, team):+ # When GitHub IS connected, keep the existing attribution: act as the integration creator,+ # not an arbitrary member — so the decoupling doesn't change behavior for set-up teams.+ _create_user("[email protected]", organization)+ creator = _create_user("[email protected]", organization)+ _create_github_integration(team, created_by=creator)++ assert resolve_acting_user_id_for_team(team.id) == creator.iddiff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.pyindex bfdc847dbd84..cea2183e0c4e 100644--- a/products/signals/backend/test/test_scout_harness.py+++ b/products/signals/backend/test/test_scout_harness.py@@ -241,7 +241,7 @@ async def test_successful_run_creates_bridge_row_pointing_at_task_run(ateam, aerreturn_value="env-id",),patch(- "products.signals.backend.scout_harness.runner.resolve_user_id_for_team",+ "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",return_value=42,),):@@ -289,7 +289,7 @@ async def test_run_tags_session_with_scout_ai_stage(ateam, aerrors_skill):return_value="env-id",),patch(- "products.signals.backend.scout_harness.runner.resolve_user_id_for_team",+ "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",return_value=42,),):@@ -315,7 +315,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_user_id_for_team",+ "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",return_value=42,),):@@ -344,7 +344,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_user_id_for_team",+ "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",return_value=42,),patch("products.signals.backend.scout_harness.runner.posthoganalytics.capture") as capture,@@ -385,7 +385,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_user_id_for_team",+ "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",return_value=42,),patch("products.signals.backend.scout_harness.runner.posthoganalytics.capture") as capture,@@ -418,7 +418,7 @@ async def test_failed_run_captures_run_finished_event(ateam, aerrors_skill):return_value="env-id",),patch(- "products.signals.backend.scout_harness.runner.resolve_user_id_for_team",+ "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",return_value=42,),patch("products.signals.backend.scout_harness.runner.posthoganalytics.capture") as capture,@@ -432,6 +432,37 @@ async def test_failed_run_captures_run_finished_event(ateam, aerrors_skill):# No bridge row persisted (TaskRun never created), so no emit tally or join key.assert props["emitted_count"] == 0assert props["task_run_id"] is None+ # Failure reason rides on the event so the failure rate is breakable down by cause+ # without digging into worker logs — the bulk of scout failures fail here, before the+ # process-task workflow's own task_run_failed event fires.+ assert props["error_type"] == "RuntimeError"+ assert props["error_message"] == "sandbox refused to start"+++async def test_run_skipped_when_no_acting_user(ateam, aerrors_skill):+ # When no user can be resolved to act as (no active org member — `resolve_acting_user_id_for_team`+ # returns None), the run must skip rather than crash deep in _spawn_and_run and book a bogus+ # `failed`. That instant-crash-as-failure is what let a handful of teams dominate the fleet+ # failure rate. A skip leaves no row, no lifecycle event, just a skip_reason. (A team merely+ # 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",+ return_value=None,+ ),+ patch("products.signals.backend.scout_harness.runner.posthoganalytics.capture") as capture,+ ):+ run_result = await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")++ assert run_result.status is None+ assert run_result.run_id is None+ assert run_result.skip_reason == "no active user to act as for team"+ # Skipped runs are not runs: no started / finished / failed event is emitted.+ assert capture.call_count == 0+ has_runs = await database_sync_to_async(SignalScoutRun.objects.filter(team=ateam).exists)()+ assert not has_runs@pytest.mark.asyncio@@ -443,6 +474,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.scout_harness.runner._spawn_and_run", side_effect=fake_spawn),patch("products.signals.backend.scout_harness.runner.posthoganalytics.capture") as capture,):@@ -548,7 +580,10 @@ async def test_skip_if_running_lock_keys_on_team_and_skill_not_just_team(ateam,spawn_calls.append(kwargs)return "ok"- with patch("products.signals.backend.scout_harness.runner._spawn_and_run", side_effect=fake_spawn):+ with (+ patch("products.signals.backend.scout_harness.runner.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")# Spawn went through — the OTHER skill's RUNNING row didn't gate ours.@@ -587,7 +622,10 @@ async def test_stale_in_progress_run_is_reaped_and_unblocks_dispatch(ateam, aerrspawn_calls.append(kwargs)return "ok", str(task_run.id)- with patch("products.signals.backend.scout_harness.runner._spawn_and_run", side_effect=fake_spawn):+ with (+ patch("products.signals.backend.scout_harness.runner.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")# The orphan was reaped, so the guard didn't block — dispatch went through.@@ -689,7 +727,10 @@ async def test_cancelled_run_re_raises(ateam, aerrors_skill):async def fake_spawn(**_kwargs):raise asyncio.CancelledError("worker is shutting down")- with patch("products.signals.backend.scout_harness.runner._spawn_and_run", side_effect=fake_spawn):+ with (+ patch("products.signals.backend.scout_harness.runner.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):await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")