Skip to content
Open
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
6 changes: 6 additions & 0 deletions src/sentry/investigations/endpoints/serializers/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
__all__ = (
"InvestigationActionRequestSerializer",
"InvestigationActionRequestSerializerResponse",
"InvestigationBlockSerializer",
"InvestigationBlockSerializerResponse",
"InvestigationDetailsSerializer",
Expand All @@ -11,6 +13,10 @@
)


from .action_request import (
InvestigationActionRequestSerializer,
InvestigationActionRequestSerializerResponse,
)
from .block import InvestigationBlockSerializer, InvestigationBlockSerializerResponse
from .investigation import (
InvestigationDetailsSerializer,
Expand Down
142 changes: 142 additions & 0 deletions src/sentry/investigations/endpoints/serializers/action_request.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
from __future__ import annotations

from collections.abc import Mapping, MutableMapping, Sequence
from datetime import datetime
from typing import Any, TypedDict, override

from django.contrib.auth.models import AnonymousUser

from sentry.api.serializers import Serializer, register
from sentry.investigations.models import (
InvestigationActionRequest,
InvestigationActionRequestAnchorType,
InvestigationBlock,
)
from sentry.users.api.serializers.user import UserSerializerResponse
from sentry.users.models.user import User
from sentry.users.services.user.model import RpcUser
from sentry.users.services.user.serial import serialize_generic_user
from sentry.users.services.user.service import user_service


class InvestigationActionRequestAnchorResponse(TypedDict):
"""`id` is Seer's ID: a block's agent key or a hypothesis ID. `blockId` is the live block
it points to, if there is one.
"""

type: str
id: str
blockId: str | None


class InvestigationActionRequestSerializerResponse(TypedDict):
"""
A step Seer suggests. `primary` marks the recommended next step after a run, and `anchor`
puts a request under a block or hypothesis. `action` is null when it's only advice. What's
in `appliedDetails` depends on the action kind, and `appliedBy` is null when Sentry applied
it automatically.
"""

id: str
key: str
reportRevision: int
primary: bool
anchor: InvestigationActionRequestAnchorResponse | None
title: str
rationale: str
impact: str | None
state: str
reason: str | None
action: dict[str, Any] | None
appliedBy: UserSerializerResponse | None
appliedDetails: dict[str, Any] | None
dateApplied: datetime | None
error: dict[str, Any] | None
dateCreated: datetime


@register(InvestigationActionRequest)
class InvestigationActionRequestSerializer(
Serializer[InvestigationActionRequestSerializerResponse]
):
def _anchored_block_ids(
self, item_list: Sequence[InvestigationActionRequest]
) -> dict[tuple[int, str], str]:
keys = {
item.anchor_id
for item in item_list
if item.anchor_type == InvestigationActionRequestAnchorType.BLOCK and item.anchor_id
}
if not keys:
return {}
return {
(investigation_id, key): str(block_id)
for investigation_id, key, block_id in InvestigationBlock.objects.filter(
investigation_id__in={item.investigation_id for item in item_list},
stable_agent_key__in=keys,
deleted_at__isnull=True,
).values_list("investigation_id", "stable_agent_key", "id")
if key is not None
}

@override
def get_attrs(
self,
item_list: Sequence[InvestigationActionRequest],
user: User | RpcUser | AnonymousUser,
**kwargs: Any,
) -> MutableMapping[InvestigationActionRequest, dict[str, Any]]:
anchored_blocks = self._anchored_block_ids(item_list)
applier_ids = {item.applied_by_id for item in item_list if item.applied_by_id is not None}
appliers = (
{
applier["id"]: applier
for applier in user_service.serialize_many(
filter={"user_ids": list(applier_ids)}, as_user=serialize_generic_user(user)
)
}
if applier_ids
else {}
)
return {
item: {
"block_id": (
anchored_blocks.get((item.investigation_id, item.anchor_id or ""))
if item.anchor_type == InvestigationActionRequestAnchorType.BLOCK
else None
),
"applied_by": appliers.get(str(item.applied_by_id)),
}
for item in item_list
}

@override
def serialize(
self,
obj: InvestigationActionRequest,
attrs: Mapping[Any, Any],
user: User | RpcUser | AnonymousUser,
**kwargs: Any,
) -> InvestigationActionRequestSerializerResponse:
return {
"id": str(obj.id),
"key": obj.key,
"reportRevision": obj.report_revision,
"primary": obj.primary,
"anchor": (
{"type": obj.anchor_type, "id": obj.anchor_id, "blockId": attrs["block_id"]}
if obj.anchor_type is not None and obj.anchor_id is not None
else None
),
"title": obj.title,
"rationale": obj.rationale,
"impact": obj.impact,
"state": obj.state,
"reason": obj.reason,
"action": obj.action_payload,
"appliedBy": attrs["applied_by"],
"appliedDetails": obj.applied_details,
"dateApplied": obj.date_applied,
"error": obj.error,
"dateCreated": obj.date_added,
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@
from django.db.models import Count, Q

from sentry.api.serializers import Serializer, register, serialize
from sentry.investigations.endpoints.serializers.action_request import (
InvestigationActionRequestSerializer,
InvestigationActionRequestSerializerResponse,
)
from sentry.investigations.endpoints.serializers.block import (
InvestigationBlockSerializer,
InvestigationBlockSerializerResponse,
Expand All @@ -19,6 +23,8 @@
)
from sentry.investigations.models import (
Investigation,
InvestigationActionRequest,
InvestigationActionRequestState,
InvestigationBlock,
InvestigationFavoriteUser,
InvestigationOrchestrationRun,
Expand Down Expand Up @@ -111,6 +117,8 @@ class InvestigationDetailsSerializerResponse(InvestigationSerializerResponse):
"""
Full notebook with ordered active blocks, parameter definitions and saved values, project
IDs, and source context. source.snapshot is present only for source-backed investigations.
actionRequests has Seer's action requests that aren't superseded, newest report first, with
that report's primary at the top.
"""

template: InvestigationTemplateSerializerResponse | None
Expand All @@ -119,6 +127,7 @@ class InvestigationDetailsSerializerResponse(InvestigationSerializerResponse):
projectIds: list[int]
parameters: list[InvestigationParameterSerializerResponse]
blocks: list[InvestigationBlockSerializerResponse]
actionRequests: list[InvestigationActionRequestSerializerResponse]


@register(Investigation)
Expand Down Expand Up @@ -228,6 +237,27 @@ def _parameters_by_investigation(
by_investigation[parameter.investigation_id].append(parameter_response)
return by_investigation

def _action_requests_by_investigation(
self, item_list: Sequence[Investigation], user: User | RpcUser | AnonymousUser
) -> MutableMapping[int, list[InvestigationActionRequestSerializerResponse]]:
action_requests = list(
InvestigationActionRequest.objects.filter(investigation__in=item_list)
.exclude(state=InvestigationActionRequestState.SUPERSEDED)
.order_by("-report_revision", "-primary", "id")
)
serialized = serialize(
action_requests,
user,
InvestigationActionRequestSerializer(),
)

by_investigation: MutableMapping[
int, list[InvestigationActionRequestSerializerResponse]
] = defaultdict(list)
for action_request, response in zip(action_requests, serialized):
by_investigation[action_request.investigation_id].append(response)
return by_investigation

@override
def get_attrs(
self,
Expand All @@ -239,6 +269,7 @@ def get_attrs(

blocks_by_investigation = self._blocks_by_investigation(item_list, user)
parameters_by_investigation = self._parameters_by_investigation(item_list, user)
action_requests_by_investigation = self._action_requests_by_investigation(item_list, user)

project_ids_by_investigation: MutableMapping[int, list[int]] = defaultdict(list)
for investigation_id, project_id in (
Expand All @@ -252,6 +283,9 @@ def get_attrs(
attrs[investigation]["blocks"] = blocks_by_investigation[investigation.id]
attrs[investigation]["parameters"] = parameters_by_investigation[investigation.id]
attrs[investigation]["project_ids"] = project_ids_by_investigation[investigation.id]
attrs[investigation]["action_requests"] = action_requests_by_investigation[
investigation.id
]

return attrs

Expand Down Expand Up @@ -284,5 +318,6 @@ def serialize(
"projectIds": attrs["project_ids"],
"parameters": attrs["parameters"],
"blocks": attrs["blocks"],
"actionRequests": attrs["action_requests"],
"titleGeneration": {"status": obj.title_generation_status},
}
Loading
Loading