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(devex): return 400 for bad list paging input and fix list schemas (#126465)

Julian Bez1ec1ab4c2998
diff --git a/frontend/src/layout/today/todaySpacesLogic.ts b/frontend/src/layout/today/todaySpacesLogic.ts
index 3e5d44de5708..82c1741e5288 100644
--- a/frontend/src/layout/today/todaySpacesLogic.ts
+++ b/frontend/src/layout/today/todaySpacesLogic.ts
@@ -391,7 +391,7 @@ export const todaySpacesLogic = kea<todaySpacesLogicType>([
}
const response = await taskChannelsList(String(values.currentTeamId))
// Without `limit` the endpoint answers with a bare array rather than a page.
- return Array.isArray(response) ? (response as ChannelDTOApi[]) : response.results
+ return Array.isArray(response) ? response : response.results
},
},
],
diff --git a/posthog/api/cohort.py b/posthog/api/cohort.py
index ee21c22ab1de..653bb5b70039 100644
--- a/posthog/api/cohort.py
+++ b/posthog/api/cohort.py
@@ -805,6 +805,23 @@ class CohortUsedInResponseSerializer(serializers.Serializer):
)
+# Each run carries its per-query stats, so a page stays bounded well above the UI page size of 100.
+COHORT_CALCULATION_HISTORY_MAX_LIMIT = 500
+
+
+class CohortCalculationHistoryQuerySerializer(serializers.Serializer):
+ limit = serializers.IntegerField(
+ required=False,
+ default=100,
+ min_value=1,
+ max_value=COHORT_CALCULATION_HISTORY_MAX_LIMIT,
+ help_text=f"Number of calculation runs to return. Defaults to 100, at most {COHORT_CALCULATION_HISTORY_MAX_LIMIT}.",
+ )
+ offset = serializers.IntegerField(
+ required=False, default=0, min_value=0, help_text="Number of calculation runs to skip. Defaults to 0."
+ )
+
+
class CohortCalculationHistorySerializer(serializers.ModelSerializer):
duration_seconds = serializers.ReadOnlyField()
is_completed = serializers.ReadOnlyField()
@@ -814,7 +831,6 @@ class CohortCalculationHistorySerializer(serializers.ModelSerializer):
total_read_rows = serializers.ReadOnlyField()
total_written_rows = serializers.ReadOnlyField()
main_query = serializers.ReadOnlyField()
- main_query_id = serializers.ReadOnlyField()
class Meta:
model = CohortCalculationHistory
@@ -834,10 +850,20 @@ class CohortCalculationHistorySerializer(serializers.ModelSerializer):
"total_read_rows",
"total_written_rows",
"main_query",
- "main_query_id",
]
+class CohortCalculationHistoryResponseSerializer(serializers.Serializer):
+ results = CohortCalculationHistorySerializer(many=True, help_text="Calculation runs on this page, newest first.")
+ count = serializers.IntegerField(help_text="Number of calculation runs recorded for the cohort.")
+ next = serializers.CharField(
+ allow_null=True, help_text="Query string for the next page, such as `?limit=100&offset=100`, or null."
+ )
+ previous = serializers.CharField(
+ allow_null=True, help_text="Query string for the previous page, or null on the first page."
+ )
+
+
class CSVConfig:
"""Configuration constants for CSV processing"""
@@ -2737,10 +2763,16 @@ class CohortViewSet(TeamAndOrgViewSetMixin, ForbidDestroyModel, viewsets.ModelVi
)
return activity_page_response(activity_page, page_params.limit, page_params.page, request)
+ @extend_schema(
+ parameters=[CohortCalculationHistoryQuerySerializer],
+ responses={200: CohortCalculationHistoryResponseSerializer},
+ )
@action(methods=["GET"], detail=True, required_scopes=["cohort:read"])
def calculation_history(self, request: request.Request, **kwargs):
- limit = int(request.query_params.get("limit", "100"))
- offset = int(request.query_params.get("offset", "0"))
+ query = CohortCalculationHistoryQuerySerializer(data=request.query_params)
+ query.is_valid(raise_exception=True)
+ limit: int = query.validated_data["limit"]
+ offset: int = query.validated_data["offset"]
cohort: Cohort = self.get_object()
diff --git a/posthog/api/data_color_theme.py b/posthog/api/data_color_theme.py
index 622137e052c6..eaf2eb4c5f13 100644
--- a/posthog/api/data_color_theme.py
+++ b/posthog/api/data_color_theme.py
@@ -78,6 +78,8 @@ class DataColorThemeViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
serializer_class = DataColorThemeSerializer
permission_classes = [GlobalThemePermission, PaidThemePermission, TeamMemberStrictManagementPermission]
sharing_enabled_actions = ["retrieve", "list"]
+ # The list returns every theme the team can use as one array, so it has no pages.
+ pagination_class = None
# override the team scope queryset to also include global themes
def dangerously_get_queryset(self):
diff --git a/posthog/api/dead_letter_queue.py b/posthog/api/dead_letter_queue.py
index 2230e9ce4fef..7af091cb0ac3 100644
--- a/posthog/api/dead_letter_queue.py
+++ b/posthog/api/dead_letter_queue.py
@@ -123,6 +123,12 @@ class DeadLetterQueueMetricsSerializer(serializers.Serializer):
subrows = serializers.JSONField(read_only=True)
+class DeadLetterQueueMetricQuerySerializer(serializers.Serializer):
+ offset = serializers.IntegerField(
+ required=False, default=0, min_value=0, help_text="Number of metric rows to skip. Defaults to 0."
+ )
+
+
class DeadLetterQueueViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mixins.RetrieveModelMixin):
permission_classes = [permissions.IsAuthenticated, IsStaffUser]
serializer_class = DeadLetterQueueMetricsSerializer
@@ -146,7 +152,9 @@ class DeadLetterQueueViewSet(viewsets.GenericViewSet, mixins.ListModelMixin, mix
return output
def get_object(self) -> DeadLetterQueueMetric:
- offset = int(self.request.GET.get("offset", "0"))
+ query = DeadLetterQueueMetricQuerySerializer(data=self.request.GET)
+ query.is_valid(raise_exception=True)
+ offset: int = query.validated_data["offset"]
after = self.request.GET.get("after", "-7d")
before = self.request.GET.get("before", None)
after_datetime = relative_date_parse(after, ZoneInfo("UTC"))
diff --git a/posthog/api/event.py b/posthog/api/event.py
index c4fe8fe19656..12f43a19c1d3 100644
--- a/posthog/api/event.py
+++ b/posthog/api/event.py
@@ -113,6 +113,11 @@ class EventValueQueryParams:
value: str | None
+class EventListPagingQuerySerializer(serializers.Serializer):
+ limit = serializers.IntegerField(required=False, min_value=0, help_text="The maximum number of results to return")
+ offset = serializers.IntegerField(required=False, default=0, min_value=0, help_text="Number of rows to skip.")
+
+
class ElementSerializer(serializers.ModelSerializer):
event = serializers.CharField()
@@ -274,23 +279,16 @@ class EventViewSet(
)
def list(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:
tag_queries(product=ProductKey.PRODUCT_ANALYTICS, feature=Feature.QUERY)
+ is_csv_request = self.request.accepted_renderer.format == "csv"
+ # An empty `limit=` or `offset=` means the default, so only non-empty values are validated.
+ paging = EventListPagingQuerySerializer(
+ data={key: request.GET[key] for key in ("limit", "offset") if request.GET.get(key)}
+ )
+ paging.is_valid(raise_exception=True)
+ default_limit = QUERY_DEFAULT_EXPORT_LIMIT if is_csv_request else DEFAULT_RETURNED_ROWS
+ limit = min(paging.validated_data.get("limit", default_limit), EVENT_LIST_MAX_LIMIT)
+ offset: int = paging.validated_data["offset"]
try:
- is_csv_request = self.request.accepted_renderer.format == "csv"
-
- if self.request.GET.get("limit", None):
- limit = int(self.request.GET.get("limit")) # type: ignore
- elif is_csv_request:
- limit = QUERY_DEFAULT_EXPORT_LIMIT
- else:
- limit = DEFAULT_RETURNED_ROWS
-
- limit = min(limit, EVENT_LIST_MAX_LIMIT)
-
- try:
- offset = int(request.GET["offset"]) if request.GET.get("offset") else 0
- except ValueError:
- offset = 0
-
team = self.team
deprecate_offset = (
diff --git a/posthog/api/test/test_cohort.py b/posthog/api/test/test_cohort.py
index 3f7cf4504d7f..2e656ace3f29 100644
--- a/posthog/api/test/test_cohort.py
+++ b/posthog/api/test/test_cohort.py
@@ -6788,6 +6788,21 @@ [email protected],
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIn("too much memory", response.json()["last_error_message"].lower())
+ @parameterized.expand(
+ [
+ ("non_numeric_limit", "limit=abc"),
+ ("limit_over_max", "limit=501"),
+ ("non_numeric_offset", "offset=abc"),
+ ("negative_offset", "offset=-1"),
+ ]
+ )
+ def test_calculation_history_rejects_bad_paging_params(self, _name: str, query: str) -> None:
+ cohort = Cohort.objects.create(team=self.team, name="Test Cohort")
+
+ response = self.client.get(f"/api/projects/{self.team.id}/cohorts/{cohort.id}/calculation_history/?{query}")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
def test_cohort_last_error_message_clears_after_subsequent_success(self):
"""Test that a subsequent completed successful calculation clears last_error_message in detail, list, and fallback paths"""
from posthog.api.cohort import CohortSerializer
diff --git a/posthog/api/test/test_dead_letter_queue.py b/posthog/api/test/test_dead_letter_queue.py
new file mode 100644
index 000000000000..b37b0cdefd6b
--- /dev/null
+++ b/posthog/api/test/test_dead_letter_queue.py
@@ -0,0 +1,15 @@
+from posthog.test.base import APIBaseTest
+
+from parameterized import parameterized
+from rest_framework import status
+
+
+class TestDeadLetterQueueAPI(APIBaseTest):
+ @parameterized.expand([("non_numeric", "abc"), ("negative", "-1")])
+ def test_retrieve_rejects_bad_offset(self, _name: str, offset: str) -> None:
+ self.user.is_staff = True
+ self.user.save()
+
+ response = self.client.get(f"/api/dead_letter_queue/dlq_events/?offset={offset}")
+
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
diff --git a/posthog/api/test/test_event.py b/posthog/api/test/test_event.py
index 12a5d741686f..8d68740865bb 100644
--- a/posthog/api/test/test_event.py
+++ b/posthog/api/test/test_event.py
@@ -1031,6 +1031,20 @@ class TestEvents(ClickhouseTestMixin, APIBaseTest):
response = self.client.get(f"/api/projects/{self.team.id}/events/?limit=50000").json()
assert len(response["results"]) == 2
+ @parameterized.expand(
+ [
+ ("non_numeric_limit", "limit", "abc"),
+ ("negative_limit", "limit", "-1"),
+ ("non_numeric_offset", "offset", "abc"),
+ ("negative_offset", "offset", "-1"),
+ ]
+ )
+ def test_list_rejects_bad_paging_params(self, _name: str, param: str, value: str) -> None:
+ response = self.client.get(f"/api/projects/{self.team.id}/events/?{param}={value}")
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json()["attr"] == param
+
@patch("posthog.api.event.get_persons_mapped_by_distinct_id")
def test_list_without_include_person_skips_person_lookup(self, mock_get_persons):
_create_person(team=self.team, distinct_ids=["1"], is_identified=True)
diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.py
index 4cbb97e073c4..a33fb4d1bf4b 100644
--- a/posthog/session_recordings/session_recording_api.py
+++ b/posthog/session_recordings/session_recording_api.py
@@ -23,7 +23,7 @@ import requests
import structlog
import posthoganalytics
from clickhouse_driver.errors import ServerException
-from drf_spectacular.utils import extend_schema
+from drf_spectacular.utils import extend_schema, extend_schema_serializer
from openai.types.chat import (
ChatCompletionAssistantMessageParam,
ChatCompletionMessageParam,
@@ -623,6 +623,18 @@ class SessionRecordingConsoleLogsResponseSerializer(serializers.Serializer):
)
+@extend_schema_serializer(many=False)
+class SessionRecordingListResponseSerializer(serializers.Serializer):
+ results = SessionRecordingSerializer(many=True, help_text="Recordings on this page.")
+ has_next = serializers.BooleanField(help_text="Whether more recordings match the query after this page.")
+ version = serializers.IntegerField(help_text="Version of the listing response format.")
+ next_cursor = serializers.CharField(
+ required=False,
+ help_text="Cursor for the next page. Send it back as `after` to load the next page. "
+ "Absent when the query does not page by cursor or there is no next page.",
+ )
+
+
@frozen
class RecordingsListingResult:
recordings: list[SessionRecording]
@@ -984,6 +996,7 @@ class SessionRecordingViewSet(
return [*super().get_throttles(), ListingBurstRateThrottle(), ListingSustainedRateThrottle()]
return super().get_throttles()
+ @extend_schema(responses={200: SessionRecordingListResponseSerializer(many=False)})
def list(self, request: request.Request, *args: Any, **kwargs: Any) -> Response:
tag_queries(product=Product.REPLAY, feature=Feature.QUERY)
user_distinct_id = cast(User, request.user).distinct_id
diff --git a/posthog/session_recordings/session_recording_playlist_api.py b/posthog/session_recordings/session_recording_playlist_api.py
index 5e05c76c69f9..f70cdec6c556 100644
--- a/posthog/session_recordings/session_recording_playlist_api.py
+++ b/posthog/session_recordings/session_recording_playlist_api.py
@@ -134,21 +134,6 @@ def playlist_name_sort_key(playlist: SessionRecordingPlaylist) -> str:
return (playlist.name or playlist.derived_name or "").lower()
-def parse_non_negative_int(value: Any, default: int) -> int:
- try:
- return max(0, int(value))
- except (TypeError, ValueError):
- return default
-
-
-def parse_positive_int(value: Any, default: int) -> int:
- """Like parse_non_negative_int but rejects 0. A limit of 0 makes the paginator's
- next link point back at the same offset — an infinite-paging loop — so non-positive
- input falls back to the default, matching DRF's LimitOffsetPagination."""
- parsed = parse_non_negative_int(value, default)
- return parsed if parsed > 0 else default
-
-
def create_synthetic_playlist_instance(
synthetic_def: SyntheticPlaylistDefinition, team: Team, user: User
) -> SessionRecordingPlaylist:
@@ -684,6 +669,27 @@ class SessionRecordingPlaylistSerializer(serializers.ModelSerializer, UserAccess
return updated_playlist
+class SessionRecordingPlaylistListQuerySerializer(serializers.Serializer):
+ limit = serializers.IntegerField(
+ required=False,
+ default=SessionRecordingPlaylistPagination.default_limit,
+ min_value=0,
+ help_text=f"Number of playlists to return. Defaults to 100, also for 0. Values above {PLAYLIST_LIST_MAX_LIMIT} are capped.",
+ )
+ offset = serializers.IntegerField(
+ required=False, default=0, min_value=0, help_text="Number of playlists to skip. Defaults to 0."
+ )
+
+
+class SessionRecordingPlaylistRecordingsQuerySerializer(serializers.Serializer):
+ limit = serializers.IntegerField(
+ required=False, default=50, min_value=1, help_text="Number of recordings to return. Defaults to 50."
+ )
+ offset = serializers.IntegerField(
+ required=False, default=0, min_value=0, help_text="Number of recordings to skip. Defaults to 0."
+ )
+
+
@extend_schema(tags=["replay"])
class SessionRecordingPlaylistViewSet(
TeamAndOrgViewSetMixin, AccessControlViewSetMixin, ForbidDestroyModel, viewsets.ModelViewSet
@@ -754,8 +760,13 @@ class SessionRecordingPlaylistViewSet(
synth_count = len(sorted_synthetics)
total_count = db_count + synth_count
- limit = min(parse_positive_int(request.GET.get("limit"), 100), PLAYLIST_LIST_MAX_LIMIT)
- offset = parse_non_negative_int(request.GET.get("offset"), 0)
+ paging = SessionRecordingPlaylistListQuerySerializer(data=request.GET)
+ paging.is_valid(raise_exception=True)
+ # A limit of 0 makes the next link point back at the same offset (infinite paging), so it means
+ # the default, as in DRF's LimitOffsetPagination.
+ requested_limit: int = paging.validated_data["limit"] or SessionRecordingPlaylistPagination.default_limit
+ limit = min(requested_limit, PLAYLIST_LIST_MAX_LIMIT)
+ offset: int = paging.validated_data["offset"]
span.set_attribute("team_id", self.team.id)
span.set_attribute("db_count", db_count)
@@ -1003,8 +1014,10 @@ class SessionRecordingPlaylistViewSet(
tag_queries(team_id=self.team.id, product=Product.REPLAY, feature=Feature.QUERY)
playlist = self.get_object()
- limit = int(request.GET.get("limit", 50))
- offset = int(request.GET.get("offset", 0))
+ paging = SessionRecordingPlaylistRecordingsQuerySerializer(data=request.GET)
+ paging.is_valid(raise_exception=True)
+ limit: int = paging.validated_data["limit"]
+ offset: int = paging.validated_data["offset"]
# Handle synthetic playlists differently
if getattr(playlist, "_is_synthetic", False):
diff --git a/posthog/session_recordings/test/test_session_recording_playlist.py b/posthog/session_recordings/test/test_session_recording_playlist.py
index 05363b1867e9..4942c1d535d9 100644
--- a/posthog/session_recordings/test/test_session_recording_playlist.py
+++ b/posthog/session_recordings/test/test_session_recording_playlist.py
@@ -2,7 +2,6 @@ import json
from datetime import UTC, datetime, timedelta
from uuid import uuid4
-import pytest
import time_machine
from posthog.test.base import APIBaseTest, QueryMatchingTest, snapshot_postgres_queries
from unittest import mock
@@ -36,8 +35,6 @@ from posthog.session_recordings.session_recording_playlist_api import (
_attach_empty_recordings_counts,
_empty_saved_filters_counts,
count_collection_recordings,
- parse_non_negative_int,
- parse_positive_int,
precompute_recordings_counts,
)
from posthog.session_recordings.synthetic_playlists import ExpiringPlaylistSource
@@ -915,6 +912,27 @@ class TestSessionRecordingPlaylist(APIBaseTest, QueryMatchingTest):
assert response.status_code == status.HTTP_200_OK
assert {x["id"] for x in response.json()["results"]} == set(sessions_newest_first[:2])
+ @parameterized.expand(
+ [
+ ("recordings_non_numeric_limit", True, {"limit": "abc"}),
+ ("recordings_negative_offset", True, {"offset": -1}),
+ ("list_non_numeric_limit", False, {"limit": "abc"}),
+ ("list_negative_limit", False, {"limit": -5}),
+ ("list_negative_offset", False, {"offset": -1}),
+ ]
+ )
+ def test_rejects_bad_paging_params(self, _name: str, recordings: bool, params: dict[str, str | int]) -> None:
+ url = f"/api/projects/{self.team.id}/session_recording_playlists"
+ if recordings:
+ playlist = SessionRecordingPlaylist.objects.create(
+ team=self.team, name="collection", created_by=self.user, type="collection"
+ )
+ url = f"{url}/{playlist.short_id}/recordings"
+
+ response = self.client.get(url, data=params)
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+
@parameterized.expand(
[
("narrow_window_excludes", "-1d", False),
@@ -1887,31 +1905,3 @@ class TestPrecomputeRecordingsCounts(APIBaseTest):
# and certainly no self-referential loop.
assert data["next"] is None
assert len(data["results"]) == data["count"]
-
-
- "value,expected",
- [
- ("30", 30),
- ("0", 0),
- ("-5", 0),
- ("abc", 100),
- (None, 100),
- ],
-)
-def test_parse_non_negative_int(value: object, expected: int) -> None:
- assert parse_non_negative_int(value, 100) == expected
-
-
- "value,expected",
- [
- ("30", 30),
- ("0", 100), # limit=0 would loop pagination -> default
- ("-5", 100), # non-positive -> default
- ("abc", 100),
- (None, 100),
- ],
-)
-def test_parse_positive_int(value: object, expected: int) -> None:
- assert parse_positive_int(value, 100) == expected
diff --git a/products/actions/backend/api/action.py b/products/actions/backend/api/action.py
index 6d9e4bd45d05..717d9e8e1622 100644
--- a/products/actions/backend/api/action.py
+++ b/products/actions/backend/api/action.py
@@ -9,7 +9,13 @@ from django.db.models import Count
import structlog
from drf_spectacular.types import OpenApiTypes
-from drf_spectacular.utils import OpenApiParameter, PolymorphicProxySerializer, extend_schema, extend_schema_field
+from drf_spectacular.utils import (
+ OpenApiParameter,
+ PolymorphicProxySerializer,
+ extend_schema,
+ extend_schema_field,
+ extend_schema_serializer,
+)
from rest_framework import request, serializers, viewsets
from rest_framework.decorators import action as drf_action
from rest_framework.renderers import BaseRenderer
@@ -599,6 +605,23 @@ def count_action_references_bulk(action_ids: list[int], team: Team) -> dict[int,
return dict(counts)
+class ActionListPagingQuerySerializer(serializers.Serializer):
+ limit = serializers.IntegerField(
+ required=False, min_value=0, help_text="Maximum number of actions to return. Omit to return all."
+ )
+ offset = serializers.IntegerField(
+ required=False, default=0, min_value=0, help_text="Number of actions to skip before returning results."
+ )
+
+
+@extend_schema_serializer(many=False)
+class ActionListResponseSerializer(serializers.Serializer):
+ count = serializers.IntegerField(
+ help_text="Number of actions that match the filters. Without `limit`, it is `offset` plus the number of actions returned."
+ )
+ results = ActionSerializer(many=True, help_text="Actions on this page, or every matching action without `limit`.")
+
+
class ActionViewSet(
TeamAndOrgViewSetMixin,
AccessControlViewSetMixin,
@@ -679,16 +702,6 @@ class ActionViewSet(
refs = find_action_references(action_obj.id, action_obj.team)
return Response(ActionReferenceSerializer(refs, many=True).data)
- @staticmethod
- def _parse_non_negative_int(raw: str | None) -> int | None:
- if raw is None:
- return None
- try:
- value = int(raw)
- except (TypeError, ValueError):
- return None
- return value if value >= 0 else None
-
_ORDERING_WHITELIST = {"name", "created_at", "pinned_at", "created_by"}
def _ordering_from_request(self, request: request.Request) -> list[str] | None:
@@ -735,7 +748,8 @@ class ActionViewSet(
OpenApiTypes.STR,
description="Field to order by (name, created_at, pinned_at, created_by). Prefix with '-' for descending.",
),
- ]
+ ],
+ responses={200: ActionListResponseSerializer(many=False)},
)
def list(self, request: request.Request, *args: Any, **kwargs: Any) -> Response:
# :HACKY: we need to override this viewset method until actions support
@@ -773,8 +787,10 @@ class ActionViewSet(
if ordering:
actions = actions.order_by(*ordering)
- offset = self._parse_non_negative_int(request.query_params.get("offset")) or 0
- limit = self._parse_non_negative_int(request.query_params.get("limit"))
+ paging = ActionListPagingQuerySerializer(data=request.query_params)
+ paging.is_valid(raise_exception=True)
+ offset: int = paging.validated_data["offset"]
+ limit: int | None = paging.validated_data.get("limit")
# Only pay for a COUNT query when actually paginating. The full-list default
# (no `limit`) is a hot path shared with the taxonomic filter, so we derive the
# count from the serialized results there instead of hitting the DB again.
diff --git a/products/actions/backend/api/test/test_action.py b/products/actions/backend/api/test/test_action.py
index a1e70ad5052c..2fc58af67635 100644
--- a/products/actions/backend/api/test/test_action.py
+++ b/products/actions/backend/api/test/test_action.py
@@ -555,6 +555,18 @@ class TestActionApi(ClickhouseTestMixin, APIBaseTest, QueryMatchingTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual([action["name"] for action in response.json()["results"]], expected_names)
+ @parameterized.expand(
+ [
+ ("non_numeric_limit", "limit", "abc"),
+ ("negative_limit", "limit", "-1"),
+ ("non_numeric_offset", "offset", "abc"),
+ ]
+ )
+ def test_listing_actions_rejects_bad_paging_params(self, _name: str, param: str, value: str) -> None:
+ response = self.client.get(f"/api/projects/{self.team.id}/actions/?{param}={value}")
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ self.assertEqual(response.json()["attr"], param)
+
def test_list_count_reflects_full_filtered_set_not_the_page(self) -> None:
for name in ["alpha", "beta", "gamma", "delta"]:
Action.objects.create(team=self.team, name=name)
diff --git a/products/actions/frontend/generated/api.schemas.ts b/products/actions/frontend/generated/api.schemas.ts
index 874692ebdbd0..1b2ebc805620 100644
--- a/products/actions/frontend/generated/api.schemas.ts
+++ b/products/actions/frontend/generated/api.schemas.ts
@@ -604,12 +604,10 @@ export interface ActionApi {
readonly user_access_level: string | null
}
-export interface PaginatedActionListApi {
+export interface ActionListResponseApi {
+ /** Number of actions that match the filters. Without `limit`, it is `offset` plus the number of actions returned. */
count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
+ /** Actions on this page, or every matching action without `limit`. */
results: ActionApi[]
}
diff --git a/products/actions/frontend/generated/api.ts b/products/actions/frontend/generated/api.ts
index 299ccf269997..58e883617c5b 100644
--- a/products/actions/frontend/generated/api.ts
+++ b/products/actions/frontend/generated/api.ts
@@ -10,6 +10,7 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
*/
import type {
ActionApi,
+ ActionListResponseApi,
ActionReferenceApi,
ActionSelectorMatchChangeApi,
ActionsBulkUpdateTagsCreateParams,
@@ -23,7 +24,6 @@ import type {
ActionsUpdateParams,
BulkUpdateTagsRequestApi,
BulkUpdateTagsResponseApi,
- PaginatedActionListApi,
PatchedActionApi,
} from './api.schemas'
@@ -64,8 +64,8 @@ export const actionsList = async (
projectId: string,
params?: ActionsListParams,
options?: RequestInit
-): Promise<PaginatedActionListApi> => {
- return apiMutator<PaginatedActionListApi>(getActionsListUrl(projectId, params), {
+): Promise<ActionListResponseApi> => {
+ return apiMutator<ActionListResponseApi>(getActionsListUrl(projectId, params), {
...options,
method: 'GET',
})
diff --git a/products/canvas/frontend/canvasTasksApi.ts b/products/canvas/frontend/canvasTasksApi.ts
index 4269a3841ba9..aac671676cb3 100644
--- a/products/canvas/frontend/canvasTasksApi.ts
+++ b/products/canvas/frontend/canvasTasksApi.ts
@@ -9,7 +9,11 @@ import {
tasksRunCreate,
tasksRunsCommandCreate,
} from 'products/tasks/frontend/generated/api'
-import type { ChannelDTOApi, TaskDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'
+import type {
+ ChannelDTOApi,
+ ChannelListResponseApi,
+ TaskDetailDTOApi,
+} from 'products/tasks/frontend/generated/api.schemas'
import { canvasesVersionsRetrieve } from './generated/api'
import type { CanvasApi } from './generated/api.schemas'
@@ -42,13 +46,13 @@ export function isTerminalRunStatus(status: string | null | undefined): boolean
return !!status && TERMINAL_RUN_STATUSES.has(status)
}
-function toSpaces(response: unknown): CanvasSpace[] {
- const rows = Array.isArray(response) ? response : ((response as { results?: unknown[] })?.results ?? [])
- return (rows as Record<string, unknown>[]).map((row) => ({
+function toSpaces(response: ChannelListResponseApi): CanvasSpace[] {
+ const rows = Array.isArray(response) ? response : response.results
+ return rows.map((row) => ({
id: String(row.id),
- name: String(row.name ?? ''),
- system_role: row.system_role === 'personal' || row.system_role === 'general' ? row.system_role : null,
- channel_type: String(row.channel_type ?? ''),
+ name: row.name ?? '',
+ system_role: row.system_role ?? null,
+ channel_type: row.channel_type ?? '',
}))
}
diff --git a/products/cohorts/frontend/generated/api.schemas.ts b/products/cohorts/frontend/generated/api.schemas.ts
index 9f1bae2b7771..c6fb99fdc612 100644
--- a/products/cohorts/frontend/generated/api.schemas.ts
+++ b/products/cohorts/frontend/generated/api.schemas.ts
@@ -615,6 +615,84 @@ export interface CohortUsedInWorkflowsBlockApi {
has_more: boolean
}
+export interface CohortCalculationHistoryApi {
+ readonly id: string
+ /** Cohort filters/properties at time of calculation */
+ filters: unknown
+ /**
+ * Number of people in cohort
+ * @minimum 0
+ * @maximum 2147483647
+ * @nullable
+ */
+ count?: number | null
+ /** When calculation started */
+ started_at?: string
+ /**
+ * When calculation finished
+ * @nullable
+ */
+ finished_at?: string | null
+ /** Array of query information (query, query_id, query_ms, memory_mb, read_rows, written_rows) */
+ queries?: unknown
+ /**
+ * Error message if calculation failed
+ * @nullable
+ */
+ error?: string | null
+ /**
+ * Calculate duration in seconds if both start and end times are available
+ * @nullable
+ */
+ readonly duration_seconds: number | null
+ /** Check if calculation is completed (successfully or with error) */
+ readonly is_completed: boolean
+ /** Check if calculation completed successfully */
+ readonly is_successful: boolean
+ /**
+ * Get total query duration across all queries
+ * @nullable
+ */
+ readonly total_query_ms: number | null
+ /**
+ * Get total memory usage across all queries
+ * @nullable
+ */
+ readonly total_memory_mb: number | null
+ /**
+ * Get total rows read across all queries
+ * @nullable
+ */
+ readonly total_read_rows: number | null
+ /**
+ * Get total rows written across all queries
+ * @nullable
+ */
+ readonly total_written_rows: number | null
+ /**
+ * Get the main query (first query in the array)
+ * @nullable
+ */
+ readonly main_query: string | null
+}
+
+export interface CohortCalculationHistoryResponseApi {
+ /** Calculation runs on this page, newest first. */
+ results: CohortCalculationHistoryApi[]
+ /** Number of calculation runs recorded for the cohort. */
+ count: number
+ /**
+ * Query string for the next page, such as `?limit=100&offset=100`, or null.
+ * @nullable
+ */
+ next: string | null
+ /**
+ * Query string for the previous page, or null on the first page.
+ * @nullable
+ */
+ previous: string | null
+}
+
/**
* The actor's properties.
*/
@@ -824,6 +902,20 @@ export type CohortsActivityRetrieveParams = {
page?: number
}
+export type CohortsCalculationHistoryRetrieveParams = {
+ /**
+ * Number of calculation runs to return. Defaults to 100, at most 500.
+ * @minimum 1
+ * @maximum 500
+ */
+ limit?: number
+ /**
+ * Number of calculation runs to skip. Defaults to 0.
+ * @minimum 0
+ */
+ offset?: number
+}
+
export type CohortsPersonsRetrieveParams = {
format?: CohortsPersonsRetrieveFormat
/**
diff --git a/products/cohorts/frontend/generated/api.ts b/products/cohorts/frontend/generated/api.ts
index 00246ec08315..f7dd68410c28 100644
--- a/products/cohorts/frontend/generated/api.ts
+++ b/products/cohorts/frontend/generated/api.ts
@@ -11,10 +11,12 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
import type {
ActivityLogPaginatedResponseApi,
CohortApi,
+ CohortCalculationHistoryResponseApi,
CohortPersonsResponseApi,
CohortUsedInResponseApi,
CohortUsedInWorkflowsBlockApi,
CohortsActivityRetrieveParams,
+ CohortsCalculationHistoryRetrieveParams,
CohortsListParams,
CohortsPersonsRetrieveParams,
CohortsStaffListParams,
@@ -305,19 +307,39 @@ export const cohortsBlockingWorkflowsRetrieve = async (
})
}
-export const getCohortsCalculationHistoryRetrieveUrl = (projectId: string, id: number) => {
- return `/api/projects/${projectId}/cohorts/${id}/calculation_history/`
+export const getCohortsCalculationHistoryRetrieveUrl = (
+ projectId: string,
+ id: number,
+ params?: CohortsCalculationHistoryRetrieveParams
+) => {
+ const normalizedParams = new URLSearchParams()
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : String(value))
+ }
+ })
+
+ const stringifiedParams = normalizedParams.toString()
+
+ return stringifiedParams.length > 0
+ ? `/api/projects/${projectId}/cohorts/${id}/calculation_history/?${stringifiedParams}`
+ : `/api/projects/${projectId}/cohorts/${id}/calculation_history/`
}
export const cohortsCalculationHistoryRetrieve = async (
projectId: string,
id: number,
+ params?: CohortsCalculationHistoryRetrieveParams,
options?: RequestInit
-): Promise<void> => {
- return apiMutator<void>(getCohortsCalculationHistoryRetrieveUrl(projectId, id), {
- ...options,
- method: 'GET',
- })
+): Promise<CohortCalculationHistoryResponseApi> => {
+ return apiMutator<CohortCalculationHistoryResponseApi>(
+ getCohortsCalculationHistoryRetrieveUrl(projectId, id, params),
+ {
+ ...options,
+ method: 'GET',
+ }
+ )
}
export const getCohortsPersonsRetrieveUrl = (projectId: string, id: number, params?: CohortsPersonsRetrieveParams) => {
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 23372b354cc5..d6ae1db51e75 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -10866,15 +10866,6 @@ export interface DataColorThemeApi {
readonly created_by: UserBasicApi
}
-export interface PaginatedDataColorThemeListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
- results: DataColorThemeApi[]
-}
-
export interface PatchedDataColorThemeApi {
readonly id?: number
/** @maxLength 100 */
@@ -11458,14 +11449,3 @@ export const DashboardsWidgetCatalogRetrieveWidgetTypeItem = {
SessionReplayList: 'session_replay_list',
SurveyResults: 'survey_results',
} as const
-
-export type DataColorThemesListParams = {
- /**
- * Number of results to return per page.
- */
- limit?: number
- /**
- * The initial index from which to return the results.
- */
- offset?: number
-}
diff --git a/products/dashboards/frontend/generated/api.ts b/products/dashboards/frontend/generated/api.ts
index 7bc7c6ef587d..85ac02272e38 100644
--- a/products/dashboards/frontend/generated/api.ts
+++ b/products/dashboards/frontend/generated/api.ts
@@ -49,12 +49,10 @@ import type {
DashboardsWidgetCatalogRetrieveParams,
DashboardsWidgetsBatchCreateParams,
DataColorThemeApi,
- DataColorThemesListParams,
DeleteTileRequestApi,
MoveTileRequestApi,
PaginatedDashboardBasicListApi,
PaginatedDashboardTemplateListApi,
- PaginatedDataColorThemeListApi,
PatchedDashboardTemplateApi,
PatchedDataColorThemeApi,
PatchedMoveTileRequestApi,
@@ -1108,28 +1106,12 @@ export const dashboardsWidgetCatalogRetrieve = async (
})
}
-export const getDataColorThemesListUrl = (projectId: string, params?: DataColorThemesListParams) => {
- const normalizedParams = new URLSearchParams()
-
- Object.entries(params || {}).forEach(([key, value]) => {
- if (value !== undefined) {
- normalizedParams.append(key, value === null ? 'null' : String(value))
- }
- })
-
- const stringifiedParams = normalizedParams.toString()
-
- return stringifiedParams.length > 0
- ? `/api/projects/${projectId}/data_color_themes/?${stringifiedParams}`
- : `/api/projects/${projectId}/data_color_themes/`
+export const getDataColorThemesListUrl = (projectId: string) => {
+ return `/api/projects/${projectId}/data_color_themes/`
}
-export const dataColorThemesList = async (
- projectId: string,
- params?: DataColorThemesListParams,
- options?: RequestInit
-): Promise<PaginatedDataColorThemeListApi> => {
- return apiMutator<PaginatedDataColorThemeListApi>(getDataColorThemesListUrl(projectId, params), {
+export const dataColorThemesList = async (projectId: string, options?: RequestInit): Promise<DataColorThemeApi[]> => {
+ return apiMutator<DataColorThemeApi[]>(getDataColorThemesListUrl(projectId), {
...options,
method: 'GET',
})
diff --git a/products/logs/backend/presentation/views/api.py b/products/logs/backend/presentation/views/api.py
index 9534d5ada73c..9923683000aa 100644
--- a/products/logs/backend/presentation/views/api.py
+++ b/products/logs/backend/presentation/views/api.py
@@ -347,6 +347,11 @@ def _session_scope_field(noun: str) -> serializers.CharField:
)
+# The query action uses _LOGS_QUERY_SERVER_DEFAULT_LIMIT when the body omits limit, and caps larger values.
+_LOGS_QUERY_MAX_LIMIT = 2000
+_LOGS_QUERY_SERVER_DEFAULT_LIMIT = 1000
+
+
class _LogsQueryBodySerializer(serializers.Serializer):
dateRange = _DateRangeSerializer(
required=False,
@@ -377,7 +382,12 @@ class _LogsQueryBodySerializer(serializers.Serializer):
"or a filter group object with nested AND/OR groups."
),
)
- limit = serializers.IntegerField(required=False, default=100, help_text="Max results (1-1000).")
+ limit = serializers.IntegerField(
+ required=False,
+ default=100,
+ min_value=1,
+ help_text=f"Max results. Values above {_LOGS_QUERY_MAX_LIMIT} are capped at {_LOGS_QUERY_MAX_LIMIT}.",
+ )
after = serializers.CharField(required=False, help_text="Pagination cursor from previous response.")
excludeAttributes = serializers.BooleanField(
required=False,
@@ -399,6 +409,11 @@ class _LogsQueryBodySerializer(serializers.Serializer):
sessionId = _session_scope_field("results")
+class _LogsBodyLimitSerializer(serializers.Serializer):
+ # Validates only the limit key of a raw query body; the other keys pass through untouched.
+ limit = serializers.IntegerField(required=False, allow_null=True, min_value=1, help_text="Max results.")
+
+
class _LogsQueryRequestSerializer(serializers.Serializer):
query = _LogsQueryBodySerializer(help_text="The logs query to execute.")
@@ -1603,8 +1618,10 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
except (KeyError, ValueError, json.JSONDecodeError):
pass # Invalid cursor format, continue with original date range
- limit = query_data.get("limit")
- requested_limit = min(1000 if limit is None else limit, 2000)
+ paging = _LogsBodyLimitSerializer(data=query_data)
+ paging.is_valid(raise_exception=True)
+ limit = paging.validated_data.get("limit")
+ requested_limit = min(_LOGS_QUERY_SERVER_DEFAULT_LIMIT if limit is None else limit, _LOGS_QUERY_MAX_LIMIT)
logs_query_params = {
"dateRange": date_range,
"severityLevels": query_data.get("severityLevels", []),
@@ -2053,13 +2070,17 @@ class LogsViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet):
else:
group_bys = [(query_data.get("groupBy", ""), query_data.get("groupBySource", "log"))]
+ paging = _LogsBodyLimitSerializer(data=query_data)
+ paging.is_valid(raise_exception=True)
+ limit = paging.validated_data.get("limit")
+
try:
runner = LogsGroupByQueryRunner(
team=self.team,
query=query,
group_bys=group_bys,
order_groups_by=query_data.get("orderGroupsBy", "log_count"),
- group_limit=int(query_data.get("limit", DEFAULT_GROUP_LIMIT)),
+ group_limit=DEFAULT_GROUP_LIMIT if limit is None else limit,
)
except (ValueError, TypeError) as e:
return Response({"error": str(e)}, status=status.HTTP_400_BAD_REQUEST)
diff --git a/products/logs/backend/test/test_logs_query_runner.py b/products/logs/backend/test/test_logs_query_runner.py
index c897b462c5a7..a135823fbcd1 100644
--- a/products/logs/backend/test/test_logs_query_runner.py
+++ b/products/logs/backend/test/test_logs_query_runner.py
@@ -644,6 +644,23 @@ class TestLogsQueryRunner(ClickhouseTestMixin, APIBaseTest):
self.assertEqual(len(response["results"]), 51)
self.assertFalse(response["hasMore"])
+ @parameterized.expand(
+ [
+ ("query_string", "query", "abc"),
+ ("query_negative", "query", -1),
+ ("group_by_string", "group-by", "abc"),
+ ("group_by_zero", "group-by", 0),
+ ]
+ )
+ def test_logs_rejects_a_bad_limit(self, _name: str, action: str, limit: str | int) -> None:
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/logs/{action}",
+ data={"query": {"dateRange": {"date_from": "-1h"}, "limit": limit}},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.content)
+ self.assertEqual(response.json()["attr"], "limit")
+
@time_machine.travel("2025-12-16T10:33:00Z", tick=False)
def test_logs_slicing(self):
# should slice the query, only return 100 results first time, then get the rest
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index 28805dadb27f..4c3c65ffaa9a 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -2651,7 +2651,10 @@ export interface _LogsQueryBodyApi {
searchTerm?: string
/** Property filters for the query. Pass a list of filters, which are all combined with AND, or a filter group object with nested AND/OR groups. */
filterGroup?: LogsFilterGroupInputApi
- /** Max results (1-1000). */
+ /**
+ * Max results. Values above 2000 are capped at 2000.
+ * @minimum 1
+ */
limit?: number
/** Pagination cursor from previous response. */
after?: string
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index 184e6daaa3be..4b787c3dcb5b 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -1729,6 +1729,7 @@ export const LogsPatternsDiffCreateBody = /* @__PURE__ */ zod.object({
export const logsQueryCreateBodyQueryOneSeverityLevelsDefault = []
export const logsQueryCreateBodyQueryOneServiceNamesDefault = []
export const logsQueryCreateBodyQueryOneLimitDefault = 100
+
export const logsQueryCreateBodyQueryOneExcludeAttributesDefault = false
export const logsQueryCreateBodyQueryOneCustomColumnsDefault = []
@@ -1893,7 +1894,11 @@ export const LogsQueryCreateBody = /* @__PURE__ */ zod.object({
.describe(
'Property filters for the query. Pass a list of filters, which are all combined with AND, or a filter group object with nested AND\/OR groups.'
),
- limit: zod.number().default(logsQueryCreateBodyQueryOneLimitDefault).describe('Max results (1-1000).'),
+ limit: zod
+ .number()
+ .min(1)
+ .default(logsQueryCreateBodyQueryOneLimitDefault)
+ .describe('Max results. Values above 2000 are capped at 2000.'),
after: zod.string().optional().describe('Pagination cursor from previous response.'),
excludeAttributes: zod
.boolean()
diff --git a/products/replay/frontend/generated/api.schemas.ts b/products/replay/frontend/generated/api.schemas.ts
index 554e0b7a4056..0085bd196e65 100644
--- a/products/replay/frontend/generated/api.schemas.ts
+++ b/products/replay/frontend/generated/api.schemas.ts
@@ -271,13 +271,15 @@ export interface SessionRecordingApi {
readonly event_count: number | null
}
-export interface PaginatedSessionRecordingListApi {
- count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
+export interface SessionRecordingListResponseApi {
+ /** Recordings on this page. */
results: SessionRecordingApi[]
+ /** Whether more recordings match the query after this page. */
+ has_next: boolean
+ /** Version of the listing response format. */
+ version: number
+ /** Cursor for the next page. Send it back as `after` to load the next page. Absent when the query does not page by cursor or there is no next page. */
+ next_cursor?: string
}
export type PatchedSessionRecordingApiExternalReferencesItem = { [key: string]: unknown }
diff --git a/products/replay/frontend/generated/api.ts b/products/replay/frontend/generated/api.ts
index 28bb8ac8a3ec..43f65a9cb37c 100644
--- a/products/replay/frontend/generated/api.ts
+++ b/products/replay/frontend/generated/api.ts
@@ -9,7 +9,6 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'
* OpenAPI spec version: 1.0.0
*/
import type {
- PaginatedSessionRecordingListApi,
PaginatedSessionRecordingPlaylistListApi,
PatchedSessionRecordingApi,
PatchedSessionRecordingPlaylistApi,
@@ -17,6 +16,7 @@ import type {
SessionRecordingBulkDeleteRequestApi,
SessionRecordingBulkDeleteResponseApi,
SessionRecordingConsoleLogsResponseApi,
+ SessionRecordingListResponseApi,
SessionRecordingPlaylistApi,
SessionRecordingPlaylistsListParams,
SessionRecordingsConsoleLogsRetrieveParams,
@@ -246,8 +246,8 @@ export const sessionRecordingsList = async (
projectId: string,
params?: SessionRecordingsListParams,
options?: RequestInit
-): Promise<PaginatedSessionRecordingListApi> => {
- return apiMutator<PaginatedSessionRecordingListApi>(getSessionRecordingsListUrl(projectId, params), {
+): Promise<SessionRecordingListResponseApi> => {
+ return apiMutator<SessionRecordingListResponseApi>(getSessionRecordingsListUrl(projectId, params), {
...options,
method: 'GET',
})
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index e709ab7c7a86..3f8ae282c668 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -2466,6 +2466,22 @@ class ChannelSerializer(DataclassSerializer):
]
+class ChannelPageSerializer(serializers.Serializer):
+ count = serializers.IntegerField(help_text="Number of channels the requester can access.")
+ next = serializers.URLField(allow_null=True, help_text="URL of the next page, or null on the last page.")
+ previous = serializers.URLField(allow_null=True, help_text="URL of the previous page, or null on the first page.")
+ results = ChannelSerializer(many=True, help_text="Channels on this page.")
+
+
+# The channel list is an array without `limit` and a page with `limit`, so its schema is one of the two.
+ChannelListResponseSerializer = PolymorphicProxySerializer(
+ component_name="ChannelListResponse",
+ serializers=[ChannelSerializer(many=True), ChannelPageSerializer],
+ resource_type_field_name=None,
+ many=False,
+)
+
+
class ChannelContributorsSerializer(DataclassSerializer):
"""The people who own at least one task or canvas in a channel."""
diff --git a/products/tasks/backend/presentation/views/channels_api.py b/products/tasks/backend/presentation/views/channels_api.py
index 04685b759b7d..98115ae8d680 100644
--- a/products/tasks/backend/presentation/views/channels_api.py
+++ b/products/tasks/backend/presentation/views/channels_api.py
@@ -38,6 +38,7 @@ from products.tasks.backend.presentation.serializers import (
ChannelFeedMessageWriteSerializer,
ChannelInstructionsSerializer,
ChannelInstructionsWriteSerializer,
+ ChannelListResponseSerializer,
ChannelMembersWriteSerializer,
ChannelSerializer,
ChannelSetupResponseSerializer,
@@ -136,7 +137,12 @@ class ChannelViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
return authenticator.access_token.sandbox_task_id
@extend_schema(
- responses={200: OpenApiResponse(response=ChannelSerializer(many=True), description="List of channels")},
+ responses={
+ 200: OpenApiResponse(
+ response=ChannelListResponseSerializer,
+ description="An array of channels without limit, or a page of channels with limit",
+ )
+ },
summary="List channels",
description=(
"List channels the requester can access, sorted by name and ID. "
diff --git a/products/tasks/frontend/generated/api.schemas.ts b/products/tasks/frontend/generated/api.schemas.ts
index 89d8154d01b5..276851afc257 100644
--- a/products/tasks/frontend/generated/api.schemas.ts
+++ b/products/tasks/frontend/generated/api.schemas.ts
@@ -490,15 +490,25 @@ export interface ChannelDTOApi {
readonly system_role: ChannelSystemRoleEnumApi | null
}
-export interface PaginatedChannelDTOListApi {
+export interface ChannelPageApi {
+ /** Number of channels the requester can access. */
count: number
- /** @nullable */
- next?: string | null
- /** @nullable */
- previous?: string | null
+ /**
+ * URL of the next page, or null on the last page.
+ * @nullable
+ */
+ next: string | null
+ /**
+ * URL of the previous page, or null on the first page.
+ * @nullable
+ */
+ previous: string | null
+ /** Channels on this page. */
results: ChannelDTOApi[]
}
+export type ChannelListResponseApi = ChannelDTOApi[] | ChannelPageApi
+
/**
* * `public` - public
* * `private` - private
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index bba97877bcc2..48eb7e628894 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -16,6 +16,7 @@ import type {
ChannelFeedMessageWriteApi,
ChannelInstructionsDTOApi,
ChannelInstructionsWriteApi,
+ ChannelListResponseApi,
ChannelMembersWriteApi,
ChannelSetupWriteApi,
ChannelStarWriteApi,
@@ -28,7 +29,6 @@ import type {
OnboardingSessionApi,
OnboardingSessionTestApi,
OnboardingSessionTestResponseApi,
- PaginatedChannelDTOListApi,
PaginatedChannelFeedMessageDTOListApi,
PaginatedChannelInstructionsDTOListApi,
PaginatedSandboxCustomImageDTOListApi,
@@ -592,8 +592,8 @@ export const taskChannelsList = async (
projectId: string,
params?: TaskChannelsListParams,
options?: RequestInit
-): Promise<PaginatedChannelDTOListApi> => {
- return apiMutator<PaginatedChannelDTOListApi>(getTaskChannelsListUrl(projectId, params), {
+): Promise<ChannelListResponseApi> => {
+ return apiMutator<ChannelListResponseApi>(getTaskChannelsListUrl(projectId, params), {
...options,
method: 'GET',
})
diff --git a/products/tracing/backend/presentation/views.py b/products/tracing/backend/presentation/views.py
index 82ae52990bca..5e79a6da957f 100644
--- a/products/tracing/backend/presentation/views.py
+++ b/products/tracing/backend/presentation/views.py
@@ -13,7 +13,7 @@ No business logic here - that belongs in logic.py via the facade.
import json
import base64
from collections.abc import Callable
-from typing import cast
+from typing import Any, cast
from django.db import models
@@ -289,6 +289,15 @@ class _TracingQueryBodySerializer(serializers.Serializer):
)
+class _TracingBodyPagingSerializer(serializers.Serializer):
+ # Validates only the paging keys of a raw query body; the other keys pass through untouched.
+ limit = serializers.IntegerField(required=False, allow_null=True, min_value=1, help_text="Max results.")
+ offset = serializers.IntegerField(required=False, allow_null=True, min_value=0, help_text="Pagination offset.")
+ prefetchSpans = serializers.IntegerField(
+ required=False, allow_null=True, min_value=1, help_text="Number of child spans to prefetch per trace."
+ )
+
+
class _TracingQueryRequestSerializer(serializers.Serializer):
query = _TracingQueryBodySerializer(help_text="The tracing spans query to execute.")
@@ -505,7 +514,7 @@ class _TracingErrorCountsResponseSerializer(serializers.Serializer):
class _TracingAttributesQuerySerializer(_TracingDateQueryParamsSerializer):
- search = serializers.CharField(required=False, help_text="Search filter for attribute names.")
+ search = serializers.CharField(required=False, allow_blank=True, help_text="Search filter for attribute names.")
search_values = serializers.BooleanField(
required=False,
default=False,
@@ -517,9 +526,11 @@ class _TracingAttributesQuerySerializer(_TracingDateQueryParamsSerializer):
help_text='Type of attributes: "span_attribute" for span-level attributes, "span_resource_attribute" for resource-level attributes.',
)
limit = serializers.IntegerField(
- required=False, min_value=1, max_value=100, help_text="Max results (default: 100)."
+ required=False, default=100, min_value=1, max_value=100, help_text="Max results (default: 100)."
+ )
+ offset = serializers.IntegerField(
+ required=False, default=0, min_value=0, help_text="Pagination offset (default: 0)."
)
- offset = serializers.IntegerField(required=False, min_value=0, help_text="Pagination offset (default: 0).")
class _TracingAttributeEntrySerializer(serializers.Serializer):
@@ -556,11 +567,13 @@ class _TracingValuesQuerySerializer(_TracingDateQueryParamsSerializer):
required=False,
help_text='Type of attribute: "span" for built-in span fields (e.g. name), "span_attribute" for span-level attributes, "span_resource_attribute" for resource-level attributes.',
)
- value = serializers.CharField(required=False, help_text="Search filter for attribute values.")
+ value = serializers.CharField(required=False, allow_blank=True, help_text="Search filter for attribute values.")
limit = serializers.IntegerField(
- required=False, min_value=1, max_value=100, help_text="Max results (default: 100)."
+ required=False, default=100, min_value=1, max_value=100, help_text="Max results (default: 100)."
+ )
+ offset = serializers.IntegerField(
+ required=False, default=0, min_value=0, help_text="Pagination offset (default: 0)."
)
- offset = serializers.IntegerField(required=False, min_value=0, help_text="Pagination offset (default: 0).")
class _CompareFilterSerializer(serializers.Serializer):
@@ -1377,11 +1390,14 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
if order_direction not in ("ASC", "DESC"):
order_direction = "DESC"
- offset = query_data.get("offset") or 0
- requested_limit = min(query_data.get("limit", 100), 1000)
- prefetch_spans = query_data.get("prefetchSpans", None)
+ paging = _TracingBodyPagingSerializer(data=query_data)
+ paging.is_valid(raise_exception=True)
+ offset = paging.validated_data.get("offset") or 0
+ limit = paging.validated_data.get("limit")
+ requested_limit = min(100 if limit is None else limit, 1000)
+ prefetch_spans = paging.validated_data.get("prefetchSpans")
if prefetch_spans is not None:
- prefetch_spans = min(int(prefetch_spans), 100)
+ prefetch_spans = min(prefetch_spans, 100)
flat_spans = bool(query_data.get("flatSpans", False))
filter_group = (
@@ -1433,7 +1449,7 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
else:
descending = order_direction == "DESC"
sort_key = "trace_duration" if by_duration else "trace_start"
- trace_keys: dict[str, object] = {span["trace_id"]: span[sort_key] for span in all_results}
+ trace_keys: dict[str, Any] = {span["trace_id"]: span[sort_key] for span in all_results}
ordered_traces = sorted(
trace_keys.items(),
@@ -1988,7 +2004,9 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
except (ValidationError, ValueError, ParseError):
filter_group = None
- offset = max(int(query_data.get("offset") or 0), 0)
+ trace_request = _TracingTraceRequestSerializer(data=query_data)
+ trace_request.is_valid(raise_exception=True)
+ offset: int = trace_request.validated_data.get("offset", 0)
# The waterfall loads a trace one page at a time, earliest spans first, with infinite scroll
# fetching the next page. Order by start time ASC so a page is the first N spans by start
@@ -2097,8 +2115,10 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
tag_queries(product=ProductKey.TRACING, feature=Feature.QUERY)
search = request.GET.get("search", "")
search_values = request.GET.get("search_values", "false").lower() == "true"
- limit = int(request.GET.get("limit", "100"))
- offset = int(request.GET.get("offset", "0"))
+ params = _TracingAttributesQuerySerializer(data=request.GET)
+ params.is_valid(raise_exception=True)
+ limit: int = params.validated_data["limit"]
+ offset: int = params.validated_data["offset"]
date_range = self.get_model(_date_range_from_query_params(request), DateRange)
@@ -2127,8 +2147,10 @@ class SpansViewSet(TeamAndOrgViewSetMixin, PydanticModelMixin, viewsets.ViewSet)
return Response({"error": "key is required"}, status=status.HTTP_400_BAD_REQUEST)
search = request.GET.get("value", "")
- limit = int(request.GET.get("limit", "100"))
- offset = int(request.GET.get("offset", "0"))
+ params = _TracingValuesQuerySerializer(data=request.GET)
+ params.is_valid(raise_exception=True)
+ limit: int = params.validated_data["limit"]
+ offset: int = params.validated_data["offset"]
date_range = self.get_model(_date_range_from_query_params(request), DateRange)
diff --git a/products/tracing/backend/tests/test_span_endpoint_errors.py b/products/tracing/backend/tests/test_span_endpoint_errors.py
index 31977617a7c5..80425fad7d94 100644
--- a/products/tracing/backend/tests/test_span_endpoint_errors.py
+++ b/products/tracing/backend/tests/test_span_endpoint_errors.py
@@ -95,3 +95,39 @@ class TestSpanCountErrorHandling(APIBaseTest):
format="json",
)
self.assertEqual(response.status_code, 400, response.content)
+
+ @parameterized.expand(
+ [
+ ("query_string_limit", "post", "query/", {"query": {"limit": "abc"}}),
+ ("query_string_prefetch_spans", "post", "query/", {"query": {"prefetchSpans": "abc"}}),
+ ("query_negative_prefetch_spans", "post", "query/", {"query": {"prefetchSpans": -5}}),
+ ("query_negative_offset", "post", "query/", {"query": {"offset": -1}}),
+ ("trace_string_offset", "post", "trace/abcdef/", {"offset": "abc"}),
+ ("trace_negative_offset", "post", "trace/abcdef/", {"offset": -1}),
+ ("attributes_string_limit", "get", "attributes/", {"limit": "abc"}),
+ ("attributes_limit_over_max", "get", "attributes/", {"limit": "1000000"}),
+ ("attributes_negative_offset", "get", "attributes/", {"offset": "-1"}),
+ ("values_string_offset", "get", "values/", {"key": "http.method", "offset": "abc"}),
+ ("values_limit_over_max", "get", "values/", {"key": "http.method", "limit": "101"}),
+ ]
+ )
+ def test_rejects_bad_paging_params(self, _name: str, method: str, path: str, data: dict) -> None:
+ url = f"/api/projects/{self.team.id}/tracing/spans/{path}"
+ if method == "post":
+ response = self.client.post(url, data, format="json")
+ else:
+ response = self.client.get(url, data)
+ self.assertEqual(response.status_code, 400, response.content)
+
+ @parameterized.expand(
+ [
+ ("attributes", "attributes/", {"search": ""}, "run_attribute_names_query", ([], 0)),
+ ("values", "values/", {"key": "http.method", "value": ""}, "run_attribute_values_query", []),
+ ]
+ )
+ def test_accepts_a_blank_search(self, _name: str, path: str, params: dict, runner: str, runner_result) -> None:
+ with patch(f"products.tracing.backend.presentation.views.{runner}", return_value=runner_result) as run:
+ response = self.client.get(f"/api/projects/{self.team.id}/tracing/spans/{path}", params)
+
+ self.assertEqual(response.status_code, 200, response.content)
+ self.assertEqual(run.call_args.kwargs["search"], "")
diff --git a/products/tracing/frontend/generated/api.schemas.ts b/products/tracing/frontend/generated/api.schemas.ts
index 27aa6b1034f5..11adc4ed820d 100644
--- a/products/tracing/frontend/generated/api.schemas.ts
+++ b/products/tracing/frontend/generated/api.schemas.ts
@@ -1570,7 +1570,6 @@ export type TracingSpansAttributesRetrieveParams = {
offset?: number
/**
* Search filter for attribute names.
- * @minLength 1
*/
search?: string
/**
@@ -1653,7 +1652,6 @@ export type TracingSpansValuesRetrieveParams = {
offset?: number
/**
* Search filter for attribute values.
- * @minLength 1
*/
value?: string
}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index f87693b32d1c..0b31c9dc7b27 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -4740,6 +4740,13 @@ export namespace Schemas {
properties?: (EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter | CohortPropertyFilter)[] | null;
}
+ export interface ActionListResponse {
+ /** Number of actions that match the filters. Without `limit`, it is `offset` plus the number of actions returned. */
+ count: number;
+ /** Actions on this page, or every matching action without `limit`. */
+ results: Action[];
+ }
+
export interface ActionReference {
/** Resource type: insight, experiment, cohort, or hog_function */
type: string;
@@ -24119,6 +24126,25 @@ export namespace Schemas {
base_version?: number | null;
}
+ export interface ChannelPage {
+ /** Number of channels the requester can access. */
+ count: number;
+ /**
+ * URL of the next page, or null on the last page.
+ * @nullable
+ */
+ next: string | null;
+ /**
+ * URL of the previous page, or null on the first page.
+ * @nullable
+ */
+ previous: string | null;
+ /** Channels on this page. */
+ results: ChannelDTO[];
+ }
+
+ export type ChannelListResponse = ChannelDTO[] | ChannelPage;
+
export interface ChannelMembersWrite {
/**
* Required list of member user IDs. This list replaces the current members. The creator remains a member. Send an empty list to remove all other members. Each submitted user must have project access.
@@ -25493,6 +25519,84 @@ export namespace Schemas {
_create_static_person_ids?: string[];
}
+ export interface CohortCalculationHistory {
+ readonly id: string;
+ /** Cohort filters/properties at time of calculation */
+ filters: unknown;
+ /**
+ * Number of people in cohort
+ * @minimum 0
+ * @maximum 2147483647
+ * @nullable
+ */
+ count?: number | null;
+ /** When calculation started */
+ started_at?: string;
+ /**
+ * When calculation finished
+ * @nullable
+ */
+ finished_at?: string | null;
+ /** Array of query information (query, query_id, query_ms, memory_mb, read_rows, written_rows) */
+ queries?: unknown;
+ /**
+ * Error message if calculation failed
+ * @nullable
+ */
+ error?: string | null;
+ /**
+ * Calculate duration in seconds if both start and end times are available
+ * @nullable
+ */
+ readonly duration_seconds: number | null;
+ /** Check if calculation is completed (successfully or with error) */
+ readonly is_completed: boolean;
+ /** Check if calculation completed successfully */
+ readonly is_successful: boolean;
+ /**
+ * Get total query duration across all queries
+ * @nullable
+ */
+ readonly total_query_ms: number | null;
+ /**
+ * Get total memory usage across all queries
+ * @nullable
+ */
+ readonly total_memory_mb: number | null;
+ /**
+ * Get total rows read across all queries
+ * @nullable
+ */
+ readonly total_read_rows: number | null;
+ /**
+ * Get total rows written across all queries
+ * @nullable
+ */
+ readonly total_written_rows: number | null;
+ /**
+ * Get the main query (first query in the array)
+ * @nullable
+ */
+ readonly main_query: string | null;
+ }
+
+ export interface CohortCalculationHistoryResponse {
+ /** Calculation runs on this page, newest first. */
+ results: CohortCalculationHistory[];
+ /** Number of calculation runs recorded for the cohort. */
+ count: number;
+ /**
+ * Query string for the next page, such as `?limit=100&offset=100`, or null.
+ * @nullable
+ */
+ next: string | null;
+ /**
+ * Query string for the previous page, or null on the first page.
+ * @nullable
+ */
+ previous: string | null;
+ }
+
/**
* Minimal serializer for cohort references, read by the person cohorts endpoint.
*/
@@ -77380,15 +77484,6 @@ export namespace Schemas {
results: AccountTrackRuleRunView[];
}
- export interface PaginatedActionList {
- count: number;
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
- results: Action[];
- }
-
export interface PaginatedActivityLogList {
/** @nullable */
next?: string | null;
@@ -77612,15 +77707,6 @@ export namespace Schemas {
results: ChangeRequest[];
}
- export interface PaginatedChannelDTOList {
- count: number;
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
- results: ChannelDTO[];
- }
-
export interface PaginatedChannelFeedMessageDTOList {
count: number;
/** @nullable */
@@ -77851,15 +77937,6 @@ export namespace Schemas {
results: DataCatalogRelationshipProposal[];
}
- export interface PaginatedDataColorThemeList {
- count: number;
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
- results: DataColorTheme[];
- }
-
export interface PaginatedDataDeletionRequestList {
count: number;
/** @nullable */
@@ -80461,76 +80538,6 @@ export namespace Schemas {
results: SessionRecordingExternalRef[];
}
- export type SessionRecordingExternalReferencesItem = { [key: string]: unknown };
-
- export interface SessionRecording {
- readonly id: string;
- /** @nullable */
- readonly distinct_id: string | null;
- readonly viewed: boolean;
- readonly viewers: readonly string[];
- readonly recording_duration: number;
- /** @nullable */
- readonly active_seconds: number | null;
- /** @nullable */
- readonly inactive_seconds: number | null;
- /** @nullable */
- readonly start_time: string | null;
- /** @nullable */
- readonly end_time: string | null;
- /** @nullable */
- readonly click_count: number | null;
- /** @nullable */
- readonly keypress_count: number | null;
- /** @nullable */
- readonly mouse_activity_count: number | null;
- /** @nullable */
- readonly console_log_count: number | null;
- /** @nullable */
- readonly console_warn_count: number | null;
- /** @nullable */
- readonly console_error_count: number | null;
- /** @nullable */
- readonly start_url: string | null;
- person?: MinimalPerson;
- /** @nullable */
- readonly retention_period_days: number | null;
- /** @nullable */
- readonly expiry_time: string | null;
- /** @nullable */
- readonly recording_ttl: number | null;
- /** @nullable */
- readonly snapshot_source: string | null;
- /** @nullable */
- readonly snapshot_library: string | null;
- readonly ongoing: boolean;
- /** @nullable */
- readonly activity_score: number | null;
- /** Load external references (linked issues) for this recording */
- readonly external_references: readonly SessionRecordingExternalReferencesItem[];
- /** Whether this recording matched the filters of the listing query that returned it. False only when a recording requested via session_recording_id was included despite not matching the filters. */
- readonly matches_filters: boolean;
- /**
- * Total stored size of the recording's snapshot data in bytes. Only populated when the recording's metadata is loaded, e.g. on retrieve; null in list responses.
- * @nullable
- */
- readonly total_size: number | null;
- /**
- * Number of captured rrweb events in the recording. Only populated when the recording's metadata is loaded, e.g. on retrieve; null in list responses.
- * @nullable
- */
- readonly event_count: number | null;
- }
-
- export interface PaginatedSessionRecordingList {
- count: number;
- /** @nullable */
- next?: string | null;
- /** @nullable */
- previous?: string | null;
- results: SessionRecording[];
- }
-
/**
* * `collection` - Collection
* * `filters` - Filters
@@ -111443,6 +111450,67 @@ export namespace Schemas {
date_to: string;
}
+ export type SessionRecordingExternalReferencesItem = { [key: string]: unknown };
+
+ export interface SessionRecording {
+ readonly id: string;
+ /** @nullable */
+ readonly distinct_id: string | null;
+ readonly viewed: boolean;
+ readonly viewers: readonly string[];
+ readonly recording_duration: number;
+ /** @nullable */
+ readonly active_seconds: number | null;
+ /** @nullable */
+ readonly inactive_seconds: number | null;
+ /** @nullable */
+ readonly start_time: string | null;
+ /** @nullable */
+ readonly end_time: string | null;
+ /** @nullable */
+ readonly click_count: number | null;
+ /** @nullable */
+ readonly keypress_count: number | null;
+ /** @nullable */
+ readonly mouse_activity_count: number | null;
+ /** @nullable */
+ readonly console_log_count: number | null;
+ /** @nullable */
+ readonly console_warn_count: number | null;
+ /** @nullable */
+ readonly console_error_count: number | null;
+ /** @nullable */
+ readonly start_url: string | null;
+ person?: MinimalPerson;
+ /** @nullable */
+ readonly retention_period_days: number | null;
+ /** @nullable */
+ readonly expiry_time: string | null;
+ /** @nullable */
+ readonly recording_ttl: number | null;
+ /** @nullable */
+ readonly snapshot_source: string | null;
+ /** @nullable */
+ readonly snapshot_library: string | null;
+ readonly ongoing: boolean;
+ /** @nullable */
+ readonly activity_score: number | null;
+ /** Load external references (linked issues) for this recording */
+ readonly external_references: readonly SessionRecordingExternalReferencesItem[];
+ /** Whether this recording matched the filters of the listing query that returned it. False only when a recording requested via session_recording_id was included despite not matching the filters. */
+ readonly matches_filters: boolean;
+ /**
+ * Total stored size of the recording's snapshot data in bytes. Only populated when the recording's metadata is loaded, e.g. on retrieve; null in list responses.
+ * @nullable
+ */
+ readonly total_size: number | null;
+ /**
+ * Number of captured rrweb events in the recording. Only populated when the recording's metadata is loaded, e.g. on retrieve; null in list responses.
+ * @nullable
+ */
+ readonly event_count: number | null;
+ }
+
export interface SessionRecordingBulkDeleteRequest {
/**
* Session IDs of the recordings to delete (max 100 per call).
@@ -111494,6 +111562,17 @@ export namespace Schemas {
logs_expired: boolean;
}
+ export interface SessionRecordingListResponse {
+ /** Recordings on this page. */
+ results: SessionRecording[];
+ /** Whether more recordings match the query after this page. */
+ has_next: boolean;
+ /** Version of the listing response format. */
+ version: number;
+ /** Cursor for the next page. Send it back as `after` to load the next page. Absent when the query does not page by cursor or there is no next page. */
+ next_cursor?: string;
+ }
+
export type SessionReplayListWidgetCatalogEntryOpenApiWidgetType = typeof SessionReplayListWidgetCatalogEntryOpenApiWidgetType[keyof typeof SessionReplayListWidgetCatalogEntryOpenApiWidgetType];
@@ -127413,7 +127492,10 @@ export namespace Schemas {
searchTerm?: string;
/** Property filters for the query. Pass a list of filters, which are all combined with AND, or a filter group object with nested AND/OR groups. */
filterGroup?: LogsFilterGroupInput;
- /** Max results (1-1000). */
+ /**
+ * Max results. Values above 2000 are capped at 2000.
+ * @minimum 1
+ */
limit?: number;
/** Pagination cursor from previous response. */
after?: string;
@@ -132721,6 +132803,20 @@ export namespace Schemas {
page?: number;
};
+ export type CohortsCalculationHistoryRetrieveParams = {
+ /**
+ * Number of calculation runs to return. Defaults to 100, at most 500.
+ * @minimum 1
+ * @maximum 500
+ */
+ limit?: number;
+ /**
+ * Number of calculation runs to skip. Defaults to 0.
+ * @minimum 0
+ */
+ offset?: number;
+ };
+
export type CohortsPersonsRetrieveParams = {
format?: CohortsPersonsRetrieveFormat;
/**
@@ -133837,17 +133933,6 @@ export namespace Schemas {
table_name?: string;
};
- export type DataColorThemesListParams = {
- /**
- * Number of results to return per page.
- */
- limit?: number;
- /**
- * The initial index from which to return the results.
- */
- offset?: number;
- };
-
export type DataDeletionRequestsListParams = {
/**
* Number of results to return per page.
@@ -143975,7 +144060,6 @@ export namespace Schemas {
offset?: number;
/**
* Search filter for attribute names.
- * @minLength 1
*/
search?: string;
/**
@@ -144058,7 +144142,6 @@ export namespace Schemas {
offset?: number;
/**
* Search filter for attribute values.
- * @minLength 1
*/
value?: string;
};
diff --git a/services/mcp/src/generated/logs/api.ts b/services/mcp/src/generated/logs/api.ts
index 25e7f1169703..a7d61589f5d9 100644
--- a/services/mcp/src/generated/logs/api.ts
+++ b/services/mcp/src/generated/logs/api.ts
@@ -6581,6 +6581,7 @@ export const LogsQueryCreateParams = () => zod.object({
export const logsQueryCreateBodyQueryOneSeverityLevelsDefault = []
export const logsQueryCreateBodyQueryOneServiceNamesDefault = []
export const logsQueryCreateBodyQueryOneLimitDefault = 100
+
export const logsQueryCreateBodyQueryOneExcludeAttributesDefault = false
export const logsQueryCreateBodyQueryOneCustomColumnsDefault = []
@@ -6745,7 +6746,11 @@ export const LogsQueryCreateBody = () => zod.object({
.describe(
'Property filters for the query. Pass a list of filters, which are all combined with AND, or a filter group object with nested AND\/OR groups.'
),
- limit: zod.number().default(logsQueryCreateBodyQueryOneLimitDefault).describe('Max results (1-1000).'),
+ limit: zod
+ .number()
+ .min(1)
+ .default(logsQueryCreateBodyQueryOneLimitDefault)
+ .describe('Max results. Values above 2000 are capped at 2000.'),
after: zod.string().optional().describe('Pagination cursor from previous response.'),
excludeAttributes: zod
.boolean()
diff --git a/services/mcp/src/generated/tracing/api.ts b/services/mcp/src/generated/tracing/api.ts
index 0f4ae969a66a..5e08307c37c7 100644
--- a/services/mcp/src/generated/tracing/api.ts
+++ b/services/mcp/src/generated/tracing/api.ts
@@ -293,8 +293,10 @@ export const TracingSpansAttributesRetrieveParams = () => zod.object({
),
})
+export const tracingSpansAttributesRetrieveQueryLimitDefault = 100
export const tracingSpansAttributesRetrieveQueryLimitMax = 100
+export const tracingSpansAttributesRetrieveQueryOffsetDefault = 0
export const tracingSpansAttributesRetrieveQueryOffsetMin = 0
export const tracingSpansAttributesRetrieveQuerySearchValuesDefault = false
@@ -319,14 +321,14 @@ export const TracingSpansAttributesRetrieveQueryParams = () => zod.object({
.number()
.min(1)
.max(tracingSpansAttributesRetrieveQueryLimitMax)
- .optional()
+ .default(tracingSpansAttributesRetrieveQueryLimitDefault)
.describe('Max results (default: 100).'),
offset: zod
.number()
.min(tracingSpansAttributesRetrieveQueryOffsetMin)
- .optional()
+ .default(tracingSpansAttributesRetrieveQueryOffsetDefault)
.describe('Pagination offset (default: 0).'),
- search: zod.string().min(1).optional().describe('Search filter for attribute names.'),
+ search: zod.string().optional().describe('Search filter for attribute names.'),
search_values: zod
.boolean()
.default(tracingSpansAttributesRetrieveQuerySearchValuesDefault)
@@ -1176,8 +1178,10 @@ export const TracingSpansValuesRetrieveParams = () => zod.object({
),
})
+export const tracingSpansValuesRetrieveQueryLimitDefault = 100
export const tracingSpansValuesRetrieveQueryLimitMax = 100
+export const tracingSpansValuesRetrieveQueryOffsetDefault = 0
export const tracingSpansValuesRetrieveQueryOffsetMin = 0
export const TracingSpansValuesRetrieveQueryParams = () => zod.object({
@@ -1201,12 +1205,12 @@ export const TracingSpansValuesRetrieveQueryParams = () => zod.object({
.number()
.min(1)
.max(tracingSpansValuesRetrieveQueryLimitMax)
- .optional()
+ .default(tracingSpansValuesRetrieveQueryLimitDefault)
.describe('Max results (default: 100).'),
offset: zod
.number()
.min(tracingSpansValuesRetrieveQueryOffsetMin)
- .optional()
+ .default(tracingSpansValuesRetrieveQueryOffsetDefault)
.describe('Pagination offset (default: 0).'),
- value: zod.string().min(1).optional().describe('Search filter for attribute values.'),
+ value: zod.string().optional().describe('Search filter for attribute values.'),
})
diff --git a/services/mcp/src/tools/generated/actions.ts b/services/mcp/src/tools/generated/actions.ts
index eaefb454b609..289f357fd4b1 100644
--- a/services/mcp/src/tools/generated/actions.ts
+++ b/services/mcp/src/tools/generated/actions.ts
@@ -144,14 +144,14 @@ const ActionsGetAllSchema = () => {
const actionsGetAll = (): ToolBase<
ReturnType<typeof ActionsGetAllSchema>,
- WithPostHogUrl<Schemas.PaginatedActionList>
+ WithPostHogUrl<Schemas.ActionListResponse>
> =>
withUiApp('action-list', {
name: 'actions-get-all',
schema: ActionsGetAllSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof ActionsGetAllSchema>>) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.PaginatedActionList>({
+ const result = await context.api.request<Schemas.ActionListResponse>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/actions/`,
query: {
diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.ts
index 6df98b01405c..ef7118dbe601 100644
--- a/services/mcp/src/tools/generated/tasks.ts
+++ b/services/mcp/src/tools/generated/tasks.ts
@@ -110,12 +110,12 @@ const ChannelListSchema = () => {
return TaskChannelsListQueryParams
}
-const channelList = (): ToolBase<ReturnType<typeof ChannelListSchema>, Schemas.PaginatedChannelDTOList> => ({
+const channelList = (): ToolBase<ReturnType<typeof ChannelListSchema>, Schemas.ChannelListResponse> => ({
name: 'channel-list',
schema: ChannelListSchema(),
handler: async (context: Context, params: z.infer<ReturnType<typeof ChannelListSchema>>) => {
const projectId = await context.stateManager.getProjectId()
- const result = await context.api.request<Schemas.PaginatedChannelDTOList>({
+ const result = await context.api.request<Schemas.ChannelListResponse>({
method: 'GET',
path: `/api/projects/${encodeURIComponent(String(projectId))}/task_channels/`,
query: {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attribute-values-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attribute-values-list.json
index 581cd6be2fce..d3fddb15e0bd 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attribute-values-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attribute-values-list.json
@@ -27,19 +27,20 @@
"type": "string"
},
"limit": {
+ "default": 100,
"description": "Max results (default: 100).",
"maximum": 100,
"minimum": 1,
"type": "number"
},
"offset": {
+ "default": 0,
"description": "Pagination offset (default: 0).",
"minimum": 0,
"type": "number"
},
"value": {
"description": "Search filter for attribute values.",
- "minLength": 1,
"type": "string"
}
},
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attributes-list.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attributes-list.json
index 454dc07a66e3..a48da22ea81d 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attributes-list.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/apm-attributes-list.json
@@ -22,19 +22,20 @@
"type": "string"
},
"limit": {
+ "default": 100,
"description": "Max results (default: 100).",
"maximum": 100,
"minimum": 1,
"type": "number"
},
"offset": {
+ "default": 0,
"description": "Pagination offset (default: 0).",
"minimum": 0,
"type": "number"
},
"search": {
"description": "Search filter for attribute names.",
- "minLength": 1,
"type": "string"
},
"search_values": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.json
index 345b117bf122..d32c644641c3 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/query-logs.json
@@ -171,7 +171,8 @@
},
"limit": {
"default": 100,
- "description": "Max results (1-1000).",
+ "description": "Max results. Values above 2000 are capped at 2000.",
+ "minimum": 1,
"type": "number"
},
"orderBy": {