: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(mcp-analytics): stratified session sampling so low/mid-volume tools aren't erased from intent clusters (#87138)
Daniel Visca45c39515b39c
diff --git a/posthog/temporal/mcp_analytics/intent_clustering/activities.py b/posthog/temporal/mcp_analytics/intent_clustering/activities.pyindex ed78cb141a15..7670453acd1b 100644--- a/posthog/temporal/mcp_analytics/intent_clustering/activities.py+++ b/posthog/temporal/mcp_analytics/intent_clustering/activities.py@@ -109,12 +109,49 @@ async def compute_intent_clusters_activity(inputs: IntentClusteringWorkflowInputsnapshot = await _mark_computing(team, user)try:- session_ids = await database_sync_to_async(intent_clustering.sample_corpus_sessions)(- team, lookback_days=inputs.lookback_days+ # Stratified sampling: bucket intent-bearing sessions per tool+ # so every tool keeps a floor, instead of a uniform sample that+ # erases low/mid-volume tools (logs/tracing/metrics). The+ # uniform sample still fills the rest of the corpus budget, and+ # carries it alone when the per-tool buckets can't be fetched,+ # so a capture or schema gap never blocks a run.+ try:+ tools_by_session = await database_sync_to_async(intent_clustering.fetch_tools_by_session)(+ team,+ lookback_days=inputs.lookback_days,+ max_sessions_per_tool=intent_clustering.MIN_SESSIONS_PER_TOOL,+ )+ except Exception:+ logger.warning(+ "mcpa.intent_clustering.tool_buckets_unavailable_falling_back_to_uniform",+ team_id=inputs.team_id,+ )+ tools_by_session = {}++ uniform_sample = await database_sync_to_async(intent_clustering.sample_corpus_sessions)(+ team, lookback_days=inputs.lookback_days, max_sessions=intent_clustering.MAX_CORPUS_SESSIONS+ )+ session_ids = intent_clustering.select_corpus_sessions(+ tools_by_session,+ uniform_sample,+ min_sessions_per_tool=intent_clustering.MIN_SESSIONS_PER_TOOL,+ max_total_sessions=intent_clustering.MAX_CORPUS_SESSIONS,)+call_rows = await database_sync_to_async(intent_clustering.fetch_session_calls)(team, session_ids, lookback_days=inputs.lookback_days)+ # Cap dominant tools so they can't occupy the whole intent corpus.+ cap_result = intent_clustering.cap_per_tool_call_volume(+ call_rows, max_calls_per_tool=intent_clustering.MAX_CALLS_PER_TOOL+ )+ call_rows = cap_result.kept_rows+ if cap_result.per_tool_report:+ logger.info(+ "mcpa.intent_clustering.capped_overrepresented_tools",+ team_id=inputs.team_id,+ per_tool=cap_result.per_tool_report,+ )records, calls_by_session, corpus_stats = intent_clustering.build_call_corpus(call_rows, top_n=inputs.top_n)diff --git a/posthog/temporal/mcp_analytics/intent_clustering/constants.py b/posthog/temporal/mcp_analytics/intent_clustering/constants.pyindex 0c6830761102..9abcde1cffbd 100644--- a/posthog/temporal/mcp_analytics/intent_clustering/constants.py+++ b/posthog/temporal/mcp_analytics/intent_clustering/constants.py@@ -21,7 +21,10 @@ CHILD_WORKFLOW_ID_PREFIX = "mcpa-intent-clustering-team"# Sampling ------------------------------------------------------------------DEFAULT_LOOKBACK_DAYS = 7-DEFAULT_TOP_N_INTENTS = 500+# Matches the pipeline default in products/mcp_analytics/backend/intent_clustering.py.+# Raised to 1000 with stratified sampling: per-tool floors + the per-tool call cap+# keep the extra intents spread across tools instead of long-tail exec/scout noise.+DEFAULT_TOP_N_INTENTS = 1000MIN_INTENTS_FOR_CLUSTERING = 2# Workflow + activity envelopes --------------------------------------------diff --git a/posthog/temporal/mcp_analytics/intent_clustering/tests/test_coordinator.py b/posthog/temporal/mcp_analytics/intent_clustering/tests/test_coordinator.pyindex fdabbc6fb945..152bf69979e2 100644--- a/posthog/temporal/mcp_analytics/intent_clustering/tests/test_coordinator.py+++ b/posthog/temporal/mcp_analytics/intent_clustering/tests/test_coordinator.py@@ -126,7 +126,7 @@ class TestCoordinatorParseInputs:@pytest.mark.parametrize("args, expected_lookback, expected_top_n, expected_max_concurrent",[- ([], 7, 500, 4),+ ([], 7, 1000, 4),(["14", "200", "2"], 14, 200, 2),],)diff --git a/posthog/temporal/mcp_analytics/intent_clustering/tests/test_workflow.py b/posthog/temporal/mcp_analytics/intent_clustering/tests/test_workflow.pyindex e23465e0faf0..90971ec53e79 100644--- a/posthog/temporal/mcp_analytics/intent_clustering/tests/test_workflow.py+++ b/posthog/temporal/mcp_analytics/intent_clustering/tests/test_workflow.py@@ -87,11 +87,11 @@ class TestParseInputs:"raw_payload, expected_team_id, expected_lookback_days, expected_top_n, expected_user_id",[# Empty input falls back to dataclass defaults.- ([], 0, 7, 500, None),+ ([], 0, 7, 1000, None),# Full JSON payload overrides every field.(['{"team_id": 99, "lookback_days": 3, "top_n": 50, "user_id": 5}'], 99, 3, 50, 5),# Partial payload preserves dataclass defaults for omitted fields.- (['{"team_id": 99}'], 99, 7, 500, None),+ (['{"team_id": 99}'], 99, 7, 1000, None),],)def test_parse_inputs_cases(diff --git a/products/mcp_analytics/backend/intent_clustering.py b/products/mcp_analytics/backend/intent_clustering.pyindex 1caba22daee2..db8fd971ee96 100644--- a/products/mcp_analytics/backend/intent_clustering.py+++ b/products/mcp_analytics/backend/intent_clustering.py@@ -30,7 +30,7 @@ import mathimport asyncioimport hashlibfrom collections import Counter, defaultdict-from collections.abc import Collection+from collections.abc import Collection, Sequencefrom dataclasses import dataclass, fieldfrom typing import Any@@ -44,6 +44,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.api.embedding_worker import EmbeddingResponse, async_generate_embeddingfrom posthog.clickhouse.query_tagging import Feature, Product, tags_context+from posthog.dataclasses import frozenfrom posthog.models.team.team import Teamfrom posthog.sync import database_sync_to_async@@ -148,10 +149,31 @@ class WindowStats:# Intent corpus ------------------------------------------------------------# Bound on sessions sampled from ClickHouse for the corpus. Keeps the IN-tuple-# in the per-session queries below at a sane size; a larger sample mostly adds-# long-tail singleton intents past DEFAULT_TOP_N_INTENTS anyway.-MAX_CORPUS_SESSIONS = 2000+# Total corpus budget. Raised alongside stratified sampling: the per-tool floors+# below have to fit inside it before any of the budget goes to the dominant+# tools, and the per-tool call cap (below) stops the extra sessions from+# belonging only to those tools. The IN-tuple stays sane because per-session+# queries chunk the ids.+MAX_CORPUS_SESSIONS = 6000++# Each tool keeps at least this many sessions in the corpus, so a low/mid-volume+# tool (logs/tracing/metrics) survives sampling instead of being erased by the+# dominant exec/scout traffic. ~400 is the statistical floor for reading a+# discovery/capture rate to ±5%. Doubles as the per-tool candidate pool size in+# ``fetch_tools_by_session``: a pool bigger than the floor buys nothing, since+# the rest of the corpus budget comes from the uniform sample.+MIN_SESSIONS_PER_TOOL = 400++# No tool may contribute more than this many attributed calls to the corpus.+# Stops one dominant tool from occupying the entire intent space; the freed+# budget is what lets mid/low tools cluster into real themes rather than noise.+MAX_CALLS_PER_TOOL = 1500++# Sender-controlled tool names only ever expand the ``_SESSION_TOOLS_SQL``+# buckets. One session honestly uses a handful of distinct tools, so bound how+# many distinct tools a single session can contribute — an attacker emitting+# thousands of unique names can't fan the buckets out from one session.+MAX_DISTINCT_TOOLS_PER_SESSION_BUCKET = 500# execute_hogql_query injects LIMIT 100 into any query without an explicit# LIMIT — far below what the per-session queries return at production scale@@ -415,6 +437,218 @@ def fetch_window_stats(team: Team, lookback_days: int = DEFAULT_LOOKBACK_DAYS) -)+# Intent-bearing sessions bucketed by effective tool, capped *per tool*.+#+# A single cap on candidate sessions cannot work here: the hash-ordered cut runs+# before any bucketing, so at high total volume a low/mid-volume tool's handful+# of sessions falls outside it and the per-tool floor has nothing left to keep —+# the erasure this pipeline exists to prevent. ``LIMIT n BY tool`` gives each+# tool its own pool, so whether a tool reaches the corpus stops depending on the+# team's total session count.+#+# Both dimensions are sender-controlled, so each is bounded: ``groupUniqArray``+# de-duplicates a session's tool names in aggregate state and ``arraySlice``+# caps how many of them leave it, while the per-tool cap and the absolute row+# cap bound the rows. Grouping by session alone (rather than session x tool)+# keeps the aggregation one dimension wide, and lets a session qualify on any of+# its calls carrying an intent — the population ``sample_corpus_sessions`` draws+# from.+#+# ``cityHash64`` here and in ``sample_corpus_sessions`` is a fast pseudo-random+# ordering, not a security boundary — the memory/CPU protection comes from the+# numeric caps, not the hash. ``arraySort`` keeps the per-session tool slice+# stable across reruns so repeat runs re-hit the embedding cache.+_SESSION_TOOLS_SQL = """+SELECT session_id, arrayJoin(tools) AS tool+FROM (+ SELECT+ $session_id AS session_id,+ arraySlice(arraySort(groupUniqArray(left({tool_expr}, {max_tool_len}))), 1, {max_distinct_tools}) AS tools,+ countIf(coalesce(toString(properties.$mcp_intent), '') != '') AS intent_calls+ FROM events+ WHERE event = {event}+ AND timestamp >= now() - INTERVAL {lookback_days} DAY+ AND $session_id != ''+ AND notEmpty({tool_expr_where})+ GROUP BY session_id+ HAVING intent_calls > 0+)+ORDER BY cityHash64(session_id)+LIMIT {max_sessions_per_tool} BY tool+LIMIT {max_rows}+"""+++def fetch_tools_by_session(+ team: Team,+ lookback_days: int = DEFAULT_LOOKBACK_DAYS,+ max_sessions_per_tool: int = MIN_SESSIONS_PER_TOOL,+) -> dict[str, set[str]]:+ """Return ``{tool: {intent-bearing session_ids}}``, capped per tool.++ Each tool gets its own deterministic cityHash pool, so a tool's presence in+ the corpus is independent of the team's total session count. The pool only+ has to cover the tool's floor — ``select_corpus_sessions`` spends whatever+ budget is left on the uniform sample.+ """+ query = parse_select(+ _SESSION_TOOLS_SQL,+ placeholders={+ "event": ast.Constant(value=MCP_TOOL_CALL_EVENT),+ "tool_expr": parse_expr(EFFECTIVE_TOOL_SQL),+ "tool_expr_where": parse_expr(EFFECTIVE_TOOL_SQL),+ "lookback_days": ast.Constant(value=lookback_days),+ "max_tool_len": ast.Constant(value=MAX_TOOL_NAME_LENGTH),+ "max_sessions_per_tool": ast.Constant(value=max_sessions_per_tool),+ "max_distinct_tools": ast.Constant(value=MAX_DISTINCT_TOOLS_PER_SESSION_BUCKET),+ "max_rows": ast.Constant(value=MAX_QUERY_ROWS),+ },+ )+ rows = _run_corpus_query(team, query)+ if len(rows) >= MAX_QUERY_ROWS:+ # The row cap hit before every tool's pool came back, so some tool's+ # bucket is short of its floor. Say so rather than let the missing tool+ # read as a traffic change.+ logger.warning(+ "mcpa.intent_clustering.tool_buckets_truncated",+ team_id=team.id,+ max_rows=MAX_QUERY_ROWS,+ max_sessions_per_tool=max_sessions_per_tool,+ )+ out: dict[str, set[str]] = defaultdict(set)+ for row in rows:+ session_id, tool = str(row[0] or ""), str(row[1] or "")+ if session_id and tool:+ out[tool].add(session_id)+ return dict(out)+++def stratify_session_ids(+ tool_sessions: dict[str, set[str]],+ min_sessions_per_tool: int,+ max_total_sessions: int,+) -> set[str]:+ """Choose corpus sessions so no tool is erased by the dominant tools.++ The prior uniform sample drew sessions proportionally to traffic, so in a+ window where ``exec``/scout dominate, a low/mid-volume tool's handful of+ sessions is statistically dropped and the tool becomes invisible to+ clustering. This guarantees each tool keeps up to ``min_sessions_per_tool``+ sessions (its full set when smaller), then fills any remaining budget with+ the highest-volume tools, capped at ``max_total_sessions``.++ Deterministic: per-tool session ids take the sorted-prefix, so reruns+ re-hit the same ids and the embedding cache.++ Every tool is visited: the budget is apportioned across tools rather than+ consumed by the first ones, so a later (or alphabetically later equal-volume)+ tool is never skipped, and the result is always within ``max_total_sessions``+ regardless of how the floors interact with the budget.+ """+ tools = sorted(tool_sessions)+ if not tools or max_total_sessions <= 0:+ return set()++ # The budget cannot always give every tool its full floor (many tools x+ # floor swamps max_total_sessions), so the effective per-tool floor is+ # min(the request, an even share of the budget). Even-share is the only+ # allocation that never starves a tool while always fitting the budget.+ budget_floor = max(1, max_total_sessions // len(tools))+ floor_size = max(1, min(min_sessions_per_tool, budget_floor))++ selected: set[str] = set()+ # Ascending volume secures scarce tools' floors before dominant tools add+ # their own (shared ids are de-duped through ``selected``).+ for tool in sorted(tools, key=lambda t: (len(tool_sessions[t]), t)):+ selected.update(sorted(tool_sessions[tool])[:floor_size])++ # Spend the remainder on the highest-volume tools, which hold the bulk of+ # the window's calls, keeping the whole result within budget.+ room = max_total_sessions - len(selected)+ if room > 0:+ for tool in sorted(tools, key=lambda t: (-len(tool_sessions[t]), t)):+ if room <= 0:+ break+ for sid in sorted(tool_sessions[tool]):+ if room <= 0:+ break+ if sid not in selected:+ selected.add(sid)+ room -= 1+ return selected+++def select_corpus_sessions(+ tool_sessions: dict[str, set[str]],+ uniform_sample: Sequence[str],+ min_sessions_per_tool: int,+ max_total_sessions: int,+) -> list[str]:+ """The corpus session ids: per-tool floors first, uniform sample for the rest.++ The floors are what keep a low/mid-volume tool in the corpus at any traffic+ volume, but they only cover each tool's floor, so on their own they would+ shrink the corpus for a team with a handful of tools. Spending the remaining+ budget on the uniform hash sample keeps the corpus full size and keeps the+ bulk of the window's traffic represented — the per-tool call cap is what+ stops that bulk from crowding the intent space later.++ ``uniform_sample`` is also the whole corpus when the per-tool buckets are+ unavailable, so a capture or schema gap degrades to the prior behavior+ rather than emptying the corpus.+ """+ if max_total_sessions <= 0:+ return []+ selected = stratify_session_ids(tool_sessions, min_sessions_per_tool, max_total_sessions)+ for session_id in uniform_sample:+ if len(selected) >= max_total_sessions:+ break+ selected.add(session_id)+ return sorted(selected)+++@frozen+class ToolCallCapResult:+ """Outcome of ``cap_per_tool_call_volume``: the kept rows plus, for each+ over-capped tool, how many of its calls were kept vs dropped."""++ kept_rows: list[tuple[str, str, str, bool]]+ per_tool_report: dict[str, dict[str, int]]+++def cap_per_tool_call_volume(+ rows: list[tuple[str, str, str, bool]],+ max_calls_per_tool: int,+) -> ToolCallCapResult:+ """Down-sample an over-represented tool's raw call rows before attribution.++ Row-level (pre-attribution) so intents and LOCF see the capped population.+ Deterministic: keeps an even stride across the tool's rows so the surviving+ calls still span the tool's whole session/intent range rather than a prefix.+ Each over-capped tool reports how many calls were ``kept`` vs ``dropped``.+ """+ tool_row_indexes: dict[str, list[int]] = defaultdict(list)+ for idx, (_, tool, _, _) in enumerate(rows):+ tool_row_indexes[tool].append(idx)++ keep_indexes: set[int] = set()+ report: dict[str, dict[str, int]] = {}+ for tool, indexes in tool_row_indexes.items():+ total = len(indexes)+ if total <= max_calls_per_tool:+ keep_indexes.update(indexes)+ continue+ # Even stride keeps breadth across the tool's calls.+ stride = total / max_calls_per_tool+ kept_positions = {int(i * stride) for i in range(max_calls_per_tool)}+ kept = {indexes[pos] for pos in kept_positions}+ keep_indexes.update(kept)+ report[tool] = {"kept": len(kept), "dropped": total - len(kept)}++ kept_rows = [row for idx, row in enumerate(rows) if idx in keep_indexes]+ return ToolCallCapResult(kept_rows=kept_rows, per_tool_report=report)++def fetch_tool_descriptions(team: Team, tools: Collection[str], lookback_days: int = DEFAULT_LOOKBACK_DAYS) -> dict[str, str]:@@ -1170,6 +1404,16 @@ def build_snapshot("dropped_tools": dropped_tools,"dropped_overlap_pairs": dropped_pairs,"description_coverage_pct": _pct(described_tools, len(tools)) if tools else None,+ # Representation honesty: these per-tool numbers come from a *balanced+ # sample*, never the population. Downstream surfaces must warn before+ # treating a tool's capture/discovery rate as its true traffic share.+ "sampled": True,+ "corpus_strategy": "stratified_by_tool",+ "sampling_warning": (+ "Intent clusters are computed from a stratified sample of sessions "+ "(per-tool floors, dominant tools capped). Per-tool capture and "+ "discovery rates are sample statistics, not population totals."+ ),}return {@@ -1222,5 +1466,12 @@ def empty_snapshot("dropped_tools": 0,"dropped_overlap_pairs": 0,"description_coverage_pct": None,+ "sampled": True,+ "corpus_strategy": "stratified_by_tool",+ "sampling_warning": (+ "Intent clusters are computed from a stratified sample of sessions "+ "(per-tool floors, dominant tools capped). Per-tool capture and "+ "discovery rates are sample statistics, not population totals."+ ),},}diff --git a/products/mcp_analytics/backend/tests/test_intent_clustering.py b/products/mcp_analytics/backend/tests/test_intent_clustering.pyindex 9c61e9899001..bc96f58a4ac7 100644--- a/products/mcp_analytics/backend/tests/test_intent_clustering.py+++ b/products/mcp_analytics/backend/tests/test_intent_clustering.py@@ -75,6 +75,10 @@ def _unit(vec: list[float]) -> np.ndarray:return arr / np.linalg.norm(arr)+def _snapshot_record(intent: str, tool: str, count: int) -> IntentRecord:+ return IntentRecord(intent_text=intent, frequency=count, tool_counts={tool: count})++# cluster_embeddings ------------------------------------------------------@@ -258,6 +262,20 @@ class TestBuildSnapshot:assert snapshot["clusters"][0]["label"] == "center"+ def test_meta_marks_snapshot_as_sampled_not_population(self) -> None:+ # The page presents per-tool numbers as if they were the population; the+ # snapshot must carry the sampling/balance metadata so the UI can warn.+ records = [_snapshot_record("i1", "exec", 3), _snapshot_record("i2", "query-apm-spans", 1)]+ labels = np.array([0, 1], dtype=np.int64)+ embeddings = np.array([_unit([1.0, 0.0]), _unit([0.0, 1.0])], dtype=np.float32)++ snapshot = build_snapshot(records, labels, embeddings, calls_by_session={})++ meta = snapshot["computed_with"]+ assert meta["sampled"] is True+ assert "corpus_strategy" in meta+ assert "sampling_warning" in meta+def test_misaligned_inputs_raise(self) -> None:records = [IntentRecord(intent_text="a", frequency=1, tool_counts={"tool_a": 1})]with pytest.raises(AssertionError):@@ -480,6 +498,171 @@ class TestBuildCallCorpus:assert stats.kept_calls == 5+# stratified corpus ---------------------------------------------------------+++class TestStratifySessionIds:+ """The uniform 0.5% session sample is what erases low/mid-volume tools (the+ APM logs/tracing/metrics complaint). Stratifying the *session ids* before+ the corpus SQL guarantees every tool keeps a floor of sessions, so no tool+ is silently dropped from clustering just because exec/scout dominate."""++ def test_every_tool_keeps_a_floor_of_sessions(self) -> None:+ from products.mcp_analytics.backend.intent_clustering import stratify_session_ids++ tool_sessions: dict[str, set[str]] = {+ "exec": {f"exec-s{i}" for i in range(2000)},+ "query-apm-spans": {f"apm-s{i}" for i in range(30)},+ }+ union = set().union(*tool_sessions.values())++ selected = stratify_session_ids(tool_sessions, min_sessions_per_tool=400, max_total_sessions=2000)++ # The 30-session APM tool must survive even though a uniform sample of+ # ~2000/2030 will statistically drop most of them.+ assert {sid for sid in selected if sid.startswith("apm-s")} == set(tool_sessions["query-apm-spans"])+ assert selected.issubset(union)++ def test_total_respects_max_total_sessions(self) -> None:+ from products.mcp_analytics.backend.intent_clustering import stratify_session_ids++ tool_sessions = {f"tool_{t}": {f"tool_{t}-s{i}" for i in range(600)} for t in range(10)}++ selected = stratify_session_ids(tool_sessions, min_sessions_per_tool=400, max_total_sessions=2000)++ assert len(selected) <= 2000++ def test_selection_is_deterministic(self) -> None:+ from products.mcp_analytics.backend.intent_clustering import stratify_session_ids++ tool_sessions = {f"tool_{t}": {f"tool_{t}-s{i}" for i in range(50)} for t in range(5)}++ first = stratify_session_ids(tool_sessions, min_sessions_per_tool=20, max_total_sessions=80)+ second = stratify_session_ids(tool_sessions, min_sessions_per_tool=20, max_total_sessions=80)++ assert first == second++ def test_scarce_tool_is_kept_entirely(self) -> None:+ from products.mcp_analytics.backend.intent_clustering import stratify_session_ids++ tool_sessions = {"query-metrics": {f"m-s{i}" for i in range(4)}, "exec": {f"e-s{i}" for i in range(3000)}}++ selected = stratify_session_ids(tool_sessions, min_sessions_per_tool=400, max_total_sessions=2000)++ assert {sid for sid in selected if sid.startswith("m-s")} == tool_sessions["query-metrics"]++ def test_budget_apportions_floors_and_stays_within_total(self) -> None:+ # Regression for the over-budget trimming bug: 3 x 250 = 750 must come+ # back under a 700 budget, and no tool may be skipped.+ from products.mcp_analytics.backend.intent_clustering import stratify_session_ids++ tool_sessions = {f"tool_{t}": {f"tool_{t}-s{i}" for i in range(300)} for t in range(3)}++ selected = stratify_session_ids(tool_sessions, min_sessions_per_tool=250, max_total_sessions=700)++ assert len(selected) <= 700+ for t in range(3):+ assert any(sid.startswith(f"tool_{t}-s") for sid in selected), f"tool_{t} was skipped"++ def test_late_tool_is_not_skipped_when_floors_fill_the_budget(self) -> None:+ # Regression for the break that skipped every tool once earlier floors+ # hit the budget: a late, higher-volume tool must still get a floor.+ from products.mcp_analytics.backend.intent_clustering import stratify_session_ids++ tool_sessions: dict[str, set[str]] = {+ "alpha": {f"a-s{i}" for i in range(500)},+ "beta": {f"b-s{i}" for i in range(500)},+ "zeta": {f"z-s{i}" for i in range(1000)},+ }++ selected = stratify_session_ids(tool_sessions, min_sessions_per_tool=400, max_total_sessions=900)++ assert any(sid.startswith("z-s") for sid in selected)+ assert len(selected) <= 900++ def test_never_exceeds_budget_when_many_tools_share_many_sessions(self) -> None:+ # 10 tools each with 400 shared sessions: sum of floors (4000) far+ # exceeds the budget even after de-dup (shared ids), so any overshoot+ # must be trimmed.+ from products.mcp_analytics.backend.intent_clustering import stratify_session_ids++ shared = {f"s{i}" for i in range(400)}+ tool_sessions = {f"tool_{t}": set(shared) for t in range(10)}++ selected = stratify_session_ids(tool_sessions, min_sessions_per_tool=400, max_total_sessions=1500)++ assert len(selected) <= 1500+++class TestSelectCorpusSessions:+ """The per-tool buckets only carry each tool's floor, so the rest of the+ corpus budget is filled from the uniform hash sample. The top-up must never+ displace a floor session — that would undo the stratification — and must+ still produce a full-size corpus for a team with only a couple of tools."""++ def test_floors_survive_a_uniform_sample_larger_than_the_budget(self) -> None:+ from products.mcp_analytics.backend.intent_clustering import select_corpus_sessions++ tool_sessions = {"query-metrics": {"m-s0", "m-s1"}}+ uniform = [f"exec-s{i}" for i in range(50)]++ selected = select_corpus_sessions(tool_sessions, uniform, min_sessions_per_tool=400, max_total_sessions=10)++ assert {"m-s0", "m-s1"}.issubset(selected)+ assert len(selected) == 10++ def test_uniform_sample_is_the_whole_corpus_when_buckets_are_unavailable(self) -> None:+ from products.mcp_analytics.backend.intent_clustering import select_corpus_sessions++ uniform = [f"exec-s{i}" for i in range(30)]++ selected = select_corpus_sessions({}, uniform, min_sessions_per_tool=400, max_total_sessions=10)++ assert len(selected) == 10+ assert set(selected).issubset(uniform)++ def test_budget_already_filled_by_floors_admits_no_top_up(self) -> None:+ from products.mcp_analytics.backend.intent_clustering import select_corpus_sessions++ tool_sessions = {f"tool_{t}": {f"tool_{t}-s{i}" for i in range(3)} for t in range(4)}++ selected = select_corpus_sessions(tool_sessions, ["uniform-s0"], min_sessions_per_tool=3, max_total_sessions=12)++ assert "uniform-s0" not in selected+ assert len(selected) == 12+++class TestCapPerToolCallVolume:+ """After sampling, a single high-volume tool (exec) must not be allowed to+ occupy the whole intent corpus; cap its attributed calls so mid/low tools+ retain enough signal to cluster."""++ def test_caps_overrepresented_tool_and_reports_it(self) -> None:+ from products.mcp_analytics.backend.intent_clustering import cap_per_tool_call_volume++ rows = [("s1", "exec", "operate", False)] * 100 + [("s2", "query-logs", "tail logs", False)] * 2++ result = cap_per_tool_call_volume(rows, max_calls_per_tool=10)++ per_tool_count: dict[str, int] = {}+ for _, tool, _, _ in result.kept_rows:+ per_tool_count[tool] = per_tool_count.get(tool, 0) + 1+ assert per_tool_count["exec"] <= 10+ # low-volume tool is untouched+ assert per_tool_count["query-logs"] == 2+ assert result.per_tool_report["exec"]["dropped"] >= 90++ def test_deterministic_about_which_calls_survive(self) -> None:+ from products.mcp_analytics.backend.intent_clustering import cap_per_tool_call_volume++ rows = [("s1", "exec", f"op {i}", False) for i in range(50)]++ first = cap_per_tool_call_volume(rows, max_calls_per_tool=10)+ second = cap_per_tool_call_volume(rows, max_calls_per_tool=10)++ assert first == second++# compute_cluster_flows ----------------------------------------------------@@ -999,6 +1182,39 @@ class TestCorpusQueries(_MCPAnalyticsTeamScopedTestMixin, ClickhouseTestMixin, Bassert len(advertised["session-chatty"]) <= MAX_ADVERTISED_LIST_EVENTS_PER_SESSIONassert len(advertised["session-union"]) == MAX_ADVERTISED_TOOLS_PER_SESSION+ def test_tools_by_session_buckets_intent_bearing_sessions_by_effective_tool(self) -> None:+ # session-a carries an intent; session-quiet does not, so its tools must+ # not buckify it. The exec wrapper resolves to the inner effective tool.+ self._seed_tool_call("session-a", "query-logs", intent="tail error logs")+ self._seed_tool_call("session-a", "exec", intent="tail error logs", exec_tool_name="query-apm-spans")+ self._seed_tool_call("session-quiet", "query-metrics")+ flush_persons_and_events()++ buckets = intent_clustering.fetch_tools_by_session(self.team)++ assert buckets.get("query-logs") == {"session-a"}+ # the exec-wrapped call buckets under its inner tool+ assert buckets.get("query-apm-spans") == {"session-a"}+ assert "session-quiet" not in buckets.get("query-metrics", set())++ def test_tool_buckets_are_capped_per_tool_not_globally(self) -> None:+ # A global cap on candidate sessions re-erases the low-volume tool the+ # per-tool floor exists to protect: at high total volume its sessions+ # fall outside the hash-ordered cut before any bucketing happens, so the+ # floor has nothing left to keep. The cap has to apply per tool.+ for i in range(12):+ self._seed_tool_call(f"exec-s{i}", "exec", intent="operate the thing")+ for i in range(2):+ self._seed_tool_call(f"metrics-s{i}", "query-metrics", intent="check p99 latency")+ flush_persons_and_events()++ buckets = intent_clustering.fetch_tools_by_session(self.team, max_sessions_per_tool=3)++ assert buckets["query-metrics"] == {"metrics-s0", "metrics-s1"}+ # exec is capped at the same number, so the two buckets together hold+ # more sessions than the cap — the pool was never cut globally.+ assert len(buckets["exec"]) == 3+def test_window_stats_count_calls_intents_and_sessions(self) -> None:self._seed_tool_call("session-a", "execute_sql", intent="find slow queries")self._seed_tool_call("session-a", "query_trends")