From 1aeab30d4102f69d4147a4b244325398a7663a20 Mon Sep 17 00:00:00 2001 From: Alexander Alderman Webb Date: Thu, 17 Sep 2026 13:53:02 +0200 Subject: [PATCH] chore: Inline span-streaming branch of tracing shims in Seer files --- src/sentry/seer/agent/service_map_utils.py | 41 +++++++++++-------- src/sentry/seer/autofix/autofix.py | 8 ++-- src/sentry/seer/autofix/autofix_agent.py | 4 +- src/sentry/seer/autofix/commit_author.py | 4 +- src/sentry/seer/autofix/issue_summary.py | 11 +++-- src/sentry/seer/autofix/on_completion_hook.py | 17 ++++---- .../seer/autofix/pr_iteration/check_suites.py | 12 +++--- src/sentry/seer/autofix/pr_iteration/emit.py | 4 +- .../feedback_sources/check_suite.py | 6 +-- .../pr_iteration/listeners/check_suite.py | 11 ++--- .../pr_iteration/missing_permissions.py | 4 +- .../autofix/pr_iteration/ready_for_review.py | 4 +- .../autofix/pr_iteration/review_request.py | 4 +- .../seer/endpoints/organization_seer_rpc.py | 6 +-- src/sentry/seer/endpoints/seer_rpc.py | 14 ++++--- src/sentry/seer/signed_seer_api.py | 4 +- src/sentry/tasks/seer/context_engine_index.py | 20 +++++---- src/sentry/tasks/seer/explorer_index.py | 7 ++-- src/sentry/tasks/seer/pr_iteration.py | 20 +++++---- 19 files changed, 112 insertions(+), 89 deletions(-) diff --git a/src/sentry/seer/agent/service_map_utils.py b/src/sentry/seer/agent/service_map_utils.py index 9f4b1c93aaea..449b5d21c5cf 100644 --- a/src/sentry/seer/agent/service_map_utils.py +++ b/src/sentry/seer/agent/service_map_utils.py @@ -15,6 +15,7 @@ from typing import Any, cast import orjson +from sentry_sdk import traces from sentry import options from sentry.search.eap.types import SearchResolverConfig @@ -27,7 +28,6 @@ ) from sentry.snuba.referrer import Referrer from sentry.snuba.spans_rpc import Spans -from sentry.utils.tracing import set_span_data, start_span logger = logging.getLogger(__name__) @@ -79,10 +79,13 @@ def _process_rows(rows: list[dict]) -> None: # Broad scan: Org-wide — only segments WITH a parent (cross-project candidates). page_limit = min(_SNUBA_MAX_ROWS, max_segments) - with start_span( - op="explorer.service_map.broad_scan", name="explorer.service_map.broad_scan" + with traces.start_span( + name="explorer.service_map.broad_scan", + attributes={ + "sentry.op": "explorer.service_map.broad_scan", + "limit": page_limit, + }, ) as span: - set_span_data(span, "limit", page_limit) result = Spans.run_table_query( params=snuba_params, query_string="is_transaction:true has:parent_span", @@ -95,8 +98,8 @@ def _process_rows(rows: list[dict]) -> None: ) rows = result.get("data", []) _process_rows(rows) - set_span_data(span, "rows_returned", len(rows)) - set_span_data(span, "covered_projects", len(covered_project_ids)) + span.set_attribute("rows_returned", len(rows)) + span.set_attribute("covered_projects", len(covered_project_ids)) # Fallback scan: One scoped query for projects with no representation in the broad scan. # No has:parent_span filter — broad scan to give low-traffic projects a second chance. @@ -108,11 +111,14 @@ def _process_rows(rows: list[dict]) -> None: ) uncovered_params = dataclasses.replace(snuba_params, projects=uncovered) page_limit = min(_SNUBA_MAX_ROWS, max_segments) - with start_span( - op="explorer.service_map.fallback_scan", name="explorer.service_map.fallback_scan" + with traces.start_span( + name="explorer.service_map.fallback_scan", + attributes={ + "sentry.op": "explorer.service_map.fallback_scan", + "uncovered_projects": len(uncovered), + "limit": page_limit, + }, ) as span: - set_span_data(span, "uncovered_projects", len(uncovered)) - set_span_data(span, "limit", page_limit) result = Spans.run_table_query( params=uncovered_params, query_string="is_transaction:true", @@ -131,7 +137,7 @@ def _process_rows(rows: list[dict]) -> None: ) rows = result.get("data", []) _process_rows(rows) - set_span_data(span, "rows_returned", len(rows)) + span.set_attribute("rows_returned", len(rows)) unique_parent_span_ids = list(segments_by_parent.keys()) if not unique_parent_span_ids: @@ -143,11 +149,14 @@ def _process_rows(rows: list[dict]) -> None: edges_by_pair: dict[tuple[int, str, int, str], int] = defaultdict(int) batch_size = options.get("explorer.service_map.parent_span_batch_size") - with start_span( - op="explorer.service_map.resolve_parents", name="explorer.service_map.resolve_parents" + with traces.start_span( + name="explorer.service_map.resolve_parents", + attributes={ + "sentry.op": "explorer.service_map.resolve_parents", + "unique_parent_spans": len(unique_parent_span_ids), + "batch_count": math.ceil(len(unique_parent_span_ids) / batch_size), + }, ) as span: - set_span_data(span, "unique_parent_spans", len(unique_parent_span_ids)) - set_span_data(span, "batch_count", math.ceil(len(unique_parent_span_ids) / batch_size)) for i in range(0, len(unique_parent_span_ids), batch_size): batch = unique_parent_span_ids[i : i + batch_size] span_ids = ",".join(batch) @@ -179,7 +188,7 @@ def _process_rows(rows: list[dict]) -> None: segment["child_project_slug"], ) edges_by_pair[edge_key] += 1 - set_span_data(span, "edges_found", len(edges_by_pair)) + span.set_attribute("edges_found", len(edges_by_pair)) edges = [ { diff --git a/src/sentry/seer/autofix/autofix.py b/src/sentry/seer/autofix/autofix.py index 2bfbcb5c0686..d677a1e5187d 100644 --- a/src/sentry/seer/autofix/autofix.py +++ b/src/sentry/seer/autofix/autofix.py @@ -5,6 +5,8 @@ from datetime import datetime, timedelta from typing import Any +from sentry_sdk import traces + from sentry import tagstore from sentry.api.endpoints.organization_trace import OrganizationTraceEndpoint from sentry.constants import ObjectStatus @@ -15,7 +17,6 @@ from sentry.services.eventstore.models import Event, GroupEvent from sentry.snuba.referrer import Referrer from sentry.utils.concurrent import ContextPropagatingThreadPoolExecutor -from sentry.utils.tracing import start_span logger = logging.getLogger(__name__) @@ -88,8 +89,9 @@ def _fetch_trace(): } try: - with start_span( - op="seer.autofix.get_trace_tree_for_event", name="seer.autofix.get_trace_tree_for_event" + with traces.start_span( + name="seer.autofix.get_trace_tree_for_event", + attributes={"sentry.op": "seer.autofix.get_trace_tree_for_event"}, ): with ContextPropagatingThreadPoolExecutor() as executor: future = executor.submit(_fetch_trace) diff --git a/src/sentry/seer/autofix/autofix_agent.py b/src/sentry/seer/autofix/autofix_agent.py index b3806d927488..12a47b58c4e5 100644 --- a/src/sentry/seer/autofix/autofix_agent.py +++ b/src/sentry/seer/autofix/autofix_agent.py @@ -10,6 +10,7 @@ from pydantic import BaseModel from rest_framework.exceptions import PermissionDenied from scm.types import GetBranchProtocol, GetRepositoryProtocol +from sentry_sdk import traces from sentry import features, quotas from sentry.analytics.events.autofix_events import ( @@ -82,7 +83,6 @@ from sentry.sentry_apps.tasks.sentry_apps import broadcast_webhooks_for_organization from sentry.sentry_apps.utils.webhooks import SeerActionType from sentry.utils import json, metrics -from sentry.utils.tracing import trace if TYPE_CHECKING: from django.contrib.auth.models import AnonymousUser @@ -492,7 +492,7 @@ def _assert_existing_run_belongs_to_group(group: Group, run_id: int) -> None: raise SeerPermissionError(UNKNOWN_RUN_ID_FOR_GROUP) -@trace +@traces.trace def trigger_autofix_agent( group: Group, step: AutofixStep, diff --git a/src/sentry/seer/autofix/commit_author.py b/src/sentry/seer/autofix/commit_author.py index 68186e380f93..45ea4e42814a 100644 --- a/src/sentry/seer/autofix/commit_author.py +++ b/src/sentry/seer/autofix/commit_author.py @@ -6,6 +6,7 @@ from django.contrib.auth.models import AnonymousUser from django.db.models import Q +from sentry_sdk import traces from sentry.integrations.models.external_actor import ExternalActor from sentry.integrations.types import ExternalProviders @@ -23,7 +24,6 @@ from sentry.users.services.user.model import RpcUser from sentry.users.services.user.service import user_service from sentry.utils import json, metrics -from sentry.utils.tracing import trace logger = logging.getLogger(__name__) @@ -171,7 +171,7 @@ def _feedback_actor(source: FeedbackSourceBase) -> tuple[str, str] | None: return ("github", user.login.lstrip("@").lower()) -@trace +@traces.trace def commit_author_for_feedback( items: Sequence[Feedback], organization_id: int ) -> SeerCommitAuthor | None: diff --git a/src/sentry/seer/autofix/issue_summary.py b/src/sentry/seer/autofix/issue_summary.py index a502f9158851..b93bdc4115bd 100644 --- a/src/sentry/seer/autofix/issue_summary.py +++ b/src/sentry/seer/autofix/issue_summary.py @@ -8,6 +8,7 @@ import sentry_sdk from django.conf import settings from django.contrib.auth.models import AnonymousUser +from sentry_sdk import traces from taskbroker_client.retry import Retry from urllib3 import BaseHTTPResponse from urllib3.connectionpool import HTTPConnectionPool @@ -58,7 +59,6 @@ from sentry.users.services.user.model import RpcUser from sentry.utils.cache import cache from sentry.utils.locking import UnableToAcquireLock -from sentry.utils.tracing import start_span logger = logging.getLogger(__name__) @@ -165,7 +165,9 @@ def _trigger_autofix_task( sentry_sdk.capture_exception(e) return - with start_span(op="ai_summary.trigger_autofix", name="ai_summary.trigger_autofix"): + with traces.start_span( + name="ai_summary.trigger_autofix", attributes={"sentry.op": "ai_summary.trigger_autofix"} + ): try: group = Group.objects.get(id=group_id) except Group.DoesNotExist: @@ -349,8 +351,9 @@ def get_and_update_group_fixability_score( extra={"group_id": group.id}, ) - with start_span( - op="ai_summary.generate_fixability_score", name="ai_summary.generate_fixability_score" + with traces.start_span( + name="ai_summary.generate_fixability_score", + attributes={"sentry.op": "ai_summary.generate_fixability_score"}, ): issue_summary = _generate_fixability_score(group, summary=summary) diff --git a/src/sentry/seer/autofix/on_completion_hook.py b/src/sentry/seer/autofix/on_completion_hook.py index bfb8820dc538..2b16e9553fab 100644 --- a/src/sentry/seer/autofix/on_completion_hook.py +++ b/src/sentry/seer/autofix/on_completion_hook.py @@ -10,6 +10,7 @@ from django.utils import timezone from pydantic import ValidationError from scm.manager import SourceCodeManager +from sentry_sdk import traces from sentry import analytics, features from sentry.analytics.events.autofix_events import ( @@ -96,7 +97,6 @@ consume_queued_autofix_feedback, ) from sentry.utils import metrics -from sentry.utils.tracing import start_span, trace if TYPE_CHECKING: from sentry.seer.agent.client_models import SeerRunState @@ -198,12 +198,13 @@ def execute(cls, organization: Organization, run_id: int) -> None: organization: The organization context run_id: The ID of the completed run """ + traces.new_trace() with ( sentry_sdk.isolation_scope(), - start_span( + traces.start_span( name="autofix.on_completion_hook", - op="function", - transaction=True, + attributes={"sentry.op": "function"}, + parent_span=None, ), ): cls._execute(organization, run_id) @@ -443,7 +444,7 @@ def _repo_name_for_feedback( return None @classmethod - @trace + @traces.trace def _maybe_react_to_completed_iteration( cls, organization: Organization, @@ -1059,7 +1060,7 @@ def _maybe_continue_pipeline( ) @classmethod - @trace + @traces.trace def _consume_queued_feedback( cls, log_ctx: PrIterationLogContext, @@ -1211,7 +1212,7 @@ def _latest_iteration_touched_files( return bool(iteration_repos(iterations[-1])) @classmethod - @trace + @traces.trace def _pr_iteration_push_outcome( cls, log_ctx: PrIterationLogContext, @@ -1296,7 +1297,7 @@ def _pr_iteration_push_outcome( return None if pushed else PrIterationOutcome.PUSH_FAILED @classmethod - @trace + @traces.trace def _push_iteration_changes( cls, log_ctx: PrIterationLogContext, diff --git a/src/sentry/seer/autofix/pr_iteration/check_suites.py b/src/sentry/seer/autofix/pr_iteration/check_suites.py index d757c0b4f813..00a04e7fd77e 100644 --- a/src/sentry/seer/autofix/pr_iteration/check_suites.py +++ b/src/sentry/seer/autofix/pr_iteration/check_suites.py @@ -30,6 +30,7 @@ PaginationParams, PullRequest, ) +from sentry_sdk import traces from sentry import features from sentry.constants import ObjectStatus @@ -50,7 +51,6 @@ from sentry.seer.models import SeerApiError from sentry.seer.models.run import SeerRun from sentry.utils import metrics -from sentry.utils.tracing import trace logger = logging.getLogger(__name__) @@ -341,7 +341,7 @@ class CheckSuiteAutofixRun: group_id: int -@trace +@traces.trace def resolve_check_suite_autofix_run( event: GithubCheckSuiteEvent, repositories: Sequence[Repository] | None = None ) -> CheckSuiteAutofixRun | None: @@ -589,7 +589,7 @@ def pr_iteration_enabled(organization: Organization) -> bool: ) -@trace +@traces.trace def resolve_green_check_suite( check_suite_event: CheckSuiteEvent, ) -> ResolvedGreenCheckSuite | None: @@ -720,7 +720,7 @@ def inspect_check_suite_head( ) -@trace +@traces.trace def confirm_green_check_suite( resolved: ResolvedGreenCheckSuite, ) -> GreenCheckSuiteContext | None: @@ -748,7 +748,7 @@ def confirm_green_check_suite( ) -@trace +@traces.trace def should_defer_pr_iteration(resolved: ResolvedGreenCheckSuite) -> bool: """Whether a PR-iteration event on this head must leave a parked consume deferred. @@ -839,7 +839,7 @@ def record(self, *, outcome: str) -> None: ) -@trace +@traces.trace def sweep_check_runs( scm: SourceCodeManager, head_sha: str, *, log_extra: Mapping[str, object] ) -> CheckRunsSweep | None: diff --git a/src/sentry/seer/autofix/pr_iteration/emit.py b/src/sentry/seer/autofix/pr_iteration/emit.py index cdcee7699ba3..93f92d7efba2 100644 --- a/src/sentry/seer/autofix/pr_iteration/emit.py +++ b/src/sentry/seer/autofix/pr_iteration/emit.py @@ -22,6 +22,7 @@ from typing import TypeVar from django.utils import timezone +from sentry_sdk import traces from sentry import analytics from sentry.analytics.events.pr_iteration_events import ( @@ -47,7 +48,6 @@ from sentry.seer.autofix.pr_iteration.pause import PauseReason from sentry.seer.autofix.pr_iteration.tracing import set_pr_iteration_attributes from sentry.seer.models.run import SeerRun, SeerRunPrIteration -from sentry.utils.tracing import trace EventT = TypeVar("EventT", bound=analytics.Event) @@ -400,7 +400,7 @@ def record_pr_iteration_blocked( log_ctx.error("autofix.pr_iteration.details.blocked_failed") -@trace +@traces.trace def complete_pr_iteration_details( *, log_ctx: PrIterationLogContext, diff --git a/src/sentry/seer/autofix/pr_iteration/feedback_sources/check_suite.py b/src/sentry/seer/autofix/pr_iteration/feedback_sources/check_suite.py index 6a7aec48593e..a28e7a78da11 100644 --- a/src/sentry/seer/autofix/pr_iteration/feedback_sources/check_suite.py +++ b/src/sentry/seer/autofix/pr_iteration/feedback_sources/check_suite.py @@ -5,6 +5,7 @@ from typing import Any, Literal from pydantic import Field, PrivateAttr, root_validator +from sentry_sdk import traces from sentry.seer.agent.client_models import SeerRunState from sentry.seer.autofix.pr_iteration.check_suites import ( @@ -25,7 +26,6 @@ TriggerDecision, ) from sentry.utils import metrics -from sentry.utils.tracing import trace logger = logging.getLogger(__name__) @@ -178,7 +178,7 @@ def _live_head(self, run_state: SeerRunState) -> LivePullRequestHead: ) return LivePullRequestHead("unexpected_error") - @trace + @traces.trace def should_consume(self, run_state: SeerRunState) -> Decision: head_sha, repo_name, matched = self._matches_current_head(run_state) attempt_key = self.check_suite_attempt_key() @@ -214,7 +214,7 @@ def should_consume(self, run_state: SeerRunState) -> Decision: return Decision(ok=False, reason="live_head_mismatch") return Decision(ok=True, reason="head_matches") - @trace + @traces.trace def should_trigger(self, run_state: SeerRunState) -> TriggerDecision: from sentry.seer.autofix.pr_iteration.feedback import automated_iteration_cap_reached diff --git a/src/sentry/seer/autofix/pr_iteration/listeners/check_suite.py b/src/sentry/seer/autofix/pr_iteration/listeners/check_suite.py index ffc05be714c3..4b45db4d9243 100644 --- a/src/sentry/seer/autofix/pr_iteration/listeners/check_suite.py +++ b/src/sentry/seer/autofix/pr_iteration/listeners/check_suite.py @@ -3,6 +3,7 @@ import orjson import sentry_sdk from pydantic import ValidationError +from sentry_sdk import traces from sentry.scm.private.event_stream import scm_event_stream from sentry.scm.types import CheckSuiteEvent @@ -40,12 +41,11 @@ from sentry.seer.autofix.pr_iteration.review_request import request_review_from_context from sentry.seer.autofix.pr_iteration.run_markers import get_run_marker from sentry.utils import metrics -from sentry.utils.tracing import start_span, trace logger = logging.getLogger(__name__) -@trace +@traces.trace def _retrigger_deferred_iteration( log_ctx: PrIterationLogContext, resolved: ResolvedGreenCheckSuite ) -> None: @@ -126,12 +126,13 @@ def _retrigger_deferred_iteration( @scm_event_stream.listen_for(event_type="check_suite") def pr_iteration_from_check_suite_listener(check_suite_event: CheckSuiteEvent): + traces.new_trace() with ( sentry_sdk.isolation_scope(), - start_span( + traces.start_span( name="pr_iteration.check_suite_listener", - op="function", - transaction=True, + attributes={"sentry.op": "function"}, + parent_span=None, ), ): return _handle_check_suite_event(check_suite_event) diff --git a/src/sentry/seer/autofix/pr_iteration/missing_permissions.py b/src/sentry/seer/autofix/pr_iteration/missing_permissions.py index dae4618d3719..d776c2680a37 100644 --- a/src/sentry/seer/autofix/pr_iteration/missing_permissions.py +++ b/src/sentry/seer/autofix/pr_iteration/missing_permissions.py @@ -37,6 +37,7 @@ from django.utils import timezone from scm import actions as scm_actions from scm.types import CreatePullRequestCommentProtocol +from sentry_sdk import traces from sentry import analytics from sentry.analytics.events.pr_iteration_events import ( @@ -55,7 +56,6 @@ from sentry.seer.autofix.pr_iteration.run_markers import get_run_marker, record_run_marker from sentry.seer.models.run import SeerRun from sentry.utils import metrics -from sentry.utils.tracing import trace MISSING_PERMISSIONS_EXTRA = "missing_permissions" @@ -224,7 +224,7 @@ def _skip(log_ctx: PrIterationLogContext, reason: str, **log_fields: Any) -> Non log_ctx.info("autofix.pr_iteration.missing_permissions.skipped", reason=reason, **log_fields) -@trace +@traces.trace def block_iteration_for_missing_permissions( *, organization: Organization, diff --git a/src/sentry/seer/autofix/pr_iteration/ready_for_review.py b/src/sentry/seer/autofix/pr_iteration/ready_for_review.py index fc132fa40177..e0475c40ed3c 100644 --- a/src/sentry/seer/autofix/pr_iteration/ready_for_review.py +++ b/src/sentry/seer/autofix/pr_iteration/ready_for_review.py @@ -20,6 +20,7 @@ from django.utils import timezone from scm import actions as scm_actions from scm.types import MarkPullRequestDraftStateProtocol +from sentry_sdk import traces from sentry.locks import locks from sentry.models.group import Group @@ -31,7 +32,6 @@ from sentry.seer.models.run import SeerRun from sentry.utils import metrics from sentry.utils.locking import UnableToAcquireLock -from sentry.utils.tracing import trace logger = logging.getLogger(__name__) @@ -96,7 +96,7 @@ def _emit_ready_for_review_signal(ctx: GreenCheckSuiteContext) -> None: _failed("emit_ready_signal_failed", resolved.log_extra) -@trace +@traces.trace def mark_ready_for_review(ctx: GreenCheckSuiteContext) -> None: """Undraft the PR for ``ctx.head_sha``. diff --git a/src/sentry/seer/autofix/pr_iteration/review_request.py b/src/sentry/seer/autofix/pr_iteration/review_request.py index 2990968591f4..1401d15d2d57 100644 --- a/src/sentry/seer/autofix/pr_iteration/review_request.py +++ b/src/sentry/seer/autofix/pr_iteration/review_request.py @@ -33,6 +33,7 @@ from django.utils import timezone from scm import actions as scm_actions from scm.types import RequestReviewProtocol +from sentry_sdk import traces from sentry.locks import locks from sentry.seer.autofix.pr_iteration.check_suites import ( @@ -48,7 +49,6 @@ from sentry.seer.models.run import SeerRun from sentry.utils import metrics from sentry.utils.locking import UnableToAcquireLock -from sentry.utils.tracing import trace logger = logging.getLogger(__name__) @@ -128,7 +128,7 @@ def _record_review_request_skip_marker( ) -@trace +@traces.trace def request_review_from_context(ctx: GreenCheckSuiteContext) -> None: """Request review for an already-confirmed green tip (own lock + marker).""" resolved = ctx.resolved diff --git a/src/sentry/seer/endpoints/organization_seer_rpc.py b/src/sentry/seer/endpoints/organization_seer_rpc.py index 63a36ff2fa19..714523ac69b5 100644 --- a/src/sentry/seer/endpoints/organization_seer_rpc.py +++ b/src/sentry/seer/endpoints/organization_seer_rpc.py @@ -7,6 +7,7 @@ from rest_framework.exceptions import NotFound, ParseError, PermissionDenied, ValidationError from rest_framework.request import Request from rest_framework.response import Response +from sentry_sdk import traces from sentry import features from sentry.api.api_owners import ApiOwner @@ -74,7 +75,6 @@ from sentry.seer.fetch_issues import by_error_type, by_function_name, by_text_query, utils from sentry.utils import metrics from sentry.utils.env import in_test_environment -from sentry.utils.tracing import trace from sentry.viewer_context import get_viewer_context, observe_viewer_context_propagation logger = logging.getLogger(__name__) @@ -282,7 +282,7 @@ def _filter_issue_scoped_result(self, request: Request, method_name: str, result return result - @trace + @traces.trace def _dispatch_to_local_method( self, request: Request, @@ -320,7 +320,7 @@ def _dispatch_to_local_method( raise RpcResolutionException(f"Unknown method {method_name}") - @trace + @traces.trace def post(self, request: Request, organization: Organization, method_name: str) -> Response: sentry_sdk.set_tag("rpc.method", method_name) sentry_sdk.set_attribute("rpc.method", method_name) diff --git a/src/sentry/seer/endpoints/seer_rpc.py b/src/sentry/seer/endpoints/seer_rpc.py index 4743ec84b0c2..c877a7718d77 100644 --- a/src/sentry/seer/endpoints/seer_rpc.py +++ b/src/sentry/seer/endpoints/seer_rpc.py @@ -33,6 +33,7 @@ from sentry_protos.snuba.v1.request_common_pb2 import RequestMeta, TraceItemType from sentry_protos.snuba.v1.trace_item_attribute_pb2 import AttributeKey, AttributeValue, StrArray from sentry_protos.snuba.v1.trace_item_filter_pb2 import ComparisonFilter, TraceItemFilter +from sentry_sdk import traces from sentry import features from sentry.api.api_owners import ApiOwner @@ -166,7 +167,6 @@ from sentry.utils.env import in_test_environment from sentry.utils.groupreference import find_fix_statements from sentry.utils.snuba_rpc import SnubaRPCRateLimitExceeded -from sentry.utils.tracing import start_span, trace from sentry.viewer_context import ( get_viewer_context, observe_viewer_context_propagation, @@ -288,7 +288,7 @@ class SeerRpcServiceEndpoint(Endpoint): permission_classes = () enforce_rate_limit = False - @trace + @traces.trace def _is_authorized(self, request: Request) -> bool: return bool(request.auth) and isinstance( request.successful_authenticator, @@ -348,7 +348,7 @@ def _enforce_investigation_event_viewer_context( if viewer is None or viewer.organization_id != organization_id: raise PermissionDenied("Viewer context organization does not match request") - @trace + @traces.trace def _dispatch_to_local_method(self, method_name: str, arguments: dict[str, Any]) -> Any: if method_name not in seer_method_registry: raise RpcResolutionException(f"Unknown method {method_name}") @@ -360,7 +360,7 @@ def _dispatch_to_local_method(self, method_name: str, arguments: dict[str, Any]) return result.dict() return result - @trace + @traces.trace def post(self, request: Request, method_name: str) -> Response: sentry_sdk.set_tag("rpc.method", method_name) sentry_sdk.set_attribute("rpc.method", method_name) @@ -498,7 +498,7 @@ def get_organization_features( feature_set: set[str] = set() - with start_span(op="features.check", name="check batch features"): + with traces.start_span(name="check batch features", attributes={"sentry.op": "features.check"}): batch = features.batch_has( list(features_to_check), actor=actor, @@ -512,7 +512,9 @@ def get_organization_features( feature_set.add(name[len(_ORGANIZATION_SCOPE_PREFIX) :]) features_to_check.discard(name) - with start_span(op="features.check", name="check individual features"): + with traces.start_span( + name="check individual features", attributes={"sentry.op": "features.check"} + ): for name in features_to_check: if features.has(name, organization, actor=actor, skip_entity=True): feature_set.add(name[len(_ORGANIZATION_SCOPE_PREFIX) :]) diff --git a/src/sentry/seer/signed_seer_api.py b/src/sentry/seer/signed_seer_api.py index a08651f3293c..7aa4a8be55df 100644 --- a/src/sentry/seer/signed_seer_api.py +++ b/src/sentry/seer/signed_seer_api.py @@ -6,11 +6,11 @@ import orjson from django.conf import settings +from sentry_sdk import traces from urllib3 import BaseHTTPResponse, HTTPConnectionPool, Retry from sentry.net.http import connection_from_url from sentry.utils import metrics -from sentry.utils.tracing import trace from sentry.viewer_context import ( ViewerContext, encode_viewer_context, @@ -140,7 +140,7 @@ def _resolve_viewer_context( ) -@trace +@traces.trace def make_signed_seer_api_request( connection_pool: HTTPConnectionPool, path: str, diff --git a/src/sentry/tasks/seer/context_engine_index.py b/src/sentry/tasks/seer/context_engine_index.py index ad5a3cd987b2..8ee8adc3f2c1 100644 --- a/src/sentry/tasks/seer/context_engine_index.py +++ b/src/sentry/tasks/seer/context_engine_index.py @@ -4,6 +4,7 @@ from datetime import UTC, datetime, timedelta, timezone import sentry_sdk +from sentry_sdk import traces from taskbroker_client.retry import Retry from sentry import features, options @@ -49,7 +50,6 @@ from sentry.utils.hashlib import md5_text from sentry.utils.query import RangeQuerySetWrapper from sentry.utils.snuba_rpc import SnubaRPCRateLimitExceeded -from sentry.utils.tracing import start_span logger = logging.getLogger(__name__) @@ -93,21 +93,21 @@ def index_org_project_knowledge(org_id: int) -> None: ) return - with start_span( - op="explorer.context_engine.get_top_transactions_for_org_projects", + with traces.start_span( name="explorer.context_engine.get_top_transactions_for_org_projects", + attributes={"sentry.op": "explorer.context_engine.get_top_transactions_for_org_projects"}, ): transactions_by_project = get_top_transactions_for_org_projects( high_volume_projects, start, end ) - with start_span( - op="explorer.context_engine.get_top_span_ops_for_org_projects", + with traces.start_span( name="explorer.context_engine.get_top_span_ops_for_org_projects", + attributes={"sentry.op": "explorer.context_engine.get_top_span_ops_for_org_projects"}, ): span_ops_by_project = get_top_span_ops_for_org_projects(high_volume_projects, start, end) - with start_span( - op="explorer.context_engine.get_sdk_names_for_org_projects", + with traces.start_span( name="explorer.context_engine.get_sdk_names_for_org_projects", + attributes={"sentry.op": "explorer.context_engine.get_sdk_names_for_org_projects"}, ): sdk_names_by_project = get_sdk_names_for_org_projects(high_volume_projects, start, end) @@ -319,9 +319,11 @@ def get_allowed_org_ids_context_engine_indexing() -> list[int]: Only the bucket matching the current hour is checked for the seer-explorer-index feature flag, keeping feature check volume at ~1/24th of total orgs. """ - with start_span( - op="explorer.context_engine.get_allowed_org_ids_context_engine_indexing", + with traces.start_span( name="explorer.context_engine.get_allowed_org_ids_context_engine_indexing", + attributes={ + "sentry.op": "explorer.context_engine.get_allowed_org_ids_context_engine_indexing" + }, ): now = datetime.now(UTC) TOTAL_HOURLY_SLOTS = 24 diff --git a/src/sentry/tasks/seer/explorer_index.py b/src/sentry/tasks/seer/explorer_index.py index 2d5f6e7ade43..9c08af0e9825 100644 --- a/src/sentry/tasks/seer/explorer_index.py +++ b/src/sentry/tasks/seer/explorer_index.py @@ -6,6 +6,7 @@ from datetime import datetime, timedelta from django.utils import timezone as django_timezone +from sentry_sdk import traces from sentry import features, options from sentry.constants import ObjectStatus @@ -21,7 +22,6 @@ from sentry.tasks.utils import compute_delay from sentry.taskworker.namespaces import seer_tasks from sentry.utils.query import RangeQuerySetWrapper -from sentry.utils.tracing import start_span from sentry.viewer_context import ActorType, ViewerContext, viewer_context_scope logger = logging.getLogger("sentry.tasks.seer_explorer_indexer") @@ -70,8 +70,9 @@ def get_seer_explorer_enabled_projects() -> Generator[tuple[int, int]]: continue is_eligible = False - with start_span( - op="seer_explorer_index.has_feature", name="seer_explorer_index.has_feature" + with traces.start_span( + name="seer_explorer_index.has_feature", + attributes={"sentry.op": "seer_explorer_index.has_feature"}, ): batch_result = features.batch_has(FEATURE_NAMES, organization=project.organization) diff --git a/src/sentry/tasks/seer/pr_iteration.py b/src/sentry/tasks/seer/pr_iteration.py index 49742a49e172..71a00848983e 100644 --- a/src/sentry/tasks/seer/pr_iteration.py +++ b/src/sentry/tasks/seer/pr_iteration.py @@ -39,6 +39,7 @@ ReviewComment, ReviewThread, ) +from sentry_sdk import traces from taskbroker_client.retry import Retry from taskbroker_client.state import current_task @@ -123,7 +124,6 @@ from sentry.users.services.user.model import RpcUser from sentry.utils import metrics from sentry.utils.locking import UnableToAcquireLock -from sentry.utils.tracing import start_span, trace logger = logging.getLogger(__name__) @@ -191,7 +191,7 @@ def _organization_for_gate(run_id: int, organization_id: int) -> Organization | return None -@trace +@traces.trace def trigger_consume_pr_iteration_feedback( *, log_ctx: PrIterationLogContext, @@ -539,7 +539,7 @@ def _discard_iteration( ) -@trace +@traces.trace def _drain_queued_autofix_feedback( *, log_ctx: PrIterationLogContext, @@ -1258,12 +1258,13 @@ def trigger_pr_iteration_from_comment( four the flow is followed by, and it is joined to the others by the ids in ``pr_iteration.tracing`` rather than by the trace it was queued from. """ + traces.new_trace() with ( sentry_sdk.isolation_scope(), - start_span( + traces.start_span( name="pr_iteration.trigger_from_comment", - op="function", - transaction=True, + attributes={"sentry.op": "function"}, + parent_span=None, ), ): _trigger_pr_iteration_from_comment( @@ -1634,12 +1635,13 @@ def trigger_pr_iteration_from_review( four the flow is followed by, and it is joined to the others by the ids in ``pr_iteration.tracing`` rather than by the trace it was queued from. """ + traces.new_trace() with ( sentry_sdk.isolation_scope(), - start_span( + traces.start_span( name="pr_iteration.trigger_from_review", - op="function", - transaction=True, + attributes={"sentry.op": "function"}, + parent_span=None, ), ): _trigger_pr_iteration_from_review(