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 d2ff6c6028f9..fc8ca96cddb5 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 ( @@ -85,7 +86,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 @@ -590,7 +590,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 e7a0c2069f3e..50e6f2eab556 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__) @@ -175,7 +175,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 372ff8602ec8..c9feb49eaf49 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 @@ -63,7 +64,6 @@ from sentry.utils.cache import cache from sentry.utils.locking import UnableToAcquireLock from sentry.utils.settings import is_self_hosted -from sentry.utils.tracing import start_span logger = logging.getLogger(__name__) @@ -171,7 +171,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: @@ -355,8 +357,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 3d476d8aaddc..55fe1c2d44f1 100644 --- a/src/sentry/seer/autofix/on_completion_hook.py +++ b/src/sentry/seer/autofix/on_completion_hook.py @@ -7,6 +7,7 @@ from django.db import router, transaction from django.utils import timezone from pydantic import ValidationError +from sentry_sdk import traces from sentry import analytics, features from sentry.analytics.events.autofix_events import ( @@ -73,7 +74,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 metrics -from sentry.utils.tracing import start_span from sentry.viewer_context import get_viewer_context if TYPE_CHECKING: @@ -130,15 +130,14 @@ def execute(cls, organization: Organization, run_id: int) -> None: organization: The organization context run_id: The ID of the completed run """ - with ( - sentry_sdk.isolation_scope(), - start_span( + with sentry_sdk.isolation_scope(): + traces.new_trace() + with traces.start_span( name="autofix.on_completion_hook", - op="function", - transaction=True, - ), - ): - cls._execute(organization, run_id) + attributes={"sentry.op": "function"}, + parent_span=None, + ): + cls._execute(organization, run_id) @classmethod def _execute(cls, organization: Organization, run_id: int) -> None: diff --git a/src/sentry/seer/autofix/pr_iteration/check_suites.py b/src/sentry/seer/autofix/pr_iteration/check_suites.py index 37f75dacbd8c..883df6ffc24b 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, SeerUnavailableError from sentry.seer.models.run import SeerRun from sentry.utils import metrics -from sentry.utils.tracing import trace logger = logging.getLogger(__name__) @@ -346,7 +346,7 @@ class CheckSuiteAutofixRun: group_id: int -@trace +@traces.trace def resolve_check_suite_autofix_run( event: GithubCheckSuiteEvent, repositories: Sequence[Repository] | None = None ) -> CheckSuiteAutofixRun | None: @@ -597,7 +597,7 @@ def pr_iteration_enabled(organization: Organization) -> bool: ) -@trace +@traces.trace def resolve_green_check_suite( check_suite_event: CheckSuiteEvent, ) -> ResolvedGreenCheckSuite | None: @@ -728,7 +728,7 @@ def inspect_check_suite_head( ) -@trace +@traces.trace def confirm_green_check_suite( resolved: ResolvedGreenCheckSuite, ) -> GreenCheckSuiteContext | None: @@ -756,7 +756,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. @@ -847,7 +847,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 8c5654592d98..9078bb04aa09 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 ( @@ -43,7 +44,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) @@ -446,7 +446,7 @@ def record_pr_iteration_failure_reason( log_ctx.error("autofix.pr_iteration.details.failure_reason_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 1c05117b8525..8d561c4396e7 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 ( @@ -24,7 +25,6 @@ TriggerDecision, ) from sentry.utils import metrics -from sentry.utils.tracing import trace logger = logging.getLogger(__name__) @@ -163,7 +163,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 = check_suite_head_match(self.event, run_state) attempt_key = self.check_suite_attempt_key() @@ -199,7 +199,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: try: autofix_run = self.autofix_run 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 3be584ddb43a..ca2193415da9 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: @@ -127,37 +127,36 @@ def _retrigger_deferred_iteration( @scm_event_stream.listen_for(event_type="check_suite") def pr_iteration_from_check_suite_listener(check_suite_event: CheckSuiteEvent) -> None: """Drop suites we can't act on, then queue the rest for a task that can retry.""" - with ( - sentry_sdk.isolation_scope(), - start_span( + with sentry_sdk.isolation_scope(): + traces.new_trace() + with traces.start_span( name="pr_iteration.check_suite_listener", - op="function", - transaction=True, - ), - ): - if check_suite_event.action != "completed": - return None + attributes={"sentry.op": "function"}, + parent_span=None, + ): + if check_suite_event.action != "completed": + return None - conclusion = check_suite_event.check_suite["conclusion"] - is_green = conclusion in GREEN_CONCLUSIONS - if not is_green and conclusion not in FAILURE_CONCLUSIONS: - return None + conclusion = check_suite_event.check_suite["conclusion"] + is_green = conclusion in GREEN_CONCLUSIONS + if not is_green and conclusion not in FAILURE_CONCLUSIONS: + return None - # Drop suites nobody behind the installation can act on - gate_flags = GREEN_CHECK_SUITE_FLAGS if is_green else FAILING_CHECK_SUITE_FLAGS - if not resolve_check_suite_flag_gate( - check_suite_event, gate_flags - ).flagged_organization_ids: - return None + # Drop suites nobody behind the installation can act on + gate_flags = GREEN_CHECK_SUITE_FLAGS if is_green else FAILING_CHECK_SUITE_FLAGS + if not resolve_check_suite_flag_gate( + check_suite_event, gate_flags + ).flagged_organization_ids: + return None - # Lazy: the task module can't load while this listener registers in AppConfig.ready. - from sentry.scm.private.ipc import serialize_check_suite_event - from sentry.tasks.seer.pr_iteration import process_pr_iteration_check_suite + # Lazy: the task module can't load while this listener registers in AppConfig.ready. + from sentry.scm.private.ipc import serialize_check_suite_event + from sentry.tasks.seer.pr_iteration import process_pr_iteration_check_suite - process_pr_iteration_check_suite.delay( - event_data=serialize_check_suite_event(check_suite_event) - ) - return None + process_pr_iteration_check_suite.delay( + event_data=serialize_check_suite_event(check_suite_event) + ) + return None def process_check_suite_event(check_suite_event: CheckSuiteEvent) -> None: diff --git a/src/sentry/seer/autofix/pr_iteration/missing_permissions.py b/src/sentry/seer/autofix/pr_iteration/missing_permissions.py index 04ef4f254ec8..69ec5d6eae27 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 ( @@ -56,7 +57,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" @@ -249,7 +249,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 3525d19bba7d..3b79b7f8529f 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 b4beca2ffac1..7e7839ea102c 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 @@ -73,7 +74,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__) @@ -280,7 +280,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, @@ -318,7 +318,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 88c93dbc43a0..9b92ec300271 100644 --- a/src/sentry/seer/endpoints/seer_rpc.py +++ b/src/sentry/seer/endpoints/seer_rpc.py @@ -25,6 +25,7 @@ from rest_framework.response import Response from sentry_protos.snuba.v1.endpoint_trace_item_details_pb2 import TraceItemDetailsRequest from sentry_protos.snuba.v1.request_common_pb2 import RequestMeta, TraceItemType +from sentry_sdk import traces from sentry import features from sentry.api.api_owners import ApiOwner @@ -150,7 +151,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, @@ -272,7 +272,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, @@ -332,7 +332,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}") @@ -344,7 +344,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) @@ -482,7 +482,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, @@ -496,7 +496,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 0d0be01baf21..0b2df3e72001 100644 --- a/src/sentry/seer/signed_seer_api.py +++ b/src/sentry/seer/signed_seer_api.py @@ -7,11 +7,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, @@ -137,7 +137,7 @@ def _resolve_viewer_context( return replace(vc, organization_id=org_id, user_id=user_id) -@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 5cfde04df0e5..6c3f79f48d21 100644 --- a/src/sentry/tasks/seer/context_engine_index.py +++ b/src/sentry/tasks/seer/context_engine_index.py @@ -5,6 +5,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 @@ -50,7 +51,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 from sentry.viewer_context import ( ActorType, ViewerContext, @@ -111,21 +111,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) @@ -342,9 +342,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 1f8a3f006119..90190dda7bbd 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 @@ -22,7 +23,6 @@ from sentry.taskworker.namespaces import seer_tasks from sentry.utils.query import RangeQuerySetWrapper from sentry.utils.settings import is_self_hosted -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") @@ -72,8 +72,9 @@ def get_seer_explorer_enabled_projects() -> Generator[tuple[int, int]]: if bool(project.organization.get_option("sentry:hide_ai_features")): continue - 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) if batch_result: diff --git a/src/sentry/tasks/seer/pr_iteration.py b/src/sentry/tasks/seer/pr_iteration.py index 4da0845e1510..0a897d2ec98e 100644 --- a/src/sentry/tasks/seer/pr_iteration.py +++ b/src/sentry/tasks/seer/pr_iteration.py @@ -33,6 +33,7 @@ Review, ReviewComment, ) +from sentry_sdk import traces from taskbroker_client.retry import Retry from taskbroker_client.state import current_task @@ -120,7 +121,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__) @@ -198,7 +198,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, @@ -616,7 +616,7 @@ def _hand_off_exhausted_cap( ) -@trace +@traces.trace def _drain_queued_autofix_feedback( *, log_ctx: PrIterationLogContext, @@ -1353,21 +1353,21 @@ 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. """ - with ( - sentry_sdk.isolation_scope(), - start_span( + + with sentry_sdk.isolation_scope(): + traces.new_trace() + with traces.start_span( name="pr_iteration.trigger_from_comment", - op="function", - transaction=True, - ), - ): - _trigger_pr_iteration_from_comment( - organization_id=organization_id, - repo_id=repo_id, - integration_id=integration_id, - pr_number=pr_number, - feedback=feedback, - ) + attributes={"sentry.op": "function"}, + parent_span=None, + ): + _trigger_pr_iteration_from_comment( + organization_id=organization_id, + repo_id=repo_id, + integration_id=integration_id, + pr_number=pr_number, + feedback=feedback, + ) def _trigger_pr_iteration_from_comment( @@ -1729,25 +1729,25 @@ 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. """ - with ( - sentry_sdk.isolation_scope(), - start_span( + + with sentry_sdk.isolation_scope(): + traces.new_trace() + with traces.start_span( name="pr_iteration.trigger_from_review", - op="function", - transaction=True, - ), - ): - _trigger_pr_iteration_from_review( - organization_id=organization_id, - repo_id=repo_id, - integration_id=integration_id, - pr_number=pr_number, - review_id=review_id, - author_username=author_username, - author_external_id=author_external_id, - author_is_bot=author_is_bot, - delivery_authenticated=delivery_authenticated, - ) + attributes={"sentry.op": "function"}, + parent_span=None, + ): + _trigger_pr_iteration_from_review( + organization_id=organization_id, + repo_id=repo_id, + integration_id=integration_id, + pr_number=pr_number, + review_id=review_id, + author_username=author_username, + author_external_id=author_external_id, + author_is_bot=author_is_bot, + delivery_authenticated=delivery_authenticated, + ) def _trigger_pr_iteration_from_review(