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.

feat(scouts): per-scout model selection for dogfooding (#66113)

Joshua Snyder0a44f849e3ad
diff --git a/products/signals/backend/scout_harness/model_selection.py b/products/signals/backend/scout_harness/model_selection.py
new file mode 100644
index 000000000000..933df576ef8a
--- /dev/null
+++ b/products/signals/backend/scout_harness/model_selection.py
@@ -0,0 +1,196 @@
+"""Resolve which LLM the scout agent runs on, from the `scouts-model-selection` flag payload.
+
+Default posture: leave the agent model unset (`None`) so the sandbox agent server uses its
+built-in default. The flag lets scouts be routed onto other models — for no-deploy A/B/n trials of
+new models (open-weights GLM, a newer GPT, …) against the default on the real scout workload. The
+resolved string is passed straight through `CustomPromptSandboxContext.model` → `Task.create_and_run`
+→ the agent server, and per-run model is tagged on each `$ai_generation` so runs are comparable by
+model in LLM analytics.
+
+Everything is driven by the flag's JSON payload, keyed by team → scout → model, so a single payload
+configures any number of teams (team 2, internal side projects, …) with a different model mix each —
+no per-team release-condition fiddling and no deploy. Like the sibling `signals-scout` flag in
+`team_limits.py`, the flag is kept 100%-on and the payload (read once via a synthetic discovery
+distinct_id) is the single source of truth; a team with no entry runs entirely on the default model.
+
+ {
+ "teams": {
+ "2": {
+ "scouts": {
+ "signals-scout-team-self-driving": {"@cf/zai-org/glm-5.2": 0.2, "gpt-5.5": 0.2},
+ "signals-scout-signals-dashboards": {"@cf/zai-org/glm-5.2": 0.25}
+ }
+ },
+ "112495": {"scouts": {"*": {"@cf/zai-org/glm-5.2": 0.5}}}
+ }
+ }
+
+- `teams` — `{team_id: {"scouts": {...}}}`. A team is configured iff it has an entry (or the `"*"`
+ team wildcard applies); either the canonical project id or a child-env id key resolves.
+- `scouts` — `{skill_name: {model_id: fraction}}`. Each value maps a model id to the fraction of
+ that scout's runs (0..1) it serves. `signals-scout-team-self-driving` above runs 20% on glm-5.2,
+ 20% on gpt-5.5, and the remaining 60% on the agent-server default. `"*"` is the fallback
+ distribution for scouts not listed explicitly.
+- The reserved `"default"` key inside a scout's map names the model the *remaining* (unallocated)
+ runs use instead of the agent-server default — its value is a model-id string, not a fraction.
+
+Each run is bucketed deterministically on `run_id`, so a scout A/Bs against itself across runs and
+the per-run decision is reproducible. An absent payload / no matching team or scout / read failure
+all resolve to `None` — the agent-server default. Gating the model must never be able to fail a run.
+
+This is separate from the `signals-scout` enrollment/limits flag — that decides *whether* a team
+runs scouts; this decides *on which model*.
+"""
+
+from __future__ import annotations
+
+import json
+import hashlib
+
+import posthoganalytics
+
+from posthog.exceptions_capture import capture_exception
+from posthog.models.team.team import Team
+
+SCOUTS_MODEL_FLAG = "scouts-model-selection"
+
+# Fixed distinct_id for the payload read — config is team-keyed in the payload, not per-user. Matches
+# the `signals-scout` discovery pattern: the flag stays 100%-on so the payload is always served, and
+# `match_value=True` forces the true-variant payload under local evaluation.
+SCOUTS_MODEL_DISCOVERY_DISTINCT_ID = "internal_scouts_model_selection_discovery"
+
+# Convenience constant for the model we're trialling first; the model ids themselves live entirely
+# in the flag payload now, so this is just a well-known id for docs/tests, not special-cased in code.
+GLM_MODEL = "@cf/zai-org/glm-5.2"
+
+# Payload structure keys.
+TEAMS_KEY = "teams"
+SCOUTS_KEY = "scouts"
+
+# Wildcard token, used at both the team level (`teams["*"]`) and the scout level
+# (`scouts["*"]`): the fallback applied to any team / scout not listed explicitly.
+WILDCARD = "*"
+
+# Reserved key inside a scout's distribution naming the model for the unallocated remainder (instead
+# of the agent-server default). Its value is a model-id string, not a fraction — a model id of
+# literally "default" is not addressable, which is fine (real ids look like `@cf/...`, `gpt-5.5`).
+DEFAULT_MODEL_KEY = "default"
+
+
+def _read_payload() -> dict | None:
+ """Read + parse the `scouts-model-selection` flag's JSON payload once.
+
+ The flag must stay 100%-on so the payload is served for the synthetic discovery distinct_id;
+ `match_value=True` forces the true-variant payload under local evaluation. Returns the parsed
+ dict, or `None` when the payload is absent / not an object / unreadable. A read error never
+ breaks a run — the caller falls back to the default model.
+ """
+ try:
+ payload = posthoganalytics.get_feature_flag_payload(
+ SCOUTS_MODEL_FLAG, SCOUTS_MODEL_DISCOVERY_DISTINCT_ID, match_value=True
+ )
+ if isinstance(payload, str):
+ payload = json.loads(payload)
+ return payload if isinstance(payload, dict) else None
+ except Exception as error:
+ capture_exception(error)
+ return None
+
+
+def _team_scouts(payload: object, team_id: int, canonical_team_id: int) -> dict:
+ """The `{skill_name: {...}}` scout map configured for a team, or `{}` when none applies.
+
+ Looks up `teams[team_id]`, then `teams[canonical_team_id]` (so an operator can key by either the
+ child-env id or the parent project id), then the `"*"` team wildcard. Returns the entry's
+ `scouts` map. Defensive — a non-object payload / `teams` / team entry / `scouts` value yields
+ `{}` (the team runs on the default model).
+ """
+ if not isinstance(payload, dict):
+ return {}
+ teams = payload.get(TEAMS_KEY)
+ if not isinstance(teams, dict):
+ return {}
+
+ entry: object = None
+ for key in (str(team_id), str(canonical_team_id), WILDCARD):
+ candidate = teams.get(key)
+ if isinstance(candidate, dict):
+ entry = candidate
+ break
+ if not isinstance(entry, dict):
+ return {}
+
+ scouts = entry.get(SCOUTS_KEY)
+ return scouts if isinstance(scouts, dict) else {}
+
+
+def _scout_config(scouts: dict, skill_name: str) -> tuple[dict[str, float], str | None]:
+ """The `(distribution, default_model)` for one scout from a team's scout map.
+
+ Looks up `scouts[skill_name]`, falling back to the `"*"` scout wildcard. The reserved `"default"`
+ string key is pulled out as `default_model` (the model for the unallocated remainder; `None` =
+ agent-server default); every other entry is a `model_id -> fraction` weight. Defensive — a
+ missing/non-object scout entry, or a malformed weight (not a positive number, or a bool) is
+ dropped rather than failing the run, so a typo can't crash a scout or route it unintended.
+ """
+ raw = scouts.get(skill_name)
+ if not isinstance(raw, dict):
+ raw = scouts.get(WILDCARD)
+ if not isinstance(raw, dict):
+ return {}, None
+
+ default_value = raw.get(DEFAULT_MODEL_KEY)
+ default_model = default_value if isinstance(default_value, str) and default_value else None
+
+ distribution: dict[str, float] = {}
+ for model_id, weight in raw.items():
+ if model_id == DEFAULT_MODEL_KEY:
+ continue
+ if not isinstance(model_id, str) or not model_id:
+ continue
+ if not isinstance(weight, int | float) or isinstance(weight, bool) or weight <= 0:
+ continue
+ distribution[model_id] = min(1.0, float(weight))
+ return distribution, default_model
+
+
+def _bucket(run_id: str) -> float:
+ """A stable value in [0, 1) derived from `run_id` — the per-run draw used for selection.
+
+ A hash of the run id (not a random draw) so the model a run gets is reproducible: the same run
+ always resolves the same model, which keeps tests deterministic and lets a run's model be
+ re-derived after the fact. Over many runs the buckets are uniform, so observed model shares
+ converge on the configured fractions.
+ """
+ return int.from_bytes(hashlib.sha256(run_id.encode()).digest()[:8], "big") / 2**64
+
+
+def _select_model(run_id: str, distribution: dict[str, float], default_model: str | None) -> str | None:
+ """Pick a model for this run from the scout's distribution, deterministically on `run_id`.
+
+ Walks the models in sorted-id order accumulating their fractions; the run's bucket falls into
+ exactly one model's slice, or past them all into the remainder → `default_model`. Sorted order
+ makes the assignment stable across runs/processes. If the fractions sum to ≥ 1 the remainder is
+ empty and `default_model` simply never runs.
+ """
+ cumulative = 0.0
+ for model_id in sorted(distribution):
+ cumulative += distribution[model_id]
+ if _bucket(run_id) < cumulative:
+ return model_id
+ return default_model
+
+
+def resolve_scout_model(team: Team, skill_name: str, run_id: str) -> str | None:
+ """The agent-model override for one scout run, or `None` to keep the agent-server default.
+
+ Resolves this team's scout map from the `scouts-model-selection` payload, then this scout's
+ per-run model from its distribution. Returns `None` (agent-server default) when the team has no
+ entry, the scout has no distribution, or the run falls in the unallocated remainder with no
+ named `default`. A payload read failure is swallowed and falls back to the default model —
+ gating the model must never be able to fail a scout run.
+ """
+ payload = _read_payload()
+ scouts = _team_scouts(payload, team.id, team.parent_team_id or team.id)
+ distribution, default_model = _scout_config(scouts, skill_name)
+ return _select_model(run_id, distribution, default_model)
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index 718ccad493b9..c7581091d2b3 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -19,6 +19,7 @@ from posthog.sync import database_sync_to_async
from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
from products.signals.backend.scout_harness.lazy_seed import sync_canonical_skills
from products.signals.backend.scout_harness.limits import DEFAULT_MAX_RUNTIME_S, STALE_RUN_CUTOFF_S
+from products.signals.backend.scout_harness.model_selection import resolve_scout_model
from products.signals.backend.scout_harness.prompt import SignalScoutRunSummary, build_run_prompt
from products.signals.backend.scout_harness.skill_loader import LoadedSkill, load_skill_for_run
from products.signals.backend.scout_harness.team_limits import withheld_skills_for_team
@@ -199,6 +200,13 @@ async def arun_signals_scout(
# the agent's first turn — so first-turn finding emits can resolve the run by id.
run_id = uuid7()
started_at = timezone.now()
+
+ # Resolve the scout's agent model from the `scouts-model-selection` gate. `None` keeps the
+ # agent-server default; an override routes this run on that model. The flag payload is a
+ # per-team, per-scout model distribution, bucketed per run on `run_id` — so a scout can A/B/n
+ # across models against itself across runs. Resolved once here so the whole run is consistent.
+ # Off the event loop — the flag read does blocking network I/O.
+ model = await database_sync_to_async(resolve_scout_model, thread_sensitive=False)(team, skill.name, str(run_id))
try:
last_message, task_run_id = await _spawn_and_run(
team=team,
@@ -209,6 +217,7 @@ async def arun_signals_scout(
repository=repository,
verbose=verbose,
user_id=user_id,
+ model=model,
)
runtime_s = time.monotonic() - started
emitted_count, _ = await database_sync_to_async(_read_run_metrics, thread_sensitive=False)(
@@ -327,10 +336,12 @@ async def _spawn_and_run(
repository: str | None,
verbose: bool,
user_id: int,
+ model: str | None,
) -> tuple[str, str]:
"""Spawn the sandbox, create the bridge row before the first turn, run the agent.
- `user_id` is the acting user resolved (and validated non-None) by the caller. Returns
+ `user_id` is the acting user resolved (and validated non-None) by the caller. `model` is the
+ agent-model override (`None` keeps the agent-server default). Returns
`(last_message, task_run_id)`.
"""
sandbox_env_id = await database_sync_to_async(get_or_create_signals_sandbox_env, thread_sensitive=False)(
@@ -357,6 +368,10 @@ async def _spawn_and_run(
# `forget`, and `emit_finding` tools — even though the OAuth token does carry the
# right scope to call them.
posthog_mcp_scopes="signals_scout",
+ # `None` keeps the agent-server default; an override pins the whole run on one model
+ # (the `scouts-model-selection` gate routes it here). The model the gateway actually serves
+ # is tagged on each $ai_generation, so per-run model is queryable in LLM analytics.
+ model=model,
)
prompt = build_run_prompt(skill, run_id=str(run_id), team_id=team.id, started_at=started_at)
logger.info(
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index cea2183e0c4e..e3779cd74eb6 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -298,6 +298,47 @@ async def test_run_tags_session_with_scout_ai_stage(ateam, aerrors_skill):
assert captured["ai_stage"] == "scout"
+ "resolved_model, expected_context_model",
+ [
+ ("@cf/zai-org/glm-5.2", "@cf/zai-org/glm-5.2"),
+ (None, None),
+ ],
+)
+async def test_run_pins_sandbox_to_resolved_scout_model(ateam, aerrors_skill, resolved_model, expected_context_model):
+ # The `scouts-glm` gate resolves an agent-model override (glm-5.2) or None (agent-server
+ # default); the runner must hand that straight to the sandbox via the context's `model` field.
+ session, result = await database_sync_to_async(_make_fake_session, thread_sensitive=False)(ateam)
+ captured: dict = {}
+
+ async def _capture_start(*args, on_task_run_created=None, **kwargs):
+ captured.update(kwargs)
+ if on_task_run_created is not None:
+ await on_task_run_created(session.task_run)
+ return session, result
+
+ with (
+ patch("products.signals.backend.scout_harness.runner.MultiTurnSession.start", new=_capture_start),
+ patch(
+ "products.signals.backend.scout_harness.runner.resolve_scout_model",
+ return_value=resolved_model,
+ ),
+ patch(
+ "products.signals.backend.scout_harness.runner.get_or_create_signals_sandbox_env",
+ return_value="env-id",
+ ),
+ patch(
+ "products.signals.backend.scout_harness.runner.resolve_acting_user_id_for_team",
+ return_value=42,
+ ),
+ ):
+ await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")
+
+ assert captured["context"].model == expected_context_model
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_failed_run_returns_failed_outcome_and_skips_bridge_insert(ateam, aerrors_skill):
diff --git a/products/signals/backend/test/test_scout_model_selection.py b/products/signals/backend/test/test_scout_model_selection.py
new file mode 100644
index 000000000000..493dea01940b
--- /dev/null
+++ b/products/signals/backend/test/test_scout_model_selection.py
@@ -0,0 +1,127 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import cast
+
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.models.team.team import Team
+
+from products.signals.backend.scout_harness.model_selection import GLM_MODEL, resolve_scout_model
+
+_PAYLOAD_PATH = "products.signals.backend.scout_harness.model_selection.posthoganalytics.get_feature_flag_payload"
+
+_TEAM_ID = 2
+_SKILL = "signals-scout-team-self-driving"
+_OTHER_SKILL = "signals-scout-errors"
+_GPT = "gpt-5.5"
+_RUN_ID = "0190a000-0000-7000-8000-000000000001"
+
+
+def _fake_team(team_id: int = _TEAM_ID, parent_team_id: int | None = None) -> Team:
+ # resolve_scout_model only reads id + parent_team_id, so a lightweight stand-in avoids the DB.
+ return cast(Team, SimpleNamespace(id=team_id, parent_team_id=parent_team_id))
+
+
+def _resolve(skill: str = _SKILL, run_id: str = _RUN_ID, *, team: Team | None = None, payload: object) -> str | None:
+ with patch(_PAYLOAD_PATH, return_value=payload):
+ return resolve_scout_model(team or _fake_team(), skill, run_id)
+
+
+def _scouts(scouts: dict, team_id: int = _TEAM_ID) -> dict:
+ return {"teams": {str(team_id): {"scouts": scouts}}}
+
+
+def _share(payload: object, skill: str = _SKILL, n: int = 400) -> dict[str | None, int]:
+ # Empirical model split across many run ids — buckets are uniform, so shares track the config.
+ counts: dict[str | None, int] = {}
+ for i in range(n):
+ model = _resolve(skill=skill, run_id=f"run-{i}", payload=payload)
+ counts[model] = counts.get(model, 0) + 1
+ return counts
+
+
+class TestResolveScoutModel:
+ @parameterized.expand(
+ [
+ ("no_payload", None),
+ ("no_teams_key", {}),
+ ("team_not_listed", {"teams": {"999": {"scouts": {_SKILL: {GLM_MODEL: 1}}}}}),
+ ("scout_not_listed", _scouts({_OTHER_SKILL: {GLM_MODEL: 1}})),
+ ("empty_distribution", _scouts({_SKILL: {}})),
+ ]
+ )
+ def test_keeps_agent_default_when_unconfigured(self, _name: str, payload: object) -> None:
+ assert _resolve(payload=payload) is None
+
+ def test_full_weight_routes_every_run(self) -> None:
+ assert _resolve(payload=_scouts({_SKILL: {GLM_MODEL: 1}})) == GLM_MODEL
+
+ def test_locks_flag_key(self) -> None:
+ with patch(_PAYLOAD_PATH, return_value=None) as mock_payload:
+ resolve_scout_model(_fake_team(), _SKILL, _RUN_ID)
+ assert mock_payload.call_args.args[0] == "scouts-model-selection"
+
+ def test_each_team_gets_its_own_config(self) -> None:
+ # One payload, two teams, different model per team — the whole point of the team key.
+ payload = {
+ "teams": {
+ "2": {"scouts": {_SKILL: {GLM_MODEL: 1}}},
+ "112495": {"scouts": {_SKILL: {_GPT: 1}}},
+ }
+ }
+ assert _resolve(team=_fake_team(2), payload=payload) == GLM_MODEL
+ assert _resolve(team=_fake_team(112495), payload=payload) == _GPT
+
+ def test_child_env_resolves_via_parent_project_key(self) -> None:
+ # A child env keyed by its parent project id still resolves.
+ payload = _scouts({_SKILL: {GLM_MODEL: 1}}, team_id=2)
+ child = _fake_team(team_id=555, parent_team_id=2)
+ assert _resolve(team=child, payload=payload) == GLM_MODEL
+
+ def test_team_wildcard_applies_to_unlisted_team(self) -> None:
+ payload = {"teams": {"*": {"scouts": {_SKILL: {GLM_MODEL: 1}}}}}
+ assert _resolve(team=_fake_team(999), payload=payload) == GLM_MODEL
+
+ def test_scout_wildcard_applies_to_unlisted_scout(self) -> None:
+ assert _resolve(skill=_OTHER_SKILL, payload=_scouts({"*": {GLM_MODEL: 1}})) == GLM_MODEL
+
+ def test_named_default_takes_the_remainder(self) -> None:
+ # 20% gpt, the remaining 80% pinned to a named default model (not the agent-server default).
+ shares = _share(_scouts({_SKILL: {_GPT: 0.2, "default": GLM_MODEL}}))
+ assert set(shares) == {_GPT, GLM_MODEL}
+ assert None not in shares
+
+ def test_multi_model_split_is_proportional(self) -> None:
+ # 30% glm, 30% gpt, 40% agent-server default — all three buckets are non-trivially populated.
+ shares = _share(_scouts({_SKILL: {GLM_MODEL: 0.3, _GPT: 0.3}}))
+ assert shares.get(GLM_MODEL, 0) > 0
+ assert shares.get(_GPT, 0) > 0
+ assert shares.get(None, 0) > 0
+ # The remainder (default) is the largest slice here (0.4 vs 0.3 each).
+ assert shares[None] == max(shares.values())
+
+ def test_selection_is_deterministic_per_run(self) -> None:
+ # Full 50/50 split (no remainder) so every run resolves to a real model, then assert the
+ # same run_id resolves the same model twice — the determinism guarantee, not None == None.
+ payload = _scouts({_SKILL: {GLM_MODEL: 0.5, _GPT: 0.5}})
+ first = _resolve(payload=payload)
+ assert first in {GLM_MODEL, _GPT}
+ assert first == _resolve(payload=payload)
+
+ @parameterized.expand(
+ [
+ ("malformed_weight_dropped", {GLM_MODEL: "lots"}),
+ ("zero_weight_dropped", {GLM_MODEL: 0}),
+ ("bool_weight_dropped", {GLM_MODEL: True}),
+ ]
+ )
+ def test_malformed_weights_keep_agent_default(self, _name: str, dist: dict) -> None:
+ assert _resolve(payload=_scouts({_SKILL: dist})) is None
+
+ def test_payload_read_failure_keeps_agent_default(self) -> None:
+ # A scout must never fail to run because the gate was unreachable — fall back to the default.
+ with patch(_PAYLOAD_PATH, side_effect=RuntimeError("flag service down")):
+ assert resolve_scout_model(_fake_team(), _SKILL, _RUN_ID) is None