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(trends): bound the per-series query fan-out (#102774)

Thomas Obermülleree28548e518a
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index e0ed76be9ff0..a14f45d4c40c 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -51839,6 +51839,7 @@
"items": {
"$ref": "#/definitions/StickinessQuerySeriesNode"
},
+ "maxItems": 200,
"type": "array"
},
"stickinessFilter": {
@@ -54540,6 +54541,7 @@
"items": {
"$ref": "#/definitions/TrendsQuerySeriesNode"
},
+ "maxItems": 200,
"type": "array"
},
"tags": {
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 44fe15289f91..1bd7cafabbfc 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -1950,7 +1950,10 @@ export interface TrendsQuery extends InsightsQueryBase<TrendsQueryResponse> {
* @default day
*/
interval?: IntervalType
- /** Events and actions to include */
+ /**
+ * Events and actions to include
+ * @maxItems 200
+ */
series: TrendsQuerySeriesNode[]
/** Properties specific to the trends insight */
trendsFilter?: TrendsFilter
@@ -2553,7 +2556,10 @@ export interface StickinessQuery extends Omit<
* How many intervals comprise a period. Only used for cohorts, otherwise default 1.
*/
intervalCount?: positive_integer
- /** Events and actions to include */
+ /**
+ * Events and actions to include
+ * @maxItems 200
+ */
series: StickinessQuerySeriesNode[]
/** Properties specific to the stickiness insight */
stickinessFilter?: StickinessFilter
diff --git a/posthog/hogql/constants.py b/posthog/hogql/constants.py
index 46e81b282dff..e91e93d87034 100644
--- a/posthog/hogql/constants.py
+++ b/posthog/hogql/constants.py
@@ -44,6 +44,12 @@ MAX_SELECT_POSTHOG_AI_LIMIT = 500 # 500 rows
DEFAULT_POSTHOG_AI_RETURNED_ROWS = 100
MAX_SELECT_DATA_CATALOG_LIMIT = 10000
DEFAULT_DATA_CATALOG_RETURNED_ROWS = 1000
+# Cap on series x cohort breakdown values x compare, because each expanded series becomes its own
+# ClickHouse query on its own thread holding its own Postgres connection.
+MAX_EXPANDED_INSIGHT_QUERIES = 200
+# How many of those per-series queries run at the same time inside one request.
+INSIGHT_QUERY_FANOUT_CONCURRENCY = 10
+
# Max amount of memory usage when doing group by before swapping to disk. Only used in certain queries
MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY = 22 * 1024 * 1024 * 1024
diff --git a/posthog/hogql_queries/validation/rules.py b/posthog/hogql_queries/validation/rules.py
index bc94b3c9b4ae..6d280fd1c41a 100644
--- a/posthog/hogql_queries/validation/rules.py
+++ b/posthog/hogql_queries/validation/rules.py
@@ -2,6 +2,8 @@ from rest_framework.exceptions import ValidationError
from posthog.schema import EntityType, FunnelsQuery, LifecycleQuery, RetentionQuery, StickinessQuery, TrendsQuery
+from posthog.hogql.constants import MAX_EXPANDED_INSIGHT_QUERIES
+
from posthog.hogql_queries.utils.entities import has_data_warehouse_node
from posthog.hogql_queries.utils.properties import has_any_property_filters
from posthog.hogql_queries.validation.utils import get_query_insight_name
@@ -60,3 +62,39 @@ def _query_has_data_warehouse_series(
)
return has_data_warehouse_node(query.series)
+
+
+SERIES_FAN_OUT_TOO_LARGE = "insight_series_fan_out_too_large"
+
+
+def expanded_series_count(query: TrendsQuery | StickinessQuery, *, cohort_breakdown_expands: bool) -> int:
+ """How many ClickHouse queries this insight expands into, one per series after breakdown and compare.
+
+ The caller decides whether a cohort breakdown expands, because a conjoined cohort breakdown
+ resolves to a single query per series instead of one per cohort.
+ """
+ count = len(query.series)
+
+ breakdown_filter = getattr(query, "breakdownFilter", None)
+ if cohort_breakdown_expands and breakdown_filter is not None and isinstance(breakdown_filter.breakdown, list):
+ count *= max(1, len(breakdown_filter.breakdown))
+
+ if query.compareFilter is not None and query.compareFilter.compare:
+ count *= 2
+
+ return count
+
+
+def validate_series_fan_out(query: TrendsQuery | StickinessQuery, *, cohort_breakdown_expands: bool) -> None:
+ """Reject an insight that expands into more queries than one request is allowed to run.
+
+ Runners call this from setup_series rather than from validators(), because setup_series copies
+ the whole query once per cohort and runs before the standard validation rules do.
+ """
+ count = expanded_series_count(query, cohort_breakdown_expands=cohort_breakdown_expands)
+ if count > MAX_EXPANDED_INSIGHT_QUERIES:
+ raise ValidationError(
+ f"This insight needs {count} queries to run, which is over the limit of {MAX_EXPANDED_INSIGHT_QUERIES}. "
+ f"Use fewer series, break down by fewer cohorts, or turn off comparing to the previous period.",
+ code=SERIES_FAN_OUT_TOO_LARGE,
+ )
diff --git a/posthog/hogql_queries/validation/test_rules.py b/posthog/hogql_queries/validation/test_rules.py
index e9965bd57593..388011ed4d31 100644
--- a/posthog/hogql_queries/validation/test_rules.py
+++ b/posthog/hogql_queries/validation/test_rules.py
@@ -1,19 +1,34 @@
from posthog.test.base import BaseTest
from unittest.mock import MagicMock
+from django.test import SimpleTestCase
+
+import pydantic
from parameterized import parameterized
from rest_framework.exceptions import ValidationError
from posthog.schema import (
+ BreakdownFilter,
+ BreakdownType,
+ CompareFilter,
EventsNode,
FilterLogicalOperator,
LifecycleDataWarehouseNode,
LifecycleQuery,
PropertyGroupFilter,
PropertyGroupFilterValue,
+ StickinessQuery,
+ TrendsQuery,
)
-from posthog.hogql_queries.validation.rules import DisallowUnsupportedDataWarehouseSettings, RequireAtLeastOneSeries
+from posthog.hogql.constants import MAX_EXPANDED_INSIGHT_QUERIES
+
+from posthog.hogql_queries.validation.rules import (
+ DisallowUnsupportedDataWarehouseSettings,
+ RequireAtLeastOneSeries,
+ expanded_series_count,
+ validate_series_fan_out,
+)
from posthog.hogql_queries.validation.validation import QueryValidationContext
@@ -113,3 +128,89 @@ class TestDisallowUnsupportedDataWarehouseSettings(BaseTest):
)
DisallowUnsupportedDataWarehouseSettings().validate(self._context(query))
+
+
+def _series(count: int) -> list[EventsNode]:
+ return [EventsNode(event=f"event_{index}") for index in range(count)]
+
+
+def _cohort_breakdown(count: int) -> BreakdownFilter:
+ return BreakdownFilter(breakdown_type=BreakdownType.COHORT, breakdown=list(range(1, count + 1)))
+
+
+class TestValidateSeriesFanOut(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("at_the_limit", 200, None, False),
+ ("compare_doubles_up_to_the_limit", 100, None, True),
+ ("cohorts_multiply_up_to_the_limit", 40, _cohort_breakdown(5), False),
+ ("every_factor_together_at_the_limit", 25, _cohort_breakdown(4), True),
+ ]
+ )
+ def test_allows_expansions_within_the_limit(
+ self, _name: str, series_count: int, breakdown_filter: BreakdownFilter | None, compare: bool
+ ) -> None:
+ query = TrendsQuery(
+ series=_series(series_count),
+ breakdownFilter=breakdown_filter,
+ compareFilter=CompareFilter(compare=compare),
+ )
+
+ validate_series_fan_out(query, cohort_breakdown_expands=True)
+
+ @parameterized.expand(
+ [
+ ("compare_doubles_past_the_limit", 101, None, True, 202),
+ ("cohorts_multiply_past_the_limit", 50, _cohort_breakdown(5), False, 250),
+ ("every_factor_together_past_the_limit", 34, _cohort_breakdown(3), True, 204),
+ ]
+ )
+ def test_rejects_expansions_over_the_limit(
+ self, _name: str, series_count: int, breakdown_filter: BreakdownFilter | None, compare: bool, expected: int
+ ) -> None:
+ query = TrendsQuery(
+ series=_series(series_count),
+ breakdownFilter=breakdown_filter,
+ compareFilter=CompareFilter(compare=compare),
+ )
+
+ with self.assertRaises(ValidationError) as context:
+ validate_series_fan_out(query, cohort_breakdown_expands=True)
+
+ self.assertIn(f"needs {expected} queries", str(context.exception))
+ self.assertEqual(context.exception.get_codes(), ["insight_series_fan_out_too_large"])
+
+ def test_breakdown_that_does_not_expand_leaves_the_series_count_alone(self) -> None:
+ query = TrendsQuery(
+ series=_series(200),
+ breakdownFilter=BreakdownFilter(
+ breakdown_type=BreakdownType.EVENT, breakdown=[f"prop_{index}" for index in range(10)]
+ ),
+ )
+
+ validate_series_fan_out(query, cohort_breakdown_expands=False)
+
+ def test_rejects_stickiness_expansion_over_the_limit(self) -> None:
+ query = StickinessQuery(series=_series(101), compareFilter=CompareFilter(compare=True))
+
+ with self.assertRaises(ValidationError) as context:
+ validate_series_fan_out(query, cohort_breakdown_expands=False)
+
+ self.assertEqual(context.exception.get_codes(), ["insight_series_fan_out_too_large"])
+
+ def test_conjoined_cohort_breakdown_does_not_multiply_the_series(self) -> None:
+ query = TrendsQuery(series=_series(150), breakdownFilter=_cohort_breakdown(5))
+
+ self.assertEqual(expanded_series_count(query, cohort_breakdown_expands=False), 150)
+ self.assertEqual(expanded_series_count(query, cohort_breakdown_expands=True), 750)
+
+ validate_series_fan_out(query, cohort_breakdown_expands=False)
+
+
+class TestSeriesLengthSchemaLimit(SimpleTestCase):
+ @parameterized.expand([("trends", TrendsQuery), ("stickiness", StickinessQuery)])
+ def test_series_longer_than_the_limit_is_rejected_before_the_runner(self, _name: str, query_class) -> None:
+ query_class(series=_series(MAX_EXPANDED_INSIGHT_QUERIES))
+
+ with self.assertRaises(pydantic.ValidationError):
+ query_class(series=_series(MAX_EXPANDED_INSIGHT_QUERIES + 1))
diff --git a/posthog/schema.py b/posthog/schema.py
index 8d8a0f813da9..bca51440389b 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -30316,7 +30316,7 @@ class StickinessQuery(BaseModel):
response: StickinessQueryResponse | None = None
samplingFactor: float | None = Field(default=None, description="Sampling rate")
series: list[Annotated[EventsNode | ActionsNode | DataWarehouseNode, Field(discriminator="kind")]] = Field(
- ..., description="Events and actions to include"
+ ..., description="Events and actions to include", max_length=200
)
stickinessFilter: StickinessFilter | None = Field(
default=None, description="Properties specific to the stickiness insight"
@@ -30507,7 +30507,7 @@ class TrendsQuery(BaseModel):
response: TrendsQueryResponse | None = None
samplingFactor: float | None = Field(default=None, description="Sampling rate")
series: list[Annotated[EventsNode | ActionsNode | DataWarehouseNode | GroupNode, Field(discriminator="kind")]] = (
- Field(..., description="Events and actions to include")
+ Field(..., description="Events and actions to include", max_length=200)
)
tags: QueryLogTags | None = Field(default=None, description="Tags that will be added to the Query log comment")
trendsFilter: TrendsFilter | None = Field(default=None, description="Properties specific to the trends insight")
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 1e7b495931f8..30ade8d9f0b7 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -3095,7 +3095,10 @@ export interface TrendsQueryApi {
response?: TrendsQueryResponseApi | null
/** Sampling rate */
samplingFactor?: number | null
- /** Events and actions to include */
+ /**
+ * Events and actions to include
+ * @maxItems 200
+ */
series: (EventsNodeApi | ActionsNodeApi | DataWarehouseNodeApi | GroupNodeApi)[]
/** Tags that will be added to the Query log comment */
tags?: QueryLogTagsApi | null
@@ -4243,7 +4246,10 @@ export interface StickinessQueryApi {
response?: StickinessQueryResponseApi | null
/** Sampling rate */
samplingFactor?: number | null
- /** Events and actions to include */
+ /**
+ * Events and actions to include
+ * @maxItems 200
+ */
series: (EventsNodeApi | ActionsNodeApi | DataWarehouseNodeApi)[]
/** Properties specific to the stickiness insight */
stickinessFilter?: StickinessFilterApi | null
diff --git a/products/product_analytics/backend/hogql_queries/stickiness/stickiness_query_runner.py b/products/product_analytics/backend/hogql_queries/stickiness/stickiness_query_runner.py
index 76552cea9116..f984b407adc0 100644
--- a/products/product_analytics/backend/hogql_queries/stickiness/stickiness_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/stickiness/stickiness_query_runner.py
@@ -31,7 +31,11 @@ from posthog.hogql_queries.utils.query_compare_to_date_range import QueryCompare
from posthog.hogql_queries.utils.query_date_range import QueryDateRange
from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRange
from posthog.hogql_queries.utils.utils import get_response_hogql
-from posthog.hogql_queries.validation.rules import DisallowUnsupportedDataWarehouseSettings, RequireAtLeastOneSeries
+from posthog.hogql_queries.validation.rules import (
+ DisallowUnsupportedDataWarehouseSettings,
+ RequireAtLeastOneSeries,
+ validate_series_fan_out,
+)
from posthog.hogql_queries.validation.validation import QueryValidationRule
from posthog.models import Team
from posthog.models.filters.mixins.utils import cached_property
@@ -487,6 +491,8 @@ class StickinessQueryRunner(AnalyticsQueryRunner[StickinessQueryResponse]):
return action.name
def setup_series(self) -> list[SeriesWithExtras]:
+ validate_series_fan_out(self.query, cohort_breakdown_expands=False)
+
series_with_extras = [
SeriesWithExtras(
series,
diff --git a/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_query_runner.py b/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_query_runner.py
index 717cce8ac3ca..7e1d74332b95 100644
--- a/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/stickiness/test/test_stickiness_query_runner.py
@@ -18,6 +18,7 @@ from unittest.mock import MagicMock, patch
from django.test import override_settings
from parameterized import parameterized
+from rest_framework.exceptions import ValidationError
from posthog.schema import (
ActionsNode,
@@ -1598,3 +1599,16 @@ class TestStickinessSeriesCustomNames(BaseTest):
assert patched_response.results == expected_results
assert was_modified is expect_modified
+
+
+class TestStickinessSeriesFanOut(BaseTest):
+ def test_runner_rejects_an_expansion_over_the_limit_before_it_expands_the_series(self) -> None:
+ query = StickinessQuery(
+ series=[EventsNode(event=f"event_{index}") for index in range(101)],
+ compareFilter=CompareFilter(compare=True),
+ )
+
+ with self.assertRaises(ValidationError) as context:
+ StickinessQueryRunner(query=query, team=self.team)
+
+ self.assertEqual(context.exception.get_codes(), ["insight_series_fan_out_too_large"])
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_trend_validation_rules.py b/products/product_analytics/backend/hogql_queries/trends/test/test_trend_validation_rules.py
index eb1be9de59a8..d5d22a2e6637 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_trend_validation_rules.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_trend_validation_rules.py
@@ -8,6 +8,7 @@ from posthog.schema import (
Breakdown,
BreakdownFilter,
BreakdownType,
+ CompareFilter,
DataWarehouseNode,
DateRange,
EventsNode,
@@ -24,6 +25,7 @@ from products.product_analytics.backend.hogql_queries.trends.trend_validation_ru
DisallowUnsupportedPropertyMathForHistogramBreakdown,
ValidateDataWarehouseBreakdown,
)
+from products.product_analytics.backend.hogql_queries.trends.trends_query_runner import TrendsQueryRunner
class TestValidateDataWarehouseBreakdown(BaseTest):
@@ -370,3 +372,43 @@ class TestDisallowDaysOfWeekWithSmoothing(BaseTest):
DisallowDaysOfWeekWithSmoothing().validate(self._context(query))
self.assertEqual(context.exception.get_codes(), ["days_of_week_unsupported_with_smoothing"])
+
+
+class TestTrendsQueryRunnerSeriesFanOut(BaseTest):
+ def test_runner_rejects_an_expansion_over_the_limit_before_it_expands_the_series(self) -> None:
+ query = TrendsQuery(
+ series=[EventsNode(event=f"event_{index}") for index in range(150)],
+ compareFilter=CompareFilter(compare=True),
+ )
+
+ with self.assertRaises(ValidationError) as context:
+ TrendsQueryRunner(query=query, team=self.team)
+
+ self.assertEqual(context.exception.get_codes(), ["insight_series_fan_out_too_large"])
+
+ @parameterized.expand(
+ [
+ (
+ "conjoined_cohorts_do_not_expand",
+ 150,
+ BreakdownFilter(breakdown_type=BreakdownType.COHORT, breakdown=[1, 2]),
+ ),
+ (
+ "non_cohort_breakdown_does_not_expand",
+ 150,
+ BreakdownFilter(breakdown_type=BreakdownType.EVENT, breakdown=[f"prop_{index}" for index in range(10)]),
+ ),
+ ("all_cohort_expands", 50, BreakdownFilter(breakdown_type=BreakdownType.COHORT, breakdown=["all", 1, 2])),
+ ]
+ )
+ def test_accepted_query_expands_to_the_count_the_validator_used(
+ self, _name: str, series_count: int, breakdown_filter: BreakdownFilter
+ ) -> None:
+ query = TrendsQuery(
+ series=[EventsNode(event=f"event_{index}") for index in range(series_count)],
+ breakdownFilter=breakdown_filter,
+ )
+
+ runner = TrendsQueryRunner(query=query, team=self.team)
+
+ self.assertEqual(len(runner.series), 150)
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_runner.py b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_runner.py
index 8ea4e5f3f1d6..be8a119c4889 100644
--- a/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_trends_query_runner.py
@@ -8193,3 +8193,37 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert len(response.results) == 1
assert response.results[0]["count"] == expected_count
+
+
+class TestTrendsQueryRunnerParallelExecution(ClickhouseTestMixin, APIBaseTest):
+ """Runs without override_settings(IN_UNIT_TESTING=True) so the queries go through the executor."""
+
+ def _run(self, series: list[EventsNode], breakdown: Optional[BreakdownFilter] = None):
+ return TrendsQueryRunner(
+ team=self.team,
+ query=TrendsQuery(
+ dateRange=DateRange(date_from="2020-01-09", date_to="2020-01-20"),
+ interval=IntervalType.DAY,
+ series=series,
+ breakdownFilter=breakdown,
+ ),
+ ).calculate()
+
+ def test_every_series_comes_back_when_the_queries_run_through_the_executor(self):
+ _create_person(distinct_ids=["p1"], team=self.team)
+ for event in ("a", "b", "c"):
+ _create_event(team=self.team, event=event, distinct_id="p1", timestamp="2020-01-11T12:00:00Z")
+ flush_persons_and_events()
+
+ response = self._run([EventsNode(event=event) for event in ("a", "b", "c")])
+
+ self.assertEqual([result["label"] for result in response.results], ["a", "b", "c"])
+ self.assertEqual([sum(result["data"]) for result in response.results], [1, 1, 1])
+
+ def test_empty_cohort_breakdown_returns_no_results_instead_of_raising(self):
+ response = self._run(
+ [EventsNode(event="$pageview")],
+ breakdown=BreakdownFilter(breakdown_type=BreakdownType.COHORT, breakdown=[]),
+ )
+
+ self.assertEqual(response.results, [])
diff --git a/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py b/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py
index c7607cba8394..eb313d913aa8 100644
--- a/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py
@@ -1,5 +1,5 @@
-import threading
from collections.abc import Sequence
+from concurrent.futures import ThreadPoolExecutor
from copy import deepcopy
from datetime import date, datetime, timedelta
from math import ceil
@@ -44,7 +44,12 @@ from posthog.schema import (
)
from posthog.hogql import ast, query_stats
-from posthog.hogql.constants import MAX_SELECT_RETURNED_ROWS, HogQLGlobalSettings, LimitContext
+from posthog.hogql.constants import (
+ INSIGHT_QUERY_FANOUT_CONCURRENCY,
+ MAX_SELECT_RETURNED_ROWS,
+ HogQLGlobalSettings,
+ LimitContext,
+)
from posthog.hogql.query import execute_hogql_query
from posthog.hogql.query_stats import QueryStats
from posthog.hogql.timings import HogQLTimings
@@ -73,7 +78,11 @@ from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPr
from posthog.hogql_queries.utils.sampling import correct_result_for_sampling
from posthog.hogql_queries.utils.timestamp_utils import format_label_date, get_earliest_timestamp_from_series
from posthog.hogql_queries.utils.utils import get_response_hogql
-from posthog.hogql_queries.validation.rules import DisallowUnsupportedDataWarehouseSettings, RequireAtLeastOneSeries
+from posthog.hogql_queries.validation.rules import (
+ DisallowUnsupportedDataWarehouseSettings,
+ RequireAtLeastOneSeries,
+ validate_series_fan_out,
+)
from posthog.hogql_queries.validation.validation import QueryValidationRule
from posthog.models import Team
from posthog.models.filters.mixins.utils import cached_property
@@ -453,30 +462,33 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
timings_matrix[0] = self.timings.to_list(back_out_stack=False)
self.timings.clear_timings()
- # This exists so that we're not spawning threads during unit tests. We can't do
- # this right now due to the lack of multithreaded support of Django
- if len(queries) == 1 or settings.IN_UNIT_TESTING:
+ # A count of 0 or 1 needs no thread, and an empty series expansion produces 0 queries.
+ # IN_UNIT_TESTING keeps a test class on this path as well, because Django does not make
+ # the test transaction visible to another thread.
+ if len(queries) <= 1 or settings.IN_UNIT_TESTING:
for index, query in enumerate(queries):
run(index, query, self.timings.clone_for_subquery(index), False)
else:
- # A thread starts with an empty context, so the query tags and the query scan
+ # A worker thread starts with an empty context, so the query tags and the query scan
# accumulator are handed over explicitly.
- jobs = [
- threading.Thread(
- target=run,
- args=(
+ parent_tags = query_tagging.get_query_tags().model_copy(deep=True)
+ parent_stats = query_stats.get_active()
+ max_workers = min(INSIGHT_QUERY_FANOUT_CONCURRENCY, len(queries))
+ with ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix="trends_series") as executor:
+ futures = [
+ executor.submit(
+ run,
index,
query,
self.timings.clone_for_subquery(index),
True,
- query_tagging.get_query_tags().model_copy(deep=True),
- query_stats.get_active(),
- ),
- )
- for index, query in enumerate(queries)
- ]
- [j.start() for j in jobs] # type:ignore
- [j.join() for j in jobs] # type:ignore
+ parent_tags,
+ parent_stats,
+ )
+ for index, query in enumerate(queries)
+ ]
+ for future in futures:
+ future.result()
# Raise any errors raised in a seperate thread
if len(errors) > 0:
@@ -948,6 +960,13 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
)
def setup_series(self) -> list[SeriesWithExtras]:
+ cohort_breakdown_expands = (
+ self.modifiers.inCohortVia != InCohortVia.LEFTJOIN_CONJOINED
+ and self.query.breakdownFilter is not None
+ and self.query.breakdownFilter.breakdown_type == "cohort"
+ )
+ validate_series_fan_out(self.query, cohort_breakdown_expands=cohort_breakdown_expands)
+
series_with_extras = [
SeriesWithExtras(
series=series,
@@ -959,11 +978,7 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
for index, series in enumerate(self.query.series)
]
- if (
- self.modifiers.inCohortVia != InCohortVia.LEFTJOIN_CONJOINED
- and self.query.breakdownFilter is not None
- and self.query.breakdownFilter.breakdown_type == "cohort"
- ):
+ if cohort_breakdown_expands and self.query.breakdownFilter is not None:
updated_series = []
if isinstance(self.query.breakdownFilter.breakdown, list):
cohort_ids = self.query.breakdownFilter.breakdown
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 92df69906165..c33cc3ae3440 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -2055,7 +2055,10 @@ export interface TrendsQueryApi {
response?: TrendsQueryResponseApi | null
/** Sampling rate */
samplingFactor?: number | null
- /** Events and actions to include */
+ /**
+ * Events and actions to include
+ * @maxItems 200
+ */
series: (EventsNodeApi | ActionsNodeApi | DataWarehouseNodeApi | GroupNodeApi)[]
/** Tags that will be added to the Query log comment */
tags?: QueryLogTagsApi | null
@@ -3203,7 +3206,10 @@ export interface StickinessQueryApi {
response?: StickinessQueryResponseApi | null
/** Sampling rate */
samplingFactor?: number | null
- /** Events and actions to include */
+ /**
+ * Events and actions to include
+ * @maxItems 200
+ */
series: (EventsNodeApi | ActionsNodeApi | DataWarehouseNodeApi)[]
/** Properties specific to the stickiness insight */
stickinessFilter?: StickinessFilterApi | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 072ecfbcae57..379d552fc9be 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -4209,7 +4209,10 @@ export namespace Schemas {
response?: TrendsQueryResponse | null;
/** Sampling rate */
samplingFactor?: number | null;
- /** Events and actions to include */
+ /**
+ * Events and actions to include
+ * @maxItems 200
+ */
series: (EventsNode | ActionsNode | DataWarehouseNode | GroupNode)[];
/** Tags that will be added to the Query log comment */
tags?: QueryLogTags | null;
@@ -5016,7 +5019,10 @@ export namespace Schemas {
response?: StickinessQueryResponse | null;
/** Sampling rate */
samplingFactor?: number | null;
- /** Events and actions to include */
+ /**
+ * Events and actions to include
+ * @maxItems 200
+ */
series: (EventsNode | ActionsNode | DataWarehouseNode)[];
/** Properties specific to the stickiness insight */
stickinessFilter?: StickinessFilter | null;