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(llma): order guaranteed teams first in clustering discovery (#63239)

Carlos Marchal3937307f9468
diff --git a/posthog/temporal/ai_observability/team_discovery.py b/posthog/temporal/ai_observability/team_discovery.py
index 22dc61a2e150..65f6531e0fef 100644
--- a/posthog/temporal/ai_observability/team_discovery.py
+++ b/posthog/temporal/ai_observability/team_discovery.py
@@ -164,7 +164,10 @@ async def get_team_ids_for_ai_observability(inputs: TeamDiscoveryInput) -> list[
sample_size = math.ceil(len(remaining) * sample_percentage)
sampled = random.sample(remaining, min(sample_size, len(remaining)))
- result = sorted((guaranteed | set(sampled)) - skip)
+ # Guaranteed teams first: the coordinator processes teams in this order and
+ # may exhaust its run budget before reaching the tail, so allowlisted teams
+ # must never sit behind the sampled set.
+ result = sorted(guaranteed - skip) + sorted(sampled)
logger.info(
"Team discovery completed",
diff --git a/posthog/temporal/ai_observability/test_team_discovery.py b/posthog/temporal/ai_observability/test_team_discovery.py
index ebe2a110e34d..110462f227e8 100644
--- a/posthog/temporal/ai_observability/test_team_discovery.py
+++ b/posthog/temporal/ai_observability/test_team_discovery.py
@@ -136,14 +136,17 @@ class TestGetTeamIdsForAIObservability:
assert len(result) == len(set(result))
@patch("posthog.tasks.ai_observability_usage_report.get_teams_with_ai_events")
- async def test_result_is_sorted(self, mock_get_teams, mock_ff):
- mock_ff.return_value = {"sample_percentage": 1.0}
- mock_get_teams.return_value = [9999, 5555, 3333]
+ async def test_guaranteed_teams_ordered_before_sampled(self, mock_get_teams, mock_ff):
+ # High guaranteed id placed ahead of a lower sampled id proves ordering is by
+ # guaranteed-first, not global sort — the coordinator must reach allowlisted
+ # teams before it exhausts its run budget on the sampled tail.
+ mock_ff.return_value = {"guaranteed_team_ids": [9000], "sample_percentage": 1.0}
+ mock_get_teams.return_value = [5555, 3333, 7777]
inputs = TeamDiscoveryInput()
result = await get_team_ids_for_ai_observability(inputs)
- assert result == sorted(result)
+ assert result == [9000, 3333, 5555, 7777]
@patch("posthog.tasks.ai_observability_usage_report.get_teams_with_ai_events")
async def test_zero_sample_returns_only_guaranteed(self, mock_get_teams, mock_ff):