Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/sentry/seer/endpoints/seer_rpc.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
rpc_get_trace_for_transaction,
rpc_get_transactions_for_project,
)
from sentry.seer.explorer.tools import execute_trace_query_chart, execute_trace_query_table
from sentry.seer.fetch_issues import by_error_type, by_function_name, by_text_query, utils
from sentry.seer.seer_setup import get_seer_org_acknowledgement
from sentry.sentry_apps.tasks.sentry_apps import broadcast_webhooks_for_organization
Expand Down Expand Up @@ -234,6 +235,21 @@ def get_organization_slug(*, org_id: int) -> dict:
return {"slug": org.slug}


def get_organization_project_ids(*, org_id: int) -> dict:
"""Get all project IDs for an organization"""
from sentry.models.project import Project

try:
organization = Organization.objects.get(id=org_id)
except Organization.DoesNotExist:
return {"project_ids": []}

project_ids = list(
Project.objects.filter(organization=organization).values_list("id", flat=True)
)
return {"project_ids": project_ids}


def _can_use_prevent_ai_features(org: Organization) -> bool:
hide_ai_features = org.get_option("sentry:hide_ai_features", HIDE_AI_FEATURES_DEFAULT)
pr_review_test_generation_enabled = bool(
Expand Down Expand Up @@ -972,6 +988,7 @@ def send_seer_webhook(*, event_name: str, organization_id: int, payload: dict) -
# Common to Seer features
"get_organization_seer_consent_by_org_name": get_organization_seer_consent_by_org_name,
"get_github_enterprise_integration_config": get_github_enterprise_integration_config,
"get_organization_project_ids": get_organization_project_ids,
#
# Autofix
"get_organization_slug": get_organization_slug,
Expand Down Expand Up @@ -999,6 +1016,8 @@ def send_seer_webhook(*, event_name: str, organization_id: int, payload: dict) -
"get_trace_for_transaction": rpc_get_trace_for_transaction,
"get_profiles_for_trace": rpc_get_profiles_for_trace,
"get_issues_for_transaction": rpc_get_issues_for_transaction,
"execute_trace_query_chart": execute_trace_query_chart,
"execute_trace_query_table": execute_trace_query_table,
#
# Replays
"get_replay_summary_logs": rpc_get_replay_summary_logs,
Expand Down
135 changes: 135 additions & 0 deletions src/sentry/seer/explorer/tools.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import logging
from typing import Any

from sentry.api import client
from sentry.models.apikey import ApiKey
from sentry.models.organization import Organization
from sentry.snuba.referrer import Referrer

logger = logging.getLogger(__name__)


def execute_trace_query_chart(
*,
org_id: int,
query: str,
stats_period: str,
y_axes: list[str],
group_by: list[str] | None = None,
) -> dict[str, Any] | None:
"""
Execute a trace query to get chart/timeseries data by calling the events-stats endpoint.
"""
try:
organization = Organization.objects.get(id=org_id)
except Organization.DoesNotExist:
logger.warning("Organization not found", extra={"org_id": org_id})
return None

# Get all project IDs for the organization
project_ids = list(organization.project_set.values_list("id", flat=True))
if not project_ids:
logger.warning("No projects found for organization", extra={"org_id": org_id})
return None

params: dict[str, Any] = {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what do you think about moving more of this logic to the caller? so that way this can basically be a passthrough

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hmm to me this stuff feels like a lot of internal implementation of querying sentry data though, rather than stuff seer should worry about

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's transformations that seer needs to consume sentry data though right? shouldn't it live in seer? the more you can make this a passthrough interface, the easier it gets to add new ones if you need, IMO.

"query": query,
"statsPeriod": stats_period,
"yAxis": y_axes,
"project": project_ids,
"dataset": "spans",
"referrer": Referrer.SEER_RPC,
"transformAliasToInputFormat": "1", # Required for RPC datasets
}

# Add group_by if provided (for top events)
if group_by and len(group_by) > 0:
params["topEvents"] = 5
params["field"] = group_by
params["excludeOther"] = "0" # Include "Other" series

resp = client.get(
auth=ApiKey(organization_id=organization.id, scope_list=["org:read", "project:read"]),
user=None,
path=f"/organizations/{organization.slug}/events-stats/",
params=params,
)
data = resp.data

# Normalize response format: single-axis returns flat format, multi-axis returns nested
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also wondering if we can do this in the caller

# We always want the nested format {"metric": {"data": [...]}}
if isinstance(data, dict) and "data" in data and len(y_axes) == 1:
# Single axis response - wrap it
metric_name = y_axes[0]
return {metric_name: data}

return data


def execute_trace_query_table(
*,
org_id: int,
query: str,
stats_period: str,
sort: str,
group_by: list[str] | None = None,
y_axes: list[str] | None = None,
per_page: int = 50,
) -> dict[str, Any] | None:
"""
Execute a trace query to get table data by calling the events endpoint.
"""
try:
organization = Organization.objects.get(id=org_id)
except Organization.DoesNotExist:
logger.warning("Organization not found", extra={"org_id": org_id})
return None

# Get all project IDs for the organization
project_ids = list(organization.project_set.values_list("id", flat=True))
if not project_ids:
logger.warning("No projects found for organization", extra={"org_id": org_id})
return None

# Determine fields based on mode
if group_by and len(group_by) > 0:
# Aggregates mode: group_by fields + aggregate functions
fields = list(group_by)
if y_axes:
fields.extend(y_axes)
else:
# Samples mode: default span fields
fields = [
"id",
"span.op",
"span.description",
"span.duration",
"transaction",
"timestamp",
"project",
"project.name",
"trace",
]

params: dict[str, Any] = {
"query": query,
"statsPeriod": stats_period,
"field": fields,
"sort": sort if sort else ("-timestamp" if not group_by else None),
"per_page": per_page,
"project": project_ids,
"dataset": "spans",
"referrer": Referrer.SEER_RPC,
"transformAliasToInputFormat": "1", # Required for RPC datasets
}

# Remove None values
params = {k: v for k, v in params.items() if v is not None}

resp = client.get(
auth=ApiKey(organization_id=organization.id, scope_list=["org:read", "project:read"]),
user=None,
path=f"/organizations/{organization.slug}/events/",
params=params,
)
return resp.data
Loading
Loading